<commit_before>/**
 * Created by Leonardo on 5/27/2017.
 */
var express = require('express');
var router = express.Router();
var Instance = require('../models/instance');
var validate = require('express-jsonschema').validate;
var InstanceSchema = require('../models/instance_validate_schema').InstanceSchema;
var InstancePutSchema = require('../models/instance_validate_schema').InstancePutSchema;

router.get('/', function(req, res, next) {

    var db_query = {};
    if (req.query.q){
        var query = req.query.q;
        db_query = {
            $or: [
                {organisms: { $in: [query] }},
                {$text: {$search: query}},
                {name: {$regex: query, $options: "i"}}
            ]
        }
    }

    Instance.find(db_query, function(err, instances){
        if (err){
            res.send(err);
        }
        var api_response = {};
        api_response['instances'] = instances
        api_response['statusCode'] = 200;
        if (instances.length === 0){
            api_response['statusCode'] = 404;
        }
        api_response['executionTime'] = new Date().toLocaleString();
        res.status(api_response['statusCode']).json(api_response);
    });
});

router.get('/:id', function(req, res, next) {
    var toFind = req.params.id;
    Instance.find({
        $or:[ { id: toFind}, {name: toFind} ]  // Is Case Sensitive
    },
    function(err, instances){
        if (err){
            res.send(err);
        }
        api_response = {};
        api_response['instance'] = instances[0];
        api_response['statusCode'] = 200;
        if (typeof instances[0] === 'undefined'){
            api_response['errorMsg'] = "Not Found"
            api_response['statusCode'] = 404;
        }
        api_response['executionTime'] = new Date().toLocaleString();
        res.status(api_response['statusCode']).json(api_response);
    });
});

router.delete('/:id', function(req, res, next){
    Instance.find({id: req.params.id}).remove(function(err, info){
        if (err){
            res.send(err);
        }
        var statusCode = 200;
        n_removed = info['result']['n'];
        var message = 'Instance Successfully Deleted';
        if (n_removed === 0){
            statusCode = 404;
            message = 'Instance Not Found';
        }
        res.status(statusCode).json({
            statusCode: statusCode,
            message: message,
            executionTime: new Date().toLocaleString()
        });
    });
});

router.post('/', validate({body: InstanceSchema}), function(req, res, next){

    // Check if the request is an 'application/json' type.
    if (req.get('Content-Type') !== 'application/json'){
        res.status(406).json({
            statusCode: 406,
            message: "Bad Request",
            executionTime: new Date().toLocaleString()
        });
        return;
    }

    newInstanceId = "";
    Instance.find().sort([['id', 'descending']]).exec(function(err, found){
        if (err){
            res.send(err);
        }
        newInstanceId = parseInt(found[0].id) + 1;

        var newInstanceObject = {
            id:                 newInstanceId.toString(),
            name:               req.body.name,
            neighbours:         req.body.neighbours,
            organisms:          req.body.organisms,
            twitter:            req.body.twitter,
            location:           req.body.location,
            url:                req.body.url,
            description:        req.body.description,
            created_at:         new Date(),
            last_time_updated:  new Date()
        };

        newInstanceObject.api_version =  typeof(req.body.api_version) !== 'undefined' ? req.body.api_version : "";
        newInstanceObject.release_version =  typeof(req.body.release_version) !== 'undefined' ? req.body.release_version : "";
        newInstanceObject.intermine_version =  typeof(req.body.intermine_version) !== 'undefined' ? req.body.intermine_version : "";
        newInstanceObject.colors =  typeof(req.body.colors) !== 'undefined' ? req.body.colors : "";
        newInstanceObject.images =  typeof(req.body.images) !== 'undefined' ? req.body.images : "";

        var newInstance = new Instance(newInstanceObject);

        newInstance.save(function(err){
            if (err){
                res.send(err);
            }
            res.status(201).json({
                instance_id: newInstanceId,
                statusCode: 201,
                message: "Instance Successfully Added to the Registry",
                executionTime: new Date().toLocaleString()
            });
        });
    });
});

router.put('/:id', validate({body: InstancePutSchema}), function(req, res, next){
    // Check if the request is an 'application/json' type.
    if (req.get('Content-Type') !== 'application/json'){
        res.status(406).json({
            statusCode: 406,
            message: "Bad Request",
            executionTime: new Date().toLocaleString()
        });
        return;
    }

    Instance.findOne({id : req.params.id}, function(err, instance){
        if (instance == null){
            res.status(404).json({
                statusCode: 404,
                message: "Instance Not Found",
                executionTime: new Date().toLocaleString()
            });
            return;
        }
        instance.name = typeof(req.body.name) !== 'undefined' ? req.body.name : instance.name;
        instance.neighbours = typeof(req.body.neighbours) !== 'undefined' ? req.body.neighbours : instance.neighbours;
        instance.organisms = typeof(req.body.organisms) !== 'undefined' ? req.body.organisms : instance.organisms;
        instance.twitter = typeof(req.body.twitter) !== 'undefined' ? req.body.twitter : instance.twitter;
        if (typeof(req.body.location) !== 'undefined'){
            instance.location.latitude = typeof(req.body.location.latitude) !== 'undefined' ? req.body.location.latitude : instance.location.latitude;
            instance.location.longitude = typeof(req.body.location.longitude) !== 'undefined' ? req.body.location.longitude : instance.location.longitude;
        }
        instance.url = typeof(req.body.url) !== 'undefined' ? req.body.url : instance.url;
        instance.description = typeof(req.body.description) !== 'undefined' ? req.body.description : instance.description;
        instance.last_time_updated = new Date();
        instance.api_version =  typeof(req.body.api_version) !== 'undefined' ? req.body.api_version : instance.api_version;
        instance.release_version =  typeof(req.body.release_version) !== 'undefined' ? req.body.release_version : instance.release_version;
        instance.intermine_version =  typeof(req.body.intermine_version) !== 'undefined' ? req.body.intermine_version : instance.intermine_version;
        if (typeof(req.body.colors) !== 'undefined'){
            if (typeof(req.body.colors.focus) !== 'undefined'){
                instance.colors.focus.fg =  typeof(req.body.colors.focus.fg) !== 'undefined' ? req.body.colors.focus.fg : instance.colors.focus.fg;
                instance.colors.focus.bg =  typeof(req.body.colors.focus.bg) !== 'undefined' ? req.body.colors.focus.bg : instance.colors.focus.bg;
            }
        }
        if (typeof(req.body.colors) !== 'undefined'){
            if (typeof(req.body.colors.main) !== 'undefined'){
                instance.colors.main.fg =  typeof(req.body.colors.main.fg) !== 'undefined' ? req.body.colors.main.fg : instance.colors.main.fg;
                instance.colors.main.bg =  typeof(req.body.colors.main.bg) !== 'undefined' ? req.body.colors.main.bg : instance.colors.main.bg;
            }
        }
        if (typeof(req.body.images) !== 'undefined'){
            instance.images.small =  typeof(req.body.images.small) !== 'undefined' ? req.body.images.small : instance.images.small;
            instance.images.main =  typeof(req.body.images.main) !== 'undefined' ? req.body.images.main : instance.images.main;
        }

        instance.save(function(err){
            if (err){
                res.send(err);
            }
            res.status(201).json({
                updated_instance_id: req.params.id,
                statusCode: 201,
                message: "Instance Successfully Updated",
                executionTime: new Date().toLocaleString()
            });
        });
    });
});

module.exports = router;
<commit_msg>API Endpoint: GET/:id - Case Insensitive Search<commit_after>var express = require('express');
var router = express.Router();
var Instance = require('../models/instance');
var validate = require('express-jsonschema').validate;
var InstanceSchema = require('../models/instance_validate_schema').InstanceSchema;
var InstancePutSchema = require('../models/instance_validate_schema').InstancePutSchema;

router.get('/', function(req, res, next) {

    var db_query = {};
    if (req.query.q){
        var query = req.query.q;
        db_query = {
            $or: [
                {organisms: { $in: [query] }},
                {$text: {$search: query}},
                {name: {$regex: query, $options: "i"}}
            ]
        }
    }

    Instance.find(db_query, function(err, instances){
        if (err){
            res.send(err);
        }
        var api_response = {};
        api_response['instances'] = instances
        api_response['statusCode'] = 200;
        if (instances.length === 0){
            api_response['statusCode'] = 404;
        }
        api_response['executionTime'] = new Date().toLocaleString();
        res.status(api_response['statusCode']).json(api_response);
    });
});

router.get('/:id', function(req, res, next) {
    var toFind = req.params.id;
    Instance.find({
        $or:[ { id: toFind}, {name: {$regex: toFind, $options: "i"}} ]  // Case Insensitive
    },
    function(err, instances){
        if (err){
            res.send(err);
        }
        api_response = {};
        api_response['instance'] = instances[0];
        api_response['statusCode'] = 200;
        if (typeof instances[0] === 'undefined'){
            api_response['errorMsg'] = "Not Found"
            api_response['statusCode'] = 404;
        }
        api_response['executionTime'] = new Date().toLocaleString();
        res.status(api_response['statusCode']).json(api_response);
    });
});

router.delete('/:id', function(req, res, next){
    Instance.find({id: req.params.id}).remove(function(err, info){
        if (err){
            res.send(err);
        }
        var statusCode = 200;
        n_removed = info['result']['n'];
        var message = 'Instance Successfully Deleted';
        if (n_removed === 0){
            statusCode = 404;
            message = 'Instance Not Found';
        }
        res.status(statusCode).json({
            statusCode: statusCode,
            message: message,
            executionTime: new Date().toLocaleString()
        });
    });
});

router.post('/', validate({body: InstanceSchema}), function(req, res, next){

    // Check if the request is an 'application/json' type.
    if (req.get('Content-Type') !== 'application/json'){
        res.status(406).json({
            statusCode: 406,
            message: "Bad Request",
            executionTime: new Date().toLocaleString()
        });
        return;
    }

    newInstanceId = "";
    Instance.find().sort([['id', 'descending']]).exec(function(err, found){
        if (err){
            res.send(err);
        }
        newInstanceId = parseInt(found[0].id) + 1;

        var newInstanceObject = {
            id:                 newInstanceId.toString(),
            name:               req.body.name,
            neighbours:         req.body.neighbours,
            organisms:          req.body.organisms,
            twitter:            req.body.twitter,
            location:           req.body.location,
            url:                req.body.url,
            description:        req.body.description,
            created_at:         new Date(),
            last_time_updated:  new Date()
        };

        newInstanceObject.api_version =  typeof(req.body.api_version) !== 'undefined' ? req.body.api_version : "";
        newInstanceObject.release_version =  typeof(req.body.release_version) !== 'undefined' ? req.body.release_version : "";
        newInstanceObject.intermine_version =  typeof(req.body.intermine_version) !== 'undefined' ? req.body.intermine_version : "";
        newInstanceObject.colors =  typeof(req.body.colors) !== 'undefined' ? req.body.colors : "";
        newInstanceObject.images =  typeof(req.body.images) !== 'undefined' ? req.body.images : "";

        var newInstance = new Instance(newInstanceObject);

        newInstance.save(function(err){
            if (err){
                res.send(err);
            }
            res.status(201).json({
                instance_id: newInstanceId,
                statusCode: 201,
                message: "Instance Successfully Added to the Registry",
                executionTime: new Date().toLocaleString()
            });
        });
    });
});

router.put('/:id', validate({body: InstancePutSchema}), function(req, res, next){
    // Check if the request is an 'application/json' type.
    if (req.get('Content-Type') !== 'application/json'){
        res.status(406).json({
            statusCode: 406,
            message: "Bad Request",
            executionTime: new Date().toLocaleString()
        });
        return;
    }

    Instance.findOne({id : req.params.id}, function(err, instance){
        if (instance == null){
            res.status(404).json({
                statusCode: 404,
                message: "Instance Not Found",
                executionTime: new Date().toLocaleString()
            });
            return;
        }
        instance.name = typeof(req.body.name) !== 'undefined' ? req.body.name : instance.name;
        instance.neighbours = typeof(req.body.neighbours) !== 'undefined' ? req.body.neighbours : instance.neighbours;
        instance.organisms = typeof(req.body.organisms) !== 'undefined' ? req.body.organisms : instance.organisms;
        instance.twitter = typeof(req.body.twitter) !== 'undefined' ? req.body.twitter : instance.twitter;
        if (typeof(req.body.location) !== 'undefined'){
            instance.location.latitude = typeof(req.body.location.latitude) !== 'undefined' ? req.body.location.latitude : instance.location.latitude;
            instance.location.longitude = typeof(req.body.location.longitude) !== 'undefined' ? req.body.location.longitude : instance.location.longitude;
        }
        instance.url = typeof(req.body.url) !== 'undefined' ? req.body.url : instance.url;
        instance.description = typeof(req.body.description) !== 'undefined' ? req.body.description : instance.description;
        instance.last_time_updated = new Date();
        instance.api_version =  typeof(req.body.api_version) !== 'undefined' ? req.body.api_version : instance.api_version;
        instance.release_version =  typeof(req.body.release_version) !== 'undefined' ? req.body.release_version : instance.release_version;
        instance.intermine_version =  typeof(req.body.intermine_version) !== 'undefined' ? req.body.intermine_version : instance.intermine_version;
        if (typeof(req.body.colors) !== 'undefined'){
            if (typeof(req.body.colors.focus) !== 'undefined'){
                instance.colors.focus.fg =  typeof(req.body.colors.focus.fg) !== 'undefined' ? req.body.colors.focus.fg : instance.colors.focus.fg;
                instance.colors.focus.bg =  typeof(req.body.colors.focus.bg) !== 'undefined' ? req.body.colors.focus.bg : instance.colors.focus.bg;
            }
        }
        if (typeof(req.body.colors) !== 'undefined'){
            if (typeof(req.body.colors.main) !== 'undefined'){
                instance.colors.main.fg =  typeof(req.body.colors.main.fg) !== 'undefined' ? req.body.colors.main.fg : instance.colors.main.fg;
                instance.colors.main.bg =  typeof(req.body.colors.main.bg) !== 'undefined' ? req.body.colors.main.bg : instance.colors.main.bg;
            }
        }
        if (typeof(req.body.images) !== 'undefined'){
            instance.images.small =  typeof(req.body.images.small) !== 'undefined' ? req.body.images.small : instance.images.small;
            instance.images.main =  typeof(req.body.images.main) !== 'undefined' ? req.body.images.main : instance.images.main;
        }

        instance.save(function(err){
            if (err){
                res.send(err);
            }
            res.status(201).json({
                updated_instance_id: req.params.id,
                statusCode: 201,
                message: "Instance Successfully Updated",
                executionTime: new Date().toLocaleString()
            });
        });
    });
});

module.exports = router;
<|endoftext|>


<commit_before>pc.extend(pc, function () {
    var ImageElement = function ImageElement (element) {
        this._element = element;
        this._entity = element.entity;
        this._system = element.system;

        // public
        this._textureAsset = null;
        this._texture = null;
        this._materialAsset = null;
        this._material = null;

        this._rect = new pc.Vec4(0,0,1,1); // x, y, w, h

        this._color = new pc.Color(1,1,1,1);

        // private
        this._positions = [];
        this._normals = [];
        this._uvs = [];
        this._indices = [];

        this._mesh = this._createMesh();
        this._node = new pc.GraphNode();
        this._model = new pc.Model();
        this._model.graph = this._node;
        this._meshInstance = new pc.MeshInstance(this._node, this._mesh, this._material);
        this._model.meshInstances.push(this._meshInstance);
        this._drawOrder = 0;

        // add model to sceen
        if (this._entity.enabled) {
            this._system.app.scene.addModel(this._model);
        }

        this._entity.addChild(this._model.graph);
        this._model._entity = this._entity;

        // initialize based on screen
        this._onScreenChange(this._element.screen);

        // listen for events
        this._element.on('resize', this._onParentResize, this);
        this._element.on('screen:set:screenspace', this._onScreenSpaceChange, this);
        this._element.on('set:screen', this._onScreenChange, this);
        this._element.on('set:draworder', this._onDrawOrderChange, this);
        this._element.on('screen:set:resolution', this._onResolutionChange, this);
    };

    pc.extend(ImageElement.prototype, {
        destroy: function () {
            if (this._model) {
                this._system.app.scene.removeModel(this._model);
                this._model.destroy();
                this._model = null;
            }

            this._element.off('resize', this._onParentResize, this);
            this._element.off('screen:set:screenspace', this._onScreenSpaceChange, this);
            this._element.off('set:screen', this._onScreenChange, this);
            this._element.off('set:draworder', this._onDrawOrderChange, this);
            this._element.off('screen:set:resolution', this._onResolutionChange, this);
        },

        _onResolutionChange: function (res) {
        },

        _onParentResize: function () {
            if (this._mesh) this._updateMesh(this._mesh);
        },

        _onScreenSpaceChange: function (value) {
            this._updateMaterial(value);
        },

        _onScreenChange: function (screen) {
            if (screen) {
                this._updateMaterial(screen.screen.screenSpace);
            } else {
                this._updateMaterial(false);
            }
        },

        _onDrawOrderChange: function (order) {
            this._drawOrder = order;
            if (this._meshInstance) {
                this._meshInstance.drawOrder = order;
            }
        },

        _updateMaterial: function (screenSpace) {
            if (screenSpace) {
                if (!this._materialAsset) {
                    this._material = this._system.defaultScreenSpaceImageMaterial;
                }
                if (this._meshInstance) this._meshInstance.layer = pc.scene.LAYER_HUD;
            } else {
                if (!this._materialAsset) {
                    this._material = this._system.defaultImageMaterial;
                }
                if (this._meshInstance) this._meshInstance.layer = pc.scene.LAYER_WORLD;
            }
            if (this._meshInstance) {
                this._meshInstance.material = this._material;
                this._meshInstance.screenSpace = screenSpace;
            }
        },

        // build a quad for the image
        _createMesh: function () {
            var w = this._element.width;
            var h = this._element.height;

            this._positions[0] = 0;
            this._positions[1] = 0;
            this._positions[2] = 0;
            this._positions[3] = w;
            this._positions[4] = 0;
            this._positions[5] = 0;
            this._positions[6] = w;
            this._positions[7] = h;
            this._positions[8] = 0;
            this._positions[9] = 0;
            this._positions[10] = h;
            this._positions[11] = 0;

            for (var i = 0; i < 12; i+=3) {
                this._normals[i] = 0;
                this._normals[i+1] = 0;
                this._normals[i+2] = -1;
            }

            this._uvs[0] = this._rect.data[0];
            this._uvs[1] = this._rect.data[1];
            this._uvs[2] = this._rect.data[0] + this._rect.data[2];
            this._uvs[3] = this._rect.data[1];
            this._uvs[4] = this._rect.data[0] + this._rect.data[2];
            this._uvs[5] = this._rect.data[1] + this._rect.data[3];
            this._uvs[6] = this._rect.data[0];
            this._uvs[7] = this._rect.data[1] + this._rect.data[3];;

            this._indices[0] = 0;
            this._indices[1] = 1;
            this._indices[2] = 3;
            this._indices[3] = 2;
            this._indices[4] = 3;
            this._indices[5] = 1;

            var mesh = pc.createMesh(this._system.app.graphicsDevice, this._positions, {uvs: this._uvs, normals: this._normals, indices: this._indices});
            this._updateMesh(mesh);

            return mesh;
        },

        _updateMesh: function (mesh) {
            var w = this._element.width;
            var h = this._element.height;

            // update material
            if (this._element.screen) {
                this._updateMaterial(this._element.screen.screen.screenSpace);
            } else {
                this._updateMaterial();
            }

            this._positions[0] = 0;
            this._positions[1] = 0;
            this._positions[2] = 0;
            this._positions[3] = w;
            this._positions[4] = 0;
            this._positions[5] = 0;
            this._positions[6] = w;
            this._positions[7] = h;
            this._positions[8] = 0;
            this._positions[9] = 0;
            this._positions[10] = h;
            this._positions[11] = 0;

            // offset for pivot
            var hp = this._element.pivot.data[0];
            var vp = this._element.pivot.data[1];

            for (var i = 0; i < this._positions.length; i += 3) {
                this._positions[i] -= hp*w;
                this._positions[i+1] -= vp*h;
            }

            this._uvs[0] = this._rect.data[0];
            this._uvs[1] = this._rect.data[1];
            this._uvs[2] = this._rect.data[0] + this._rect.data[2];
            this._uvs[3] = this._rect.data[1];
            this._uvs[4] = this._rect.data[0] + this._rect.data[2];
            this._uvs[5] = this._rect.data[1] + this._rect.data[3];
            this._uvs[6] = this._rect.data[0];
            this._uvs[7] = this._rect.data[1] + this._rect.data[3];;

            var vb = mesh.vertexBuffer;
            var it = new pc.VertexIterator(vb);
            var numVertices = 4;
            for (var i = 0; i < numVertices; i++) {
                it.element[pc.SEMANTIC_POSITION].set(this._positions[i*3+0], this._positions[i*3+1], this._positions[i*3+2]);
                it.element[pc.SEMANTIC_NORMAL].set(this._normals[i*3+0], this._normals[i*3+1], this._normals[i*3+2]);
                it.element[pc.SEMANTIC_TEXCOORD0].set(this._uvs[i*2+0], this._uvs[i*2+1]);

                it.next();
            }
            it.end();

            mesh.aabb.compute(this._positions);
        },

        _onMaterialLoad: function (asset) {
            this.material = asset.resource;
        },

        _onMaterialChange: function () {

        },

        _onMaterialRemove: function () {

        },

        _onTextureLoad: function (asset) {
            this.texture = asset.resource;
        },

        _onTextureChange: function (asset) {

        },

        _onTextureRemove: function (asset) {

        },

        onEnable: function () {
            if (this._model && !this._system.app.scene.containsModel(this._model)) {
                this._system.app.scene.addModel(this._model);
            }
        },

        onDisable: function () {
            if (this._model && this._system.app.scene.containsModel(this._model)) {
                this._system.app.scene.removeModel(this._model);
            }
        }
    });

    Object.defineProperty(ImageElement.prototype, "color", {
        get: function () {
            return this._color;
        },

        set: function (value) {
            this._color.data[0] = value.data[0];
            this._color.data[1] = value.data[1];
            this._color.data[2] = value.data[2];

            if (this._meshInstance) {
                this._meshInstance.setParameter('material_emissive', this._color.data3);
            }
        }
    });

    Object.defineProperty(ImageElement.prototype, "opacity", {
        get: function () {
            return this._color.data[3];
        },

        set: function (value) {
            this._color.data[3] = value;
            this._meshInstance.setParameter("material_opacity", value);
        }
    });

    Object.defineProperty(ImageElement.prototype, "rect", {
        get: function () {
            return this._rect;
        },

        set: function (value) {
            if (value instanceof pc.Vec4) {
                this._rect.set(value.x, value.y, value.z, value.w);
            } else {
                this._rect.set(value[0], value[1], value[2], value[3]);
            }
            if (this._mesh) this._updateMesh(this._mesh);
        }
    });

    Object.defineProperty(ImageElement.prototype, "material", {
        get: function () {
            return this._material;
        },
        set: function (value) {
            if (! value) {
                var screenSpace = this._element.screen ? this._element.screen.screen.screenSpace : false;
                value = screenSpace ? this._system.defaultScreenSpaceImageMaterial : this._system.defaultImageMaterial;
            }

            this._material = value;
            if (value) {
                this._meshInstance.material = value;

                // if we are back to the default material
                // and we have no texture then reset color properties
                if (value === this._system.defaultScreenSpaceImageMaterial || value === this._system.defaultImageMaterial) {
                    if (! this._texture) {
                        this._meshInstance.deleteParameter('material_opacity');
                        this._meshInstance.deleteParameter('material_emissive');
                    }
                }
            }
        }
    });

    Object.defineProperty(ImageElement.prototype, "materialAsset", {
        get: function () {
            return this._materialAsset;
        },

        set: function (value) {
            var assets = this._system.app.assets;
            var _id = value;

            if (value instanceof pc.Asset) {
                _id = value.id;
            }

            if (this._materialAsset !== _id) {
                if (this._materialAsset) {
                    var _prev = assets.get(this._materialAsset);

                    _prev.off("load", this._onMaterialLoad, this);
                    _prev.off("change", this._onMaterialChange, this);
                    _prev.off("remove", this._onMaterialRemove, this);
                }

                this._materialAsset = _id;
                if (this._materialAsset) {
                    var asset = assets.get(this._materialAsset);

                    asset.on("load", this._onMaterialLoad, this);
                    asset.on("change", this._onMaterialChange, this);
                    asset.on("remove", this._onMaterialRemove, this);

                    if (asset.resource) {
                        this._onMaterialLoad(asset);
                    } else {
                        assets.load(asset);
                    }
                } else {
                    this.material = null;
                }
            }
        }
    });

    Object.defineProperty(ImageElement.prototype, "texture", {
        get: function () {
            return this._texture;
        },
        set: function (value) {
            this._texture = value;

            if (value) {
                // default texture just uses emissive and opacity maps
                this._meshInstance.setParameter("texture_emissiveMap", this._texture);
                this._meshInstance.setParameter("texture_opacityMap", this._texture);
                this._meshInstance.setParameter("material_emissive", this._color.data3);
                this._meshInstance.setParameter("material_opacity", this._color.data[3]);
            } else {
                // clear texture params
                this._meshInstance.deleteParameter("texture_emissiveMap");
                this._meshInstance.deleteParameter("texture_opacityMap");

                // if we are back to the default material then reset
                // color parameters
                if (this._material === this._system.defaultImageMaterial || this._material === this._system.defaultScreenSpaceImageMaterial) {
                    this._meshInstance.deleteParameter('material_opacity');
                    this._meshInstance.deleteParameter('material_emissive');
                }
            }
        }
    });

    Object.defineProperty(ImageElement.prototype, "textureAsset", {
        get: function () {
            return this._textureAsset;
        },

        set: function (value) {
            var assets = this._system.app.assets;
            var _id = value;

            if (value instanceof pc.Asset) {
                _id = value.id;
            }

            if (this._textureAsset !== _id) {
                if (this._textureAsset) {
                    var _prev = assets.get(this._textureAsset);

                    _prev.off("load", this._onTextureLoad, this);
                    _prev.off("change", this._onTextureChange, this);
                    _prev.off("remove", this._onTextureRemove, this);
                }

                this._textureAsset = _id;
                if (this._textureAsset) {
                    var asset = assets.get(this._textureAsset);

                    asset.on("load", this._onTextureLoad, this);
                    asset.on("change", this._onTextureChange, this);
                    asset.on("remove", this._onTextureRemove, this);

                    if (asset.resource) {
                        this._onTextureLoad(asset);
                    } else {
                        assets.load(asset);
                    }
                } else {
                    this.texture = null;
                }
            }
        }
    });

    return {
        ImageElement: ImageElement
    };
}());

<commit_msg>[FIX] errors in image element when texture asset is not the registry<commit_after>pc.extend(pc, function () {
    var ImageElement = function ImageElement (element) {
        this._element = element;
        this._entity = element.entity;
        this._system = element.system;

        // public
        this._textureAsset = null;
        this._texture = null;
        this._materialAsset = null;
        this._material = null;

        this._rect = new pc.Vec4(0,0,1,1); // x, y, w, h

        this._color = new pc.Color(1,1,1,1);

        // private
        this._positions = [];
        this._normals = [];
        this._uvs = [];
        this._indices = [];

        this._mesh = this._createMesh();
        this._node = new pc.GraphNode();
        this._model = new pc.Model();
        this._model.graph = this._node;
        this._meshInstance = new pc.MeshInstance(this._node, this._mesh, this._material);
        this._model.meshInstances.push(this._meshInstance);
        this._drawOrder = 0;

        // add model to sceen
        if (this._entity.enabled) {
            this._system.app.scene.addModel(this._model);
        }

        this._entity.addChild(this._model.graph);
        this._model._entity = this._entity;

        // initialize based on screen
        this._onScreenChange(this._element.screen);

        // listen for events
        this._element.on('resize', this._onParentResize, this);
        this._element.on('screen:set:screenspace', this._onScreenSpaceChange, this);
        this._element.on('set:screen', this._onScreenChange, this);
        this._element.on('set:draworder', this._onDrawOrderChange, this);
        this._element.on('screen:set:resolution', this._onResolutionChange, this);
    };

    pc.extend(ImageElement.prototype, {
        destroy: function () {
            if (this._model) {
                this._system.app.scene.removeModel(this._model);
                this._model.destroy();
                this._model = null;
            }

            this._element.off('resize', this._onParentResize, this);
            this._element.off('screen:set:screenspace', this._onScreenSpaceChange, this);
            this._element.off('set:screen', this._onScreenChange, this);
            this._element.off('set:draworder', this._onDrawOrderChange, this);
            this._element.off('screen:set:resolution', this._onResolutionChange, this);
        },

        _onResolutionChange: function (res) {
        },

        _onParentResize: function () {
            if (this._mesh) this._updateMesh(this._mesh);
        },

        _onScreenSpaceChange: function (value) {
            this._updateMaterial(value);
        },

        _onScreenChange: function (screen) {
            if (screen) {
                this._updateMaterial(screen.screen.screenSpace);
            } else {
                this._updateMaterial(false);
            }
        },

        _onDrawOrderChange: function (order) {
            this._drawOrder = order;
            if (this._meshInstance) {
                this._meshInstance.drawOrder = order;
            }
        },

        _updateMaterial: function (screenSpace) {
            if (screenSpace) {
                if (!this._materialAsset) {
                    this._material = this._system.defaultScreenSpaceImageMaterial;
                }
                if (this._meshInstance) this._meshInstance.layer = pc.scene.LAYER_HUD;
            } else {
                if (!this._materialAsset) {
                    this._material = this._system.defaultImageMaterial;
                }
                if (this._meshInstance) this._meshInstance.layer = pc.scene.LAYER_WORLD;
            }
            if (this._meshInstance) {
                this._meshInstance.material = this._material;
                this._meshInstance.screenSpace = screenSpace;
            }
        },

        // build a quad for the image
        _createMesh: function () {
            var w = this._element.width;
            var h = this._element.height;

            this._positions[0] = 0;
            this._positions[1] = 0;
            this._positions[2] = 0;
            this._positions[3] = w;
            this._positions[4] = 0;
            this._positions[5] = 0;
            this._positions[6] = w;
            this._positions[7] = h;
            this._positions[8] = 0;
            this._positions[9] = 0;
            this._positions[10] = h;
            this._positions[11] = 0;

            for (var i = 0; i < 12; i+=3) {
                this._normals[i] = 0;
                this._normals[i+1] = 0;
                this._normals[i+2] = -1;
            }

            this._uvs[0] = this._rect.data[0];
            this._uvs[1] = this._rect.data[1];
            this._uvs[2] = this._rect.data[0] + this._rect.data[2];
            this._uvs[3] = this._rect.data[1];
            this._uvs[4] = this._rect.data[0] + this._rect.data[2];
            this._uvs[5] = this._rect.data[1] + this._rect.data[3];
            this._uvs[6] = this._rect.data[0];
            this._uvs[7] = this._rect.data[1] + this._rect.data[3];;

            this._indices[0] = 0;
            this._indices[1] = 1;
            this._indices[2] = 3;
            this._indices[3] = 2;
            this._indices[4] = 3;
            this._indices[5] = 1;

            var mesh = pc.createMesh(this._system.app.graphicsDevice, this._positions, {uvs: this._uvs, normals: this._normals, indices: this._indices});
            this._updateMesh(mesh);

            return mesh;
        },

        _updateMesh: function (mesh) {
            var w = this._element.width;
            var h = this._element.height;

            // update material
            if (this._element.screen) {
                this._updateMaterial(this._element.screen.screen.screenSpace);
            } else {
                this._updateMaterial();
            }

            this._positions[0] = 0;
            this._positions[1] = 0;
            this._positions[2] = 0;
            this._positions[3] = w;
            this._positions[4] = 0;
            this._positions[5] = 0;
            this._positions[6] = w;
            this._positions[7] = h;
            this._positions[8] = 0;
            this._positions[9] = 0;
            this._positions[10] = h;
            this._positions[11] = 0;

            // offset for pivot
            var hp = this._element.pivot.data[0];
            var vp = this._element.pivot.data[1];

            for (var i = 0; i < this._positions.length; i += 3) {
                this._positions[i] -= hp*w;
                this._positions[i+1] -= vp*h;
            }

            this._uvs[0] = this._rect.data[0];
            this._uvs[1] = this._rect.data[1];
            this._uvs[2] = this._rect.data[0] + this._rect.data[2];
            this._uvs[3] = this._rect.data[1];
            this._uvs[4] = this._rect.data[0] + this._rect.data[2];
            this._uvs[5] = this._rect.data[1] + this._rect.data[3];
            this._uvs[6] = this._rect.data[0];
            this._uvs[7] = this._rect.data[1] + this._rect.data[3];;

            var vb = mesh.vertexBuffer;
            var it = new pc.VertexIterator(vb);
            var numVertices = 4;
            for (var i = 0; i < numVertices; i++) {
                it.element[pc.SEMANTIC_POSITION].set(this._positions[i*3+0], this._positions[i*3+1], this._positions[i*3+2]);
                it.element[pc.SEMANTIC_NORMAL].set(this._normals[i*3+0], this._normals[i*3+1], this._normals[i*3+2]);
                it.element[pc.SEMANTIC_TEXCOORD0].set(this._uvs[i*2+0], this._uvs[i*2+1]);

                it.next();
            }
            it.end();

            mesh.aabb.compute(this._positions);
        },

        _onMaterialLoad: function (asset) {
            this.material = asset.resource;
        },

        _onMaterialChange: function () {

        },

        _onMaterialRemove: function () {

        },

        _onTextureAdded: function (asset) {
            this._system.app.assets.off('add:' + asset.id, this._onTextureAdded, this);
            if (this._textureAsset === asset.id) {
                this._bindTextureAsset(asset);
            }
        },

        _bindTextureAsset: function (asset) {
            asset.on("load", this._onTextureLoad, this);
            asset.on("change", this._onTextureChange, this);
            asset.on("remove", this._onTextureRemove, this);

            if (asset.resource) {
                this._onTextureLoad(asset);
            } else {
                this._system.app.assets.load(asset);
            }
        },

        _onTextureLoad: function (asset) {
            this.texture = asset.resource;
        },

        _onTextureChange: function (asset) {

        },

        _onTextureRemove: function (asset) {

        },

        onEnable: function () {
            if (this._model && !this._system.app.scene.containsModel(this._model)) {
                this._system.app.scene.addModel(this._model);
            }
        },

        onDisable: function () {
            if (this._model && this._system.app.scene.containsModel(this._model)) {
                this._system.app.scene.removeModel(this._model);
            }
        }
    });

    Object.defineProperty(ImageElement.prototype, "color", {
        get: function () {
            return this._color;
        },

        set: function (value) {
            this._color.data[0] = value.data[0];
            this._color.data[1] = value.data[1];
            this._color.data[2] = value.data[2];

            if (this._meshInstance) {
                this._meshInstance.setParameter('material_emissive', this._color.data3);
            }
        }
    });

    Object.defineProperty(ImageElement.prototype, "opacity", {
        get: function () {
            return this._color.data[3];
        },

        set: function (value) {
            this._color.data[3] = value;
            this._meshInstance.setParameter("material_opacity", value);
        }
    });

    Object.defineProperty(ImageElement.prototype, "rect", {
        get: function () {
            return this._rect;
        },

        set: function (value) {
            if (value instanceof pc.Vec4) {
                this._rect.set(value.x, value.y, value.z, value.w);
            } else {
                this._rect.set(value[0], value[1], value[2], value[3]);
            }
            if (this._mesh) this._updateMesh(this._mesh);
        }
    });

    Object.defineProperty(ImageElement.prototype, "material", {
        get: function () {
            return this._material;
        },
        set: function (value) {
            if (! value) {
                var screenSpace = this._element.screen ? this._element.screen.screen.screenSpace : false;
                value = screenSpace ? this._system.defaultScreenSpaceImageMaterial : this._system.defaultImageMaterial;
            }

            this._material = value;
            if (value) {
                this._meshInstance.material = value;

                // if we are back to the default material
                // and we have no texture then reset color properties
                if (value === this._system.defaultScreenSpaceImageMaterial || value === this._system.defaultImageMaterial) {
                    if (! this._texture) {
                        this._meshInstance.deleteParameter('material_opacity');
                        this._meshInstance.deleteParameter('material_emissive');
                    }
                }
            }
        }
    });

    Object.defineProperty(ImageElement.prototype, "materialAsset", {
        get: function () {
            return this._materialAsset;
        },

        set: function (value) {
            var assets = this._system.app.assets;
            var _id = value;

            if (value instanceof pc.Asset) {
                _id = value.id;
            }

            if (this._materialAsset !== _id) {
                if (this._materialAsset) {
                    var _prev = assets.get(this._materialAsset);

                    _prev.off("load", this._onMaterialLoad, this);
                    _prev.off("change", this._onMaterialChange, this);
                    _prev.off("remove", this._onMaterialRemove, this);
                }

                this._materialAsset = _id;
                if (this._materialAsset) {
                    var asset = assets.get(this._materialAsset);

                    asset.on("load", this._onMaterialLoad, this);
                    asset.on("change", this._onMaterialChange, this);
                    asset.on("remove", this._onMaterialRemove, this);

                    if (asset.resource) {
                        this._onMaterialLoad(asset);
                    } else {
                        assets.load(asset);
                    }
                } else {
                    this.material = null;
                }
            }
        }
    });

    Object.defineProperty(ImageElement.prototype, "texture", {
        get: function () {
            return this._texture;
        },
        set: function (value) {
            this._texture = value;

            if (value) {
                // default texture just uses emissive and opacity maps
                this._meshInstance.setParameter("texture_emissiveMap", this._texture);
                this._meshInstance.setParameter("texture_opacityMap", this._texture);
                this._meshInstance.setParameter("material_emissive", this._color.data3);
                this._meshInstance.setParameter("material_opacity", this._color.data[3]);
            } else {
                // clear texture params
                this._meshInstance.deleteParameter("texture_emissiveMap");
                this._meshInstance.deleteParameter("texture_opacityMap");

                // if we are back to the default material then reset
                // color parameters
                if (this._material === this._system.defaultImageMaterial || this._material === this._system.defaultScreenSpaceImageMaterial) {
                    this._meshInstance.deleteParameter('material_opacity');
                    this._meshInstance.deleteParameter('material_emissive');
                }
            }
        }
    });

    Object.defineProperty(ImageElement.prototype, "textureAsset", {
        get: function () {
            return this._textureAsset;
        },

        set: function (value) {
            var assets = this._system.app.assets;
            var _id = value;

            if (value instanceof pc.Asset) {
                _id = value.id;
            }

            if (this._textureAsset !== _id) {
                if (this._textureAsset) {
                    var _prev = assets.get(this._textureAsset);

                    _prev.off("load", this._onTextureLoad, this);
                    _prev.off("change", this._onTextureChange, this);
                    _prev.off("remove", this._onTextureRemove, this);
                }

                this._textureAsset = _id;
                if (this._textureAsset) {
                    var asset = assets.get(this._textureAsset);
                    if (! asset) {
                        assets.on('add:' + this._textureAsset, this._onTextureAdded, this);
                    } else {
                        this._bindTextureAsset(asset);
                    }
                } else {
                    this.texture = null;
                }
            }
        }
    });

    return {
        ImageElement: ImageElement
    };
}());

<|endoftext|>


<commit_before>"use strict";
var cache = {};
var mock = {
    setItem: jest.genMockFunction().mockImplementation((key, value) => {
        return new Promise((resolve, reject) => {
            resolve(cache[key] = value);
        });
    }),
    getItem: jest.genMockFunction().mockImplementation(key => {
        return new Promise((resolve, reject) => {
            if (cache.hasOwnProperty(key))
                resolve(cache[key]);
            resolve('');
        });
    }),
    removeItem: jest.genMockFunction().mockImplementation(key => {
        return new Promise((resolve, reject) => {
            if (cache.hasOwnProperty(key))
                resolve(delete cache[key]);
            reject('No such item!');
        });
    }),
    clear: jest.genMockFunction().mockImplementation(() => {
        return new Promise((resolve, reject) => {
            resolve(cache = {});
        });
    }),
    _forceClear() {
        cache = {};
    }
};

module.exports = mock;
<commit_msg>Added verbosity for mockStorage<commit_after>"use strict";
// Replicate resolve and reject values from:
// https://github.com/facebook/react-native/blob/master/Libraries/Storage/AsyncStorage.js
// Haven't implemented callbacks as not yet used in react-native-store
// Haven't implemented multiGet/Set as not yet used in react-native-store

var cache = {};
var mock = {
    setItem: jest.genMockFunction().mockImplementation((key, value) => {
        return new Promise((resolve, reject) => {
            resolve(cache[key] = value);
        });
    }),
    getItem: jest.genMockFunction().mockImplementation(key => {
        return new Promise((resolve, reject) => {
            if (cache.hasOwnProperty(key))
                resolve(cache[key]);
            resolve(null);
        });
    }),
    removeItem: jest.genMockFunction().mockImplementation(key => {
        return new Promise((resolve, reject) => {
            if (cache.hasOwnProperty(key))
                resolve(delete cache[key]);
            reject('No such item!');
        });
    }),
    clear: jest.genMockFunction().mockImplementation(() => {
        return new Promise((resolve, reject) => {
            resolve(cache = {});
        });
    }),
    _forceClear() {
        cache = {};
    }
};

module.exports = mock;
<|endoftext|>


<commit_before>/**
 * This file contains all necessary Angular controller definitions for 'frontend.admin.login-history' module.
 *
 * Note that this file should only contain controllers and nothing else.
 */
(function() {
    'use strict';

    angular.module('frontend.plugins')
        .service('PluginHelperService', [
            '_','$log','BackendConfig','Upload','PluginsService',
            function( _,$log,BackendConfig,Upload,PluginsService) {

                function assignExtraProperties(_pluginName, options,fields,prefix) {
                    Object.keys(fields).forEach(function (item) {
                        if(fields[item].schema) {
                            assignExtraProperties(_pluginName, options,fields[item].schema.fields,item);
                        }else{
                            var path = prefix ? prefix + "." + item : item;
                            var value = fields[item].default;

                            if ((fields[item].type === 'array' || fields[item].type === 'set')
                                && (typeof value === 'object' || typeof value === 'string')
                                && _pluginName !== 'statsd'
                            ) {
                                value = [];
                            }
                            fields[item].value = value
                            fields[item].help = _.get(options,path) ? _.get(options,path).help : '';
                        }
                    });
                }

                function createConfigProperties(pluginName,fields,prefix,data) {
                    Object.keys(fields).forEach(function (key) {
                        if(fields[key].schema) {
                            createConfigProperties(pluginName,fields[key].schema.fields,key,data);
                        }else{
                            var path = prefix ? prefix + "." + key : key;
                            // if (fields[key].value instanceof Array && pluginName !== 'statsd') {
                            //     // Transform to comma separated string
                            //     // data['config.' + path] = fields[key].value.join(",");
                            //     if(!data.config) data.config = {};
                            //     if(fields[key].value) {
                            //         data.config[path] = fields[key].value.join(",");
                            //     }
                            // } else {
                            //     // data['config.' + path] = fields[key].value;
                            //     if(!data.config) data.config = {};
                            //     if(fields[key].value) {
                            //         data.config[path] = fields[key].value;
                            //     }
                            // }

                            if(!data.config) data.config = {};

                            if(fields[key].fields) {
                                fields[key].fields.forEach(field => {
                                    if(!data.config[path]) data.config[path] = {};
                                    const prop = Object.keys(field)[0];
                                    data.config[path][Object.keys(field)[0]] = _.get(field, `${prop}.value`);
                                })
                            }else{
                                if(fields[key].value !== ""
                                  && fields[key].value !== null
                                  && fields[key].value !== 'undefined'
                                  && fields[key].value !== undefined) {
                                    data.config[path] = fields[key].value;
                                }
                            }

                        }
                    });

                }

                var handlers  = {
                    common : function(data,success,error) {

                        PluginsService.add(data)
                            .then(function(resp){
                                success(resp);
                            }).catch(function(err){
                            error(err);
                        });
                    },
                    ssl : function(data, success,error,event) {
                        var files = [];

                        files.push(data['config.cert'])
                        files.push(data['config.key'])

                        Upload.upload({
                            url: 'kong/plugins',
                            arrayKey: '',
                            data: {
                                file: files,
                                'name' : data.name,
                                'config.only_https': data['config.only_https'],
                                'config.accept_http_if_already_terminated': data['config.accept_http_if_already_terminated']
                            }
                        }).then(function (resp) {
                            success(resp)
                        }, function (err) {
                            error(err)
                        }, function (evt) {
                            event(evt)
                        });
                    }
                }

                return {
                    addPlugin : function(data, success,error,event) {

                        if(handlers[data.name]) {
                            return handlers[data.name](data, success,error,event);
                        }else{
                            return handlers['common'](data, success,error,event);
                        }
                    },

                    createConfigProperties : function(pluginName,fields,prefix) {
                        var output = {}
                        createConfigProperties(pluginName,fields,prefix,output)
                        return output;
                    },

                    assignExtraProperties : function(_pluginName, options,fields,prefix) {
                        return  assignExtraProperties(_pluginName, options,fields,prefix)
                    },

                    /**
                     * Customize data fields for specified plugins if required by Konga's logic
                     * @param pluginName
                     * @param fields
                     */
                    customizeDataFieldsForPlugin : function(pluginName,fields) {

                        switch (pluginName) {
                            case 'ssl':
                                fields.cert.type = 'file'
                                fields.key.type = 'file'
                                break;
                        }
                    },

                    /**
                     * Mutate request data for specified plugins if required by Konga's logic
                     * @param request_data
                     * @param fields
                     */
                    applyMonkeyPatches : function(request_data,fields) {
                        if(request_data.name === 'response-ratelimiting'
                            && fields.limits.custom_fields) {
                            //console.log("fields.limits.custom_fields",fields.limits.custom_fields)
                            Object.keys(fields.limits.custom_fields)
                                .forEach(function(key){
                                    Object.keys(fields.limits.custom_fields[key])
                                        .forEach(function(cf_key){
                                            request_data['config.limits.' + key + '.' + cf_key] = fields.limits.custom_fields[key][cf_key].value

                                        });
                                });
                        }
                    }

                };
            }
        ])
    ;
}());
<commit_msg>Fix issue 443 plugin proxy_cache got "expected an integer"<commit_after>/**
 * This file contains all necessary Angular controller definitions for 'frontend.admin.login-history' module.
 *
 * Note that this file should only contain controllers and nothing else.
 */
(function() {
    'use strict';

    angular.module('frontend.plugins')
        .service('PluginHelperService', [
            '_','$log','BackendConfig','Upload','PluginsService',
            function( _,$log,BackendConfig,Upload,PluginsService) {

                function assignExtraProperties(_pluginName, options,fields,prefix) {
                    Object.keys(fields).forEach(function (item) {
                        if(fields[item].schema) {
                            assignExtraProperties(_pluginName, options,fields[item].schema.fields,item);
                        }else{
                            var path = prefix ? prefix + "." + item : item;
                            var value = fields[item].default;

                            if ((fields[item].type === 'array' || fields[item].type === 'set')
                                && (typeof value === 'object' || typeof value === 'string')
                                && _pluginName !== 'statsd'
                            ) {
                                value = [];
                            }
                            fields[item].value = value
                            fields[item].help = _.get(options,path) ? _.get(options,path).help : '';
                        }
                    });
                }

                function createConfigProperties(pluginName,fields,prefix,data) {
                    Object.keys(fields).forEach(function (key) {
                        if(fields[key].schema) {
                            createConfigProperties(pluginName,fields[key].schema.fields,key,data);
                        }else{
                            var path = prefix ? prefix + "." + key : key;
                            // if (fields[key].value instanceof Array && pluginName !== 'statsd') {
                            //     // Transform to comma separated string
                            //     // data['config.' + path] = fields[key].value.join(",");
                            //     if(!data.config) data.config = {};
                            //     if(fields[key].value) {
                            //         data.config[path] = fields[key].value.join(",");
                            //     }
                            // } else {
                            //     // data['config.' + path] = fields[key].value;
                            //     if(!data.config) data.config = {};
                            //     if(fields[key].value) {
                            //         data.config[path] = fields[key].value;
                            //     }
                            // }

                            if (fields[key].value instanceof Array
                                && fields[key].elements.type === "integer") {
                                fields[key].value = fields[key].value.map(function(value) {
                                    return parseInt(value);
                                });
                            }

                            if(!data.config) data.config = {};

                            if(fields[key].fields) {
                                fields[key].fields.forEach(field => {
                                    if(!data.config[path]) data.config[path] = {};
                                    const prop = Object.keys(field)[0];
                                    data.config[path][Object.keys(field)[0]] = _.get(field, `${prop}.value`);
                                })
                            }else{
                                if(fields[key].value !== ""
                                  && fields[key].value !== null
                                  && fields[key].value !== 'undefined'
                                  && fields[key].value !== undefined) {
                                    data.config[path] = fields[key].value;
                                }
                            }

                        }
                    });

                }

                var handlers  = {
                    common : function(data,success,error) {

                        PluginsService.add(data)
                            .then(function(resp){
                                success(resp);
                            }).catch(function(err){
                            error(err);
                        });
                    },
                    ssl : function(data, success,error,event) {
                        var files = [];

                        files.push(data['config.cert'])
                        files.push(data['config.key'])

                        Upload.upload({
                            url: 'kong/plugins',
                            arrayKey: '',
                            data: {
                                file: files,
                                'name' : data.name,
                                'config.only_https': data['config.only_https'],
                                'config.accept_http_if_already_terminated': data['config.accept_http_if_already_terminated']
                            }
                        }).then(function (resp) {
                            success(resp)
                        }, function (err) {
                            error(err)
                        }, function (evt) {
                            event(evt)
                        });
                    }
                }

                return {
                    addPlugin : function(data, success,error,event) {

                        if(handlers[data.name]) {
                            return handlers[data.name](data, success,error,event);
                        }else{
                            return handlers['common'](data, success,error,event);
                        }
                    },

                    createConfigProperties : function(pluginName,fields,prefix) {
                        var output = {}
                        createConfigProperties(pluginName,fields,prefix,output)
                        return output;
                    },

                    assignExtraProperties : function(_pluginName, options,fields,prefix) {
                        return  assignExtraProperties(_pluginName, options,fields,prefix)
                    },

                    /**
                     * Customize data fields for specified plugins if required by Konga's logic
                     * @param pluginName
                     * @param fields
                     */
                    customizeDataFieldsForPlugin : function(pluginName,fields) {

                        switch (pluginName) {
                            case 'ssl':
                                fields.cert.type = 'file'
                                fields.key.type = 'file'
                                break;
                        }
                    },

                    /**
                     * Mutate request data for specified plugins if required by Konga's logic
                     * @param request_data
                     * @param fields
                     */
                    applyMonkeyPatches : function(request_data,fields) {
                        if(request_data.name === 'response-ratelimiting'
                            && fields.limits.custom_fields) {
                            //console.log("fields.limits.custom_fields",fields.limits.custom_fields)
                            Object.keys(fields.limits.custom_fields)
                                .forEach(function(key){
                                    Object.keys(fields.limits.custom_fields[key])
                                        .forEach(function(cf_key){
                                            request_data['config.limits.' + key + '.' + cf_key] = fields.limits.custom_fields[key][cf_key].value

                                        });
                                });
                        }
                    }

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


<commit_before>const
    cheerio          = require('cheerio')
  , request          = require('request')
  , rootURL          = 'http://www.artsandscience.utoronto.ca'
  , winterCoursesURL = '/ofr/timetable/winter'
  , listingsURL      = '/sponsors.htm';

/*
----------------------------------------
Function: getProgramURL
----------------------------------------
  Returns a string of the course listing URL link.
----------------------------------------
Example Usage Calls
----------------------------------------
  getProgramURL('csc, function(err, courseURL) {
    console.log(courseURL);
  });

  'csc.html'

----------------------------------------
Number of Requests
----------------------------------------
  Min/Max: 1 (parses the listings page)
*/

exports.getProgramURL = function(course, callback) {

  request(rootURL + winterCoursesURL + listingsURL, function(error, response, body) {

    /* Scrape the course URLs from the main course listings page */
    if(!error && response.statusCode === 200) {

      var $            = cheerio.load(body)
        , webPageRegex = new RegExp(/[A-Za-z]\.html/);

      /* Grab the course links from the program bullet points */
      $('li a', '#content').each(function(foundLink) {
        var currentLink = $(this);
        /* Every course link has its course code */
        if (
          webPageRegex.test(currentLink.attr('href').toString()) &&
          currentLink.text().toString().indexOf('[' + course.toUpperCase() + ' courses') > -1)
          {
            callback(null, currentLink.attr('href').toString());
            return;
          };
      });
    };
  });
};

/*
----------------------------------------
Function: getProgramURLs
----------------------------------------
  Returns a json object, containing all Arts and Science department URLs.
----------------------------------------
Example Usage Calls
----------------------------------------
  getProgramURLs(function(urls) {
    console.log(urls);
  });

  [ { courseURL: 'asabs.html' },
  { courseURL: 'ana.html' },
  ...
  { courseURL: 'wdw.html' },
  { courseURL: 'wgsi.html' } ]

----------------------------------------
Number of Requests
----------------------------------------
  Min/Max: 1 (parses the listings page)

*/
exports.getProgramURLs = function(callback) {
  request(rootURL + winterCoursesURL + listingsURL, function(error, response, body) {

    // Scrape the course URLs from the main course listings page
    if(!error && response.statusCode === 200) {

      var $            = cheerio.load(body)
        , urls         = []
        , webPageRegex = new RegExp(/[A-Za-z]\.html/);

      // Grab the course links from the program bullet points
      $('li a', '#content').each(function(foundLink) {
        var currentLink = $(this).attr('href').toString();
        if (webPageRegex.test(currentLink)) {
          urls.push(currentLink);
        };
      });
    };
    callback(null, urls);
  });
};

/*
----------------------------------------
Function: getDepartment
----------------------------------------
  Returns a callback with an array of JSON objects,
  containing the parameter department data.
----------------------------------------
Example Usage Calls
----------------------------------------
  getDepartment('csc', function(err, department) {
    console.log(department);
  });

  { ['Computer Science'] }
----------------------------------------
Number of Requests
----------------------------------------
  Min/Max: 0 (makes no requests)

*/
exports.getDepartment = function(body, abbrev, callback) {
    var $             = cheerio.load(body)
      , departments   = []
      , webPageRegex  = new RegExp(/[A-Za-z]\.html/);

    $('li a', '#content').each(function(foundLink) {
      var linkText = $(this).text().toString()
        , linkAttr = $(this).attr('href').toString();

      /* Decide whether to retrieve all
      departments or just the abbrev department */
      var courseToGet = (abbrev === null)
        ? true
        : linkText.indexOf('[' + abbrev.toUpperCase() + ' courses') > -1;

      // If abbrev has a course in that department
      if (webPageRegex.test(linkAttr) && courseToGet) {
        // Push just the program name, not the extra info
        departments.push({
          "department": linkText.slice(0, linkText.indexOf('[')).trim()
        });
      };
    });
    callback(null, departments);
};

/*
----------------------------------------
Function: getCourseData
----------------------------------------
  Returns a callback with an array of JSON objects,
  containing the specified course data.
----------------------------------------
Example Usage Calls
----------------------------------------
  getDepartment('csc', function(err, courseData) {
    console.log(courseData);
  });
----------------------------------------
Number of Requests
----------------------------------------
  Min/Max: 0 (makes no requests)

*/
exports.getCourseData = function(body, getCancelledCourses, callback) {

  /* Load the new markup from this request. */
  var $                   = cheerio.load(body)
    , courseCodeRegex     = new RegExp(/[A-Za-z]{3}[0-9]{3}[A-Za-z]{1}[0-9]{1}/)
    , courseTutorialRegex = new RegExp(/[^L][0-9]{4}/)
    , courseSectionRegex  = new RegExp(/[L][0-9]{4}/)
    , courseTermRegex     = new RegExp(/[F|S|Y]/)
    , courseWaitListRegex = new RegExp(/[Y|N]/)
    , coursesJSON         = [];

  /* Get the course code from the page markup */
  $('tr').each(function(foundCourse) {
    var currentRow = $(this)
      , section      = currentRow.children().last()
      , cellCount    = 0;

    /* Find the course code starting from the end of the table */
    while(!courseSectionRegex.test(section.text().toString()) && cellCount < 9) {
      section = section.prev();
      cellCount++;
    };

    /* Once the lecture section is found, the other important course
    data is relative to its position. */
    courseWait      = section.next();
    courseName      = section.prev();
    courseTerm      = section.prev().prev();
    courseCode      = section.prev().prev().prev();
    courseProfessor = section.next().next().next().next();

    /* Determine whether or not to include
    cancelled courses in the callback JSON array */
    var acceptCancelledCourses = (getCancelledCourses === true)
      ? true
      : courseWait.text().toString().indexOf('Cancel') === -1;

    /* Make sure we have valid course data */
    if(courseSectionRegex.test(section.text().toString())  &&
       courseTermRegex.test(courseTerm.text().toString())  &&
       courseCodeRegex.test(courseCode.text().toString())  &&
       acceptCancelledCourses)
    {

      var courseProfessors = [];

      /* There may be multiple profs for one course
      section, if so, parse and append them */
      (courseProfessor.text().toString().indexOf('/') > -1)
        ? courseProfessors = courseProfessor.text().toString().split('/')
        : courseProfessors.push(courseProfessor.text().toString());

      coursesJSON.push({
        "courseName": courseName.text().toString(),
        "courseCode": courseCode.text().toString(),
        "courseTerm": courseTerm.text().toString(),
        "courseWait": courseWait.text().toString(),
        "courseProf": courseProfessors
      });
    };
  });
  callback(coursesJSON);
};
<commit_msg>Local variable scope.<commit_after>const
    cheerio          = require('cheerio')
  , request          = require('request')
  , rootURL          = 'http://www.artsandscience.utoronto.ca'
  , winterCoursesURL = '/ofr/timetable/winter'
  , listingsURL      = '/sponsors.htm';

/*
----------------------------------------
Function: getProgramURL
----------------------------------------
  Returns a string of the course listing URL link.
----------------------------------------
Example Usage Calls
----------------------------------------
  getProgramURL('csc, function(err, courseURL) {
    console.log(courseURL);
  });

  'csc.html'

----------------------------------------
Number of Requests
----------------------------------------
  Min/Max: 1 (parses the listings page)
*/

exports.getProgramURL = function(course, callback) {

  request(rootURL + winterCoursesURL + listingsURL, function(error, response, body) {

    /* Scrape the course URLs from the main course listings page */
    if(!error && response.statusCode === 200) {

      var $            = cheerio.load(body)
        , webPageRegex = new RegExp(/[A-Za-z]\.html/);

      /* Grab the course links from the program bullet points */
      $('li a', '#content').each(function(foundLink) {
        var currentLink = $(this);
        /* Every course link has its course code */
        if (
          webPageRegex.test(currentLink.attr('href').toString()) &&
          currentLink.text().toString().indexOf('[' + course.toUpperCase() + ' courses') > -1)
          {
            callback(null, currentLink.attr('href').toString());
            return;
          };
      });
    };
  });
};

/*
----------------------------------------
Function: getProgramURLs
----------------------------------------
  Returns a json object, containing all Arts and Science department URLs.
----------------------------------------
Example Usage Calls
----------------------------------------
  getProgramURLs(function(urls) {
    console.log(urls);
  });

  [ { courseURL: 'asabs.html' },
  { courseURL: 'ana.html' },
  ...
  { courseURL: 'wdw.html' },
  { courseURL: 'wgsi.html' } ]

----------------------------------------
Number of Requests
----------------------------------------
  Min/Max: 1 (parses the listings page)

*/
exports.getProgramURLs = function(callback) {
  request(rootURL + winterCoursesURL + listingsURL, function(error, response, body) {

    // Scrape the course URLs from the main course listings page
    if(!error && response.statusCode === 200) {

      var $            = cheerio.load(body)
        , urls         = []
        , webPageRegex = new RegExp(/[A-Za-z]\.html/);

      // Grab the course links from the program bullet points
      $('li a', '#content').each(function(foundLink) {
        var currentLink = $(this).attr('href').toString();
        if (webPageRegex.test(currentLink)) {
          urls.push(currentLink);
        };
      });
    };
    callback(null, urls);
  });
};

/*
----------------------------------------
Function: getDepartment
----------------------------------------
  Returns a callback with an array of JSON objects,
  containing the parameter department data.
----------------------------------------
Example Usage Calls
----------------------------------------
  getDepartment('csc', function(err, department) {
    console.log(department);
  });

  { ['Computer Science'] }
----------------------------------------
Number of Requests
----------------------------------------
  Min/Max: 0 (makes no requests)

*/
exports.getDepartment = function(body, abbrev, callback) {
    var $             = cheerio.load(body)
      , departments   = []
      , webPageRegex  = new RegExp(/[A-Za-z]\.html/);

    $('li a', '#content').each(function(foundLink) {
      var linkText = $(this).text().toString()
        , linkAttr = $(this).attr('href').toString();

      /* Decide whether to retrieve all
      departments or just the abbrev department */
      var courseToGet = (abbrev === null)
        ? true
        : linkText.indexOf('[' + abbrev.toUpperCase() + ' courses') > -1;

      // If abbrev has a course in that department
      if (webPageRegex.test(linkAttr) && courseToGet) {
        // Push just the program name, not the extra info
        departments.push({
          "department": linkText.slice(0, linkText.indexOf('[')).trim()
        });
      };
    });
    callback(null, departments);
};

/*
----------------------------------------
Function: getCourseData
----------------------------------------
  Returns a callback with an array of JSON objects,
  containing the specified course data.
----------------------------------------
Example Usage Calls
----------------------------------------
  getDepartment('csc', function(err, courseData) {
    console.log(courseData);
  });
----------------------------------------
Number of Requests
----------------------------------------
  Min/Max: 0 (makes no requests)

*/
exports.getCourseData = function(body, getCancelledCourses, callback) {

  /* Load the new markup from this request. */
  var $                   = cheerio.load(body)
    , courseCodeRegex     = new RegExp(/[A-Za-z]{3}[0-9]{3}[A-Za-z]{1}[0-9]{1}/)
    , courseTutorialRegex = new RegExp(/[^L][0-9]{4}/)
    , courseSectionRegex  = new RegExp(/[L][0-9]{4}/)
    , courseTermRegex     = new RegExp(/[F|S|Y]/)
    , courseWaitListRegex = new RegExp(/[Y|N]/)
    , coursesJSON         = [];

  /* Get the course code from the page markup */
  $('tr').each(function(foundCourse) {
    var currentRow = $(this)
      , section      = currentRow.children().last()
      , cellCount    = 0;

    /* Find the course code starting from the end of the table */
    while(!courseSectionRegex.test(section.text().toString()) && cellCount < 9) {
      section = section.prev();
      cellCount++;
    };

    /* Once the lecture section is found, the other important course
    data is relative to its position. */
    var courseWait      = section.next()
      , courseName      = section.prev()
      , courseTerm      = section.prev().prev()
      , courseCode      = section.prev().prev().prev()
      , courseProfessor = section.next().next().next().next()

    /* Determine whether or not to include
    cancelled courses in the callback JSON array */
    var acceptCancelledCourses = (getCancelledCourses === true)
      ? true
      : courseWait.text().toString().indexOf('Cancel') === -1;

    /* Make sure we have valid course data */
    if(courseSectionRegex.test(section.text().toString())  &&
       courseTermRegex.test(courseTerm.text().toString())  &&
       courseCodeRegex.test(courseCode.text().toString())  &&
       acceptCancelledCourses)
    {

      var courseProfessors = [];

      /* There may be multiple profs for one course
      section, if so, parse and append them */
      (courseProfessor.text().toString().indexOf('/') > -1)
        ? courseProfessors = courseProfessor.text().toString().split('/')
        : courseProfessors.push(courseProfessor.text().toString());

      coursesJSON.push({
        "courseName": courseName.text().toString(),
        "courseCode": courseCode.text().toString(),
        "courseTerm": courseTerm.text().toString(),
        "courseWait": courseWait.text().toString(),
        "courseProf": courseProfessors
      });
    };
  });
  callback(coursesJSON);
};
<|endoftext|>


<commit_before>// ==UserScript==
// @name        Bwin registration
// @namespace   Bwin registration
// @description Prefill registration form on for all bwin labels
// @include     *bwin*/*/registration*
// @include     *gamebookers.com/*/registration*
// @include     *giocodigitale.it/*/registration*
// @include     *partycasino.com/*/registration*
// @include     *sportingbet*/*/registration*
// @version     0.5.2
// @require     https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.js
// @require     https://raw.githubusercontent.com/drizet/PortalUserScripts/master/src/core/common.js
// @require     https://raw.githubusercontent.com/drizet/PortalUserScripts/master/src/core/random.js
// @require     https://raw.githubusercontent.com/blueimp/JavaScript-MD5/master/js/md5.min.js
// ==/UserScript==

$(function () {
    // Portal labels
    var BAW = "bwin.com";
    var BE = "bwin.be";
    var ES = "bwin.es";
    var SHDE = "sh.bwin.de";
    var FR = "bwin.fr";
    var IT = "bwin.it";
    var GD = "giocodigitale.it";
    var GB = "gamebookers.com";
    var GR = "bwin.gr";
	var SPB = "sportingbet"; // includes ro/com and other

    if ($("#registration-form").length) {
        SetupPersonalData();
        SetupAccountData();

        if (LabelIs(BE)) {
            SetupIdentificationData();
        }

        if (LabelIs(ES)) {
            SetupNieNifData();
        }

        if(LabelIs(IT) || LabelIs(GD)){
            SetupDocumentData();
        }

        SetupConfirmationData();

        // Allow submit disabled fields. Replace 'disabled' attr to 'points-events'
        $("input:disabled, select:disabled").removeAttr('disabled').css("pointer-events", "none").css("opacity", "0.4");
    }

    function SetupPersonalData() {
        $("#Input_NameData_FirstName").val(Random.getText(10));
        $("#Input_NameData_LastName").val(Random.getText(10));

        if(LabelIs(ES)){
            $("#Input_AddressData_AddressCountryCode").selectOptionByValue("ES");
        }
        else if(LabelIs(BAW)){
            $("#Input_AddressData_AddressCountryCode").selectOptionByValue("GB");
        }
        else if(LabelIs(IT)){
            $("#Input_AddressData_AddressCountryCode").selectOptionByValue("IT");
        }
        else if(LabelIs(GD)){
            $("#Input_AddressData_AddressCountryCode").selectOptionByValue("IT");
        }
        else{
          $("#Input_AddressData_AddressCountryCode").selectOptionByIndex(1);
        }

        if(LabelIs(SPB)){
            $("#Input_IdentificationData_DocumentNumber").val("1920101"+ Random.getNumbers(6));
        }

        $("#Input_AddressData_AddressState").selectOptionByIndex(1);
        $("#Input_AddressData_AddressCity").val(Random.getText(6));
        $("#Input_AddressData_AddressZip").val("2" + Random.getNumbers(4));
        $("#Input_AddressData_AddressLine1").val("address");
        $("#Input_AddressData_AddressLine2").val("address2");
        $("#Input_CurrencyData_CurrencyCode").selectOptionByValue("EUR");
        $("#Input_BirthData_DateOfBirth").setDate(1, 1, 1992);
        $("#Input_ContactData_EmailAddress").val(Random.getEmail(8, "yopmail.com"));
        $("#Input_ContactData_MobileCountryCode").selectOptionByValue("380")
        $("#Input_ContactData_MobileNumber").val(Random.getNumbers(7));

        if (LabelIs(ES)) {
            $("#Input_NameData_SecondLastName").val(Random.getText(10));
        }

        if (LabelIs(SHDE)) {
            $("#Input_AddressData_Nationality").selectOptionByIndex(1);
            $("#Input_BirthData_PlaceOfBirth").val(Random.getText(7));
        }

        if (LabelIs(FR) || LabelIs(IT) || LabelIs(GD)) {
            $("#Input_BirthData_BirthState").selectOptionByIndex(2, true);
            $("#Input_BirthData_BirthCity").selectOptionByIndex(1, true);
        }

        if(LabelIs(IT) || LabelIs(GD)){
             $("#Input_BirthData_FiscalCodeConfirmed").checkWhenEntered("#Input_BirthData_FiscalCode");
        }
    }

    function SetupAccountData() {
        if (LabelIs(ES)) {
            SetPassword("123123Qq")
        }
        else {
            SetPassword("123123qq")
        }
        $("#Input_LoginData_Username").val(Random.getUserName(4));

        $("#Input_SecurityData_SecurityQuestion").selectOptionByIndex(1);
    }

    function SetPassword(password) {
        $("#Input_LoginData_Password, #Input_LoginData_PasswordConfirmation, #Input_SecurityData_SecurityAnswer").val(password);
    }

    function SetupConfirmationData() {
        $("#Input_TermsAndConditions_TacAcceptance, #Input_BonusData_BonusTacAccepted, #Input_PrivacyPolicy_PrivacyPolicyAccepted").check();

        if(LabelIs(IT) || LabelIs(GD)){
            $("#Input_NewslettersSubscription_NewslettersSubscriptionAccepted, #Input_OtherNoticeSubscription_OtherNoticeSubscriptionsAccepted").check()
        }

        $("#Captcha_Input_Answer").val("+++");
    }

    function SetupIdentificationData() {
        var nrnDate = "920101";
        var nrnSerialNumber = Random.getNumbers(3);
        var nrnChecksum = 97 - (parseInt(nrnDate + nrnSerialNumber) % 97);

        $("#Input_IdentificationData_NRNDate").val(nrnDate);
        $("#Input_IdentificationData_NRNSerialNumber").val(nrnSerialNumber);
        $("#Input_IdentificationData_NRNChecksum").val(pad(nrnChecksum, 2));
        $("#Input_IdentificationData_Profession").selectOptionByIndex(1);
        $("#Input_IdentificationData_CityOfBirth").val(Random.getText(6));
    }

    function SetupNieNifData() {
        $("#Input_NieNif_TaxProvince").selectOptionByIndex(1);

        var dni = Random.getNumbers(8);
        var characters = "TRWAGMYFPDXBNJZSQVHLCKE";
        dni = dni + characters[parseInt(dni) % 23];
        $("#Input_NieNif_IdDocumentNumber").val(dni);
    }

    function SetupDocumentData(){
        $("#Input_IdentificationData_DocumentType").selectOptionByIndex(1);
        $("#Input_IdentificationData_DocumentNumber").val(Random.getText(6));
        $("#Input_IdentificationData_DocumentReleaseDate").setDate(1, 1, 1992);
        $("#Input_IdentificationData_DocumentReleasedBy").selectOptionByIndex(1);
        $("#Input_IdentificationData_DocumentReleaseLocation").val(Random.getText(6));
    }

    function pad(n, width, z) {
        z = z || '0';
        n = n + '';
        return n.length >= width ? n : new Array(width - n.length + 1).join(z) + n;
    }

    function LabelIs(host) {
        return document.location.href.indexOf(host) != -1;
    }
});<commit_msg>Added a new checkbox for bwin.gr<commit_after>// ==UserScript==
// @name        Bwin registration
// @namespace   Bwin registration
// @description Prefill registration form on for all bwin labels
// @include     *bwin*/*/registration*
// @include     *gamebookers.com/*/registration*
// @include     *giocodigitale.it/*/registration*
// @include     *partycasino.com/*/registration*
// @include     *sportingbet*/*/registration*
// @version     0.5.2
// @require     https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.js
// @require     https://raw.githubusercontent.com/drizet/PortalUserScripts/master/src/core/common.js
// @require     https://raw.githubusercontent.com/drizet/PortalUserScripts/master/src/core/random.js
// @require     https://raw.githubusercontent.com/blueimp/JavaScript-MD5/master/js/md5.min.js
// ==/UserScript==

$(function () {
    // Portal labels
    var BAW = "bwin.com";
    var BE = "bwin.be";
    var ES = "bwin.es";
    var SHDE = "sh.bwin.de";
    var FR = "bwin.fr";
    var IT = "bwin.it";
    var GD = "giocodigitale.it";
    var GB = "gamebookers.com";
    var GR = "bwin.gr";
	var SPB = "sportingbet"; // includes ro/com and other

    if ($("#registration-form").length) {
        SetupPersonalData();
        SetupAccountData();

        if (LabelIs(BE)) {
            SetupIdentificationData();
        }

        if (LabelIs(ES)) {
            SetupNieNifData();
        }

        if(LabelIs(IT) || LabelIs(GD)){
            SetupDocumentData();
        }

        SetupConfirmationData();

        // Allow submit disabled fields. Replace 'disabled' attr to 'points-events'
        $("input:disabled, select:disabled").removeAttr('disabled').css("pointer-events", "none").css("opacity", "0.4");
    }

    function SetupPersonalData() {
        $("#Input_NameData_FirstName").val(Random.getText(10));
        $("#Input_NameData_LastName").val(Random.getText(10));

        if(LabelIs(ES)){
            $("#Input_AddressData_AddressCountryCode").selectOptionByValue("ES");
        }
        else if(LabelIs(BAW)){
            $("#Input_AddressData_AddressCountryCode").selectOptionByValue("GB");
        }
        else if(LabelIs(IT)){
            $("#Input_AddressData_AddressCountryCode").selectOptionByValue("IT");
        }
        else if(LabelIs(GD)){
            $("#Input_AddressData_AddressCountryCode").selectOptionByValue("IT");
        }
        else{
          $("#Input_AddressData_AddressCountryCode").selectOptionByIndex(1);
        }

        if(LabelIs(SPB)){
            $("#Input_IdentificationData_DocumentNumber").val("1920101"+ Random.getNumbers(6));
        }

        $("#Input_AddressData_AddressState").selectOptionByIndex(1);
        $("#Input_AddressData_AddressCity").val(Random.getText(6));
        $("#Input_AddressData_AddressZip").val("2" + Random.getNumbers(4));
        $("#Input_AddressData_AddressLine1").val("address");
        $("#Input_AddressData_AddressLine2").val("address2");
        $("#Input_CurrencyData_CurrencyCode").selectOptionByValue("EUR");
        $("#Input_BirthData_DateOfBirth").setDate(1, 1, 1992);
        $("#Input_ContactData_EmailAddress").val(Random.getEmail(8, "yopmail.com"));
        $("#Input_ContactData_MobileCountryCode").selectOptionByValue("380")
        $("#Input_ContactData_MobileNumber").val(Random.getNumbers(7));

        if (LabelIs(ES)) {
            $("#Input_NameData_SecondLastName").val(Random.getText(10));
        }

        if (LabelIs(SHDE)) {
            $("#Input_AddressData_Nationality").selectOptionByIndex(1);
            $("#Input_BirthData_PlaceOfBirth").val(Random.getText(7));
        }

        if (LabelIs(FR) || LabelIs(IT) || LabelIs(GD)) {
            $("#Input_BirthData_BirthState").selectOptionByIndex(2, true);
            $("#Input_BirthData_BirthCity").selectOptionByIndex(1, true);
        }

        if(LabelIs(IT) || LabelIs(GD)){
             $("#Input_BirthData_FiscalCodeConfirmed").checkWhenEntered("#Input_BirthData_FiscalCode");
        }
    }

    function SetupAccountData() {
        if (LabelIs(ES)) {
            SetPassword("123123Qq")
        }
        else {
            SetPassword("123123qq")
        }
        $("#Input_LoginData_Username").val(Random.getUserName(4));

        $("#Input_SecurityData_SecurityQuestion").selectOptionByIndex(1);
    }

    function SetPassword(password) {
        $("#Input_LoginData_Password, #Input_LoginData_PasswordConfirmation, #Input_SecurityData_SecurityAnswer").val(password);
    }

    function SetupConfirmationData() {
        $("#Input_TermsAndConditions_TacAcceptance, #Input_BonusData_BonusTacAccepted, #Input_PrivacyPolicy_PrivacyPolicyAccepted").check();

		if(LabelIs(GR))
        {
            $("#Input_FundProtection_FundProtectionAcceptance").check();
        }

        if(LabelIs(IT) || LabelIs(GD)){
            $("#Input_NewslettersSubscription_NewslettersSubscriptionAccepted, #Input_OtherNoticeSubscription_OtherNoticeSubscriptionsAccepted").check()
        }

        $("#Captcha_Input_Answer").val("+++");
    }

    function SetupIdentificationData() {
        var nrnDate = "920101";
        var nrnSerialNumber = Random.getNumbers(3);
        var nrnChecksum = 97 - (parseInt(nrnDate + nrnSerialNumber) % 97);

        $("#Input_IdentificationData_NRNDate").val(nrnDate);
        $("#Input_IdentificationData_NRNSerialNumber").val(nrnSerialNumber);
        $("#Input_IdentificationData_NRNChecksum").val(pad(nrnChecksum, 2));
        $("#Input_IdentificationData_Profession").selectOptionByIndex(1);
        $("#Input_IdentificationData_CityOfBirth").val(Random.getText(6));
    }

    function SetupNieNifData() {
        $("#Input_NieNif_TaxProvince").selectOptionByIndex(1);

        var dni = Random.getNumbers(8);
        var characters = "TRWAGMYFPDXBNJZSQVHLCKE";
        dni = dni + characters[parseInt(dni) % 23];
        $("#Input_NieNif_IdDocumentNumber").val(dni);
    }

    function SetupDocumentData(){
        $("#Input_IdentificationData_DocumentType").selectOptionByIndex(1);
        $("#Input_IdentificationData_DocumentNumber").val(Random.getText(6));
        $("#Input_IdentificationData_DocumentReleaseDate").setDate(1, 1, 1992);
        $("#Input_IdentificationData_DocumentReleasedBy").selectOptionByIndex(1);
        $("#Input_IdentificationData_DocumentReleaseLocation").val(Random.getText(6));
    }

    function pad(n, width, z) {
        z = z || '0';
        n = n + '';
        return n.length >= width ? n : new Array(width - n.length + 1).join(z) + n;
    }

    function LabelIs(host) {
        return document.location.href.indexOf(host) != -1;
    }
});<|endoftext|>