<commit_before>/**
 * Created by n on 12.12.2016.
 */
var GridFSBucket = require('mongodb').GridFSBucket;
var fs = require('fs');

var repository_core = function (connector) {

    var self = this;
    var _connector = connector;

    //payload extracts
    /**
     * _collectionName: string
     */
    var _collectionName = null; //CRUD [CRUD] COUNT AGGREGATE CREATE-INDEX UPLOAD-FILE DOWNLOAD-FILE
    /**
     * _document: {}
     */
    var _document = null;       //C--- [----] ----- --------- CREATE-INDEX ----------- -------------
    /**
     * _query: {}
     */
    var _query = null;          //-RUD [-RUD] COUNT --------- ------------ ----------- -------------
    /**
     * _update: {}
     */
    var _update = null;         //--U- [--U-] ----- --------- ------------ ----------- -------------
    /**
     * _options: {}
     */
    var _options = null;        //C-UD [C-UD] COUNT AGGREGATE CREATE-INDEX UPLOAD-FILE DOWNLOAD-FILE
    /**
     * _documentsList: []
     */
    var _documentsList = null;  //---- [C---] ----- --------- ------------ ----------- -------------
    /**
     * _cursorOptions: {
     *      project: {},
     *      skip: number,
     *      limit: number,
     *      sort: {},
     *      toArray: bool
     * }
     */
    var _cursorOptions = null;  //---- [-R--] ----- AGGREGATE ------------ ----------- -------------
    /**
     * _pipeline: []
     */
    var _pipeline = null;       //---- [----] ----- AGGREGATE ------------ ----------- -------------
    /**
     * _fileName: string
     */
    var _fileName = null;       //---- [----] ----- --------- ------------ UPLOAD-FILE -------------
    /**
     * _fileOptions: {}
     */
    var _fileOptions = null;    //---- [----] ----- --------- ------------ UPLOAD-FILE DOWNLOAD-FILE
    /**
     * _filePath: string
     */
    var _filePath = null;       //---- [----] ----- --------- ------------ UPLOAD-FILE -------------
    /**
     * _fileId: ObjectID
     */
    var _fileId = null;         //---- [----] ----- --------- ------------ ----------- DOWNLOAD-FILE

    //private functions
    var reconnect = function (func, payload, callback) {
        _connector.reconnect(function (err, res) {
            if (err) return callback(err, null);
            func(payload, callback);
        });
    };
    var payloadExtract = function (payload) {
        _collectionName = payload && payload.collectionName ? payload.collectionName : null;
        _document = payload && payload.document ? payload.document : null;
        _query = payload && payload.query ? payload.query : null;
        _update = payload && payload.update ? payload.update : null;
        _options = payload && payload.options ? payload.options : null;
        _documentsList = payload && payload.documentsList ? payload.documentsList : null;
        _cursorOptions = payload && payload.cursorOptions ? payload.cursorOptions : null;
        _pipeline = payload && payload.pipeline ? payload.pipeline : null;
        _fileName = payload && payload.fileName ? payload.fileName : null;
        _fileOptions = payload && payload.fileOptions ? payload.fileOptions : null;
        _filePath = payload && payload.filePath ? payload.filePath : null;
        _fileId = payload && payload.fileId ? payload.fileId : null;

    };
    var isDbConnectionProblem = function (err) {
        if (err && err.message && err.message.indexOf('topology was destroyed') != -1) {
            return true;
        }
        else if (err && err.message && err.message.indexOf('ECONNRESET') != -1) {
            return true;
        }
        return false;
    };

    //private functions
    var createOne = function (payload, callback) {

        payloadExtract(payload);

        if (!_collectionName || !_document) return callback('payload error', null);

        if (_connector.isConnected()) {

            var collection = _connector.db().collection(_collectionName);
            collection.insertOne(_document, _options, function (err, res) {
                if (err) {
                    if (isDbConnectionProblem(err)) {
                        reconnect(createOne, payload, callback);
                    }
                    else {
                        callback(err, null);
                    }
                }
                else {
                    callback(null, res);
                }
            });
        }
        else {
            reconnect(createOne, payload, callback);
        }
    };
    var readOne = function (payload, callback) {

        payloadExtract(payload);

        if (!_collectionName) return callback('payload error', null);

        if (_connector.isConnected()) {

            var collection = _connector.db().collection(_collectionName);
            collection.find(_query).limit(1).next(function (err, doc) {
                if (err) {
                    if (isDbConnectionProblem(err)) {
                        reconnect(readOne, payload, callback);
                    }
                    else {
                        callback(err, null);
                    }
                }
                else {
                    callback(null, doc);
                }
            });
        }
        else {
            reconnect(readOne, payload, callback);
        }
    };
    var updateOne = function (payload, callback) {

        payloadExtract(payload);

        if (!_collectionName) return callback('payload error', null);

        if (_connector.isConnected()) {

            var collection = _connector.db().collection(_collectionName);
            collection.updateOne(_query, _update, _options, function (err, res) {
                if (err) {
                    if (isDbConnectionProblem(err)) {
                        reconnect(updateOne, payload, callback);
                    }
                    else {
                        callback(err, null);
                    }
                }
                else {
                    callback(null, res);
                }
            });
        }
        else {
            reconnect(updateOne, payload, callback);
        }

    };
    var deleteOne = function (payload, callback) {

        payloadExtract(payload);

        if (!_collectionName) return callback('payload error', null);

        if (_connector.isConnected()) {

            var collection = _connector.db().collection(_collectionName);
            collection.updateOne(_query, _update, _options, function (err, res) {
                if (err) {
                    if (isDbConnectionProblem(err)) {
                        reconnect(deleteOne, payload, callback);
                    }
                    else {
                        callback(err, null);
                    }
                }
                else {
                    callback(null, res);
                }
            });
        }
        else {
            reconnect(deleteOne, payload, callback);
        }

    };
    var createMany = function (payload, callback) {

        payloadExtract(payload);

        if (!_collectionName || !_documentsList) return callback('payload error', null);

        if (_connector.isConnected()) {

            var collection = _connector.db().collection(_collectionName);
            collection.insertMany(_documentsList, _options, function (err, res) {
                if (err) {
                    if (isDbConnectionProblem(err)) {
                        reconnect(createMany, payload, callback);
                    }
                    else {
                        callback(err, null);
                    }
                }
                else {
                    callback(null, res);
                }
            });
        }
        else {
            reconnect(createMany, payload, callback);
        }

    };
    var readMany = function (payload, callback) {

        payloadExtract(payload);

        if (!_collectionName) return callback('payload error', null);

        if (_connector.isConnected()) {

            var collection = _connector.db().collection(_collectionName);
            var cursor = collection.find(_query);
            if (_cursorOptions && _cursorOptions.project) cursor = cursor.project(_cursorOptions.project);
            if (_cursorOptions && _cursorOptions.skip) cursor = cursor.skip(_cursorOptions.skip);
            if (_cursorOptions && _cursorOptions.limit) cursor = cursor.limit(_cursorOptions.limit);
            if (_cursorOptions && _cursorOptions.sort) cursor = cursor.sort(_cursorOptions.sort);
            if (_cursorOptions && _cursorOptions.toArray) {
                cursor.toArray(function (err, docs) {
                    if (err) {
                        if (isDbConnectionProblem(err)) {
                            reconnect(readMany, payload, callback);
                        }
                        else {
                            callback(err, null);
                        }
                    }
                    else {
                        callback(null, docs);
                    }
                });
            }
            else {
                callback(null, cursor);
            }

        }
        else {
            reconnect(readMany, payload, callback);
        }

    };
    var updateMany = function (payload, callback) {

        payloadExtract(payload);

        if (!_collectionName) return callback('payload error', null);

        if (_connector.isConnected()) {

            var collection = _connector.db().collection(_collectionName);
            collection.updateMany(_query, _update, _options, function (err, res) {
                if (err) {
                    if (isDbConnectionProblem(err)) {
                        reconnect(updateMany, payload, callback);
                    }
                    else {
                        callback(err, null);
                    }
                }
                else {
                    callback(null, res);
                }
            });
        }
        else {
            reconnect(updateMany, payload, callback);
        }

    };
    var deleteMany = function (payload, callback) {

        payloadExtract(payload);

        if (!_collectionName) return callback('payload error', null);

        if (_connector.isConnected()) {

            var collection = _connector.db().collection(_collectionName);
            collection.updateMany(_query, _update, _options, function (err, res) {
                if (err) {
                    if (isDbConnectionProblem(err)) {
                        reconnect(deleteMany, payload, callback);
                    }
                    else {
                        callback(err, null);
                    }
                }
                else {
                    callback(null, res);
                }
            });
        }
        else {
            reconnect(deleteMany, payload, callback);
        }

    };
    var aggregate = function (payload, callback) {

        payloadExtract(payload);

        if (!_collectionName || !_pipeline) return callback('payload error', null);

        if (_connector.isConnected()) {

            var collection = _connector.db().collection(_collectionName);
            var cursor = collection.aggregate(_pipeline, _options);
            if (_cursorOptions && _cursorOptions.toArray) {
                cursor.toArray(function (err, docs) {
                    if (err) {
                        if (isDbConnectionProblem(err)) {
                            reconnect(aggregate, payload, callback);
                        }
                        else {
                            callback(err, null);
                        }
                    }
                    else {
                        callback(null, docs);
                    }
                });
            }
            else {
                callback(null, cursor);
            }

        }
        else {
            reconnect(aggregate, payload, callback);
        }

    };
    var count = function (payload, callback) {

        payloadExtract(payload);

        if (!_collectionName) return callback('payload error', null);

        if (_connector.isConnected()) {

            var collection = _connector.db().collection(_collectionName);
            collection.count(_query, _options, function (err, res) {
                if (err) {
                    if (isDbConnectionProblem(err)) {
                        reconnect(count, payload, callback);
                    }
                    else {
                        callback(err, null);
                    }
                }
                else {
                    callback(null, res);
                }
            });
        }
        else {
            reconnect(count, payload, callback);
        }

    };
    var createIndex = function (payload, callback) {

        payloadExtract(payload);

        if (!_collectionName || !_document) return callback('payload error', null);

        if (_connector.isConnected()) {

            var collection = _connector.db().collection(_collectionName);
            collection.createIndex(_document, _options, function (err, res) {
                if (err) {
                    if (isDbConnectionProblem(err)) {
                        reconnect(createIndex, payload, callback);
                    }
                    else {
                        callback(err, null);
                    }
                }
                else {
                    callback(null, res);
                }
            });
        }
        else {
            reconnect(createIndex, payload, callback);
        }

    };
    var uploadFile = function (payload, callback) {

        payloadExtract(payload);

        if (!_filePath || !fs.existsSync(_filePath)) return callback('payload error', null);

        if (_connector.isConnected()) {

            var bucket = new GridFSBucket(_connector.db(), _options);
            var uploadStream = bucket.openUploadStream(_fileName, _fileOptions);
            var readStream = fs.createReadStream(_filePath);

            readStream.pipe(uploadStream)
                .on('error', function (err) {
                    if (isDbConnectionProblem(err)) {
                        reconnect(uploadFile, payload, callback);
                    }
                    else {
                        callback(err, null);
                    }
                })
                .on('finish', function () {
                    callback(null, uploadStream.id);
                });

        }
        else {
            reconnect(uploadFile, payload, callback);
        }

    };
    var downloadFile = function (payload, callback) {

        payloadExtract(payload);

        if (!_fileId) return callback('payload error', null);

        if (_connector.isConnected()) {

            var bucket = new GridFSBucket(_connector.db(), _options);
            var downloadStream = bucket.openDownloadStream(_fileId, _fileOptions);

            callback(null, downloadStream);

        }
        else {
            reconnect(downloadFile, payload, callback);
        }

    };

    //public functions
    this.createOne = function (payload, callback) {
        if (payload && payload.document && !payload.document._id) {
            if (!payload.options) {
                payload.options = {};
            }
            payload.options.forceServerObjectId = true;
        }
        createOne(payload, callback);
    };
    this.readOne = function (payload, callback) {
        readOne(payload, callback);
    };
    this.updateOne = function (payload, callback) {
        updateOne(payload, callback);
    };
    this.deleteOne = function (payload, callback) {
        if (payload) {
            payload.update = {};
            payload.update.$set = {};
            payload.update.$set.isDeleted = true;
        }
        deleteOne(payload, callback);
    };
    this.createMany = function (payload, callback) {
        createMany(payload, callback);
    };
    this.readMany = function (payload, callback) {
        if (payload) {
            if (!payload.cursorOptions) {
                payload.cursorOptions = {};
            }
            if (!payload.cursorOptions.limit && payload.cursorOptions.limit != 0 && payload.cursorOptions.toArray) {
                payload.cursorOptions.limit = 100;
            }
        }
        readMany(payload, callback);
    };
    this.updateMany = function (payload, callback) {
        updateMany(payload, callback);
    };
    this.deleteMany = function (payload, callback) {
        if (payload) {
            payload.update = {};
            payload.update.$set = {};
            payload.update.$set.isDeleted = true;
        }
        deleteMany(payload, callback);
    };
    this.aggregate = function (payload, callback) {
        if (payload) {
            if (!payload.options) {
                payload.options = {};
            }
            if (!payload.options.cursor) {
                payload.options.cursor = {};
            }
        }
        aggregate(payload, callback);
    };
    this.count = function (payload, callback) {
        count(payload, callback);
    };
    this.createIndex = function (payload, callback) {
        createIndex(payload, callback);
    };
    this.uploadFile = function (payload, callback) {
        uploadFile(payload, callback);
    };
    this.downloadFile = function (payload, callback) {
        downloadFile(payload, callback);
    };

};

module.exports = repository_core;

<commit_msg>docs fix<commit_after>/**
 * Created by n on 12.12.2016.
 */
var GridFSBucket = require('mongodb').GridFSBucket;
var fs = require('fs');

var repository_core = function (connector) {

    var self = this;
    var _connector = connector;

    //payload extracts
    /**
     * _collectionName: string
     */
    var _collectionName = null; //CRUD [CRUD] COUNT AGGREGATE CREATE-INDEX ----------- -------------
    /**
     * _document: {}
     */
    var _document = null;       //C--- [----] ----- --------- CREATE-INDEX ----------- -------------
    /**
     * _query: {}
     */
    var _query = null;          //-RUD [-RUD] COUNT --------- ------------ ----------- -------------
    /**
     * _update: {}
     */
    var _update = null;         //--U- [--U-] ----- --------- ------------ ----------- -------------
    /**
     * _options: {}
     */
    var _options = null;        //C-UD [C-UD] COUNT AGGREGATE CREATE-INDEX UPLOAD-FILE DOWNLOAD-FILE
    /**
     * _documentsList: []
     */
    var _documentsList = null;  //---- [C---] ----- --------- ------------ ----------- -------------
    /**
     * _cursorOptions: {
     *      project: {},
     *      skip: number,
     *      limit: number,
     *      sort: {},
     *      toArray: bool
     * }
     */
    var _cursorOptions = null;  //---- [-R--] ----- AGGREGATE ------------ ----------- -------------
    /**
     * _pipeline: []
     */
    var _pipeline = null;       //---- [----] ----- AGGREGATE ------------ ----------- -------------
    /**
     * _fileName: string
     */
    var _fileName = null;       //---- [----] ----- --------- ------------ UPLOAD-FILE -------------
    /**
     * _fileOptions: {}
     */
    var _fileOptions = null;    //---- [----] ----- --------- ------------ UPLOAD-FILE DOWNLOAD-FILE
    /**
     * _filePath: string
     */
    var _filePath = null;       //---- [----] ----- --------- ------------ UPLOAD-FILE -------------
    /**
     * _fileId: ObjectID
     */
    var _fileId = null;         //---- [----] ----- --------- ------------ ----------- DOWNLOAD-FILE

    //private functions
    var reconnect = function (func, payload, callback) {
        _connector.reconnect(function (err, res) {
            if (err) return callback(err, null);
            func(payload, callback);
        });
    };
    var payloadExtract = function (payload) {
        _collectionName = payload && payload.collectionName ? payload.collectionName : null;
        _document = payload && payload.document ? payload.document : null;
        _query = payload && payload.query ? payload.query : null;
        _update = payload && payload.update ? payload.update : null;
        _options = payload && payload.options ? payload.options : null;
        _documentsList = payload && payload.documentsList ? payload.documentsList : null;
        _cursorOptions = payload && payload.cursorOptions ? payload.cursorOptions : null;
        _pipeline = payload && payload.pipeline ? payload.pipeline : null;
        _fileName = payload && payload.fileName ? payload.fileName : null;
        _fileOptions = payload && payload.fileOptions ? payload.fileOptions : null;
        _filePath = payload && payload.filePath ? payload.filePath : null;
        _fileId = payload && payload.fileId ? payload.fileId : null;

    };
    var isDbConnectionProblem = function (err) {
        if (err && err.message && err.message.indexOf('topology was destroyed') != -1) {
            return true;
        }
        else if (err && err.message && err.message.indexOf('ECONNRESET') != -1) {
            return true;
        }
        return false;
    };

    //private functions
    var createOne = function (payload, callback) {

        payloadExtract(payload);

        if (!_collectionName || !_document) return callback('payload error', null);

        if (_connector.isConnected()) {

            var collection = _connector.db().collection(_collectionName);
            collection.insertOne(_document, _options, function (err, res) {
                if (err) {
                    if (isDbConnectionProblem(err)) {
                        reconnect(createOne, payload, callback);
                    }
                    else {
                        callback(err, null);
                    }
                }
                else {
                    callback(null, res);
                }
            });
        }
        else {
            reconnect(createOne, payload, callback);
        }
    };
    var readOne = function (payload, callback) {

        payloadExtract(payload);

        if (!_collectionName) return callback('payload error', null);

        if (_connector.isConnected()) {

            var collection = _connector.db().collection(_collectionName);
            collection.find(_query).limit(1).next(function (err, doc) {
                if (err) {
                    if (isDbConnectionProblem(err)) {
                        reconnect(readOne, payload, callback);
                    }
                    else {
                        callback(err, null);
                    }
                }
                else {
                    callback(null, doc);
                }
            });
        }
        else {
            reconnect(readOne, payload, callback);
        }
    };
    var updateOne = function (payload, callback) {

        payloadExtract(payload);

        if (!_collectionName) return callback('payload error', null);

        if (_connector.isConnected()) {

            var collection = _connector.db().collection(_collectionName);
            collection.updateOne(_query, _update, _options, function (err, res) {
                if (err) {
                    if (isDbConnectionProblem(err)) {
                        reconnect(updateOne, payload, callback);
                    }
                    else {
                        callback(err, null);
                    }
                }
                else {
                    callback(null, res);
                }
            });
        }
        else {
            reconnect(updateOne, payload, callback);
        }

    };
    var deleteOne = function (payload, callback) {

        payloadExtract(payload);

        if (!_collectionName) return callback('payload error', null);

        if (_connector.isConnected()) {

            var collection = _connector.db().collection(_collectionName);
            collection.updateOne(_query, _update, _options, function (err, res) {
                if (err) {
                    if (isDbConnectionProblem(err)) {
                        reconnect(deleteOne, payload, callback);
                    }
                    else {
                        callback(err, null);
                    }
                }
                else {
                    callback(null, res);
                }
            });
        }
        else {
            reconnect(deleteOne, payload, callback);
        }

    };
    var createMany = function (payload, callback) {

        payloadExtract(payload);

        if (!_collectionName || !_documentsList) return callback('payload error', null);

        if (_connector.isConnected()) {

            var collection = _connector.db().collection(_collectionName);
            collection.insertMany(_documentsList, _options, function (err, res) {
                if (err) {
                    if (isDbConnectionProblem(err)) {
                        reconnect(createMany, payload, callback);
                    }
                    else {
                        callback(err, null);
                    }
                }
                else {
                    callback(null, res);
                }
            });
        }
        else {
            reconnect(createMany, payload, callback);
        }

    };
    var readMany = function (payload, callback) {

        payloadExtract(payload);

        if (!_collectionName) return callback('payload error', null);

        if (_connector.isConnected()) {

            var collection = _connector.db().collection(_collectionName);
            var cursor = collection.find(_query);
            if (_cursorOptions && _cursorOptions.project) cursor = cursor.project(_cursorOptions.project);
            if (_cursorOptions && _cursorOptions.skip) cursor = cursor.skip(_cursorOptions.skip);
            if (_cursorOptions && _cursorOptions.limit) cursor = cursor.limit(_cursorOptions.limit);
            if (_cursorOptions && _cursorOptions.sort) cursor = cursor.sort(_cursorOptions.sort);
            if (_cursorOptions && _cursorOptions.toArray) {
                cursor.toArray(function (err, docs) {
                    if (err) {
                        if (isDbConnectionProblem(err)) {
                            reconnect(readMany, payload, callback);
                        }
                        else {
                            callback(err, null);
                        }
                    }
                    else {
                        callback(null, docs);
                    }
                });
            }
            else {
                callback(null, cursor);
            }

        }
        else {
            reconnect(readMany, payload, callback);
        }

    };
    var updateMany = function (payload, callback) {

        payloadExtract(payload);

        if (!_collectionName) return callback('payload error', null);

        if (_connector.isConnected()) {

            var collection = _connector.db().collection(_collectionName);
            collection.updateMany(_query, _update, _options, function (err, res) {
                if (err) {
                    if (isDbConnectionProblem(err)) {
                        reconnect(updateMany, payload, callback);
                    }
                    else {
                        callback(err, null);
                    }
                }
                else {
                    callback(null, res);
                }
            });
        }
        else {
            reconnect(updateMany, payload, callback);
        }

    };
    var deleteMany = function (payload, callback) {

        payloadExtract(payload);

        if (!_collectionName) return callback('payload error', null);

        if (_connector.isConnected()) {

            var collection = _connector.db().collection(_collectionName);
            collection.updateMany(_query, _update, _options, function (err, res) {
                if (err) {
                    if (isDbConnectionProblem(err)) {
                        reconnect(deleteMany, payload, callback);
                    }
                    else {
                        callback(err, null);
                    }
                }
                else {
                    callback(null, res);
                }
            });
        }
        else {
            reconnect(deleteMany, payload, callback);
        }

    };
    var aggregate = function (payload, callback) {

        payloadExtract(payload);

        if (!_collectionName || !_pipeline) return callback('payload error', null);

        if (_connector.isConnected()) {

            var collection = _connector.db().collection(_collectionName);
            var cursor = collection.aggregate(_pipeline, _options);
            if (_cursorOptions && _cursorOptions.toArray) {
                cursor.toArray(function (err, docs) {
                    if (err) {
                        if (isDbConnectionProblem(err)) {
                            reconnect(aggregate, payload, callback);
                        }
                        else {
                            callback(err, null);
                        }
                    }
                    else {
                        callback(null, docs);
                    }
                });
            }
            else {
                callback(null, cursor);
            }

        }
        else {
            reconnect(aggregate, payload, callback);
        }

    };
    var count = function (payload, callback) {

        payloadExtract(payload);

        if (!_collectionName) return callback('payload error', null);

        if (_connector.isConnected()) {

            var collection = _connector.db().collection(_collectionName);
            collection.count(_query, _options, function (err, res) {
                if (err) {
                    if (isDbConnectionProblem(err)) {
                        reconnect(count, payload, callback);
                    }
                    else {
                        callback(err, null);
                    }
                }
                else {
                    callback(null, res);
                }
            });
        }
        else {
            reconnect(count, payload, callback);
        }

    };
    var createIndex = function (payload, callback) {

        payloadExtract(payload);

        if (!_collectionName || !_document) return callback('payload error', null);

        if (_connector.isConnected()) {

            var collection = _connector.db().collection(_collectionName);
            collection.createIndex(_document, _options, function (err, res) {
                if (err) {
                    if (isDbConnectionProblem(err)) {
                        reconnect(createIndex, payload, callback);
                    }
                    else {
                        callback(err, null);
                    }
                }
                else {
                    callback(null, res);
                }
            });
        }
        else {
            reconnect(createIndex, payload, callback);
        }

    };
    var uploadFile = function (payload, callback) {

        payloadExtract(payload);

        if (!_filePath || !fs.existsSync(_filePath)) return callback('payload error', null);

        if (_connector.isConnected()) {

            var bucket = new GridFSBucket(_connector.db(), _options);
            var uploadStream = bucket.openUploadStream(_fileName, _fileOptions);
            var readStream = fs.createReadStream(_filePath);

            readStream.pipe(uploadStream)
                .on('error', function (err) {
                    if (isDbConnectionProblem(err)) {
                        reconnect(uploadFile, payload, callback);
                    }
                    else {
                        callback(err, null);
                    }
                })
                .on('finish', function () {
                    callback(null, uploadStream.id);
                });

        }
        else {
            reconnect(uploadFile, payload, callback);
        }

    };
    var downloadFile = function (payload, callback) {

        payloadExtract(payload);

        if (!_fileId) return callback('payload error', null);

        if (_connector.isConnected()) {

            var bucket = new GridFSBucket(_connector.db(), _options);
            var downloadStream = bucket.openDownloadStream(_fileId, _fileOptions);

            callback(null, downloadStream);

        }
        else {
            reconnect(downloadFile, payload, callback);
        }

    };

    //public functions
    this.createOne = function (payload, callback) {
        if (payload && payload.document && !payload.document._id) {
            if (!payload.options) {
                payload.options = {};
            }
            payload.options.forceServerObjectId = true;
        }
        createOne(payload, callback);
    };
    this.readOne = function (payload, callback) {
        readOne(payload, callback);
    };
    this.updateOne = function (payload, callback) {
        updateOne(payload, callback);
    };
    this.deleteOne = function (payload, callback) {
        if (payload) {
            payload.update = {};
            payload.update.$set = {};
            payload.update.$set.isDeleted = true;
        }
        deleteOne(payload, callback);
    };
    this.createMany = function (payload, callback) {
        createMany(payload, callback);
    };
    this.readMany = function (payload, callback) {
        if (payload) {
            if (!payload.cursorOptions) {
                payload.cursorOptions = {};
            }
            if (!payload.cursorOptions.limit && payload.cursorOptions.limit != 0 && payload.cursorOptions.toArray) {
                payload.cursorOptions.limit = 100;
            }
        }
        readMany(payload, callback);
    };
    this.updateMany = function (payload, callback) {
        updateMany(payload, callback);
    };
    this.deleteMany = function (payload, callback) {
        if (payload) {
            payload.update = {};
            payload.update.$set = {};
            payload.update.$set.isDeleted = true;
        }
        deleteMany(payload, callback);
    };
    this.aggregate = function (payload, callback) {
        if (payload) {
            if (!payload.options) {
                payload.options = {};
            }
            if (!payload.options.cursor) {
                payload.options.cursor = {};
            }
        }
        aggregate(payload, callback);
    };
    this.count = function (payload, callback) {
        count(payload, callback);
    };
    this.createIndex = function (payload, callback) {
        createIndex(payload, callback);
    };
    this.uploadFile = function (payload, callback) {
        uploadFile(payload, callback);
    };
    this.downloadFile = function (payload, callback) {
        downloadFile(payload, callback);
    };

};

module.exports = repository_core;

<|endoftext|>


<commit_before>(function() {
  slMapClickHandler = function(infobox) {
    // Private attributes

    var map_click_handler = this;

    /**
     * The OpenLayers.Geometry object of the circle.
     * @type {Object}
     */
    var circle = null;

    /**
     * Stores the state if the infobox.
     * @type {Bool}
     */
    var visible = false;

    // Public attributes and functions

    /**
     * @expose
     * Click handler which shows a info box at the click location.
     */
    map_click_handler.trigger = function(e) {
      // do nothing if this is visible, let the event handler close the box.
      if (visible) return;

      // create bounding box in map coordinates around mouse cursor
      var pixel = new OpenLayers.Pixel(e.layerX, e.layerY);
      var clickTolerance = 15;
      var llPx = pixel.add(-clickTolerance / 2, clickTolerance / 2);
      var urPx = pixel.add(clickTolerance / 2, -clickTolerance / 2);
      var ll = map.getLonLatFromPixel(llPx);
      var ur = map.getLonLatFromPixel(urPx);
      var loc = map.getLonLatFromPixel(pixel);

      var loc_wgs84 = loc.clone()
          .transform(map.getProjectionObject(), WGS84_PROJ);
      var lon = loc_wgs84.lon,
          lat = loc_wgs84.lat;

      infobox.stop(true, true); // remove any running delays or animations
      infobox.empty();

      // search for a aircraft position within the bounding box
      var nearest = searchForPlane(
          new OpenLayers.Bounds(ll.lon, ll.lat, ur.lon, ur.lat),
          loc,
          clickTolerance);

      if (nearest !== null) {
        var index = nearest.from;
        var flight = flights[nearest.fid];
        var dx = nearest.along;

        lon = flight.lonlat[index].lon +
            (flight.lonlat[index + 1].lon - flight.lonlat[index].lon) * dx;
        lat = flight.lonlat[index].lat +
            (flight.lonlat[index + 1].lat - flight.lonlat[index].lat) * dx;
        var time = flight.t[index] +
            (flight.t[index + 1] - flight.t[index]) * dx;

        // flight info
        var flight_info = flightInfo(flight);
        infobox.append(flight_info);

        // near flights link
        var get_near_flights = nearFlights(lon, lat, time, flight);
        infobox.append(get_near_flights);
      }

      // airspace info
      var get_airspace_info = airspaceInfo(lon, lat);
      infobox.append(get_airspace_info);

      // general events

      map.events.register('move', this, function(e) {
        if (e.object.getExtent().scale(2).containsLonLat(infobox.latlon)) {
          var pixel = e.object.getPixelFromLonLat(infobox.latlon);
          infobox.css('left', (pixel.x + 15) + 'px');
          infobox.css('top', (pixel.y - infobox.height() / 2) + 'px');
        } else {
          infobox.hide();
          hideCircle(0);
          visible = false;
        }
      });

      // hide box when clicked outside
      // use OL click event which doesn't get fired on panning
      map.events.register('click', this, function(e) {
        var outside = true;

        infobox.children().each(function() {
          if ($(this).find(e.target).length !== 0) outside = false;
        });

        if (outside) {
          infobox.hide();
          hideCircle(0);
          visible = false;
        }
      });

      infobox.latlon = new OpenLayers.LonLat(lon, lat)
          .transform(WGS84_PROJ, map.getProjectionObject());

      pixel = e.object.getPixelFromLonLat(infobox.latlon);
      infobox.css('left', (pixel.x + 15) + 'px');
      infobox.css('top', (pixel.y - infobox.height() / 2) + 'px');

      infobox.show();
      showCircle(lon, lat);

      visible = true;

      return false; // stop bubbeling
    };

    // Private functions

    function flightInfo(flight) {
      return $(
          '' +
          (flight.additional && flight.additional['registration'] || '') +
          ''
      );
    };

    function nearFlights(lon, lat, time, flight) {
      var get_near_flights = $(
          '
' +
          'Load nearby flights' +
          '
'
          );

      get_near_flights.on('click touchend', function(e) {
        infobox.hide();
        getNearFlights(lon, lat, time, flight);
        visible = false;
      });

      return get_near_flights;
    };

    function airspaceInfo(lon, lat) {
      var get_airspace_info = $(
          '
' +
          'Get airspace info' +
          '
'
          );

      get_airspace_info.on('click touchend', function(e) {
        getAirspaceInfo(lon, lat);
      });

      return get_airspace_info;
    };

    /**
     * Show a circle at the clicked position
     *
     * @param {Number} lon Longitude.
     * @param {Number} lat Latitude.
     */
    function showCircle(lon, lat) {
      // first, calculate how many map units are 1000 meters. This is
      // approximate, but close enough for our purpose. In google maps
      // (and openstreetmap) spherical projection (aka EPSG:900913 or
      // EPSG:3857), one meter at the equator is exactly one unit.
      // Cut off at 85 deg.
      var distance_deg = 1000 / Math.cos(Math.PI / 180 *
          Math.min(Math.abs(lat, 85)));

      var point = new OpenLayers.Geometry.Point(lon, lat)
                  .transform(WGS84_PROJ, map.getProjectionObject());

      circle = new OpenLayers.Feature.Vector(
          new OpenLayers.Geometry.Polygon.createRegularPolygon(point,
              distance_deg, 40, 0));

      // draw this circle and fade the inner fill within 500ms
      circle.renderIntent = 'nearestCircle';

      map.getLayersByName('Flight')[0].addFeatures(circle);

      // escape points in the id, see
      // http://docs.jquery.com/Frequently_Asked_Questions#How_do_I_select_an_
      // element_by_an_ID_that_has_characters_used_in_CSS_notation.3F
      var circle_id = '#' + circle.geometry.id.replace(/(:|\.)/g, '\\$1');
      $(circle_id).animate({fillOpacity: 0}, 500);
    };

    /**
     * Hides the search circle
     *
     * @param {Integer} duration Fade duration.
     */
    function hideCircle(duration) {
      if (circle === null) return;

      var circle_id = '#' + circle.geometry.id.replace(/(:|\.)/g, '\\$1');
      // fade circle out and remove it from layer
      $(circle_id).fadeOut(duration, function() {
        // check if circle still exists, because it might got deleted before
        // the animation was done.
        if (circle !== null) {
          map.getLayersByName('Flight')[0].destroyFeatures(circle);
          circle = null;
        }
      });
    };

    /**
     * Request near flights via ajax
     *
     * @param {Number} lon Longitude.
     * @param {Number} lat Latitude.
     * @param {Number} time Time.
     * @param {Object} flight Flight.
     */
    function getNearFlights(lon, lat, time, flight) {
      $.ajax('/flights/' + flight.sfid + '/near?lon=' + lon +
          '&lat=' + lat + '&time=' + time, {
            success: function(data) {
              for (var i = 0; i < data.flights.length; ++i) {
                // skip retrieved flight if already on map
                var next = false;
                for (var fid = 0; fid < flights.length; ++fid)
                  if (flights[fid].sfid == data.flights[i].sfid) next = true;
                  if (next) continue;

                  var flight_id = addFlight(data.flights[i].sfid,
                      data.flights[i].encoded.points,
                      data.flights[i].encoded.levels,
                      data.flights[i].num_levels,
                      data.flights[i].barogram_t,
                      data.flights[i].barogram_h,
                      data.flights[i].enl,
                      data.flights[i].zoom_levels,
                      data.flights[i].contests,
                      data.flights[i].additional);
              }
            },
            complete: function() {
              hideCircle(1000);
            }
          });
    };

    /**
     * Request airspace informations via ajax
     *
     * @param {Number} lon Longitude.
     * @param {Number} lat Latitude.
     */
    function getAirspaceInfo(lon, lat) {
      var req = $.ajax('/airspace/info?lon=' + lon + '&lat=' + lat);

      req.done(function(data) {
        if (data.airspaces && data.airspaces.length != 0)
          showAirspaceData(data.airspaces);
        else
          showAirspaceData(null);
      });

      req.fail(function() {
        showAirspaceData(null);
      });
    };

    /**
     * Show airspace data in infobox
     *
     * @param {Object} data Airspace data.
     */
    function showAirspaceData(data) {
      if (!visible) return; // do nothing if infobox is closed already

      infobox.empty();
      var item = $('

');

      if (!data) {
        item.html('No airspace data retrieved for this location');

        infobox.delay(1500).fadeOut(1000, function() {
          infobox.hide();
          visible = false;
        });

        hideCircle(1000);

      } else {
        var table = $('

');

        table.append($(
            '

' +
            'Name	' +
            'Class	' +
            'Base	' +
            'Top	' +
            '

'
            ));

        var table_body = $('
</tbody');

        for (var i = 0; i < data.length; ++i) {
          table_body.append($(
              '
' +
              '' + data[i].name + '	' +
              '' + data[i].airspace_class + '	' +
              '' + data[i].base + '	' +
              '' + data[i].top + '	' +
              '
'
              ));
        }

        table.append(table_body);
        item.append(table);
      }

      infobox.append(item);

      pixel = map.getPixelFromLonLat(infobox.latlon);
      infobox.css('left', (pixel.x + 15) + 'px');
      infobox.css('top', (pixel.y - infobox.height() / 2) + 'px');
    };

  };
})();
<commit_msg>map-click-handler.js: replace jquery.ajax callback settings by better readable™ methods<commit_after>(function() {
  slMapClickHandler = function(infobox) {
    // Private attributes

    var map_click_handler = this;

    /**
     * The OpenLayers.Geometry object of the circle.
     * @type {Object}
     */
    var circle = null;

    /**
     * Stores the state if the infobox.
     * @type {Bool}
     */
    var visible = false;

    // Public attributes and functions

    /**
     * @expose
     * Click handler which shows a info box at the click location.
     */
    map_click_handler.trigger = function(e) {
      // do nothing if this is visible, let the event handler close the box.
      if (visible) return;

      // create bounding box in map coordinates around mouse cursor
      var pixel = new OpenLayers.Pixel(e.layerX, e.layerY);
      var clickTolerance = 15;
      var llPx = pixel.add(-clickTolerance / 2, clickTolerance / 2);
      var urPx = pixel.add(clickTolerance / 2, -clickTolerance / 2);
      var ll = map.getLonLatFromPixel(llPx);
      var ur = map.getLonLatFromPixel(urPx);
      var loc = map.getLonLatFromPixel(pixel);

      var loc_wgs84 = loc.clone()
          .transform(map.getProjectionObject(), WGS84_PROJ);
      var lon = loc_wgs84.lon,
          lat = loc_wgs84.lat;

      infobox.stop(true, true); // remove any running delays or animations
      infobox.empty();

      // search for a aircraft position within the bounding box
      var nearest = searchForPlane(
          new OpenLayers.Bounds(ll.lon, ll.lat, ur.lon, ur.lat),
          loc,
          clickTolerance);

      if (nearest !== null) {
        var index = nearest.from;
        var flight = flights[nearest.fid];
        var dx = nearest.along;

        lon = flight.lonlat[index].lon +
            (flight.lonlat[index + 1].lon - flight.lonlat[index].lon) * dx;
        lat = flight.lonlat[index].lat +
            (flight.lonlat[index + 1].lat - flight.lonlat[index].lat) * dx;
        var time = flight.t[index] +
            (flight.t[index + 1] - flight.t[index]) * dx;

        // flight info
        var flight_info = flightInfo(flight);
        infobox.append(flight_info);

        // near flights link
        var get_near_flights = nearFlights(lon, lat, time, flight);
        infobox.append(get_near_flights);
      }

      // airspace info
      var get_airspace_info = airspaceInfo(lon, lat);
      infobox.append(get_airspace_info);

      // general events

      map.events.register('move', this, function(e) {
        if (e.object.getExtent().scale(2).containsLonLat(infobox.latlon)) {
          var pixel = e.object.getPixelFromLonLat(infobox.latlon);
          infobox.css('left', (pixel.x + 15) + 'px');
          infobox.css('top', (pixel.y - infobox.height() / 2) + 'px');
        } else {
          infobox.hide();
          hideCircle(0);
          visible = false;
        }
      });

      // hide box when clicked outside
      // use OL click event which doesn't get fired on panning
      map.events.register('click', this, function(e) {
        var outside = true;

        infobox.children().each(function() {
          if ($(this).find(e.target).length !== 0) outside = false;
        });

        if (outside) {
          infobox.hide();
          hideCircle(0);
          visible = false;
        }
      });

      infobox.latlon = new OpenLayers.LonLat(lon, lat)
          .transform(WGS84_PROJ, map.getProjectionObject());

      pixel = e.object.getPixelFromLonLat(infobox.latlon);
      infobox.css('left', (pixel.x + 15) + 'px');
      infobox.css('top', (pixel.y - infobox.height() / 2) + 'px');

      infobox.show();
      showCircle(lon, lat);

      visible = true;

      return false; // stop bubbeling
    };

    // Private functions

    function flightInfo(flight) {
      return $(
          '' +
          (flight.additional && flight.additional['registration'] || '') +
          ''
      );
    };

    function nearFlights(lon, lat, time, flight) {
      var get_near_flights = $(
          '
' +
          'Load nearby flights' +
          '
'
          );

      get_near_flights.on('click touchend', function(e) {
        infobox.hide();
        getNearFlights(lon, lat, time, flight);
        visible = false;
      });

      return get_near_flights;
    };

    function airspaceInfo(lon, lat) {
      var get_airspace_info = $(
          '
' +
          'Get airspace info' +
          '
'
          );

      get_airspace_info.on('click touchend', function(e) {
        getAirspaceInfo(lon, lat);
      });

      return get_airspace_info;
    };

    /**
     * Show a circle at the clicked position
     *
     * @param {Number} lon Longitude.
     * @param {Number} lat Latitude.
     */
    function showCircle(lon, lat) {
      // first, calculate how many map units are 1000 meters. This is
      // approximate, but close enough for our purpose. In google maps
      // (and openstreetmap) spherical projection (aka EPSG:900913 or
      // EPSG:3857), one meter at the equator is exactly one unit.
      // Cut off at 85 deg.
      var distance_deg = 1000 / Math.cos(Math.PI / 180 *
          Math.min(Math.abs(lat, 85)));

      var point = new OpenLayers.Geometry.Point(lon, lat)
                  .transform(WGS84_PROJ, map.getProjectionObject());

      circle = new OpenLayers.Feature.Vector(
          new OpenLayers.Geometry.Polygon.createRegularPolygon(point,
              distance_deg, 40, 0));

      // draw this circle and fade the inner fill within 500ms
      circle.renderIntent = 'nearestCircle';

      map.getLayersByName('Flight')[0].addFeatures(circle);

      // escape points in the id, see
      // http://docs.jquery.com/Frequently_Asked_Questions#How_do_I_select_an_
      // element_by_an_ID_that_has_characters_used_in_CSS_notation.3F
      var circle_id = '#' + circle.geometry.id.replace(/(:|\.)/g, '\\$1');
      $(circle_id).animate({fillOpacity: 0}, 500);
    };

    /**
     * Hides the search circle
     *
     * @param {Integer} duration Fade duration.
     */
    function hideCircle(duration) {
      if (circle === null) return;

      var circle_id = '#' + circle.geometry.id.replace(/(:|\.)/g, '\\$1');
      // fade circle out and remove it from layer
      $(circle_id).fadeOut(duration, function() {
        // check if circle still exists, because it might got deleted before
        // the animation was done.
        if (circle !== null) {
          map.getLayersByName('Flight')[0].destroyFeatures(circle);
          circle = null;
        }
      });
    };

    /**
     * Request near flights via ajax
     *
     * @param {Number} lon Longitude.
     * @param {Number} lat Latitude.
     * @param {Number} time Time.
     * @param {Object} flight Flight.
     */
    function getNearFlights(lon, lat, time, flight) {
      var req = $.ajax('/flights/' + flight.sfid + '/near?lon=' + lon +
          '&lat=' + lat + '&time=' + time);

      req.done(function(data) {
        for (var i = 0; i < data.flights.length; ++i) {
          // skip retrieved flight if already on map
          var next = false;
          for (var fid = 0; fid < flights.length; ++fid) {
            if (flights[fid].sfid == data.flights[i].sfid) next = true;
          }

          if (next) continue;

          var flight_id = addFlight(data.flights[i].sfid,
              data.flights[i].encoded.points,
              data.flights[i].encoded.levels,
              data.flights[i].num_levels,
              data.flights[i].barogram_t,
              data.flights[i].barogram_h,
              data.flights[i].enl,
              data.flights[i].zoom_levels,
              data.flights[i].contests,
              data.flights[i].additional);
        }
      });

      req.always(function() {
        hideCircle(1000);
      });
    };

    /**
     * Request airspace informations via ajax
     *
     * @param {Number} lon Longitude.
     * @param {Number} lat Latitude.
     */
    function getAirspaceInfo(lon, lat) {
      var req = $.ajax('/airspace/info?lon=' + lon + '&lat=' + lat);

      req.done(function(data) {
        if (data.airspaces && data.airspaces.length != 0)
          showAirspaceData(data.airspaces);
        else
          showAirspaceData(null);
      });

      req.fail(function() {
        showAirspaceData(null);
      });
    };

    /**
     * Show airspace data in infobox
     *
     * @param {Object} data Airspace data.
     */
    function showAirspaceData(data) {
      if (!visible) return; // do nothing if infobox is closed already

      infobox.empty();
      var item = $('

');

      if (!data) {
        item.html('No airspace data retrieved for this location');

        infobox.delay(1500).fadeOut(1000, function() {
          infobox.hide();
          visible = false;
        });

        hideCircle(1000);

      } else {
        var table = $('

');

        table.append($(
            '

' +
            'Name	' +
            'Class	' +
            'Base	' +
            'Top	' +
            '

'
            ));

        var table_body = $('
</tbody');

        for (var i = 0; i < data.length; ++i) {
          table_body.append($(
              '
' +
              '' + data[i].name + '	' +
              '' + data[i].airspace_class + '	' +
              '' + data[i].base + '	' +
              '' + data[i].top + '	' +
              '
'
              ));
        }

        table.append(table_body);
        item.append(table);
      }

      infobox.append(item);

      pixel = map.getPixelFromLonLat(infobox.latlon);
      infobox.css('left', (pixel.x + 15) + 'px');
      infobox.css('top', (pixel.y - infobox.height() / 2) + 'px');
    };

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


<commit_before>/** @license MIT License (c) copyright 2010-2013 original author or authors */

/**
 * Licensed under the MIT License at:
 * http://www.opensource.org/licenses/mit-license.php
 *
 * @author Brian Cavalier
 * @author John Hann
 */

var async = require('./async');

module.exports = Stream;

Stream.of = of;
Stream.empty = empty;
Stream.iterate = iterate;
Stream.repeat = repeat;

function Stream(emitter) {
	this._emitter = emitter;
}

function of(x) {
	return new Stream(function (next, end) {
		try {
			next(x);
			end();
		} catch (e) {
			end(e);
		}

		return noop;
	});
}

function empty() {
	return new Stream(emptyEmitter);
}

function iterate(f, x) {
	var value = x;
	return new Stream(function(next, end) {
		try {
			(next(value) === false) ? end() : async(emitNext);
		} catch(e) {
			end(e)
		}

		function emitNext() {
			try {
				(next(value = f(value)) === false) ? end() : async(emitNext);
			} catch(e) {
				end(e);
			}
		}
	});
}

function repeat(x) {
	return iterate(identity, x);
}

var proto = Stream.prototype = {};

proto.constructor = Stream;

/**
 * Start consuming items in the stream.
 * @param {function} next called once for each item in the stream
 * @param {function?} end called once when either:
 *
 *  1. the stream is ended, that is, when it has no more items, *or*
 *  2. when a fatal error has occurred in the stream. In this case, the error
 *     will be passed to end.
 *  In either case, neither next nor end will ever be called again.
 *  If end is not provided, and an error occurs, it will be rethrown to the host
 *  environment.
 * @returns {function} function to unsubscribe from the stream. After calling
 *  this, next and end will never be called again.
 */
proto.forEach = function(next, end) {
	var ended, unsubscribed, unsubscribe, self = this;

	if(typeof end !== 'function') {
		end = fatal;
	}

	async(function() {
		unsubscribe = self._emitter(safeNext, safeEnd);
	});

	function safeUnsubscribe() {
		if(unsubscribed) {
			return;
		}

		unsubscribed = true;

		async(function() {
			if(typeof unsubscribe === 'function') {
				unsubscribe();
			}
		});
	}

	function safeNext(x) {
		if(ended || unsubscribed) {
			return false;
		}
		next(x);

		return true;
	}

	function safeEnd() {
		if(ended) {
			return;
		}
		ended = true;
		safeUnsubscribe();

		end.apply(void 0, arguments);
	}

	return safeUnsubscribe;
};

proto.map = function(f) {
	var stream = this._emitter;
	return new Stream(function(next, end) {
		stream(function(x) {
			return next(f(x));
		}, end);
	});
};

proto.ap = function(stream2) {
	return this.flatMap(function(f) {
		return stream2.map(f);
	});
};

proto.flatMap = function(f) {
	var stream = this._emitter;
	var cont = true;
	return new Stream(function(next, end) {
		stream(function(x) {
			f(x)._emitter(function(x) {
				return (cont = next(x));
			}, endOnError(end));
			return cont;
		}, end);
	});
};

proto.flatten = function() {
	return this.flatMap(identity);
};

proto.cycle = function() {
	var stream = this._emitter;
	var cont = true;
	return new Stream(function(next, end) {
		stream(next, handleEnd);
		function handleEnd(e) {
			if(e != null) {
				end(e);
			} else {
				if (cont === false) {
					end();
				} else {
					async(function() {
						stream(function(x) {
							return (cont = next(x));
						}, handleEnd);
					});
				}
			}
		}
	});
};

proto.filter = function(predicate) {
	var stream = this._emitter;
	return new Stream(function(next, end) {
		stream(function(x) {
			if (predicate(x)) {
				return next(x);
			}
		}, end);
	});
};

proto.interleave = function(other) {
	var stream = this._emitter;
	return new Stream(function(next, end) {
		var count = 2;

		stream(next, handleEnd);
		other._emitter(next, handleEnd);

		function handleEnd(e) {
			count -= 1;
			if(e != null) {
				end(e);
			} else if (count === 0) {
				end();
			}
		}
	});
};

proto.intersperse = function(val) {
	var stream = this._emitter;
	return new Stream(function(next, end) {
		stream(function(x) {
			next(x);
			return next(val);
		}, end);
	});
};

proto.zipWith = function(other, f) {
	var stream = this._emitter;
	return new Stream(function(next, end) {
		var buffer = [], count = 2;

		stream(function(x) {
			if(buffer.length == 0) {
				buffer.push(x);
				return;
			}
			return next(f(x, buffer.shift()));
		}, handleEnd);
		other._emitter(function(x) {
			if(buffer.length == 0) {
				buffer.push(x);
				return;
			}
			return next(f(buffer.shift(), x));
		}, handleEnd);

		function handleEnd(e) {
			count -= 1;
			if(e != null) {
				end(e);
			} else if (count === 0) {
				end();
			}
		}
	});
};

proto.zip = function(other) {
	return this.zipWith(other, function(x, y) {
		return [x, y];
	});
};

proto.concat = function(other) {
	// TODO: Should this accept an array?  a stream of streams?
	var stream = this._emitter;
	return new Stream(function(next, end) {
		stream(next, function(e) {
			e == null ? other._emitter(next, end) : end(e);
		});
	});
};

proto.tap = function(f) {
	var stream = this._emitter;
	return new Stream(function(next, end) {
		stream(function(x) {
			f(x);
			return next(x);
		}, end);
	});
};

proto.drop = function(m) {
	var remaining = m;
	return this.dropWhile(function() {
		remaining -= 1;
		return remaining >= 0;
	});
};

proto.dropWhile = function(predicate) {
	var stream = this._emitter;
	return new Stream(function(next, end) {
		stream(function(x) {
			if (predicate !== void 0) {
				if (predicate(x)) {
					return;
				}
				predicate = void 0;
			}
			return next(x);
		}, end);
	});
};

proto.take = function(m) {
	var taken = 0;
	return this.takeWhile(function() {
		taken += 1;
		return taken <= m;
	});
};

proto.takeWhile = function(predicate) {
	var self = this;
	return new Stream(function(next, end) {
		var unsubscribe = self.forEach(function(x) {
			predicate(x) ? next(x) : unsubscribe();
		}, end);
	});
};

proto.buffer = function(windower) {
	var stream = this._emitter;
	var cont = true;
	return new Stream(function(next, end) {
		var buffer;
		stream(function(x) {
			function n(x) {
				cont = next(x);
			}
			buffer = windower(n, x, buffer||[]);
			return cont;
		}, end);
	});
};

proto.bufferCount = function(n) {
	return this.buffer(createCountBuffer(n));
};

proto.bufferTime = function(interval) {
	return this.buffer(createTimeBuffer(interval));
};

proto.delay = function(ms) {
	var stream = this._emitter;
	var cont = true;
	return new Stream(function(next, end) {
		stream(function(x) {
			setTimeout(function() {
				cont = next(x);
			}, ms||0);
			return cont;
		}, end);
	});
};

proto.debounce = function(interval) {
	var nextEventTime = interval;
	var stream = this._emitter;
	var cont = true;

	return new Stream(function(next, end) {
		stream(function(x) {
			var now = Date.now();
			if(now >= nextEventTime) {
				nextEventTime = now + interval;
				cont = next(x);
			}
			return cont;
		}, end);
	});
};

proto.throttle = function(interval) {
	var cachedEvent, throttled;
	var stream = this._emitter;
	var cont = true;

	return new Stream(function(next, end) {
		stream(function(x) {
			cachedEvent = x;

			if(throttled === void 0) {
				throttled = setTimeout(function() {
					throttled = void 0;
					cont = next(cachedEvent);
				}, interval);
			}
			return cont;
		}, end);
	});
};

proto['catch'] = function(f) {
	var stream = this._emitter;
	return new Stream(function(next, end) {
		stream(next, function(e1) {
			var error;
			if(e1 != null) {
				try {
					next(f(e1));
				} catch(e2) {
					error = e2;
				}
			}

			if(error != null) {
				end(error);
			}
		});
	});
};

proto.reduce = function(f, initial) {
	var stream = this._emitter;
	return new Stream(function(next, end) {
		var value = initial;
		stream(function(x) {
			value = f(value, x);
		}, function(e) {
			if(e == null) {
				next(value);
			}

			end(e);
		});
	});
};

proto.reduceRight = function(f, initial) {
	var stream = this._emitter;
	return new Stream(function(next, end) {
		// This is a brute-force approach that uses an array to buffer
		// items, then runs array.reduceRight. Less elegant than recursion,
		// but much faster and more practical in JS.
		var buffer = [];
		stream(function(x) {
			buffer.push(x);
		}, function(e) {
			if(e == null) {
				next(buffer.reduceRight(f, initial));
			}

			end(e);
		});
	});
};

proto.scan = function(f, initial) {
	return this.map(function(x) {
		return initial = f(initial, x);
	});
};

function emptyEmitter(_, end) {
	end();
}

function createTimeBuffer(interval) {
	var buffered;
	return function(next, x, buffer) {
		if(!buffered) {
			buffered = true;
			buffer = [x];

			setTimeout(function() {
				next(buffer.slice());
				buffered = false;
			}, interval);
		} else {
			buffer.push(x);
		}

		return buffer;
	};
}

function createCountBuffer(n) {
	return function (next, x, buffer) {
		buffer && buffer.push(x) || (buffer = [x]);

		if(buffer.length >= n) {
			next(buffer);
			buffer = void 0;
		}

		return buffer;
	};
}

function endOnError(end) {
	return function(e) {
		e == null || end(e);
	};
}

function fatal(e) {
	if(e != null) {
		throw e;
	}
}

function identity(x) {
	return x;
}

function noop() {}<commit_msg>Cleaning<commit_after>/** @license MIT License (c) copyright 2010-2013 original author or authors */

/**
 * Licensed under the MIT License at:
 * http://www.opensource.org/licenses/mit-license.php
 *
 * @author Brian Cavalier
 * @author John Hann
 */

var async = require('./async');

module.exports = Stream;

Stream.of = of;
Stream.empty = empty;
Stream.iterate = iterate;
Stream.repeat = repeat;

function Stream(emitter) {
	this._emitter = emitter;
}

function of(x) {
	return new Stream(function (next, end) {
		try {
			next(x);
			end();
		} catch (e) {
			end(e);
		}

		return noop;
	});
}

function empty() {
	return new Stream(emptyEmitter);
}

function iterate(f, x) {
	var value = x;
	return new Stream(function(next, end) {
		try {
			(next(value) === false) ? end() : async(emitNext);
		} catch(e) {
			end(e)
		}

		function emitNext() {
			try {
				(next(value = f(value)) === false) ? end() : async(emitNext);
			} catch(e) {
				end(e);
			}
		}
	});
}

function repeat(x) {
	return iterate(identity, x);
}

var proto = Stream.prototype = {};

proto.constructor = Stream;

/**
 * Start consuming items in the stream.
 * @param {function} next called once for each item in the stream
 * @param {function?} end called once when either:
 *
 *  1. the stream is ended, that is, when it has no more items, *or*
 *  2. when a fatal error has occurred in the stream. In this case, the error
 *     will be passed to end.
 *  In either case, neither next nor end will ever be called again.
 *  If end is not provided, and an error occurs, it will be rethrown to the host
 *  environment.
 * @returns {function} function to unsubscribe from the stream. After calling
 *  this, next and end will never be called again.
 */
proto.forEach = function(next, end) {
	var ended, unsubscribed, unsubscribe, self = this;

	if(typeof end !== 'function') {
		end = fatal;
	}

	async(function() {
		unsubscribe = self._emitter(safeNext, safeEnd);
	});

	function safeUnsubscribe() {
		if(unsubscribed) {
			return;
		}

		unsubscribed = true;

		async(function() {
			if(typeof unsubscribe === 'function') {
				unsubscribe();
			}
		});
	}

	function safeNext(x) {
		if(ended || unsubscribed) {
			return false;
		}
		next(x);

		return true;
	}

	function safeEnd() {
		if(ended) {
			return;
		}
		ended = true;
		safeUnsubscribe();

		end.apply(void 0, arguments);
	}

	return safeUnsubscribe;
};

proto.map = function(f) {
	var stream = this._emitter;
	return new Stream(function(next, end) {
		stream(function(x) {
			return next(f(x));
		}, end);
	});
};

proto.ap = function(stream2) {
	return this.flatMap(function(f) {
		return stream2.map(f);
	});
};

proto.flatMap = function(f) {
	var stream = this._emitter;
	var cont = true;
	return new Stream(function(next, end) {
		stream(function(x) {
			f(x)._emitter(function(x) {
				return (cont = next(x));
			}, endOnError(end));
			return cont;
		}, end);
	});
};

proto.flatten = function() {
	return this.flatMap(identity);
};

proto.cycle = function() {
	var stream = this._emitter;
	var cont = true;
	return new Stream(function(next, end) {
		stream(next, handleEnd);
		function handleEnd(e) {
			if(e != null) {
				end(e);
			} else {
				if (cont === false) {
					end();
				} else {
					async(function() {
						stream(function(x) {
							return (cont = next(x));
						}, handleEnd);
					});
				}
			}
		}
	});
};

proto.filter = function(predicate) {
	var stream = this._emitter;
	return new Stream(function(next, end) {
		stream(function(x) {
			if (predicate(x)) {
				return next(x);
			}
		}, end);
	});
};

proto.interleave = function(other) {
	var stream = this._emitter;
	return new Stream(function(next, end) {
		var count = 2;

		stream(next, handleEnd);
		other._emitter(next, handleEnd);

		function handleEnd(e) {
			count -= 1;
			if(e != null) {
				end(e);
			} else if (count === 0) {
				end();
			}
		}
	});
};

proto.intersperse = function(val) {
	var stream = this._emitter;
	return new Stream(function(next, end) {
		stream(function(x) {
			next(x);
			return next(val);
		}, end);
	});
};

proto.zipWith = function(other, f) {
	var stream = this._emitter;
	return new Stream(function(next, end) {
		var buffer = [], count = 2;

		stream(function(x) {
			if(buffer.length == 0) {
				buffer.push(x);
				return;
			}
			return next(f(x, buffer.shift()));
		}, handleEnd);
		other._emitter(function(x) {
			if(buffer.length == 0) {
				buffer.push(x);
				return;
			}
			return next(f(buffer.shift(), x));
		}, handleEnd);

		function handleEnd(e) {
			count -= 1;
			if(e != null) {
				end(e);
			} else if (count === 0) {
				end();
			}
		}
	});
};

proto.zip = function(other) {
	return this.zipWith(other, function(x, y) {
		return [x, y];
	});
};

proto.concat = function(other) {
	// TODO: Should this accept an array?  a stream of streams?
	var stream = this._emitter;
	return new Stream(function(next, end) {
		stream(next, function(e) {
			e == null ? other._emitter(next, end) : end(e);
		});
	});
};

proto.tap = function(f) {
	var stream = this._emitter;
	return new Stream(function(next, end) {
		stream(function(x) {
			f(x);
			return next(x);
		}, end);
	});
};

proto.drop = function(m) {
	var remaining = m;
	return this.dropWhile(function() {
		remaining -= 1;
		return remaining >= 0;
	});
};

proto.dropWhile = function(predicate) {
	var stream = this._emitter;
	return new Stream(function(next, end) {
		stream(function(x) {
			if (predicate !== void 0) {
				if (predicate(x)) {
					return;
				}
				predicate = void 0;
			}
			return next(x);
		}, end);
	});
};

proto.take = function(m) {
	var taken = 0;
	return this.takeWhile(function() {
		taken += 1;
		return taken <= m;
	});
};

proto.takeWhile = function(predicate) {
	var self = this;
	return new Stream(function(next, end) {
		var unsubscribe = self.forEach(function(x) {
			predicate(x) ? next(x) : unsubscribe();
		}, end);
	});
};

proto.buffer = function(windower) {
	var stream = this._emitter;
	var cont = true;
	return new Stream(function(next, end) {
		var buffer;
		stream(function(x) {
			buffer = windower(function(x) {cont = next(x);}, x, buffer||[]);
			return cont;
		}, end);
	});
};

proto.bufferCount = function(n) {
	return this.buffer(createCountBuffer(n));
};

proto.bufferTime = function(interval) {
	return this.buffer(createTimeBuffer(interval));
};

proto.delay = function(ms) {
	var stream = this._emitter;
	var cont = true;
	return new Stream(function(next, end) {
		stream(function(x) {
			setTimeout(function() {
				cont = next(x);
			}, ms||0);
			return cont;
		}, end);
	});
};

proto.debounce = function(interval) {
	var nextEventTime = interval;
	var stream = this._emitter;
	var cont = true;

	return new Stream(function(next, end) {
		stream(function(x) {
			var now = Date.now();
			if(now >= nextEventTime) {
				nextEventTime = now + interval;
				cont = next(x);
			}
			return cont;
		}, end);
	});
};

proto.throttle = function(interval) {
	var cachedEvent, throttled;
	var stream = this._emitter;
	var cont = true;

	return new Stream(function(next, end) {
		stream(function(x) {
			cachedEvent = x;

			if(throttled === void 0) {
				throttled = setTimeout(function() {
					throttled = void 0;
					cont = next(cachedEvent);
				}, interval);
			}
			return cont;
		}, end);
	});
};

proto['catch'] = function(f) {
	var stream = this._emitter;
	return new Stream(function(next, end) {
		stream(next, function(e1) {
			var error;
			if(e1 != null) {
				try {
					next(f(e1));
				} catch(e2) {
					error = e2;
				}
			}

			if(error != null) {
				end(error);
			}
		});
	});
};

proto.reduce = function(f, initial) {
	var stream = this._emitter;
	return new Stream(function(next, end) {
		var value = initial;
		stream(function(x) {
			value = f(value, x);
		}, function(e) {
			if(e == null) {
				next(value);
			}

			end(e);
		});
	});
};

proto.reduceRight = function(f, initial) {
	var stream = this._emitter;
	return new Stream(function(next, end) {
		// This is a brute-force approach that uses an array to buffer
		// items, then runs array.reduceRight. Less elegant than recursion,
		// but much faster and more practical in JS.
		var buffer = [];
		stream(function(x) {
			buffer.push(x);
		}, function(e) {
			if(e == null) {
				next(buffer.reduceRight(f, initial));
			}

			end(e);
		});
	});
};

proto.scan = function(f, initial) {
	return this.map(function(x) {
		return initial = f(initial, x);
	});
};

function emptyEmitter(_, end) {
	end();
}

function createTimeBuffer(interval) {
	var buffered;
	return function(next, x, buffer) {
		if(!buffered) {
			buffered = true;
			buffer = [x];

			setTimeout(function() {
				next(buffer.slice());
				buffered = false;
			}, interval);
		} else {
			buffer.push(x);
		}

		return buffer;
	};
}

function createCountBuffer(n) {
	return function (next, x, buffer) {
		buffer && buffer.push(x) || (buffer = [x]);

		if(buffer.length >= n) {
			next(buffer);
			buffer = void 0;
		}

		return buffer;
	};
}

function endOnError(end) {
	return function(e) {
		e == null || end(e);
	};
}

function fatal(e) {
	if(e != null) {
		throw e;
	}
}

function identity(x) {
	return x;
}

function noop() {}
<|endoftext|>


<commit_before>var activeCueIds = [];

$( document ).ready(function() {
  //for when DOM is ready..
  nScrubs = 0; //number of times scrubed. Could put in a function to reset after x number scrubs, and then instead load new subs in same genre.

  //initialise with subs:
  scrubTrack(0);

	var iframe_active = $(".activevideo:first").data("zid");
	if (iframe_active == null || iframe_active <= 0) $('#ajax-loader-video').toggle();

	$('#'+iframe_active).load(function(){
		$('#ajax-loader-video').toggle();
  });

	document.getElementById('video').addEventListener('loadedmetadata', function() {
		this.currentTime = 3;
	}, false);

});

$(function() {
	//Enable swiping...
	$(".swipescrub").swipe( {
		//Generic swipe handler for all directions
    swipe: function(event, direction, distance, duration, fingerCount, fingerData) {

      if (direction == null) return false;

      if (direction == 'up') {
        console.log("scrub up");
        scrubTrack(nScrubs);
        nScrubs++;
        if(nScrubs => 9) nScrubs = 0
      }

      if (direction == 'down') console.log("down"); //return false;

      if (direction == 'right') console.log("right"); //return false;

      if (direction == 'left') console.log("left"); //return false;
      //if (direction == 'left') rotatelement(".info-panels",180); //return false;
    },
   //Default is 75px
   threshold:15
	});
});

function scrubTrack(offsetIndex){

  var track = video.addTextTrack("captions", "comedy", "en");

  track.mode = "showing";

  //arrays for upcoming cues
  var starttime = [], endtime = [] , text = [] ;

  $selector = $("#comedy li").eq(offsetIndex);

  //making a buffer of 60 seconds from the list-items in the api, storing them in the starttime, endtime and text arrays.
  $selector.each(function(i){
  	starttime[i] = $selector.eq(i).find(".start").text();
  	endtime[i]   = $selector.eq(i).find(".end").text();
  	text[i]      = $selector.eq(i).find(".text").text();
	});

  //console.log(starttime.length, starttime);
  //console.log($selector);

	for (var i = 0; i < starttime.length; i++) {
	  //console.log(i, starttime[i], endtime[i], text[i]);
	  newCue = new VTTCue(starttime[i], endtime[i], text[i]);
	  track.addCue(newCue);
    //storing cue ID's in the activeCueIds array - to be used for deletion
	  activeCueIds[i] = newCue.id;
	}

	/*track.addCue(new VTTCue(0, 12, "Loaded Cues"));
	track.addCue(new VTTCue(18.7, 21.5, "This blade has a dark past."));
	track.addCue(new VTTCue(22.8, 26.8, "It has shed much innocent blood."));
	track.addCue(new VTTCue(29, 32.45, "You're a fool for traveling alone, so completely unprepared."));
	track.addCue(new VTTCue(32.75, 35.8, "You're lucky your blood's still flowing."));
	track.addCue(new VTTCue(36.25, 37.3, "Thank you."));
	track.addCue(new VTTCue(38.5, 40, "So..."));
	track.addCue(new VTTCue(40.4, 44.8, "What brings you to the land of the gatekeepers?"));
	track.addCue(new VTTCue(46, 48.5, "I'm searching for someone."));
	track.addCue(new VTTCue(49, 53.2, "Someone very dear? A kindred spirit?"));
	track.addCue(new VTTCue(54.4, 56, "A dragon."));
	track.addCue(new VTTCue(58.85, 61.75, "A dangerous quest for a lone hunter."));
	track.addCue(new VTTCue(62.95, 65.87, "I've been alone for as long as I can remember."));
	track.addCue(new VTTCue(118.25, 119.5, "We're almost done. Shhh..."));	*/
	return offsetIndex;
}

/*laravel specifics? don't know where these came from */

function pinClone() {
	balancelement(".info-panels");
	var ZIDkey_val = $("#info:first").data("todo");
	//$('#ajax-loader-pindu').toggle();
	$('.active').slideToggle();
	var nextactivetodo = $('.active').nextAll('.col-lg-4:first');
	$( ".active" ).remove();
	nextactivetodo.slideToggle().addClass( "active" );

    //Get value and make sure it is not null
	if (ZIDkey_val.length == 0)  window.location.reload();
		$.ajax({
      url: "pages/functions/votes_addupvote.php",
      type: "post",
      dataType:"json",
      data: { ZID_key : ZIDkey_val },
      statusCode: {
          404: function() {
            alert("Big problem! Page not found");
          }
        },
      success: function(data){
    		if (data.bool_flag) {
      		return;
    		} else {
      		console.log(data.message + '  ' + data.dbconn);
      		return;
      		//$('#ajax-loader-pindu').toggle();
      		// window.location.reload();
    		}
      },
      error:function(data){
        console.log(' Function error  ');
        $('#ajax-loader-pindu').toggle();
        //window.location.reload();
      }
    });
  return;
}

function pinRemove() {
	balancelement(".info-panels");
	var ZIDkey_val = $("#info:first").data("todo");
	//$('#ajax-loader-pindu').toggle();
	$('.active').slideToggle();
	var nextactivetodo = $('.active').nextAll('.col-lg-4:first');
	$( ".active" ).remove();
	nextactivetodo.slideToggle().addClass( "active" );

  //Get value and make sure it is not null
	if (ZIDkey_val.length == 0)  window.location.reload();

	$.ajax({
    url: "pages/functions/votes_adddownvote.php",
    type: "post",
    dataType:"json",
		data: { ZID_key : ZIDkey_val },
    statusCode: {
      404: function() {
        alert("Big problem! Page not found");
      }
    },
    success: function(data){
			if (data.bool_flag) {
			return;
			} else {
  			console.log(data.message + '  ' + data.dbconn);
  			return;
  			//$('#ajax-loader-pindu').toggle();
  			// window.location.reload();
			}
    },
    error:function(data){
  		console.log(' Function error  ');
  		$('#ajax-loader-pindu').toggle();
  		//window.location.reload();
    }
  });

return;

}

function visitorSubmit() {
	$('#ajax-loader-visitorSubmit').toggle();
	var ZIDkey_val = $("#visitorTask").val();
	if (ZIDkey_val.length == 0)  window.location.reload();

			$.ajax({
	            url: "pages/functions/tasks_visitors_add.php",
	            type: "post",
	            dataType:"json",
				data: { body_tasks : ZIDkey_val },
	            statusCode: {
	                404: function() {
	                  alert("Big problem! Page not found");
	                }
	              },
	            success: function(data){
					if (data.bool_flag) {
						window.location.assign("./login.html");
						return;
					} else {
						$('#ajax-loader-pindu').toggle();
						console.log(data.message + '  ' + data.dbconn);
						alert(data.message + '  ' + data.dbconn);
						window.location.reload();
						return;
					}
	            },
	            error:function(data){
					console.log(' Function error  ');
					$('#ajax-loader-pindu').toggle();
					//window.location.reload();
	            }
	        });

}

function pinLater() {
	$('#ajax-loader-pindu').toggle();
	//$('#ajax-loader-later').toggle();
	window.location.reload();
}
<commit_msg>Update scrubr.js<commit_after>var activeCueIds = [];

$( document ).ready(function() {
  //for when DOM is ready..
  nScrubs = 0; //number of times scrubed. Could put in a function to reset after x number scrubs, and then instead load new subs in same genre.

  //initialise with subs:
  scrubTrack(0);

	var iframe_active = $(".activevideo:first").data("zid");
	if (iframe_active == null || iframe_active <= 0) $('#ajax-loader-video').toggle();

	$('#'+iframe_active).load(function(){
		$('#ajax-loader-video').toggle();
  });

	document.getElementById('video').addEventListener('loadedmetadata', function() {
		this.currentTime = 3;
	}, false);

});

$(function() {
	//Enable swiping...
	$(".swipescrub").swipe( {
		//Generic swipe handler for all directions
    swipe: function(event, direction, distance, duration, fingerCount, fingerData) {

      if (direction == null) return false;

      if (direction == 'up') {
        console.log("scrub up");
        scrubTrack(nScrubs);
        nScrubs++;
        if(nScrubs => 9) nScrubs = 0;
      }

      if (direction == 'down') console.log("down"); //return false;

      if (direction == 'right') console.log("right"); //return false;

      if (direction == 'left') console.log("left"); //return false;
      //if (direction == 'left') rotatelement(".info-panels",180); //return false;
    },
   //Default is 75px
   threshold:15
	});
});

function scrubTrack(offsetIndex){

  var track = video.addTextTrack("captions", "comedy", "en");

  track.mode = "showing";

  //arrays for upcoming cues
  var starttime = [], endtime = [] , text = [] ;

  $selector = $("#comedy li").eq(offsetIndex);

  //making a buffer of 60 seconds from the list-items in the api, storing them in the starttime, endtime and text arrays.
  $selector.each(function(i){
  	starttime[i] = $selector.eq(i).find(".start").text();
  	endtime[i]   = $selector.eq(i).find(".end").text();
  	text[i]      = $selector.eq(i).find(".text").text();
	});

  //console.log(starttime.length, starttime);
  //console.log($selector);

	for (var i = 0; i < starttime.length; i++) {
	  //console.log(i, starttime[i], endtime[i], text[i]);
	  newCue = new VTTCue(starttime[i], endtime[i], text[i]);
	  track.addCue(newCue);
    //storing cue ID's in the activeCueIds array - to be used for deletion
	  activeCueIds[i] = newCue.id;
	}

	/*track.addCue(new VTTCue(0, 12, "Loaded Cues"));
	track.addCue(new VTTCue(18.7, 21.5, "This blade has a dark past."));
	track.addCue(new VTTCue(22.8, 26.8, "It has shed much innocent blood."));
	track.addCue(new VTTCue(29, 32.45, "You're a fool for traveling alone, so completely unprepared."));
	track.addCue(new VTTCue(32.75, 35.8, "You're lucky your blood's still flowing."));
	track.addCue(new VTTCue(36.25, 37.3, "Thank you."));
	track.addCue(new VTTCue(38.5, 40, "So..."));
	track.addCue(new VTTCue(40.4, 44.8, "What brings you to the land of the gatekeepers?"));
	track.addCue(new VTTCue(46, 48.5, "I'm searching for someone."));
	track.addCue(new VTTCue(49, 53.2, "Someone very dear? A kindred spirit?"));
	track.addCue(new VTTCue(54.4, 56, "A dragon."));
	track.addCue(new VTTCue(58.85, 61.75, "A dangerous quest for a lone hunter."));
	track.addCue(new VTTCue(62.95, 65.87, "I've been alone for as long as I can remember."));
	track.addCue(new VTTCue(118.25, 119.5, "We're almost done. Shhh..."));	*/
	return offsetIndex;
}

/*laravel specifics? don't know where these came from */

function pinClone() {
	balancelement(".info-panels");
	var ZIDkey_val = $("#info:first").data("todo");
	//$('#ajax-loader-pindu').toggle();
	$('.active').slideToggle();
	var nextactivetodo = $('.active').nextAll('.col-lg-4:first');
	$( ".active" ).remove();
	nextactivetodo.slideToggle().addClass( "active" );

    //Get value and make sure it is not null
	if (ZIDkey_val.length == 0)  window.location.reload();
		$.ajax({
      url: "pages/functions/votes_addupvote.php",
      type: "post",
      dataType:"json",
      data: { ZID_key : ZIDkey_val },
      statusCode: {
          404: function() {
            alert("Big problem! Page not found");
          }
        },
      success: function(data){
    		if (data.bool_flag) {
      		return;
    		} else {
      		console.log(data.message + '  ' + data.dbconn);
      		return;
      		//$('#ajax-loader-pindu').toggle();
      		// window.location.reload();
    		}
      },
      error:function(data){
        console.log(' Function error  ');
        $('#ajax-loader-pindu').toggle();
        //window.location.reload();
      }
    });
  return;
}

function pinRemove() {
	balancelement(".info-panels");
	var ZIDkey_val = $("#info:first").data("todo");
	//$('#ajax-loader-pindu').toggle();
	$('.active').slideToggle();
	var nextactivetodo = $('.active').nextAll('.col-lg-4:first');
	$( ".active" ).remove();
	nextactivetodo.slideToggle().addClass( "active" );

  //Get value and make sure it is not null
	if (ZIDkey_val.length == 0)  window.location.reload();

	$.ajax({
    url: "pages/functions/votes_adddownvote.php",
    type: "post",
    dataType:"json",
		data: { ZID_key : ZIDkey_val },
    statusCode: {
      404: function() {
        alert("Big problem! Page not found");
      }
    },
    success: function(data){
			if (data.bool_flag) {
			return;
			} else {
  			console.log(data.message + '  ' + data.dbconn);
  			return;
  			//$('#ajax-loader-pindu').toggle();
  			// window.location.reload();
			}
    },
    error:function(data){
  		console.log(' Function error  ');
  		$('#ajax-loader-pindu').toggle();
  		//window.location.reload();
    }
  });

return;

}

function visitorSubmit() {
	$('#ajax-loader-visitorSubmit').toggle();
	var ZIDkey_val = $("#visitorTask").val();
	if (ZIDkey_val.length == 0)  window.location.reload();

			$.ajax({
	            url: "pages/functions/tasks_visitors_add.php",
	            type: "post",
	            dataType:"json",
				data: { body_tasks : ZIDkey_val },
	            statusCode: {
	                404: function() {
	                  alert("Big problem! Page not found");
	                }
	              },
	            success: function(data){
					if (data.bool_flag) {
						window.location.assign("./login.html");
						return;
					} else {
						$('#ajax-loader-pindu').toggle();
						console.log(data.message + '  ' + data.dbconn);
						alert(data.message + '  ' + data.dbconn);
						window.location.reload();
						return;
					}
	            },
	            error:function(data){
					console.log(' Function error  ');
					$('#ajax-loader-pindu').toggle();
					//window.location.reload();
	            }
	        });

}

function pinLater() {
	$('#ajax-loader-pindu').toggle();
	//$('#ajax-loader-later').toggle();
	window.location.reload();
}
<|endoftext|>


<commit_before>/*
   csound control-events module from <csound.h>
   https://csound.com/docs/api/modules.html
*/

import { freeStringPtr, ptr2string, string2ptr } from "@utils/string-pointers";

/**
 * Inputs an immediate score event
 * without any pre-process parsing
 * @async
 * @function
 * @name inputMessage
 * @memberof CsoundObj
 * @return {Promise.<number>}
 */
export const csoundInputMessage = (wasm) => (csound, scoEvent) => {
  const stringPtr = string2ptr(wasm, scoEvent);
  const result = wasm.exports.csoundInputMessage(csound, stringPtr);
  freeStringPtr(wasm, stringPtr);
  return result;
};

csoundInputMessage.toString = () => "inputMessage = async (scoreEvent) => Number;";

/**
 * Inputs an immediate score event
 * without any pre-process parsing
 * @async
 * @function
 * @name inputMessageAsync
 * @memberof CsoundObj
 * @return {Promise.<number>}
 */
export const csoundInputMessageAsync = (wasm) => (csound, scoEvent) => {
  const stringPtr = string2ptr(wasm, scoEvent);
  const result = wasm.exports.csoundInputMessageAsync(csound, stringPtr);
  freeStringPtr(wasm, stringPtr);
  return result;
};

csoundInputMessageAsync.toString = () => "inputMessageAsync = async (scoreEvent) => Number;";

/**
 * Retrieves the value of control channel identified by channelName.
 * If the err argument is not NULL, the error (or success) code finding
 * or accessing the channel is stored in it.
 * @async
 * @function
 * @name getControlChannel
 * @memberof CsoundObj
 * @param {string} channelName
 * @return {Promise.<undefined>}
 */
export const csoundGetControlChannel = (wasm) => (csound, channelName) => {
  const stringPtr = string2ptr(wasm, channelName);
  const result = wasm.exports.csoundGetControlChannelWasi(csound, stringPtr);
  freeStringPtr(wasm, stringPtr);
  return result;
};

csoundGetControlChannel.toString = () => "getControlChannel = async (channelName) => Number;";

/**
 * Sets the value of control channel identified by channelName
 * @async
 * @function
 * @name setControlChannel
 * @memberof CsoundObj
 * @param {string} channelName
 * @param {number} value
 * @return {Promise.<undefined>}
 */
export const csoundSetControlChannel = (wasm) => (csound, channelName, value) => {
  const stringPtr = string2ptr(wasm, channelName);
  wasm.exports.csoundSetControlChannel(csound, stringPtr, value);
  freeStringPtr(wasm, stringPtr);
};

csoundSetControlChannel.toString = () => "setControlChannel = async (channelName, value) => void;";

/**
 * Retrieves the string channel identified by channelName
 * @async
 * @function
 * @name getStringChannel
 * @memberof CsoundObj
 * @param {string} channelName
 * @return {Promise.<undefined>}
 */
export const csoundGetStringChannel = (wasm) => (csound, channelName) => {
  const stringPtr = string2ptr(wasm, channelName);
  const pointerToResult = wasm.exports.csoundGetStringChannelWasi(csound, stringPtr);
  const result = ptr2string(wasm, pointerToResult);

  freeStringPtr(wasm, stringPtr);
  freeStringPtr(wasm, pointerToResult);
  return result;
};

csoundGetStringChannel.toString = () => "getStringChannel = async (channelName) => String;";

/**
 * Sets the string channel value identified by channelName
 * @async
 * @function
 * @name setStringChannel
 * @memberof CsoundObj
 * @param {string} channelName
 * @param {string} value
 * @return {Promise.<undefined>}
 */
export const csoundSetStringChannel = (wasm) => (csound, channelName, value) => {
  const stringPtr = string2ptr(wasm, channelName);
  const stringPtr2 = string2ptr(wasm, value);
  wasm.exports.csoundSetStringChannel(csound, stringPtr, stringPtr2);
  freeStringPtr(wasm, stringPtr);
  freeStringPtr(wasm, stringPtr2);
};

csoundSetStringChannel.toString = () => "setStringChannel = async (channelName, value) => void;";

// csoundGetChannelPtr (CSOUND *, MYFLT **p, const char *name, int type)
// csoundListChannels (CSOUND *, controlChannelInfo_t **lst)
// csoundDeleteChannelList (CSOUND *, controlChannelInfo_t *lst)
// csoundSetControlChannelHints (CSOUND *, const char *name, controlChannelHints_t hints)
// csoundGetControlChannelHints (CSOUND *, const char *name, controlChannelHints_t *hints)
// csoundGetChannelLock (CSOUND *, const char *name)
// csoundSetControlChannel (CSOUND *csound, const char *name, MYFLT val)
// csoundGetChannelDatasize (CSOUND *csound, const char *name)
// csoundSetInputChannelCallback (CSOUND *csound, channelCallback_t inputChannelCalback)
// csoundSetOutputChannelCallback (CSOUND *csound, channelCallback_t outputChannelCalback)
// csoundSetPvsChannel (CSOUND *, const PVSDATEXT *fin, const char *name)
// csoundGetPvsChannel (CSOUND *csound, PVSDATEXT *fout, const char *name)
// csoundScoreEvent (CSOUND *, char type, const MYFLT *pFields, long numFields)
// csoundScoreEventAsync (CSOUND *, char type, const MYFLT *pFields, long numFields)
// csoundScoreEventAbsolute (CSOUND *, char type, const MYFLT *pfields, long numFields, double time_ofs)
// csoundScoreEventAbsoluteAsync (CSOUND *, char type, const MYFLT *pfields, long numFields, double time_ofs)
// csoundKillInstance (CSOUND *csound, MYFLT instr, char *instrName, int mode, int allow_release)
// csoundRegisterSenseEventCallback (CSOUND *, void(*func)(CSOUND *, void *), void *userData)
// csoundKeyPress (CSOUND *, char c)
// csoundRegisterKeyboardCallback (CSOUND *, int(*func)(void *userData, void *p, unsigned int type), void *userData, unsigned int type)
// csoundRemoveKeyboardCallback (CSOUND *csound, int(*func)(void *, void *, unsigned int))
<commit_msg>inputMessage and inputMessageAsync have scoreEvent parameter<commit_after>/*
   csound control-events module from <csound.h>
   https://csound.com/docs/api/modules.html
*/

import { freeStringPtr, ptr2string, string2ptr } from "@utils/string-pointers";

/**
 * Inputs an immediate score event
 * without any pre-process parsing
 * @async
 * @function
 * @name inputMessage
 * @memberof CsoundObj
 * @param {string} scoreEvent
 * @return {Promise.<number>}
 */
export const csoundInputMessage = (wasm) => (csound, scoEvent) => {
  const stringPtr = string2ptr(wasm, scoEvent);
  const result = wasm.exports.csoundInputMessage(csound, stringPtr);
  freeStringPtr(wasm, stringPtr);
  return result;
};

csoundInputMessage.toString = () => "inputMessage = async (scoreEvent) => Number;";

/**
 * Inputs an immediate score event
 * without any pre-process parsing
 * @async
 * @function
 * @name inputMessageAsync
 * @memberof CsoundObj
 * @param {string} scoreEvent
 * @return {Promise.<number>}
 */
export const csoundInputMessageAsync = (wasm) => (csound, scoEvent) => {
  const stringPtr = string2ptr(wasm, scoEvent);
  const result = wasm.exports.csoundInputMessageAsync(csound, stringPtr);
  freeStringPtr(wasm, stringPtr);
  return result;
};

csoundInputMessageAsync.toString = () => "inputMessageAsync = async (scoreEvent) => Number;";

/**
 * Retrieves the value of control channel identified by channelName.
 * If the err argument is not NULL, the error (or success) code finding
 * or accessing the channel is stored in it.
 * @async
 * @function
 * @name getControlChannel
 * @memberof CsoundObj
 * @param {string} channelName
 * @return {Promise.<undefined>}
 */
export const csoundGetControlChannel = (wasm) => (csound, channelName) => {
  const stringPtr = string2ptr(wasm, channelName);
  const result = wasm.exports.csoundGetControlChannelWasi(csound, stringPtr);
  freeStringPtr(wasm, stringPtr);
  return result;
};

csoundGetControlChannel.toString = () => "getControlChannel = async (channelName) => Number;";

/**
 * Sets the value of control channel identified by channelName
 * @async
 * @function
 * @name setControlChannel
 * @memberof CsoundObj
 * @param {string} channelName
 * @param {number} value
 * @return {Promise.<undefined>}
 */
export const csoundSetControlChannel = (wasm) => (csound, channelName, value) => {
  const stringPtr = string2ptr(wasm, channelName);
  wasm.exports.csoundSetControlChannel(csound, stringPtr, value);
  freeStringPtr(wasm, stringPtr);
};

csoundSetControlChannel.toString = () => "setControlChannel = async (channelName, value) => void;";

/**
 * Retrieves the string channel identified by channelName
 * @async
 * @function
 * @name getStringChannel
 * @memberof CsoundObj
 * @param {string} channelName
 * @return {Promise.<undefined>}
 */
export const csoundGetStringChannel = (wasm) => (csound, channelName) => {
  const stringPtr = string2ptr(wasm, channelName);
  const pointerToResult = wasm.exports.csoundGetStringChannelWasi(csound, stringPtr);
  const result = ptr2string(wasm, pointerToResult);

  freeStringPtr(wasm, stringPtr);
  freeStringPtr(wasm, pointerToResult);
  return result;
};

csoundGetStringChannel.toString = () => "getStringChannel = async (channelName) => String;";

/**
 * Sets the string channel value identified by channelName
 * @async
 * @function
 * @name setStringChannel
 * @memberof CsoundObj
 * @param {string} channelName
 * @param {string} value
 * @return {Promise.<undefined>}
 */
export const csoundSetStringChannel = (wasm) => (csound, channelName, value) => {
  const stringPtr = string2ptr(wasm, channelName);
  const stringPtr2 = string2ptr(wasm, value);
  wasm.exports.csoundSetStringChannel(csound, stringPtr, stringPtr2);
  freeStringPtr(wasm, stringPtr);
  freeStringPtr(wasm, stringPtr2);
};

csoundSetStringChannel.toString = () => "setStringChannel = async (channelName, value) => void;";

// csoundGetChannelPtr (CSOUND *, MYFLT **p, const char *name, int type)
// csoundListChannels (CSOUND *, controlChannelInfo_t **lst)
// csoundDeleteChannelList (CSOUND *, controlChannelInfo_t *lst)
// csoundSetControlChannelHints (CSOUND *, const char *name, controlChannelHints_t hints)
// csoundGetControlChannelHints (CSOUND *, const char *name, controlChannelHints_t *hints)
// csoundGetChannelLock (CSOUND *, const char *name)
// csoundSetControlChannel (CSOUND *csound, const char *name, MYFLT val)
// csoundGetChannelDatasize (CSOUND *csound, const char *name)
// csoundSetInputChannelCallback (CSOUND *csound, channelCallback_t inputChannelCalback)
// csoundSetOutputChannelCallback (CSOUND *csound, channelCallback_t outputChannelCalback)
// csoundSetPvsChannel (CSOUND *, const PVSDATEXT *fin, const char *name)
// csoundGetPvsChannel (CSOUND *csound, PVSDATEXT *fout, const char *name)
// csoundScoreEvent (CSOUND *, char type, const MYFLT *pFields, long numFields)
// csoundScoreEventAsync (CSOUND *, char type, const MYFLT *pFields, long numFields)
// csoundScoreEventAbsolute (CSOUND *, char type, const MYFLT *pfields, long numFields, double time_ofs)
// csoundScoreEventAbsoluteAsync (CSOUND *, char type, const MYFLT *pfields, long numFields, double time_ofs)
// csoundKillInstance (CSOUND *csound, MYFLT instr, char *instrName, int mode, int allow_release)
// csoundRegisterSenseEventCallback (CSOUND *, void(*func)(CSOUND *, void *), void *userData)
// csoundKeyPress (CSOUND *, char c)
// csoundRegisterKeyboardCallback (CSOUND *, int(*func)(void *userData, void *p, unsigned int type), void *userData, unsigned int type)
// csoundRemoveKeyboardCallback (CSOUND *csound, int(*func)(void *, void *, unsigned int))
<|endoftext|>