<commit_before>'use strict';

Array.prototype.concatMap = function (f) {
  return Array.prototype.concat.apply([], this.map(f));
};

var should = require('should');

var esprima = require('esprima');
var j = require('junify');

var assert = require('assert');

function hasBinding(binding, ast) {
  return declarationsOf(ast).some(match([
    { type: 'FunctionDeclaration', id: identifier(binding), _: j._ },
    { type: 'VariableDeclarator', id: identifier(binding), init: j._ }
  ]));
}

function match(patterns) {
  return function(it) {
    return patterns.some(function(pattern) {
      return  j.unify(pattern, it);
    });
  };
}

function identifier(binding) {
  return { type: 'Identifier', name: binding };
}

function declarationsOf(ast) {
  return ast.body.concatMap(function (node) {
    if (j.unify({ type: 'FunctionDeclaration', _: j._ }, node)) {
      return [node];
    } else if (j.unify({ type: 'VariableDeclaration', _: j._ }, node)) {
      return node.declarations;
    } else {
      return [];
    }
  });
}

function p(code) {
  return esprima.parse(code);
}

describe('hasBinding', function () {

  it('hasBinding when function declaration exists for binding', function(){
    assert(hasBinding('foo', p('function foo(){}')));
  });

  it('not hasBinding when function declaration exist for other binding', function(){
    assert(!hasBinding('bar', p('function foo(){}')));
  });

  it('not hasBinding when code is empty', function(){
    assert(!hasBinding('bar', p('')));
  });

  it('hasBinding when code has variable for binding', function(){
    assert(hasBinding('bar', p('var bar = 4')));
  });

  it('not hasBinding when code has variable for other binding', function(){
    assert(!hasBinding('bar', p('var foo = 4')));
  });

  it('not hasBinding when code has expression', function(){
    assert(!hasBinding('bar', p('5 + 2')));
  });

  it('hasBinding for first declarator when code has multiple varible declarators', function(){
    assert(hasBinding('a', p('var a = 5, b = 2;')));
  });

  it('hasBinding for second declarator when code has multiple varible declarators', function(){
    assert(hasBinding('b', p('var a = 5, b = 2;')));
  });

});

describe('concatMap', function () {

  it('concatMap', function(){

    var concatMap = [{foo: [1,2]}, {foo: [3,4]}].concatMap(function (obj) { return obj.foo; });

    concatMap.should.be.eql([1,2,3,4]);

  });

});
<commit_msg>jshint<commit_after>'use strict';

Array.prototype.concatMap = function (f) {
  return Array.prototype.concat.apply([], this.map(f));
};

var should = require('should');

var esprima = require('esprima');
var j = require('junify');

var assert = require('assert');

function hasBinding(binding, ast) {
  return declarationsOf(ast).some(match([
    { type: 'FunctionDeclaration', id: identifier(binding), _: j._ },
    { type: 'VariableDeclarator', id: identifier(binding), init: j._ }
  ]));
}

function match(patterns) {
  return function (it) {
    return patterns.some(function (pattern) {
      return  j.unify(pattern, it);
    });
  };
}

function identifier(binding) {
  return { type: 'Identifier', name: binding };
}

function declarationsOf(ast) {
  return ast.body.concatMap(function (node) {
    if (j.unify({ type: 'FunctionDeclaration', _: j._ }, node)) {
      return [node];
    } else if (j.unify({ type: 'VariableDeclaration', _: j._ }, node)) {
      return node.declarations;
    } else {
      return [];
    }
  });
}

function p(code) {
  return esprima.parse(code);
}

describe('hasBinding', function () {

  it('hasBinding when function declaration exists for binding', function () {
    assert(hasBinding('foo', p('function foo(){}')));
  });

  it('not hasBinding when function declaration exist for other binding', function () {
    assert(!hasBinding('bar', p('function foo(){}')));
  });

  it('not hasBinding when code is empty', function () {
    assert(!hasBinding('bar', p('')));
  });

  it('hasBinding when code has variable for binding', function () {
    assert(hasBinding('bar', p('var bar = 4')));
  });

  it('not hasBinding when code has variable for other binding', function () {
    assert(!hasBinding('bar', p('var foo = 4')));
  });

  it('not hasBinding when code has expression', function () {
    assert(!hasBinding('bar', p('5 + 2')));
  });

  it('hasBinding for first declarator when code has multiple varible declarators', function () {
    assert(hasBinding('a', p('var a = 5, b = 2;')));
  });

  it('hasBinding for second declarator when code has multiple varible declarators', function () {
    assert(hasBinding('b', p('var a = 5, b = 2;')));
  });

});

describe('concatMap', function () {

  it('concatMap', function () {

    var concatMap = [{foo: [1,2]}, {foo: [3,4]}].concatMap(function (obj) { return obj.foo; });

    concatMap.should.be.eql([1,2,3,4]);

  });

});
<|endoftext|>


<commit_before>// ==UserScript==
// @name         ProgrammersForum Detect Bots
// @namespace    programmersforum.ru
// @version      1.3.3
// @description  adds detectBots function that loads the list of online users and counts bots, and logUsers/startLogDaemon functions to save users into IndexedDB
// @author       Alex P
// @include      *programmersforum.ru/*
// @require      https://unpkg.com/dexie@2.0.4/dist/dexie.js
// @grant        none
// @downloadURL  https://github.com/AlexP11223/ProgForumRuUserscripts/raw/master/pf_detect_bots.user.js
// ==/UserScript==

(function () {
    'use strict';

    function countItems(arr) {
        return arr.reduce((acc, item) => {
            acc[item] = acc[item] ? acc[item] + 1 : 1;
            return acc;
        }, {});
    }

    function sleep(ms) {
        return new Promise(resolve => setTimeout(resolve, ms));
    }

    function identify(users) {
        const botUaParts = [
            'bot', 'crawl', 'spider', 'batch', 'bing',
            'share', 'preview', 'facebook', 'vk.com',
            'curl', 'indy', 'http',
            'media', 'metrics', '(compatible)',
            'zh-cn', 'zh_cn', 'mb2345', 'liebao', 'micromessenger', 'kinza', // chinese https://www.johnlarge.co.uk/blocking-aggressive-chinese-crawlers-scrapers-bots/
        ];

        const ipCounts = countItems(users.map(u => u.ip));
        const subnet3Counts = countItems(users.map(u => u.subnet(3)));
        const subnet2Counts = countItems(users.map(u => u.subnet(2)));

        const detectors = [
            user => user.useragent.length < 20 || botUaParts.some(s => user.useragent.includes(s)) ? 'ua' : null,
            user => ipCounts[user.ip] > 2 ? 'ip' : null,
            user => subnet3Counts[user.subnet(3)] > 5 ? 'subnet3' : null,
            user => subnet2Counts[user.subnet(2)] > 20 ? 'subnet2' : null,
        ];

        return users.map(user => {
            const detections = detectors.map(d => d(user)).filter(Boolean);
            return Object.assign(user, {
                detections,
                isBot: function () {
                    return this.detections.length;
                },
            })
        });
    }

    async function loadOnlineUsers(url = '/online.php?s=&sortfield=time&sortorder=desc&who=all&ua=1&pp=200') {
        console.log(`Loading ${url}`);
        const html = await $.get(url);

        const users = $(html).find('[id^=resolveip]').toArray()
            .map(el => ({
                ip: $(el).text().trim(),
                useragent: $(el).parent().text().trim().split('\n').slice(-1)[0].toLowerCase().trim(),
                subnet: function (n) {
                    return this.ip.split('.').slice(0, n).join('.');
                },
            }));

        const nextPageLinks = $(html).find('a[href^=online][rel=next]');
        if (!nextPageLinks.length) {
            return users;
        }

        const nextPageUrl = nextPageLinks[0].href;
        return users.concat(await loadOnlineUsers(nextPageUrl));
    }

    window.detectBots = async function () {
        const users = identify(await loadOnlineUsers());

        const bots = users.filter(u => u.isBot());

        const mapToOutput = u => ({ ip: u.ip, useragent: u.useragent, detections: u.detections.join(', ') });
        console.log(`${bots.length} bots, ${users.length - bots.length} normal users`);
        console.log('Bots:');
        console.log(bots.map(mapToOutput));
        console.log('Normal users:');
        console.log(users.filter(u => !u.isBot()).map(mapToOutput));

        window.onlineUsers = users;
    };

    let _db = null;

    function db() {
        if (!_db) {
            _db = new Dexie('UserLogDatabase');
            _db.version(1).stores({ users: '++, date, ip, useragent, *detections' });
        }
        return _db;
    }

    window.userLogsDb = db;

    window.logUsers = async function () {
        const users = identify(await loadOnlineUsers());

        await db().users.bulkPut(users.map(u => ({
            date: new Date(),
            ip: u.ip,
            useragent: u.useragent,
            detections: u.detections,
        })));
        console.log(`Saved ${users.length} users to db`);
    };

    window.startLogDaemon = async function () {
        while (true) {
            try {
                await logUsers();
            } catch (e) {
                console.log(e);
            }

            await sleep(20 * 60 * 1000);
        }
    };
})();
<commit_msg>query<commit_after>// ==UserScript==
// @name         ProgrammersForum Detect Bots
// @namespace    programmersforum.ru
// @version      1.4.0
// @description  adds detectBots function that loads the list of online users and counts bots, and logUsers/startLogDaemon functions to save users into IndexedDB
// @author       Alex P
// @include      *programmersforum.ru/*
// @require      https://unpkg.com/dexie@2.0.4/dist/dexie.js
// @require      https://cdn.jsdelivr.net/npm/file-saver@2.0.2/dist/FileSaver.min.js
// @require      https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js
// @require      https://unpkg.com/papaparse@5.1.0/papaparse.min.js
// @grant        none
// @downloadURL  https://github.com/AlexP11223/ProgForumRuUserscripts/raw/master/pf_detect_bots.user.js
// ==/UserScript==

(function () {
    'use strict';

    function countItems(arr) {
        return arr.reduce((acc, item) => {
            acc[item] = acc[item] ? acc[item] + 1 : 1;
            return acc;
        }, {});
    }

    function sleep(ms) {
        return new Promise(resolve => setTimeout(resolve, ms));
    }

    function identify(users) {
        const botUaParts = [
            'bot', 'crawl', 'spider', 'batch', 'bing',
            'share', 'preview', 'facebook', 'vk.com',
            'curl', 'indy', 'http',
            'media', 'metrics', '(compatible)',
            'zh-cn', 'zh_cn', 'mb2345', 'liebao', 'micromessenger', 'kinza', // chinese https://www.johnlarge.co.uk/blocking-aggressive-chinese-crawlers-scrapers-bots/
        ];

        const ipCounts = countItems(users.map(u => u.ip));
        const subnet3Counts = countItems(users.map(u => u.subnet(3)));
        const subnet2Counts = countItems(users.map(u => u.subnet(2)));

        const detectors = [
            user => user.useragent.length < 20 || botUaParts.some(s => user.useragent.includes(s)) ? 'ua' : null,
            user => ipCounts[user.ip] > 2 ? 'ip' : null,
            user => subnet3Counts[user.subnet(3)] > 5 ? 'subnet3' : null,
            user => subnet2Counts[user.subnet(2)] > 20 ? 'subnet2' : null,
        ];

        return users.map(user => {
            const detections = detectors.map(d => d(user)).filter(Boolean);
            return Object.assign(user, {
                detections,
                isBot: function () {
                    return this.detections.length;
                },
            })
        });
    }

    async function loadOnlineUsers(url = '/online.php?s=&sortfield=time&sortorder=desc&who=all&ua=1&pp=200') {
        console.log(`Loading ${url}`);
        const html = await $.get(url);

        const users = $(html).find('[id^=resolveip]').toArray()
            .map(el => ({
                ip: $(el).text().trim(),
                useragent: $(el).parent().text().trim().split('\n').slice(-1)[0].toLowerCase().trim(),
                subnet: function (n) {
                    return this.ip.split('.').slice(0, n).join('.');
                },
            }));

        const nextPageLinks = $(html).find('a[href^=online][rel=next]');
        if (!nextPageLinks.length) {
            return users;
        }

        const nextPageUrl = nextPageLinks[0].href;
        return users.concat(await loadOnlineUsers(nextPageUrl));
    }

    window.detectBots = async function () {
        const users = identify(await loadOnlineUsers());

        const bots = users.filter(u => u.isBot());

        const mapToOutput = u => ({ ip: u.ip, useragent: u.useragent, detections: u.detections.join(', ') });
        console.log(`${bots.length} bots, ${users.length - bots.length} normal users`);
        console.log('Bots:');
        console.log(bots.map(mapToOutput));
        console.log('Normal users:');
        console.log(users.filter(u => !u.isBot()).map(mapToOutput));

        window.onlineUsers = users;
    };

    let _db = null;

    function db() {
        if (!_db) {
            _db = new Dexie('UserLogDatabase');
            _db.version(1).stores({ users: '++, date, ip, useragent, *detections' });
        }
        return _db;
    }

    window.userLogsDb = db;

    window.logUsers = async function () {
        const users = identify(await loadOnlineUsers());

        await db().users.bulkPut(users.map(u => ({
            date: new Date(),
            ip: u.ip,
            useragent: u.useragent,
            detections: u.detections,
        })));
        console.log(`Saved ${users.length} users to db`);
    };

    window.startLogDaemon = async function () {
        while (true) {
            try {
                await logUsers();
            } catch (e) {
                console.log(e);
            }

            await sleep(20 * 60 * 1000);
        }
    };

    window.filterUserLogs = async function (filter = () => true, startDate = moment().subtract(10, 'years').toDate(), endDate = moment().toDate()) {
        return await db().users
            .where('date').between(startDate, endDate)
            .and(filter)
            .toArray();
    };
})();
<|endoftext|>


<commit_before>/** The FlamingLayer Class **/

/**
 * @constructor
 * @augments Layer
 * @description The superclass for all flamingolayers
 * @param id The id of the layer
 * @param options The options to be given to the layer
 * @param flamingoObject The flamingo object of the layer
 *
 */

Ext.define("viewer.viewercontroller.flamingo.FlamingoLayer",{
    enabledEvents: null,
    type: null,
    constructor :function (config){
        if (config.id){
            config.id=""+config.id;
        }
        if((config.id).indexOf(":") != -1){
            config.id = (config.id).replace(/:/g,'_');
        }
        this.enabledEvents=new Object();
        return this;
    },
    /**
     * Get's the frameworklayer: the viewer specific layer.
     */
    getFrameworkLayer : function(){
        if (this.map==null){
            return null;
        }
        return this.map.getFrameworkMap();
    },

    toXML : function(){
        Ext.Error.raise({msg: "FlamingoLayer.toXML(): .toXML() must be made!"});
    },

    getTagName : function(){
        Ext.Error.raise({msg: "FlamingoLayer.getTagName: .getTagName() must be made!"});
    },
    setOption : function(optionKey,optionValue){
        this.options[optionKey]=optionValue;
    },
    getId : function(){
        return this.id;
    },
    getFrameworkId: function(){
        return this.map.getId()+"_"+this.getId();
    },
    setAlpha : function (alpha){
        this.map.getFrameworkMap().callMethod(this.getFrameworkId(),"setAlpha",alpha)
    },
    getAlpha : function (){
        return this.map.getFrameworkMap().callMethod(this.getFrameworkId(),"getAlpha");
    },
    /**
     * Get the last getMap request array
     * @see viewer.viewerController.controller.Layer#getLastMapRequest
     */
    getLastMapRequest: function(){
        var request=this.map.getFrameworkMap().callMethod(this.getFrameworkId(),"getLastGetMapRequest");
        if (request==null){
            return null;
        }
        return [request];
    },
    /**
     * Returns the type of the layer.
     */
    getType: function(){
        return this.type;
    },
    update: function(){
        return this.map.getFrameworkMap().callMethod(this.getFrameworkId(),"update");
    },
    /**
     * Overwrites the addListener function. Add's the event to allowexternalinterface of flamingo
     * so flamingo is allowed to broadcast the event.
     */
    addListener : function(event,handler,scope){
       // viewer.viewercontroller.flamingo.FlamingoLayer.superclass.addListener.call(this,event,handler,scope);
        //enable flamingo event broadcasting
        var flamEvent=this.map.mapComponent.eventList[event];
        if (flamEvent!=undefined){
            //if not enabled yet, add it
            if (this.enabledEvents[flamEvent]==undefined){
               this.map.getFrameworkMap().callMethod(this.map.mapComponent.getId(),"addAllowExternalInterface",this.getFrameworkId()+"."+flamEvent);
               this.enabledEvents[flamEvent]=true;
            }
        }
    },
    setVisible : function (visible){
        this.map.getFrameworkMap().callMethod(this.map.id + "_" + this.id, "setVisible", visible);
        this.visible = visible;
        if (this.options!=null)
            this.options["visible"] = visible;
    }

});<commit_msg>Don't crash when there is no config.id<commit_after>/** The FlamingLayer Class **/

/**
 * @constructor
 * @augments Layer
 * @description The superclass for all flamingolayers
 * @param id The id of the layer
 * @param options The options to be given to the layer
 * @param flamingoObject The flamingo object of the layer
 *
 */

Ext.define("viewer.viewercontroller.flamingo.FlamingoLayer",{
    enabledEvents: null,
    type: null,
    constructor :function (config){
        if (config.id){
            config.id=""+config.id;
            if((config.id).indexOf(":") != -1){
                config.id = (config.id).replace(/:/g,'_');
            }
        }
        this.enabledEvents=new Object();
        return this;
    },
    /**
     * Get's the frameworklayer: the viewer specific layer.
     */
    getFrameworkLayer : function(){
        if (this.map==null){
            return null;
        }
        return this.map.getFrameworkMap();
    },

    toXML : function(){
        Ext.Error.raise({msg: "FlamingoLayer.toXML(): .toXML() must be made!"});
    },

    getTagName : function(){
        Ext.Error.raise({msg: "FlamingoLayer.getTagName: .getTagName() must be made!"});
    },
    setOption : function(optionKey,optionValue){
        this.options[optionKey]=optionValue;
    },
    getId : function(){
        return this.id;
    },
    getFrameworkId: function(){
        return this.map.getId()+"_"+this.getId();
    },
    setAlpha : function (alpha){
        this.map.getFrameworkMap().callMethod(this.getFrameworkId(),"setAlpha",alpha)
    },
    getAlpha : function (){
        return this.map.getFrameworkMap().callMethod(this.getFrameworkId(),"getAlpha");
    },
    /**
     * Get the last getMap request array
     * @see viewer.viewerController.controller.Layer#getLastMapRequest
     */
    getLastMapRequest: function(){
        var request=this.map.getFrameworkMap().callMethod(this.getFrameworkId(),"getLastGetMapRequest");
        if (request==null){
            return null;
        }
        return [request];
    },
    /**
     * Returns the type of the layer.
     */
    getType: function(){
        return this.type;
    },
    update: function(){
        return this.map.getFrameworkMap().callMethod(this.getFrameworkId(),"update");
    },
    /**
     * Overwrites the addListener function. Add's the event to allowexternalinterface of flamingo
     * so flamingo is allowed to broadcast the event.
     */
    addListener : function(event,handler,scope){
       // viewer.viewercontroller.flamingo.FlamingoLayer.superclass.addListener.call(this,event,handler,scope);
        //enable flamingo event broadcasting
        var flamEvent=this.map.mapComponent.eventList[event];
        if (flamEvent!=undefined){
            //if not enabled yet, add it
            if (this.enabledEvents[flamEvent]==undefined){
               this.map.getFrameworkMap().callMethod(this.map.mapComponent.getId(),"addAllowExternalInterface",this.getFrameworkId()+"."+flamEvent);
               this.enabledEvents[flamEvent]=true;
            }
        }
    },
    setVisible : function (visible){
        this.map.getFrameworkMap().callMethod(this.map.id + "_" + this.id, "setVisible", visible);
        this.visible = visible;
        if (this.options!=null)
            this.options["visible"] = visible;
    }

});<|endoftext|>


<commit_before>/**
 * Display a notification
 * @param {string} text  Notification text
 * @param {string} [type=notice]  Notofication type (one of: notice, error, success)
 */
Gittip.notification = function(text, type, timeout) {
    var type = type || 'notice';
    var timeout = timeout || 10000;

    var dialog = ['div', { 'class': 'notification notification-' + type }, [ 'div', text ]];
    var $dialog = $([
        Gittip.jsonml(dialog),
        Gittip.jsonml(dialog)
    ]);

    if (!$('#notification-area').length)
        $('body').prepend('

');

    $('#notification-area').prepend($dialog.get(0));
    $('#notification-area .notifications-fixed').prepend($dialog.get(1));

    function fadeOut() {
        $dialog.addClass('fade-out');
    }

    $dialog.on('click', fadeOut);
    if (timeout > 0) setTimeout(fadeOut, timeout);
};
<commit_msg>fix typo<commit_after>/**
 * Display a notification
 * @param {string} text  Notification text
 * @param {string} [type=notice]  Notification type (one of: notice, error, success)
 */
Gittip.notification = function(text, type, timeout) {
    var type = type || 'notice';
    var timeout = timeout || 10000;

    var dialog = ['div', { 'class': 'notification notification-' + type }, [ 'div', text ]];
    var $dialog = $([
        Gittip.jsonml(dialog),
        Gittip.jsonml(dialog)
    ]);

    if (!$('#notification-area').length)
        $('body').prepend('

');

    $('#notification-area').prepend($dialog.get(0));
    $('#notification-area .notifications-fixed').prepend($dialog.get(1));

    function fadeOut() {
        $dialog.addClass('fade-out');
    }

    $dialog.on('click', fadeOut);
    if (timeout > 0) setTimeout(fadeOut, timeout);
};
<|endoftext|>


<commit_before>(function(Browser) {

	Browser.Views = Browser.Views || {};
	Browser.Views.FancyBox = Browser.Views.FancyBox || {};

	Browser.Views.FancyBox.Video = Browser.Views._Fancybox.extend({
		initialize: function()
		{
			Browser.Views._Fancybox.prototype.initialize.call(this); //This is like calling super()
		},

		/* Pass in the element that the user clicked on from fancybox. */

	/* Pass in the element that the user clicked on from fancybox. */
	render: function(obj)
	{

		sessionStorage.setItem('currentItemId', this.model.id);

		//Call parent class to do captioning and metadata
		Browser.Views._Fancybox.prototype.render.call(this, obj); //This is like calling super()

		this.unique =Math.floor(Math.random() *10000)
		$(this.el).find('.fancybox-media-item').append($('<div>').attr({id:'fancybox-video-'+this.unique}).addClass('fancybox-shrinkable'));

		//set fancybox content
		obj.content = $(this.el);

		return this;
	},
	afterShow:function(){

		switch( this.model.get("layer_type") )
			{

				case 'Video':
					var source = this.model.get('uri');
					this.plyr = new Plyr('fancybox-video-'+this.unique,{url:source,controls:1});
					break;
				case 'Youtube':
					var source = "http://www.youtube.com/watch?v="+this.model.get('uri');
					this.plyr = new Plyr('fancybox-video-'+this.unique,{url:source,controls:1});
					break;
				case 'Vimeo':
					var source = "http://vimeo.com/"+this.model.get('uri');
					this.plyr = new Plyr('fancybox-video-'+this.unique,{url:source,controls:0});
					break;

			}

	},

	beforeClose: function(){
		this.plyr.destroy();

	},

});

})(jda.module("browser"));<commit_msg>fixes #136<commit_after>(function(Browser) {

	Browser.Views = Browser.Views || {};
	Browser.Views.FancyBox = Browser.Views.FancyBox || {};

	Browser.Views.FancyBox.Video = Browser.Views._Fancybox.extend({
		initialize: function()
		{
			Browser.Views._Fancybox.prototype.initialize.call(this); //This is like calling super()
		},

		/* Pass in the element that the user clicked on from fancybox. */

	/* Pass in the element that the user clicked on from fancybox. */
	render: function(obj)
	{

		sessionStorage.setItem('currentItemId', this.model.id);

		//Call parent class to do captioning and metadata
		Browser.Views._Fancybox.prototype.render.call(this, obj); //This is like calling super()

		this.unique =Math.floor(Math.random() *10000)
		$(this.el).find('.fancybox-media-item').append($('<div>').attr({id:'fancybox-video-'+this.unique}).addClass('fancybox-shrinkable'));

		//set fancybox content
		obj.content = $(this.el);

		return this;
	},
	afterShow:function(){

		Browser.Views._Fancybox.prototype.afterShow.call(this);
		switch( this.model.get("layer_type") )
			{

				case 'Video':
					var source = this.model.get('uri');
					this.plyr = new Plyr('fancybox-video-'+this.unique,{url:source,controls:1});
					break;
				case 'Youtube':
					var source = "http://www.youtube.com/watch?v="+this.model.get('uri');
					this.plyr = new Plyr('fancybox-video-'+this.unique,{url:source,controls:1});
					break;
				case 'Vimeo':
					var source = "http://vimeo.com/"+this.model.get('uri');
					this.plyr = new Plyr('fancybox-video-'+this.unique,{url:source,controls:0});
					break;

			}

	},

	beforeClose: function(){
		this.plyr.destroy();

	},

});

})(jda.module("browser"));<|endoftext|>


<commit_before>// --- SITE SETTINGS
mm.sites.get({
  siteId: '',
  siteName: ''
});

mm.sites.scripts.get({
  siteId: '',
  siteName: ''
});

mm.sites.actions.get({
  siteId: '',
  siteName: ''
});

mm.sites.scripts.update({
  siteId: '',
  siteName: '',
  scriptId: '',
  scriptName: '',

  name: '',
  description: '',
  content: ''
});

// --- CAMPAIGN SETTINGS
// campaigns
mm.campaigns.get({
  siteId: '',
  siteName: '',
  campaignId: '',
  campaignName: ''
});

mm.campaigns.create({
  siteId: '',
  siteName: '',

  name: 'a3-test',
  description: 'a3-test description'
});

// elements
mm.elements.create({
  siteId: '',
  siteName: '',
  campaignId: '',
  campaignName: ''
})

mm.elements.create({
  siteId: '',
  siteName: '',
  campaignId: '',
  campaignName: '',

  name: '',
  description: ''
});

// variants
mm.variants.get({
  siteId: '',
  siteName: '',
  campaignId: '',
  campaignName: '',
  elementId: '',
  elementName: ''
});

mm.variants.create({
  siteId: '',
  siteName: '',
  campaignId: '',
  campaignName: '',
  elementId: '',
  elementName: '',

  name: '',
  description: '',
  name: '',
  content: '',
  isControl: '',
  weight: ''
});

mm.variants.update({
  siteId: '',
  siteName: '',
  campaignId: '',
  campaignName: '',
  elementId: '',
  elementName: '',

  name: '',
  description: '',
  name: '',
  content: '',
  isControl: '',
  weight: ''
});

// scripts
mm.campaigns.scripts.get({
  siteId: '',
  siteName: '',
  campaignId: '',
  campaignName: ''
});

mm.campaigns.scripts.create({
  siteId: '',
  siteName: '',
  campaignId: '',
  campaignName: '',

  name: '',
  content: ''
  description: ''
});

mm.campaigns.scripts.update({
  siteId: '',
  siteName: '',
  campaignId: '',
  campaignName: '',

  name: '',
  content: ''
  description: ''
});

// actions
mm.campaigns.actions.get({
  siteId: '',
  siteName: '',
  campaignId: '',
  campaignName: ''
});
<commit_msg>remove api-refs<commit_after><|endoftext|>


<commit_before>// Copyright (c) 2011-2012 UX Productivity Pty Ltd. All rights reserved.

var Styles_getAllStyles;
var Styles_updateStyle;
var Styles_addDefaultRule;
var Styles_addDefaultRuleCategory;
var Styles_discoverStyles;
var Styles_init;

(function() {

    // FIXME: We should have a separate HTML style element for each style, so we only have to
    // update that one style each time we make a change. We should measure the performance benefit
    // of doing so first. If we use multiple style elements, we should consolidate them before
    // saving the file.

    var HTML_DISPLAY_NAMES = {
        "BODY": "Document defaults",
        "TABLE": "Table",
        "CAPTION": "Table caption",
        "FIGURE": "Figure",
        "FIGCAPTION": "Figure caption",
        "UL": "Bulleted list",
        "OL": "Numbered list",
        "P": "Normal paragraph",
        "H1": "Heading 1",
        "H2": "Heading 2",
        "H3": "Heading 3",
        "H4": "Heading 4",
        "H5": "Heading 5",
        "H6": "Heading 6",
        "PRE": "Preformatted text",
        "BLOCKQUOTE": "Block quote"
    };

    function Style(styleId,displayName,rules)
    {
        this.styleId = styleId;
        this.displayName = displayName;
        this.rules = rules;
    }

    function Rule(selector,properties)
    {
        this.selector = selector;
        this.properties = properties;
        this.nilTextIfEmpty = false;
    }

    var styleList = null;
    var stylesById = null;
    var rulesBySelector = null;
    var documentStyleElement = null;
    var cssTextDirty = false;

    var defaultRuleCategories = {
        "td-paragraph-margins": {
            "td > p:first-child": {"margin-top": "0"},
            "td > p:last-child": {"margin-bottom": "0"},
        },
        "th-paragraph-margins": {
            "th > p:first-child": {"margin-top": "0"},
            "th > p:last-child": {"margin-bottom": "0"},
        },
        "table-borders": {
            "table": {"border-collapse": "collapse"},
            "td": {"border": "1px solid black"},
        },
        "table-caption": {
            "caption": {"caption-side": "bottom"},
        },
    };

    function stringsAllEqual(strings)
    {
        var first = strings[0];
        for (var i = 1; i < strings.length; i++) {
            if (first != strings[i])
                return false;
        }
        return true;
    }

    function condenseProperties(properties)
    {
        // Make a copy of cssProperties because we want to make some changes before preparing the
        // CSS text, while leaving the object itself unchanged
        properties = clone(properties);

        if ((properties["margin-left"] != null) &&
            stringsAllEqual(properties["margin-left"],
                            properties["margin-right"],
                            properties["margin-top"],
                            properties["margin-bottom"])) {
            properties["margin"] = properties["margin-left"];
            delete properties["margin-left"];
            delete properties["margin-right"];
            delete properties["margin-top"];
            delete properties["margin-bottom"];
        }

        var borderLeft = "";
        var borderRight = "";
        var borderTop = "";
        var borderBottom = "";

        if (properties["border-left-width"] != null)
            borderLeft += " " + properties["border-left-width"];
        if (properties["border-right-width"] != null)
            borderRight += " " + properties["border-right-width"];
        if (properties["border-top-width"] != null)
            borderTop += " " + properties["border-top-width"];
        if (properties["border-bottom-width"] != null)
            borderBottom += " " + properties["border-bottom-width"];

        if (properties["border-left-style"] != null)
            borderLeft += " " + properties["border-left-style"];
        if (properties["border-right-style"] != null)
            borderRight += " " + properties["border-right-style"];
        if (properties["border-top-style"] != null)
            borderTop += " " + properties["border-top-style"];
        if (properties["border-bottom-style"] != null)
            borderBottom += " " + properties["border-bottom-style"];

        if (properties["border-left-color"] != null)
            borderLeft += " " + properties["border-left-color"];
        if (properties["border-right-color"] != null)
            borderRight += " " + properties["border-right-color"];
        if (properties["border-top-color"] != null)
            borderTop += " " + properties["border-top-color"];
        if (properties["border-bottom-color"] != null)
            borderBottom += " " + properties["border-bottom-color"];

        if ((borderLeft.length > 0) &&
            (borderLeft == borderRight) &&
            (borderLeft == borderTop) &&
            (borderLeft == borderBottom)) {
            properties["border"] = borderLeft.substring(1);
        }
        else {
            if (borderLeft.length > 0)
                properties["border-left"] = borderLeft.substring(1);
            if (borderRight.length > 0)
                properties["border-right"] = borderRight.substring(1);
            if (borderTop.length > 0)
                properties["border-top"] = borderTop.substring(1);
            if (borderBottom.length > 0)
                properties["border-bottom"] = borderBottom.substring(1);
        }

        delete properties["border-left-width"];
        delete properties["border-right-width"];
        delete properties["border-top-width"];
        delete properties["border-bottom-width"];

        delete properties["border-left-style"];
        delete properties["border-right-style"];
        delete properties["border-top-style"];
        delete properties["border-bottom-style"];

        delete properties["border-left-color"];
        delete properties["border-right-color"];
        delete properties["border-top-color"];
        delete properties["border-bottom-color"];

        if ((properties["border-top-left-radius"] != null) &&
            stringsAllEqual(properties["border-top-left-radius"],
                            properties["border-top-right-radius"],
                            properties["border-bottom-left-radius"],
                            properties["border-bottom-right-radius"])) {
            properties["border-radius"] = properties["border-top-left-radius"];
            delete properties["border-top-left-radius"];
            delete properties["border-top-right-radius"];
            delete properties["border-bottom-left-radius"];
            delete properties["border-bottom-right-radius"];
        }

        if ((properties["padding-left"] != null) &&
            stringsAllEqual(properties["padding-left"],
                            properties["padding-right"],
                            properties["padding-top"],
                            properties["padding-bottom"])) {
            properties["padding"] = properties["padding-left"];
            delete properties["padding-left"];
            delete properties["padding-right"];
            delete properties["padding-top"];
            delete properties["padding-bottom"];
        }
        return properties;
    }

    function propertyListText(properties)
    {
        properties = condenseProperties(properties);

        if ((properties["font-family"] != null) &&
            (properties["font-family"].match(/\s+/))) {
            properties["font-family"] = JSON.stringify(properties["font-family"]);
        }

        var lines = new Array();
        var keys = Object.getOwnPropertyNames(properties).sort();
        for (var i = 0; i < keys.length; i++) {
            lines.push("    "+keys[i]+": "+properties[keys[i]]+";\n");
        }
        return lines.join("");
    }

    // Unfortunately, modifying the CSS stylesheet object associated with a style element
    // does not cause its text content to be updated. Thus, we have to do it ourselves.
    // To avoid doing this multiple times for a single editing operation, call the
    // scheduleApplyCSSTextChanges() function, which will cause the changes to be applied
    // when PostponedActions_perform() is next called.
    function applyCSSTextChanges()
    {
        if (cssTextDirty) {
            cssTextDirty = false;

            var styleElement = getOrCreateStyleElement();
            var cssTextArray = new Array();

            var selectors = Object.getOwnPropertyNames(rulesBySelector).sort();
            for (var i = 0; i < selectors.length; i++) {
                var rule = rulesBySelector[selectors[i]];
                var text = propertyListText(rule.properties);
                if ((text != "") || !rule.nilTextIfEmpty)
                    cssTextArray.push(rule.selector+" {\n"+text+"}\n");
            }
            var allCSSText = cssTextArray.join("");

            DOM_deleteAllChildren(styleElement);
            DOM_appendChild(styleElement,DOM_createTextNode(document,allCSSText));
        }
    }

    function scheduleApplyCSSTextChanges()
    {
        cssTextDirty = true;
        PostponedActions_add(applyCSSTextChanges);
    }

    function canonicaliseSelector(selector)
    {
        // FIXME: are class names case sensitive?
        return selector.toLowerCase().replace(/\s+/g," ");
    }

    function getOrCreateStyleElement()
    {
        if (documentStyleElement != null)
            return documentStyleElement;
        var head = DOM_documentHead(document);
        for (var child = head.lastChild; child != null; child = child.previousSibling) {
            if (DOM_upperName(child) == "STYLE") {
                documentStyleElement = child;
                return documentStyleElement;
            }
        }
        documentStyleElement = DOM_createElement(document,"STYLE");
        documentStyleElement.setAttribute("type","text/css");
        DOM_appendChild(head,documentStyleElement);
        return documentStyleElement;
    }

    // public
    function getAllStyles()
    {
        return styleList;
    }

    // public
    function updateStyle(style)
    {
    }

    // public
    function addDefaultRule(selector,defaultProperties)
    {
        selector = canonicaliseSelector(selector);

        if (rulesBySelector[selector] == null)
            rulesBySelector[selector] = new Rule(selector,{});

        var rule = rulesBySelector[selector];

        for (name in defaultProperties) {
            if (rule.properties[name] == null)
                rule.properties[name] = defaultProperties[name];
        }

        scheduleApplyCSSTextChanges();
    }

    // public
    function addDefaultRuleCategory(category)
    {
        var selectors = defaultRuleCategories[category];
        if (selectors == null)
            throw new Error("No default rule category \""+category+"\"");
        var names = Object.getOwnPropertyNames(selectors).sort();
        for (var i = 0; i < names.length; i++) {
            addDefaultRule(names[i],selectors[names[i]]);
        }
    }

    function addStyleFromCSS(selector,properties)
    {
        selector = canonicaliseSelector(selector);
        var displayName = displayNameForSelector(selector);
        var rule = new Rule(selector,properties);
        var style = new Style(selector,displayName,{base: rule});
        styleList.push(style);
        stylesById[selector] = style;
        rulesBySelector[selector] = rule;
        return style;
    }

    function addStyleIfNotPresent(selector)
    {
        if (stylesById[selector] == null) {
            var style = addStyleFromCSS(selector,{});
            style.rules.base.nilTextIfEmpty = true;
        }
    }

    // public
    function discoverStyles()
    {
        styleList = new Array();
        stylesById = new Object();
        rulesBySelector = new Object();

        for (var i = 0; i < document.styleSheets.length; i++) {
            var sheet = document.styleSheets[i];
            var str = "";
            for (name in sheet)
                str += name+"\n";
            for (var j = 0; j < sheet.cssRules.length; j++) {
                var rule = sheet.cssRules[j];
                if (rule.type == CSSRule.STYLE_RULE) {
                    var properties = new Object();
                    for (k = 0; k < rule.style.length; k++)
                        properties[rule.style[k]] = rule.style.getPropertyValue(rule.style[k]);

                    addStyleFromCSS(rule.selectorText,properties);
                }
            }
        }
    }

    function displayNameForSelector(selector)
    {
        selector = selector.replace(/_/g," ");
        var uppercaseSelector = selector.toUpperCase();
        var name = HTML_DISPLAY_NAMES[uppercaseSelector];
        if (name != null)
            return name;
        else if ((selector.length > 0) && (selector.charAt(0) == "."))
            return selector.substring(1);
        else
            return selector;
    }

    // public
    function init()
    {
        Styles_discoverStyles();

        addStyleIfNotPresent("BODY");
        addStyleIfNotPresent("UL");
        addStyleIfNotPresent("OL");
        addStyleIfNotPresent("P");
        addStyleIfNotPresent("H1");
        addStyleIfNotPresent("H2");
        addStyleIfNotPresent("H3");
        addStyleIfNotPresent("H4");
        addStyleIfNotPresent("H5");
        addStyleIfNotPresent("H6");
        addStyleIfNotPresent("PRE");
        addStyleIfNotPresent("BLOCKQUOTE");
        addStyleIfNotPresent("TABLE");
        addStyleIfNotPresent("CAPTION");
        addStyleIfNotPresent("FIGURE");
        addStyleIfNotPresent("FIGCAPTION");
    }

    Styles_getAllStyles = trace(getAllStyles);
    Styles_updateStyle = trace(updateStyle);
    Styles_addDefaultRule = trace(addDefaultRule);
    Styles_addDefaultRuleCategory = trace(addDefaultRuleCategory);
    Styles_discoverStyles = trace(discoverStyles);
    Styles_init = trace(init);

    condenseProperties = trace(condenseProperties);
    propertyListText = trace(propertyListText);
    applyCSSTextChanges = trace(applyCSSTextChanges);

})();
<commit_msg>Added a type field to CSSStyle<commit_after>// Copyright (c) 2011-2012 UX Productivity Pty Ltd. All rights reserved.

var Styles_getAllStyles;
var Styles_updateStyle;
var Styles_addDefaultRule;
var Styles_addDefaultRuleCategory;
var Styles_discoverStyles;
var Styles_init;

(function() {

    // FIXME: We should have a separate HTML style element for each style, so we only have to
    // update that one style each time we make a change. We should measure the performance benefit
    // of doing so first. If we use multiple style elements, we should consolidate them before
    // saving the file.

    var HTML_DISPLAY_NAMES = {
        "BODY": "Document defaults",
        "TABLE": "Table",
        "CAPTION": "Table caption",
        "FIGURE": "Figure",
        "FIGCAPTION": "Figure caption",
        "UL": "Bulleted list",
        "OL": "Numbered list",
        "P": "Normal paragraph",
        "H1": "Heading 1",
        "H2": "Heading 2",
        "H3": "Heading 3",
        "H4": "Heading 4",
        "H5": "Heading 5",
        "H6": "Heading 6",
        "PRE": "Preformatted text",
        "BLOCKQUOTE": "Block quote"
    };

    function Style(styleId,displayName,rules)
    {
        this.styleId = styleId;
        this.displayName = displayName;
        this.rules = rules;
        this.type = null;
    }

    function Rule(selector,properties)
    {
        this.selector = selector;
        this.properties = properties;
        this.nilTextIfEmpty = false;
    }

    var styleList = null;
    var stylesById = null;
    var rulesBySelector = null;
    var documentStyleElement = null;
    var cssTextDirty = false;

    var defaultRuleCategories = {
        "td-paragraph-margins": {
            "td > p:first-child": {"margin-top": "0"},
            "td > p:last-child": {"margin-bottom": "0"},
        },
        "th-paragraph-margins": {
            "th > p:first-child": {"margin-top": "0"},
            "th > p:last-child": {"margin-bottom": "0"},
        },
        "table-borders": {
            "table": {"border-collapse": "collapse"},
            "td": {"border": "1px solid black"},
        },
        "table-caption": {
            "caption": {"caption-side": "bottom"},
        },
    };

    function stringsAllEqual(strings)
    {
        var first = strings[0];
        for (var i = 1; i < strings.length; i++) {
            if (first != strings[i])
                return false;
        }
        return true;
    }

    function condenseProperties(properties)
    {
        // Make a copy of cssProperties because we want to make some changes before preparing the
        // CSS text, while leaving the object itself unchanged
        properties = clone(properties);

        if ((properties["margin-left"] != null) &&
            stringsAllEqual(properties["margin-left"],
                            properties["margin-right"],
                            properties["margin-top"],
                            properties["margin-bottom"])) {
            properties["margin"] = properties["margin-left"];
            delete properties["margin-left"];
            delete properties["margin-right"];
            delete properties["margin-top"];
            delete properties["margin-bottom"];
        }

        var borderLeft = "";
        var borderRight = "";
        var borderTop = "";
        var borderBottom = "";

        if (properties["border-left-width"] != null)
            borderLeft += " " + properties["border-left-width"];
        if (properties["border-right-width"] != null)
            borderRight += " " + properties["border-right-width"];
        if (properties["border-top-width"] != null)
            borderTop += " " + properties["border-top-width"];
        if (properties["border-bottom-width"] != null)
            borderBottom += " " + properties["border-bottom-width"];

        if (properties["border-left-style"] != null)
            borderLeft += " " + properties["border-left-style"];
        if (properties["border-right-style"] != null)
            borderRight += " " + properties["border-right-style"];
        if (properties["border-top-style"] != null)
            borderTop += " " + properties["border-top-style"];
        if (properties["border-bottom-style"] != null)
            borderBottom += " " + properties["border-bottom-style"];

        if (properties["border-left-color"] != null)
            borderLeft += " " + properties["border-left-color"];
        if (properties["border-right-color"] != null)
            borderRight += " " + properties["border-right-color"];
        if (properties["border-top-color"] != null)
            borderTop += " " + properties["border-top-color"];
        if (properties["border-bottom-color"] != null)
            borderBottom += " " + properties["border-bottom-color"];

        if ((borderLeft.length > 0) &&
            (borderLeft == borderRight) &&
            (borderLeft == borderTop) &&
            (borderLeft == borderBottom)) {
            properties["border"] = borderLeft.substring(1);
        }
        else {
            if (borderLeft.length > 0)
                properties["border-left"] = borderLeft.substring(1);
            if (borderRight.length > 0)
                properties["border-right"] = borderRight.substring(1);
            if (borderTop.length > 0)
                properties["border-top"] = borderTop.substring(1);
            if (borderBottom.length > 0)
                properties["border-bottom"] = borderBottom.substring(1);
        }

        delete properties["border-left-width"];
        delete properties["border-right-width"];
        delete properties["border-top-width"];
        delete properties["border-bottom-width"];

        delete properties["border-left-style"];
        delete properties["border-right-style"];
        delete properties["border-top-style"];
        delete properties["border-bottom-style"];

        delete properties["border-left-color"];
        delete properties["border-right-color"];
        delete properties["border-top-color"];
        delete properties["border-bottom-color"];

        if ((properties["border-top-left-radius"] != null) &&
            stringsAllEqual(properties["border-top-left-radius"],
                            properties["border-top-right-radius"],
                            properties["border-bottom-left-radius"],
                            properties["border-bottom-right-radius"])) {
            properties["border-radius"] = properties["border-top-left-radius"];
            delete properties["border-top-left-radius"];
            delete properties["border-top-right-radius"];
            delete properties["border-bottom-left-radius"];
            delete properties["border-bottom-right-radius"];
        }

        if ((properties["padding-left"] != null) &&
            stringsAllEqual(properties["padding-left"],
                            properties["padding-right"],
                            properties["padding-top"],
                            properties["padding-bottom"])) {
            properties["padding"] = properties["padding-left"];
            delete properties["padding-left"];
            delete properties["padding-right"];
            delete properties["padding-top"];
            delete properties["padding-bottom"];
        }
        return properties;
    }

    function propertyListText(properties)
    {
        properties = condenseProperties(properties);

        if ((properties["font-family"] != null) &&
            (properties["font-family"].match(/\s+/))) {
            properties["font-family"] = JSON.stringify(properties["font-family"]);
        }

        var lines = new Array();
        var keys = Object.getOwnPropertyNames(properties).sort();
        for (var i = 0; i < keys.length; i++) {
            lines.push("    "+keys[i]+": "+properties[keys[i]]+";\n");
        }
        return lines.join("");
    }

    // Unfortunately, modifying the CSS stylesheet object associated with a style element
    // does not cause its text content to be updated. Thus, we have to do it ourselves.
    // To avoid doing this multiple times for a single editing operation, call the
    // scheduleApplyCSSTextChanges() function, which will cause the changes to be applied
    // when PostponedActions_perform() is next called.
    function applyCSSTextChanges()
    {
        if (cssTextDirty) {
            cssTextDirty = false;

            var styleElement = getOrCreateStyleElement();
            var cssTextArray = new Array();

            var selectors = Object.getOwnPropertyNames(rulesBySelector).sort();
            for (var i = 0; i < selectors.length; i++) {
                var rule = rulesBySelector[selectors[i]];
                var text = propertyListText(rule.properties);
                if ((text != "") || !rule.nilTextIfEmpty)
                    cssTextArray.push(rule.selector+" {\n"+text+"}\n");
            }
            var allCSSText = cssTextArray.join("");

            DOM_deleteAllChildren(styleElement);
            DOM_appendChild(styleElement,DOM_createTextNode(document,allCSSText));
        }
    }

    function scheduleApplyCSSTextChanges()
    {
        cssTextDirty = true;
        PostponedActions_add(applyCSSTextChanges);
    }

    function canonicaliseSelector(selector)
    {
        // FIXME: are class names case sensitive?
        return selector.toLowerCase().replace(/\s+/g," ");
    }

    function getOrCreateStyleElement()
    {
        if (documentStyleElement != null)
            return documentStyleElement;
        var head = DOM_documentHead(document);
        for (var child = head.lastChild; child != null; child = child.previousSibling) {
            if (DOM_upperName(child) == "STYLE") {
                documentStyleElement = child;
                return documentStyleElement;
            }
        }
        documentStyleElement = DOM_createElement(document,"STYLE");
        documentStyleElement.setAttribute("type","text/css");
        DOM_appendChild(head,documentStyleElement);
        return documentStyleElement;
    }

    // public
    function getAllStyles()
    {
        return styleList;
    }

    // public
    function updateStyle(style)
    {
    }

    // public
    function addDefaultRule(selector,defaultProperties)
    {
        selector = canonicaliseSelector(selector);

        if (rulesBySelector[selector] == null)
            rulesBySelector[selector] = new Rule(selector,{});

        var rule = rulesBySelector[selector];

        for (name in defaultProperties) {
            if (rule.properties[name] == null)
                rule.properties[name] = defaultProperties[name];
        }

        scheduleApplyCSSTextChanges();
    }

    // public
    function addDefaultRuleCategory(category)
    {
        var selectors = defaultRuleCategories[category];
        if (selectors == null)
            throw new Error("No default rule category \""+category+"\"");
        var names = Object.getOwnPropertyNames(selectors).sort();
        for (var i = 0; i < names.length; i++) {
            addDefaultRule(names[i],selectors[names[i]]);
        }
    }

    function addStyleFromCSS(selector,properties)
    {
        selector = canonicaliseSelector(selector);
        var displayName = displayNameForSelector(selector);
        var rule = new Rule(selector,properties);
        var style = new Style(selector,displayName,{base: rule});
        styleList.push(style);
        stylesById[selector] = style;
        rulesBySelector[selector] = rule;
        return style;
    }

    function addStyleIfNotPresent(selector)
    {
        if (stylesById[selector] == null) {
            var style = addStyleFromCSS(selector,{});
            style.rules.base.nilTextIfEmpty = true;
        }
    }

    // public
    function discoverStyles()
    {
        styleList = new Array();
        stylesById = new Object();
        rulesBySelector = new Object();

        for (var i = 0; i < document.styleSheets.length; i++) {
            var sheet = document.styleSheets[i];
            var str = "";
            for (name in sheet)
                str += name+"\n";
            for (var j = 0; j < sheet.cssRules.length; j++) {
                var rule = sheet.cssRules[j];
                if (rule.type == CSSRule.STYLE_RULE) {
                    var properties = new Object();
                    for (k = 0; k < rule.style.length; k++)
                        properties[rule.style[k]] = rule.style.getPropertyValue(rule.style[k]);

                    addStyleFromCSS(rule.selectorText,properties);
                }
            }
        }
    }

    function displayNameForSelector(selector)
    {
        selector = selector.replace(/_/g," ");
        var uppercaseSelector = selector.toUpperCase();
        var name = HTML_DISPLAY_NAMES[uppercaseSelector];
        if (name != null)
            return name;
        else if ((selector.length > 0) && (selector.charAt(0) == "."))
            return selector.substring(1);
        else
            return selector;
    }

    // public
    function init()
    {
        Styles_discoverStyles();

        addStyleIfNotPresent("BODY");
        addStyleIfNotPresent("UL");
        addStyleIfNotPresent("OL");
        addStyleIfNotPresent("P");
        addStyleIfNotPresent("H1");
        addStyleIfNotPresent("H2");
        addStyleIfNotPresent("H3");
        addStyleIfNotPresent("H4");
        addStyleIfNotPresent("H5");
        addStyleIfNotPresent("H6");
        addStyleIfNotPresent("PRE");
        addStyleIfNotPresent("BLOCKQUOTE");
        addStyleIfNotPresent("TABLE");
        addStyleIfNotPresent("CAPTION");
        addStyleIfNotPresent("FIGURE");
        addStyleIfNotPresent("FIGCAPTION");
    }

    Styles_getAllStyles = trace(getAllStyles);
    Styles_updateStyle = trace(updateStyle);
    Styles_addDefaultRule = trace(addDefaultRule);
    Styles_addDefaultRuleCategory = trace(addDefaultRuleCategory);
    Styles_discoverStyles = trace(discoverStyles);
    Styles_init = trace(init);

    condenseProperties = trace(condenseProperties);
    propertyListText = trace(propertyListText);
    applyCSSTextChanges = trace(applyCSSTextChanges);

})();
<|endoftext|>


<commit_before>(function(app) {
  'use strict';

  var helper = app.helper || require('../helper.js');
  var dom = app.dom || require('../dom.js');
  var Component = app.Component || require('./component.js');
  var Main = app.Main || require('./main.js');
  var Sidebar = app.Sidebar || require('./sidebar.js');

  var Body = Component.inherits(function(props) {
    this.dragCount = this.prop(0);
    this.sidebar = new Sidebar({ element: this.childElement('.sidebar') });
    this.main = new Main({ element: this.childElement('.main') });
  });

  Body.prototype.isDragging = function() {
    return (this.dragCount() > 0);
  };

  Body.prototype.incrementDragCount = function() {
    this.dragCount(this.dragCount() + 1);
  };

  Body.prototype.decrementDragCount = function() {
    this.dragCount(this.dragCount() - 1);
  };

  Body.prototype.disabled = function(value) {
    this.sidebar.disabled(value);
    this.main.disabled(value);
  };

  Body.prototype.currentDemoName = function() {
    return dom.urlQuery(dom.location()).demo || '';
  };

  Body.prototype.demoUrl = function(name) {
    return 'demos/' + name + '.json';
  };

  Body.prototype.load = function() {
    return this.sidebar.loadEntries().then(function() {
      return this.loadDemo(this.currentDemoName());
    }.bind(this));
  };

  Body.prototype.loadModule = function(name, x, y) {
    var point = this.main.contentLocalPoint({ x: x, y: y });
    if (point.x < 0 || point.y < 0) {
      return;
    }

    var entry = this.sidebar.entry(name);
    this.main.loadModule(helper.extend({
      title: entry.label,
      name: name,
    }, point), entry.visiblePortNames);
  };

  Body.prototype.loadDemo = function(name) {
    return (name ? this.main.loadUrl(this.demoUrl(name)) : Promise.resolve());
  };

  Body.prototype.oninit = function() {
    dom.ready(Body.prototype.onready.bind(this));
    this.sidebar.on('dragstart', this.ondragstart.bind(this));
    this.sidebar.on('dragend', this.ondragend.bind(this));
    this.sidebar.on('drop', this.ondrop.bind(this));
    this.main.on('sidebartoggle', this.onsidebartoggle.bind(this));
    this.main.on('dragstart', this.ondragstart.bind(this));
    this.main.on('dragend', this.ondragend.bind(this));
    this.main.on('loadstart', this.onloadstart.bind(this));
    this.main.on('loadend', this.onloadend.bind(this));
  };

  Body.prototype.onredraw = function() {
    this.redrawBy('isDragging', function(isDragging) {
      dom.toggleClass(this.element(), 'dragging', isDragging);
    });
  };

  Body.prototype.onready = function() {
    this.disabled(true);
    this.load().catch(function(e) {
      alert(e);
    }).then(function() {
      this.disabled(false);
    }.bind(this));
  };

  Body.prototype.ondragstart = function() {
    this.incrementDragCount();
  };

  Body.prototype.ondragend = function() {
    this.decrementDragCount();
  };

  Body.prototype.ondrop = function(name, x, y) {
    this.loadModule(name, x, y);
  };

  Body.prototype.onsidebartoggle = function() {
    this.sidebar.disabled(!this.sidebar.disabled());
  };

  Body.prototype.onloadstart = function() {
    this.disabled(true);
  };

  Body.prototype.onloadend = function() {
    this.disabled(false);
  };

  if (typeof module !== 'undefined' && module.exports) {
    module.exports = Body;
  } else {
    app.Body = Body;
  }
})(this.app || (this.app = {}));
<commit_msg>Make method to toggle sidebar in body component<commit_after>(function(app) {
  'use strict';

  var helper = app.helper || require('../helper.js');
  var dom = app.dom || require('../dom.js');
  var Component = app.Component || require('./component.js');
  var Main = app.Main || require('./main.js');
  var Sidebar = app.Sidebar || require('./sidebar.js');

  var Body = Component.inherits(function(props) {
    this.dragCount = this.prop(0);
    this.sidebar = new Sidebar({ element: this.childElement('.sidebar') });
    this.main = new Main({ element: this.childElement('.main') });
  });

  Body.prototype.isDragging = function() {
    return (this.dragCount() > 0);
  };

  Body.prototype.incrementDragCount = function() {
    this.dragCount(this.dragCount() + 1);
  };

  Body.prototype.decrementDragCount = function() {
    this.dragCount(this.dragCount() - 1);
  };

  Body.prototype.disabled = function(value) {
    this.sidebar.disabled(value);
    this.main.disabled(value);
  };

  Body.prototype.toggleSidebar = function() {
    this.sidebar.disabled(!this.sidebar.disabled());
  };

  Body.prototype.currentDemoName = function() {
    return dom.urlQuery(dom.location()).demo || '';
  };

  Body.prototype.demoUrl = function(name) {
    return 'demos/' + name + '.json';
  };

  Body.prototype.load = function() {
    return this.sidebar.loadEntries().then(function() {
      return this.loadDemo(this.currentDemoName());
    }.bind(this));
  };

  Body.prototype.loadModule = function(name, x, y) {
    var point = this.main.contentLocalPoint({ x: x, y: y });
    if (point.x < 0 || point.y < 0) {
      return;
    }

    var entry = this.sidebar.entry(name);
    this.main.loadModule(helper.extend({
      title: entry.label,
      name: name,
    }, point), entry.visiblePortNames);
  };

  Body.prototype.loadDemo = function(name) {
    return (name ? this.main.loadUrl(this.demoUrl(name)) : Promise.resolve());
  };

  Body.prototype.oninit = function() {
    dom.ready(Body.prototype.onready.bind(this));
    this.sidebar.on('dragstart', this.ondragstart.bind(this));
    this.sidebar.on('dragend', this.ondragend.bind(this));
    this.sidebar.on('drop', this.ondrop.bind(this));
    this.main.on('sidebartoggle', this.onsidebartoggle.bind(this));
    this.main.on('dragstart', this.ondragstart.bind(this));
    this.main.on('dragend', this.ondragend.bind(this));
    this.main.on('loadstart', this.onloadstart.bind(this));
    this.main.on('loadend', this.onloadend.bind(this));
  };

  Body.prototype.onredraw = function() {
    this.redrawBy('isDragging', function(isDragging) {
      dom.toggleClass(this.element(), 'dragging', isDragging);
    });
  };

  Body.prototype.onready = function() {
    this.disabled(true);
    this.load().catch(function(e) {
      alert(e);
    }).then(function() {
      this.disabled(false);
    }.bind(this));
  };

  Body.prototype.ondragstart = function() {
    this.incrementDragCount();
  };

  Body.prototype.ondragend = function() {
    this.decrementDragCount();
  };

  Body.prototype.ondrop = function(name, x, y) {
    this.loadModule(name, x, y);
  };

  Body.prototype.onsidebartoggle = function() {
    this.toggleSidebar();
  };

  Body.prototype.onloadstart = function() {
    this.disabled(true);
  };

  Body.prototype.onloadend = function() {
    this.disabled(false);
  };

  if (typeof module !== 'undefined' && module.exports) {
    module.exports = Body;
  } else {
    app.Body = Body;
  }
})(this.app || (this.app = {}));
<|endoftext|>


<commit_before>const errors = require('@tryghost/errors');
const {i18n} = require('../../../../lib/common');
const auth = require('../../../../services/auth');
const shared = require('../../../shared');
const apiMw = require('../../middleware');

const notImplemented = function (req, res, next) {
    // CASE: user is logged in, allow
    if (!req.api_key) {
        return next();
    }

    // @NOTE: integrations have limited access for now
    const whitelisted = {
        // @NOTE: stable
        site: ['GET'],
        posts: ['GET', 'PUT', 'DELETE', 'POST'],
        pages: ['GET', 'PUT', 'DELETE', 'POST'],
        images: ['POST'],
        // @NOTE: experimental
        actions: ['GET'],
        tags: ['GET', 'PUT', 'DELETE', 'POST'],
        labels: ['GET', 'PUT', 'DELETE', 'POST'],
        users: ['GET'],
        themes: ['POST', 'PUT'],
        members: ['GET', 'PUT', 'DELETE', 'POST'],
        config: ['GET'],
        webhooks: ['POST', 'PUT', 'DELETE'],
        schedules: ['PUT'],
        db: ['POST']
    };

    const match = req.url.match(/^\/(\w+)\/?/);

    if (match) {
        const entity = match[1];

        if (whitelisted[entity] && whitelisted[entity].includes(req.method)) {
            return next();
        }
    }

    next(new errors.GhostError({
        errorType: 'NotImplementedError',
        message: i18n.t('errors.api.common.notImplemented'),
        statusCode: '501'
    }));
};

/**
 * Authentication for private endpoints
 */
module.exports.authAdminApi = [
    auth.authenticate.authenticateAdminApi,
    auth.authorize.authorizeAdminApi,
    apiMw.updateUserLastSeen,
    apiMw.cors,
    shared.middlewares.urlRedirects.adminSSLAndHostRedirect,
    shared.middlewares.prettyUrls,
    notImplemented
];

/**
 * Authentication for private endpoints with token in URL
 * Ex.: For scheduler publish endpoint
 */
module.exports.authAdminApiWithUrl = [
    auth.authenticate.authenticateAdminApiWithUrl,
    auth.authorize.authorizeAdminApi,
    apiMw.updateUserLastSeen,
    apiMw.cors,
    shared.middlewares.urlRedirects.adminSSLAndHostRedirect,
    shared.middlewares.prettyUrls,
    notImplemented
];

/**
 * Middleware for public admin endpoints
 */
module.exports.publicAdminApi = [
    apiMw.cors,
    shared.middlewares.urlRedirects.adminSSLAndHostRedirect,
    shared.middlewares.prettyUrls,
    notImplemented
];
<commit_msg>Moved canary/v3 webhooks API to "stable" group<commit_after>const errors = require('@tryghost/errors');
const {i18n} = require('../../../../lib/common');
const auth = require('../../../../services/auth');
const shared = require('../../../shared');
const apiMw = require('../../middleware');

const notImplemented = function (req, res, next) {
    // CASE: user is logged in, allow
    if (!req.api_key) {
        return next();
    }

    // @NOTE: integrations have limited access for now
    const allowlisted = {
        // @NOTE: stable
        site: ['GET'],
        posts: ['GET', 'PUT', 'DELETE', 'POST'],
        pages: ['GET', 'PUT', 'DELETE', 'POST'],
        images: ['POST'],
        webhooks: ['POST', 'PUT', 'DELETE'],
        // @NOTE: experimental
        actions: ['GET'],
        tags: ['GET', 'PUT', 'DELETE', 'POST'],
        labels: ['GET', 'PUT', 'DELETE', 'POST'],
        users: ['GET'],
        themes: ['POST', 'PUT'],
        members: ['GET', 'PUT', 'DELETE', 'POST'],
        config: ['GET'],
        schedules: ['PUT'],
        db: ['POST']
    };

    const match = req.url.match(/^\/(\w+)\/?/);

    if (match) {
        const entity = match[1];

        if (allowlisted[entity] && allowlisted[entity].includes(req.method)) {
            return next();
        }
    }

    next(new errors.GhostError({
        errorType: 'NotImplementedError',
        message: i18n.t('errors.api.common.notImplemented'),
        statusCode: '501'
    }));
};

/**
 * Authentication for private endpoints
 */
module.exports.authAdminApi = [
    auth.authenticate.authenticateAdminApi,
    auth.authorize.authorizeAdminApi,
    apiMw.updateUserLastSeen,
    apiMw.cors,
    shared.middlewares.urlRedirects.adminSSLAndHostRedirect,
    shared.middlewares.prettyUrls,
    notImplemented
];

/**
 * Authentication for private endpoints with token in URL
 * Ex.: For scheduler publish endpoint
 */
module.exports.authAdminApiWithUrl = [
    auth.authenticate.authenticateAdminApiWithUrl,
    auth.authorize.authorizeAdminApi,
    apiMw.updateUserLastSeen,
    apiMw.cors,
    shared.middlewares.urlRedirects.adminSSLAndHostRedirect,
    shared.middlewares.prettyUrls,
    notImplemented
];

/**
 * Middleware for public admin endpoints
 */
module.exports.publicAdminApi = [
    apiMw.cors,
    shared.middlewares.urlRedirects.adminSSLAndHostRedirect,
    shared.middlewares.prettyUrls,
    notImplemented
];
<|endoftext|>


<commit_before>var path = require('path');
var express = require('express');
var webpack = require('webpack');
var config = require('./webpack.config');

var app = express();
var compiler = webpack(config);

app.use(require('webpack-dev-middleware')(compiler, {
    noInfo: true,
    publicPath: config.output.publicPath
}));

app.use(require('webpack-hot-middleware')(compiler));

app.get('/', function(req, res) {
  res.sendFile(path.join(__dirname, 'index.html'));
});

app.get('/tetris', function(req, res) {
  res.sendFile(path.join(__dirname, 'tetris.html'));
});

app.get('/layouts', function(req, res) {
  res.sendFile(path.join(__dirname, 'layouts.html'));
});

app.get('/layout-test', function(req, res) {
  res.sendFile(path.join(__dirname, 'layout-test.html'));
});

app.listen(3000, 'localhost', function (err) {
  if (err) {
    console.log(err);
    return;
  }

  console.log('Listening at http://localhost:3000');
});
<commit_msg>No longer hard-coding routes in express<commit_after>var path = require('path');
var express = require('express');
var webpack = require('webpack');
var config = require('./webpack.config');

var app = express();
var compiler = webpack(config);

app.use(require('webpack-dev-middleware')(compiler, {
    noInfo: true,
    publicPath: config.output.publicPath
}));

app.use(require('webpack-hot-middleware')(compiler));

app.get('*', function(req, res) {
  var reqPath = req.path.slice(1); // Remove initial slash
  res.sendFile(path.join(__dirname, reqPath + '.html'));
});

app.listen(3000, 'localhost', function (err) {
  if (err) {
    console.log(err);
    return;
  }

  console.log('Listening at http://localhost:3000');
});
<|endoftext|>


<commit_before>(function () {
    'use strict';
    var pending = false, inp, md5, md5s, othermd5s, variants;
    var divReplaceWhat, checkboxCollection;
    var smallToBig, bigToSmall, spaceToNone, r;   // r = replacements

    /**
     * From http://stackoverflow.com/a/171256/194309
     * Overwrites obj1's values with obj2's and adds obj2's if non existent in obj1
     * @param obj1
     * @param obj2
     * @returns obj3 a new object based on obj1 and obj2
     */
    function merge_objects(obj1,obj2){
        var obj3 = {};
        for (var attrname in obj1) { obj3[attrname] = obj1[attrname]; }
        for (var attrname in obj2) { obj3[attrname] = obj2[attrname]; }
        return obj3;
    }

    function calcVariants(variants) {
        var txt, md5, str, regex, desired, regexcellent;
        regex = new RegExp(/\d$/);
        desired = document.getElementById("desired").value;

        regexcellent = new RegExp(desired + "$");
        for(var i=0; i<variants.length; i++) {
            txt = variants[i];
            md5 = CryptoJS.MD5(txt);
            str = md5.toString();

            if(str.match(regexcellent)) {
                md5s.innerHTML += "
\"`" + txt + "`\" (" + desired + ")

" + md5 + "
";
//            } else if(str.match(regex)) {
//                othermd5s.innerHTML += "" + txt + "
" + md5 + "
";
            }
        }
    }
    function veryRecurse(txt) {
        var tweak = [], p, first, remain, variants, tweaks;
        if(!txt || txt.length === 0) return [];

        if(txt.length ===1) {
            tweak.push(txt);
            for(p in r[txt]) {
                tweak.push(r[txt][p]);
            }
            return tweak;
        } else {
            first = txt[0];
            remain = txt.slice(1);
            variants = veryRecurse(remain);
            for(tweaks in variants) {
                tweak.push(first + variants[tweaks]);
                for(p in r[first]) {
                    tweak.push(r[first][p] + variants[tweaks]);
                }
            }
            return tweak;
        }
    }
    function makeVariants(txt) {
        var len;
        variants = [];
        md5s.innerHTML = "";
        othermd5s.innerHTML = "";
        variants = veryRecurse(txt);
        calcVariants(variants);
    }

    function calc() {
        var txt;
        if (pending) {
            txt = inp.value.trim();
            md5.innerHTML = txt === "" ? "" : CryptoJS.MD5(txt);
            makeVariants(txt);
            pending = false;
        }
    }
    function queue() {
        if (!pending) {
            pending = true;
            calc();
        }
    }
    inp = document.getElementById("inp");
    md5 = document.getElementById("md5");
    md5s = document.getElementById("md5s");
    othermd5s = document.getElementById("othermd5s");
    divReplaceWhat = document.getElementById("replace-what");
    inp.onkeyup = queue;

    smallToBig = {
        a:['A','@'],
        b:['B'],
        c:['C'],
        d:['D'],
        e:['E'],
        f:['F'],
        g:['G'],
        h:['H'],
        i:['I'],
        j:['J'],
        k:['K'],
        l:['L'],
        m:['M'],
        n:['N'],
        o:['O'],
        p:['P'],
        q:['Q'],
        r:['R'],
        s:['S'],
        t:['T'],
        u:['U'],
        v:['V'],
        w:['W'],
        x:['X'],
        y:['Y'],
        z:['Z']
    };
    bigToSmall = {
        A:['a','@'],
        B:['b'],
        C:['c'],
        D:['d'],
        E:['e'],
        F:['f'],
        G:['g'],
        H:['h'],
        I:['i'],
        J:['j'],
        K:['k'],
        L:['l'],
        M:['m'],
        N:['n'],
        O:['o'],
        P:['p'],
        Q:['q'],
        R:['r'],
        S:['s'],
        T:['t'],
        U:['u'],
        V:['v'],
        W:['w'],
        X:['x'],
        Y:['y'],
        Z:['z']
    };
    spaceToNone = {};
    spaceToNone[' '] = [''];

    var collection = divReplaceWhat.getElementsByTagName('INPUT');
    for (var x=0; x<collection.length; x++) {
        if (collection[x].type.toUpperCase()=='CHECKBOX')
            collection[x].addEventListener("click",setReplaceObject);
    }

    function setReplaceObject() {
        r = {};
        if(document.getElementById('bigToSmall').checked && document.getElementById('smallToBig').checked && document.getElementById('spaceToNone').checked) {
            r = merge_objects(merge_objects(bigToSmall,smallToBig),spaceToNone);
        } else if(document.getElementById('bigToSmall').checked && document.getElementById('smallToBig').checked) {
            r = merge_objects(bigToSmall,smallToBig);
        } else if(document.getElementById('bigToSmall').checked && document.getElementById('spaceToNone').checked) {
            r = merge_objects(smallToBig,spaceToNone);
        } else if(document.getElementById('smallToBig').checked && document.getElementById('spaceToNone').checked) {
            r = merge_objects(smallToBig,spaceToNone);
        } else if(document.getElementById('bigToSmall').checked) {
            r = bigToSmall;
        } else if(document.getElementById('smallToBig').checked) {
            r = smallToBig;
        } else if(document.getElementById('spaceToNone').checked) {
            r = spaceToNone;
        } else {
            r = {};
        }
    }
})();

<commit_msg>Give initial value to r (otherwise fails until we click a checkbox)<commit_after>(function () {
    'use strict';
    var pending = false, inp, md5, md5s, othermd5s, variants;
    var divReplaceWhat, checkboxCollection;
    var smallToBig, bigToSmall, spaceToNone, r = {};   // r = replacements

    /**
     * From http://stackoverflow.com/a/171256/194309
     * Overwrites obj1's values with obj2's and adds obj2's if non existent in obj1
     * @param obj1
     * @param obj2
     * @returns obj3 a new object based on obj1 and obj2
     */
    function merge_objects(obj1,obj2){
        var obj3 = {};
        for (var attrname in obj1) { obj3[attrname] = obj1[attrname]; }
        for (var attrname in obj2) { obj3[attrname] = obj2[attrname]; }
        return obj3;
    }

    function calcVariants(variants) {
        var txt, md5, str, regex, desired, regexcellent;
        regex = new RegExp(/\d$/);
        desired = document.getElementById("desired").value;

        regexcellent = new RegExp(desired + "$");
        for(var i=0; i<variants.length; i++) {
            txt = variants[i];
            md5 = CryptoJS.MD5(txt);
            str = md5.toString();

            if(str.match(regexcellent)) {
                md5s.innerHTML += "
\"`" + txt + "`\" (" + desired + ")

" + md5 + "
";
//            } else if(str.match(regex)) {
//                othermd5s.innerHTML += "" + txt + "
" + md5 + "
";
            }
        }
    }
    function veryRecurse(txt) {
        var tweak = [], p, first, remain, variants, tweaks;
        if(!txt || txt.length === 0) return [];

        if(txt.length ===1) {
            tweak.push(txt);
            for(p in r[txt]) {
                tweak.push(r[txt][p]);
            }
            return tweak;
        } else {
            first = txt[0];
            remain = txt.slice(1);
            variants = veryRecurse(remain);
            for(tweaks in variants) {
                tweak.push(first + variants[tweaks]);
                for(p in r[first]) {
                    tweak.push(r[first][p] + variants[tweaks]);
                }
            }
            return tweak;
        }
    }
    function makeVariants(txt) {
        var len;
        variants = [];
        md5s.innerHTML = "";
        othermd5s.innerHTML = "";
        variants = veryRecurse(txt);
        calcVariants(variants);
    }

    function calc() {
        var txt;
        if (pending) {
            txt = inp.value.trim();
            md5.innerHTML = txt === "" ? "" : CryptoJS.MD5(txt);
            makeVariants(txt);
            pending = false;
        }
    }
    function queue() {
        if (!pending) {
            pending = true;
            calc();
        }
    }
    inp = document.getElementById("inp");
    md5 = document.getElementById("md5");
    md5s = document.getElementById("md5s");
    othermd5s = document.getElementById("othermd5s");
    divReplaceWhat = document.getElementById("replace-what");
    inp.onkeyup = queue;

    smallToBig = {
        a:['A','@'],
        b:['B'],
        c:['C'],
        d:['D'],
        e:['E'],
        f:['F'],
        g:['G'],
        h:['H'],
        i:['I'],
        j:['J'],
        k:['K'],
        l:['L'],
        m:['M'],
        n:['N'],
        o:['O'],
        p:['P'],
        q:['Q'],
        r:['R'],
        s:['S'],
        t:['T'],
        u:['U'],
        v:['V'],
        w:['W'],
        x:['X'],
        y:['Y'],
        z:['Z']
    };
    bigToSmall = {
        A:['a','@'],
        B:['b'],
        C:['c'],
        D:['d'],
        E:['e'],
        F:['f'],
        G:['g'],
        H:['h'],
        I:['i'],
        J:['j'],
        K:['k'],
        L:['l'],
        M:['m'],
        N:['n'],
        O:['o'],
        P:['p'],
        Q:['q'],
        R:['r'],
        S:['s'],
        T:['t'],
        U:['u'],
        V:['v'],
        W:['w'],
        X:['x'],
        Y:['y'],
        Z:['z']
    };
    spaceToNone = {};
    spaceToNone[' '] = [''];

    var collection = divReplaceWhat.getElementsByTagName('INPUT');
    for (var x=0; x<collection.length; x++) {
        if (collection[x].type.toUpperCase()=='CHECKBOX')
            collection[x].addEventListener("click",setReplaceObject);
    }

    function setReplaceObject() {
        r = {};
        if(document.getElementById('bigToSmall').checked && document.getElementById('smallToBig').checked && document.getElementById('spaceToNone').checked) {
            r = merge_objects(merge_objects(bigToSmall,smallToBig),spaceToNone);
        } else if(document.getElementById('bigToSmall').checked && document.getElementById('smallToBig').checked) {
            r = merge_objects(bigToSmall,smallToBig);
        } else if(document.getElementById('bigToSmall').checked && document.getElementById('spaceToNone').checked) {
            r = merge_objects(smallToBig,spaceToNone);
        } else if(document.getElementById('smallToBig').checked && document.getElementById('spaceToNone').checked) {
            r = merge_objects(smallToBig,spaceToNone);
        } else if(document.getElementById('bigToSmall').checked) {
            r = bigToSmall;
        } else if(document.getElementById('smallToBig').checked) {
            r = smallToBig;
        } else if(document.getElementById('spaceToNone').checked) {
            r = spaceToNone;
        } else {
            r = {};
        }
    }
})();

<|endoftext|>