<commit_before>define([
    "tools/random",
    "modules/data-types/Hex",
    "modules/channels/EventEmitter",
    "modules/channels/tlke",
    "modules/channels/tlht",
    "modules/channels/TestTransport",
    "modules/channels/Route",
    "zepto",
], function (random, Hex, EventEmitter, Tlke, Tlht, Transport, Route, $) {

    describe("True Link Key Exchange", function() {

        function Builder(name) {
            this.name = name;
            this._defineEvent("networkPacket");
            this._defineEvent("offer");
            this._defineEvent("auth");
            this._defineEvent("addrIn");
        }
        Builder.prototype = new EventEmitter();
        $.extend(Builder.prototype, {
            build: function() {
                var tlke = this.tlke = new Tlke();
                tlke.setRng(random);
                var route = this.route = new Route();

                route.on("packet", tlke.processPacket, tlke);
                route.on("networkPacket", this.on_sendPacket, this);
                route.on("addrIn", this.on_addrIn, this);

                tlke.on("packet", route.processPacket, route);
                tlke.on("addr", route.setAddr, route);
                tlke.on("keyReady", this.keyReady, this);
                tlke.on("offer", this.on_requestOffer, this);
                tlke.on("auth", this.on_requestAuth, this);
            },
            processNetworkPacket: function(packet) {
                this._log("processNetworkPacket", packet);
                this.route.processNetworkPacket(packet);
            },
            generate: function() {
                this._log("generate");
                this.tlke.generate();
            },
            keyReady: function(args) {
                this._log("keyReady", args);
                this.inId = args.inId;
                this.outId = args.outId;
                this.key = args.key;
            },
            enterOffer: function(offer) {
                this._log("enterOffer", offer);
                this.tlke.enterOffer(offer);
            },
            enterAuth: function(auth) {
                this._log("enterAuth", auth);
                this.tlke.enterAuth(auth);
            },
            on_sendPacket: function(packet) {
                this._log("on_sendPacket", packet);
                this.fire("networkPacket", packet);
            },
            on_requestOffer: function(offer) {
                this._log("on_requestOffer", offer);
                this.fire("offer", offer);
            },
            on_requestAuth: function(auth) {
                this._log("on_requestAuth", auth);
                if (auth) {
                    this.fire("auth", auth);
                }
            },
            on_addrIn: function(addr) {
                this._log("on_addrIn", addr);
                this.fire("addrIn", addr);
            },
            _log: function() {
                //console.log(this.name, arguments);
            }
        });

        describe("with route short-circuited", function() {
            beforeEach(function() {
                var alice = this.alice = new Builder("Alice");
                var bob = this.bob = new Builder("Bob");
                alice.on("networkPacket", bob.processNetworkPacket, bob);
                bob.on("networkPacket", alice.processNetworkPacket, alice);

                alice.on("offer", bob.enterOffer, bob);
                alice.on("auth", bob.enterAuth, bob);

                alice.build();
                bob.build();
                alice.generate();
            });

            it("alice key is ready", function() {
                expect(this.alice.inId).not.toBeUndefined();
                expect(this.alice.outId).not.toBeUndefined();
                expect(this.alice.key).not.toBeUndefined();
            });

            it("bob key is ready", function() {
                expect(this.bob.inId).not.toBeUndefined();
                expect(this.bob.outId).not.toBeUndefined();
                expect(this.bob.key).not.toBeUndefined();
            });

            it("channel ids matched", function() {
                expect(this.alice.inId.as(Hex).isEqualTo(this.bob.outId.as(Hex))).toBe(true);
                expect(this.alice.outId.as(Hex).isEqualTo(this.bob.inId.as(Hex))).toBe(true);
            });

            it("keys are the same", function() {
                expect(this.alice.key.as(Hex).isEqualTo(this.bob.key.as(Hex))).toBe(true);
            });
        });

        describe("with transport", function() {
            beforeEach(function() {
                var transport = this.transport = new Transport();
                var alice = this.alice = new Builder("Alice");
                var bob = this.bob = new Builder("Bob");
                alice.on("networkPacket", transport.sendNetworkPacket, transport);
                bob.on("networkPacket", transport.sendNetworkPacket, transport);

                alice.on("addrIn", transport.openAddr, transport);
                bob.on("addrIn", transport.openAddr, transport);

                transport.on("networkPacket", alice.processNetworkPacket, alice);
                transport.on("networkPacket", bob.processNetworkPacket, bob);

                alice.on("offer", bob.enterOffer, bob);
                alice.on("auth", bob.enterAuth, bob);

                alice.build();
                bob.build();
                alice.generate();
            });

            it("alice key is ready", function() {
                expect(this.alice.inId).not.toBeUndefined();
                expect(this.alice.outId).not.toBeUndefined();
                expect(this.alice.key).not.toBeUndefined();
            });

            it("bob key is ready", function() {
                expect(this.bob.inId).not.toBeUndefined();
                expect(this.bob.outId).not.toBeUndefined();
                expect(this.bob.key).not.toBeUndefined();
            });

            it("channel ids matched", function() {
                expect(this.alice.inId.as(Hex).isEqualTo(this.bob.outId.as(Hex))).toBe(true);
                expect(this.alice.outId.as(Hex).isEqualTo(this.bob.inId.as(Hex))).toBe(true);
            });

            it("keys are the same", function() {
                expect(this.alice.key.as(Hex).isEqualTo(this.bob.key.as(Hex))).toBe(true);
            });

        });

    });

    describe("True Link Hash Tail Exchange", function() {

        function TlkeBuilder(name, transport) {
            this.name = "TlkeBuilder" + name;
            this._defineEvent("offer");
            this._defineEvent("auth");
            this._defineEvent("done");
            this.transport = transport;
        }
        TlkeBuilder.prototype = new EventEmitter();
        $.extend(TlkeBuilder.prototype, {
            build: function() {
                var tlke = this.tlke = new Tlke();
                tlke.setRng(random);
                var route = this.route = new Route();
                var transport = this.transport;

                route.on("packet", tlke.processPacket, tlke);
                route.on("networkPacket", transport.sendNetworkPacket, transport);
                route.on("addrIn", transport.openAddr, transport);

                tlke.on("packet", route.processPacket, route);
                tlke.on("addr", route.setAddr, route);
                tlke.on("keyReady", this.on_keyReady, this);
                tlke.on("offer", this.on_requestOffer, this);
                tlke.on("auth", this.on_requestAuth, this);

                transport.on("networkPacket", route.processNetworkPacket, route);
            },
            generate: function() {
                this._log("generate");
                this.tlke.generate();
            },
            keyReady: function(args) {
                this._log("keyReady", args);
                this.inId = args.inId;
                this.outId = args.outId;
                this.key = args.key;
            },
            enterOffer: function(offer) {
                this._log("enterOffer", offer);
                this.tlke.enterOffer(offer);
            },
            enterAuth: function(auth) {
                this._log("enterAuth", auth);
                this.tlke.enterAuth(auth);
            },
            on_requestOffer: function(offer) {
                this._log("on_requestOffer", offer);
                this.fire("offer", offer);
            },
            on_requestAuth: function(auth) {
                this._log("on_requestAuth", auth);
                if (auth) {
                    this.fire("auth", auth);
                }
            },
            on_keyReady: function(args) {
                this._log("on_keyReady", args);
                this.fire("done", args);
            },
            _log: function() {
                //console.log(this.name, arguments);
            }
        });

        function TlhtBuilder(name, transport) {
            this.name = "TlhtBuilder::" + name;
            this._defineEvent("done");
            this.transport = transport;
        }
        TlhtBuilder.prototype = new EventEmitter();
        $.extend(TlhtBuilder.prototype, {
            build: function(args) {
                var tlht = this.tlht = new Tlht();
                var route = this.route = new Route();
                var transport = this.transport;

                route.on("packet", tlht.processPacket, tlht);
                route.on("networkPacket", transport.sendNetworkPacket, transport);
                route.on("addrIn", transport.openAddr, transport);

                tlht.on("packet", route.processPacket, route);

                transport.on("networkPacket", route.processNetworkPacket, route);
                tlht.on("htReady", this.on_htReady, this);

                tlht.setRng(random);
                tlht.init(args.key);
                route.setAddr(args);
                tlht.generate();
            },
            on_htReady: function(args) {
                this._log("on_htReady", args);
                this.hashStart = args.hashStart;
                this.hashEnd = args.hashEnd;
                this._log("hashStart", args.hashStart.as(Hex));
                this._log("hashEnd", args.hashEnd.as(Hex));
            },
            _log: function() {
                //console.log(this.name, arguments);
            }
        });

        describe("with transport", function() {
            beforeEach(function() {
                var transport = this.transport = new Transport();
                var aliceTlke = this.aliceTlke = new TlkeBuilder("Alice", transport);
                var bobTlke = this.bobTlke = new TlkeBuilder("Bob", transport);
                var aliceTlth = this.aliceTlth = new TlhtBuilder("Alice", transport);
                var bobTlht = this.bobTlht = new TlhtBuilder("Bob", transport);

                aliceTlke.on("offer", bobTlke.enterOffer, bobTlke);
                aliceTlke.on("auth", bobTlke.enterAuth, bobTlke);

                aliceTlke.on("done", aliceTlth.build, aliceTlth);
                bobTlke.on("done", bobTlht.build, bobTlht);

                aliceTlke.build();
                bobTlke.build();
                aliceTlke.generate();
            });

            it("alice hash tails are ready", function() {
                expect(this.aliceTlth.hashStart).not.toBeUndefined();
                expect(this.aliceTlth.hashEnd).not.toBeUndefined();
            });

            it("bob hash tails are ready", function() {
                expect(this.bobTlht.hashStart).not.toBeUndefined();
                expect(this.bobTlht.hashEnd).not.toBeUndefined();
            });

        });

    });

});
<commit_msg>make jslint happy<commit_after>define([
    "tools/random",
    "modules/data-types/Hex",
    "modules/channels/EventEmitter",
    "modules/channels/tlke",
    "modules/channels/tlht",
    "modules/channels/TestTransport",
    "modules/channels/Route",
    "zepto"
], function (random, Hex, EventEmitter, Tlke, Tlht, Transport, Route, $) {

    describe("True Link Key Exchange", function () {

        function Builder(name) {
            this.name = name;
            this._defineEvent("networkPacket");
            this._defineEvent("offer");
            this._defineEvent("auth");
            this._defineEvent("addrIn");
        }
        Builder.prototype = new EventEmitter();
        $.extend(Builder.prototype, {
            build: function () {
                var tlke = this.tlke = new Tlke();
                tlke.setRng(random);
                var route = this.route = new Route();

                route.on("packet", tlke.processPacket, tlke);
                route.on("networkPacket", this.on_sendPacket, this);
                route.on("addrIn", this.on_addrIn, this);

                tlke.on("packet", route.processPacket, route);
                tlke.on("addr", route.setAddr, route);
                tlke.on("keyReady", this.keyReady, this);
                tlke.on("offer", this.on_requestOffer, this);
                tlke.on("auth", this.on_requestAuth, this);
            },
            processNetworkPacket: function (packet) {
                this._log("processNetworkPacket", packet);
                this.route.processNetworkPacket(packet);
            },
            generate: function () {
                this._log("generate");
                this.tlke.generate();
            },
            keyReady: function (args) {
                this._log("keyReady", args);
                this.inId = args.inId;
                this.outId = args.outId;
                this.key = args.key;
            },
            enterOffer: function (offer) {
                this._log("enterOffer", offer);
                this.tlke.enterOffer(offer);
            },
            enterAuth: function (auth) {
                this._log("enterAuth", auth);
                this.tlke.enterAuth(auth);
            },
            on_sendPacket: function (packet) {
                this._log("on_sendPacket", packet);
                this.fire("networkPacket", packet);
            },
            on_requestOffer: function (offer) {
                this._log("on_requestOffer", offer);
                this.fire("offer", offer);
            },
            on_requestAuth: function (auth) {
                this._log("on_requestAuth", auth);
                if (auth) {
                    this.fire("auth", auth);
                }
            },
            on_addrIn: function (addr) {
                this._log("on_addrIn", addr);
                this.fire("addrIn", addr);
            },
            _log: function () {
                //console.log(this.name, arguments);
            }
        });

        describe("with route short-circuited", function () {
            beforeEach(function () {
                var alice = this.alice = new Builder("Alice");
                var bob = this.bob = new Builder("Bob");
                alice.on("networkPacket", bob.processNetworkPacket, bob);
                bob.on("networkPacket", alice.processNetworkPacket, alice);

                alice.on("offer", bob.enterOffer, bob);
                alice.on("auth", bob.enterAuth, bob);

                alice.build();
                bob.build();
                alice.generate();
            });

            it("alice key is ready", function () {
                expect(this.alice.inId).not.toBeUndefined();
                expect(this.alice.outId).not.toBeUndefined();
                expect(this.alice.key).not.toBeUndefined();
            });

            it("bob key is ready", function () {
                expect(this.bob.inId).not.toBeUndefined();
                expect(this.bob.outId).not.toBeUndefined();
                expect(this.bob.key).not.toBeUndefined();
            });

            it("channel ids matched", function () {
                expect(this.alice.inId.as(Hex).isEqualTo(this.bob.outId.as(Hex))).toBe(true);
                expect(this.alice.outId.as(Hex).isEqualTo(this.bob.inId.as(Hex))).toBe(true);
            });

            it("keys are the same", function () {
                expect(this.alice.key.as(Hex).isEqualTo(this.bob.key.as(Hex))).toBe(true);
            });
        });

        describe("with transport", function () {
            beforeEach(function () {
                var transport = this.transport = new Transport();
                var alice = this.alice = new Builder("Alice");
                var bob = this.bob = new Builder("Bob");
                alice.on("networkPacket", transport.sendNetworkPacket, transport);
                bob.on("networkPacket", transport.sendNetworkPacket, transport);

                alice.on("addrIn", transport.openAddr, transport);
                bob.on("addrIn", transport.openAddr, transport);

                transport.on("networkPacket", alice.processNetworkPacket, alice);
                transport.on("networkPacket", bob.processNetworkPacket, bob);

                alice.on("offer", bob.enterOffer, bob);
                alice.on("auth", bob.enterAuth, bob);

                alice.build();
                bob.build();
                alice.generate();
            });

            it("alice key is ready", function () {
                expect(this.alice.inId).not.toBeUndefined();
                expect(this.alice.outId).not.toBeUndefined();
                expect(this.alice.key).not.toBeUndefined();
            });

            it("bob key is ready", function () {
                expect(this.bob.inId).not.toBeUndefined();
                expect(this.bob.outId).not.toBeUndefined();
                expect(this.bob.key).not.toBeUndefined();
            });

            it("channel ids matched", function () {
                expect(this.alice.inId.as(Hex).isEqualTo(this.bob.outId.as(Hex))).toBe(true);
                expect(this.alice.outId.as(Hex).isEqualTo(this.bob.inId.as(Hex))).toBe(true);
            });

            it("keys are the same", function () {
                expect(this.alice.key.as(Hex).isEqualTo(this.bob.key.as(Hex))).toBe(true);
            });

        });

    });

    describe("True Link Hash Tail Exchange", function () {

        function TlkeBuilder(name, transport) {
            this.name = "TlkeBuilder" + name;
            this._defineEvent("offer");
            this._defineEvent("auth");
            this._defineEvent("done");
            this.transport = transport;
        }
        TlkeBuilder.prototype = new EventEmitter();
        $.extend(TlkeBuilder.prototype, {
            build: function () {
                var tlke = this.tlke = new Tlke();
                tlke.setRng(random);
                var route = this.route = new Route();
                var transport = this.transport;

                route.on("packet", tlke.processPacket, tlke);
                route.on("networkPacket", transport.sendNetworkPacket, transport);
                route.on("addrIn", transport.openAddr, transport);

                tlke.on("packet", route.processPacket, route);
                tlke.on("addr", route.setAddr, route);
                tlke.on("keyReady", this.on_keyReady, this);
                tlke.on("offer", this.on_requestOffer, this);
                tlke.on("auth", this.on_requestAuth, this);

                transport.on("networkPacket", route.processNetworkPacket, route);
            },
            generate: function () {
                this._log("generate");
                this.tlke.generate();
            },
            keyReady: function (args) {
                this._log("keyReady", args);
                this.inId = args.inId;
                this.outId = args.outId;
                this.key = args.key;
            },
            enterOffer: function (offer) {
                this._log("enterOffer", offer);
                this.tlke.enterOffer(offer);
            },
            enterAuth: function (auth) {
                this._log("enterAuth", auth);
                this.tlke.enterAuth(auth);
            },
            on_requestOffer: function (offer) {
                this._log("on_requestOffer", offer);
                this.fire("offer", offer);
            },
            on_requestAuth: function (auth) {
                this._log("on_requestAuth", auth);
                if (auth) {
                    this.fire("auth", auth);
                }
            },
            on_keyReady: function (args) {
                this._log("on_keyReady", args);
                this.fire("done", args);
            },
            _log: function () {
                //console.log(this.name, arguments);
            }
        });

        function TlhtBuilder(name, transport) {
            this.name = "TlhtBuilder::" + name;
            this._defineEvent("done");
            this.transport = transport;
        }
        TlhtBuilder.prototype = new EventEmitter();
        $.extend(TlhtBuilder.prototype, {
            build: function (args) {
                var tlht = this.tlht = new Tlht();
                var route = this.route = new Route();
                var transport = this.transport;

                route.on("packet", tlht.processPacket, tlht);
                route.on("networkPacket", transport.sendNetworkPacket, transport);
                route.on("addrIn", transport.openAddr, transport);

                tlht.on("packet", route.processPacket, route);

                transport.on("networkPacket", route.processNetworkPacket, route);
                tlht.on("htReady", this.on_htReady, this);

                tlht.setRng(random);
                tlht.init(args.key);
                route.setAddr(args);
                tlht.generate();
            },
            on_htReady: function (args) {
                this._log("on_htReady", args);
                this.hashStart = args.hashStart;
                this.hashEnd = args.hashEnd;
                this._log("hashStart", args.hashStart.as(Hex));
                this._log("hashEnd", args.hashEnd.as(Hex));
            },
            _log: function () {
                //console.log(this.name, arguments);
            }
        });

        describe("with transport", function () {
            beforeEach(function () {
                var transport = this.transport = new Transport();
                var aliceTlke = this.aliceTlke = new TlkeBuilder("Alice", transport);
                var bobTlke = this.bobTlke = new TlkeBuilder("Bob", transport);
                var aliceTlth = this.aliceTlth = new TlhtBuilder("Alice", transport);
                var bobTlht = this.bobTlht = new TlhtBuilder("Bob", transport);

                aliceTlke.on("offer", bobTlke.enterOffer, bobTlke);
                aliceTlke.on("auth", bobTlke.enterAuth, bobTlke);

                aliceTlke.on("done", aliceTlth.build, aliceTlth);
                bobTlke.on("done", bobTlht.build, bobTlht);

                aliceTlke.build();
                bobTlke.build();
                aliceTlke.generate();
            });

            it("alice hash tails are ready", function () {
                expect(this.aliceTlth.hashStart).not.toBeUndefined();
                expect(this.aliceTlth.hashEnd).not.toBeUndefined();
            });

            it("bob hash tails are ready", function () {
                expect(this.bobTlht.hashStart).not.toBeUndefined();
                expect(this.bobTlht.hashEnd).not.toBeUndefined();
            });

        });

    });

});
<|endoftext|>


<commit_before>var CoreView = require('backbone/core-view');
var template = require('./analyses-workflow-item.tpl');
var nodeIds = require('../../../../value-objects/analysis-node-ids');
var layerColors = require('../../../../data/layer-colors');
var AnalysisTooltip = require('../../analysis-views/analyses-tooltip-error');
var TipsyTooltipView = require('../../../../components/tipsy-tooltip-view');
var Analyses = require('../../../../data/analyses');

module.exports = CoreView.extend({

  tagName: 'li',
  className: 'HorizontalBlockList-item',

  events: {
    'click': '_onNodeClick'
  },

  initialize: function (opts) {
    if (!opts.analysisNode && !opts.formModel) throw new Error('analysisNode or formModel is required');
    if (!opts.viewModel) throw new Error('viewModel is required');

    this._isNew = !opts.analysisNode;
    this._analysisNode = opts.analysisNode || opts.formModel; // if form model represents a new node there is no analysis yet; use form model as fallback
    this._viewModel = opts.viewModel;

    this._analysisNode.on('change:status', this.render, this);
    this.add_related_model(this._analysisNode);

    this._analysisTooltip = new AnalysisTooltip({
      analysisNode: this._analysisNode,
      element: this.$el,
      triggerSelector: '.Editor-ListAnalysis-itemError'
    });

    this.addView(this._analysisTooltip);
  },

  render: function () {
    var status = this._analysisNode.get('status');
    var isDone = this._isNew || status === 'ready' || status === 'failed';
    var isSelected = this._analysisNode.id === this._viewModel.get('selectedNodeId');
    var letter = nodeIds.letter(this._analysisNode.id);
    var bgColor = layerColors.getColorForLetter(letter);

    this.$el.html(
      template({
        isNew: this._isNew,
        isDone: isDone,
        bgColor: bgColor,
        isSelected: isSelected,
        nodeId: this._analysisNode.id,
        hasError: status === 'failed'
      })
    );

    this.$el.css({
      background: isSelected ? bgColor : '',
      border: isSelected ? '1px solid ' + bgColor : ''
    });
    this.$el.toggleClass('is-selected', isSelected);
    this.$el.toggleClass('has-error', status === 'failed');

    var tooltip = new TipsyTooltipView({
      el: this.$el,
      title: function () {
        return Analyses.title(this._analysisNode.get('type') || '');
      }.bind(this)
    });
    this.addView(tooltip);

    return this;
  },

  _onNodeClick: function () {
    this._viewModel.set('selectedNodeId', this._analysisNode.id);
  }
});
<commit_msg>Show title & error on analysis workflow tooltip<commit_after>var CoreView = require('backbone/core-view');
var template = require('./analyses-workflow-item.tpl');
var nodeIds = require('../../../../value-objects/analysis-node-ids');
var layerColors = require('../../../../data/layer-colors');
var AnalysisTooltip = require('../../analysis-views/analyses-tooltip-error');
var TipsyTooltipView = require('../../../../components/tipsy-tooltip-view');
var Analyses = require('../../../../data/analyses');
var NotificationErrorMessageHandler = require('../../notification-error-message-handler');

module.exports = CoreView.extend({

  tagName: 'li',
  className: 'HorizontalBlockList-item',

  events: {
    'click': '_onNodeClick'
  },

  initialize: function (opts) {
    if (!opts.analysisNode && !opts.formModel) throw new Error('analysisNode or formModel is required');
    if (!opts.viewModel) throw new Error('viewModel is required');

    this._isNew = !opts.analysisNode;
    this._analysisNode = opts.analysisNode || opts.formModel; // if form model represents a new node there is no analysis yet; use form model as fallback
    this._viewModel = opts.viewModel;

    this._analysisNode.on('change:status', this.render, this);
    this.add_related_model(this._analysisNode);
  },

  render: function () {
    var status = this._analysisNode.get('status');
    var isDone = this._isNew || status === 'ready' || status === 'failed';
    var isSelected = this._analysisNode.id === this._viewModel.get('selectedNodeId');
    var letter = nodeIds.letter(this._analysisNode.id);
    var bgColor = layerColors.getColorForLetter(letter);
    var analysisTitle = Analyses.title(this._analysisNode.get('type') || '');
    var tooltipTitle = analysisTitle;
    var hasFailed = status === 'failed';

    if (hasFailed) {
      var message = NotificationErrorMessageHandler.extractErrorFromAnalysisNode(this.analysisNode);
      tooltipTitle = analysisTitle + ': ' + message;
    }

    this.$el.html(
      template({
        isNew: this._isNew,
        isDone: isDone,
        bgColor: bgColor,
        isSelected: isSelected,
        nodeId: this._analysisNode.id,
        hasError: status === 'failed'
      })
    );

    this.$el.css({
      background: isSelected ? bgColor : '',
      border: isSelected ? '1px solid ' + bgColor : ''
    });
    this.$el.toggleClass('is-selected', isSelected);
    this.$el.toggleClass('has-error', status === 'failed');

    var tooltip = new TipsyTooltipView({
      el: this.$el,
      className: hasFailed ? 'is-error' : '',
      title: function () {
        return tooltipTitle;
      }
    });
    this.addView(tooltip);

    return this;
  },

  _onNodeClick: function () {
    this._viewModel.set('selectedNodeId', this._analysisNode.id);
  }
});
<|endoftext|>


<commit_before>/** Layout for restful simplified editors.
 *
 * @xtype administratorrestfulsimplifiedlayout
 * */
Ext.define('devilry.extjshelpers.RestfulSimplifiedLayout', {
    extend: 'Ext.panel.Panel',
    alias: 'widget.administratorrestfulsimplifiedlayout',
    border: 0,
    bodyStyle: {
        'background-color': 'transparent'
    },

    initComponent: function() {
        var me = this;

        var deletebuttonargs = {
            xtype: 'button',
            text: 'Delete',
            flex: 0,
            hidden: !this.supports_delete,
            iconCls: 'icon-delete',
            handler: function() {
                // TODO: Confirm
                me.editform.submit({
                    submitEmptyText: true,
                    method: 'DELETE',
                    waitMsg: 'Deleting item...',
                    success: function() {
                    }
                });
            }
        };

        var savebuttonargs = {
            xtype: 'button',
            text: 'Save',
            scale: 'large',
            iconCls: 'icon-save',
            handler: function() {
                me.editform.getForm().submit({
                    submitEmptyText: true,
                    waitMsg: 'Saving item...',
                    success: function(form, action) {
                        var record = action.record;
                        me.editform.loadRecord(record); // Need to load the record. If not, the proxy will do a POST instead of PUT on next save.
                        me.readonly();
                    }
                });
            }
        };

        var clicktoeditbuttonargs = {
            xtype: 'button',
            //scale: 'large',
            text: 'Click to edit',
            iconCls: 'icon-edit',
            listeners: {
                click: function(button, pressed) {
                    me.editable();
                }
            }
        };

        this.overlayBar = Ext.create('Ext.container.Container', {
            floating: true,
            cls: 'form-overlay-bar',
            height: 40,
            width: 300,
            layout: {
                type: 'hbox',
                align: 'stretch',
                pack: 'end'
            },
            items: [
                deletebuttonargs,
                {xtype: 'component', width: 10},
                clicktoeditbuttonargs
            ]
        });

        var editformargs = {
            id: me.getChildIdBySuffix('editform'),
            xtype: 'form',
            model: this.model,
            items: this.editformitems,

            // Fields will be arranged vertically, stretched to full width
            layout: 'anchor',
            defaults: {
                anchor: '100%',
            },

            bodyStyle: {
                padding: '15px'
            },

            // Disable by default
            disabled: true,

            // Only save button. Other buttons are in overlayBar
            buttons: [
                savebuttonargs,
            ]
        };

        Ext.apply(this, {
            items: [editformargs],
            layout: 'fit'
        });
        this.callParent(arguments);

        this.editform = Ext.getCmp(editformargs.id);
    },

    getChildIdBySuffix: function(idsuffix) {
        return this.id + '-' + idsuffix;
    },

    /** Load the request record into the form. */
    loadRecordFromStore: function (record_id) {
        var me = this;
        Ext.ModelManager.getModel(this.model).load(record_id, {
            success: function(record) {
                me.editform.loadRecord(record);
                //var title = Ext.String.format('Edit', record.data.long_name, record.data.short_name);
                //me.editform.setTitle(title);
                var fields = me.editform.getForm().getFields();
                Ext.each(me.foreignkeys, function(fieldname) {
                    var field = fields.filter('name', fieldname).items[0];
                    field.store.load(function(store, records, successful) {
                        field.setValue(record.data[fieldname]);
                    });
                });
            }
        });
    },

    getFormButtonBar: function() {
        return this.editform.dockedItems.items[0];
    },

    readonly: function() {
        this.editform.disable();
        this.overlayBar.show();
        this.overlayBar.alignTo(this, 'tr-tr');
        this.getFormButtonBar().hide();
    },
    editable: function() {
        this.editform.enable();
        this.overlayBar.hide();
        this.getFormButtonBar().show();
    },

    loadUpdateMode: function(record_id) {
        this.loadRecordFromStore(record_id);
        this.readonly();
    },
    loadCreateMode: function() {
        this.editable();
    },
    loadMode: function(mode, record_id) {
        if(mode == "update") {
            this.loadUpdateMode(record_id);
        } else if(mode == "create") {
            this.loadCreateMode();
        }
    }
});
<commit_msg>apps.administrator: Confirm delete.<commit_after>/** Layout for restful simplified editors.
 *
 * @xtype administratorrestfulsimplifiedlayout
 * */
Ext.define('devilry.extjshelpers.RestfulSimplifiedLayout', {
    extend: 'Ext.panel.Panel',
    alias: 'widget.administratorrestfulsimplifiedlayout',
    border: 0,
    bodyStyle: {
        'background-color': 'transparent'
    },

    initComponent: function() {
        var me = this;

        var deletebuttonargs = {
            xtype: 'button',
            text: 'Delete',
            flex: 0,
            hidden: !this.supports_delete,
            iconCls: 'icon-delete',
            handler: function() {
                Ext.MessageBox.show({
                    title: 'Confirm delete',
                    msg: 'Are you sure you want to delete?',
                    animateTarget: this,
                    buttons: Ext.Msg.YESNO,
                    icon: Ext.Msg.ERROR,
                    fn: function(btn) {
                        if(btn == 'yes') {
                            me.deleteCurrent();
                        }
                    }
                });
            }
        };

        var savebuttonargs = {
            xtype: 'button',
            text: 'Save',
            scale: 'medium',
            iconCls: 'icon-save',
            handler: function() {
                me.editform.getForm().submit({
                    submitEmptyText: true,
                    waitMsg: 'Saving item...',
                    success: function(form, action) {
                        var record = action.record;
                        me.editform.loadRecord(record); // Need to load the record. If not, the proxy will do a POST instead of PUT on next save.
                        me.readonly();
                    }
                });
            }
        };

        var clicktoeditbuttonargs = {
            xtype: 'button',
            text: 'Click to edit',
            iconCls: 'icon-edit',
            listeners: {
                click: function(button, pressed) {
                    me.editable();
                }
            }
        };

        this.overlayBar = Ext.create('Ext.container.Container', {
            floating: true,
            cls: 'form-overlay-bar',
            height: 30,
            width: 300,
            layout: {
                type: 'hbox',
                align: 'stretch',
                pack: 'end'
            },
            items: [
                deletebuttonargs,
                {xtype: 'component', width: 10},
                clicktoeditbuttonargs
            ]
        });

        var editformargs = {
            id: me.getChildIdBySuffix('editform'),
            xtype: 'form',
            model: this.model,
            items: this.editformitems,

            // Fields will be arranged vertically, stretched to full width
            layout: 'anchor',
            defaults: {
                anchor: '100%',
            },

            bodyStyle: {
                padding: '15px'
            },

            // Disable by default
            disabled: true,

            // Only save button. Other buttons are in overlayBar
            buttons: [
                savebuttonargs,
            ]
        };

        Ext.apply(this, {
            items: [editformargs],
            layout: 'fit'
        });
        this.callParent(arguments);

        this.editform = Ext.getCmp(editformargs.id);
    },

    deleteCurrent: function() {
        this.editform.submit({
            submitEmptyText: true,
            method: 'DELETE',
            waitMsg: 'Deleting item...',
            success: function() {
            }
        });
    },

    getChildIdBySuffix: function(idsuffix) {
        return this.id + '-' + idsuffix;
    },

    /** Load the request record into the form. */
    loadRecordFromStore: function (record_id) {
        var me = this;
        Ext.ModelManager.getModel(this.model).load(record_id, {
            success: function(record) {
                me.editform.loadRecord(record);
                //var title = Ext.String.format('Edit', record.data.long_name, record.data.short_name);
                //me.editform.setTitle(title);
                var fields = me.editform.getForm().getFields();
                Ext.each(me.foreignkeys, function(fieldname) {
                    var field = fields.filter('name', fieldname).items[0];
                    field.store.load(function(store, records, successful) {
                        field.setValue(record.data[fieldname]);
                    });
                });
            }
        });
    },

    getFormButtonBar: function() {
        return this.editform.dockedItems.items[0];
    },

    readonly: function() {
        this.editform.disable();
        this.overlayBar.show();
        this.overlayBar.alignTo(this, 'tr-tr');
        this.getFormButtonBar().hide();
    },
    editable: function() {
        this.editform.enable();
        this.overlayBar.hide();
        this.getFormButtonBar().show();
    },

    loadUpdateMode: function(record_id) {
        this.loadRecordFromStore(record_id);
        this.readonly();
    },
    loadCreateMode: function() {
        this.editable();
    },
    loadMode: function(mode, record_id) {
        if(mode == "update") {
            this.loadUpdateMode(record_id);
        } else if(mode == "create") {
            this.loadCreateMode();
        }
    }
});
<|endoftext|>


<commit_before>/**
 * jQuery Cookie plugin
 *
 * Copyright (c) 2010 Klaus Hartl (stilbuero.de)
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 *
 */
jQuery.cookie = function (key, value, options) {

    // key and at least value given, set cookie...
    if (arguments.length > 1 && String(value) !== "[object Object]") {
        options = jQuery.extend({}, options);

        if (value === null || value === undefined) {
            options.expires = -1;
        }

        if (typeof options.expires === 'number') {
            var days = options.expires, t = options.expires = new Date();
            t.setDate(t.getDate() + days);
        }

        value = String(value);

        return (document.cookie = [
            encodeURIComponent(key), '=',
            options.raw ? value : encodeURIComponent(value),
            options.expires ? '; expires=' + options.expires.toUTCString() : '', // use expires attribute, max-age is not supported by IE
            options.path ? '; path=' + options.path : '',
            options.domain ? '; domain=' + options.domain : '',
            options.secure ? '; secure' : ''
        ].join(''));
    }

    // key and possibly options given, get cookie...
    options = value || {};
    var result, decode = options.raw ? function (s) { return s; } : decodeURIComponent;
    return (result = new RegExp('(?:^|; )' + encodeURIComponent(key) + '=([^;]*)').exec(document.cookie)) ? decode(result[1]) : null;
};
<commit_msg>Setup jquery-cookie in a closure<commit_after>/**
 * jQuery Cookie plugin
 *
 * Copyright (c) 2010 Klaus Hartl (stilbuero.de)
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 *
 */
(function($) {
    $.cookie = function (key, value, options) {

        // key and at least value given, set cookie...
        if (arguments.length > 1 && String(value) !== "[object Object]") {
            options = $.extend({}, options);

            if (value === null || value === undefined) {
                options.expires = -1;
            }

            if (typeof options.expires === 'number') {
                var days = options.expires, t = options.expires = new Date();
                t.setDate(t.getDate() + days);
            }

            value = String(value);

            return (document.cookie = [
                encodeURIComponent(key), '=',
                options.raw ? value : encodeURIComponent(value),
                options.expires ? '; expires=' + options.expires.toUTCString() : '', // use expires attribute, max-age is not supported by IE
                options.path ? '; path=' + options.path : '',
                options.domain ? '; domain=' + options.domain : '',
                options.secure ? '; secure' : ''
            ].join(''));
        }

        // key and possibly options given, get cookie...
        options = value || {};
        var result, decode = options.raw ? function (s) { return s; } : decodeURIComponent;
        return (result = new RegExp('(?:^|; )' + encodeURIComponent(key) + '=([^;]*)').exec(document.cookie)) ? decode(result[1]) : null;
    };
})(jQuery);
<|endoftext|>


<commit_before>// Main javascript file

$("#buat-post").on('click', function() {
    $("#dashboard").fadeOut(300, function() {
        $("#add-post").fadeIn(400);
        runTinyMCE();
    });
})

$(window).load(function() {
    runTinyMCE();
})

function runTinyMCE() {
    tinymce.init({
        selector: "textarea#editor",
        height: 400,
        plugins: [
            'advlist autolink lists link charmap print preview hr anchor pagebreak',
            'searchreplace wordcount visualblocks visualchars code fullscreen',
            'insertdatetime nonbreaking save table contextmenu directionality',
            'emoticons template paste textcolor colorpicker textpattern imagetools'
        ],
        toolbar1: 'insertfile undo redo | styleselect | bold italic | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | link',
        toolbar2: 'print preview | forecolor backcolor emoticons',
        image_advtab: true
    });
}
<commit_msg>Perubahan kecil pada inisialisasi tinyMCE<commit_after>// Main javascript file

$("#buat-post").on('click', function() {
    $("#dashboard").fadeOut(300, function() {
        $("#add-post").fadeIn(400);
        runTinyMCE();
    });
})

$(window).load(function() {
    runTinyMCE();
})

function runTinyMCE() {
    tinymce.init({
        selector: "textarea#editor",
        height: 400,
        plugins: [
            'advlist autolink lists link charmap print preview hr anchor pagebreak',
            'searchreplace wordcount visualblocks visualchars code fullscreen',
            'insertdatetime nonbreaking save table contextmenu directionality',
            'emoticons template paste textcolor colorpicker textpattern imagetools image'
        ],
        toolbar1: 'insertfile undo redo | styleselect | bold italic | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | link image',
        toolbar2: 'print preview | forecolor backcolor emoticons',
        image_advtab: true
    });
}
<|endoftext|>


<commit_before>/**
 * Author: Olaolu Olawuyi

 * Date Created: 20/08/2015

 * Last Modified: 30/01/2016

 * Twitter: @whizkydee, @webtwic

 * Github: https://github.com/whizkydee/webtwic

*/
var Webtwic = {} || Webtwic;

Webtwic = {
	// Basic Information about Webtwic
	name: "Webtwic",
	description: "A community for coding and tech tweaks where beginners and experts can learn.",
	repo: "https://github.com/whizkydee/webtwic",
	author: "Olaolu Olawuyi",
	version: 1.07,

	// Start main functions for the object

	// Function to add browser name and version to body class
	_showBrowser: function(b) {
		$("body").addClass(b + " " + b + parseInt(browser.version));
	},

	// Function to set attributes and values to elements
	_setAttr: function(elem, name, val) {
		$(elem, this).attr(name, val);
	},

	// Function to hide Notifications
	_hideNotif: function() {
		$("#notifBanner").removeClass("notif_vis");
	},

	// Function to push down .site-content
	_adjustSiteContent: function() {
		if( $("body").hasClass("default-body") ) {
			$(".top-stripe").addClass("adjustedMargin");
			$("#header .logo").addClass("adjustedTop");
			$(".main-menu").addClass("adjustedMargin");
			$("#header").addClass("adjustSiteContent");
		} else if ( $("body").hasClass("secondary-body") ) {
			$(".site-content").addClass("adjustSiteContent");
			$(".secondary-header").addClass("adjustedMargin");
		}
	},

	// Function to push up .site-content to default state
	_undoSiteAdjust: function() {
		if( $("body").hasClass("default-body") ) {
			$(".top-stripe").removeClass("adjustedMargin");
			$("#header .logo").removeClass("adjustedTop");
			$(".main-menu").removeClass("adjustedMargin");
			$("#header").removeClass("adjustSiteContent");
		} else if ( $("body").hasClass("secondary-body") ) {
			$(".secondary-header").removeClass("adjustedMargin");
		}
	},

	_resetSite: function() {
		WBT._showNotif();
		WBT._adjustSiteContent();
	},

	_undoReset: function() {
		WBT._hideNotif();
		WBT._undoSiteAdjust();
	},

	// Function to show Notifications before header
	_showNotif: function(text = notif_text) {
		WBT._adjustSiteContent();
		if( $("body").hasClass("default-body") ) {
			$(".top-stripe").before(
				"
"+text+"
"
			);
		} else if ( $("body").hasClass("secondary-body") ) {
			$(".secondary-header").before(
				"
"+text+"
"
			);
		} else {
			return;
		}
		$(".close-button").on("click", function() {
			WBT._hideNotif();
			WBT._undoSiteAdjust();
		});
	},

	// Function to launch modal

	_launchModal: function(w, h, r, p, c, e, b) {
		this.width = w;
	}

};

jQuery(document).ready(function() {

	// Define Variables
	var is_notifBanner = $("div").hasClass("notif_vis"),
	img = $("img"),
	is_noAlt = img.attr("alt", null),
	scripts = $("script"),
	is_noType = scripts.attr("type", null),
	is_noCharset = scripts.attr("charset", null);

	var $to_top = $("a.to-top"),
	is_toggle_active = $(".hamburger").hasClass("is_active"),
	height = 200;

	// Performance Fixes

	// Start browser detection

	browser = bowser;
	browser.ie = browser.msie;

	if (browser.webkit) {
		$("body").addClass("webkit");
	}
	if(browser.chrome) {
		WBT._showBrowser("chrome");
	}
	if(browser.msedge) {
		WBT._showBrowser("msedge");
	}
	if(browser.firefox) {
		WBT._showBrowser("firefox");
	}
	if(browser.msie) {
		WBT._showBrowser("ie");
	}
	if(browser.safari) {
		WBT._showBrowser("safari");
	}
	if(browser.opera) {
		WBT._showBrowser("opera");
	}

	// Performance fixes for attributes

	if(is_noAlt) {
		WBT._setAttr(img, "alt", "...");
	} else {
		return img.attr("alt");
	}

	if(is_noCharset) {
		WBT._setAttr(scripts, "charset", "utf-8");
	} else {
		return scripts.attr("charset");
	}

	if(is_noType) {
		WBT._setAttr(scripts, "type", "text/javascript");
	} else {
		return scripts.attr("type");
	}

	if (!Modernizr.flexbox || !Modernizr.inlinesvg || !Modernizr.svg || !Modernizr.svgclippaths || !Modernizr.fontface || !Modernizr.boxshadow || !Modernizr.borderradius || !Modernizr.csstransforms) {
		WBT._showNotif();
	} else {
		WBT._hideNotif();
	}

	// Start Main Page

	$("nav li ul.drop-nav").hide().removeClass("dropNavFallback");

	if ( $(window).width() > 860 ) {
		$("nav li.dropdown").hover(function() {
			$("ul.drop-nav", this).stop().slideDown("fast");
		}, function() {
			$("ul.drop-nav", this).stop().slideUp("fast");
		});
	}

	$(".active-item").append(
		"<svg viewBox='0 0 32 32' xmlns='http://www.w3.org/2000/svg' xmlns:xlink='http://www.w3.org/1999/xlink'><path d='M 16.682,19.674c 0.010-0.012, 0.014-0.028, 0.024-0.040l 6.982-7.714c 0.39-0.434, 0.39-1.138,0-1.572 c-0.004-0.004-0.008-0.006-0.012-0.008C 23.496,10.13, 23.244,10, 22.964,10L 8.998,10 c-0.286,0-0.54,0.138-0.722,0.352L 8.272,10.348 c-0.39,0.434-0.39,1.138,0,1.572l 6.998,7.754C 15.66,20.108, 16.292,20.108, 16.682,19.674z'></path></svg>"
	);

	$("a.hamburger").click(function(e) {
		$(this).toggleClass("is_active");

		e.preventDefault();
	});
	$(".mobile-header .mobile-nav").hide();

	$(window).scroll(function() {
		($(this).scrollTop() > height) ? $to_top.addClass("topVisible"): $to_top.removeClass("topVisible");
	});

	// Styles for homepage article-social

	$(".article .article-social a").hover(function() {
		$("span", this).eq(1).fadeIn(400);
	}, function() {
		$("span", this).eq(1).fadeOut(250);
	});

	// Functions for search-icon and ui-overlay-search

	$(".header-follow-search .search-wrap").on("click", function() {
		openUiOverlay();
	});

	$(".header-follow-search .close-icon").on("click", function() {
		closeUiOverlay();
	});

	$(".header-follow-search .close-icon").hover(
		function() {
			$(this).addClass("spin");
		},
		function() {
			$(this).removeClass("spin");
		});

	function openUiOverlay() {
		$(".ui-overlay-search").fadeIn(400).addClass("is_open");
	}

	function closeUiOverlay() {
		$(".ui-overlay-search").fadeOut(400).removeClass("is_open");
	}

	$(".ui-overlay-search .search-input input").focus(function() {
		$(".search-input").attr("data-focused", true);
		$(".search-input input").addClass("_is-focused");
		$("#__expand").addClass("visible");
	});

	$(".ui-overlay-search .search-input input").blur(function() {
		$(".search-input").attr("data-focused", false);
		$(".search-input input").removeClass("_is-focused");
		$("#__expand").removeClass("visible");
	});

	$(".post-meta .post-meta-inner .cta-btns a.is_inactive").on("click", function(e) {
		e.preventDefault();
	});

	$(document).keydown(function(e) {
    if (e.keyCode == 27) {
        closeUiOverlay();
    } else {
		 return;
	 }});

	 $(".mobile-nav").hide();

	// Functions for more-posts button click

	function addLoader() {
		$(".secondary-category-section .category-posts-column [data-clicked='false']").attr("data-clicked", "true").append("");
	}
	$(".secondary-category-section .category-posts-column [data-clicked='false']").on("click", function(e) {
		$(this).css({
			"background": "#50ABF1",
			"color": "#fff"
		});
		addLoader();
		e.preventDefault();
	});

	$to_top.on("click", function(e) {
		$("body,html").animate({
			scrollTop: 0
		}, 1000);

		e.preventDefault();
	});

});
<commit_msg>Update WBT<commit_after>/**
 * Author: Olaolu Olawuyi

 * Date Created: 20/08/2015

 * Last Modified: 30/01/2016

 * Twitter: @whizkydee, @webtwic

 * Github: https://github.com/whizkydee/webtwic

*/
var Webtwic = {} || Webtwic;

Webtwic = {
	// Basic Information about Webtwic
	name: "Webtwic",
	description: "A community for coding and tech tweaks where beginners and experts can learn.",
	repo: "https://github.com/whizkydee/webtwic",
	author: "Olaolu Olawuyi",
	version: 1.07,

	// Start main functions for the object

	// Function to add browser name and version to body class
	_showBrowser: function(b) {
		$("body").addClass(b + " " + b + parseInt(browser.version));
	},

	// Function to set attributes and values to elements
	_setAttr: function(elem, name, val) {
		$(elem, this).attr(name, val);
	},

	// Function to hide Notifications
	_hideNotif: function() {
		$("#notifBanner").removeClass("notif_vis");
	},

	// Function to push down .site-content
	_adjustSiteContent: function() {
		if( $("body").hasClass("default-body") ) {
			$(".top-stripe").addClass("adjustedMargin");
			$("#header .logo").addClass("adjustedTop");
			$(".main-menu").addClass("adjustedMargin");
			$("#header").addClass("adjustSiteContent");
		} else if ( $("body").hasClass("secondary-body") ) {
			$(".site-content").addClass("adjustSiteContent");
			$(".secondary-header").addClass("adjustedMargin");
		}
	},

	// Function to push up .site-content to default state
	_undoSiteAdjust: function() {
		if( $("body").hasClass("default-body") ) {
			$(".top-stripe").removeClass("adjustedMargin");
			$("#header .logo").removeClass("adjustedTop");
			$(".main-menu").removeClass("adjustedMargin");
			$("#header").removeClass("adjustSiteContent");
		} else if ( $("body").hasClass("secondary-body") ) {
			$(".secondary-header").removeClass("adjustedMargin");
		}
	},

	_resetSite: function() {
		WBT._showNotif();
		WBT._adjustSiteContent();
	},

	_undoReset: function() {
		WBT._hideNotif();
		WBT._undoSiteAdjust();
	},

	// Function to show Notifications before header
	_showNotif: function(text = notif_text) {
		WBT._adjustSiteContent();
		if( $("body").hasClass("default-body") ) {
			$(".top-stripe").before(
				"
"+text+"
"
			);
		} else if ( $("body").hasClass("secondary-body") ) {
			$(".secondary-header").before(
				"
"+text+"
"
			);
		} else {
			return;
		}
		$(".close-button").on("click", function() {
			WBT._hideNotif();
			WBT._undoSiteAdjust();
		});
	},

	// Function to launch modal

	_launchModal: function(w, h, r, p, c, e, b) {
		this.width = w;
	}

}, WBT = Webtwic,
notif_text = "Some features which affect the functionality of webtwic are disabled in your browser. Please try refreshing the page or get a better browser. ";

jQuery(document).ready(function() {

	// Define Variables
	var is_notifBanner = $("div").hasClass("notif_vis"),
	img = $("img"),
	is_noAlt = img.attr("alt", null),
	scripts = $("script"),
	is_noType = scripts.attr("type", null),
	is_noCharset = scripts.attr("charset", null);

	var $to_top = $("a.to-top"),
	is_toggle_active = $(".hamburger").hasClass("is_active"),
	height = 200;

	// Performance Fixes

	// Start browser detection

	browser = bowser;
	browser.ie = browser.msie;

	if (browser.webkit) {
		$("body").addClass("webkit");
	}
	if(browser.chrome) {
		WBT._showBrowser("chrome");
	}
	if(browser.msedge) {
		WBT._showBrowser("msedge");
	}
	if(browser.firefox) {
		WBT._showBrowser("firefox");
	}
	if(browser.msie) {
		WBT._showBrowser("ie");
	}
	if(browser.safari) {
		WBT._showBrowser("safari");
	}
	if(browser.opera) {
		WBT._showBrowser("opera");
	}

	// Performance fixes for attributes

	if(is_noAlt) {
		WBT._setAttr(img, "alt", "...");
	} else {
		return img.attr("alt");
	}

	if(is_noCharset) {
		WBT._setAttr(scripts, "charset", "utf-8");
	} else {
		return scripts.attr("charset");
	}

	if(is_noType) {
		WBT._setAttr(scripts, "type", "text/javascript");
	} else {
		return scripts.attr("type");
	}

	if (!Modernizr.flexbox || !Modernizr.inlinesvg || !Modernizr.svg || !Modernizr.svgclippaths || !Modernizr.fontface || !Modernizr.boxshadow || !Modernizr.borderradius || !Modernizr.csstransforms) {
		WBT._showNotif();
	} else {
		WBT._hideNotif();
	}

	// Start Main Page

	$("nav li ul.drop-nav").hide().removeClass("dropNavFallback");

	if ( $(window).width() > 860 ) {
		$("nav li.dropdown").hover(function() {
			$("ul.drop-nav", this).stop().slideDown("fast");
		}, function() {
			$("ul.drop-nav", this).stop().slideUp("fast");
		});
	}

	$(".active-item").append(
		"<svg viewBox='0 0 32 32' xmlns='http://www.w3.org/2000/svg' xmlns:xlink='http://www.w3.org/1999/xlink'><path d='M 16.682,19.674c 0.010-0.012, 0.014-0.028, 0.024-0.040l 6.982-7.714c 0.39-0.434, 0.39-1.138,0-1.572 c-0.004-0.004-0.008-0.006-0.012-0.008C 23.496,10.13, 23.244,10, 22.964,10L 8.998,10 c-0.286,0-0.54,0.138-0.722,0.352L 8.272,10.348 c-0.39,0.434-0.39,1.138,0,1.572l 6.998,7.754C 15.66,20.108, 16.292,20.108, 16.682,19.674z'></path></svg>"
	);

	$("a.hamburger").click(function(e) {
		$(this).toggleClass("is_active");

		e.preventDefault();
	});
	$(".mobile-header .mobile-nav").hide();

	$(window).scroll(function() {
		($(this).scrollTop() > height) ? $to_top.addClass("topVisible"): $to_top.removeClass("topVisible");
	});

	// Styles for homepage article-social

	$(".article .article-social a").hover(function() {
		$("span", this).eq(1).fadeIn(400);
	}, function() {
		$("span", this).eq(1).fadeOut(250);
	});

	// Functions for search-icon and ui-overlay-search

	$(".header-follow-search .search-wrap").on("click", function() {
		openUiOverlay();
	});

	$(".header-follow-search .close-icon").on("click", function() {
		closeUiOverlay();
	});

	$(".header-follow-search .close-icon").hover(
		function() {
			$(this).addClass("spin");
		},
		function() {
			$(this).removeClass("spin");
		});

	function openUiOverlay() {
		$(".ui-overlay-search").fadeIn(400).addClass("is_open");
	}

	function closeUiOverlay() {
		$(".ui-overlay-search").fadeOut(400).removeClass("is_open");
	}

	$(".ui-overlay-search .search-input input").focus(function() {
		$(".search-input").attr("data-focused", true);
		$(".search-input input").addClass("_is-focused");
		$("#__expand").addClass("visible");
	});

	$(".ui-overlay-search .search-input input").blur(function() {
		$(".search-input").attr("data-focused", false);
		$(".search-input input").removeClass("_is-focused");
		$("#__expand").removeClass("visible");
	});

	$(".post-meta .post-meta-inner .cta-btns a.is_inactive").on("click", function(e) {
		e.preventDefault();
	});

	$(document).keydown(function(e) {
    if (e.keyCode == 27) {
        closeUiOverlay();
    } else {
		 return;
	 }});

	 $(".mobile-nav").hide();

	// Functions for more-posts button click

	function addLoader() {
		$(".secondary-category-section .category-posts-column [data-clicked='false']").attr("data-clicked", "true").append("");
	}
	$(".secondary-category-section .category-posts-column [data-clicked='false']").on("click", function(e) {
		$(this).css({
			"background": "#50ABF1",
			"color": "#fff"
		});
		addLoader();
		e.preventDefault();
	});

	$to_top.on("click", function(e) {
		$("body,html").animate({
			scrollTop: 0
		}, 1000);

		e.preventDefault();
	});

});
<|endoftext|>


<commit_before>var path = require('path');
var nroonga = require('../../wrapped-nroonga');
var Domain = require('../../database').Domain;
var Translator = require('../../batch/translator').Translator;
var dateFormat = require('dateformat');
var xmlbuilder = require('../../xmlbuilder');

exports.version = path.basename(__dirname);

var XMLNS = 'http://cloudsearch.amazonaws.com/doc/2011-02-01';

function createCommonErrorResponse(errorCode, error) {
  var doc = xmlbuilder.create();
  doc.begin('Response', { version: '1.0' })
    .element('Errors')
      .element('Error')
        .element('Code').text(errorCode).up()
        .element('Message').text(error.message || error).up()
      .up()
    .up()
    .element('RequestID').up();
  return doc.toString();
}

var handlers = Object.create(null);

function getBaseDomain(domain) {
  return domain.replace(/^cloudsearch\./, '');
}

function createDomainStatus(options) {
  var domainStatus = xmlbuilder.create();
  domainStatus.begin('DomainStatus', { version: '1.0' })
    .element('Created').text(options.created || 'false').up()
    .element('Deleted').text(options.deleted || 'false').up()
    .element('DocService')
      .element('Endpoint').text(options.domain.getDocumentsEndpoint(options.hostname)).up()
    .up()
    .element('DomainId')
      .text(options.domain.domainId)
    .up()
    .element('DomainName').text(options.domain.name).up()
    .element('NumSearchableDocs')
      .text(options.domain.searchableDocumentsCount)
    .up()
    .element('RequiresIndexDocuments')
      .text(options.domain.requiresIndexDocuments)
    .up()
    .element('SearchInstanceCount')
      .text(options.domain.searchInstanceCount)
    .up()
    .element('SearchPartitionCount')
      .text(options.domain.searchPartitionCount)
    .up()
    .element('SearchService')
      .element('Endpoint').text(options.domain.getSearchEndpoint(options.hostname)).up()
    .up();
  return domainStatus;
}

function createCreateDomainResponse(options) {
  var doc = xmlbuilder.create();
  doc.begin('CreateDomainResponse', { version: '1.0' })
    .attribute('xmlns', XMLNS)
    .element('CreateDomainResult')
      .importXMLBuilder(createDomainStatus(options))
    .up()
    .element('ResponseMetadata')
      .element('RequestId').text(options.requestId || '').up()
    .up();
  return doc.toString();
}

handlers.CreateDomain = function(context, request, response) {
  var domain = new Domain(request, context);
  try {
    domain.createSync();
    var host = getBaseDomain(request.headers.host);
    host = host ? '.' + host : '';
    response.contentType('application/xml');
    response.send(createCreateDomainResponse({
      domain: domain,
      hostname: host,
      created: true
    }));
  } catch (error) {
    var body = createCommonErrorResponse('InternalFailure', error);
    response.contentType('application/xml');
    response.send(body, 400);
  }
};

function createDeleteDomainResponse(options) {
  var doc = xmlbuilder.create();
  doc.begin('DeleteDomainResponse', { version: '1.0' })
    .attribute('xmlns', XMLNS)
    .element('DeleteDomainResult')
      .importXMLBuilder(createDomainStatus(options))
    .up()
    .element('ResponseMetadata')
      .element('RequestId').text(options.requestId || '').up()
    .up();
  return doc.toString();
}

handlers.DeleteDomain = function(context, request, response) {
  var domain = new Domain(request, context);
  try {
    domain.deleteSync();
    var host = getBaseDomain(request.headers.host);
    host = host ? '.' + host : '';
    response.contentType('application/xml');
    response.send(createDeleteDomainResponse({
      domain: domain,
      hostname: host,
      deleted: true
    }));
  } catch (error) {
    var body = createCommonErrorResponse('InternalFailure', error.message);
    response.contentType('application/xml');
    response.send(body, 400);
  }
};

function createIndexFieldOptionStatus(options) {
  switch (options.field.type) {
    case 'text':
      var textOptions = xmlbuilder.create();
      textOptions.begin('TextOptions', { version: '1.0' })
        .element('DefaultValue').up()
        .element('FacetEnabled').text(options.field.facetEnabled).up()
        .element('ResultEnabled').text(options.field.resultEnabled);
      return textOptions;
    case 'uint':
      var uintOptions = xmlbuilder.create();
      uintOptions.begin('UIntOptions', { version: '1.0' })
        .element('DefaultValue');
      return uintOptions;
    case 'literal':
      var literalOptions = xmlbuilder.create();
      literalOptions.begin('LiteralOptions', { version: '1.0' })
        .element('DefaultValue').up()
        .element('FacetEnabled').text(options.field.facetEnabled).up()
        .element('ResultEnabled').text(options.field.resultEnabled).up()
        .element('SearchEnabled').text(options.field.searchEnabled);
      return literalOptions;
  }
}

function createIndexFieldStatus(options) {
  var indexFieldStatus = xmlbuilder.create();
  indexFieldStatus.begin('IndexField', { version: '1.0' })
    .element('Options')
      .element('IndexFieldName').text(options.field.name).up()
      .element('IndexFieldType').text(options.field.type).up()
      .importXMLBuilder(createIndexFieldOptionStatus(options))
    .up()
    .element('Status')
      .element('CreationDate').text(dateFormat(options.createdAt,
                                               'isoUtcDateTime')).up()
      .element('State').text(options.field.state).up()
      .element('UpdateDate').text(dateFormat(options.updatedAt,
                                             'isoUtcDateTime')).up()
      .element('UpdateVersion').text(options.updateVersion || '0').up()
    .up();
  return indexFieldStatus;
}

function createDefineIndexFieldResponse(options) {
  var doc = xmlbuilder.create();
  doc.begin('DefineIndexFieldResponse', { version: '1.0' })
    .attribute('xmlns', XMLNS)
    .element('DefineIndexFieldResult')
      .importXMLBuilder(createIndexFieldStatus(options))
    .up()
    .element('ResponseMetadata')
      .element('RequestId').text(options.requestId || '').up()
    .up();
  return doc.toString();
}

handlers.DefineIndexField = function(context, request, response) {
  var domain = new Domain(request, context);

  var fieldName = request.query['IndexField.IndexFieldName'] || '';
  var fieldType = request.query['IndexField.IndexFieldType'] || 'text';
  var field = domain.getIndexField(fieldName);

  var createdAt = new Date();
  try {
    field.type = fieldType;
    field.createSync();
    response.contentType('application/xml');
    response.send(createDefineIndexFieldResponse({
      field: field,
      createdAt: createdAt,
      updatedAt: createdAt
    }));
  } catch (error) {
    var body = createCommonErrorResponse('InternalFailure', error.message);
    response.contentType('application/xml');
    response.send(body, 400);
  }
};

function createDeleteIndexFieldResponse(options) {
  var doc = xmlbuilder.create();
  doc.begin('DeleteIndexFieldResponse', {version: '1.0'})
    .attribute('xmlns', XMLNS)
    .element('DeleteIndexFieldResult').up()
    .element('ResponseMetadata')
      .element('RequestId').text(options.requestId || '').up()
    .up();
  return doc.toString();
}

handlers.DeleteIndexField = function(context, request, response) {
  var domain = new Domain(request, context);

  var fieldName = request.query['IndexFieldName'] || '';
  var field = domain.getIndexField(fieldName);
  try {
    field.deleteSync();
    response.contentType('application/xml');
    response.send(createDeleteIndexFieldResponse({}));
  } catch (error) {
    var body = createCommonErrorResponse('InternalFailure', error.message);
    response.contentType('application/xml');
    response.send(body, 400);
  }
};

function createIndexDocumentsResponse(options) {
  var doc = xmlbuilder.create();
  var root = doc.begin('IndexDocumentsResponse', {version: '1.0'})
                .attribute('xmlns', XMLNS);

  var fieldNames = root.element('IndexDocumentsResult')
                       .element('FieldNames');
  options.fieldNames.forEach(function(fieldName) {
    var member = xmlbuilder.create();
    member.begin('member', { version: '1.0' })
      .text(fieldName);
    fieldNames.importXMLBuilder(member);
  });

  root.element('ResponseMetadata')
      .element('RequestId').text(options.requestId || '');

  return doc.toString();
}

handlers.IndexDocuments = function(context, request, response) {
  var domain = new Domain(request, context);
  var indexFieldNames = domain.indexFields
                          .map(function(field) {
                            return field.name;
                          })
                          .sort();
  try {
    domain.reindexSync();
    response.contentType('application/xml');
    response.send(createIndexDocumentsResponse({
      fieldNames: indexFieldNames
    }));
  } catch (error) {
    var body = createCommonErrorResponse('InternalFailure', error.message);
    response.contentType('application/xml');
    response.send(body, 400);
  }
};

function createUpdateSynonymOptionsResponse(options) {
  var doc = xmlbuilder.create();
  doc.begin('UpdateSynonymOptionsResponse', { version: '1.0' })
    .attribute('xmlns', XMLNS)
    .element('UpdateSynonymOptionsResult')
      .element('Synonyms')
        .element('Status')
          .element('CreationDate').text(dateFormat(options.createdAt,
                                                   'isoUtcDateTime')).up()
          .element('UpdateVersion').text(options.updateVersion || '0').up()
          .element('State').text(options.state || 'RequiresIndexDocuments').up()
          .element('UpdateDate').text(dateFormat(options.updatedAt,
                                                 'isoUtcDateTime')).up()
        .up()
        .element('Options')
          .text(options.synonymOptions || '{}')
        .up()
      .up()
    .up()
    .element('ResponseMetadata')
      .element('RequestId').text(options.requestId || '').up()
    .up();
  return doc.toString();
}
handlers.UpdateSynonymOptions = function(context, request, response) {
  var domain = new Domain(request, context);
  try {
    var synonymOptionsJson = request.query.Synonyms;
    var synonymOptions = JSON.parse(synonymOptionsJson);

    var updatedAt = new Date();

    domain.updateSynonymsSync(synonymOptions);

    response.send(createUpdateSynonymOptionsResponse({
      synonymOptions: JSON.stringify(synonymOptions),
      updatedAt: updatedAt,
      createdAt: updatedAt
    }));
  } catch (error) {
    var body = createCommonErrorResponse('InternalFailure', error.message);
    response.contentType('application/xml');
    response.send(body, 400);
  }
};

exports.createHandler = function(context) {
  return function(request, response, next) {
    var message, body;

    // GCS specific behaviour: fallback to other handlers for the endpoint
    // if no action is given.
    var action = request.query.Action || '';
    if (!action)
      return next();

    var version = request.query.Version;
    if (!version) {
      message = 'An input parameter "Version" that is mandatory for ' +
                'processing the request is not supplied.';
      body = createCommonErrorResponse('MissingParameter', message);
      response.contentType('application/xml');
      return response.send(body, 400);
    }

    if (version != exports.version) {
      message = 'A bad or out-of-range value "' + version + '" was supplied ' +
                'for the "Version" input parameter.';
      body = createCommonErrorResponse('InvalidParameterValue', message);
      response.contentType('application/xml');
      return response.send(body, 400);
    }

    if (!(action in handlers)) {
      message = 'The action ' + action + ' is not valid for this web service.';
      body = createCommonErrorResponse('InvalidAction', message);
      response.contentType('application/xml');
      return response.send(body, 400);
    }

    var handler = handlers[action];
    handler(context, request, response);
  };
};
<commit_msg>Collect field names in createIndexDocumentsResponse()<commit_after>var path = require('path');
var nroonga = require('../../wrapped-nroonga');
var Domain = require('../../database').Domain;
var Translator = require('../../batch/translator').Translator;
var dateFormat = require('dateformat');
var xmlbuilder = require('../../xmlbuilder');

exports.version = path.basename(__dirname);

var XMLNS = 'http://cloudsearch.amazonaws.com/doc/2011-02-01';

function createCommonErrorResponse(errorCode, error) {
  var doc = xmlbuilder.create();
  doc.begin('Response', { version: '1.0' })
    .element('Errors')
      .element('Error')
        .element('Code').text(errorCode).up()
        .element('Message').text(error.message || error).up()
      .up()
    .up()
    .element('RequestID').up();
  return doc.toString();
}

var handlers = Object.create(null);

function getBaseDomain(domain) {
  return domain.replace(/^cloudsearch\./, '');
}

function createDomainStatus(options) {
  var domainStatus = xmlbuilder.create();
  domainStatus.begin('DomainStatus', { version: '1.0' })
    .element('Created').text(options.created || 'false').up()
    .element('Deleted').text(options.deleted || 'false').up()
    .element('DocService')
      .element('Endpoint').text(options.domain.getDocumentsEndpoint(options.hostname)).up()
    .up()
    .element('DomainId')
      .text(options.domain.domainId)
    .up()
    .element('DomainName').text(options.domain.name).up()
    .element('NumSearchableDocs')
      .text(options.domain.searchableDocumentsCount)
    .up()
    .element('RequiresIndexDocuments')
      .text(options.domain.requiresIndexDocuments)
    .up()
    .element('SearchInstanceCount')
      .text(options.domain.searchInstanceCount)
    .up()
    .element('SearchPartitionCount')
      .text(options.domain.searchPartitionCount)
    .up()
    .element('SearchService')
      .element('Endpoint').text(options.domain.getSearchEndpoint(options.hostname)).up()
    .up();
  return domainStatus;
}

function createCreateDomainResponse(options) {
  var doc = xmlbuilder.create();
  doc.begin('CreateDomainResponse', { version: '1.0' })
    .attribute('xmlns', XMLNS)
    .element('CreateDomainResult')
      .importXMLBuilder(createDomainStatus(options))
    .up()
    .element('ResponseMetadata')
      .element('RequestId').text(options.requestId || '').up()
    .up();
  return doc.toString();
}

handlers.CreateDomain = function(context, request, response) {
  var domain = new Domain(request, context);
  try {
    domain.createSync();
    var host = getBaseDomain(request.headers.host);
    host = host ? '.' + host : '';
    response.contentType('application/xml');
    response.send(createCreateDomainResponse({
      domain: domain,
      hostname: host,
      created: true
    }));
  } catch (error) {
    var body = createCommonErrorResponse('InternalFailure', error);
    response.contentType('application/xml');
    response.send(body, 400);
  }
};

function createDeleteDomainResponse(options) {
  var doc = xmlbuilder.create();
  doc.begin('DeleteDomainResponse', { version: '1.0' })
    .attribute('xmlns', XMLNS)
    .element('DeleteDomainResult')
      .importXMLBuilder(createDomainStatus(options))
    .up()
    .element('ResponseMetadata')
      .element('RequestId').text(options.requestId || '').up()
    .up();
  return doc.toString();
}

handlers.DeleteDomain = function(context, request, response) {
  var domain = new Domain(request, context);
  try {
    domain.deleteSync();
    var host = getBaseDomain(request.headers.host);
    host = host ? '.' + host : '';
    response.contentType('application/xml');
    response.send(createDeleteDomainResponse({
      domain: domain,
      hostname: host,
      deleted: true
    }));
  } catch (error) {
    var body = createCommonErrorResponse('InternalFailure', error.message);
    response.contentType('application/xml');
    response.send(body, 400);
  }
};

function createIndexFieldOptionStatus(options) {
  switch (options.field.type) {
    case 'text':
      var textOptions = xmlbuilder.create();
      textOptions.begin('TextOptions', { version: '1.0' })
        .element('DefaultValue').up()
        .element('FacetEnabled').text(options.field.facetEnabled).up()
        .element('ResultEnabled').text(options.field.resultEnabled);
      return textOptions;
    case 'uint':
      var uintOptions = xmlbuilder.create();
      uintOptions.begin('UIntOptions', { version: '1.0' })
        .element('DefaultValue');
      return uintOptions;
    case 'literal':
      var literalOptions = xmlbuilder.create();
      literalOptions.begin('LiteralOptions', { version: '1.0' })
        .element('DefaultValue').up()
        .element('FacetEnabled').text(options.field.facetEnabled).up()
        .element('ResultEnabled').text(options.field.resultEnabled).up()
        .element('SearchEnabled').text(options.field.searchEnabled);
      return literalOptions;
  }
}

function createIndexFieldStatus(options) {
  var indexFieldStatus = xmlbuilder.create();
  indexFieldStatus.begin('IndexField', { version: '1.0' })
    .element('Options')
      .element('IndexFieldName').text(options.field.name).up()
      .element('IndexFieldType').text(options.field.type).up()
      .importXMLBuilder(createIndexFieldOptionStatus(options))
    .up()
    .element('Status')
      .element('CreationDate').text(dateFormat(options.createdAt,
                                               'isoUtcDateTime')).up()
      .element('State').text(options.field.state).up()
      .element('UpdateDate').text(dateFormat(options.updatedAt,
                                             'isoUtcDateTime')).up()
      .element('UpdateVersion').text(options.updateVersion || '0').up()
    .up();
  return indexFieldStatus;
}

function createDefineIndexFieldResponse(options) {
  var doc = xmlbuilder.create();
  doc.begin('DefineIndexFieldResponse', { version: '1.0' })
    .attribute('xmlns', XMLNS)
    .element('DefineIndexFieldResult')
      .importXMLBuilder(createIndexFieldStatus(options))
    .up()
    .element('ResponseMetadata')
      .element('RequestId').text(options.requestId || '').up()
    .up();
  return doc.toString();
}

handlers.DefineIndexField = function(context, request, response) {
  var domain = new Domain(request, context);

  var fieldName = request.query['IndexField.IndexFieldName'] || '';
  var fieldType = request.query['IndexField.IndexFieldType'] || 'text';
  var field = domain.getIndexField(fieldName);

  var createdAt = new Date();
  try {
    field.type = fieldType;
    field.createSync();
    response.contentType('application/xml');
    response.send(createDefineIndexFieldResponse({
      field: field,
      createdAt: createdAt,
      updatedAt: createdAt
    }));
  } catch (error) {
    var body = createCommonErrorResponse('InternalFailure', error.message);
    response.contentType('application/xml');
    response.send(body, 400);
  }
};

function createDeleteIndexFieldResponse(options) {
  var doc = xmlbuilder.create();
  doc.begin('DeleteIndexFieldResponse', {version: '1.0'})
    .attribute('xmlns', XMLNS)
    .element('DeleteIndexFieldResult').up()
    .element('ResponseMetadata')
      .element('RequestId').text(options.requestId || '').up()
    .up();
  return doc.toString();
}

handlers.DeleteIndexField = function(context, request, response) {
  var domain = new Domain(request, context);

  var fieldName = request.query['IndexFieldName'] || '';
  var field = domain.getIndexField(fieldName);
  try {
    field.deleteSync();
    response.contentType('application/xml');
    response.send(createDeleteIndexFieldResponse({}));
  } catch (error) {
    var body = createCommonErrorResponse('InternalFailure', error.message);
    response.contentType('application/xml');
    response.send(body, 400);
  }
};

function createIndexDocumentsResponse(options) {
  var doc = xmlbuilder.create();
  var root = doc.begin('IndexDocumentsResponse', {version: '1.0'})
                .attribute('xmlns', XMLNS);

  var fieldNames = root.element('IndexDocumentsResult')
                       .element('FieldNames');
  options.domain.indexFields
    .map(function(field) {
      return field.name;
    })
    .sort()
    .forEach(function(fieldName) {
      var member = xmlbuilder.create();
      member.begin('member', { version: '1.0' })
        .text(fieldName);
     fieldNames.importXMLBuilder(member);
    });

  root.element('ResponseMetadata')
      .element('RequestId').text(options.requestId || '');

  return doc.toString();
}

handlers.IndexDocuments = function(context, request, response) {
  var domain = new Domain(request, context);
  try {
    domain.reindexSync();
    response.contentType('application/xml');
    response.send(createIndexDocumentsResponse({
      domain: domain
    }));
  } catch (error) {
    var body = createCommonErrorResponse('InternalFailure', error.message);
    response.contentType('application/xml');
    response.send(body, 400);
  }
};

function createUpdateSynonymOptionsResponse(options) {
  var doc = xmlbuilder.create();
  doc.begin('UpdateSynonymOptionsResponse', { version: '1.0' })
    .attribute('xmlns', XMLNS)
    .element('UpdateSynonymOptionsResult')
      .element('Synonyms')
        .element('Status')
          .element('CreationDate').text(dateFormat(options.createdAt,
                                                   'isoUtcDateTime')).up()
          .element('UpdateVersion').text(options.updateVersion || '0').up()
          .element('State').text(options.state || 'RequiresIndexDocuments').up()
          .element('UpdateDate').text(dateFormat(options.updatedAt,
                                                 'isoUtcDateTime')).up()
        .up()
        .element('Options')
          .text(options.synonymOptions || '{}')
        .up()
      .up()
    .up()
    .element('ResponseMetadata')
      .element('RequestId').text(options.requestId || '').up()
    .up();
  return doc.toString();
}
handlers.UpdateSynonymOptions = function(context, request, response) {
  var domain = new Domain(request, context);
  try {
    var synonymOptionsJson = request.query.Synonyms;
    var synonymOptions = JSON.parse(synonymOptionsJson);

    var updatedAt = new Date();

    domain.updateSynonymsSync(synonymOptions);

    response.send(createUpdateSynonymOptionsResponse({
      synonymOptions: JSON.stringify(synonymOptions),
      updatedAt: updatedAt,
      createdAt: updatedAt
    }));
  } catch (error) {
    var body = createCommonErrorResponse('InternalFailure', error.message);
    response.contentType('application/xml');
    response.send(body, 400);
  }
};

exports.createHandler = function(context) {
  return function(request, response, next) {
    var message, body;

    // GCS specific behaviour: fallback to other handlers for the endpoint
    // if no action is given.
    var action = request.query.Action || '';
    if (!action)
      return next();

    var version = request.query.Version;
    if (!version) {
      message = 'An input parameter "Version" that is mandatory for ' +
                'processing the request is not supplied.';
      body = createCommonErrorResponse('MissingParameter', message);
      response.contentType('application/xml');
      return response.send(body, 400);
    }

    if (version != exports.version) {
      message = 'A bad or out-of-range value "' + version + '" was supplied ' +
                'for the "Version" input parameter.';
      body = createCommonErrorResponse('InvalidParameterValue', message);
      response.contentType('application/xml');
      return response.send(body, 400);
    }

    if (!(action in handlers)) {
      message = 'The action ' + action + ' is not valid for this web service.';
      body = createCommonErrorResponse('InvalidAction', message);
      response.contentType('application/xml');
      return response.send(body, 400);
    }

    var handler = handlers[action];
    handler(context, request, response);
  };
};
<|endoftext|>


<commit_before>
/*!--------------------------------*\
   3-Jekyll Theme
   @author Peiwen Lu (P233)
   https://github.com/P233/3-Jekyll
\*---------------------------------*/

// Detect window size, if less than 1280px add class 'mobile' to sidebar therefore it will be auto hide when trigger the pjax request in small screen devices.
if ($(window).width() <= 1920) {
  $('#sidebar').addClass('mobile')
}

// Variables
var sidebar    = $('#sidebar'),
    container  = $('#post'),
    content    = $('#pjax'),
    button     = $('#icon-arrow');

// Tags switcher
var clickHandler = function(id) {
  return function() {
    $(this).addClass('active').siblings().removeClass('active');
    $('.pl__all').hide();
    $('.' + id).delay(50).fadeIn(350);
  }
};

$('#tags__ul li').each(function(index){
  $('#' + $(this).attr('id')).on('click', clickHandler($(this).attr('id')));
});

//判断是否是微信浏览器
function isWeiXin(){
    var ua = window.navigator.userAgent.toLowerCase();
    if(ua.match(/MicroMessenger/i) == 'micromessenger'){
        return true;
    }else{
        return false;
    }
}

// If sidebar has class 'mobile', hide it after clicking.
$('.pl__all').on('click', function(even) {
  $(this).addClass('active').siblings().removeClass('active');
  if( isWeiXin() ){
    setTimeout(function(){
      alert(location.href)
      location.reload(true);
    },0);
  }else{
    $('#sidebar, #pjax, #icon-arrow').addClass('fullscreen');
  }
});

$(document).ready(function() {
  if (sidebar.hasClass('mobile')) {
    $('#sidebar, #pjax, #icon-arrow').addClass('fullscreen');
  }

  //@16-09-09 监听Ctrl+Enter || Enter键--以打开或关闭左边SideBar---Start;
  document.onkeydown=function(event){
　　 if(13 == event.keyCode && event.ctrlKey){
        openOrCloseSidebar(true)
    }else if(13 == event.keyCode){
        openOrCloseSidebar(false)
    }
　}
  //@16-09-09 监听Ctrl+Enter || Enter键--以打开或关闭左边SideBar----End;

  //@17-11-20 Randomly updated ads display basis configuration
  var jadeAdsConfArr = [
    {path: '//t.cn/Rj36MOy', image: '//t.cn/Rj36MOU'},
    {path: '//t.cn/RjB8Z0C', image: '//t.cn/Rik8XrG'}]
  var randomIdx = Math.floor(Math.random() * jadeAdsConfArr.length)
  $('#jade-ads-block .jade-ads-a').attr("href", jadeAdsConfArr[randomIdx].path)
  $('#jade-ads-block .jade-ads-img').attr("src", jadeAdsConfArr[randomIdx].image)
});

//Modify On-2016-02-26.-----------------Start
$allLink = $('.pl__all');//所有链接
$('#search-input').on('input', function(e){
    var value = this.value;
    $allLink.hide();
    var filter = "all"; //所有链接中搜索
    if (filter === 'all') {
        $.each($allLink, function(k, v){
            $(v).filter(":contains('"+value+"')").fadeIn(350);
        });
    }else{
       $.each($filterLink[filter], function(k, v){
            $(v).filter(":contains('"+value+"')").fadeIn(350);
        });
    }
});
//Modify On-2016-02-26.-----------------End

function openOrCloseSidebar(isFocus){
    if (button.hasClass('fullscreen')) {
      sidebar.removeClass('fullscreen');
      button.removeClass('fullscreen');
      content.delay(300).queue(function(){
        $(this).removeClass('fullscreen').dequeue();
      });
      if(isFocus){
        setTimeout(function(){document.getElementById('search-input').focus();},0)
      }
    } else {
      sidebar.addClass('fullscreen');
      button.addClass('fullscreen');
      content.delay(200).queue(function(){
        $(this).addClass('fullscreen').dequeue();
      });
    }
}

// Enable fullscreen.
$('#js-fullscreen').on('click', function() {
    openOrCloseSidebar()
});

$('#mobile-avatar').on('click', function(){
  $('#sidebar, #pjax, #icon-arrow').addClass('fullscreen');
});

// Pjax
$(document).pjax('#avatar, #mobile-avatar, .pl__all', '#pjax', { fragment: '#pjax', timeout: 10000 });
$(document).on({
  'pjax:click': function() {
    content.removeClass('fadeIn').addClass('fadeOut');
    NProgress.start();
  },
  'pjax:start': function() {
    content.css({'opacity':0});
  },
  'pjax:end': function() {
    NProgress.done();
    container.scrollTop(0);
    content.css({'opacity':1}).removeClass('fadeOut').addClass('fadeIn');
    afterPjax();
  }
});

// Re-run scripts for post content after pjax
function afterPjax() {
  // Open links in new tab
  $('#post__content a').attr('target','_blank');

  // Generate post TOC for h1 h2 and h3
  var toc = $('#post__toc-ul');
  // Empty TOC and generate an entry for h1
  toc.empty().append('
' + $('#post__title').text() + '
');

  // Generate entries for h2 and h3
  $('#post__content').children('h2,h3').each(function() {
    // Generate random ID for each heading
    $(this).attr('id', function() {
      var ID = "",
          alphabet = "abcdefghijklmnopqrstuvwxyz";

      for(var i=0; i < 5; i++) {
        ID += alphabet.charAt(Math.floor(Math.random() * alphabet.length));
      }
      return ID;
    });

    if ($(this).prop("tagName") == 'H2') {
      toc.append('
' + $(this).text() + '
');
    } else {
      toc.append('
' + $(this).text() + '
');
    }
  });

  // Smooth scrolling
  $('.js-anchor-link').on('click', function() {
    var target = $(this.hash);
    container.animate({scrollTop: target.offset().top + container.scrollTop() - 70}, 500, function() {
      target.addClass('flash').delay(700).queue(function() {
        $(this).removeClass('flash').dequeue();
      });
    });
  });

  // Lazy Loading Disqus
  // http://jsfiddle.net/dragoncrew/SHGwe/1/
  var ds_loaded = false,
      top = $('#disqus_thread').offset().top;
  window.disqus_shortname = $('#disqus_thread').attr('name');

  function check() {
    if ( !ds_loaded && container.scrollTop() + container.height() > top ) {
      $.ajax({
        type: 'GET',
        url: '//' + disqus_shortname + '.disqus.com/embed.js',
        dataType: 'script',
        cache: true
      });
      ds_loaded = true;
    }
  }check();
  container.scroll(check);
}
afterPjax();
<commit_msg>fix(mobile): fix bug about switch page on wechat🐛<commit_after>
/*!--------------------------------*\
   3-Jekyll Theme
   @author Peiwen Lu (P233)
   https://github.com/P233/3-Jekyll
\*---------------------------------*/

// Detect window size, if less than 1280px add class 'mobile' to sidebar therefore it will be auto hide when trigger the pjax request in small screen devices.
if ($(window).width() <= 1920) {
  $('#sidebar').addClass('mobile')
}

// Variables
var sidebar    = $('#sidebar'),
    container  = $('#post'),
    content    = $('#pjax'),
    button     = $('#icon-arrow');

// Tags switcher
var clickHandler = function(id) {
  return function() {
    $(this).addClass('active').siblings().removeClass('active');
    $('.pl__all').hide();
    $('.' + id).delay(50).fadeIn(350);
  }
};

$('#tags__ul li').each(function(index){
  $('#' + $(this).attr('id')).on('click', clickHandler($(this).attr('id')));
});

//判断是否是微信浏览器
function isWeiXin(){
    var ua = window.navigator.userAgent.toLowerCase();
    if(ua.match(/MicroMessenger/i) == 'micromessenger'){
        return true;
    }else{
        return false;
    }
}

// If sidebar has class 'mobile', hide it after clicking.
$('.pl__all').on('click', function(even) {
  $(this).addClass('active').siblings().removeClass('active');
  $('#sidebar, #pjax, #icon-arrow').addClass('fullscreen');
  if( isWeiXin() ){
    setTimeout(function(){location.reload(true);},0);
  }
});

$(document).ready(function() {
  if (sidebar.hasClass('mobile')) {
    $('#sidebar, #pjax, #icon-arrow').addClass('fullscreen');
  }

  //@16-09-09 监听Ctrl+Enter || Enter键--以打开或关闭左边SideBar---Start;
  document.onkeydown=function(event){
　　 if(13 == event.keyCode && event.ctrlKey){
        openOrCloseSidebar(true)
    }else if(13 == event.keyCode){
        openOrCloseSidebar(false)
    }
　}
  //@16-09-09 监听Ctrl+Enter || Enter键--以打开或关闭左边SideBar----End;

  //@17-11-20 Randomly updated ads display basis configuration
  var jadeAdsConfArr = [
    {path: '//t.cn/Rj36MOy', image: '//t.cn/Rj36MOU'},
    {path: '//t.cn/RjB8Z0C', image: '//t.cn/Rik8XrG'}]
  var randomIdx = Math.floor(Math.random() * jadeAdsConfArr.length)
  $('#jade-ads-block .jade-ads-a').attr("href", jadeAdsConfArr[randomIdx].path)
  $('#jade-ads-block .jade-ads-img').attr("src", jadeAdsConfArr[randomIdx].image)
});

//Modify On-2016-02-26.-----------------Start
$allLink = $('.pl__all');//所有链接
$('#search-input').on('input', function(e){
    var value = this.value;
    $allLink.hide();
    var filter = "all"; //所有链接中搜索
    if (filter === 'all') {
        $.each($allLink, function(k, v){
            $(v).filter(":contains('"+value+"')").fadeIn(350);
        });
    }else{
       $.each($filterLink[filter], function(k, v){
            $(v).filter(":contains('"+value+"')").fadeIn(350);
        });
    }
});
//Modify On-2016-02-26.-----------------End

function openOrCloseSidebar(isFocus){
    if (button.hasClass('fullscreen')) {
      sidebar.removeClass('fullscreen');
      button.removeClass('fullscreen');
      content.delay(300).queue(function(){
        $(this).removeClass('fullscreen').dequeue();
      });
      if(isFocus){
        setTimeout(function(){document.getElementById('search-input').focus();},0)
      }
    } else {
      sidebar.addClass('fullscreen');
      button.addClass('fullscreen');
      content.delay(200).queue(function(){
        $(this).addClass('fullscreen').dequeue();
      });
    }
}

// Enable fullscreen.
$('#js-fullscreen').on('click', function() {
    openOrCloseSidebar()
});

$('#mobile-avatar').on('click', function(){
  $('#sidebar, #pjax, #icon-arrow').addClass('fullscreen');
});

// Pjax
$(document).pjax('#avatar, #mobile-avatar, .pl__all', '#pjax', { fragment: '#pjax', timeout: 10000 });
$(document).on({
  'pjax:click': function() {
    content.removeClass('fadeIn').addClass('fadeOut');
    NProgress.start();
  },
  'pjax:start': function() {
    content.css({'opacity':0});
  },
  'pjax:end': function() {
    NProgress.done();
    container.scrollTop(0);
    content.css({'opacity':1}).removeClass('fadeOut').addClass('fadeIn');
    afterPjax();
  }
});

// Re-run scripts for post content after pjax
function afterPjax() {
  // Open links in new tab
  $('#post__content a').attr('target','_blank');

  // Generate post TOC for h1 h2 and h3
  var toc = $('#post__toc-ul');
  // Empty TOC and generate an entry for h1
  toc.empty().append('
' + $('#post__title').text() + '
');

  // Generate entries for h2 and h3
  $('#post__content').children('h2,h3').each(function() {
    // Generate random ID for each heading
    $(this).attr('id', function() {
      var ID = "",
          alphabet = "abcdefghijklmnopqrstuvwxyz";

      for(var i=0; i < 5; i++) {
        ID += alphabet.charAt(Math.floor(Math.random() * alphabet.length));
      }
      return ID;
    });

    if ($(this).prop("tagName") == 'H2') {
      toc.append('
' + $(this).text() + '
');
    } else {
      toc.append('
' + $(this).text() + '
');
    }
  });

  // Smooth scrolling
  $('.js-anchor-link').on('click', function() {
    var target = $(this.hash);
    container.animate({scrollTop: target.offset().top + container.scrollTop() - 70}, 500, function() {
      target.addClass('flash').delay(700).queue(function() {
        $(this).removeClass('flash').dequeue();
      });
    });
  });

  // Lazy Loading Disqus
  // http://jsfiddle.net/dragoncrew/SHGwe/1/
  var ds_loaded = false,
      top = $('#disqus_thread').offset().top;
  window.disqus_shortname = $('#disqus_thread').attr('name');

  function check() {
    if ( !ds_loaded && container.scrollTop() + container.height() > top ) {
      $.ajax({
        type: 'GET',
        url: '//' + disqus_shortname + '.disqus.com/embed.js',
        dataType: 'script',
        cache: true
      });
      ds_loaded = true;
    }
  }check();
  container.scroll(check);
}
afterPjax();
<|endoftext|>