<commit_before>describe("PostMessageCourier Sanity Tests with iFrame creation from the outside", function () {
    var courierLocal;
    var msgChannel;
    var evChannel;
    var ignorePorts = ["80", "443", "0", ":"];
    var protocol = location.protocol + "//";
    var hostname = location.hostname === "localhost" ? "127.0.0.1" : "localhost";
    var port = (-1 === ignorePorts.indexOf(location.port.toString())) ? ":" + location.port.replace(":", "") : "";
    var split = location.href.split("/");
    var base = split.splice(3, split.length - 4).join("/");
    var url = protocol + hostname + port + "/" + base + "/courier_test_frame.html";
    var buster = 0;
    var withChannel = window.PHANTOMJS ? false : void 0;
    var sandbox;
    var PostMessageCourier;

    if (false === withChannel) {
        url += "?lpPMCPolyfill=true";
    }

    before(function (done) {
        if ("undefined" !== typeof define) {
            require(["Chronos.PostMessageCourier"], function (lpPostMessageCourier) {
                PostMessageCourier = lpPostMessageCourier;
                done();
            });
        } else {
            // Do not use new deliberately to test if component is adding it
            require("../../src/courier/PostMessageCourier")(done);
        }
    });
    beforeEach("Init Courier & iFrame", function (done) {
        // create a sandbox
        sandbox = sinon.sandbox.create();

        var completed = false;
        var target = {
            url: url + (0 < url.indexOf("?") ? "&" : "?") + "_d=" + buster++,
            callback: function() {
                courierLocal = new PostMessageCourier({
                    target: frame,
                    targetOrigin: protocol + hostname + port,
                    channel: withChannel
                });
                msgChannel = courierLocal.getMessageChannel();
                evChannel = courierLocal.getEventChannel();

                if (!completed) {
                    completed = true;
                    done();
                }
            }
        };
        var frame = createIFrame({ target: target });
    });

    afterEach("Dispose iFrame", function (done) {
        sandbox.restore();
        courierLocal.dispose();
        courierLocal = null;

        var frame = document.getElementsByTagName("iframe");
        for (var i = 0; frame.length; i++) {
            // Always 0 since we remove it every time
            frame.item(0).parentNode.removeChild(frame.item(0));
        }

        done();
    });

    describe("check trigger and bind works", function () {
        it("should get event back upon triggering", function (done) {
            var original = 1;
            courierLocal.bind({
                appName: "frame",
                eventName: "got_it",
                func: eventHandler
            });

            function eventHandler(data) {
                expect(data).to.be.defined;
                expect(data).to.equal(original * 2);
                done();
            }

            courierLocal.trigger({
                appName: "host",
                eventName: "multiply",
                data: original
            });

            var hasFired = courierLocal.getEventChannel().hasFiredEvents("host", "multiply");
            expect(hasFired.length).to.equal(1);

        });
    });

    describe("check command and comply works", function () {
        it("should get command back upon complying", function (done) {
            var original = {
                num: 3
            };
            var id = courierLocal.comply({
                appName: "frame",
                cmdName: "expect",
                func: complyHandler
            });

            expect(id).to.be.defined;

            function complyHandler(data) {
                expect(data).to.be.defined;
                expect(data.num).to.be.defined;
                expect(data.num).to.equal(original.num * original.num);
                done();
            }

            var res = courierLocal.command({
                appName: "host",
                cmdName: "square",
                data: original
            });

            expect(res).to.be.undefined;
        });
    });

    describe("check command and comply works with callback", function () {
        it("should get command back upon complying", function (done) {
            var complyHandler = sandbox.spy(function(data) {
                expect(data).to.be.defined;
                expect(data.num).to.be.defined;
                expect(data.num).to.equal(original.num * original.num);

                return data.num;
            });
            var callback = function(err) {
                expect(err).to.be.null;
                expect(complyHandler.calledOnce).to.be.true;
                done();
            };
            var original = {
                num: 3
            };
            var id = courierLocal.comply({
                appName: "frame",
                cmdName: "expect",
                func: complyHandler
            });

            expect(id).to.be.defined;

            var res = courierLocal.command({
                appName: "host",
                cmdName: "square",
                data: original
            }, callback);

            expect(res).to.be.undefined;
        });
    });

    describe("check request and reply works", function () {
        it("should get request back upon replying", function (done) {
            var original = {
                num: 4
            };
            var id = courierLocal.reply({
                appName: "frame",
                reqName: "askBack",
                func: replyHandler
            });

            expect(id).to.be.defined;

            function replyHandler(data) {
                expect(data).to.be.defined;
                expect(data.num).to.be.defined;
                expect(data.num).to.equal(original.num / original.num);
                done();
            }

            var res = courierLocal.request({
                appName: "host",
                reqName: "divide",
                data: original
            });

            expect(res).to.be.undefined;
        });
    });

    describe("check request and reply works with callback", function () {
        it("should get request back upon replying", function (done) {
            var replyHandler = sandbox.spy(function(data) {
                expect(data).to.be.defined;
                expect(data.num).to.be.defined;
                expect(data.num).to.equal(original.num / original.num);

                return data.num;
            });
            var callback = function(err) {
                expect(err).to.be.null;
                expect(replyHandler.calledOnce).to.be.true;
                done();
            };
            var original = {
                num: 4
            };

            var id = courierLocal.reply({
                appName: "frame",
                reqName: "askBack",
                func: replyHandler
            });

            expect(id).to.be.defined;

            var res = courierLocal.request({
                appName: "host",
                reqName: "divide",
                data: original
            }, callback);

            expect(res).to.be.undefined;
        });
    });

    describe("check can run request on iframe and get async response (based on promise which will be resolved) with the value sent", function () {

        it("run request on iframe and get async response (based on promise which will be resolved) with the value sent", function (done) {
            var request = courierLocal.request({
                appName: "host",
                reqName: "Async Ma Shlomha?",
                data: {
                    text: "TODA!"
                }
            }, function(err, data) {
                expect(err).to.be.null;
                expect(data).to.be.equal("TODA!");
                done();
            });

            expect(request).to.be.undefined;
        });
    });

    describe("check can run request on iframe and timeout the async response (based on promise which will be resolved) with the value sent", function () {

        it("run request on iframe and timeout the async response (based on promise which will be resolved) with the value sent", function (done) {
            var request = courierLocal.request({
                appName: "host",
                reqName: "Async Ma Shlomha?",
                data: {
                    text: "TODA!"
                }
            }, function(err, data) {
                expect(err).to.be.defined;
                expect(err.message).to.be.equal("Callback: Operation Timeout!");
                expect(data).to.be.undefined;
                done();
            }, 500);

            expect(request).to.be.undefined;
        });
    });

    describe("check can run request on iframe and get async response after an iframe redirect", function () {

        it("run request on iframe and get async response after an iframe redirect", function (done) {
            var request = courierLocal.request({
                appName: "host",
                reqName: "Redirect"
            }, function (err, data) {
                expect(err).to.be.null;
                expect(data).to.be.equal("Going to Redirect...");

                setTimeout(function() {
                    var request2 = courierLocal.request({
                        appName: "host",
                        reqName: "Async Ma Shlomha?",
                        data: {
                            text: "TODA!"
                        }
                    }, function (err, data) {
                        expect(err).to.be.null;
                        expect(data).to.be.equal("TODA!");
                        done();
                    });
                }, 300);
            });

            expect(request).to.be.undefined;
        });
    });
});

function addElementEventListener(element, event, callback) {
    if ("undefined" !== typeof element.addEventListener) {
        element.addEventListener(event, callback, false);
    }
    else {
        element.attachEvent("on" + event, callback);
    }
}

function createIFrame(options) {
    var frame = document.createElement("IFRAME");

    frame.setAttribute("id", "MyId");
    frame.setAttribute("name", "MyName");
    frame.setAttribute("tabindex", "-1");       // To prevent it getting focus when tabbing through the page
    frame.setAttribute("aria-hidden", "true");  // To prevent it being picked up by screen-readers
    frame.setAttribute("title", "");            // Adding an empty title at AT&Ts insistence
    frame.setAttribute("role", "presentation"); // Adding a presentation role http://yahoodevelopers.tumblr.com/post/59489724815/easy-fixes-to-common-accessibility-problems
    frame.setAttribute("allowTransparency", "true");

    if (options && options.target && options.target.style) {
        for (var attr in options.target.style) {
            if (options.target.style.hasOwnProperty(attr)) {
                frame.style[attr] = options.target.style[attr];
            }
        }
    }
    else {
        frame.style.width = "0px";
        frame.style.height = "0px";
        frame.style.position = "absolute";
        frame.style.top = "-1000px";
        frame.style.left = "-1000px";
    }

    document.body.appendChild(frame);

    addElementEventListener(frame, "load", function() {
        if (options && options.target && options.target.callback) {
            options.target.callback(options.target.context);
        }
    }.bind(this));

    document.body.appendChild(frame);

    if (options && options.target && options.target.url) {
        var src = options.target.url + (0 < options.target.url.indexOf("?") ? "&bust=" : "?bust=");
        src += (new Date()).getTime();
        src += ("&lpHost=" + document.location.protocol + "//" + document.location.host);
        frame.setAttribute("src", src);
    }

    return frame;
}
<commit_msg>remove double append in external iframe courier tests<commit_after>describe("PostMessageCourier Sanity Tests with iFrame creation from the outside", function () {
    var courierLocal;
    var msgChannel;
    var evChannel;
    var ignorePorts = ["80", "443", "0", ":"];
    var protocol = location.protocol + "//";
    var hostname = location.hostname === "localhost" ? "127.0.0.1" : "localhost";
    var port = (-1 === ignorePorts.indexOf(location.port.toString())) ? ":" + location.port.replace(":", "") : "";
    var split = location.href.split("/");
    var base = split.splice(3, split.length - 4).join("/");
    var url = protocol + hostname + port + "/" + base + "/courier_test_frame.html";
    var buster = 0;
    var withChannel = window.PHANTOMJS ? false : void 0;
    var sandbox;
    var PostMessageCourier;

    if (false === withChannel) {
        url += "?lpPMCPolyfill=true";
    }

    before(function (done) {
        if ("undefined" !== typeof define) {
            require(["Chronos.PostMessageCourier"], function (lpPostMessageCourier) {
                PostMessageCourier = lpPostMessageCourier;
                done();
            });
        } else {
            // Do not use new deliberately to test if component is adding it
            require("../../src/courier/PostMessageCourier")(done);
        }
    });
    beforeEach("Init Courier & iFrame", function (done) {
        // create a sandbox
        sandbox = sinon.sandbox.create();

        var completed = false;
        var target = {
            url: url + (0 < url.indexOf("?") ? "&" : "?") + "_d=" + buster++,
            callback: function() {
                courierLocal = new PostMessageCourier({
                    target: frame,
                    targetOrigin: protocol + hostname + port,
                    channel: withChannel
                });
                msgChannel = courierLocal.getMessageChannel();
                evChannel = courierLocal.getEventChannel();

                if (!completed) {
                    completed = true;
                    done();
                }
            }
        };
        var frame = createIFrame({ target: target });
    });

    afterEach("Dispose iFrame", function (done) {
        sandbox.restore();
        courierLocal.dispose();
        courierLocal = null;

        var frame = document.getElementsByTagName("iframe");
        for (var i = 0; frame.length; i++) {
            // Always 0 since we remove it every time
            frame.item(0).parentNode.removeChild(frame.item(0));
        }

        done();
    });

    describe("check trigger and bind works", function () {
        it("should get event back upon triggering", function (done) {
            var original = 1;
            courierLocal.bind({
                appName: "frame",
                eventName: "got_it",
                func: eventHandler
            });

            function eventHandler(data) {
                expect(data).to.be.defined;
                expect(data).to.equal(original * 2);
                done();
            }

            courierLocal.trigger({
                appName: "host",
                eventName: "multiply",
                data: original
            });

            var hasFired = courierLocal.getEventChannel().hasFiredEvents("host", "multiply");
            expect(hasFired.length).to.equal(1);

        });
    });

    describe("check command and comply works", function () {
        it("should get command back upon complying", function (done) {
            var original = {
                num: 3
            };
            var id = courierLocal.comply({
                appName: "frame",
                cmdName: "expect",
                func: complyHandler
            });

            expect(id).to.be.defined;

            function complyHandler(data) {
                expect(data).to.be.defined;
                expect(data.num).to.be.defined;
                expect(data.num).to.equal(original.num * original.num);
                done();
            }

            var res = courierLocal.command({
                appName: "host",
                cmdName: "square",
                data: original
            });

            expect(res).to.be.undefined;
        });
    });

    describe("check command and comply works with callback", function () {
        it("should get command back upon complying", function (done) {
            var complyHandler = sandbox.spy(function(data) {
                expect(data).to.be.defined;
                expect(data.num).to.be.defined;
                expect(data.num).to.equal(original.num * original.num);

                return data.num;
            });
            var callback = function(err) {
                expect(err).to.be.null;
                expect(complyHandler.calledOnce).to.be.true;
                done();
            };
            var original = {
                num: 3
            };
            var id = courierLocal.comply({
                appName: "frame",
                cmdName: "expect",
                func: complyHandler
            });

            expect(id).to.be.defined;

            var res = courierLocal.command({
                appName: "host",
                cmdName: "square",
                data: original
            }, callback);

            expect(res).to.be.undefined;
        });
    });

    describe("check request and reply works", function () {
        it("should get request back upon replying", function (done) {
            var original = {
                num: 4
            };
            var id = courierLocal.reply({
                appName: "frame",
                reqName: "askBack",
                func: replyHandler
            });

            expect(id).to.be.defined;

            function replyHandler(data) {
                expect(data).to.be.defined;
                expect(data.num).to.be.defined;
                expect(data.num).to.equal(original.num / original.num);
                done();
            }

            var res = courierLocal.request({
                appName: "host",
                reqName: "divide",
                data: original
            });

            expect(res).to.be.undefined;
        });
    });

    describe("check request and reply works with callback", function () {
        it("should get request back upon replying", function (done) {
            var replyHandler = sandbox.spy(function(data) {
                expect(data).to.be.defined;
                expect(data.num).to.be.defined;
                expect(data.num).to.equal(original.num / original.num);

                return data.num;
            });
            var callback = function(err) {
                expect(err).to.be.null;
                expect(replyHandler.calledOnce).to.be.true;
                done();
            };
            var original = {
                num: 4
            };

            var id = courierLocal.reply({
                appName: "frame",
                reqName: "askBack",
                func: replyHandler
            });

            expect(id).to.be.defined;

            var res = courierLocal.request({
                appName: "host",
                reqName: "divide",
                data: original
            }, callback);

            expect(res).to.be.undefined;
        });
    });

    describe("check can run request on iframe and get async response (based on promise which will be resolved) with the value sent", function () {

        it("run request on iframe and get async response (based on promise which will be resolved) with the value sent", function (done) {
            var request = courierLocal.request({
                appName: "host",
                reqName: "Async Ma Shlomha?",
                data: {
                    text: "TODA!"
                }
            }, function(err, data) {
                expect(err).to.be.null;
                expect(data).to.be.equal("TODA!");
                done();
            });

            expect(request).to.be.undefined;
        });
    });

    describe("check can run request on iframe and timeout the async response (based on promise which will be resolved) with the value sent", function () {

        it("run request on iframe and timeout the async response (based on promise which will be resolved) with the value sent", function (done) {
            var request = courierLocal.request({
                appName: "host",
                reqName: "Async Ma Shlomha?",
                data: {
                    text: "TODA!"
                }
            }, function(err, data) {
                expect(err).to.be.defined;
                expect(err.message).to.be.equal("Callback: Operation Timeout!");
                expect(data).to.be.undefined;
                done();
            }, 500);

            expect(request).to.be.undefined;
        });
    });

    describe("check can run request on iframe and get async response after an iframe redirect", function () {

        it("run request on iframe and get async response after an iframe redirect", function (done) {
            var request = courierLocal.request({
                appName: "host",
                reqName: "Redirect"
            }, function (err, data) {
                expect(err).to.be.null;
                expect(data).to.be.equal("Going to Redirect...");

                setTimeout(function() {
                    var request2 = courierLocal.request({
                        appName: "host",
                        reqName: "Async Ma Shlomha?",
                        data: {
                            text: "TODA!"
                        }
                    }, function (err, data) {
                        expect(err).to.be.null;
                        expect(data).to.be.equal("TODA!");
                        done();
                    });
                }, 300);
            });

            expect(request).to.be.undefined;
        });
    });
});

function addElementEventListener(element, event, callback) {
    if ("undefined" !== typeof element.addEventListener) {
        element.addEventListener(event, callback, false);
    }
    else {
        element.attachEvent("on" + event, callback);
    }
}

function createIFrame(options) {
    var frame = document.createElement("IFRAME");

    frame.setAttribute("id", "MyId");
    frame.setAttribute("name", "MyName");
    frame.setAttribute("tabindex", "-1");       // To prevent it getting focus when tabbing through the page
    frame.setAttribute("aria-hidden", "true");  // To prevent it being picked up by screen-readers
    frame.setAttribute("title", "");            // Adding an empty title at AT&Ts insistence
    frame.setAttribute("role", "presentation"); // Adding a presentation role http://yahoodevelopers.tumblr.com/post/59489724815/easy-fixes-to-common-accessibility-problems
    frame.setAttribute("allowTransparency", "true");

    if (options && options.target && options.target.style) {
        for (var attr in options.target.style) {
            if (options.target.style.hasOwnProperty(attr)) {
                frame.style[attr] = options.target.style[attr];
            }
        }
    }
    else {
        frame.style.width = "0px";
        frame.style.height = "0px";
        frame.style.position = "absolute";
        frame.style.top = "-1000px";
        frame.style.left = "-1000px";
    }

    document.body.appendChild(frame);

    addElementEventListener(frame, "load", function() {
        if (options && options.target && options.target.callback) {
            options.target.callback(options.target.context);
        }
    }.bind(this));

    if (options && options.target && options.target.url) {
        var src = options.target.url + (0 < options.target.url.indexOf("?") ? "&bust=" : "?bust=");
        src += (new Date()).getTime();
        src += ("&lpHost=" + document.location.protocol + "//" + document.location.host);
        frame.setAttribute("src", src);
    }

    return frame;
}
<|endoftext|>


<commit_before>import React from 'react';
import Masonry from 'react-masonry-component';

import SmallHeader from './SmallHeader';

import AdvisorsStore from '../stores/AdvisorsStore';
import DetailsStore from '../stores/DetailsStore';
import DetailsActions from '../actions/DetailsActions';

let masonryOptions = {
    transitionDuration: 0,
    columnWidth: '.masonrySizer',
    percentPosition: true,
    gutter: 16
};
var overlayColor = 'rgba(39, 58, 65, 0.75)';

export default class AdvisorDetails extends React.Component {
    constructor(props) {
        super(props);
        this.state = {};
        this.onAdvisorsChanged = this.onAdvisorsChanged.bind(this);
        this.onDetailsChanged = this.onDetailsChanged.bind(this);
    }

    componentDidMount() {
        this.onAdvisorsChanged(AdvisorsStore.getState());
        this.onDetailsChanged(DetailsStore.getState());

        AdvisorsStore.listen(this.onAdvisorsChanged);
        DetailsStore.listen(this.onDetailsChanged);
        DetailsActions.fetchAdvisor(this.props.params.id);
    }

    componentWillUnmount() {
        AdvisorsStore.unlisten(this.onAdvisorsChanged);
        DetailsStore.unlisten(this.onDetailsChanged);
    }

    componentDidUpdate(prevProps) {
        if (prevProps.params.id !== this.props.params.id) {
            this.onAdvisorsChanged(AdvisorsStore.getState());
            DetailsActions.fetchAdvisor(this.props.params.id);
        }
    }

    onAdvisorsChanged(advisors) {
        if (advisors && advisors.summaries) {
            let summary = advisors.summaries[this.props.params.id];
            if (summary) {
                this.setState({
                    summary: summary
                });
            }
        }
    }

    onDetailsChanged(store) {
        if (store) {
            if (store.errorMessage) {
                this.setState({
                    errorMessage: store.errorMessage
                });
            }
            else if (store.details) {
                let details = store.details[this.props.params.id];
                if (details) {
                    this.setState({
                        details: details
                    });
                }
            }
        }
    }

    renderIcon(summary) {
        if (summary.icon) {
            let iconStyle = {
                backgroundImage: `url('${summary.icon}')`
            };
            return (

            );
        }
        return null;
    }

    renderHeroImage() {
        let summary = this.state.summary || {
            name: null,
            type: null,
            image: null,
            icon: null
        };

        let heroImageStyle = {
            background: summary.image
                ? `linear-gradient(${overlayColor}, ${overlayColor}), url('${summary.image}')`
                : overlayColor
        };
        let icon = this.renderIcon(summary);
        return (

                <SmallHeader />

                        {icon}

{summary.type}

{summary.name}

        );
    }

    renderDetails() {
        if (this.state.errorMessage) {
            return
{this.state.errorMessage}
;
        }
        if (!this.state.details) {
            return
Loading...
;
        }
        if (this.state.details.length > 0) {
            let childElements = this.state.details
                ? this.state.details.map((item, i) =>

{item.name}

)
                : null;
            return (
                <Masonry className="detailsMasonry"
                    options={masonryOptions}>

                    {childElements}
                </Masonry>
            );
        }
        else {
            return
We couldn't find any activity details.
;
        }
    }

    render() {
        let hero = this.renderHeroImage();
        let details = this.renderDetails();

        return (

                {hero}
                {details}

        );
    };
}<commit_msg>Minor refactoring.<commit_after>import React from 'react';
import Masonry from 'react-masonry-component';

import SmallHeader from './SmallHeader';

import AdvisorsStore from '../stores/AdvisorsStore';
import DetailsStore from '../stores/DetailsStore';
import DetailsActions from '../actions/DetailsActions';

let masonryOptions = {
    transitionDuration: 0,
    columnWidth: '.masonrySizer',
    percentPosition: true,
    gutter: 16
};
var overlayColor = 'rgba(39, 58, 65, 0.75)';

export default class AdvisorDetails extends React.Component {
    constructor(props) {
        super(props);
        this.state = {};
        this.onAdvisorsChanged = this.onAdvisorsChanged.bind(this);
        this.onDetailsChanged = this.onDetailsChanged.bind(this);
    }

    update() {
        this.onAdvisorsChanged(AdvisorsStore.getState());
        this.onDetailsChanged(DetailsStore.getState());
        if (!this.state.details) {
            DetailsActions.fetchAdvisor(this.props.params.id);
        }
    }

    componentDidMount() {
        AdvisorsStore.listen(this.onAdvisorsChanged);
        DetailsStore.listen(this.onDetailsChanged);
        this.update();
    }

    componentWillUnmount() {
        AdvisorsStore.unlisten(this.onAdvisorsChanged);
        DetailsStore.unlisten(this.onDetailsChanged);
    }

    componentDidUpdate(prevProps) {
        if (prevProps.params.id !== this.props.params.id) {
            this.update();
        }
    }

    onAdvisorsChanged(advisors) {
        if (advisors && advisors.summaries) {
            let summary = advisors.summaries[this.props.params.id];
            if (summary) {
                this.setState({
                    summary: summary
                });
            }
        }
    }

    onDetailsChanged(store) {
        if (store) {
            if (store.errorMessage) {
                this.setState({
                    errorMessage: store.errorMessage
                });
            }
            else if (store.details) {
                let details = store.details[this.props.params.id];
                if (details) {
                    this.setState({
                        details: details
                    });
                }
            }
        }
    }

    renderIcon(summary) {
        if (summary.icon) {
            let iconStyle = {
                backgroundImage: `url('${summary.icon}')`
            };
            return (

            );
        }
        return null;
    }

    renderHeroImage() {
        let summary = this.state.summary || {
            name: null,
            type: null,
            image: null,
            icon: null
        };

        let heroImageStyle = {
            background: summary.image
                ? `linear-gradient(${overlayColor}, ${overlayColor}), url('${summary.image}')`
                : overlayColor
        };
        let icon = this.renderIcon(summary);
        return (

                <SmallHeader />

                        {icon}

{summary.type}

{summary.name}

        );
    }

    renderDetails() {
        if (this.state.errorMessage) {
            return
{this.state.errorMessage}
;
        }
        if (!this.state.details) {
            return
Loading...
;
        }
        if (this.state.details.length > 0) {
            let childElements = this.state.details
                ? this.state.details.map((item, i) =>

{item.name}

)
                : null;
            return (
                <Masonry className="detailsMasonry"
                    options={masonryOptions}>

                    {childElements}
                </Masonry>
            );
        }
        else {
            return
We couldn't find any activity details.
;
        }
    }

    render() {
        let hero = this.renderHeroImage();
        let details = this.renderDetails();

        return (

                {hero}
                {details}

        );
    };
}<|endoftext|>


<commit_before>'use strict'
var remixLib = require('remix-lib')
var SourceMappingDecoder = remixLib.SourceMappingDecoder
var AstWalker = remixLib.AstWalker
var EventManager = remixLib.EventManager

/*
  trigger contextChanged(nodes)
*/
class ContextualListener {
  constructor (api, events) {
    this.event = new EventManager()
    this._api = api
    this._index = {
      Declarations: {},
      FlatReferences: {}
    }
    this._activeHighlights = []

    events.compiler.register('compilationFinished', (success, data, source) => {
      this._stopHighlighting()
      this._index = {
        Declarations: {},
        FlatReferences: {}
      }
      if (success) {
        this._buildIndex(data, source)
      }
    })

    events.editor.register('contentChanged', () => { this._stopHighlighting() })

    this.sourceMappingDecoder = new SourceMappingDecoder()
    this.astWalker = new AstWalker()
    setInterval(() => {
      this._highlightItems(api.getCursorPosition(), api.getCompilationResult(), api.getCurrentFile())
    }, 1000)
  }

  getActiveHighlights () {
    return [...this._activeHighlights]
  }

  declarationOf (node) {
    if (node.attributes && node.attributes.referencedDeclaration) {
      return this._index['FlatReferences'][node.attributes.referencedDeclaration]
    }
    return null
  }

  referencesOf (node) {
    return this._index['Declarations'][node.id]
  }

  _highlightItems (cursorPosition, compilationResult, file) {
    if (this.currentPosition === cursorPosition) return
    if (this.currentFile !== file) {
      this.currentFile = file
      this.currentPosition = cursorPosition
      return
    }
    this._stopHighlighting()
    this.currentPosition = cursorPosition
    this.currentFile = file
    if (compilationResult && compilationResult.data && compilationResult.data.sources[file]) {
      var nodes = this.sourceMappingDecoder.nodesAtPosition(null, cursorPosition, compilationResult.data.sources[file])
      if (nodes && nodes.length && nodes[nodes.length - 1]) {
        this._highlightExpressions(nodes[nodes.length - 1], compilationResult)
      }
      this.event.trigger('contextChanged', [nodes])
    }
  }

  _buildIndex (compilationResult, source) {
    if (compilationResult && compilationResult.sources) {
      var self = this
      var callback = {}
      callback['*'] = function (node) {
        if (node && node.attributes && node.attributes.referencedDeclaration) {
          if (!self._index['Declarations'][node.attributes.referencedDeclaration]) {
            self._index['Declarations'][node.attributes.referencedDeclaration] = []
          }
          self._index['Declarations'][node.attributes.referencedDeclaration].push(node)
        }
        self._index['FlatReferences'][node.id] = node
        return true
      }
      for (var s in compilationResult.sources) {
        this.astWalker.walk(compilationResult.sources[s].legacyAST, callback)
      }
    }
  }

  _getGasEstimation (results) {
    this.results = results
    this.contractName = Object.keys(results.data.contracts[results.source.target])[0]
    this.target = results.data.contracts[results.source.target]
    this.functions = Object.keys(this.target[this.contractName].evm.gasEstimates.external)
    this.creationCost = this.target[this.contractName].evm.gasEstimates.creation.totalCost
  }

  gasEstimation (node) {
    if (node.name === 'FunctionDefinition') {
      var estimation
      if (!node.attributes.isConstructor) {
        var functionName = node.attributes.name
        var fn
        for (var x in this.functions) {
          if (!!~this.functions[x].indexOf(functionName)) {
            fn = this.functions[x]
            break
          }
        }
        estimation = this.target[this.contractName].evm.gasEstimates.external[fn]
      } else {
        estimation = this.creationCost
      }
    }
    return estimation
  }

  _highlight (node, compilationResult) {
    if (!node) return
    var position = this.sourceMappingDecoder.decode(node.src)
    var eventId = this._api.highlight(position, node)
    if (eventId) {
      this._activeHighlights.push({ eventId, position, fileTarget: this._api.getSourceName(position.file), nodeId: node.id })
    }
  }

  _highlightExpressions (node, compilationResult) {
    var self = this
    function highlights (id) {
      if (self._index['Declarations'] && self._index['Declarations'][id]) {
        var refs = self._index['Declarations'][id]
        for (var ref in refs) {
          var node = refs[ref]
          self._highlight(node, compilationResult)
        }
      }
    }
    if (node.attributes && node.attributes.referencedDeclaration) {
      highlights(node.attributes.referencedDeclaration)
      var current = this._index['FlatReferences'][node.attributes.referencedDeclaration]
      this._highlight(current, compilationResult)
    } else {
      highlights(node.id)
      this._highlight(node, compilationResult)
    }
    this._getGasEstimation(compilationResult)
  }

  _stopHighlighting () {
    for (var event in this._activeHighlights) {
      this._api.stopHighlighting(this._activeHighlights[event])
    }
    this._activeHighlights = []
  }
}

module.exports = ContextualListener
<commit_msg>Include internal functions<commit_after>'use strict'
var remixLib = require('remix-lib')
var SourceMappingDecoder = remixLib.SourceMappingDecoder
var AstWalker = remixLib.AstWalker
var EventManager = remixLib.EventManager

/*
  trigger contextChanged(nodes)
*/
class ContextualListener {
  constructor (api, events) {
    this.event = new EventManager()
    this._api = api
    this._index = {
      Declarations: {},
      FlatReferences: {}
    }
    this._activeHighlights = []

    events.compiler.register('compilationFinished', (success, data, source) => {
      this._stopHighlighting()
      this._index = {
        Declarations: {},
        FlatReferences: {}
      }
      if (success) {
        this._buildIndex(data, source)
      }
    })

    events.editor.register('contentChanged', () => { this._stopHighlighting() })

    this.sourceMappingDecoder = new SourceMappingDecoder()
    this.astWalker = new AstWalker()
    setInterval(() => {
      this._highlightItems(api.getCursorPosition(), api.getCompilationResult(), api.getCurrentFile())
    }, 1000)
  }

  getActiveHighlights () {
    return [...this._activeHighlights]
  }

  declarationOf (node) {
    if (node.attributes && node.attributes.referencedDeclaration) {
      return this._index['FlatReferences'][node.attributes.referencedDeclaration]
    }
    return null
  }

  referencesOf (node) {
    return this._index['Declarations'][node.id]
  }

  _highlightItems (cursorPosition, compilationResult, file) {
    if (this.currentPosition === cursorPosition) return
    if (this.currentFile !== file) {
      this.currentFile = file
      this.currentPosition = cursorPosition
      return
    }
    this._stopHighlighting()
    this.currentPosition = cursorPosition
    this.currentFile = file
    if (compilationResult && compilationResult.data && compilationResult.data.sources[file]) {
      var nodes = this.sourceMappingDecoder.nodesAtPosition(null, cursorPosition, compilationResult.data.sources[file])
      if (nodes && nodes.length && nodes[nodes.length - 1]) {
        this._highlightExpressions(nodes[nodes.length - 1], compilationResult)
      }
      this.event.trigger('contextChanged', [nodes])
    }
  }

  _buildIndex (compilationResult, source) {
    if (compilationResult && compilationResult.sources) {
      var self = this
      var callback = {}
      callback['*'] = function (node) {
        if (node && node.attributes && node.attributes.referencedDeclaration) {
          if (!self._index['Declarations'][node.attributes.referencedDeclaration]) {
            self._index['Declarations'][node.attributes.referencedDeclaration] = []
          }
          self._index['Declarations'][node.attributes.referencedDeclaration].push(node)
        }
        self._index['FlatReferences'][node.id] = node
        return true
      }
      for (var s in compilationResult.sources) {
        this.astWalker.walk(compilationResult.sources[s].legacyAST, callback)
      }
    }
  }

  _getGasEstimation (results) {
    this.contractName = Object.keys(results.data.contracts[results.source.target])[0]
    this.target = results.data.contracts[results.source.target]
    this.contract = this.target[this.contractName]
    this.estimationObj = this.contract.evm.gasEstimates
    if (this.estimationObj.external) this.externalFunctions = Object.keys(this.estimationObj.external)
    if (this.estimationObj.internal) this.internalFunctions = Object.keys(this.estimationObj.internal)
    this.creationCost = this.estimationObj.creation.totalCost
  }

  gasEstimation (node) {
    if (node.name === 'FunctionDefinition') {
      if (!node.attributes.isConstructor) {
        var functionName = node.attributes.name
        if (this.externalFunctions) {
          return this.estimationObj.external[this._getFn(this.externalFunctions, functionName)]
        }
        if (this.internalFunctions) {
          return this.estimationObj.internal[this._getFn(this.internalFunctions, functionName)]
        }
      } else {
        return this.creationCost
      }
    }
  }

  _getFn (functions, name) {
    for (var x in functions) {
      if (!!~functions[x].indexOf(name)) {
        var fn = functions[x]
        break
      }
    }
    return fn
  }

  _highlight (node, compilationResult) {
    if (!node) return
    var position = this.sourceMappingDecoder.decode(node.src)
    var eventId = this._api.highlight(position, node)
    if (eventId) {
      this._activeHighlights.push({ eventId, position, fileTarget: this._api.getSourceName(position.file), nodeId: node.id })
    }
  }

  _highlightExpressions (node, compilationResult) {
    var self = this
    function highlights (id) {
      if (self._index['Declarations'] && self._index['Declarations'][id]) {
        var refs = self._index['Declarations'][id]
        for (var ref in refs) {
          var node = refs[ref]
          self._highlight(node, compilationResult)
        }
      }
    }
    if (node.attributes && node.attributes.referencedDeclaration) {
      highlights(node.attributes.referencedDeclaration)
      var current = this._index['FlatReferences'][node.attributes.referencedDeclaration]
      this._highlight(current, compilationResult)
    } else {
      highlights(node.id)
      this._highlight(node, compilationResult)
    }
    this._getGasEstimation(compilationResult)
  }

  _stopHighlighting () {
    for (var event in this._activeHighlights) {
      this._api.stopHighlighting(this._activeHighlights[event])
    }
    this._activeHighlights = []
  }
}

module.exports = ContextualListener
<|endoftext|>


<commit_before>var app = app || {};

$(function () {
	'use strict';

	app.CodemagicView = Backbone.View.extend({
		that: this,
		el: '#container',
		events : {
			'click #update': 'updateResults',
			'click #prettify': 'prettify',
			'click #fullscreen': 'toggleFullscreen',
			'click .editor-fullscreen-toggle': 'editorFullscreen',
			'mousedown .resizer': 'resizeInitialize',
			'mouseup': 'resizeFinalize',
			'mousemove': 'resizeRefresh',
			'click .editor-options-toggle': 'toggleTargetedEditorOptions',
			'change .codeChoice': 'toggleSelectedEditorOptions',
			'click .editor-toggle': 'toggleEditorState'
		},
		prettify: function () {
			// parameterize these depending on the editor's settings
			// https://github.com/einars/js-beautify#options
			if ($('#markupChoice').val() === 'HTML') {
				app.editors.htmlSession.setValue(html_beautify(app.editors.htmlSession.getValue(), {
					'brace_style': 'collapse',
					'indent_size': 1,
					'indent_char': '\t',
					'preserve-newlines': true,
					'max-preserve-newlines': 1,
					'wrap-line-length': 0,
					'unformatted': [],
					'indent-inner-html': true
				}));

				app.editors.htmlSession.selection.moveCursorFileStart();
			}

			if ($('#styleChoice').val() === 'CSS') {
				app.editors.cssSession.setValue(css_beautify(app.editors.cssSession.getValue(), {
					'brace_style': 'collapse',
					'indent_size': 1,
					'indent_char': '\t',
					'preserve-newlines': true,
					'max-preserve-newlines': 1,
					'wrap-line-length': 0,
					'unformatted': []
				}));

				app.editors.cssSession.selection.moveCursorFileStart();
			}

			if ($('#scriptChoice').val() === 'JavaScript') {
				app.editors.jsSession.setValue(js_beautify(app.editors.jsSession.getValue(), {
					'indent_size': 1,
					'indent_char': '\t',
					'preserve_newlines': true,
					'jslint_happy': true,
					'brace_style': 'collapse',
					'keep_array_indentation': false,
					'keep_function_indentation': false,
					'eval_code': false,
					'unescape_strings': false,
					'break_chained_methods': false
				}));

				app.editors.jsSession.selection.moveCursorFileStart();
			}
		},
		toggleEditorState: function (selector) {
			var target;
			if(selector instanceof Array){
				for (var i = 0; i < selector.length; i++) {
					$(selector[i]).toggleClass('enabled');
					$('#' + selector[i] + '-editor').closest('.editor-module').toggleClass('enabled');
					$('#' + selector[i] + '-editor-toggle').toggleClass('enabled');
				}
				target = false;
			}else if(typeof selector === 'object'){
				target = $(selector.currentTarget).prop('id').replace('-editor-toggle', '');
			} else {
				target = selector;
			}

			if(target !== false){
				$('#' + target + '-editor-toggle').toggleClass('enabled');
				$('#' + target + '-editor').closest('.editor-module').toggleClass('enabled');
				app.utils.toggleEditorState(target);
			}
		},
		toggleSelectedEditorOptions: function (e) {
			var value = $(e.currentTarget).val();
			var editorTarget = $(e.currentTarget).parent();
			var target = editorTarget.parent().find('.editor-option-title');
			$(target).html(value);
			this.toggleTargetedEditorOptions(e);
			app.utils.setEditorMode(editorTarget.prop('id').replace('-editor-options', ''), value.toLowerCase());
		},
		toggleTargetedEditorOptions: function (e) {
			if($(e.currentTarget).prop('tagName') === 'SELECT'){
				this.toggleEditorOptions($(e.currentTarget).parent());
			} else {
				this.toggleEditorOptions($(e.currentTarget).next());
			}
		},
		toggleEditorOptions: function (target) {
			$(target).toggleClass('enabled');
		},
		resizeInitialize: function (e) {
			app.session.resize = e.pageY;
			app.session.resizeTarget = app.session.resizeTarget || {};
			app.session.resizeTarget.id = $(e.currentTarget).prev().find('.editor');
			app.session.resizeTarget.id = app.session.resizeTarget.id.prop('id');
			app.session.resizeTarget.height = $('#' + app.session.resizeTarget.id).parent().height();
		},
		resizeRefresh: function (e) {
			if (app.session.resize) {
				$('#editors').css('padding-bottom', '30%');
				$('#' + app.session.resizeTarget.id).parent().height(app.session.resizeTarget.height + e.pageY - app.session.resize);
				app.utils.updateLayout(app.editors);
			}
		},
		resizeFinalize: function () {
			app.session.resize = false;
			if(typeof app.session.resizeTarget !== 'undefined'){
				if(typeof app.session.resizeTarget.height !== 'undefined'){
					app.session.resizeTarget.height = $('#' + app.session.resizeTarget.id).height();
				}
			}
			app.utils.updateLayout(app.editors);
			$('#editors').css('padding-bottom', '0');
		},
		toggleFullscreen: function () {
			if ($('#fullscreen').hasClass('enabled')) {
				$('#fullscreen').removeClass('enabled');
				$('#editors').show();
				$('#result').removeClass('fullscreen');
			} else {
				$('#fullscreen').addClass('enabled');
				$('#editors').hide();
				$('#result').addClass('fullscreen');
			}
		},
		editorFullscreen: function (e) {
			var target;
			if(e.container !== undefined){
				target = $(e.container).prop('id');
			}else{
				target = $(e.currentTarget).prop('id');
				target = target.replace('-editor-fullscreen-toggle', '') + '-editor';
			}
			target = document.getElementById(target);

			if (!document.fullscreenElement && !document.mozFullScreenElement && !document.webkitFullscreenElement) {
				if (target.requestFullscreen) {
					target.requestFullscreen();
				} else
				if (target.mozRequestFullScreen) {
					target.mozRequestFullScreen();
				} else
				if (target.webkitRequestFullscreen) {
					target.webkitRequestFullscreen(Element.ALLOW_KEYBOARD_INPUT);
				}
			}
			else {
				if (document.cancelFullScreen) {
					document.cancelFullScreen();
				}
				else if (document.mozCancelFullScreen) {
					document.mozCancelFullScreen();
				}
				else if (document.webkitCancelFullScreen) {
					document.webkitCancelFullScreen();
				}
			}
		},
		updateResults: function () {
			$('#console-editor').html('');

			var content = '';
			var style= '';
			var script= '';

			if ($('#markupChoice').val() === 'Markdown') {
				content = marked(app.editors.html.getValue());
			} else if ($('#markupChoice').val() === 'HAML') {
				app.utils.consoleLog('HAML support is not ready yet');
			} else if ($('#markupChoice').val() === 'Jade') {
				app.utils.consoleLog('Jade support is not ready yet');
			} else {
				content = app.editors.html.getValue();
			}

			if ($('#styleChoice').val() === 'Less') {
				var parser = new(less.Parser)();

				parser.parse(app.editors.css.getValue(), function (e, tree) {
					if (e) {
						// TODO: error handling in console
						$('#console-editor').append('> ' + e.message + '
');
						console.log(e);
					}
					style = tree.toCSS();
				});
			} else if ($('#styleChoice').val() === 'SASS' || $('#styleChoice').val() === 'SCSS') {
				app.utils.consoleLog('SASS/SCSS support is not ready yet');
			} else if ($('#styleChoice').val() === 'Stylus') {
				app.utils.consoleLog('Stylus support is not ready yet');
			} else {
				style = app.editors.css.getValue();
			}

			if ($('#styleChoice').val() === 'CoffeeScript') {
			} else {
				script = app.editors.js.getValue();
			}

			// WHY: breaking down logger into many pieces to prevent proxies from chocking by passing the 500 character limit
			var logger = '';

			var head = '<!doctype html>' + logger + '<meta charset="utf-8"><title>Title</title><meta name="description" content="Description"><meta name="author" content="Author">';
			var body = '' + content + '';

			var result = head + body;

			var iframeContainer = document.getElementById('result');

			$('#result iframe').remove();

			// TODO: write the lines below in JQuery (if performance and stability allow it)
			var iframe = document.createElement('iframe');

			iframeContainer.appendChild(iframe);

			var iDoc = iframe.contentDocument;
			iDoc.open();
			iDoc.write(result);
			iDoc.close();

			$('iframe').height(Math.max($('#editors').height(), $('iframe').height()));
		},
		initialize: function () {
			this.template = _.template($('#codemagic-template').html());
			this.render();

			// populate editors with example content
			app.editors.htmlSession.setValue('
Hello World
\n\n
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Consequuntur, nobis, inventore, cupiditate, itaque quae quas commodi reprehenderit expedita aliquid nulla vero voluptatem esse modi quasi similique atque sequi tempore dolore ut nesciunt aliquam quidem dolorum ipsa totam eaque accusamus odit maiores fugiat incidunt iste. Itaque necessitatibus cupiditate consequatur vitae maxime.
');
			app.editors.cssSession.setValue('body{ margin: 0; padding: 1rem; }\n\nh1{\n	margin-top: 0;\n	color: #666;\n}\n\np{\n	color: #999;\n}');
			app.editors.jsSession.setValue('var x = document.querySelector("p");\nx.style.textAlign = "justify";\nx.style.textIndent= "1rem";');
			this.updateResults();
		},
		render: function () {
			this.$el.append(this.template());

			/* *******************************************************
				Editors
			******************************************************* */

			app.session = {
				settings : {
					title : 'codeMagic',
					description : '',
					author : '',
					html : {
						state : true,
						mode : 'html',
						content : ''
					},
					css : {
						state : true,
						mode : 'css',
						content : ''
					},
					js : {
						state : true,
						content : ''
					},
					console : {
						state : false,
						content : ''
					},
					theme : app.utils.getSettings('editor.theme') || 'tomorrow',
					tabSize : parseInt(app.utils.getSettings('editor.tabSize'), 10) || 4,
					showPrintMargin : app.utils.getSettings('editor.showPrintMargin') || false,
					useWrapMode : app.utils.getSettings('editor.useWrapMode') || true,
					useWorker : true,
					fontSize : parseInt(app.utils.getSettings('editor.fontSize'), 10) || 12,
					showInvisibles : app.utils.getSettings('editor.showInvisibles') || false,
					behavioursEnabled : app.utils.getSettings('editor.behavioursEnabled') || true
				}
			};

			app.utils.setSettings('editor.theme', app.session.settings.theme);
			app.utils.setSettings('editor.tabSize', app.session.settings.tabSize);
			app.utils.setSettings('editor.showPrintMargin', app.session.settings.showPrintMargin);
			app.utils.setSettings('editor.useWrapMode', app.session.settings.useWrapMode);
			app.utils.setSettings('editor.useWorker', app.session.settings.useWorker);
			app.utils.setSettings('editor.fontSize', app.session.settings.fontSize);
			app.utils.setSettings('editor.showInvisibles', app.session.settings.showInvisibles);
			app.utils.setSettings('editor.behavioursEnabled', app.session.settings.behavioursEnabled);

			app.editors = {};
			app.editors.html = ace.edit('html-editor');
			app.editors.css = ace.edit('css-editor');
			app.editors.js = ace.edit('js-editor');
			app.editors.htmlSession = app.editors.html.getSession();
			app.editors.cssSession = app.editors.css.getSession();
			app.editors.jsSession = app.editors.js.getSession();

			app.emmet = ace.require('ace/ext/emmet');
			app.language_tools = ace.require('ace/ext/language_tools');

			_.each([app.editors.html, app.editors.css, app.editors.js], function(editor) {
				editor.commands.removeCommand('showSettingsMenu');
				editor.commands.addCommand({
					name: 'fullscreen',
					bindKey: {
						win: 'Ctrl-Shift-F',
						mac: 'Command-Shift-F'
					},
					exec: function (e) {
						app.codemagicView.editorFullscreen(e);
					},
					readOnly: true
				});
				editor.setOptions({
					enableSnippets: true,
					enableLiveAutoComplete: true,
					enableBasicAutocompletion: true,
					showPrintMargin: app.session.settings.showPrintMargin,
					useSoftTabs: false,
					fontSize: app.session.settings.fontSize,
					showInvisibles: app.session.settings.showInvisibles,
					behavioursEnabled: app.session.settings.behavioursEnabled,
					tabSize: app.session.settings.tabSize,
					wrap: app.session.settings.useWrapMode,
					useWorker: app.session.settings.useWorker,
					highlightActiveLine: false,
					enableEmmet: true
				});
			});

			// editor syntax highlighting modes
			app.editors.htmlSession.setMode('ace/mode/' + app.session.settings.html.mode);
			app.editors.cssSession.setMode('ace/mode/' + app.session.settings.css.mode);
			app.editors.jsSession.setMode('ace/mode/javascript');

			// set the Default theme
			app.utils.setTheme(app.editors, app.session.settings.theme);

			this.toggleEditorState(['html', 'css', 'js']);

			return this;
		}
	});
});
<commit_msg>added custom updateResults shortcut<commit_after>var app = app || {};

$(function () {
	'use strict';

	app.CodemagicView = Backbone.View.extend({
		that: this,
		el: '#container',
		events : {
			'click #update': 'updateResults',
			'click #prettify': 'prettify',
			'click #fullscreen': 'toggleFullscreen',
			'click .editor-fullscreen-toggle': 'editorFullscreen',
			'mousedown .resizer': 'resizeInitialize',
			'mouseup': 'resizeFinalize',
			'mousemove': 'resizeRefresh',
			'click .editor-options-toggle': 'toggleTargetedEditorOptions',
			'change .codeChoice': 'toggleSelectedEditorOptions',
			'click .editor-toggle': 'toggleEditorState'
		},
		prettify: function () {
			// parameterize these depending on the editor's settings
			// https://github.com/einars/js-beautify#options
			if ($('#markupChoice').val() === 'HTML') {
				app.editors.htmlSession.setValue(html_beautify(app.editors.htmlSession.getValue(), {
					'brace_style': 'collapse',
					'indent_size': 1,
					'indent_char': '\t',
					'preserve-newlines': true,
					'max-preserve-newlines': 1,
					'wrap-line-length': 0,
					'unformatted': [],
					'indent-inner-html': true
				}));

				app.editors.htmlSession.selection.moveCursorFileStart();
			}

			if ($('#styleChoice').val() === 'CSS') {
				app.editors.cssSession.setValue(css_beautify(app.editors.cssSession.getValue(), {
					'brace_style': 'collapse',
					'indent_size': 1,
					'indent_char': '\t',
					'preserve-newlines': true,
					'max-preserve-newlines': 1,
					'wrap-line-length': 0,
					'unformatted': []
				}));

				app.editors.cssSession.selection.moveCursorFileStart();
			}

			if ($('#scriptChoice').val() === 'JavaScript') {
				app.editors.jsSession.setValue(js_beautify(app.editors.jsSession.getValue(), {
					'indent_size': 1,
					'indent_char': '\t',
					'preserve_newlines': true,
					'jslint_happy': true,
					'brace_style': 'collapse',
					'keep_array_indentation': false,
					'keep_function_indentation': false,
					'eval_code': false,
					'unescape_strings': false,
					'break_chained_methods': false
				}));

				app.editors.jsSession.selection.moveCursorFileStart();
			}
		},
		toggleEditorState: function (selector) {
			var target;
			if(selector instanceof Array){
				for (var i = 0; i < selector.length; i++) {
					$(selector[i]).toggleClass('enabled');
					$('#' + selector[i] + '-editor').closest('.editor-module').toggleClass('enabled');
					$('#' + selector[i] + '-editor-toggle').toggleClass('enabled');
				}
				target = false;
			}else if(typeof selector === 'object'){
				target = $(selector.currentTarget).prop('id').replace('-editor-toggle', '');
			} else {
				target = selector;
			}

			if(target !== false){
				$('#' + target + '-editor-toggle').toggleClass('enabled');
				$('#' + target + '-editor').closest('.editor-module').toggleClass('enabled');
				app.utils.toggleEditorState(target);
			}
		},
		toggleSelectedEditorOptions: function (e) {
			var value = $(e.currentTarget).val();
			var editorTarget = $(e.currentTarget).parent();
			var target = editorTarget.parent().find('.editor-option-title');
			$(target).html(value);
			this.toggleTargetedEditorOptions(e);
			app.utils.setEditorMode(editorTarget.prop('id').replace('-editor-options', ''), value.toLowerCase());
		},
		toggleTargetedEditorOptions: function (e) {
			if($(e.currentTarget).prop('tagName') === 'SELECT'){
				this.toggleEditorOptions($(e.currentTarget).parent());
			} else {
				this.toggleEditorOptions($(e.currentTarget).next());
			}
		},
		toggleEditorOptions: function (target) {
			$(target).toggleClass('enabled');
		},
		resizeInitialize: function (e) {
			app.session.resize = e.pageY;
			app.session.resizeTarget = app.session.resizeTarget || {};
			app.session.resizeTarget.id = $(e.currentTarget).prev().find('.editor');
			app.session.resizeTarget.id = app.session.resizeTarget.id.prop('id');
			app.session.resizeTarget.height = $('#' + app.session.resizeTarget.id).parent().height();
		},
		resizeRefresh: function (e) {
			if (app.session.resize) {
				$('#editors').css('padding-bottom', '30%');
				$('#' + app.session.resizeTarget.id).parent().height(app.session.resizeTarget.height + e.pageY - app.session.resize);
				app.utils.updateLayout(app.editors);
			}
		},
		resizeFinalize: function () {
			app.session.resize = false;
			if(typeof app.session.resizeTarget !== 'undefined'){
				if(typeof app.session.resizeTarget.height !== 'undefined'){
					app.session.resizeTarget.height = $('#' + app.session.resizeTarget.id).height();
				}
			}
			app.utils.updateLayout(app.editors);
			$('#editors').css('padding-bottom', '0');
		},
		toggleFullscreen: function () {
			if ($('#fullscreen').hasClass('enabled')) {
				$('#fullscreen').removeClass('enabled');
				$('#editors').show();
				$('#result').removeClass('fullscreen');
			} else {
				$('#fullscreen').addClass('enabled');
				$('#editors').hide();
				$('#result').addClass('fullscreen');
			}
		},
		editorFullscreen: function (e) {
			var target;
			if(e.container !== undefined){
				target = $(e.container).prop('id');
			}else{
				target = $(e.currentTarget).prop('id');
				target = target.replace('-editor-fullscreen-toggle', '') + '-editor';
			}
			target = document.getElementById(target);

			if (!document.fullscreenElement && !document.mozFullScreenElement && !document.webkitFullscreenElement) {
				if (target.requestFullscreen) {
					target.requestFullscreen();
				} else
				if (target.mozRequestFullScreen) {
					target.mozRequestFullScreen();
				} else
				if (target.webkitRequestFullscreen) {
					target.webkitRequestFullscreen(Element.ALLOW_KEYBOARD_INPUT);
				}
			}
			else {
				if (document.cancelFullScreen) {
					document.cancelFullScreen();
				}
				else if (document.mozCancelFullScreen) {
					document.mozCancelFullScreen();
				}
				else if (document.webkitCancelFullScreen) {
					document.webkitCancelFullScreen();
				}
			}
		},
		updateResults: function () {
			$('#console-editor').html('');

			var content = '';
			var style= '';
			var script= '';

			if ($('#markupChoice').val() === 'Markdown') {
				content = marked(app.editors.html.getValue());
			} else if ($('#markupChoice').val() === 'HAML') {
				app.utils.consoleLog('HAML support is not ready yet');
			} else if ($('#markupChoice').val() === 'Jade') {
				app.utils.consoleLog('Jade support is not ready yet');
			} else {
				content = app.editors.html.getValue();
			}

			if ($('#styleChoice').val() === 'Less') {
				var parser = new(less.Parser)();

				parser.parse(app.editors.css.getValue(), function (e, tree) {
					if (e) {
						// TODO: error handling in console
						$('#console-editor').append('> ' + e.message + '
');
						console.log(e);
					}
					style = tree.toCSS();
				});
			} else if ($('#styleChoice').val() === 'SASS' || $('#styleChoice').val() === 'SCSS') {
				app.utils.consoleLog('SASS/SCSS support is not ready yet');
			} else if ($('#styleChoice').val() === 'Stylus') {
				app.utils.consoleLog('Stylus support is not ready yet');
			} else {
				style = app.editors.css.getValue();
			}

			if ($('#styleChoice').val() === 'CoffeeScript') {
			} else {
				script = app.editors.js.getValue();
			}

			// WHY: breaking down logger into many pieces to prevent proxies from chocking by passing the 500 character limit
			var logger = '';

			var head = '<!doctype html>' + logger + '<meta charset="utf-8"><title>Title</title><meta name="description" content="Description"><meta name="author" content="Author">';
			var body = '' + content + '';

			var result = head + body;

			var iframeContainer = document.getElementById('result');

			$('#result iframe').remove();

			// TODO: write the lines below in JQuery (if performance and stability allow it)
			var iframe = document.createElement('iframe');

			iframeContainer.appendChild(iframe);

			var iDoc = iframe.contentDocument;
			iDoc.open();
			iDoc.write(result);
			iDoc.close();

			$('iframe').height(Math.max($('#editors').height(), $('iframe').height()));
		},
		initialize: function () {
			this.template = _.template($('#codemagic-template').html());
			this.render();

			// populate editors with example content
			app.editors.htmlSession.setValue('
Hello World
\n\n
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Consequuntur, nobis, inventore, cupiditate, itaque quae quas commodi reprehenderit expedita aliquid nulla vero voluptatem esse modi quasi similique atque sequi tempore dolore ut nesciunt aliquam quidem dolorum ipsa totam eaque accusamus odit maiores fugiat incidunt iste. Itaque necessitatibus cupiditate consequatur vitae maxime.
');
			app.editors.cssSession.setValue('body{ margin: 0; padding: 1rem; }\n\nh1{\n	margin-top: 0;\n	color: #666;\n}\n\np{\n	color: #999;\n}');
			app.editors.jsSession.setValue('var x = document.querySelector("p");\nx.style.textAlign = "justify";\nx.style.textIndent= "1rem";');
			this.updateResults();
		},
		render: function () {
			this.$el.append(this.template());

			/* *******************************************************
				Editors
			******************************************************* */

			app.session = {
				settings : {
					title : 'codeMagic',
					description : '',
					author : '',
					html : {
						state : true,
						mode : 'html',
						content : ''
					},
					css : {
						state : true,
						mode : 'css',
						content : ''
					},
					js : {
						state : true,
						content : ''
					},
					console : {
						state : false,
						content : ''
					},
					theme : app.utils.getSettings('editor.theme') || 'tomorrow',
					tabSize : parseInt(app.utils.getSettings('editor.tabSize'), 10) || 4,
					showPrintMargin : app.utils.getSettings('editor.showPrintMargin') || false,
					useWrapMode : app.utils.getSettings('editor.useWrapMode') || true,
					useWorker : true,
					fontSize : parseInt(app.utils.getSettings('editor.fontSize'), 10) || 12,
					showInvisibles : app.utils.getSettings('editor.showInvisibles') || false,
					behavioursEnabled : app.utils.getSettings('editor.behavioursEnabled') || true
				}
			};

			app.utils.setSettings('editor.theme', app.session.settings.theme);
			app.utils.setSettings('editor.tabSize', app.session.settings.tabSize);
			app.utils.setSettings('editor.showPrintMargin', app.session.settings.showPrintMargin);
			app.utils.setSettings('editor.useWrapMode', app.session.settings.useWrapMode);
			app.utils.setSettings('editor.useWorker', app.session.settings.useWorker);
			app.utils.setSettings('editor.fontSize', app.session.settings.fontSize);
			app.utils.setSettings('editor.showInvisibles', app.session.settings.showInvisibles);
			app.utils.setSettings('editor.behavioursEnabled', app.session.settings.behavioursEnabled);

			app.editors = {};
			app.editors.html = ace.edit('html-editor');
			app.editors.css = ace.edit('css-editor');
			app.editors.js = ace.edit('js-editor');
			app.editors.htmlSession = app.editors.html.getSession();
			app.editors.cssSession = app.editors.css.getSession();
			app.editors.jsSession = app.editors.js.getSession();

			app.emmet = ace.require('ace/ext/emmet');
			app.language_tools = ace.require('ace/ext/language_tools');

			_.each([app.editors.html, app.editors.css, app.editors.js], function(editor) {
				editor.commands.removeCommand('showSettingsMenu');
				editor.commands.addCommand({
					name: 'fullscreen',
					bindKey: {
						win: 'Ctrl-Shift-F',
						mac: 'Command-Shift-F'
					},
					exec: function (e) {
						app.codemagicView.editorFullscreen(e);
					},
					readOnly: true
				});
				editor.commands.addCommand({
					name: 'updateResults',
					bindKey: {
						win: 'Ctrl-Enter',
						mac: 'Command-Enter'
					},
					exec: function (e) {
						app.codemagicView.updateResults();
					},
					readOnly: true
				});
				editor.setOptions({
					enableSnippets: true,
					enableLiveAutoComplete: true,
					enableBasicAutocompletion: true,
					showPrintMargin: app.session.settings.showPrintMargin,
					useSoftTabs: false,
					fontSize: app.session.settings.fontSize,
					showInvisibles: app.session.settings.showInvisibles,
					behavioursEnabled: app.session.settings.behavioursEnabled,
					tabSize: app.session.settings.tabSize,
					wrap: app.session.settings.useWrapMode,
					useWorker: app.session.settings.useWorker,
					highlightActiveLine: false,
					enableEmmet: true
				});
			});

			// editor syntax highlighting modes
			app.editors.htmlSession.setMode('ace/mode/' + app.session.settings.html.mode);
			app.editors.cssSession.setMode('ace/mode/' + app.session.settings.css.mode);
			app.editors.jsSession.setMode('ace/mode/javascript');

			// set the Default theme
			app.utils.setTheme(app.editors, app.session.settings.theme);

			this.toggleEditorState(['html', 'css', 'js']);

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


<commit_before>var $db = require(global.cwd + '/lib/mongo');
var debug = require('debug')('wol:leaderboard');
var Arpad = require('arpad');
var $q = require('q');

module.exports = function singles(game, match) {
    /* stop if <> 1v1 */
    if (match.players.length != 2) return;

    /* find winner and loser */
    var winner = -1;
    var loser = -1;

    match.players.forEach(function(player, index) {
        if (player.won > 0) winner = index;
        if (player.loss > 0) loser = index;
    });

    /* discontinue if no winner /and/ loser */
    if (winner < 0 || loser < 0) return;

    var elo = new Arpad();
    var $players = $db.get(game +'_players');

    /* get points for players */
    points(game, match.players).then(function(players) {
        match.players = players; /* reassign modified players */
        var update = {$set: {}}; /* query to update match obj */

        /* note the type of match */
        update.$set.type = 'singles';

        match.players.forEach(function(player, index) {
            var opponent = match.players[loser];
            var method = 'newRatingIfWon';

            if (player.loss > 0) {
                opponent = match.players[winner];
                method = 'newRatingIfLost';
            }

            /* calculate new point value */
            player.exp = elo[method](player.points, opponent.points);

            /* update or create player */
            $players.update({name: player.name}, {
                $set: {points: player.exp},
                $push: {games: match.idno},
                $inc: {
                    wins: player.won,
                    losses: player.loss,
                    disconnects: player.discon
                }
            }, {upsert: true});

            /* update player in match object */
            var str = ['players', index, 'exp'].join('.');
            update.$set[str] = Math.abs(player.points - player.exp);
        });

        /* update match object */
        $db.get(game +'_games').update({idno: match.idno}, update);
    });
};

function points(game, players) {
    var deferred = $q.defer();

    var search = [];
    players.forEach(function(player) {
       search.push(player.name);
    });

    $db.get(game +'_players').find({name: {$in: search}}, function(err, data) {
        players.forEach(function(player) {
            players[player].points = 1000;

            data.forEach(function(row) {
                if (row.points && player.name == row.name) {
                    players[player].points = row.points;
                }
            });
        });

        deferred.resolve(players);
    });

    return deferred.promise;
}
<commit_msg>possible fix, points was not being awarded to specific player<commit_after>var $db = require(global.cwd + '/lib/mongo');
var debug = require('debug')('wol:leaderboard');
var Arpad = require('arpad');
var $q = require('q');

module.exports = function singles(game, match) {
    /* stop if <> 1v1 */
    if (match.players.length != 2) return;

    /* find winner and loser */
    var winner = -1;
    var loser = -1;

    match.players.forEach(function (player, index) {
        if (player.won > 0) winner = index;
        if (player.loss > 0) loser = index;
    });

    /* discontinue if no winner /and/ loser */
    if (winner < 0 || loser < 0) return;

    var elo = new Arpad();
    var $players = $db.get(game + '_players');

    /* get points for players */
    points(game, match.players).then(function (players) {
        match.players = players;
        /* reassign modified players */
        var update = {$set: {}};
        /* query to update match obj */

        /* note the type of match */
        update.$set.type = 'singles';

        match.players.forEach(function (player, index) {
            var opponent = match.players[loser];
            var method = 'newRatingIfWon';

            if (player.loss > 0) {
                opponent = match.players[winner];
                method = 'newRatingIfLost';
            }

            /* calculate new point value */
            player.exp = elo[method](player.points, opponent.points);

            /* update or create player */
            $players.update({name: player.name}, {
                $set: {points: player.exp},
                $push: {games: match.idno},
                $inc: {
                    wins: player.won,
                    losses: player.loss,
                    disconnects: player.discon
                }
            }, {upsert: true});

            /* update player in match object */
            var str = ['players', index, 'exp'].join('.');
            update.$set[str] = Math.abs(player.points - player.exp);
        });

        /* update match object */
        $db.get(game + '_games').update({idno: match.idno}, update);
    });
};

function points(game, players) {
    var deferred = $q.defer();

    var search = [];
    players.forEach(function (player) {
        search.push(player.name);
    });

    $db.get(game + '_players').find({name: {$in: search}}, function (err, data) {
        players.forEach(function (player, key) {

            players[key].points = 1000;

            data.forEach(function (row) {
                if (row.points && player.name == row.name) {
                    players[key].points = row.points;
                }
            });
        });

        deferred.resolve(players);
    });

    return deferred.promise;
}
<|endoftext|>


<commit_before>/*jshint -W004 */
var $db = require(global.cwd + '/lib/mongo');
var debug = require('debug')('wol:leaderboard');
var Arpad = require('arpad');
var $q = require('q');

module.exports = function singles(game, match, packets) {
    /* stop if <> 1v1 */
    if (match.players.length != 2) return;
    packets = packets || [];

    /* find winner and loser */
    var winner = -1;
    var loser = -1;

    match.players.forEach(function (player, index) {
        if (player.won > 0) winner = index;
        if (player.loss > 0) loser = index;
    });

    /* D/C Scenario: 1 packet, no clear winner */
    if (packets[0] && !packets[1] && (winner < 0 || loser < 0)) {
        match.players.forEach(function(player, index) {
            loser = index;
            player.discon = 1;
            player.loss = 1;
            player.won = 0;

            /* assume uploader won */
            if (player.name == packets[0].client.nick) {
                winner = index;
                player.discon = 0;
                player.won = 1;
                player.loss = 0;
            }
        });
    }

    /* D/C Scenario: no clear winner, check if pils or para exists */
    if (packets.length > 1 && (winner < 0 || loser < 0)) {
        if (packets[0].client.pils >= 0 && packets[1].client.pils >= 0) {
            match.players.forEach(function(player, index) {
                loser = index;
                player.discon = 1;
                player.loss = 1;
                player.won = 0;

                /* higher pils means you lost connection */
                if (player.name == packets[0].client.nick) {
                    /* player attempted abort */
                    if (packets[0].client.para > 0) return;

                    if (packets[0].client.pils < packets[1].client.pils) {
                        winner = index;
                        player.discon = 0;
                        player.won = 1;
                        player.loss = 0;
                    }
                } else if (player.name == packets[1].client.nick) {
                    /* player attempted abort */
                    if (packets[1].client.para > 0) return;

                    if (packets[1].client.pils < packets[0].client.pils) {
                        winner = index;
                        player.discon = 0;
                        player.won = 1;
                        player.loss = 0;
                    }
                }
            });
        }
    }

    var elo = new Arpad();
    var $players = $db.get(game + '_players');

    /* get points for players */
    points(game, match.players).then(function (players) {
        /* reassign modified players */
        match.players = players;

        /* query to update match obj */
        var update = {$set: {}};

        /* note the type of match */
        update.$set.type = 'singles';

        /* determine if game is out of sync */
        packets.forEach(function(packet) {
            if (packet.client.oosy) {
                update.$set.oosy = 1;
                winner = loser = -1;
            }
        });

        match.players.forEach(function (player, index) {
            /* query to update player obj */
            var _player = {
                $push: {games: match.idno},
                $inc: {
                    wins: player.won,
                    losses: player.loss,
                    disconnects: player.discon
                }
            };

            /* increase out of sync for player */
            if (update.$set.oosy) {
                _player.$inc.oos = 1;
            }

            /* calculate points if winner and loser */
            if (winner >= 0 && loser >= 0) {
                var opponent = match.players[loser];
                var method = 'newRatingIfWon';

                if (player.loss > 0) {
                    opponent = match.players[winner];
                    method = 'newRatingIfLost';
                }

                /* calculate new point value */
                player.exp = elo[method](player.points, opponent.points);
            }

            /* if we only have losers, deduct from both players */
            else if (winner < 0 && loser >= 0) {
                /* deduct 0.7% percent of points (higher points, d/c hits harder) */
                player.exp = player.points - Math.floor((0.7 / 100) * player.points);
            }

            /* if we have points, update the game and player records */
            if (player.exp) {
                /* update _player points */
                _player.$set = {points: player.exp};

                /* update player, experience gained/loss in match object */
                var str = ['players', index, 'exp'].join('.');
                update.$set[str] = Math.abs(player.points - player.exp);
            }

            /* update win/loss/discon in game object just in case it's changed */
            var str = ['players', index].join('.');
            update.$set[str + '.won'] = player.won;
            update.$set[str + '.loss'] = player.loss;
            update.$set[str + '.discon'] = player.discon;

            /* update or create player */
            $players.update({name: player.name}, _player, {upsert: true});
        });

        /* update match object */
        $db.get(game + '_games').update({idno: match.idno}, update);
    });
};

function points(game, players) {
    var deferred = $q.defer();

    var search = [];
    players.forEach(function (player) {
        search.push(player.name);
    });

    $db.get(game + '_players').find({name: {$in: search}}, function (err, data) {
        players.forEach(function (player, key) {

            players[key].points = 1000;

            data.forEach(function (row) {
                if (row.points && player.name == row.name) {
                    players[key].points = row.points;
                }
            });
        });

        deferred.resolve(players);
    });

    return deferred.promise;
}
<commit_msg>lowercasing packet nick for comparison<commit_after>/*jshint -W004 */
var $db = require(global.cwd + '/lib/mongo');
var debug = require('debug')('wol:leaderboard');
var Arpad = require('arpad');
var $q = require('q');

module.exports = function singles(game, match, packets) {
    /* stop if <> 1v1 */
    if (match.players.length != 2) return;
    packets = packets || [];

    /* find winner and loser */
    var winner = -1;
    var loser = -1;

    match.players.forEach(function (player, index) {
        if (player.won > 0) winner = index;
        if (player.loss > 0) loser = index;
    });

    if (packets[0].client) {
        packets[0].client.nick = (packets[0].client.nick || '').toLowerCase();
    }

    if (packets[1].client) {
        packets[1].client.nick = (packets[1].client.nick || '').toLowerCase();
    }

    /* D/C Scenario: 1 packet, no clear winner */
    if (packets[0] && !packets[1] && (winner < 0 || loser < 0)) {
        match.players.forEach(function(player, index) {
            loser = index;
            player.discon = 1;
            player.loss = 1;
            player.won = 0;

            /* assume uploader won */
            if (player.name == packets[0].client.nick) {
                winner = index;
                player.discon = 0;
                player.won = 1;
                player.loss = 0;
            }
        });
    }

    /* D/C Scenario: no clear winner, check if pils or para exists */
    if (packets.length > 1 && (winner < 0 || loser < 0)) {
        if (packets[0].client.pils >= 0 && packets[1].client.pils >= 0) {
            match.players.forEach(function(player, index) {
                loser = index;
                player.discon = 1;
                player.loss = 1;
                player.won = 0;

                /* higher pils means you lost connection */
                if (player.name == packets[0].client.nick) {
                    /* player attempted abort */
                    if (packets[0].client.para > 0) return;

                    if (packets[0].client.pils < packets[1].client.pils) {
                        winner = index;
                        player.discon = 0;
                        player.won = 1;
                        player.loss = 0;
                    }
                } else if (player.name == packets[1].client.nick) {
                    /* player attempted abort */
                    if (packets[1].client.para > 0) return;

                    if (packets[1].client.pils < packets[0].client.pils) {
                        winner = index;
                        player.discon = 0;
                        player.won = 1;
                        player.loss = 0;
                    }
                }
            });
        }
    }

    var elo = new Arpad();
    var $players = $db.get(game + '_players');

    /* get points for players */
    points(game, match.players).then(function (players) {
        /* reassign modified players */
        match.players = players;

        /* query to update match obj */
        var update = {$set: {}};

        /* note the type of match */
        update.$set.type = 'singles';

        /* determine if game is out of sync */
        packets.forEach(function(packet) {
            if (packet.client.oosy) {
                update.$set.oosy = 1;
                winner = loser = -1;
            }
        });

        match.players.forEach(function (player, index) {
            /* query to update player obj */
            var _player = {
                $push: {games: match.idno},
                $inc: {
                    wins: player.won,
                    losses: player.loss,
                    disconnects: player.discon
                }
            };

            /* increase out of sync for player */
            if (update.$set.oosy) {
                _player.$inc.oos = 1;
            }

            /* calculate points if winner and loser */
            if (winner >= 0 && loser >= 0) {
                var opponent = match.players[loser];
                var method = 'newRatingIfWon';

                if (player.loss > 0) {
                    opponent = match.players[winner];
                    method = 'newRatingIfLost';
                }

                /* calculate new point value */
                player.exp = elo[method](player.points, opponent.points);
            }

            /* if we only have losers, deduct from both players */
            else if (winner < 0 && loser >= 0) {
                /* deduct 0.7% percent of points (higher points, d/c hits harder) */
                player.exp = player.points - Math.floor((0.7 / 100) * player.points);
            }

            /* if we have points, update the game and player records */
            if (player.exp) {
                /* update _player points */
                _player.$set = {points: player.exp};

                /* update player, experience gained/loss in match object */
                var str = ['players', index, 'exp'].join('.');
                update.$set[str] = Math.abs(player.points - player.exp);
            }

            /* update win/loss/discon in game object just in case it's changed */
            var str = ['players', index].join('.');
            update.$set[str + '.won'] = player.won;
            update.$set[str + '.loss'] = player.loss;
            update.$set[str + '.discon'] = player.discon;

            /* update or create player */
            $players.update({name: player.name}, _player, {upsert: true});
        });

        /* update match object */
        $db.get(game + '_games').update({idno: match.idno}, update);
    });
};

function points(game, players) {
    var deferred = $q.defer();

    var search = [];
    players.forEach(function (player) {
        search.push(player.name);
    });

    $db.get(game + '_players').find({name: {$in: search}}, function (err, data) {
        players.forEach(function (player, key) {

            players[key].points = 1000;

            data.forEach(function (row) {
                if (row.points && player.name == row.name) {
                    players[key].points = row.points;
                }
            });
        });

        deferred.resolve(players);
    });

    return deferred.promise;
}
<|endoftext|>


<commit_before>$(function() {
	makeButtons();

	$.ajaxSetup ({
		cache: false
	});

	$(".gradingTable").find(".details-row").hide();

	$(".toggleButton").click(function(event) {
		var firstRow = $(this).parents(".first-row").get(0);
		$(".gradingTable").find(".details-row").each(function(index, value) {
			if($(value).is(":visible")) {
				$(value).hide();
			}else if(!$(value).is(":visible") && $(value).attr("id") === $(firstRow).next().attr("id")) {
				if($(value).find(".replaceWithComments").children().length == 0) {
					var oldSrc = $(firstRow).find(".toggleStatus").attr("src");
					oldSrc = oldSrc.replace("loading.gif", "");
					oldSrc = oldSrc.replace("no-status.png", "");

					$(firstRow).find(".toggleStatus").attr("src", oldSrc + "loading.gif");

					var href=$(value).find(".commentsLink").attr("href");
					var ci = href.indexOf("Comment");
					href = "/sakai-lessonbuildertool-tool/faces/" + href.substring(ci);
					$(value).find(".replaceWithComments").load(href, function() {
						var current = $(value);
						var next = $(value).next().next();

						makeButtons();

						$(current).show();

						var oldSrc = $(firstRow).find(".toggleStatus").attr("src");
						oldSrc = oldSrc.replace("loading.gif", "");
						oldSrc = oldSrc.replace("no-status.png", "");

						$(firstRow).find(".toggleStatus").attr("src", oldSrc + "no-status.png");

						setMainFrameHeight(window.name);
						prefetchComments(next);
					});
				}else {
					$(value).show();
					setMainFrameHeight(window.name);
					prefetchComments($(value).next().next());
				}
			}
		});

		return false;
	});

	$(".pointsBox").each(function(index, value) {
		$(value).parent().children("img").attr("id", "statusImg" + index);
		$(value).val($(value).parent().children(".pointsSpan").text());
	});

	$(".pointsBox").live('change', function(){
		var img = $(this).parent().children("img");
		img.attr("src", getStrippedImgSrc(img.attr("id")) + "no-status.png");
		$(this).addClass("unsubmitted");
	});

	$(".pointsBox").keyup(function(event){
		if(event.keyCode == 13) {
			var img = $(this).parent().children("img");

			$(this).removeClass("unsubmitted");
			img.attr("src", getStrippedImgSrc(img.attr("id")) + "loading.gif");

			$(".idField").val($(this).parent().children(".uuidBox").text()).change();
			$(".jsIdField").val(img.attr("id")).change();
			$(".typeField").val("comment");

			// This one triggers the update
			$(".pointsField").val($(this).val()).change();
		}
	});
});

function prefetchComments(value) {
	// Prefetch the next one as well, so that it's ready when they need it.
	if($(value).length > 0 && $(value).find(".replaceWithComments").children().length == 0) {
		var href=$(value).find(".commentsLink").attr("href");
		var ci = href.indexOf("Comment");
		href = "/sakai-lessonbuildertool-tool/faces/" + href.substring(ci);
		$(value).find(".replaceWithComments").load(href, makeButtons);
	}
}

function makeButtons() {
	if (!(navigator.userAgent.indexOf("Firefox/2.") > 0)) {
	    $('.usebutton').button({text:true});
	} else {
	    // fake it; can't seem to get rid of underline though
	    $('.usebutton').css('border', '1px solid black').css('padding', '1px 4px').css('color', 'black');
	}
}<commit_msg>fix up urls so "show context" works<commit_after>// GradingPane is called by ajax from a URL like
// /sakai-lessonbuildertool-tool/faces/GradingPane
// however URLs we generate need to be the usual
// /portal/pda/xxxx/tool/xxxx/ShowPage
// it's hard to get RSF to generate specified URLs, so
// we fix them up in javascript.

function fixurls() {

    var pageurl = window.location + "";
    var pi = pageurl.indexOf("/GradingPane");

    pageurl = pageurl.substring(0,pi);
    $('a[target="_lbcomments"]').each(function(index, value) {
	    var linkurl = $(this).attr('href');
	    var li = linkurl.indexOf("/faces/") + 6;
	    if (li >= 0) {
		linkurl = pageurl + linkurl.substring(li);
		$(this).attr('href',linkurl);
	    }
	});
}

$(function() {
	makeButtons();

	$.ajaxSetup ({
		cache: false
	});

	$(".gradingTable").find(".details-row").hide();

	$(".toggleButton").click(function(event) {
		var firstRow = $(this).parents(".first-row").get(0);
		$(".gradingTable").find(".details-row").each(function(index, value) {
			if($(value).is(":visible")) {
				$(value).hide();
			}else if(!$(value).is(":visible") && $(value).attr("id") === $(firstRow).next().attr("id")) {
				if($(value).find(".replaceWithComments").children().length == 0) {
					var oldSrc = $(firstRow).find(".toggleStatus").attr("src");
					oldSrc = oldSrc.replace("loading.gif", "");
					oldSrc = oldSrc.replace("no-status.png", "");

					$(firstRow).find(".toggleStatus").attr("src", oldSrc + "loading.gif");

					var href=$(value).find(".commentsLink").attr("href");
					var ci = href.indexOf("Comment");
					href = "/sakai-lessonbuildertool-tool/faces/" + href.substring(ci);
					$(value).find(".replaceWithComments").load(href, function() {
						var current = $(value);
						var next = $(value).next().next();

						makeButtons();

						$(current).show();

						var oldSrc = $(firstRow).find(".toggleStatus").attr("src");
						oldSrc = oldSrc.replace("loading.gif", "");
						oldSrc = oldSrc.replace("no-status.png", "");

						$(firstRow).find(".toggleStatus").attr("src", oldSrc + "no-status.png");

						fixurls();

						setMainFrameHeight(window.name);
						prefetchComments(next);
					});
				}else {
					fixurls();
					$(value).show();
					setMainFrameHeight(window.name);
					prefetchComments($(value).next().next());
				}
			}
		});

		return false;
	});

	$(".pointsBox").each(function(index, value) {
		$(value).parent().children("img").attr("id", "statusImg" + index);
		$(value).val($(value).parent().children(".pointsSpan").text());
	});

	$(".pointsBox").live('change', function(){
		var img = $(this).parent().children("img");
		img.attr("src", getStrippedImgSrc(img.attr("id")) + "no-status.png");
		$(this).addClass("unsubmitted");
	});

	$(".pointsBox").keyup(function(event){
		if(event.keyCode == 13) {
			var img = $(this).parent().children("img");

			$(this).removeClass("unsubmitted");
			img.attr("src", getStrippedImgSrc(img.attr("id")) + "loading.gif");

			$(".idField").val($(this).parent().children(".uuidBox").text()).change();
			$(".jsIdField").val(img.attr("id")).change();
			$(".typeField").val("comment");

			// This one triggers the update
			$(".pointsField").val($(this).val()).change();
		}
	});
});

function prefetchComments(value) {
	// Prefetch the next one as well, so that it's ready when they need it.
	if($(value).length > 0 && $(value).find(".replaceWithComments").children().length == 0) {
		var href=$(value).find(".commentsLink").attr("href");
		var ci = href.indexOf("Comment");
		href = "/sakai-lessonbuildertool-tool/faces/" + href.substring(ci);
		$(value).find(".replaceWithComments").load(href, makeButtons);
	}
}

function makeButtons() {
	if (!(navigator.userAgent.indexOf("Firefox/2.") > 0)) {
	    $('.usebutton').button({text:true});
	} else {
	    // fake it; can't seem to get rid of underline though
	    $('.usebutton').css('border', '1px solid black').css('padding', '1px 4px').css('color', 'black');
	}
}<|endoftext|>


<commit_before>(function ($) {
  $.extend($.summernote.lang, {
    'ta-IN': {
      font: {
        bold: 'தடித்த',
        italic: 'சாய்வு',
        underline: 'அடிக்கோடு',
        clear: 'நீக்கு',
        height: 'வரி  உயரம்',
        name: 'எழுத்துரு பெயர்',
        strikethrough: 'குறுக்குக் கோடு',
        size: 'எழுத்துரு அளவு',
        superscript: 'மேல் ஒட்டு',
        subscript: 'கீழ் ஒட்டு'
      },
      image: {
        image: 'படம்',
        insert: 'படத்தை செருகு',
        resizeFull: 'முழு அளவை',
        resizeHalf: 'அரை அளவை',
        resizeQuarter: 'கால் அளவை',
        floatLeft: 'இடப்பக்கமாக வை',
        floatRight: 'வலப்பக்கமாக வை',
        floatNone: 'இயல்பு நிலையில் வை',
        dragImageHere: 'படத்தை இங்கே வை',
        selectFromFiles: 'கோப்புகளை தேர்வு செய்',
        url: 'இணையதள முகவரி',
        remove: 'படத்தை நீக்கு'
      },
      video: {
        video: 'காணொளி',
        videoLink: 'காணொளி இணைப்பு',
        insert: 'காணொளியை செருகு',
        url: 'இணையதள முகவரி',
        providers: '(YouTube, Vimeo, Vine, Instagram, DailyMotion ou Youku)'
      },
      link: {
        link: 'இணைப்பு',
        insert: 'இணைப்பை செருகு',
        unlink: 'இணைப்பை நீக்கு',
        edit: 'இணைப்பை தொகு',
        textToDisplay: 'காட்சி வாசகம்',
        url: 'இணையதள முகவரி',
        openInNewWindow: 'புதிய சாளரத்தில் திறக்க'
      },
      table: {
        table: 'அட்டவணை'
      },
      hr: {
        insert: 'கிடைமட்ட கோடு'
      },
      style: {
        style: 'தொகுப்பு',
        p: 'பத்தி',
        blockquote: 'மேற்கோள்',
        pre: 'குறியீடு',
        h1: 'தலைப்பு 1',
        h2: 'தலைப்பு 2',
        h3: 'தலைப்பு 3',
        h4: 'தலைப்பு 4',
        h5: 'தலைப்பு 5',
        h6: 'தலைப்பு 6'
      },
      lists: {
        unordered: 'வரிசையிடாத',
        ordered: 'வரிசையிட்ட'
      },
      options: {
        help: 'உதவி',
        fullscreen: 'முழு திரை',
        codeview: 'நிரலாக்க காட்சி'
      },
      paragraph: {
        paragraph: 'பத்தி',
        outdent: 'வெளித்தள்ளு',
        indent: 'உள்ளே தள்ளு',
        left: 'இடது சீரமைப்பு',
        center: 'நடு சீரமைப்பு',
        right: 'வலது சீரமைப்பு',
        justify: 'இருபுற சீரமைப்பு'
      },
      color: {
        recent: 'அண்மை நிறம்',
        more: 'மேலும்',
        background: 'பின்புல நிறம்',
        foreground: 'முன்புற நிறம்',
        transparent: 'தெளிமையான',
        setTransparent: 'தெளிமையாக்கு',
        reset: 'மீட்டமைக்க',
        resetToDefault: 'இயல்புநிலைக்கு மீட்டமை'
      },
      shortcut: {
        shortcuts: 'குறுக்குவழி',
        close: 'மூடு',
        textFormatting: 'எழுத்து வடிவமைப்பு',
        action: 'செயல்படுத்து',
        paragraphFormatting: 'பத்தி வடிவமைப்பு',
        documentStyle: 'ஆவண பாணி'
      },
      history: {
        undo: 'மீளமை',
        redo: 'மீண்டும்'
      }
    }
  });
})(jQuery);
<commit_msg>Add shape translation in Image<commit_after>(function ($) {
  $.extend($.summernote.lang, {
    'ta-IN': {
      font: {
        bold: 'தடித்த',
        italic: 'சாய்வு',
        underline: 'அடிக்கோடு',
        clear: 'நீக்கு',
        height: 'வரி  உயரம்',
        name: 'எழுத்துரு பெயர்',
        strikethrough: 'குறுக்குக் கோடு',
        size: 'எழுத்துரு அளவு',
        superscript: 'மேல் ஒட்டு',
        subscript: 'கீழ் ஒட்டு'
      },
      image: {
        image: 'படம்',
        insert: 'படத்தை செருகு',
        resizeFull: 'முழு அளவை',
        resizeHalf: 'அரை அளவை',
        resizeQuarter: 'கால் அளவை',
        floatLeft: 'இடப்பக்கமாக வை',
        floatRight: 'வலப்பக்கமாக வை',
        floatNone: 'இயல்பு நிலையில் வை',
        shapeRounded: 'வட்டமான வடிவம்',
        shapeCircle: 'வட்ட வடிவம்',
        shapeThumbnail: 'சிறு வடிவம்',
        shapeNone: 'வடிவத்தை நீக்கு',
        dragImageHere: 'படத்தை இங்கே இழுத்து வை',
        dropImage: 'படத்தை விடு',
        selectFromFiles: 'கோப்புகளை தேர்வு செய்',
        maximumFileSize: 'அதிகபட்ச கோப்பு அளவு',
        maximumFileSizeError: 'கோப்பு அதிகபட்ச அளவை மீறிவிட்டது',
        url: 'இணையதள முகவரி',
        remove: 'படத்தை நீக்கு'
      },
      video: {
        video: 'காணொளி',
        videoLink: 'காணொளி இணைப்பு',
        insert: 'காணொளியை செருகு',
        url: 'இணையதள முகவரி',
        providers: '(YouTube, Vimeo, Vine, Instagram, DailyMotion ou Youku)'
      },
      link: {
        link: 'இணைப்பு',
        insert: 'இணைப்பை செருகு',
        unlink: 'இணைப்பை நீக்கு',
        edit: 'இணைப்பை தொகு',
        textToDisplay: 'காட்சி வாசகம்',
        url: 'இணையதள முகவரி',
        openInNewWindow: 'புதிய சாளரத்தில் திறக்க'
      },
      table: {
        table: 'அட்டவணை'
      },
      hr: {
        insert: 'கிடைமட்ட கோடு'
      },
      style: {
        style: 'தொகுப்பு',
        p: 'பத்தி',
        blockquote: 'மேற்கோள்',
        pre: 'குறியீடு',
        h1: 'தலைப்பு 1',
        h2: 'தலைப்பு 2',
        h3: 'தலைப்பு 3',
        h4: 'தலைப்பு 4',
        h5: 'தலைப்பு 5',
        h6: 'தலைப்பு 6'
      },
      lists: {
        unordered: 'வரிசையிடாத',
        ordered: 'வரிசையிட்ட'
      },
      options: {
        help: 'உதவி',
        fullscreen: 'முழுத்திரை',
        codeview: 'நிரலாக்க காட்சி'
      },
      paragraph: {
        paragraph: 'பத்தி',
        outdent: 'வெளித்தள்ளு',
        indent: 'உள்ளே தள்ளு',
        left: 'இடது சீரமைப்பு',
        center: 'நடு சீரமைப்பு',
        right: 'வலது சீரமைப்பு',
        justify: 'இருபுற சீரமைப்பு'
      },
      color: {
        recent: 'அண்மை நிறம்',
        more: 'மேலும்',
        background: 'பின்புல நிறம்',
        foreground: 'முன்புற நிறம்',
        transparent: 'தெளிமையான',
        setTransparent: 'தெளிமையாக்கு',
        reset: 'மீட்டமைக்க',
        resetToDefault: 'இயல்புநிலைக்கு மீட்டமை'
      },
      shortcut: {
        shortcuts: 'குறுக்குவழி',
        close: 'மூடு',
        textFormatting: 'எழுத்து வடிவமைப்பு',
        action: 'செயல்படுத்து',
        paragraphFormatting: 'பத்தி வடிவமைப்பு',
        documentStyle: 'ஆவண பாணி'
      },
      history: {
        undo: 'மீளமை',
        redo: 'மீண்டும்'
      }
    }
  });
})(jQuery);
<|endoftext|>