<commit_before>/*
Copyright 2011 Museum of Moving Image

Licensed under the Educational Community License (ECL), Version 2.0.
You may not use this file except in compliance with this License.

You may obtain a copy of the ECL 2.0 License at
https://source.collectionspace.org/collection-space/LICENSE.txt
*/

/*global cspace:true, jQuery, fluid, window*/
"use strict";

cspace = cspace || {};

(function ($, fluid) {

    fluid.defaults("cspace.reportProducer", {
        gradeNames: ["fluid.rendererComponent", "autoInit"],
        produceTree: "cspace.reportProducer.produceTree",
        invokers: {
            generateReport: {
                funcName: "cspace.reportProducer.generateReport",
                args: ["{reportProducer}.confirmation", "{reportProducer}.options.strings", "{reportProducer}.requestReport"]
            },
            requestReport: {
                funcName: "cspace.reportProducer.requestReport",
                args: ["{reportProducer}.model", "{reportProducer}.options", "{reportProducer}.events", "{arguments}.0"]
            }
        },
        components: {
            confirmation: {
                type: "cspace.confirmation"
            },
            reportStatus: {
                type: "cspace.reportProducer.reportStatus",
                createOnEvent: "ready",
                container: "{reportProducer}.reportLoadingIndicatorContainer",
                options: {
                    events: {
                        onStop: "{reportProducer}.events.onStop"
                    }
                }
            },
            messageBar: "{messageBar}"
        },
        events: {
            onError: null,
            onStop: null,
            reportStarted: null,
            reportFinished: null,
            ready: null
        },
        selectors: {
            reportHeader: ".csc-reportProducer-header",
            reportButton: ".csc-reportProducer-button",
            reportType: ".csc-reportProducer-type",
            report: ".csc-reportProducer",
            reportLoadingIndicatorContainer: ".csc-reportProducer-loadingIndicatorContainer"
        },
        selectorsToIgnore: ["reportLoadingIndicatorContainer"],
        strings: {
            reportHeader: "Create Report",
            reportButton: "Create",
            reportError: "Error creating report: ",
            primaryMessage: "Are you sure you want to run this report",
            actText: "Create",
            actAlt: "Create Report"
        },
        styles: {
            reportHeader: "cs-reportProducer-header",
            reportButton: "cs-reportProducer-button",
            report: "cs-reportProducer",
            reportType: "cs-reportProducer-reportType",
            reportLoadingIndicatorContainer: "cs-reportProducer-loadingIndicator"
        },
        resources: {
            template: cspace.resourceSpecExpander({
                fetchClass: "fastTemplate",
                url: "%webapp/html/components/ReportProducerTemplate.html",
                options: {
                    dataType: "html"
                }
            })
        },
        model: {
            reportTypes: ["Please select a value"],
            reportTypeSelection: "",
            enableReporting: {
                expander: {
                    type: "fluid.deferredInvokeCall",
                    func: "cspace.permissions.resolve",
                    args: {
                        resolver: "{permissionsResolver}",
                        permission: "read",
                        target: "reporting"
                    }
                }
            }
        },
        urls: cspace.componentUrlBuilder({
            reportUrl: "%chain/reporting"
        }),
        finalInitFunction: "cspace.reportProducer.finalInit",
        postInitFunction: "cspace.reportProducer.postInit",
        preInitFunction: "cspace.reportProducer.preInit"
    });

    cspace.reportProducer.getReportTypes = function (recordType, strategy, options) {
        var config = {
            strategies: [fluid.invokeGlobalFunction(strategy, [options])]
        };
        return fluid.makeArray(fluid.get({}, fluid.model.composeSegments("reporting", recordType), config));
    };

    fluid.fetchResources.primeCacheFromResources("cspace.reportProducer");

    cspace.reportProducer.preInit = function (that) {
        that.options.listeners = {
            reportStarted: function () {
                that.applier.requestChange("reportTypeSelection", that.model.reportTypeSelection || that.model.reportTypes[0]);
                that.reportStatus.show(that.model.reportTypeSelection);
            },
            reportFinished: function () {
                that.reportStatus.hide();
            },
            onError: function (message) {
                that.reportStatus.hide();
                that.messageBar.show(that.options.strings.reportError + message, null, true)
            },
            onStop: function (reportType) {
                that.applier.requestChange("reportTypeSelection", reportType);
                that.requestReport(true);
            }
        };
    };

    cspace.reportProducer.postInit = function (that) {
        that.reportLoadingIndicatorContainer = $("<div/>")
            .addClass(that.options.selectors.reportLoadingIndicatorContainer.substr(1))
            .addClass(that.options.styles.reportLoadingIndicatorContainer)
            .hide();
        $("body").append(that.reportLoadingIndicatorContainer);
    };

    cspace.reportProducer.finalInit = function (that) {
        that.refreshView();
        that.events.ready.fire();
    };

    cspace.reportProducer.requestReport = function (model, options, events, stop) {
        if (!stop) {
            events.reportStarted.fire();
        }
        fluid.fetchResources({
            report: {
                href: options.urls.reportUrl,
                options: {
                    type: "POST",
                    dataType: "json",
                    data: JSON.stringify({
                        recordType: options.recordType,
                        stop: stop,
                        reportType: model.reportTypeSelection
                    }),
                    success: function (data) {
                        events.reportFinished.fire();
                    },
                    error: function (xhr, textStatus, errorThrown) {
                        events.onError.fire(textStatus);
                    }
                }
            }
        });
    };

    cspace.reportProducer.generateReport = function (confirmation, strings, requestReport) {
        confirmation.open("cspace.confirmation.deleteDialog", undefined, {
            strings: {
                primaryMessage: strings.primaryMessage,
                actText: strings.actText,
                actAlt: strings.actAlt
            },
            listeners: {
                onClose: function (userAction) {
                    if (userAction === "act") {
                        requestReport(false);
                    }
                }
            }
        });
    };

    cspace.reportProducer.produceTree = function (that) {
        return {
            expander: {
                type: "fluid.renderer.condition",
                condition: "${enableReporting}",
                trueTree: {
                    report: {
                        decorators: {"addClass": "{styles}.report"}
                    }
                }
            },
            reportHeader: {
                messagekey: "reportHeader",
                decorators: {"addClass": "{styles}.reportHeader"}
            },
            reportType: {
                optionnames: "${reportTypes}",
                optionlist: "${reportTypes}",
                selection: "${reportTypeSelection}",
                decorators: {"addClass": "{styles}.reportType"}
            },
            reportButton: {
                decorators: [{
                    type: "attrs",
                    attributes: {
                        value: that.options.strings.reportButton
                    }
                }, {
                    addClass: "{styles}.reportButton"
                }, {
                    type: "jQuery",
                    func: "click",
                    args: that.generateReport
                }]
            }
        };
    };

    fluid.defaults("cspace.reportProducer.reportStatus", {
        gradeNames: ["fluid.rendererComponent", "autoInit"],
        resources: {
            template: cspace.resourceSpecExpander({
                fetchClass: "slowTemplate",
                url: "%webapp/html/components/ReportStatusTemplate.html",
                options: {
                    dataType: "html"
                }
            })
        },
        events: {
            onStop: null
        },
        produceTree: "cspace.reportProducer.reportStatus.produceTree",
        finalInitFunction: "cspace.reportProducer.reportStatus.finalInit",
        selectors: {
            message: ".csc-reportStatus-message",
            stop: ".csc-reportStatus-stop"
        },
        styles: {
            message: "cs-reportStatus-message",
            stop: "cs-reportStatus-stop"
        },
        strings: {
            message: "Creating %reportType report...",
            stop: "Stop"
        }
    });

    fluid.fetchResources.primeCacheFromResources("cspace.reportProducer.reportStatus");

    cspace.reportProducer.reportStatus.produceTree = function (that) {
        return {
            message: {
                messagekey: "message",
                args: {reportType: "${reportType}"},
                decorators: {"addClass": "{styles}.message"}
            },
            stop: {
                decorators: [{
                    type: "attrs",
                    attributes: {
                        value: that.options.strings.stop
                    }
                }, {
                    "addClass": "{styles}.stop"
                }, {
                    type: "jQuery",
                    func: "click",
                    args: function () {
                        that.events.onStop.fire(that.model.reportType);
                    }
                }]
            }
        };
    };
    cspace.reportProducer.reportStatus.finalInit = function (that) {
        that.show = function (reportType) {
            that.applier.requestChange("reportType", reportType);
            that.refreshView();
            that.container.show();
        };
        that.hide = function () {
            that.container.hide();
        }
    };

})(jQuery, fluid);<commit_msg>CSPACE-2438: Adding a confirmation when the user tries to navigate away from a page were report is generated.<commit_after>/*
Copyright 2011 Museum of Moving Image

Licensed under the Educational Community License (ECL), Version 2.0.
You may not use this file except in compliance with this License.

You may obtain a copy of the ECL 2.0 License at
https://source.collectionspace.org/collection-space/LICENSE.txt
*/

/*global cspace:true, jQuery, fluid, window*/
"use strict";

cspace = cspace || {};

(function ($, fluid) {

    fluid.defaults("cspace.reportProducer", {
        gradeNames: ["fluid.rendererComponent", "autoInit"],
        produceTree: "cspace.reportProducer.produceTree",
        invokers: {
            generateReport: {
                funcName: "cspace.reportProducer.generateReport",
                args: ["{reportProducer}.confirmation", "{reportProducer}.options.strings", "{reportProducer}.requestReport"]
            },
            requestReport: {
                funcName: "cspace.reportProducer.requestReport",
                args: ["{reportProducer}.model", "{reportProducer}.options", "{reportProducer}.events", "{arguments}.0", "{arguments}.1"]
            }
        },
        components: {
            confirmation: {
                type: "cspace.confirmation"
            },
            reportStatus: {
                type: "cspace.reportProducer.reportStatus",
                createOnEvent: "ready",
                container: "{reportProducer}.reportLoadingIndicatorContainer",
                options: {
                    events: {
                        onStop: "{reportProducer}.events.onStop"
                    }
                }
            },
            messageBar: "{messageBar}",
            globalNavigator: "{globalNavigator}"
        },
        events: {
            onError: null,
            onStop: null,
            reportStarted: null,
            reportFinished: null,
            ready: null
        },
        selectors: {
            reportHeader: ".csc-reportProducer-header",
            reportButton: ".csc-reportProducer-button",
            reportType: ".csc-reportProducer-type",
            report: ".csc-reportProducer",
            reportLoadingIndicatorContainer: ".csc-reportProducer-loadingIndicatorContainer"
        },
        selectorsToIgnore: ["reportLoadingIndicatorContainer"],
        strings: {
            reportHeader: "Create Report",
            reportButton: "Create",
            reportError: "Error creating report: ",
            primaryMessage: "Are you sure you want to run this report",
            actText: "Create",
            actAlt: "Create Report",
            stopPrimaryMessage: "You are about to navigate away from this page.",
            stopSecondaryMessage: "Do you want to stop current report?",
            stopActText: "Stop",
            stopActAlt: "Stop report."
        },
        styles: {
            reportHeader: "cs-reportProducer-header",
            reportButton: "cs-reportProducer-button",
            report: "cs-reportProducer",
            reportType: "cs-reportProducer-reportType",
            reportLoadingIndicatorContainer: "cs-reportProducer-loadingIndicator"
        },
        resources: {
            template: cspace.resourceSpecExpander({
                fetchClass: "fastTemplate",
                url: "%webapp/html/components/ReportProducerTemplate.html",
                options: {
                    dataType: "html"
                }
            })
        },
        model: {
            reportTypes: ["Please select a value"],
            reportTypeSelection: "",
            reportInProgress: false,
            enableReporting: {
                expander: {
                    type: "fluid.deferredInvokeCall",
                    func: "cspace.permissions.resolve",
                    args: {
                        resolver: "{permissionsResolver}",
                        permission: "read",
                        target: "reporting"
                    }
                }
            }
        },
        urls: cspace.componentUrlBuilder({
            reportUrl: "%chain/reporting"
        }),
        finalInitFunction: "cspace.reportProducer.finalInit",
        postInitFunction: "cspace.reportProducer.postInit",
        preInitFunction: "cspace.reportProducer.preInit"
    });

    cspace.reportProducer.getReportTypes = function (recordType, strategy, options) {
        var config = {
            strategies: [fluid.invokeGlobalFunction(strategy, [options])]
        };
        return fluid.makeArray(fluid.get({}, fluid.model.composeSegments("reporting", recordType), config));
    };

    fluid.fetchResources.primeCacheFromResources("cspace.reportProducer");

    cspace.reportProducer.preInit = function (that) {
        that.options.listeners = {
            reportStarted: function () {
                that.applier.requestChange("reportInProgress", true);
                that.applier.requestChange("reportTypeSelection", that.model.reportTypeSelection || that.model.reportTypes[0]);
                that.reportStatus.show(that.model.reportTypeSelection);
            },
            reportFinished: function () {
                that.applier.requestChange("reportInProgress", false);
                that.reportStatus.hide();
            },
            onError: function (message) {
                that.applier.requestChange("reportInProgress", false);
                that.reportStatus.hide();
                that.messageBar.show(that.options.strings.reportError + message, null, true)
            },
            onStop: function (reportType) {
                that.applier.requestChange("reportInProgress", false);
                that.applier.requestChange("reportTypeSelection", reportType);
                that.requestReport(true);
            }
        };
    };

    cspace.reportProducer.postInit = function (that) {
        that.reportLoadingIndicatorContainer = $("<div/>")
            .addClass(that.options.selectors.reportLoadingIndicatorContainer.substr(1))
            .addClass(that.options.styles.reportLoadingIndicatorContainer)
            .hide();
        $("body").append(that.reportLoadingIndicatorContainer);
    };

    cspace.reportProducer.finalInit = function (that) {
        that.refreshView();
        that.globalNavigator.events.onPerformNavigation.addListener(function (callback) {
            if (that.model.reportInProgress) {
                that.confirmation.open("cspace.confirmation.deleteDialog", undefined, {
                    strings: {
                        primaryMessage: that.options.strings.stopPrimaryMessage,
                        secondaryMessage: that.options.strings.stopSecondaryMessage,
                        actText: that.options.strings.stopActText,
                        actAlt: that.options.strings.stopActAlt
                    },
                    model: {
                        messages: ["primaryMessage", "secondaryMessage"]
                    },
                    listeners: {
                        onClose: function (userAction) {
                            if (userAction === "act") {
                                that.requestReport(true, callback);
                            }
                        }
                    }
                });
                return false;
            }
        });
        that.events.ready.fire();
    };

    cspace.reportProducer.requestReport = function (model, options, events, stop, callback) {
        if (!stop) {
            events.reportStarted.fire();
        }
        fluid.fetchResources({
            report: {
                href: options.urls.reportUrl,
                options: {
                    type: "POST",
                    dataType: "json",
                    data: JSON.stringify({
                        recordType: options.recordType,
                        stop: stop,
                        reportType: model.reportTypeSelection
                    }),
                    success: function (data) {
                        events.reportFinished.fire();
                        if (callback) {
                            callback();
                        }
                    },
                    error: function (xhr, textStatus, errorThrown) {
                        events.onError.fire(textStatus);
                    }
                }
            }
        });
    };

    cspace.reportProducer.generateReport = function (confirmation, strings, requestReport) {
        confirmation.open("cspace.confirmation.deleteDialog", undefined, {
            strings: {
                primaryMessage: strings.primaryMessage,
                actText: strings.actText,
                actAlt: strings.actAlt
            },
            listeners: {
                onClose: function (userAction) {
                    if (userAction === "act") {
                        requestReport(false);
                    }
                }
            }
        });
    };

    cspace.reportProducer.produceTree = function (that) {
        return {
            expander: {
                type: "fluid.renderer.condition",
                condition: "${enableReporting}",
                trueTree: {
                    report: {
                        decorators: {"addClass": "{styles}.report"}
                    }
                }
            },
            reportHeader: {
                messagekey: "reportHeader",
                decorators: {"addClass": "{styles}.reportHeader"}
            },
            reportType: {
                optionnames: "${reportTypes}",
                optionlist: "${reportTypes}",
                selection: "${reportTypeSelection}",
                decorators: {"addClass": "{styles}.reportType"}
            },
            reportButton: {
                decorators: [{
                    type: "attrs",
                    attributes: {
                        value: that.options.strings.reportButton
                    }
                }, {
                    addClass: "{styles}.reportButton"
                }, {
                    type: "jQuery",
                    func: "click",
                    args: that.generateReport
                }]
            }
        };
    };

    fluid.defaults("cspace.reportProducer.reportStatus", {
        gradeNames: ["fluid.rendererComponent", "autoInit"],
        resources: {
            template: cspace.resourceSpecExpander({
                fetchClass: "slowTemplate",
                url: "%webapp/html/components/ReportStatusTemplate.html",
                options: {
                    dataType: "html"
                }
            })
        },
        events: {
            onStop: null
        },
        produceTree: "cspace.reportProducer.reportStatus.produceTree",
        finalInitFunction: "cspace.reportProducer.reportStatus.finalInit",
        selectors: {
            message: ".csc-reportStatus-message",
            stop: ".csc-reportStatus-stop"
        },
        styles: {
            message: "cs-reportStatus-message",
            stop: "cs-reportStatus-stop"
        },
        strings: {
            message: "Creating %reportType report...",
            stop: "Stop"
        }
    });

    fluid.fetchResources.primeCacheFromResources("cspace.reportProducer.reportStatus");

    cspace.reportProducer.reportStatus.produceTree = function (that) {
        return {
            message: {
                messagekey: "message",
                args: {reportType: "${reportType}"},
                decorators: {"addClass": "{styles}.message"}
            },
            stop: {
                decorators: [{
                    type: "attrs",
                    attributes: {
                        value: that.options.strings.stop
                    }
                }, {
                    "addClass": "{styles}.stop"
                }, {
                    type: "jQuery",
                    func: "click",
                    args: function () {
                        that.events.onStop.fire(that.model.reportType);
                    }
                }]
            }
        };
    };
    cspace.reportProducer.reportStatus.finalInit = function (that) {
        that.show = function (reportType) {
            that.applier.requestChange("reportType", reportType);
            that.refreshView();
            that.container.show();
        };
        that.hide = function () {
            that.container.hide();
        }
    };

})(jQuery, fluid);<|endoftext|>


<commit_before>/*
 *   Initializes a new instance of the Renderer class.
 */
function Renderer(width, height) {
    this.width = width;
    this.height = height;

    var fragment = document.createDocumentFragment();
    var svg = this.createBackground();
    var canvas = this.creteCanvas();

    fragment.appendChild(svg);
    fragment.appendChild(canvas);
    document.body.appendChild(fragment);

    this.ctx = canvas.getContext('2d');
}

/*
 *   Draws all objects.
 */
Renderer.prototype.drawAll = function(blaze, eggman) {
    this.ctx.clearRect(0, 0, this.width, this.height);
    this.drawBlaze(blaze);
    this.drawClip(blaze);
    this.drawScore(blaze);

    if (eggman) {
        this.drawEggman(eggman);
    }
};

/*
 *   Constants for the game object.
 */
Renderer.CONFIG = function() {
    var constants = {
        BLAZE_LINE_LENGTH: 60,
        BLAZE_INNER_RADIUS: 10,
        BLAZE_OUTER_RADIUS: 20,
        BLAZE_COLOR: 'white',
        SVG_NS: 'http://www.w3.org/2000/svg',
        BULLET_WIDTH: 20,
        BULLET_HEIGHT: 30,
        BULLET_SPACING: 5,
        BACKGROUND_COLOR: '#181e4b',
        BACKGROUND_STARS_COUNT: 50,
        BACKGROUND_PLANETS_COUNT: 5
    };

    return {
        get: function(name) {
            return constants[name];
        }
    };
}();

/*
 *   Draws Blaze.
 */
Renderer.prototype.drawBlaze = function(blaze) {

    var LINE_LENGTH = Renderer.CONFIG.get('BLAZE_LINE_LENGTH');
    var INNER_RADIUS = Renderer.CONFIG.get('BLAZE_INNER_RADIUS');
    var OUTER_RADIUS = Renderer.CONFIG.get('BLAZE_OUTER_RADIUS');

    var centerX = blaze.position.x;
    var centerY = blaze.position.y;

    var point1X = centerX + LINE_LENGTH / 2;
    var point1Y = centerY;

    var point2X = centerX - LINE_LENGTH / 2;
    var point2Y = centerY;

    var point3X = centerX;
    var point3Y = centerY + LINE_LENGTH / 2;

    var point4X = centerX;
    var point4Y = centerY - LINE_LENGTH / 2;

    this.ctx.beginPath();
    this.ctx.moveTo(point1X, point1Y);
    this.ctx.lineTo(point2X, point2Y);
    this.ctx.moveTo(point3X, point3Y);
    this.ctx.lineTo(point4X, point4Y);
    this.ctx.moveTo(centerX, centerY);
    this.ctx.arc(centerX, centerY, INNER_RADIUS, 0, 2 * Math.PI, false);
    this.ctx.moveTo(centerX, centerY);
    this.ctx.arc(centerX, centerY, OUTER_RADIUS, 0, 2 * Math.PI, false);
    this.ctx.strokeStyle = Renderer.CONFIG.get('BLAZE_COLOR');
    this.ctx.stroke();
};

/*
 *   Draws the clip (available bullets).
 */
Renderer.prototype.drawClip = function(blaze) {
    var sx = 20;
    var sy = this.height - Renderer.CONFIG.get('BULLET_HEIGHT') - sx;
    var bulletsCount = blaze.bullets;
    var image = new Image();
    image.src = 'resources/imgs/bullet.png';

    for (var i = 0; i < bulletsCount; i += 1) {
        this.ctx.drawImage(image, sx, sy);
        sx += Renderer.CONFIG.get('BULLET_WIDTH') + Renderer.CONFIG.get('BULLET_SPACING');
    }
};

/*
 *   Draws Eggman.
 */
Renderer.prototype.drawEggman = function(eggman) {
    var eggmanTopLeftX = eggman.position.x;
    var eggmanTopLeftY = eggman.position.y;
    this.ctx.strokeStyle = 'green';
    this.ctx.strokeRect(eggmanTopLeftX, eggmanTopLeftY, eggman.width, eggman.height);
};

/*
 *   Creates the background.
 */
Renderer.prototype.createBackground = function() {
    // Creates the svg element
    var svg = document.createElementNS(Renderer.CONFIG.get('SVG_NS'), 'svg');
    svg.setAttribute('height', this.height.toString());
    svg.setAttribute('width', this.width.toString());
    svg.style.position = 'fixed';
    svg.style.top = '31px';
    svg.style.left = '31px';

    // Sets the background color.
    var rect = document.createElementNS(Renderer.CONFIG.get('SVG_NS'), 'rect');
    rect.setAttribute('x', '0');
    rect.setAttribute('y', '0');
    rect.setAttribute('width', this.width.toString());
    rect.setAttribute('height', this.height.toString());
    var backgroundColorText = 'fill:' + Renderer.CONFIG.get('BACKGROUND_COLOR') + ';';
    rect.setAttribute('style', backgroundColorText);
    svg.appendChild(rect);

    var rectAmmo = document.createElementNS(Renderer.CONFIG.get('SVG_NS'), 'rect');
    rectAmmo.setAttribute('x', '15');
    rectAmmo.setAttribute('y', (this.height - 55).toString());
    rectAmmo.setAttribute('width', (20 * 3 + 10 * 2 + 10).toString());
    rectAmmo.setAttribute('height', '40');

    rectAmmo.setAttribute('style', 'fill: #dcdcdc;');

    svg.appendChild(rectAmmo);

    // Creates the stars
    var starsCount = Renderer.CONFIG.get('BACKGROUND_STARS_COUNT');

    for (var i = 0; i < starsCount; i++) {
        svg.appendChild(this.createRandomStar());
    }

    // Creates the planets
    var planetsCount = Renderer.CONFIG.get('BACKGROUND_PLANETS_COUNT');

    for (i = 0; i < planetsCount; i++) {
        svg.appendChild(this.createRandomPlanet());
    }

    return svg;
};

Renderer.prototype.creteCanvas = function() {
    var canvas = document.createElement('canvas');
    canvas.setAttribute('id', 'drawing');
    canvas.setAttribute('width', this.width.toString());
    canvas.setAttribute('height', this.height.toString());
    canvas.style.position = 'fixed';
    canvas.style.left = '30px';
    canvas.style.top = '30px';
    return canvas;
};

/*
 *   Creates a random star.
 */
Renderer.prototype.createRandomStar = function() {
    var polygon = document.createElementNS(Renderer.CONFIG.get('SVG_NS'), 'polygon');

    var x = getRandomInt(50, this.width - 50);
    var y = getRandomInt(50, this.height - 50);

    var point1X = x + 2.9389;
    var point1Y = y + 9.0451;

    var point2X = x + 4.7553;
    var point2Y = y + 3.4549;

    var point3X = x - 4.7553;
    var point3Y = y + 3.4549;

    var point4X = x - 2.9389;
    var point4Y = y + 9.0451;

    var pointsText = x + ',' + y + ' ' + point1X + ',' + point1Y + ' ' + point3X + ',' + point3Y + ' ' + point2X + ',' + point2Y + ' ' + point4X + ',' + point4Y;
    polygon.setAttribute('points', pointsText);
    polygon.setAttribute('style', 'fill:#dcdcdc');

    var angle = getRandomInt(0, 360);
    var rotateText = 'rotate(' + angle + ' ' + x + ' ' + y + ')';
    polygon.setAttribute('transform', rotateText.toString());

    return polygon;
};

/*
 *   Creates a random planet.
 */
Renderer.prototype.createRandomPlanet = function() {
    var circle = document.createElementNS(Renderer.CONFIG.get('SVG_NS'), 'circle');
    var cx = getRandomInt(50, this.width - 50);
    var cy = getRandomInt(50, this.height - 50);
    var radius = 10;
    circle.setAttribute('cx', cx.toString());
    circle.setAttribute('cy', cy.toString());
    circle.setAttribute('r', radius.toString());
    circle.setAttribute('fill', '#dd5f22');
    return circle;
};

/*
 *   Draws the score.
 */
Renderer.prototype.drawScore = function(blaze) {
    var scoreText = "Score: " + (blaze.score | 0); //todo: add blaze score
    this.ctx.font = "30px Comic Sans MS, Arial, Sans";
    this.ctx.fillStyle = '#dcdcdc';
    this.ctx.fillText(scoreText, 10, 30);
};

/*
 *   Draws the Intro screen.
 */
Renderer.prototype.drawIntro = function() {

};

/*
 *   Draws the Exit screen
 */
Renderer.prototype.drawExit = function() {

};

<commit_msg>Adding background to  level 1<commit_after>/*
 *   Initializes a new instance of the Renderer class.
 */
function Renderer(width, height) {
    this.width = width;
    this.height = height;

    var fragment = document.createDocumentFragment();
    var svg = this.createBackground();
    var canvas = this.creteCanvas();

    fragment.appendChild(svg);
    fragment.appendChild(canvas);
    document.body.appendChild(fragment);

    this.ctx = canvas.getContext('2d');
}

/*
 *   Draws all objects.
 */
Renderer.prototype.drawAll = function(blaze, eggman) {
    this.ctx.clearRect(0, 0, this.width, this.height);
    this.drawBlaze(blaze);
    this.drawClip(blaze);
    this.drawScore(blaze);

    if (eggman) {
        this.drawEggman(eggman);
    }
};

/*
 *   Constants for the game object.
 */
Renderer.CONFIG = function() {
    var constants = {
        BLAZE_LINE_LENGTH: 60,
        BLAZE_INNER_RADIUS: 10,
        BLAZE_OUTER_RADIUS: 20,
        BLAZE_COLOR: 'white',
        SVG_NS: 'http://www.w3.org/2000/svg',
        BULLET_WIDTH: 20,
        BULLET_HEIGHT: 30,
        BULLET_SPACING: 5,
        BACKGROUND_COLOR: '#181e4b',
        BACKGROUND_STARS_COUNT: 50,
        BACKGROUND_PLANETS_COUNT: 5
    };

    return {
        get: function(name) {
            return constants[name];
        }
    };
}();

/*
 *   Draws Blaze.
 */
Renderer.prototype.drawBlaze = function(blaze) {

    var LINE_LENGTH = Renderer.CONFIG.get('BLAZE_LINE_LENGTH');
    var INNER_RADIUS = Renderer.CONFIG.get('BLAZE_INNER_RADIUS');
    var OUTER_RADIUS = Renderer.CONFIG.get('BLAZE_OUTER_RADIUS');

    var centerX = blaze.position.x;
    var centerY = blaze.position.y;

    var point1X = centerX + LINE_LENGTH / 2;
    var point1Y = centerY;

    var point2X = centerX - LINE_LENGTH / 2;
    var point2Y = centerY;

    var point3X = centerX;
    var point3Y = centerY + LINE_LENGTH / 2;

    var point4X = centerX;
    var point4Y = centerY - LINE_LENGTH / 2;

    this.ctx.beginPath();
    this.ctx.moveTo(point1X, point1Y);
    this.ctx.lineTo(point2X, point2Y);
    this.ctx.moveTo(point3X, point3Y);
    this.ctx.lineTo(point4X, point4Y);
    this.ctx.moveTo(centerX, centerY);
    this.ctx.arc(centerX, centerY, INNER_RADIUS, 0, 2 * Math.PI, false);
    this.ctx.moveTo(centerX, centerY);
    this.ctx.arc(centerX, centerY, OUTER_RADIUS, 0, 2 * Math.PI, false);
    this.ctx.strokeStyle = Renderer.CONFIG.get('BLAZE_COLOR');
    this.ctx.stroke();
};

/*
 *   Draws the clip (available bullets).
 */
Renderer.prototype.drawClip = function(blaze) {
    var sx = 20;
    var sy = this.height - Renderer.CONFIG.get('BULLET_HEIGHT') - sx;
    var bulletsCount = blaze.bullets;
    var image = new Image();
    image.src = 'resources/imgs/bullet.png';

    for (var i = 0; i < bulletsCount; i += 1) {
        this.ctx.drawImage(image, sx, sy);
        sx += Renderer.CONFIG.get('BULLET_WIDTH') + Renderer.CONFIG.get('BULLET_SPACING');
    }
};

/*
 *   Draws Eggman.
 */
Renderer.prototype.drawEggman = function(eggman) {
    var eggmanTopLeftX = eggman.position.x;
    var eggmanTopLeftY = eggman.position.y;
    this.ctx.strokeStyle = 'green';
    this.ctx.strokeRect(eggmanTopLeftX, eggmanTopLeftY, eggman.width, eggman.height);
};

/*
 *   Creates the background.
 */
Renderer.prototype.createBackground = function() {
    // Creates the svg element
    var svg = document.createElementNS(Renderer.CONFIG.get('SVG_NS'), 'svg');
    svg.setAttribute('height', this.height.toString());
    svg.setAttribute('width', this.width.toString());
    svg.style.position = 'fixed';
    svg.style.top = '31px';
    svg.style.left = '31px';

    // Sets the background color.
    var rect = document.createElementNS(Renderer.CONFIG.get('SVG_NS'), 'rect');
    rect.setAttribute('x', '0');
    rect.setAttribute('y', '0');
    rect.setAttribute('width', this.width.toString());
    rect.setAttribute('height', this.height.toString());
    var backgroundColorText = 'fill:' + Renderer.CONFIG.get('BACKGROUND_COLOR') + ';';
    rect.setAttribute('style', backgroundColorText);
    svg.appendChild(rect);

    var rectAmmo = document.createElementNS(Renderer.CONFIG.get('SVG_NS'), 'rect');
    rectAmmo.setAttribute('x', '15');
    rectAmmo.setAttribute('y', (this.height - 55).toString());
    rectAmmo.setAttribute('width', (20 * 3 + 10 * 2 + 10).toString());
    rectAmmo.setAttribute('height', '40');

    rectAmmo.setAttribute('style', 'fill: #dcdcdc;');

    svg.appendChild(rectAmmo);

    // Creates the stars
    var starsCount = Renderer.CONFIG.get('BACKGROUND_STARS_COUNT');

    for (var i = 0; i < starsCount; i++) {
        svg.appendChild(this.createRandomStar());
    }

    // Creates the planets
    var planetsCount = Renderer.CONFIG.get('BACKGROUND_PLANETS_COUNT');

    for (i = 0; i < planetsCount; i++) {
        svg.appendChild(this.createRandomPlanet());
    }

    return svg;
};

Renderer.prototype.creteCanvas = function() {
    var canvas = document.createElement('canvas');
    canvas.setAttribute('id', 'drawing');
    canvas.setAttribute('width', this.width.toString());
    canvas.setAttribute('height', this.height.toString());
    canvas.style.position = 'fixed';
    canvas.style.left = '30px';
    canvas.style.top = '30px';
    return canvas;
};

/*
 *   Creates a random star.
 */
Renderer.prototype.createRandomStar = function() {
    var polygon = document.createElementNS(Renderer.CONFIG.get('SVG_NS'), 'polygon');

    var x = getRandomInt(50, this.width - 50);
    var y = getRandomInt(50, this.height - 50);

    var point1X = x + 2.9389;
    var point1Y = y + 9.0451;

    var point2X = x + 4.7553;
    var point2Y = y + 3.4549;

    var point3X = x - 4.7553;
    var point3Y = y + 3.4549;

    var point4X = x - 2.9389;
    var point4Y = y + 9.0451;

    var pointsText = x + ',' + y + ' ' + point1X + ',' + point1Y + ' ' + point3X + ',' + point3Y + ' ' + point2X + ',' + point2Y + ' ' + point4X + ',' + point4Y;
    polygon.setAttribute('points', pointsText);
    polygon.setAttribute('style', 'fill:#dcdcdc');

    var angle = getRandomInt(0, 360);
    var rotateText = 'rotate(' + angle + ' ' + x + ' ' + y + ')';
    polygon.setAttribute('transform', rotateText.toString());

    return polygon;
};

/*
 *   Creates a random planet.
 */
Renderer.prototype.createRandomPlanet = function() {
    var circle = document.createElementNS(Renderer.CONFIG.get('SVG_NS'), 'circle');
    var cx = getRandomInt(50, this.width - 50);
    var cy = getRandomInt(50, this.height - 50);
    var radius = 10;
    circle.setAttribute('cx', cx.toString());
    circle.setAttribute('cy', cy.toString());
    circle.setAttribute('r', radius.toString());
    circle.setAttribute('fill', '#dd5f22');
    return circle;
};

/*
 *   Draws the score.
 */
Renderer.prototype.drawScore = function(blaze) {
    var scoreText = "Score: " + (blaze.score | 0); //todo: add blaze score
    this.ctx.font = "30px Comic Sans MS, Arial, Sans";
    this.ctx.fillStyle = '#dcdcdc';
    this.ctx.fillText(scoreText, 10, 30);
};

/*
 *   Draws the Intro screen.
 */
Renderer.prototype.drawIntro = function() {

};

/*
 *   Draws the Exit screen
 */
Renderer.prototype.drawExit = function() {

};

Renderer.prototype.drawB1 = function () {

    var paper = Raphael(container, 800, 600);
    var x = 0,
    y = 0;

    /*Draw background - sky*/

    paper.rect(x, y, 800, 600)
    .attr({
        fill: 'lightblue',
        'stroke-width': 0
    });

    /* Draw sand.*/

    paper.rect(x, (y + 400), 800, 200)
    .attr({
        fill: '100-darkgoldenrod-gold',
        opacity: 0.8,
        'stroke-width': 0
    });

    /* Draw sea. */
    paper.rect(0, 350, 800, 50)
    .attr({
        fill: '100-blue:2-darkblue:100',
        opacity: 1,
        'stroke-width': 3,
        stroke: '40-blue-darkblue',
        'stroke-linecap': 'round'
    });

    /*
    *   Draw waves.
    */
    paper.path('M 0 400 C 50 450 150 400 170 400 C 170 400 380 470 450 400  C 450 400 570 440 650 400 C 650 400 700 450 800 400 Z')
    .attr({
        fill: '90-white-blue',
        opacity: 0.9,
        stroke: '90-#000f48-#ffffff',
        'stroke-width': 5,
        'stroke-linecap': 'round',
        'stroke-linejoin': 'round'
    });

    /*Draw cloud.*/

    paper.path('M700 50 C 720 70 710 100 690 90 C 680 110 660 95 650 90 C 630 100 620 90 650 70 C 620 60 655 50 660 45 C 675 35 680 45 690 40 Z')
    .attr({
        fill: '270-white-azure',
        opacity: 0.2,
        stroke: '100-gray-white-blue',
        'stroke-width': 5,
        'stroke-linecap': 'round',
        'stroke-linejoin': 'round'

    });

    /* Draw mountains */

    paper.path("M" + (x - 10) + "," + (y + 350)
        + "C" + (x + 130) + "," + (y + 100) + "," + (x + 260) + "," + (y + 340) + "," + (x + 300) + "," + (y + 320)
        + "C" + (x + 300) + "," + (y + 320) + "," + (x + 350) + "," + (y + 280) + "," + (x + 400) + "," + (y + 310)
        + "C" + (x + 400) + "," + (y + 310) + "," + (x + 530) + "," + (y + 280) + "," + (x + 630) + "," + (y + 320)
        + "C" + (x + 630) + "," + (y + 320) + "," + (x + 900) + "," + (y + 20) + "," + (x + 800) + "," + (y + 350)
        + "Z")
    //paper.path("M"+(x -10) 350 C 130 100 260 340 300 320 C 300 320 350 280 400 310 C 400 310 530 280 630 320 C 630 320 900 20 800 350 Z ')
    .attr({
        fill: "100-darkgreen-white",
        opacity: 0.1,
        stroke: "100-darkgreen-white",
        'stroke-width': 5,
        'stroke-linecap': 'round',
        'stroke-linejoin': 'round'
    })
    /* */
    paper.path("M" + (x + 50) + "," + (y + 50) + " L" + (x + 100) + "," + (y + 100));

};

<|endoftext|>


<commit_before>/**
 * This work is provided under the terms of the CREATIVE COMMONS PUBLIC
 * LICENSE. This work is protected by copyright and/or other applicable
 * law. Any use of the work other than as authorized under this license
 * or copyright law is prohibited.
 *
 * http://creativecommons.org/licenses/by-nc-sa/2.5/
 *
 * © 2011 Open-Xchange Inc., Tarrytown, NY, USA. info@open-xchange.com
 *
 * @author Viktor Pracht <viktor.pracht@open-xchange.com>
 * @author Julian Bäume <julian.baeume@open-xchange.com>
 */

'use strict';

(function (module) {
    var fs = require('fs');
    var url = require('url');
    var path = require('path');
    var mime = require('connect').static.mime;

    function charset(type) {
        var t = mime.charsets.lookup(type);
        return t ? ';charset=' + t : '';
    }

    function create(options) {
        var verbose = options.verbose;
        var prefixes = options.prefixes;

        return function (request, response, next) {
            if ('GET' != request.method && 'HEAD' != request.method) {
                return next();
            }
            var pathname = url.parse(request.url).pathname,
                filename,
                type;

            if (/\/appsuite\/api\//.test(pathname)) {
                return next();
            }
            pathname = pathname.slice(pathname.indexOf('/apps/'));
            pathname = pathname.replace(/^v=[^\/]+\//, '');
            pathname = pathname.replace(/^$/, 'core');
            filename = prefixes.map(function (p) {
                return path.join(p, pathname);
            })
            .filter(function (filename) {
                return (path.existsSync(filename) && fs.statSync(filename).isFile());
            })[0];
            if (!filename) {
                if (verbose.local) console.log('localfile not found: ', pathname);
                return next();
            }

            if (pathname === 'core' || pathname === 'signin') {
                type = 'text/html';
            } else {
                type = mime.lookup(filename);
            }
            // set headers
            if (verbose.local) console.log(filename);
            response.setHeader('Content-Type', type + charset(type));
            response.setHeader('Expires', '0');
            response.write(fs.readFileSync(filename));
            response.end();
            return true;
        };
    }

    module.exports = {
        create: create
    };
}(module));
<commit_msg>fixup for 0904dfee8f: fix loading of localfiles from tests<commit_after>/**
 * This work is provided under the terms of the CREATIVE COMMONS PUBLIC
 * LICENSE. This work is protected by copyright and/or other applicable
 * law. Any use of the work other than as authorized under this license
 * or copyright law is prohibited.
 *
 * http://creativecommons.org/licenses/by-nc-sa/2.5/
 *
 * © 2011 Open-Xchange Inc., Tarrytown, NY, USA. info@open-xchange.com
 *
 * @author Viktor Pracht <viktor.pracht@open-xchange.com>
 * @author Julian Bäume <julian.baeume@open-xchange.com>
 */

'use strict';

(function (module) {
    var fs = require('fs');
    var url = require('url');
    var path = require('path');
    var mime = require('connect').static.mime;

    function charset(type) {
        var t = mime.charsets.lookup(type);
        return t ? ';charset=' + t : '';
    }

    function create(options) {
        var verbose = options.verbose;
        var prefixes = options.prefixes;

        return function (request, response, next) {
            if ('GET' != request.method && 'HEAD' != request.method) {
                return next();
            }
            var pathname = url.parse(request.url).pathname,
                filename,
                type;

            if (/\/appsuite\/api\//.test(pathname)) {
                return next();
            }

            //remove base directories (only /appsuite/ and /base/)
            //TODO: handle custom base directories (?)
            pathname = pathname.replace(/^\/appsuite\//, '/')
            pathname = pathname.replace(/^\/base\//, '/')

            pathname = pathname.replace(/^\/v=[^\/]+\//, '/');
            pathname = pathname.replace(/^\/$/, '/core');
            filename = prefixes.map(function (p) {
                return path.join(p, pathname);
            })
            .filter(function (filename) {
                return (path.existsSync(filename) && fs.statSync(filename).isFile());
            })[0];
            if (!filename) {
                if (verbose.local) console.log('localfile not found: ', pathname);
                return next();
            }

            if (pathname === '/core' || pathname === '/signin') {
                type = 'text/html';
            } else {
                type = mime.lookup(filename);
            }
            // set headers
            if (verbose.local) console.log(filename);
            response.setHeader('Content-Type', type + charset(type));
            response.setHeader('Expires', '0');
            response.write(fs.readFileSync(filename));
            response.end();
            return true;
        };
    }

    module.exports = {
        create: create
    };
}(module));
<|endoftext|>


<commit_before>/*
 * L.Mixin.Events is used to add custom events functionality to Leaflet classes.
 */

var key = '_leaflet_events';

L.Mixin = {};

L.Mixin.Events = {

	addEventListener: function (types, fn, context) { // (String, Function[, Object]) or (Object[, Object])

		var events = this[key] = this[key] || {},
		    contextId = context && L.stamp(context),
		    type, i, len, evt,
		    objKey, objLenKey, eventsObj;

		// types can be a map of types/handlers
		if (typeof types === 'object') {
			for (type in types) {
				if (types.hasOwnProperty(type)) {
					this.addEventListener(type, types[type], fn);
				}
			}

			return this;
		}

		// types can be a string of space-separated words
		types = L.Util.splitWords(types);

		for (i = 0, len = types.length; i < len; i++) {
			evt = {
				action: fn,
				context: context || this
			};

			if (contextId) {
				// store listeners of a particular context in a separate hash (if it has an id)
				// gives a major performance boost when removing thousands of map layers

				objKey = types[i] + '_idx',
				objLenKey = objKey + '_len',
				eventsObj = events[objKey] = events[objKey] || {};

				if (eventsObj[contextId]) {
					eventsObj[contextId].push(evt);
				} else {
					eventsObj[contextId] = [evt];
					events[objLenKey] = (events[objLenKey] || 0) + 1;
				}

			} else {
				events[types[i]] = events[types[i]] || [];
				events[types[i]].push(evt);
			}
		}

		return this;
	},

	hasEventListeners: function (type) { // (String) -> Boolean
		return (key in this) &&
		       (((type in this[key]) && this[key][type].length > 0) ||
		        (this[key][type + '_idx_len'] > 0));
	},

	removeEventListener: function (types, fn, context) { // (String[, Function, Object]) or (Object[, Object])
		var events = this[key],
		    contextId = context && L.stamp(context),
		    type, i, len, listeners, j,
		    objKey, objLenKey;

		if (typeof types === 'object') {
			for (type in types) {
				if (types.hasOwnProperty(type)) {
					this.removeEventListener(type, types[type], fn);
				}
			}
			return this;
		}

		types = L.Util.splitWords(types);

		for (i = 0, len = types.length; i < len; i++) {
			if (this.hasEventListeners(types[i])) {

				objKey = types[i] + '_idx';

				if (contextId && events[objKey]) {
					listeners =  events[objKey][contextId] || [];
				} else {
					listeners = events[types[i]] || [];
				}

				for (j = listeners.length - 1; j >= 0; j--) {
					if ((!fn || listeners[j].action === fn) && (!context || (listeners[j].context === context))) {
						listeners.splice(j, 1);
					}
				}

				if (contextId && listeners.length === 0 && events[objKey] && events[objKey][contextId]) {
					objLenKey = objKey + '_len';
					delete events[objKey][contextId];
					events[objLenKey] = (events[objLenKey] || 1) - 1;
				}
			}
		}

		return this;
	},

	fireEvent: function (type, data) { // (String[, Object])
		if (!this.hasEventListeners(type)) {
			return this;
		}

		var event = L.Util.extend({}, data, { type: type, target: this });

		var listeners, i, len, eventsObj, contextId;

		if (this[key][type]) {
			listeners = this[key][type].slice();

			for (i = 0, len = listeners.length; i < len; i++) {
				listeners[i].action.call(listeners[i].context || this, event);
			}
		}

		// fire event for the context-indexed listeners as well

		eventsObj = this[key][type + '_idx'];

		if (eventsObj) {
			for (contextId in eventsObj) {
				if (eventsObj.hasOwnProperty(contextId)) {
					listeners = eventsObj[contextId];
					if (listeners) {
						for (i = 0, len = listeners.length; i < len; i++) {
							listeners[i].action.call(listeners[i].context || this, event);
						}
					}
				}
			}
		}

		return this;
	},

	once: function(types, fn, context) {
	    var handlerFor = function (fn, type, context) {
	        var handler = function () {
	            this.removeEventListener(type, fn, context);
	            this.removeEventListener(type, handler, context);
	        }
	        return handler;
	    }

	    if (typeof types === 'object') {
	        for (type in types) {
	            if (types.hasOwnProperty(type)) {
	                this.addEventListener(type, types[type], fn);
	                this.addEventListener(type, handlerFor(types[type], type, fn), fn);
	            }
	        }
	        return this;
	    }

	    this.addEventListener(types, fn, context);
	    return this.addEventListener(types, handlerFor(fn, types, context), context);
	}
};

L.Mixin.Events.on = L.Mixin.Events.addEventListener;
L.Mixin.Events.off = L.Mixin.Events.removeEventListener;
L.Mixin.Events.fire = L.Mixin.Events.fireEvent;
<commit_msg>fixing jshint errors<commit_after>/*
 * L.Mixin.Events is used to add custom events functionality to Leaflet classes.
 */

var key = '_leaflet_events';

L.Mixin = {};

L.Mixin.Events = {

	addEventListener: function (types, fn, context) { // (String, Function[, Object]) or (Object[, Object])

		var events = this[key] = this[key] || {},
		    contextId = context && L.stamp(context),
		    type, i, len, evt,
		    objKey, objLenKey, eventsObj;

		// types can be a map of types/handlers
		if (typeof types === 'object') {
			for (type in types) {
				if (types.hasOwnProperty(type)) {
					this.addEventListener(type, types[type], fn);
				}
			}

			return this;
		}

		// types can be a string of space-separated words
		types = L.Util.splitWords(types);

		for (i = 0, len = types.length; i < len; i++) {
			evt = {
				action: fn,
				context: context || this
			};

			if (contextId) {
				// store listeners of a particular context in a separate hash (if it has an id)
				// gives a major performance boost when removing thousands of map layers

				objKey = types[i] + '_idx',
				objLenKey = objKey + '_len',
				eventsObj = events[objKey] = events[objKey] || {};

				if (eventsObj[contextId]) {
					eventsObj[contextId].push(evt);
				} else {
					eventsObj[contextId] = [evt];
					events[objLenKey] = (events[objLenKey] || 0) + 1;
				}

			} else {
				events[types[i]] = events[types[i]] || [];
				events[types[i]].push(evt);
			}
		}

		return this;
	},

	hasEventListeners: function (type) { // (String) -> Boolean
		return (key in this) &&
		       (((type in this[key]) && this[key][type].length > 0) ||
		        (this[key][type + '_idx_len'] > 0));
	},

	removeEventListener: function (types, fn, context) { // (String[, Function, Object]) or (Object[, Object])
		var events = this[key],
		    contextId = context && L.stamp(context),
		    type, i, len, listeners, j,
		    objKey, objLenKey;

		if (typeof types === 'object') {
			for (type in types) {
				if (types.hasOwnProperty(type)) {
					this.removeEventListener(type, types[type], fn);
				}
			}
			return this;
		}

		types = L.Util.splitWords(types);

		for (i = 0, len = types.length; i < len; i++) {
			if (this.hasEventListeners(types[i])) {

				objKey = types[i] + '_idx';

				if (contextId && events[objKey]) {
					listeners =  events[objKey][contextId] || [];
				} else {
					listeners = events[types[i]] || [];
				}

				for (j = listeners.length - 1; j >= 0; j--) {
					if ((!fn || listeners[j].action === fn) && (!context || (listeners[j].context === context))) {
						listeners.splice(j, 1);
					}
				}

				if (contextId && listeners.length === 0 && events[objKey] && events[objKey][contextId]) {
					objLenKey = objKey + '_len';
					delete events[objKey][contextId];
					events[objLenKey] = (events[objLenKey] || 1) - 1;
				}
			}
		}

		return this;
	},

	fireEvent: function (type, data) { // (String[, Object])
		if (!this.hasEventListeners(type)) {
			return this;
		}

		var event = L.Util.extend({}, data, { type: type, target: this });

		var listeners, i, len, eventsObj, contextId;

		if (this[key][type]) {
			listeners = this[key][type].slice();

			for (i = 0, len = listeners.length; i < len; i++) {
				listeners[i].action.call(listeners[i].context || this, event);
			}
		}

		// fire event for the context-indexed listeners as well

		eventsObj = this[key][type + '_idx'];

		if (eventsObj) {
			for (contextId in eventsObj) {
				if (eventsObj.hasOwnProperty(contextId)) {
					listeners = eventsObj[contextId];
					if (listeners) {
						for (i = 0, len = listeners.length; i < len; i++) {
							listeners[i].action.call(listeners[i].context || this, event);
						}
					}
				}
			}
		}

		return this;
	},

	once: function (types, fn, context) {
	    var handlerFor = function (fn, type, context) {
	        var handler = function () {
	            this.removeEventListener(type, fn, context);
	            this.removeEventListener(type, handler, context);
	        };
	        return handler;
	    };

	    if (typeof types === 'object') {
	        for (var type in types) {
	            if (types.hasOwnProperty(type)) {
	                this.addEventListener(type, types[type], fn);
	                this.addEventListener(type, handlerFor(types[type], type, fn), fn);
	            }
	        }
	        return this;
	    }

	    this.addEventListener(types, fn, context);
	    return this.addEventListener(types, handlerFor(fn, types, context), context);
	}
};

L.Mixin.Events.on = L.Mixin.Events.addEventListener;
L.Mixin.Events.off = L.Mixin.Events.removeEventListener;
L.Mixin.Events.fire = L.Mixin.Events.fireEvent;
<|endoftext|>


<commit_before>/**
 * @module animation
 */

modules.define('animation', ['i-bem-dom'], function(provide, bemDom) {
  /**
   * @exports
   * @class animation
   * @bem
   */
  provide(bemDom.declBlock(this.name, /** @lends animation.prototype */ {
    /**
     * Animation Start Event
     */
    _onStart: function() {
      this._emit('start');
    },

    /**
    * Animation End Event
    */
    _onEnd: function() {
      this._emit('end');
    },

    /**
    * Animation Iteration Event
    */
    _onIteration: function() {
      this._emit('iteration');
    }
  }, /** @lends animation */ {
    lazyInit: true,
    onInit: function() {
      let animationEnd = [
        'animationend',
        'oanimationend',
        'webkitAnimationEnd',
        'MSAnimationEnd'
      ];
      let animationStart = [
        'animationstart',
        'oanimationstart',
        'webkitAnimationStart',
        'MSAnimationStart'
      ];
      let animationIteration = [
        'animationiteration',
        'oanimationiteration',
        'webkitAnimationIteration',
        'MSAnimationIteration'
      ];

      this._domEvents()
        .on(animationEnd.join(' '), this.prototype._onEnd)
        .on(animationStart.join(' '), this.prototype._onStart)
        .on(animationIteration.join(' '), this.prototype._onIteration);
      return this.__base.apply(this, arguments);
    }
  }));
});
<commit_msg>Add API: start method<commit_after>/**
 * @module animation
 */

modules.define('animation', ['i-bem-dom'], function(provide, bemDom) {
  /**
   * @exports
   * @class animation
   * @bem
   */
  provide(bemDom.declBlock(this.name, /** @lends animation.prototype */ {

    /**
     * Start animation
     * @param  {String}   type     name of type animation
     * @param  {Function} callback callback for events
     * @param  {Boolean}  hide     flag for hide
     * @return {Bem}               block instance
     */
    start: function(type, callback, hide) {
      this.domElem.show();
      this.setMod('type', type);

      if (callback === undefined) {
        return this;
      }

      if (callback.constructor === Boolean) {
        hide = callback;
      }

      if (callback.constructor === Function) {
        this._singleEvent(this._prefixed('AnimationEnd'), callback, hide);
        return this;
      }

      if (callback.constructor === Object) {
        if (callback.onStart) {
          this._singleEvent(this._prefixed('AnimationStart'), callback.onStart, hide);
        }
        if (callback.onEnd) {
          this._singleEvent(this._prefixed('AnimationEnd'), callback.onEnd, hide);
        }
        if (callback.onIteration) {
          this._singleEvent(this._prefixed('AnimationIteration'), callback.onIteration, hide);
        }

        return this;
      }

      // default behavior
      this._singleEvent(this._prefixed('AnimationEnd'), false, hide);
      return this;
    },

    /**
     * Function for run sindle event
     * @param  {String}   event    target event
     * @param  {Function} callback callback function
     * @param  {Boolean}  hide     flag for hide block
     * @return {Bem}               block instance
     */
    _singleEvent: function(event, callback, hide) {
      this.domElem.on(event, () => {
        this.domElem.off(event);
        if (hide === true) {
          this.domElem.hide();
        }
        if (callback.constructor === Function) {
          callback();
        }
      });
      return this;
    },

    /**
     * Animation Start Event
     */
    _onStart: function() {
      this._emit('start');
    },

    /**
    * Animation End Event
    */
    _onEnd: function() {
      this._emit('end');
    },

    /**
    * Animation Iteration Event
    */
    _onIteration: function() {
      this._emit('iteration');
    },

    /**
     * Add prefixes for event
     * @param  {String} event event name
     * @return {String} return prefixed events
     */
    _prefixed: function(event) {
      var prefixes = ['webkit', 'moz', 'MS', 'o', ''];
      return prefixes.map(prefix => {
        if (prefix === '') {
          return event.toLowerCase();
        }
        return prefix + event;
      }).join(' ');
    }
  }, /** @lends animation */ {
    lazyInit: true,
    onInit: function() {
      this.__base.apply(this, arguments);
      let ptp = this.prototype;
      this._domEvents()
        .on(ptp._prefixed('AnimationEnd'), this.prototype._onEnd)
        .on(ptp._prefixed('AnimationStart'), this.prototype._onStart)
        .on(ptp._prefixed('AnimationIteration'), this.prototype._onIteration);
    }
  }));
});
<|endoftext|>


<commit_before>/* eslint-disable no-var, prefer-template, object-shorthand */

var path = require('path')
var webpack = require('webpack')
var Config = require('webpack-config').default
var DirectoryNamedWebpackPlugin = require('../plugins/directory-named')

module.exports = new Config().merge({
  cache: true,
  entry: {
    portrait: path.resolve('src/index.js'),
    'docs/index': [
      'bootstrap-sass/assets/javascripts/bootstrap',
      path.resolve('docs/entry.js'),
      path.resolve('docs/theme.scss'),
    ],
  },
  output: {
    path: path.resolve('lib'),
    filename: '[name].js',
    chunkFilename: 'docs/chunks/[id].[name].js',
    libraryTarget: 'umd',
    umdNamedDefine: true,
    pathinfo: true,
  },
  module: {
    loaders: [
      {
        test: require.resolve('bootstrap-sass//assets/javascripts/bootstrap'),
        loader: 'imports-loader?jQuery=jquery,$=jquery',
      },
      {
        test: /\.jsx?$/,
        loader: 'babel?cacheDirectory=true',
        exclude: /node_modules/,
      },
      {
        test: /\.woff(2)?(\?v=[0-9]\.[0-9]\.[0-9])?$/,
        loader: 'url-loader?limit=10000&mimetype=application/font-woff',
        exclude: /node_modules/,
      },
      {
        test: /\.(ttf|eot|svg)(\?v=[0-9]\.[0-9]\.[0-9])?$/,
        loader: 'file-loader',
        exclude: /node_modules/,
      },
      {
        test: /\.json$/,
        loader: 'json',
      },
      {
        test: /\.yml/,
        loaders: ['json', 'yaml'],
        exclude: /node_modules/,
      },
    ],
  },
  resolve: {
    root: path.resolve('src'),
    extensions: ['', '.js', '.jsx'],
  },
  resolveLoader: {
    fallback: [
      path.resolve('webpack/loaders'),
      path.resolve('node_modules'),
    ],
  },
  plugins: [
    new webpack.ResolverPlugin(new DirectoryNamedWebpackPlugin(true)),
  ],
})
<commit_msg>Imports font awesome<commit_after>/* eslint-disable no-var, prefer-template, object-shorthand */

var path = require('path')
var webpack = require('webpack')
var Config = require('webpack-config').default
var DirectoryNamedWebpackPlugin = require('../plugins/directory-named')

module.exports = new Config().merge({
  cache: true,
  entry: {
    portrait: path.resolve('src/index.js'),
    'docs/index': [
      'bootstrap-sass/assets/javascripts/bootstrap',
      'font-awesome/css/font-awesome.css',
      path.resolve('docs/entry.js'),
      path.resolve('docs/theme.scss'),
    ],
  },
  output: {
    path: path.resolve('lib'),
    filename: '[name].js',
    chunkFilename: 'docs/chunks/[id].[name].js',
    libraryTarget: 'umd',
    umdNamedDefine: true,
    pathinfo: true,
  },
  module: {
    loaders: [
      {
        test: require.resolve('bootstrap-sass//assets/javascripts/bootstrap'),
        loader: 'imports-loader?jQuery=jquery,$=jquery',
      },
      {
        test: /\.jsx?$/,
        loader: 'babel?cacheDirectory=true',
        exclude: /node_modules/,
      },
      {
        test: /\.(eot|ttf|woff|woff2|svg)(\?v=[0-9]\.[0-9]\.[0-9])?$/,
        loader: 'file-loader',
      },
      {
        test: /\.json$/,
        loader: 'json',
      },
      {
        test: /\.yml/,
        loaders: ['json', 'yaml'],
        exclude: /node_modules/,
      },
    ],
  },
  resolve: {
    root: path.resolve('src'),
    extensions: ['', '.js', '.jsx'],
  },
  resolveLoader: {
    fallback: [
      path.resolve('webpack/loaders'),
      path.resolve('node_modules'),
    ],
  },
  plugins: [
    new webpack.ResolverPlugin(new DirectoryNamedWebpackPlugin(true)),
  ],
})
<|endoftext|>


<commit_before>/*!
  Copyright (C) 2017 Google Inc.
  Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
*/

describe('CMS.Controllers.InnerNav', function () {
  'use strict';

  var Ctrl;  // the controller under test

  beforeAll(function () {
    Ctrl = CMS.Controllers.InnerNav;
  });

  describe('sortWidgets() method', function () {
    var ctrlInst;  // fake controller instance
    var sortWidgets;
    var options;

    beforeEach(function () {
      options = {
        widget_list: new can.Observe.List([])
      };

      ctrlInst = {
        options: new can.Map(options)
      };

      sortWidgets = Ctrl.prototype.sortWidgets.bind(ctrlInst);
    });

    it('sorts widgets by their "order" attribute', function () {
      var widgetOrder;
      var widgets = [
        {widget_id: 'aaa', order: 40},
        {widget_id: 'bbb', order: 20},
        {widget_id: 'ccc', order: 50},
        {widget_id: 'ddd', order: 10},
        {widget_id: 'eee', order: 30}
      ];
      options.widget_list.replace(widgets);

      sortWidgets();

      widgetOrder = _.map(ctrlInst.options.widget_list, 'widget_id');
      expect(widgetOrder).toEqual(['ddd', 'bbb', 'eee', 'aaa', 'ccc']);
    });

    it('places widgets with unknown "order" at the end', function () {
      var lastWidget;
      var widgets = [
        {widget_id: 'aaa', order: 40},
        {widget_id: 'bbb', order: undefined},
        {widget_id: 'ccc', order: 50},
        {widget_id: 'ddd', order: 10},
        {widget_id: 'eee', order: 30}
      ];
      options.widget_list.replace(widgets);

      sortWidgets();

      lastWidget = ctrlInst.options.widget_list[4];
      expect(lastWidget.widget_id).toEqual('bbb');
    });
  });
});
<commit_msg>Tests for InnerNav controller show_hide_titles method<commit_after>/*!
  Copyright (C) 2017 Google Inc.
  Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
*/

describe('CMS.Controllers.InnerNav', function () {
  'use strict';

  var Ctrl;  // the controller under test

  beforeAll(function () {
    Ctrl = CMS.Controllers.InnerNav;
  });

  describe('sortWidgets() method', function () {
    var ctrlInst;  // fake controller instance
    var sortWidgets;
    var options;

    beforeEach(function () {
      options = {
        widget_list: new can.Observe.List([])
      };

      ctrlInst = {
        options: new can.Map(options)
      };

      sortWidgets = Ctrl.prototype.sortWidgets.bind(ctrlInst);
    });

    it('sorts widgets by their "order" attribute', function () {
      var widgetOrder;
      var widgets = [
        {internav_display: 'aaa', order: 40},
        {internav_display: 'bbb', order: 20},
        {internav_display: 'ccc', order: 50},
        {internav_display: 'ddd', order: 10},
        {internav_display: 'eee', order: 30}
      ];
      options.widget_list.replace(widgets);

      sortWidgets();

      widgetOrder = _.map(ctrlInst.options.widget_list, 'internav_display');
      expect(widgetOrder).toEqual(['ddd', 'bbb', 'eee', 'aaa', 'ccc']);
    });

    it('places widgets with unknown "order" at the end and sort them in alphabetical order', function () {
      var widgetOrder;
      var widgets = [
        {internav_display: 'abc'},
        {internav_display: 'aaa', order: 40},
        {internav_display: 'cba'},
        {internav_display: 'ccc', order: 50},
        {internav_display: 'qwerty'},
        {internav_display: 'ddd', order: 10},
        {internav_display: 'xyz'},
        {internav_display: 'eee', order: 30}
      ];
      options.widget_list.replace(widgets);

      sortWidgets();

      widgetOrder = _.map(ctrlInst.options.widget_list, 'internav_display');
      expect(widgetOrder)
        .toEqual(['ddd', 'eee', 'aaa', 'ccc', 'abc', 'cba', 'qwerty', 'xyz']);
    });
  });

  describe('show_hide_titles() method', function () {
    var DISPLAY_WIDTH = 1920;
    var ctrlInst;  // fake controller instance
    var showHideTitles;
    var options;

    function createWidgets(titlesStatus) {
      var widgets = [
        {name: 'aaa', show_title: titlesStatus},
        {name: 'bbb', show_title: titlesStatus},
        {name: 'ccc', show_title: titlesStatus},
        {name: 'ddd', show_title: titlesStatus},
        {name: 'eee', show_title: titlesStatus},
        {name: 'fff', show_title: titlesStatus}
      ];
      options.attr('widget_list', widgets);
      return widgets;
    }

    function setWidgetsWidth(first, second) {
      spyOn(Array.prototype, 'reduce').and.returnValues(first, second);
    }

    beforeEach(function () {
      options = new can.Map({
        widget_list: new can.Observe.List([]),
        dividedTabsMode: false,
        priorityTabs: null
      });

      ctrlInst = {
        element: {
          children: jasmine.createSpy(),
          width: jasmine.createSpy().and.returnValue(DISPLAY_WIDTH)
        },
        options: options
      };

      spyOn(_, 'map')
        .and
        .returnValue([]);

      showHideTitles = Ctrl.prototype.show_hide_titles.bind(ctrlInst);
    });

    afterEach(function () {
      Array.prototype.reduce.calls.reset();
    });

    it('doesnt hide titles if the width is enough', function () {
      createWidgets(false);

      setWidgetsWidth(1500);

      showHideTitles();

      expect(_.every(options.attr('widget_list'), 'show_title')).toBeTruthy();
    });

    it('hides titles if the width isnt enough', function () {
      createWidgets(true);

      setWidgetsWidth(2500);

      showHideTitles();

      expect(_.every(options.widget_list, 'show_title', false)).toBeTruthy();
    });

    it('hides not priority titles if the width isnt enough', function () {
      var widgetList;
      createWidgets(true);

      options.attr('dividedTabsMode', true);
      options.attr('priorityTabs', 3);

      setWidgetsWidth(2500, 1500);

      showHideTitles();

      widgetList = options.attr('widget_list');

      expect(_.every(widgetList.slice(0, 3), 'show_title')).toBeTruthy();
      expect(_.every(widgetList.slice(3), 'show_title', false)).toBeTruthy();
    });

    it('hides all titles if the width isnt enough', function () {
      var widgetList;
      createWidgets(true);

      options.attr('dividedTabsMode', true);
      options.attr('priorityTabs', 3);

      setWidgetsWidth(3000, 2000);

      showHideTitles();

      widgetList = options.attr('widget_list');

      expect(_.every(widgetList, 'show_title', false)).toBeTruthy();
    });
  });
});
<|endoftext|>


<commit_before>import Emitter from '../emitter';
import define from '../define';
import is from '../is';
import util from '../util';
import Selector from '../selector';

let emitterOptions = {
  qualifierCompare: function( selector1, selector2 ){
    if( selector1 == null || selector2 == null ){
      return selector1 == null && selector2 == null;
    } else {
      return selector1.sameText( selector2 );
    }
  },
  eventMatches: function( cy, listener, eventObj ){
    let selector = listener.qualifier;

    if( selector != null ){
      return cy !== eventObj.target && is.element( eventObj.target ) && selector.matches( eventObj.target );
    }

    return true;
  },
  addEventFields: function( cy, evt ){
    evt.cy = cy;
    evt.target = cy;
  },
  callbackContext: function( cy, listener, eventObj ){
    return listener.qualifier != null ? eventObj.target : cy;
  }
};

let argSelector = function( arg ){
  if( is.string(arg) ){
    return new Selector( arg );
  } else {
    return arg;
  }
};

let elesfn = ({
  createEmitter: function(){
    let _p = this._private;

    if( !_p.emitter ){
      _p.emitter = new Emitter( emitterOptions, this );
    }

    return this;
  },

  emitter: function(){
    return this._private.emitter;
  },

  on: function( events, selector, callback ){
    this.emitter().on( events, argSelector(selector), callback );

    return this;
  },

  removeListener: function( events, selector, callback ){
    this.emitter().removeListener( events, argSelector(selector), callback );

    return this;
  },

  one: function( events, selector, callback ){
    this.emitter().one( events, argSelector(selector), callback );

    return this;
  },

  once: function( events, selector, callback ){
    this.emitter().one( events, argSelector(selector), callback );

    return this;
  },

  emit: function( events, extraParams ){
    this.emitter().emit( events, extraParams );

    return this;
  }
});

define.eventAliasesOn( elesfn );

export default elesfn;
<commit_msg>Lint fix : no-unused-vars<commit_after>import Emitter from '../emitter';
import define from '../define';
import is from '../is';
import Selector from '../selector';

let emitterOptions = {
  qualifierCompare: function( selector1, selector2 ){
    if( selector1 == null || selector2 == null ){
      return selector1 == null && selector2 == null;
    } else {
      return selector1.sameText( selector2 );
    }
  },
  eventMatches: function( cy, listener, eventObj ){
    let selector = listener.qualifier;

    if( selector != null ){
      return cy !== eventObj.target && is.element( eventObj.target ) && selector.matches( eventObj.target );
    }

    return true;
  },
  addEventFields: function( cy, evt ){
    evt.cy = cy;
    evt.target = cy;
  },
  callbackContext: function( cy, listener, eventObj ){
    return listener.qualifier != null ? eventObj.target : cy;
  }
};

let argSelector = function( arg ){
  if( is.string(arg) ){
    return new Selector( arg );
  } else {
    return arg;
  }
};

let elesfn = ({
  createEmitter: function(){
    let _p = this._private;

    if( !_p.emitter ){
      _p.emitter = new Emitter( emitterOptions, this );
    }

    return this;
  },

  emitter: function(){
    return this._private.emitter;
  },

  on: function( events, selector, callback ){
    this.emitter().on( events, argSelector(selector), callback );

    return this;
  },

  removeListener: function( events, selector, callback ){
    this.emitter().removeListener( events, argSelector(selector), callback );

    return this;
  },

  one: function( events, selector, callback ){
    this.emitter().one( events, argSelector(selector), callback );

    return this;
  },

  once: function( events, selector, callback ){
    this.emitter().one( events, argSelector(selector), callback );

    return this;
  },

  emit: function( events, extraParams ){
    this.emitter().emit( events, extraParams );

    return this;
  }
});

define.eventAliasesOn( elesfn );

export default elesfn;
<|endoftext|>


<commit_before>(function () {
    var moduleInjection = {};
    BI.module = BI.module || function (xtype, cls) {
        if (moduleInjection[xtype] != null) {
            _global.console && console.error("module:[" + xtype + "] has been registed");
        }
        moduleInjection[xtype] = cls;
    };

    var constantInjection = {};
    BI.constant = BI.constant || function (xtype, cls) {
        if (constantInjection[xtype] != null) {
            _global.console && console.error("constant:[" + xtype + "] has been registed");
        }
        constantInjection[xtype] = cls;
    };

    var modelInjection = {};
    BI.model = BI.model || function (xtype, cls) {
        if (modelInjection[xtype] != null) {
            _global.console && console.error("model:[" + xtype + "] has been registed");
        }
        modelInjection[xtype] = cls;
    };

    var storeInjection = {};
    BI.store = BI.store || function (xtype, cls) {
        if (storeInjection[xtype] != null) {
            _global.console && console.error("store:[" + xtype + "] has been registed");
        }
        storeInjection[xtype] = cls;
    };

    var serviceInjection = {};
    BI.service = BI.service || function (xtype, cls) {
        if (serviceInjection[xtype] != null) {
            _global.console && console.error("service:[" + xtype + "] has been registed");
        }
        serviceInjection[xtype] = cls;
    };

    var providerInjection = {};
    BI.provider = BI.provider || function (xtype, cls) {
        if (providerInjection[xtype] != null) {
            _global.console && console.error("provider:[" + xtype + "] has been registed");
        }
        providerInjection[xtype] = cls;
    };

    var configFunctions = {};
    BI.config = BI.config || function (type, configFn, opt) {
        if (!configFunctions[type]) {
            configFunctions[type] = [];
        }
        configFunctions[type].push({fn: configFn, args: opt});
    };

    BI.Configs = BI.Configs || {
        getConfigs: function () {
            return configFunctions;
        },
        getConfig: function (type) {
            return configFunctions[type];
        },
    };

    var actions = {};
    var globalAction = [];
    BI.action = BI.action || function (type, actionFn) {
        if (BI.isFunction(type)) {
            globalAction.push(type);
            return function () {
                BI.remove(globalAction, function (idx) {
                    return globalAction.indexOf(actionFn) === idx;
                });
            };
        }
        if (!actions[type]) {
            actions[type] = [];
        }
        actions[type].push(actionFn);
        return function () {
            BI.remove(actions[type], function (idx) {
                return actions[type].indexOf(actionFn) === idx;
            });
            if (actions[type].length === 0) {
                delete actions[type];
            }
        };
    };

    var points = {};
    BI.point = BI.point || function (type, action, pointFn, after) {
        if (!points[type]) {
            points[type] = {};
        }
        if (!points[type][action]) {
            points[type][action] = {};
        }
        if (!points[type][action][after ? "after" : "before"]) {
            points[type][action][after ? "after" : "before"] = [];
        }
        points[type][action][after ? "after" : "before"].push(pointFn);
    };

    BI.Modules = BI.Modules || {
        getModule: function (type) {
            if (!moduleInjection[type]) {
                _global.console && console.error("module:[" + type + "] does not exists");
                return false;
            }
            return moduleInjection[type];
        },
        getAllModules: function () {
            return moduleInjection;
        }
    };

    BI.Constants = BI.Constants || {
        getConstant: function (type) {
            var instance = constantInjection[type];
            BI.each(configFunctions[type], function (i, cf) {
                var res = cf.fn(instance);
                if (res) {
                    instance = res;
                }
            });
            constantInjection[type] = instance;
            configFunctions[type] && (configFunctions[type] = null);
            return instance;
        }
    };

    var callPoint = function (inst, types) {
        types = BI.isArray(types) ? types : [types];
        BI.each(types, function (idx, type) {
            if (points[type]) {
                for (var action in points[type]) {
                    var bfns = points[type][action].before;
                    if (bfns) {
                        BI.aspect.before(inst, action, function (bfns) {
                            return function () {
                                for (var i = 0, len = bfns.length; i < len; i++) {
                                    try {
                                        bfns[i].apply(inst, arguments);
                                    } catch (e) {
                                        _global.console && console.error(e);
                                    }
                                }
                            };
                        }(bfns));
                    }
                    var afns = points[type][action].after;
                    if (afns) {
                        BI.aspect.after(inst, action, function (afns) {
                            return function () {
                                for (var i = 0, len = afns.length; i < len; i++) {
                                    try {
                                        afns[i].apply(inst, arguments);
                                    } catch (e) {
                                        _global.console && console.error(e);
                                    }
                                }
                            };
                        }(afns));
                    }
                }
            }
        });
    };

    BI.Models = BI.Models || {
        getModel: function (type, config) {
            var inst = new modelInjection[type](config);
            inst._constructor && inst._constructor(config);
            inst.mixins && callPoint(inst, inst.mixins);
            callPoint(inst, type);
            return inst;
        }
    };

    var stores = {};

    BI.Stores = BI.Stores || {
        getStore: function (type, config) {
            if (stores[type]) {
                return stores[type];
            }
            var inst = stores[type] = new storeInjection[type](config);
            inst._constructor && inst._constructor(config, function () {
                delete stores[type];
            });
            callPoint(inst, type);
            return inst;
        }
    };

    var services = {};

    BI.Services = BI.Services || {
        getService: function (type, config) {
            if (services[type]) {
                return services[type];
            }
            services[type] = new serviceInjection[type](config);
            callPoint(services[type], type);
            return services[type];
        }
    };

    var providers = {},
        providerInstance = {};

    BI.Providers = BI.Providers || {
        getProvider: function (type, config) {
            if (!providers[type]) {
                providers[type] = new providerInjection[type]();
            }
            var instance = providers[type];
            BI.each(configFunctions[type], function (i, cf) {
                if (providerInstance[type]) {
                    delete providerInstance[type];
                }
                cf.fn(instance);
            });
            if (!providerInstance[type]) {
                providerInstance[type] = new (providers[type].$get())(config);
            }
            configFunctions[type] && (configFunctions[type] = null);
            return providerInstance[type];
        }
    };

    BI.Actions = BI.Actions || {
        runAction: function (type, event, config) {
            BI.each(actions[type], function (i, act) {
                try {
                    act(event, config);
                } catch (e) {
                    _global.console && console.error(e);
                }
            });
        },
        runGlobalAction: function () {
            var args = [].slice.call(arguments);
            BI.each(globalAction, function (i, act) {
                try {
                    act.apply(null, args);
                } catch (e) {
                    _global.console && console.error(e);
                }
            });
        }
    };

    BI.getResource = BI.getResource || function (type, config) {
        if (constantInjection[type]) {
            return BI.Constants.getConstant(type);
        }
        if (modelInjection[type]) {
            return BI.Models.getModel(type, config);
        }
        if (storeInjection[type]) {
            return BI.Stores.getStore(type, config);
        }
        if (serviceInjection[type]) {
            return BI.Services.getService(type, config);
        }
        if (providerInjection[type]) {
            return BI.Providers.getProvider(type, config);
        }
    };
})();
<commit_msg>Pull request #1615: 无JIRA任务 BI.config提供immdiate参数来立即执行回调<commit_after>(function () {
    var moduleInjection = {};
    BI.module = BI.module || function (xtype, cls) {
        if (moduleInjection[xtype] != null) {
            _global.console && console.error("module:[" + xtype + "] has been registed");
        }
        moduleInjection[xtype] = cls;
    };

    var constantInjection = {};
    BI.constant = BI.constant || function (xtype, cls) {
        if (constantInjection[xtype] != null) {
            _global.console && console.error("constant:[" + xtype + "] has been registed");
        }
        constantInjection[xtype] = cls;
    };

    var modelInjection = {};
    BI.model = BI.model || function (xtype, cls) {
        if (modelInjection[xtype] != null) {
            _global.console && console.error("model:[" + xtype + "] has been registed");
        }
        modelInjection[xtype] = cls;
    };

    var storeInjection = {};
    BI.store = BI.store || function (xtype, cls) {
        if (storeInjection[xtype] != null) {
            _global.console && console.error("store:[" + xtype + "] has been registed");
        }
        storeInjection[xtype] = cls;
    };

    var serviceInjection = {};
    BI.service = BI.service || function (xtype, cls) {
        if (serviceInjection[xtype] != null) {
            _global.console && console.error("service:[" + xtype + "] has been registed");
        }
        serviceInjection[xtype] = cls;
    };

    var providerInjection = {};
    BI.provider = BI.provider || function (xtype, cls) {
        if (providerInjection[xtype] != null) {
            _global.console && console.error("provider:[" + xtype + "] has been registed");
        }
        providerInjection[xtype] = cls;
    };

    var configFunctions = {};
    BI.config = BI.config || function (type, configFn, opt) {
        if (opt && opt.immediate) {
            if (constantInjection[type]) {
                return (constantInjection[type] = configFn(constantInjection[type]));
            }
            if (providerInjection[type]) {
                if (!providers[type]) {
                    providers[type] = new providerInjection[type]();
                }
                // 如果config被重新配置的话，需要删除掉之前的实例
                if (providerInstance[type]) {
                    delete providerInstance[type];
                }
                return configFn(providers[type]);
            }
            return BI.Plugin.configWidget(type, configFn, opt);
        }
        if (!configFunctions[type]) {
            configFunctions[type] = [];
        }
        configFunctions[type].push({fn: configFn, args: opt});
    };

    BI.Configs = BI.Configs || {
        getConfigs: function () {
            return configFunctions;
        },
        getConfig: function (type) {
            return configFunctions[type];
        },
    };

    var actions = {};
    var globalAction = [];
    BI.action = BI.action || function (type, actionFn) {
        if (BI.isFunction(type)) {
            globalAction.push(type);
            return function () {
                BI.remove(globalAction, function (idx) {
                    return globalAction.indexOf(actionFn) === idx;
                });
            };
        }
        if (!actions[type]) {
            actions[type] = [];
        }
        actions[type].push(actionFn);
        return function () {
            BI.remove(actions[type], function (idx) {
                return actions[type].indexOf(actionFn) === idx;
            });
            if (actions[type].length === 0) {
                delete actions[type];
            }
        };
    };

    var points = {};
    BI.point = BI.point || function (type, action, pointFn, after) {
        if (!points[type]) {
            points[type] = {};
        }
        if (!points[type][action]) {
            points[type][action] = {};
        }
        if (!points[type][action][after ? "after" : "before"]) {
            points[type][action][after ? "after" : "before"] = [];
        }
        points[type][action][after ? "after" : "before"].push(pointFn);
    };

    BI.Modules = BI.Modules || {
        getModule: function (type) {
            if (!moduleInjection[type]) {
                _global.console && console.error("module:[" + type + "] does not exists");
                return false;
            }
            return moduleInjection[type];
        },
        getAllModules: function () {
            return moduleInjection;
        }
    };

    BI.Constants = BI.Constants || {
        getConstant: function (type) {
            var instance = constantInjection[type];
            BI.each(configFunctions[type], function (i, cf) {
                var res = cf.fn(instance);
                if (res) {
                    instance = res;
                }
            });
            constantInjection[type] = instance;
            configFunctions[type] && (configFunctions[type] = null);
            return instance;
        }
    };

    var callPoint = function (inst, types) {
        types = BI.isArray(types) ? types : [types];
        BI.each(types, function (idx, type) {
            if (points[type]) {
                for (var action in points[type]) {
                    var bfns = points[type][action].before;
                    if (bfns) {
                        BI.aspect.before(inst, action, function (bfns) {
                            return function () {
                                for (var i = 0, len = bfns.length; i < len; i++) {
                                    try {
                                        bfns[i].apply(inst, arguments);
                                    } catch (e) {
                                        _global.console && console.error(e);
                                    }
                                }
                            };
                        }(bfns));
                    }
                    var afns = points[type][action].after;
                    if (afns) {
                        BI.aspect.after(inst, action, function (afns) {
                            return function () {
                                for (var i = 0, len = afns.length; i < len; i++) {
                                    try {
                                        afns[i].apply(inst, arguments);
                                    } catch (e) {
                                        _global.console && console.error(e);
                                    }
                                }
                            };
                        }(afns));
                    }
                }
            }
        });
    };

    BI.Models = BI.Models || {
        getModel: function (type, config) {
            var inst = new modelInjection[type](config);
            inst._constructor && inst._constructor(config);
            inst.mixins && callPoint(inst, inst.mixins);
            callPoint(inst, type);
            return inst;
        }
    };

    var stores = {};

    BI.Stores = BI.Stores || {
        getStore: function (type, config) {
            if (stores[type]) {
                return stores[type];
            }
            var inst = stores[type] = new storeInjection[type](config);
            inst._constructor && inst._constructor(config, function () {
                delete stores[type];
            });
            callPoint(inst, type);
            return inst;
        }
    };

    var services = {};

    BI.Services = BI.Services || {
        getService: function (type, config) {
            if (services[type]) {
                return services[type];
            }
            services[type] = new serviceInjection[type](config);
            callPoint(services[type], type);
            return services[type];
        }
    };

    var providers = {},
        providerInstance = {};

    BI.Providers = BI.Providers || {
        getProvider: function (type, config) {
            if (!providers[type]) {
                providers[type] = new providerInjection[type]();
            }
            var instance = providers[type];
            BI.each(configFunctions[type], function (i, cf) {
                if (providerInstance[type]) {
                    delete providerInstance[type];
                }
                cf.fn(instance);
            });
            if (!providerInstance[type]) {
                providerInstance[type] = new (providers[type].$get())(config);
            }
            configFunctions[type] && (configFunctions[type] = null);
            return providerInstance[type];
        }
    };

    BI.Actions = BI.Actions || {
        runAction: function (type, event, config) {
            BI.each(actions[type], function (i, act) {
                try {
                    act(event, config);
                } catch (e) {
                    _global.console && console.error(e);
                }
            });
        },
        runGlobalAction: function () {
            var args = [].slice.call(arguments);
            BI.each(globalAction, function (i, act) {
                try {
                    act.apply(null, args);
                } catch (e) {
                    _global.console && console.error(e);
                }
            });
        }
    };

    BI.getResource = BI.getResource || function (type, config) {
        if (constantInjection[type]) {
            return BI.Constants.getConstant(type);
        }
        if (modelInjection[type]) {
            return BI.Models.getModel(type, config);
        }
        if (storeInjection[type]) {
            return BI.Stores.getStore(type, config);
        }
        if (serviceInjection[type]) {
            return BI.Services.getService(type, config);
        }
        if (providerInjection[type]) {
            return BI.Providers.getProvider(type, config);
        }
    };
})();
<|endoftext|>


<commit_before>jQuery(function($){
	var $masonryContainer = $('.masonry-wrapper .masonry-results');

	var masonryEvents = {
		init: function() {
			if($masonryContainer.length > 0) this.renderMasonry();
		},
		renderMasonry: function() {
			var settings = this.masonrySettings();
			$masonryContainer.masonry(settings);
			$masonryContainer.imagesLoaded(function(){
				$masonryContainer.masonry(settings);
			});
		},
		masonrySettings: function(){
			return {
				isFitWidth: false,
				percentPosition: true,
				columnWidth: ".masonry-sizer",
				isInitLayout: false,
				itemSelector: '.masonry-wrapper .masonry-results li'
			};
		},
		reinit: function(){
			$masonryContainer = $('body').find('.masonry-wrapper .masonry-results');
			if($masonryContainer.length > 0) this.renderMasonry();
		}
	};

	masonryEvents.init();
	reinitButtons();
	reinitSelect();

	$('select[name="category"]').each(function(){
		var $select = $(this);
		var $options = $(this).find('option');
		var $parent = $('body').find('.filters');
		var $wrapper = $('

');
		var $itemWrapper = $('

');

		$options.each(function(){
			var $option = $(this);
			var text = $(this).text();
			var btnClass = text.toLowerCase();
				btnClass = 'btn--'+btn_class.replace(' ','-');
			var value = $(this).val();
			var $link = $('');
			var $new_link = $link.clone();
			var $list_wrapper = $itemWrapper.clone();
			$new_link.text(text).attr('href', $select.attr('name'));
			$list_wrapper.append($new_link);
			$wrapper.append($list_wrapper);
		});
		$parent.append($wrapper);
	});

	$('body').on('click', ".btn--category", function(e){
		e.preventDefault();
		var $this = $(this);
		var $select = $('body').find('select[name="category"]');
		var $options = $select.find('option');
		var index = $this.parent().index();
		var $option = $select.find('option').eq(index);

		$options.removeAttr('selected');
		$option.attr('selected', 'selected');
		$select.trigger('change');
		$(this).parent().parent().find('li').each(function(){
			$(this).find('.btn--category').removeClass('active');
		})
		$(this).addClass('active');

	});

	function reinitButtons(){
		$('body').find('.pager__item').find('a').on("click", function(e){
			setTimeout(function(){
				masonryEvents.reinit();
				reinitButtons();
			}, 1000);
		});
	}

	function reinitSelect(){
		$('body').on('change', 'select', function(){
			setTimeout(function(){
				masonryEvents.reinit();
				reinitSelect();
			}, 1000);
		});
	}

});
<commit_msg>Impact Stories JS Fix<commit_after>jQuery(function($){
	var $masonryContainer = $('.masonry-wrapper .masonry-results');

	var masonryEvents = {
		init: function() {
			if($masonryContainer.length > 0) this.renderMasonry();
		},
		renderMasonry: function() {
			var settings = this.masonrySettings();
			$masonryContainer.masonry(settings);
			$masonryContainer.imagesLoaded(function(){
				$masonryContainer.masonry(settings);
			});
		},
		masonrySettings: function(){
			return {
				isFitWidth: false,
				percentPosition: true,
				columnWidth: ".masonry-sizer",
				isInitLayout: false,
				itemSelector: '.masonry-wrapper .masonry-results li'
			};
		},
		reinit: function(){
			$masonryContainer = $('body').find('.masonry-wrapper .masonry-results');
			if($masonryContainer.length > 0) this.renderMasonry();
		}
	};

	masonryEvents.init();
	reinitButtons();
	reinitSelect();

	$('select[name="category"]').each(function(){
		var $select = $(this);
		var $options = $(this).find('option');
		var $parent = $('body').find('.filters');
		var $wrapper = $('

');
		var $itemWrapper = $('

');

		$options.each(function(){
			var $option = $(this);
			var text = $(this).text();
			var btnClass = text.toLowerCase();
				btnClass = 'btn--'+btnClass.replace(/\s/g,'-');
			var value = $(this).val();
			var $link = $('');
			var $new_link = $link.clone();
			var $list_wrapper = $itemWrapper.clone();
			$new_link.text(text).attr('href', $select.attr('name'));
			$list_wrapper.append($new_link);
			$wrapper.append($list_wrapper);
		});
		$parent.append($wrapper);
	});

	$('body').on('click', ".btn--category", function(e){
		e.preventDefault();
		var $this = $(this);
		var $select = $('body').find('select[name="category"]');
		var $options = $select.find('option');
		var index = $this.parent().index();
		var $option = $select.find('option').eq(index);

		$options.removeAttr('selected');
		$option.attr('selected', 'selected');
		$select.trigger('change');
		$(this).parent().parent().find('li').each(function(){
			$(this).find('.btn--category').removeClass('active');
		})
		$(this).addClass('active');

	});

	function reinitButtons(){
		$('body').find('.pager__item').find('a').on("click", function(e){
			setTimeout(function(){
				masonryEvents.reinit();
				reinitButtons();
			}, 1000);
		});
	}

	function reinitSelect(){
		$('body').on('change', 'select', function(){
			setTimeout(function(){
				masonryEvents.reinit();
				reinitSelect();
			}, 1000);
		});
	}

});
<|endoftext|>