<commit_before>/**
 * Module dependencies.
 */

var express = require('../../..');
var fs = require('fs');

module.exports = function(parent, options){
  var verbose = options.verbose;
  fs.readdirSync(__dirname + '/../controllers').forEach(function(name){
    verbose && console.log('\n   %s:', name);
    var obj = require('./../controllers/' + name);
    var name = obj.name || name;
    var prefix = obj.prefix || '';
    var app = express();
    var handler;
    var method;
    var path;

    // allow specifying the view engine
    if (obj.engine) app.set('view engine', obj.engine);
    app.set('views', __dirname + '/../controllers/' + name + '/views');

    // generate routes based
    // on the exported methods
    for (var key in obj) {
      // "reserved" exports
      if (~['name', 'prefix', 'engine', 'before'].indexOf(key)) continue;
      // route exports
      switch (key) {
        case 'show':
          method = 'get';
          path = '/' + name + '/:' + name + '_id';
          break;
        case 'list':
          method = 'get';
          path = '/' + name + 's';
          break;
        case 'edit':
          method = 'get';
          path = '/' + name + '/:' + name + '_id/edit';
          break;
        case 'update':
          method = 'put';
          path = '/' + name + '/:' + name + '_id';
          break;
        case 'create':
          method = 'post';
          path = '/' + name;
          break;
        case 'index':
          method = 'get';
          path = '/';
          break;
        default:
          /* istanbul ignore next */
          throw new Error('unrecognized route: ' + name + '.' + key);
      }

      // setup
      handler = obj[key];
      path = prefix + path;

      // before middleware support
      if (obj.before) {
        app[method](path, obj.before, handler);
        verbose && console.log('     %s %s -> before -> %s', method.toUpperCase(), path, key);
      } else {
        app[method](path, handler);
        verbose && console.log('     %s %s -> %s', method.toUpperCase(), path, key);
      }
    }

    // mount the app
    parent.use(app);
  });
};
<commit_msg>examples: fix mvc example to ignore files in controllers dir<commit_after>/**
 * Module dependencies.
 */

var express = require('../../..');
var fs = require('fs');

module.exports = function(parent, options){
  var verbose = options.verbose;
  fs.readdirSync(__dirname + '/../controllers').forEach(function(name){
    if (!fs.statSync(__dirname + '/../controllers/' + name).isDirectory()) return;
    verbose && console.log('\n   %s:', name);
    var obj = require('./../controllers/' + name);
    var name = obj.name || name;
    var prefix = obj.prefix || '';
    var app = express();
    var handler;
    var method;
    var path;

    // allow specifying the view engine
    if (obj.engine) app.set('view engine', obj.engine);
    app.set('views', __dirname + '/../controllers/' + name + '/views');

    // generate routes based
    // on the exported methods
    for (var key in obj) {
      // "reserved" exports
      if (~['name', 'prefix', 'engine', 'before'].indexOf(key)) continue;
      // route exports
      switch (key) {
        case 'show':
          method = 'get';
          path = '/' + name + '/:' + name + '_id';
          break;
        case 'list':
          method = 'get';
          path = '/' + name + 's';
          break;
        case 'edit':
          method = 'get';
          path = '/' + name + '/:' + name + '_id/edit';
          break;
        case 'update':
          method = 'put';
          path = '/' + name + '/:' + name + '_id';
          break;
        case 'create':
          method = 'post';
          path = '/' + name;
          break;
        case 'index':
          method = 'get';
          path = '/';
          break;
        default:
          /* istanbul ignore next */
          throw new Error('unrecognized route: ' + name + '.' + key);
      }

      // setup
      handler = obj[key];
      path = prefix + path;

      // before middleware support
      if (obj.before) {
        app[method](path, obj.before, handler);
        verbose && console.log('     %s %s -> before -> %s', method.toUpperCase(), path, key);
      } else {
        app[method](path, handler);
        verbose && console.log('     %s %s -> %s', method.toUpperCase(), path, key);
      }
    }

    // mount the app
    parent.use(app);
  });
};
<|endoftext|>


<commit_before>/*
 @author Zakai Hamilton
 @component MediaFile
 */

screens.media.sessions = function MediaSessions(me, { core, cache }) {
    me.getPaths = async () => {
        const { cdn, bucket, sessions } = await cache.path.get() || {};
        me.cdn = cdn;
        me.bucket = bucket;
        me.sessions = sessions;
    };
    me.list = async function (update) {
        const groups = await me.groups(update);
        const metadataList = await cache.playlists.get("$userId") || [];
        await me.getPaths();
        const { cdn, bucket, sessions } = me;
        return { groups, metadataList, cdn, bucket, sessions };
    };
    me.groups = async (update) => {
        core.mutex.enable(me.id, true);
        var unlock = await core.mutex.lock(me.id);
        await me.getPaths();
        const path = "aws/" + me.sessions;
        if (!await cache.listing.exists(path)) {
            const results = await core.message.send_server("cache.listing.loadRecursive", path, "$userName");
            if (results) {
                for (const result of results) {
                    if (result.component) {
                        await cache[result.component].write(result.path, result.result);
                    }
                }
            }
        }
        const listing = await cache.listing.get(path, update) || [];
        let groups = [];
        try {
            for (const group of listing) {
                const { name } = group;
                const sessions = await me.group(name, update);
                groups.push({ name, sessions });
            }
            groups = groups.sort((a, b) => a.name.localeCompare(b.name));
        }
        catch (err) {
            // eslint-disable-next-line no-console
            console.error(err);
        }
        unlock();
        return groups;
    };
    me.group = async (groupName, update) => {
        const listing = await cache.listing.get("aws/" + me.sessions + "/" + groupName, update) || [];
        const years = [];
        for (const year of listing) {
            years.push(await me.year(groupName, year.name, update));
        }
        const sessions = years.flat(1);
        sessions.reverse();
        return sessions;
    };
    me.year = async (groupName, yearName, update) => {
        const path = "aws/" + me.sessions + "/" + groupName + "/" + yearName;
        const listing = await cache.listing.get(path, update);
        const durations = await cache.duration.get(path, update);
        const positions = await cache.stream.get("$userName/" + groupName, update);
        let sessions = [];
        if (!listing) {
            return [];
        }
        for (const file of listing) {
            const [, date, name, extension] = file.name.match(/([0-9]*-[0-9]*-[0-9]*) (.*)\.(.*)/);
            const [title, resolution] = name.split("_");
            const durationItem = durations.find(item => item.name === file.name);
            const duration = parseInt((durationItem && durationItem.duration) || 0);
            const dateAndTitle = date + " " + title;
            const sessionName = dateAndTitle + "." + extension;
            const positionItem = await positions.find(item => item.group === groupName && item.session === dateAndTitle);
            var position = parseInt((positionItem && positionItem.position) || 0);
            var watched = (position === 0) ? "not_viewed" : (position === duration) ? "viewed" : "continue";
            let item = sessions.find(item => item.name === name);
            if (!item) {
                item = {
                    group: groupName,
                    extension,
                    date,
                    title,
                    name: sessionName,
                    session: dateAndTitle,
                    label: core.string.title(dateAndTitle),
                    resolutions: [],
                    ...durationItem && durationItem.duration && {
                        duration: durationItem.duration,
                        durationText: core.string.formatDuration(durationItem.duration)
                    },
                    position,
                    watched
                };
                Object.assign(item, me.paths(groupName, file.name));
                sessions.push(item);
            }
            item.resolutions = [...item.resolutions, resolution];
        }
        return sessions;
    };
    me.paths = function (groupName, name) {
        const [, year] = name.match(/([0-9]*)-.*/);
        var paths = {
            local: "cache/" + name,
            remote: "/sessions/" + groupName + "/" + year + "/" + name,
            aws: me.sessions + "/" + groupName + "/" + year + "/" + name
        };
        return paths;
    };
    me.updateMetadata = async function () {
        me.metadataList = await cache.playlists.get("$userId") || [];
        return me.metadataList;
    };
    me.exists = async function (name) {
        var groups = await me.groups(false);
        for (var group of groups) {
            for (var session of group.sessions) {
                if (session.name.includes(name)) {
                    return group.name;
                }
            }
        }
        return null;
    };
};
<commit_msg>bug fix<commit_after>/*
 @author Zakai Hamilton
 @component MediaFile
 */

screens.media.sessions = function MediaSessions(me, { core, cache }) {
    me.getPaths = async () => {
        const { cdn, bucket, sessions } = await cache.path.get() || {};
        me.cdn = cdn;
        me.bucket = bucket;
        me.sessions = sessions;
    };
    me.list = async function (update) {
        const groups = await me.groups(update);
        const metadataList = await cache.playlists.get("$userId") || [];
        await me.getPaths();
        const { cdn, bucket, sessions } = me;
        return { groups, metadataList, cdn, bucket, sessions };
    };
    me.groups = async (update) => {
        core.mutex.enable(me.id, true);
        var unlock = await core.mutex.lock(me.id);
        await me.getPaths();
        const path = "aws/" + me.sessions;
        if (!await cache.listing.exists(path)) {
            const results = await core.message.send_server("cache.listing.loadRecursive", path, "$userName");
            if (results) {
                for (const result of results) {
                    if (result.component) {
                        await cache[result.component].write(result.path, result.result);
                    }
                }
            }
        }
        const listing = await cache.listing.get(path, update) || [];
        let groups = [];
        try {
            for (const group of listing) {
                const { name } = group;
                const sessions = await me.group(name, update);
                groups.push({ name, sessions });
            }
            groups = groups.sort((a, b) => a.name.localeCompare(b.name));
        }
        catch (err) {
            // eslint-disable-next-line no-console
            console.error(err);
        }
        unlock();
        return groups;
    };
    me.group = async (groupName, update) => {
        const listing = await cache.listing.get("aws/" + me.sessions + "/" + groupName, update) || [];
        const years = [];
        for (const year of listing) {
            years.push(await me.year(groupName, year.name, update));
        }
        const sessions = years.flat(1);
        sessions.reverse();
        return sessions;
    };
    me.year = async (groupName, yearName, update) => {
        const path = "aws/" + me.sessions + "/" + groupName + "/" + yearName;
        const listing = await cache.listing.get(path, update);
        const durations = await cache.duration.get(path, update);
        const positions = await cache.stream.get("$userName/" + groupName, update);
        let sessions = [];
        if (!listing) {
            return [];
        }
        for (const file of listing) {
            if (!(file.name.endsWith(".m4a") || file.name.endsWith(".mp4"))) {
                continue;
            }
            const [, date, name, extension] = file.name.match(/([0-9]*-[0-9]*-[0-9]*) (.*)\.(.*)/);
            const [title, resolution] = name.split("_");
            const durationItem = durations.find(item => item.name === file.name);
            const duration = parseInt((durationItem && durationItem.duration) || 0);
            const dateAndTitle = date + " " + title;
            const sessionName = dateAndTitle + "." + extension;
            const positionItem = await positions.find(item => item.group === groupName && item.session === dateAndTitle);
            var position = parseInt((positionItem && positionItem.position) || 0);
            var watched = (position === 0) ? "not_viewed" : (position === duration) ? "viewed" : "continue";
            let item = sessions.find(item => item.name === name);
            if (!item) {
                item = {
                    group: groupName,
                    extension,
                    date,
                    title,
                    name: sessionName,
                    session: dateAndTitle,
                    label: core.string.title(dateAndTitle),
                    resolutions: [],
                    ...durationItem && durationItem.duration && {
                        duration: durationItem.duration,
                        durationText: core.string.formatDuration(durationItem.duration)
                    },
                    position,
                    watched
                };
                Object.assign(item, me.paths(groupName, file.name));
                sessions.push(item);
            }
            item.resolutions = [...item.resolutions, resolution];
        }
        return sessions;
    };
    me.paths = function (groupName, name) {
        const [, year] = name.match(/([0-9]*)-.*/);
        var paths = {
            local: "cache/" + name,
            remote: "/sessions/" + groupName + "/" + year + "/" + name,
            aws: me.sessions + "/" + groupName + "/" + year + "/" + name
        };
        return paths;
    };
    me.updateMetadata = async function () {
        me.metadataList = await cache.playlists.get("$userId") || [];
        return me.metadataList;
    };
    me.exists = async function (name) {
        var groups = await me.groups(false);
        for (var group of groups) {
            for (var session of group.sessions) {
                if (session.name.includes(name)) {
                    return group.name;
                }
            }
        }
        return null;
    };
};
<|endoftext|>


<commit_before>//=require ./button_like_a_link<commit_msg>Put test javascript into the index.js<commit_after>//=require ./button_like_a_link

$(document).ready(function(){
  alert("hello inside index document onready")
})<|endoftext|>


<commit_before>// Ionic Starter App

// angular.module is a global place for creating, registering and retrieving Angular modules
// 'starter' is the name of this angular module example (also set in a <body> attribute in index.html)
// the 2nd parameter is an array of 'requires'
// angular.module('starter', ['ionic'])

angular.module('app', [
  'ionic',
  'app.services',
  'app.home',
  'app.courses',
  'app.times',
  'app.invite'
])

.config(function($stateProvider, $urlRouterProvider) {

  $stateProvider
  .state('tab', {
    url: '/tab',
    abstract: true,
    templateUrl: 'app/app.html'
  });

  $urlRouterProvider.otherwise('/tab/courses');

})

.run(function($ionicPlatform) {
  $ionicPlatform.ready(function() {
    // Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
    // for form inputs)
    if(window.cordova && window.cordova.plugins.Keyboard) {
      cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
    }
    if(window.StatusBar) {
      StatusBar.styleDefault();
    }
  });
});
<commit_msg>change angular 'otherwise' redirect route to /tab/home<commit_after>// Ionic Starter App

// angular.module is a global place for creating, registering and retrieving Angular modules
// 'starter' is the name of this angular module example (also set in a <body> attribute in index.html)
// the 2nd parameter is an array of 'requires'
// angular.module('starter', ['ionic'])

angular.module('app', [
  'ionic',
  'app.services',
  'app.home',
  'app.courses',
  'app.times',
  'app.invite'
])

.config(function($stateProvider, $urlRouterProvider) {

  $stateProvider
  .state('tab', {
    url: '/tab',
    abstract: true,
    templateUrl: 'app/app.html'
  });

  $urlRouterProvider.otherwise('/tab/home');

})

.run(function($ionicPlatform) {
  $ionicPlatform.ready(function() {
    // Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
    // for form inputs)
    if(window.cordova && window.cordova.plugins.Keyboard) {
      cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
    }
    if(window.StatusBar) {
      StatusBar.styleDefault();
    }
  });
});
<|endoftext|>


<commit_before>import getModifiedProps from '../../src/utils/getModifiedProps';

describe('utils/getModifiedProps', () => {

  it('should return only modified props', () => {
    const prevProps = {
      firstProp: true,
      secondProp: true
    };

    const currProps = {
      firstProp: true,
      secondProp: false
    };

    const returnedProps = getModifiedProps(prevProps, currProps, false);
    expect(returnedProps).toEqual({ secondProp: false });

  });

  it('should return false for non modified props', () => {
    const prevProps = {
      firstProp: true,
      secondProp: true
    };

    const returnedProps = getModifiedProps(prevProps, prevProps, false);
    expect(returnedProps).toEqual(false);
  });

  it('should return modified props for undefined prevProps', () => {
    const prevProps = undefined;

    const currProps = {
      firstProp: true,
      secondProp: false
    };

    const returnedProps = getModifiedProps(prevProps, currProps, false);
    expect(returnedProps).toEqual(currProps);

  });

  it('should return modified props for null prevProps', () => {
    const prevProps = null;

    const currProps = {
      firstProp: true,
      secondProp: false
    };

    const returnedProps = getModifiedProps(prevProps, currProps, false);
    expect(returnedProps).toEqual(currProps);

  });
  it('should not return text when children is not defined', () => {
    const prevProps = null;

    const currProps = {
      a: 1
    };

    const returnedProps = getModifiedProps(prevProps, currProps, true);
    expect(returnedProps.text).not.toBeDefined();
    expect(returnedProps.a).toBe(1);
  });

  it('should return text when children changes', () => {
    const prevProps = {};

    const currProps = {
      children: "teststring"
    };

    const returnedProps = getModifiedProps(prevProps, currProps, true);
    expect(returnedProps.text).toBe("teststring");
  });

});

<commit_msg>Add one more test for getModifiedProps<commit_after>import getModifiedProps from '../../src/utils/getModifiedProps';

describe('utils/getModifiedProps', () => {

  it('should return only modified props', () => {
    const prevProps = {
      firstProp: true,
      secondProp: true
    };

    const currProps = {
      firstProp: true,
      secondProp: false
    };

    const returnedProps = getModifiedProps(prevProps, currProps, false);
    expect(returnedProps).toEqual({ secondProp: false });

  });

  it('should return false for non modified props', () => {
    const prevProps = {
      firstProp: true,
      secondProp: true
    };

    const returnedProps = getModifiedProps(prevProps, prevProps, false);
    expect(returnedProps).toEqual(false);
  });

  it('should return added props', () => {
    const prevProps = {
      firstProp: true,
    };

    const currProps = {
      secondProp: false
    };

    const returnedProps = getModifiedProps(prevProps, currProps, false);
    expect(returnedProps).toEqual({ secondProp: false });

  });

  it('should return modified props for undefined prevProps', () => {
    const prevProps = undefined;

    const currProps = {
      firstProp: true,
      secondProp: false
    };

    const returnedProps = getModifiedProps(prevProps, currProps, false);
    expect(returnedProps).toEqual(currProps);

  });

  it('should return modified props for null prevProps', () => {
    const prevProps = null;

    const currProps = {
      firstProp: true,
      secondProp: false
    };

    const returnedProps = getModifiedProps(prevProps, currProps, false);
    expect(returnedProps).toEqual(currProps);

  });
  it('should not return text when children is not defined', () => {
    const prevProps = null;

    const currProps = {
      a: 1
    };

    const returnedProps = getModifiedProps(prevProps, currProps, true);
    expect(returnedProps.text).not.toBeDefined();
    expect(returnedProps.a).toBe(1);
  });

  it('should return text when children changes', () => {
    const prevProps = {};

    const currProps = {
      children: "teststring"
    };

    const returnedProps = getModifiedProps(prevProps, currProps, true);
    expect(returnedProps.text).toBe("teststring");
  });

});

<|endoftext|>


<commit_before>// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.
(function($, cloudStack) {
    cloudStack.sections.vmsnapshots = {
        title: 'label.vmsnapshot',
        id: 'vmsnapshots',
        listView: {
            id: 'vmsnapshots',
            isMaximized: true,
            fields: {
                displayname: {
                    label: 'label.name'
                },
                state: {
                    label: 'label.state',
                    indicator: {
                        'Ready': 'on',
                        'Error': 'off'
                    }
                },
                type: {
                    label: 'label.vmsnapshot.type'
                },
                current: {
                    label: 'label.vmsnapshot.current',
                    converter: cloudStack.converters.toBooleanText
                },
                parentName: {
                    label: 'label.vmsnapshot.parentname'
                },
                created: {
                    label: 'label.date',
                    converter: cloudStack.converters.toLocalDate
                }
            },

            dataProvider: function(args) {
                var apiCmd = "listVMSnapshot&listAll=true";
                if (args.context != null) {
                    if ("instances" in args.context) {
                        apiCmd += "&virtualmachineid=" + args.context.instances[0].id;
                    }
                }
                $.ajax({
                    url: createURL(apiCmd),
                    dataType: "json",
                    async: true,
                    success: function(json) {
                        var jsonObj;
                        jsonObj = json.listvmsnapshotresponse.vmSnapshot;
                        args.response.success({
                            data: jsonObj
                        });
                    }
                });
            },
            //dataProvider end
            detailView: {
                tabs: {
                    details: {
                        title: 'label.details',
                        fields: {
                            id: {
                                label: 'label.id'
                            },
                            name: {
                                label: 'label.name'
                            },
                            displayname: {
                                label: 'label.display.name',
                            },
                            type: {
                                label: 'label.vmsnapshot.type',
                            },
                            description: {
                                label: 'label.description',
                            },
                            state: {
                                label: 'label.state',
                                indicator: {
                                    'Ready': 'on',
                                    'Error': 'off'
                                }
                            },
                            current: {
                                label: 'label.vmsnapshot.current',
                                converter: cloudStack.converters.toBooleanText
                            },
                            parentName: {
                                label: 'label.vmsnapshot.parentname'
                            },
                            created: {
                                label: 'label.date',
                                converter: cloudStack.converters.toLocalDate
                            },

                        },
                        dataProvider: function(args) {
                            $.ajax({
                                url: createURL("listVMSnapshot&listAll=true&id=" + args.context.vmsnapshots[0].id),
                                dataType: "json",
                                async: true,
                                success: function(json) {
                                    var jsonObj;
                                    jsonObj = json.listvmsnapshotresponse.vmSnapshot[0];
                                    args.response.success({
                                        //actionFilter: vmActionfilter,
                                        data: jsonObj
                                    });
                                }
                            });
                        },
                        tags: cloudStack.api.tags({
                            resourceType: 'VMSnapshot',
                            contextId: 'vmsnapshots'
                        })
                    }
                },
                actions: {
                    //delete a snapshot
                    remove: {
                        label: 'label.action.vmsnapshot.delete',
                        messages: {
                            confirm: function(args) {
                                return 'message.action.vmsnapshot.delete';
                            },
                            notification: function(args) {
                                return 'label.action.vmsnapshot.delete';
                            }
                        },
                        action: function(args) {
                            $.ajax({
                                url: createURL("deleteVMSnapshot&vmsnapshotid=" + args.context.vmsnapshots[0].id),
                                dataType: "json",
                                async: true,
                                success: function(json) {
                                    var jid = json.deletevmsnapshotresponse.jobid;
                                    args.response.success({
                                        _custom: {
                                            jobId: jid
                                        }
                                    });
                                }
                            });
                        },
                        notification: {
                            poll: pollAsyncJobResult
                        }
                    },
                    restart: {
                        label: 'label.action.vmsnapshot.revert',
                        messages: {
                            confirm: function(args) {
                                return 'label.action.vmsnapshot.revert';
                            },
                            notification: function(args) {
                                return 'message.action.vmsnapshot.revert';
                            }
                        },
                        action: function(args) {
                            $.ajax({
                                url: createURL("revertToVMSnapshot&vmsnapshotid=" + args.context.vmsnapshots[0].id),
                                dataType: "json",
                                async: true,
                                success: function(json) {
                                    var jid = json.reverttovmsnapshotresponse.jobid;
                                    args.response.success({
                                        _custom: {
                                            jobId: jid
                                        }
                                    });
                                }
                            });

                        },
                        notification: {
                            poll: pollAsyncJobResult
                        }
                    }
                }
            }
            //detailview end
        }
    }
})(jQuery, cloudStack);
<commit_msg>fix UI display bug for vmsnapshot, detailView of vmsnapshot always show the same one<commit_after>// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.
(function($, cloudStack) {
    cloudStack.sections.vmsnapshots = {
        title: 'label.vmsnapshot',
        id: 'vmsnapshots',
        listView: {
            id: 'vmsnapshots',
            isMaximized: true,
            fields: {
                displayname: {
                    label: 'label.name'
                },
                state: {
                    label: 'label.state',
                    indicator: {
                        'Ready': 'on',
                        'Error': 'off'
                    }
                },
                type: {
                    label: 'label.vmsnapshot.type'
                },
                current: {
                    label: 'label.vmsnapshot.current',
                    converter: cloudStack.converters.toBooleanText
                },
                parentName: {
                    label: 'label.vmsnapshot.parentname'
                },
                created: {
                    label: 'label.date',
                    converter: cloudStack.converters.toLocalDate
                }
            },

            dataProvider: function(args) {
                var apiCmd = "listVMSnapshot&listAll=true";
                if (args.context != null) {
                    if ("instances" in args.context) {
                        apiCmd += "&virtualmachineid=" + args.context.instances[0].id;
                    }
                }
                $.ajax({
                    url: createURL(apiCmd),
                    dataType: "json",
                    async: true,
                    success: function(json) {
                        var jsonObj;
                        jsonObj = json.listvmsnapshotresponse.vmSnapshot;
                        args.response.success({
                            data: jsonObj
                        });
                    }
                });
            },
            //dataProvider end
            detailView: {
                tabs: {
                    details: {
                        title: 'label.details',
                        fields: {
                            id: {
                                label: 'label.id'
                            },
                            name: {
                                label: 'label.name'
                            },
                            displayname: {
                                label: 'label.display.name',
                            },
                            type: {
                                label: 'label.vmsnapshot.type',
                            },
                            description: {
                                label: 'label.description',
                            },
                            state: {
                                label: 'label.state',
                                indicator: {
                                    'Ready': 'on',
                                    'Error': 'off'
                                }
                            },
                            current: {
                                label: 'label.vmsnapshot.current',
                                converter: cloudStack.converters.toBooleanText
                            },
                            parentName: {
                                label: 'label.vmsnapshot.parentname'
                            },
                            created: {
                                label: 'label.date',
                                converter: cloudStack.converters.toLocalDate
                            },

                        },
                        dataProvider: function(args) {
                            $.ajax({
                                url: createURL("listVMSnapshot&listAll=true&vmsnapshotid=" + args.context.vmsnapshots[0].id),
                                dataType: "json",
                                async: true,
                                success: function(json) {
                                    var jsonObj;
                                    jsonObj = json.listvmsnapshotresponse.vmSnapshot[0];
                                    args.response.success({
                                        //actionFilter: vmActionfilter,
                                        data: jsonObj
                                    });
                                }
                            });
                        },
                        tags: cloudStack.api.tags({
                            resourceType: 'VMSnapshot',
                            contextId: 'vmsnapshots'
                        })
                    }
                },
                actions: {
                    //delete a snapshot
                    remove: {
                        label: 'label.action.vmsnapshot.delete',
                        messages: {
                            confirm: function(args) {
                                return 'message.action.vmsnapshot.delete';
                            },
                            notification: function(args) {
                                return 'label.action.vmsnapshot.delete';
                            }
                        },
                        action: function(args) {
                            $.ajax({
                                url: createURL("deleteVMSnapshot&vmsnapshotid=" + args.context.vmsnapshots[0].id),
                                dataType: "json",
                                async: true,
                                success: function(json) {
                                    var jid = json.deletevmsnapshotresponse.jobid;
                                    args.response.success({
                                        _custom: {
                                            jobId: jid
                                        }
                                    });
                                }
                            });
                        },
                        notification: {
                            poll: pollAsyncJobResult
                        }
                    },
                    restart: {
                        label: 'label.action.vmsnapshot.revert',
                        messages: {
                            confirm: function(args) {
                                return 'label.action.vmsnapshot.revert';
                            },
                            notification: function(args) {
                                return 'message.action.vmsnapshot.revert';
                            }
                        },
                        action: function(args) {
                            $.ajax({
                                url: createURL("revertToVMSnapshot&vmsnapshotid=" + args.context.vmsnapshots[0].id),
                                dataType: "json",
                                async: true,
                                success: function(json) {
                                    var jid = json.reverttovmsnapshotresponse.jobid;
                                    args.response.success({
                                        _custom: {
                                            jobId: jid
                                        }
                                    });
                                }
                            });

                        },
                        notification: {
                            poll: pollAsyncJobResult
                        }
                    }
                }
            }
            //detailview end
        }
    }
})(jQuery, cloudStack);
<|endoftext|>


<commit_before>//     (c) 2012 Victor Saiz, Michael Aufreiter
//     Proper is freely distributable under the MIT license.
//     For all details and documentation:
//     http://github.com/substance/proper

// Goals:
//
// * Annotations (strong, em, code, link) are exclusive. No text can be both
//   emphasized and strong.
// * The output is plain.
// * Cross-browser compatibility: Support the most recent versions of Chrome,
//   Safari, Firefox and Internet Explorer. Proper should behave the same on
//   all these platforms (if possible).

(function(){

  // Proper
  // ------

  this.Proper = function(options){

    var range
      , annotationList = []
      , events = _.extend({}, _.Events),
      tools =
      '
 \

Emphasis
 \

Strong
\

';

    // Init codeMirror
    var cm = CodeMirror.fromTextArea($(options.el)[0], options);

    // Override options
    cm.setOption('lineWrapping', true);

    // CodeMirror events
    cm.setOption('onCursorActivity', function(cm){
      // Make sure we at least have 1 character selected
      if(cm.getSelection().length !== 0){
        // Set the selection range
        var from = cm.getCursor(true)
        ,   to = cm.getCursor(false)
        , str = cm.getSelection();

        range = {'from':from, 'to':to, 'str': str};

        // When we have at least one character we show the tools
        if(cm.getSelection().length < 2){
          var node = $(tools)[0];
          cm.addWidget(cm.getCursor(false), node, true);
        }

        findMatching();
      }else{
        // no chars selected we remove the tools
        removeTools();
      }
    });

    cm.setOption('onFocus', function(e){
      $(cm.getWrapperElement()).addClass('active');
    });

    cm.setOption('onBlur', function(e){
      $(cm.getWrapperElement()).removeClass('active');
      // removeTools();
    });

    function removeTools(){
      // There's a strange bug where it won't be removed
      // when no characters are selected
      $('#tooltip').remove();
      $('#tooltip').remove();
    }

    // Resets the cursor selection to the actual range
    function restetCursor(range){
      // Reselect trimmed range and string value
      cm.setSelection(range.from, range.to);
    }

    // Unselects left or right blank characters
    function trim(sel){
      var first = sel.str.charCodeAt(0);
      var last = sel.str.charCodeAt(sel.str.length-1);
      // Check if first character is blank and adjusts the annotation range if it is
      if(first === 32){
        sel.from.ch = sel.from.ch + 1;
      }

      // Check if last character is blank and adjusts the annotation range if it is
      if(last === 32){
        sel.to.ch = sel.to.ch - 1;
      }

      // Get selection string
      sel.str = cm.getRange(sel.from, sel.to);
      return sel;
    }

    // Turns position line objects into a single value representing the offset from character 0
    function toOffset(pos){
      var offset = 0;
      if(pos.line > 0){
        var i = 0;
        for(; i < pos.line; i++ ){
          offset += cm.lineInfo(i).text.length + 1;//count the newline character as 1?
        }
      }
      return pos.ch + offset;
    }

    // Returns the current selection
    function selection(){
      range = trim(range);
      var start = toOffset(range.from);
      var end = toOffset(range.to);
      return {'start': start, 'end': end};
    }

    // Adds annotation (uses the current selection)
    function annotate(note){

      if(cm.getSelection().length > 0){
        note.pos = selection();
        //autogenerated id based on the type and the ofsset position string
        note.id = note.type + '/' + note.pos.start + '' + note.pos.end;
        restetCursor(range);

        // Fast marking techinque
        $('#' + note.type).addClass('selected');
        annotationList.push(note);
      }
    }

    // Finds matching annotations for the selected range
    function findMatching(){
      var start = toOffset(range.from);
      var end = toOffset(range.to);
      var id = 'comment/' + start + '' + end;
      var found = _.find(annotationList, function(ann){ return ann.id == id; });

      if(typeof found !== 'undefined'){
        // Fast marking techinque
        $('#' + found.type).addClass('selected');
      }else{
        $('.command').removeClass('selected');
      }
    }

    // Expose public API
    // -----------------

    return {
      annotations: function(){ return annotationList;},

      selection: selection,
      annotate: annotate,
    };
  };
})();<commit_msg>from id to class for toggles<commit_after>//     (c) 2012 Victor Saiz, Michael Aufreiter
//     Proper is freely distributable under the MIT license.
//     For all details and documentation:
//     http://github.com/substance/proper

// Goals:
//
// * Annotations (strong, em, code, link) are exclusive. No text can be both
//   emphasized and strong.
// * The output is plain.
// * Cross-browser compatibility: Support the most recent versions of Chrome,
//   Safari, Firefox and Internet Explorer. Proper should behave the same on
//   all these platforms (if possible).

(function(){

  // Proper
  // ------

  this.Proper = function(options){

    var range
      , annotationList = []
      , events = _.extend({}, _.Events),
      tools =
      '
 \

Emphasis
 \

Strong
\

';

    // Init codeMirror
    var cm = CodeMirror.fromTextArea($(options.el)[0], options);

    // Override options
    cm.setOption('lineWrapping', true);

    // CodeMirror events
    cm.setOption('onCursorActivity', function(cm){
      // Make sure we at least have 1 character selected
      if(cm.getSelection().length !== 0){
        // Set the selection range
        var from = cm.getCursor(true)
        ,   to = cm.getCursor(false)
        , str = cm.getSelection();

        range = {'from':from, 'to':to, 'str': str};

        // When we have at least one character we show the tools
        if(cm.getSelection().length < 2){
          var node = $(tools)[0];
          cm.addWidget(cm.getCursor(false), node, true);
        }

        findMatching();
      }else{
        // no chars selected we remove the tools
        removeTools();
      }
    });

    cm.setOption('onFocus', function(e){
      $(cm.getWrapperElement()).addClass('active');
    });

    cm.setOption('onBlur', function(e){
      $(cm.getWrapperElement()).removeClass('active');
      // removeTools();
    });

    function removeTools(){
      // There's a strange bug where it won't be removed
      // when no characters are selected
      $('#tooltip').remove();
      $('#tooltip').remove();
    }

    // Resets the cursor selection to the actual range
    function restetCursor(range){
      // Reselect trimmed range and string value
      cm.setSelection(range.from, range.to);
    }

    // Unselects left or right blank characters
    function trim(sel){
      var first = sel.str.charCodeAt(0);
      var last = sel.str.charCodeAt(sel.str.length-1);
      // Check if first character is blank and adjusts the annotation range if it is
      if(first === 32){
        sel.from.ch = sel.from.ch + 1;
      }

      // Check if last character is blank and adjusts the annotation range if it is
      if(last === 32){
        sel.to.ch = sel.to.ch - 1;
      }

      // Get selection string
      sel.str = cm.getRange(sel.from, sel.to);
      return sel;
    }

    // Turns position line objects into a single value representing the offset from character 0
    function toOffset(pos){
      var offset = 0;
      if(pos.line > 0){
        var i = 0;
        for(; i < pos.line; i++ ){
          offset += cm.lineInfo(i).text.length + 1;//count the newline character as 1?
        }
      }
      return pos.ch + offset;
    }

    // Returns the current selection
    function selection(){
      range = trim(range);
      var start = toOffset(range.from);
      var end = toOffset(range.to);
      return {'start': start, 'end': end};
    }

    // Adds annotation (uses the current selection)
    function annotate(note){

      if(cm.getSelection().length > 0){
        note.pos = selection();
        //autogenerated id based on the type and the ofsset position string
        note.id = note.type + '/' + note.pos.start + '' + note.pos.end;
        restetCursor(range);

        // Fast marking techinque
        $('.' + note.type).addClass('selected');
        annotationList.push(note);
      }
    }

    // Finds matching annotations for the selected range
    function findMatching(){
      var start = toOffset(range.from);
      var end = toOffset(range.to);
      var id = 'comment/' + start + '' + end;
      var found = _.find(annotationList, function(ann){ return ann.id == id; });

      if(typeof found !== 'undefined'){
        // Fast marking techinque
        $('#' + found.type).addClass('selected');
      }else{
        $('.command').removeClass('selected');
      }
    }

    // Expose public API
    // -----------------

    return {
      annotations: function(){ return annotationList;},

      selection: selection,
      annotate: annotate,
    };
  };
})();<|endoftext|>


<commit_before>function combinedHeader(contacts) {
  return contacts.reduce(function (prev, cur) {
    Object.keys(cur).forEach(function(key) {
      if (prev.indexOf(key) === -1) prev.push(key);
    });
    return prev;
  },[]);
}

function displayWidth(str) {
  str = str.toString();
  var ret = str.length;
  for (var i = 0; i < str.length; i++)
    if (str.charCodeAt(i) > 255)
      ret++;
  return ret;
}

function max(arr) {
  return arr.reduce(function(prev, cur) {
    return prev >= cur ? prev : cur;
  }, 0);
}

function repeat(ch, count) {
  var ret = '';
  for (var i = 0; i < count ; i++) {
    ret += ch;
  }
  return ret;
}

function tablizeLine(people, maxColWidth) {
  return '| ' +
    people.map(function(v, i) {
      return v + repeat(' ', maxColWidth[i] - displayWidth(v));
    }).join(' | ') + ' |'
}

function sepLine(maxColWidth) {
  return '+-' +
    maxColWidth.map(function(v) {
      return repeat('-', v);
    }).join('-+-') + '-+'
}

function print(contacts) {
  var header = combinedHeader(contacts);

  var tableLineArr = contacts.map(function(people) {
    return header.map(function(headerKey) {
      return people[headerKey] || '';
    });
  });

  tableLineArr.unshift(header);

  var maxColWidth = header.map(function(v, i) {
    var columnWitdh = tableLineArr.map(function(v) { return displayWidth(v[i]); });
    return max(columnWitdh);
  });

  var tableStr = tableLineArr.reduce(function(prev, cur) {
    return prev + tablizeLine(cur, maxColWidth) + '\n' + sepLine(maxColWidth) + '\n';
  }, sepLine(maxColWidth) + '\n');

  console.log(tableStr);
  console.log(maxColWidth);
}

exports.print = print;
<commit_msg>select output as table with word wrap<commit_after>
var maxTableWidth = 200;

function combinedHeader(contacts) {
  return contacts.reduce(function (prev, cur) {
    Object.keys(cur).forEach(function(key) {
      if (prev.indexOf(key) === -1) prev.push(key);
    });
    return prev;
  },[]);
}

function displayWidth(str) {
  str = str.toString();
  var ret = str.length;
  for (var i = 0; i < str.length; i++)
    if (str.charCodeAt(i) > 255)
      ret++;
  return ret;
}

function displaySubString(str, len) {
  var firstHalf = '';
  for (var i = 0; i < str.length && displayWidth(firstHalf) < len; i++)
    firstHalf += str[i];
  return [str.substring(0, i - 1), str.substring(i - 1)];
}

function max(arr) {
  return arr.reduce(function(prev, cur) {
    return prev >= cur ? prev : cur;
  }, 0);
}

function repeat(ch, count) {
  var ret = '';
  for (var i = 0; i < count ; i++) {
    ret += ch;
  }
  return ret;
}

function tablizeLine(people, maxColWidthArr) {
  var peopleRemaining = people.map(function() { return ''; });

  var peopleInCell =  '| ' +
    people.map(function(v, i) {
      if (displayWidth(v) > maxColWidthArr[i]) {
        peopleRemaining[i] = displaySubString(v, maxColWidthArr[i])[1];
        v = displaySubString(v, maxColWidthArr[i])[0]
      }
      return v + repeat(' ', maxColWidthArr[i] - displayWidth(v));
    }).join(' | ') + ' |'

  if (peopleRemaining.reduce(function(prev, cur) {return prev + cur; }, '').trim().length > 0) {
    peopleInCell += '\n' + tablizeLine(peopleRemaining, maxColWidthArr);
  }
  return peopleInCell;
}

function sepLine(maxColWidthArr) {
  return '+-' +
    maxColWidthArr.map(function(v) {
      return repeat('-', v);
    }).join('-+-') + '-+'
}

function trimColWidthArr(maxColWidthArr, totalColWidth) {
  var extraWidth = totalColWidth - maxTableWidth;
  var averageWidth = Math.floor(maxTableWidth/maxColWidthArr.length);

  var longColArr = maxColWidthArr.map(function(v) {
    return v > averageWidth ? v  : 0;
  });
  var longColArrSum = longColArr.reduce(function(prev, cur) {return prev + cur; }, 0);

  var trimmedColWidthArr1 = maxColWidthArr.map(function(v, i) {
    return Math.ceil((longColArr[i]/longColArrSum) * extraWidth);
  });

  var trimmedColWidthArr = maxColWidthArr.map(function(v, i) {
    return v - Math.ceil((longColArr[i]/longColArrSum) * extraWidth);
  });

  return trimmedColWidthArr;
}

function print(contacts) {
  var header = combinedHeader(contacts);

  var tableLineArr = contacts.map(function(people) {
    return header.map(function(headerKey) {
      return people[headerKey] || '';
    });
  });

  tableLineArr.unshift(header);

  var maxColWidthArr = header.map(function(v, i) {
    var columnWitdh = tableLineArr.map(function(v) { return displayWidth(v[i]); });
    return max(columnWitdh);
  });

  var totalColWidth = maxColWidthArr.reduce(function(prev, cur) {
    return prev + cur + 3;
  }, 1);

  if (totalColWidth > maxTableWidth) {
    maxColWidthArr = trimColWidthArr(maxColWidthArr, totalColWidth);
  }

  var tableStr = tableLineArr.reduce(function(prev, cur) {
    return prev + tablizeLine(cur, maxColWidthArr) + '\n' + sepLine(maxColWidthArr) + '\n';
  }, sepLine(maxColWidthArr) + '\n');

  console.log(tableStr);
}

exports.print = print;
<|endoftext|>


<commit_before>/*
 * This file is part of the RedKiteCmsBunde Application and it is distributed
 * under the GPL LICENSE Version 2.0. To use this application you must leave
 * intact this copyright notice.
 *
 * Copyright (c) RedKite Labs <webmaster@redkite-labs.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 *
 * For extra documentation and help please visit http://www.redkite-labs.com
 *
 * @license    GPL LICENSE Version 2.0
 *
 */

;(function($){
    var methods = {
        start: function()
        {
            stopBlocksMenu = false;
            $(this).mouseenter(function(event) {
                var $this = $(this);
                if ( ! isIncluded($this)) {
                    if (stopBlocksMenu) {
                        return;
                    }

                    $(this).highligther('highlight', {
                        cssClass: 'al-slot-highlighted'
                    });
                }
            })
            .click(function() {
                var $this = $(this);

                if ( ! isIncluded($this)) {
                    stopBlocksMenu = true;
                    $('#al_old_slots').position({
                            my: "right top",
                            at: "right bottom",
                            of: $this
                        })
                        .show()
                        .css('visibility', 'visible')
                        .data('parent', $this)
                    ;

                    $('#al-undo-slot-assignment').data('html', $this.html());
                    $(this).highligther('activate',   {
                        cssClass: 'al-slot-highlighted',
                        toggleClass: 'al-slot-editing'
                    });
                }

                return false;
            });

            initCommands();

            return this;
        },
        stop: function()
        {
            $(this).unbind();
            $('#al_old_slots').find('.al-slot').unbind();
            $('#al-undo-slot-assignment').unbind();
            $('#al-close-slots-panel').unbind();
            $('#al-save-slot-assignment').unbind();
            close();
        }
    };

    function isIncluded(element) {
        return (element.is('[data-included="1"]')) ? true : false;
    }

    function close() {
        $('#al_old_slots').css('visibility', 'hidden');
        var parent = $('#al_old_slots').data('parent');
        if (parent != null) {
            parent.highligther('deactivate');
        }
        stopBlocksMenu = false;
    }

    function initCommands() {
        $('#al_old_slots').find('.al-slot').unbind().click(function(){
            var $this = $(this);
            $('#al-save-slot-assignment').data('slot', $this.attr('data-slot-name'));
            $('#al_old_slots').data('parent').html($this.attr('data-content'));

            return false;
        });

        $('#al-undo-slot-assignment').unbind().click(function(){
            $('#al_old_slots').data('parent').html($(this).data('html'));

            return false;
        });

        $('#al-close-slots-panel').unbind().click(function(){
            close();

            return false;
        });

        $('#al-save-slot-assignment').click(function(){
            try{
                var $this = $(this);
                $.ajax({
                    type: 'POST',
                    url: frontController + 'backend/' + $('#al_available_languages option:selected').val() + '/al_changeSlot',
                    data: {
                        'pageId' :  $('#al_pages_navigator').attr('rel'),
                        'languageId' : $('#al_languages_navigator').attr('rel'),
                        'sourceSlotName' : $this.data('slot'),
                        'targetSlotName' : $('#al_old_slots').data('parent').attr('data-slot-name')
                    },
                    beforeSend: function()
                    {
                        $('body').AddAjaxLoader();
                    },
                    success: function(response)
                    {
                        $(response).each(function(key, item)
                        {
                            switch(item.key)
                            {
                                case "message":
                                    $('body').showAlert(item.value);

                                    break;
                                case "slots":
                                    $('#al_old_slots').html(item.value);
                                    initCommands();

                                    break;
                            }
                        });

                        close();
                    },
                    error: function(err)
                    {
                        $('body').showAlert(err.responseText, 0, 'alert-error alert-danger');
                    },
                    complete: function()
                    {
                        $('body').RemoveAjaxLoader();
                    }
                });
            }
            catch(e){
                $('body').showAlert('An unespected error occoured in al-theme file while saving slots. Here is the error from the server:

' + e + '

Please open an issue at Github reporting this entire message.', 0, 'alert-error alert-danger');
            }

            return false;
        });
    }

    $.fn.changeTheme = function( method, options )
    {
        if ( methods[method] ) {
            return methods[ method ].apply( this, Array.prototype.slice.call( arguments, 1 ));
        } else if ( typeof method === 'object' || ! method ) {
            return methods.init.apply( this, arguments );
        } else {
            $.error( 'Method ' +  method + ' does not exist on jQuery.changeTheme' );
        }
    };
})($);

(function($){
    var methods = {
        change: function()
        {
            this.each(function()
            {
                $(this).click(function()
                {
                    try{
                        $.ajax({
                            type: 'POST',
                            url: frontController + 'backend/' + $('#al_available_languages option:selected').val() + '/al_showThemeChanger',
                            data: {
                                'themeName' : $(this).attr('data-theme-name')
                            },
                            beforeSend: function()
                            {
                                $('body').AddAjaxLoader();
                            },
                            success: function(html)
                            {
                                $('body').showDialog(html, {width:300, buttons: null});
                            },
                            error: function(err)
                            {
                                $('body').showDialog(err);
                            },
                            complete: function()
                            {
                                $('body').RemoveAjaxLoader();
                            }
                        });
                    }
                    catch(e){
                        $('body').showAlert('An unespected error occoured in al-theme file method change. Here is the error from the server:

' + e + '

Please open an issue at Github reporting this entire message.', 0, 'alert-error alert-danger');
                    }

                    return false;
                });
            });
        },
        scratch: function()
        {
            this.each(function()
            {
                $(this).click(function()
                {
                    if ( ! confirm(translate('WARNING: this command will destroy all the saved data and start a new site base on the choosen theme from the scratch: are you sure to continue?'))) {
                        return false;
                    }

                    try {
                        var themeName = $(this).attr('data-theme-name');

                        $.ajax({
                            type: 'POST',
                            url: frontController + 'backend/' + $('#al_available_languages option:selected').val() + '/startFromTheme',
                            data: {
                                'themeName' : themeName
                            },
                            beforeSend: function()
                            {
                                $('body').AddAjaxLoader();
                            },
                            success: function(html)
                            {
                                $('body').showAlert(html);
                                Navigate($('#al_languages_navigator').html(), $('#al_pages_navigator').html());
                            },
                            error: function(err)
                            {
                                $('body').showAlert(err.responseText, 0, 'alert-error alert-danger');
                            },
                            complete: function()
                            {
                                $('body').RemoveAjaxLoader();
                            }
                        });
                    }
                    catch(e){
                        $('body').showAlert('An unespected error occoured in al-theme file method scratch. Here is the error from the server:

' + e + '

Please open an issue at Github reporting this entire message.', 0, 'alert-error alert-danger');
                    }

                    return false;
                });
            });
        }
    };

    $.fn.manageTheme = function( method, options )
    {
        if ( methods[method] ) {
            return methods[ method ].apply( this, Array.prototype.slice.call( arguments, 1 ));
        } else if ( typeof method === 'object' || ! method ) {
            return methods.init.apply( this, arguments );
        } else {
            $.error( 'Method ' +  method + ' does not exist on jQuery.manageTheme' );
        }
    };

})($);

(function($){
    var methods = {
        load: function() {
            location.href = frontController + 'backend/' + $('#al-language').val() + '/al_previewTheme/' + $('#al-language').val() + '/' + $('#al-page').val() + '/' + $('#al-theme').val() + '/' + $(this).attr('rel');
        }
    };

    $.fn.template = function( method, options )
    {
        if ( methods[method] ) {
            return methods[ method ].apply( this, Array.prototype.slice.call( arguments, 1 ));
        } else if ( typeof method === 'object' || ! method ) {
            return methods.init.apply( this, arguments );
        } else {
            $.error( 'Method ' +  method + ' does not exist on jQuery.template' );
        }
    };

})($);

ObserveThemeCommands = function()
{
    try {
        $('.al_themes_changer').unbind().manageTheme('change');
        $('.al_start_from_theme').unbind().manageTheme('scratch');
    } catch (e) {}
};
<commit_msg>improved and refactored the manageTheme plugin<commit_after>/*
 * This file is part of the RedKiteCmsBunde Application and it is distributed
 * under the GPL LICENSE Version 2.0. To use this application you must leave
 * intact this copyright notice.
 *
 * Copyright (c) RedKite Labs <webmaster@redkite-labs.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 *
 * For extra documentation and help please visit http://www.redkite-labs.com
 *
 * @license    GPL LICENSE Version 2.0
 *
 */

;(function($){
    var methods = {
        start: function()
        {
            stopBlocksMenu = false;
            $(this).mouseenter(function(event) {
                var $this = $(this);
                if ( ! isIncluded($this)) {
                    if (stopBlocksMenu) {
                        return;
                    }

                    $(this).highligther('highlight', {
                        cssClass: 'al-slot-highlighted'
                    });
                }
            })
            .click(function() {
                var $this = $(this);

                if ( ! isIncluded($this)) {
                    stopBlocksMenu = true;
                    $('#al_old_slots').position({
                            my: "right top",
                            at: "right bottom",
                            of: $this
                        })
                        .show()
                        .css('visibility', 'visible')
                        .data('parent', $this)
                    ;

                    $('#al-undo-slot-assignment').data('html', $this.html());
                    $(this).highligther('activate',   {
                        cssClass: 'al-slot-highlighted',
                        toggleClass: 'al-slot-editing'
                    });
                }

                return false;
            });

            initCommands();

            return this;
        },
        stop: function()
        {
            $(this).unbind();
            $('#al_old_slots').find('.al-slot').unbind();
            $('#al-undo-slot-assignment').unbind();
            $('#al-close-slots-panel').unbind();
            $('#al-save-slot-assignment').unbind();
            close();
        }
    };

    function isIncluded(element) {
        return (element.is('[data-included="1"]')) ? true : false;
    }

    function close() {
        $('#al_old_slots').css('visibility', 'hidden');
        var parent = $('#al_old_slots').data('parent');
        if (parent != null) {
            parent.highligther('deactivate');
        }
        stopBlocksMenu = false;
    }

    function initCommands() {
        $('#al_old_slots').find('.al-slot').unbind().click(function(){
            var $this = $(this);
            $('#al-save-slot-assignment').data('slot', $this.attr('data-slot-name'));
            $('#al_old_slots').data('parent').html($this.attr('data-content'));

            return false;
        });

        $('#al-undo-slot-assignment').unbind().click(function(){
            $('#al_old_slots').data('parent').html($(this).data('html'));

            return false;
        });

        $('#al-close-slots-panel').unbind().click(function(){
            close();

            return false;
        });

        $('#al-save-slot-assignment').click(function(){
            try{
                var $this = $(this);
                $.ajax({
                    type: 'POST',
                    url: frontController + 'backend/' + $('#al_available_languages option:selected').val() + '/al_changeSlot',
                    data: {
                        'pageId' :  $('#al_pages_navigator').attr('rel'),
                        'languageId' : $('#al_languages_navigator').attr('rel'),
                        'sourceSlotName' : $this.data('slot'),
                        'targetSlotName' : $('#al_old_slots').data('parent').attr('data-slot-name')
                    },
                    beforeSend: function()
                    {
                        $('body').AddAjaxLoader();
                    },
                    success: function(response)
                    {
                        $(response).each(function(key, item)
                        {
                            switch(item.key)
                            {
                                case "message":
                                    $('body').showAlert(item.value);

                                    break;
                                case "slots":
                                    $('#al_old_slots').html(item.value);
                                    initCommands();

                                    break;
                            }
                        });

                        close();
                    },
                    error: function(err)
                    {
                        $('body').showAlert(err.responseText, 0, 'alert-error alert-danger');
                    },
                    complete: function()
                    {
                        $('body').RemoveAjaxLoader();
                    }
                });
            }
            catch(e){
                $('body').showAlert('An unespected error occoured in al-theme file while saving slots. Here is the error from the server:

' + e + '

Please open an issue at Github reporting this entire message.', 0, 'alert-error alert-danger');
            }

            return false;
        });
    }

    $.fn.changeTheme = function( method, options )
    {
        if ( methods[method] ) {
            return methods[ method ].apply( this, Array.prototype.slice.call( arguments, 1 ));
        } else if ( typeof method === 'object' || ! method ) {
            return methods.init.apply( this, arguments );
        } else {
            $.error( 'Method ' +  method + ' does not exist on jQuery.changeTheme' );
        }
    };
})($);

(function($){
    var methods = {
        init: function()
        {
            $('.al_themes_changer').unbind().manageTheme('change');
            $('.al_start_from_theme').unbind().manageTheme('scratch');
        },
        change: function()
        {
            $(this).click(function()
            {
                try{
                    $.ajax({
                        type: 'POST',
                        url: frontController + 'backend/' + $('#al_available_languages option:selected').val() + '/al_showThemeChanger',
                        data: {
                            'themeName' : $(this).attr('data-theme-name')
                        },
                        beforeSend: function()
                        {
                            $('body').AddAjaxLoader();
                        },
                        success: function(html)
                        {
                            $('body').showDialog(html, {width:300, buttons: null});
                        },
                        error: function(err)
                        {
                            $('body').showAlert(err.responseText, 0, 'alert-error alert-danger');
                        },
                        complete: function()
                        {
                            $('body').RemoveAjaxLoader();
                        }
                    });
                }
                catch(e){
                    $('body').showAlert('An unespected error occoured in al-theme file method change. Here is the error from the server:

' + e + '

Please open an issue at Github reporting this entire message.', 0, 'alert-error alert-danger');
                }

                return false;
            });
        },
        scratch: function()
        {
            $(this).click(function()
            {
                if ( ! confirm(translate('WARNING: this command will destroy all the saved data and start a new site base on the choosen theme from the scratch: are you sure to continue?'))) {
                    return false;
                }

                try {
                    var themeName = $(this).attr('data-theme-name');

                    $.ajax({
                        type: 'POST',
                        url: frontController + 'backend/' + $('#al_available_languages option:selected').val() + '/startFromTheme',
                        data: {
                            'themeName' : themeName
                        },
                        beforeSend: function()
                        {
                            $('body').AddAjaxLoader();
                        },
                        success: function(html)
                        {
                            $('body').showAlert(html);
                            Navigate($('#al_languages_navigator').html(), $('#al_pages_navigator').html());
                        },
                        error: function(err)
                        {
                            $('body').showAlert(err.responseText, 0, 'alert-error alert-danger');
                        },
                        complete: function()
                        {
                            $('body').RemoveAjaxLoader();
                        }
                    });
                }
                catch(e){
                    $('body').showAlert('An unespected error occoured in al-theme file method scratch. Here is the error from the server:

' + e + '

Please open an issue at Github reporting this entire message.', 0, 'alert-error alert-danger');
                }

                return false;
            });
        }
    };

    $.fn.manageTheme = function( method, options )
    {
        if ( methods[method] ) {
            return methods[ method ].apply( this, Array.prototype.slice.call( arguments, 1 ));
        } else if ( typeof method === 'object' || ! method ) {
            return methods.init.apply( this, arguments );
        } else {
            $.error( 'Method ' +  method + ' does not exist on jQuery.manageTheme' );
        }
    };

})($);

(function($){
    var methods = {
        load: function() {
            location.href = frontController + 'backend/' + $('#al-language').val() + '/al_previewTheme/' + $('#al-language').val() + '/' + $('#al-page').val() + '/' + $('#al-theme').val() + '/' + $(this).attr('rel');
        }
    };

    $.fn.template = function( method, options )
    {
        if ( methods[method] ) {
            return methods[ method ].apply( this, Array.prototype.slice.call( arguments, 1 ));
        } else if ( typeof method === 'object' || ! method ) {
            return methods.init.apply( this, arguments );
        } else {
            $.error( 'Method ' +  method + ' does not exist on jQuery.template' );
        }
    };

})($);<|endoftext|>


<commit_before>var color = require('../config/color');

exports.parseEmoticons = parseEmoticons;

var emotes = {
	':absol:': 'http://cbc.pokecommunity.com/config/emoticons/absol.png',
	':arceus:': 'http://cbc.pokecommunity.com/config/emoticons/arceus.png',
	':armycat:': 'http://cbc.pokecommunity.com/config/emoticons/armycat.png',
	':azelf:': 'http://cbc.pokecommunity.com/config/emoticons/azelf.png',
	':bidoof:': 'http://cbc.pokecommunity.com/config/emoticons/bidoof.png',
	':bowie:': 'http://cbc.pokecommunity.com/config/emoticons/bowie.png',
	':castform:': 'http://cbc.pokecommunity.com/config/emoticons/castform.png',
	':catflip:': 'http://cbc.pokecommunity.com/config/emoticons/catflip.png',
	':charizard:': 'http://cbc.pokecommunity.com/config/emoticons/charizard.png',
	':clown:': 'http://cbc.pokecommunity.com/config/emoticons/clown.png',
	':cookie:': 'http://cbc.pokecommunity.com/config/emoticons/cookie.png',
	':dk:': 'http://cbc.pokecommunity.com/config/emoticons/dk.png',
	':electrode:': 'http://cbc.pokecommunity.com/config/emoticons/electrode.png',
	':espurr:': 'http://cbc.pokecommunity.com/config/emoticons/espurr.png',
	':flirt:': 'http://cbc.pokecommunity.com/config/emoticons/flirt.png',
	':gav:': 'http://cbc.pokecommunity.com/config/emoticons/gav.png',
	':gloom:': 'http://cbc.pokecommunity.com/config/emoticons/gloom.png',
	':growlithe:': 'http://cbc.pokecommunity.com/config/emoticons/growlithe.png',
	':hamster:': 'http://cbc.pokecommunity.com/config/emoticons/hamster.png',
	':helix:': 'http://cbc.pokecommunity.com/config/emoticons/helix.png',
	':houndoom:': 'http://cbc.pokecommunity.com/config/emoticons/houndoom.png',
	':jigglypuff:': 'http://cbc.pokecommunity.com/config/emoticons/jigglypuff.png',
	':jynx:': 'http://cbc.pokecommunity.com/config/emoticons/jynx.png',
	':kappa:': 'http://cbc.pokecommunity.com/config/emoticons/kappa.png',
	':keepo:': 'http://cbc.pokecommunity.com/config/emoticons/keepo.png',
	':kermit:': 'http://cbc.pokecommunity.com/config/emoticons/kermit.png',
	':kreygasm:': 'http://cbc.pokecommunity.com/config/emoticons/kreygasm.png',
	':lapras:': 'http://cbc.pokecommunity.com/config/emoticons/lapras.png',
	':lileep:': 'http://cbc.pokecommunity.com/config/emoticons/lileep.png',
	':ludicolo:': 'http://cbc.pokecommunity.com/config/emoticons/ludicolo.png',
	':luvdisc:': 'http://cbc.pokecommunity.com/config/emoticons/luvdisc.png',
	':magikarp:': 'http://cbc.pokecommunity.com/config/emoticons/magikarp.png',
	':meganium:': 'http://cbc.pokecommunity.com/config/emoticons/meganium.png',
	':meowstic:': 'http://cbc.pokecommunity.com/config/emoticons/meowstic.png',
	':meowsticf:': 'http://cbc.pokecommunity.com/config/emoticons/meowsticf.png',
	':metagross:': 'http://cbc.pokecommunity.com/config/emoticons/metagross.png',
	':moo:': 'http://cbc.pokecommunity.com/config/emoticons/moo.gif',
	':nw:': 'http://cbc.pokecommunity.com/config/emoticons/nw.gif',
	':oddish:': 'http://cbc.pokecommunity.com/config/emoticons/oddish.png',
	':pear:': 'http://cbc.pokecommunity.com/config/emoticons/pear.png',
	':pjsalt:': 'http://cbc.pokecommunity.com/config/emoticons/pjsalt.png',
	':pogchamp:': 'http://cbc.pokecommunity.com/config/emoticons/pogchamp.png',
	':potato:': 'http://cbc.pokecommunity.com/config/emoticons/potato.png',
	':psyduck:': 'http://cbc.pokecommunity.com/config/emoticons/psyduck.png',
	':pyoshi:': 'http://cbc.pokecommunity.com/config/emoticons/pyoshi.png',
	':seduce:': 'http://cbc.pokecommunity.com/config/emoticons/seduce.png',
	':senpai:': 'http://cbc.pokecommunity.com/config/emoticons/senpai.png',
	':sims:': 'http://cbc.pokecommunity.com/config/emoticons/sims.png',
	':slowpoke:': 'http://cbc.pokecommunity.com/config/emoticons/slowpoke.png',
	':snorlax:': 'http://cbc.pokecommunity.com/config/emoticons/snorlax.png',
	':spheal:': 'http://cbc.pokecommunity.com/config/emoticons/spheal.png',
	':sri:': 'http://cbc.pokecommunity.com/config/emoticons/sri.png',
	':strut:': 'http://cbc.pokecommunity.com/config/emoticons/strut.png',
	':suicune:': 'http://cbc.pokecommunity.com/config/emoticons/suicune.png',
	':superman:': 'http://cbc.pokecommunity.com/config/emoticons/superman.png',
	':sweep:': 'http://cbc.pokecommunity.com/config/emoticons/sweep.gif',
	':taco:': 'http://cbc.pokecommunity.com/config/emoticons/taco.png',
	':vulpix:': 'http://cbc.pokecommunity.com/config/emoticons/vulpix.png',
	':wave:': 'http://cbc.pokecommunity.com/config/emoticons/wave.gif',
	':weezing:': 'http://cbc.pokecommunity.com/config/emoticons/weezing.png',
	':why:': 'http://cbc.pokecommunity.com/config/emoticons/why.png',
	':wobbuffet:': 'http://cbc.pokecommunity.com/config/emoticons/wobbuffet.png',
	':wooper:': 'http://cbc.pokecommunity.com/config/emoticons/wooper.png',
	':wynaut:': 'http://cbc.pokecommunity.com/config/emoticons/wynaut.png',
	':y:': 'http://cbc.pokecommunity.com/config/emoticons/y.png',
	':yoshi:': 'http://cbc.pokecommunity.com/config/emoticons/yoshi.png'
};

var emotesKeys = Object.keys(emotes);
var patterns = [];
var metachars = /[[\]{}()*+?.\\|^$\-,&#\s]/g;

for (var i in emotes) {
	if (emotes.hasOwnProperty(i)) {
		patterns.push('(' + i.replace(metachars, '\\$&') + ')');
	}
}
var patternRegex = new RegExp(patterns.join('|'), 'g');

/**
 * Parse emoticons in message.
 *
 * @param {String} message
 * @param {Object} room
 * @param {Object} user
 * @param {Boolean} pm - returns a string if it is in private messages
 * @returns {Boolean|String}
 */
function parseEmoticons(message, room, user, pm) {
	if (typeof message !== 'string' || (!pm && room.disableEmoticons)) return false;

	var match = false;
	var len = emotesKeys.length;

	while (len--) {
		if (message && message.indexOf(emotesKeys[len]) >= 0) {
			match = true;
			break;
		}
	}

	if (!match) return false;

	// escape HTML
	message = Tools.escapeHTML(message);

	// add emotes
	message = message.replace(patternRegex, function (match) {
		var emote = emotes[match];
		if (match === ':gav:' || match === ':kermit:' || match === ':nw:' || match === ':superman:' || match === ':sweep:' || match === ':yoshi:') return typeof emote != 'undefined' ?
			'' :
			match;
		if (match === ':bowie:') return typeof emote != 'undefined' ?
			'' :
			match;
		if (match === ':catflip:') return typeof emote != 'undefined' ?
			'' :
			match;
		if (match === ':strut:') return typeof emote != 'undefined' ?
			'' :
			match;
		return typeof emote != 'undefined' ?
			'' :
			match;
	});

	// __italics__
	message = message.replace(/\_\_([^< ](?:[^<]*?[^< ])?)\_\_(?![^<]*?<\/a)/g, '$1');

	// **bold**
	message = message.replace(/\*\*([^< ](?:[^<]*?[^< ])?)\*\*/g, '$1');

	var group = user.getIdentity().charAt(0);
	if (room.auth) group = room.auth[user.userid] || group;

	var style = "background:none;border:0;padding:0 5px 0 0;font-family:Verdana,Helvetica,Arial,sans-serif;font-size:9pt;cursor:pointer";

	message = "
" + "" + group + "" + "<button name='parseCommand' value='/user " + user.name + "' style='" + style + "'>" + "" + user.name + ":" + "</button>" + message + "
";
	if (pm) return message;

	room.addRaw(message);

	return true;
}

/**
 * Create a two column table listing emoticons.
 *
 * @return {String} emotes table
 */
function create_table() {
	var emotes_name = Object.keys(emotes);
	var emotes_list = [];
	var emotes_group_list = [];
	var len = emotes_name.length;

	for (var i = 0; i < len; i++) {
		emotes_list.push("" +
			"" +
			emotes_name[i] + "	");
	}

	var emotes_list_right = emotes_list.splice(len / 2, len / 2);

	for (var i = 0; i < len / 2; i++) {
		var emote1 = emotes_list[i],
			emote2 = emotes_list_right[i];
		if (emote2) {
			emotes_group_list.push("
" + emote1 + emote2 + "
");
		} else {
			emotes_group_list.push("
" + emote1 + "
");
		}
	}

	return "
List of Emoticons" + "

" + "
" + emotes_group_list.join("") + "
" + "

";
}

var emotes_table = create_table();

exports.commands = {
	blockemote: 'blockemoticons',
	blockemotes: 'blockemoticons',
	blockemoticon: 'blockemoticons',
	blockemoticons: function (target, room, user) {
		if (user.blockEmoticons === (target || true)) return this.sendReply("You are already blocking emoticons in private messages! To unblock, use /unblockemoticons");
		user.blockEmoticons = true;
		return this.sendReply("You are now blocking emoticons in private messages.");
	},
	blockemoticonshelp: ["/blockemoticons - Blocks emoticons in private messages. Unblock them with /unblockemoticons."],

	unblockemote: 'unblockemoticons',
	unblockemotes: 'unblockemoticons',
	unblockemoticon: 'unblockemoticons',
	unblockemoticons: function (target, room, user) {
		if (!user.blockEmoticons) return this.sendReply("You are not blocking emoticons in private messages! To block, use /blockemoticons");
		user.blockEmoticons = false;
		return this.sendReply("You are no longer blocking emoticons in private messages.");
	},
	unblockemoticonshelp: ["/unblockemoticons - Unblocks emoticons in private messages. Block them with /blockemoticons."],

	emote: 'emoticons',
	emotes: 'emoticons',
	emoticon: 'emoticons',
	emoticons: function (target, room, user) {
		if (!this.canBroadcast()) return;
		this.sendReply("|raw|" + emotes_table);
	},
	emoticonshelp: ["/emoticons - Get a list of emoticons."],

	toggleemote: 'toggleemoticons',
	toggleemotes: 'toggleemoticons',
	toggleemoticons: function (target, room, user) {
		if (!this.can('warn', null, room)) return false;
		room.disableEmoticons = !room.disableEmoticons;
		this.sendReply("Disallowing emoticons is set to " + room.disableEmoticons + " in this room.");
		if (room.disableEmoticons) {
			this.add("|raw|
Emoticons are disabled!
Emoticons will not work.
");
		} else {
			this.add("|raw|
Emoticons are enabled!
Emoticons will work now.
");
		}
	},
	toggleemoticonshelp: ["/toggleemoticons - Toggle emoticons on or off."]
};
<commit_msg>Add new emoticons<commit_after>var color = require('../config/color');

exports.parseEmoticons = parseEmoticons;

var emotes = {
	':absol:': 'http://cbc.pokecommunity.com/config/emoticons/absol.png',
	':arceus:': 'http://cbc.pokecommunity.com/config/emoticons/arceus.png',
	':armycat:': 'http://cbc.pokecommunity.com/config/emoticons/armycat.png',
	':azelf:': 'http://cbc.pokecommunity.com/config/emoticons/azelf.png',
	':bidoof:': 'http://cbc.pokecommunity.com/config/emoticons/bidoof.png',
	':bowie:': 'http://cbc.pokecommunity.com/config/emoticons/bowie.png',
	':castform:': 'http://cbc.pokecommunity.com/config/emoticons/castform.png',
	':catflip:': 'http://cbc.pokecommunity.com/config/emoticons/catflip.png',
	':charizard:': 'http://cbc.pokecommunity.com/config/emoticons/charizard.png',
	':clown:': 'http://cbc.pokecommunity.com/config/emoticons/clown.png',
	':cookie:': 'http://cbc.pokecommunity.com/config/emoticons/cookie.png',
	':cthulhu:': 'http://cbc.pokecommunity.com/config/emoticons/cthulhu.png',
	':dedenne:': 'http://cbc.pokecommunity.com/config/emoticons/dedenne.png',
	':diddy:': 'http://cbc.pokecommunity.com/config/emoticons/diddy.png',
	':dk:': 'http://cbc.pokecommunity.com/config/emoticons/dk.png',
	':eevee:': 'http://cbc.pokecommunity.com/config/emoticons/eevee.png',
	':electrode:': 'http://cbc.pokecommunity.com/config/emoticons/electrode.png',
	':espurr:': 'http://cbc.pokecommunity.com/config/emoticons/espurr.png',
	':feebas:': 'http://cbc.pokecommunity.com/config/emoticons/feebas.png',
	':flirt:': 'http://cbc.pokecommunity.com/config/emoticons/flirt.png',
	':infernape:': 'http://cbc.pokecommunity.com/config/emoticons/infernape.png',
	':gav:': 'http://cbc.pokecommunity.com/config/emoticons/gav.png',
	':gloom:': 'http://cbc.pokecommunity.com/config/emoticons/gloom.png',
	':growlithe:': 'http://cbc.pokecommunity.com/config/emoticons/growlithe.png',
	':hamster:': 'http://cbc.pokecommunity.com/config/emoticons/hamster.png',
	':helix:': 'http://cbc.pokecommunity.com/config/emoticons/helix.png',
	':houndoom:': 'http://cbc.pokecommunity.com/config/emoticons/houndoom.png',
	':jigglypuff:': 'http://cbc.pokecommunity.com/config/emoticons/jigglypuff.png',
	':jynx:': 'http://cbc.pokecommunity.com/config/emoticons/jynx.png',
	':kappa:': 'http://cbc.pokecommunity.com/config/emoticons/kappa.png',
	':keepo:': 'http://cbc.pokecommunity.com/config/emoticons/keepo.png',
	':kermit:': 'http://cbc.pokecommunity.com/config/emoticons/kermit.png',
	':kreygasm:': 'http://cbc.pokecommunity.com/config/emoticons/kreygasm.png',
	':lapras:': 'http://cbc.pokecommunity.com/config/emoticons/lapras.png',
	':latias:': 'http://cbc.pokecommunity.com/config/emoticons/latias.png',
	':latios:': 'http://cbc.pokecommunity.com/config/emoticons/latios.png',
	':lickitung:': 'http://cbc.pokecommunity.com/config/emoticons/lickitung.png',
	':lileep:': 'http://cbc.pokecommunity.com/config/emoticons/lileep.png',
	':ludicolo:': 'http://cbc.pokecommunity.com/config/emoticons/ludicolo.png',
	':luvdisc:': 'http://cbc.pokecommunity.com/config/emoticons/luvdisc.png',
	':magikarp:': 'http://cbc.pokecommunity.com/config/emoticons/magikarp.png',
	':meganium:': 'http://cbc.pokecommunity.com/config/emoticons/meganium.png',
	':meowstic:': 'http://cbc.pokecommunity.com/config/emoticons/meowstic.png',
	':meowsticf:': 'http://cbc.pokecommunity.com/config/emoticons/meowsticf.png',
	':metagross:': 'http://cbc.pokecommunity.com/config/emoticons/metagross.png',
	':moo:': 'http://cbc.pokecommunity.com/config/emoticons/moo.gif',
	':mudkip:': 'http://cbc.pokecommunity.com/config/emoticons/mudkip.png',
	':nw:': 'http://cbc.pokecommunity.com/config/emoticons/nw.gif',
	':oddish:': 'http://cbc.pokecommunity.com/config/emoticons/oddish.png',
	':pachirisu:': 'http://cbc.pokecommunity.com/config/emoticons/pachirisu.png',
	':pear:': 'http://cbc.pokecommunity.com/config/emoticons/pear.png',
	':pjsalt:': 'http://cbc.pokecommunity.com/config/emoticons/pjsalt.png',
	':pogchamp:': 'http://cbc.pokecommunity.com/config/emoticons/pogchamp.png',
	':potato:': 'http://cbc.pokecommunity.com/config/emoticons/potato.png',
	':psyduck:': 'http://cbc.pokecommunity.com/config/emoticons/psyduck.png',
	':pyoshi:': 'http://cbc.pokecommunity.com/config/emoticons/pyoshi.png',
	':scizor:': 'http://cbc.pokecommunity.com/config/emoticons/scizor.png',
	':seduce:': 'http://cbc.pokecommunity.com/config/emoticons/seduce.png',
	':senpai:': 'http://cbc.pokecommunity.com/config/emoticons/senpai.png',
	':sims:': 'http://cbc.pokecommunity.com/config/emoticons/sims.png',
	':skarmory:': 'http://cbc.pokecommunity.com/config/emoticons/skarmory.png',
	':slowpoke:': 'http://cbc.pokecommunity.com/config/emoticons/slowpoke.png',
	':snivy:': 'http://cbc.pokecommunity.com/config/emoticons/snivy.png',
	':snorlax:': 'http://cbc.pokecommunity.com/config/emoticons/snorlax.png',
	':spheal:': 'http://cbc.pokecommunity.com/config/emoticons/spheal.png',
	':sri:': 'http://cbc.pokecommunity.com/config/emoticons/sri.png',
	':strut:': 'http://cbc.pokecommunity.com/config/emoticons/strut.png',
	':suicune:': 'http://cbc.pokecommunity.com/config/emoticons/suicune.png',
	':superman:': 'http://cbc.pokecommunity.com/config/emoticons/superman.png',
	':sweep:': 'http://cbc.pokecommunity.com/config/emoticons/sweep.gif',
	':taco:': 'http://cbc.pokecommunity.com/config/emoticons/taco.png',
	':victini:': 'http://cbc.pokecommunity.com/config/emoticons/victini.gif',
	':vulpix:': 'http://cbc.pokecommunity.com/config/emoticons/vulpix.png',
	':wave:': 'http://cbc.pokecommunity.com/config/emoticons/wave.gif',
	':weezing:': 'http://cbc.pokecommunity.com/config/emoticons/weezing.png',
	':why:': 'http://cbc.pokecommunity.com/config/emoticons/why.png',
	':wigglytuff:': 'http://cbc.pokecommunity.com/config/emoticons/wigglytuff.png',
	':wobbuffet:': 'http://cbc.pokecommunity.com/config/emoticons/wobbuffet.png',
	':wooper:': 'http://cbc.pokecommunity.com/config/emoticons/wooper.png',
	':wynaut:': 'http://cbc.pokecommunity.com/config/emoticons/wynaut.png',
	':y:': 'http://cbc.pokecommunity.com/config/emoticons/y.png',
	':yoshi:': 'http://cbc.pokecommunity.com/config/emoticons/yoshi.png'
};

var emotesKeys = Object.keys(emotes);
var patterns = [];
var metachars = /[[\]{}()*+?.\\|^$\-,&#\s]/g;

for (var i in emotes) {
	if (emotes.hasOwnProperty(i)) {
		patterns.push('(' + i.replace(metachars, '\\$&') + ')');
	}
}
var patternRegex = new RegExp(patterns.join('|'), 'g');

/**
 * Parse emoticons in message.
 *
 * @param {String} message
 * @param {Object} room
 * @param {Object} user
 * @param {Boolean} pm - returns a string if it is in private messages
 * @returns {Boolean|String}
 */
function parseEmoticons(message, room, user, pm) {
	if (typeof message !== 'string' || (!pm && room.disableEmoticons)) return false;

	var match = false;
	var len = emotesKeys.length;

	while (len--) {
		if (message && message.indexOf(emotesKeys[len]) >= 0) {
			match = true;
			break;
		}
	}

	if (!match) return false;

	// escape HTML
	message = Tools.escapeHTML(message);

	// add emotes
	message = message.replace(patternRegex, function (match) {
		var emote = emotes[match];
		if (match === ':gav:' || match === ':kermit:' || match === ':nw:' || match === ':superman:' || match === ':sweep:' || match === ':yoshi:') return typeof emote != 'undefined' ?
			'' :
			match;
		if (match === ':bowie:') return typeof emote != 'undefined' ?
			'' :
			match;
		if (match === ':catflip:') return typeof emote != 'undefined' ?
			'' :
			match;
		if (match === ':strut:') return typeof emote != 'undefined' ?
			'' :
			match;
		return typeof emote != 'undefined' ?
			'' :
			match;
	});

	// __italics__
	message = message.replace(/\_\_([^< ](?:[^<]*?[^< ])?)\_\_(?![^<]*?<\/a)/g, '$1');

	// **bold**
	message = message.replace(/\*\*([^< ](?:[^<]*?[^< ])?)\*\*/g, '$1');

	var group = user.getIdentity().charAt(0);
	if (room.auth) group = room.auth[user.userid] || group;

	var style = "background:none;border:0;padding:0 5px 0 0;font-family:Verdana,Helvetica,Arial,sans-serif;font-size:9pt;cursor:pointer";

	message = "
" + "" + group + "" + "<button name='parseCommand' value='/user " + user.name + "' style='" + style + "'>" + "" + user.name + ":" + "</button>" + message + "
";
	if (pm) return message;

	room.addRaw(message);

	return true;
}

/**
 * Create a two column table listing emoticons.
 *
 * @return {String} emotes table
 */
function create_table() {
	var emotes_name = Object.keys(emotes);
	var emotes_list = [];
	var emotes_group_list = [];
	var len = emotes_name.length;

	for (var i = 0; i < len; i++) {
		emotes_list.push("" +
			"" +
			emotes_name[i] + "	");
	}

	var emotes_list_right = emotes_list.splice(len / 2, len / 2);

	for (var i = 0; i < len / 2; i++) {
		var emote1 = emotes_list[i],
			emote2 = emotes_list_right[i];
		if (emote2) {
			emotes_group_list.push("
" + emote1 + emote2 + "
");
		} else {
			emotes_group_list.push("
" + emote1 + "
");
		}
	}

	return "
List of Emoticons" + "

" + "
" + emotes_group_list.join("") + "
" + "

";
}

var emotes_table = create_table();

exports.commands = {
	blockemote: 'blockemoticons',
	blockemotes: 'blockemoticons',
	blockemoticon: 'blockemoticons',
	blockemoticons: function (target, room, user) {
		if (user.blockEmoticons === (target || true)) return this.sendReply("You are already blocking emoticons in private messages! To unblock, use /unblockemoticons");
		user.blockEmoticons = true;
		return this.sendReply("You are now blocking emoticons in private messages.");
	},
	blockemoticonshelp: ["/blockemoticons - Blocks emoticons in private messages. Unblock them with /unblockemoticons."],

	unblockemote: 'unblockemoticons',
	unblockemotes: 'unblockemoticons',
	unblockemoticon: 'unblockemoticons',
	unblockemoticons: function (target, room, user) {
		if (!user.blockEmoticons) return this.sendReply("You are not blocking emoticons in private messages! To block, use /blockemoticons");
		user.blockEmoticons = false;
		return this.sendReply("You are no longer blocking emoticons in private messages.");
	},
	unblockemoticonshelp: ["/unblockemoticons - Unblocks emoticons in private messages. Block them with /blockemoticons."],

	emote: 'emoticons',
	emotes: 'emoticons',
	emoticon: 'emoticons',
	emoticons: function (target, room, user) {
		if (!this.canBroadcast()) return;
		this.sendReply("|raw|" + emotes_table);
	},
	emoticonshelp: ["/emoticons - Get a list of emoticons."],

	toggleemote: 'toggleemoticons',
	toggleemotes: 'toggleemoticons',
	toggleemoticons: function (target, room, user) {
		if (!this.can('warn', null, room)) return false;
		room.disableEmoticons = !room.disableEmoticons;
		this.sendReply("Disallowing emoticons is set to " + room.disableEmoticons + " in this room.");
		if (room.disableEmoticons) {
			this.add("|raw|
Emoticons are disabled!
Emoticons will not work.
");
		} else {
			this.add("|raw|
Emoticons are enabled!
Emoticons will work now.
");
		}
	},
	toggleemoticonshelp: ["/toggleemoticons - Toggle emoticons on or off."]
};
<|endoftext|>


<commit_before>import React from 'react';
import PropTypes from 'prop-types';
import { LearnMore } from 'react-components';

const CLASSES = {
    info: 'mb1 block-info-standard',
    warning: 'mb1 block-info-standard-warning',
    error: 'mb1 block-info-standard-error',
    success: 'mb1 block-info-standard-success'
};

const Alert = ({ type = 'info', children, learnMore, className }) => {
    return (
        <div className={CLASSES[type].concat(` ${className || ''}`)}>

{children}

            {learnMore ? (

                    <LearnMore url={learnMore} />

            ) : null}

    );
};

Alert.propTypes = {
    type: PropTypes.oneOf(['info', 'error', 'warning', 'success']),
    children: PropTypes.node.isRequired,
    className: PropTypes.string,
    learnMore: PropTypes.string
};

export default Alert;
<commit_msg>Fix alert block max width (#240)<commit_after>import React from 'react';
import PropTypes from 'prop-types';
import { LearnMore } from 'react-components';

const CLASSES = {
    info: 'mb1 block-info-standard',
    warning: 'mb1 block-info-standard-warning',
    error: 'mb1 block-info-standard-error',
    success: 'mb1 block-info-standard-success'
};

const Alert = ({ type = 'info', children, learnMore, className }) => {
    return (
        <div className={CLASSES[type].concat(` ${className || ''}`)}>

{children}

            {learnMore ? (

                    <LearnMore url={learnMore} />

            ) : null}

    );
};

Alert.propTypes = {
    type: PropTypes.oneOf(['info', 'error', 'warning', 'success']),
    children: PropTypes.node.isRequired,
    className: PropTypes.string,
    learnMore: PropTypes.string
};

export default Alert;
<|endoftext|>