<commit_before>'use strict';

var mongoDBStoreCachedFactory = require('../../lib/index.js');

var express = require('express');
var session = require('express-session');
var MongoDBStoreCached = mongoDBStoreCachedFactory(session);
var request = require('request');

var sinon = require('sinon');

describe('MongoDBStoreCached', function () {

    var server, store,
        getMethod, destroyMethod, setMethod,
        cacheGetMethod, cacheRemoveMethod, cacheSetMethod;

    describe('with default options', function () {

        before(function (done) {

            store = new MongoDBStoreCached({
                collection: 'connect-mongodb-session-cached'
            });

            getMethod = sinon.spy(store, 'get');
            destroyMethod = sinon.spy(store, 'destroy');
            setMethod = sinon.spy(store, 'set');

            cacheGetMethod = sinon.spy(store._cache, 'get');
            cacheRemoveMethod = sinon.spy(store._cache, 'remove');
            cacheSetMethod = sinon.spy(store._cache, 'set');

            request = request.defaults({ jar: request.jar() });

            var app = express();

            app.use(session({
                store: store,
                secret: 'sssh!',
                saveUninitialized: true,
                resave: true,
                unset: 'destroy'
            }));

            app.get('/destroy', function (req, res) {
                delete req.session;
                res.send('Destroyed!');
            });

            app.get('*', function (req, res) {
                res.send('Hello World!');
            });

            server = app.listen(3030, function () {
                done();
            });

        });

        after(function (done) {

            server.close();
            store.db.close();
            store._cache.destroy();
            done();

        });

        it('should set the session entry', function (done) {

            request('http://localhost:3030', function (err, response, body) {

                expect(body).to.eql('Hello World!');

                expect(getMethod.callCount).to.eql(0);
                expect(destroyMethod.callCount).to.eql(0);
                expect(setMethod.callCount).to.eql(2);

                expect(cacheGetMethod.callCount).to.eql(0);
                expect(cacheRemoveMethod.callCount).to.eql(0);
                expect(cacheSetMethod.callCount).to.eql(2);

                done();

            });

        });

        it('should get the session from cache', function (done) {

            request('http://localhost:3030', function (err, response, body) {

                expect(body).to.eql('Hello World!');

                expect(getMethod.callCount).to.eql(1);
                expect(destroyMethod.callCount).to.eql(0);
                expect(setMethod.callCount).to.eql(3);

                expect(cacheGetMethod.callCount).to.eql(1);
                expect(cacheRemoveMethod.callCount).to.eql(0);
                expect(cacheSetMethod.callCount).to.eql(3);

                done();

            });

        });

        it('should get the session from db if cache empty', function (done) {

            store._cache.remove(cacheSetMethod.lastCall.args[0]);

            request('http://localhost:3030', function (err, response, body) {

                expect(body).to.eql('Hello World!');

                expect(getMethod.callCount).to.eql(2);
                expect(destroyMethod.callCount).to.eql(0);
                expect(setMethod.callCount).to.eql(4);

                expect(cacheGetMethod.callCount).to.eql(2);
                expect(cacheRemoveMethod.callCount).to.eql(1);
                expect(cacheSetMethod.callCount).to.eql(4);

                expect(cacheGetMethod.threw('Error')).to.eql(true);

                done();

            });

        });

        it('should destroy the session entry', function (done) {

            request('http://localhost:3030/destroy', function (err, response, body) {

                expect(body).to.eql('Destroyed!');

                expect(getMethod.callCount).to.eql(3);
                expect(destroyMethod.callCount).to.eql(1);
                expect(setMethod.callCount).to.eql(4);

                expect(cacheGetMethod.callCount).to.eql(3);
                expect(cacheRemoveMethod.callCount).to.eql(2);
                expect(cacheSetMethod.callCount).to.eql(4);

                done();

            });

        });

    });

    describe('with option for short cache expiry', function () {

        before(function (done) {

            store = new MongoDBStoreCached({
                collection: 'connect-mongodb-session-cached',
                expireCacheAfter: 10
            });

            getMethod = sinon.spy(store, 'get');
            destroyMethod = sinon.spy(store, 'destroy');
            setMethod = sinon.spy(store, 'set');

            cacheGetMethod = sinon.spy(store._cache, 'get');
            cacheRemoveMethod = sinon.spy(store._cache, 'remove');
            cacheSetMethod = sinon.spy(store._cache, 'set');

            request = request.defaults({ jar: request.jar() });

            var app = express();

            app.use(session({
                store: store,
                secret: 'sssh!',
                saveUninitialized: true,
                resave: true,
                unset: 'destroy'
            }));

            app.get('/destroy', function (req, res) {
                delete req.session;
                res.send('Destroyed!');
            });

            app.get('*', function (req, res) {
                res.send('Hello World!');
            });

            server = app.listen(3030, function () {
                done();
            });

        });

        after(function (done) {

            server.close();
            store.db.close();
            store._cache.destroy();
            done();

        });

        it('should load the session from db after cache expired', function (done) {

            request('http://localhost:3030', function (err, response, body) {

                expect(body).to.eql('Hello World!');

                expect(getMethod.callCount).to.eql(0);
                expect(destroyMethod.callCount).to.eql(0);
                expect(setMethod.callCount).to.eql(2);

                expect(cacheGetMethod.callCount).to.eql(0);
                expect(cacheRemoveMethod.callCount).to.eql(0);
                expect(cacheSetMethod.callCount).to.eql(2);

                setTimeout(function () {

                    request('http://localhost:3030', function (err, response, body) {

                        expect(body).to.eql('Hello World!');

                        expect(getMethod.callCount).to.eql(1);
                        expect(destroyMethod.callCount).to.eql(0);
                        expect(setMethod.callCount).to.eql(3);

                        expect(cacheGetMethod.callCount).to.eql(1);
                        expect(cacheRemoveMethod.callCount).to.eql(0);
                        expect(cacheSetMethod.callCount).to.eql(3);

                        expect(cacheGetMethod.threw('Error')).to.eql(true);

                        done();

                    });

                }, 20);

            });

        });

    });

});
<commit_msg>test: added output to pin down failures<commit_after>'use strict';

var mongoDBStoreCachedFactory = require('../../lib/index.js');

var express = require('express');
var session = require('express-session');
var MongoDBStoreCached = mongoDBStoreCachedFactory(session);
var request = require('request');

var sinon = require('sinon');

describe('MongoDBStoreCached', function () {

    var server, store,
        getMethod, destroyMethod, setMethod,
        cacheGetMethod, cacheRemoveMethod, cacheSetMethod;

    describe('with default options', function () {

        before(function (done) {

            store = new MongoDBStoreCached({
                collection: 'connect-mongodb-session-cached'
            });

            getMethod = sinon.spy(store, 'get');
            destroyMethod = sinon.spy(store, 'destroy');
            setMethod = sinon.spy(store, 'set');

            cacheGetMethod = sinon.spy(store._cache, 'get');
            cacheRemoveMethod = sinon.spy(store._cache, 'remove');
            cacheSetMethod = sinon.spy(store._cache, 'set');

            request = request.defaults({ jar: request.jar() });

            var app = express();

            app.use(session({
                store: store,
                secret: 'sssh!',
                saveUninitialized: true,
                resave: true,
                unset: 'destroy'
            }));

            app.get('/destroy', function (req, res) {
                delete req.session;
                res.send('Destroyed!');
            });

            app.get('*', function (req, res) {
                res.send('Hello World!');
            });

            server = app.listen(3030, function () {
                done();
            });

        });

        after(function (done) {

            server.close();
            store.db.close();
            store._cache.destroy();
            done();

        });

        it('should set the session entry', function (done) {

            expect(getMethod.callCount).to.eql(0);
            expect(destroyMethod.callCount).to.eql(0);
            expect(setMethod.callCount, setMethod.getCalls()).to.eql(0);

            expect(cacheGetMethod.callCount).to.eql(0);
            expect(cacheRemoveMethod.callCount).to.eql(0);
            expect(cacheSetMethod.callCount).to.eql(0);

            request('http://localhost:3030', function (err, response, body) {

                expect(body).to.eql('Hello World!');

                expect(getMethod.callCount).to.eql(0);
                expect(destroyMethod.callCount).to.eql(0);
                expect(setMethod.callCount, setMethod.getCalls()).to.eql(2);

                expect(cacheGetMethod.callCount).to.eql(0);
                expect(cacheRemoveMethod.callCount).to.eql(0);
                expect(cacheSetMethod.callCount).to.eql(2);

                done();

            });

        });

        it('should get the session from cache', function (done) {

            request('http://localhost:3030', function (err, response, body) {

                expect(body).to.eql('Hello World!');

                expect(getMethod.callCount).to.eql(1);
                expect(destroyMethod.callCount).to.eql(0);
                expect(setMethod.callCount, setMethod.getCalls()).to.eql(3);

                expect(cacheGetMethod.callCount).to.eql(1);
                expect(cacheRemoveMethod.callCount).to.eql(0);
                expect(cacheSetMethod.callCount).to.eql(3);

                done();

            });

        });

        it('should get the session from db if cache empty', function (done) {

            store._cache.remove(cacheSetMethod.lastCall.args[0]);

            request('http://localhost:3030', function (err, response, body) {

                expect(body).to.eql('Hello World!');

                expect(getMethod.callCount).to.eql(2);
                expect(destroyMethod.callCount).to.eql(0);
                expect(setMethod.callCount, setMethod.getCalls()).to.eql(4);

                expect(cacheGetMethod.callCount).to.eql(2);
                expect(cacheRemoveMethod.callCount).to.eql(1);
                expect(cacheSetMethod.callCount).to.eql(4);

                expect(cacheGetMethod.threw('Error')).to.eql(true);

                done();

            });

        });

        it('should destroy the session entry', function (done) {

            request('http://localhost:3030/destroy', function (err, response, body) {

                expect(body).to.eql('Destroyed!');

                expect(getMethod.callCount).to.eql(3);
                expect(destroyMethod.callCount).to.eql(1);
                expect(setMethod.callCount, setMethod.getCalls()).to.eql(4);

                expect(cacheGetMethod.callCount).to.eql(3);
                expect(cacheRemoveMethod.callCount).to.eql(2);
                expect(cacheSetMethod.callCount).to.eql(4);

                done();

            });

        });

    });

    describe('with option for short cache expiry', function () {

        before(function (done) {

            store = new MongoDBStoreCached({
                collection: 'connect-mongodb-session-cached',
                expireCacheAfter: 10
            });

            getMethod = sinon.spy(store, 'get');
            destroyMethod = sinon.spy(store, 'destroy');
            setMethod = sinon.spy(store, 'set');

            cacheGetMethod = sinon.spy(store._cache, 'get');
            cacheRemoveMethod = sinon.spy(store._cache, 'remove');
            cacheSetMethod = sinon.spy(store._cache, 'set');

            request = request.defaults({ jar: request.jar() });

            var app = express();

            app.use(session({
                store: store,
                secret: 'sssh!',
                saveUninitialized: true,
                resave: true,
                unset: 'destroy'
            }));

            app.get('/destroy', function (req, res) {
                delete req.session;
                res.send('Destroyed!');
            });

            app.get('*', function (req, res) {
                res.send('Hello World!');
            });

            server = app.listen(3030, function () {
                done();
            });

        });

        after(function (done) {

            server.close();
            store.db.close();
            store._cache.destroy();
            done();

        });

        it('should load the session from db after cache expired', function (done) {

            expect(getMethod.callCount).to.eql(0);
            expect(destroyMethod.callCount).to.eql(0);
            expect(setMethod.callCount, setMethod.getCalls()).to.eql(0);

            expect(cacheGetMethod.callCount).to.eql(0);
            expect(cacheRemoveMethod.callCount).to.eql(0);
            expect(cacheSetMethod.callCount).to.eql(0);

            request('http://localhost:3030', function (err, response, body) {

                expect(body).to.eql('Hello World!');

                expect(getMethod.callCount).to.eql(0);
                expect(destroyMethod.callCount).to.eql(0);
                expect(setMethod.callCount, setMethod.getCalls()).to.eql(2);

                expect(cacheGetMethod.callCount).to.eql(0);
                expect(cacheRemoveMethod.callCount).to.eql(0);
                expect(cacheSetMethod.callCount).to.eql(2);

                setTimeout(function () {

                    request('http://localhost:3030', function (err, response, body) {

                        expect(body).to.eql('Hello World!');

                        expect(getMethod.callCount).to.eql(1);
                        expect(destroyMethod.callCount).to.eql(0);
                        expect(setMethod.callCount, setMethod.getCalls()).to.eql(3);

                        expect(cacheGetMethod.callCount).to.eql(1);
                        expect(cacheRemoveMethod.callCount).to.eql(0);
                        expect(cacheSetMethod.callCount).to.eql(3);

                        expect(cacheGetMethod.threw('Error')).to.eql(true);

                        done();

                    });

                }, 20);

            });

        });

    });

});
<|endoftext|>


<commit_before>var chai      = require('chai');
var sinon     = require('sinon');
var sinonChai = require('sinon-chai');
var expect    = chai.expect;
var Store     = require('../lib/Store');
var Model     = require('../lib/Model');

describe('Store', function() {
  describe('#add', function() {
    it('stores the object within a particular namespace', function() {
      var store  = new Store();
      var result = store.add('tags', { id: 100 });

      expect(result).to.eql(store);
    });

    it('vivifies data into a model wrapper', function() {
      var store = new Store();
      store.add('tags', { id: 100 });

      expect(store.get('tags', 100)).to.be.instanceof(Model);
    });

    it('injects a reference to the store into models', function() {
      var store = new Store();
      store.add('tags', { id: 100 });

      expect(store.get('tags', 100).store).to.eql(store);
    });

    it('vivifies objects in buckets with matching models', function() {
      var Tag = function(attributes) {
        this.id   = attributes.id;
        this.name = attributes.name;
      };

      var store = new Store(null, { Tag: Tag });
      var result = store.add('tags', { id: 100, name: 'gamma' });

      return store.find('tags', 100).then(function(tag) {
        expect(tag).to.be.an.instanceOf(Tag);
        expect(tag.name).to.eq('gamma');
      });
    });

    it('emits an add event', function() {
      var store  = new Store();
      var listen = sinon.spy();

      store.on(Store.ADD_EVENT, listen);
      store.add('tags', { id: 100 });

      expect(listen).to.be.called;
    });
  });

  describe('#find', function() {
    it('retrieves a stored object', function() {
      var store  = new Store();
      var object = { id: 100 };
      store.add('tags', object);

      return store.find('tags', 100).then(function(tag) {
        expect(tag.id).to.eq(object.id);
      });
    });
  });

  describe('#all', function() {
    it('retrieves all objects stored within a namespace', function() {
      var store = new Store();
      store.add('tags', { id: 100 });

      expect(store.all('tags')).to.have.length(1);
    });
  });

  describe('#some', function() {
    it('retrieves each from a list of ids', function() {
      var store   = new Store();
      var objectA = { id: 100 };
      var objectB = { id: 101 };

      store
        .add('tags', objectA)
        .add('tags', objectB);

      expect(store.some('tags', [100, 101])).to.have.length(2);
    });
  });

  describe('#where', function() {
    it('retrieves all objects where a condition is true', function() {
      var store = new Store();

      store
        .add('tags', { id: 100, name: 'alpha', group: 'greek' })
        .add('tags', { id: 101, name: 'beta',  group: 'greek' })

      expect(store.where('tags', { name: 'beta' })).to.have.length(1);
    });
  });

  describe('#count', function() {
    it('counts the number of objects within a namespace', function() {
      var store = new Store();

      store.add('tags', { id: 100 });

      expect(store.count('tags')).to.eq(1);
    });
  });

  describe('#parse', function() {
    var payload = {
      thing:    { id: 1 },
      authors:  [{ id: 1 }],
      comments: [{ id: 1 }, { id: 2 }],
      posts:    [{ id: 1 }, { id: 2 }]
    }

    it('extracts a payload of rooted arrays into corresponding buckets', function() {
      var store = new Store();

      store.parse(payload);

      expect(store.count('things')).to.eq(1);
      expect(store.count('authors')).to.eq(1);
      expect(store.count('comments')).to.eq(2);
      expect(store.count('posts')).to.eq(2);
    });
  });

  describe('#delete', function() {
    it('removes the model from its bucket', function() {
      var store = new Store();

      store.add('tags', { id: 100 });
      store.delete({ namespace: 'tags', id: 100 });

      expect(store.count('tags')).to.eq(0);
    });

    it('instructs the adapter to persist deletion', function() {
      var store   = new Store(adapter);
      var adapter = store.adapter;

      sinon.spy(adapter, 'delete');

      store.add('tags', { id: 100 });
      store.delete('tags', { id: 100 });

      expect(adapter.delete).to.be.called;
    });

    it('emits a delete event', function() {
      var store  = new Store();
      var listen = sinon.spy();

      store.on(Store.DELETE_EVENT, listen);
      store.add('tags', { id: 100 });

      return store.delete('tags', { id: 100 }).then(function() {
        expect(listen).to.be.called;
      });
    });
  });

  describe('#reload', function() {
    it('instructs the adapter to reload the model', function() {
      var store   = new Store();
      var adapter = store.adapter;

      sinon.spy(adapter, 'read');

      store.add('tags', { id: 100 });
      store.reload('tags', { id: 100 });

      expect(adapter.read).to.be.called;
    });

    it('emits a reload event', function() {
      var store  = new Store();
      var listen = sinon.spy();

      store.on(Store.RELOAD_EVENT, listen);

      return store.reload({ id: 100 }).then(function() {
        expect(listen).to.be.called;
      });
    });
  });

  describe('#save', function() {
    it('instructs the adapter to update the model', function() {
      var store   = new Store();
      var adapter = store.adapter;

      sinon.spy(adapter, 'update');

      store.save({ id: 100 });

      expect(adapter.update).to.be.called;
    });

    it('emits a change event', function() {
      var store  = new Store();
      var listen = sinon.spy();

      store.on(Store.CHANGE_EVENT, listen);

      return store.save({ id: 100 }).then(function(model) {
        expect(listen).to.be.called;
      });
    });
  });
});
<commit_msg>Bump the number of expected items in store test<commit_after>var chai      = require('chai');
var sinon     = require('sinon');
var sinonChai = require('sinon-chai');
var expect    = chai.expect;
var Store     = require('../lib/Store');
var Model     = require('../lib/Model');

describe('Store', function() {
  describe('#add', function() {
    it('stores the object within a particular namespace', function() {
      var store  = new Store();
      var result = store.add('tags', { id: 100 });

      expect(result).to.eql(store);
    });

    it('vivifies data into a model wrapper', function() {
      var store = new Store();
      store.add('tags', { id: 100 });

      expect(store.get('tags', 100)).to.be.instanceof(Model);
    });

    it('injects a reference to the store into models', function() {
      var store = new Store();
      store.add('tags', { id: 100 });

      expect(store.get('tags', 100).store).to.eql(store);
    });

    it('vivifies objects in buckets with matching models', function() {
      var Tag = function(attributes) {
        this.id   = attributes.id;
        this.name = attributes.name;
      };

      var store = new Store(null, { Tag: Tag });
      var result = store.add('tags', { id: 100, name: 'gamma' });

      return store.find('tags', 100).then(function(tag) {
        expect(tag).to.be.an.instanceOf(Tag);
        expect(tag.name).to.eq('gamma');
      });
    });

    it('emits an add event', function() {
      var store  = new Store();
      var listen = sinon.spy();

      store.on(Store.ADD_EVENT, listen);
      store.add('tags', { id: 100 });

      expect(listen).to.be.called;
    });
  });

  describe('#find', function() {
    it('retrieves a stored object', function() {
      var store  = new Store();
      var object = { id: 100 };
      store.add('tags', object);

      return store.find('tags', 100).then(function(tag) {
        expect(tag.id).to.eq(object.id);
      });
    });
  });

  describe('#all', function() {
    it('retrieves all objects stored within a namespace', function() {
      var store = new Store();
      store.add('tags', { id: 100 });

      expect(store.all('tags')).to.have.length(1);
    });
  });

  describe('#some', function() {
    it('retrieves each from a list of ids', function() {
      var store   = new Store();
      var objectA = { id: 100 };
      var objectB = { id: 101 };

      store
        .add('tags', objectA)
        .add('tags', objectB);

      expect(store.some('tags', [100, 101])).to.have.length(2);
    });
  });

  describe('#where', function() {
    it('retrieves all objects where a condition is true', function() {
      var store = new Store();

      store
        .add('tags', { id: 100, name: 'alpha', group: 'greek' })
        .add('tags', { id: 101, name: 'beta',  group: 'greek' })

      expect(store.where('tags', { name: 'beta' })).to.have.length(1);
    });
  });

  describe('#count', function() {
    it('counts the number of objects within a namespace', function() {
      var store = new Store();

      store
        .add('tags', { id: 100 })
        .add('tags', { id: 101 });

      expect(store.count('tags')).to.eq(2);
    });
  });

  describe('#parse', function() {
    var payload = {
      thing:    { id: 1 },
      authors:  [{ id: 1 }],
      comments: [{ id: 1 }, { id: 2 }],
      posts:    [{ id: 1 }, { id: 2 }]
    }

    it('extracts a payload of rooted arrays into corresponding buckets', function() {
      var store = new Store();

      store.parse(payload);

      expect(store.count('things')).to.eq(1);
      expect(store.count('authors')).to.eq(1);
      expect(store.count('comments')).to.eq(2);
      expect(store.count('posts')).to.eq(2);
    });
  });

  describe('#delete', function() {
    it('removes the model from its bucket', function() {
      var store = new Store();

      store.add('tags', { id: 100 });
      store.delete({ namespace: 'tags', id: 100 });

      expect(store.count('tags')).to.eq(0);
    });

    it('instructs the adapter to persist deletion', function() {
      var store   = new Store(adapter);
      var adapter = store.adapter;

      sinon.spy(adapter, 'delete');

      store.add('tags', { id: 100 });
      store.delete('tags', { id: 100 });

      expect(adapter.delete).to.be.called;
    });

    it('emits a delete event', function() {
      var store  = new Store();
      var listen = sinon.spy();

      store.on(Store.DELETE_EVENT, listen);
      store.add('tags', { id: 100 });

      return store.delete('tags', { id: 100 }).then(function() {
        expect(listen).to.be.called;
      });
    });
  });

  describe('#reload', function() {
    it('instructs the adapter to reload the model', function() {
      var store   = new Store();
      var adapter = store.adapter;

      sinon.spy(adapter, 'read');

      store.add('tags', { id: 100 });
      store.reload('tags', { id: 100 });

      expect(adapter.read).to.be.called;
    });

    it('emits a reload event', function() {
      var store  = new Store();
      var listen = sinon.spy();

      store.on(Store.RELOAD_EVENT, listen);

      return store.reload({ id: 100 }).then(function() {
        expect(listen).to.be.called;
      });
    });
  });

  describe('#save', function() {
    it('instructs the adapter to update the model', function() {
      var store   = new Store();
      var adapter = store.adapter;

      sinon.spy(adapter, 'update');

      store.save({ id: 100 });

      expect(adapter.update).to.be.called;
    });

    it('emits a change event', function() {
      var store  = new Store();
      var listen = sinon.spy();

      store.on(Store.CHANGE_EVENT, listen);

      return store.save({ id: 100 }).then(function(model) {
        expect(listen).to.be.called;
      });
    });
  });
});
<|endoftext|>


<commit_before>function ask(request, handleReply)
{
    var xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function()
    {
        if(xhttp.readyState == 4 && xhttp.status == 200)
        {
            var responseReceivedTime = new Date().getTime();
            var serverTime = responseReceivedTime - ms;
            var msLabel = document.getElementById("ms");
            msLabel.innerHTML = "Time (ms) " + serverTime;
            var returnedJson = JSON.parse(xhttp.responseText);
            if(returnedJson["status"] != "SUCCESS")
            {
                var errorLab = document.getElementById("errorLabel");
                errorLab.innerHTML = returnedJson["message"];
            }
            handleReply(returnedJson);
        }
    };

    xhttp.open("POST", "http://54.237.198.126:8088",true);
    // xhttp.open("POST", "http://127.0.0.1:8088",true);
    xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    var ms = new Date().getTime();
    xhttp.send(JSON.stringify(request));
}

function newAsk(request, params)
{
    return {"guid" : "testGUID", "request" : request, "parameters" : params};
}

function ping()
{
    var request  = newAsk("ping", {});
    var handler = function(j)
    {
       var pingLabel = document.getElementById("pingLabel");
       pingLabel.innerHTML = j["status"];
    };
    ask(request, handler);
}

function createAlbum()
{
    var name    = document.getElementById("newAlbumName").value;
    var params  = {"name" : name};
    var request = newAsk("newAlbum", params);
    var handler = function(j) { if(j["status"] != "SUCCESS"){showAlbums();} };
    ask(request, handler);
}

function getImage()
{

    var album       = document.getElementById("getImageAlbum").value;
    var imgFileName = document.getElementById("getImage").value;

    var params = {"album" : album, "name" : imgFileName};

    var request = newAsk("getImage", params);
    var handler = function(j)
    {
        if(j["status"] == "SUCCESS") {
            var image = new Image();
            image.src = 'data:image/jpg;base64,' + j["data"]["image"];
            document.body.appendChild(image);
        }
    };

    ask(request, handler);
}

function eraseImage()
{
    var album       = document.getElementById("eraseImageAlbum").value;
    var imgFileName = document.getElementById("eraseImage").value;

    var params = {"album" : album, "name" : imgFileName};
    var request = newAsk("eraseImage", params);
    var handler = function(j)
    {
        displayImages(album);
    };

    ask(request,handler);
}

function uploadImage2(aFile)
{
    var album = document.getElementById("uploadAlbumName").value;
    var reader = new FileReader();

    if(reader != null)
    {
        reader.onload = function(e)
        {
            var b64 = showThumbGetPic(e);
            var params = {"album" : album, "name" : aFile.name, "image" : b64};
            var request = newAsk("saveImage", params);
            var handler = function(j){
                if(j["message"].length == 0)
                   displayImages(album);
               };
            ask(request, handler);
        };
        reader.readAsDataURL(aFile);
    }
}
function uploadImage(allfiles)
{
    if (allfiles == null || allfiles == undefined)
    {
        document.write("This Browser has no support for HTML5 FileReader yet!");
        return false;
    }

    var files = filterNonImages(allfiles);

    for (var i = 0; i < files.length; i++) {
        var file = files[i];
        uploadImage2(file);
    }
}

function displayImages(album)
{
    var params = {"album" : album};
    var request = newAsk("imageNames", params);
    var handler = function(j)
    {
        var images = document.getElementById("images");
        images.innerHTML = j["data"]["images"];
    };

    ask(request, handler);
}

function showImages()
{
    var album = document.getElementById("albumName").value;
    displayImages(album);
}

function eraseAlbum()
{
    var name = document.getElementById("eraseAlbumName").value;
    var params = {"name" : name};
    var request = newAsk("eraseAlbum", params);
    var handler = function(j)
    {
        showAlbums();
    };

    ask(request, handler);
}

function showAlbums()
{
    var request = newAsk("albumNames", {});
    var handler = function(j)
    {
        var albums = document.getElementById("albums");
        albums.innerHTML = j["data"]["albums"];
    };

    ask(request, handler);
}

function filterNonImages(files) {
    var imgs = [];
    var imageType = /image.*/;
    for(var i = 0; i < files.length; i++)
        if(files[i].type.match(imageType))
            imgs.push(files[i]);
    return imgs;
}

function thumb(allFiles) {
    if (allFiles == null || allFiles == undefined)
    {
        document.write("This Browser has no support for HTML5 FileReader yet!");
        return false;
    }

    var files = filterNonImages(allFiles);
    var b64Images = [];
    for (var i = 0; i < files.length; i++) {
        var file = files[i];

        var reader = new FileReader();

        if (reader != null) {
            reader.onload = function(e){
                var src = showThumbGetPic(e);
                b64Images.push(src);

                if(files.length == b64Images.length)
                {
                    var obj = {"request" : "saveImages",
                               "content" :
                                           {
                                               "setName": "images1",
                                               "images" : b64Images
                                           }
                              };
                    ask(obj,function(j){alert(j["response"])});
                }
                return src;
            };
            reader.readAsDataURL(file);
        }
    }
}

function showThumbGetPic(e){
    var myCan = document.createElement('canvas');
    var img   = new Image();
    img.src   = e.target.result;

    img.onload = function () {
        myCan.id = "myTempCanvas";
        var tsize = document.getElementById("txtThumbSize").value;
        myCan.width = Number(tsize);
        myCan.height = Number(tsize);
        if (myCan.getContext) {
            var cntxt = myCan.getContext("2d");
            cntxt.drawImage(img, 0, 0, myCan.width, myCan.height);
            var dataURL = myCan.toDataURL();

            if (dataURL != null && dataURL != undefined) {
                var nImg = document.createElement('img');
                nImg.src = dataURL;
                document.body.appendChild(nImg);
            }
            else
                alert('unable to get context');
        }
    };
    return img.src;
}

function init()
{
//     ask({"requestType":"imageSets"}, function(j){
//         var namesArr = j["sets"]; //get array of image set names
//         var parent = document.getElementById("showImgSets");
//         for(var i = 0; i < namesArr.length; i++)
//         {
//             var aLabel = document.createElement("Button");
//             aLabel.className = "PicSet";
//             aLabel.innerHTML = namesArr[i];
//             parent.appendChild(aLabel);
//         }
//     });
}
<commit_msg>fixed a testing bug<commit_after>function ask(request, handleReply)
{
    var xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function()
    {
        if(xhttp.readyState == 4 && xhttp.status == 200)
        {
            var responseReceivedTime = new Date().getTime();
            var serverTime = responseReceivedTime - ms;
            var msLabel = document.getElementById("ms");
            msLabel.innerHTML = "Time (ms) " + serverTime;
            var returnedJson = JSON.parse(xhttp.responseText);
            if(returnedJson["status"] != "SUCCESS")
            {
                var errorLab = document.getElementById("errorLabel");
                errorLab.innerHTML = returnedJson["message"];
            }
            handleReply(returnedJson);
        }
    };

    xhttp.open("POST", "http://54.237.198.126:8088",true);
    // xhttp.open("POST", "http://127.0.0.1:8088",true);
    xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    var ms = new Date().getTime();
    xhttp.send(JSON.stringify(request));
}

function newAsk(request, params)
{
    return {"guid" : "testGUID", "request" : request, "parameters" : params};
}

function ping()
{
    var request  = newAsk("ping", {});
    var handler = function(j)
    {
       var pingLabel = document.getElementById("pingLabel");
       pingLabel.innerHTML = j["status"];
    };
    ask(request, handler);
}

function createAlbum()
{
    var name    = document.getElementById("newAlbumName").value;
    var params  = {"name" : name};
    var request = newAsk("newAlbum", params);
    var handler = function(j) { if(j["status"] == "SUCCESS"){showAlbums();} };
    ask(request, handler);
}

function getImage()
{

    var album       = document.getElementById("getImageAlbum").value;
    var imgFileName = document.getElementById("getImage").value;

    var params = {"album" : album, "name" : imgFileName};

    var request = newAsk("getImage", params);
    var handler = function(j)
    {
        if(j["status"] == "SUCCESS") {
            var image = new Image();
            image.src = 'data:image/jpg;base64,' + j["data"]["image"];
            document.body.appendChild(image);
        }
    };

    ask(request, handler);
}

function eraseImage()
{
    var album       = document.getElementById("eraseImageAlbum").value;
    var imgFileName = document.getElementById("eraseImage").value;

    var params = {"album" : album, "name" : imgFileName};
    var request = newAsk("eraseImage", params);
    var handler = function(j)
    {
        displayImages(album);
    };

    ask(request,handler);
}

function uploadImage2(aFile)
{
    var album = document.getElementById("uploadAlbumName").value;
    var reader = new FileReader();

    if(reader != null)
    {
        reader.onload = function(e)
        {
            var b64 = showThumbGetPic(e);
            var params = {"album" : album, "name" : aFile.name, "image" : b64};
            var request = newAsk("saveImage", params);
            var handler = function(j){
                if(j["message"].length == 0)
                   displayImages(album);
               };
            ask(request, handler);
        };
        reader.readAsDataURL(aFile);
    }
}
function uploadImage(allfiles)
{
    if (allfiles == null || allfiles == undefined)
    {
        document.write("This Browser has no support for HTML5 FileReader yet!");
        return false;
    }

    var files = filterNonImages(allfiles);

    for (var i = 0; i < files.length; i++) {
        var file = files[i];
        uploadImage2(file);
    }
}

function displayImages(album)
{
    var params = {"album" : album};
    var request = newAsk("imageNames", params);
    var handler = function(j)
    {
        var images = document.getElementById("images");
        images.innerHTML = j["data"]["images"];
    };

    ask(request, handler);
}

function showImages()
{
    var album = document.getElementById("albumName").value;
    displayImages(album);
}

function eraseAlbum()
{
    var name = document.getElementById("eraseAlbumName").value;
    var params = {"name" : name};
    var request = newAsk("eraseAlbum", params);
    var handler = function(j)
    {
        if(j["status"] == "SUCCESS")
            showAlbums();
    };

    ask(request, handler);
}

function showAlbums()
{
    var request = newAsk("albumNames", {});
    var handler = function(j)
    {
        var albums = document.getElementById("albums");
        albums.innerHTML = j["data"]["albums"];
    };

    ask(request, handler);
}

function filterNonImages(files) {
    var imgs = [];
    var imageType = /image.*/;
    for(var i = 0; i < files.length; i++)
        if(files[i].type.match(imageType))
            imgs.push(files[i]);
    return imgs;
}

function thumb(allFiles) {
    if (allFiles == null || allFiles == undefined)
    {
        document.write("This Browser has no support for HTML5 FileReader yet!");
        return false;
    }

    var files = filterNonImages(allFiles);
    var b64Images = [];
    for (var i = 0; i < files.length; i++) {
        var file = files[i];

        var reader = new FileReader();

        if (reader != null) {
            reader.onload = function(e){
                var src = showThumbGetPic(e);
                b64Images.push(src);

                if(files.length == b64Images.length)
                {
                    var obj = {"request" : "saveImages",
                               "content" :
                                           {
                                               "setName": "images1",
                                               "images" : b64Images
                                           }
                              };
                    ask(obj,function(j){alert(j["response"])});
                }
                return src;
            };
            reader.readAsDataURL(file);
        }
    }
}

function showThumbGetPic(e){
    var myCan = document.createElement('canvas');
    var img   = new Image();
    img.src   = e.target.result;

    img.onload = function () {
        myCan.id = "myTempCanvas";
        var tsize = document.getElementById("txtThumbSize").value;
        myCan.width = Number(tsize);
        myCan.height = Number(tsize);
        if (myCan.getContext) {
            var cntxt = myCan.getContext("2d");
            cntxt.drawImage(img, 0, 0, myCan.width, myCan.height);
            var dataURL = myCan.toDataURL();

            if (dataURL != null && dataURL != undefined) {
                var nImg = document.createElement('img');
                nImg.src = dataURL;
                document.body.appendChild(nImg);
            }
            else
                alert('unable to get context');
        }
    };
    return img.src;
}

function init()
{
//     ask({"requestType":"imageSets"}, function(j){
//         var namesArr = j["sets"]; //get array of image set names
//         var parent = document.getElementById("showImgSets");
//         for(var i = 0; i < namesArr.length; i++)
//         {
//             var aLabel = document.createElement("Button");
//             aLabel.className = "PicSet";
//             aLabel.innerHTML = namesArr[i];
//             parent.appendChild(aLabel);
//         }
//     });
}
<|endoftext|>


<commit_before>function CreatePDF(resp) {
    var doc = new jsPDF();
    doc.setFontSize(22);
    doc.text(20, 20, 'Proposal');
    doc.setFontSize(10);
    doc.setFont("times");
    doc.setFontType("normal");
    doc.text(20, 30, 'Insurance for ' + resp.insuranceType);
    doc.text(20, 50, 'Surname:');
    doc.text(20, 60, 'First Name:');
    doc.text(20, 70, 'Middle Name:');
    doc.text(20, 80, 'Title:');
    doc.text(20, 90, 'Occupation:');
    doc.text(100, 50, 'Mothers Maiden Name: ');
    doc.text(100, 60, 'Other Names/Aliases: ');
    doc.text(100, 70, 'ID Type: ');
    doc.text(100, 80, 'ID Number: ');
    doc.text(100, 90, 'Expiration Date: ');
    doc.text(100, 100, 'Source of Funds: ');
    doc.text(20, 120, 'Street Number and Name: ');
    doc.text(20, 130, 'City/Town/Postal Zone: ');
    doc.text(20, 140, 'Parish: ');
    doc.text(100, 120, 'TRN: ');
    doc.text(100, 130, 'Email Address: ');
    doc.text(100, 140, 'Mobile Number: ');
    doc.text(100, 150, 'Home Number: ');
    doc.text(100, 160, 'Work Number: ');
    doc.text(20, 180, 'Street Number and Name: ');
    doc.text(20, 190, 'City/Town/Postal Zone: ');
    doc.text(20, 200, 'Parish ');
    doc.text(100, 180, 'Date of Birth: ');
    doc.text(100, 190, 'Place of Birth: ');
    doc.text(100, 200, 'Nationality: ');
    doc.text(20, 220, 'Company Name:');
    doc.text(100, 220, 'Street Number and Name:');
    doc.text(100, 230, 'Town');
    doc.text(100, 240, 'Parish');
    doc.setFontType("bold");
    doc.text(50, 50, resp.applicantSurname); /*doc.text(50, 60, resp.applicantFirstName); doc.text(50, 70, resp.applicantMiddleName);*/
    doc.text(50, 80, resp.applicantTitle);
    doc.text(50, 90, resp.applicantOccupation);
    doc.text(150, 50, resp.applicantMothersMaidenName);
    doc.text(150, 60, resp.applicantAlias);
    doc.text(150, 70, resp.applicantIDType);
    doc.text(150, 80, resp.applicantIDnumber);
    doc.text(150, 90, resp.applicationIDExpirationDate); /* doc.text(150, 100, resp.SourceOfFunds); */
    doc.text(20, 125, resp.applicantHomeStreetName);
    doc.text(20, 135, resp.applicantHomeTown);
    doc.text(50, 140, resp.applicantHomeParish); /* doc.text(150, 120, resp.applicantTRN); */
    doc.text(150, 130, resp.applicantEmailAddress); /* doc.text(150, 140, resp.ApplicantMobileNumber); */
    doc.text(150, 150, resp.applicantHomeNumber);
    doc.text(150, 160, resp.applicantWorkNumber); /* doc.text(20, 185, resp.applicantMailStreetName); */
    doc.text(20, 195, resp.applicantMailTown);
    doc.text(50, 200, resp.applicantMailParish);
    doc.text(150, 180, resp.applicantDateOfBirth);
    doc.text(150, 190, resp.applicantPlaceOfBirth);
    doc.text(150, 200, resp.applicantNationality);
    doc.text(50, 220, resp.employerName);
    doc.text(150, 220, resp.employerStreetName);
    doc.text(150, 230, resp.employerTown);
    doc.text(150, 240, resp.employerParish);
    doc.setFontType("bold");
    doc.setFontSize("14");
    doc.text(20, 40, 'Name');
    doc.text(20, 110, 'Home Address');
    doc.text(20, 170, 'Mailing Address');
    doc.text(20, 210, 'Employer Details');

    doc.addPage();

    doc.setFontSize("10");
    doc.setFontType("bold");
    doc.text(20, 20, "Particulars Of Vehicles to Be Insured");

    doc.text(20,80, "NOTE: You are required to ensure that the Sum Insured is revised annually to reflect the current market value.  ");

    doc.text(20, 85, "Claims will be settled based on the market value at the time of the loss. For total losses you will be paid based in");

    doc.text(20, 90, "time of the loss. For total losses you will be paid based on the market value or Policy Sum Insured whichever is lesser.");

    doc.text(20, 100, "Lien Holder");

    doc.text(20, 140, "Select cover required(tick the appropriate box)");

    doc.setFontType("normal");
    doc.text(20, 50, "Are you the owner of the vehicle(s) and is/are/they registered in your name?");

    doc.text(20, 60, "If not, state the name and address of the owner:");

    doc.text(20, 70, "Will a trailer be used?");

    doc.text(20, 110, "Name in Full:");

    doc. text(100, 110, "Street Number and Name:");

    doc.text(100, 120, "Town:");

    doc.text(100, 130, "Parish:");

    doc.text(20, 150, "Please indicate if the vehicle is to be used as:");

    doc.text(20, 160, "Is the vehicle fitted with an anti-theft device?");

    doc.text(20, 170, "If yes, state the name, type of device and name of provider");

    doc.text(20, 180, "Will you have regular custody of the vehicle?");

    doc.text(20, 190, "If not, please provide details");

    doc.text(20, 200, "Is the vehicle garaged at the Proposer's home address?");

    doc.text(20, 210, "If not, please state where:");

    doc.text(20, 220, "Is the vehicle kept in?");

    doc.setFontType("bold");

   /* doc.text(110, 50, resp.isOwnerOfVehicle); */

    doc.text(110, 60, resp.nameAddressOfOwner);

  /*  doc.text(110, 70, resp.trailerUsed); */

    doc.text(110, 110, resp.lienHolderNameInFull);

    doc. text(100, 115, resp.lienHolderStreetName);

    doc.text(150, 120, resp.lienHolderTown);

    doc.text(150, 130, resp.lienHolderParish);

    doc.text(110, 150, resp.vehicleUsedAs);

   /* doc.text(110, 160, resp.vehicleAntiTheftDevice); */

    doc.text(20, 175, resp.vehicleAntiTheftDeviceName + " " + resp.vehicleAntiTheftDeviceType + " " + resp.vehicleAntiTheftDeviceNameOfProvider);

    doc.text(110, 180, resp.vehicleRegularCustody?resp.vehicleRegularCustody:"");

    doc.text(110, 190, resp.vehicleRegularCustodyDetails?resp.vehicleRegularCustodyDetails:"");

    doc.text(110, 200, resp.vehicleGaragedAtProposersHome?resp.vehicleGaragedAtProposersHome:"");

    doc.text(110, 210, resp.vehicleGaragedAtProposersHomeDetails?resp.vehicleGaragedAtProposersHomeDetails:"");

    doc.text(110, 220, resp.vehicleKeptIn?resp.vehicleKeptIn:"");

    doc.addPage();

    doc.setFontSize("10");

    doc.text(20, 20, "Is the proposer now insured or was previously insured in respect of any vehicle(s)");

    doc.text(20, 40, "If yes, state the name and address of the Insurance Company:");

    doc.text(20, 50, "Is the proposer entitled to No Claim Discount from previous Insurer(s) In respect of any vehicle(s) described in the ");

    doc.text(20, 55, "proposal?")

    doc.text(20, 60, "If yes, please attach proof of No Claim Discount Letter or Renewal Notice.");

    doc.text(20, 70, "Do you have any other Insurance(s) with IronRock Insurance Company Ltd.?");

    doc.text(20, 80, "If yes, please state type(s):");

    doc.text(20, 90, "Has any Insurer(s) in respect of the Proposer or any other Person who will regularly drive ever?");

    doc.text(20, 130, "If yes, please indicate above and give details:");

    doc.text(20, 140, "Type of Authorized Driver Clause:");

    doc.addPage();

    doc.text(20, 20, "Have you or any regular drivers had any accidents or losses during the past three(3) years (whether insured ");

    doc.text(20, 25, "or not in respect of all vehicles)");

    doc.text(20, 30, "I. Owned by you, whether or not you were the driver at the material time?");

    doc.text(20, 35, "II. Not owned by you, but driven by you or in your custody at the material time?");

    doc.text(20, 45, "If yes, please give details below");

    doc.text(20, 80, "To the best of your knowledge and belief have you, or any person who to your knowledge");

    doc.text(20, 85, "will drive have suffered from, or now suffer from:");

    doc.text(20, 100, "If yes, please indicate above and give details:");

    doc.text(20, 110, "Have you or any person who to your knowledge will drive received any traffic ticket(s) and");

    doc.text(20, 115, "or have been convicted of any offence in connection with the driving of any motor vehicle within the ");

    doc.text(20, 120, "last three (3) years?");

    doc.text(20, 130, "If yes, please give details:");

    doc.text(20, 140, "has the vehicle been modified or converted from maker's standard specification or do you intend to do so?");

    doc.text(20, 150, "If yes, please give details:");

    doc.text(20, 160, "Do you require increased limits (in excess of the Standard Limits)");

    doc.save('Proposal' + resp.applicantQuoteNo + '.pdf');
}<commit_msg>table not working<commit_after>var doc;
function CreatePDF(resp) {
    doc = new jsPDF();
    console.log(resp);
    doc.setFontSize(22);
    doc.text(20, 20, 'Proposal');
    doc.setFontSize(10);
    doc.setFont("times");
    doc.setFontType("normal");
    doc.text(20, 30, 'Insurance for ' + resp.insuranceType);
    doc.text(20, 50, 'Surname:');
    doc.text(20, 60, 'First Name:');
    doc.text(20, 70, 'Middle Name:');
    doc.text(20, 80, 'Title:');
    doc.text(20, 90, 'Occupation:');
    doc.text(100, 50, 'Mothers Maiden Name: ');
    doc.text(100, 60, 'Other Names/Aliases: ');
    doc.text(100, 70, 'ID Type: ');
    doc.text(100, 80, 'ID Number: ');
    doc.text(100, 90, 'Expiration Date: ');
    doc.text(100, 100, 'Source of Funds: ');
    doc.text(20, 120, 'Street Number and Name: ');
    doc.text(20, 130, 'City/Town/Postal Zone: ');
    doc.text(20, 140, 'Parish: ');
    doc.text(100, 120, 'TRN: ');
    doc.text(100, 130, 'Email Address: ');
    doc.text(100, 140, 'Mobile Number: ');
    doc.text(100, 150, 'Home Number: ');
    doc.text(100, 160, 'Work Number: ');
    doc.text(20, 180, 'Street Number and Name: ');
    doc.text(20, 190, 'City/Town/Postal Zone: ');
    doc.text(20, 200, 'Parish ');
    doc.text(100, 180, 'Date of Birth: ');
    doc.text(100, 190, 'Place of Birth: ');
    doc.text(100, 200, 'Nationality: ');
    doc.text(20, 220, 'Company Name:');
    doc.text(100, 220, 'Street Number and Name:');
    doc.text(100, 230, 'Town');
    doc.text(100, 240, 'Parish');
    doc.setFontType("bold");
    doc.text(50, 50, resp.applicantSurname); /*doc.text(50, 60, resp.applicantFirstName); doc.text(50, 70, resp.applicantMiddleName);*/
    doc.text(50, 80, resp.applicantTitle);
    doc.text(50, 90, resp.applicantOccupation);
    doc.text(150, 50, resp.applicantMothersMaidenName);
    doc.text(150, 60, resp.applicantAlias);
    doc.text(150, 70, resp.applicantIDType);
    doc.text(150, 80, resp.applicantIDnumber);
    doc.text(150, 90, resp.applicationIDExpirationDate); /* doc.text(150, 100, resp.SourceOfFunds); */
    doc.text(20, 125, resp.applicantHomeStreetName);
    doc.text(20, 135, resp.applicantHomeTown);
    doc.text(50, 140, resp.applicantHomeParish); /* doc.text(150, 120, resp.applicantTRN); */
    doc.text(150, 130, resp.applicantEmailAddress); /* doc.text(150, 140, resp.ApplicantMobileNumber); */
    doc.text(150, 150, resp.applicantHomeNumber);
    doc.text(150, 160, resp.applicantWorkNumber); /* doc.text(20, 185, resp.applicantMailStreetName); */
    doc.text(20, 195, resp.applicantMailTown);
    doc.text(50, 200, resp.applicantMailParish);
    doc.text(150, 180, resp.applicantDateOfBirth);
    doc.text(150, 190, resp.applicantPlaceOfBirth);
    doc.text(150, 200, resp.applicantNationality);
    doc.text(50, 220, resp.employerName);
    doc.text(150, 220, resp.employerStreetName);
    doc.text(150, 230, resp.employerTown);
    doc.text(150, 240, resp.employerParish);
    doc.setFontType("bold");
    doc.setFontSize("14");
    doc.text(20, 40, 'Name');
    doc.text(20, 110, 'Home Address');
    doc.text(20, 170, 'Mailing Address');
    doc.text(20, 210, 'Employer Details');

    doc.addPage();
    if(resp.insuranceType=='motor'){
        MotorPDF(resp);
    }else{
        ProperPDF(resp);
    }

    doc.save('Proposal' + resp.applicantQuoteNo + '.pdf');
}

function MotorPDF(resp){
    doc.setFontSize("10");
    doc.setFontType("bold");
    doc.text(20, 20, "Particulars Of Vehicles to Be Insured");

    doc.text(20,80, "NOTE: You are required to ensure that the Sum Insured is revised annually to reflect the current market value.  ");

    doc.text(20, 85, "Claims will be settled based on the market value at the time of the loss. For total losses you will be paid based in");

    doc.text(20, 90, "time of the loss. For total losses you will be paid based on the market value or Policy Sum Insured whichever is lesser.");

    doc.text(20, 100, "Lien Holder");

    doc.text(20, 140, "Select cover required(tick the appropriate box)");

    doc.setFontType("normal");
    doc.text(20, 50, "Are you the owner of the vehicle(s) and is/are/they registered in your name?");

    doc.text(20, 60, "If not, state the name and address of the owner:");

    doc.text(20, 70, "Will a trailer be used?");

    doc.text(20, 110, "Name in Full:");

    doc. text(100, 110, "Street Number and Name:");

    doc.text(100, 120, "Town:");

    doc.text(100, 130, "Parish:");

    doc.text(20, 150, "Please indicate if the vehicle is to be used as:");

    doc.text(20, 160, "Is the vehicle fitted with an anti-theft device?");

    doc.text(20, 170, "If yes, state the name, type of device and name of provider");

    doc.text(20, 180, "Will you have regular custody of the vehicle?");

    doc.text(20, 190, "If not, please provide details");

    doc.text(20, 200, "Is the vehicle garaged at the Proposer's home address?");

    doc.text(20, 210, "If not, please state where:");

    doc.text(20, 220, "Is the vehicle kept in?");

    doc.setFontType("bold");

   /* doc.text(110, 50, resp.isOwnerOfVehicle); */

    doc.text(110, 60, resp.nameAddressOfOwner);

  /*  doc.text(110, 70, resp.trailerUsed); */

    doc.text(110, 110, resp.lienHolderNameInFull);

    doc. text(100, 115, resp.lienHolderStreetName);

    doc.text(150, 120, resp.lienHolderTown);

    doc.text(150, 130, resp.lienHolderParish);

    doc.text(110, 150, resp.vehicleUsedAs);

   /* doc.text(110, 160, resp.vehicleAntiTheftDevice); */

    doc.text(20, 175, resp.vehicleAntiTheftDeviceName + " " + resp.vehicleAntiTheftDeviceType + " " + resp.vehicleAntiTheftDeviceNameOfProvider);

    doc.text(110, 180, resp.vehicleRegularCustody?resp.vehicleRegularCustody:"");

    doc.text(110, 190, resp.vehicleRegularCustodyDetails?resp.vehicleRegularCustodyDetails:"");

    doc.text(110, 200, resp.vehicleGaragedAtProposersHome?resp.vehicleGaragedAtProposersHome:"");

    doc.text(110, 210, resp.vehicleGaragedAtProposersHomeDetails?resp.vehicleGaragedAtProposersHomeDetails:"");

    doc.text(110, 220, resp.vehicleKeptIn?resp.vehicleKeptIn:"");

    doc.addPage();

    doc.setFontSize("10");
    doc.setFontType("normal");

    doc.text(20, 20, "Is the proposer now insured or was previously insured in respect of any vehicle(s)");

    doc.text(20, 40, "If yes, state the name and address of the Insurance Company:");

    doc.text(20, 50, "Is the proposer entitled to No Claim Discount from previous Insurer(s) In respect of any vehicle(s) described in the ");

    doc.text(20, 55, "proposal?")

    doc.text(20, 60, "If yes, please attach proof of No Claim Discount Letter or Renewal Notice.");

    doc.text(20, 70, "Do you have any other Insurance(s) with IronRock Insurance Company Ltd.?");

    doc.text(20, 80, "If yes, please state type(s):");

    doc.text(20, 90, "Has any Insurer(s) in respect of the Proposer or any other Person who will regularly drive ever?");

    doc.text(20, 130, "If yes, please indicate above and give details:");

    doc.text(20, 140, "Type of Authorized Driver Clause:");

    doc.setFontType("bold");

    doc.text(20, 25, resp.proposerInsured?resp.proposerInsured:"");

    doc.text(20, 45, resp.proposerInsuranceDetails?resp.proposerInsuranceDetails:"");

    doc.text(50, 55, resp.proposerEntitledToNOClaimDiscount?resp.proposerEntitledToNOClaimDiscount:"")

    doc.text(20, 75, resp.applicantOtherInsurer?resp.applicantOtherInsurer:"");

    doc.text(20, 85, resp.applicantOtherInsurerType?resp.applicantOtherInsurerType:"");

    doc.text(20, 125, resp.applicantPreviouslyInsured?resp.applicantPreviouslyInsured:"" );

    doc.text(20, 135, resp.ApplicantPreviouslyInsuredDetails?resp.ApplicantPreviouslyInsuredDetails:"");

    doc.text(20, 145, resp.typeOfAuthorizedDriver?resp.typeOfAuthorizedDriver:"");

    doc.addPage();

    doc.setFontType("normal");
    doc.text(20, 20, "Have you or any regular drivers had any accidents or losses during the past three(3) years (whether insured ");

    doc.text(20, 25, "or not in respect of all vehicles)");

    doc.text(20, 30, "I. Owned by you, whether or not you were the driver at the material time?");

    doc.text(20, 35, "II. Not owned by you, but driven by you or in your custody at the material time?");

    doc.text(20, 45, "If yes, please give details below");

    doc.text(20, 80, "To the best of your knowledge and belief have you, or any person who to your knowledge");

    doc.text(20, 85, "will drive have suffered from, or now suffer from:");

    doc.text(20, 100, "If yes, please indicate above and give details:");

    doc.text(20, 110, "Have you or any person who to your knowledge will drive received any traffic ticket(s) and");

    doc.text(20, 115, "or have been convicted of any offence in connection with the driving of any motor vehicle within the ");

    doc.text(20, 120, "last three (3) years?");

    doc.text(20, 130, "If yes, please give details:");

    doc.text(20, 140, "has the vehicle been modified or converted from maker's standard specification or do you intend to do so?");

    doc.text(20, 150, "If yes, please give details:");

    doc.text(20, 160, "Do you require increased limits (in excess of the Standard Limits)");

    doc.setFontType("bold");

    doc.text(20, 20, "Have you or any regular drivers had any accidents or losses during the past three(3) years (whether insured ");

    doc.text(20, 25, "or not in respect of all vehicles)");

    doc.text(20, 30, "I. Owned by you, whether or not you were the driver at the material time?");

    doc.text(20, 35, "II. Not owned by you, but driven by you or in your custody at the material time?");

    doc.text(20, 45, "If yes, please give details below");

    doc.text(20, 80, "To the best of your knowledge and belief have you, or any person who to your knowledge");

    doc.text(20, 85, "will drive have suffered from, or now suffer from:");

    doc.text(20, 100, "If yes, please indicate above and give details:");

    doc.text(20, 110, "Have you or any person who to your knowledge will drive received any traffic ticket(s) and");

    doc.text(20, 115, "or have been convicted of any offence in connection with the driving of any motor vehicle within the ");

    doc.text(20, 120, "last three (3) years?");

    doc.text(20, 130, "If yes, please give details:");

    doc.text(20, 140, "has the vehicle been modified or converted from maker's standard specification or do you intend to do so?");

    doc.text(20, 150, "If yes, please give details:");

    doc.text(20, 160, "Do you require increased limits (in excess of the Standard Limits)");

    doc.addPage();
    function ProperPDF(resp){

    doc.setFontType("bold");
    doc.setFontSize(10);
    doc.setFont("times");

    if(resp.regularDriversDL0){
        doc.text(20, 160, "uhkhkjnnjknk");
        doc.text(50, 160, "klmlkmlkmlkm");
        doc.text(100, 160, "llmllmlml");
        doc.text(150, 160, "kjnknknknk");

    }
    if(resp.regularDriversDL1){
        doc.text(20, 170, resp.regularDriversName1);
        doc.text(50, 170, resp.regularDriversDL1);
        doc.text(100, 170, resp.regularDriversName1);
        doc.text(150, 170, resp.regularDriversName1);

    }
    if(resp.regularDriversDL2){
        doc.text(20, 180, resp.regularDriversName1);
        doc.text(50, 180, resp.regularDriversDL1);
        doc.text(100, 180, resp.regularDriversName1);
        doc.text(150, 180, resp.regularDriversName1);

    }
}

}

function ProperPDF(resp){

    doc.setFontType("bold");
    doc.setFontSize(10);
    doc.setFont("times");

    doc.text(20, 20, "Particulars Of Home To Be Insured");

    doc.text(20, 60, "Construction of Dwelling");

    doc.text(20, 110, "Garages or Out Buildings?");

    doc.setFontType("normal");

    doc.text( 20, 30, "Risk Address:");

    doc.text(20, 40, "Is the home:");

    doc.text(20, 80, "External Walls");

    doc.text(100, 80, "Roof:");

    doc.text(20, 100, "Internal Walls:");

    doc.text(20, 120, "External walls:");

    doc.text(20, 140, "Internal Walls:");

    doc.text(100, 120, "Roof:");

    doc.text(20, 160, "Are the buildings in good state of repairs and will be so maintained?");

    doc.text(20, 180, "Is the Dwelling occupied solely by you, your family and domestic employees?");

    doc.text(20, 190, "If no, give the details of other occupants:");

    doc.text(20, 200, "Is any part of the Dwelling or Outbuilding used for any income-earning activity?");

    doc.text(20, 210, "If yes, give details:");

    doc.text(20, 220, "Are all externally communicating doors, windows and other openings grilled?");

    doc.text(20, 230, "If no, describe the security arrangements in place:");

    doc.text(20, 240, "Does any institution or individual have a financial interest in the Property:");

    doc.text(20, 250, "If yes, state their name and address:");

    doc.text(20, 260, "Are there any Waterside Structures i.e. docks, jetties, piers, sea walls and any other structure abutting the sea, a river or any other body of water?");

    if(resp.regularDriversDL0){
        doc.text(20, 160, "uhkhkjnnjknk");
        doc.text(50, 160, "klmlkmlkmlkm");
        doc.text(100, 160, "llmllmlml");
        doc.text(150, 160, "kjnknknknk");

    }
    if(resp.regularDriversDL1){
        doc.text(20, 170, resp.regularDriversName1);
        doc.text(50, 170, resp.regularDriversDL1);
        doc.text(100, 170, resp.regularDriversName1);
        doc.text(150, 170, resp.regularDriversName1);

    }
    if(resp.regularDriversDL2){
        doc.text(20, 180, resp.regularDriversName1);
        doc.text(50, 180, resp.regularDriversDL1);
        doc.text(100, 180, resp.regularDriversName1);
        doc.text(150, 180, resp.regularDriversName1);

    }
}<|endoftext|>


<commit_before>import _curry2 from './internal/_curry2';
import equals from './equals';
import takeLast from './takeLast';

/**
 * Checks if a list ends with the provided sublist.
 *
 * Similarly, checks if a string ends with the provided substring.
 *
 * @func
 * @memberOf R
 * @since v0.24.0
 * @category List
 * @sig [a] -> [a] -> Boolean
 * @sig String -> String -> Boolean
 * @param {*} suffix
 * @param {*} list
 * @return {Boolean}
 *  * @see R.startsWith
 * @example
 *
 *      R.endsWith('c', 'abc')                //=> true
 *      R.endsWith('b', 'abc')                //=> false
 *      R.endsWith(['c'], ['a', 'b', 'c'])    //=> true
 *      R.endsWith(['b'], ['a', 'b', 'c'])    //=> false
 */
var endsWith = _curry2(function(suffix, list) {
  return equals(takeLast(suffix.length, list), suffix);
});
export default endsWith;
<commit_msg>Update endsWith.js<commit_after>import _curry2 from './internal/_curry2';
import equals from './equals';
import takeLast from './takeLast';

/**
 * Checks if a list ends with the provided sublist.
 *
 * Similarly, checks if a string ends with the provided substring.
 *
 * @func
 * @memberOf R
 * @since v0.24.0
 * @category List
 * @sig [a] -> [a] -> Boolean
 * @sig String -> String -> Boolean
 * @param {*} suffix
 * @param {*} list
 * @return {Boolean}
 * @see R.startsWith
 * @example
 *
 *      R.endsWith('c', 'abc')                //=> true
 *      R.endsWith('b', 'abc')                //=> false
 *      R.endsWith(['c'], ['a', 'b', 'c'])    //=> true
 *      R.endsWith(['b'], ['a', 'b', 'c'])    //=> false
 */
var endsWith = _curry2(function(suffix, list) {
  return equals(takeLast(suffix.length, list), suffix);
});
export default endsWith;
<|endoftext|>


<commit_before>import RNTest from './react-native-testkit/'
import React from 'react'
import RNFetchBlob from 'react-native-fetch-blob'

import {
  StyleSheet,
  Text,
  View,
  ScrollView,
  CameraRoll,
  Platform,
  Dimensions,
  Image,
} from 'react-native';

const fs = RNFetchBlob.fs
const { Assert, Comparer, Info, prop } = RNTest
const describe = RNTest.config({
  group : '0.6.2',
  run : true,
  expand : false,
  timeout : 12000,
})
const { TEST_SERVER_URL_SSL, DROPBOX_TOKEN, styles } = prop()
const  dirs = RNFetchBlob.fs.dirs

let prefix = ((Platform.OS === 'android') ? 'file://' : '')

describe('upload asset from camera roll', (report, done) => {
  let imgName = `image-from-camera-roll-${Platform.OS}.jpg`
  CameraRoll.getPhotos({first : 10})
    .then((resp) => {
      let url = resp.edges[0].node.image.uri
      return fs.readFile(url, 'base64')
    })
    .then((data) => {
      return RNFetchBlob.fetch('POST', 'https://content.dropboxapi.com/2/files/upload', {
        Authorization : `Bearer ${DROPBOX_TOKEN}`,
        'Dropbox-API-Arg': `{\"path\": \"/rn-upload/${imgName}\",\"mode\": \"add\",\"autorename\": false,\"mute\": false}`,
        'Content-Type' : 'application/octet-stream',
      }, data)
    })
    .then((resp) => {
      resp = resp.json()
      report(
        <Assert key="confirm the file has been uploaded" expect={imgName} actual={resp.name}/>
      )
      done()
    })

})

describe('access assets from camera roll', (report, done) => {
  let photo = null
  CameraRoll.getPhotos({first : 10})
    .then((resp) => {
      photo = resp.edges[0].node.image.uri
      report(<Info key="items">
        <Text>{photo}</Text>
      </Info>)
      return fs.readFile(photo, 'base64')
    })
    .then((data) => {
      report(<Info key="asset image">
        <Image
          style={styles.image}
          source={{uri: `data:image/png;base64, ${data}`}}/>
      </Info>)
      done()
    })
})

describe('read asset in app bundle',(report, done) => {
  let target = fs.asset('test-asset2.png')
  fs.readFile(target, 'base64')
  .then((data) => {
    report(<Info key="asset image">
      <Image
        style={styles.image}
        source={{uri: `data:image/png;base64, ${data}`}}/>
    </Info>)
    return fs.readFile(fs.asset('test-asset1.json'), 'utf8')
  })
  .then((resp) => {
    report(
      <Assert key="asset content verify"
        expect="asset#1"
        actual={JSON.parse(resp).secret}/>)
      done()
  })
})

describe('stat assets in app', (report, done) => {
  fs.stat(fs.asset('test-asset2.png'))
    .then((data) => {
      report(<Info key="list of assets">
        <Text>{JSON.stringify(data)}</Text>
      </Info>)
      done()
    })
})

describe('copy asset', (report, done) => {
  let dest = `${dirs.DocumentDir}/test-asset-1-${Date.now()}.json`
  fs.cp(fs.asset('test-asset1.json'), dest)
    .then(() => fs.readFile(dest, 'utf8'))
    .then((data) => {
      report(<Assert key="asset copied correctly"
        expect={'asset#1'}
        actual={JSON.parse(data).secret}/>)
      return fs.stat(fs.asset('test-asset1.json'))
    })
    .then((stat) => {
      report(<Assert key="file size check"
        expect={27}
        actual={Math.floor(stat.size)}/>,
      <Info key="dest file info">
        <Text>{JSON.stringify(stat)}</Text>
      </Info>)
      done()
    })
})
<commit_msg>Add test cases #45<commit_after>import RNTest from './react-native-testkit/'
import React from 'react'
import RNFetchBlob from 'react-native-fetch-blob'

import {
  StyleSheet,
  Text,
  View,
  ScrollView,
  CameraRoll,
  Platform,
  Dimensions,
  Image,
} from 'react-native';

const fs = RNFetchBlob.fs
const { Assert, Comparer, Info, prop } = RNTest
const describe = RNTest.config({
  group : '0.6.2',
  run : true,
  expand : false,
  timeout : 12000,
})
const { TEST_SERVER_URL, TEST_SERVER_URL_SSL, DROPBOX_TOKEN, styles } = prop()
const  dirs = RNFetchBlob.fs.dirs

let prefix = ((Platform.OS === 'android') ? 'file://' : '')
let photo = null

describe('upload asset from camera roll', (report, done) => {
  let imgName = `image-from-camera-roll-${Platform.OS}.jpg`
  CameraRoll.getPhotos({first : 10})
    .then((resp) => {
      let url = resp.edges[0].node.image.uri
      photo = url
      return RNFetchBlob.fetch('POST', 'https://content.dropboxapi.com/2/files/upload', {
        Authorization : `Bearer ${DROPBOX_TOKEN}`,
        'Dropbox-API-Arg': `{\"path\": \"/rn-upload/${imgName}\",\"mode\": \"add\",\"autorename\": false,\"mute\": false}`,
        'Content-Type' : 'application/octet-stream',
      }, RNFetchBlob.wrap(url))
    })
    .then((resp) => {
      resp = resp.json()
      report(
        <Assert key="confirm the file has been uploaded" expect={imgName} actual={resp.name}/>
      )
      done()
    })
})

describe('Upload multipart data with file from CameraRoll', (report, done) => {
    let filename = 'test-from-storage-img-'+Date.now()+'.png'
    RNFetchBlob.fetch('POST', `${TEST_SERVER_URL}/upload-form`, {
        'Content-Type' : 'multipart/form-data',
      }, [
        { name : 'test-img', filename : filename, data: RNFetchBlob.wrap(photo)},
        { name : 'test-text', filename : 'test-text.txt', data: RNFetchBlob.base64.encode('hello.txt')},
        { name : 'field1', data : 'hello !!'},
        { name : 'field2', data : 'hello2 !!'}
      ])
    .then((resp) => {
      resp = resp.json()
      report(
        <Assert key="check posted form data #1" expect="hello !!" actual={resp.fields.field1}/>,
        <Assert key="check posted form data #2" expect="hello2 !!" actual={resp.fields.field2}/>,
      )
      return RNFetchBlob.fetch('GET', `${TEST_SERVER_URL}/public/${filename}`)
    })
    .then((resp) => {
      report(<Info key="uploaded image">
        <Image
          style={styles.image}
          source={{ uri : 'data:image/png;base64, '+ resp.base64()}}/>
      </Info>)
      done()
    })
})

//
// describe('access assets from camera roll', (report, done) => {
//   let photo = null
//   CameraRoll.getPhotos({first : 10})
//     .then((resp) => {
//       photo = resp.edges[0].node.image.uri
//       report(<Info key="items">
//         <Text>{photo}</Text>
//       </Info>)
//       return fs.readFile(photo, 'base64')
//     })
//     .then((data) => {
//       report(<Info key="asset image">
//         <Image
//           style={styles.image}
//           source={{uri: `data:image/png;base64, ${data}`}}/>
//       </Info>)
//       done()
//     })
// })
//
// describe('read asset in app bundle',(report, done) => {
//   let target = fs.asset('test-asset2.png')
//   fs.readFile(target, 'base64')
//   .then((data) => {
//     report(<Info key="asset image">
//       <Image
//         style={styles.image}
//         source={{uri: `data:image/png;base64, ${data}`}}/>
//     </Info>)
//     return fs.readFile(fs.asset('test-asset1.json'), 'utf8')
//   })
//   .then((resp) => {
//     report(
//       <Assert key="asset content verify"
//         expect="asset#1"
//         actual={JSON.parse(resp).secret}/>)
//       done()
//   })
// })
//
// describe('stat assets in app', (report, done) => {
//   fs.stat(fs.asset('test-asset2.png'))
//     .then((data) => {
//       report(<Info key="list of assets">
//         <Text>{JSON.stringify(data)}</Text>
//       </Info>)
//       done()
//     })
// })
//
// describe('copy asset', (report, done) => {
//   let dest = `${dirs.DocumentDir}/test-asset-1-${Date.now()}.json`
//   fs.cp(fs.asset('test-asset1.json'), dest)
//     .then(() => fs.readFile(dest, 'utf8'))
//     .then((data) => {
//       report(<Assert key="asset copied correctly"
//         expect={'asset#1'}
//         actual={JSON.parse(data).secret}/>)
//       return fs.stat(fs.asset('test-asset1.json'))
//     })
//     .then((stat) => {
//       report(<Assert key="file size check"
//         expect={27}
//         actual={Math.floor(stat.size)}/>,
//       <Info key="dest file info">
//         <Text>{JSON.stringify(stat)}</Text>
//       </Info>)
//       done()
//     })
// })
<|endoftext|>


<commit_before>$(document).ready(function(){

	//parcel details
	$.ajax({
		type:"GET",
		url:"http://zoomcar-ui.0x10.info/api/courier?type=json&query=list_parcel",
		cache:false,
		dataType:"json",
		success:function(data){
			$('span.parcel-count').text(data.parcels.length);
			var parcelTemplateScript = $('#parcel-template').html();
			var parcelTemplate = Handlebars.compile(parcelTemplateScript);
			var parcelHtml = parcelTemplate(data);
			$('section > .row').html(parcelHtml).find('div').last();

			// Instantiate MixItUp:
			$('#parcel-item-container').mixItUp();

			$('.parcel-item a').on('click',function(){

				var modalTemplateScript = $('#modal-template').html();
				var modalTemplate = Handlebars.compile(modalTemplateScript);

				var $this = $(this),
				    data = $this.parents('.parcel-item'),
					templateData = {
					    name : data.find('h2[data-name]').data('name'),
					    date : data.find('p[data-date]').data('date'),
					    type : data.find('p[data-type]').data('type'),
					    weight : data.find('p[data-weight]').data('weight'),
					    price : data.find('p[data-price]').data('price'),
					    quantity : data.find('p[data-qty]').data('qty'),
					    image : data.find('.parcel-image[data-image]').data('image'),
					    color : data.find('p[data-color]').data('color'),
					    phone : data.find('p[data-phone]').data('phone')
					};

				var modalHtml = modalTemplate(templateData);
				$('.product-info').remove();
				$('#parcel-window > .fake-modal-wrapper').prepend(modalHtml);

				//Like button click - Local Storage
				$('.like-button').on('click',function(){
					var $this = $(this);
					var count=1;
					var key = $this.parents('#parcel-window').find('.product-info').data('uid');
					if(localStorage[key]){
						count += parseInt(localStorage[key]);
						localStorage[key] = count;
					}else{
						localStorage[key] = count;
					}
					$this.find('span.like-count').text(count);
				});

				//Map Refresh button click
				$('.map-refresh-button').on('click',function(){
					var $this = $(this);
					var uid = $this.parents('#parcel-window').find('.product-info').data('uid');
					getCoordinates(uid);
				});
				//$('#parcel-window').foundation('reveal','open');
				$('#map_canvas').empty();
				getCoordinates($this.parents('.parcel-item').data('uid'));

				//Like Count Init
				var likes = getLikeCount($this.parents('.parcel-item').data('uid'));
				if(likes){
					$('#parcel-window span.like-count').text(likes);
				}else{
					$('#parcel-window span.like-count').text(0);
				}

				$('#parcel-window').toggleClass('hidden');
				$('html').toggleClass('noscroll');
			});
		},
		error:function(xhr,status,error){
			alert('error');
		}
	});

	$('.dropdown a').on('click',function(e){
		$(this).next('ul').slideToggle();
		e.stopPropagation();
	});
	$('html').on('click',function(){
		if($('.dropdown ul').is(':visible')){
			$('.dropdown ul').slideToggle();
		}
	});

	$('#search-input').on('keyup',function(e){
		var $this = $(this);
		var query = $this.val();

		searchParcels(query);
	});
	//sort asc desc switch pending
	/*var sortHistory;
	$('button.sort').on('click',function(){
		var $this = $(this);
		var sort= $this.data('sort').split(':');
		if(sortHistory === sort[0]){
			if(sort[1]==="asc"){
				$this.data('sort',sort[0]+':desc');
			}else{
				$this.data('sort',sort[0]+':asc');
			}
		}else{
			sortHistory = sort[0];
		}
	});

	$('button.sort-type').on('click',function(){
		var $this = $(this);
		var type = $this.data('type');
		$('button.sort').each(function(){
			$(this).data('sort',$(this).data('sort').split(':')[0]+':'+type);
		});
		$this.siblings().prop('disabled',false);
		$this.prop('disabled',true);
	});	*/

	$('#parcel-window').on('click',function(){
		if($(this).is(':visible')){
			$(this).toggleClass('hidden');
			$('html').toggleClass('noscroll');
		}
	});
	$('a.close-window').on('click',function(){
		$(this).parents('#parcel-window').toggleClass('hidden');
		$('html').toggleClass('noscroll');
	});
	$('.fake-modal-wrapper').on('click',function(e){
		e.stopPropagation();
	});
	//api hits
	$.ajax({
		type:"GET",
		url:"http://zoomcar-ui.0x10.info/api/courier?type=json&query=api_hits",
		cache:false,
		dataType:"json",
		success:function(data){
			console.log(data);
		},
		error:function(xhr,status,error){
			alert('error');
		}
	});
});

function getCoordinates(uid){
	$.ajax({
		type:"GET",
		url:"http://zoomcar-ui.0x10.info/api/courier?type=json&query=list_parcel",
		cache:false,
		dataType:"json",
		success:function(data){
			for(var i=0;i<data.parcels.length;i++){
				if(data.parcels[i].color===uid){
					createMap(data.parcels[i].live_location.latitude,data.parcels[i].live_location.longitude);
					return;
				}
			}
		},
		error:function(xhr,status,error){
		}
	});
}

function createMap(lat,lng){
	var latlng = new google.maps.LatLng(lat, lng),
        image = 'http://www.google.com/intl/en_us/mapfiles/ms/micons/blue-dot.png',
        mapOptions = {
             center: new google.maps.LatLng(lat, lng),
             zoom: 13,
             mapTypeId: google.maps.MapTypeId.ROADMAP,
             panControl: true,
             panControlOptions: {
                 position: google.maps.ControlPosition.TOP_RIGHT
             },
             zoomControl: true,
             zoomControlOptions: {
                 style: google.maps.ZoomControlStyle.LARGE,
                 position: google.maps.ControlPosition.TOP_left
             }
         };
        map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions),
        marker = new google.maps.Marker({
                 position: latlng,
                 map: map,
                 icon: image
             });

        //marker.setIcon(image);
		//marker.setPosition(latlng);
	    //infowindow.setContent(placeName);
	var infowindow = new google.maps.InfoWindow();

    google.maps.event.addListener(map, 'click', function (event) {
         infowindow.close();
         var geocoder = new google.maps.Geocoder();
         geocoder.geocode({
             "latLng":event.latLng
         }, function (results, status) {
             console.log(results, status);
             if (status == google.maps.GeocoderStatus.OK) {
                 console.log(results);
                 var lat = results[0].geometry.location.lat(),
                     lng = results[0].geometry.location.lng(),
                     placeName = results[0].address_components[0].long_name,
                     latlng = new google.maps.LatLng(lat, lng);

                 marker.setIcon(image);
			     marker.setPosition(latlng);
			     infowindow.setContent(placeName);
             }
         });
    });
}

function moveMarker(placeName, latlng) {

     //infowindow.open(map, marker);
 }

 function getLikeCount(uid){
 	if(localStorage[uid]){
 		return localStorage[uid];
 	}else{
 		return null;
 	}
 }

 function searchParcels(query){
 	var searchSet = $('#parcel-item-container .parcel-item');

 	searchSet.each(function(index){
 		var name = $(this).data('name').toString();
 		var weight = $(this).data('weight').toString();
 		var price = $(this).data('price').toString();

 		if(name.toLowerCase().indexOf(query) != -1 || weight.toLowerCase().indexOf(query) != -1 || price.toLowerCase().indexOf(query) != -1 ){
 			$(this).fadeIn(400);
 		}else{
 			$(this).fadeOut(400);
 		}
 	});
 }<commit_msg>changes<commit_after>$(document).ready(function(){

	//parcel details
	$.ajax({
		type:"GET",
		url:"http://zoomcar-ui.0x10.info/api/courier?type=json&query=list_parcel",
		cache:false,
		dataType:"json",
		success:function(data){
			$('span.parcel-count').text(data.parcels.length);
			var parcelTemplateScript = $('#parcel-template').html();
			var parcelTemplate = Handlebars.compile(parcelTemplateScript);
			var parcelHtml = parcelTemplate(data);
			$('section > .row').html(parcelHtml).find('div').last();

			// Instantiate MixItUp:
			$('#parcel-item-container').mixItUp();

			$('.parcel-item a').on('click',function(){

				var modalTemplateScript = $('#modal-template').html();
				var modalTemplate = Handlebars.compile(modalTemplateScript);

				var $this = $(this),
				    data = $this.parents('.parcel-item'),
					templateData = {
					    name : data.find('h2[data-name]').data('name'),
					    date : data.find('p[data-date]').data('date'),
					    type : data.find('p[data-type]').data('type'),
					    weight : data.find('p[data-weight]').data('weight'),
					    price : data.find('p[data-price]').data('price'),
					    quantity : data.find('p[data-qty]').data('qty'),
					    image : data.find('.parcel-image[data-image]').data('image'),
					    color : data.find('p[data-color]').data('color'),
					    phone : data.find('p[data-phone]').data('phone')
					};

				var modalHtml = modalTemplate(templateData);
				$('.product-info').remove();
				$('#parcel-window > .fake-modal-wrapper').prepend(modalHtml);

				//Like button click - Local Storage
				$('.like-button').on('click',function(){
					var $this = $(this);
					var count=1;
					var key = $this.parents('#parcel-window').find('.product-info').data('uid');
					if(localStorage[key]){
						count += parseInt(localStorage[key]);
						localStorage[key] = count;
					}else{
						localStorage[key] = count;
					}
					$this.find('span.like-count').text(count);
				});

				//Map Refresh button click
				$('.map-refresh-button').on('click',function(){
					var $this = $(this);
					var uid = $this.parents('#parcel-window').find('.product-info').data('uid');
					getCoordinates(uid);
				});
				//$('#parcel-window').foundation('reveal','open');
				$('#map_canvas').empty();
				getCoordinates($this.parents('.parcel-item').data('uid'));

				//Like Count Init
				var likes = getLikeCount($this.parents('.parcel-item').data('uid'));
				if(likes){
					$('#parcel-window span.like-count').text(likes);
				}else{
					$('#parcel-window span.like-count').text(0);
				}

				$('#parcel-window').toggleClass('hidden');
				$('html').toggleClass('noscroll');
			});
		},
		error:function(xhr,status,error){
			alert('error');
		}
	});

	$('.dropdown a').on('click',function(e){
		$(this).next('ul').slideToggle();
		e.stopPropagation();
	});
	$('html').on('click',function(){
		if($('.dropdown ul').is(':visible')){
			$('.dropdown ul').slideToggle();
		}
	});

	$('#search-input').on('keyup',function(e){
		var $this = $(this);
		var query = $this.val();

		searchParcels(query);
	});
	//sort asc desc switch pending
	/*var sortHistory;
	$('button.sort').on('click',function(){
		var $this = $(this);
		var sort= $this.data('sort').split(':');
		if(sortHistory === sort[0]){
			if(sort[1]==="asc"){
				$this.data('sort',sort[0]+':desc');
			}else{
				$this.data('sort',sort[0]+':asc');
			}
		}else{
			sortHistory = sort[0];
		}
	});

	$('button.sort-type').on('click',function(){
		var $this = $(this);
		var type = $this.data('type');
		$('button.sort').each(function(){
			$(this).data('sort',$(this).data('sort').split(':')[0]+':'+type);
		});
		$this.siblings().prop('disabled',false);
		$this.prop('disabled',true);
	});	*/

	$('#parcel-window').on('click',function(){
		if($(this).is(':visible')){
			$(this).toggleClass('hidden');
			$('html').toggleClass('noscroll');
		}
	});
	$('a.close-window').on('click',function(){
		$(this).parents('#parcel-window').toggleClass('hidden');
		$('html').toggleClass('noscroll');
	});
	$('.fake-modal-wrapper').on('click',function(e){
		e.stopPropagation();
	});
	//api hits
	$.ajax({
		type:"GET",
		url:"http://zoomcar-ui.0x10.info/api/courier?type=json&query=api_hits",
		cache:false,
		dataType:"json",
		success:function(data){
			console.log(data);
		},
		error:function(xhr,status,error){
			alert('error');
		}
	});
});

function getCoordinates(uid){
	$.ajax({
		type:"GET",
		url:"http://zoomcar-ui.0x10.info/api/courier?type=json&query=list_parcel",
		cache:false,
		dataType:"json",
		success:function(data){
			for(var i=0;i<data.parcels.length;i++){
				if(data.parcels[i].color===uid){
					createMap(data.parcels[i].live_location.latitude,data.parcels[i].live_location.longitude);
					return;
				}
			}
		},
		error:function(xhr,status,error){
		}
	});
}

function createMap(lat,lng){
	var latlng = new google.maps.LatLng(lat, lng),
        image = 'http://www.google.com/intl/en_us/mapfiles/ms/micons/blue-dot.png',
        mapOptions = {
             center: new google.maps.LatLng(lat, lng),
             zoom: 13,
             mapTypeId: google.maps.MapTypeId.ROADMAP,
             panControl: true,
             panControlOptions: {
                 position: google.maps.ControlPosition.TOP_RIGHT
             },
             zoomControl: true,
             zoomControlOptions: {
                 style: google.maps.ZoomControlStyle.LARGE,
                 position: google.maps.ControlPosition.TOP_left
             }
         };
        map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions),
        marker = new google.maps.Marker({
                 position: latlng,
                 map: map,
                 icon: image
             });

        //marker.setIcon(image);
		//marker.setPosition(latlng);
	    //infowindow.setContent(placeName);
	var infowindow = new google.maps.InfoWindow();

    google.maps.event.addListener(map, 'click', function (event) {
         infowindow.close();
         var geocoder = new google.maps.Geocoder();
         geocoder.geocode({
             "latLng":event.latLng
         }, function (results, status) {
             console.log(results, status);
             if (status == google.maps.GeocoderStatus.OK) {
                 console.log(results);
                 var lat = results[0].geometry.location.lat(),
                     lng = results[0].geometry.location.lng(),
                     placeName = results[0].address_components[0].long_name,
                     latlng = new google.maps.LatLng(lat, lng);

                 marker.setIcon(image);
			     marker.setPosition(latlng);
			     infowindow.setContent(placeName);
             }
         });
    });
}

function moveMarker(placeName, latlng) {

     //infowindow.open(map, marker);
 }

 function getLikeCount(uid){
 	if(localStorage[uid]){
 		return localStorage[uid];
 	}else{
 		return null;
 	}
 }

 function searchParcels(query){
 	var searchSet = $('#parcel-item-container .parcel-item');

 	searchSet.each(function(index){
 		var name = $(this).data('name').toLowerCase();
 		var weight = $(this).data('weight').toString();
 		var price = $(this).data('price').toString();

 		if(name.indexOf(query) != -1 || weight.indexOf(query) != -1 || price.indexOf(query) != -1 ){
 			$(this).fadeIn(400);
 		}else{
 			$(this).fadeOut(400);
 		}
 	});
 }<|endoftext|>


<commit_before>'use strict';
/* global it, expect */

var h = require('../helpers');

h.describe('Graph API methods', function() {
    it('can get me', function() {
        h.runAsync(function(done) {
            h.request('GET', h.baseURL + 'graph/me').end(function(res) {
                expect(res.statusCode).toBe(200);

                // Make sure we get nodes and links
                expect(typeof res.body.nodes).toEqual('object');
                expect(typeof res.body.links).toEqual('object');

                // Check that there's the right amount of nodes and links
                var nodeKeys = Object.keys(res.body.nodes);
                expect(nodeKeys.length).toBe(5);
                expect(res.body.links.length).toBe(4);

                // Validate all the nodes
                nodeKeys.forEach(function(id) {
                    var node = res.body.nodes[id];

                    expect(typeof node.id).toBe('string');
                    expect(typeof node.type).toBe('string');
                    expect(typeof node.team).toBe('string');
                    switch (node.type) {
                    case 'me':
                        expect(typeof node.fullName).toBe('string');
                        expect(typeof node.coordX).toBe('number');
                        expect(typeof node.coordY).toBe('number');
                        break;
                    case 'user':
                        expect(typeof node.fullName).toBe('string');
                        break;
                    case 'friendOfFriend':
						expect(typeof node.fullName).toBe('undefined');
                        break;
                    case 'default':
                        expect('unkown node type').toBe('never happening');
                    }
                });

                // TODO: check that not too much information is exposed (no names or num activity infos for friends of friends)
                done();
            });
        });
    });

    it('cannot get graph of a full user if not logged in as that user', function() {
        h.runAsync(function(done) {
            h.request('GET', h.baseURL + 'graph/000000000000000000000001').end(function(res) {
                expect(res.statusCode).toBe(403);
                done();
            });
        }) ;
    });

    it('can get graph of a maybe user', function() {
        h.runAsync(function(done) {
            h.request('GET', h.baseURL + 'graph/000000000000000000000003').end(function(res) {
                expect(res.statusCode).toBe(200);

                expect(typeof res.body.nodes).toEqual('object');
                expect(typeof res.body.links).toEqual('object');
                expect(Object.keys(res.body.nodes).length).toBe(4); // 1 me, 1 the other use, 2 friends of that friend
                expect(res.body.links.length).toBe(3);
                done();
            });
        });
    });
});
<commit_msg>Use toBeUndefined matcher.<commit_after>'use strict';
/* global it, expect */

var h = require('../helpers');

h.describe('Graph API methods', function() {
    it('can get me', function() {
        h.runAsync(function(done) {
            h.request('GET', h.baseURL + 'graph/me').end(function(res) {
                expect(res.statusCode).toBe(200);

                // Make sure we get nodes and links
                expect(typeof res.body.nodes).toEqual('object');
                expect(typeof res.body.links).toEqual('object');

                // Check that there's the right amount of nodes and links
                var nodeKeys = Object.keys(res.body.nodes);
                expect(nodeKeys.length).toBe(5);
                expect(res.body.links.length).toBe(4);

                // Validate all the nodes
                nodeKeys.forEach(function(id) {
                    var node = res.body.nodes[id];

                    expect(typeof node.id).toBe('string');
                    expect(typeof node.type).toBe('string');
                    expect(typeof node.team).toBe('string');
                    switch (node.type) {
                    case 'me':
                        expect(typeof node.fullName).toBe('string');
                        expect(typeof node.coordX).toBe('number');
                        expect(typeof node.coordY).toBe('number');
                        break;
                    case 'user':
                        expect(typeof node.fullName).toBe('string');
                        break;
                    case 'friendOfFriend':
						expect(node.fullName).toBeUndefined();
                        break;
                    case 'default':
                        expect('unkown node type').toBe('never happening');
                    }
                });

                // TODO: check that not too much information is exposed (no names or num activity infos for friends of friends)
                done();
            });
        });
    });

    it('cannot get graph of a full user if not logged in as that user', function() {
        h.runAsync(function(done) {
            h.request('GET', h.baseURL + 'graph/000000000000000000000001').end(function(res) {
                expect(res.statusCode).toBe(403);
                done();
            });
        }) ;
    });

    it('can get graph of a maybe user', function() {
        h.runAsync(function(done) {
            h.request('GET', h.baseURL + 'graph/000000000000000000000003').end(function(res) {
                expect(res.statusCode).toBe(200);

                expect(typeof res.body.nodes).toEqual('object');
                expect(typeof res.body.links).toEqual('object');
                expect(Object.keys(res.body.nodes).length).toBe(4); // 1 me, 1 the other use, 2 friends of that friend
                expect(res.body.links.length).toBe(3);
                done();
            });
        });
    });
});
<|endoftext|>