<commit_before>let extend = require('node.extend');
let PersistentCollection = require('./persistent-collection');
let connectionManager = require('../pom/connection-mysql');
let dataTranslator = require('./mysql-translator');
let stamp = require('../model/stamp');
let catalogueNumberHelper = require('../model/catalogue-number-helper');
let ownership = require('../model/ownership');
let catalogueNumber = require('../model/catalogue-number');
let catalogue = require('../model/catalogue');
let country = require('../model/country');
let catalogues = require('./catalogues');
let _ = require('lodash');
let q = require('q');
let Logger = require('../util/logger');

let sqlTrace = Logger.getLogger("sql");

let stamps = extend(true, {}, new PersistentCollection(), function () {

    "use strict";

    function generateColumnExpression(fields, tableRef,distinct) {
        let s = "";
        _.each(fields, function (field, indx) {
            let c = tableRef + "." + field.column;
            if( distinct === true && field.column === 'ID' ) {
                c = "DISTINCT(" + c + ")";
            }
            s += c;
            if (indx < fields.length - 1) {
                s += ',';
            }
        });
        return s;
    }

    function populateKey(stamp, k) {
        if (!_.has(stamp, k)) {
            stamp[k] = [];
        }
    }

    function processRow(rows, row, fieldDef, key) {
        let s = _.findWhere(rows, { ID: row.STAMP_ID });
        if (!s) {
            sqlTrace.trace("No stamp found for " + row.STAMP_ID);
            return;
        }
        s[key].push(row);
    }

    function getFromTableForChildren (fieldDefinition) {
        let tables = stamp.getTableName() + ' AS ' + stamp.getAlias() + ' JOIN ' + fieldDefinition.getTableName() + ' AS ' + fieldDefinition.getAlias();
        tables += ' ON ' + stamp.getAlias() + '.ID=' + fieldDefinition.getAlias() + '.STAMP_ID';
        return tables;
    }

    function generateChildSelection(supportedFields, fieldDefinition, inValues) {
        let select = 'SELECT ' + generateColumnExpression(supportedFields, fieldDefinition.getAlias());
        select += ' FROM ' + getFromTableForChildren(fieldDefinition) + ' WHERE ' + fieldDefinition.getAlias() + '.STAMP_ID IN ' + inValues;
        return select;
    }

    let cachePolicy = true;

    const getCatalogues = () => {
        return catalogues.find();
    }

    return {

        setCachePolicy: val => {
            cachePolicy = val;
        },

        preCommitUpdate: async function (connection, merged, storedObj) {
            let catalogues = (await getCatalogues()).rows;
            return new Promise((resolve, reject) => {
                let that = this;
                let updateList = [], createList = [];
                let parseChildren = function (childName, fieldDef) {
                    if (merged[childName] && _.isArray(merged[childName])) {
                        _.each(merged[childName], function (obj) {
                            if (obj.ID) {
                                let current = _.findWhere(storedObj[childName], {ID: obj.ID});
                                if (childName === 'CATALOGUENUMBER') {
                                    obj.NUMBERSORT = catalogueNumberHelper.serialize(obj, catalogues);
                                }
                                let sql = dataTranslator.generateUpdateByFields(fieldDef, obj, current, true);
                                if (sql !== null) {
                                    updateList.push(sql);
                                }
                            } else {
                                obj.STAMP_ID = merged.ID;
                                if (childName === 'CATALOGUENUMBER') {
                                    obj.NUMBERSORT = catalogueNumberHelper.serialize(obj, cats);
                                }
                                createList.push({fieldDefinition: fieldDef, object: obj});
                            }
                        });
                    }
                };
                parseChildren("CATALOGUENUMBER", catalogueNumber);
                parseChildren("OWNERSHIP", ownership);

                let total = updateList.length + createList.length;
                let count = 0;
                let resolveWhenFinished = function () {
                    if (count === total) {
                        resolve({
                            modified: total > 0
                        });
                    }
                };
                resolveWhenFinished();
                _.each(updateList, function (sql) {
                    sqlTrace.debug(sql);
                    connection.query(sql, function (err, data) {
                        if (err !== null) {
                            reject(dataTranslator.getErrorMessage(err));
                        } else {
                            count++;
                            resolveWhenFinished();
                        }

                    });
                });
                _.each(createList, function (obj) {
                    let creating = obj;
                    PersistentCollection.getNextSequence(creating.fieldDefinition, function (err, id) {
                        if (err !== null) {
                            reject(dataTranslator.getErrorMessage(err));
                        } else {
                            creating.object.ID = id;
                            let c_sql = dataTranslator.generateInsertByFields(creating.fieldDefinition, creating.object);
                            sqlTrace.debug(c_sql);
                            connection.query(c_sql, function (err, data) {
                                if (err !== null) {
                                    reject(dataTranslator.getErrorMessage(err));
                                } else {
                                    count++;
                                    resolveWhenFinished();
                                }
                            });
                            PersistentCollection.updateSequence(id, creating.fieldDefinition);
                        }
                    });
                });
            });
        },

        preCreate: async provided => {
            let catResult = await getCatalogues();
            let cats = catResult.rows;
            if(provided.CATALOGUENUMBER) {
                _.each(provided.CATALOGUENUMBER, cn => {
                    cn.NUMBERSORT = catalogueNumberHelper.serialize(cn, cats);
                });
            }
        },

        postCreate: function (connection, obj) {
            let defer = q.defer();
            let total = ((obj.CATALOGUENUMBER) ? obj.CATALOGUENUMBER.length : 0) + ((obj.OWNERSHIP) ? obj.OWNERSHIP.length : 0);
            let created = 0;
            let that = this;
            if (obj.CATALOGUENUMBER && _.isArray(obj.CATALOGUENUMBER)) {
                _.each(obj.CATALOGUENUMBER, function (catNum) {
                    catNum.STAMP_ID = obj.ID;
                    that.generateId(catalogueNumber, catNum).then(function (id) {
                        catNum.ID = id;
                        let sql = dataTranslator. generateInsertByFields(catalogueNumber, catNum);
                        sqlTrace.debug(sql);
                        connection.query(sql, function (err, result) {
                            if (err) {
                                defer.reject(dataTranslator.getErrorMessage(err));
                            } else {
                                created++;
                                if (created === total) {
                                    defer.resolve(obj);
                                }
                            }
                        });
                    }, function (err) {
                        defer.reject(dataTranslator.getErrorMessage(err));
                    });
                });
            }
            if (obj.OWNERSHIP && _.isArray(obj.OWNERSHIP)) {
                _.each(obj.OWNERSHIP, function (owner) {
                    owner.STAMP_ID = obj.ID;
                    that.generateId(ownership, owner).then(function (id) {
                        owner.ID = id;
                        let sql = dataTranslator. generateInsertByFields(ownership, owner);
                        sqlTrace.debug(sql);
                        connection.query(sql, function (err, result) {
                            if (err) {
                                defer.reject(dataTranslator.getErrorMessage(err));
                            } else {
                                created++;
                                if (created === total) {
                                    defer.resolve(obj);
                                }
                            }

                        });
                    });
                }, function (err) {
                    defer.reject(dataTranslator.getErrorMessage(err));
                });
            }
            return defer.promise;
        },

        getFromTables: function (params) {
            let tables = stamp.getTableName() + ' AS ' + stamp.getAlias() + ' JOIN ' + catalogueNumber.getTableName() + ' AS ' + catalogueNumber.getAlias();
            tables += ' ON ' + stamp.getAlias() + '.ID=' + catalogueNumber.getAlias() + '.STAMP_ID ';
            tables += 'LEFT JOIN ' + ownership.getTableName() + ' AS ' + ownership.getAlias() + ' ON ' + stamp.getAlias() + '.ID = ' + ownership.getAlias() + '.STAMP_ID';
            if( params.$orderby ) {
                let orderby = params.$orderby;
                /*if( orderby.indexOf('number') > -1) {
                    tables += ' LEFT JOIN ' + catalogue.getTableName() + ' AS ' + catalogue.getAlias() + ' ON ' + catalogueNumber.getAlias() + '.CATALOGUE_REF=' + catalogue.getAlias() + '.ID';
                } else*/ if( orderby.indexOf('countryRef') > -1) {
                    tables += ' LEFT JOIN ' + country.getTableName() + ' AS ' + country.getAlias() + ' ON ' + stamp.getAlias() + '.COUNTRY_ID=' + country.getAlias() + '.ID';
                }
            }
            return tables;
        },

        getWhereClause: function (params) {
            let clause = (params && params.$filter) ? dataTranslator.toWhereClause(params.$filter, [stamp, catalogueNumber, ownership]) : '';
            if( clause.length > 0 ) {
                clause += ' AND ' + catalogueNumber.getAlias() + '.ACTIVE=1';
            }
            return clause;
        },

        find: function (params) {
            let defer = q.defer();
            let that = this;

            let rejectFn = function (field) {
                return (field.internal && field.internal === true && field.required !== true || field.model);
            };
            let stampDef = _.reject(stamp.getFieldDefinitions(), rejectFn);
            let catDef = _.reject(catalogueNumber.getFieldDefinitions(), rejectFn);
            let ownerDef = _.reject(ownership.getFieldDefinitions(), rejectFn);

            let select = 'SELECT SQL_CALC_FOUND_ROWS ' + generateColumnExpression(stampDef, stamp.getAlias(),true) + ' FROM ' + this.getFromTables(params);
            let whereClause = this.getWhereClause(params);
            let orderby = this.getOrderByClause(params, [stamp, ownership, catalogueNumber]);
            select += ((whereClause.length > 0) ? (' WHERE ' + whereClause) : '') + ' ' + orderby + ' LIMIT ' + params.$offset + ',' + params.$limit;
            sqlTrace.debug(select);
            let t = (new Date()).getTime();
            connectionManager.getConnection().then(function (connection) {
                let query = connection.query(select, function (err, stamps) {
                    if (err) {
                        connection.release();
                        defer.reject(dataTranslator.getErrorMessage(err));
                    } else {
                        connection.query("SELECT FOUND_ROWS() AS ROWCOUNT", function (err, countData) {
                            if (err) {
                                connection.release();
                                defer.reject(dataTranslator.getErrorMessage(err));
                            } else {
                                let result = {
                                    rows: stamps,
                                    total: countData[0].ROWCOUNT
                                };
                                if (result.total === 0) {
                                    connection.release();
                                    defer.resolve(result);
                                } else {
                                    let ids = [];
                                    _.each(result.rows, function(row) {
                                        populateKey(row,'CATALOGUENUMBER');
                                        populateKey(row,'OWNERSHIP');
                                        ids.push(row.ID);
                                    });
                                    let inValues = dataTranslator.generateInValueStatement(ids);
                                    let queries = [
                                        {
                                            sql: generateChildSelection(catDef, catalogueNumber, inValues),
                                            fieldDefinition: catalogueNumber,
                                            collectionKey: 'CATALOGUENUMBER'
                                        },
                                        {
                                            sql: generateChildSelection(ownerDef, ownership, inValues),
                                            fieldDefinition: ownership,
                                            collectionKey: 'OWNERSHIP'
                                        }
                                    ];
                                    let completed = 0;
                                    let toExecute = queries.length;
                                    _.each(queries, function (query) {
                                        sqlTrace.debug(query.sql);
                                        let _query = connection.query(query.sql);
                                        _query.on('result', function (row) {
                                            processRow(result.rows, row, query.fieldDefinition, query.collectionKey);
                                        }).on('end', function () {
                                            completed++;
                                            if (completed === toExecute) {
                                                connection.release();
                                                sqlTrace.info("Time to query and process rows: " + (new Date().getTime() - t) + "ms");
                                                defer.resolve(result);
                                            }
                                        }).on('error', function (err) {
                                            connection.release();
                                            defer.reject(dataTranslator.getErrorMessage(err));
                                        });
                                    });
                                }
                            }
                        });
                    }
                });
            }, function (err) {
                defer.reject(dataTranslator.getErrorMessage(err));
            });
            return defer.promise;
        },
        collectionName: 'stamps',
        fieldDefinition: stamp
    };
}());

module.exports = stamps;
<commit_msg>Small fix on saving secondary catalogue numbers<commit_after>let extend = require('node.extend');
let PersistentCollection = require('./persistent-collection');
let connectionManager = require('../pom/connection-mysql');
let dataTranslator = require('./mysql-translator');
let stamp = require('../model/stamp');
let catalogueNumberHelper = require('../model/catalogue-number-helper');
let ownership = require('../model/ownership');
let catalogueNumber = require('../model/catalogue-number');
let catalogue = require('../model/catalogue');
let country = require('../model/country');
let catalogues = require('./catalogues');
let _ = require('lodash');
let q = require('q');
let Logger = require('../util/logger');

let sqlTrace = Logger.getLogger("sql");

let stamps = extend(true, {}, new PersistentCollection(), function () {

    "use strict";

    function generateColumnExpression(fields, tableRef,distinct) {
        let s = "";
        _.each(fields, function (field, indx) {
            let c = tableRef + "." + field.column;
            if( distinct === true && field.column === 'ID' ) {
                c = "DISTINCT(" + c + ")";
            }
            s += c;
            if (indx < fields.length - 1) {
                s += ',';
            }
        });
        return s;
    }

    function populateKey(stamp, k) {
        if (!_.has(stamp, k)) {
            stamp[k] = [];
        }
    }

    function processRow(rows, row, fieldDef, key) {
        let s = _.findWhere(rows, { ID: row.STAMP_ID });
        if (!s) {
            sqlTrace.trace("No stamp found for " + row.STAMP_ID);
            return;
        }
        s[key].push(row);
    }

    function getFromTableForChildren (fieldDefinition) {
        let tables = stamp.getTableName() + ' AS ' + stamp.getAlias() + ' JOIN ' + fieldDefinition.getTableName() + ' AS ' + fieldDefinition.getAlias();
        tables += ' ON ' + stamp.getAlias() + '.ID=' + fieldDefinition.getAlias() + '.STAMP_ID';
        return tables;
    }

    function generateChildSelection(supportedFields, fieldDefinition, inValues) {
        let select = 'SELECT ' + generateColumnExpression(supportedFields, fieldDefinition.getAlias());
        select += ' FROM ' + getFromTableForChildren(fieldDefinition) + ' WHERE ' + fieldDefinition.getAlias() + '.STAMP_ID IN ' + inValues;
        return select;
    }

    let cachePolicy = true;

    const getCatalogues = () => {
        return catalogues.find();
    }

    return {

        setCachePolicy: val => {
            cachePolicy = val;
        },

        preCommitUpdate: async function (connection, merged, storedObj) {
            let catalogues = (await getCatalogues()).rows;
            return new Promise((resolve, reject) => {
                let that = this;
                let updateList = [], createList = [];
                let parseChildren = function (childName, fieldDef) {
                    if (merged[childName] && _.isArray(merged[childName])) {
                        _.each(merged[childName], function (obj) {
                            if (obj.ID) {
                                let current = _.findWhere(storedObj[childName], {ID: obj.ID});
                                if (childName === 'CATALOGUENUMBER') {
                                    obj.NUMBERSORT = catalogueNumberHelper.serialize(obj, catalogues);
                                }
                                let sql = dataTranslator.generateUpdateByFields(fieldDef, obj, current, true);
                                if (sql !== null) {
                                    updateList.push(sql);
                                }
                            } else {
                                obj.STAMP_ID = merged.ID;
                                if (childName === 'CATALOGUENUMBER') {
                                    obj.NUMBERSORT = catalogueNumberHelper.serialize(obj, catalogues);
                                }
                                createList.push({fieldDefinition: fieldDef, object: obj});
                            }
                        });
                    }
                };
                parseChildren("CATALOGUENUMBER", catalogueNumber);
                parseChildren("OWNERSHIP", ownership);

                let total = updateList.length + createList.length;
                let count = 0;
                let resolveWhenFinished = function () {
                    if (count === total) {
                        resolve({
                            modified: total > 0
                        });
                    }
                };
                resolveWhenFinished();
                _.each(updateList, function (sql) {
                    sqlTrace.debug(sql);
                    connection.query(sql, function (err, data) {
                        if (err !== null) {
                            reject(dataTranslator.getErrorMessage(err));
                        } else {
                            count++;
                            resolveWhenFinished();
                        }

                    });
                });
                _.each(createList, function (obj) {
                    let creating = obj;
                    PersistentCollection.getNextSequence(creating.fieldDefinition, function (err, id) {
                        if (err !== null) {
                            reject(dataTranslator.getErrorMessage(err));
                        } else {
                            creating.object.ID = id;
                            let c_sql = dataTranslator.generateInsertByFields(creating.fieldDefinition, creating.object);
                            sqlTrace.debug(c_sql);
                            connection.query(c_sql, function (err, data) {
                                if (err !== null) {
                                    reject(dataTranslator.getErrorMessage(err));
                                } else {
                                    count++;
                                    resolveWhenFinished();
                                }
                            });
                            PersistentCollection.updateSequence(id, creating.fieldDefinition);
                        }
                    });
                });
            });
        },

        preCreate: async provided => {
            let catResult = await getCatalogues();
            let cats = catResult.rows;
            if(provided.CATALOGUENUMBER) {
                _.each(provided.CATALOGUENUMBER, cn => {
                    cn.NUMBERSORT = catalogueNumberHelper.serialize(cn, cats);
                });
            }
        },

        postCreate: function (connection, obj) {
            let defer = q.defer();
            let total = ((obj.CATALOGUENUMBER) ? obj.CATALOGUENUMBER.length : 0) + ((obj.OWNERSHIP) ? obj.OWNERSHIP.length : 0);
            let created = 0;
            let that = this;
            if (obj.CATALOGUENUMBER && _.isArray(obj.CATALOGUENUMBER)) {
                _.each(obj.CATALOGUENUMBER, function (catNum) {
                    catNum.STAMP_ID = obj.ID;
                    that.generateId(catalogueNumber, catNum).then(function (id) {
                        catNum.ID = id;
                        let sql = dataTranslator. generateInsertByFields(catalogueNumber, catNum);
                        sqlTrace.debug(sql);
                        connection.query(sql, function (err, result) {
                            if (err) {
                                defer.reject(dataTranslator.getErrorMessage(err));
                            } else {
                                created++;
                                if (created === total) {
                                    defer.resolve(obj);
                                }
                            }
                        });
                    }, function (err) {
                        defer.reject(dataTranslator.getErrorMessage(err));
                    });
                });
            }
            if (obj.OWNERSHIP && _.isArray(obj.OWNERSHIP)) {
                _.each(obj.OWNERSHIP, function (owner) {
                    owner.STAMP_ID = obj.ID;
                    that.generateId(ownership, owner).then(function (id) {
                        owner.ID = id;
                        let sql = dataTranslator. generateInsertByFields(ownership, owner);
                        sqlTrace.debug(sql);
                        connection.query(sql, function (err, result) {
                            if (err) {
                                defer.reject(dataTranslator.getErrorMessage(err));
                            } else {
                                created++;
                                if (created === total) {
                                    defer.resolve(obj);
                                }
                            }

                        });
                    });
                }, function (err) {
                    defer.reject(dataTranslator.getErrorMessage(err));
                });
            }
            return defer.promise;
        },

        getFromTables: function (params) {
            let tables = stamp.getTableName() + ' AS ' + stamp.getAlias() + ' JOIN ' + catalogueNumber.getTableName() + ' AS ' + catalogueNumber.getAlias();
            tables += ' ON ' + stamp.getAlias() + '.ID=' + catalogueNumber.getAlias() + '.STAMP_ID ';
            tables += 'LEFT JOIN ' + ownership.getTableName() + ' AS ' + ownership.getAlias() + ' ON ' + stamp.getAlias() + '.ID = ' + ownership.getAlias() + '.STAMP_ID';
            if( params.$orderby ) {
                let orderby = params.$orderby;
                /*if( orderby.indexOf('number') > -1) {
                    tables += ' LEFT JOIN ' + catalogue.getTableName() + ' AS ' + catalogue.getAlias() + ' ON ' + catalogueNumber.getAlias() + '.CATALOGUE_REF=' + catalogue.getAlias() + '.ID';
                } else*/ if( orderby.indexOf('countryRef') > -1) {
                    tables += ' LEFT JOIN ' + country.getTableName() + ' AS ' + country.getAlias() + ' ON ' + stamp.getAlias() + '.COUNTRY_ID=' + country.getAlias() + '.ID';
                }
            }
            return tables;
        },

        getWhereClause: function (params) {
            let clause = (params && params.$filter) ? dataTranslator.toWhereClause(params.$filter, [stamp, catalogueNumber, ownership]) : '';
            if( clause.length > 0 ) {
                clause += ' AND ' + catalogueNumber.getAlias() + '.ACTIVE=1';
            }
            return clause;
        },

        find: function (params) {
            let defer = q.defer();
            let that = this;

            let rejectFn = function (field) {
                return (field.internal && field.internal === true && field.required !== true || field.model);
            };
            let stampDef = _.reject(stamp.getFieldDefinitions(), rejectFn);
            let catDef = _.reject(catalogueNumber.getFieldDefinitions(), rejectFn);
            let ownerDef = _.reject(ownership.getFieldDefinitions(), rejectFn);

            let select = 'SELECT SQL_CALC_FOUND_ROWS ' + generateColumnExpression(stampDef, stamp.getAlias(),true) + ' FROM ' + this.getFromTables(params);
            let whereClause = this.getWhereClause(params);
            let orderby = this.getOrderByClause(params, [stamp, ownership, catalogueNumber]);
            select += ((whereClause.length > 0) ? (' WHERE ' + whereClause) : '') + ' ' + orderby + ' LIMIT ' + params.$offset + ',' + params.$limit;
            sqlTrace.debug(select);
            let t = (new Date()).getTime();
            connectionManager.getConnection().then(function (connection) {
                let query = connection.query(select, function (err, stamps) {
                    if (err) {
                        connection.release();
                        defer.reject(dataTranslator.getErrorMessage(err));
                    } else {
                        connection.query("SELECT FOUND_ROWS() AS ROWCOUNT", function (err, countData) {
                            if (err) {
                                connection.release();
                                defer.reject(dataTranslator.getErrorMessage(err));
                            } else {
                                let result = {
                                    rows: stamps,
                                    total: countData[0].ROWCOUNT
                                };
                                if (result.total === 0) {
                                    connection.release();
                                    defer.resolve(result);
                                } else {
                                    let ids = [];
                                    _.each(result.rows, function(row) {
                                        populateKey(row,'CATALOGUENUMBER');
                                        populateKey(row,'OWNERSHIP');
                                        ids.push(row.ID);
                                    });
                                    let inValues = dataTranslator.generateInValueStatement(ids);
                                    let queries = [
                                        {
                                            sql: generateChildSelection(catDef, catalogueNumber, inValues),
                                            fieldDefinition: catalogueNumber,
                                            collectionKey: 'CATALOGUENUMBER'
                                        },
                                        {
                                            sql: generateChildSelection(ownerDef, ownership, inValues),
                                            fieldDefinition: ownership,
                                            collectionKey: 'OWNERSHIP'
                                        }
                                    ];
                                    let completed = 0;
                                    let toExecute = queries.length;
                                    _.each(queries, function (query) {
                                        sqlTrace.debug(query.sql);
                                        let _query = connection.query(query.sql);
                                        _query.on('result', function (row) {
                                            processRow(result.rows, row, query.fieldDefinition, query.collectionKey);
                                        }).on('end', function () {
                                            completed++;
                                            if (completed === toExecute) {
                                                connection.release();
                                                sqlTrace.info("Time to query and process rows: " + (new Date().getTime() - t) + "ms");
                                                defer.resolve(result);
                                            }
                                        }).on('error', function (err) {
                                            connection.release();
                                            defer.reject(dataTranslator.getErrorMessage(err));
                                        });
                                    });
                                }
                            }
                        });
                    }
                });
            }, function (err) {
                defer.reject(dataTranslator.getErrorMessage(err));
            });
            return defer.promise;
        },
        collectionName: 'stamps',
        fieldDefinition: stamp
    };
}());

module.exports = stamps;
<|endoftext|>


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

  // Set some default values
  var currentUploads = 0;

  // Initialize autocomplete
  $('.autocomplete.speaker')
    .autocomplete({
      source: [{
        url: 'http://localhost:3001/user?find=%QUERY%',
        type:'remote'
      }],
      limit: 5,
      minLength: 1,
      titleKey: 'displayname',
      valueKey: 'id',
      getTitle: function(speaker) {
        return speaker.firstname + ' ' + speaker.name;
      },
      getValue: function(speaker) {
        return speaker.firstname + ' ' + speaker.name;
      }
    })
    .on('selected.xdsoft', function(e, speaker) {
      // Set ID in hidden field when suggestion was selected
      var target = $(this).attr('data-hidden-field-id');
      if (target != undefined) {
        $('#' + target).val(speaker.id);
      }
    });

  // Initialize datepicker
  $('.datepicker').datepicker({
    format: 'dd.mm.yyyy',
    weekStart: 1
  });
  $('[data-datepicker-id]').click(function() {
    var id= $(this).attr('data-datepicker-id');
    $('#'+id).datepicker('show');
  });

  // Disable dropzone auto discover for all elements:
  Dropzone.autoDiscover = false;

  $(".dropzone").each(function() {
    // Global dropzone configuration
    var config = {
      method: 'put',
      maxFiles: 1,
      createImageThumbnails: false,
      previewTemplate: $('#preview-template').html(),
      targetId: $(this).attr('data-id-target'),
      sending: function(file) {
        currentUploads++;
      },
      complete: function(file) {
        currentUploads--;
      },
      success: function(file, response) {
        // Set returned ID into hidden field
        $('input[name=' + this.options.targetId + ']').val(response.id);
      },
      error: function(file, message) {
        alert(message);
        this.removeFile(file);
      },
      canceled: function(file) {
        this.removeFile(file);
      }
    };

    // Individual dropzone configuration
    switch ($(this).attr('id')) {
      case 'sessionSlides':
        config.acceptedFiles = 'application/pdf,application/vnd.ms-powerpoint,application/vnd.openxmlformats-officedocument.presentationml.presentation';
        break;
      case 'sessionScreenshot':
        config.acceptedFiles = 'image/*';
        break;
      case 'sessionVideo':
        config.acceptedFiles = 'video/*';
        break;
    }

    // Initialize  dropzone
    $(this).dropzone(config);
  });

  // Watch save button
  $('.save-session').click(function() {
    // Cancel submit when at least one upload is still in progress
    if (currentUploads > 0) {
      alert(currentUploads + ' upload(s) in progress. Please wait.');
      return;
    }

    // TODO: check form data

  });

});
<commit_msg>Fix endpoint<commit_after>$(document).ready(function() {

  // Set some default values
  var currentUploads = 0;

  // Initialize autocomplete
  $('.autocomplete.speaker')
    .autocomplete({
      source: [{
        url: '/event/api/user?find=%QUERY%',
        type:'remote'
      }],
      limit: 5,
      minLength: 1,
      titleKey: 'displayname',
      valueKey: 'id',
      getTitle: function(speaker) {
        return speaker.firstname + ' ' + speaker.name;
      },
      getValue: function(speaker) {
        return speaker.firstname + ' ' + speaker.name;
      }
    })
    .on('selected.xdsoft', function(e, speaker) {
      // Set ID in hidden field when suggestion was selected
      var target = $(this).attr('data-hidden-field-id');
      if (target != undefined) {
        $('#' + target).val(speaker.id);
      }
    });

  // Initialize datepicker
  $('.datepicker').datepicker({
    format: 'dd.mm.yyyy',
    weekStart: 1
  });
  $('[data-datepicker-id]').click(function() {
    var id= $(this).attr('data-datepicker-id');
    $('#'+id).datepicker('show');
  });

  // Disable dropzone auto discover for all elements:
  Dropzone.autoDiscover = false;

  $(".dropzone").each(function() {
    // Global dropzone configuration
    var config = {
      method: 'put',
      maxFiles: 1,
      createImageThumbnails: false,
      previewTemplate: $('#preview-template').html(),
      targetId: $(this).attr('data-id-target'),
      sending: function(file) {
        currentUploads++;
      },
      complete: function(file) {
        currentUploads--;
      },
      success: function(file, response) {
        // Set returned ID into hidden field
        $('input[name=' + this.options.targetId + ']').val(response.id);
      },
      error: function(file, message) {
        alert(message);
        this.removeFile(file);
      },
      canceled: function(file) {
        this.removeFile(file);
      }
    };

    // Individual dropzone configuration
    switch ($(this).attr('id')) {
      case 'sessionSlides':
        config.acceptedFiles = 'application/pdf,application/vnd.ms-powerpoint,application/vnd.openxmlformats-officedocument.presentationml.presentation';
        break;
      case 'sessionScreenshot':
        config.acceptedFiles = 'image/*';
        break;
      case 'sessionVideo':
        config.acceptedFiles = 'video/*';
        break;
    }

    // Initialize  dropzone
    $(this).dropzone(config);
  });

  // Watch save button
  $('.save-session').click(function() {
    // Cancel submit when at least one upload is still in progress
    if (currentUploads > 0) {
      alert(currentUploads + ' upload(s) in progress. Please wait.');
      return;
    }

    // TODO: check form data

  });

});
<|endoftext|>


<commit_before>(function (factory) {
  /* global define */
  if (typeof define === 'function' && define.amd) {
    // AMD. Register as an anonymous module.
    define(['jquery'], factory);
  } else if (typeof module === 'object' && module.exports) {
    // Node/CommonJS
    module.exports = factory(require('jquery'));
  } else {
    // Browser globals
    factory(window.jQuery);
  }
}(function ($) {
  // Extends lang for print plugin.
  $.each({
    'en-US': {
      print: {
        print: 'Print'
      }
    },
    'ko-KR': {
      print: {
        print: '인쇄'
      }
    }
  }, function (locale, strings) { $.extend($.summernote.lang[locale], strings); });

  // Extends plugins for print plugin.
  $.extend($.summernote.plugins, {
    /**
     * @param {Object} context - context object has status of editor.
     */
    'print': function (context) {
      var self = this;

      // ui has renders to build ui elements.
      //  - you can create a button with `ui.button`
      var ui = $.summernote.ui;
      var $editor = context.layoutInfo.editor;
      var options = context.options;
      var lang = options.langInfo;

      // add print button
      context.memo('button.print', function () {
        // create button
        var button = ui.button({
          contents: '' + lang.print.print,
          tooltip: lang.print.print,
          click: function () {
            self.$printframe.contents().find('body').html(context.invoke('code'));
            window.frames.summernotePrintFrame.window.focus();
            window.frames.summernotePrintFrame.window.print();
          }
        });
        // create jQuery object from button instance.
        var $print = button.render();
        return $print;
      });

      this.initialize = function () {
        var $container = options.dialogsInBody ? $(document.body) : $editor;

        this.$printframe = $(
          '' +
          '');
        this.$printframe.appendTo($container);

        var $head = this.$printframe.contents().find('head');
        if (options.print && options.print.stylesheetUrl) {
          // Use dedicated styles
          var css = document.createElement('link');
          css.href = options.print.stylesheetUrl;
          css.rel = 'stylesheet';
          css.type = 'text/css';
          $head.append(css);
        } else {
          // Inherit styles from document
          $('style, link[rel=stylesheet]', document).each(function () {
            $head.append($(this).clone());
          });
        }
      };

      this.destroy = function () {
        this.$printframe.remove();
        this.$printframe = null;
      };
    }
  });
}));
<commit_msg>Using deep extend for locales<commit_after>(function (factory) {
  /* global define */
  if (typeof define === 'function' && define.amd) {
    // AMD. Register as an anonymous module.
    define(['jquery'], factory);
  } else if (typeof module === 'object' && module.exports) {
    // Node/CommonJS
    module.exports = factory(require('jquery'));
  } else {
    // Browser globals
    factory(window.jQuery);
  }
}(function ($) {
  // Extends lang for print plugin.
  $.extend(true, $.summernote.lang, {
    'en-US': {
      print: {
        print: 'Print'
      }
    },
    'ko-KR': {
      print: {
        print: '인쇄'
      }
    }
  });

  // Extends plugins for print plugin.
  $.extend($.summernote.plugins, {
    /**
     * @param {Object} context - context object has status of editor.
     */
    'print': function (context) {
      var self = this;

      // ui has renders to build ui elements.
      //  - you can create a button with `ui.button`
      var ui = $.summernote.ui;
      var $editor = context.layoutInfo.editor;
      var options = context.options;
      var lang = options.langInfo;

      // add print button
      context.memo('button.print', function () {
        // create button
        var button = ui.button({
          contents: '' + lang.print.print,
          tooltip: lang.print.print,
          click: function () {
            self.$printframe.contents().find('body').html(context.invoke('code'));
            window.frames.summernotePrintFrame.window.focus();
            window.frames.summernotePrintFrame.window.print();
          }
        });
        // create jQuery object from button instance.
        var $print = button.render();
        return $print;
      });

      this.initialize = function () {
        var $container = options.dialogsInBody ? $(document.body) : $editor;

        this.$printframe = $(
          '' +
          '');
        this.$printframe.appendTo($container);

        var $head = this.$printframe.contents().find('head');
        if (options.print && options.print.stylesheetUrl) {
          // Use dedicated styles
          var css = document.createElement('link');
          css.href = options.print.stylesheetUrl;
          css.rel = 'stylesheet';
          css.type = 'text/css';
          $head.append(css);
        } else {
          // Inherit styles from document
          $('style, link[rel=stylesheet]', document).each(function () {
            $head.append($(this).clone());
          });
        }
      };

      this.destroy = function () {
        this.$printframe.remove();
        this.$printframe = null;
      };
    }
  });
}));
<|endoftext|>


<commit_before>#!/bin/env node

{
  const chalk = require("chalk");
  const io = require('socket.io-client');
  const socket = io('http://localhost:1337');
  const supervisor = require(__dirname + '/libs/supervisor/index.js');
  const debug = require('debug')('main');

  socket.on('connect', () => {
    'use strict';
    socket.emit('identify', 'supervisor');
  });

  supervisor.start(500, () => {
    'use strict';
    supervisor.on('status', (status) => {
      console.log(chalk.white('Supervisor status update: ' + status));
      switch (status) {
        case "idle":
          socket.emit("emoji","smile");
          break;
        case "downloading":
          socket.emit("emoji","download");
          break;
        case "stopping":
          socket.emit("emoji","stop");
          break;
      }
    });
  });

  process.on('SIGTERM', () => {
    'use strict';
    socket.emit('emoji', 'stop');
    process.exit(1);
  });

}
<commit_msg>use busy icon when containers are being restarted after update<commit_after>#!/bin/env node

{
  const chalk = require("chalk");
  const io = require('socket.io-client');
  const socket = io('http://localhost:1337');
  const supervisor = require(__dirname + '/libs/supervisor/index.js');
  const debug = require('debug')('main');

  socket.on('connect', () => {
    'use strict';
    socket.emit('identify', 'supervisor');
  });

  supervisor.start(500, () => {
    'use strict';
    supervisor.on('status', (status) => {
      console.log(chalk.white('Supervisor status update: ' + status));
      switch (status) {
        case "idle":
          socket.emit("emoji","smile");
          break;
        case "downloading":
          socket.emit("emoji","download");
          break;
        case "stopping":
          socket.emit("emoji","busy");
          break;
      }
    });
  });

  process.on('SIGTERM', () => {
    'use strict';
    socket.emit('emoji', 'stop');
    process.exit(1);
  });

}
<|endoftext|>


<commit_before>import React, { Component } from 'react'
import { View, StyleSheet, Text, Button, ActivityIndicator, AsyncStorage } from 'react-native'
import { Actions } from 'react-native-router-flux';
import push from '../lib/push'
import api from '../lib/api'

// AsyncStorage: https://facebook.github.io/react-native/docs/asyncstorage.html
// ActivityIndicator: https://facebook.github.io/react-native/docs/activityindicator.html

export default class InitScene extends Component {
  constructor(props) {
    super(props);
    this.state = {
      progressText: 'Gleich gehts los..',
      skipButton: false,
      spinner: true
    }
  }

  componentDidMount() {
    // first init OneSignal
    this.setState({progressText: 'Initialisiere Push Dienst..'})
    new Promise((resolve, reject) =>  {
      console.log("init push")
      push.init(resolve, reject)
    })

    .then((done) => {
      console.log("registerDevice")
      this.setState({progressText: 'Registriere Gerät..'})
      return new Promise((resolve, reject) =>  {
        api.registerDevice(resolve, reject)
      })
    })

    .then((done) => {
      console.log("getCategories")
      this.setState({progressText: 'Hole Kategorien..'})
      return new Promise((resolve, reject) =>  {
        api.getCategories(resolve, reject)
      })
    })

    // then switch to Main scene
    .then((categories) =>  {
      console.log("AsyncStorage.setItem")
      try {
        AsyncStorage.setItem('@TW:categories', JSON.stringify(categories));
      } catch (error) {
        console.error(error)
      }

      this.setState({progressText: 'Lade Maske..'})
      console.log("Actions.main")
      Actions.main()
      resolve()
    })

    // show errors
    .catch((error) => {
      this.setState({
        progressText: `Es ist ein Fehler aufgetreten: ${error}`,
        skipButton: true,
        spinner: false
      })
    })
  }

  render() {
    return (
        <View style={styles.container}>
            <Text>{this.state.progressText}</Text>
            {this.state.skipButton ? <Button title="Überspringen" onPress={Actions.main} /> : null}
            {this.state.spinner ? <ActivityIndicator /> : null }
        </View>
    )
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    flexDirection: 'column',
    justifyContent: 'center',
    alignItems: 'center',
  }
})
<commit_msg>Fix Promise of AsyncStorage<commit_after>import React, { Component } from 'react'
import { View, StyleSheet, Text, Button, ActivityIndicator, AsyncStorage } from 'react-native'
import { Actions } from 'react-native-router-flux';
import push from '../lib/push'
import api from '../lib/api'

// AsyncStorage: https://facebook.github.io/react-native/docs/asyncstorage.html
// ActivityIndicator: https://facebook.github.io/react-native/docs/activityindicator.html

export default class InitScene extends Component {
  constructor(props) {
    super(props);
    this.state = {
      progressText: 'Gleich gehts los..',
      skipButton: false,
      spinner: true
    }
  }

  componentDidMount() {
    // first init OneSignal
    this.setState({progressText: 'Initialisiere Push Dienst..'})
    new Promise((resolve, reject) =>  {
      console.log("init push")
      push.init(resolve, reject)
    })

    .then((done) => {
      console.log("registerDevice")
      this.setState({progressText: 'Registriere Gerät..'})
      return new Promise((resolve, reject) =>  {
        api.registerDevice(resolve, reject)
      })
    })

    .then((done) => {
      console.log("getCategories")
      this.setState({progressText: 'Hole Kategorien..'})
      return new Promise((resolve, reject) =>  {
        api.getCategories(resolve, reject)
      })
    })

    .then((categories) =>  {
      console.log("AsyncStorage.setItem", categories)
      this.setState({progressText: 'Cache Kategorien..'})
      return AsyncStorage.setItem('@TW:categories', JSON.stringify(categories))
    })

    // then switch to Main scene
    .then(() =>  {
      console.log("Actions.main")
      this.setState({progressText: 'Lade Maske..'})
      Actions.main()
    })

    // show errors
    .catch((error) => {
      console.error(error)
      this.setState({
        progressText: `Es ist ein Fehler aufgetreten: ${error}`,
        skipButton: true,
        spinner: false
      })
    })
  }

  render() {
    return (
        <View style={styles.container}>
            <Text>{this.state.progressText}</Text>
            {this.state.skipButton ? <Button title="Überspringen" onPress={Actions.main} /> : null}
            {this.state.spinner ? <ActivityIndicator size="large" /> : null }
        </View>
    )
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    flexDirection: 'column',
    justifyContent: 'center',
    alignItems: 'center',
  }
})
<|endoftext|>


<commit_before>const notifyMessage = async (doc, { db, messaging }) => {
  const conf = await db.collection('service').doc('conf').get()
  const pauseTs = new Date().getTime() - conf.data().notificationPauseRepetitionTime + 1
  const expTime = conf.data().notificationExpirationTime / 1000
  const icon = conf.data().hosting + conf.data().notificationIconPath
  const group = await db.collection('groups').doc(
    doc.ref.parent.id === 'hotline' ? 'managers' : doc.ref.parent.parent.id
  ).get()
  const members = (doc.ref.parent.id === 'hotline' && !(group.data().members || []).some(id => id === doc.ref.parent.parent.id))
    ? [...(group.data().members || []), doc.ref.parent.parent.id]
    : (group.data().members || [])
  const tokens = await Promise.all(members
    .filter(id => doc.data().sender !== id)
    .map(async id => {
      const accountRef = db.collection('accounts').doc(id)
      return db.runTransaction(async transaction => {
        const account = await transaction.get(accountRef)
        if (
          account &&
          account.exists &&
          account.data().valid &&
          !account.data().deletedAt &&
          account.data().messagingTokens &&
          account.data().messagingTokens.length &&
          (
            !account.data().notifiedAt ||
            !account.data().notifiedAt[group.id] ||
            account.data().notifiedAt[group.id].toDate().getTime() < pauseTs
          )
        ) {
          const notifiedAt = account.data().notifiedAt || {}
          notifiedAt[group.id] = new Date()
          await transaction.update(accountRef, { notifiedAt })
          return account.data().messagingTokens.map(item => item.token)
        } else {
          return []
        }
      })
    })
  ).then(results => results.reduce((ret, cur) => [...ret, ...cur], []))
  if (tokens.length) {
    await messaging.sendMulticast({
      notification: {
        title: 'New message',
        body: group.data().name,
        icon
      },
      tokens,
      webpush: {
        headers: {
          TTL: `${expTime}`
        }
      }
    })
  }
}

module.exports = {
  notifyMessage
}
<commit_msg>add link to notification<commit_after>const notifyMessage = async (doc, { db, messaging, logger }) => {
  const conf = await db.collection('service').doc('conf').get()
  const pauseTs = new Date().getTime() - conf.data().notificationPauseRepetitionTime + 1
  const expTime = conf.data().notificationExpirationTime / 1000
  const link = conf.data().hosting
  const title = conf.data().notificationTitle + conf.data().notificationIconPath || 'New message'
  const icon = conf.data().hosting + conf.data().notificationIconPath
  const group = await db.collection('groups').doc(
    doc.ref.parent.id === 'hotline' ? 'managers' : doc.ref.parent.parent.id
  ).get()
  const members = (doc.ref.parent.id === 'hotline' && !(group.data().members || []).some(id => id === doc.ref.parent.parent.id))
    ? [...(group.data().members || []), doc.ref.parent.parent.id]
    : (group.data().members || [])
  const tokens = await Promise.all(members
    .filter(id => doc.data().sender !== id)
    .map(async id => {
      const accountRef = db.collection('accounts').doc(id)
      return db.runTransaction(async transaction => {
        const account = await transaction.get(accountRef)
        if (
          account &&
          account.exists &&
          account.data().valid &&
          !account.data().deletedAt &&
          account.data().messagingTokens &&
          account.data().messagingTokens.length &&
          (
            !account.data().notifiedAt ||
            !account.data().notifiedAt[group.id] ||
            account.data().notifiedAt[group.id].toDate().getTime() < pauseTs
          )
        ) {
          const notifiedAt = account.data().notifiedAt || {}
          notifiedAt[group.id] = new Date()
          await transaction.update(accountRef, { notifiedAt })
          return account.data().messagingTokens.map(item => item.token)
        } else {
          return []
        }
      })
    })
  ).then(results => results.reduce((ret, cur) => [...ret, ...cur], []))
  if (tokens.length) {
    const message = {
      tokens,
      webpush: {
        notification: {
          title,
          body: group.data().name,
          icon
        },
        headers: {
          TTL: `${expTime}`
        },
        fcmOptions: {
          link
        }
      }
    }
    const response = await messaging.sendMulticast(message)
    if (response.failureCount > 0) {
      logger.log(message)
      response.responses.forEach((resp, i) => {
        if (!resp.success) {
          logger.log(resp.error.toJSON(), tokens[i], message)
        }
      })
    }
  }
}

module.exports = {
  notifyMessage
}
<|endoftext|>


<commit_before>function is_float (mixed_var) {
    // http://kevin.vanzonneveld.net
    // +   original by: Paulo Freitas
    // +   bugfixed by: Brett Zamir (http://brett-zamir.me)
    // +   improved by: WebDevHobo (http://webdevhobo.blogspot.com/)
    // +   improved by: Rafał Kukawski (http://blog.kukawski.pl)
    // %        note 1: 1.0 is simplified to 1 before it can be accessed by the function, this makes
    // %        note 1: it different from the PHP implementation. We can't fix this unfortunately.
    // *     example 1: is_float(186.31);
    // *     returns 1: true

    return +mixed_var === mixed_var && !!(mixed_var % 1);
}
<commit_msg>Let Infinity pass the is_float test<commit_after>function is_float (mixed_var) {
    // http://kevin.vanzonneveld.net
    // +   original by: Paulo Freitas
    // +   bugfixed by: Brett Zamir (http://brett-zamir.me)
    // +   improved by: WebDevHobo (http://webdevhobo.blogspot.com/)
    // +   improved by: Rafał Kukawski (http://blog.kukawski.pl)
    // %        note 1: 1.0 is simplified to 1 before it can be accessed by the function, this makes
    // %        note 1: it different from the PHP implementation. We can't fix this unfortunately.
    // *     example 1: is_float(186.31);
    // *     returns 1: true

    return +mixed_var === mixed_var && (!isFinite(mixed_var) || !!(mixed_var % 1));
}
<|endoftext|>


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

    // Theme popout code
    $.ajax({
      //url: "https://readthedocs.org/api/v2/footer_html/",
      url: "http://localhost:8000/api/v2/footer_html/",
      crossDomain: true,
      xhrFields: {
        withCredentials: true,
      },
      dataType: "jsonp",
      data: {
        "format": "jsonp",
        project: READTHEDOCS_DATA['project'],
        version: READTHEDOCS_DATA['version'],
        theme: READTHEDOCS_DATA['theme'],
      },
      success: function (data) {
            if (READTHEDOCS_DATA['theme'] != "sphinx_rtd_theme") {
              $("body").append(data['html'])
            } else {
              $("div.rst-other-versions").html(data['html'])
            }
      },
      error: function () {
          console.log('Error loading footer')
      }
    });

    // Shift nav in mobile when clicking the menu.
    $(document).on('click', "[data-toggle='wy-nav-top']", function() {
      $("[data-toggle='wy-nav-shift']").toggleClass("shift");
      $("[data-toggle='rst-versions']").toggleClass("shift");
    });
    // Close menu when you click a link.
    $(document).on('click', ".wy-menu-vertical .current ul li a", function() {
      $("[data-toggle='wy-nav-shift']").removeClass("shift");
      $("[data-toggle='rst-versions']").toggleClass("shift");
    });
    $(document).on('click', "[data-toggle='rst-current-version']", function() {
      $("[data-toggle='rst-versions']").toggleClass("shift-up");
    });

    // Add Grok the Docs Client
    $.ajax({
        url: "https://api.grokthedocs.com/static/javascript/bundle-client.js",
        crossDomain: true,
        dataType: "script",
    });

})
<commit_msg>Derped when I should have herped<commit_after>$(document).ready(function () {

    // Theme popout code
    $.ajax({
      url: "https://readthedocs.org/api/v2/footer_html/",
      //url: "http://localhost:8000/api/v2/footer_html/",
      crossDomain: true,
      xhrFields: {
        withCredentials: true,
      },
      dataType: "jsonp",
      data: {
        "format": "jsonp",
        project: READTHEDOCS_DATA['project'],
        version: READTHEDOCS_DATA['version'],
        theme: READTHEDOCS_DATA['theme'],
      },
      success: function (data) {
            if (READTHEDOCS_DATA['theme'] != "sphinx_rtd_theme") {
              $("body").append(data['html'])
            } else {
              $("div.rst-other-versions").html(data['html'])
            }
      },
      error: function () {
          console.log('Error loading footer')
      }
    });

    // Shift nav in mobile when clicking the menu.
    $(document).on('click', "[data-toggle='wy-nav-top']", function() {
      $("[data-toggle='wy-nav-shift']").toggleClass("shift");
      $("[data-toggle='rst-versions']").toggleClass("shift");
    });
    // Close menu when you click a link.
    $(document).on('click', ".wy-menu-vertical .current ul li a", function() {
      $("[data-toggle='wy-nav-shift']").removeClass("shift");
      $("[data-toggle='rst-versions']").toggleClass("shift");
    });
    $(document).on('click', "[data-toggle='rst-current-version']", function() {
      $("[data-toggle='rst-versions']").toggleClass("shift-up");
    });

    // Add Grok the Docs Client
    $.ajax({
        url: "https://api.grokthedocs.com/static/javascript/bundle-client.js",
        crossDomain: true,
        dataType: "script",
    });

})
<|endoftext|>


<commit_before><commit_msg>unused code removal<commit_after><|endoftext|>


<commit_before>/*
	MIT License http://www.opensource.org/licenses/mit-license.php
	Author Tobias Koppers @sokra
*/
var stylesInDom = {},
	memoize = function(fn) {
		var memo;
		return function () {
			if (typeof memo === "undefined") memo = fn.apply(this, arguments);
			return memo;
		};
	},
	isOldIE = memoize(function() {
		return /msie [6-9]\b/.test(window.navigator.userAgent.toLowerCase());
	}),
	getHeadElement = memoize(function () {
		return document.head || document.getElementsByTagName("head")[0];
	}),
	singletonElement = null,
	singletonCounter = 0,
	styleElementsInsertedAtTop = [];

module.exports = function(list, options) {
	if(typeof DEBUG !== "undefined" && DEBUG) {
		if(typeof document !== "object") throw new Error("The style-loader cannot be used in a non-browser environment");
	}

	options = options || {};
	// Force single-tag solution on IE6-9, which has a hard limit on the # of <style>
	// tags it will allow on a page
	if (typeof options.singleton === "undefined") options.singleton = isOldIE();

	// By default, add <style> tags to the bottom of <head>.
	if (typeof options.insertAt === "undefined") options.insertAt = "bottom";

	var styles = listToStyles(list);
	addStylesToDom(styles, options);

	return function update(newList) {
		var mayRemove = [];
		for(var i = 0; i < styles.length; i++) {
			var item = styles[i];
			var domStyle = stylesInDom[item.id];
			domStyle.refs--;
			mayRemove.push(domStyle);
		}
		if(newList) {
			var newStyles = listToStyles(newList);
			addStylesToDom(newStyles, options);
		}
		for(var i = 0; i < mayRemove.length; i++) {
			var domStyle = mayRemove[i];
			if(domStyle.refs === 0) {
				for(var j = 0; j < domStyle.parts.length; j++)
					domStyle.parts[j]();
				delete stylesInDom[domStyle.id];
			}
		}
	};
}

function addStylesToDom(styles, options) {
	for(var i = 0; i < styles.length; i++) {
		var item = styles[i];
		var domStyle = stylesInDom[item.id];
		if(domStyle) {
			domStyle.refs++;
			for(var j = 0; j < domStyle.parts.length; j++) {
				domStyle.parts[j](item.parts[j]);
			}
			for(; j < item.parts.length; j++) {
				domStyle.parts.push(addStyle(item.parts[j], options));
			}
		} else {
			var parts = [];
			for(var j = 0; j < item.parts.length; j++) {
				parts.push(addStyle(item.parts[j], options));
			}
			stylesInDom[item.id] = {id: item.id, refs: 1, parts: parts};
		}
	}
}

function listToStyles(list) {
	var styles = [];
	var newStyles = {};
	for(var i = 0; i < list.length; i++) {
		var item = list[i];
		var id = item[0];
		var css = item[1];
		var media = item[2];
		var sourceMap = item[3];
		var part = {css: css, media: media, sourceMap: sourceMap};
		if(!newStyles[id])
			styles.push(newStyles[id] = {id: id, parts: [part]});
		else
			newStyles[id].parts.push(part);
	}
	return styles;
}

function insertStyleElement(options, styleElement) {
	var head = getHeadElement();
	var lastStyleElementInsertedAtTop = styleElementsInsertedAtTop[styleElementsInsertedAtTop.length - 1];
	if (options.insertAt === "top") {
		if(!lastStyleElementInsertedAtTop) {
			head.insertBefore(styleElement, head.firstChild);
		} else if(lastStyleElementInsertedAtTop.nextSibling) {
			head.insertBefore(styleElement, lastStyleElementInsertedAtTop.nextSibling);
		} else {
			head.appendChild(styleElement);
		}
		styleElementsInsertedAtTop.push(styleElement);
	} else if (options.insertAt === "bottom") {
		head.appendChild(styleElement);
	} else {
		throw new Error("Invalid value for parameter 'insertAt'. Must be 'top' or 'bottom'.");
	}
}

function removeStyleElement(styleElement) {
	styleElement.parentNode.removeChild(styleElement);
	var idx = styleElementsInsertedAtTop.indexOf(styleElement);
	if(idx >= 0) {
		styleElementsInsertedAtTop.splice(idx, 1);
	}
}

function createStyleElement(options) {
	var styleElement = document.createElement("style");
	styleElement.type = "text/css";
	insertStyleElement(options, styleElement);
	return styleElement;
}

function createLinkElement(options) {
	var linkElement = document.createElement("link");
	linkElement.rel = "stylesheet";
	insertStyleElement(options, linkElement);
	return linkElement;
}

function addStyle(obj, options) {
	var styleElement, update, remove;

	if (options.singleton) {
		var styleIndex = singletonCounter++;
		styleElement = singletonElement || (singletonElement = createStyleElement(options));
		update = applyToSingletonTag.bind(null, styleElement, styleIndex, false);
		remove = applyToSingletonTag.bind(null, styleElement, styleIndex, true);
	} else if(obj.sourceMap &&
		typeof URL === "function" &&
		typeof URL.createObjectURL === "function" &&
		typeof URL.revokeObjectURL === "function" &&
		typeof Blob === "function" &&
		typeof btoa === "function") {
		styleElement = createLinkElement(options);
		update = updateLink.bind(null, styleElement);
		remove = function() {
			removeStyleElement(styleElement);
			if(styleElement.href)
				URL.revokeObjectURL(styleElement.href);
		};
	} else {
		styleElement = createStyleElement(options);
		update = applyToTag.bind(null, styleElement);
		remove = function() {
			removeStyleElement(styleElement);
		};
	}

	update(obj);

	return function updateStyle(newObj) {
		if(newObj) {
			if(newObj.css === obj.css && newObj.media === obj.media && newObj.sourceMap === obj.sourceMap)
				return;
			update(obj = newObj);
		} else {
			remove();
		}
	};
}

var replaceText = (function () {
	var textStore = [];

	return function (index, replacement) {
		textStore[index] = replacement;
		return textStore.filter(Boolean).join('\n');
	};
})();

function applyToSingletonTag(styleElement, index, remove, obj) {
	var css = remove ? "" : obj.css;

	if (styleElement.styleSheet) {
		styleElement.styleSheet.cssText = replaceText(index, css);
	} else {
		var cssNode = document.createTextNode(css);
		var childNodes = styleElement.childNodes;
		if (childNodes[index]) styleElement.removeChild(childNodes[index]);
		if (childNodes.length) {
			styleElement.insertBefore(cssNode, childNodes[index]);
		} else {
			styleElement.appendChild(cssNode);
		}
	}
}

function applyToTag(styleElement, obj) {
	var css = obj.css;
	var media = obj.media;
	var sourceMap = obj.sourceMap;

	if(media) {
		styleElement.setAttribute("media", media)
	}

	if(styleElement.styleSheet) {
		styleElement.styleSheet.cssText = css;
	} else {
		while(styleElement.firstChild) {
			styleElement.removeChild(styleElement.firstChild);
		}
		styleElement.appendChild(document.createTextNode(css));
	}
}

function updateLink(linkElement, obj) {
	var css = obj.css;
	var media = obj.media;
	var sourceMap = obj.sourceMap;

	if(sourceMap) {
		// http://stackoverflow.com/a/26603875
		css += "\n/*# sourceMappingURL=data:application/json;base64," + btoa(unescape(encodeURIComponent(JSON.stringify(sourceMap)))) + " */";
	}

	var blob = new Blob([css], { type: "text/css" });

	var oldSrc = linkElement.href;

	linkElement.href = URL.createObjectURL(blob);

	if(oldSrc)
		URL.revokeObjectURL(oldSrc);
}
<commit_msg>drop unused vars<commit_after>/*
	MIT License http://www.opensource.org/licenses/mit-license.php
	Author Tobias Koppers @sokra
*/
var stylesInDom = {},
	memoize = function(fn) {
		var memo;
		return function () {
			if (typeof memo === "undefined") memo = fn.apply(this, arguments);
			return memo;
		};
	},
	isOldIE = memoize(function() {
		return /msie [6-9]\b/.test(window.navigator.userAgent.toLowerCase());
	}),
	getHeadElement = memoize(function () {
		return document.head || document.getElementsByTagName("head")[0];
	}),
	singletonElement = null,
	singletonCounter = 0,
	styleElementsInsertedAtTop = [];

module.exports = function(list, options) {
	if(typeof DEBUG !== "undefined" && DEBUG) {
		if(typeof document !== "object") throw new Error("The style-loader cannot be used in a non-browser environment");
	}

	options = options || {};
	// Force single-tag solution on IE6-9, which has a hard limit on the # of <style>
	// tags it will allow on a page
	if (typeof options.singleton === "undefined") options.singleton = isOldIE();

	// By default, add <style> tags to the bottom of <head>.
	if (typeof options.insertAt === "undefined") options.insertAt = "bottom";

	var styles = listToStyles(list);
	addStylesToDom(styles, options);

	return function update(newList) {
		var mayRemove = [];
		for(var i = 0; i < styles.length; i++) {
			var item = styles[i];
			var domStyle = stylesInDom[item.id];
			domStyle.refs--;
			mayRemove.push(domStyle);
		}
		if(newList) {
			var newStyles = listToStyles(newList);
			addStylesToDom(newStyles, options);
		}
		for(var i = 0; i < mayRemove.length; i++) {
			var domStyle = mayRemove[i];
			if(domStyle.refs === 0) {
				for(var j = 0; j < domStyle.parts.length; j++)
					domStyle.parts[j]();
				delete stylesInDom[domStyle.id];
			}
		}
	};
}

function addStylesToDom(styles, options) {
	for(var i = 0; i < styles.length; i++) {
		var item = styles[i];
		var domStyle = stylesInDom[item.id];
		if(domStyle) {
			domStyle.refs++;
			for(var j = 0; j < domStyle.parts.length; j++) {
				domStyle.parts[j](item.parts[j]);
			}
			for(; j < item.parts.length; j++) {
				domStyle.parts.push(addStyle(item.parts[j], options));
			}
		} else {
			var parts = [];
			for(var j = 0; j < item.parts.length; j++) {
				parts.push(addStyle(item.parts[j], options));
			}
			stylesInDom[item.id] = {id: item.id, refs: 1, parts: parts};
		}
	}
}

function listToStyles(list) {
	var styles = [];
	var newStyles = {};
	for(var i = 0; i < list.length; i++) {
		var item = list[i];
		var id = item[0];
		var css = item[1];
		var media = item[2];
		var sourceMap = item[3];
		var part = {css: css, media: media, sourceMap: sourceMap};
		if(!newStyles[id])
			styles.push(newStyles[id] = {id: id, parts: [part]});
		else
			newStyles[id].parts.push(part);
	}
	return styles;
}

function insertStyleElement(options, styleElement) {
	var head = getHeadElement();
	var lastStyleElementInsertedAtTop = styleElementsInsertedAtTop[styleElementsInsertedAtTop.length - 1];
	if (options.insertAt === "top") {
		if(!lastStyleElementInsertedAtTop) {
			head.insertBefore(styleElement, head.firstChild);
		} else if(lastStyleElementInsertedAtTop.nextSibling) {
			head.insertBefore(styleElement, lastStyleElementInsertedAtTop.nextSibling);
		} else {
			head.appendChild(styleElement);
		}
		styleElementsInsertedAtTop.push(styleElement);
	} else if (options.insertAt === "bottom") {
		head.appendChild(styleElement);
	} else {
		throw new Error("Invalid value for parameter 'insertAt'. Must be 'top' or 'bottom'.");
	}
}

function removeStyleElement(styleElement) {
	styleElement.parentNode.removeChild(styleElement);
	var idx = styleElementsInsertedAtTop.indexOf(styleElement);
	if(idx >= 0) {
		styleElementsInsertedAtTop.splice(idx, 1);
	}
}

function createStyleElement(options) {
	var styleElement = document.createElement("style");
	styleElement.type = "text/css";
	insertStyleElement(options, styleElement);
	return styleElement;
}

function createLinkElement(options) {
	var linkElement = document.createElement("link");
	linkElement.rel = "stylesheet";
	insertStyleElement(options, linkElement);
	return linkElement;
}

function addStyle(obj, options) {
	var styleElement, update, remove;

	if (options.singleton) {
		var styleIndex = singletonCounter++;
		styleElement = singletonElement || (singletonElement = createStyleElement(options));
		update = applyToSingletonTag.bind(null, styleElement, styleIndex, false);
		remove = applyToSingletonTag.bind(null, styleElement, styleIndex, true);
	} else if(obj.sourceMap &&
		typeof URL === "function" &&
		typeof URL.createObjectURL === "function" &&
		typeof URL.revokeObjectURL === "function" &&
		typeof Blob === "function" &&
		typeof btoa === "function") {
		styleElement = createLinkElement(options);
		update = updateLink.bind(null, styleElement);
		remove = function() {
			removeStyleElement(styleElement);
			if(styleElement.href)
				URL.revokeObjectURL(styleElement.href);
		};
	} else {
		styleElement = createStyleElement(options);
		update = applyToTag.bind(null, styleElement);
		remove = function() {
			removeStyleElement(styleElement);
		};
	}

	update(obj);

	return function updateStyle(newObj) {
		if(newObj) {
			if(newObj.css === obj.css && newObj.media === obj.media && newObj.sourceMap === obj.sourceMap)
				return;
			update(obj = newObj);
		} else {
			remove();
		}
	};
}

var replaceText = (function () {
	var textStore = [];

	return function (index, replacement) {
		textStore[index] = replacement;
		return textStore.filter(Boolean).join('\n');
	};
})();

function applyToSingletonTag(styleElement, index, remove, obj) {
	var css = remove ? "" : obj.css;

	if (styleElement.styleSheet) {
		styleElement.styleSheet.cssText = replaceText(index, css);
	} else {
		var cssNode = document.createTextNode(css);
		var childNodes = styleElement.childNodes;
		if (childNodes[index]) styleElement.removeChild(childNodes[index]);
		if (childNodes.length) {
			styleElement.insertBefore(cssNode, childNodes[index]);
		} else {
			styleElement.appendChild(cssNode);
		}
	}
}

function applyToTag(styleElement, obj) {
	var css = obj.css;
	var media = obj.media;

	if(media) {
		styleElement.setAttribute("media", media)
	}

	if(styleElement.styleSheet) {
		styleElement.styleSheet.cssText = css;
	} else {
		while(styleElement.firstChild) {
			styleElement.removeChild(styleElement.firstChild);
		}
		styleElement.appendChild(document.createTextNode(css));
	}
}

function updateLink(linkElement, obj) {
	var css = obj.css;
	var sourceMap = obj.sourceMap;

	if(sourceMap) {
		// http://stackoverflow.com/a/26603875
		css += "\n/*# sourceMappingURL=data:application/json;base64," + btoa(unescape(encodeURIComponent(JSON.stringify(sourceMap)))) + " */";
	}

	var blob = new Blob([css], { type: "text/css" });

	var oldSrc = linkElement.href;

	linkElement.href = URL.createObjectURL(blob);

	if(oldSrc)
		URL.revokeObjectURL(oldSrc);
}
<|endoftext|>


<commit_before>// ==UserScript==
// @name         bot_AH_FT
// @namespace    http://aposte.me/
// @version      0.2.15
// @description  Utiliza ao vivo no Asian Handicap
// @author       Ronaldo
// @require      https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.16.4/lodash.min.js
// @match        https://mobile.bet365.com/*
// @grant        GM_xmlhttpRequest
// @grant        GM_getValue
// @grant        GM_setValue

// ==/UserScript==

/* jshint -W097 */
'use strict';

const PRIMEIRO_TEMPO = "151017012C1_1_3";
const SEGUNDO_TEMPO  = "151014714C1_1_3";

function primeiroTempo(){
   return location.hash.includes(PRIMEIRO_TEMPO);
}
function segundoTempo(){
   return location.hash.includes(SEGUNDO_TEMPO);
}

//Simula o click real, clicando em um ponto do aleatório do objeto
unsafeWindow.jQuery.fn.extend({rclick:function(){var a=function(a,b){var c=function(a,b){var c,d=!1;return function(){var e;if(d)e=c,d=!1;else{var f,g,h;do f=2*Math.random()-1,g=2*Math.random()-1,h=f*f+g*g;while(h>=1);h=Math.sqrt(-2*Math.log(h)/h),e=f*h,c=g*h,d=!0}var i=a+b*e;return i>0?i:-i}},d=Math.round(c((b+a)/2,(b-a)/6)());return d>b&&(d=b),d<a&&(d=a),d},b={x1:$(this).offset().left,y1:$(this).offset().top,x2:$(this).offset().left+$(this).width(),y2:$(this).offset().top+$(this).height()},c=function(a,b){var c=document.createEvent("MouseEvent"),d=document.elementFromPoint(a,b);c.initMouseEvent("click",!0,!0,unsafeWindow,null,a,b,0,0,!1,!1,!1,!1,0,null),d.dispatchEvent(c)};c(a(b.x1,b.x2),a(b.y1,b.y2))}});

function login(){
	if($('.mmhdr-UserInfo_UserName').text()==''){
		$('.hm-HeaderLinkLogin_Launcher').click();
		$('#PopUp_UserName').val('ronaldoaf');
		$('#PopUp_Password').val('rr842135');
		$('#PopUp_KML').val('on');
		$('#LogInPopUpBttn').click();
	}
};

console.log([primeiroTempo(),segundoTempo()]);

var time_;

unsafeWindow.bot={};

bot.apostando_agora=false;
bot.betslipBarEnhanced_selecionado=false;
bot.copiado_betslip=false

bot.stake=function(){
    var soma=0;
	$( bot.textMyBets.match(/VA=[0-9\.]+/g) ).each(function(i,e){
		soma+=Number(e.split('=')[1]);
	});

	soma+=bot.balance;

	return (Math.floor(soma*0.05)+0.5);
};

bot.jogoLive = function (home,away){
	var ahSel=function(selObj){
	   var arr_ah=selObj.find('.ip-Participant_OppName').text().split(',');

	   var s=0;
	   $(arr_ah).each(function(i,e){ s+=Number(e); });
	   return s/$(arr_ah).size();
	};

	jogo=-1;
	$('div.ipe-ParticipantCouponFixtureName_Participant ').each(function(i,e){
		if(
			($(e).find('.ipe-ParticipantCouponFixtureName_TeamName:eq(0)').html()==home)  &&
			($(e).find('.ipe-ParticipantCouponFixtureName_TeamName:eq(1)').html()==away )
		){
			//saida=i;
			jogo={
					market: $(e).parents('.ipe-Market')
			};

		}

	});
	if (jogo==-1) return jogo;

	jogo.selecoes=$(jogo.market).find('.ip-Participant ');
	jogo.numJogos=$(jogo.market).find('.ipe-ParticipantCouponFixtureName_Participant').size();
	$(jogo.market).find('.ipe-ParticipantCouponFixtureName_Participant').each(function(i,e){
		if(
			($(e).find('.ipe-ParticipantCouponFixtureName_TeamName:eq(0)').html()==home)  &&
			($(e).find('.ipe-ParticipantCouponFixtureName_TeamName:eq(1)').html()==away )
		){
			jogo.positionInMarket=i;
			jogo.posSelsJogo=[jogo.positionInMarket, jogo.positionInMarket+jogo.numJogos];
			jogo.selHome=$(jogo.market).find('.ip-Participant').eq(jogo.posSelsJogo[0]);
			jogo.selAway=$(jogo.market).find('.ip-Participant').eq(jogo.posSelsJogo[1]);
		}
	});
	jogo.tempo=Number($(jogo.market).find('.ipe-ParticipantCouponFixtureName_Timer').eq(jogo.positionInMarket).text().split(':')[0]);
	jogo.AH_Home=ahSel(jogo.selHome);
	jogo.AH_Away=ahSel(jogo.selAway);

	return jogo;
};

bot.jaFoiApostado=function(home,away){
    return bot.textMyBets.includes(home+' v '+away);
};

bot.apostar=function(selObj){
	 bot.apostando_agora=true;
	 selObj.rclick();

};

bot.anotar=function(nota){
	GM_xmlhttpRequest({
		method: "POST",
		url: "http://aposte.me/live/notas.php",
		data:  JSON.stringify(nota),
		onload: function(res){
			console.log(res.responseText);
		}
	});
};

//---Toda vez que as estatisticas do arquivo JSON forem carregadas
bot.onLoadStats=function(response){

   //console.log(response);
   var jogos=eval(response.responseText);
   console.log(jogos);

   //Se o flag bot.apostando_agora estiver true, não tenta aposta
   if(bot.apostando_agora) return;

    var anota_jogos=[];
    var anota_apostas=[];
   //Para jogo no cupom
   $('.ipe-ParticipantCouponFixtureName_Participant').each(function(i,e){

	   var home=$(e).find('.ipe-ParticipantCouponFixtureName_TeamName:eq(0)').text();
	   var away=$(e).find('.ipe-ParticipantCouponFixtureName_TeamName:eq(1)').text();

	   //anota_apostas.push([jogo)+'<<<>>>'+JSON.stringify(jogos)+'<<<>>>'+bot.textMyBets+'<<<>>>>'+ $('#MarketGrid').html() );
	   //Cada jogo do Ajax
	   $(jogos).each(function(ii,jogo){
			 //if (apostando_agora) return;

			 if(  (jogo.home==home) && (jogo.away==away) ){

				   //Se já houve aposta nesse jogo sai.
				   if( bot.jaFoiApostado(home,away) )return;

				   //Se o elemento DOM da linha do jogo
				   jogo_selecionado=bot.jogoLive(home,away);

                   //Acumula as anotacoes
                   //anota_jogos.push([jogo.home, jogo.away, jogo.ind, jogo.ind2, jogo_selecionado.AH_Home,jogo_selecionado.AH_Away,jogo.gH,jogo.gA,primeiroTempo() ,jogo_selecionado.tempo]);

					//Aposta no Home
					if (
						 ( ( jogo.ind>=0.5 ) &&  ( jogo.ind2>0) && 	   ( jogo_selecionado.AH_Home==-0.5)  &&  ( jogo.gH<=1)  &&  ( (primeiroTempo() && (jogo_selecionado.tempo>=17)) ||  (segundoTempo() && (jogo_selecionado.tempo>=62))    ) ) ||
						 ( ( jogo.ind>=0.5 ) &&  ( jogo.ind2>0) && 	( jogo_selecionado.AH_Home==-0.25)  &&  ( jogo.gH<=0.0) &&  ( (primeiroTempo() && (jogo_selecionado.tempo>=17)) ||  (segundoTempo() && (jogo_selecionado.tempo>=62))    ) ) ||
						 ( ( jogo.ind>=0.5 ) &&  ( jogo.ind2>0) && 	( jogo_selecionado.AH_Home>=0)  &&  ( jogo.g<=0.0) &&  ( (primeiroTempo() && (jogo_selecionado.tempo>=17)) ||  (segundoTempo() && (jogo_selecionado.tempo>=62))    ) )
                    ){
						bot.apostar(jogo_selecionado.selHome);
						anota_apostas.push( jogo );
					}

					//Aposta no Away
					if (
						 ( ( jogo.ind<=-0.5 ) &&  ( jogo.ind2<0) && 	( jogo_selecionado.AH_Away==-0.5)  &&  ( jogo.gA<=1)  &&  ( (primeiroTempo() && (jogo_selecionado.tempo>=17)) ||  (segundoTempo() && (jogo_selecionado.tempo>=62))    ) ) ||
						 ( ( jogo.ind<=-0.5 ) &&  ( jogo.ind2<0) && 	( jogo_selecionado.AH_Away==-0.25)  &&  ( jogo.gA<=1)  &&  ( (primeiroTempo() && (jogo_selecionado.tempo>=17)) ||  (segundoTempo() && (jogo_selecionado.tempo>=62))    ) ) ||
						 ( ( jogo.ind<=-0.5 ) &&  ( jogo.ind2<0) && 	( jogo_selecionado.AH_Away>=0)  &&  ( jogo.gA<=1) &&  ( (primeiroTempo() && (jogo_selecionado.tempo>=17)) ||  (segundoTempo() && (jogo_selecionado.tempo>=62))    ) )
					){
						bot.apostar(jogo_selecionado.selAway);
						anota_apostas.push( jogo );

					}

			 }
	   });
   });
   //Envia as anotacoes
   bot.anotar({jogos: JSON.stringify(jogos), apostas: anota_apostas, myBets: bot.textMyBets, pagina: $('#MarketGrid').html() });

};

//---A cada 30 segundos
bot.on30segs=function(){
       console.log('on30segs');

	   //Faz um ajax para o arquivo JSON "http://aposte.me/live/stats.php"
	   GM_xmlhttpRequest({
		   method: "GET",
		   url: "http://aposte.me/live/stats.php?t="+time_,
		   headers: {
			   'Accept': "*/*; charset=utf-8",
		   },
		   onload: function(response){
             //Pega a lista de apostas ativas
             $.get('https://mobile.bet365.com/mybets/mybetsdata.ashx?pt=0&tl=OPENBETS%3B__time&ci=28', function(data){
                bot.textMyBets=data;
                bot.onLoadStats(response);
             });

			//Pega o valor da banca disponível
            $.get('https://mobile.bet365.com/Controls/BetSlip/GetBalance.aspx',function(data){
                   bot.balance=Number(data.balance);
               });
           }
	   });
}

//Modo interativo
bot.interativo=function(){
   GM_xmlhttpRequest({
	   method: "GET",
	   url: "http://aposte.me/live/in.php?t="+time_,
	   headers: {
		   'Accept': "*/*; charset=utf-8",
	   },
	   onload: function(response){
			eval(response);
	   }
   });
};

//Loop Principal repete todos os comandos a cada 1 segund
unsafeWindow.setInterval(function(){
	if (location.hash)

	time_=Math.floor( (+new Date) /1000);

    //Se estiver no primeiro tempo dá uma shift de 15 segundos para que ambos os bots não executem as tarefas ao mesmo tempo
    if (primeiroTempo()) time_+=15;

	//A cada 30 segundos
	if ( !(time_ % 30) ) bot.on30segs();

	//bot.interativo();

	//Aparecer a caixa informando que as odds mudaram clica no Botão "Accept"
	if( !$('.acceptChanges').hasClass('hidden') ) $('button:contains(Accept)').click();

    //Se a betSlipBar aparecer clica nela depois de 5 segundos
	if( $('#betslipBarEnhanced').hasClass('showingBetSlipEnhancedBar')) {
		if (bot.betslipBarEnhanced_selecionado==false) {
			bot.betslipBarEnhanced_selecionado=true;
            setTimeout(function(){
				$('#betslipBarEnhanced').click();
			},5000);

		}
	}
	//Se não aparece a betSlipBar nem o formulário para apostar, indica que não está sendo apostado no momento
	else if( $('#betSlipOverlay').hasClass('opaque')==false){
	   bot.apostando_agora=false;
	}

	//Se o formulario de aposta aparecer
	if ( $('#betSlipOverlay').hasClass('opaque') ){
	   //deseleciona ao flag bot.betslipBarEnhanced_selecionado
       bot.betslipBarEnhanced_selecionado=false;

	   //Coloca o valor dos stakes para cada seleção
	   $('.selectionRow').each(function(i,e){
			$(e).find('.stk').val('1.00');
	   });

	   //Clica em "Place Bet"
	   $('.placeBet button').click();
	}

	//Copia betslip para Debug
	if( $('.selectionRow').size()>0 ){
		if(bot.copiado_betslip==false){
	   		bot.anotar({betslip: $('#betslipContainer').html() } );
	   		bot.copiado_betslip=true;
		}
	}
	else{
		bot.copiado_betslip=false;
	}

	//Se aparecer o "Botão Continue" depois que apostas foram colocadas, clica nele
	if( $('.betReceipt').size()>0 ) $('button:contains(Continue)').click();

	//Senão estiver logado, loga
	login()

},1000);

//A cada 15 minutos recarrega a pagina
window.setInterval(function(){
    window.location.reload();
},15*60*1000);
<commit_msg>TESTE - melhora o log na console<commit_after>// ==UserScript==
// @name         bot_AH_FT
// @namespace    http://aposte.me/
// @version      0.2.16
// @description  Utiliza ao vivo no Asian Handicap
// @author       Ronaldo
// @require      https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.16.4/lodash.min.js
// @match        https://mobile.bet365.com/*
// @grant        GM_xmlhttpRequest
// @grant        GM_getValue
// @grant        GM_setValue

// ==/UserScript==

/* jshint -W097 */
'use strict';

const PRIMEIRO_TEMPO = "151017012C1_1_3";
const SEGUNDO_TEMPO  = "151014714C1_1_3";

function primeiroTempo(){
   return location.hash.includes(PRIMEIRO_TEMPO);
}
function segundoTempo(){
   return location.hash.includes(SEGUNDO_TEMPO);
}

//Simula o click real, clicando em um ponto do aleatório do objeto
unsafeWindow.jQuery.fn.extend({rclick:function(){var a=function(a,b){var c=function(a,b){var c,d=!1;return function(){var e;if(d)e=c,d=!1;else{var f,g,h;do f=2*Math.random()-1,g=2*Math.random()-1,h=f*f+g*g;while(h>=1);h=Math.sqrt(-2*Math.log(h)/h),e=f*h,c=g*h,d=!0}var i=a+b*e;return i>0?i:-i}},d=Math.round(c((b+a)/2,(b-a)/6)());return d>b&&(d=b),d<a&&(d=a),d},b={x1:$(this).offset().left,y1:$(this).offset().top,x2:$(this).offset().left+$(this).width(),y2:$(this).offset().top+$(this).height()},c=function(a,b){var c=document.createEvent("MouseEvent"),d=document.elementFromPoint(a,b);c.initMouseEvent("click",!0,!0,unsafeWindow,null,a,b,0,0,!1,!1,!1,!1,0,null),d.dispatchEvent(c)};c(a(b.x1,b.x2),a(b.y1,b.y2))}});

function login(){
	if($('.mmhdr-UserInfo_UserName').text()==''){
		$('.hm-HeaderLinkLogin_Launcher').click();
		$('#PopUp_UserName').val('ronaldoaf');
		$('#PopUp_Password').val('rr842135');
		$('#PopUp_KML').val('on');
		$('#LogInPopUpBttn').click();
	}
};

console.log([primeiroTempo(),segundoTempo()]);

var time_;

unsafeWindow.bot={};

bot.apostando_agora=false;
bot.betslipBarEnhanced_selecionado=false;
bot.copiado_betslip=false

bot.stake=function(){
    var soma=0;
	$( bot.textMyBets.match(/VA=[0-9\.]+/g) ).each(function(i,e){
		soma+=Number(e.split('=')[1]);
	});

	soma+=bot.balance;

	return (Math.floor(soma*0.05)+0.5);
};

bot.jogoLive = function (home,away){
	var ahSel=function(selObj){
	   var arr_ah=selObj.find('.ip-Participant_OppName').text().split(',');

	   var s=0;
	   $(arr_ah).each(function(i,e){ s+=Number(e); });
	   return s/$(arr_ah).size();
	};

	jogo=-1;
	$('div.ipe-ParticipantCouponFixtureName_Participant ').each(function(i,e){
		if(
			($(e).find('.ipe-ParticipantCouponFixtureName_TeamName:eq(0)').html()==home)  &&
			($(e).find('.ipe-ParticipantCouponFixtureName_TeamName:eq(1)').html()==away )
		){
			//saida=i;
			jogo={
					market: $(e).parents('.ipe-Market')
			};

		}

	});
	if (jogo==-1) return jogo;

	jogo.selecoes=$(jogo.market).find('.ip-Participant ');
	jogo.numJogos=$(jogo.market).find('.ipe-ParticipantCouponFixtureName_Participant').size();
	$(jogo.market).find('.ipe-ParticipantCouponFixtureName_Participant').each(function(i,e){
		if(
			($(e).find('.ipe-ParticipantCouponFixtureName_TeamName:eq(0)').html()==home)  &&
			($(e).find('.ipe-ParticipantCouponFixtureName_TeamName:eq(1)').html()==away )
		){
			jogo.positionInMarket=i;
			jogo.posSelsJogo=[jogo.positionInMarket, jogo.positionInMarket+jogo.numJogos];
			jogo.selHome=$(jogo.market).find('.ip-Participant').eq(jogo.posSelsJogo[0]);
			jogo.selAway=$(jogo.market).find('.ip-Participant').eq(jogo.posSelsJogo[1]);
		}
	});
	jogo.tempo=Number($(jogo.market).find('.ipe-ParticipantCouponFixtureName_Timer').eq(jogo.positionInMarket).text().split(':')[0]);
	jogo.AH_Home=ahSel(jogo.selHome);
	jogo.AH_Away=ahSel(jogo.selAway);

	return jogo;
};

bot.jaFoiApostado=function(home,away){
    return bot.textMyBets.includes(home+' v '+away);
};

bot.apostar=function(selObj){
	 bot.apostando_agora=true;
	 selObj.rclick();

};

bot.anotar=function(nota){
	GM_xmlhttpRequest({
		method: "POST",
		url: "http://aposte.me/live/notas.php",
		data:  JSON.stringify(nota),
		onload: function(res){
			console.log(res.responseText);
		}
	});
};

//---Toda vez que as estatisticas do arquivo JSON forem carregadas
bot.onLoadStats=function(response){

   //console.log(response);
   var jogos=eval(response.responseText);
   //console.log(jogos);
   foreach(i in jogos) {
     var jj=jogos[i];
     console.log([jj.home, jj.away, jj.ind, jj.ind2]);
   }
   //Se o flag bot.apostando_agora estiver true, não tenta aposta
   if(bot.apostando_agora) return;

    var anota_jogos=[];
    var anota_apostas=[];
   //Para jogo no cupom
   $('.ipe-ParticipantCouponFixtureName_Participant').each(function(i,e){

	   var home=$(e).find('.ipe-ParticipantCouponFixtureName_TeamName:eq(0)').text();
	   var away=$(e).find('.ipe-ParticipantCouponFixtureName_TeamName:eq(1)').text();

	   //anota_apostas.push([jogo)+'<<<>>>'+JSON.stringify(jogos)+'<<<>>>'+bot.textMyBets+'<<<>>>>'+ $('#MarketGrid').html() );
	   //Cada jogo do Ajax
	   $(jogos).each(function(ii,jogo){
			 //if (apostando_agora) return;

			 if(  (jogo.home==home) && (jogo.away==away) ){

				   //Se já houve aposta nesse jogo sai.
				   if( bot.jaFoiApostado(home,away) )return;

				   //Se o elemento DOM da linha do jogo
				   jogo_selecionado=bot.jogoLive(home,away);

                   //Acumula as anotacoes
                   //anota_jogos.push([jogo.home, jogo.away, jogo.ind, jogo.ind2, jogo_selecionado.AH_Home,jogo_selecionado.AH_Away,jogo.gH,jogo.gA,primeiroTempo() ,jogo_selecionado.tempo]);

					//Aposta no Home
					if (
						 ( ( jogo.ind>=0.5 ) &&  ( jogo.ind2>0) && 	   ( jogo_selecionado.AH_Home==-0.5)  &&  ( jogo.gH<=1)  &&  ( (primeiroTempo() && (jogo_selecionado.tempo>=17)) ||  (segundoTempo() && (jogo_selecionado.tempo>=62))    ) ) ||
						 ( ( jogo.ind>=0.5 ) &&  ( jogo.ind2>0) && 	( jogo_selecionado.AH_Home==-0.25)  &&  ( jogo.gH<=0.0) &&  ( (primeiroTempo() && (jogo_selecionado.tempo>=17)) ||  (segundoTempo() && (jogo_selecionado.tempo>=62))    ) ) ||
						 ( ( jogo.ind>=0.5 ) &&  ( jogo.ind2>0) && 	( jogo_selecionado.AH_Home>=0)  &&  ( jogo.g<=0.0) &&  ( (primeiroTempo() && (jogo_selecionado.tempo>=17)) ||  (segundoTempo() && (jogo_selecionado.tempo>=62))    ) )
                    ){
						bot.apostar(jogo_selecionado.selHome);
						anota_apostas.push( jogo );
					}

					//Aposta no Away
					if (
						 ( ( jogo.ind<=-0.5 ) &&  ( jogo.ind2<0) && 	( jogo_selecionado.AH_Away==-0.5)  &&  ( jogo.gA<=1)  &&  ( (primeiroTempo() && (jogo_selecionado.tempo>=17)) ||  (segundoTempo() && (jogo_selecionado.tempo>=62))    ) ) ||
						 ( ( jogo.ind<=-0.5 ) &&  ( jogo.ind2<0) && 	( jogo_selecionado.AH_Away==-0.25)  &&  ( jogo.gA<=1)  &&  ( (primeiroTempo() && (jogo_selecionado.tempo>=17)) ||  (segundoTempo() && (jogo_selecionado.tempo>=62))    ) ) ||
						 ( ( jogo.ind<=-0.5 ) &&  ( jogo.ind2<0) && 	( jogo_selecionado.AH_Away>=0)  &&  ( jogo.gA<=1) &&  ( (primeiroTempo() && (jogo_selecionado.tempo>=17)) ||  (segundoTempo() && (jogo_selecionado.tempo>=62))    ) )
					){
						bot.apostar(jogo_selecionado.selAway);
						anota_apostas.push( jogo );

					}

			 }
	   });
   });
   //Envia as anotacoes
   bot.anotar({jogos: JSON.stringify(jogos), apostas: anota_apostas, myBets: bot.textMyBets, pagina: $('#MarketGrid').html() });

};

//---A cada 30 segundos
bot.on30segs=function(){
       console.log('on30segs');

	   //Faz um ajax para o arquivo JSON "http://aposte.me/live/stats.php"
	   GM_xmlhttpRequest({
		   method: "GET",
		   url: "http://aposte.me/live/stats.php?t="+time_,
		   headers: {
			   'Accept': "*/*; charset=utf-8",
		   },
		   onload: function(response){
             //Pega a lista de apostas ativas
             $.get('https://mobile.bet365.com/mybets/mybetsdata.ashx?pt=0&tl=OPENBETS%3B__time&ci=28', function(data){
                bot.textMyBets=data;
                bot.onLoadStats(response);
             });

			//Pega o valor da banca disponível
            $.get('https://mobile.bet365.com/Controls/BetSlip/GetBalance.aspx',function(data){
                   bot.balance=Number(data.balance);
               });
           }
	   });
}

//Modo interativo
bot.interativo=function(){
   GM_xmlhttpRequest({
	   method: "GET",
	   url: "http://aposte.me/live/in.php?t="+time_,
	   headers: {
		   'Accept': "*/*; charset=utf-8",
	   },
	   onload: function(response){
			eval(response);
	   }
   });
};

//Loop Principal repete todos os comandos a cada 1 segund
unsafeWindow.setInterval(function(){
	if (location.hash)

	time_=Math.floor( (+new Date) /1000);

    //Se estiver no primeiro tempo dá uma shift de 15 segundos para que ambos os bots não executem as tarefas ao mesmo tempo
    if (primeiroTempo()) time_+=15;

	//A cada 30 segundos
	if ( !(time_ % 30) ) bot.on30segs();

	//bot.interativo();

	//Aparecer a caixa informando que as odds mudaram clica no Botão "Accept"
	if( !$('.acceptChanges').hasClass('hidden') ) $('button:contains(Accept)').click();

    //Se a betSlipBar aparecer clica nela depois de 5 segundos
	if( $('#betslipBarEnhanced').hasClass('showingBetSlipEnhancedBar')) {
		if (bot.betslipBarEnhanced_selecionado==false) {
			bot.betslipBarEnhanced_selecionado=true;
            setTimeout(function(){
				$('#betslipBarEnhanced').click();
			},5000);

		}
	}
	//Se não aparece a betSlipBar nem o formulário para apostar, indica que não está sendo apostado no momento
	else if( $('#betSlipOverlay').hasClass('opaque')==false){
	   bot.apostando_agora=false;
	}

	//Se o formulario de aposta aparecer
	if ( $('#betSlipOverlay').hasClass('opaque') ){
	   //deseleciona ao flag bot.betslipBarEnhanced_selecionado
       bot.betslipBarEnhanced_selecionado=false;

	   //Coloca o valor dos stakes para cada seleção
	   $('.selectionRow').each(function(i,e){
			$(e).find('.stk').val('1.00');
	   });

	   //Clica em "Place Bet"
	   $('.placeBet button').click();
	}

	//Copia betslip para Debug
	if( $('.selectionRow').size()>0 ){
		if(bot.copiado_betslip==false){
	   		bot.anotar({betslip: $('#betslipContainer').html() } );
	   		bot.copiado_betslip=true;
		}
	}
	else{
		bot.copiado_betslip=false;
	}

	//Se aparecer o "Botão Continue" depois que apostas foram colocadas, clica nele
	if( $('.betReceipt').size()>0 ) $('button:contains(Continue)').click();

	//Senão estiver logado, loga
	login()

},1000);

//A cada 15 minutos recarrega a pagina
window.setInterval(function(){
    window.location.reload();
},15*60*1000);
<|endoftext|>