<commit_before>/**
 * Main controller for Ghost frontend
 */

/*global require, module */

var moment      = require('moment'),
    rss         = require('../data/xml/rss'),
    _           = require('lodash'),
    Promise     = require('bluebird'),
    api         = require('../api'),
    config      = require('../config'),
    filters     = require('../filters'),
    template    = require('../helpers/template'),
    errors      = require('../errors'),
    routeMatch  = require('path-match')(),
    path        = require('path'),

    frontendControllers,
    staticPostPermalink;

// Cache static post permalink regex
staticPostPermalink = routeMatch('/:slug/:edit?');

function getPostPage(options) {
    return api.settings.read('postsPerPage').then(function (response) {
        var postPP = response.settings[0],
            postsPerPage = parseInt(postPP.value, 10);

        // No negative posts per page, must be number
        if (!isNaN(postsPerPage) && postsPerPage > 0) {
            options.limit = postsPerPage;
        }
        options.include = 'author,tags,fields';
        return api.posts.browse(options);
    });
}

function getTagAllPosts(tag) {
    return api.settings.read('postsPerPage').then(function (response) {
        var options = {
            page: 1,
            tag: tag,
            limit: 99,
        };
        options.include = 'author,tags,fields';
        return api.posts.browse(options);
    });
}

/**
 * formats variables for handlebars in multi-post contexts.
 * If extraValues are available, they are merged in the final value
 * @return {Object} containing page variables
 */
function formatPageResponse(posts, page, extraValues) {
    extraValues = extraValues || {};

    var resp = {
        posts: posts,
        pagination: page.meta.pagination
    };
    return _.extend(resp, extraValues);
}

/**
 * similar to formatPageResponse, but for single post pages
 * @return {Object} containing page variables
 */
function formatResponse(post) {
    return {
        post: post
    };
}

function handleError(next) {
    return function (err) {
        return next(err);
    };
}

function setResponseContext(req, res, data) {
    var contexts = [],
        pageParam = req.params.page !== undefined ? parseInt(req.params.page, 10) : 1,
        tagPattern = new RegExp('^\\/' + config.routeKeywords.tag + '\\/'),
        authorPattern = new RegExp('^\\/' + config.routeKeywords.author + '\\/'),
        privatePattern = new RegExp('^\\/' + config.routeKeywords.private + '\\/');

    // paged context
    if (!isNaN(pageParam) && pageParam > 1) {
        contexts.push('paged');
    }

    if (req.route.path === '/' + config.routeKeywords.page + '/:page/') {
        contexts.push('index');
    } else if (req.route.path === '/') {
        contexts.push('home');
        contexts.push('index');
    } else if (/\/rss\/(:page\/)?$/.test(req.route.path)) {
        contexts.push('rss');
    } else if (privatePattern.test(req.route.path)) {
        contexts.push('private');
    } else if (tagPattern.test(req.route.path)) {
        contexts.push('tag');
    } else if (authorPattern.test(req.route.path)) {
        contexts.push('author');
    } else if (data && data.post && data.post.page) {
        contexts.push('page');
    } else {
        contexts.push('post');
    }

    res.locals.context = contexts;
}

// Add Request context parameter to the data object
// to be passed down to the templates
function setReqCtx(req, data) {
    (Array.isArray(data) ? data : [data]).forEach(function (d) {
        d.secure = req.secure;
    });
}

/**
 * Returns the paths object of the active theme via way of a promise.
 * @return {Promise} The promise resolves with the value of the paths.
 */
function getActiveThemePaths() {
    return api.settings.read({
        key: 'activeTheme',
        context: {
            internal: true
        }
    }).then(function (response) {
        var activeTheme = response.settings[0],
            paths = config.paths.availableThemes[activeTheme.value];

        return paths;
    });
}

/*
* Sets the response context around a post and renders it
* with the current theme's post view. Used by post preview
* and single post methods.
* Returns a function that takes the post to be rendered.
*/
function renderPost(req, res) {
    return function (post) {
        return getActiveThemePaths().then(function (paths) {
            var view = template.getThemeViewForPost(paths, post),
                response = formatResponse(post);

            setResponseContext(req, res, response);
            res.render(view, response);
        });
    };
}

function renderChannel(channelOpts) {
    channelOpts = channelOpts || {};

    return function renderChannel(req, res, next) {
        var pageParam = req.params.page !== undefined ? parseInt(req.params.page, 10) : 1,
            options = {
                page: pageParam
            },
            hasSlug,
            filter, filterKey;

        // Add the slug if it exists in the route
        if (channelOpts.route.indexOf(':slug') !== -1) {
            options[channelOpts.name] = req.params.slug;
            hasSlug = true;
        }

        function createUrl(page) {
            var url = config.paths.subdir + channelOpts.route;

            if (hasSlug) {
                url = url.replace(':slug', options[channelOpts.name]);
            }

            if (page && page > 1) {
                url += 'page/' + page + '/';
            }

            return url;
        }

        if (isNaN(pageParam) || pageParam < 1 || (req.params.page !== undefined && pageParam === 1)) {
            return res.redirect(createUrl());
        }

        return getPostPage(options).then(function (page) {
            // If page is greater than number of pages we have, redirect to last page
            if (pageParam > page.meta.pagination.pages) {
                return res.redirect(createUrl(page.meta.pagination.pages));
            }

            setReqCtx(req, page.posts);
            if (channelOpts.filter && page.meta.filters[channelOpts.filter]) {
                filterKey = page.meta.filters[channelOpts.filter];
                filter = (_.isArray(filterKey)) ? filterKey[0] : filterKey;
                setReqCtx(req, filter);
            }

            filters.doFilter('prePostsRender', page.posts, res.locals).then(function (posts) {
                getActiveThemePaths().then(function (paths) {
                    var view = 'index',
                        result,
                        extra = {};

                    if (channelOpts.firstPageTemplate && paths.hasOwnProperty(channelOpts.firstPageTemplate + '.hbs')) {
                        view = (pageParam > 1) ? 'index' : channelOpts.firstPageTemplate;
                    } else if (channelOpts.slugTemplate) {
                        view = template.getThemeViewForChannel(paths, channelOpts.name, options[channelOpts.name]);
                    } else if (paths.hasOwnProperty(channelOpts.name + '.hbs')) {
                        view = channelOpts.name;
                    }

                    if (channelOpts.filter) {
                        extra[channelOpts.name] = (filterKey) ? filter : '';

                        if (!extra[channelOpts.name]) {
                            return next();
                        }

                        result = formatPageResponse(posts, page, extra);
                    } else {
                        result = formatPageResponse(posts, page);
                    }

                    setResponseContext(req, res);
                    res.render(view, result);
                });
            });
        }).catch(handleError(next));
    };
}

frontendControllers = {
    homepage: renderChannel({
        name: 'home',
        route: '/',
        firstPageTemplate: 'home'
    }),
    tag: renderChannel({
        name: 'tag',
        route: '/' + config.routeKeywords.tag + '/:slug/',
        filter: 'tags',
        slugTemplate: true
    }),
    author: renderChannel({
        name: 'author',
        route: '/' + config.routeKeywords.author + '/:slug/',
        filter: 'author',
        slugTemplate: true
    }),
    preview: function (req, res, next) {
        var params = {
                uuid: req.params.uuid,
                status: 'all',
                include: 'author,tags,fields'
            };

        api.posts.read(params).then(function (result) {
            var post = result.posts[0];

            if (!post) {
                return next();
            }

            if (post.status === 'published') {
                return res.redirect(301, config.urlFor('post', {post: post}));
            }

            setReqCtx(req, post);

            filters.doFilter('prePostsRender', post, res.locals)
                .then(renderPost(req, res));
        }).catch(function (err) {
            if (err.errorType === 'NotFoundError') {
                return next();
            }

            return handleError(next)(err);
        });
    },

    single: function (req, res, next) {
        var path = req.path,
            params,
            usingStaticPermalink = false;

        api.settings.read('permalinks').then(function (response) {
            var permalink = response.settings[0],
                editFormat,
                postLookup,
                match;

            editFormat = permalink.value[permalink.value.length - 1] === '/' ? ':edit?' : '/:edit?';

            // Convert saved permalink into a path-match function
            permalink = routeMatch(permalink.value + editFormat);
            match = permalink(path);

            // Check if the path matches the permalink structure.
            //
            // If there are no matches found we then
            // need to verify it's not a static post,
            // and test against that permalink structure.
            if (match === false) {
                match = staticPostPermalink(path);
                // If there are still no matches then return.
                if (match === false) {
                    // Reject promise chain with type 'NotFound'
                    return Promise.reject(new errors.NotFoundError());
                }

                usingStaticPermalink = true;
            }

            params = match;

            // Sanitize params we're going to use to lookup the post.
            postLookup = _.pick(params, 'slug', 'id');
            // Add author, tag and fields
            postLookup.include = 'author,tags,fields,next,previous';

            // Query database to find post
            return api.posts.read(postLookup);
        }).then(function (result) {
            var post = result.posts[0],
                slugDate = [],
                slugFormat = [];

            if (!post) {
                return next();
            }

            function render() {
                // If we're ready to render the page but the last param is 'edit' then we'll send you to the edit page.
                if (params.edit) {
                    params.edit = params.edit.toLowerCase();
                }
                if (params.edit === 'edit') {
                    return res.redirect(config.paths.subdir + '/ghost/editor/' + post.id + '/');
                } else if (params.edit !== undefined) {
                    // reject with type: 'NotFound'
                    return Promise.reject(new errors.NotFoundError());
                }

                setReqCtx(req, post);

                filters.doFilter('prePostsRender', post, res.locals)
                    .then(renderPost(req, res));
            }

            // If we've checked the path with the static permalink structure
            // then the post must be a static post.
            // If it is not then we must return.
            if (usingStaticPermalink) {
                if (post.page) {
                    return render();
                }

                return next();
            }

            // If there is an author parameter in the slug, check that the
            // post is actually written by the given author\
            if (params.author) {
                if (post.author.slug === params.author) {
                    return render();
                }
                return next();
            }

            // If there is any date based parameter in the slug
            // we will check it against the post published date
            // to verify it's correct.
            if (params.year || params.month || params.day) {
                if (params.year) {
                    slugDate.push(params.year);
                    slugFormat.push('YYYY');
                }

                if (params.month) {
                    slugDate.push(params.month);
                    slugFormat.push('MM');
                }

                if (params.day) {
                    slugDate.push(params.day);
                    slugFormat.push('DD');
                }

                slugDate = slugDate.join('/');
                slugFormat = slugFormat.join('/');

                if (slugDate === moment(post.published_at).format(slugFormat)) {
                    return render();
                }

                return next();
            }

            return render();
        }).catch(function (err) {
            // If we've thrown an error message
            // of type: 'NotFound' then we found
            // no path match.
            if (err.errorType === 'NotFoundError') {
                return next();
            }

            return handleError(next)(err);
        });
    },

    custom_project: function (req, res, next) {
        var tag = "project";

        return getTagAllPosts(tag).then(function (page) {
            setReqCtx(req, page.posts);
            if (page.meta.filters.tags) {
                setReqCtx(req, page.meta.filters.tags[0]);
            }

            // Render the page of posts
            filters.doFilter('prePostsRender', page.posts).then(function (posts) {
                getActiveThemePaths().then(function (paths) {
                    var customPageView = 'page-' + tag,
                        view = 'post',
                        result;

                    if (paths.hasOwnProperty(customPageView + '.hbs')) {
                        view = customPageView;
                    } else if (paths.hasOwnProperty('page.hbs')) {
                        view = 'page';
                    }
                    // Format data for template
                    result = formatPageResponse(posts, page, {
                        tag: page.meta.filters.tags ? page.meta.filters.tags[0] : ''
                    });

                    // If the resulting tag is '' then 404.
                    if (!result.tag) {
                        return next();
                    }
                    setResponseContext(req, res);
                    res.render(view, result);
                });
            });
        }).catch(handleError(next));
    },

    rss: rss,
    private: function (req, res) {
        var defaultPage = path.resolve(config.paths.adminViews, 'private.hbs');
        return getActiveThemePaths().then(function (paths) {
            var data = {};
            if (res.error) {
                data.error = res.error;
            }

            setResponseContext(req, res);
            if (paths.hasOwnProperty('private.hbs')) {
                return res.render('private', data);
            } else {
                return res.render(defaultPage, data);
            }
        });
    }
};

module.exports = frontendControllers;
<commit_msg>setup custom project page get StaticPages<commit_after>/**
 * Main controller for Ghost frontend
 */

/*global require, module */

var moment      = require('moment'),
    rss         = require('../data/xml/rss'),
    _           = require('lodash'),
    Promise     = require('bluebird'),
    api         = require('../api'),
    config      = require('../config'),
    filters     = require('../filters'),
    template    = require('../helpers/template'),
    errors      = require('../errors'),
    routeMatch  = require('path-match')(),
    path        = require('path'),

    frontendControllers,
    staticPostPermalink;

// Cache static post permalink regex
staticPostPermalink = routeMatch('/:slug/:edit?');

function getPostPage(options) {
    return api.settings.read('postsPerPage').then(function (response) {
        var postPP = response.settings[0],
            postsPerPage = parseInt(postPP.value, 10);

        // No negative posts per page, must be number
        if (!isNaN(postsPerPage) && postsPerPage > 0) {
            options.limit = postsPerPage;
        }
        options.include = 'author,tags,fields';
        return api.posts.browse(options);
    });
}

function getTagAllPosts(tag, isStaticPages) {
    return api.settings.read('postsPerPage').then(function (response) {
        var options = {
            page: 1,
            tag: tag,
            limit: 99,
            staticPages: isStaticPages
        };
        options.include = 'author,tags,fields';
        return api.posts.browse(options);
    });
}

/**
 * formats variables for handlebars in multi-post contexts.
 * If extraValues are available, they are merged in the final value
 * @return {Object} containing page variables
 */
function formatPageResponse(posts, page, extraValues) {
    extraValues = extraValues || {};

    var resp = {
        posts: posts,
        pagination: page.meta.pagination
    };
    return _.extend(resp, extraValues);
}

/**
 * similar to formatPageResponse, but for single post pages
 * @return {Object} containing page variables
 */
function formatResponse(post) {
    return {
        post: post
    };
}

function handleError(next) {
    return function (err) {
        return next(err);
    };
}

function setResponseContext(req, res, data) {
    var contexts = [],
        pageParam = req.params.page !== undefined ? parseInt(req.params.page, 10) : 1,
        tagPattern = new RegExp('^\\/' + config.routeKeywords.tag + '\\/'),
        authorPattern = new RegExp('^\\/' + config.routeKeywords.author + '\\/'),
        privatePattern = new RegExp('^\\/' + config.routeKeywords.private + '\\/');

    // paged context
    if (!isNaN(pageParam) && pageParam > 1) {
        contexts.push('paged');
    }

    if (req.route.path === '/' + config.routeKeywords.page + '/:page/') {
        contexts.push('index');
    } else if (req.route.path === '/') {
        contexts.push('home');
        contexts.push('index');
    } else if (/\/rss\/(:page\/)?$/.test(req.route.path)) {
        contexts.push('rss');
    } else if (privatePattern.test(req.route.path)) {
        contexts.push('private');
    } else if (tagPattern.test(req.route.path)) {
        contexts.push('tag');
    } else if (authorPattern.test(req.route.path)) {
        contexts.push('author');
    } else if (data && data.post && data.post.page) {
        contexts.push('page');
    } else {
        contexts.push('post');
    }

    res.locals.context = contexts;
}

// Add Request context parameter to the data object
// to be passed down to the templates
function setReqCtx(req, data) {
    (Array.isArray(data) ? data : [data]).forEach(function (d) {
        d.secure = req.secure;
    });
}

/**
 * Returns the paths object of the active theme via way of a promise.
 * @return {Promise} The promise resolves with the value of the paths.
 */
function getActiveThemePaths() {
    return api.settings.read({
        key: 'activeTheme',
        context: {
            internal: true
        }
    }).then(function (response) {
        var activeTheme = response.settings[0],
            paths = config.paths.availableThemes[activeTheme.value];

        return paths;
    });
}

/*
* Sets the response context around a post and renders it
* with the current theme's post view. Used by post preview
* and single post methods.
* Returns a function that takes the post to be rendered.
*/
function renderPost(req, res) {
    return function (post) {
        return getActiveThemePaths().then(function (paths) {
            var view = template.getThemeViewForPost(paths, post),
                response = formatResponse(post);

            setResponseContext(req, res, response);
            res.render(view, response);
        });
    };
}

function renderChannel(channelOpts) {
    channelOpts = channelOpts || {};

    return function renderChannel(req, res, next) {
        var pageParam = req.params.page !== undefined ? parseInt(req.params.page, 10) : 1,
            options = {
                page: pageParam
            },
            hasSlug,
            filter, filterKey;

        // Add the slug if it exists in the route
        if (channelOpts.route.indexOf(':slug') !== -1) {
            options[channelOpts.name] = req.params.slug;
            hasSlug = true;
        }

        function createUrl(page) {
            var url = config.paths.subdir + channelOpts.route;

            if (hasSlug) {
                url = url.replace(':slug', options[channelOpts.name]);
            }

            if (page && page > 1) {
                url += 'page/' + page + '/';
            }

            return url;
        }

        if (isNaN(pageParam) || pageParam < 1 || (req.params.page !== undefined && pageParam === 1)) {
            return res.redirect(createUrl());
        }

        return getPostPage(options).then(function (page) {
            // If page is greater than number of pages we have, redirect to last page
            if (pageParam > page.meta.pagination.pages) {
                return res.redirect(createUrl(page.meta.pagination.pages));
            }

            setReqCtx(req, page.posts);
            if (channelOpts.filter && page.meta.filters[channelOpts.filter]) {
                filterKey = page.meta.filters[channelOpts.filter];
                filter = (_.isArray(filterKey)) ? filterKey[0] : filterKey;
                setReqCtx(req, filter);
            }

            filters.doFilter('prePostsRender', page.posts, res.locals).then(function (posts) {
                getActiveThemePaths().then(function (paths) {
                    var view = 'index',
                        result,
                        extra = {};

                    if (channelOpts.firstPageTemplate && paths.hasOwnProperty(channelOpts.firstPageTemplate + '.hbs')) {
                        view = (pageParam > 1) ? 'index' : channelOpts.firstPageTemplate;
                    } else if (channelOpts.slugTemplate) {
                        view = template.getThemeViewForChannel(paths, channelOpts.name, options[channelOpts.name]);
                    } else if (paths.hasOwnProperty(channelOpts.name + '.hbs')) {
                        view = channelOpts.name;
                    }

                    if (channelOpts.filter) {
                        extra[channelOpts.name] = (filterKey) ? filter : '';

                        if (!extra[channelOpts.name]) {
                            return next();
                        }

                        result = formatPageResponse(posts, page, extra);
                    } else {
                        result = formatPageResponse(posts, page);
                    }

                    setResponseContext(req, res);
                    res.render(view, result);
                });
            });
        }).catch(handleError(next));
    };
}

frontendControllers = {
    homepage: renderChannel({
        name: 'home',
        route: '/',
        firstPageTemplate: 'home'
    }),
    tag: renderChannel({
        name: 'tag',
        route: '/' + config.routeKeywords.tag + '/:slug/',
        filter: 'tags',
        slugTemplate: true
    }),
    author: renderChannel({
        name: 'author',
        route: '/' + config.routeKeywords.author + '/:slug/',
        filter: 'author',
        slugTemplate: true
    }),
    preview: function (req, res, next) {
        var params = {
                uuid: req.params.uuid,
                status: 'all',
                include: 'author,tags,fields'
            };

        api.posts.read(params).then(function (result) {
            var post = result.posts[0];

            if (!post) {
                return next();
            }

            if (post.status === 'published') {
                return res.redirect(301, config.urlFor('post', {post: post}));
            }

            setReqCtx(req, post);

            filters.doFilter('prePostsRender', post, res.locals)
                .then(renderPost(req, res));
        }).catch(function (err) {
            if (err.errorType === 'NotFoundError') {
                return next();
            }

            return handleError(next)(err);
        });
    },

    single: function (req, res, next) {
        var path = req.path,
            params,
            usingStaticPermalink = false;

        api.settings.read('permalinks').then(function (response) {
            var permalink = response.settings[0],
                editFormat,
                postLookup,
                match;

            editFormat = permalink.value[permalink.value.length - 1] === '/' ? ':edit?' : '/:edit?';

            // Convert saved permalink into a path-match function
            permalink = routeMatch(permalink.value + editFormat);
            match = permalink(path);

            // Check if the path matches the permalink structure.
            //
            // If there are no matches found we then
            // need to verify it's not a static post,
            // and test against that permalink structure.
            if (match === false) {
                match = staticPostPermalink(path);
                // If there are still no matches then return.
                if (match === false) {
                    // Reject promise chain with type 'NotFound'
                    return Promise.reject(new errors.NotFoundError());
                }

                usingStaticPermalink = true;
            }

            params = match;

            // Sanitize params we're going to use to lookup the post.
            postLookup = _.pick(params, 'slug', 'id');
            // Add author, tag and fields
            postLookup.include = 'author,tags,fields,next,previous';
            // Query database to find post
            return api.posts.read(postLookup);
        }).then(function (result) {
            var post = result.posts[0],
                slugDate = [],
                slugFormat = [];

            if (!post) {
                return next();
            }

            function render() {
                // If we're ready to render the page but the last param is 'edit' then we'll send you to the edit page.
                if (params.edit) {
                    params.edit = params.edit.toLowerCase();
                }
                if (params.edit === 'edit') {
                    return res.redirect(config.paths.subdir + '/ghost/editor/' + post.id + '/');
                } else if (params.edit !== undefined) {
                    // reject with type: 'NotFound'
                    return Promise.reject(new errors.NotFoundError());
                }

                setReqCtx(req, post);

                filters.doFilter('prePostsRender', post, res.locals)
                    .then(renderPost(req, res));
            }

            // If we've checked the path with the static permalink structure
            // then the post must be a static post.
            // If it is not then we must return.
            if (usingStaticPermalink) {
                if (post.page) {
                    return render();
                }

                return next();
            }

            // If there is an author parameter in the slug, check that the
            // post is actually written by the given author\
            if (params.author) {
                if (post.author.slug === params.author) {
                    return render();
                }
                return next();
            }

            // If there is any date based parameter in the slug
            // we will check it against the post published date
            // to verify it's correct.
            if (params.year || params.month || params.day) {
                if (params.year) {
                    slugDate.push(params.year);
                    slugFormat.push('YYYY');
                }

                if (params.month) {
                    slugDate.push(params.month);
                    slugFormat.push('MM');
                }

                if (params.day) {
                    slugDate.push(params.day);
                    slugFormat.push('DD');
                }

                slugDate = slugDate.join('/');
                slugFormat = slugFormat.join('/');

                if (slugDate === moment(post.published_at).format(slugFormat)) {
                    return render();
                }

                return next();
            }

            return render();
        }).catch(function (err) {
            // If we've thrown an error message
            // of type: 'NotFound' then we found
            // no path match.
            if (err.errorType === 'NotFoundError') {
                return next();
            }

            return handleError(next)(err);
        });
    },

    custom_project: function (req, res, next) {
        var tag = "project";

        return getTagAllPosts(tag, true).then(function (page) {
            setReqCtx(req, page.posts);
            if (page.meta.filters.tags) {
                setReqCtx(req, page.meta.filters.tags[0]);
            }

            // Render the page of posts
            filters.doFilter('prePostsRender', page.posts).then(function (posts) {
                getActiveThemePaths().then(function (paths) {
                    var customPageView = 'page-' + tag,
                        view = 'post',
                        result;

                    if (paths.hasOwnProperty(customPageView + '.hbs')) {
                        view = customPageView;
                    } else if (paths.hasOwnProperty('page.hbs')) {
                        view = 'page';
                    }
                    // Format data for template
                    result = formatPageResponse(posts, page, {
                        tag: page.meta.filters.tags ? page.meta.filters.tags[0] : ''
                    });

                    // If the resulting tag is '' then 404.
                    if (!result.tag) {
                        return next();
                    }
                    setResponseContext(req, res);
                    res.render(view, result);
                });
            });
        }).catch(handleError(next));
    },

    rss: rss,
    private: function (req, res) {
        var defaultPage = path.resolve(config.paths.adminViews, 'private.hbs');
        return getActiveThemePaths().then(function (paths) {
            var data = {};
            if (res.error) {
                data.error = res.error;
            }

            setResponseContext(req, res);
            if (paths.hasOwnProperty('private.hbs')) {
                return res.render('private', data);
            } else {
                return res.render(defaultPage, data);
            }
        });
    }
};

module.exports = frontendControllers;
<|endoftext|>


<commit_before>
// stomp-server/connection.js -- Definition of the Connection class

// Load modules
var events          = require('events'),
    frame           = require('./frame'),
    StringBuffer    = require('./stringbuffer').StringBuffer;

function Connection( stream, bufferLimit ) {
    var self = this;

    // Extend EventEmitter
    events.EventEmitter.call(this);

    // Set the buffer limit
    if( bufferLimit == null )
        bufferLimit = 65536;

    // Initialize members
    this._stream = stream;
    this._buf = new StringBuffer(bufferLimit);
    this.connected = false;
    this.secure = false;
    this.bufferLimit = bufferLimit;
    this.strict = false;

    // Configure basic event handlers
    this._stream.on('connect', function() { self.connected = true; self.emit('connect'); });
    this._stream.on('secure', function() { self.secure = true; } );
    this._stream.on('timeout', function() { self._stream.end(); self.emit('timeout'); });
    this._stream.on('end', function() { self._stream.end(); });
    this._stream.on('close', function (had_error) {
            self.connected = false;
            self.emit('close', had_error);
        });
    this._stream.on('error', function(exception) {
            self.emit('error', exception);
            if( self.strict ) self._stream.destroy();
        });

    // Define the packet serializer
    this._stream.on('data', function(data) {
            try {
                // Accumulate data in the buffer
                self._buf.write(data);

                // Extract frames
                var buffer = self._buf;
                do {
                    // Extract a single frame from the stream
                    var frame_obj = frame.fromBuffer(buffer);

                    // Emit the frame, if any
                    if( frame_obj != null )
                        self.emit('frame', frame_obj);
                } while( frame_obj != null );
            } catch( err ) {
                // Emit an error
                self.emit('error', err);

                // Close the connection if strict
                if( self.strict ) self._stream.destroy();
            };
        });

}

// Connection.send(frame_obj, cbk(err)
Connection.prototype.send = function(frame_obj) {
    this._stream.write(frame_obj.toBuffer());
};

// Export classes
module.exports.Connection = Connection;
<commit_msg>Emitting secure events for the Connection class<commit_after>
// stomp-server/connection.js -- Definition of the Connection class

// Load modules
var events          = require('events'),
    frame           = require('./frame'),
    StringBuffer    = require('./stringbuffer').StringBuffer;

function Connection( stream, bufferLimit ) {
    var self = this;

    // Extend EventEmitter
    events.EventEmitter.call(this);

    // Set the buffer limit
    if( bufferLimit == null )
        bufferLimit = 65536;

    // Initialize members
    this._stream = stream;
    this._buf = new StringBuffer(bufferLimit);
    this.connected = false;
    this.secure = false;
    this.bufferLimit = bufferLimit;
    this.strict = false;

    // Configure basic event handlers
    this._stream.on('connect', function() { self.connected = true; self.emit('connect'); });
    this._stream.on('secure', function() { self.secure = true; self.emit('secure');} );
    this._stream.on('timeout', function() { self._stream.end(); self.emit('timeout'); });
    this._stream.on('end', function() { self._stream.end(); });
    this._stream.on('close', function (had_error) {
            self.connected = false;
            self.emit('close', had_error);
        });
    this._stream.on('error', function(exception) {
            self.emit('error', exception);
            if( self.strict ) self._stream.destroy();
        });

    // Define the packet serializer
    this._stream.on('data', function(data) {
            try {
                // Accumulate data in the buffer
                self._buf.write(data);

                // Extract frames
                var buffer = self._buf;
                do {
                    // Extract a single frame from the stream
                    var frame_obj = frame.fromBuffer(buffer);

                    // Emit the frame, if any
                    if( frame_obj != null )
                        self.emit('frame', frame_obj);
                } while( frame_obj != null );
            } catch( err ) {
                // Emit an error
                self.emit('error', err);

                // Close the connection if strict
                if( self.strict ) self._stream.destroy();
            };
        });
}

// Connection.send(frame_obj, cbk(err)
Connection.prototype.send = function(frame_obj) {
    this._stream.write(frame_obj.toBuffer());
};

// Export classes
module.exports.Connection = Connection;
<|endoftext|>


<commit_before>/* Populate the IGT pane */
function populateIGTs(index, data) {
    var fl = $('#fine-list')
    fl.text('Loading...')
    $.ajax({
        url:'/populate/'+data['value'],
        error: populateError,
        success: populateSuccess
    })
}

function populateSuccess(r, stat, jqXHR) {
    $('#fine-list').html(r);
    $('#igtlist').datalist({
        lines:true
    });
}

function populateError() {
    $('#fine-lists').text("An error occurred.");
}

/* display a single IGT instance */
function displayIGT(corp_id, igt_id) {
    $('#editor-panel').text("Loading...");
    url = 'display/'+corp_id+'/'+igt_id
    $.ajax({
        url: url,
        success: displaySuccess,
        error: displayError,
        dataType: "text"
    });
}

function displaySuccess(r, stat, jqXHR) {
    $('#editor-panel').html(r);
}

function displayError(r, stat, jqXHR) {
    $('#editor-panel').text("An error occurred.");
}

function get_raw_lines() {
    lines = [];
    $('.raw-tier .textrow').each(function(i, el){
        linedata = {};
        linedata['tag'] = $(el).find('.tags').text();
        linedata['text'] = $(el).find('.text').text();
        lines.push(linedata);
    });
    return lines;
}

/* Retrieve Clean Tiers */
function get_tier_lines(rowSelector) {

    var lines = [];

    /* Iterate over all the clean items, and add them to the data */
    $(rowSelector).each(function(i, el) {

        linedata = {};

        linedata['tag'] = $(el).find('.tag-input').val();

        li = $(el).find('.line-input');
        linedata['text'] = li.val();
        linedata['id'] = li.attr('id');
        linedata['num'] = i+1;

        /* Skip the line if it's disabled */
        if (!li.attr('disabled')) {
            lines.push(linedata);
        }

    });

    return lines;
}

function get_clean_lines() {
    return get_tier_lines('.cleanrow');
}

function get_normal_lines() {
    return get_tier_lines('normalrow');
}

/* Normalization */
function normalizeIGT(corp_id, igt_id) {
    console.log('Normalizing '+igt_id);
    $('#normalized-contents').text('Loading...');

    cleanData = get_clean_lines();

    $.ajax({
        url: '/normalize/'+corp_id+'/'+igt_id,
        type: 'POST',
        dataType: 'text',
        contentType: 'text/plain',
        data: JSON.stringify(cleanData),
        success: normalizeSuccess,
        error: normalizeError
    });
}

function normalizeSuccess(r, stat, jqXHR) {
    $('#normalized-tier').show();
    $('#normalized-contents').html(r);
}

function normalizeError() {
    $('#normalized-contents').text("An error occured while normalizing.");
}

/* INTENT-ification */
function generateFromNormalized(corp_id, igt_id) {
    normalData = get_normal_lines();
    cleanData  = get_clean_lines();
    rawData    = get_raw_lines();

    data = {raw: rawData,
            clean: cleanData,
            normal: normalData}

    $.ajax({
        url: '/intentify/'+corp_id+'/'+igt_id,
        contentType: 'text/plain',
        type: 'POST',
        data: JSON.stringify(data),
        success: intentifySuccess,
        error: intentifyError
    });
}

function intentifySuccess(r, stat, jqXHR) {
    console.log(r);
}

function intentifyError() {
    $('#remaining-content').text("An error occurred producing the remaining tiers.")
}

/* Edit/Delete Scripts */
function deleteItem(itemId) {
    $(itemId).find('input').prop('disabled',true);
    $(itemId).css('background-color','pink');
}

function restoreItem(itemId) {
    $(itemId).find('input').prop('disabled',false);
    $(itemId).css('background-color', 'inherit');
}

function addItem(jqAfter) {
    numitems = $('.cleantable tr').length;

    id = 'c-'+(numitems+1).toString();

    jqAfter.after('
\
        \
            \
            \
            \
        	\
        \
            <input class="tag-input" type="text" value=""/>\
        	\
        \
            <input class="line-input" type="text" value=""/>\
        	\

');
}<commit_msg>Bugfix<commit_after>/* Populate the IGT pane */
function populateIGTs(index, data) {
    var fl = $('#fine-list')
    fl.text('Loading...')
    $.ajax({
        url:'/populate/'+data['value'],
        error: populateError,
        success: populateSuccess
    })
}

function populateSuccess(r, stat, jqXHR) {
    $('#fine-list').html(r);
    $('#igtlist').datalist({
        lines:true
    });
}

function populateError() {
    $('#fine-lists').text("An error occurred.");
}

/* display a single IGT instance */
function displayIGT(corp_id, igt_id) {
    $('#editor-panel').text("Loading...");
    url = 'display/'+corp_id+'/'+igt_id
    $.ajax({
        url: url,
        success: displaySuccess,
        error: displayError,
        dataType: "text"
    });
}

function displaySuccess(r, stat, jqXHR) {
    $('#editor-panel').html(r);
}

function displayError(r, stat, jqXHR) {
    $('#editor-panel').text("An error occurred.");
}

function get_raw_lines() {
    lines = [];
    $('.raw-tier .textrow').each(function(i, el){
        linedata = {};
        linedata['tag'] = $(el).find('.tags').text();
        linedata['text'] = $(el).find('.text').text();
        lines.push(linedata);
    });
    return lines;
}

/* Retrieve Clean Tiers */
function get_tier_lines(rowSelector) {

    var lines = [];

    /* Iterate over all the clean items, and add them to the data */
    $(rowSelector).each(function(i, el) {

        linedata = {};

        linedata['tag'] = $(el).find('.tag-input').val();

        li = $(el).find('.line-input');
        linedata['text'] = li.val();
        linedata['id'] = li.attr('id');
        linedata['num'] = i+1;

        /* Skip the line if it's disabled */
        if (!li.attr('disabled')) {
            lines.push(linedata);
        }

    });

    return lines;
}

function get_clean_lines() {
    return get_tier_lines('.cleanrow');
}

function get_normal_lines() {
    return get_tier_lines('.normalrow');
}

/* Normalization */
function normalizeIGT(corp_id, igt_id) {
    console.log('Normalizing '+igt_id);
    $('#normalized-contents').text('Loading...');

    cleanData = get_clean_lines();

    $.ajax({
        url: '/normalize/'+corp_id+'/'+igt_id,
        type: 'POST',
        dataType: 'text',
        contentType: 'text/plain',
        data: JSON.stringify(cleanData),
        success: normalizeSuccess,
        error: normalizeError
    });
}

function normalizeSuccess(r, stat, jqXHR) {
    $('#normalized-tier').show();
    $('#normalized-contents').html(r);
}

function normalizeError() {
    $('#normalized-contents').text("An error occured while normalizing.");
}

/* INTENT-ification */
function generateFromNormalized(corp_id, igt_id) {
    normalData = get_normal_lines();
    cleanData  = get_clean_lines();
    rawData    = get_raw_lines();

    data = {raw: rawData,
            clean: cleanData,
            normal: normalData}

    $.ajax({
        url: '/intentify/'+corp_id+'/'+igt_id,
        contentType: 'text/plain',
        type: 'POST',
        data: JSON.stringify(data),
        success: intentifySuccess,
        error: intentifyError
    });
}

function intentifySuccess(r, stat, jqXHR) {
    console.log(r);
}

function intentifyError() {
    $('#remaining-content').text("An error occurred producing the remaining tiers.")
}

/* Edit/Delete Scripts */
function deleteItem(itemId) {
    $(itemId).find('input').prop('disabled',true);
    $(itemId).css('background-color','pink');
}

function restoreItem(itemId) {
    $(itemId).find('input').prop('disabled',false);
    $(itemId).css('background-color', 'inherit');
}

function addItem(jqAfter) {
    numitems = $('.cleantable tr').length;

    id = 'c-'+(numitems+1).toString();

    jqAfter.after('
\
        \
            \
            \
            \
        	\
        \
            <input class="tag-input" type="text" value=""/>\
        	\
        \
            <input class="line-input" type="text" value=""/>\
        	\

');
}<|endoftext|>


<commit_before>const fs = require('fs-extra')
const path = require('path')

module.exports = function nuxtAxios(options) {
  // Don't include on dev mode
  if (this.options.dev && process.env.NODE_ENV !== 'production') {
    return
  }

  // Add google analytics script to head
  this.options.head.script.push({
    src: options.analyticsURL || 'https://www.google-analytics.com/analytics.js',
    async: true
  })

  // Register plugin
  this.addPlugin({src: path.resolve(__dirname, 'plugin.js'), ssr: false, options})
}

module.exports.meta = require('./package.json')
<commit_msg>fix(google-analytics): function name typo<commit_after>const fs = require('fs-extra')
const path = require('path')

module.exports = function nuxtAnalytics(options) {
  // Don't include on dev mode
  if (this.options.dev && process.env.NODE_ENV !== 'production') {
    return
  }

  // Add google analytics script to head
  this.options.head.script.push({
    src: options.analyticsURL || 'https://www.google-analytics.com/analytics.js',
    async: true
  })

  // Register plugin
  this.addPlugin({src: path.resolve(__dirname, 'plugin.js'), ssr: false, options})
}

module.exports.meta = require('./package.json')
<|endoftext|>


<commit_before>import React, { Component } from 'react';
import PropTypes from 'prop-types';

import {
  StyleSheet,
  View,
  Text,
  TouchableOpacity,
  Keyboard,
  ViewPropTypes,
} from 'react-native';

import KeyboardAccessoryView from './KeyboardAccessoryView';
import Arrow from './components/Arrow';

// Render a prev/hidden arrow button
const AccessoryArrowButton = ({style, hidden, disabled, onPress ...props}) => {
  if (hidden) {
    return null;
  } else {
    return (
      <TouchableOpacity
        disabled={disabled}
        style={style}
        onPress={onPress}
      >
        {props.customButton ? props.customButton : (
          <Arrow
            direction={props.direction}
            disabled={disabled}
            tintColor={props.tintColor}
          />
        )}
      </TouchableOpacity>
    );
  }
}

AccessoryArrowButton.propTypes = {
  style: PropTypes.oneOfType([
    PropTypes.object,
    PropTypes.number
  ]).isRequired,
  customButton: PropTypes.element,
  tintColor: PropTypes.string.isRequired,
  direction: PropTypes.string.isRequired,
  disabled: PropTypes.bool.isRequired,
  hidden: PropTypes.bool.isRequired,
  onPress: PropTypes.func.isRequired,
}

class KeyboardAccessoryNavigation extends Component {

  handleDoneButton() {
    this.props.onDone && this.props.onDone();
    Keyboard.dismiss();
  }

  render() {
    const {
      nextButton,
      previousButton,
      doneButton,
      doneButtonTitle,
      infoContainer,
      infoMessage,
      tintColor,
      onNext,
      onPrevious,
      nextDisabled,
      prevDisabled,
      nextHidden,
      prevHidden,
      style,
      accessoryStyle,
      nextButtonStyle,
      previousButtonStyle,
      doneButtonStyle,
      doneButtonTitleStyle,
      infoMessageStyle,
      nextButtonDirection,
      previousButtonDirection,
      alwaysVisible,
    } = this.props;

    return (
      <KeyboardAccessoryView {...(style ? { style } : {})} alwaysVisible={alwaysVisible}>
        <View style={[styles.accessoryContainer, accessoryStyle]}>
          {!nextHidden && !prevHidden && (
            <View style={styles.leftContainer}>
              <AccessoryArrowButton
                style={[styles.previousButton, previousButtonStyle]}
                hidden={prevHidden}
                disabled={prevDisabled}
                direction={prevButtonDirection}
                customButton={prevButton}
                tintColor={tintColor}
                onPress={onPrevious}
              />
              <AccessoryArrowButton
                style={{...(style ? { style: nextButtonStyle } : {})}}
                hidden={nextHidden}
                disabled={nextDisabled}
                direction={nextButtonDirection}
                customButton={nextButton}
                tintColor={tintColor}
                onPress={onNext}
              />
            </View>
          )}
          { (infoMessage || infoContainer) &&
            <View style={styles.infoContainer}>
              { infoContainer ? infoContainer : (
                <Text style={[infoMessageStyle, {
                  color: tintColor,
                }]}>
                  { infoMessage }
                </Text>
              )}
            </View>
          }
          <TouchableOpacity
            style={[styles.doneButton, doneButtonStyle]}
            onPress={this.handleDoneButton.bind(this)} >
            { doneButton ? doneButton : (
              <Text style={[ styles.doneButtonText, doneButtonTitleStyle, {
                color: tintColor,
              }]}>
                {doneButtonTitle}
              </Text>
            )}
          </TouchableOpacity>
        </View>
      </KeyboardAccessoryView>
    );
  }
}

KeyboardAccessoryNavigation.propTypes = {
  doneButtonTitle: PropTypes.string,
  infoMessage: PropTypes.string,
  doneButton: PropTypes.element,
  nextButton: PropTypes.element,
  previousButton: PropTypes.element,
  infoContainer: PropTypes.element,
  onNext: PropTypes.func,
  onPrevious: PropTypes.func,
  onDone: PropTypes.func,
  nextDisabled: PropTypes.bool,
  prevDisabled: PropTypes.bool,
  doneDisabled: PropTypes.bool,
  nextHidden: PropTypes.bool,
  prevHidden: PropTypes.bool,
  alwaysVisible: PropTypes.bool,
  tintColor: PropTypes.string,
  style: PropTypes.oneOfType([
    PropTypes.object,
    PropTypes.number
  ]),
  accessoryStyle: PropTypes.oneOfType([
    PropTypes.object,
    PropTypes.number
  ]),
  previousButtonStyle: PropTypes.oneOfType([
    PropTypes.object,
    PropTypes.number
  ]),
  nextButtonStyle: PropTypes.oneOfType([
    PropTypes.object,
    PropTypes.number
  ]),
  doneButtonStyle: PropTypes.oneOfType([
    PropTypes.object,
    PropTypes.number
  ]),
  doneButtonTitleStyle: PropTypes.oneOfType([
    PropTypes.object,
    PropTypes.number
  ]),
  infoMessageStyle: PropTypes.oneOfType([
    PropTypes.object,
    PropTypes.number
  ]),
  nextButtonDirection: PropTypes.oneOf(['up', 'down', 'left', 'right']),
  previousButtonDirection: PropTypes.oneOf(['up', 'down', 'left', 'right']),
}

KeyboardAccessoryNavigation.defaultProps = {
  doneButtonTitle: 'Done',
  tintColor: '#007AFF',
  nextDisabled: false,
  previousDisabled: false,
  nextHidden: false,
  prevHidden: false,
  nextButtonDirection: 'down',
  previousButtonDirection: 'up',
  alwaysVisible: false,
}

const styles = StyleSheet.create({
  accessoryContainer: {
    height: 45,
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
    paddingLeft: 15,
    paddingRight: 15,
  },
  leftContainer: {
    flexDirection: 'row',
    alignItems: 'center',
  },
  previousButton: {
    marginRight: 16,
  },
  doneButtonText: {
    fontWeight: 'bold'
  }
})

export default KeyboardAccessoryNavigation;
<commit_msg>Fix props<commit_after>import React, { Component } from 'react';
import PropTypes from 'prop-types';

import {
  StyleSheet,
  View,
  Text,
  TouchableOpacity,
  Keyboard,
  ViewPropTypes,
} from 'react-native';

import KeyboardAccessoryView from './KeyboardAccessoryView';
import Arrow from './components/Arrow';

// Render a prev/hidden arrow button
const AccessoryArrowButton = ({style, hidden = false, disabled = false, onPress, ...props}) => {
  if (hidden) {
    return null;
  } else {
    return (
      <TouchableOpacity
        disabled={disabled}
        style={style}
        onPress={onPress}
      >
        {props.customButton ? props.customButton : (
          <Arrow
            direction={props.direction}
            disabled={disabled}
            tintColor={props.tintColor}
          />
        )}
      </TouchableOpacity>
    );
  }
}

AccessoryArrowButton.propTypes = {
  style: PropTypes.oneOfType([
    PropTypes.object,
    PropTypes.number
  ]),
  customButton: PropTypes.element,
  tintColor: PropTypes.string.isRequired,
  direction: PropTypes.string.isRequired,
  disabled: PropTypes.bool.isRequired,
  hidden: PropTypes.bool.isRequired,
  onPress: PropTypes.func.isRequired,
}

class KeyboardAccessoryNavigation extends Component {

  handleDoneButton() {
    this.props.onDone && this.props.onDone();
    Keyboard.dismiss();
  }

  render() {
    const {
      nextButton,
      previousButton,
      doneButton,
      doneButtonTitle,
      infoContainer,
      infoMessage,
      tintColor,
      onNext,
      onPrevious,
      nextDisabled,
      previousDisabled,
      nextHidden,
      previousHidden,
      style,
      accessoryStyle,
      nextButtonStyle,
      previousButtonStyle,
      doneButtonStyle,
      doneButtonTitleStyle,
      infoMessageStyle,
      nextButtonDirection,
      previousButtonDirection,
      alwaysVisible,
    } = this.props;

    return (
      <KeyboardAccessoryView {...(style ? { style } : {})} alwaysVisible={alwaysVisible}>
        <View style={[styles.accessoryContainer, accessoryStyle]}>
          {!nextHidden && !previousHidden && (
            <View style={styles.leftContainer}>
              <AccessoryArrowButton
                style={[styles.previousButton, previousButtonStyle]}
                hidden={previousHidden}
                disabled={previousDisabled}
                direction={previousButtonDirection}
                customButton={previousButton}
                tintColor={tintColor}
                onPress={onPrevious}
              />
              <AccessoryArrowButton
                style={{...(style ? { style: nextButtonStyle } : {})}}
                hidden={nextHidden}
                disabled={nextDisabled}
                direction={nextButtonDirection}
                customButton={nextButton}
                tintColor={tintColor}
                onPress={onNext}
              />
            </View>
          )}
          {(infoMessage || infoContainer) && (
            <View style={styles.infoContainer}>
              {infoContainer ? infoContainer : (
                <Text style={[infoMessageStyle, {
                  color: tintColor,
                }]}>
                  {infoMessage}
                </Text>
              )}
            </View>
          )}
          <TouchableOpacity
            style={[styles.doneButton, doneButtonStyle]}
            onPress={this.handleDoneButton.bind(this)} >
            {doneButton ? doneButton : (
              <Text style={[ styles.doneButtonText, doneButtonTitleStyle, {
                color: tintColor,
              }]}>
                {doneButtonTitle}
              </Text>
            )}
          </TouchableOpacity>
        </View>
      </KeyboardAccessoryView>
    );
  }
}

KeyboardAccessoryNavigation.propTypes = {
  doneButtonTitle: PropTypes.string,
  infoMessage: PropTypes.string,
  doneButton: PropTypes.element,
  nextButton: PropTypes.element,
  previousButton: PropTypes.element,
  infoContainer: PropTypes.element,
  onNext: PropTypes.func,
  onPrevious: PropTypes.func,
  onDone: PropTypes.func,
  nextDisabled: PropTypes.bool,
  previousDisabled: PropTypes.bool,
  doneDisabled: PropTypes.bool,
  nextHidden: PropTypes.bool,
  previousHidden: PropTypes.bool,
  alwaysVisible: PropTypes.bool,
  tintColor: PropTypes.string,
  style: PropTypes.oneOfType([
    PropTypes.object,
    PropTypes.number
  ]),
  accessoryStyle: PropTypes.oneOfType([
    PropTypes.object,
    PropTypes.number
  ]),
  previousButtonStyle: PropTypes.oneOfType([
    PropTypes.object,
    PropTypes.number
  ]),
  nextButtonStyle: PropTypes.oneOfType([
    PropTypes.object,
    PropTypes.number
  ]),
  doneButtonStyle: PropTypes.oneOfType([
    PropTypes.object,
    PropTypes.number
  ]),
  doneButtonTitleStyle: PropTypes.oneOfType([
    PropTypes.object,
    PropTypes.number
  ]),
  infoMessageStyle: PropTypes.oneOfType([
    PropTypes.object,
    PropTypes.number
  ]),
  nextButtonDirection: PropTypes.oneOf(['up', 'down', 'left', 'right']),
  previousButtonDirection: PropTypes.oneOf(['up', 'down', 'left', 'right']),
}

KeyboardAccessoryNavigation.defaultProps = {
  doneButtonTitle: 'Done',
  tintColor: '#007AFF',
  nextDisabled: false,
  previousDisabled: false,
  nextHidden: false,
  previousHidden: false,
  nextButtonDirection: 'down',
  previousButtonDirection: 'up',
  alwaysVisible: false,
}

const styles = StyleSheet.create({
  accessoryContainer: {
    height: 45,
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
    paddingLeft: 15,
    paddingRight: 15,
  },
  leftContainer: {
    flexDirection: 'row',
    alignItems: 'center',
  },
  previousButton: {
    marginRight: 16,
  },
  doneButtonText: {
    fontWeight: 'bold'
  }
})

export default KeyboardAccessoryNavigation;
<|endoftext|>


<commit_before>$(document).ready(function () {

	/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
	/* # Variables globales */
	/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
	lastNumberAssigned = 0;
	playerName = "";

	pipePlayers = { "actions" : []}

	/* # Initialisation de la partie */
	gameInit();

	/* # Synchronisations */
	//setInterval(getMetrology, 12000);
	//setInterval(getPlayers, 30000);

	/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
	/* # Gestionnaires d'événements */
	/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */

	/* # Rejoindre une partie */
	$( "#formGameJoin" ).submit(function( event ) {
	  event.preventDefault();

	  /* # le joueur rejoin la partie */
	  var name = $('#name').val();
	  gameRejoin(name);

	  /* # liste de joueur */
	  getPlayers();

	});

	/* # Ajouter une recette dans le panier du joueur */
	$( "#formproduction" ).submit(function( event ) {
	  event.preventDefault();

	  getInfoRecette()

	});

	/* # raffraichir les données */
	$('#btnRefreshGameInfo').click(function() {
		getMetrology();
	})

	/* # Choix d'une recette */
	if($('#recettadd') != undefined){
		$('#recettadd').change(function() {
			getRepiceByName($(this).val())
		})
	}

	/* # supprimer une recette dans le pipe */
	callbackDelPlayerPipe()

	/* # Valider les actions : achat des recettes,... */
	$('#valideracions').click(function() {
		sendAction()
	})

	/* # Quitter la partie en cours */
	$('#btnexitgame').click(function() {
		exitGameByName()
	})

	/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
	/* # Les fonctions */
	/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */

	var rand = function() {
	    return Math.random().toString(36).substr(2); // remove `0.`
	};

	var token = function() {
	    return rand() + rand(); // to make it longer
	};

	function getInfoRecette(){
		var recette = $('#recettadd').val();
		  var prixu = $('#prixunitaire').text()
		  var quantite = parseInt($('#quantity').val());
		  var prixvente = parseFloat($('#prixvente').val());

		  if(Number.isInteger(quantite)){
		  	addPlayerPipe(recette,prixu,quantite,prixvente);
		  }
	}

	/**
	*
	*/
	function addPlayerPipe(recette,prixu,quantite,prixvente) {
		$.ajax({
			url: "/recipe/"+recette,
			type: "GET",
			contentType: 'application/json',
			success: function(result){
				var token = lastNumberAssigned++;

				var itemRecette = $('

'+result.recipe[0].rec_nom+'

'+quantite+'

'+prixvente+'

'+quantite*prixvente+'

');
				$('#additemrecette').before(itemRecette);

				/* # Event : supprimer une recette dans le pipe */
				callbackDelPlayerPipe()

				/* # Ajout dans la liste pipePlayers */
				// {"actions" : [{"kind" : "drinks","prepare" : [{"1":50},{"3":20}],"price" : [{"1":8},{"3":2}]} ]}

				var tmp1 = [];
				var tmp2 = [];
				recette = (result.recipe[0].rec_nom).toString();
				tmp1[recette] = quantite;
				tmp2[recette] = prixvente;

				if(pipePlayers.actions != undefined && pipePlayers.actions.length > 0){
					if(pipePlayers.actions[0].prepare != undefined){
						pipePlayers.actions[0].prepare.push(tmp1);
					}

					if(pipePlayers.actions[0].price != undefined){
						pipePlayers.actions[0].price.push(tmp2);
					}
				}else{
					pipePlayers["actions"] = {}
					var drinksAction = {
						"kind" : "drinks",
						"prepare" : [],
						"price" : []
					};

					pipePlayers.actions.push(
						drinksAction.prepare.push(pipePlayers.actions.prepare.push(tmp1);)
						drinksAction.price.push(pipePlayers.actions.price.push(tmp2);)
					)
				}

				console.log(pipePlayers)

				//console.log(JSON.stringify(pipePlayers))
	    	}
		});

	}

	/**
	*
	*/
	function getMetrology () {
		$.ajax({
			url: "/metrology",
			type: "GET",
			contentType: 'application/json',
			success: function(result){

				$('#timer').html(result.timestamp);
				$.each(result.weather, function( index, value ) {
					if(value['dfn'] == 0)
						$('#weatherToday').html(value['weather']);
	        		else
	        			$('#weatherTomorrow').html(value['weather']);
				});
	    	}
		});
	}

	function loadTime() {

	}
	loadTime();

	/**
	*
	*/
	function getPlayers() {
		$.ajax({
			url: "/players",
			type: "GET",
			contentType: 'application/json',
			success: function(result){

				if(result.players.length > 0){
					var item = $('

');

					$('#playerList').html("");
					for (var i = 0; i < result.players.length; i++) {
						item.append($('
'+ result.players[i].pl_pseudo +'
'))
					};
					$('#playerList').append(item);
				}else{
					$('#playerList').html("Liste vide :(");
				}
	    	}
		});
	}

	function getRepices() {
		$.ajax({
			url: "/recipes",
			type: "GET",
			contentType: 'application/json',
			success: function(result){

				$.each(result.recipes, function( index, value ) {

					$('#recettadd').append($('<option value="'+ value['rec_id'] +'">'+ value['rec_nom'] +'</option>'))
				});
	    	}
		});
	}

	function getRepiceByName(rc_id) {
		$.ajax({
			url: "/recipe/"+rc_id,
			type: "GET",
			contentType: 'application/json',
			success: function(result){

				var totalCost = 0;
				$.each(result.ingredients, function( index, value ) {
					totalCost += value['ing_prix'];
				});
				$('#prixunitaire').html(totalCost)
	    	}
		});
	}

	function exitGameByName(rc_id) {
			$.ajax({
				url: "/players/"+playerName,
				type: "DELETE",
				contentType: 'application/json',
				success: function(result){

		    	}
			});
		}

	/**
	*
	*/
	function gameRejoin(name) {
		var data = {"name": name}
		$.ajax({
			url: "/players",
			data : JSON.stringify(data),
			type: "POST",
			contentType: 'application/json',
			success: function(result){
	        	resetFormGameJoin();

	        	/* Supprimer le bloque rejoindre la partie */
	        	$('#inscriptionbloc').remove();

	        	/* Mise à jour des informations relatives au player */
	        	$('#username').html(result.name);
	        	playerName = result.name
	        	$('#budgetplayer').html(result.info.cash)

	        	/* Affichage d'un message de bienvenue */
	        	var title = 'Coucou '+playerName+'. ';
	        	var msg = 'Toujours aussi BD ?';
	        	var status = 'success';
	        	showMessage(title,msg,status);

	        	/*console.log(result.info.profit)
	        	console.log(result.info.sales)
	        	console.log(result.info.drinksOffered)
	        	console.log(result.info.longitude)
	        	console.log(result.info.latitude)*/

	        	/* Afficher l'interface de simulation */
	        	$('#infogamebloc').removeClass("hidden");

	    	}
		});
	}

	/**
	*
	*/
	function resetFormGameJoin () {
		$('#name').val("");
	}

	/**
	*
	*/
	function gameInit () {

		if(playerName.length > 0){
			$('#infogamebloc').removeClass("hidden");

			/* # Confirmation du player pour quitter une partie */
			exitGame();
		}else{
			$('#infogamebloc').addClass("hidden");
		}

	  	/* # Liste de joueurs */
	  	getPlayers();

	  	if($('#blocSimul') != undefined)
	 		getRepices();

	}

	function exitGame () {
		window.onbeforeunload = function() {
		    return "Etes-vous sûr de quitter la partie ?";
		}
	}

	function callbackDelPlayerPipe () {
		/* # supprimer une recette dans le pipe */
		$('.btnSuppRecette').click(function (event) {
			var tmp  = '#'+event.target.id.split("-")[0];

			$.each(pipePlayers.actions[0].prepare, function( index, value ) {
				if (parseInt(index) == parseInt(event.target.id.split("-")[0]))
					pipePlayers.actions[0].prepare.splice(index, 1);
			});

			$.each(pipePlayers.actions[0].price, function( index, value ) {
				if (parseInt(index) == parseInt(event.target.id.split("-")[0]))
					pipePlayers.actions[0].price.splice(index, 1);
			});

			$(tmp).remove()

			//console.log(pipePlayers)

		})
	}

	/**
	*
	*/
	function sendAction() {
		console.log(pipePlayers)

		$.ajax({
			url: "/actions/"+playerName,
			pipePlayers : $.parseJSON(pipePlayers),
			type: "POST",
			contentType: 'application/json',
			success: function(result){
				var title, msg, status;

				if(result.sufficientFunds == "false"){
					title = 'Solde insuffisant';
					msg = 'Nous ne pouvez pas acheter ces boissons !';
					status = 'danger';
					showMessage(title,msg,status)
				}else if(result.sufficientFunds == "true"){
					title = 'Félicitation';
					msg = 'Vos boissons ont été ajoutés avec succès !';
					status = 'success';
					showMessage(title,msg,status)
				}
	    	}
		});
	}

	function showMessage (title,msg,status) {
		$.notify({
					title: title,
					message: msg
				},{
					type: status
				});
	}

})<commit_msg>test 16<commit_after>$(document).ready(function () {

	/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
	/* # Variables globales */
	/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
	lastNumberAssigned = 0;
	playerName = "";

	pipePlayers = { "actions" : []}

	/* # Initialisation de la partie */
	gameInit();

	/* # Synchronisations */
	//setInterval(getMetrology, 12000);
	//setInterval(getPlayers, 30000);

	/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
	/* # Gestionnaires d'événements */
	/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */

	/* # Rejoindre une partie */
	$( "#formGameJoin" ).submit(function( event ) {
	  event.preventDefault();

	  /* # le joueur rejoin la partie */
	  var name = $('#name').val();
	  gameRejoin(name);

	  /* # liste de joueur */
	  getPlayers();

	});

	/* # Ajouter une recette dans le panier du joueur */
	$( "#formproduction" ).submit(function( event ) {
	  event.preventDefault();

	  getInfoRecette()

	});

	/* # raffraichir les données */
	$('#btnRefreshGameInfo').click(function() {
		getMetrology();
	})

	/* # Choix d'une recette */
	if($('#recettadd') != undefined){
		$('#recettadd').change(function() {
			getRepiceByName($(this).val())
		})
	}

	/* # supprimer une recette dans le pipe */
	callbackDelPlayerPipe()

	/* # Valider les actions : achat des recettes,... */
	$('#valideracions').click(function() {
		sendAction()
	})

	/* # Quitter la partie en cours */
	$('#btnexitgame').click(function() {
		exitGameByName()
	})

	/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
	/* # Les fonctions */
	/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */

	var rand = function() {
	    return Math.random().toString(36).substr(2); // remove `0.`
	};

	var token = function() {
	    return rand() + rand(); // to make it longer
	};

	function getInfoRecette(){
		var recette = $('#recettadd').val();
		  var prixu = $('#prixunitaire').text()
		  var quantite = parseInt($('#quantity').val());
		  var prixvente = parseFloat($('#prixvente').val());

		  if(Number.isInteger(quantite)){
		  	addPlayerPipe(recette,prixu,quantite,prixvente);
		  }
	}

	/**
	*
	*/
	function addPlayerPipe(recette,prixu,quantite,prixvente) {
		$.ajax({
			url: "/recipe/"+recette,
			type: "GET",
			contentType: 'application/json',
			success: function(result){
				var token = lastNumberAssigned++;

				var itemRecette = $('

'+result.recipe[0].rec_nom+'

'+quantite+'

'+prixvente+'

'+quantite*prixvente+'

');
				$('#additemrecette').before(itemRecette);

				/* # Event : supprimer une recette dans le pipe */
				callbackDelPlayerPipe()

				/* # Ajout dans la liste pipePlayers */
				// {"actions" : [{"kind" : "drinks","prepare" : [{"1":50},{"3":20}],"price" : [{"1":8},{"3":2}]} ]}

				var tmp1 = [];
				var tmp2 = [];
				recette = (result.recipe[0].rec_nom).toString();
				tmp1[recette] = quantite;
				tmp2[recette] = prixvente;

				if(pipePlayers.actions != undefined && pipePlayers.actions.length > 0){
					if(pipePlayers.actions[0].prepare != undefined){
						pipePlayers.actions[0].prepare.push(tmp1);
					}

					if(pipePlayers.actions[0].price != undefined){
						pipePlayers.actions[0].price.push(tmp2);
					}
				}else{
					pipePlayers["actions"] = {}
					var drinksAction = {
						"kind" : "drinks",
						"prepare" : [],
						"price" : []
					};

					pipePlayers.actions.push(
						drinksAction.prepare.push(pipePlayers.actions.prepare.push(tmp1));
						drinksAction.price.push(pipePlayers.actions.price.push(tmp2));
					)
				}

				console.log(pipePlayers)

				//console.log(JSON.stringify(pipePlayers))
	    	}
		});

	}

	/**
	*
	*/
	function getMetrology () {
		$.ajax({
			url: "/metrology",
			type: "GET",
			contentType: 'application/json',
			success: function(result){

				$('#timer').html(result.timestamp);
				$.each(result.weather, function( index, value ) {
					if(value['dfn'] == 0)
						$('#weatherToday').html(value['weather']);
	        		else
	        			$('#weatherTomorrow').html(value['weather']);
				});
	    	}
		});
	}

	function loadTime() {

	}
	loadTime();

	/**
	*
	*/
	function getPlayers() {
		$.ajax({
			url: "/players",
			type: "GET",
			contentType: 'application/json',
			success: function(result){

				if(result.players.length > 0){
					var item = $('

');

					$('#playerList').html("");
					for (var i = 0; i < result.players.length; i++) {
						item.append($('
'+ result.players[i].pl_pseudo +'
'))
					};
					$('#playerList').append(item);
				}else{
					$('#playerList').html("Liste vide :(");
				}
	    	}
		});
	}

	function getRepices() {
		$.ajax({
			url: "/recipes",
			type: "GET",
			contentType: 'application/json',
			success: function(result){

				$.each(result.recipes, function( index, value ) {

					$('#recettadd').append($('<option value="'+ value['rec_id'] +'">'+ value['rec_nom'] +'</option>'))
				});
	    	}
		});
	}

	function getRepiceByName(rc_id) {
		$.ajax({
			url: "/recipe/"+rc_id,
			type: "GET",
			contentType: 'application/json',
			success: function(result){

				var totalCost = 0;
				$.each(result.ingredients, function( index, value ) {
					totalCost += value['ing_prix'];
				});
				$('#prixunitaire').html(totalCost)
	    	}
		});
	}

	function exitGameByName(rc_id) {
			$.ajax({
				url: "/players/"+playerName,
				type: "DELETE",
				contentType: 'application/json',
				success: function(result){

		    	}
			});
		}

	/**
	*
	*/
	function gameRejoin(name) {
		var data = {"name": name}
		$.ajax({
			url: "/players",
			data : JSON.stringify(data),
			type: "POST",
			contentType: 'application/json',
			success: function(result){
	        	resetFormGameJoin();

	        	/* Supprimer le bloque rejoindre la partie */
	        	$('#inscriptionbloc').remove();

	        	/* Mise à jour des informations relatives au player */
	        	$('#username').html(result.name);
	        	playerName = result.name
	        	$('#budgetplayer').html(result.info.cash)

	        	/* Affichage d'un message de bienvenue */
	        	var title = 'Coucou '+playerName+'. ';
	        	var msg = 'Toujours aussi BD ?';
	        	var status = 'success';
	        	showMessage(title,msg,status);

	        	/*console.log(result.info.profit)
	        	console.log(result.info.sales)
	        	console.log(result.info.drinksOffered)
	        	console.log(result.info.longitude)
	        	console.log(result.info.latitude)*/

	        	/* Afficher l'interface de simulation */
	        	$('#infogamebloc').removeClass("hidden");

	    	}
		});
	}

	/**
	*
	*/
	function resetFormGameJoin () {
		$('#name').val("");
	}

	/**
	*
	*/
	function gameInit () {

		if(playerName.length > 0){
			$('#infogamebloc').removeClass("hidden");

			/* # Confirmation du player pour quitter une partie */
			exitGame();
		}else{
			$('#infogamebloc').addClass("hidden");
		}

	  	/* # Liste de joueurs */
	  	getPlayers();

	  	if($('#blocSimul') != undefined)
	 		getRepices();

	}

	function exitGame () {
		window.onbeforeunload = function() {
		    return "Etes-vous sûr de quitter la partie ?";
		}
	}

	function callbackDelPlayerPipe () {
		/* # supprimer une recette dans le pipe */
		$('.btnSuppRecette').click(function (event) {
			var tmp  = '#'+event.target.id.split("-")[0];

			$.each(pipePlayers.actions[0].prepare, function( index, value ) {
				if (parseInt(index) == parseInt(event.target.id.split("-")[0]))
					pipePlayers.actions[0].prepare.splice(index, 1);
			});

			$.each(pipePlayers.actions[0].price, function( index, value ) {
				if (parseInt(index) == parseInt(event.target.id.split("-")[0]))
					pipePlayers.actions[0].price.splice(index, 1);
			});

			$(tmp).remove()

			//console.log(pipePlayers)

		})
	}

	/**
	*
	*/
	function sendAction() {
		console.log(pipePlayers)

		$.ajax({
			url: "/actions/"+playerName,
			pipePlayers : $.parseJSON(pipePlayers),
			type: "POST",
			contentType: 'application/json',
			success: function(result){
				var title, msg, status;

				if(result.sufficientFunds == "false"){
					title = 'Solde insuffisant';
					msg = 'Nous ne pouvez pas acheter ces boissons !';
					status = 'danger';
					showMessage(title,msg,status)
				}else if(result.sufficientFunds == "true"){
					title = 'Félicitation';
					msg = 'Vos boissons ont été ajoutés avec succès !';
					status = 'success';
					showMessage(title,msg,status)
				}
	    	}
		});
	}

	function showMessage (title,msg,status) {
		$.notify({
					title: title,
					message: msg
				},{
					type: status
				});
	}

})<|endoftext|>


<commit_before>// ==UserScript==
// @name        Chameleon
// @description Auto color formatting for the chatbox.
// @namespace   how much grease
// @include     http://aimgames.forummotion.com/*
// @version     3.trippy.4.1.programer.1452964254.7
// @grant       none
// @icon        http://i.imgur.com/g8MwvQd.png
// @license     MIT License (Expat); opensource.org/licenses/MIT
// ==/UserScript==

////// CODE FOR DEALING WITH OBJECTS
function values(o) {
  return Object.keys(o) .map(function (k) {
    return o[k];
  });
}

////// TOOLBOX
function ayyliumLanguage(n)
  {
    var nybHexString = "0123456789ABCDEF";
    return String(nybHexString.substr((n >> 4) & 0x0F,1)) + nybHexString.substr(n & 0x0F,1);
  }

function strangeAyylium(r,g,b)
  {
    return '#' + ayyliumLanguage(r) + ayyliumLanguage(g) + ayyliumLanguage(b);
  }

function hexToRgb(hex) {
    var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
    return result ? {
        r: parseInt(result[1], 16),
        g: parseInt(result[2], 16),
        b: parseInt(result[3], 16)
    } : null;
}

function capitalizeFirstLetter(string) {
    return string.charAt(0).toUpperCase() + string.slice(1);
}
//////

function createRainbow(center, width, f_r, f_g, f_b, cutoff) {
var a= [];
var frequency_r = .1;
var frequency_g = .2;
var frequency_b = .3;
for (var i = 0; i < cutoff; ++i)
{
   var red   = Math.sin(frequency_r*i + 0) * width + center;
   var green = Math.sin(frequency_g*i + 2*Math.PI/3) * width + center;
   var blue  = Math.sin(frequency_b*i + 4*Math.PI/3) * width + center;
   a[i] = strangeAyylium(red,green,blue);

}
return a;
}
//////

//////COLOR
var color_array = []; ///main array what we want gets moved into
var color_style = [ "Normal", "Trippy", "Patriotic", "Warm", "Light", "Different"];
////
//
//
var color_hex = {
    normal: createRainbow(128,127, .3, .3, .3, 32),
    ///trippy needs work
    trippy: [ "#ff3300", "#0033cc", "#00cc00", "#ffcc00", "#cc00cc", "#6600ff", "#00ffff" ],
    patriotic: [ "#ff0000", "#ffffff", "#0000ff" ],
    warm: [ "#ff3300", "#0033cc", "#00cc00", "#ffcc00", "#cc00cc", "#6600ff", "#00ffff" ],
    light: createRainbow(200,55, .3, .3, .3, 32),
    different: createRainbow(128, 127, .1, .2, .3, 27)
};
//

///////COOKIE SHIT
function setCookie(name, value, days) {
  var expires = '';
  if (days) {
    var date = new Date();
    date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
    expires = '; expires=' + date.toGMTString();
  }
  else expires = '';
  document.cookie = name + '=' + value + expires + '; path=/';
}

function getCookie(c_name) {
  var name = c_name + '=';
  var ca = document.cookie.split(';');
  for (var i = 0; i < ca.length; i++) {
    var c = ca[i];
    while (c.charAt(0) == ' ') c = c.substring(1);
    if (c.indexOf(name) === 0) return c.substring(name.length, c.length);
  }
  return '';
}
///////

function returnOption(text){
	var option = document.createElement("option");
	option.text = text;
	option.style.dir = "rtl";
	option.style.paddingRight = "4px";
	return option;
}

function createSelectBox(){
	var new_td = document.createElement("td");
	new_td.id = "Cha";

  	document.getElementById("chatbox_messenger_form").getElementsByTagName("tr")[0].insertBefore(
		new_td,
		document.getElementById("chatbox_messenger_form").getElementsByTagName("tr")[0].childNodes[0]
  	);

	var gen_location = document.getElementById("Cha");
        select = document.createElement('select');
        select.id = 'selectCha';
        gen_location.appendChild(select);

	var sel_location = document.getElementById('selectCha');

	sel_location.addEventListener('change', function() {whatdo(this);}, false);
	for(var num_entries = 0; num_entries < color_style.length; num_entries++){
	   sel_location.appendChild(returnOption(color_style[num_entries]));
	}
}

var counter = 0;

function whatdo(wew){
    var dunwan = [];
    color_array = []; //clear it
    counter = 0;

   if(wew.value == "Normal"){
    dunwan = color_hex['normal'];
   }else if(wew.value == "Patriotic"){
    dunwan = color_hex['patriotic'];
   }else if(wew.value == "Warm"){
    dunwan = color_hex['warm'];
   }else if(wew.value == "Light"){
    dunwan = color_hex['light'];
    }else if(wew.value == "Different"){
    dunwan = color_hex['different'];
    }

   setCookie('chameleon_color_style', wew.value.toLowerCase(), 1);

   for (var all = 0; all < dunwan.length; all++) {
        color_array[all] = dunwan[all];
        console.log("kek");
   }
}

window.addEventListener('load', function() {
   createSelectBox();

   var array_watch = [];

   if (getCookie('chameleon_color_style') === "") {
      setCookie('chameleon_color_style', color_hex['normal'], 1);
      array_watch = color_hex['normal'];
    } else{
      array_watch = getCookie('chameleon_color_style');
      document.getElementById('selectCha').value = capitalizeFirstLetter(getCookie('chameleon_color_style'));
    }

    for (var all = 0; all < color_hex['normal'].length; all++) { ////load normal at first
        color_array[all] = values(color_hex['normal'])[all];
        console.log("only once pls");
   }

if (document.getElementById('frame_chatbox') !== null || document.getElementById('message') !== null) {
  if (window.location.pathname.length <= 1) {
    if (getCookie('chameleon_counter') === 0) {
      setCookie('CB_color', color_array[counter], 1);
    } else{
      counter = getCookie('chameleon_counter');
    }
    document.getElementById('frame_chatbox') .contentWindow.document.getElementById('message') .addEventListener('keydown', function (event) {
      var code = (event.keyCode) ? event.keyCode : event.which;
      if (code == 13) {
        counter++;
        if (counter == color_array.length) {
          counter = 0;
        }
      }
    }, false);
    document.getElementById('frame_chatbox') .contentWindow.document.getElementById('message') .addEventListener('keyup', function (event) {
      var code = (event.keyCode) ? event.keyCode : event.which;
      if (code == 13) {
        setCookie('chameleon_counter', counter, 1);
        setCookie('CB_color', color_array[counter], 1);
        document.getElementById('frame_chatbox') .contentWindow.document.getElementById('scolor') .value = color_array[counter];
        document.getElementById('frame_chatbox') .contentWindow.document.getElementById('divcolor-preview') .style.cssText = 'background-color: rgb(' + hexToRgb(color_array[counter]).r + ',' + hexToRgb(color_array[counter]).g + ',' + hexToRgb(color_array[counter]).b + ');';
        document.getElementById('frame_chatbox') .contentWindow.document.getElementById('message') .style.color = color_array[counter];
      }
    }, false);
  } else {
    if (getCookie('chameleon_counter') === 0) {
      setCookie('CB_color', color_array[counter], 1);
    } else{
      counter = getCookie('chameleon_counter');
    }
    document.getElementById('message') .addEventListener('keydown', function (event) {
      var code = (event.keyCode) ? event.keyCode : event.which;
      if (code == 13) {
        counter++;
        if (counter == color_array.length) {
          counter = 0;
        }
      }
    }, false);
    document.getElementById('message') .addEventListener('keyup', function (event) {
      var code = (event.keyCode) ? event.keyCode : event.which;
      if (code == 13) {
        setCookie('chameleon_counter', counter, 1);
        setCookie('CB_color', color_array[counter], 1);
        console.log(color_array[counter]);
        document.getElementById('scolor') .value = color_array[counter];
        document.getElementById('divcolor-preview') .style.cssText = 'background-color: rgb(' + hexToRgb(color_array[counter]).r + ',' + hexToRgb(color_array[counter]).g + ',' + hexToRgb(color_array[counter]).b + ');';
        document.getElementById('message') .style.color = color_array[counter];
      }
    }, false);
  }
}
}, false);

<commit_msg>wasn't using all the arguments in createRainbow()<commit_after>// ==UserScript==
// @name        Chameleon
// @description Auto color formatting for the chatbox.
// @namespace   how much grease
// @include     http://aimgames.forummotion.com/*
// @version     3.trippy.4.1.programer.1452964254.7
// @grant       none
// @icon        http://i.imgur.com/g8MwvQd.png
// @license     MIT License (Expat); opensource.org/licenses/MIT
// ==/UserScript==

////// CODE FOR DEALING WITH OBJECTS
function values(o) {
  return Object.keys(o) .map(function (k) {
    return o[k];
  });
}

////// TOOLBOX
function ayyliumLanguage(n)
  {
    var nybHexString = "0123456789ABCDEF";
    return String(nybHexString.substr((n >> 4) & 0x0F,1)) + nybHexString.substr(n & 0x0F,1);
  }

function strangeAyylium(r,g,b)
  {
    return '#' + ayyliumLanguage(r) + ayyliumLanguage(g) + ayyliumLanguage(b);
  }

function hexToRgb(hex) {
    var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
    return result ? {
        r: parseInt(result[1], 16),
        g: parseInt(result[2], 16),
        b: parseInt(result[3], 16)
    } : null;
}

function capitalizeFirstLetter(string) {
    return string.charAt(0).toUpperCase() + string.slice(1);
}
//////

function createRainbow(center, width, f_r, f_g, f_b, cutoff) {
var a= [];
var frequency_r = f_r;
var frequency_g = f_g;
var frequency_b = f_b;
for (var i = 0; i < cutoff; ++i)
{
   var red   = Math.sin(frequency_r*i + 0) * width + center;
   var green = Math.sin(frequency_g*i + 2*Math.PI/3) * width + center;
   var blue  = Math.sin(frequency_b*i + 4*Math.PI/3) * width + center;
   a[i] = strangeAyylium(red,green,blue);

}
return a;
}
//////

//////COLOR
var color_array = []; ///main array what we want gets moved into
var color_style = [ "Normal", "Trippy", "Patriotic", "Warm", "Light", "Different"];
////
//
//
var color_hex = {
    normal: createRainbow(128,127, .3, .3, .3, 32),
    ///trippy needs work
    trippy: [ "#ff3300", "#0033cc", "#00cc00", "#ffcc00", "#cc00cc", "#6600ff", "#00ffff" ],
    patriotic: [ "#ff0000", "#ffffff", "#0000ff" ],
    warm: [ "#ff3300", "#0033cc", "#00cc00", "#ffcc00", "#cc00cc", "#6600ff", "#00ffff" ],
    light: createRainbow(200,55, .3, .3, .3, 32),
    different: createRainbow(128, 127, .1, .2, .3, 27)
};
//

///////COOKIE SHIT
function setCookie(name, value, days) {
  var expires = '';
  if (days) {
    var date = new Date();
    date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
    expires = '; expires=' + date.toGMTString();
  }
  else expires = '';
  document.cookie = name + '=' + value + expires + '; path=/';
}

function getCookie(c_name) {
  var name = c_name + '=';
  var ca = document.cookie.split(';');
  for (var i = 0; i < ca.length; i++) {
    var c = ca[i];
    while (c.charAt(0) == ' ') c = c.substring(1);
    if (c.indexOf(name) === 0) return c.substring(name.length, c.length);
  }
  return '';
}
///////

function returnOption(text){
	var option = document.createElement("option");
	option.text = text;
	option.style.dir = "rtl";
	option.style.paddingRight = "4px";
	return option;
}

function createSelectBox(){
	var new_td = document.createElement("td");
	new_td.id = "Cha";

  	document.getElementById("chatbox_messenger_form").getElementsByTagName("tr")[0].insertBefore(
		new_td,
		document.getElementById("chatbox_messenger_form").getElementsByTagName("tr")[0].childNodes[0]
  	);

	var gen_location = document.getElementById("Cha");
        select = document.createElement('select');
        select.id = 'selectCha';
        gen_location.appendChild(select);

	var sel_location = document.getElementById('selectCha');

	sel_location.addEventListener('change', function() {whatdo(this);}, false);
	for(var num_entries = 0; num_entries < color_style.length; num_entries++){
	   sel_location.appendChild(returnOption(color_style[num_entries]));
	}
}

var counter = 0;

function whatdo(wew){
    var dunwan = [];
    color_array = []; //clear it
    counter = 0;

   if(wew.value == "Normal"){
    dunwan = color_hex['normal'];
   }else if(wew.value == "Patriotic"){
    dunwan = color_hex['patriotic'];
   }else if(wew.value == "Warm"){
    dunwan = color_hex['warm'];
   }else if(wew.value == "Light"){
    dunwan = color_hex['light'];
    }else if(wew.value == "Different"){
    dunwan = color_hex['different'];
    }

   setCookie('chameleon_color_style', wew.value.toLowerCase(), 1);

   for (var all = 0; all < dunwan.length; all++) {
        color_array[all] = dunwan[all];
        console.log("kek");
   }
}

window.addEventListener('load', function() {
   createSelectBox();

   var array_watch = [];

   if (getCookie('chameleon_color_style') === "") {
      setCookie('chameleon_color_style', color_hex['normal'], 1);
      array_watch = color_hex['normal'];
    } else{
      array_watch = getCookie('chameleon_color_style');
      document.getElementById('selectCha').value = capitalizeFirstLetter(getCookie('chameleon_color_style'));
    }

    for (var all = 0; all < color_hex['normal'].length; all++) { ////load normal at first
        color_array[all] = values(color_hex['normal'])[all];
        console.log("only once pls");
   }

if (document.getElementById('frame_chatbox') !== null || document.getElementById('message') !== null) {
  if (window.location.pathname.length <= 1) {
    if (getCookie('chameleon_counter') === 0) {
      setCookie('CB_color', color_array[counter], 1);
    } else{
      counter = getCookie('chameleon_counter');
    }
    document.getElementById('frame_chatbox') .contentWindow.document.getElementById('message') .addEventListener('keydown', function (event) {
      var code = (event.keyCode) ? event.keyCode : event.which;
      if (code == 13) {
        counter++;
        if (counter == color_array.length) {
          counter = 0;
        }
      }
    }, false);
    document.getElementById('frame_chatbox') .contentWindow.document.getElementById('message') .addEventListener('keyup', function (event) {
      var code = (event.keyCode) ? event.keyCode : event.which;
      if (code == 13) {
        setCookie('chameleon_counter', counter, 1);
        setCookie('CB_color', color_array[counter], 1);
        document.getElementById('frame_chatbox') .contentWindow.document.getElementById('scolor') .value = color_array[counter];
        document.getElementById('frame_chatbox') .contentWindow.document.getElementById('divcolor-preview') .style.cssText = 'background-color: rgb(' + hexToRgb(color_array[counter]).r + ',' + hexToRgb(color_array[counter]).g + ',' + hexToRgb(color_array[counter]).b + ');';
        document.getElementById('frame_chatbox') .contentWindow.document.getElementById('message') .style.color = color_array[counter];
      }
    }, false);
  } else {
    if (getCookie('chameleon_counter') === 0) {
      setCookie('CB_color', color_array[counter], 1);
    } else{
      counter = getCookie('chameleon_counter');
    }
    document.getElementById('message') .addEventListener('keydown', function (event) {
      var code = (event.keyCode) ? event.keyCode : event.which;
      if (code == 13) {
        counter++;
        if (counter == color_array.length) {
          counter = 0;
        }
      }
    }, false);
    document.getElementById('message') .addEventListener('keyup', function (event) {
      var code = (event.keyCode) ? event.keyCode : event.which;
      if (code == 13) {
        setCookie('chameleon_counter', counter, 1);
        setCookie('CB_color', color_array[counter], 1);
        console.log(color_array[counter]);
        document.getElementById('scolor') .value = color_array[counter];
        document.getElementById('divcolor-preview') .style.cssText = 'background-color: rgb(' + hexToRgb(color_array[counter]).r + ',' + hexToRgb(color_array[counter]).g + ',' + hexToRgb(color_array[counter]).b + ');';
        document.getElementById('message') .style.color = color_array[counter];
      }
    }, false);
  }
}
}, false);

<|endoftext|>