<commit_before>'use strict';

module.exports = function(grunt) {
  require('load-grunt-tasks')(grunt);
  require('time-grunt')(grunt);
  grunt.loadNpmTasks('grunt-contrib-htmlmin');
  grunt.loadNpmTasks('grunt-bower-task');
  grunt.loadNpmTasks('grunt-karma');

  grunt.initConfig({
    yeoman: {
      // configurable paths
      app: require('./bower.json').appPath || 'src',
      gen: require('./bower.json').appPath || 'src-gen',
      dist: 'www'
    },
    watch: {
      compass: {
        files: ['<%= yeoman.app %>/styles/{,*/}*.{scss,sass}'],
        tasks: ['compass:server', 'autoprefixer']
      },
      styles: {
        files: ['<%= yeoman.app %>/styles/{,*/}*.css'],
        tasks: ['copy:styles', 'autoprefixer']
      },
      livereload: {
        options: {
          livereload: '<%= connect.options.livereload %>'
        },
        files: [
          '<%= yeoman.app %>/{,*/}*.html',
          '.tmp/styles/{,*/}*.css',
          '{.tmp,<%= yeoman.app %>}/scripts/{,*/}*.js',
          '<%= yeoman.app %>/images/{,*/}*.{png,jpg,jpeg,gif,webp,svg}',
          'bower_components/{,*/}*'
        ]
      }
    },
    autoprefixer: {
      options: ['last 1 version'],
      dist: {
        files: [{
          expand: true,
          cwd: '.tmp/styles/',
          src: '{,*/}*.css',
          dest: '.tmp/styles/'
        }]
      }
    },
    connect: {
      options: {
        port: 9000,
        // Change this to '0.0.0.0' to access the server from outside.
        hostname: 'localhost',
        livereload: 35729
      },
      livereload: {
        options: {
          open: true,
          base: [
            '.tmp',
            '<%= yeoman.app %>',
            '.'
          ]
        }
      },
      test: {
        options: {
          port: 9001,
          base: [
            '<%= yeoman.app %>/{,*/}*.html',
            '.tmp/styles/{,*/}*.css',
            '{.tmp,<%= yeoman.app %>}/scripts/{,*/}*.js',
            '<%= yeoman.app %>/images/{,*/}*.{png,jpg,jpeg,gif,webp,svg}',
            'bower_components/{,*/}*'
          ]
        }
      },
      dist: {
        options: {
          base: '<%= yeoman.dist %>'
        }
      }
    },
    clean: {
      dist: {
        files: [{
          dot: true,
          src: [
            '.tmp',
            '<%= yeoman.dist %>/*',
            '!<%= yeoman.dist %>/.git*'
          ]
        }]
      },
      server: '.tmp'
    },
    jshint: {
      options: {
        jshintrc: '.jshintrc'
      },
      all: [
        'Gruntfile.js',
        '<%= yeoman.app %>/scripts/{,*/}*.js'
      ]
    },
    compass: {
      options: {
        sassDir: '<%= yeoman.app %>/styles',
        cssDir: '.tmp/styles',
        generatedImagesDir: '.tmp/images/generated',
        imagesDir: '<%= yeoman.app %>/images',
        javascriptsDir: '<%= yeoman.app %>/scripts',
        fontsDir: '<%= yeoman.app %>/styles/fonts',
        importPath: 'bower_components',
        httpImagesPath: '/images',
        httpGeneratedImagesPath: '/images/generated',
        httpFontsPath: '/styles/fonts',
        relativeAssets: false
      },
      dist: {},
      server: {
        options: {
          debugInfo: true
        }
      }
    },
    useminPrepare: {
      html: '<%= yeoman.app %>/index.html',
      options: {
        dest: '<%= yeoman.dist %>'
      }
    },
    usemin: {
      html: ['<%= yeoman.dist %>/{,*/}*.html'],
      css: ['<%= yeoman.dist %>/styles/{,*/}*.css'],
      options: {
        dirs: ['<%= yeoman.dist %>']
      }
    },
    htmlmin: {
      dist: {
        options: {},
        files: [{
          expand: true,
          cwd: '<%= yeoman.app %>',
          src: ['index.html'],
          dest: '<%= yeoman.dist %>'
        }]
      }
    },
    // Put files not handled in other tasks here
    copy: {
      dist: {
        files: [{
          expand: true,
          dot: true,
          cwd: '<%= yeoman.app %>',
          dest: '<%= yeoman.dist %>',
          src: [
            '*.{ico,png,txt}',
            '.htaccess',
            'config.json',
            'images/{,*/}*.*',
            'styles/fonts/*',
            'scripts/webworker*.js',
            '*.js',
            'views/*.html',
            'templates/*.html'
          ]
        }, {
          expand: true,
          dot: true,
          cwd: '<%= yeoman.gen %>',
          dest: '<%= yeoman.dist %>',
          src: [
            '*.{ico,png,txt}',
            '.htaccess',
            'config.json',
            'images/{,*/}*.*',
            'styles/fonts/*',
            '*.js'
          ]
        }, {
          expand: true,
          cwd: '.tmp/images',
          dest: '<%= yeoman.dist %>/images',
          src: [
            'generated/*'
          ]
        }, {
          expand: true,
          cwd: 'bower_components/mobile-angular-ui/dist/fonts',
          dest: '<%= yeoman.dist %>/fonts',
          src: [
            '*',
          ]
        }, {
          expand: true,
          cwd: 'bower_components/bootstrap-sass/vendor/assets/fonts/bootstrap',
          dest: '<%= yeoman.dist %>/fonts',
          src: [
            '*'
          ]
        }]
      },
      styles: {
        expand: true,
        cwd: '<%= yeoman.app %>/styles',
        dest: '.tmp/styles/',
        src: '{,*/}*.css'
      }
    },
    concurrent: {
      server: [
        'compass:server',
        'copy:styles'
      ],
      test: [
        'compass',
        'copy:styles'
      ],
      dist: [
        'compass:dist',
        'copy:styles',
        'htmlmin'
      ]
    },
    karma: {
      unit: {
        configFile: 'karma.conf.js',
        singleRun: true
      },
      server: {
        configFile: 'karma.conf.js',
        singleRun: false,
        autoWatch: true
      }
    },
    cdnify: {
      dist: {
        html: ['<%= yeoman.dist %>/*.html']
      }
    },
    ngmin: {
      dist: {
        files: [{
          expand: true,
          cwd: '<%= yeoman.dist %>/scripts',
          src: ['*.js', '!webworker*.js'],
          dest: '<%= yeoman.dist %>/scripts'
        }]
      }
    },
    uglify: {
      dist: {
        files: {
          '<%= yeoman.dist %>/scripts/scripts.js': [
            '<%= yeoman.dist %>/scripts/scripts.js'
          ]
        }
      }
    },
    shell: {
      options: {
        failOnError: true,
        stdout: true,
        stderr: true,
        execOptions: {
          maxBuffer: Infinity
        }
      },
      buildIOS: {
        command: 'cordova build ios'
      },
      buildAndroid: {
        command: 'cordova build android'
      }
    }
  });

  grunt.registerTask('ci:ios', 'Set up CI for iOS (noop)', function() {
    //
  });

  grunt.registerTask('ci:android', 'Set up CI for Android (noop)', function() {
    var done = this.async();

    var setup = require('child_process').spawn('./etc/setupAndroidSDK.sh');

    setup.stdout.pipe(process.stdout);
    setup.stderr.pipe(process.stderr);

    setup.on('close', function(code) {
      done(code === 0);
    });
  });

  grunt.registerTask('test:ios', ['shell:buildIOS']);

  grunt.registerTask('test:android', ['shell:buildAndroid']);

  grunt.registerTask('ios', ['clean', 'release', 'test:ios']);

  grunt.registerTask('android', ['clean', 'release', 'test:android']);

  grunt.registerTask('server', function(target) {
    if (target === 'dist') {
      return grunt.task.run(['build', 'connect:dist:keepalive']);
    }

    grunt.task.run([
      'clean:server',
      'concurrent:server',
      'autoprefixer',
      'connect:livereload',
      'watch'
    ]);
  });

  grunt.registerTask('test', [
    'clean:server',
    'concurrent:test',
    'autoprefixer',
    'connect:test',
    'karma:unit'
  ]);

  grunt.registerTask('build', [
    'clean:dist',
    'useminPrepare',
    'concurrent:dist',
    'autoprefixer',
    'concat',
    'copy:dist',
    'usemin'
  ]);

  grunt.registerTask('release', [
    'clean:dist',
    'useminPrepare',
    'concurrent:dist',
    'autoprefixer',
    'concat',
    'copy:dist',
    'ngmin',
    'cssmin',
    'uglify',
    'usemin'
  ]);

  grunt.registerTask('default', [
    'test',
    'build'
  ]);
};<commit_msg>Adding platforms in grunt build<commit_after>'use strict';

module.exports = function(grunt) {
  require('load-grunt-tasks')(grunt);
  require('time-grunt')(grunt);
  grunt.loadNpmTasks('grunt-contrib-htmlmin');
  grunt.loadNpmTasks('grunt-bower-task');
  grunt.loadNpmTasks('grunt-karma');

  grunt.initConfig({
    yeoman: {
      // configurable paths
      app: require('./bower.json').appPath || 'src',
      gen: require('./bower.json').appPath || 'src-gen',
      dist: 'www'
    },
    watch: {
      compass: {
        files: ['<%= yeoman.app %>/styles/{,*/}*.{scss,sass}'],
        tasks: ['compass:server', 'autoprefixer']
      },
      styles: {
        files: ['<%= yeoman.app %>/styles/{,*/}*.css'],
        tasks: ['copy:styles', 'autoprefixer']
      },
      livereload: {
        options: {
          livereload: '<%= connect.options.livereload %>'
        },
        files: [
          '<%= yeoman.app %>/{,*/}*.html',
          '.tmp/styles/{,*/}*.css',
          '{.tmp,<%= yeoman.app %>}/scripts/{,*/}*.js',
          '<%= yeoman.app %>/images/{,*/}*.{png,jpg,jpeg,gif,webp,svg}',
          'bower_components/{,*/}*'
        ]
      }
    },
    autoprefixer: {
      options: ['last 1 version'],
      dist: {
        files: [{
          expand: true,
          cwd: '.tmp/styles/',
          src: '{,*/}*.css',
          dest: '.tmp/styles/'
        }]
      }
    },
    connect: {
      options: {
        port: 9000,
        // Change this to '0.0.0.0' to access the server from outside.
        hostname: 'localhost',
        livereload: 35729
      },
      livereload: {
        options: {
          open: true,
          base: [
            '.tmp',
            '<%= yeoman.app %>',
            '.'
          ]
        }
      },
      test: {
        options: {
          port: 9001,
          base: [
            '<%= yeoman.app %>/{,*/}*.html',
            '.tmp/styles/{,*/}*.css',
            '{.tmp,<%= yeoman.app %>}/scripts/{,*/}*.js',
            '<%= yeoman.app %>/images/{,*/}*.{png,jpg,jpeg,gif,webp,svg}',
            'bower_components/{,*/}*'
          ]
        }
      },
      dist: {
        options: {
          base: '<%= yeoman.dist %>'
        }
      }
    },
    clean: {
      dist: {
        files: [{
          dot: true,
          src: [
            '.tmp',
            '<%= yeoman.dist %>/*',
            '!<%= yeoman.dist %>/.git*'
          ]
        }]
      },
      server: '.tmp'
    },
    jshint: {
      options: {
        jshintrc: '.jshintrc'
      },
      all: [
        'Gruntfile.js',
        '<%= yeoman.app %>/scripts/{,*/}*.js'
      ]
    },
    compass: {
      options: {
        sassDir: '<%= yeoman.app %>/styles',
        cssDir: '.tmp/styles',
        generatedImagesDir: '.tmp/images/generated',
        imagesDir: '<%= yeoman.app %>/images',
        javascriptsDir: '<%= yeoman.app %>/scripts',
        fontsDir: '<%= yeoman.app %>/styles/fonts',
        importPath: 'bower_components',
        httpImagesPath: '/images',
        httpGeneratedImagesPath: '/images/generated',
        httpFontsPath: '/styles/fonts',
        relativeAssets: false
      },
      dist: {},
      server: {
        options: {
          debugInfo: true
        }
      }
    },
    useminPrepare: {
      html: '<%= yeoman.app %>/index.html',
      options: {
        dest: '<%= yeoman.dist %>'
      }
    },
    usemin: {
      html: ['<%= yeoman.dist %>/{,*/}*.html'],
      css: ['<%= yeoman.dist %>/styles/{,*/}*.css'],
      options: {
        dirs: ['<%= yeoman.dist %>']
      }
    },
    htmlmin: {
      dist: {
        options: {},
        files: [{
          expand: true,
          cwd: '<%= yeoman.app %>',
          src: ['index.html'],
          dest: '<%= yeoman.dist %>'
        }]
      }
    },
    // Put files not handled in other tasks here
    copy: {
      dist: {
        files: [{
          expand: true,
          dot: true,
          cwd: '<%= yeoman.app %>',
          dest: '<%= yeoman.dist %>',
          src: [
            '*.{ico,png,txt}',
            '.htaccess',
            'config.json',
            'images/{,*/}*.*',
            'styles/fonts/*',
            'scripts/webworker*.js',
            '*.js',
            'views/*.html',
            'templates/*.html'
          ]
        }, {
          expand: true,
          dot: true,
          cwd: '<%= yeoman.gen %>',
          dest: '<%= yeoman.dist %>',
          src: [
            '*.{ico,png,txt}',
            '.htaccess',
            'config.json',
            'images/{,*/}*.*',
            'styles/fonts/*',
            '*.js'
          ]
        }, {
          expand: true,
          cwd: '.tmp/images',
          dest: '<%= yeoman.dist %>/images',
          src: [
            'generated/*'
          ]
        }, {
          expand: true,
          cwd: 'bower_components/mobile-angular-ui/dist/fonts',
          dest: '<%= yeoman.dist %>/fonts',
          src: [
            '*',
          ]
        }, {
          expand: true,
          cwd: 'bower_components/bootstrap-sass/vendor/assets/fonts/bootstrap',
          dest: '<%= yeoman.dist %>/fonts',
          src: [
            '*'
          ]
        }]
      },
      styles: {
        expand: true,
        cwd: '<%= yeoman.app %>/styles',
        dest: '.tmp/styles/',
        src: '{,*/}*.css'
      }
    },
    concurrent: {
      server: [
        'compass:server',
        'copy:styles'
      ],
      test: [
        'compass',
        'copy:styles'
      ],
      dist: [
        'compass:dist',
        'copy:styles',
        'htmlmin'
      ]
    },
    karma: {
      unit: {
        configFile: 'karma.conf.js',
        singleRun: true
      },
      server: {
        configFile: 'karma.conf.js',
        singleRun: false,
        autoWatch: true
      }
    },
    cdnify: {
      dist: {
        html: ['<%= yeoman.dist %>/*.html']
      }
    },
    ngmin: {
      dist: {
        files: [{
          expand: true,
          cwd: '<%= yeoman.dist %>/scripts',
          src: ['*.js', '!webworker*.js'],
          dest: '<%= yeoman.dist %>/scripts'
        }]
      }
    },
    uglify: {
      dist: {
        files: {
          '<%= yeoman.dist %>/scripts/scripts.js': [
            '<%= yeoman.dist %>/scripts/scripts.js'
          ]
        }
      }
    },
    shell: {
      options: {
        failOnError: true,
        stdout: true,
        stderr: true,
        execOptions: {
          maxBuffer: Infinity
        }
      },
      buildIOS: {
        command: 'cordova platform add ios && cordova build ios'
      },
      buildAndroid: {
        command: 'cordova platform add android && build android'
      }
    }
  });

  grunt.registerTask('ci:ios', 'Set up CI for iOS (noop)', function() {
    //
  });

  grunt.registerTask('ci:android', 'Set up CI for Android (noop)', function() {
    var done = this.async();

    var setup = require('child_process').spawn('./etc/setupAndroidSDK.sh');

    setup.stdout.pipe(process.stdout);
    setup.stderr.pipe(process.stderr);

    setup.on('close', function(code) {
      done(code === 0);
    });
  });

  grunt.registerTask('test:ios', ['shell:buildIOS']);

  grunt.registerTask('test:android', ['shell:buildAndroid']);

  grunt.registerTask('ios', ['clean', 'release', 'test:ios']);

  grunt.registerTask('android', ['clean', 'release', 'test:android']);

  grunt.registerTask('server', function(target) {
    if (target === 'dist') {
      return grunt.task.run(['build', 'connect:dist:keepalive']);
    }

    grunt.task.run([
      'clean:server',
      'concurrent:server',
      'autoprefixer',
      'connect:livereload',
      'watch'
    ]);
  });

  grunt.registerTask('test', [
    'clean:server',
    'concurrent:test',
    'autoprefixer',
    'connect:test',
    'karma:unit'
  ]);

  grunt.registerTask('build', [
    'clean:dist',
    'useminPrepare',
    'concurrent:dist',
    'autoprefixer',
    'concat',
    'copy:dist',
    'usemin'
  ]);

  grunt.registerTask('release', [
    'clean:dist',
    'useminPrepare',
    'concurrent:dist',
    'autoprefixer',
    'concat',
    'copy:dist',
    'ngmin',
    'cssmin',
    'uglify',
    'usemin'
  ]);

  grunt.registerTask('default', [
    'test',
    'build'
  ]);
};<|endoftext|>


<commit_before>/* eslint-disable consistent-return, no-undef, no-unused-expressions */
import { expect } from "chai";
import { env } from "jsdom";

import * as dom from "../src/dom";

const fakeWindow = {
    getComputedStyle() {
        return { position: "relative" }
    },
    document: {
        body: {
            getBoundingClientRect() {
                return {
                    top: -100,
                    left: -50
                };
            }
        }
    }
};

describe("DOM utilities", () => {
    describe("getOffsetScroll", () => {
        it("must return an object with `left` and `top` numeric properties", () => {
            const scroll = dom.getOffsetScroll(fakeWindow);
            expect(scroll).to.be.an("object");
            expect(scroll.left).to.be.a("number");
            expect(scroll.top).to.be.a("number");
        });
        it("must return the normalized top and left scroll of the page", () => {
            const scroll = dom.getOffsetScroll(fakeWindow);
            expect(scroll).to.include({ top: -100, left: -50 });
        });
    });

    describe("matches", () => {
        it("must work like `Element.prototype.matches`", (done) => {
            env("
Bar
", (err, _window) => {
                expect(err).to.be.null;

                const selectorMatches = {
                    ".foo": ".wrapper > span",
                    span: "#main > span",
                    "#main": "main"
                };

                for (const selector of Object.keys(selectorMatches)) {
                    const match = selectorMatches[selector];
                    const element = _window.document.querySelector(selector);
                    if (!element) {
                        return done(Error(`Can't find element ${selector}`));
                    }

                    const test = dom.matches(element, match);
                    if (test !== element.matches(match)) {
                        return done(Error(`Element ${selector} doesn't behave like 'matches' for ${match} (${test})`));
                    }
                }

                done();
            });
        });
    });

    describe("closest", () => {
        it("must return the closest matching ancestor", (done) => {
            env("
Bar
", (err, _window) => {
                expect(err).to.be.null;

                const foo = _window.document.querySelector(".foo");
                const wrapper = _window.document.querySelector(".wrapper");
                const ancestor = dom.closest(foo, ".wrapper");

                expect(ancestor).to.equal(wrapper);

                done();
            });
        });
        it("must return null if no ancestor matches the selector", (done) => {
            env("
Bar
", (err, _window) => {
                expect(err).to.be.null;

                const foo = _window.document.querySelector(".foo");
                const ancestor = dom.closest(foo, ".bar");

                expect(ancestor).to.be.null;

                done();
            });
        });
    });

    describe("contains", () => {
        it("must return true if and only if the ancestor contains the target or it's the same node", (done) => {
            env("
Bar
", (err, _window) => {
                expect(err).to.be.null;

                const target = _window.document.querySelector(".foo");
                const ancestor = _window.document.querySelector(".wrapper");

                expect(dom.contains(ancestor, target)).to.be.true;
                expect(dom.contains(ancestor, ancestor)).to.be.true;
                expect(dom.contains(ancestor, _window.document.body)).to.be.false;

                done();
            });
        });
        it("must work with any kind of node", (done) => {
            env("
Bar
", (err, _window) => {
                expect(err).to.be.null;

                const target = _window.document.querySelector(".foo");
                const text = target.firstChild;
                const ancestor = _window.document.querySelector(".wrapper");
                const comment = ancestor.lastChild;

                expect(dom.contains(ancestor, text)).to.be.true;
                expect(dom.contains(ancestor, comment)).to.be.true;

                done();
            });
        });
    });
});
<commit_msg>Linting<commit_after>/* eslint-disable consistent-return, no-undef, no-unused-expressions */
import { expect } from "chai";
import { env } from "jsdom";

import * as dom from "../src/dom";

const fakeWindow = {
    getComputedStyle() {
        return { position: "relative" };
    },
    document: {
        body: {
            getBoundingClientRect() {
                return {
                    top: -100,
                    left: -50
                };
            }
        }
    }
};

describe("DOM utilities", () => {
    describe("getOffsetScroll", () => {
        it("must return an object with `left` and `top` numeric properties", () => {
            const scroll = dom.getOffsetScroll(fakeWindow);
            expect(scroll).to.be.an("object");
            expect(scroll.left).to.be.a("number");
            expect(scroll.top).to.be.a("number");
        });
        it("must return the normalized top and left scroll of the page", () => {
            const scroll = dom.getOffsetScroll(fakeWindow);
            expect(scroll).to.include({ top: -100, left: -50 });
        });
    });

    describe("matches", () => {
        it("must work like `Element.prototype.matches`", (done) => {
            env("
Bar
", (err, _window) => {
                expect(err).to.be.null;

                const selectorMatches = {
                    ".foo": ".wrapper > span",
                    span: "#main > span",
                    "#main": "main"
                };

                for (const selector of Object.keys(selectorMatches)) {
                    const match = selectorMatches[selector];
                    const element = _window.document.querySelector(selector);
                    if (!element) {
                        return done(Error(`Can't find element ${selector}`));
                    }

                    const test = dom.matches(element, match);
                    if (test !== element.matches(match)) {
                        return done(Error(`Element ${selector} doesn't behave like 'matches' for ${match} (${test})`));
                    }
                }

                done();
            });
        });
    });

    describe("closest", () => {
        it("must return the closest matching ancestor", (done) => {
            env("
Bar
", (err, _window) => {
                expect(err).to.be.null;

                const foo = _window.document.querySelector(".foo");
                const wrapper = _window.document.querySelector(".wrapper");
                const ancestor = dom.closest(foo, ".wrapper");

                expect(ancestor).to.equal(wrapper);

                done();
            });
        });
        it("must return null if no ancestor matches the selector", (done) => {
            env("
Bar
", (err, _window) => {
                expect(err).to.be.null;

                const foo = _window.document.querySelector(".foo");
                const ancestor = dom.closest(foo, ".bar");

                expect(ancestor).to.be.null;

                done();
            });
        });
    });

    describe("contains", () => {
        it("must return true if and only if the ancestor contains the target or it's the same node", (done) => {
            env("
Bar
", (err, _window) => {
                expect(err).to.be.null;

                const target = _window.document.querySelector(".foo");
                const ancestor = _window.document.querySelector(".wrapper");

                expect(dom.contains(ancestor, target)).to.be.true;
                expect(dom.contains(ancestor, ancestor)).to.be.true;
                expect(dom.contains(ancestor, _window.document.body)).to.be.false;

                done();
            });
        });
        it("must work with any kind of node", (done) => {
            env("
Bar
", (err, _window) => {
                expect(err).to.be.null;

                const target = _window.document.querySelector(".foo");
                const text = target.firstChild;
                const ancestor = _window.document.querySelector(".wrapper");
                const comment = ancestor.lastChild;

                expect(dom.contains(ancestor, text)).to.be.true;
                expect(dom.contains(ancestor, comment)).to.be.true;

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


<commit_before>/*
  jquery.popline.blockformat.js 0.0.1

  Version: 0.0.1
  Updated: May 18th, 2013

  (c) 2013 by kenshin54
*/
;(function($) {

  var tags = ["P", "H1", "H2", "H3", "H4", "H5", "H6", "VOID"];

  var wrap = function(tag) {
    var range = window.getSelection().getRangeAt(0);
    var anchorNode = window.getSelection().anchorNode, focusNode = window.getSelection().focusNode;
    var matchedNode = $.popline.utils.findNodeWithTags(focusNode, tags);
    tag = matchedNode && matchedNode.tagName === tag ? "VOID" : tag;
    var node = document.createElement(tag);
    var fragment = range.extractContents();

    removeEmptyTag(matchedNode);

    var textNode = document.createTextNode($(fragment).text());
    node.appendChild(textNode);

    range.insertNode(node);
    window.getSelection().selectAllChildren(node);
  }

  var removeEmptyTag = function(node) {
    if ($.popline.utils.trim($(node).text()) === "") {
      $(node).remove();
    }
  }

  $.popline.addButton({
    blockFormat: {
      iconClass: "fa fa-header",

      mode: "edit",
      buttons: {
        normal: {
          text: "P",
          textClass: "lighter",
          action: function(event) {
            wrap("P");
          }
        },
        h1: {
          text: "H1",
          action: function(event) {
            wrap("H1");
          }
        },
        h2: {
          text: "H2",
          action: function(event) {
            wrap("H2");
          }
        },
        h3: {
          text: "H3",
          action: function(event) {
            wrap("H3");
          }
        },
        h4: {
          text: "H4",
          action: function(event) {
            wrap("H4");
          }
        },
        h5: {
          text: "H5",
          action: function(event) {
            wrap("H5");
          }
        },
        h6: {
          text: "H6",
          action: function(event) {
            wrap("H6");
          }
        }
      },
      afterHide: function(popline){
        popline.target.find("void").contents().unwrap();
      }
    }
  });

})(jQuery);
<commit_msg>Creando panel de herramientas de edición<commit_after>/*
  jquery.popline.blockformat.js 0.0.1

  Version: 0.0.1
  Updated: May 18th, 2013

  (c) 2013 by kenshin54
*/
;(function($) {

  var tags = ["P", "H1", "H2", "H3", "H4", "H5", "H6", "VOID"];

  var wrap = function(tag) {
    var range = window.getSelection().getRangeAt(0);
    var anchorNode = window.getSelection().anchorNode, focusNode = window.getSelection().focusNode;
    var matchedNode = $.popline.utils.findNodeWithTags(focusNode, tags);
    tag = matchedNode && matchedNode.tagName === tag ? "VOID" : tag;
    var node = document.createElement(tag);
    var fragment = range.extractContents();

    removeEmptyTag(matchedNode);

    var textNode = document.createTextNode($(fragment).text());
    node.appendChild(textNode);

    range.insertNode(node);
    window.getSelection().selectAllChildren(node);
  }

  var removeEmptyTag = function(node) {
    if ($.popline.utils.trim($(node).text()) === "") {
      $(node).remove();
    }
  }

  $.popline.addButton({
    blockFormat: {
      //iconClass: "fa fa-header",
      text: "H",
      mode: "edit",
      buttons: {
        normal: {
          text: "P",
          textClass: "lighter",
          action: function(event) {
            wrap("P");
          }
        },
        h1: {
          text: "H1",
          action: function(event) {
            wrap("H1");
          }
        },
        h2: {
          text: "H2",
          action: function(event) {
            wrap("H2");
          }
        },
        h3: {
          text: "H3",
          action: function(event) {
            wrap("H3");
          }
        },
        h4: {
          text: "H4",
          action: function(event) {
            wrap("H4");
          }
        },
        h5: {
          text: "H5",
          action: function(event) {
            wrap("H5");
          }
        },
        h6: {
          text: "H6",
          action: function(event) {
            wrap("H6");
          }
        }
      },
      afterHide: function(popline){
        popline.target.find("void").contents().unwrap();
      }
    }
  });

})(jQuery);
<|endoftext|>


<commit_before>module.exports = function(grunt) {
	grunt.initConfig({
		pkg: grunt.file.readJSON('package.json'),

		jshint: {
			options: grunt.file.readJSON('src/.jshintrc'),
			src: ['src/*.js']
		},

		concat: {
			options: {
				separator: ';'
			},
			dist: {
				src: ['src/ecma5.js', 'src/Console.js', 'src/Styles.js', 'src/Stack.js'],
				dest: 'console.js'
			}
		},
		uglify: {
			options: {
				banner: '/*! <%= pkg.name %> v<%= pkg.version %> */\n'
			},
			build: {
				src: 'console.js',
				dest: 'console.min.js'
			}
		},

		bump: {
			options: {
				files: ['package.json', 'bower.json'],
				updateConfigs: ['pkg'],
				commit: false,
				commitMessage: 'Release v%VERSION%',
				commitFiles: ['package.json', 'bower.json'],
				createTag: false,
				tagName: 'v%VERSION%',
				tagMessage: 'Version %VERSION%',
				push: false,
				pushTo: 'upstream',
				gitDescribeOptions: '--tags --always --abbrev=1 --dirty=-d',
				globalReplace: false,
				prereleaseName: false,
				regExp: false
			}
		}
	});

	grunt.loadNpmTasks('grunt-contrib-concat');
	grunt.loadNpmTasks('grunt-contrib-uglify');
	grunt.loadNpmTasks('grunt-contrib-jshint');
	grunt.loadNpmTasks('grunt-bump');

	grunt.registerTask('build', ['jshint', 'concat', 'uglify']);
};<commit_msg>commit bumped version<commit_after>module.exports = function(grunt) {
	grunt.initConfig({
		pkg: grunt.file.readJSON('package.json'),

		jshint: {
			options: grunt.file.readJSON('src/.jshintrc'),
			src: ['src/*.js']
		},

		concat: {
			options: {
				separator: ';'
			},
			dist: {
				src: ['src/ecma5.js', 'src/Console.js', 'src/Styles.js', 'src/Stack.js'],
				dest: 'console.js'
			}
		},
		uglify: {
			options: {
				banner: '/*! <%= pkg.name %> v<%= pkg.version %> */\n'
			},
			build: {
				src: 'console.js',
				dest: 'console.min.js'
			}
		},

		bump: {
			options: {
				files: ['package.json', 'bower.json'],
				updateConfigs: ['pkg'],
				commit: true,
				commitMessage: 'Release v%VERSION%',
				commitFiles: ['package.json', 'bower.json'],
				createTag: false,
				tagName: 'v%VERSION%',
				tagMessage: 'Version %VERSION%',
				push: false,
				pushTo: 'upstream',
				gitDescribeOptions: '--tags --always --abbrev=1 --dirty=-d',
				globalReplace: false,
				prereleaseName: false,
				regExp: false
			}
		}
	});

	grunt.loadNpmTasks('grunt-contrib-concat');
	grunt.loadNpmTasks('grunt-contrib-uglify');
	grunt.loadNpmTasks('grunt-contrib-jshint');
	grunt.loadNpmTasks('grunt-bump');

	grunt.registerTask('build', ['jshint', 'concat', 'uglify']);
};<|endoftext|>


<commit_before>/* Main code */

/* RequireJS configurations */
requirejs.config({
	shim: {
		'bootstrap':{
			deps: ['jquery']
		},
		'showdown':{
			deps: [],
			exports: 'Showdown'
		}
	}
});

require(["jquery", "moment", "bootstrap", "showdown"], function(jquery, moment, bootstrap, Showdown) {

	var SERVER_CONFIG = {};
	var INFODESK_GLOBAL = {};

	/* Pop error message */
	function add_error(args) {
		//alert('error: '+ JSON.stringify(args));
		var data, dialog;
		if(args && (typeof args === 'object')) {
			if(args.error) {
				args.title = args.error;
				delete args.error;
			}
			if(args.title || args.desc) {
				data = args;
			} else {
				data = {'desc': JSON.stringify(args)};
			}
		} else {
			data = {'title':''+args};
		}
		if(!data.date) data.date = new Date();
		dialog = jquery('#elements .error_dialog').clone();
		dialog.find('.date').text(data.date);
		dialog.find('.title').text(data.title);
		if(data.desc && ((data.desc+'').length > 0) ) {
			dialog.find('.desc').text(data.desc);
		} else {
			dialog.find('.desc_container').hide();
		}
		dialog.prependTo('#notifications');
		dialog.alert();
	};

	/* Post message to server */
	function remove_msg(log_id, success_fn) {
		var jqxhr = jquery.post('backend.php', {'remove_msg':log_id});
		jqxhr.complete(function(response) {
			try {
				if(response && response.status && (200 === response.status) && (response.responseText.substr(0, 2) === 'OK') ) {
					success_fn();
				} else if(response && (response.status !== undefined)) {
					add_error({'title':'Connection failed with #' + response.status, 'desc':response.responseText});
				} else {
					add_error('Connection failed');
				}
			} catch(e) {
				add_error('Connection failed');
			}
		});
	}

	/* Post message to server */
	function post_msg(args) {
		//alert('In post_msg() with args=' + JSON.stringify(args) );
		var args = args || {};
		var msg = (args && (typeof args === 'object') && args.msg) ? ''+args.msg : '';
		if( (msg.length === 0) || (msg.length >= SERVER_CONFIG.MAX_MSG_LENGTH) ) {
			return;
		}
		var jqxhr = jquery.post('backend.php', {'send_msg':'1', 'msg':''+msg});
		jqxhr.complete(function(response) {
			try {
				if(response && response.status && (200 === response.status) && (response.responseText.substr(0, 2) === 'OK') ) {
					jquery("#control_form .msg_field").val('');
					update_events();
				} else if(response && (response.status !== undefined)) {
					add_error({'title':'Connection failed with #' + response.status, 'desc':response.responseText});
				} else {
					add_error('Connection failed');
				}
			} catch(e) {
				add_error('Connection failed');
			}
		});
	}

	/* Post message to server */
	function post_msg_form() {
		var msg = jquery('#control_form').find('.msg_field').val();
		//alert('Calling post_msg() with msg=' + msg);
		post_msg({'msg':msg});
		return false;
	}

	/* */
	function change_search_string(q) {

		if(INFODESK_GLOBAL.updating === true) { return; }

		//alert(hashtag);
		INFODESK_GLOBAL.search_string = ''+q;
		jquery('#events .events-header').empty();
		jquery('#events .events-body').empty();
		if(q !== '') {
			var header = jquery('
').append('Results for ').append(format_msg(''+q)).append(' ');
			var link = jquery('').html("Close ×").click(function(event){
				event.preventDefault();
				change_search_string('');
				return false;
			});
			link.appendTo(header);
			header.appendTo('#events .events-header');
		}
		jquery('#search_field').val('');
		INFODESK_GLOBAL.last_id = 0;
		update_events();
	}

	/* */
	function format_msg(msg) {
		msg = jquery('
').text(msg).html();

		// Format normal links
		msg = msg.replace(/(https?|ftp):\/\/([^\s]+)/g, function($0, $1, $2) {
			var link = ''+$1+'://'+$2;
			var div = jquery('
');
			var a = jquery('').attr('href', link).text($2);
			a.appendTo(div);
			return div.html();
		});

		// Format hashtags
		msg = msg.replace(/#([a-zA-Z0-9\._]+)/g, function($0, $1) {
			var h = (''+$1).toLowerCase();
			var div = jquery('
');
			var a = jquery('').text('#'+$1);
			a.appendTo(div);
			return div.html();
		});

		// Format @-links
		msg = msg.replace(/@([a-zA-Z0-9\._]+)/g, function($0, $1) {
			var h = (''+$1).toLowerCase();
			var div = jquery('
');
			var a = jquery('').text('@'+$1);
			a.appendTo(div);
			return div.html();
		});

		var elem = jquery('').html(msg);

		// Hashtag click events
		elem.find('.hashtag_link').click(function(e) {
			e.preventDefault();
			change_search_string( jquery(this).text() );
			return false;
		});

		return elem.contents();
	}

	/* */
	function update_events() {
		var next_id, hashtag;
		if(INFODESK_GLOBAL.updating === true) { return; }
		INFODESK_GLOBAL.updating = true;
		next_id = INFODESK_GLOBAL.last_id+1;
		var options = {'msgs':'1', 'start':''+next_id};
		if(INFODESK_GLOBAL.search_string && (INFODESK_GLOBAL.search_string !== '')) {
			options.q = INFODESK_GLOBAL.search_string;
		}
		var jqxhr = jquery.get('backend.php', options, function(data) {
			var response = JSON.parse(data),
			    events = response.events,
			    server_time = response.time,
			    our_user_id = response.user_id;

			//alert('got events: ' + events.length);
			for(i in events) if(events.hasOwnProperty(i)) {
				(function() {
					var event = events[i],
					    id = parseInt(event.log_id, 10),
					    seconds_since = server_time - event.updated,
					    updated = new Date();

						updated.setTime( event.updated*1000 );

					if(id > INFODESK_GLOBAL.last_id) {
						INFODESK_GLOBAL.last_id = id;
					}

					var div = jquery('#elements .event_container').clone();
					div.find('.log_id').text(''+event.log_id);
					div.find('.date').text( moment(updated).format("HH:mm:ss") );
					div.find('.msg').append( format_msg(event.msg) );

					var close = div.find('.close');
					if ( (our_user_id === event.user_id) && (seconds_since < 5*60) ) {
						//alert("seconds_since = " + seconds_since);
						close.show();
						setTimeout(function() {
							close.hide();
						}, (5*60 - seconds_since)*1000);
					} else {
						close.hide();
					}

					close.click(function(e) {
						e.preventDefault();
						remove_msg(event.log_id, function() {
							div.remove();
						});
						return false;
					});

					div.prependTo('#events .events-body');
				}());
			}
			INFODESK_GLOBAL.updating = false;
		});

		jqxhr.complete(function(data, status) {
			if(status === "success") return;
			if(data && data.responseText) {
				try {
					var obj = JSON.parse(data.responseText);
					if(obj && obj.error) {
						add_error(obj.error, jquery);
						return;
					}
					add_error(obj);
				} catch(e) {
					add_error(data);
				}
			} else {
				add_error(status + ' with ' + data);
			}
		});
	}

	/* */
	function update_clock() {
		function f(d) { return ((''+d).length===1) ? '0'+d : ''+d; }
		var now = new Date();
		jquery('#clock').val( f(now.getHours()) + ':' + f(now.getMinutes()) );
	}

	/* */
	INFODESK_GLOBAL.timer = undefined;
	INFODESK_GLOBAL.updating = false;
	INFODESK_GLOBAL.last_id = 0;
	function update_events_timer() {
		update_events();
		//update_clock();
		setTimeout(update_events_timer, 1000);
	}

	/* Init everything at onLoad event */
	window.onload = function() {

		// Setup SERVER_CONFIG
		jquery.getJSON('/api/config.json', function(data){
			SERVER_CONFIG = data;
		}).error(function() {
			add_error("Failed to load server config");
		});

		// TODO: Setup simple clock on control form

		// TODO: Setup previous event history
		// TODO: Start fetching new events
		//update_events();
		update_events_timer();

		// Setup ajax calls
		jquery.ajaxSetup({cache:false});

		// Setup search form
		jquery('.form-search').submit(function() {
			var q = jquery('#search_field').val();
			change_search_string(q);
			return false;
		});

		// Setup about modal's body
		jquery.get('README.md', function(data) {
			var converter = new Showdown.converter();
			jquery('#about .modal-body').html(converter.makeHtml(data));
		});

		// Focus on message field
		jquery('#control_form .msg_field').focus();

		// Update form message size
		var form = jquery('#control_form');
		var field = form.find('.msg_field');
		var field_help = form.find('.msg_field_help');
		var field_max = parseInt(field.attr("maxlength"), 10);
		field.removeAttr("maxlength");
		function field_update() {
			var len = field.val().length;
			if(len < field_max) {
				// Success
				field_help.show();
				if(!form.hasClass('success')) form.toggleClass('success');
				if(form.hasClass('error')) form.toggleClass('error');
				field_help.text('' + (field_max-len));
			} else {
				// Error
				field_help.show();
				if(form.hasClass('success')) form.toggleClass('success');
				if(!form.hasClass('error')) form.toggleClass('error');
				field_help.text('' + (field_max-len));
			}
		}
		field.keydown(field_update);
		field.keyup(field_update);
		field.change(field_update);

		// Setup send message button
		jquery("#controls .submit-btn").removeAttr('disabled').click(function(event){
			event.preventDefault();
			post_msg_form();
			return false;
		});

		// Setup new channel form
		jquery("#join_channel").submit(function(event) {
			var channel = jquery(this).find('.channel_field').val();
			if(channel.match(/^[a-zA-Z0-9\._]+$/)) {
				window.location = 'http://' + channel + '.' + SERVER_CONFIG.TOP_DOMAIN;
			} else {
				add_error("Channel name invalid: " + channel);
			}
			return false;
		});

	};

// End of require
}, function(err) {
	alert('Error: ' . err);
});
/* EOF */
<commit_msg>Updated<commit_after>/* Main code */

/* RequireJS configurations */
requirejs.config({
	shim: {
		'bootstrap':{
			deps: ['jquery']
		},
		'showdown':{
			deps: [],
			exports: 'Showdown'
		}
	}
});

require(["jquery", "moment", "bootstrap", "showdown"], function(jquery, moment, bootstrap, Showdown) {

	var SERVER_CONFIG = {};
	var INFODESK_GLOBAL = {};

	/* Pop error message */
	function add_error(args) {
		//alert('error: '+ JSON.stringify(args));
		var data, dialog;
		if(args && (typeof args === 'object')) {
			if(args.error) {
				args.title = args.error;
				delete args.error;
			}
			if(args.title || args.desc) {
				data = args;
			} else {
				data = {'desc': JSON.stringify(args)};
			}
		} else {
			data = {'title':''+args};
		}
		if(!data.date) data.date = new Date();
		dialog = jquery('#elements .error_dialog').clone();
		dialog.find('.date').text(data.date);
		dialog.find('.title').text(data.title);
		if(data.desc && ((data.desc+'').length > 0) ) {
			dialog.find('.desc').text(data.desc);
		} else {
			dialog.find('.desc_container').hide();
		}
		dialog.prependTo('#notifications');
		dialog.alert();
	};

	/* Post message to server */
	function remove_msg(log_id, success_fn) {
		var jqxhr = jquery.post('backend.php', {'remove_msg':log_id});
		jqxhr.complete(function(response) {
			try {
				if(response && response.status && (200 === response.status) && (response.responseText.substr(0, 2) === 'OK') ) {
					success_fn();
				} else if(response && (response.status !== undefined)) {
					add_error({'title':'Connection failed with #' + response.status, 'desc':response.responseText});
				} else {
					add_error('Connection failed');
				}
			} catch(e) {
				add_error('Connection failed');
			}
		});
	}

	/* Post message to server */
	function post_msg(args) {
		get_config(function(config) {
			//alert('In post_msg() with args=' + JSON.stringify(args) );
			var args = args || {};
			var msg = (args && (typeof args === 'object') && args.msg) ? ''+args.msg : '';
			if( (msg.length === 0) || (msg.length >= config.MAX_MSG_LENGTH) ) {
				return;
			}
			var jqxhr = jquery.post('backend.php', {'send_msg':'1', 'msg':''+msg});
			jqxhr.complete(function(response) {
				try {
					if(response && response.status && (200 === response.status) && (response.responseText.substr(0, 2) === 'OK') ) {
						jquery("#control_form .msg_field").val('');
						update_events();
					} else if(response && (response.status !== undefined)) {
						add_error({'title':'Connection failed with #' + response.status, 'desc':response.responseText});
					} else {
						add_error('Connection failed');
					}
				} catch(e) {
					add_error('Connection failed');
				}
			});
		});
	}

	/* Post message to server */
	function post_msg_form() {
		var msg = jquery('#control_form').find('.msg_field').val();
		//alert('Calling post_msg() with msg=' + msg);
		post_msg({'msg':msg});
		return false;
	}

	/* */
	function change_search_string(q) {

		if(INFODESK_GLOBAL.updating === true) { return; }

		//alert(hashtag);
		INFODESK_GLOBAL.search_string = ''+q;
		jquery('#events .events-header').empty();
		jquery('#events .events-body').empty();
		if(q !== '') {
			var header = jquery('
').append('Results for ').append(format_msg(''+q)).append(' ');
			var link = jquery('').html("Close ×").click(function(event){
				event.preventDefault();
				change_search_string('');
				return false;
			});
			link.appendTo(header);
			header.appendTo('#events .events-header');
		}
		jquery('#search_field').val('');
		INFODESK_GLOBAL.last_id = 0;
		update_events();
	}

	/* */
	function format_msg(msg) {
		msg = jquery('
').text(msg).html();

		// Format normal links
		msg = msg.replace(/(https?|ftp):\/\/([^\s]+)/g, function($0, $1, $2) {
			var link = ''+$1+'://'+$2;
			var div = jquery('
');
			var a = jquery('').attr('href', link).text($2);
			a.appendTo(div);
			return div.html();
		});

		// Format hashtags
		msg = msg.replace(/#([a-zA-Z0-9\._]+)/g, function($0, $1) {
			var h = (''+$1).toLowerCase();
			var div = jquery('
');
			var a = jquery('').text('#'+$1);
			a.appendTo(div);
			return div.html();
		});

		// Format @-links
		get_config(function(config) {
			msg = msg.replace(/@([a-zA-Z0-9\._]+)/g, function($0, $1) {
				var h = (''+$1).toLowerCase();
				var div = jquery('
');
				var a = jquery('').text('@'+$1);
				a.appendTo(div);
				return div.html();
			});
		});

		var elem = jquery('').html(msg);

		// Hashtag click events
		elem.find('.hashtag_link').click(function(e) {
			e.preventDefault();
			change_search_string( jquery(this).text() );
			return false;
		});

		return elem.contents();
	}

	/* */
	function update_events() {
		var next_id, hashtag;
		if(INFODESK_GLOBAL.updating === true) { return; }
		INFODESK_GLOBAL.updating = true;
		next_id = INFODESK_GLOBAL.last_id+1;
		var options = {'msgs':'1', 'start':''+next_id};
		if(INFODESK_GLOBAL.search_string && (INFODESK_GLOBAL.search_string !== '')) {
			options.q = INFODESK_GLOBAL.search_string;
		}
		var jqxhr = jquery.get('backend.php', options, function(data) {
			var response = JSON.parse(data),
			    events = response.events,
			    server_time = response.time,
			    our_user_id = response.user_id;

			//alert('got events: ' + events.length);
			for(i in events) if(events.hasOwnProperty(i)) {
				(function() {
					var event = events[i],
					    id = parseInt(event.log_id, 10),
					    seconds_since = server_time - event.updated,
					    updated = new Date();

						updated.setTime( event.updated*1000 );

					if(id > INFODESK_GLOBAL.last_id) {
						INFODESK_GLOBAL.last_id = id;
					}

					var div = jquery('#elements .event_container').clone();
					div.find('.log_id').text(''+event.log_id);
					div.find('.date').text( moment(updated).format("HH:mm:ss") );
					div.find('.msg').append( format_msg(event.msg) );

					var close = div.find('.close');
					if ( (our_user_id === event.user_id) && (seconds_since < 5*60) ) {
						//alert("seconds_since = " + seconds_since);
						close.show();
						setTimeout(function() {
							close.hide();
						}, (5*60 - seconds_since)*1000);
					} else {
						close.hide();
					}

					close.click(function(e) {
						e.preventDefault();
						remove_msg(event.log_id, function() {
							div.remove();
						});
						return false;
					});

					div.prependTo('#events .events-body');
				}());
			}
			INFODESK_GLOBAL.updating = false;
		});

		jqxhr.complete(function(data, status) {
			if(status === "success") return;
			if(data && data.responseText) {
				try {
					var obj = JSON.parse(data.responseText);
					if(obj && obj.error) {
						add_error(obj.error, jquery);
						return;
					}
					add_error(obj);
				} catch(e) {
					add_error(data);
				}
			} else {
				add_error(status + ' with ' + data);
			}
		});
	}

	/* */
	function update_clock() {
		function f(d) { return ((''+d).length===1) ? '0'+d : ''+d; }
		var now = new Date();
		jquery('#clock').val( f(now.getHours()) + ':' + f(now.getMinutes()) );
	}

	/* */
	INFODESK_GLOBAL.timer = undefined;
	INFODESK_GLOBAL.updating = false;
	INFODESK_GLOBAL.last_id = 0;
	function update_events_timer() {
		update_events();
		//update_clock();
		setTimeout(update_events_timer, 1000);
	}

	function get_config(fn) {

		if(SERVER_CONFIG.time) {
			return fn(SERVER_CONFIG);
		}

		// Setup SERVER_CONFIG
		jquery.getJSON('/api/config.json', function(data){
			SERVER_CONFIG = data;
			return fn(SERVER_CONFIG);
		}).error(function() {
			add_error("Failed to load server config");
		});
	}

	/* Init everything at onLoad event */
	window.onload = function() {

		// TODO: Setup simple clock on control form

		// TODO: Setup previous event history
		// TODO: Start fetching new events
		//update_events();
		update_events_timer();

		// Setup ajax calls
		jquery.ajaxSetup({cache:false});

		// Setup search form
		jquery('.form-search').submit(function() {
			var q = jquery('#search_field').val();
			change_search_string(q);
			return false;
		});

		// Setup about modal's body
		jquery.get('README.md', function(data) {
			var converter = new Showdown.converter();
			jquery('#about .modal-body').html(converter.makeHtml(data));
		});

		// Focus on message field
		jquery('#control_form .msg_field').focus();

		// Update form message size
		var form = jquery('#control_form');
		var field = form.find('.msg_field');
		var field_help = form.find('.msg_field_help');
		var field_max = parseInt(field.attr("maxlength"), 10);
		field.removeAttr("maxlength");
		function field_update() {
			var len = field.val().length;
			if(len < field_max) {
				// Success
				field_help.show();
				if(!form.hasClass('success')) form.toggleClass('success');
				if(form.hasClass('error')) form.toggleClass('error');
				field_help.text('' + (field_max-len));
			} else {
				// Error
				field_help.show();
				if(form.hasClass('success')) form.toggleClass('success');
				if(!form.hasClass('error')) form.toggleClass('error');
				field_help.text('' + (field_max-len));
			}
		}
		field.keydown(field_update);
		field.keyup(field_update);
		field.change(field_update);

		// Setup send message button
		jquery("#controls .submit-btn").removeAttr('disabled').click(function(event){
			event.preventDefault();
			post_msg_form();
			return false;
		});

		// Setup new channel form
		jquery("#join_channel").submit(function(event) {
			var channel = jquery(this).find('.channel_field').val();
			if(channel.match(/^[a-zA-Z0-9\._]+$/)) {
				get_config(function(config) {
					window.location = 'http://' + channel + '.' + config.TOP_DOMAIN;
				});
			} else {
				add_error("Channel name invalid: " + channel);
			}
			return false;
		});

	};

// End of require
}, function(err) {
	alert('Error: ' . err);
});
/* EOF */
<|endoftext|>


<commit_before>var app = (function(me) {
  me.engine = (function(me) {
    var currentTick = 0;
    var registeredTickers = [];
    var tickIntervalId = setInterval(ticked, 25);

    me.onTick = onTick;
    me.offTick = offTick;

    function onTick(fn, tickMod) {
      registeredTickers.push({fn: fn, tickMod: tickMod});
    }

    function offTick(fn) {
      for(var i = 0, len = registeredTickers.length; i < len; i++) {
        var curTicker = registeredTickers[i];
        if (curTicker.fn === fn) {
          registeredTickers.splice(i, 1);
          return;
        }
      }
    }

    function ticked() {
      currentTick++;
      registeredTickers.forEach(runRegisteredTicker);
    }

    function runRegisteredTicker(ticker) {
      var tickMod = ticker.tickMod;
      if (tickMod == null || (tickMod != null && currentTick % tickMod === 0)) {
        ticker.fn(currentTick);
      }
    }

    return me;
  })(me.engine || {});

  return me;
})(window.app || {});
<commit_msg>Updated tick interval<commit_after>var app = (function(me) {
  me.engine = (function(me) {
    var currentTick = 0;
    var registeredTickers = [];
    var tickIntervalId = setInterval(ticked, 15);

    me.onTick = onTick;
    me.offTick = offTick;

    function onTick(fn, tickMod) {
      registeredTickers.push({fn: fn, tickMod: tickMod});
    }

    function offTick(fn) {
      for(var i = 0, len = registeredTickers.length; i < len; i++) {
        var curTicker = registeredTickers[i];
        if (curTicker.fn === fn) {
          registeredTickers.splice(i, 1);
          return;
        }
      }
    }

    function ticked() {
      currentTick++;
      registeredTickers.forEach(runRegisteredTicker);
    }

    function runRegisteredTicker(ticker) {
      var tickMod = ticker.tickMod;
      if (tickMod == null || (tickMod != null && currentTick % tickMod === 0)) {
        ticker.fn(currentTick);
      }
    }

    return me;
  })(me.engine || {});

  return me;
})(window.app || {});
<|endoftext|>


<commit_before>'use strict';
const EmberAddon = require('ember-cli/lib/broccoli/ember-addon');

const UnwatchedDir = require('broccoli-source').UnwatchedDir;
const MergeTrees = require('broccoli-merge-trees');
const Funnel = require('broccoli-funnel');

function treeForPackage(packageName) {
  let addonFiles = new Funnel(`../${packageName}/addon`, {
    destDir: `@ember-decorators/${packageName}`
  });

  return addonFiles;
}

module.exports = function(defaults) {
  // Build addon docs tree
  let baseFiles = new Funnel(new UnwatchedDir('./'), {
    include: ['package.json', 'README.md']
  });

  let tree = new MergeTrees([
    baseFiles,
    treeForPackage('component'),
    treeForPackage('controller'),
    treeForPackage('data'),
    treeForPackage('object'),
    treeForPackage('service'),
  ]);

  let trees;

  if (process.env.GENERATE_TYPESCRIPT_TESTS) {
    trees = {
      tests: new Funnel('tests', {
        getDestinationPath(path) {
          return path.replace('.js', '.ts');
        },
      }),
    };
  } else {
    trees = {
      tests: 'tests'
    };
  }

  var app = new EmberAddon(defaults, {
    trees,

    'ember-cli-addon-docs': {
      projects: {
        main: tree
      }
    }
  });

  /*
    This build file specifies the options for the dummy test app of this
    addon, located in `/tests/dummy`
    This build file does *not* influence how the addon or the app using it
    behave. You most likely want to be modifying `./index.js` or app's build file
  */

  return app.toTree();
};
<commit_msg>fix production build<commit_after>'use strict';
const EmberAddon = require('ember-cli/lib/broccoli/ember-addon');

const UnwatchedDir = require('broccoli-source').UnwatchedDir;
const MergeTrees = require('broccoli-merge-trees');
const Funnel = require('broccoli-funnel');

function treeForPackage(packageName) {
  let addonFiles = new Funnel(`../${packageName}/addon`, {
    destDir: `@ember-decorators/${packageName}`
  });

  return addonFiles;
}

module.exports = function(defaults) {
  // Build addon docs tree
  let baseFiles = new Funnel(new UnwatchedDir('./'), {
    include: ['package.json', 'README.md']
  });

  let tree = new MergeTrees([
    baseFiles,
    treeForPackage('component'),
    treeForPackage('controller'),
    treeForPackage('data'),
    treeForPackage('object'),
    treeForPackage('service'),
  ]);

  let trees;

  if (process.env.GENERATE_TYPESCRIPT_TESTS) {
    trees = {
      tests: new Funnel('tests', {
        getDestinationPath(path) {
          return path.replace('.js', '.ts');
        },
      }),
    };
  } else {
    trees = {
      tests: 'tests'
    };
  }

  var app = new EmberAddon(defaults, {
    trees,

    'ember-cli-uglify': {
			uglify: {
				compress: {
					collapse_vars: false
				}
			}
		},

    'ember-cli-addon-docs': {
      projects: {
        main: tree
      }
    }
  });

  /*
    This build file specifies the options for the dummy test app of this
    addon, located in `/tests/dummy`
    This build file does *not* influence how the addon or the app using it
    behave. You most likely want to be modifying `./index.js` or app's build file
  */

  return app.toTree();
};
<|endoftext|>


<commit_before>////////////////////////////////////////////////////////////////////////////////
// Media Entry
////////////////////////////////////////////////////////////////////////////////
/*global jQuery */
var yalp = yalp || {};

yalp.controls = function (controls, $, services, data) {
	var

	// static event handlers
	onClick,
	onChecked;

	controls.media = function (row) {
		var self = Object.create(controls.control()),

		// sub-controls
		rater,
		tagger;

		self.data.row = row;

		//////////////////////////////
		// Business functions

		// calls playback service
		self.play = function (elem) {
			elem
				.siblings().removeClass('playing').end()
				.addClass('playing');
			services.play(row.path);
			data.pagestate.lastPlayed = row.mediaid;
			return self;
		};

		// tells whether this media entry is selected
		self.selected = function () {
			return $('#' + self.id).find(':checked').length > 0;
		};

		//////////////////////////////
		// Overrides

		self.init = function (elem) {
			elem.find('a.play')
				.click(onClick);
		};

		function build() {
			self.clear();
			rater = controls.rater(row).appendTo(self);
			tagger = controls.tagger(row).appendTo(self);
		}

		self.html = function () {
			self.data.that = this;

			build();

			return [
				'
',
				'',
				'<input type="checkbox" ', row.mediaid in controls.library.selected ? 'checked="checked" ' : '', '/>',
				'	',
				'',
				'', row.file, '',
				'	',
				'',
				rater.html(),
				'	',
				'',
				tagger.html(),
				'	',
				'
'
			].join('');
		};

		return self;
	};

	//////////////////////////////
	// Static event handlers

	onClick = function () {
		var media = $(this).closest('.media'),
				self = controls.lookup[media.attr('id')].data.that;
		self.play(media);
		return false;
	};

	onChecked = function () {
		var $this = $(this),
				media = $this.closest('.media'),
				self = controls.lookup[media.attr('id')].data.that;
		if ($this.is(':checked')) {
			controls.library.selected[self.data.row.mediaid] = true;
		} else {
			delete controls.library.selected[self.data.row.mediaid];
		}
	};

	$('a.play').live('click', onClick);
	$('td.check :checkbox').live('click', onChecked);

	return controls;
}(yalp.controls || {},
	jQuery,
	yalp.services,
	yalp.data);

<commit_msg>showing keywords on mouseover<commit_after>////////////////////////////////////////////////////////////////////////////////
// Media Entry
////////////////////////////////////////////////////////////////////////////////
/*global jQuery */
var yalp = yalp || {};

yalp.controls = function (controls, $, services, data) {
	var

	// static event handlers
	onClick,
	onChecked;

	controls.media = function (row) {
		var self = Object.create(controls.control()),

		// sub-controls
		rater,
		tagger;

		self.data.row = row;

		//////////////////////////////
		// Business functions

		// calls playback service
		self.play = function (elem) {
			elem
				.siblings().removeClass('playing').end()
				.addClass('playing');
			services.play(row.path);
			data.pagestate.lastPlayed = row.mediaid;
			return self;
		};

		// tells whether this media entry is selected
		self.selected = function () {
			return $('#' + self.id).find(':checked').length > 0;
		};

		//////////////////////////////
		// Overrides

		self.init = function (elem) {
			elem.find('a.play')
				.click(onClick);
		};

		function build() {
			self.clear();
			rater = controls.rater(row).appendTo(self);
			tagger = controls.tagger(row).appendTo(self);
		}

		self.html = function () {
			self.data.that = this;

			build();

			return [
				'
',
				'',
				'<input type="checkbox" ', row.mediaid in controls.library.selected ? 'checked="checked" ' : '', '/>',
				'	',
				'',
				'', row.file, '',
				'	',
				'',
				rater.html(),
				'	',
				'',
				tagger.html(),
				'	',
				'
'
			].join('');
		};

		return self;
	};

	//////////////////////////////
	// Static event handlers

	onClick = function () {
		var media = $(this).closest('.media'),
				self = controls.lookup[media.attr('id')].data.that;
		self.play(media);
		return false;
	};

	onChecked = function () {
		var $this = $(this),
				media = $this.closest('.media'),
				self = controls.lookup[media.attr('id')].data.that;
		if ($this.is(':checked')) {
			controls.library.selected[self.data.row.mediaid] = true;
		} else {
			delete controls.library.selected[self.data.row.mediaid];
		}
	};

	$('a.play').live('click', onClick);
	$('td.check :checkbox').live('click', onChecked);

	return controls;
}(yalp.controls || {},
	jQuery,
	yalp.services,
	yalp.data);

<|endoftext|>


<commit_before>/*jshint esversion: 6 */
const gulp = require('gulp');
const del = require('del');
const typescript = require('gulp-typescript');
const tscConfig = require('./tsconfig.json');
const sass = require('gulp-sass');

// clean the contents of the distribution directory
gulp.task('clean', function () {
  return del('dist/**/*');
});

// TypeScript compile
gulp.task('compile:ts', ['clean'], function () {
  return gulp
    .src('app/**/*.ts')
    .pipe(typescript(tscConfig.compilerOptions))
    .pipe(gulp.dest('dist/app'));
});

// Styles compile
gulp.task('compile:scss', ['clean'], function () {
    return gulp
        .src('app/**/*.scss')
        .pipe(sass({outputStyle: 'compressed'}).on('error', sass.logError))
        .pipe(gulp.dest('app'));
});

gulp.task('copy:libs', ['clean'], function () {
  return gulp.src([
      'node_modules/es6-shim/es6-shim.min.js',
      'node_modules/zone.js/dist/zone.js',
      'node_modules/reflect-metadata/Reflect.js',
      'node_modules/systemjs/dist/system.src.js',
      'node_modules/rxjs/bundles/Rx.js'
    ])
    .pipe(gulp.dest('dist/lib'));
});

gulp.task('copy:assets', ['clean'], function () {
  return gulp
    .src('app/**/*.html')
    .pipe(gulp.dest('dist/app'));
});

gulp.task('copy:css', ['clean'], function () {
  return gulp.src('app/styles/*.css')
    .pipe(gulp.dest('dist/app/styles'));
});

gulp.task('build', ['compile:ts','compile:scss', 'copy:libs', 'copy:assets', 'copy:css']);
gulp.task('default', ['build']);<commit_msg>long line fix<commit_after>/*jshint esversion: 6 */
const gulp = require('gulp');
const del = require('del');
const typescript = require('gulp-typescript');
const tscConfig = require('./tsconfig.json');
const sass = require('gulp-sass');

// clean the contents of the distribution directory
gulp.task('clean', function () {
  return del('dist/**/*');
});

// TypeScript compile
gulp.task('compile:ts', ['clean'], function () {
  return gulp
    .src('app/**/*.ts')
    .pipe(typescript(tscConfig.compilerOptions))
    .pipe(gulp.dest('dist/app'));
});

// Styles compile
gulp.task('compile:scss', ['clean'], function () {
    return gulp
        .src('app/**/*.scss')
        .pipe(sass({outputStyle: 'compressed'}).on('error', sass.logError))
        .pipe(gulp.dest('app'));
});

gulp.task('copy:libs', ['clean'], function () {
  return gulp.src([
      'node_modules/es6-shim/es6-shim.min.js',
      'node_modules/zone.js/dist/zone.js',
      'node_modules/reflect-metadata/Reflect.js',
      'node_modules/systemjs/dist/system.src.js',
      'node_modules/rxjs/bundles/Rx.js'
    ])
    .pipe(gulp.dest('dist/lib'));
});

gulp.task('copy:assets', ['clean'], function () {
  return gulp
    .src('app/**/*.html')
    .pipe(gulp.dest('dist/app'));
});

gulp.task('copy:css', ['clean'], function () {
  return gulp.src('app/styles/*.css')
    .pipe(gulp.dest('dist/app/styles'));
});

gulp.task('build', [
    'compile:ts',
    'compile:scss',
    'copy:libs',
    'copy:assets',
    'copy:css'
]);

gulp.task('default', ['build']);<|endoftext|>


<commit_before>/* NHN (developers@xpressengine.com) */
jQuery(function($){

$('form.siteMap')
	.delegate('li:not(.placeholder)', 'dropped.st', function() {
		var $this = $(this), $pkey, $mkey, is_child;

		$pkey = $this.find('>input._parent_key');
		is_child = !!$this.parent('ul').parent('li').length;

		if(is_child) {
			$pkey.val($this.parent('ul').parent('li').find('>input._item_key').val());
		} else {
			$pkey.val('0');
		}
	})

	var editForm = $('#editForm');
	var menuSrl = null;
	var menuForm = null;
	var menuUrl = null;

	$('a._edit').click(function(){
		var itemKey = $(this).parent().prevAll('._item_key').val();
		menuSrl = $(this).parents().prevAll('input[name=menu_srl]').val();
		menuForm = $('#menu_'+menuSrl);
		var menuItemSrl = null;

		menuItemSrl = itemKey;

		var params = new Array();
		var response_tags = new Array('menu_item');
		params['menu_item_srl'] = menuItemSrl;

		exec_xml("menu","getMenuAdminItemInfo", params, completeGetActList, response_tags);
	});

	function completeGetActList(obj)
	{
		var menuItem = obj.menu_item;
		menuUrl = menuItem.url;
		editForm.find('.h2').html('Edit Menu');
		editForm.find('input[name=menu_srl]').val(menuItem.menu_srl);
		editForm.find('input[name=menu_item_srl]').val(menuItem.menu_item_srl);
		editForm.find('input[name=parent_srl]').val(menuItem.parent_srl);
		editForm.find('input[name=menu_name]').val(menuItem.name);

		var moduleType = menuItem.moduleType;
		var inputCType = editForm.find('input[name=cType]');

		if(moduleType == 'url')
		{
			inputCType[2].checked = true;
			editForm.find('input[name=menu_url]').val(menuItem.url);
		}
		else
		{
			inputCType[1].checked = true;
			editForm.find('input[name=select_menu_url]').val(menuItem.url);
		}
		typeCheck();
		getModuleList();

		var openWindow = menuItem.open_window;
		var openWindowForm = editForm.find('input=[name=menu_open_window]');
		if(openWindow == 'Y') openWindowForm[1].checked = true;
		else openWindowForm[0].checked = true;

		// button image
		if(menuItem.normal_btn) $('#normal_btn_preview').html('<input type="checkbox" name="isNormalDelete" value="Y"> Delete');
		if(menuItem.hover_btn) $('#hover_btn_preview').html('<input type="checkbox" name="isHoverDelete" value="Y"> Delete');
		if(menuItem.active_btn) $('#active_btn_preview').html('<input type="checkbox" name="isActiveDelete" value="Y"> Delete');

		var htmlBuffer = '';
		for(x in menuItem.groupList.item)
		{
			var groupObj = menuItem.groupList.item[x];

			htmlBuffer += '<input type="checkbox" name="group_srls[]" id="group_srls_'+groupObj.group_srl+'" value="'+groupObj.group_srl+'"';
			if(groupObj.isChecked) htmlBuffer += ' checked="checked" ';
			htmlBuffer += '/> '+groupObj.title+''
		}
		$('#groupList').html(htmlBuffer);
	}

	$('a._delete').click(function() {
		menuSrl = $(this).parents().prevAll('input[name=menu_srl]').val();
		menuForm = $('#menu_'+menuSrl);

		var menu_item_srl = $(this).parent().prevAll('._item_key').val();
		menuForm.find('input[name=menu_item_srl]').val(menu_item_srl);
		menuForm.submit();
	});

	var kindModuleLayer = $('#kindModule');
	var createModuleLayer = $('#createModule');
	var selectModuleLayer = $('#selectModule');
	var insertUrlLayer = $('#insertUrl');
	kindModuleLayer.hide();
	createModuleLayer.hide();
	selectModuleLayer.hide();
	insertUrlLayer.hide();

	$('a._add').click(function()
	{
		editForm.find('.h2').html('Add Menu');
		editForm.find('input[name=menu_srl]').val($(this).parents().prevAll('input[name=menu_srl]').val());
		editForm.find('input[name=parent_srl]').val(0);
		editForm.find('input[name=menu_name]').val('');
		editForm.find('input[name=cType]').attr('checked', false);
		editForm.find('input=[name=create_menu_url]').val('');
		editForm.find('input=[name=select_menu_url]').val('');
		editForm.find('input=[name=menu_url]').val('');
		editForm.find('input=[name=menu_open_window]')[0].checked = true;
		editForm.find('input=[name=group_srls\\[\\]]').attr('checked', false);
	});

	$('input._typeCheck').click(typeCheck);

	function typeCheck()
	{
		var inputTypeCheck = $('input._typeCheck');
		var checkedValue = null;
		for(var i=0; i<3; i++)
		{
			if(inputTypeCheck[i].checked)
			{
				checkedValue = inputTypeCheck[i].value;
				break;
			}
		}

		if(checkedValue == 'CREATE')
		{
			kindModuleLayer.show();
			createModuleLayer.show()
			selectModuleLayer.hide()
			insertUrlLayer.hide()
		}
		else if(checkedValue == 'SELECT')
		{
			kindModuleLayer.show();
			createModuleLayer.hide()
			selectModuleLayer.show()
			insertUrlLayer.hide()
		}
		// type is URL
		else
		{
			kindModuleLayer.hide();
			createModuleLayer.hide()
			selectModuleLayer.hide()
			insertUrlLayer.show()
		}
	}

	$('#kModule').change(getModuleList).change();
	function getModuleList()
	{
		var params = new Array();
		var response_tags = ['error', 'message', 'module_list'];

		exec_xml('module','procModuleAdminGetList',params, completeGetModuleList, response_tags);
	}

	function completeGetModuleList(ret_obj)
	{
		var midList = ret_obj.module_list[$('#kModule').val()].list;

		var htmlBuffer = "";
		for(x in midList)
		{
			var midObject = midList[x];
			htmlBuffer += '<option value="'+midObject.mid+'"';
			if(menuUrl == midObject.mid) htmlBuffer += ' selected ';
			htmlBuffer += '>'+midObject.browser_title+'</option>';
		}
		selectModuleLayer.find('select').html(htmlBuffer);
	}

	$('a.tgMap').click(function() {
		var $this = $(this);

		$($this.attr('href')).slideToggle('fast');
		$this.closest('.siteMap').toggleClass('fold');

		return false;
	});
});
<commit_msg>issue 160 when new menu add after menu edit in sitemap. not create new menu, and old menu overwrite. this bug fix<commit_after>/* NHN (developers@xpressengine.com) */
jQuery(function($){

$('form.siteMap')
	.delegate('li:not(.placeholder)', 'dropped.st', function() {
		var $this = $(this), $pkey, $mkey, is_child;

		$pkey = $this.find('>input._parent_key');
		is_child = !!$this.parent('ul').parent('li').length;

		if(is_child) {
			$pkey.val($this.parent('ul').parent('li').find('>input._item_key').val());
		} else {
			$pkey.val('0');
		}
	})

	var editForm = $('#editForm');
	var menuSrl = null;
	var menuForm = null;
	var menuUrl = null;

	$('a._edit').click(function(){
		var itemKey = $(this).parent().prevAll('._item_key').val();
		menuSrl = $(this).parents().prevAll('input[name=menu_srl]').val();
		menuForm = $('#menu_'+menuSrl);
		var menuItemSrl = null;

		menuItemSrl = itemKey;

		var params = new Array();
		var response_tags = new Array('menu_item');
		params['menu_item_srl'] = menuItemSrl;

		exec_xml("menu","getMenuAdminItemInfo", params, completeGetActList, response_tags);
	});

	function completeGetActList(obj)
	{
		var menuItem = obj.menu_item;
		menuUrl = menuItem.url;
		editForm.find('.h2').html('Edit Menu');
		editForm.find('input[name=menu_srl]').val(menuItem.menu_srl);
		editForm.find('input[name=menu_item_srl]').val(menuItem.menu_item_srl);
		editForm.find('input[name=parent_srl]').val(menuItem.parent_srl);
		editForm.find('input[name=menu_name]').val(menuItem.name);

		var moduleType = menuItem.moduleType;
		var inputCType = editForm.find('input[name=cType]');

		if(moduleType == 'url')
		{
			inputCType[2].checked = true;
			editForm.find('input[name=menu_url]').val(menuItem.url);
		}
		else
		{
			inputCType[1].checked = true;
			editForm.find('input[name=select_menu_url]').val(menuItem.url);
		}
		typeCheck();
		getModuleList();

		var openWindow = menuItem.open_window;
		var openWindowForm = editForm.find('input=[name=menu_open_window]');
		if(openWindow == 'Y') openWindowForm[1].checked = true;
		else openWindowForm[0].checked = true;

		// button image
		if(menuItem.normal_btn) $('#normal_btn_preview').html('<input type="checkbox" name="isNormalDelete" value="Y"> Delete');
		if(menuItem.hover_btn) $('#hover_btn_preview').html('<input type="checkbox" name="isHoverDelete" value="Y"> Delete');
		if(menuItem.active_btn) $('#active_btn_preview').html('<input type="checkbox" name="isActiveDelete" value="Y"> Delete');

		var htmlBuffer = '';
		for(x in menuItem.groupList.item)
		{
			var groupObj = menuItem.groupList.item[x];

			htmlBuffer += '<input type="checkbox" name="group_srls[]" id="group_srls_'+groupObj.group_srl+'" value="'+groupObj.group_srl+'"';
			if(groupObj.isChecked) htmlBuffer += ' checked="checked" ';
			htmlBuffer += '/> '+groupObj.title+''
		}
		$('#groupList').html(htmlBuffer);
	}

	$('a._delete').click(function() {
		menuSrl = $(this).parents().prevAll('input[name=menu_srl]').val();
		menuForm = $('#menu_'+menuSrl);

		var menu_item_srl = $(this).parent().prevAll('._item_key').val();
		menuForm.find('input[name=menu_item_srl]').val(menu_item_srl);
		menuForm.submit();
	});

	var kindModuleLayer = $('#kindModule');
	var createModuleLayer = $('#createModule');
	var selectModuleLayer = $('#selectModule');
	var insertUrlLayer = $('#insertUrl');
	kindModuleLayer.hide();
	createModuleLayer.hide();
	selectModuleLayer.hide();
	insertUrlLayer.hide();

	$('a._add').click(function()
	{
		editForm.find('.h2').html('Add Menu');
		editForm.find('input[name=menu_srl]').val($(this).parents().prevAll('input[name=menu_srl]').val());
		editForm.find('input[name=menu_item_srl]').val('');
		editForm.find('input[name=parent_srl]').val(0);
		editForm.find('input[name=menu_name]').val('');
		editForm.find('input[name=cType]').attr('checked', false);
		editForm.find('input=[name=create_menu_url]').val('');
		editForm.find('input=[name=select_menu_url]').val('');
		editForm.find('input=[name=menu_url]').val('');
		editForm.find('input=[name=menu_open_window]')[0].checked = true;
		editForm.find('input=[name=group_srls\\[\\]]').attr('checked', false);
	});

	$('input._typeCheck').click(typeCheck);

	function typeCheck()
	{
		var inputTypeCheck = $('input._typeCheck');
		var checkedValue = null;
		for(var i=0; i<3; i++)
		{
			if(inputTypeCheck[i].checked)
			{
				checkedValue = inputTypeCheck[i].value;
				break;
			}
		}

		if(checkedValue == 'CREATE')
		{
			kindModuleLayer.show();
			createModuleLayer.show()
			selectModuleLayer.hide()
			insertUrlLayer.hide()
		}
		else if(checkedValue == 'SELECT')
		{
			kindModuleLayer.show();
			createModuleLayer.hide()
			selectModuleLayer.show()
			insertUrlLayer.hide()
		}
		// type is URL
		else
		{
			kindModuleLayer.hide();
			createModuleLayer.hide()
			selectModuleLayer.hide()
			insertUrlLayer.show()
		}
	}

	$('#kModule').change(getModuleList).change();
	function getModuleList()
	{
		var params = new Array();
		var response_tags = ['error', 'message', 'module_list'];

		exec_xml('module','procModuleAdminGetList',params, completeGetModuleList, response_tags);
	}

	function completeGetModuleList(ret_obj)
	{
		var midList = ret_obj.module_list[$('#kModule').val()].list;

		var htmlBuffer = "";
		for(x in midList)
		{
			var midObject = midList[x];
			htmlBuffer += '<option value="'+midObject.mid+'"';
			if(menuUrl == midObject.mid) htmlBuffer += ' selected ';
			htmlBuffer += '>'+midObject.browser_title+'</option>';
		}
		selectModuleLayer.find('select').html(htmlBuffer);
	}

	$('a.tgMap').click(function() {
		var $this = $(this);

		$($this.attr('href')).slideToggle('fast');
		$this.closest('.siteMap').toggleClass('fold');

		return false;
	});
});
<|endoftext|>


<commit_before>var e = module.exports = {};

e.init = () => {

    e.category = bu.CommandType.GENERAL;
};
e.requireCtx = require;

e.isCommand = true;
e.hidden = false;
e.usage = 'help [command]';
e.info = 'Gets a list of command or specific command help.';
e.longinfo = `
Returns a list of commands and custom commands. If a command name is specified, it will return a description
        of that command instead.
`;

e.execute = async function (msg, words) {
    if (words.length > 1) {
        var message = '';
        if (bu.commandList.hasOwnProperty(words[1]) && !bu.commandList[words[1]].hidden) {
            message = `Command Name: ${bu.commandList[words[1]].name}
Usage: \`${bu.commandList[words[1]].usage}\`
${bu.commandList[words[1]].info}`;
        } else {
            message = `No description could be found for command \`${words[1]}\`.`;
        }
        bu.send(msg, message);
    } else {
        var commandsString = '```prolog\nGeneral Commands:\n  ';
        var generalCommands = [];
        var otherCommands = {};
        var modifiedCommands = [];
        let storedGuild, permOverride, staffPerms;
        if (msg.channel.guild) {
            storedGuild = await r.table('guild').get(msg.channel.guild.id).run();
            permOverride = await bu.guildSettings.get(msg.channel.guild.id, 'permoverride');
            staffPerms = await bu.guildSettings.get(msg.channel.guild.id, 'staffPerms');
            let customizedCommands = storedGuild.commandperms;
            //    logger.debug(customizedCommands);
            for (let key in customizedCommands) {
                if (customizedCommands[key].rolename != null)
                    for (let i = 0; i < customizedCommands[key].rolename.length; i++) {
                        if (!otherCommands[customizedCommands[key].rolename[i].toLowerCase()]) {
                            otherCommands[customizedCommands[key].rolename[i].toLowerCase()] = [];
                        }
                        otherCommands[customizedCommands[key].rolename[i].toLowerCase()]
                            .push(key);
                        modifiedCommands.push(key);
                    }
            }
        }
        //    logger.debug(modifiedCommands);
        //   logger.debug(otherCommands);
        for (var command in bu.commandList) {
            if (modifiedCommands.indexOf(command) == -1)
                if (!bu.commandList[command].hidden) {
                    if (bu.commandList[command].category == bu.CommandType.GENERAL) {
                        if ((await bu.canExecuteCommand(msg, command, true, storedGuild, permOverride, staffPerms))[0])
                            generalCommands.push(command);
                    }
                    else {
                        if (!otherCommands[bu.commandList[command].category])
                            otherCommands[bu.commandList[command].category] = [];
                        otherCommands[bu.commandList[command].category].push(command);
                    }
                }
        }
        generalCommands.sort();
        commandsString += generalCommands.join(', ');

        var onComplete = async function () {
            if (msg.channel.guild) {
                let ccommands = storedGuild.ccommands;
                //      logger.debug(ccommands);
                if (ccommands && Object.keys(ccommands).length > 0) {
                    var ccommandsString = 'Custom Commands:\n  ';
                    var helpCommandList = [];
                    for (var key in ccommands) {
                        helpCommandList.push(key);
                    }
                    helpCommandList.sort();
                    ccommandsString += helpCommandList.join(', ');
                    commandsString += `\n${ccommandsString}`;
                }
            }

            commandsString += '```';
            let dmhelp = msg.channel.guild ? await bu.guildSettings.get(msg.channel.guild.id, 'dmhelp') : true;
            let doDM = dmhelp && dmhelp != 0;
            let sendString = `${doDM ? `Here are your commands ${msg.channel.guild ? 'for ' + msg.channel.guild.name : ''}.\n` : ''}${commandsString}\n${!msg.channel.guild
                ? 'Not all of these bu.commands work in DMs.\n'
                : ''
                }For more information about commands, do \`help <commandname>\` or visit https://blargbot.xyz/commands`;

            if (doDM) {
                bot.getDMChannel(msg.author.id).then(pc => {
                    bu.send(msg, '📧 DMing you a list of commands 📧');
                    bu.send(pc.id, sendString);
                });
            } else {
                bu.send(msg, sendString);
            }
        };

        function nextCommand(category, completeCommandList) {
            if (!bu.CommandType.properties.hasOwnProperty(category)
                || bu.CommandType.properties[category].requirement(msg)) {
                if (completeCommandList.length > 0) {
                    completeCommandList.sort();
                    commandsString += `\n${bu.CommandType.properties.hasOwnProperty(category)
                        ? bu.CommandType.properties[category].name
                        : category.charAt(0).toUpperCase() + category.slice(1)} Commands:\n  `;
                    commandsString += completeCommandList.join(', ');
                }
            }
            i++;
            completeCommandList.length = 0;
            processCategory(i);
        }
        let completeCommandList = []
            , category
            , counter
            , i = 0
            , ii;

        function doThing(val) {
            if (val[0]) {
                completeCommandList.push(val[1]);
            }
            if (--counter == 0) {
                nextCommand(category, completeCommandList);
            }
        }
        function processCategory() {
            if (i == Object.keys(otherCommands).length) {
                onComplete();
            } else {
                category = Object.keys(otherCommands)[i];
                //    if (!bu.CommandType.properties.hasOwnProperty(category) || bu.CommandType.properties[category].requirement(msg)) {
                //otherCommands[category].sort();
                counter = otherCommands[category].length;
                for (ii = 0; ii < otherCommands[category].length; ii++) {
                    bu.canExecuteCommand(msg, otherCommands[category][ii], true, storedGuild, permOverride, staffPerms).then(doThing);
                }
                //    }
            }
        }
        processCategory(i);
    }
};
<commit_msg>aliases no longer show<commit_after>var e = module.exports = {};

e.init = () => {

    e.category = bu.CommandType.GENERAL;
};
e.requireCtx = require;

e.isCommand = true;
e.hidden = false;
e.usage = 'help [command]';
e.info = 'Gets a list of command or specific command help.';
e.longinfo = `
Returns a list of commands and custom commands. If a command name is specified, it will return a description
        of that command instead.
`;

e.execute = async function(msg, words) {
        if (words.length > 1) {
            var message = '';
            if (bu.commandList.hasOwnProperty(words[1]) && !bu.commandList[words[1]].hidden) {
                message = `Command Name: ${bu.commandList[words[1]].name}
Usage: \`${bu.commandList[words[1]].usage}\`
Aliases: [ ${bu.commands[bu.commandList[words[1]].name].alias.join(', ')}]
${bu.commandList[words[1]].info}`;
            } else {
                message = `No description could be found for command \`${words[1]}\`.`;
            }
            bu.send(msg, message);
        } else {
            var commandsString = '```prolog\nGeneral Commands:\n  ';
            var generalCommands = [];
            var otherCommands = {};
            var modifiedCommands = [];
            let storedGuild, permOverride, staffPerms;
            if (msg.channel.guild) {
                storedGuild = await r.table('guild').get(msg.channel.guild.id).run();
                permOverride = await bu.guildSettings.get(msg.channel.guild.id, 'permoverride');
                staffPerms = await bu.guildSettings.get(msg.channel.guild.id, 'staffPerms');
                let customizedCommands = storedGuild.commandperms;
                //    logger.debug(customizedCommands);
                for (let key in customizedCommands) {
                    if (customizedCommands[key].rolename != null)
                        for (let i = 0; i < customizedCommands[key].rolename.length; i++) {
                            if (!otherCommands[customizedCommands[key].rolename[i].toLowerCase()]) {
                                otherCommands[customizedCommands[key].rolename[i].toLowerCase()] = [];
                            }
                            otherCommands[customizedCommands[key].rolename[i].toLowerCase()]
                                .push(key);
                            modifiedCommands.push(key);
                        }
                }
            }
            //    logger.debug(modifiedCommands);
            //   logger.debug(otherCommands);
            for (var command in bu.commands) {
                if (modifiedCommands.indexOf(command) == -1)
                    if (!bu.commands[command].hidden) {
                        if (bu.commands[command].category == bu.CommandType.GENERAL) {
                            if ((await bu.canExecuteCommand(msg, command, true, storedGuild, permOverride, staffPerms))[0])
                                generalCommands.push(command);
                        } else {
                            if (!otherCommands[bu.commands[command].category])
                                otherCommands[bu.commands[command].category] = [];
                            otherCommands[bu.commands[command].category].push(command);
                        }
                    }
            }
            generalCommands.sort();
            commandsString += generalCommands.join(', ');

            var onComplete = async function() {
                    if (msg.channel.guild) {
                        let ccommands = storedGuild.ccommands;
                        //      logger.debug(ccommands);
                        if (ccommands && Object.keys(ccommands).length > 0) {
                            var ccommandsString = 'Custom Commands:\n  ';
                            var helpCommandList = [];
                            for (var key in ccommands) {
                                helpCommandList.push(key);
                            }
                            helpCommandList.sort();
                            ccommandsString += helpCommandList.join(', ');
                            commandsString += `\n${ccommandsString}`;
                        }
                    }

                    commandsString += '```';
                    let dmhelp = msg.channel.guild ? await bu.guildSettings.get(msg.channel.guild.id, 'dmhelp') : true;
                    let doDM = dmhelp && dmhelp != 0;
                    let sendString = `${doDM ? `Here are your commands ${msg.channel.guild ? 'for ' + msg.channel.guild.name : ''}.\n` : ''}${commandsString}\n${!msg.channel.guild
                ? 'Not all of these bu.commands work in DMs.\n'
                : ''
                }For more information about commands, do \`help <commandname>\` or visit https://blargbot.xyz/commands`;

            if (doDM) {
                bot.getDMChannel(msg.author.id).then(pc => {
                    bu.send(msg, '📧 DMing you a list of commands 📧');
                    bu.send(pc.id, sendString);
                });
            } else {
                bu.send(msg, sendString);
            }
        };

        function nextCommand(category, completeCommandList) {
            if (!bu.CommandType.properties.hasOwnProperty(category)
                || bu.CommandType.properties[category].requirement(msg)) {
                if (completeCommandList.length > 0) {
                    completeCommandList.sort();
                    commandsString += `\n${bu.CommandType.properties.hasOwnProperty(category)
                        ? bu.CommandType.properties[category].name
                        : category.charAt(0).toUpperCase() + category.slice(1)} Commands:\n  `;
                    commandsString += completeCommandList.join(', ');
                }
            }
            i++;
            completeCommandList.length = 0;
            processCategory(i);
        }
        let completeCommandList = []
            , category
            , counter
            , i = 0
            , ii;

        function doThing(val) {
            if (val[0]) {
                completeCommandList.push(val[1]);
            }
            if (--counter == 0) {
                nextCommand(category, completeCommandList);
            }
        }
        function processCategory() {
            if (i == Object.keys(otherCommands).length) {
                onComplete();
            } else {
                category = Object.keys(otherCommands)[i];
                //    if (!bu.CommandType.properties.hasOwnProperty(category) || bu.CommandType.properties[category].requirement(msg)) {
                //otherCommands[category].sort();
                counter = otherCommands[category].length;
                for (ii = 0; ii < otherCommands[category].length; ii++) {
                    bu.canExecuteCommand(msg, otherCommands[category][ii], true, storedGuild, permOverride, staffPerms).then(doThing);
                }
                //    }
            }
        }
        processCategory(i);
    }
};<|endoftext|>