<commit_before>var gulp = require('gulp');
var browserSync = require('browser-sync').create();
var uglify = require('gulp-uglify');
var browserify = require('browserify');
var concat = require('gulp-concat');
var rename = require('gulp-rename');
var sass = require('gulp-sass');
var inject = require('gulp-inject');

gulp.task('default', ['serve']);

// Static Server + watching js/scss/html files
gulp.task('serve', ['sass', 'js', 'html', 'bower'], function() {

    browserSync.init({
        server: {
            baseDir: "./app",
            routes: {
                "/vendor": "app/vendor",
                "/js": "app/js",
                "/css": "app/css",
                "/partials": "app/partials"
            }
        }
    });

    /* If you use a proxy replace the previous code with the below script replacing "yourlocal.dev" with your local proxy

        browserSync.init({
            proxy: "yourlocal.dev"
        });

   */

    gulp.watch("./scss/*.scss", ['sass-watch']);

    gulp.watch("./app/**/*.html", ['html-watch']);

    gulp.watch("./app/js/**/*.js", ['js-watch']);

    gulp.watch("./bower_components/**/*.js", ['bower']);
});

gulp.task('index', function() {
    var target = gulp.src('./app/index.html');
    var sources = gulp.src(["./bower_components/**/*.js", "./app/js/app.js", "./app/js/factories/**/.js", "./app/js/services/**/.js", "./app/js/controllers/**/.js", "./app/js/directives/**/.js", "./app/js/decorators/**/.js", "./bower_components/**/*.css"], { read: false });

    return target.pipe(inject(sources))
        .pipe(gulp.dest('./app'));
});

// Compile sass into CSS & auto-inject into browsers
gulp.task('html', function() {
    return gulp.src("./app/**/*.html")
        .pipe(gulp.dest("./app"))
        .pipe(gulp.dest("./dist"))
        .pipe(browserSync.stream());
});

// Compile sass into CSS & auto-inject into browsers
gulp.task('sass', function() {
    return gulp.src("scss/**/*.scss")
        .pipe(sass())
        .pipe(gulp.dest("./app/css"))
        .pipe(gulp.dest("./dist/css"))
        .pipe(browserSync.stream());
});
// process JS files and return the stream.
gulp.task('js', function() {
    return gulp.src('./app/js/**/*.js')
        .pipe(gulp.dest('./dist/js'));
});

// process JS files and return the stream.
gulp.task('uglify-js', function() {
    return gulp.src('./app/js/**/*.js')
        .pipe(concat('all.js'))
        .pipe(gulp.dest('./dist'))
        .pipe(rename('all.min.js'))
        .pipe(uglify())
        .pipe(gulp.dest('./dist/js'));
});

// process JS files and return the stream.
gulp.task('bower', ['index'], function() {
    return gulp.src(["./bower_components/**/*.min.js", "./bower_components/**/*.min.css"])
        .pipe(gulp.dest('./app/bower_components'))
        .pipe(gulp.dest('./dist/bower_components'));
});

gulp.task('html-watch', ['html'], function(done) {
    browserSync.reload();
    done();
});

gulp.task('sass-watch', ['sass', 'index'], function(done) {
    browserSync.reload();
    done();
});

gulp.task('js-watch', ['js', 'index'], function(done) {
    browserSync.reload();
    done();
});
<commit_msg>Added all dependency injection<commit_after>var gulp = require('gulp');
var browserSync = require('browser-sync').create();
var uglify = require('gulp-uglify');
var browserify = require('browserify');
var concat = require('gulp-concat');
var rename = require('gulp-rename');
var sass = require('gulp-sass');
var inject = require('gulp-inject');

gulp.task('default', ['serve']);

// Static Server + watching js/scss/html files
gulp.task('serve', ['sass', 'js', 'html', 'bower'], function() {

    browserSync.init({
        server: {
            baseDir: "./app",
            routes: {
                "/vendor": "app/vendor",
                "/js": "app/js",
                "/css": "app/css",
                "/partials": "app/partials"
            }
        }
    });

    /* If you use a proxy replace the previous code with the below script replacing "yourlocal.dev" with your local proxy

        browserSync.init({
            proxy: "yourlocal.dev"
        });

   */

    gulp.watch("./scss/*.scss", ['sass-watch']);

    gulp.watch("./app/**/*.html", ['html-watch']);

    gulp.watch("./app/js/**/*.js", ['js-watch']);

    gulp.watch("./bower_components/**/*.js", ['bower']);
});

gulp.task('index', function() {
    var target = gulp.src('./app/index.html');
    var sources = gulp.src(["./bower_components/**/*.js", "./app/js/app.js", "./app/js/factories/**/.js", "./app/js/services/**/.js", "./app/js/controllers/**/.js", "./app/js/directives/**/.js", "./app/js/decorators/**/.js", "./bower_components/**/*.css", "./app/css/**/*.css"], { read: false });

    return target.pipe(inject(sources))
        .pipe(gulp.dest('./app'));
});

// Compile sass into CSS & auto-inject into browsers
gulp.task('html', function() {
    return gulp.src("./app/**/*.html")
        .pipe(gulp.dest("./app"))
        .pipe(gulp.dest("./dist"))
        .pipe(browserSync.stream());
});

// Compile sass into CSS & auto-inject into browsers
gulp.task('sass', function() {
    return gulp.src("scss/**/*.scss")
        .pipe(sass())
        .pipe(gulp.dest("./app/css"))
        .pipe(gulp.dest("./dist/css"))
        .pipe(browserSync.stream());
});
// process JS files and return the stream.
gulp.task('js', function() {
    return gulp.src('./app/js/**/*.js')
        .pipe(gulp.dest('./dist/js'));
});

// process JS files and return the stream.
gulp.task('uglify-js', function() {
    return gulp.src('./app/js/**/*.js')
        .pipe(concat('all.js'))
        .pipe(gulp.dest('./dist'))
        .pipe(rename('all.min.js'))
        .pipe(uglify())
        .pipe(gulp.dest('./dist/js'));
});

// process JS files and return the stream.
gulp.task('bower', ['index'], function() {
    return gulp.src(["./bower_components/**/*.min.js", "./bower_components/**/*.min.css"])
        .pipe(gulp.dest('./app/bower_components'))
        .pipe(gulp.dest('./dist/bower_components'));
});

gulp.task('html-watch', ['html'], function(done) {
    browserSync.reload();
    done();
});

gulp.task('sass-watch', ['sass', 'index'], function(done) {
    browserSync.reload();
    done();
});

gulp.task('js-watch', ['js', 'index'], function(done) {
    browserSync.reload();
    done();
});
<|endoftext|>


<commit_before>/*
 * This file is part of the CoreSphereConsoleBundle.
 *
 * (c) Laszlo Korte <me@laszlokorte.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

window.CoreSphereConsole = (function (window) {
    "use strict";

    if (typeof window.jQuery === "undefied") {
        window.alert('jQuery has not been loaded');
        return;
    }

    var $ = window.jQuery,

        default_options = {
            'filters' : {
                'clear' : function () {
                    this.log.html('');

                    return '';
                }
            },

            'active_suggestion_class' : 'active'
        },

        helpers = {

            htmlEscape : function (input) {
                return input
                    .split("&").join("&")
                    .split("<").join("<")
                    .split(">").join(">");
            },

            regexpEscape : (function () {
                var regexp = new RegExp(
                    '(\\' + [
                        '.', '*', '+', '?', '|',
                        '(', ')', '[', ']', '{', '}', '\\'
                    ].join('|\\') + ')',
                    'g'
                );

                return function (input) {
                    return input.replace(regexp, '\\$1');
                };
            }()),

            focusInput : function (el) {
                var range, sel, textRange;
                el.focus();
                if (typeof window.getSelection !== "undefined"
                        && typeof window.document.createRange !== "undefined") {
                    range = window.document.createRange();
                    sel = window.getSelection();
                    range.selectNodeContents(el);
                    range.collapse(false);
                    sel.removeAllRanges();
                    sel.addRange(range);
                } else if (typeof window.document.body.createTextRange !== "undefined") {
                    textRange = window.document.body.createTextRange();
                    textRange.moveToElementText(el);
                    textRange.collapse(false);
                    textRange.select();
                }
            }

        },

        keys = {
            'tab' : 9,
            'enter' : 13,
            'escape' : 27,
            'left' : 37,
            'up' : 38,
            'right' : 39,
            'down': 40
        },

        Console = function (base_element, options) {
            this.options = $.extend(default_options, options);

            this.base             = base_element;
            this.input            = base_element.find('.console_input');
            this.log_container    = base_element.find('.console_log_container');
            this.log              = base_element.find('.console_log');
            this.suggestion_box   = base_element.find('.console_suggestions');
            this.active_suggestion = null;
            this.first_suggestion  = null;

            this.initHistory();
            this.bindEvents();
            this.unlock();
            this.focus();
            this.welcome();
        };

    Console.prototype.focus = function () {
        helpers.focusInput(this.input[0]);
    };

    Console.prototype.initHistory = function () {
        if (!window.localStorage.coresphere_console_history) {
            window.localStorage.coresphere_console_history = '[]';
        }

        this.history = JSON.parse(window.localStorage.coresphere_console_history).slice(-20);
        this.history_position = this.history.length;
    };

    Console.prototype.pushHistory = function (val) {
        this.history.push(val);
        this.history_position = this.history.length;

        window.localStorage.coresphere_console_history = JSON.stringify(this.history);
    };

    Console.prototype.clearHistory = function () {
        window.localStorage.removeKey('coresphere_console_history');
    };

    Console.prototype.bindEvents = function () {
        var enable_suggestions = true,
            this_console = this;

        this.base

            .on('click.coresphere_console', '.console_command', function () {
                enable_suggestions = true;
                this_console.setValue($(this).text()).trigger('keyup');
                this_console.focus();
            })

            .on('mouseover.coresphere_console', '.console_suggestions li', function () {
                var $this = $(this);

                this_console.suggestion_box.find('.' + this_console.options.active_suggestion_class).removeClass(this_console.options.active_suggestion_class);
                $this.addClass(this_console.options.active_suggestion_class);
                this_console.active_suggestion = $this.text();

                this_console.focus();
            })

            .on('click.coresphere_console', '.console_suggestions li', function (event) {
                event.stopPropagation();
                var $this = $(this);
                this_console.setValue($this.text());
                this_console.clearSuggestions();
                this_console.focus();
            })

            .on('click.coresphere_console', '.console_log_input', function () {
                $(this).next('.console_log_output').stop().slideToggle(100);
            })

            .on('keydown.coresphere_console', '.console_input', function (event) {
                var val,
                    command,
                    filter,
                    current_suggestions,
                    active_suggestion,
                    next;

                if (this_console.isLocked()) {
                    return;
                }

                val = this_console.getValue();

                if (event.which === keys.tab) {

                    event.preventDefault();

                    if (this_console.active_suggestion) {
                        this_console.setValue(this_console.active_suggestion);
                        this_console.focus();
                    } else if (this_console.first_suggestion) {
                        this_console.setValue(this_console.first_suggestion);
                        this_console.focus();
                    }

                } else if (event.which === keys.enter && !event.shiftKey) {

                    if (this_console.active_suggestion) {
                        if (val !== this_console.active_suggestion) {
                            this_console.setValue(val = this_console.active_suggestion);
                            this_console.clearSuggestions();
                            this_console.focus();

                            event.preventDefault();
                            return;
                        }
                    }

                    command = val;

                    this_console.setValue('');

                    if (val.length && this_console.history[this_console.history.length - 1] !== val) {
                        this_console.pushHistory(val);
                    }

                    if (command.substr(0, 1) === '.') {
                        filter = command.substr(1);

                        if (this_console.options.filters[filter]) {
                            command = this_console.options.filters[filter].call(this_console);
                        }
                    }

                    if (command.length) {
                        this_console.lock();

                        this_console.log.find('li:not(.console_loading) .console_log_output').last().hide();

                        this_console.log.append('

' + helpers.htmlEscape(val) + '

' + this_console.options.lang.loading + '

');

                        this_console.sendCommand(command);
                    } else {
                        this_console.focus();
                    }

                    event.preventDefault();

                } else if (event.which === keys.up || event.which === keys.down) {

                    current_suggestions = this_console.suggestion_box.find('li');
                    active_suggestion = current_suggestions.filter('.' + this_console.options.active_suggestion_class);

                    if (event.which === keys.up) {
                        if (current_suggestions.size()) {
                            next = active_suggestion.size() ? active_suggestion.removeClass(this_console.options.active_suggestion_class).prev() : current_suggestions.last();
                            next = next.size() ? next : current_suggestions.last();
                            this_console.active_suggestion = next.addClass(this_console.options.active_suggestion_class).text();
                        } else {
                            this_console.history_position -= 1;
                            if (this_console.history_position < 0) {
                                this_console.history_position = 0;
                            } else {
                                this_console.setValue(this_console.history[this_console.history_position]);
                            }
                        }
                    } else {
                        // DOWN

                        if (current_suggestions.size()) {
                            next = active_suggestion.size() ? active_suggestion.removeClass(this_console.options.active_suggestion_class).next() : current_suggestions.first();
                            next = next.size() ? next : current_suggestions.first();
                            this_console.active_suggestion = next.addClass(this_console.options.active_suggestion_class).text();
                        } else {
                            this_console.history_position += 1;
                            if (this_console.history_position >= this_console.history.length) {
                                this_console.history_position = this_console.history.length;
                                this_console.setValue('');
                            } else {
                                this_console.setValue(this_console.history[this_console.history_position]);
                            }
                        }

                    }

                    this_console.focus();
                    enable_suggestions = false;

                    event.preventDefault();

                } else if (event.which === keys.escape) {

                    if (this_console.suggestion_box.find('li').size()) {
                        this_console.suggestion_box.text('');
                    } else {
                        this_console.setValue('');
                    }
                    enable_suggestions = false;
                    this_console.focus();
                }

                if ((event.which < keys.left || event.which > keys.down) && event.which !== keys.escape) {
                    enable_suggestions = true;
                }
            })

            .on('keyup.coresphere_console', '.console_input', function () {

                if (enable_suggestions) {
                    var val = this_console.getValue(),
                        best_suggestions = [],
                        other_suggestions = [],
                        suggestions,
                        any = 0,
                        htmlcode,
                        index,
                        j;

                    if (val.length) {
                        for (index = 0, j = this_console.options.commands.length; index < j; index += 1) {
                            if (new RegExp('^' + helpers.regexpEscape(val)).test(this_console.options.commands[index])) {
                                best_suggestions.push(this_console.options.commands[index]);
                                any += 1;
                            } else if (new RegExp(helpers.regexpEscape(val)).test(this_console.options.commands[index])) {
                                other_suggestions.push(this_console.options.commands[index]);
                                any += 1;
                            }
                            if (this_console.options.commands[index] === val) {
                                any -= 1;
                            }
                        }

                        suggestions = best_suggestions.concat(other_suggestions);
                    }

                    if (any) {
                        this_console.first_suggestion = best_suggestions[0];

                        if (!this_console.active_suggestion) {
                            this_console.active_suggestion = this_console.first_suggestion;
                        }

                        enable_suggestions = false;

                        htmlcode  = '
' + this_console.options.lang.suggestion_head + '
';
                        htmlcode += '
';
                        for (index = 0, j = suggestions.length; index < j; index += 1) {
                            htmlcode += suggestions[index] === this_console.active_suggestion ? '
' : '
';
                            htmlcode += suggestions[index].replace(val, '' + val + '') + '
';
                        }
                        htmlcode += '
';
                        this_console.suggestion_box.html(htmlcode);
                    } else {
                        this_console.first_suggestion = null;
                        this_console.active_suggestion = null;

                        this_console.suggestion_box.text('');
                    }
                }

            })

            .on('focus.coresphere_console', '.console_input', function () {
                this_console.suggestion_box.show();
            });

        $(window.document)

            .on('mousedown.coresphere_console', function (event) {
                var $target = $(event.target);
                if ($target.is('.console_input')
                        || $target.is('.console_suggestions')
                        || $target.is('.console_suggestions li')
                        ) {
                    return;
                }
                this_console.suggestion_box.hide();
            })

            .on('focus.coresphere_console', function () {
                this_console.focus();
            });
    };

    Console.prototype.unbindEvents = function () {
        this.base.off('.coresphere_console');
        $(window.document).off('.coresphere_console');
    };

    Console.prototype.lock = function () {
        this.locked = true;
    };

    Console.prototype.unlock = function () {
        this.locked = false;
    };

    Console.prototype.isLocked = function () {
        return this.locked === true;
    };

    Console.prototype.getValue = function () {
        return this.input.text();
    };

    Console.prototype.setValue = function (val) {
        return this.input.text(val);
    };

    Console.prototype.getActiveSuggestion = function () {
        return this.active_suggestion;
    };

    Console.prototype.clearSuggestions = function () {
        return this.suggestion_box.text('');
    };

    Console.prototype.welcome = function () {
        this.log.append('
' + this.options.lang.welcome_message + '
');
    };

    Console.prototype.sendCommand = function (command) {

        var this_console = this;

        return $.ajax({
            url: this.options.post_path,
            type: "POST",
            data: ({"command" : command}),
            dataType: "json"
        })

            .done(function (json) {
                var answer = json.output.replace(/^\s+|\s+$/g, ""),
                    htmlcode = '

'
                                + helpers.htmlEscape(command)

                                + (json.environment !== this_console.options.environment ?
                                    '' + this_console.options.lang.environment + ': '
                                    + json.environment
                                    + ''
                                    :
                                    ''
                               )

                                + '

'
                                + (answer.length ? answer : this_console.options.lang.empty_response)
                                + '

';

                this_console.log.append(htmlcode);
            })

            .fail(function (xhr, msg, error) {
                this_console.log.append('

' + helpers.htmlEscape(command) + '

[' + msg + '] ' + error + '

');
            })

            .then(function () {
                this_console.log.find('.console_loading').remove();
                this_console.unlock();
                this_console.log_container.scrollTop(this_console.log.outerHeight());
                this_console.focus();
            });
    };

    return Console;

}(window));
<commit_msg>fix regexp escape of ^ and $<commit_after>/*
 * This file is part of the CoreSphereConsoleBundle.
 *
 * (c) Laszlo Korte <me@laszlokorte.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

window.CoreSphereConsole = (function (window) {
    "use strict";

    if (typeof window.jQuery === "undefied") {
        window.alert('jQuery has not been loaded');
        return;
    }

    var $ = window.jQuery,

        default_options = {
            'filters' : {
                'clear' : function () {
                    this.log.html('');

                    return '';
                }
            },

            'active_suggestion_class' : 'active'
        },

        helpers = {

            htmlEscape : function (input) {
                return input
                    .split("&").join("&")
                    .split("<").join("<")
                    .split(">").join(">");
            },

            regexpEscape : (function () {
                var regexp = new RegExp(
                    '(\\' + [
                        '.', '*', '+', '?', '|',
                        '^', '$',
                        '(', ')', '[', ']', '{', '}', '\\'
                    ].join('|\\') + ')',
                    'g'
                );

                return function (input) {
                    return input.replace(regexp, '\\$1');
                };
            }()),

            focusInput : function (el) {
                var range, sel, textRange;
                el.focus();
                if (typeof window.getSelection !== "undefined"
                        && typeof window.document.createRange !== "undefined") {
                    range = window.document.createRange();
                    sel = window.getSelection();
                    range.selectNodeContents(el);
                    range.collapse(false);
                    sel.removeAllRanges();
                    sel.addRange(range);
                } else if (typeof window.document.body.createTextRange !== "undefined") {
                    textRange = window.document.body.createTextRange();
                    textRange.moveToElementText(el);
                    textRange.collapse(false);
                    textRange.select();
                }
            }

        },

        keys = {
            'tab' : 9,
            'enter' : 13,
            'escape' : 27,
            'left' : 37,
            'up' : 38,
            'right' : 39,
            'down': 40
        },

        Console = function (base_element, options) {
            this.options = $.extend(default_options, options);

            this.base             = base_element;
            this.input            = base_element.find('.console_input');
            this.log_container    = base_element.find('.console_log_container');
            this.log              = base_element.find('.console_log');
            this.suggestion_box   = base_element.find('.console_suggestions');
            this.active_suggestion = null;
            this.first_suggestion  = null;

            this.initHistory();
            this.bindEvents();
            this.unlock();
            this.focus();
            this.welcome();
        };

    Console.prototype.focus = function () {
        helpers.focusInput(this.input[0]);
    };

    Console.prototype.initHistory = function () {
        if (!window.localStorage.coresphere_console_history) {
            window.localStorage.coresphere_console_history = '[]';
        }

        this.history = JSON.parse(window.localStorage.coresphere_console_history).slice(-20);
        this.history_position = this.history.length;
    };

    Console.prototype.pushHistory = function (val) {
        this.history.push(val);
        this.history_position = this.history.length;

        window.localStorage.coresphere_console_history = JSON.stringify(this.history);
    };

    Console.prototype.clearHistory = function () {
        window.localStorage.removeKey('coresphere_console_history');
    };

    Console.prototype.bindEvents = function () {
        var enable_suggestions = true,
            this_console = this;

        this.base

            .on('click.coresphere_console', '.console_command', function () {
                enable_suggestions = true;
                this_console.setValue($(this).text()).trigger('keyup');
                this_console.focus();
            })

            .on('mouseover.coresphere_console', '.console_suggestions li', function () {
                var $this = $(this);

                this_console.suggestion_box.find('.' + this_console.options.active_suggestion_class).removeClass(this_console.options.active_suggestion_class);
                $this.addClass(this_console.options.active_suggestion_class);
                this_console.active_suggestion = $this.text();

                this_console.focus();
            })

            .on('click.coresphere_console', '.console_suggestions li', function (event) {
                event.stopPropagation();
                var $this = $(this);
                this_console.setValue($this.text());
                this_console.clearSuggestions();
                this_console.focus();
            })

            .on('click.coresphere_console', '.console_log_input', function () {
                $(this).next('.console_log_output').stop().slideToggle(100);
            })

            .on('keydown.coresphere_console', '.console_input', function (event) {
                var val,
                    command,
                    filter,
                    current_suggestions,
                    active_suggestion,
                    next;

                if (this_console.isLocked()) {
                    return;
                }

                val = this_console.getValue();

                if (event.which === keys.tab) {

                    event.preventDefault();

                    if (this_console.active_suggestion) {
                        this_console.setValue(this_console.active_suggestion);
                        this_console.focus();
                    } else if (this_console.first_suggestion) {
                        this_console.setValue(this_console.first_suggestion);
                        this_console.focus();
                    }

                } else if (event.which === keys.enter && !event.shiftKey) {

                    if (this_console.active_suggestion) {
                        if (val !== this_console.active_suggestion) {
                            this_console.setValue(val = this_console.active_suggestion);
                            this_console.clearSuggestions();
                            this_console.focus();

                            event.preventDefault();
                            return;
                        }
                    }

                    command = val;

                    this_console.setValue('');

                    if (val.length && this_console.history[this_console.history.length - 1] !== val) {
                        this_console.pushHistory(val);
                    }

                    if (command.substr(0, 1) === '.') {
                        filter = command.substr(1);

                        if (this_console.options.filters[filter]) {
                            command = this_console.options.filters[filter].call(this_console);
                        }
                    }

                    if (command.length) {
                        this_console.lock();

                        this_console.log.find('li:not(.console_loading) .console_log_output').last().hide();

                        this_console.log.append('

' + helpers.htmlEscape(val) + '

' + this_console.options.lang.loading + '

');

                        this_console.sendCommand(command);
                    } else {
                        this_console.focus();
                    }

                    event.preventDefault();

                } else if (event.which === keys.up || event.which === keys.down) {

                    current_suggestions = this_console.suggestion_box.find('li');
                    active_suggestion = current_suggestions.filter('.' + this_console.options.active_suggestion_class);

                    if (event.which === keys.up) {
                        if (current_suggestions.size()) {
                            next = active_suggestion.size() ? active_suggestion.removeClass(this_console.options.active_suggestion_class).prev() : current_suggestions.last();
                            next = next.size() ? next : current_suggestions.last();
                            this_console.active_suggestion = next.addClass(this_console.options.active_suggestion_class).text();
                        } else {
                            this_console.history_position -= 1;
                            if (this_console.history_position < 0) {
                                this_console.history_position = 0;
                            } else {
                                this_console.setValue(this_console.history[this_console.history_position]);
                            }
                        }
                    } else {
                        // DOWN

                        if (current_suggestions.size()) {
                            next = active_suggestion.size() ? active_suggestion.removeClass(this_console.options.active_suggestion_class).next() : current_suggestions.first();
                            next = next.size() ? next : current_suggestions.first();
                            this_console.active_suggestion = next.addClass(this_console.options.active_suggestion_class).text();
                        } else {
                            this_console.history_position += 1;
                            if (this_console.history_position >= this_console.history.length) {
                                this_console.history_position = this_console.history.length;
                                this_console.setValue('');
                            } else {
                                this_console.setValue(this_console.history[this_console.history_position]);
                            }
                        }

                    }

                    this_console.focus();
                    enable_suggestions = false;

                    event.preventDefault();

                } else if (event.which === keys.escape) {

                    if (this_console.suggestion_box.find('li').size()) {
                        this_console.suggestion_box.text('');
                    } else {
                        this_console.setValue('');
                    }
                    enable_suggestions = false;
                    this_console.focus();
                }

                if ((event.which < keys.left || event.which > keys.down) && event.which !== keys.escape) {
                    enable_suggestions = true;
                }
            })

            .on('keyup.coresphere_console', '.console_input', function () {

                if (enable_suggestions) {
                    var val = this_console.getValue(),
                        best_suggestions = [],
                        other_suggestions = [],
                        suggestions,
                        any = 0,
                        htmlcode,
                        index,
                        j;

                    if (val.length) {
                        for (index = 0, j = this_console.options.commands.length; index < j; index += 1) {
                            if (new RegExp('^' + helpers.regexpEscape(val)).test(this_console.options.commands[index])) {
                                best_suggestions.push(this_console.options.commands[index]);
                                any += 1;
                            } else if (new RegExp(helpers.regexpEscape(val)).test(this_console.options.commands[index])) {
                                other_suggestions.push(this_console.options.commands[index]);
                                any += 1;
                            }
                            if (this_console.options.commands[index] === val) {
                                any -= 1;
                            }
                        }

                        suggestions = best_suggestions.concat(other_suggestions);
                    }

                    if (any) {
                        this_console.first_suggestion = best_suggestions[0];

                        if (!this_console.active_suggestion) {
                            this_console.active_suggestion = this_console.first_suggestion;
                        }

                        enable_suggestions = false;

                        htmlcode  = '
' + this_console.options.lang.suggestion_head + '
';
                        htmlcode += '
';
                        for (index = 0, j = suggestions.length; index < j; index += 1) {
                            htmlcode += suggestions[index] === this_console.active_suggestion ? '
' : '
';
                            htmlcode += suggestions[index].replace(val, '' + val + '') + '
';
                        }
                        htmlcode += '
';
                        this_console.suggestion_box.html(htmlcode);
                    } else {
                        this_console.first_suggestion = null;
                        this_console.active_suggestion = null;

                        this_console.suggestion_box.text('');
                    }
                }

            })

            .on('focus.coresphere_console', '.console_input', function () {
                this_console.suggestion_box.show();
            });

        $(window.document)

            .on('mousedown.coresphere_console', function (event) {
                var $target = $(event.target);
                if ($target.is('.console_input')
                        || $target.is('.console_suggestions')
                        || $target.is('.console_suggestions li')
                        ) {
                    return;
                }
                this_console.suggestion_box.hide();
            })

            .on('focus.coresphere_console', function () {
                this_console.focus();
            });
    };

    Console.prototype.unbindEvents = function () {
        this.base.off('.coresphere_console');
        $(window.document).off('.coresphere_console');
    };

    Console.prototype.lock = function () {
        this.locked = true;
    };

    Console.prototype.unlock = function () {
        this.locked = false;
    };

    Console.prototype.isLocked = function () {
        return this.locked === true;
    };

    Console.prototype.getValue = function () {
        return this.input.text();
    };

    Console.prototype.setValue = function (val) {
        return this.input.text(val);
    };

    Console.prototype.getActiveSuggestion = function () {
        return this.active_suggestion;
    };

    Console.prototype.clearSuggestions = function () {
        return this.suggestion_box.text('');
    };

    Console.prototype.welcome = function () {
        this.log.append('
' + this.options.lang.welcome_message + '
');
    };

    Console.prototype.sendCommand = function (command) {

        var this_console = this;

        return $.ajax({
            url: this.options.post_path,
            type: "POST",
            data: ({"command" : command}),
            dataType: "json"
        })

            .done(function (json) {
                var answer = json.output.replace(/^\s+|\s+$/g, ""),
                    htmlcode = '

'
                                + helpers.htmlEscape(command)

                                + (json.environment !== this_console.options.environment ?
                                    '' + this_console.options.lang.environment + ': '
                                    + json.environment
                                    + ''
                                    :
                                    ''
                               )

                                + '

'
                                + (answer.length ? answer : this_console.options.lang.empty_response)
                                + '

';

                this_console.log.append(htmlcode);
            })

            .fail(function (xhr, msg, error) {
                this_console.log.append('

' + helpers.htmlEscape(command) + '

[' + msg + '] ' + error + '

');
            })

            .then(function () {
                this_console.log.find('.console_loading').remove();
                this_console.unlock();
                this_console.log_container.scrollTop(this_console.log.outerHeight());
                this_console.focus();
            });
    };

    return Console;

}(window));
<|endoftext|>


<commit_before>(function () {
	//Detailwindow en zijn elementen
	var DetailWindow = {
		window: Titanium.UI.createWindow({
			top: 			0,
			height: 		'100%',
			width: 			'100%',
			backgroundColor: VwApp.Config.ViewBackgroundColor,
			contentHeight: 	'auto'
		}),

		// Een container waar we alles in stoppen
		Container: Titanium.UI.createScrollView({
			height:			'100%',
			width:			'100%',
			layout:			'vertical'
		}),
		//wanneer er een foto beschikbaar is deze weergeven in een imageview
		Imagebridge : 	Ti.UI.createImageView({
			image:				'',
			height: 			'auto',
			width: 				'80%',
			top: 				'2%',
			bottom:				'5%'
		}),
		//Wanneer er geen foto beschikbaar is komt er een tekst te staan
		NoImagebridge : Titanium.UI.createLabel({
			text : 			"",
			textAlign : 	"left",
			left: 			'3 %',
			bottom: 		'5%',
			width : 		'auto',
			heigth : 		'auto',
			color:			VwApp.Config.TextColor
		}),

		//Hieronder staan de eigenschappen van de data
		Type : Titanium.UI.createLabel({
			text : 			"",
			textAlign : 	"left",
			left: 			'3 %',
			width : 		'auto',
			heigth : 		'auto',
			color:			VwApp.Config.TextColor
		}),

		Hoogte : Titanium.UI.createLabel({
			text : 			"",
			textAlign : 	"left",
			left: 			'3 %',
			width : 		'auto',
			heigth : 		'auto',
			color:			VwApp.Config.TextColor
		}),

		Breedte : Titanium.UI.createLabel({
			text : 			"",
			textAlign : 	"left",
			left: 			'3 %',
			width : 		'auto',
			heigth : 		'auto',
			color:			VwApp.Config.TextColor
		}),

		Bron : 	Titanium.UI.createLabel({
			text : 			"",
			textAlign : 	"left",
			left: 			'3 %',
			width : 		'auto',
			heigth : 		'auto',
			color:			VwApp.Config.TextColor
		}),

		Adres : Titanium.UI.createLabel({
			text : 			"",
			textAlign : 	"left",
			left: 			'3 %',
			width : 		'auto',
			heigth : 		'auto',
			top:			'5%',
			color:			VwApp.Config.TextColor
		}),

		Postcode : 	Titanium.UI.createLabel({
			text : 			"",
			textAlign : 	"left",
			left: 			'3 %',
			width : 		'auto',
			heigth : 		'auto',
			color:			VwApp.Config.TextColor
		}),

		Stad : 	Titanium.UI.createLabel({
			text : 			"",
			textAlign : 	"left",
			left: 			'3 %',
			width : 		'auto',
			heigth : 		'auto',
			color:			VwApp.Config.TextColor
		}),

		Oppervlakte : 	Titanium.UI.createLabel({
			text : 			"",
			textAlign : 	"left",
			left: 			'3 %',
			width : 		'auto',
			heigth : 		'auto',
			color:			VwApp.Config.TextColor
		}),

		Code : 	Titanium.UI.createLabel({
			text : 			"",
			textAlign : 	"left",
			left: 			'3 %',
			width : 		'auto',
			heigth : 		'auto',
			color:			VwApp.Config.TextColor
		}),

		//de button om de brug op de kaart te tonen
		Toonkaart : Titanium.UI.createButton({
			top: 			60,
			image:			VwApp.Config.ShowOnMap,
			position: 		'center'
		})
	};
	//variabelen voor de lat en de lon
	var Lat = "";
	var Lon = "";

	//changevalue wanneer er iets aangeklikt wordt in de lijst
	function ChangeValue(data) {
		//wanneer er geen data is gevonden, niks doen.
		if (!data) {
			return;
		}
		//title
		if (data.title){
			DetailWindow.window.setTitle(data.title);
		}
		else{
			DetailWindow.window.setTitle("-");
		}

		//afbeelding
		if(data.TYPE == 'ligplaatsen' || data.TYPE == 'bruggen')
		{
			//kijken of er een foto beschikbaar is en of het laten zien van foto's aangevinkt is in de settings.
			if(data.PICTURE && Titanium.App.Properties.getBool('laadData', true)){
				//foto tonen
				if(data.TYPE == 'bruggen'){
					DetailWindow.Imagebridge.setImage(ChangeBridgeLink(data.PICTURE));
				}
				if(data.TYPE == 'ligplaatsen'){
						DetailWindow.Imagebridge.setImage(ChangeMoorageLink(data.PICTURE));
				}

				DetailWindow.Imagebridge.setHeight('auto');
				DetailWindow.NoImagebridge.setText("");
			}
			else {  //geen foto beschikbaar
				// wanneer foto's laden ingeschakeld is en er is geen foto beschikbaar toon de tekst dat er geen foto beschikbaar is
				if (Titanium.App.Properties.getBool('laadData', true)) {
						DetailWindow.Imagebridge.setHeight('0%');  //image hoogte is 0%, dus niet zichtbaar
						DetailWindow.NoImagebridge.setText(VwApp.Config.NoPictureDetail);
				}
				// als het laden van foto's uitgeschakeld is geef hierover een melding
				else {

					DetailWindow.Imagebridge.setHeight('0%'); //image hoogte is 0%, dus niet zichtbaar
					DetailWindow.NoImagebridge.setText(VwApp.Config.PictureOffDetail);
				}
			}
			DetailWindow.Container.add(DetailWindow.Imagebridge);
			DetailWindow.Container.add(DetailWindow.NoImagebridge);
		}
		//adres, geldt alleen voor bepaalde types
		if (data.TYPE == 'jachthavens' || data.TYPE == 'bruggen'){
			if (data.ADRESS) {
				DetailWindow.Adres.setText(VwApp.Config.AdressDetail + data.ADRESS);
			}
			else {
				DetailWindow.Adres.setText(VwApp.Config.AdressDetail + "-");
			}
			DetailWindow.Container.add(DetailWindow.Adres);
		}

		if(data.TYPE == 'bruggen') {
			//hoogte
			if(data.HEIGHT || data.HEIGHT == 0) {
				DetailWindow.Hoogte.setText(VwApp.Config.HeigthDetail + data.HEIGHT + VwApp.Config.UnitDetail);
			} else {
				DetailWindow.Hoogte.setText(VwApp.Config.HeigthDetail + "-");
			}

			//breedte
			if(data.WIDTH || data.WIDTH == 0) {
				DetailWindow.Breedte.setText(VwApp.Config.WidthDetail + data.WIDTH + VwApp.Config.UnitDetail);
			} else {
				DetailWindow.Breedte.setText(VwApp.Config.WidthDetail +"-");
			}

			//type
			if(data.BRIDGETYPE) {
				DetailWindow.Type.setText(VwApp.Config.TypeDetail + data.BRIDGETYPE);
			} else {
				DetailWindow.Type.setText(VwApp.Config.TypeDetail + "-");
			}

			//bron
			if(data.SOURCE) {
				DetailWindow.Type.setText(VwApp.Config.BronDetail + data.SOURCE);
			} else {
				DetailWindow.Type.setText(VwApp.Config.BronDetail + "-");
			}

			DetailWindow.Container.add(DetailWindow.Type);
			DetailWindow.Container.add(DetailWindow.Hoogte);
			DetailWindow.Container.add(DetailWindow.Breedte);
			DetailWindow.Container.add(DetailWindow.Bron);
		}
		if(data.TYPE == 'jachthavens') {
			//postcode
			if(data.ZIPCODE) {
				DetailWindow.Postcode.setText(VwApp.Config.ZipcodeDetail + data.ZIPCODE);
			} else {
				DetailWindow.Postcode.setText(VwApp.Config.ZipcodeDetail + "-");
			}

			//stad
			if(data.CITY) {
				DetailWindow.Stad.setText(VwApp.Config.CityDetail + data.CITY);
			} else {
				DetailWindow.Stad.setText(VwApp.Config.CityDetail + "-");
			}

			//oppervlakte
			if(data.SIZE) {
				DetailWindow.Oppervlakte.setText(VwApp.Config.SizeDetail + data.SIZE + VwApp.Config.SquareUnitDetail);
			} else {
				DetailWindow.Oppervlakte.setText(VwApp.Config.SizeDetail + "-");
			}

			DetailWindow.Container.add(DetailWindow.Stad);
			DetailWindow.Container.add(DetailWindow.Postcode);
			DetailWindow.Container.add(DetailWindow.Oppervlakte);
		}
		if(data.TYPE == 'ligplaatsen') {
			if(data.MOORAGETYPE) {
				DetailWindow.Type.setText(VwApp.Config.TypeDetail + data.MOORAGETYPE);
			} else {
				DetailWindow.Type.setText(VwApp.Config.TypeDetail + "-");
			}

			if(data.CODE) {
				DetailWindow.Code.setText(VwApp.Config.CodeDetail + data.CODE);
			} else {
				DetailWindow.Code.setText(VwApp.Config.CodeDetail + "-");
			}

			DetailWindow.Container.add(DetailWindow.Type);
			DetailWindow.Container.add(DetailWindow.Code);
		}

		if(data.LON && data.LAT) {
		    Lat = data.LAT;
		  	Lon = data.LON;
		} else {
			Lat = "";
		  	Lon = "";
		}

		//toonkaart hier pas toevoegen, anders komt deze bovenaan te staan
		DetailWindow.Container.add(DetailWindow.Toonkaart);
	}

	/**
	 * De onnodige info van de link afhalen zodat deze in te laden is als image, toe te passen op de bruglinks
 	 * @param {string} link, van de afbeelding naar een pagina van de brug
 	 *
	 */
	function ChangeBridgeLink(link) {
		//inladen van de oude link
		var oldlink = link;

		//link die ontstaat uit de oude link
		var newlink = "";

		//integer om het aantal '/' te tellen
		var slash = 0;

		//de oude link doorlopen, karakter voor karakter
		for(var i = 0; i < oldlink.length; i++)	{
			//wanneer en een ',' voorkomt, stoppen met het maken van de nieuwe link
			if(oldlink[i] == ',')
				return newlink;

			//het aantal '/' tellen
			if(oldlink[i] == '/') {
				newlink = newlink + oldlink[i];
				slash++;
			}
			//bij de 6de slash
			if(slash == 6) {
				slash++;

				//alles er tussenuithalen tot er een '=' komt
				while(oldlink[i] != '=') {
					i++
				}
			}
			//else de nieuwe link maken
			if(oldlink[i] != ',' && oldlink[i] != '/' && oldlink[i] != '=' && oldlink[i] != undefined) {
				newlink = newlink + oldlink[i];
			}

		}
	}

	function ChangeMoorageLink(oldlink) {

		//link die ontstaat uit de oude link
		var newlink = "";

		//integer om het aantal '/' te tellen
		var slash = 0;

		//de oude link doorlopen, karakter voor karakter
		for (var i = 0; i < oldlink.length; i++) {
			if(oldlink[i] == '/') {
				slash++
			}

			//bij de 7de slash
			if(slash == 7) {
				//stukje toevoegen aan de nieuwe link
				newlink = newlink +"/foto_marrekrite/";
				//de laatste 5 karakters plakken aan de nieuwe link
				for(var n = oldlink.length - 5; n < oldlink.length; n++) {
					newlink = newlink + oldlink[n];
				}
				//fotonummer toevoegen aan de link, in dit geval altijd 1
				newlink = newlink + "_1.jpg";
				return newlink;
			}
			//newlink maken uit de oude link
			newlink = newlink + oldlink[i];
		}

	}
	//wanneer er geklikt wordt op de button setlocation op map en open de map, mits lat en lon aanwezig
	DetailWindow.Toonkaart.addEventListener('click', function(){
		if(Lat != "") {
			VwApp.Map.setLocation(Lat, Lon, VwApp.Config.DefaultUserLocZoom);
			VwApp.UI.TabBar.tabGroup.setActiveTab(VwApp.UI.TabBar.mapTab);
			VwApp.UI.DetailWindow.window.close();
		}
	});

	//toevoegen aan scrollview
	DetailWindow.window.add(DetailWindow.Container);

	VwApp.UI.DetailWindow = DetailWindow;
	VwApp.UI.changeDetailView = ChangeValue;
})();
<commit_msg>Jasper cleanup<commit_after>(function () {
	//Detailwindow en zijn elementen
	var DetailWindow = {
		window: Titanium.UI.createWindow({
			top: 			0,
			height: 		'100%',
			width: 			'100%',
			backgroundColor: VwApp.Config.ViewBackgroundColor,
			contentHeight: 	'auto'
		}),

		// Een container waar we alles in stoppen
		Container: Titanium.UI.createScrollView({
			height:			'100%',
			width:			'100%',
			layout:			'vertical'
		}),

		//wanneer er een foto beschikbaar is deze weergeven in een imageview
		Imagebridge : 	Ti.UI.createImageView({
			image:				'',
			height: 			'auto',
			width: 				'80%',
			top: 				'2%',
			bottom:				'5%'
		}),

		// Wanneer er geen foto beschikbaar is komt er een tekst te staan
		NoImagebridge : Titanium.UI.createLabel({
			text : 			"",
			textAlign : 	"left",
			left: 			'3 %',
			bottom: 		'5%',
			width : 		'auto',
			heigth : 		'auto',
			color:			VwApp.Config.TextColor
		}),

		// Hieronder staan de eigenschappen van de data
		Type : Titanium.UI.createLabel({
			text : 			"",
			textAlign : 	"left",
			left: 			'3 %',
			width : 		'auto',
			heigth : 		'auto',
			color:			VwApp.Config.TextColor
		}),

		Hoogte : Titanium.UI.createLabel({
			text : 			"",
			textAlign : 	"left",
			left: 			'3 %',
			width : 		'auto',
			heigth : 		'auto',
			color:			VwApp.Config.TextColor
		}),

		Breedte : Titanium.UI.createLabel({
			text : 			"",
			textAlign : 	"left",
			left: 			'3 %',
			width : 		'auto',
			heigth : 		'auto',
			color:			VwApp.Config.TextColor
		}),

		Bron : 	Titanium.UI.createLabel({
			text : 			"",
			textAlign : 	"left",
			left: 			'3 %',
			width : 		'auto',
			heigth : 		'auto',
			color:			VwApp.Config.TextColor
		}),

		Adres : Titanium.UI.createLabel({
			text : 			"",
			textAlign : 	"left",
			left: 			'3 %',
			width : 		'auto',
			heigth : 		'auto',
			top:			'5%',
			color:			VwApp.Config.TextColor
		}),

		Postcode : 	Titanium.UI.createLabel({
			text : 			"",
			textAlign : 	"left",
			left: 			'3 %',
			width : 		'auto',
			heigth : 		'auto',
			color:			VwApp.Config.TextColor
		}),

		Stad : 	Titanium.UI.createLabel({
			text : 			"",
			textAlign : 	"left",
			left: 			'3 %',
			width : 		'auto',
			heigth : 		'auto',
			color:			VwApp.Config.TextColor
		}),

		Oppervlakte : 	Titanium.UI.createLabel({
			text : 			"",
			textAlign : 	"left",
			left: 			'3 %',
			width : 		'auto',
			heigth : 		'auto',
			color:			VwApp.Config.TextColor
		}),

		Code : 	Titanium.UI.createLabel({
			text : 			"",
			textAlign : 	"left",
			left: 			'3 %',
			width : 		'auto',
			heigth : 		'auto',
			color:			VwApp.Config.TextColor
		}),

		//de button om de brug op de kaart te tonen
		Toonkaart : Titanium.UI.createButton({
			top: 			60,
			image:			VwApp.Config.ShowOnMap,
			position: 		'center'
		})
	};

	// variabelen voor de lat en de lon
	var Lat = "";
	var Lon = "";

	/**
	 *	Een functie die de meegegeven data zal omzetten naar
	 * 		de nieuwe informatie voor de detailView
	 *
	 *	@param {Object} [data]
	 * 		De meegegeven informatie over een annotatie
	 */
	function ChangeValue(data) {
		// wanneer er geen data is gevonden, niks doen.
		if (!data) {
			return;
		}
		// title
		if (data.title) {
			DetailWindow.window.setTitle(data.title);
		} else {
			DetailWindow.window.setTitle("-");
		}

		// afbeelding
		if (data.TYPE == 'ligplaatsen' || data.TYPE == 'bruggen') {
			//kijken of er een foto beschikbaar is en of het laten zien van foto's aangevinkt is in de settings.
			if (data.PICTURE && Titanium.App.Properties.getBool('laadData', true)) {
				//foto tonen
				if (data.TYPE == 'bruggen') {
					DetailWindow.Imagebridge.setImage(ChangeBridgeLink(data.PICTURE));
				}

				if (data.TYPE == 'ligplaatsen') {
						DetailWindow.Imagebridge.setImage(ChangeMoorageLink(data.PICTURE));
				}

				DetailWindow.Imagebridge.setHeight('auto');
				DetailWindow.NoImagebridge.setText("");
			} else {
				// geen foto beschikbaar

				// wanneer foto's laden ingeschakeld is en er is geen foto beschikbaar toon de tekst dat er geen foto beschikbaar is
				if (Titanium.App.Properties.getBool('laadData', true)) {
						DetailWindow.Imagebridge.setHeight('0%');  //image hoogte is 0%, dus niet zichtbaar
						DetailWindow.NoImagebridge.setText(VwApp.Config.NoPictureDetail);
				}
				// als het laden van foto's uitgeschakeld is geef hierover een melding
				else {

					DetailWindow.Imagebridge.setHeight('0%'); //image hoogte is 0%, dus niet zichtbaar
					DetailWindow.NoImagebridge.setText(VwApp.Config.PictureOffDetail);
				}
			}
			DetailWindow.Container.add(DetailWindow.Imagebridge);
			DetailWindow.Container.add(DetailWindow.NoImagebridge);
		}

		// adres, geldt alleen voor bepaalde types
		if (data.TYPE == 'jachthavens' || data.TYPE == 'bruggen') {
			if (data.ADRESS) {
				DetailWindow.Adres.setText(VwApp.Config.AdressDetail + data.ADRESS);
			} else {
				DetailWindow.Adres.setText(VwApp.Config.AdressDetail + "-");
			}

			DetailWindow.Container.add(DetailWindow.Adres);
		}

		if (data.TYPE == 'bruggen') {
			// hoogte
			if (data.HEIGHT || data.HEIGHT == 0) {
				DetailWindow.Hoogte.setText(VwApp.Config.HeigthDetail + data.HEIGHT + VwApp.Config.UnitDetail);
			} else {
				DetailWindow.Hoogte.setText(VwApp.Config.HeigthDetail + "-");
			}

			// breedte
			if (data.WIDTH || data.WIDTH == 0) {
				DetailWindow.Breedte.setText(VwApp.Config.WidthDetail + data.WIDTH + VwApp.Config.UnitDetail);
			} else {
				DetailWindow.Breedte.setText(VwApp.Config.WidthDetail +"-");
			}

			// type
			if (data.BRIDGETYPE) {
				DetailWindow.Type.setText(VwApp.Config.TypeDetail + data.BRIDGETYPE);
			} else {
				DetailWindow.Type.setText(VwApp.Config.TypeDetail + "-");
			}

			// bron
			if (data.SOURCE) {
				DetailWindow.Type.setText(VwApp.Config.BronDetail + data.SOURCE);
			} else {
				DetailWindow.Type.setText(VwApp.Config.BronDetail + "-");
			}

			DetailWindow.Container.add(DetailWindow.Type);
			DetailWindow.Container.add(DetailWindow.Hoogte);
			DetailWindow.Container.add(DetailWindow.Breedte);
			DetailWindow.Container.add(DetailWindow.Bron);
		}

		if (data.TYPE == 'jachthavens') {
			// postcode
			if(data.ZIPCODE) {
				DetailWindow.Postcode.setText(VwApp.Config.ZipcodeDetail + data.ZIPCODE);
			} else {
				DetailWindow.Postcode.setText(VwApp.Config.ZipcodeDetail + "-");
			}

			// stad
			if (data.CITY) {
				DetailWindow.Stad.setText(VwApp.Config.CityDetail + data.CITY);
			} else {
				DetailWindow.Stad.setText(VwApp.Config.CityDetail + "-");
			}

			// oppervlakte
			if (data.SIZE) {
				DetailWindow.Oppervlakte.setText(VwApp.Config.SizeDetail + data.SIZE + VwApp.Config.SquareUnitDetail);
			} else {
				DetailWindow.Oppervlakte.setText(VwApp.Config.SizeDetail + "-");
			}

			DetailWindow.Container.add(DetailWindow.Stad);
			DetailWindow.Container.add(DetailWindow.Postcode);
			DetailWindow.Container.add(DetailWindow.Oppervlakte);
		}

		if (data.TYPE == 'ligplaatsen') {
			if (data.MOORAGETYPE) {
				DetailWindow.Type.setText(VwApp.Config.TypeDetail + data.MOORAGETYPE);
			} else {
				DetailWindow.Type.setText(VwApp.Config.TypeDetail + "-");
			}

			if (data.CODE) {
				DetailWindow.Code.setText(VwApp.Config.CodeDetail + data.CODE);
			} else {
				DetailWindow.Code.setText(VwApp.Config.CodeDetail + "-");
			}

			DetailWindow.Container.add(DetailWindow.Type);
			DetailWindow.Container.add(DetailWindow.Code);
		}

		if (data.LON && data.LAT) {
		    Lat = data.LAT;
		  	Lon = data.LON;
		} else {
			Lat = "";
		  	Lon = "";
		}

		// toonkaart hier pas toevoegen, anders komt deze bovenaan te staan
		DetailWindow.Container.add(DetailWindow.Toonkaart);
	}

	/**
	 * De onnodige info van de link afhalen zodat deze in te laden is als image, toe te passen op de bruglinks
 	 *
 	 * @param {string} [link]
 	 * 		Een link naar een afbeelding
	 */
	function ChangeBridgeLink(link) {
		// inladen van de oude link
		var oldlink = link;

		// link die ontstaat uit de oude link
		var newlink = "";

		//integer om het aantal '/' te tellen
		var slash = 0;

		// de oude link doorlopen, karakter voor karakter
		for (var i = 0; i < oldlink.length; i++) {
			// wanneer en een ',' voorkomt, stoppen met het maken van de nieuwe link
			if (oldlink[i] == ',')
				return newlink;

			// het aantal '/' tellen
			if (oldlink[i] == '/') {
				newlink = newlink + oldlink[i];
				slash++;
			}
			// bij de 6de slash
			if (slash == 6) {
				slash++;

				// alles er tussenuithalen tot er een '=' komt
				while (oldlink[i] != '=') {
					i++
				}
			}
			// else de nieuwe link maken
			if (oldlink[i] != ',' && oldlink[i] != '/' && oldlink[i] != '=' && oldlink[i] != undefined) {
				newlink = newlink + oldlink[i];
			}

		}
	}

	/**
	 * Een functie die de link naar een marrekrite aanlegplaats
	 * 		klaarmaakt voor gebruik
	 *
 	 * @param {Object} [oldlink]
 	 * 		De link naar de afbeelding zoals deze voorkomt in de annotaties data
 	 *
	 */
	function ChangeMoorageLink(oldlink) {

		// link die ontstaat uit de oude link
		var newlink = "";

		// integer om het aantal '/' te tellen
		var slash = 0;

		// de oude link doorlopen, karakter voor karakter
		for (var i = 0; i < oldlink.length; i++) {
			if (oldlink[i] == '/') {
				slash++
			}

			// bij de 7de slash
			if (slash == 7) {
				// stukje toevoegen aan de nieuwe link
				newlink = newlink + "/foto_marrekrite/";
				// de laatste 5 karakters plakken aan de nieuwe link
				for (var n = oldlink.length - 5; n < oldlink.length; n++) {
					newlink = newlink + oldlink[n];
				}
				// fotonummer toevoegen aan de link, in dit geval altijd 1
				newlink = newlink + "_1.jpg";
				return newlink;
			}
			// newlink maken uit de oude link
			newlink = newlink + oldlink[i];
		}

	}

	// wanneer er geklikt wordt op de button setlocation op map en open de map, mits lat en lon aanwezig
	DetailWindow.Toonkaart.addEventListener('click', function() {
		if (Lat != "") {
			VwApp.Map.setLocation(Lat, Lon, VwApp.Config.DefaultUserLocZoom);
			VwApp.UI.TabBar.tabGroup.setActiveTab(VwApp.UI.TabBar.mapTab);
			VwApp.UI.DetailWindow.window.close();
		}
	});

	// toevoegen aan scrollview
	DetailWindow.window.add(DetailWindow.Container);

	VwApp.UI.DetailWindow = DetailWindow;
	VwApp.UI.changeDetailView = ChangeValue;
})();
<|endoftext|>


<commit_before>module.exports = {
    parser: 'babel-eslint', // Default parser throws unexpected token error while the syntax is correct
    parserOptions: {
        ecmaVersion: 6,
        ecmaFeatures: {
            jsx: true,
            modules: true,
            experimentalObjectRestSpread: true,
        },
    },
    env: {
        browser: true,
        es6: true,
    },
    extends: 'airbnb',
    rules: {
        'max-len': ['error', 120],
        'require-jsdoc': [
            'warn',
            {
                require: {
                    FunctionDeclaration: true,
                    MethodDefinition: true,
                    ClassDeclaration: true,
                },
            },
        ],
        'valid-jsdoc': [
            'warn',
            {
                requireReturn: false,
            },
        ],
        indent: ['error', 4, { SwitchCase: 1 }],
        'import/no-extraneous-dependencies': [
            'off',
            {
                devDependencies: false,
                optionalDependencies: false,
                peerDependencies: false,
            },
        ],
        'import/no-unresolved': ['off'],
        'import/extensions': ['off'],
        'import/no-named-as-default': ['off'],
        'import/no-named-as-default-member': ['off'],
        'no-underscore-dangle': [
            'error',
            {
                allowAfterThis: true,
            },
        ],
        'no-restricted-syntax': ['off'],
        'no-plusplus': ['off'],
        'class-methods-use-this': ['off'],
        'arrow-body-style': 'off',
        'prefer-template': 'off',
        'jsx-a11y/no-static-element-interactions': 'off',
        'jsx-a11y/no-noninteractive-element-interactions': 'off',
        'jsx-a11y/anchor-is-valid': 'off', // Due to using React-Router Link components
        'react/jsx-indent': ['error', 4],
        'react/jsx-indent-props': ['error', 4],
        'no-mixed-operators': ['error'],
        'jsx-quotes': ['error', 'prefer-single'],
        'no-else-return': 'off',
        'no-unused-vars': ['error'],
    },
    plugins: ['react'],
};<commit_msg>remove un-nessasary experimentalObjectRestSpread property<commit_after>module.exports = {
    parser: 'babel-eslint', // Default parser throws unexpected token error while the syntax is correct
    parserOptions: {
        ecmaVersion: 6,
        ecmaFeatures: {
            jsx: true,
            modules: true,
        },
    },
    env: {
        browser: true,
        es6: true,
    },
    extends: 'airbnb',
    rules: {
        'max-len': ['error', 120],
        'require-jsdoc': [
            'warn',
            {
                require: {
                    FunctionDeclaration: true,
                    MethodDefinition: true,
                    ClassDeclaration: true,
                },
            },
        ],
        'valid-jsdoc': [
            'warn',
            {
                requireReturn: false,
            },
        ],
        indent: ['error', 4, { SwitchCase: 1 }],
        'import/no-extraneous-dependencies': [
            'off',
            {
                devDependencies: false,
                optionalDependencies: false,
                peerDependencies: false,
            },
        ],
        'import/no-unresolved': ['off'],
        'import/extensions': ['off'],
        'import/no-named-as-default': ['off'],
        'import/no-named-as-default-member': ['off'],
        'no-underscore-dangle': [
            'error',
            {
                allowAfterThis: true,
            },
        ],
        'no-restricted-syntax': ['off'],
        'no-plusplus': ['off'],
        'class-methods-use-this': ['off'],
        'arrow-body-style': 'off',
        'prefer-template': 'off',
        'jsx-a11y/no-static-element-interactions': 'off',
        'jsx-a11y/no-noninteractive-element-interactions': 'off',
        'jsx-a11y/anchor-is-valid': 'off', // Due to using React-Router Link components
        'react/jsx-indent': ['error', 4],
        'react/jsx-indent-props': ['error', 4],
        'no-mixed-operators': ['error'],
        'jsx-quotes': ['error', 'prefer-single'],
        'no-else-return': 'off',
        'no-unused-vars': ['error'],
    },
    plugins: ['react'],
};<|endoftext|>


<commit_before>
// stomp-server/middleware.js -- Basic broker middleware

// Load modules
var frame = require('./frame');

function InvalidFrameError(conn, frame_obj, description) {
    Error.call(this, 'Invalid frame: ' + description );
    this.conn = conn;
    this.frame_obj = frame_obj;
    this.description = description;
}

function ProtocolError(conn, frame_obj, description) {
    Error.call(this, 'Protocol error: ' + description );
    this.conn = conn;
    this.frame_obj = frame_obj;
    this.description = description;
}

function Debug(conn, frame_obj) {
    console.log(frame_obj.cmd
                + ' '
                + JSON.stringify(frame_obj.headers)
                + ' '
                + JSON.stringify(frame_obj.body)
                + '\r');
    return frame_obj;
}

function DefaultError(conn, error_obj) {
    // Log error
    console.log('error: ' + error_obj.toString() + '\r\n');

    // Construct an ERROR frame
    var frame_obj = new frame.Frame('ERROR', null, error_obj.toString());

    // Send the ERROR frame
    this.send_frame(conn, frame_obj);

    // Operation Complete!
    return null;
}

function ValidRecvFrame(conn, frame_obj) {
    switch(frame_obj.cmd) {
        case 'CONNECT':
        case 'SUBSCRIBE':
        case 'UNSUBSCRIBE':
        case 'BEGIN':
        case 'COMMIT':
        case 'ABORT':
        case 'ACK':
        case 'DISCONNECT':
        case 'SEND':
            return frame_obj;
            break;
        default:
            throw new InvalidFrameError(conn, frame_obj, 'Invalid client command');
    }
}

function ValidSendFrame(conn, frame_obj) {
    switch(frame_obj.cmd) {
        case 'CONNECTED':
        case 'MESSAGE':
        case 'RECEIPT':
        case 'ERROR':
            return frame_obj;
            break;
        default:
            throw new InvalidFrameError(conn, frame_obj, 'Invalid server command');
    }
}

function ConnectRecv(conn, frame_obj) {
    // Make sure the client is connected
    if( !conn.connected ) {
        if( frame_obj.cmd != 'CONNECT' )
            throw new ProtocolError(conn, frame_obj, 'Client must CONNECT');
        // Automatically accept the client
        this.send_frame(
                conn,
                new frame.Frame('CONNECTED', {session: conn._id}));
        conn.connected = true;
        frame_obj.handled = true;
    }

    // Operation Complete!
    return frame_obj;
}

// NOTE: This middleware layer should be applied after frame is processed
function AutoReceiptRecv(conn, frame_obj) {
    if( frame_obj.headers.receipt )
        this.send_frame(
                conn,
                new frame.Frame(
                    'RECEIPT',
                    {'receipt-id': frame_obj.headers.receipt}));

    // Operation Complete!
    return frame_obj;
}

// Export middleware
module.exports.InvalidFrameError = InvalidFrameError;
module.exports.ProtocolError = ProtocolError;
module.exports.DefaultError = DefaultError;
module.exports.ValidRecvFrame = ValidRecvFrame;
module.exports.ValidSendFrame = ValidSendFrame;
module.exports.ConnectRecv = ConnectRecv;
module.exports.Debug = Debug;
<commit_msg>Style update<commit_after>
// stomp-server/middleware.js -- Basic broker middleware

// Load modules
var frame = require('./frame');

function InvalidFrameError(conn, frame_obj, description) {
    Error.call(this, 'Invalid frame: ' + description );
    this.conn = conn;
    this.frame_obj = frame_obj;
    this.description = description;
}

function ProtocolError(conn, frame_obj, description) {
    Error.call(this, 'Protocol error: ' + description );
    this.conn = conn;
    this.frame_obj = frame_obj;
    this.description = description;
}

function Debug(conn, frame_obj) {
    console.log(frame_obj.cmd
                + ' '
                + JSON.stringify(frame_obj.headers)
                + ' '
                + JSON.stringify(frame_obj.body)
                + '\r');
    return frame_obj;
}

function DefaultError(conn, error_obj) {
    // Log error
    console.log('error: ' + error_obj.toString() + '\r\n');

    // Construct an ERROR frame
    var frame_obj = new frame.Frame('ERROR', null, error_obj.toString());

    // Send the ERROR frame
    this.send_frame(conn, frame_obj);

    // Operation Complete!
    return null;
}

function ValidRecvFrame(conn, frame_obj) {
    switch(frame_obj.cmd) {
        case 'CONNECT':
        case 'SUBSCRIBE':
        case 'UNSUBSCRIBE':
        case 'BEGIN':
        case 'COMMIT':
        case 'ABORT':
        case 'ACK':
        case 'DISCONNECT':
        case 'SEND':
            return frame_obj;
            break;
        default:
            throw new InvalidFrameError(conn, frame_obj, 'Invalid client command');
    }
}

function ValidSendFrame(conn, frame_obj) {
    switch(frame_obj.cmd) {
        case 'CONNECTED':
        case 'MESSAGE':
        case 'RECEIPT':
        case 'ERROR':
            return frame_obj;
            break;
        default:
            throw new InvalidFrameError(conn, frame_obj, 'Invalid server command');
    }
}

function ConnectRecv(conn, frame_obj) {
    // Make sure the client is connected
    if( !conn.connected ) {
        if( frame_obj.cmd != 'CONNECT' )
            throw new ProtocolError(conn, frame_obj, 'Client must CONNECT');

        // Automatically accept the client
        this.send_frame(
                conn,
                new frame.Frame('CONNECTED', {session: conn._id}));
        conn.connected = true;
        frame_obj.handled = true;
    }

    // Operation Complete!
    return frame_obj;
}

// NOTE: This middleware layer should be applied after frame is processed
function AutoReceiptRecv(conn, frame_obj) {
    if( frame_obj.headers.receipt )
        this.send_frame(
                conn,
                new frame.Frame(
                    'RECEIPT',
                    {'receipt-id': frame_obj.headers.receipt}));

    // Operation Complete!
    return frame_obj;
}

// Export middleware
module.exports.InvalidFrameError = InvalidFrameError;
module.exports.ProtocolError = ProtocolError;
module.exports.DefaultError = DefaultError;
module.exports.ValidRecvFrame = ValidRecvFrame;
module.exports.ValidSendFrame = ValidSendFrame;
module.exports.ConnectRecv = ConnectRecv;
module.exports.Debug = Debug;
<|endoftext|>


<commit_before>'use strict';

yeomanApp.factory('AlertFactory'
  , ['$rootScope', '$http', 'UIEvents', 'NinjaUtilities'
  , function($rootScope, $http, UIEvents, NinjaUtilities) {

    return function(options) {

      this.id = null;

      this.Options = {
        type: '',
        alertee: '',
        active: false
      };

      this.Options = NinjaUtilities.ObjectMerge(this.Options, options);

      var normalize = function() {
        if (this.Options.id) {
          this.id = this.Options.id;
          delete this.Options.id;
        }

      }.bind(this);
      normalize();

      /**
       * Saves the alert
       * @param {Function} callback Optional callback function
       */
      this.Save = function(callback) {
        if (DEBUG) console.log("Alert.Save()");

        if (this.id) { // EDIT EXISTING

          $http.put('/alert/' + this.id, this.Options).success(function(response) {
            if (DEBUG) console.log("AlertFactory.Put", response);

            $rootScope.$broadcast(UIEvents.AlertUpdated, this);
            if (callback) {
              callback(response);
            }
          }.bind(this));

        } else { // CREATE NEW
          $http.post('/alert', this.Options).success(function(response) {
            if (response.id && response.id.length > 30) {
              this.id = response.id;
              if (DEBUG) console.log("AlertFactory.Post", response);

              $rootScope.$broadcast(UIEvents.AlertAdded, this);
              if (callback) {
                callback(response);
              }
            }
          }.bind(this));
        }
      };

      /**
       * Deletes this alert
       */
      this.Delete = function() {

        $http.delete('/alert/' + this.id).success(function(response) {
          if (DEBUG) console.log("Alert.Delete()", response);
          $rootScope.$broadcast(UIEvents.AlertRemoved, this);
        }.bind(this));
      };

      /**
       * Activate this alert
       * @param {Function} callback Optional callback function
       */
      this.Activate = function(callback) {
        var payload = {
          active: true
        };
        $http.put('/alert/' + this.id, payload).success(function(response) {
          if (DEBUG) console.log("Alert.Activate", response);
          $rootScope.$broadcast(UIEvents.AlertActivated);
          this.Options.active = true;

          if (callback) { callback(response); }
        }.bind(this));
      };

      /**
       * Deactivate this alert
       * @param {Function} callback Optional callback function
       */
      this.Deactivate = function(callback) {
        var payload = {
          active: false
        }
        $http.put('/alert/' + this.id, payload).success(function(response) {
          if (DEBUG) console.log("Alert.Activate", response);
          $rootScope.$broadcast(UIEvents.AlertActivated);
          this.Options.active = false;

          if (callback) { callback(response); }
        }.bind(this));
      };
    };

  }]);<commit_msg>Default Alert's to active<commit_after>'use strict';

yeomanApp.factory('AlertFactory'
  , ['$rootScope', '$http', 'UIEvents', 'NinjaUtilities'
  , function($rootScope, $http, UIEvents, NinjaUtilities) {

    return function(options) {

      this.id = null;

      this.Options = {
        type: '',
        alertee: '',
        active: true
      };

      this.Options = NinjaUtilities.ObjectMerge(this.Options, options);

      var normalize = function() {
        if (this.Options.id) {
          this.id = this.Options.id;
          delete this.Options.id;
        }

      }.bind(this);
      normalize();

      /**
       * Saves the alert
       * @param {Function} callback Optional callback function
       */
      this.Save = function(callback) {
        if (DEBUG) console.log("Alert.Save()");

        if (this.id) { // EDIT EXISTING

          $http.put('/alert/' + this.id, this.Options).success(function(response) {
            if (DEBUG) console.log("AlertFactory.Put", response);

            $rootScope.$broadcast(UIEvents.AlertUpdated, this);
            if (callback) {
              callback(response);
            }
          }.bind(this));

        } else { // CREATE NEW
          $http.post('/alert', this.Options).success(function(response) {
            if (response.id && response.id.length > 30) {
              this.id = response.id;
              if (DEBUG) console.log("AlertFactory.Post", response);

              $rootScope.$broadcast(UIEvents.AlertAdded, this);
              if (callback) {
                callback(response);
              }
            }
          }.bind(this));
        }
      };

      /**
       * Deletes this alert
       */
      this.Delete = function() {

        $http.delete('/alert/' + this.id).success(function(response) {
          if (DEBUG) console.log("Alert.Delete()", response);
          $rootScope.$broadcast(UIEvents.AlertRemoved, this);
        }.bind(this));
      };

      /**
       * Activate this alert
       * @param {Function} callback Optional callback function
       */
      this.Activate = function(callback) {
        var payload = {
          active: true
        };
        $http.put('/alert/' + this.id, payload).success(function(response) {
          if (DEBUG) console.log("Alert.Activate", response);
          $rootScope.$broadcast(UIEvents.AlertActivated);
          this.Options.active = true;

          if (callback) { callback(response); }
        }.bind(this));
      };

      /**
       * Deactivate this alert
       * @param {Function} callback Optional callback function
       */
      this.Deactivate = function(callback) {
        var payload = {
          active: false
        }
        $http.put('/alert/' + this.id, payload).success(function(response) {
          if (DEBUG) console.log("Alert.Activate", response);
          $rootScope.$broadcast(UIEvents.AlertActivated);
          this.Options.active = false;

          if (callback) { callback(response); }
        }.bind(this));
      };
    };

  }]);<|endoftext|>


<commit_before>/*global messy:true, global*/
var argv = require('minimist')(process.argv.slice(2));

global.require = require;
messy = require('messy');
var unexpected = require('unexpected').clone().installPlugin(require('./lib/unexpectedMessy'));
var generator = require('unexpected-documentation-site-generator');
argv.unexpected = unexpected;
generator(argv);
<commit_msg>generate-site.js: Use a fixed width for the output.<commit_after>/*global messy:true, global*/
var argv = require('minimist')(process.argv.slice(2));

global.require = require;
messy = require('messy');
var unexpected = require('unexpected').clone().installPlugin(require('./lib/unexpectedMessy'));
var generator = require('unexpected-documentation-site-generator');
unexpected.output.preferredWidth = 80;
argv.unexpected = unexpected;
generator(argv);
<|endoftext|>


<commit_before>/*global global*/
var argv = require('minimist')(process.argv.slice(2));

global.require = require;
var unexpected = require('unexpected').clone().installPlugin(require('./lib/unexpectedImage'));
var generator = require('unexpected-documentation-site-generator');
argv.unexpected = unexpected;
generator(argv);
<commit_msg>generate-site.js: Use a fixed width for the output.<commit_after>/*global global*/
var argv = require('minimist')(process.argv.slice(2));

global.require = require;
var unexpected = require('unexpected').clone().installPlugin(require('./lib/unexpectedImage'));
unexpected.output.preferredWidth = 80;
var generator = require('unexpected-documentation-site-generator');
argv.unexpected = unexpected;
generator(argv);
<|endoftext|>


<commit_before>define(["Tone/core/Tone", "Tone/signal/Signal"], function(Tone){

	/**
	 *  Envelope
	 *  ADR envelope generator attaches to an AudioParam or AudioNode
	 *
	 *  @constructor
	 *  @extends {Tone}
	 *  @param {Tone.Time=} attack
	 *  @param {Tone.Time=} decay
	 *  @param {number=} sustain 	a percentage (0-1) of the full amplitude
	 *  @param {Tone.Time=} release
	 *  @param {number=} minOutput the lowest point of the envelope
	 *  @param {number=} maxOutput the highest point of the envelope
	 */
	Tone.Envelope = function(attack, decay, sustain, release, minOutput, maxOutput){
		//extend Unit
		Tone.call(this);

		/** @type {number} */
		this.attack = this.defaultArg(attack, 0.01);
		/** @type {number} */
		this.decay = this.defaultArg(decay, 0.1);
		/** @type {number} */
		this.release = this.defaultArg(release, 1);
		/** @type {number} */
		this.sustain = this.defaultArg(sustain, 0.5);

		/** @type {number} */
		this.min = this.defaultArg(minOutput, 0);
		/** @type {number} */
		this.max = this.defaultArg(maxOutput, 1);

		/** @type {Tone.Signal} */
		this.control = new Tone.Signal(this.min);

		//connections
		this.chain(this.control, this.output);
	};

	Tone.extend(Tone.Envelope);

	/**
	 * attack->decay->sustain linear ramp
	 * @param  {Tone.Time} time
	 */
	Tone.Envelope.prototype.triggerAttack = function(time){
		var startVal = this.min;
		if (!time){
			startVal = this.control.getValue();
		}
		time = this.defaultArg(time, this.now());
		time = this.toSeconds(time);
		this.control.cancelScheduledValues(time);
		this.control.setValueAtTime(startVal, time);
		var attackTime = this.toSeconds(this.attack);
		var decayTime = this.toSeconds(this.decay);
		this.control.linearRampToValueAtTime(this.max, time + attackTime);
		var sustainVal = (this.max - this.min) * this.sustain + this.min;
		this.control.linearRampToValueAtTime(sustainVal, time + attackTime + decayTime);
	};

	/**
	 * attack->decay->sustain exponential ramp
	 * @param  {Tone.Time} time
	 */
	Tone.Envelope.prototype.triggerExponentialAttack = function(time){
		var startVal = this.min;
		if (!time){
			startVal = this.control.getValue();
		}
		time = this.toSeconds(time);
		this.control.cancelScheduledValues(time);
		this.control.setValueAtTime(startVal, time);
		var attackTime = this.toSeconds(this.attack);
		var decayTime = this.toSeconds(this.decay);
		this.control.linearRampToValueAtTime(this.max, time + attackTime);
		var sustainVal = (this.max - this.min) * this.sustain + this.min;
		this.control.exponentialRampToValueAtTime(sustainVal, time + attackTime + decayTime);
	};

	/**
	 * triggers the release of the envelope with a linear ramp
	 * @param  {Tone.Time} time
	 */
	Tone.Envelope.prototype.triggerRelease = function(time){
		var startVal = this.control.getValue();
		if (time){
			startVal = (this.max - this.min) * this.sustain + this.min;
		}
		time = this.toSeconds(time);
		this.control.cancelScheduledValues(time);
		this.control.setValueAtTime(startVal, time);
		this.control.linearRampToValueAtTime(this.min, time + this.toSeconds(this.release));
	};

	/**
	 * triggers the release of the envelope with an exponential ramp
	 *
	 * @param  {Tone.Time} time
	 */
	Tone.Envelope.prototype.triggerExponentialRelease = function(time){
		var startVal = this.control.getValue();
		if (time){
			startVal = (this.max - this.min) * this.sustain + this.min;
		}
		time = this.toSeconds(time);
		this.control.cancelScheduledValues(time);
		this.control.setValueAtTime(startVal, time);
		this.control.exponentialRampToValueAtTime(this.min, time + this.toSeconds(this.release));
	};

	/**
	 * 	pointer to the parent's connect method
	 * 	@private
	 */
	Tone.Envelope.prototype._connect = Tone.prototype.connect;

	/**
	 * connect the envelope
	 *
	 * if the envelope is connected to a param, the params
	 * value will be set to 0 so that it doesn't interfere with the envelope
	 *
	 * @param  {number} param
	 */
	Tone.Envelope.prototype.connect = function(param){
		if (param instanceof AudioParam){
			//set the initial value
			param.value = 0;
		}
		this._connect(param);
	};

	/**
	 *  disconnect and dispose
	 */
	Tone.Envelope.prototype.dispose = function(){
		this.control.dispose();
		this.control = null;
	};

	return Tone.Envelope;
});
<commit_msg>jsdoc'ing and default values<commit_after>define(["Tone/core/Tone", "Tone/signal/Signal"], function(Tone){

	/**
	 *  Envelope
	 *  ADR envelope generator attaches to an AudioParam or AudioNode
	 *
	 *  @constructor
	 *  @extends {Tone}
	 *  @param {Tone.Time=} attack
	 *  @param {Tone.Time=} decay
	 *  @param {number=} sustain 	a percentage (0-1) of the full amplitude
	 *  @param {Tone.Time=} release
	 *  @param {number=} minOutput the lowest point of the envelope
	 *  @param {number=} maxOutput the highest point of the envelope
	 */
	Tone.Envelope = function(attack, decay, sustain, release, minOutput, maxOutput){
		//extend Unit
		Tone.call(this);

		/** @type {number} */
		this.attack = this.toSeconds(this.defaultArg(attack, 0.01));
		/** @type {number} */
		this.decay = this.toSeconds(this.defaultArg(decay, 0.1));
		/** @type {number} */
		this.release = this.toSeconds(this.defaultArg(release, 1));
		/** @type {number} */
		this.sustain = this.toSeconds(this.defaultArg(sustain, 0.5));

		/** @type {number} */
		this.min = this.defaultArg(minOutput, 0);
		/** @type {number} */
		this.max = this.defaultArg(maxOutput, 1);

		/** @type {Tone.Signal} */
		this.control = new Tone.Signal(this.min);

		//connections
		this.chain(this.control, this.output);
	};

	Tone.extend(Tone.Envelope);

	/**
	 * attack->decay->sustain linear ramp
	 * @param  {Tone.Time=} time
	 */
	Tone.Envelope.prototype.triggerAttack = function(time){
		var sustainVal = (this.max - this.min) * this.sustain + this.min;
		if (!time){
			this.control.linearRampToValueNow(this.max, this.attack);
			this.control.linearRampToValueAtTime(sustainVal, this.now() + this.attack + this.decay);
		} else {
			var startVal = this.min;
			time = this.toSeconds(time);
			this.control.cancelScheduledValues(time);
			this.control.setValueAtTime(startVal, time);
			this.control.linearRampToValueAtTime(this.max, time + this.attack);
			this.control.linearRampToValueAtTime(sustainVal, time + this.attack + this.decay);
		}
	};

	/**
	 * attack->decay->sustain exponential attack and linear decay
	 * @param  {Tone.Time=} time
	 */
	Tone.Envelope.prototype.triggerExponentialAttack = function(time){
		var sustainVal = (this.max - this.min) * this.sustain + this.min;
		if (!time){
			this.control.exponentialRampToValueNow(this.max, this.attack);
			this.control.linearRampToValueAtTime(sustainVal, this.now() + this.attack + this.decay);
		} else {
			var startVal = this.min;
			time = this.toSeconds(time);
			this.control.cancelScheduledValues(time);
			this.control.setValueAtTime(startVal, time);
			this.control.exponentialRampToValueAtTime(this.max, time + this.attack);
			this.control.linearRampToValueAtTime(sustainVal, time + this.attack + this.decay);
		}
	};

	/**
	 * triggers the release of the envelope with a linear ramp
	 * @param  {Tone.Time=} time
	 */
	Tone.Envelope.prototype.triggerRelease = function(time){
		if (time){
			//if there's a time, start at the sustain value
			startVal = (this.max - this.min) * this.sustain + this.min;
			time = this.toSeconds(time);
			this.control.cancelScheduledValues(time);
			this.control.setValueAtTime(startVal, time);
			this.control.linearRampToValueAtTime(this.min, time + this.toSeconds(this.release));
		} else {
			this.control.linearRampToValueNow(this.min, this.toSeconds(this.release));
		}
	};

	/**
	 * triggers the release of the envelope with an exponential ramp
	 *
	 * @param  {Tone.Time=} time
	 */
	Tone.Envelope.prototype.triggerExponentialRelease = function(time){
		if (time){
			//if there's a time, start at the sustain value
			startVal = (this.max - this.min) * this.sustain + this.min;
			time = this.toSeconds(time);
			this.control.cancelScheduledValues(time);
			this.control.setValueAtTime(startVal, time);
			this.control.exponentialRampToValueAtTime(this.min, time + this.toSeconds(this.release));
		} else {
			this.control.exponentialRampToValueNow(this.min, this.toSeconds(this.release));
		}
	};

	/**
	 * 	pointer to the parent's connect method
	 * 	@private
	 */
	Tone.Envelope.prototype._connect = Tone.prototype.connect;

	/**
	 * connect the envelope
	 *
	 * if the envelope is connected to a param, the params
	 * value will be set to 0 so that it doesn't interfere with the envelope
	 *
	 * @param  {number} param
	 */
	Tone.Envelope.prototype.connect = function(param){
		if (param instanceof AudioParam){
			//set the initial value
			param.value = 0;
		}
		this._connect(param);
	};

	/**
	 *  disconnect and dispose
	 */
	Tone.Envelope.prototype.dispose = function(){
		this.control.dispose();
		this.control = null;
	};

	return Tone.Envelope;
});
<|endoftext|>