<commit_before>/*jslint browser: true, sloppy: true, plusplus: true, nomen: true*/
/*globals angular, window */
'use strict';

/* Directives */

angular.module('cms.directives', []).
    directive('appVersion', ['version', function(version) {
        return function(scope, elm, attrs) {
          elm.text(version);
        };
    }])
    .directive('articleUrlName', [ function() {

        return {
            restrict: 'A', // only activate on element attribute
            link: function link(scope, element, attributes) {

                var changeToUrlName = function(pInputValue) {
                    if (!pInputValue) {
                        return '';
                    }
                    var articleTitle = pInputValue;
                    var urlName = articleTitle.replace(/[\x7f-\xff]/g, '').replace(/[ \t\r\n\v\f]/g, '-');
                    return urlName;
                };

                scope.$watch(attributes.ngModel, function(inputValue) {
                    // prevent typeError undefined for scope.article when initalizing
                    if (scope.article) {
                        scope.article.url_name = changeToUrlName(inputValue);
                    }
                });
            }
        };

    }])
    .directive('pageUrlName', [ function() {

        return {
            restrict: 'A', // only activate on element attribute
            link: function link(scope, element, attributes) {

                var changeToUrlName = function(pInputValue) {
                    if (!pInputValue) {
                        return '';
                    }
                    var pageTitle = pInputValue;
                    var urlName = pageTitle.replace(/[\x7f-\xff]/g, '').replace(/[ \t\r\n\v\f]/g, '-');
                    return urlName;
                };

                scope.$watch(attributes.ngModel, function(inputValue) {
                    // prevent typeError undefined for scope.article when initalizing
                    if (scope.page) {
                        scope.page.url_name = changeToUrlName(inputValue);
                    }
                });
            }
        };

    }])
    .directive('sameAs', function() {
        return {
            require: 'ngModel',
            link: function(scope, elm, attrs, ctrl) {
                ctrl.$parsers.unshift(function(viewValue) {
                    if (scope.debugModus) {
                        console.log("pw1: "+scope[attrs.sameAs]);
                        console.log("pw2: "+viewValue);
                    }
                    var isEqual = viewValue === scope[attrs.sameAs];
                    ctrl.$setValidity('sameas', isEqual);

                });
            }
        };
    })
    .directive('username', [ function() {
        return {
            restrict: 'A', // only activate on element attribute
            link: function link(scope, element, attributes) {
                console.log(attributes);
                // inital values
                var firstnameShort = '',
                    lastnameShort  = '',
                    user_name;

                scope.$watch('user.first_name', function() {
                    if (scope.user) {
                        firstnameShort = scope.user.first_name.substr(0,2).toLowerCase();
                        // update scope
                        scope.user.user_name = firstnameShort + lastnameShort;
                    }
                });
                scope.$watch('user.last_name', function() {
                    if (scope.user) {
                        lastnameShort = scope.user.last_name.substr(0,5).toLowerCase();
                        // update scope
                        scope.user.user_name = firstnameShort + lastnameShort;
                    }
                });
            }
        };

    }])
    .directive('geocode', [ function () {
        return {
            restrict: 'A',
            link: function (scope, element, attrs) {
                element.bind("keydown", function (event) {
                    // check if key is between 0 and z
                    // 96-105: numpad numbers
                    // 8: backspace
                    // 13: enter
                    // 32: space
                    if(!((event.which >= 48 && event.which <= 90) ||
                         (event.which >= 96 && event.which <= 105) ||
                          event.which === 8 ||
                          event.which === 13 ||
                          event.which === 32)) {
                        return;
                    }
                    scope.$apply(function () {
                        scope.$eval('checkTypeSpeed()');
                    });

                });
            }
        }
    }])
    .directive('deleteObject', ['$interval', '$timeout', 'genService', '$location', function($interval, $timeout, genService, $location) {
        return {
            restrict: 'A',
            link: function(scope, elem, attrs) {
                    var decreasePromise,
                        resetPromise,
                        timeToRemoval = 6; // 6 seconds until removal gets initiated

                    elem.bind("click", function() {
                        if (elem.val() === "started") {
                            elem.val("stopped");
                            $interval.cancel(decreasePromise);
                            scope.deleteMsg = 'Abgebrochen';

                            resetPromise = $timeout(function () {
                                scope.deleteMsg = 'Löschen';
                            }, 800);

                        } else {
                            elem.val("started");

                            $timeout.cancel(resetPromise);

                            decreasePromise = $interval( function(ctr) {
                                scope.deleteMsg = 'Abbrechen [' + (timeToRemoval - ctr - 1) + ']';
                            }, 1000, timeToRemoval);

                            decreasePromise.then(function () {
                                scope.deleteMsg = 'Gelöscht';
                                console.log(attrs);
                                genService.deleteObjectById(attrs.deleteObjectPath, attrs.deleteObjectId).then(function () {
                                    $timeout(function() {
                                        $location.path('/' + attrs.deleteObjectPath);
                                    }, 2500);
                                });
                            });
                        }
                    })

                    elem.on('$destroy', function() {
                        $timeout.cancel(resetPromise);
                        $interval.cancel(decreasePromise);
                    });
            }
        }
    }])
    .directive('goBack', ['$interval', '$timeout', 'genService', '$location', '$window', function($interval, $timeout, genService, $location, $window) {
        return {
            restrict: 'A',
            link: function(scope, elem, attrs) {
                    elem.bind("click", function() {
                        scope.isLocked = !scope.isLocked;
                        $window.history.back();
                    })
                }
        }
    }]);
<commit_msg>Remove console log statement<commit_after>/*jslint browser: true, sloppy: true, plusplus: true, nomen: true*/
/*globals angular, window */
'use strict';

/* Directives */

angular.module('cms.directives', []).
    directive('appVersion', ['version', function(version) {
        return function(scope, elm, attrs) {
          elm.text(version);
        };
    }])
    .directive('articleUrlName', [ function() {

        return {
            restrict: 'A', // only activate on element attribute
            link: function link(scope, element, attributes) {

                var changeToUrlName = function(pInputValue) {
                    if (!pInputValue) {
                        return '';
                    }
                    var articleTitle = pInputValue;
                    var urlName = articleTitle.replace(/[\x7f-\xff]/g, '').replace(/[ \t\r\n\v\f]/g, '-');
                    return urlName;
                };

                scope.$watch(attributes.ngModel, function(inputValue) {
                    // prevent typeError undefined for scope.article when initalizing
                    if (scope.article) {
                        scope.article.url_name = changeToUrlName(inputValue);
                    }
                });
            }
        };

    }])
    .directive('pageUrlName', [ function() {

        return {
            restrict: 'A', // only activate on element attribute
            link: function link(scope, element, attributes) {

                var changeToUrlName = function(pInputValue) {
                    if (!pInputValue) {
                        return '';
                    }
                    var pageTitle = pInputValue;
                    var urlName = pageTitle.replace(/[\x7f-\xff]/g, '').replace(/[ \t\r\n\v\f]/g, '-');
                    return urlName;
                };

                scope.$watch(attributes.ngModel, function(inputValue) {
                    // prevent typeError undefined for scope.article when initalizing
                    if (scope.page) {
                        scope.page.url_name = changeToUrlName(inputValue);
                    }
                });
            }
        };

    }])
    .directive('sameAs', function() {
        return {
            require: 'ngModel',
            link: function(scope, elm, attrs, ctrl) {
                ctrl.$parsers.unshift(function(viewValue) {
                    if (scope.debugModus) {
                        console.log("pw1: "+scope[attrs.sameAs]);
                        console.log("pw2: "+viewValue);
                    }
                    var isEqual = viewValue === scope[attrs.sameAs];
                    ctrl.$setValidity('sameas', isEqual);

                });
            }
        };
    })
    .directive('username', [ function() {
        return {
            restrict: 'A', // only activate on element attribute
            link: function link(scope, element, attributes) {
                console.log(attributes);
                // inital values
                var firstnameShort = '',
                    lastnameShort  = '',
                    user_name;

                scope.$watch('user.first_name', function() {
                    if (scope.user) {
                        firstnameShort = scope.user.first_name.substr(0,2).toLowerCase();
                        // update scope
                        scope.user.user_name = firstnameShort + lastnameShort;
                    }
                });
                scope.$watch('user.last_name', function() {
                    if (scope.user) {
                        lastnameShort = scope.user.last_name.substr(0,5).toLowerCase();
                        // update scope
                        scope.user.user_name = firstnameShort + lastnameShort;
                    }
                });
            }
        };

    }])
    .directive('geocode', [ function () {
        return {
            restrict: 'A',
            link: function (scope, element, attrs) {
                element.bind("keydown", function (event) {
                    // check if key is between 0 and z
                    // 96-105: numpad numbers
                    // 8: backspace
                    // 13: enter
                    // 32: space
                    if(!((event.which >= 48 && event.which <= 90) ||
                         (event.which >= 96 && event.which <= 105) ||
                          event.which === 8 ||
                          event.which === 13 ||
                          event.which === 32)) {
                        return;
                    }
                    scope.$apply(function () {
                        scope.$eval('checkTypeSpeed()');
                    });

                });
            }
        }
    }])
    .directive('deleteObject', ['$interval', '$timeout', 'genService', '$location', function($interval, $timeout, genService, $location) {
        return {
            restrict: 'A',
            link: function(scope, elem, attrs) {
                    var decreasePromise,
                        resetPromise,
                        timeToRemoval = 6; // 6 seconds until removal gets initiated

                    elem.bind("click", function() {
                        if (elem.val() === "started") {
                            elem.val("stopped");
                            $interval.cancel(decreasePromise);
                            scope.deleteMsg = 'Abgebrochen';

                            resetPromise = $timeout(function () {
                                scope.deleteMsg = 'Löschen';
                            }, 800);

                        } else {
                            elem.val("started");

                            $timeout.cancel(resetPromise);

                            decreasePromise = $interval( function(ctr) {
                                scope.deleteMsg = 'Abbrechen [' + (timeToRemoval - ctr - 1) + ']';
                            }, 1000, timeToRemoval);

                            decreasePromise.then(function () {
                                scope.deleteMsg = 'Gelöscht';
                                genService.deleteObjectById(attrs.deleteObjectPath, attrs.deleteObjectId).then(function () {
                                    $timeout(function() {
                                        $location.path('/' + attrs.deleteObjectPath);
                                    }, 2500);
                                });
                            });
                        }
                    })

                    elem.on('$destroy', function() {
                        $timeout.cancel(resetPromise);
                        $interval.cancel(decreasePromise);
                    });
            }
        }
    }])
    .directive('goBack', ['$interval', '$timeout', 'genService', '$location', '$window', function($interval, $timeout, genService, $location, $window) {
        return {
            restrict: 'A',
            link: function(scope, elem, attrs) {
                    elem.bind("click", function() {
                        scope.isLocked = !scope.isLocked;
                        $window.history.back();
                    })
                }
        }
    }]);
<|endoftext|>


<commit_before>/*globals $, _, window, Ractive, moment, Dropzone*/

var Files = Ractive.extend({
    noIntro: true,
    data: {
        uploading_files: [],
        gotall: false,
        page: 0,
        filter: [],
        shortdate: function (date) {
            return moment(date).format("ll");
        },
        taglink: function (tag) {
            var prefix = "/files/t/";
            if (tag) {
                var old_tags = window.location.href.split(prefix, 2);
                if (old_tags.length === 2) {
                    // we have tags
                    var tags = old_tags[1].split("/");
                    tags.push(tag);
                    return prefix + tags.uniq.join("/");

                }
                return prefix + tag;
            }
        }
    },
    search: function (query) {
        return $.ajax({
            url: '/tags',
            dataType: 'json',
            type: 'get',
            data: {
                q: query
            }
        });
    },
    updateFile: function (file) {
        return $.ajax({
            url: '/files/' + file._id,
            dataType: 'json',
            type: 'put',
            data: _.pick(file, 'filename', 'tags')
        });
    }
});

module.exports.fileDetailView = function (f) {
    var files = new Files({
        el: '#file',
        template: '#template',
        data: {
            file: f
        }
    });

    files.on('toggleEdit', function (event) {
        event.original.preventDefault();
        files.toggle('file.toggledEdit');
        require('s7n').tagify({selector: '#tags'});
    });

    files.on('updateFile', function (event) {
        event.original.preventDefault();
        event.context.file.tags = $(event.node).find('#tags')[0].value;

        files.updateFile(event.context.file)
        .then(function (data) {
            var file = files.get('file');
            file.tags = data.tags;
            file.filename = data.filename;
            file.toggledEdit = false;
            files.set('file', file);
        });
    });
};

module.exports.fileListView = function (f, active_user, admin_group) {
    var files = new Files({
        el: '#files',
        template: '#template',
        data: {
            files: f,
            active_user: active_user,
            is_admin: function () {
                var is_member_of_group = _.find(active_user.groups, function (group) {
                    return group._id === admin_group._id;
                });
                return Boolean(is_member_of_group);
            }
        }
    });
    files.on('search', function (event) {
        event.original.preventDefault();

        var query = event.context.query;
        files.search(query)
        .then();
    });

    files.on('toggleEdit', function (event) {
        event.original.preventDefault();
        files.toggle('files.' + event.keypath.split('.').pop() + '.toggledEdit');
        require('s7n').tagify({selector: 'input.tags'});
    });

    files.on('editFile', function (event) {
        event.original.preventDefault();
        var index = event.keypath.split('.').pop();
        event.context.tags = $(event.node).find('input.tags')[0].value;

        files.updateFile(event.context)
        .then(function (data) {
            var file = files.get('files.' + index);
            file.tags = data.tags;
            file.filename = data.filename;
            file.toggledEdit = false;
            files.set('files.' + index, file);
        });
    });

    files.on('deleteFile', function (event) {
        event.original.preventDefault();
        var promise = $.ajax({
                url: event.node.href,
                type: 'delete',
                dataType: 'json'
            });

        promise.then(function () {
            var index = event.keypath.split('.').pop();
            files.data.files.splice(index, 1);
        });
    });
    files.on('fetchMore', function (event) {
        event.original.preventDefault();
        files.add('page', 1);
        var promise = $.ajax({
            url: '/files',
            type: 'GET',
            dataType: 'json',
            data: {page: files.get('page')}
        });

        promise.then(function (data) {
            if (data.length === 0) {
                files.set('gotall', true);
            }
            files.data.files.push.apply(files.data.files, data);
        });
    });
    var uploadzone = new Dropzone("#upload", {
      //acceptedFiles: 'image/*',
      previewTemplate: ''
    });

    uploadzone.on("sending", function (file) {
        files.data.uploading_files.push(file);
    });
    uploadzone.on("uploadprogress", function (file) { //, progress
        _.each(files.data.uploading_files, function (f, i) {
            if (f.name === file.name) {
                files.set('uploading_files.' + i, file);
            }
        });
    });
    uploadzone.on("success", function (frontend_file, backend_file) {
        _.each(files.data.uploading_files, function (f, i) {
            if (f.name === frontend_file.name) {
                files.data.uploading_files.splice(i, 1);
            }
        });
        files.data.files.unshift(backend_file);
    });

    $('#drop').on('click', function () {
        $('#upload').trigger('click');
    });

    require('s7n').tagify();
    var has_tags = window.location.href.split("/files/t/", 2);
    var tags;
    if (has_tags.length === 2) {
        tags = has_tags[1].split("/");
    }
    else {
        tags = [];
    }
    $('#filter').val(tags.join(","));

    require('s7n').tagify({selector: '#filter'}, function (element) {
        var t = element.val;
        if (t.length) {
            window.location.href = '/files/t/' + t.join('/');
        }
        else {
            window.location.href = '/files';
        }
    });
};
<commit_msg>Fix bug where fetch more is done on filter<commit_after>/*globals $, _, window, Ractive, moment, Dropzone*/

var Files = Ractive.extend({
    noIntro: true,
    data: {
        uploading_files: [],
        gotall: false,
        page: 0,
        filter: [],
        shortdate: function (date) {
            return moment(date).format("ll");
        },
        taglink: function (tag) {
            var prefix = "/files/t/";
            if (tag) {
                var old_tags = window.location.href.split(prefix, 2);
                if (old_tags.length === 2) {
                    // we have tags
                    var tags = old_tags[1].split("/");
                    tags.push(tag);
                    return prefix + tags.uniq.join("/");

                }
                return prefix + tag;
            }
        }
    },
    search: function (query) {
        return $.ajax({
            url: '/tags',
            dataType: 'json',
            type: 'get',
            data: {
                q: query
            }
        });
    },
    updateFile: function (file) {
        return $.ajax({
            url: '/files/' + file._id,
            dataType: 'json',
            type: 'put',
            data: _.pick(file, 'filename', 'tags')
        });
    }
});

module.exports.fileDetailView = function (f) {
    var files = new Files({
        el: '#file',
        template: '#template',
        data: {
            file: f
        }
    });

    files.on('toggleEdit', function (event) {
        event.original.preventDefault();
        files.toggle('file.toggledEdit');
        require('s7n').tagify({selector: '#tags'});
    });

    files.on('updateFile', function (event) {
        event.original.preventDefault();
        event.context.file.tags = $(event.node).find('#tags')[0].value;

        files.updateFile(event.context.file)
        .then(function (data) {
            var file = files.get('file');
            file.tags = data.tags;
            file.filename = data.filename;
            file.toggledEdit = false;
            files.set('file', file);
        });
    });
};

module.exports.fileListView = function (f, active_user, admin_group) {
    var files = new Files({
        el: '#files',
        template: '#template',
        data: {
            files: f,
            active_user: active_user,
            is_admin: function () {
                var is_member_of_group = _.find(active_user.groups, function (group) {
                    return group._id === admin_group._id;
                });
                return Boolean(is_member_of_group);
            }
        }
    });
    files.on('search', function (event) {
        event.original.preventDefault();

        var query = event.context.query;
        files.search(query)
        .then();
    });

    files.on('toggleEdit', function (event) {
        event.original.preventDefault();
        files.toggle('files.' + event.keypath.split('.').pop() + '.toggledEdit');
        require('s7n').tagify({selector: 'input.tags'});
    });

    files.on('editFile', function (event) {
        event.original.preventDefault();
        var index = event.keypath.split('.').pop();
        event.context.tags = $(event.node).find('input.tags')[0].value;

        files.updateFile(event.context)
        .then(function (data) {
            var file = files.get('files.' + index);
            file.tags = data.tags;
            file.filename = data.filename;
            file.toggledEdit = false;
            files.set('files.' + index, file);
        });
    });

    files.on('deleteFile', function (event) {
        event.original.preventDefault();
        var promise = $.ajax({
                url: event.node.href,
                type: 'delete',
                dataType: 'json'
            });

        promise.then(function () {
            var index = event.keypath.split('.').pop();
            files.data.files.splice(index, 1);
        });
    });
    files.on('fetchMore', function (event) {
        event.original.preventDefault();
        files.add('page', 1);
        var promise = $.ajax({
            url: window.location.href,
            type: 'GET',
            dataType: 'json',
            data: {page: files.get('page')}
        });

        promise.then(function (data) {
            if (data.length === 0) {
                files.set('gotall', true);
            }
            files.data.files.push.apply(files.data.files, data);
        });
    });
    var uploadzone = new Dropzone("#upload", {
      //acceptedFiles: 'image/*',
      previewTemplate: ''
    });

    uploadzone.on("sending", function (file) {
        files.data.uploading_files.push(file);
    });
    uploadzone.on("uploadprogress", function (file) { //, progress
        _.each(files.data.uploading_files, function (f, i) {
            if (f.name === file.name) {
                files.set('uploading_files.' + i, file);
            }
        });
    });
    uploadzone.on("success", function (frontend_file, backend_file) {
        _.each(files.data.uploading_files, function (f, i) {
            if (f.name === frontend_file.name) {
                files.data.uploading_files.splice(i, 1);
            }
        });
        files.data.files.unshift(backend_file);
    });

    $('#drop').on('click', function () {
        $('#upload').trigger('click');
    });

    require('s7n').tagify();
    var has_tags = window.location.href.split("/files/t/", 2);
    var tags;
    if (has_tags.length === 2) {
        tags = has_tags[1].split("/");
    }
    else {
        tags = [];
    }
    $('#filter').val(tags.join(","));

    require('s7n').tagify({selector: '#filter'}, function (element) {
        var t = element.val;
        if (t.length) {
            window.location.href = '/files/t/' + t.join('/');
        }
        else {
            window.location.href = '/files';
        }
    });
};
<|endoftext|>


<commit_before>/*globals $, _, window, Ractive, moment, Dropzone*/

var Files = Ractive.extend({
    noIntro: true,
    data: {
        uploading_files: [],
        gotall: false,
        page: 0,
        filter: [],
        shortdate: function (date) {
            return moment(date).format("ll");
        },
        taglink: function (tag) {
            var prefix = "/files/t/";
            if (tag) {
                var old_tags = window.location.href.split(prefix, 2);
                if (old_tags.length === 2) {
                    // we have tags
                    var tags = old_tags[1].split("/");
                    if (!_.contains(tags, tag)) {
                        tags.push(tag);
                    }
                    return prefix + tags.join("/");

                }
                return prefix + tag;
            }
        }
    },
    search: function (query) {
        return $.ajax({
            url: '/tags',
            dataType: 'json',
            type: 'get',
            data: {
                q: query
            }
        });
    },
    updateFile: function (file) {
        return $.ajax({
            url: '/files/' + file._id,
            dataType: 'json',
            type: 'put',
            data: _.pick(file, 'filename', 'tags')
        });
    }
});

module.exports.fileDetailView = function (f) {
    var files = new Files({
        el: '#file',
        template: '#template',
        data: {
            file: f
        }
    });

    files.on('toggleEdit', function (event) {
        event.original.preventDefault();
        files.toggle('file.toggledEdit');
        require('s7n').tagify({selector: '#tags'});
    });

    files.on('updateFile', function (event) {
        event.original.preventDefault();
        event.context.file.tags = $(event.node).find('#tags')[0].value;

        files.updateFile(event.context.file)
        .then(function (data) {
            var file = files.get('file');
            file.tags = data.tags;
            file.filename = data.filename;
            file.toggledEdit = false;
            files.set('file', file);
        });
    });
};

module.exports.fileListView = function (f, _tags, active_user, admin_group) {
    var files = new Files({
        el: '#files',
        template: '#template',
        data: {
            files: f,
            tags: _tags,
            active_user: active_user,
            is_admin: function () {
                var is_member_of_group = _.find(active_user.groups, function (group) {
                    return group._id === admin_group._id;
                });
                return Boolean(is_member_of_group);
            }
        }
    });
    files.on('search', function (event) {
        event.original.preventDefault();

        var query = event.context.query;
        files.search(query)
        .then();
    });

    files.on('toggleEdit', function (event) {
        event.original.preventDefault();
        files.toggle('files.' + event.keypath.split('.').pop() + '.toggledEdit');
        require('s7n').tagify({selector: 'input.tags'});
    });

    files.on('editFile', function (event) {
        event.original.preventDefault();
        var index = event.keypath.split('.').pop();
        event.context.tags = $(event.node).find('input.tags')[0].value;

        files.updateFile(event.context)
        .then(function (data) {
            var file = files.get('files.' + index);
            file.tags = data.tags;
            file.filename = data.filename;
            file.toggledEdit = false;
            files.set('files.' + index, file);
        });
    });

    files.on('deleteFile', function (event) {
        event.original.preventDefault();
        var promise = $.ajax({
                url: event.node.href,
                type: 'delete',
                dataType: 'json'
            });

        promise.then(function () {
            var index = event.keypath.split('.').pop();
            files.data.files.splice(index, 1);
        });
    });
    files.on('fetchMore', function (event) {
        event.original.preventDefault();
        files.add('page', 1);
        var promise = $.ajax({
            url: window.location.href,
            type: 'GET',
            dataType: 'json',
            data: {page: files.get('page')}
        });

        promise.then(function (data) {
            if (data.length === 0) {
                files.set('gotall', true);
            }
            files.data.files.push.apply(files.data.files, data);
        });
    });
    var uploadzone = new Dropzone("#upload", {
      //acceptedFiles: 'image/*',
      previewTemplate: ''
    });

    uploadzone.on("sending", function (file) {
        files.data.uploading_files.push(file);
    });
    uploadzone.on("uploadprogress", function (file) { //, progress
        _.each(files.data.uploading_files, function (f, i) {
            if (f.name === file.name) {
                files.set('uploading_files.' + i, file);
            }
        });
    });
    uploadzone.on("success", function (frontend_file, backend_file) {
        _.each(files.data.uploading_files, function (f, i) {
            if (f.name === frontend_file.name) {
                files.data.uploading_files.splice(i, 1);
            }
        });
        files.data.files.unshift(backend_file);
    });

    $('#drop').on('click', function () {
        $('#upload').trigger('click');
    });

    var has_tags = window.location.href.split("/files/t/", 2);
    var tags;
    if (has_tags.length === 2) {
        tags = has_tags[1].split("/");
    }
    else {
        tags = [];
    }
    $('#filter').val(tags.join(","));
    $('#tags').val(tags.join(","));

    require('s7n').tagify();
    require('s7n').tagify({selector: '#filter'}, function (element) {
        var t = element.val;
        if (t.length) {
            window.location.href = '/files/t/' + t.join('/');
        }
        else {
            window.location.href = '/files';
        }
    });
};
<commit_msg>de-garble values from url<commit_after>/*globals $, _, window, Ractive, moment, Dropzone*/

var Files = Ractive.extend({
    noIntro: true,
    data: {
        uploading_files: [],
        gotall: false,
        page: 0,
        filter: [],
        shortdate: function (date) {
            return moment(date).format("ll");
        },
        taglink: function (tag) {
            var prefix = "/files/t/";
            if (tag) {
                var old_tags = window.location.href.split(prefix, 2);
                if (old_tags.length === 2) {
                    // we have tags
                    var tags = old_tags[1].split("/");
                    if (!_.contains(tags, tag)) {
                        tags.push(tag);
                    }
                    return prefix + tags.join("/");

                }
                return prefix + tag;
            }
        }
    },
    search: function (query) {
        return $.ajax({
            url: '/tags',
            dataType: 'json',
            type: 'get',
            data: {
                q: query
            }
        });
    },
    updateFile: function (file) {
        return $.ajax({
            url: '/files/' + file._id,
            dataType: 'json',
            type: 'put',
            data: _.pick(file, 'filename', 'tags')
        });
    }
});

module.exports.fileDetailView = function (f) {
    var files = new Files({
        el: '#file',
        template: '#template',
        data: {
            file: f
        }
    });

    files.on('toggleEdit', function (event) {
        event.original.preventDefault();
        files.toggle('file.toggledEdit');
        require('s7n').tagify({selector: '#tags'});
    });

    files.on('updateFile', function (event) {
        event.original.preventDefault();
        event.context.file.tags = $(event.node).find('#tags')[0].value;

        files.updateFile(event.context.file)
        .then(function (data) {
            var file = files.get('file');
            file.tags = data.tags;
            file.filename = data.filename;
            file.toggledEdit = false;
            files.set('file', file);
        });
    });
};

module.exports.fileListView = function (f, _tags, active_user, admin_group) {
    var files = new Files({
        el: '#files',
        template: '#template',
        data: {
            files: f,
            tags: _tags,
            active_user: active_user,
            is_admin: function () {
                var is_member_of_group = _.find(active_user.groups, function (group) {
                    return group._id === admin_group._id;
                });
                return Boolean(is_member_of_group);
            }
        }
    });
    files.on('search', function (event) {
        event.original.preventDefault();

        var query = event.context.query;
        files.search(query)
        .then();
    });

    files.on('toggleEdit', function (event) {
        event.original.preventDefault();
        files.toggle('files.' + event.keypath.split('.').pop() + '.toggledEdit');
        require('s7n').tagify({selector: 'input.tags'});
    });

    files.on('editFile', function (event) {
        event.original.preventDefault();
        var index = event.keypath.split('.').pop();
        event.context.tags = $(event.node).find('input.tags')[0].value;

        files.updateFile(event.context)
        .then(function (data) {
            var file = files.get('files.' + index);
            file.tags = data.tags;
            file.filename = data.filename;
            file.toggledEdit = false;
            files.set('files.' + index, file);
        });
    });

    files.on('deleteFile', function (event) {
        event.original.preventDefault();
        var promise = $.ajax({
                url: event.node.href,
                type: 'delete',
                dataType: 'json'
            });

        promise.then(function () {
            var index = event.keypath.split('.').pop();
            files.data.files.splice(index, 1);
        });
    });
    files.on('fetchMore', function (event) {
        event.original.preventDefault();
        files.add('page', 1);
        var promise = $.ajax({
            url: window.location.href,
            type: 'GET',
            dataType: 'json',
            data: {page: files.get('page')}
        });

        promise.then(function (data) {
            if (data.length === 0) {
                files.set('gotall', true);
            }
            files.data.files.push.apply(files.data.files, data);
        });
    });
    var uploadzone = new Dropzone("#upload", {
      //acceptedFiles: 'image/*',
      previewTemplate: ''
    });

    uploadzone.on("sending", function (file) {
        files.data.uploading_files.push(file);
    });
    uploadzone.on("uploadprogress", function (file) { //, progress
        _.each(files.data.uploading_files, function (f, i) {
            if (f.name === file.name) {
                files.set('uploading_files.' + i, file);
            }
        });
    });
    uploadzone.on("success", function (frontend_file, backend_file) {
        _.each(files.data.uploading_files, function (f, i) {
            if (f.name === frontend_file.name) {
                files.data.uploading_files.splice(i, 1);
            }
        });
        files.data.files.unshift(backend_file);
    });

    $('#drop').on('click', function () {
        $('#upload').trigger('click');
    });

    var has_tags = window.location.href.split("/files/t/", 2);
    var tags;
    if (has_tags.length === 2) {
        tags = has_tags[1].split("/");
    }
    else {
        tags = [];
    }
    tags = _.map(tags, function (tag) { return decodeURIComponent(tag); });
    $('#filter').val(tags.join(","));
    $('#tags').val(tags.join(","));

    require('s7n').tagify();
    require('s7n').tagify({selector: '#filter'}, function (element) {
        var t = element.val;
        if (t.length) {
            window.location.href = '/files/t/' + t.join('/');
        }
        else {
            window.location.href = '/files';
        }
    });
};
<|endoftext|>


<commit_before>function ErrorsPage() {

	//hold the tab object
	this.tab = null;
	//Array of ErrorFiles
	this.eflist = new Object();

	//hold signals for the page
	this._signals = new Array();

	//hold status message for the page
	this._prompt = null;

	this._inited = false;

	this._init = function() {
		if(this._inited)
			return;

		this.tab = new Tab( "Errors" );
		connect( this.tab, "onfocus", bind( this._onfocus, this ) );
		connect( this.tab, "onblur", bind( this._onblur, this ) );
		connect( this.tab, "onclickclose", bind( this._close, this ) );

		tabbar.add_tab( this.tab );

		this._signals.push(connect("close-errors-page", "onclick", bind(this._close, this) ));
		this._signals.push(connect("collapse-errors-page", "onclick", bind(this._collapse_all, this) ));
		this._signals.push(connect("check-errors-page", "onclick", bind(this._check_all, this) ));
		this._signals.push(connect("expand-errors-page", "onclick", bind(this._expand_all, this) ));

		this._inited = true;
	}

	//load a new set of errors
	this.load = function(info, opts, project) {
		if(this._prompt != null) {
			this._prompt.close();
			this._prompt = null;
		}
		var path = '/' + project + '/';
		var filelist = new Array();
		this._init();
		log('Loading the ErrorPage');

		for(var i = 0; i < info.errors.length; i++) {
			var item = info.errors[i];
			var file = path + item.file;

			//if we've not seen this file before, but it has a listing already, reset it
			if(findValue(filelist, file) == -1 && this.eflist[file] != null) {
				log('Resetting '+file);
				this.eflist[file].reset();
			} else if(this.eflist[file] == null) {	//if it's null the initialise it
				this.eflist[file] = new ErrorFile(file);
				log('file '+file+' has been added');
			}
			if(findValue(filelist, file) == -1)	//add it to our list if it's not there
				filelist.push(file);

			this.eflist[file].add_item(item);
		}
		for(var i = 0; i < filelist.length; i++) {
			this.eflist[filelist[i]].load_items();
		}

		if(opts != null) {
			if(opts.switch_to)
				tabbar.switch_to(this.tab);
			if(opts.alert)
				this._prompt = status_button( info.errors.length+" errors found!", LEVEL_WARN, 'view errors',
					bind( tabbar.switch_to, tabbar, this.tab ) );
		}
	}

	this._expand_all = function() {
		for( var i in this.eflist ) {
			this.eflist[i].show_msgs();
		}
	}

	this._collapse_all = function() {
		for( var i in this.eflist ) {
			this.eflist[i].hide_msgs();
		}
	}

	this._onfocus = function() {
		showElement('errors-page');
	}

	this._onblur = function() {
		hideElement('errors-page');
	}

	this._file_count = function() {
		var count = 0;
		for( var f in this.eflist ) {
			if(this.eflist[f] != null)
				count++;
		}
		return count;
	}

	this._clear_file = function(file) {
		if(this.eflist[file] != null) {
			this.eflist[file].remove();
			this.eflist[file] = null;
		}
		if(this._file_count() == 0)
			this._close();
	}

	this._check_all = function() {
		for( var f in this.eflist ) {
			if(this.eflist[f] != null)
				this.check(f);
		}
	}

	/**
	 * use autosave parameter if to check against autosave or normal save
	 */
	this.check = function(file, opts, autosave, revision) {
		var project = IDE_path_get_project(file)
		IDE_backend_request("file/lint", {team: team,
		                                  project: project,
		                                  path: IDE_path_get_file(file),
		                                  rev: revision,
		                                  autosave: autosave
		                                 },
		                                  partial(bind(this._done_check, this), file, opts, project),
		                                  bind(this._fail_check, this, file, opts));
	}

	this._done_check = function(file, opts, project, info) {
		var cb = ( opts != null && opts.callback != null && typeof opts.callback == 'function' )
		if( info.errors.length > 0 ) {
			this.load(info, opts, project);
			if(cb) {
				opts.callback('codefail', info.errors.length);
			}
			editpage.mark_errors(file, info.errors);
		} else {
			if(cb) {
				opts.callback('pass');
			}
			//if not (quiet if pass or a mulifile call from the projpage and no errors yet and this is not the last one to check)
			if( !( opts != null && (opts.quietpass || opts.projpage_multifile && projpage.has_focus() && IDE_async_count > 1) ) )
				this._prompt = status_msg( "No errors found", LEVEL_OK );
			this._clear_file(file);
		}
	}

	this._fail_check = function(file, opts) {
		this._prompt = status_button( "Failed to check code", LEVEL_ERROR,
					"retry", bind( this.check, this, file, opts ) );

		//run the callback, after our status message so they can overwrite it if they desire
		if( opts != null &&  opts.callback != null && typeof opts.callback == 'function' )
			opts.callback('checkfail');
	}

	this._close = function() {
		if(!this._inited)
			return;

		for( var i in this.eflist ) {
			if(this.eflist[i] != null)
				this.eflist[i].remove();
		}
		this.eflist = new Array();

		this.tab.close();

		if( this._prompt != null ) {
			this._prompt.close();
			this._prompt = null;
		}

		for(var i = 0; i < this._signals.length; i++) {
			disconnect(this._signals[i]);
		}
		this._signals = new Array();

		this._inited = false;
	}

	this.show_only = function(file) {
		this.hide_all_files();
		this.eflist[file].show_errs();
	}

	this.hide_all_files = function() {
		for( var i in this.eflist ) {
			this.eflist[i].hide_errs();
		}
	}
}

function ErrorFile(name) {
	//the path of this file
	this.label = name;

	//array for the warnings in a file
	this._items = new Array();

	//the HTML element for the title
	this._name_elem = null;
	//the HTML element for the warnings
	this._items_elem = null;
	//the HTML element for all messages (errors and warnings)
	this._msgs_elem = null;
	//are the errors shown
	this._msgs_shown = true;

	//hold the main signals for the file
	this._signals = new Array();
	//hold the signals for double-clicking on the items
	this._item_signals = new Array();

	this._init = function() {
		logDebug('initing file: '+this.label);

		//make the html
		this._view_link = A({"title":'click to view file', 'href':'#'} , this.label);
		this._expand_elem = createDOM('button', null, 'Collapse');
		this._refresh_elem = createDOM('button', {'title':'Click to re-check the current saved version of the file'}, 'Check Again');
		this._name_elem = createDOM('dt', null, this._view_link, this._refresh_elem, this._expand_elem );
		this._items_elem = UL(null, null);
		this._msgs_elem = createDOM('dd', null, this._items_elem);

		//add the html to the page
		appendChildNodes("errors-listing", this._name_elem);
		appendChildNodes("errors-listing", this._msgs_elem);

		//hook up the signal
		this._signals.push(connect( this._view_link, 'onclick', bind(this._view_onclick, this, null) ));
		this._signals.push(connect( this._expand_elem, 'onclick', bind(this._expand_onclick, this) ));
		this._signals.push(connect( this._refresh_elem, 'onclick', bind(errorspage.check, errorspage, this.label, null, false) ));
	}

	this.add_item = function(w) {
		this._items.push(w)
	}

	this.load_items = function() {
		for( var i=0; i<this._items.length; i++ ) {
			var item = this._items[i];
			var li = LI({'class' : item.level}, ''+item.lineNumber+':'+' ['+item.level.charAt(0).toUpperCase()+'] '+item.message);
			li.title = 'Double click to view the error in the file.';
			this._item_signals.push(connect( li, 'ondblclick', bind(this._view_onclick, this, item.lineNumber) ));
			appendChildNodes( this._items_elem, li );
		}
		this.show_msgs();
	}

	this.reset = function() {
		this.clear_items();
	}

	this.remove = function() {
		this.reset();
		if(this._name_elem != null)
			removeElement(this._name_elem);
		if(this._msgs_elem != null)
			removeElement(this._msgs_elem);
		this._msgs_elem = null;
		this._name_elem = null;
		for(var i = 0; i < this._signals.length; i++) {
			disconnect(this._signals[i]);
		}
		this._signals = new Array();
	}

	this.clear_items = function() {
		if(this._items_elem != null)
			replaceChildNodes(this._items_elem, null);
		this._items = new Array();
		for( var i=0; i<this._item_signals.length; i++ ) {
			disconnect(this._item_signals[i]);
		}
		this._item_signals = new Array();
	}

	this._view_onclick = function(line) {
		var etab = editpage.edit_file( team, IDE_path_get_project(this.label), this.label, null, 'REPO' );
		if (etab.rev != 'HEAD') {
			etab.open_revision('HEAD');
		}
		if (line != null) {
			etab.setSelectionRange(line, 0, -1);
		}
	}

	this._expand_onclick = function() {
		if(!this._msgs_shown)
			this.show_msgs();
		else
			this.hide_msgs();
	}

	this.show_msgs = function() {
		if(!this._msgs_shown) {
			showElement( this._msgs_elem );
			this._expand_elem.innerHTML = 'Collapse';
			this._msgs_shown = true;
		}
	}

	this.hide_msgs = function() {
		if(this._msgs_shown) {
			hideElement( this._msgs_elem );
			this._expand_elem.innerHTML = 'Expand';
			this._msgs_shown = false;
		}
	}

	this._init();
}
<commit_msg>Remove a redundant partial() call.<commit_after>function ErrorsPage() {

	//hold the tab object
	this.tab = null;
	//Array of ErrorFiles
	this.eflist = new Object();

	//hold signals for the page
	this._signals = new Array();

	//hold status message for the page
	this._prompt = null;

	this._inited = false;

	this._init = function() {
		if(this._inited)
			return;

		this.tab = new Tab( "Errors" );
		connect( this.tab, "onfocus", bind( this._onfocus, this ) );
		connect( this.tab, "onblur", bind( this._onblur, this ) );
		connect( this.tab, "onclickclose", bind( this._close, this ) );

		tabbar.add_tab( this.tab );

		this._signals.push(connect("close-errors-page", "onclick", bind(this._close, this) ));
		this._signals.push(connect("collapse-errors-page", "onclick", bind(this._collapse_all, this) ));
		this._signals.push(connect("check-errors-page", "onclick", bind(this._check_all, this) ));
		this._signals.push(connect("expand-errors-page", "onclick", bind(this._expand_all, this) ));

		this._inited = true;
	}

	//load a new set of errors
	this.load = function(info, opts, project) {
		if(this._prompt != null) {
			this._prompt.close();
			this._prompt = null;
		}
		var path = '/' + project + '/';
		var filelist = new Array();
		this._init();
		log('Loading the ErrorPage');

		for(var i = 0; i < info.errors.length; i++) {
			var item = info.errors[i];
			var file = path + item.file;

			//if we've not seen this file before, but it has a listing already, reset it
			if(findValue(filelist, file) == -1 && this.eflist[file] != null) {
				log('Resetting '+file);
				this.eflist[file].reset();
			} else if(this.eflist[file] == null) {	//if it's null the initialise it
				this.eflist[file] = new ErrorFile(file);
				log('file '+file+' has been added');
			}
			if(findValue(filelist, file) == -1)	//add it to our list if it's not there
				filelist.push(file);

			this.eflist[file].add_item(item);
		}
		for(var i = 0; i < filelist.length; i++) {
			this.eflist[filelist[i]].load_items();
		}

		if(opts != null) {
			if(opts.switch_to)
				tabbar.switch_to(this.tab);
			if(opts.alert)
				this._prompt = status_button( info.errors.length+" errors found!", LEVEL_WARN, 'view errors',
					bind( tabbar.switch_to, tabbar, this.tab ) );
		}
	}

	this._expand_all = function() {
		for( var i in this.eflist ) {
			this.eflist[i].show_msgs();
		}
	}

	this._collapse_all = function() {
		for( var i in this.eflist ) {
			this.eflist[i].hide_msgs();
		}
	}

	this._onfocus = function() {
		showElement('errors-page');
	}

	this._onblur = function() {
		hideElement('errors-page');
	}

	this._file_count = function() {
		var count = 0;
		for( var f in this.eflist ) {
			if(this.eflist[f] != null)
				count++;
		}
		return count;
	}

	this._clear_file = function(file) {
		if(this.eflist[file] != null) {
			this.eflist[file].remove();
			this.eflist[file] = null;
		}
		if(this._file_count() == 0)
			this._close();
	}

	this._check_all = function() {
		for( var f in this.eflist ) {
			if(this.eflist[f] != null)
				this.check(f);
		}
	}

	/**
	 * use autosave parameter if to check against autosave or normal save
	 */
	this.check = function(file, opts, autosave, revision) {
		var project = IDE_path_get_project(file)
		IDE_backend_request("file/lint", {team: team,
		                                  project: project,
		                                  path: IDE_path_get_file(file),
		                                  rev: revision,
		                                  autosave: autosave
		                                 },
		                                  bind(this._done_check, this, file, opts, project),
		                                  bind(this._fail_check, this, file, opts));
	}

	this._done_check = function(file, opts, project, info) {
		var cb = ( opts != null && opts.callback != null && typeof opts.callback == 'function' )
		if( info.errors.length > 0 ) {
			this.load(info, opts, project);
			if(cb) {
				opts.callback('codefail', info.errors.length);
			}
			editpage.mark_errors(file, info.errors);
		} else {
			if(cb) {
				opts.callback('pass');
			}
			//if not (quiet if pass or a mulifile call from the projpage and no errors yet and this is not the last one to check)
			if( !( opts != null && (opts.quietpass || opts.projpage_multifile && projpage.has_focus() && IDE_async_count > 1) ) )
				this._prompt = status_msg( "No errors found", LEVEL_OK );
			this._clear_file(file);
		}
	}

	this._fail_check = function(file, opts) {
		this._prompt = status_button( "Failed to check code", LEVEL_ERROR,
					"retry", bind( this.check, this, file, opts ) );

		//run the callback, after our status message so they can overwrite it if they desire
		if( opts != null &&  opts.callback != null && typeof opts.callback == 'function' )
			opts.callback('checkfail');
	}

	this._close = function() {
		if(!this._inited)
			return;

		for( var i in this.eflist ) {
			if(this.eflist[i] != null)
				this.eflist[i].remove();
		}
		this.eflist = new Array();

		this.tab.close();

		if( this._prompt != null ) {
			this._prompt.close();
			this._prompt = null;
		}

		for(var i = 0; i < this._signals.length; i++) {
			disconnect(this._signals[i]);
		}
		this._signals = new Array();

		this._inited = false;
	}

	this.show_only = function(file) {
		this.hide_all_files();
		this.eflist[file].show_errs();
	}

	this.hide_all_files = function() {
		for( var i in this.eflist ) {
			this.eflist[i].hide_errs();
		}
	}
}

function ErrorFile(name) {
	//the path of this file
	this.label = name;

	//array for the warnings in a file
	this._items = new Array();

	//the HTML element for the title
	this._name_elem = null;
	//the HTML element for the warnings
	this._items_elem = null;
	//the HTML element for all messages (errors and warnings)
	this._msgs_elem = null;
	//are the errors shown
	this._msgs_shown = true;

	//hold the main signals for the file
	this._signals = new Array();
	//hold the signals for double-clicking on the items
	this._item_signals = new Array();

	this._init = function() {
		logDebug('initing file: '+this.label);

		//make the html
		this._view_link = A({"title":'click to view file', 'href':'#'} , this.label);
		this._expand_elem = createDOM('button', null, 'Collapse');
		this._refresh_elem = createDOM('button', {'title':'Click to re-check the current saved version of the file'}, 'Check Again');
		this._name_elem = createDOM('dt', null, this._view_link, this._refresh_elem, this._expand_elem );
		this._items_elem = UL(null, null);
		this._msgs_elem = createDOM('dd', null, this._items_elem);

		//add the html to the page
		appendChildNodes("errors-listing", this._name_elem);
		appendChildNodes("errors-listing", this._msgs_elem);

		//hook up the signal
		this._signals.push(connect( this._view_link, 'onclick', bind(this._view_onclick, this, null) ));
		this._signals.push(connect( this._expand_elem, 'onclick', bind(this._expand_onclick, this) ));
		this._signals.push(connect( this._refresh_elem, 'onclick', bind(errorspage.check, errorspage, this.label, null, false) ));
	}

	this.add_item = function(w) {
		this._items.push(w)
	}

	this.load_items = function() {
		for( var i=0; i<this._items.length; i++ ) {
			var item = this._items[i];
			var li = LI({'class' : item.level}, ''+item.lineNumber+':'+' ['+item.level.charAt(0).toUpperCase()+'] '+item.message);
			li.title = 'Double click to view the error in the file.';
			this._item_signals.push(connect( li, 'ondblclick', bind(this._view_onclick, this, item.lineNumber) ));
			appendChildNodes( this._items_elem, li );
		}
		this.show_msgs();
	}

	this.reset = function() {
		this.clear_items();
	}

	this.remove = function() {
		this.reset();
		if(this._name_elem != null)
			removeElement(this._name_elem);
		if(this._msgs_elem != null)
			removeElement(this._msgs_elem);
		this._msgs_elem = null;
		this._name_elem = null;
		for(var i = 0; i < this._signals.length; i++) {
			disconnect(this._signals[i]);
		}
		this._signals = new Array();
	}

	this.clear_items = function() {
		if(this._items_elem != null)
			replaceChildNodes(this._items_elem, null);
		this._items = new Array();
		for( var i=0; i<this._item_signals.length; i++ ) {
			disconnect(this._item_signals[i]);
		}
		this._item_signals = new Array();
	}

	this._view_onclick = function(line) {
		var etab = editpage.edit_file( team, IDE_path_get_project(this.label), this.label, null, 'REPO' );
		if (etab.rev != 'HEAD') {
			etab.open_revision('HEAD');
		}
		if (line != null) {
			etab.setSelectionRange(line, 0, -1);
		}
	}

	this._expand_onclick = function() {
		if(!this._msgs_shown)
			this.show_msgs();
		else
			this.hide_msgs();
	}

	this.show_msgs = function() {
		if(!this._msgs_shown) {
			showElement( this._msgs_elem );
			this._expand_elem.innerHTML = 'Collapse';
			this._msgs_shown = true;
		}
	}

	this.hide_msgs = function() {
		if(this._msgs_shown) {
			hideElement( this._msgs_elem );
			this._expand_elem.innerHTML = 'Expand';
			this._msgs_shown = false;
		}
	}

	this._init();
}
<|endoftext|>


<commit_before>function initialize_records_form() {
    $('#format_lbl').hide();
    $('#diskDiameters_lbl').hide();
    $('#reelDiameters_lbl').hide();
    $('#mediaDiameters_lbl').hide();
    $('#tapeThickness_lbl').hide();
    $('#trackTypes_lbl').hide();
    $('#cassetteSize_lbl').hide();
    $("#formatVersion_lbl").hide();
    $('#bases_lbl').hide();
    $('#recordingSpeed_lbl').hide();

    if (selectedMediaType)
        $('.new #mediaType option[value="' + selectedMediaType + '"]').attr("selected", "selected");
    $.mask.definitions['y'] = '[1-2,x]';
    $.mask.definitions['m'] = '[0-1,x]';
    $.mask.definitions['d'] = '[0-3,x]';
    $.mask.definitions['g'] = '[0-9,x]';
    $("#creationDate, #contentDate").mask("yggg-mg-dg", {optional: true});
    updateViewSetting();
    updateProjects();
    updateFormat();
    onChangeMediaType();
    showUpdateFields();
    saveBulkEdit();
    closeBtn();
    var check = 0;
    $("input,textarea,select").keypress(function () {
        if ($(this).attr('id') != 'mediaType') {
           check = 1;
        }
    });
    $("select").click(function () {
        if (check == 1 && $(this).attr('id') == 'mediaType') {
            changes = true;
        }else if ($(this).attr('id') == 'mediaType' || $(this).attr('id') == 'project') {
            changes = false;
        }
    });

    window.onbeforeunload = function () {
        if (changes)
        {
            return 'The changes are not saved and will be lost.';
        }
    }

    $('form').submit(function () {
        changes = false;
        return true; // return false to cancel form action
    });

}

function updateFormat() {
    var selfObj = this;
    selfObj.ajaxCall = false;
    /// call to get base dropdown options
//    $('#processing').html(' Processing please wait...');
    if (selectedFormat) {
        url = baseUrl + 'getFormat/' + $("#mediaType").val() + '/' + selectedFormat;
    } else {
        url = baseUrl + 'getFormat/' + $("#mediaType").val();
    }
    $.ajax({
        type: "GET",
        url: url,
        success: function (response) {
            if (response != "") {
                $('#format_lbl').show();
                $("#format").html(response);
                $("#format").change();
                $('#processing').hide();
                $('#fieldsPanel').show();
            }
        }

    }); // Ajax Call
}

function showUpdateFields() {
    $('#format').change(function () {
        var showDiskDiameter = [16, 17, 18, 19, 20, 28];
        var showMediaDiameter = [1, 2, 3, 4, 5, 24];
        var showTapeThickness = [1, 2, 3, 4, 5];
        var showTrackType = [1, 2, 3, 4, 5];
        var showCassetteSize = [59, 60, 33, 34, 35, 43, 44, 46, 47, 48, 52, 53, 54, 55, 57];
        var hideRecordingSpeedFormat = [37, 39, 40, 41];
        var hideIfFormat = [24, 25, 26];
        var showSideIfFormat = [1, 10, 11, 13, 14, 16, 17, 18, 19, 20, 27, 28];
        var showNoiceRedIfFormat = [1, 2, 4, 5, 6, 7, 10, 13, 14, 27];
        var hideBaseIfFormat = [3, 4, 5];

        if (jQuery.inArray(parseInt($(this).val()), showDiskDiameter) >= 0) {
            $('#diskDiameters_lbl').show();
        } else {
            $('#diskDiameters_lbl').hide();
        }

        if (jQuery.inArray(parseInt($(this).val()), showMediaDiameter) >= 0) {
            $('#mediaDiameters_lbl').show();
        } else {
            $('#mediaDiameters_lbl').hide();
        }

        if (jQuery.inArray(parseInt($(this).val()), showTapeThickness) >= 0) {
            $('#tapeThickness_lbl').show();
        } else {
            $('#tapeThickness_lbl').hide();
        }

        if (jQuery.inArray(parseInt($(this).val()), showTrackType) >= 0) {
            $('#trackTypes_lbl').show();
        } else {
            $('#trackTypes_lbl').hide();
        }

        if (jQuery.inArray(parseInt($(this).val()), showCassetteSize) >= 0) {
            $('#cassetteSize_lbl').show();
        } else {
            $('#cassetteSize_lbl').hide();
        }

        if (jQuery.inArray(parseInt($(this).val()), hideIfFormat) >= 0) {
            $('#slides_lbl, #monoStereo_lbl').hide();
        } else {
            $('#slides_lbl, #monoStereo_lbl').show();
        }
        if (jQuery.inArray(parseInt($(this).val()), showSideIfFormat) >= 0) {
            $('#slides_lbl').show();
        } else {
            $('#slides_lbl').hide();
        }
        if (jQuery.inArray(parseInt($(this).val()), showNoiceRedIfFormat) >= 0) {
            $('#noiceReduction_lbl').show();
        } else {
            $('#noiceReduction_lbl').hide();
        }
        if ($(this).val()) {
            if (jQuery.inArray(parseInt($(this).val()), hideBaseIfFormat) >= 0) {
                $("#bases_lbl").hide();
            } else {
                /// call to get base dropdown options
                $.ajax({
                    type: "GET",
                    url: baseUrl + 'getBase/' + $(this).val(),
                    success: function (response) {
                        if (response != "") {
                            $("#bases_lbl").show();
                            $("#bases").html(response);
                        } else {
                            $("#bases_lbl").hide();
                        }
                    }

                }); // Ajax Call
            }
            /// call to get reel diameters dropdown options
            if (selectedRD) {
                RDurl = baseUrl + 'getReelDiameter/' + $(this).val() + '/' + $("#mediaType").val() + '/' + selectedRD;
            } else {
                RDurl = baseUrl + 'getReelDiameter/' + $(this).val() + '/' + $("#mediaType").val();
            }
            $.ajax({
                type: "GET",
                url: RDurl,
                success: function (response) {
                    if (response != "") {
                        $("#reelDiameters_lbl").show();
                        $("#reelDiameters").html(response);
                    } else {
                        $("#reelDiameters_lbl").hide();
                    }
                }

            }); // Ajax Call
            if (jQuery.inArray(parseInt($(this).val()), hideRecordingSpeedFormat) >= 0) {
                $('#recordingSpeed_lbl').hide();
            } else {
                $('#recordingSpeed_lbl').show();
                /// call to get recording speed dropdown options
                if (selectedRS) {
                    url = baseUrl + 'getRecordingSpeed/' + $(this).val() + '/' + $("#mediaType").val() + '/' + selectedRS;
                } else {
                    url = baseUrl + 'getRecordingSpeed/' + $(this).val() + '/' + $("#mediaType").val();
                }
                $.ajax({
                    type: "GET",
                    url: url,
                    success: function (response) {
                        if (response != "") {
                            $("#recordingSpeed_lbl").show();
                            $("#recordingSpeed").html(response);
                        } else {
                            $("#recordingSpeed_lbl").hide();
                        }
                    }
                }); // Ajax Call
            }
            /// call to get formatversion dropdown options
            if (selectedFormatVersion) {
                formatVersiourl = baseUrl + 'getFormatVersion/' + $(this).val() + '/' + selectedFormatVersion;
            } else {
                formatVersiourl = baseUrl + 'getFormatVersion/' + $(this).val();
            }
            $.ajax({
                type: "GET",
                url: formatVersiourl,
                success: function (response) {
                    if (response != "") {
                        $("#formatVersion_lbl").show();
                        $("#formatVersion").html(response);
                    } else {
                        $("#formatVersion_lbl").hide();
                    }
                }

            }); // Ajax Call
        } else {
            $('#diskDiameters_lbl').hide();
            $('#reelDiameters_lbl').hide();
            $('#mediaDiameters_lbl').hide();
            $('#tapeThickness_lbl').hide();
            $('#trackTypes_lbl').hide();
            $('#cassetteSize_lbl').hide();
            $("#formatVersion_lbl").hide();
            $('#bases_lbl').hide();
            $('#recordingSpeed_lbl').hide();
        }
    });

}

function onChangeMediaType() {
    $(".new #mediaType").change(function () {
        if ($(this).val() == 3) {
            $('#fieldsPanel').hide();
            $('#processing').show();
            window.location.href = baseUrl + 'video/new';
        } else if ($(this).val() == 2) {
            $('#fieldsPanel').hide();
            $('#processing').show();
            window.location.href = baseUrl + 'film/new';
        } else if ($(this).val() == 1) {
            $('#fieldsPanel').hide();
            $('#processing').show();
            window.location.href = baseUrl + 'audio/new';
        }
    });
}

function saveBulkEdit() {
    $("#submitBulkEdit").click(function () {
        data = $('#frmBulkEdit').serialize();
        $(document).ajaxStart(function () {
            $("#frmBulkEdit").hide();
            $('#editProcessing').show();
            $('#editProcessing').css('color', 'black');
            $('#editProcessing').html(' Processing please wait...');
        });
        $.ajax({
            type: "POST",
            url: bulkEdit,
            data: data,
            dataType: 'json',
            success: function (response) {
                if (response.success === true) {
                    window.location.reload();
                }
            }
        }); // Ajax Call
    });
}

function closeBtn() {
    $(".bulkEditCloseBtn").on('click', function () {
        $.modal.close();
        $('#selectAll').prop("checked", false);
        $('input[name=record_checkbox]').each(function () {
            $(this).prop("checked", false);
        });
        $('#records tr').each(function () {
            $(this).removeClass("selected");
        });
        $("#selectedrecords").val('');
        window.location.reload();
    });
}

function updateProjects() {
    if (projectId) {
        selectedProject = projectId;
    }
    var path = window.location.href;
    var split_path = path.split('/');
    if ($.isNumeric(split_path[split_path.length - 1])) {
        selectedProject = split_path[split_path.length - 1];
    }
    if (selectedProject) {
        urlProjects = baseUrl + 'getAllProjects/' + selectedProject;
    } else {
        urlProjects = baseUrl + 'getAllProjects';
    }
    $.ajax({
        type: "GET",
        url: urlProjects,
        success: function (response) {
            if (response != "") {
                $("#project").html(response);
            }
        }
    }); // Ajax Call
}

function updateViewSetting() {
    $('#project').change(function () {
        var proj_id = $('#project').val();
        //  console.log(audio);
        if (proj_id) {
            // selectedProject = proj_id;
            console.log('here');
            var newUrl = viewUrl + proj_id;
            console.log(newUrl);
//            $.ajax({
//                type: "GET",
//                url: newUrl,
//                success: function (response) {
            window.location = newUrl;

//                }
//            });
        }
    })
}<commit_msg>AVCC-205 #comment fixing project_id undefined issues<commit_after>function initialize_records_form() {
    $('#format_lbl').hide();
    $('#diskDiameters_lbl').hide();
    $('#reelDiameters_lbl').hide();
    $('#mediaDiameters_lbl').hide();
    $('#tapeThickness_lbl').hide();
    $('#trackTypes_lbl').hide();
    $('#cassetteSize_lbl').hide();
    $("#formatVersion_lbl").hide();
    $('#bases_lbl').hide();
    $('#recordingSpeed_lbl').hide();

    if (selectedMediaType)
        $('.new #mediaType option[value="' + selectedMediaType + '"]').attr("selected", "selected");
    $.mask.definitions['y'] = '[1-2,x]';
    $.mask.definitions['m'] = '[0-1,x]';
    $.mask.definitions['d'] = '[0-3,x]';
    $.mask.definitions['g'] = '[0-9,x]';
    $("#creationDate, #contentDate").mask("yggg-mg-dg", {optional: true});
    updateViewSetting();
    updateProjects();
    updateFormat();
    onChangeMediaType();
    showUpdateFields();
    saveBulkEdit();
    closeBtn();
    var check = 0;
    $("input,textarea,select").keypress(function () {
        if ($(this).attr('id') != 'mediaType') {
           check = 1;
        }
    });
    $("select").click(function () {
        if (check == 1 && $(this).attr('id') == 'mediaType') {
            changes = true;
        }else if ($(this).attr('id') == 'mediaType' || $(this).attr('id') == 'project') {
            changes = false;
        }
    });

    window.onbeforeunload = function () {
        if (changes)
        {
            return 'The changes are not saved and will be lost.';
        }
    }

    $('form').submit(function () {
        changes = false;
        return true; // return false to cancel form action
    });

}

function updateFormat() {
    var selfObj = this;
    selfObj.ajaxCall = false;
    /// call to get base dropdown options
//    $('#processing').html(' Processing please wait...');
    if (selectedFormat) {
        url = baseUrl + 'getFormat/' + $("#mediaType").val() + '/' + selectedFormat;
    } else {
        url = baseUrl + 'getFormat/' + $("#mediaType").val();
    }
    $.ajax({
        type: "GET",
        url: url,
        success: function (response) {
            if (response != "") {
                $('#format_lbl').show();
                $("#format").html(response);
                $("#format").change();
                $('#processing').hide();
                $('#fieldsPanel').show();
            }
        }

    }); // Ajax Call
}

function showUpdateFields() {
    $('#format').change(function () {
        var showDiskDiameter = [16, 17, 18, 19, 20, 28];
        var showMediaDiameter = [1, 2, 3, 4, 5, 24];
        var showTapeThickness = [1, 2, 3, 4, 5];
        var showTrackType = [1, 2, 3, 4, 5];
        var showCassetteSize = [59, 60, 33, 34, 35, 43, 44, 46, 47, 48, 52, 53, 54, 55, 57];
        var hideRecordingSpeedFormat = [37, 39, 40, 41];
        var hideIfFormat = [24, 25, 26];
        var showSideIfFormat = [1, 10, 11, 13, 14, 16, 17, 18, 19, 20, 27, 28];
        var showNoiceRedIfFormat = [1, 2, 4, 5, 6, 7, 10, 13, 14, 27];
        var hideBaseIfFormat = [3, 4, 5];

        if (jQuery.inArray(parseInt($(this).val()), showDiskDiameter) >= 0) {
            $('#diskDiameters_lbl').show();
        } else {
            $('#diskDiameters_lbl').hide();
        }

        if (jQuery.inArray(parseInt($(this).val()), showMediaDiameter) >= 0) {
            $('#mediaDiameters_lbl').show();
        } else {
            $('#mediaDiameters_lbl').hide();
        }

        if (jQuery.inArray(parseInt($(this).val()), showTapeThickness) >= 0) {
            $('#tapeThickness_lbl').show();
        } else {
            $('#tapeThickness_lbl').hide();
        }

        if (jQuery.inArray(parseInt($(this).val()), showTrackType) >= 0) {
            $('#trackTypes_lbl').show();
        } else {
            $('#trackTypes_lbl').hide();
        }

        if (jQuery.inArray(parseInt($(this).val()), showCassetteSize) >= 0) {
            $('#cassetteSize_lbl').show();
        } else {
            $('#cassetteSize_lbl').hide();
        }

        if (jQuery.inArray(parseInt($(this).val()), hideIfFormat) >= 0) {
            $('#slides_lbl, #monoStereo_lbl').hide();
        } else {
            $('#slides_lbl, #monoStereo_lbl').show();
        }
        if (jQuery.inArray(parseInt($(this).val()), showSideIfFormat) >= 0) {
            $('#slides_lbl').show();
        } else {
            $('#slides_lbl').hide();
        }
        if (jQuery.inArray(parseInt($(this).val()), showNoiceRedIfFormat) >= 0) {
            $('#noiceReduction_lbl').show();
        } else {
            $('#noiceReduction_lbl').hide();
        }
        if ($(this).val()) {
            if (jQuery.inArray(parseInt($(this).val()), hideBaseIfFormat) >= 0) {
                $("#bases_lbl").hide();
            } else {
                /// call to get base dropdown options
                $.ajax({
                    type: "GET",
                    url: baseUrl + 'getBase/' + $(this).val(),
                    success: function (response) {
                        if (response != "") {
                            $("#bases_lbl").show();
                            $("#bases").html(response);
                        } else {
                            $("#bases_lbl").hide();
                        }
                    }

                }); // Ajax Call
            }
            /// call to get reel diameters dropdown options
            if (selectedRD) {
                RDurl = baseUrl + 'getReelDiameter/' + $(this).val() + '/' + $("#mediaType").val() + '/' + selectedRD;
            } else {
                RDurl = baseUrl + 'getReelDiameter/' + $(this).val() + '/' + $("#mediaType").val();
            }
            $.ajax({
                type: "GET",
                url: RDurl,
                success: function (response) {
                    if (response != "") {
                        $("#reelDiameters_lbl").show();
                        $("#reelDiameters").html(response);
                    } else {
                        $("#reelDiameters_lbl").hide();
                    }
                }

            }); // Ajax Call
            if (jQuery.inArray(parseInt($(this).val()), hideRecordingSpeedFormat) >= 0) {
                $('#recordingSpeed_lbl').hide();
            } else {
                $('#recordingSpeed_lbl').show();
                /// call to get recording speed dropdown options
                if (selectedRS) {
                    url = baseUrl + 'getRecordingSpeed/' + $(this).val() + '/' + $("#mediaType").val() + '/' + selectedRS;
                } else {
                    url = baseUrl + 'getRecordingSpeed/' + $(this).val() + '/' + $("#mediaType").val();
                }
                $.ajax({
                    type: "GET",
                    url: url,
                    success: function (response) {
                        if (response != "") {
                            $("#recordingSpeed_lbl").show();
                            $("#recordingSpeed").html(response);
                        } else {
                            $("#recordingSpeed_lbl").hide();
                        }
                    }
                }); // Ajax Call
            }
            /// call to get formatversion dropdown options
            if (selectedFormatVersion) {
                formatVersiourl = baseUrl + 'getFormatVersion/' + $(this).val() + '/' + selectedFormatVersion;
            } else {
                formatVersiourl = baseUrl + 'getFormatVersion/' + $(this).val();
            }
            $.ajax({
                type: "GET",
                url: formatVersiourl,
                success: function (response) {
                    if (response != "") {
                        $("#formatVersion_lbl").show();
                        $("#formatVersion").html(response);
                    } else {
                        $("#formatVersion_lbl").hide();
                    }
                }

            }); // Ajax Call
        } else {
            $('#diskDiameters_lbl').hide();
            $('#reelDiameters_lbl').hide();
            $('#mediaDiameters_lbl').hide();
            $('#tapeThickness_lbl').hide();
            $('#trackTypes_lbl').hide();
            $('#cassetteSize_lbl').hide();
            $("#formatVersion_lbl").hide();
            $('#bases_lbl').hide();
            $('#recordingSpeed_lbl').hide();
        }
    });

}

function onChangeMediaType() {
    $(".new #mediaType").change(function () {
        if ($(this).val() == 3) {
            $('#fieldsPanel').hide();
            $('#processing').show();
            window.location.href = baseUrl + 'video/new';
        } else if ($(this).val() == 2) {
            $('#fieldsPanel').hide();
            $('#processing').show();
            window.location.href = baseUrl + 'film/new';
        } else if ($(this).val() == 1) {
            $('#fieldsPanel').hide();
            $('#processing').show();
            window.location.href = baseUrl + 'audio/new';
        }
    });
}

function saveBulkEdit() {
    $("#submitBulkEdit").click(function () {
        data = $('#frmBulkEdit').serialize();
        $(document).ajaxStart(function () {
            $("#frmBulkEdit").hide();
            $('#editProcessing').show();
            $('#editProcessing').css('color', 'black');
            $('#editProcessing').html(' Processing please wait...');
        });
        $.ajax({
            type: "POST",
            url: bulkEdit,
            data: data,
            dataType: 'json',
            success: function (response) {
                if (response.success === true) {
                    window.location.reload();
                }
            }
        }); // Ajax Call
    });
}

function closeBtn() {
    $(".bulkEditCloseBtn").on('click', function () {
        $.modal.close();
        $('#selectAll').prop("checked", false);
        $('input[name=record_checkbox]').each(function () {
            $(this).prop("checked", false);
        });
        $('#records tr').each(function () {
            $(this).removeClass("selected");
        });
        $("#selectedrecords").val('');
        window.location.reload();
    });
}

function updateProjects() {
    if (typeof projectId !=undefined && projectId) {
        selectedProject = projectId;
    }
    var path = window.location.href;
    var split_path = path.split('/');
    if ($.isNumeric(split_path[split_path.length - 1])) {
        selectedProject = split_path[split_path.length - 1];
    }
    if (selectedProject) {
        urlProjects = baseUrl + 'getAllProjects/' + selectedProject;
    } else {
        urlProjects = baseUrl + 'getAllProjects';
    }
    $.ajax({
        type: "GET",
        url: urlProjects,
        success: function (response) {
            if (response != "") {
                $("#project").html(response);
            }
        }
    }); // Ajax Call
}

function updateViewSetting() {
    $('#project').change(function () {
        var proj_id = $('#project').val();
        //  console.log(audio);
        if (proj_id) {
            // selectedProject = proj_id;
            console.log('here');
            var newUrl = viewUrl + proj_id;
            console.log(newUrl);
//            $.ajax({
//                type: "GET",
//                url: newUrl,
//                success: function (response) {
            window.location = newUrl;

//                }
//            });
        }
    })
}<|endoftext|>


<commit_before>var max_elevation_old,
    height_diff_up_old,
    height_diff_down_old,
    access_elevation_old,
    up_snow_elevation_old,
    down_snow_elevation_old,
    height_diff_up_enable,
    height_diff_down_enable,
    up_snow_elevation_enable,
    down_snow_elevation_enable;

function hide_outings_unrelated_fields()
{
    var show_flags =
    [
        'outings_glacier',
        'outings_snow_elevation',
        'outings_track',
        'outings_conditions_levels',
        'outings_length',
        'outings_height_diff_down'
    ];
    var show_outings_glacier,
        show_outings_snow_elevation,
        show_outings_track,
        show_outings_conditions_levels,
        show_outings_length,
        show_outings_height_diff_down;

    show_flags.each(function(flag)
    {
        eval('show_' + flag + ' = false');
    });

    var activities = $A($F($('activities')));
    activities.each(function(activity)
    {
        if (activity == 1 || activity == 2 || activity == 5)
        {
            show_outings_snow_elevation = true;
            show_outings_track = true;
            show_outings_conditions_levels = true;
        }
        if (activity == 1 || activity == 2 || activity == 3)
        {
            show_outings_glacier = true;
        }
        if (activity == 1 || activity == 6 || activity == 7)
        {
            show_outings_length = true;
            show_outings_height_diff_down = true;
        }
        else
        {
            if (Math.round($('outing_length').value) > 0)
            {
                show_outings_length = true;
            }
            if (Math.round($('height_diff_down').value) > 0)
            {
                show_outings_height_diff_down = true;
            }
        }
    });

    show_flags.each(function(flag)
    {
        if (eval('show_' + flag))
        {
            $(flag).show();
        }
        else
        {
            $(flag).hide();
        }
    });
}

function check_outing_activities(e)
{
    if (outing_activities_already_tested)
    {
        // no need to check activities twice
        return;
    }

    var activities = $A($F($('activities')));
    if (activities.length == 2)
    {
        activities.sortBy(function(s){return Math.round(s);});
        var act_0 = activities[0];
        var act_1 = activities[1];
        if ((act_0 == 2 && act_1 == 3) ||
            (act_0 == 2 && act_1 == 5) ||
            (act_0 == 2 && act_1 == 7) ||
            (act_0 == 3 && act_1 == 4) ||
            (act_0 == 3 && act_1 == 6) ||
            (act_0 == 4 && act_1 == 6))
        {
            // no need to check activities for these pairs
            return;
        }
    }

    // ask for confirmation if nb activities is > 1
    if ($('revision').value.length == 0 &&
        activities.length > 1 &&
        !confirm(confirm_outing_activities_message))
    {
        Event.stop(e);
        switchFormButtonsStatus($('editform'), false);
        outing_activities_already_tested = true;
    }
}

function check_outing_date(e)
{
    if (outing_date_already_tested)
    {
        // no need to check date twice
        return;
    }

    var year = $('date_year').value;
    var month = $('date_month').value;
    var day = $('date_day').value;

    var now = new Date();

    // ask for confirmation if outing date is today and if it is sooner than 14:00
    if ($('revision').value.length == 0 &&
        year == now.getFullYear() &&
        month == (now.getMonth() + 1) &&
        day == now.getDate() &&
        now.getHours() <= 14 &&
        !confirm(confirm_outing_date_message))
    {
        Event.stop(e);
        switchFormButtonsStatus($('editform'), false);
        outing_date_already_tested = true;
    }
}

Event.observe(window, 'load', hide_outings_unrelated_fields);
Event.observe(window, 'load', function() {
    Event.observe('editform', 'submit', check_outing_activities);
    Event.observe('editform', 'submit', check_outing_date);
});

function init_outings_var()
{
    max_elevation_old = Math.round($('max_elevation').value);
    height_diff_up_old = Math.round($('height_diff_up').value);
    height_diff_down_old = Math.round($('height_diff_down').value);
    access_elevation_old = Math.round($('access_elevation').value);
    up_snow_elevation_old = Math.round($('up_snow_elevation').value);
    down_snow_elevation_old = Math.round($('down_snow_elevation').value);

    height_diff_up_enable = true;
    height_diff_down_enable = true;
    up_snow_elevation_enable = true;
    down_snow_elevation_enable = true;
}

function update_max_elevation()
{
    if (height_diff_up_enable)
    {
        var max_elevation = Math.round($('max_elevation').value);
        height_diff_up_old = Math.round(height_diff_up_old + max_elevation - max_elevation_old);
        $('height_diff_up').value = height_diff_up_old;
        max_elevation_old = max_elevation;
    }
}

// Event.observe(window, 'load', init_outings_var);
<commit_msg>#697<commit_after>var max_elevation_old,
    height_diff_up_old,
    height_diff_down_old,
    access_elevation_old,
    up_snow_elevation_old,
    down_snow_elevation_old,
    height_diff_up_enable,
    height_diff_down_enable,
    up_snow_elevation_enable,
    down_snow_elevation_enable;

function hide_outings_unrelated_fields()
{
    var show_flags =
    [
        'outings_glacier',
        'outings_snow_elevation',
        'outings_track',
        'outings_conditions_levels',
        'outings_length',
        'outings_height_diff_down'
    ];
    var show_outings_glacier,
        show_outings_snow_elevation,
        show_outings_track,
        show_outings_conditions_levels,
        show_outings_length,
        show_outings_height_diff_down;

    show_flags.each(function(flag)
    {
        eval('show_' + flag + ' = false');
    });

    var activities = $A($F($('activities')));
    activities.each(function(activity)
    {
        if (activity == 1 || activity == 2 || activity == 5 || activity == 7)
        {
            show_outings_snow_elevation = true;
            show_outings_track = true;
            show_outings_conditions_levels = true;
        }
        if (activity == 1 || activity == 2 || activity == 3 || activity == 7)
        {
            show_outings_glacier = true;
        }
        if (activity == 1 || activity == 6 || activity == 7)
        {
            show_outings_length = true;
            show_outings_height_diff_down = true;
        }
        else
        {
            if (Math.round($('outing_length').value) > 0)
            {
                show_outings_length = true;
            }
            if (Math.round($('height_diff_down').value) > 0)
            {
                show_outings_height_diff_down = true;
            }
        }
    });

    show_flags.each(function(flag)
    {
        if (eval('show_' + flag))
        {
            $(flag).show();
        }
        else
        {
            $(flag).hide();
        }
    });
}

function check_outing_activities(e)
{
    if (outing_activities_already_tested)
    {
        // no need to check activities twice
        return;
    }

    var activities = $A($F($('activities')));
    if (activities.length == 2)
    {
        activities.sortBy(function(s){return Math.round(s);});
        var act_0 = activities[0];
        var act_1 = activities[1];
        if ((act_0 == 2 && act_1 == 3) ||
            (act_0 == 2 && act_1 == 5) ||
            (act_0 == 2 && act_1 == 7) ||
            (act_0 == 3 && act_1 == 4) ||
            (act_0 == 3 && act_1 == 6) ||
            (act_0 == 4 && act_1 == 6))
        {
            // no need to check activities for these pairs
            return;
        }
    }

    // ask for confirmation if nb activities is > 1
    if ($('revision').value.length == 0 &&
        activities.length > 1 &&
        !confirm(confirm_outing_activities_message))
    {
        Event.stop(e);
        switchFormButtonsStatus($('editform'), false);
        outing_activities_already_tested = true;
    }
}

function check_outing_date(e)
{
    if (outing_date_already_tested)
    {
        // no need to check date twice
        return;
    }

    var year = $('date_year').value;
    var month = $('date_month').value;
    var day = $('date_day').value;

    var now = new Date();

    // ask for confirmation if outing date is today and if it is sooner than 14:00
    if ($('revision').value.length == 0 &&
        year == now.getFullYear() &&
        month == (now.getMonth() + 1) &&
        day == now.getDate() &&
        now.getHours() <= 14 &&
        !confirm(confirm_outing_date_message))
    {
        Event.stop(e);
        switchFormButtonsStatus($('editform'), false);
        outing_date_already_tested = true;
    }
}

Event.observe(window, 'load', hide_outings_unrelated_fields);
Event.observe(window, 'load', function() {
    Event.observe('editform', 'submit', check_outing_activities);
    Event.observe('editform', 'submit', check_outing_date);
});

function init_outings_var()
{
    max_elevation_old = Math.round($('max_elevation').value);
    height_diff_up_old = Math.round($('height_diff_up').value);
    height_diff_down_old = Math.round($('height_diff_down').value);
    access_elevation_old = Math.round($('access_elevation').value);
    up_snow_elevation_old = Math.round($('up_snow_elevation').value);
    down_snow_elevation_old = Math.round($('down_snow_elevation').value);

    height_diff_up_enable = true;
    height_diff_down_enable = true;
    up_snow_elevation_enable = true;
    down_snow_elevation_enable = true;
}

function update_max_elevation()
{
    if (height_diff_up_enable)
    {
        var max_elevation = Math.round($('max_elevation').value);
        height_diff_up_old = Math.round(height_diff_up_old + max_elevation - max_elevation_old);
        $('height_diff_up').value = height_diff_up_old;
        max_elevation_old = max_elevation;
    }
}

// Event.observe(window, 'load', init_outings_var);
<|endoftext|>


<commit_before>// function to use d3 to graph density plots with preprocessed data

function density(data) {

    var mydiv;
    if(arguments.callee.caller.name=="subset") {
        mydiv = "#subset";
    }
    else if(arguments.callee.caller.name=="setx") {
        mydiv = "#setx";
    }
    else {
        return (alert("Error: incorrect div selected for plots"));
    }

    var yVals = data.properties.y;
    var xVals = data.properties.x;

    // an array of objects
    var data2 = [];
    for(var i = 0; i < data.properties.x.length; i++) {
        data2.push({x:data.properties.x[i], y:data.properties.y[i]});
    }
   // console.log(data2);

    data2.forEach(function(d) {
                  d.x = +d.x;
                  d.y = +d.y;
                  });

    var tempWidth = d3.select(mydiv).style("width")
    var width = tempWidth.substring(0,(tempWidth.length-2));

    var tempHeight = d3.select(mydiv).style("height")
    var height = tempHeight.substring(0,(tempHeight.length-2));

    var margin = {top: 20, right: 20, bottom: 30, left: 50},
    width = 0.4 * (width - margin.left - margin.right),
    height = 0.25 * (height - margin.top - margin.bottom);

    var x = d3.scale.linear()
    .domain([d3.min(xVals), d3.max(xVals)])
    .range([0, width]);

    var y = d3.scale.linear()
    .domain([d3.min(yVals), d3.max(yVals)])
    .range([height, 0]);

    var xAxis = d3.svg.axis()
    .scale(x)
    .orient("bottom");

    var yAxis = d3.svg.axis()
    .scale(y)
    .orient("left");

    var area = d3.svg.area()
    .interpolate("monotone")
    .x(function(d) { return x(d.x); })
    .y0(height)
    .y1(function(d) { return y(d.y); });

    var plotsvg = d3.select(mydiv).append("svg")
    .attr("id", function(d){
          return data.varname.toString().concat(".",arguments.callee.caller.name);
          })
    .attr("width", width + margin.left + margin.right)
    .attr("height", height + margin.top + margin.bottom)
    .append("g")
    .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

    plotsvg.append("path")
    .datum(data2)
    .attr("class", "area")
    .attr("d", area);

    plotsvg.append("g")
    .attr("class", "x axis")
    .attr("transform", "translate(0," + height + ")")
    .call(xAxis);

    plotsvg.append("g")
    .attr("class", "y axis")
    .call(yAxis);

    plotsvg.append("text")
    .attr("x", (width / 2))
    .attr("y", 0-(margin.top / 2))
    .attr("text-anchor", "middle")
    .style("font-size", "12px")
    .text(data.varname);

    return [x, y, plotsvg, width, height];
}

function bars() {
    //...
}<commit_msg>subset setx fixes<commit_after>// function to use d3 to graph density plots with preprocessed data

function density(data) {

    var mydiv;
    if(arguments.callee.caller.name=="subset") {
        mydiv = "#subset";
    }
    else if(arguments.callee.caller.name=="setx") {
        mydiv = "#setx";
    }
    else {
        return (alert("Error: incorrect div selected for plots"));
    }

    var yVals = data.properties.y;
    var xVals = data.properties.x;

    // an array of objects
    var data2 = [];
    for(var i = 0; i < data.properties.x.length; i++) {
        data2.push({x:data.properties.x[i], y:data.properties.y[i]});
    }
   // console.log(data2);

    data2.forEach(function(d) {
                  d.x = +d.x;
                  d.y = +d.y;
                  });

    var tempWidth = d3.select(mydiv).style("width")
    var width = tempWidth.substring(0,(tempWidth.length-2));

    var tempHeight = d3.select(mydiv).style("height")
    var height = tempHeight.substring(0,(tempHeight.length-2));

    var margin = {top: 20, right: 20, bottom: 30, left: 50},
    width = 0.4 * (width - margin.left - margin.right),
    height = 0.25 * (height - margin.top - margin.bottom);

    var x = d3.scale.linear()
    .domain([d3.min(xVals), d3.max(xVals)])
    .range([0, width]);

    var y = d3.scale.linear()
    .domain([d3.min(yVals), d3.max(yVals)])
    .range([height, 0]);

    var xAxis = d3.svg.axis()
    .scale(x)
    .orient("bottom");

    var yAxis = d3.svg.axis()
    .scale(y)
    .orient("left");

    var area = d3.svg.area()
    .interpolate("monotone")
    .x(function(d) { return x(d.x); })
    .y0(height)
    .y1(function(d) { return y(d.y); });

    var plotsvg = d3.select(mydiv).append("svg")
    .attr("id", function(d){
          console.log(data.varname.toString().concat(".",mydiv.substr(1)));
          return data.varname.toString().concat(".",mydiv.substr(1));
          })
    .attr("width", width + margin.left + margin.right)
    .attr("height", height + margin.top + margin.bottom)
    .append("g")
    .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

    plotsvg.append("path")
    .datum(data2)
    .attr("class", "area")
    .attr("d", area);

    plotsvg.append("g")
    .attr("class", "x axis")
    .attr("transform", "translate(0," + height + ")")
    .call(xAxis);

    plotsvg.append("g")
    .attr("class", "y axis")
    .call(yAxis);

    plotsvg.append("text")
    .attr("x", (width / 2))
    .attr("y", 0-(margin.top / 2))
    .attr("text-anchor", "middle")
    .style("font-size", "12px")
    .text(data.varname);

    return [x, y, plotsvg, width, height];
}

function bars() {
    //...
}<|endoftext|>