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

const Nodgine = require('../../src/nodgine');
const Wrapper = require('../../src/wrapper');

describe('Nodgine', () => {
    let instance;

    beforeEach(() => {
        instance = new Nodgine();
    });

    it('should be an instance of nodgine', () => {
        expect(instance).to.be.an.instanceof(Nodgine);
    });

    it('should initialize with an empty middleware list', () => {
        expect(instance._middleware).to.have.length(0);
    });

    it('should initialize with an empty controller list', () => {
        expect(instance._controller).to.have.length(0);
    });

    it('should initialize the missing route controller with an function', () => {
        expect(instance._missingRouteController).to.be.an('function');
    });

    it('should initialize the missing route controller with a function that sends 404 Not Found to the client', () => {
        let request = {};
        let response = {
            writtenString: undefined,
            statusCode: 0,
            write: (aBuffer) => {
                response.writtenString = aBuffer;
                return response;
            },
            setStatusCode: (aStatusCode) => {
                response.statusCode = aStatusCode;
                return response;
            }
        };

        function callMissingRouteController() {
            instance._missingRouteController(request, response);
        }

        expect(callMissingRouteController).not.to.throw();
        expect(response.statusCode).to.equal(404);
        expect(response.writtenString).to.be.an('string');
        expect(response.writtenString.toString()).to.equal('Not Found');
    });

    it('should add a middleware wrapper to the private list calling addMiddleware', () => {
        function callback() { }
        let route = '/test/it';

        instance.addMiddleware(route, callback);

        expect(instance._middleware).to.have.length(1);
        let wrapper = instance._middleware[0];

        expect(wrapper).to.be.an.instanceof(Wrapper);
        expect(wrapper._callback).to.equal(callback);
        expect(route).to.match(wrapper._routePattern);
    });

    it('should add a middleware wrapper to the private list calling addMiddleware with only a callback', () => {
        function callback() { }

        instance.addMiddleware(callback);

        expect(instance._middleware).to.have.length(1);
        let wrapper = instance._middleware[0];

        expect(wrapper).to.be.an.instanceof(Wrapper);
        expect(wrapper._callback).to.equal(callback);
        expect('/').to.match(wrapper._routePattern);
    });

    it('should set the private variable to given callback calling setMissingRouteController', () => {
        function callback() { }

        instance.setMissingRouteController(callback);
        expect(instance._missingRouteController).to.equal(callback);
    });

    [0, 1, 3.14, -2.7, 'test', true, false, [], {}, undefined, null].forEach((aValue) => {
        it('should throw an error calling setMissingRouteController with param type ' + toString.call(aValue), () => {
            function setMissingRouteController() {
                instance.setMissingRouteController(aValue);
            }

            expect(setMissingRouteController).to.throw(TypeError);
        });
    });

    [0, 1, 3.14, -2.7, true, false, [], {}, undefined, null].forEach((aValue) => {
        it('should throw an error calling addMiddlware with first param type ' + toString.call(aValue), () => {
            function addMiddleware() {
                instance.addMiddleware(aValue, () => { });
            }

            expect(addMiddleware).to.throw(TypeError);
        });
    });

    [0, 1, 3.14, -2.7, true, false, () => { }, [], {}, undefined, null].forEach((aValue) => {
        it('should throw an error calling addController with first param type ' + toString.call(aValue), () => {
            function addController() {
                instance.addController(aValue, () => { });
            }

            expect(addController).to.throw(TypeError);
        });
    });

    [0, 1, 3.14, -2.7, 'test', true, false, [], {}, undefined, null].forEach((aValue) => {
        it('should throw an error calling addMiddlware with second param type ' + toString.call(aValue), () => {
            function addMiddleware() {
                instance.addMiddleware('/*', aValue);
            }

            expect(addMiddleware).to.throw(TypeError);
        });
    });

    [0, 1, 3.14, -2.7, 'test', true, false, [], undefined, null].forEach((aValue) => {
        it('should throw an error calling addController with second param type ' + toString.call(aValue), () => {
            function addController() {
                instance.addController('/*', aValue);
            }

            expect(addController).to.throw(TypeError);
        });
    });

    it('should add a controller wrapper to the private list calling addController', () => {
        function callback() { }
        let route = '/test/it';

        instance.addController(route, callback);

        expect(instance._controller).to.have.length(1);
        let wrapper = instance._controller[0];

        expect(wrapper).to.be.an.instanceof(Wrapper);
        expect(wrapper._callback).to.equal(callback);
        expect(route).to.match(wrapper._routePattern);
    });

    it('should add a controller wrapper to the private list calling addController with an object', () => {
        let servelet = {};
        let route = '/test/it';

        instance.addController(route, servelet);

        expect(instance._controller).to.have.length(1);
        let wrapper = instance._controller[0];

        expect(wrapper).to.be.an.instanceof(Wrapper);
        expect(wrapper._callback).to.be.an('function');
    });

    it('should return a routing function calling getRouter', () => {
        expect(instance.getRouter()).to.be.an('function');
    });

    it('should return a routing function expecting two arguments calling getRouter', () => {
        let router = instance.getRouter();

        expect(router).to.have.length(2);
    });

    it('should run the correct controller calling _runController', () => {
        let calledCorrectController = false;
        let calledWrongController = false;
        let calledCorrectControllerWith = [];

        let request = {
            isRequest: true
        };
        let response = {
            isResponse: true
        };

        instance.addController('/wrong', () => {
            calledWrongController = true;
        });
        instance.addController('/ok', function () {
            calledCorrectController = true;
            calledCorrectControllerWith = Array.prototype.slice.call(arguments);
        });

        instance._runController('/ok', request, response);

        expect(calledWrongController).to.equal(false);
        expect(calledCorrectController).to.equal(true);

        expect(calledCorrectControllerWith).to.have.length(3);
        expect(calledCorrectControllerWith[0]).to.equal(request);
        expect(calledCorrectControllerWith[1]).to.equal(response);
        expect(calledCorrectControllerWith[2]).to.be.an('object');
        expect(Object.keys(calledCorrectControllerWith[2])).to.have.length(0);
    });

    it('should _runMiddleware return a promise', () => {
        instance.addMiddleware(() => { });
        let result = instance._runMiddleware('/ok', {}, {});

        expect(result).to.be.an.instanceof(Promise);
    });

    it('should run all fitting middleware', (done) => {
        let calledCorrectMiddleware1 = false;
        let calledCorrectMiddleware2 = false;
        let calledWrongMiddleware = false;
        let calledCorrectMiddlewareWith1 = [];
        let calledCorrectMiddlewareWith2 = [];

        let request = {
            isRequest: true
        };
        let response = {
            isResponse: true
        };

        instance.addMiddleware('/wrong', () => {
            calledWrongMiddleware = true;
        });
        instance.addMiddleware('/ok', function () {
            calledCorrectMiddleware1 = true;
            calledCorrectMiddlewareWith1 = Array.prototype.slice.call(arguments);
        });
        instance.addMiddleware(function () {
            calledCorrectMiddleware2 = true;
            calledCorrectMiddlewareWith2 = Array.prototype.slice.call(arguments);
        });

        let runPromise = instance._runMiddleware('/ok', request, response);

        runPromise
            .then(() => {
                expect(calledWrongMiddleware).to.equal(false);
                expect(calledCorrectMiddleware1).to.equal(true);
                expect(calledCorrectMiddleware2).to.equal(true);

                expect(calledCorrectMiddlewareWith1).to.have.length(3);
                expect(calledCorrectMiddlewareWith1[0]).to.equal(request);
                expect(calledCorrectMiddlewareWith1[1]).to.equal(response);
                expect(calledCorrectMiddlewareWith1[2]).to.be.an('object');
                expect(Object.keys(calledCorrectMiddlewareWith1[2])).to.have.length(0);

                expect(calledCorrectMiddlewareWith2).to.have.length(3);
                expect(calledCorrectMiddlewareWith2[0]).to.equal(request);
                expect(calledCorrectMiddlewareWith2[1]).to.equal(response);

                done();
            })
            .catch(() => {
                expect('This should not happen').to.equal(true);
                done();
            });
    });
});<commit_msg>Added more tests of the router function<commit_after>/* global describe,expect,it,beforeEach,Buffer */
'use strict';

const Nodgine = require('../../src/nodgine');
const Wrapper = require('../../src/wrapper');
const Request = require('../../src/request');
const Response = require('../../src/response');
const chai = require('chai');
const libEvents = require('events');

describe('Nodgine', () => {
    let instance;

    beforeEach(() => {
        instance = new Nodgine();
    });

    it('should be an instance of nodgine', () => {
        expect(instance).to.be.an.instanceof(Nodgine);
    });

    it('should initialize with an empty middleware list', () => {
        expect(instance._middleware).to.have.length(0);
    });

    it('should initialize with an empty controller list', () => {
        expect(instance._controller).to.have.length(0);
    });

    it('should initialize the missing route controller with an function', () => {
        expect(instance._missingRouteController).to.be.an('function');
    });

    it('should initialize the missing route controller with a function that sends 404 Not Found to the client', () => {
        let request = {};
        let response = {
            writtenString: undefined,
            statusCode: 0,
            write: (aBuffer) => {
                response.writtenString = aBuffer;
                return response;
            },
            setStatusCode: (aStatusCode) => {
                response.statusCode = aStatusCode;
                return response;
            }
        };

        function callMissingRouteController() {
            instance._missingRouteController(request, response);
        }

        expect(callMissingRouteController).not.to.throw();
        expect(response.statusCode).to.equal(404);
        expect(response.writtenString).to.be.an('string');
        expect(response.writtenString.toString()).to.equal('Not Found');
    });

    it('should add a middleware wrapper to the private list calling addMiddleware', () => {
        function callback() { }
        let route = '/test/it';

        instance.addMiddleware(route, callback);

        expect(instance._middleware).to.have.length(1);
        let wrapper = instance._middleware[0];

        expect(wrapper).to.be.an.instanceof(Wrapper);
        expect(wrapper._callback).to.equal(callback);
        expect(route).to.match(wrapper._routePattern);
    });

    it('should add a middleware wrapper to the private list calling addMiddleware with only a callback', () => {
        function callback() { }

        instance.addMiddleware(callback);

        expect(instance._middleware).to.have.length(1);
        let wrapper = instance._middleware[0];

        expect(wrapper).to.be.an.instanceof(Wrapper);
        expect(wrapper._callback).to.equal(callback);
        expect('/').to.match(wrapper._routePattern);
    });

    it('should set the private variable to given callback calling setMissingRouteController', () => {
        function callback() { }

        instance.setMissingRouteController(callback);
        expect(instance._missingRouteController).to.equal(callback);
    });

    [0, 1, 3.14, -2.7, 'test', true, false, [], {}, undefined, null].forEach((aValue) => {
        it('should throw an error calling setMissingRouteController with param type ' + toString.call(aValue), () => {
            function setMissingRouteController() {
                instance.setMissingRouteController(aValue);
            }

            expect(setMissingRouteController).to.throw(TypeError);
        });
    });

    [0, 1, 3.14, -2.7, true, false, [], {}, undefined, null].forEach((aValue) => {
        it('should throw an error calling addMiddlware with first param type ' + toString.call(aValue), () => {
            function addMiddleware() {
                instance.addMiddleware(aValue, () => { });
            }

            expect(addMiddleware).to.throw(TypeError);
        });
    });

    [0, 1, 3.14, -2.7, true, false, () => { }, [], {}, undefined, null].forEach((aValue) => {
        it('should throw an error calling addController with first param type ' + toString.call(aValue), () => {
            function addController() {
                instance.addController(aValue, () => { });
            }

            expect(addController).to.throw(TypeError);
        });
    });

    [0, 1, 3.14, -2.7, 'test', true, false, [], {}, undefined, null].forEach((aValue) => {
        it('should throw an error calling addMiddlware with second param type ' + toString.call(aValue), () => {
            function addMiddleware() {
                instance.addMiddleware('/*', aValue);
            }

            expect(addMiddleware).to.throw(TypeError);
        });
    });

    [0, 1, 3.14, -2.7, 'test', true, false, [], undefined, null].forEach((aValue) => {
        it('should throw an error calling addController with second param type ' + toString.call(aValue), () => {
            function addController() {
                instance.addController('/*', aValue);
            }

            expect(addController).to.throw(TypeError);
        });
    });

    it('should add a controller wrapper to the private list calling addController', () => {
        function callback() { }
        let route = '/test/it';

        instance.addController(route, callback);

        expect(instance._controller).to.have.length(1);
        let wrapper = instance._controller[0];

        expect(wrapper).to.be.an.instanceof(Wrapper);
        expect(wrapper._callback).to.equal(callback);
        expect(route).to.match(wrapper._routePattern);
    });

    it('should add a controller wrapper to the private list calling addController with an object', () => {
        let servelet = {};
        let route = '/test/it';

        instance.addController(route, servelet);

        expect(instance._controller).to.have.length(1);
        let wrapper = instance._controller[0];

        expect(wrapper).to.be.an.instanceof(Wrapper);
        expect(wrapper._callback).to.be.an('function');
    });

    it('should return a routing function calling getRouter', () => {
        expect(instance.getRouter()).to.be.an('function');
    });

    it('should return a routing function expecting two arguments calling getRouter', () => {
        let router = instance.getRouter();

        expect(router).to.have.length(2);
    });

    it('should run the correct controller calling _runController', () => {
        let calledCorrectController = false;
        let calledWrongController = false;
        let calledCorrectControllerWith = [];

        let request = {
            isRequest: true
        };
        let response = {
            isResponse: true
        };

        instance.addController('/wrong', () => {
            calledWrongController = true;
        });
        instance.addController('/ok', function () {
            calledCorrectController = true;
            calledCorrectControllerWith = Array.prototype.slice.call(arguments);
        });

        instance._runController('/ok', request, response);

        expect(calledWrongController).to.equal(false);
        expect(calledCorrectController).to.equal(true);

        expect(calledCorrectControllerWith).to.have.length(3);
        expect(calledCorrectControllerWith[0]).to.equal(request);
        expect(calledCorrectControllerWith[1]).to.equal(response);
        expect(calledCorrectControllerWith[2]).to.be.an('object');
        expect(Object.keys(calledCorrectControllerWith[2])).to.have.length(0);
    });

    it('should _runMiddleware return a promise', () => {
        instance.addMiddleware(() => { });
        let result = instance._runMiddleware('/ok', {}, {});

        expect(result).to.be.an.instanceof(Promise);
    });

    it('should run all fitting middleware', (done) => {
        let calledCorrectMiddleware1 = false;
        let calledCorrectMiddleware2 = false;
        let calledWrongMiddleware = false;
        let calledCorrectMiddlewareWith1 = [];
        let calledCorrectMiddlewareWith2 = [];

        let request = {
            isRequest: true
        };
        let response = {
            isResponse: true
        };

        instance.addMiddleware('/wrong', () => {
            calledWrongMiddleware = true;
        });
        instance.addMiddleware('/ok', function () {
            calledCorrectMiddleware1 = true;
            calledCorrectMiddlewareWith1 = Array.prototype.slice.call(arguments);
        });
        instance.addMiddleware(function () {
            calledCorrectMiddleware2 = true;
            calledCorrectMiddlewareWith2 = Array.prototype.slice.call(arguments);
        });

        let runPromise = instance._runMiddleware('/ok', request, response);

        runPromise
            .then(() => {
                expect(calledWrongMiddleware).to.equal(false);
                expect(calledCorrectMiddleware1).to.equal(true);
                expect(calledCorrectMiddleware2).to.equal(true);

                expect(calledCorrectMiddlewareWith1).to.have.length(3);
                expect(calledCorrectMiddlewareWith1[0]).to.equal(request);
                expect(calledCorrectMiddlewareWith1[1]).to.equal(response);
                expect(calledCorrectMiddlewareWith1[2]).to.be.an('object');
                expect(Object.keys(calledCorrectMiddlewareWith1[2])).to.have.length(0);

                expect(calledCorrectMiddlewareWith2).to.have.length(3);
                expect(calledCorrectMiddlewareWith2[0]).to.equal(request);
                expect(calledCorrectMiddlewareWith2[1]).to.equal(response);

                done();
            })
            .catch(() => {
                expect('This should not happen').to.equal(true);
                done();
            });
    });

    it('should register event handler for data and end events on the request while executing the router', () => {
        let router = instance.getRouter();
        let request = new libEvents.EventEmitter();
        let response = {};

        router(request, response);

        expect(request.listeners('data')).to.have.length(1);
        expect(request.listeners('end')).to.have.length(1);
    });

    it('should call _runMiddleware and _runController with the correct parameters while executing the router', (done) => {
        let router = instance.getRouter();
        let executionList = [];
        let runMiddlewareWith = [];
        let runControllerWith = [];
        let requestMock = new libEvents.EventEmitter();
        let responseMock = {
            __wroteHead: false,
            __wroteData: false,
            __endedStream: false,
            writeHead: () => {
                responseMock.__wroteHead = true;
            },
            write: () => {
                responseMock.__wroteData = true;
            },
            end: () => {
                responseMock.__endedStream = true;
            }
        };

        requestMock.url = '/ok';

        instance._runMiddleware = chai.spy(function () {
            executionList.push(instance._runMiddleware);
            runMiddlewareWith = Array.prototype.slice.call(arguments);
        });
        instance._runController = chai.spy(function () {
            executionList.push(instance._runController);
            runControllerWith = Array.prototype.slice.call(arguments);
        });

        router(requestMock, responseMock);

        requestMock.emit('data', new Buffer('Hello'));
        requestMock.emit('data', new Buffer(' '));
        requestMock.emit('data', new Buffer('World'));
        let endCallback = requestMock.listeners('end')[0];

        endCallback()
            .then(() => {
                expect(instance._runMiddleware).to.have.been.called();
                expect(instance._runController).to.have.been.called();

                expect(executionList[0]).to.equal(instance._runMiddleware);
                expect(executionList[1]).to.equal(instance._runController);

                expect(responseMock.__wroteHead).to.equal(true);
                expect(responseMock.__wroteData).to.equal(true);
                expect(responseMock.__endedStream).to.equal(true);

                expect(runMiddlewareWith[0]).to.equal('/ok');
                expect(runMiddlewareWith[1]).to.be.an.instanceof(Request);
                expect(runMiddlewareWith[2]).to.be.an.instanceof(Response);

                expect(runControllerWith[0]).to.equal('/ok');
                expect(runControllerWith[1]).to.be.an.instanceof(Request);
                expect(runControllerWith[2]).to.be.an.instanceof(Response);

                expect(runMiddlewareWith[1].getBody().toString()).to.equal('Hello World');

                done();
            })
            .catch(() => {
                expect('this not to happen').to.equal(true);
                done();
            });
    });

    it('should send statuscode 500 if any part of the server has an error', (done) => {
        let router = instance.getRouter();
        let requestMock = new libEvents.EventEmitter();
        let responseMock = {
            __statusCode: 0,
            __endedStream: false,
            writeHead: (aStatusCode) => {
                responseMock.__statusCode = aStatusCode;
            },
            write: () => { },
            end: () => {
                responseMock.__endedStream = true;
            }
        };

        requestMock.url = '/ok';

        instance._runMiddleware = chai.spy(() => {
            throw Error();
        });
        instance._runController = chai.spy();

        router(requestMock, responseMock);

        let endCallback = requestMock.listeners('end')[0];

        endCallback()
            .then(() => {
                expect('this not to happen').to.equal(true);

                done();
            })
            .catch(() => {
                expect(responseMock.__statusCode).to.equal(500);
                expect(responseMock.__endedStream).to.equal(true);

                done();
            });
    });

    it('should do nothing if the request was already finished', (done) => {
        let router = instance.getRouter();
        let requestMock = new libEvents.EventEmitter();
        let responseMock = {
            __wroteHead: false,
            __wroteData: false,
            __endedStream: false,
            writeHead: () => {
                responseMock.__wroteHead = true;
            },
            write: () => {
                responseMock.__wroteData = true;
            },
            end: () => {
                responseMock.__endedStream = true;
            },
            finished: true
        };

        requestMock.url = '/ok';

        instance._runMiddleware = chai.spy(() => {
            throw Error();
        });
        instance._runController = chai.spy();

        router(requestMock, responseMock);

        let endCallback = requestMock.listeners('end')[0];

        endCallback()
            .then(() => {
                expect('this not to happen').to.equal(true);

                done();
            })
            .catch(() => {
                expect(responseMock.__wroteHead).to.equal(false);
                expect(responseMock.__wroteData).to.equal(false);
                expect(responseMock.__endedStream).to.equal(false);

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


<commit_before>var script = " ";
var html = "

 <textarea style='width:100%' name='banner' id='banner' rows='6' cols='20' onClick='copyToClipboard(this)' readonly='readonly'>

</textarea>

 <input type='button' value='Copiar' style='width:100%' onClick=\"copyToClipboard(document.getElementById('banner'))\">
"

var script_code = "<!-- Javascript Code --> <script> function copyToClipboard(object) {	object.focus();	object.select(); document.execCommand('copy'); alert('Copiado al Portapapeles');        } </script>";
var html_code = "<!-- HTML Code --> <div style='width:250px; text-align:center'> <div name='banner-container-image' id='banner-container-image'>	<a title='Entrar en Mascando Bits' target='_blank' href='http://rdch106.hol.es/'><img width='100%' src='http://rdch106.hol.es/wp-content/uploads/2016/02/Mascando_Bits_banner.jpg'></a>	</div> <br> <div style='width:100%'> <textarea style='width:100%' name='banner' id='banner' rows='6' cols='20' onClick='copyToClipboard(this)' readonly='readonly'> <div name='banner-container' id='banner-container'> <a title='Entrar en Mascando Bits' target='_blank' href='http://rdch106.hol.es/'><img width='100%' src='http://rdch106.hol.es/wp-content/uploads/2016/02/Mascando_Bits_banner.jpg'></a></div></textarea> </div> <br> <input type='button' value='Copiar' style='width:100%' onClick=\"copyToClipboard(document.getElementById('banner'))\"> </div>"

function generateBanner(){
    var generator_result = document.getElementById("generator-result");
    if (getParameterByName('banner_img')!= null && getParameterByName('width') != null){
        //Set input values
        html = html.replace("Mascando Bits", getParameterByName('name'));
        html = html.replace("Mascando Bits", getParameterByName('name'));
        html = html.replace("http://rdch106.hol.es/wp-content/uploads/2016/02/Mascando_Bits_banner.jpg", getParameterByName('banner_img'));
        html = html.replace("http://rdch106.hol.es/wp-content/uploads/2016/02/Mascando_Bits_banner.jpg", getParameterByName('banner_img'));
        html = html.replace("http://rdch106.hol.es/", getParameterByName('website'));
        html = html.replace("http://rdch106.hol.es/", getParameterByName('website'));
        html = html.replace("250px", (getParameterByName('width')+"px"));

        html_code = html_code.replace("Mascando Bits", getParameterByName('name'));
        html_code = html_code.replace("Mascando Bits", getParameterByName('name'));

        html_code = html_code.replace("http://rdch106.hol.es/wp-content/uploads/2016/02/Mascando_Bits_banner.jpg", getParameterByName('banner_img'));
        html_code = html_code.replace("http://rdch106.hol.es/wp-content/uploads/2016/02/Mascando_Bits_banner.jpg", getParameterByName('banner_img'));
        html_code = html_code.replace("http://rdch106.hol.es/", getParameterByName('website'));
        html_code = html_code.replace("http://rdch106.hol.es/", getParameterByName('website'));
        html_code = html_code.replace("250px", (getParameterByName('width')+"px"));
        //visualize
        generator_result.innerHTML = "
Preview
"
        var snippet = script + html;
        generator_result.innerHTML = generator_result.innerHTML + "
"+ snippet + "

";
        generator_result.innerHTML = generator_result.innerHTML + "
Copy this code in your Web:
";
        var snippet_code = script_code + html_code;
        generator_result.innerHTML = generator_result.innerHTML + "<textarea style='width:100%' name='code' id='banner' rows='6' cols='20' onClick='this.select();' readonly='readonly'>" + snippet_code + "</textarea>"

        //alert (getParameterByName('banner_img')+" "+ getParameterByName('width'));
    }
}

function getParameterByName(name, url) {
    if (!url) url = window.location.href;
    //url = url.toLowerCase(); // This is just to avoid case sensitiveness
    //name = name.replace(/[\[\]]/g, "\\$&").toLowerCase();// This is just to avoid case sensitiveness for query parameter name
    name = name.replace(/[\[\]]/g, "\\$&");
    var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
        results = regex.exec(url);
    if (!results) return null;
    if (!results[2]) return '';
    return decodeURIComponent(results[2].replace(/\+/g, " "));
}
// query string: ?foo=lorem&bar=&baz
//var foo = getParameterByName('foo'); // "lorem"
//var bar = getParameterByName('bar'); // "" (present with empty value)
//var baz = getParameterByName('baz'); // "" (present with no value)
//var qux = getParameterByName('qux'); // null (absent)
<commit_msg>Update script.js<commit_after>var script = " ";
var html = "

 <textarea style='width:100%' name='banner' id='banner' rows='6' cols='20' onclick='copyToClipboard(this)' readonly='readonly'>

</textarea>

 <input type='button' value='Copiar' style='width:100%' onclick=\"copyToClipboard(document.getElementById('banner'))\">
"

var script_code = "<!-- Javascript Code --> <script> function copyToClipboard(object) {	object.focus();	object.select(); document.execCommand('copy'); alert('Copiado al Portapapeles');        } </script>";
var html_code = "<!-- HTML Code --> <div style='width:250px; text-align:center'> <div name='banner-container-image' id='banner-container-image'>	<a title='Entrar en Mascando Bits' target='_blank' href='http://rdch106.hol.es/'><img width='100%' src='http://rdch106.hol.es/wp-content/uploads/2016/02/Mascando_Bits_banner.jpg'></a>	</div> <br> <div style='width:100%'> <textarea style='width:100%' name='banner' id='banner' rows='6' cols='20' onclick='copyToClipboard(this)' readonly='readonly'> <div name='banner-container' id='banner-container'> <a title='Entrar en Mascando Bits' target='_blank' href='http://rdch106.hol.es/'><img width='100%' src='http://rdch106.hol.es/wp-content/uploads/2016/02/Mascando_Bits_banner.jpg'></a></div></textarea> </div> <br> <input type='button' value='Copiar' style='width:100%' onclick=\"copyToClipboard(document.getElementById('banner'))\"> </div>"

function generateBanner(){
    var generator_result = document.getElementById("generator-result");
    if (getParameterByName('banner_img')!= null && getParameterByName('width') != null){
        //Set input values
        html = html.replace("Mascando Bits", getParameterByName('name'));
        html = html.replace("Mascando Bits", getParameterByName('name'));
        html = html.replace("http://rdch106.hol.es/wp-content/uploads/2016/02/Mascando_Bits_banner.jpg", getParameterByName('banner_img'));
        html = html.replace("http://rdch106.hol.es/wp-content/uploads/2016/02/Mascando_Bits_banner.jpg", getParameterByName('banner_img'));
        html = html.replace("http://rdch106.hol.es/", getParameterByName('website'));
        html = html.replace("http://rdch106.hol.es/", getParameterByName('website'));
        html = html.replace("250px", (getParameterByName('width')+"px"));

        html_code = html_code.replace("Mascando Bits", getParameterByName('name'));
        html_code = html_code.replace("Mascando Bits", getParameterByName('name'));

        html_code = html_code.replace("http://rdch106.hol.es/wp-content/uploads/2016/02/Mascando_Bits_banner.jpg", getParameterByName('banner_img'));
        html_code = html_code.replace("http://rdch106.hol.es/wp-content/uploads/2016/02/Mascando_Bits_banner.jpg", getParameterByName('banner_img'));
        html_code = html_code.replace("http://rdch106.hol.es/", getParameterByName('website'));
        html_code = html_code.replace("http://rdch106.hol.es/", getParameterByName('website'));
        html_code = html_code.replace("250px", (getParameterByName('width')+"px"));
        //visualize
        generator_result.innerHTML = "
Preview
"
        var snippet = script + html;
        generator_result.innerHTML = generator_result.innerHTML + "
"+ snippet + "

";
        generator_result.innerHTML = generator_result.innerHTML + "
Copy this code in your Web:
";
        var snippet_code = script_code + html_code;
        generator_result.innerHTML = generator_result.innerHTML + "<textarea style='width:100%' name='code' id='banner' rows='6' cols='20' onClick='this.select();' readonly='readonly'>" + snippet_code + "</textarea>"

        //alert (getParameterByName('banner_img')+" "+ getParameterByName('width'));
    }
}

function getParameterByName(name, url) {
    if (!url) url = window.location.href;
    //url = url.toLowerCase(); // This is just to avoid case sensitiveness
    //name = name.replace(/[\[\]]/g, "\\$&").toLowerCase();// This is just to avoid case sensitiveness for query parameter name
    name = name.replace(/[\[\]]/g, "\\$&");
    var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
        results = regex.exec(url);
    if (!results) return null;
    if (!results[2]) return '';
    return decodeURIComponent(results[2].replace(/\+/g, " "));
}
// query string: ?foo=lorem&bar=&baz
//var foo = getParameterByName('foo'); // "lorem"
//var bar = getParameterByName('bar'); // "" (present with empty value)
//var baz = getParameterByName('baz'); // "" (present with no value)
//var qux = getParameterByName('qux'); // null (absent)
<|endoftext|>


<commit_before>/*---------------------------------------------------------
 * OpenERP web_gantt
 *---------------------------------------------------------*/
openerp.web_gantt = function (openerp) {
var _t = openerp.web._t,
   _lt = openerp.web._lt;
var QWeb = openerp.web.qweb;
openerp.web.views.add('gantt', 'openerp.web_gantt.GanttView');

openerp.web_gantt.GanttView = openerp.web.View.extend({
    display_name: _lt('Gantt'),
    template: "GanttView",
    init: function() {
        this._super.apply(this, arguments);
        this.has_been_loaded = $.Deferred();
        this.chart_id = _.uniqueId();
    },
    start: function() {
        return $.when(this.rpc("/web/view/load", {"model": this.dataset.model, "view_id": this.view_id, "view_type": "gantt"}),
            this.rpc("/web/searchview/fields_get", {"model": this.dataset.model})).pipe(this.on_loaded);
    },
    on_loaded: function(fields_view, fields_get) {
        this.fields_view = fields_view[0];
        this.fields = fields_get[0].fields;
        this.field_name = 'name';

        this.has_been_loaded.resolve();
    },
    do_search: function (domains, contexts, group_bys) {
        var self = this;
        self.last_domains = domains;
        self.last_contexts = contexts;
        self.last_group_bys = group_bys;
        // select the group by
        var n_group_bys = [];
        if (this.fields_view.arch.attrs.default_group_by) {
            n_group_bys = this.fields_view.arch.attrs.default_group_by.split(',');
        }
        if (group_bys.length) {
            n_group_bys = group_bys;
        }
        // gather the fields to get
        var fields = _.compact(_.map(["date_start", "date_delay", "date_stop", "color", "colors"], function(key) {
            return self.fields_view.arch.attrs[key] || '';
        }));
        fields = _.uniq(fields.concat([this.field_name], n_group_bys));

        return $.when(this.has_been_loaded).pipe(function() {
            return self.dataset.read_slice(fields, {
                domain: domains,
                context: contexts
            }).pipe(function(data) {
                return self.on_data_loaded(data, n_group_bys);
            });
        });
    },
    reload: function() {
        if (this.last_domains !== undefined)
            return this.do_search(this.last_domains, this.last_contexts, this.last_group_bys);
    },
    on_data_loaded: function(tasks, group_bys) {
        var self = this;
        $(".oe-gantt-view-view", this.$element).html("");

        //prevent more that 1 group by
        if (group_bys.length > 0) {
            group_bys = [group_bys[0]];
        }
        // if there is no group by, simulate it
        if (group_bys.length == 0) {
            group_bys = ["_pseudo_group_by"];
            _.each(tasks, function(el) {
                el._pseudo_group_by = "Gantt View";
            });
            this.fields._pseudo_group_by = {type: "string"};
        }

        // get the groups
        var split_groups = function(tasks, group_bys) {
            if (group_bys.length === 0)
                return tasks;
            var groups = [];
            _.each(tasks, function(task) {
                var group_name = task[_.first(group_bys)];
                var group = _.find(groups, function(group) { return _.isEqual(group.name, group_name); });
                if (group === undefined) {
                    group = {name:group_name, tasks: [], __is_group: true};
                    groups.push(group);
                }
                group.tasks.push(task);
            });
            _.each(groups, function(group) {
                group.tasks = split_groups(group.tasks, _.rest(group_bys));
            });
            return groups;
        }
        var groups = split_groups(tasks, group_bys);

        // track ids of task items for context menu
        var task_ids = {};
        // creation of the chart
        var generate_task_info = function(task, plevel) {
            var level = plevel || 0;
            if (task.__is_group) {
                var task_infos = _.compact(_.map(task.tasks, function(sub_task) {
                    return generate_task_info(sub_task, level + 1);
                }));
                if (task_infos.length == 0)
                    return;
                var task_start = _.reduce(_.pluck(task_infos, "task_start"), function(date, memo) {
                    return memo === undefined || date < memo ? date : memo;
                }, undefined);
                var task_stop = _.reduce(_.pluck(task_infos, "task_stop"), function(date, memo) {
                    return memo === undefined || date > memo ? date : memo;
                }, undefined);
                var duration = (task_stop.getTime() - task_start.getTime()) / (1000 * 60 * 60);
                var group_name = openerp.web.format_value(task.name, self.fields[group_bys[level]]);
                if (level == 0) {
                    var group = new GanttProjectInfo(_.uniqueId("gantt_project_"), group_name, task_start);
                    _.each(task_infos, function(el) {
                        group.addTask(el.task_info);
                    });
                    return group;
                } else {
                    var group = new GanttTaskInfo(_.uniqueId("gantt_project_task_"), group_name, task_start, duration, 100);
                    _.each(task_infos, function(el) {
                        group.addChildTask(el.task_info);
                    });
                    return {task_info: group, task_start: task_start, task_stop: task_stop};
                }
            } else {
                var task_name = openerp.web.format_value(task[self.field_name], self.fields[self.field_name]);
                var task_start = openerp.web.auto_str_to_date(task[self.fields_view.arch.attrs.date_start]);
                if (!task_start)
                    return;
                var task_stop;
                if (self.fields_view.arch.attrs.date_stop) {
                    task_stop = openerp.web.auto_str_to_date(task[self.fields_view.arch.attrs.date_stop]);
                    if (!task_stop)
                        return;
                } else { // we assume date_duration is defined
                    var tmp = openerp.web.format_value(task[self.fields_view.arch.attrs.date_delay],
                        self.fields[self.fields_view.arch.attrs.date_delay]);
                    if (!tmp)
                        return;
                    task_stop = task_start.clone().addMilliseconds(tmp * 60 * 60 * 1000);
                }
                var duration = (task_stop.getTime() - task_start.getTime()) / (1000 * 60 * 60);
                var id = _.uniqueId("gantt_task_");
                var task_info = new GanttTaskInfo(id, task_name, task_start, ((duration / 24) * 8), 100);
                task_info.internal_task = task;
                task_ids[id] = task_info;
                return {task_info: task_info, task_start: task_start, task_stop: task_stop};
            }
        }
        var gantt = new GanttChart();
        _.each(_.compact(_.map(groups, function(e) {return generate_task_info(e, 0);})), function(project) {
            gantt.addProject(project);
        });
        gantt.setEditable(true);
        gantt.setImagePath("/web_gantt/static/lib/dhtmlxGantt/codebase/imgs/");
        gantt.attachEvent("onTaskEndDrag", function(task) {
            self.on_task_changed(task);
        });
        gantt.attachEvent("onTaskEndResize", function(task) {
            self.on_task_changed(task);
        });
        gantt.create(this.chart_id);

        // bind event to display task when we click the item in the tree
        $(".taskNameItem", self.$element).click(function(event) {
            var task_info = task_ids[event.target.id];
            if (task_info) {
                self.on_task_display(task_info.internal_task);
            }
        });

        // insertion of create button
        var td = $($("table td", self.$element)[0]);
        var rendered = QWeb.render("GanttView-create-button");
        $(rendered).prependTo(td);
        $(".oe-gantt-view-create", this.$element).click(this.on_task_create);
    },
    on_task_changed: function(task_obj) {
        var self = this;
        var itask = task_obj.TaskInfo.internal_task;
        var start = task_obj.getEST();
        var duration = (task_obj.getDuration() / 8) * 24;
        var end = start.clone().addMilliseconds(duration * 60 * 60 * 1000);
        var data = {};
        data[self.fields_view.arch.attrs.date_start] =
            openerp.web.auto_date_to_str(start, self.fields[self.fields_view.arch.attrs.date_start].type);
        if (self.fields_view.arch.attrs.date_stop) {
            data[self.fields_view.arch.attrs.date_stop] =
                openerp.web.auto_date_to_str(end, self.fields[self.fields_view.arch.attrs.date_stop].type);
        } else { // we assume date_duration is defined
            data[self.fields_view.arch.attrs.date_delay] = duration;
        }
        this.dataset.write(itask.id, data).then(function() {
            console.log("task edited");
        });
    },
    on_task_display: function(task) {
        var self = this;
        var pop = new openerp.web.form.FormOpenPopup(self);
        pop.on_write_completed.add_last(function() {
            self.reload();
        });
        pop.show_element(
            self.dataset.model,
            task.id,
            null,
            {}
        );
    },
    on_task_create: function() {
        var self = this;
        var pop = new openerp.web.form.SelectCreatePopup(this);
        pop.on_select_elements.add_last(function() {
            self.reload();
        });
        pop.select_element(
            self.dataset.model,
            {
                initial_view: "form",
            }
        );
    },
});

};
<commit_msg>[fix] problem in gantt view, now does a name_get for all models<commit_after>/*---------------------------------------------------------
 * OpenERP web_gantt
 *---------------------------------------------------------*/
openerp.web_gantt = function (openerp) {
var _t = openerp.web._t,
   _lt = openerp.web._lt;
var QWeb = openerp.web.qweb;
openerp.web.views.add('gantt', 'openerp.web_gantt.GanttView');

openerp.web_gantt.GanttView = openerp.web.View.extend({
    display_name: _lt('Gantt'),
    template: "GanttView",
    init: function() {
        this._super.apply(this, arguments);
        this.has_been_loaded = $.Deferred();
        this.chart_id = _.uniqueId();
    },
    start: function() {
        return $.when(this.rpc("/web/view/load", {"model": this.dataset.model, "view_id": this.view_id, "view_type": "gantt"}),
            this.rpc("/web/searchview/fields_get", {"model": this.dataset.model})).pipe(this.on_loaded);
    },
    on_loaded: function(fields_view, fields_get) {
        this.fields_view = fields_view[0];
        this.fields = fields_get[0].fields;

        this.has_been_loaded.resolve();
    },
    do_search: function (domains, contexts, group_bys) {
        var self = this;
        self.last_domains = domains;
        self.last_contexts = contexts;
        self.last_group_bys = group_bys;
        // select the group by
        var n_group_bys = [];
        if (this.fields_view.arch.attrs.default_group_by) {
            n_group_bys = this.fields_view.arch.attrs.default_group_by.split(',');
        }
        if (group_bys.length) {
            n_group_bys = group_bys;
        }
        // gather the fields to get
        var fields = _.compact(_.map(["date_start", "date_delay", "date_stop"], function(key) {
            return self.fields_view.arch.attrs[key] || '';
        }));
        fields = _.uniq(fields.concat(n_group_bys));

        return $.when(this.has_been_loaded).pipe(function() {
            return self.dataset.read_slice(fields, {
                domain: domains,
                context: contexts
            }).pipe(function(data) {
                return self.on_data_loaded(data, n_group_bys);
            });
        });
    },
    reload: function() {
        if (this.last_domains !== undefined)
            return this.do_search(this.last_domains, this.last_contexts, this.last_group_bys);
    },
    on_data_loaded: function(tasks, group_bys) {
        var self = this;
        var ids = _.pluck(tasks, "id");
        return this.dataset.name_get(ids).pipe(function(names) {
            var ntasks = _.map(tasks, function(task) {
                return _.extend({__name: _.detect(names, function(name) { return name[0] == task.id; })[1]}, task);
            });
            return self.on_data_loaded_2(ntasks, group_bys);
        });
    },
    on_data_loaded_2: function(tasks, group_bys) {
        var self = this;
        $(".oe-gantt-view-view", this.$element).html("");

        //prevent more that 1 group by
        if (group_bys.length > 0) {
            group_bys = [group_bys[0]];
        }
        // if there is no group by, simulate it
        if (group_bys.length == 0) {
            group_bys = ["_pseudo_group_by"];
            _.each(tasks, function(el) {
                el._pseudo_group_by = "Gantt View";
            });
            this.fields._pseudo_group_by = {type: "string"};
        }

        // get the groups
        var split_groups = function(tasks, group_bys) {
            if (group_bys.length === 0)
                return tasks;
            var groups = [];
            _.each(tasks, function(task) {
                var group_name = task[_.first(group_bys)];
                var group = _.find(groups, function(group) { return _.isEqual(group.name, group_name); });
                if (group === undefined) {
                    group = {name:group_name, tasks: [], __is_group: true};
                    groups.push(group);
                }
                group.tasks.push(task);
            });
            _.each(groups, function(group) {
                group.tasks = split_groups(group.tasks, _.rest(group_bys));
            });
            return groups;
        }
        var groups = split_groups(tasks, group_bys);

        // track ids of task items for context menu
        var task_ids = {};
        // creation of the chart
        var generate_task_info = function(task, plevel) {
            var level = plevel || 0;
            if (task.__is_group) {
                var task_infos = _.compact(_.map(task.tasks, function(sub_task) {
                    return generate_task_info(sub_task, level + 1);
                }));
                if (task_infos.length == 0)
                    return;
                var task_start = _.reduce(_.pluck(task_infos, "task_start"), function(date, memo) {
                    return memo === undefined || date < memo ? date : memo;
                }, undefined);
                var task_stop = _.reduce(_.pluck(task_infos, "task_stop"), function(date, memo) {
                    return memo === undefined || date > memo ? date : memo;
                }, undefined);
                var duration = (task_stop.getTime() - task_start.getTime()) / (1000 * 60 * 60);
                var group_name = openerp.web.format_value(task.name, self.fields[group_bys[level]]);
                if (level == 0) {
                    var group = new GanttProjectInfo(_.uniqueId("gantt_project_"), group_name, task_start);
                    _.each(task_infos, function(el) {
                        group.addTask(el.task_info);
                    });
                    return group;
                } else {
                    var group = new GanttTaskInfo(_.uniqueId("gantt_project_task_"), group_name, task_start, duration, 100);
                    _.each(task_infos, function(el) {
                        group.addChildTask(el.task_info);
                    });
                    return {task_info: group, task_start: task_start, task_stop: task_stop};
                }
            } else {
                var task_name = task.__name;
                var task_start = openerp.web.auto_str_to_date(task[self.fields_view.arch.attrs.date_start]);
                if (!task_start)
                    return;
                var task_stop;
                if (self.fields_view.arch.attrs.date_stop) {
                    task_stop = openerp.web.auto_str_to_date(task[self.fields_view.arch.attrs.date_stop]);
                    if (!task_stop)
                        return;
                } else { // we assume date_duration is defined
                    var tmp = openerp.web.format_value(task[self.fields_view.arch.attrs.date_delay],
                        self.fields[self.fields_view.arch.attrs.date_delay]);
                    if (!tmp)
                        return;
                    task_stop = task_start.clone().addMilliseconds(tmp * 60 * 60 * 1000);
                }
                var duration = (task_stop.getTime() - task_start.getTime()) / (1000 * 60 * 60);
                var id = _.uniqueId("gantt_task_");
                var task_info = new GanttTaskInfo(id, task_name, task_start, ((duration / 24) * 8), 100);
                task_info.internal_task = task;
                task_ids[id] = task_info;
                return {task_info: task_info, task_start: task_start, task_stop: task_stop};
            }
        }
        var gantt = new GanttChart();
        _.each(_.compact(_.map(groups, function(e) {return generate_task_info(e, 0);})), function(project) {
            gantt.addProject(project);
        });
        gantt.setEditable(true);
        gantt.setImagePath("/web_gantt/static/lib/dhtmlxGantt/codebase/imgs/");
        gantt.attachEvent("onTaskEndDrag", function(task) {
            self.on_task_changed(task);
        });
        gantt.attachEvent("onTaskEndResize", function(task) {
            self.on_task_changed(task);
        });
        gantt.create(this.chart_id);

        // bind event to display task when we click the item in the tree
        $(".taskNameItem", self.$element).click(function(event) {
            var task_info = task_ids[event.target.id];
            if (task_info) {
                self.on_task_display(task_info.internal_task);
            }
        });

        // insertion of create button
        var td = $($("table td", self.$element)[0]);
        var rendered = QWeb.render("GanttView-create-button");
        $(rendered).prependTo(td);
        $(".oe-gantt-view-create", this.$element).click(this.on_task_create);
    },
    on_task_changed: function(task_obj) {
        var self = this;
        var itask = task_obj.TaskInfo.internal_task;
        var start = task_obj.getEST();
        var duration = (task_obj.getDuration() / 8) * 24;
        var end = start.clone().addMilliseconds(duration * 60 * 60 * 1000);
        var data = {};
        data[self.fields_view.arch.attrs.date_start] =
            openerp.web.auto_date_to_str(start, self.fields[self.fields_view.arch.attrs.date_start].type);
        if (self.fields_view.arch.attrs.date_stop) {
            data[self.fields_view.arch.attrs.date_stop] =
                openerp.web.auto_date_to_str(end, self.fields[self.fields_view.arch.attrs.date_stop].type);
        } else { // we assume date_duration is defined
            data[self.fields_view.arch.attrs.date_delay] = duration;
        }
        this.dataset.write(itask.id, data).then(function() {
            console.log("task edited");
        });
    },
    on_task_display: function(task) {
        var self = this;
        var pop = new openerp.web.form.FormOpenPopup(self);
        pop.on_write_completed.add_last(function() {
            self.reload();
        });
        pop.show_element(
            self.dataset.model,
            task.id,
            null,
            {}
        );
    },
    on_task_create: function() {
        var self = this;
        var pop = new openerp.web.form.SelectCreatePopup(this);
        pop.on_select_elements.add_last(function() {
            self.reload();
        });
        pop.select_element(
            self.dataset.model,
            {
                initial_view: "form",
            }
        );
    },
});

};
<|endoftext|>


<commit_before>const chai = require( 'chai' );
const chaiAsPromised = require( 'chai-as-promised' );
const tripLocations = require( '../app/models/trip-location' );
import { connectToDb, disconnectFromDb, resetDb, models, mockUsers, mockTrips, mockLocations } from './bootstrap';
import { removeLocationForUser } from '../app/models/location';

chai.use( chaiAsPromised );
const expect = chai.expect;

describe( 'tripLocations', function() {
  before( function( done ) {
    connectToDb( done );
  } );

  after( function() {
    disconnectFromDb();
  } );

  beforeEach( function( done ) {
    resetDb( done );
  } );

  describe( '.listTripLocationsForUser', function() {
    it( 'returns an Array', function() {
      return expect( tripLocations.listTripLocationsForUser( mockUsers.testUserId ) ).to.eventually.be.an.instanceOf( Array );
    } );

    it( 'returns an array with all current TripLocations', function() {
      return tripLocations.listTripLocationsForUser( mockUsers.testUserId2 )
      .then( function( data ) {
        expect( data ).to.eql( mockTrips.testUserTrip2.tripLocations );
      } );
    } );

    it( 'returns an array that does not include TripLocations from other users', function() {
      return tripLocations.listTripLocationsForUser( mockUsers.testUserId )
      .then( function( data ) {
        expect( data ).to.eql( mockTrips.testUserTrip.tripLocations );
      } );
    } );

    it( 'does not return any TripLocations that have no associated Location', function() {
      const expectedTripLocations = mockTrips.testUserTrip.tripLocations.filter( loc => loc !== mockLocations.homeLocation._id );
      return removeLocationForUser( mockUsers.testUserId, mockLocations.homeLocation._id )
      .then( function() {
        return tripLocations.listTripLocationsForUser( mockUsers.testUserId )
        .then( function( data ) {
          expect( data ).to.eql( expectedTripLocations );
        } );
      } );
    } );
  } );

  describe( '.removeAllTripLocations', function() {
    it( 'removes all the TripLocations for the user', function() {
      return tripLocations.removeAllTripLocations( mockUsers.testUserId2 )
      .then( () => models.Trip.findOne( { userId: mockUsers.testUserId2 } ) )
      .then( ( data ) => {
        expect( data.tripLocations ).to.be.empty;
      } );
    } );

    it( 'does not remove TripLocations for other users', function() {
      return tripLocations.removeAllTripLocations( mockUsers.testUserId2 )
      .then( () => tripLocations.listTripLocationsForUser( mockUsers.testUserId ) )
      .then( ( data ) => {
        expect( data ).to.not.be.empty;
      } );
    } );

    it( 'returns the empty list', function() {
      return tripLocations.removeAllTripLocations( mockUsers.testUserId2 )
      .then( ( data ) => {
        expect( data ).to.be.empty;
      } );
    } );
  } );

  describe( '.updateTripForUser', function() {
    it( 'returns re-ordered TripLocations', function() {
      const ids = [ mockLocations.foodLocation._id, mockLocations.teaLocation._id ];
      const date = Date.now();
      return tripLocations.updateTripForUser( mockUsers.testUserId2, ids, date )
      .then( newIds => expect( newIds.toString() ).to.eql( ids.toString() ) );
    } );

    it( 're-orders existing TripLocations', function() {
      const ids = [ mockLocations.foodLocation._id, mockLocations.teaLocation._id ];
      const date = Date.now();
      return tripLocations.updateTripForUser( mockUsers.testUserId2, ids, date )
      .then( () => tripLocations.listTripLocationsForUser( mockUsers.testUserId2 ) )
      .then( newIds => expect( newIds.toString() ).to.eql( ids.toString() ) );
    } );

    it( 're-orders collection if params include a duplicate TripLocation ID', function() {
      const ids = [ mockLocations.foodLocation._id, mockLocations.teaLocation._id, mockLocations.teaLocation._id ];
      const date = Date.now();
      return tripLocations.updateTripForUser( mockUsers.testUserId2, ids, date )
      .then( newIds => expect( newIds.toString() ).to.eql( ids.toString() ) );
    } );

    it( 'creates a new TripLocation if one is added', function() {
      const ids = [ mockLocations.foodLocation._id, mockLocations.teaLocation._id, mockLocations.workLocation._id ];
      const date = Date.now();
      return tripLocations.updateTripForUser( mockUsers.testUserId2, ids, date )
      .then( newIds => expect( newIds.toString() ).to.eql( ids.toString() ) );
    } );

    it( 'removes TripLocations from collection if params do not include all TripLocation IDs', function() {
      const ids = [ mockLocations.foodLocation._id ];
      const date = Date.now();
      return tripLocations.updateTripForUser( mockUsers.testUserId2, ids, date )
      .then( newIds => expect( newIds.toString() ).to.eql( ids.toString() ) );
    } );

    it( 'does not add location to collection if params include a TripLocation ID for another user', function() {
      const ids = [ mockLocations.foodLocation._id, mockLocations.homeLocation._id ];
      const date = Date.now();
      return expect( tripLocations.updateTripForUser( mockUsers.testUserId2, ids, date ) ).to.eventually.be.rejected;
    } );

    it( 'does not add location to collection if param include a date which is older than the lastUpdated date', function() {
      const ids = [ mockLocations.foodLocation._id ];
      const date = new Date( ( new Date() ).valueOf() - 1000 * 60 * 60 ).getTime();
      return expect( tripLocations.updateTripForUser( mockUsers.testUserId2, ids, date ) ).to.eventually.eql( mockTrips.testUserTrip2.tripLocations );
    } );

    it( 'updates the lastUpdated date of the trip when an update is successful', function() {
      const ids = [ mockLocations.foodLocation._id ];
      const date2 = Date.now();
      const date = new Date( ( new Date() ).valueOf() + 1000 * 60 * 60 ).getTime();
      return tripLocations.updateTripForUser( mockUsers.testUserId2, ids, date )
      .then( function() {
        const ids2 = [ mockLocations.teaLocation._id ];
        return expect( tripLocations.updateTripForUser( mockUsers.testUserId2, ids2, date2 ) ).to.eventually.eql( ids );
      } );
    } );
  } );
} );
<commit_msg>Skip TripLocations tests since TripLocations deprecated<commit_after>const chai = require( 'chai' );
const chaiAsPromised = require( 'chai-as-promised' );
const tripLocations = require( '../app/models/trip-location' );
import { connectToDb, disconnectFromDb, resetDb, models, mockUsers, mockTrips, mockLocations } from './bootstrap';
import { removeLocationForUser } from '../app/models/location';

chai.use( chaiAsPromised );
const expect = chai.expect;

describe.skip( 'tripLocations', function() {
  before( function( done ) {
    connectToDb( done );
  } );

  after( function() {
    disconnectFromDb();
  } );

  beforeEach( function( done ) {
    resetDb( done );
  } );

  describe( '.listTripLocationsForUser', function() {
    it( 'returns an Array', function() {
      return expect( tripLocations.listTripLocationsForUser( mockUsers.testUserId ) ).to.eventually.be.an.instanceOf( Array );
    } );

    it( 'returns an array with all current TripLocations', function() {
      return tripLocations.listTripLocationsForUser( mockUsers.testUserId2 )
      .then( function( data ) {
        expect( data ).to.eql( mockTrips.testUserTrip2.tripLocations );
      } );
    } );

    it( 'returns an array that does not include TripLocations from other users', function() {
      return tripLocations.listTripLocationsForUser( mockUsers.testUserId )
      .then( function( data ) {
        expect( data ).to.eql( mockTrips.testUserTrip.tripLocations );
      } );
    } );

    it( 'does not return any TripLocations that have no associated Location', function() {
      const expectedTripLocations = mockTrips.testUserTrip.tripLocations.filter( loc => loc !== mockLocations.homeLocation._id );
      return removeLocationForUser( mockUsers.testUserId, mockLocations.homeLocation._id )
      .then( function() {
        return tripLocations.listTripLocationsForUser( mockUsers.testUserId )
        .then( function( data ) {
          expect( data ).to.eql( expectedTripLocations );
        } );
      } );
    } );
  } );

  describe( '.removeAllTripLocations', function() {
    it( 'removes all the TripLocations for the user', function() {
      return tripLocations.removeAllTripLocations( mockUsers.testUserId2 )
      .then( () => models.Trip.findOne( { userId: mockUsers.testUserId2 } ) )
      .then( ( data ) => {
        expect( data.tripLocations ).to.be.empty;
      } );
    } );

    it( 'does not remove TripLocations for other users', function() {
      return tripLocations.removeAllTripLocations( mockUsers.testUserId2 )
      .then( () => tripLocations.listTripLocationsForUser( mockUsers.testUserId ) )
      .then( ( data ) => {
        expect( data ).to.not.be.empty;
      } );
    } );

    it( 'returns the empty list', function() {
      return tripLocations.removeAllTripLocations( mockUsers.testUserId2 )
      .then( ( data ) => {
        expect( data ).to.be.empty;
      } );
    } );
  } );

  describe( '.updateTripForUser', function() {
    it( 'returns re-ordered TripLocations', function() {
      const ids = [ mockLocations.foodLocation._id, mockLocations.teaLocation._id ];
      const date = Date.now();
      return tripLocations.updateTripForUser( mockUsers.testUserId2, ids, date )
      .then( newIds => expect( newIds.toString() ).to.eql( ids.toString() ) );
    } );

    it( 're-orders existing TripLocations', function() {
      const ids = [ mockLocations.foodLocation._id, mockLocations.teaLocation._id ];
      const date = Date.now();
      return tripLocations.updateTripForUser( mockUsers.testUserId2, ids, date )
      .then( () => tripLocations.listTripLocationsForUser( mockUsers.testUserId2 ) )
      .then( newIds => expect( newIds.toString() ).to.eql( ids.toString() ) );
    } );

    it( 're-orders collection if params include a duplicate TripLocation ID', function() {
      const ids = [ mockLocations.foodLocation._id, mockLocations.teaLocation._id, mockLocations.teaLocation._id ];
      const date = Date.now();
      return tripLocations.updateTripForUser( mockUsers.testUserId2, ids, date )
      .then( newIds => expect( newIds.toString() ).to.eql( ids.toString() ) );
    } );

    it( 'creates a new TripLocation if one is added', function() {
      const ids = [ mockLocations.foodLocation._id, mockLocations.teaLocation._id, mockLocations.workLocation._id ];
      const date = Date.now();
      return tripLocations.updateTripForUser( mockUsers.testUserId2, ids, date )
      .then( newIds => expect( newIds.toString() ).to.eql( ids.toString() ) );
    } );

    it( 'removes TripLocations from collection if params do not include all TripLocation IDs', function() {
      const ids = [ mockLocations.foodLocation._id ];
      const date = Date.now();
      return tripLocations.updateTripForUser( mockUsers.testUserId2, ids, date )
      .then( newIds => expect( newIds.toString() ).to.eql( ids.toString() ) );
    } );

    it( 'does not add location to collection if params include a TripLocation ID for another user', function() {
      const ids = [ mockLocations.foodLocation._id, mockLocations.homeLocation._id ];
      const date = Date.now();
      return expect( tripLocations.updateTripForUser( mockUsers.testUserId2, ids, date ) ).to.eventually.be.rejected;
    } );

    it( 'does not add location to collection if param include a date which is older than the lastUpdated date', function() {
      const ids = [ mockLocations.foodLocation._id ];
      const date = new Date( ( new Date() ).valueOf() - 1000 * 60 * 60 ).getTime();
      return expect( tripLocations.updateTripForUser( mockUsers.testUserId2, ids, date ) ).to.eventually.eql( mockTrips.testUserTrip2.tripLocations );
    } );

    it( 'updates the lastUpdated date of the trip when an update is successful', function() {
      const ids = [ mockLocations.foodLocation._id ];
      const date2 = Date.now();
      const date = new Date( ( new Date() ).valueOf() + 1000 * 60 * 60 ).getTime();
      return tripLocations.updateTripForUser( mockUsers.testUserId2, ids, date )
      .then( function() {
        const ids2 = [ mockLocations.teaLocation._id ];
        return expect( tripLocations.updateTripForUser( mockUsers.testUserId2, ids2, date2 ) ).to.eventually.eql( ids );
      } );
    } );
  } );
} );
<|endoftext|>


<commit_before>/*---------------------------------------------------------
 * OpenERP web_graph
 *---------------------------------------------------------*/

'use strict';
/* jshint undef: false  */

openerp.web_graph = function (instance) {

var _lt = instance.web._lt;
var _t = instance.web._t;

instance.web.views.add('graph', 'instance.web_graph.GraphView');

 /**
  * GraphView view.  It mostly contains two widgets (PivotTable and ChartView)
  * and some data.
  */
instance.web_graph.GraphView = instance.web.View.extend({
    template: 'GraphView',
    display_name: _lt('Graph'),
    view_type: 'graph',
    events: {
        'click .graph_mode_selection li' : function (event) {
            event.preventDefault();
            var self = this,
                mode = event.target.attributes['data-mode'].nodeValue;
            if (mode == 'data') {
                this.chart_view.hide();
                this.pivot_table.show();
            } else {
                this.pivot_table.hide();
                this.get_data().done(function (data) {
                    self.chart_view.draw(data, mode);
                    self.chart_view.show(mode);
                });
            }
        },
    },

    init: function(parent, dataset, view_id, options) {
        this._super(parent, dataset, view_id, options);
        this.pivot_table = new PivotTable(this);
        this.chart_view = new ChartView(this);
        this.x_groups = [];
        this.measure = null;
        this.domain = [];
        this.model = null;
        this.model_fields = [];

    },

    view_loading: function (fields_view_get) {
        var self = this;
        this.model = new instance.web.Model(fields_view_get.model, {group_by_no_leaf: true});

        // get the default groupbys and measure defined in the field view
        _.each(fields_view_get.arch.children, function (field) {
            if ('name' in field.attrs) {
                if ('operator' in field.attrs) {
                    self.measure = field.attrs.name;
                } else {
                    self.x_groups.push(field.attrs.name);
                }
            }
        });

        this.chart_view.set_measure(this.measure);
        this.pivot_table.appendTo('.graph_main_content');
        this.chart_view.appendTo('.graph_main_content');
        this.chart_view.hide();
        this.get_data().done(this.pivot_table.draw);

        return this.model.call('fields_get', []).then(function (fields) {
            self.model_fields = fields;
        });
    },

    get_data: function () {
        var view_fields = this.x_groups.concat(this.measure);

        return query_groups(this.model, view_fields, this.domain, this.x_groups);
    },

    get_desc: function(field_id) {
        return this.model_fields[field_id].string;
    },

    do_search: function (domain, context, group_by) {
        this.domain = new instance.web.CompoundDomain(domain);
    },

    do_show: function () {
        this.do_push_state({});
        return this._super();
    },

});

 /**
  * PivotTable widget.  It displays the data in tabular data and allows the
  * user to drill down and up in the table
  */
var PivotTable = instance.web.Widget.extend({
    template: 'pivot_table',

    show: function () {
        this.$el.css('display', 'block');
    },

    hide: function () {
        this.$el.css('display', 'none');
    },

    draw: function (data) {
        console.log('data',data);
    },
});

 /**
  * ChartView widget.  It displays the data in chart form, using the nvd3
  * library.  Various modes include bar charts, pie charts or line charts.
  */
var ChartView = instance.web.Widget.extend({
    template: 'chart_view',
    measure: null,

    show: function () {
        this.$el.css('display', 'block');
    },

    hide: function () {
        this.$el.css('display', 'none');
    },

    set_measure: function (measure) {
        this.measure = measure;
    },

    draw: function (data, mode) {
        this.$el.empty();
        this.$el.append('<svg></svg>');

        switch (mode) {
            case 'bar_chart':
                this.render_bar_chart(data);
                break;
            case 'line_chart':
                this.render_line_chart(data);
                break;
            case 'pie_chart':
                this.render_pie_chart(data);
                break;
        }
    },

    format_data:  function (datapt) {
        var val = datapt.attributes;
        return {
            x: datapt.attributes.value[1],
            y: this.measure ? val.aggregates[this.measure] : val.length,
        };
    },

    render_bar_chart: function (data) {
        var formatted_data = [{
                key: 'Bar chart',
                values: _.map(data, this.format_data.bind(this)),
            }];

        nv.addGraph(function () {
            var chart = nv.models.discreteBarChart()
                .tooltips(false)
                .showValues(true)
                .staggerLabels(true)
                .width(650)
                .height(400);

            d3.select('.graph_chart svg')
                .datum(formatted_data)
                .attr('width', 650)
                .attr('height', 400)
                .call(chart);

            nv.utils.windowResize(chart.update);
            return chart;
        });
    },

    render_line_chart: function (data) {
        var measure_label = (this.measure) ? this.measure : 'Quantity';

        var formatted_data = [{
                key: measure_label,
                values: _.map(data, this.format_data.bind(this))
            }];

        nv.addGraph(function () {
            var chart = nv.models.lineChart()
                .x(function (d,u) { return u; })
                .width(600)
                .height(300)
                .margin({top: 30, right: 20, bottom: 20, left: 60});

            d3.select('.graph_chart svg')
                .attr('width', 600)
                .attr('height', 300)
                .datum(formatted_data)
                .call(chart);

            return chart;
          });
    },

    render_pie_chart: function (data) {
        var formatted_data = _.map(data, this.format_data.bind(this));

        nv.addGraph(function () {
            var chart = nv.models.pieChart()
                .color(d3.scale.category10().range())
                .width(650)
                .height(400);

            d3.select('.graph_chart svg')
                .datum(formatted_data)
                .transition().duration(1200)
                .attr('width', 650)
                .attr('height', 400)
                .call(chart);

            nv.utils.windowResize(chart.update);
            return chart;
        });
    },

});

/**
 * Query the server and return a deferred which will return the data
 * with all the groupbys applied (this is done for now, but the goal
 * is to modify read_group in order to allow eager and lazy groupbys
 */
function query_groups (model, fields, domain, groupbys) {
    return model.query(fields)
        .filter(domain)
        .group_by(groupbys)
        .then(function (results) {
            var non_empty_results = _.filter(results, function (group) {
                return group.attributes.length > 0;
            });
            if (groupbys.length <= 1) {
                return non_empty_results;
            } else {
                var get_subgroups = $.when.apply(null, _.map(non_empty_results, function (result) {
                    var new_domain = result.model._domain;
                    var new_groupings = groupbys.slice(1);
                    return query_groups(model, fields,new_domain, new_groupings).then(function (subgroups) {
                        result.subgroups_data = subgroups;
                    });
                }));
                return get_subgroups.then(function () {
                    return non_empty_results;
                });
            }
        });
}

};

<commit_msg>[REF] large refactoring of addon web_graph (mainly add widget BasicDataView and many cleanups)<commit_after>/*---------------------------------------------------------
 * OpenERP web_graph
 *---------------------------------------------------------*/

'use strict';
/* jshint undef: false  */

openerp.web_graph = function (instance) {

var _lt = instance.web._lt;
var _t = instance.web._t;

instance.web.views.add('graph', 'instance.web_graph.GraphView');

 /**
  * GraphView view.  It mostly contains two widgets (PivotTable and ChartView)
  * and some data.
  */
instance.web_graph.GraphView = instance.web.View.extend({
    template: 'GraphView',
    display_name: _lt('Graph'),
    view_type: 'graph',

    events: {
        'click .graph_mode_selection li' : function (event) {
            event.preventDefault();
            var self = this,
                mode = event.target.attributes['data-mode'].nodeValue;
            if (mode == 'data') {
                this.chart_view.hide();
                this.pivot_table.show();
            } else {
                this.pivot_table.hide();
                this.chart_view.set_mode(mode);
                this.chart_view.show();
            }
        },
    },

    view_loading: function (fields_view_get) {
        var self = this;
        var model = new instance.web.Model(fields_view_get.model, {group_by_no_leaf: true});
        var measure = null;
        var groupbys = []

        // get the default groupbys and measure defined in the field view
        _.each(fields_view_get.arch.children, function (field) {
            if ('name' in field.attrs) {
                if ('operator' in field.attrs) {
                    measure = field.attrs.name;
                } else {
                    groupbys.push(field.attrs.name);
                }
            }
        });

        return model.call('fields_get', []).then(function (fields) {
            var view_fields = groupbys.concat(measure);
            query_groups(model, view_fields, self.domain, groupbys).done(function (data) {
                self.pivot_table = new PivotTable(data, fields, groupbys, measure);
                self.chart_view = new ChartView(data, fields, groupbys, measure);
                self.pivot_table.appendTo('.graph_main_content')
                    .done(function () {
                        self.pivot_table.draw();
                    });
                self.chart_view.appendTo('.graph_main_content')
                    .done(function () {
                        self.chart_view.hide();
                    });
            });
        });
    },

    do_search: function (domain, context, group_by) {
        this.domain = new instance.web.CompoundDomain(domain);
    },

    do_show: function () {
        this.do_push_state({});
        return this._super();
    },

});

 /**
  * BasicDataView widget.  Basic widget to manage show/hide functionality
  * and to initialize some attributes.  It is inherited by PivotTable
  * and ChartView widget.
  */
var BasicDataView = instance.web.Widget.extend({
    init: function (data, fields, groupby, measure) {
        this.data = data;
        this.fields = fields;
        this.groupby = groupby;
        this.measure = measure;
    },

    show: function () {
        this.$el.css('display', 'block');
    },

    hide: function () {
        this.$el.css('display', 'none');
    },
});

 /**
  * PivotTable widget.  It displays the data in tabular data and allows the
  * user to drill down and up in the table
  */
var PivotTable = BasicDataView.extend({
    template: 'pivot_table',

    draw: function () {
        console.log('data',this.data);
    },
});

 /**
  * ChartView widget.  It displays the data in chart form, using the nvd3
  * library.  Various modes include bar charts, pie charts or line charts.
  */
var ChartView = BasicDataView.extend({
    template: 'chart_view',
    mode: 'bar_chart',

    set_mode: function (mode) {
        this.mode = mode;
        this.draw();
    },

    draw: function () {
        this.$el.empty();
        this.$el.append('<svg></svg>');

        switch (this.mode) {
            case 'bar_chart':
                this.render_bar_chart();
                break;
            case 'line_chart':
                this.render_line_chart();
                break;
            case 'pie_chart':
                this.render_pie_chart();
                break;
        }
    },

    format_data:  function (datapt) {
        var val = datapt.attributes;
        return {
            x: datapt.attributes.value[1],
            y: this.measure ? val.aggregates[this.measure] : val.length,
        };
    },

    render_bar_chart: function () {
        var formatted_data = [{
                key: 'Bar chart',
                values: _.map(this.data, this.format_data.bind(this)),
            }];

        nv.addGraph(function () {
            var chart = nv.models.discreteBarChart()
                .tooltips(false)
                .showValues(true)
                .staggerLabels(true)
                .width(650)
                .height(400);

            d3.select('.graph_chart svg')
                .datum(formatted_data)
                .attr('width', 650)
                .attr('height', 400)
                .call(chart);

            nv.utils.windowResize(chart.update);
            return chart;
        });
    },

    render_line_chart: function () {
        var measure_label = (this.measure) ? this.measure : 'Quantity';

        var formatted_data = [{
                key: measure_label,
                values: _.map(this.data, this.format_data.bind(this))
            }];

        nv.addGraph(function () {
            var chart = nv.models.lineChart()
                .x(function (d,u) { return u; })
                .width(600)
                .height(300)
                .margin({top: 30, right: 20, bottom: 20, left: 60});

            d3.select('.graph_chart svg')
                .attr('width', 600)
                .attr('height', 300)
                .datum(formatted_data)
                .call(chart);

            return chart;
          });
    },

    render_pie_chart: function () {
        var formatted_data = _.map(this.data, this.format_data.bind(this));

        nv.addGraph(function () {
            var chart = nv.models.pieChart()
                .color(d3.scale.category10().range())
                .width(650)
                .height(400);

            d3.select('.graph_chart svg')
                .datum(formatted_data)
                .transition().duration(1200)
                .attr('width', 650)
                .attr('height', 400)
                .call(chart);

            nv.utils.windowResize(chart.update);
            return chart;
        });
    },

});

/**
 * Query the server and return a deferred which will return the data
 * with all the groupbys applied (this is done for now, but the goal
 * is to modify read_group in order to allow eager and lazy groupbys
 */
function query_groups (model, fields, domain, groupbys) {
    return model.query(fields)
        .filter(domain)
        .group_by(groupbys)
        .then(function (results) {
            var non_empty_results = _.filter(results, function (group) {
                return group.attributes.length > 0;
            });
            if (groupbys.length <= 1) {
                return non_empty_results;
            } else {
                var get_subgroups = $.when.apply(null, _.map(non_empty_results, function (result) {
                    var new_domain = result.model._domain;
                    var new_groupings = groupbys.slice(1);
                    return query_groups(model, fields,new_domain, new_groupings).then(function (subgroups) {
                        result.subgroups_data = subgroups;
                    });
                }));
                return get_subgroups.then(function () {
                    return non_empty_results;
                });
            }
        });
}

};

<|endoftext|>


<commit_before>/**
 * Object wrapper for raw Google location JSON response
 * Supports checking if info is valid,
 * updating the location info,
 * retrieving info in english
 * retrieving coords as simple array
 **/
var GmapsLocation = function(location){
	if (!(this instanceof GmapsLocation)) {
		throw new TypeError("GmapsLocation constructor cannot be called as a function.");
	}
	this.setLocation(location);
}

// Verifies that the data passed is in fact a google locaton object
GmapsLocation.isGoogleObject = function(location){
	return ((typeof location == "object") && ("address_components" in location) && ("formatted_address" in location) && ("geometry" in location) && ("location" in location.geometry));
};

// Only setter function. If data is set, it must be valid
GmapsLocation.prototype.setLocation = function(location){
	if(GmapsLocation.isGoogleObject(location)){
		this.data = location;
		return true;
	}
	return false;
};

GmapsLocation.prototype.isset = function(){
	return (this.data !== null);
};

/**
 * Custom responses for the get method
 */
GmapsLocation.prototype._types = {
	'number': 'street_number',
	'street': 'route',
	'city': 'locality',
	'county': 'administrative_area_level_2',
	'state': 'administrative_area_level_1',
	'country': 'country',
	'postal': 'postal_code'
};

GmapsLocation.prototype.get = function(component, short){
	if(this.data !== null){
		// Filter address and location data
		switch(component){
			case 'location':
				return this.data;
			case 'address':
				return this.data.formatted_address;
			case 'street_address':
				return this.get('number') ? this.get('number') + ' ' + this.get('street') : this.get('street');
			case 'coords':
				return this._coords();
			case 'name':
				return this.data.name;
			case 'phone':
				return this.data.formatted_phone_number;
			case 'phone_intl':
				return this.data.international_phone_number;
			case 'website':
				return this.data.website;
			case 'gplus':
				return this.data.url;
			case 'icon':
				return this.data.icon;
			default:
			// each address component
			for(var comp in this.data.address_components){
				// each component type
				for(var type in this.data.address_components[comp]['types']){
					if(this._types[component] == this.data.address_components[comp]['types'][type]){
						return short !== true ? this.data.address_components[comp].long_name : this.data.address_components[comp].short_name;
					}
				}
			}
		} // End Switch
	}
	return false;
};

GmapsLocation.prototype._coords = function(){
	var keys = Object.keys(this.data.geometry.location);
	return {'lat': this.data.geometry.location[keys[0]], 'lng': this.data.geometry.location[keys[1]] };
};<commit_msg>Get place_id<commit_after>/**
 * Object wrapper for raw Google location JSON response
 * Supports checking if info is valid,
 * updating the location info,
 * retrieving info in english
 * retrieving coords as simple array
 **/
var GmapsLocation = function(location){
	if (!(this instanceof GmapsLocation)) {
		throw new TypeError("GmapsLocation constructor cannot be called as a function.");
	}
	this.setLocation(location);
}

// Verifies that the data passed is in fact a google locaton object
GmapsLocation.isGoogleObject = function(location){
	return ((typeof location == "object") && ("address_components" in location) && ("formatted_address" in location) && ("geometry" in location) && ("location" in location.geometry));
};

// Only setter function. If data is set, it must be valid
GmapsLocation.prototype.setLocation = function(location){
	if(GmapsLocation.isGoogleObject(location)){
		this.data = location;
		return true;
	}
	return false;
};

GmapsLocation.prototype.isset = function(){
	return (this.data !== null);
};

/**
 * Custom responses for the get method
 */
GmapsLocation.prototype._types = {
	'number': 'street_number',
	'street': 'route',
	'city': 'locality',
	'county': 'administrative_area_level_2',
	'state': 'administrative_area_level_1',
	'country': 'country',
	'postal': 'postal_code'
};

GmapsLocation.prototype.get = function(component, short){
	if(this.data !== null){
		// Filter address and location data
		switch(component){
			case 'location':
				return this.data;
			case 'id':
				return this.data.place_id;
			case 'address':
				return this.data.formatted_address;
			case 'street_address':
				return this.get('number') ? this.get('number') + ' ' + this.get('street') : this.get('street');
			case 'coords':
				return this._coords();
			case 'name':
				return this.data.name;
			case 'phone':
				return this.data.formatted_phone_number;
			case 'phone_intl':
				return this.data.international_phone_number;
			case 'website':
				return this.data.website;
			case 'gplus':
				return this.data.url;
			case 'icon':
				return this.data.icon;
			default:
			// each address component
			for(var comp in this.data.address_components){
				// each component type
				for(var type in this.data.address_components[comp]['types']){
					if(this._types[component] == this.data.address_components[comp]['types'][type]){
						return short !== true ? this.data.address_components[comp].long_name : this.data.address_components[comp].short_name;
					}
				}
			}
		} // End Switch
	}
	return false;
};

GmapsLocation.prototype._coords = function(){
	var keys = Object.keys(this.data.geometry.location);
	return {'lat': this.data.geometry.location[keys[0]], 'lng': this.data.geometry.location[keys[1]] };
};<|endoftext|>