<commit_before>"use strict";
/*
Countly Adapter Library for Google Analytics
*/
/*global Countly*/
(function () {
    // logs array for tests
    window.cly_ga_test_logs = [];
    Countly.onload = Countly.onload || [];
    // adapter function
    window.CountlyGAAdapter = function () {
        // hold ga instance
        var old_ga = window.ga;
        // array for ga calls which called before ga initialized
        var gaCalls = [];
        // hold calls in array
        window.ga = function () {
            gaCalls.push(arguments);
            return old_ga.apply(this, arguments);
        };
        // ga overrided signature
        window.ga._signature = 1;

        // hold ga_countly calls in array before countly initialized
        var gaCountlyArray = [];
        var ga_countly = function() {
            gaCountlyArray.push(arguments);
        };

        Countly.onload.push(function () {
            // cart for ga:ecommerce plugin
            var cart = Countly._internals.store('cly_ecommerce:cart') || [];
            // override ga_countly and map request to countly
            ga_countly = function (c, o, u, n, t, l/*, y*/) {
                if (typeof c === "string") {
                    var customSegments, i, count;
                    switch (c) {
                    case 'send':
                        if (typeof o === 'string') {
                            // ga('send', 'event', ..)
                            if (o === 'event') {

                                customSegments = {};
                                count = 1;
                                // ga('send', 'event', 'category', 'action')
                                if (arguments.length === 4) {
                                    customSegments["category"] = u;
                                }
                                // ga('send', 'event', 'category', 'action', 'label')
                                else if (arguments.length === 5 && typeof arguments[4] === "string") {
                                    customSegments["category"] = u;
                                    customSegments["label"] = t;
                                }
                                // ga('send', 'event', 'category', 'action', {metric:value})
                                else if (arguments.length === 5 && typeof arguments[4] === "object") {
                                    customSegments["category"] = u;
                                    for (i = 0; i < Object.keys(arguments[4]).length; i++) {
                                        customSegments[Object.keys(arguments[4])[i]] = Object.values(arguments[4])[i];
                                    }
                                }
                                // ga('send', 'event', 'category', 'action', 'label', 1)
                                else if (arguments.length >= 6) {
                                    customSegments["category"] = u;
                                    customSegments["label"] = t;
                                    count = l;
                                }

                                Countly.onload.push(function () {
                                    // add event by configured values
                                    Countly.q.push(['add_event', {
                                        key: n,
                                        count: count,
                                        segmentation: customSegments
                                    }]);
                                });

                                if (window.cly_ga_test_mode) {
                                    window.cly_ga_test_logs.push(['add_event', {
                                        key: n,
                                        count: count,
                                        segmentation: customSegments
                                    }]);
                                }
                            }
                            // ga('send', 'pageview')
                            else if (o === 'pageview' && arguments.length === 2) {
                                if (Countly._internals.store('cly_ga:page')) {
                                    Countly.q.push(['track_pageview', Countly._internals.store('cly_ga:page')]);
                                    if (window.cly_ga_test_mode) {window.cly_ga_test_logs.push(['track_pageview', Countly._internals.store('cly_ga:page')]);}
                                }
                                else {
                                    Countly.q.push(['track_pageview']);
                                    if (window.cly_ga_test_mode) {window.cly_ga_test_logs.push(['track_pageview']);}
                                }
                            }
                            // ga('send', 'pageview', 'page')
                            else if (o === 'pageview' && arguments.length >= 3 && typeof arguments[2] === "string") {
                                Countly.q.push(['track_pageview', arguments[2]]);
                                if (window.cly_ga_test_mode) {window.cly_ga_test_logs.push(['track_pageview', arguments[2]]);}
                            }
                            // ga('send', 'pageview', {'customDimension':'customValue'})
                            else if (o === 'pageview' && arguments.length >= 3 && typeof arguments[2] === "object") {
                                // we are not supported tracking pageview with custom objects for now
                                Countly.q.push(['track_pageview']);
                                if (window.cly_ga_test_mode) {window.cly_ga_test_logs.push(['track_pageview']);}
                            }
                            // ga('send', 'social', 'network', 'action', 'target')
                            else if (o === 'social') {
                                Countly.q.push(['add_event', {
                                    "key": n,
                                    "count": 1,
                                    "segmentation": {
                                        "category": o,
                                        "platform": u,
                                        "target": t
                                    }
                                }]);
                                if (window.cly_ga_test_mode) {
                                    window.cly_ga_test_logs.push(['add_event', {
                                        "key": n,
                                        "count": 1,
                                        "segmentation": {"category": o, "platform": u, "target": t}
                                    }]);
                                }
                            }
                            // ga('send', 'screenview', {..})
                            else if (o === 'screenview') {
                                customSegments = {appName: u.appName};

                                if (u.screenName) {customSegments.screenName = u.screenName;}
                                if (u.appVersion) {customSegments.appVersion = u.appVersion;}
                                if (u.appInstallerId) {customSegments.appInstallerId = u.appInstallerId;}
                                if (Countly._internals.store('cly_ga:screenname')) {customSegments.screenName = Countly._internals.store('cly_ga:screenname');}

                                Countly.q.push(['add_event', {
                                    "key": "Screen View",
                                    "count": 1,
                                    "segmentation": customSegments
                                }]);

                                if (window.cly_ga_test_mode) {
                                    window.cly_ga_test_logs.push(['add_event', {
                                        "key": "Screen View",
                                        "count": 1,
                                        "segmentation": customSegments
                                    }]);
                                }
                            }
                            // ga('send', 'exception', {..})
                            else if (o === 'exception') {
                                Countly.log_error(u.exDescription);
                                if (window.cly_ga_test_mode) {window.cly_ga_test_logs.push(u.exDescription);}
                            }
                            // ga('send', 'timing', 'timingCategory', 'timingVar', 'timingValue', 'timingLabel')
                            else if (o === 'timing') {
                                customSegments = {category: u};
                                if (l) {customSegments.label = l;}
                                Countly.q.push(['add_event', {
                                    "key": n,
                                    "count": 1,
                                    "dur": t,
                                    "segmentation": customSegments
                                }]);
                                if (window.cly_ga_test_mode) {
                                    window.cly_ga_test_logs.push(['add_event', {
                                        "key": n,
                                        "count": 1,
                                        "dur": t,
                                        "segmentation": customSegments
                                    }]);
                                }
                            }
                        }
                        // ga('send', {hitType:.., ...})
                        else if (typeof o === 'object') {
                            switch (o.hitType) {
                            // ga('send', {'hitType':'event', ..})
                            case 'event':
                                customSegments = {
                                    'category': o.eventCategory
                                };
                                count = 1;

                                if (o.eventLabel) {customSegments["label"] = o.eventLabel;}
                                if (o.eventValue) {count = o.eventValue;}

                                Countly.q.push(['add_event', {
                                    key: o.eventAction,
                                    count: count,
                                    segmentation: customSegments
                                }]);

                                if (window.cly_ga_test_mode) {
                                    window.cly_ga_test_logs.push(['add_event', {
                                        key: o.eventAction,
                                        count: count,
                                        segmentation: customSegments
                                    }]);
                                }

                                break;
                                // ga('send', {'hitType':'social', ..})
                            case 'social':
                                Countly.q.push(['add_event', {
                                    "key": o.socialAction,
                                    "count": 1,
                                    "segmentation": {
                                        "category": o.hitType,
                                        "platform": o.socialNetwork,
                                        "target": o.socialTarget
                                    }
                                }]);

                                if (window.cly_ga_test_mode) {
                                    window.cly_ga_test_logs.push(['add_event', {
                                        "key": o.socialAction,
                                        "count": 1,
                                        "segmentation": {
                                            "category": o.hitType,
                                            "platform": o.socialNetwork,
                                            "target": o.socialTarget
                                        }
                                    }]);
                                }

                                break;
                                // ga('send', {'hitType':'timing', ..})
                            case 'timing':
                                Countly.q.push(['add_event', {
                                    "key": o.timingVar,
                                    "count": 1,
                                    "dur": o.timingValue,
                                    "segmentation": {
                                        "category": o.timingCategory
                                    }
                                }]);

                                if (window.cly_ga_test_mode) {
                                    window.cly_ga_test_logs.push(['add_event', {
                                        "key": o.timingVar,
                                        "count": 1,
                                        "dur": o.timingValue,
                                        "segmentation": {"category": o.timingCategory}
                                    }]);
                                }
                                break;
                                // ga('send', {'hitType':'pageview', 'page':'page'})
                            case 'pageview':
                                Countly.q.push(['track_pageview', o.page]);
                                if (window.cly_ga_test_mode) {
                                    window.cly_ga_test_logs.push(['track_pageview', o.page]);
                                }
                                break;
                            }
                        }
                        break;
                        // ga('create', '..')
                    case 'create':
                        // ga('create', .., 'auto', '..')
                        if (arguments.length === 4 && arguments[2] === 'auto') {
                            Countly._internals.store('cly_ga:id', o);
                            if (window.cly_ga_test_mode) {
                                window.cly_ga_test_logs.push({
                                    'stored': Countly._internals.store('cly_ga:id'),
                                    'value': o
                                });
                            }
                            window.ga_adapter_integrated = true;
                            // ga('create', .., callback)
                        } else if (arguments.length === 3) {
                            Countly._internals.store('cly_ga:id', o);
                            if (window.cly_ga_test_mode) {
                                window.cly_ga_test_logs.push({
                                    'stored': Countly._internals.store('cly_ga:id'),
                                    'value': o
                                });
                            }
                            window.ga_adapter_integrated = true;
                        }
                        break;
                        // ga('set', '..')
                    case 'set':
                        // ga('set', 'page', '/login.html')
                        if (o === 'page') {
                            Countly._internals.store('cly_ga:page', u);
                        }
                        // ga('set', 'screenname', 'High scores')
                        else if (o === 'screenname') {
                            Countly._internals.store('cly_ga:screenname', u);
                            if (window.cly_ga_test_mode) {
                                window.cly_ga_test_logs.push({
                                    'stored': Countly._internals.store('cly_ga:screenname'),
                                    'value': u
                                });
                            }
                        }
                        // ga('set', 'dimension', 'custom data')
                        else if (arguments.length === 3) {
                            Countly.q.push(['userData.set', o, u]);
                            if (window.cly_ga_test_mode) {
                                window.cly_ga_test_logs.push(['userData.set', o, u]);
                            }
                        }
                        // ga('set', {key:val, anotherKey: anotherVal})
                        else if (arguments.length === 2 && typeof o === 'object') {
                            Countly.q.push(['user_details', {custom: o}]);
                            if (window.cly_ga_test_mode) {
                                window.cly_ga_test_logs.push(['user_details', {custom: o}]);
                            }
                        }
                        break;
                        // ga('ecommerce:addTransaction', {..})
                    case 'ecommerce:addTransaction':
                        customSegments = {
                            "id": o.id,
                            "affiliation": o.affiliation,
                            "shipping": o.shipping,
                            "tax": o.tax
                        };

                        if (o.currency) {customSegments["currency"] = o.currency;}

                        Countly.q.push(['add_event', {
                            "key": c,
                            "count": 1,
                            "sum": o.revenue,
                            "segmentation": customSegments
                        }]);

                        if (window.cly_ga_test_mode) {
                            window.cly_ga_test_logs.push(['add_event', {
                                "key": c,
                                "count": 1,
                                "sum": o.revenue,
                                "segmentation": customSegments
                            }]);
                        }

                        break;
                        // ga('ecommerce:addItem', {..})
                    case 'ecommerce:addItem':
                        customSegments = {
                            "id": o.id,
                            "name": o.name,
                            "sku": o.sku,
                            "category": o.category
                        };

                        if (o.currency) {customSegments["currency"] = o.currency;}

                        cart.push(['add_event', {
                            "key": c,
                            "count": o.quantity,
                            "sum": o.price,
                            "segmentation": customSegments
                        }]);

                        Countly._internals.store('cly_ecommerce:cart', cart);

                        if (window.cly_ga_test_mode) {
                            window.cly_ga_test_logs.push(['add_event', {
                                "key": c,
                                "count": o.quantity,
                                "sum": o.price,
                                "segmentation": customSegments
                            }]);
                        }

                        break;
                        // ga('ecommerce:send')
                    case 'ecommerce:send':
                        var firstLength;
                        if (window.cly_ga_test_mode) {
                            firstLength = cart.length;
                        }
                        for (i = 0; i < cart.length; i++) {
                            Countly.q.push(cart[i]);
                        }
                        cart = [];
                        Countly._internals.store('cly_ecommerce:cart', cart);

                        if (window.cly_ga_test_mode) {
                            window.cly_ga_test_logs.push({first: firstLength, last: cart.length});
                        }
                        break;
                        // ga('ecommerce:clear')
                    case 'ecommerce:clear':
                        cart = [];
                        Countly._internals.store('cly_ecommerce:cart', cart);

                        if (window.cly_ga_test_mode) {
                            window.cly_ga_test_logs.push(Countly._internals.store('cly_ecommerce:cart'));
                        }
                        break;
                    default:
                        break;
                    }
                }
            };
            // apply old countly calls to overrided function
            while(gaCountlyArray.length) {
                var args = gaCountlyArray.shift();
                ga_countly.apply(window, args);
            }
        });

        // check variable for gaAdapter is loaded?
        setTimeout(function check() {
            if (window.ga._signature) {return setTimeout(check, 125);}
            old_ga = window.ga;

            while (gaCalls.length) {
                var args = gaCalls.shift();
                ga_countly.apply(window, args);
            }

            window.ga = function () {
                ga_countly.apply(window, arguments);
                return old_ga.apply(this, arguments);
            };
        }, 125);
    };
})();<commit_msg>[eslint] wrap-iife<commit_after>"use strict";
/*
Countly Adapter Library for Google Analytics
*/
/*global Countly*/
(function () {
    // logs array for tests
    window.cly_ga_test_logs = [];
    Countly.onload = Countly.onload || [];
    // adapter function
    window.CountlyGAAdapter = function () {
        // hold ga instance
        var old_ga = window.ga;
        // array for ga calls which called before ga initialized
        var gaCalls = [];
        // hold calls in array
        window.ga = function () {
            gaCalls.push(arguments);
            return old_ga.apply(this, arguments);
        };
        // ga overrided signature
        window.ga._signature = 1;

        // hold ga_countly calls in array before countly initialized
        var gaCountlyArray = [];
        var ga_countly = function() {
            gaCountlyArray.push(arguments);
        };

        Countly.onload.push(function () {
            // cart for ga:ecommerce plugin
            var cart = Countly._internals.store('cly_ecommerce:cart') || [];
            // override ga_countly and map request to countly
            ga_countly = function (c, o, u, n, t, l/*, y*/) {
                if (typeof c === "string") {
                    var customSegments, i, count;
                    switch (c) {
                    case 'send':
                        if (typeof o === 'string') {
                            // ga('send', 'event', ..)
                            if (o === 'event') {

                                customSegments = {};
                                count = 1;
                                // ga('send', 'event', 'category', 'action')
                                if (arguments.length === 4) {
                                    customSegments["category"] = u;
                                }
                                // ga('send', 'event', 'category', 'action', 'label')
                                else if (arguments.length === 5 && typeof arguments[4] === "string") {
                                    customSegments["category"] = u;
                                    customSegments["label"] = t;
                                }
                                // ga('send', 'event', 'category', 'action', {metric:value})
                                else if (arguments.length === 5 && typeof arguments[4] === "object") {
                                    customSegments["category"] = u;
                                    for (i = 0; i < Object.keys(arguments[4]).length; i++) {
                                        customSegments[Object.keys(arguments[4])[i]] = Object.values(arguments[4])[i];
                                    }
                                }
                                // ga('send', 'event', 'category', 'action', 'label', 1)
                                else if (arguments.length >= 6) {
                                    customSegments["category"] = u;
                                    customSegments["label"] = t;
                                    count = l;
                                }

                                Countly.onload.push(function () {
                                    // add event by configured values
                                    Countly.q.push(['add_event', {
                                        key: n,
                                        count: count,
                                        segmentation: customSegments
                                    }]);
                                });

                                if (window.cly_ga_test_mode) {
                                    window.cly_ga_test_logs.push(['add_event', {
                                        key: n,
                                        count: count,
                                        segmentation: customSegments
                                    }]);
                                }
                            }
                            // ga('send', 'pageview')
                            else if (o === 'pageview' && arguments.length === 2) {
                                if (Countly._internals.store('cly_ga:page')) {
                                    Countly.q.push(['track_pageview', Countly._internals.store('cly_ga:page')]);
                                    if (window.cly_ga_test_mode) {window.cly_ga_test_logs.push(['track_pageview', Countly._internals.store('cly_ga:page')]);}
                                }
                                else {
                                    Countly.q.push(['track_pageview']);
                                    if (window.cly_ga_test_mode) {window.cly_ga_test_logs.push(['track_pageview']);}
                                }
                            }
                            // ga('send', 'pageview', 'page')
                            else if (o === 'pageview' && arguments.length >= 3 && typeof arguments[2] === "string") {
                                Countly.q.push(['track_pageview', arguments[2]]);
                                if (window.cly_ga_test_mode) {window.cly_ga_test_logs.push(['track_pageview', arguments[2]]);}
                            }
                            // ga('send', 'pageview', {'customDimension':'customValue'})
                            else if (o === 'pageview' && arguments.length >= 3 && typeof arguments[2] === "object") {
                                // we are not supported tracking pageview with custom objects for now
                                Countly.q.push(['track_pageview']);
                                if (window.cly_ga_test_mode) {window.cly_ga_test_logs.push(['track_pageview']);}
                            }
                            // ga('send', 'social', 'network', 'action', 'target')
                            else if (o === 'social') {
                                Countly.q.push(['add_event', {
                                    "key": n,
                                    "count": 1,
                                    "segmentation": {
                                        "category": o,
                                        "platform": u,
                                        "target": t
                                    }
                                }]);
                                if (window.cly_ga_test_mode) {
                                    window.cly_ga_test_logs.push(['add_event', {
                                        "key": n,
                                        "count": 1,
                                        "segmentation": {"category": o, "platform": u, "target": t}
                                    }]);
                                }
                            }
                            // ga('send', 'screenview', {..})
                            else if (o === 'screenview') {
                                customSegments = {appName: u.appName};

                                if (u.screenName) {customSegments.screenName = u.screenName;}
                                if (u.appVersion) {customSegments.appVersion = u.appVersion;}
                                if (u.appInstallerId) {customSegments.appInstallerId = u.appInstallerId;}
                                if (Countly._internals.store('cly_ga:screenname')) {customSegments.screenName = Countly._internals.store('cly_ga:screenname');}

                                Countly.q.push(['add_event', {
                                    "key": "Screen View",
                                    "count": 1,
                                    "segmentation": customSegments
                                }]);

                                if (window.cly_ga_test_mode) {
                                    window.cly_ga_test_logs.push(['add_event', {
                                        "key": "Screen View",
                                        "count": 1,
                                        "segmentation": customSegments
                                    }]);
                                }
                            }
                            // ga('send', 'exception', {..})
                            else if (o === 'exception') {
                                Countly.log_error(u.exDescription);
                                if (window.cly_ga_test_mode) {window.cly_ga_test_logs.push(u.exDescription);}
                            }
                            // ga('send', 'timing', 'timingCategory', 'timingVar', 'timingValue', 'timingLabel')
                            else if (o === 'timing') {
                                customSegments = {category: u};
                                if (l) {customSegments.label = l;}
                                Countly.q.push(['add_event', {
                                    "key": n,
                                    "count": 1,
                                    "dur": t,
                                    "segmentation": customSegments
                                }]);
                                if (window.cly_ga_test_mode) {
                                    window.cly_ga_test_logs.push(['add_event', {
                                        "key": n,
                                        "count": 1,
                                        "dur": t,
                                        "segmentation": customSegments
                                    }]);
                                }
                            }
                        }
                        // ga('send', {hitType:.., ...})
                        else if (typeof o === 'object') {
                            switch (o.hitType) {
                            // ga('send', {'hitType':'event', ..})
                            case 'event':
                                customSegments = {
                                    'category': o.eventCategory
                                };
                                count = 1;

                                if (o.eventLabel) {customSegments["label"] = o.eventLabel;}
                                if (o.eventValue) {count = o.eventValue;}

                                Countly.q.push(['add_event', {
                                    key: o.eventAction,
                                    count: count,
                                    segmentation: customSegments
                                }]);

                                if (window.cly_ga_test_mode) {
                                    window.cly_ga_test_logs.push(['add_event', {
                                        key: o.eventAction,
                                        count: count,
                                        segmentation: customSegments
                                    }]);
                                }

                                break;
                                // ga('send', {'hitType':'social', ..})
                            case 'social':
                                Countly.q.push(['add_event', {
                                    "key": o.socialAction,
                                    "count": 1,
                                    "segmentation": {
                                        "category": o.hitType,
                                        "platform": o.socialNetwork,
                                        "target": o.socialTarget
                                    }
                                }]);

                                if (window.cly_ga_test_mode) {
                                    window.cly_ga_test_logs.push(['add_event', {
                                        "key": o.socialAction,
                                        "count": 1,
                                        "segmentation": {
                                            "category": o.hitType,
                                            "platform": o.socialNetwork,
                                            "target": o.socialTarget
                                        }
                                    }]);
                                }

                                break;
                                // ga('send', {'hitType':'timing', ..})
                            case 'timing':
                                Countly.q.push(['add_event', {
                                    "key": o.timingVar,
                                    "count": 1,
                                    "dur": o.timingValue,
                                    "segmentation": {
                                        "category": o.timingCategory
                                    }
                                }]);

                                if (window.cly_ga_test_mode) {
                                    window.cly_ga_test_logs.push(['add_event', {
                                        "key": o.timingVar,
                                        "count": 1,
                                        "dur": o.timingValue,
                                        "segmentation": {"category": o.timingCategory}
                                    }]);
                                }
                                break;
                                // ga('send', {'hitType':'pageview', 'page':'page'})
                            case 'pageview':
                                Countly.q.push(['track_pageview', o.page]);
                                if (window.cly_ga_test_mode) {
                                    window.cly_ga_test_logs.push(['track_pageview', o.page]);
                                }
                                break;
                            }
                        }
                        break;
                        // ga('create', '..')
                    case 'create':
                        // ga('create', .., 'auto', '..')
                        if (arguments.length === 4 && arguments[2] === 'auto') {
                            Countly._internals.store('cly_ga:id', o);
                            if (window.cly_ga_test_mode) {
                                window.cly_ga_test_logs.push({
                                    'stored': Countly._internals.store('cly_ga:id'),
                                    'value': o
                                });
                            }
                            window.ga_adapter_integrated = true;
                            // ga('create', .., callback)
                        } else if (arguments.length === 3) {
                            Countly._internals.store('cly_ga:id', o);
                            if (window.cly_ga_test_mode) {
                                window.cly_ga_test_logs.push({
                                    'stored': Countly._internals.store('cly_ga:id'),
                                    'value': o
                                });
                            }
                            window.ga_adapter_integrated = true;
                        }
                        break;
                        // ga('set', '..')
                    case 'set':
                        // ga('set', 'page', '/login.html')
                        if (o === 'page') {
                            Countly._internals.store('cly_ga:page', u);
                        }
                        // ga('set', 'screenname', 'High scores')
                        else if (o === 'screenname') {
                            Countly._internals.store('cly_ga:screenname', u);
                            if (window.cly_ga_test_mode) {
                                window.cly_ga_test_logs.push({
                                    'stored': Countly._internals.store('cly_ga:screenname'),
                                    'value': u
                                });
                            }
                        }
                        // ga('set', 'dimension', 'custom data')
                        else if (arguments.length === 3) {
                            Countly.q.push(['userData.set', o, u]);
                            if (window.cly_ga_test_mode) {
                                window.cly_ga_test_logs.push(['userData.set', o, u]);
                            }
                        }
                        // ga('set', {key:val, anotherKey: anotherVal})
                        else if (arguments.length === 2 && typeof o === 'object') {
                            Countly.q.push(['user_details', {custom: o}]);
                            if (window.cly_ga_test_mode) {
                                window.cly_ga_test_logs.push(['user_details', {custom: o}]);
                            }
                        }
                        break;
                        // ga('ecommerce:addTransaction', {..})
                    case 'ecommerce:addTransaction':
                        customSegments = {
                            "id": o.id,
                            "affiliation": o.affiliation,
                            "shipping": o.shipping,
                            "tax": o.tax
                        };

                        if (o.currency) {customSegments["currency"] = o.currency;}

                        Countly.q.push(['add_event', {
                            "key": c,
                            "count": 1,
                            "sum": o.revenue,
                            "segmentation": customSegments
                        }]);

                        if (window.cly_ga_test_mode) {
                            window.cly_ga_test_logs.push(['add_event', {
                                "key": c,
                                "count": 1,
                                "sum": o.revenue,
                                "segmentation": customSegments
                            }]);
                        }

                        break;
                        // ga('ecommerce:addItem', {..})
                    case 'ecommerce:addItem':
                        customSegments = {
                            "id": o.id,
                            "name": o.name,
                            "sku": o.sku,
                            "category": o.category
                        };

                        if (o.currency) {customSegments["currency"] = o.currency;}

                        cart.push(['add_event', {
                            "key": c,
                            "count": o.quantity,
                            "sum": o.price,
                            "segmentation": customSegments
                        }]);

                        Countly._internals.store('cly_ecommerce:cart', cart);

                        if (window.cly_ga_test_mode) {
                            window.cly_ga_test_logs.push(['add_event', {
                                "key": c,
                                "count": o.quantity,
                                "sum": o.price,
                                "segmentation": customSegments
                            }]);
                        }

                        break;
                        // ga('ecommerce:send')
                    case 'ecommerce:send':
                        var firstLength;
                        if (window.cly_ga_test_mode) {
                            firstLength = cart.length;
                        }
                        for (i = 0; i < cart.length; i++) {
                            Countly.q.push(cart[i]);
                        }
                        cart = [];
                        Countly._internals.store('cly_ecommerce:cart', cart);

                        if (window.cly_ga_test_mode) {
                            window.cly_ga_test_logs.push({first: firstLength, last: cart.length});
                        }
                        break;
                        // ga('ecommerce:clear')
                    case 'ecommerce:clear':
                        cart = [];
                        Countly._internals.store('cly_ecommerce:cart', cart);

                        if (window.cly_ga_test_mode) {
                            window.cly_ga_test_logs.push(Countly._internals.store('cly_ecommerce:cart'));
                        }
                        break;
                    default:
                        break;
                    }
                }
            };
            // apply old countly calls to overrided function
            while(gaCountlyArray.length) {
                var args = gaCountlyArray.shift();
                ga_countly.apply(window, args);
            }
        });

        // check variable for gaAdapter is loaded?
        setTimeout(function check() {
            if (window.ga._signature) {return setTimeout(check, 125);}
            old_ga = window.ga;

            while (gaCalls.length) {
                var args = gaCalls.shift();
                ga_countly.apply(window, args);
            }

            window.ga = function () {
                ga_countly.apply(window, arguments);
                return old_ga.apply(this, arguments);
            };
        }, 125);
    };
}());<|endoftext|>


<commit_before>//META{"name":"GMedia"}*//
/*
    Defines a plugin for BetterDiscord that allows for the playback of multimedia content using HTML5 audio and video.
    Builds on the premise of mediaSupport.plugin.js
*/

var GMedia = function () { }
GMedia.prototype = {
  start: function () { this.convert() },
  load: function () { },
  unload: function () { },
  stop: function () { },
  onMessage: function () { setTimeout(this.convert(), 3000) },
  onSwitch: function () { this.convert() },
  observer: function (e) { },
  getSettingsPanel: function () { return '' },
  getName: function () { return 'GMedia' },
  getDescription: function () { return 'Adds HTML5 media support to Discord.
 Based on mediaSupport.plugin.js' },
  getVersion: function () { return '1.1.2' },
  getAuthor: function () { return 'gn0mesort' },
  convert: function () {
    let targets = $('.attachment-inner a, .markup>a') // Select targets
    let scroller = $('.scroller.messages')[0] // Select scroller
    for (let i = targets.length - 1; i >= 0; --i) { // For each targer
      let target = $(targets[i]) // Select the target
      let scroll = scroller.scrollHeight - scroller.scrollTop === scroller.clientHeight // Calculate scroll value
      if (!target.attr('handled.gnomesort.media') && target.attr('href')) { // If there's an href and not handled
        let href = target.attr('href').replace(/^(https?)/g, 'https') // Get the href
        let type = href.split('.')[href.split('.').length - 1] // Get the file type
        let fileName = href.split('/')[href.split('/').length - 1] // Get the file name
        if (type === 'mp4' || type === 'webm') { // If video
          let video = $(`<video style="height: 320px; width: 30vw;" src="${encodeURI(href)}" type="video/${type}" controls=""></video>`) // Create video element
          let metaData = null // Declare metadata
          console.log(`Media Found! type is ${type} & href is ${href}`) // Log
          target.replaceWith(video) // Replace the link with the video
          metaData = video.parent().find('.metadata') // Find the metadata element
          if (metaData.length > 0) { // If the metadata exists
            metaData[0].innerText += ` - ${fileName} - ${type}` // Fill video metadata
          } else { // Otherwise
            video.parent().append(`<div class="metadata"><a href="${href}">${href}</a></div>`) // Create metadata
          }
          video.parent().attr('handled.gnomesort.media', true) // Set handled
        } else if (type === 'mp3' || type === 'ogg' || type === 'wav') { // If audio
          if (type === 'mp3') { type = 'mpeg' } // Convert mp3 to mpeg type
          let audio = $(`<audio src="${encodeURI(href)}" type="audio/${type}" controls=""></audio>`) // Create audio element
          let metaData = null // Declare metadata
          console.log(`Media Found! type is ${type} & href is ${href}`) // Log
          target.replaceWith(audio) // Replace link with audio
          metaData = audio.parent().find('.metadata') // Find the metadata element
          if (metaData.length > 0) { // If metadata exists
            metaData[0].innerText += ` - ${fileName} - ${type}` // Fill video metadata
          } else { // Otherwise
            audio.parent().append(`<div class="metadata"><a href="${href}">${href}</a></div>`) // Create metadata
          }
          audio.parent().attr('handled.gnomesort.media', true) // Set handled
        } else { scroll = false } // If no file is found don't scroll
      } else { scroll = false } // If skipping target don't scroll
      if (scroll) { // If the message window needs to be scrolled
        scroller.scrollTop = scroller.scrollHeight // Scroll to bottom
        console.log('Scrolling to most recent!') // Log scrolling
      }
    }
  }
}
<commit_msg>Cleanup GMedia<commit_after>//META{"name":"GMedia"}*//
/*
    Defines a plugin for BetterDiscord that allows for the playback of multimedia content using HTML5 audio and video.
    Builds on the premise of mediaSupport.plugin.js
*/

var GMedia = function () { }
GMedia.prototype = {
  start: function () { this.convert() },
  load: function () { },
  unload: function () { },
  stop: function () { },
  onMessage: function () { setTimeout(this.convert(), 3000) },
  onSwitch: function () { this.convert() },
  observer: function (e) { },
  getSettingsPanel: function () { return '' },
  getName: function () { return 'GMedia' },
  getDescription: function () { return 'Adds HTML5 media support to Discord.
 Based on mediaSupport.plugin.js' },
  getVersion: function () { return '1.1.3' },
  getAuthor: function () { return 'gn0mesort' },
  convert: function () {
    let targets = $('.attachment-inner a, .markup>a') // Select targets
    let scroller = $('.scroller.messages')[0] // Select scroller
    let scroll = scroller.scrollHeight - scroller.scrollTop === scroller.clientHeight // Calculate scroll value
    for (let i = targets.length - 1; i >= 0; --i) { // For each targer
      let target = $(targets[i]) // Select the target
      if (!target.attr('handled.gnomesort.media') && target.attr('href')) { // If there's an href and not handled
        let href = target.attr('href').replace(/^(https?)/g, 'https') // Get the href
        let type = href.split('.')[href.split('.').length - 1].replace(/mp3/g, 'mpeg') // Get the file type
        let fileName = href.split('/')[href.split('/').length - 1] // Get the file name
        let metaDataElement = $(`<div class="metadata" style="font-size: 11px; color: gray"><a href="${href}" style="font-size: 11px" handled.gnomesort.media="true">${href}</a><br />${fileName} - ${type}</div>`)
        let metaData = null
        let data = null
        if (type === 'mp4' || type === 'webm') { // If video
          data = $(`<video style="height: 320px; width: 30vw;" src="${encodeURI(href)}" type="video/${type}" controls=""></video>`) // Create video element
        } else if (type === 'mpeg' || type === 'ogg' || type === 'wav') {
          data = $(`<audio src="${encodeURI(href)}" type="audio/${type}" controls=""></audio>`) // Create audio element
        } else { scroll = false }
        if (data) {
          console.log(`Media Found! type is ${type} & href is ${href}`) // Log
          target.replaceWith(data) // Replace the link with the video
          metaData = data.parent().find('.metadata') // Find the metadata element
          if (metaData.length > 0) { // If the metadata exists
            metaData.replaceWith(metaDataElement)
          } else { // Otherwise
            data.parent().append(metaDataElement) // Create metadata
          }
          data.parent().attr('handled.gnomesort.media', true) // Set handled
        }
      } else { scroll = false } // If no file is found don't scroll
    }
    if (scroll) { // If the message window needs to be scrolled
      scroller.scrollTop = scroller.scrollHeight // Scroll to bottom
      console.log('Scrolling to most recent!') // Log scrolling
    }
  }
}

<|endoftext|>


<commit_before>// ==UserScript==
// @id             iitc-plugin-draw-resonators@xelio
// @name           IITC plugin: Draw resonators
// @category       Layer
// @version        0.4.1.@@DATETIMEVERSION@@
// @namespace      https://github.com/jonatkins/ingress-intel-total-conversion
// @updateURL      @@UPDATEURL@@
// @downloadURL    @@DOWNLOADURL@@
// @description    [@@BUILDNAME@@-@@BUILDDATE@@] Draw resonators on map for currently selected portal.
// @include        https://www.ingress.com/intel*
// @include        http://www.ingress.com/intel*
// @match          https://www.ingress.com/intel*
// @match          http://www.ingress.com/intel*
// @grant          none
// ==/UserScript==

@@PLUGINSTART@@

// PLUGIN START ////////////////////////////////////////////////////////
window.RESONATOR_MIN_ZOOM = 16;

// use own namespace for plugin
window.plugin.drawResonators = function() {};

window.plugin.drawResonators.levelLayerGroup = null;

window.plugin.drawResonators.handledata = function(data) {
window.plugin.drawResonators.levelLayerGroup.clearLayers();
window.plugin.drawResonators.drawData(data);
}

window.plugin.drawResonators.drawData = function(portal) {
if(window.map.getZoom() < window.RESONATOR_MIN_ZOOM) return;
  var portalDetails = portal.portalDetails;
  var portalLatLng = [portalDetails.locationE6.latE6/1E6, portalDetails.locationE6.lngE6/1E6];
  for(var i in portalDetails.resonatorArray.resonators) {
    resoData = portalDetails.resonatorArray.resonators[i];
    if(resoData === null) continue;

    var resoLatLng = window.plugin.drawResonators.getResonatorLatLng(resoData.distanceToPortal, resoData.slot, portalLatLng);

    var resoMarker = window.plugin.drawResonators.createResoMarker(resoData, resoLatLng);
    var connMarker = window.plugin.drawResonators.createConnMarker(resoData, resoLatLng, portalLatLng);

    window.plugin.drawResonators.levelLayerGroup.addLayer(resoMarker);
    window.plugin.drawResonators.levelLayerGroup.addLayer(connMarker);
  }
}

window.plugin.drawResonators.getResonatorLatLng = function(dist, slot, portalLatLng) {
  // offset in meters
  var dn = dist*SLOT_TO_LAT[slot];
  var de = dist*SLOT_TO_LNG[slot];

  // Coordinate offset in radians
  var dLat = dn/EARTH_RADIUS;
  var dLon = de/(EARTH_RADIUS*Math.cos(Math.PI/180*portalLatLng[0]));

  // OffsetPosition, decimal degrees
  var lat0 = portalLatLng[0] + dLat * 180/Math.PI;
  var lon0 = portalLatLng[1] + dLon * 180/Math.PI;

  return [lat0, lon0];
}

window.plugin.drawResonators.createResoMarker = function(resoData, resoLatLng) {
  var resoProperty = {
  fillColor: COLORS_LVL[resoData.level],
  fillOpacity: resoData.energyTotal/RESO_NRG[resoData.level],
  color: '#aaa',
  weight: 1,
  radius: 3,
  opacity: 1,
  clickable: false};
  resoProperty.type = 'resonator';
  resoProperty.details = resoData;
  var reso = L.circleMarker(resoLatLng, resoProperty);
  return reso;
}

window.plugin.drawResonators.createConnMarker = function(resoData, resoLatLng, portalLatLng) {
  var connProperty = {
  opacity: 0.25,
  weight: 2,
  color: '#FFA000',
  dashArray: '0,10' + (new Array(25).join(',8,4')),
  fill: false,
  clickable: false};
  connProperty.type = 'connector';
  connProperty.details = resoData;
  var conn = L.polyline([portalLatLng, resoLatLng], connProperty);
  return conn;
}

window.plugin.drawResonators.zoomListener = function() {
  var ctrl = $('.leaflet-control-layers-selector + span:contains("Resonators")').parent();
  if(window.map.getZoom() < window.RESONATOR_MIN_ZOOM) {
    window.plugin.drawResonators.levelLayerGroup.clearLayers();
    ctrl.addClass('disabled').attr('title', 'Zoom in to show those.');
  } else {
    ctrl.removeClass('disabled').attr('title', 'Select a portal to draw resos');
  };
}

var setup = function() {

  window.plugin.drawResonators.levelLayerGroup = new L.LayerGroup();

  window.addLayerGroup('Resonators', window.plugin.drawResonators.levelLayerGroup, true);

  window.addHook('portalDetailsUpdated', window.plugin.drawResonators.handledata);

  window.map.on('zoomend', function() {
    window.plugin.drawResonators.zoomListener();
  });

}
// PLUGIN END //////////////////////////////////////////////////////////

@@PLUGINEND@@<commit_msg>plugin draw-resonators: clear resonators when portal is deselected. changed hooks used to handle things in a more logical way<commit_after>// ==UserScript==
// @id             iitc-plugin-draw-resonators@xelio
// @name           IITC plugin: Draw resonators
// @category       Layer
// @version        0.5.0.@@DATETIMEVERSION@@
// @namespace      https://github.com/jonatkins/ingress-intel-total-conversion
// @updateURL      @@UPDATEURL@@
// @downloadURL    @@DOWNLOADURL@@
// @description    [@@BUILDNAME@@-@@BUILDDATE@@] Draw resonators on map for currently selected portal.
// @include        https://www.ingress.com/intel*
// @include        http://www.ingress.com/intel*
// @match          https://www.ingress.com/intel*
// @match          http://www.ingress.com/intel*
// @grant          none
// ==/UserScript==

@@PLUGINSTART@@

// PLUGIN START ////////////////////////////////////////////////////////
window.RESONATOR_MIN_ZOOM = 16;

// use own namespace for plugin
window.plugin.drawResonators = function() {};

window.plugin.drawResonators.levelLayerGroup = null;

window.plugin.drawResonators.portalSelected = function(data) {
  // new portal selected - clear any existing resonators..
  window.plugin.drawResonators.levelLayerGroup.clearLayers();

  // then, if a portal is selected...
  if (data.selectedPortalGuid) {
    // draw it's resonators if we have it's details
    var details = portalDetail.get(data.selectedPortalGuid);
    if (details) {
      window.plugin.drawResonators.drawData(details);
    }
  }
}

window.plugin.drawResonators.portalDetailsLoaded = function(data) {
  // the detailed data for a portal was just loaded - if this is the selected portal, draw them

  if (data.guid == window.selectedPortal) {
    window.plugin.drawResonators.levelLayerGroup.clearLayers();
    window.plugin.drawResonators.drawData(data.details);
  }
}

window.plugin.drawResonators.drawData = function(portalDetails) {
  if(window.map.getZoom() < window.RESONATOR_MIN_ZOOM) return;

  var portalLatLng = [portalDetails.locationE6.latE6/1E6, portalDetails.locationE6.lngE6/1E6];
  for(var i in portalDetails.resonatorArray.resonators) {
    resoData = portalDetails.resonatorArray.resonators[i];
    if(resoData === null) continue;

    var resoLatLng = window.plugin.drawResonators.getResonatorLatLng(resoData.distanceToPortal, resoData.slot, portalLatLng);

    var resoMarker = window.plugin.drawResonators.createResoMarker(resoData, resoLatLng);
    var connMarker = window.plugin.drawResonators.createConnMarker(resoData, resoLatLng, portalLatLng);

    window.plugin.drawResonators.levelLayerGroup.addLayer(resoMarker);
    window.plugin.drawResonators.levelLayerGroup.addLayer(connMarker);
  }
}

window.plugin.drawResonators.getResonatorLatLng = function(dist, slot, portalLatLng) {
  // offset in meters
  var dn = dist*SLOT_TO_LAT[slot];
  var de = dist*SLOT_TO_LNG[slot];

  // Coordinate offset in radians
  var dLat = dn/EARTH_RADIUS;
  var dLon = de/(EARTH_RADIUS*Math.cos(Math.PI/180*portalLatLng[0]));

  // OffsetPosition, decimal degrees
  var lat0 = portalLatLng[0] + dLat * 180/Math.PI;
  var lon0 = portalLatLng[1] + dLon * 180/Math.PI;

  return [lat0, lon0];
}

window.plugin.drawResonators.createResoMarker = function(resoData, resoLatLng) {
  var resoProperty = {
  fillColor: COLORS_LVL[resoData.level],
  fillOpacity: resoData.energyTotal/RESO_NRG[resoData.level],
  color: '#aaa',
  weight: 1,
  radius: 3,
  opacity: 1,
  clickable: false};
  resoProperty.type = 'resonator';
  resoProperty.details = resoData;
  var reso = L.circleMarker(resoLatLng, resoProperty);
  return reso;
}

window.plugin.drawResonators.createConnMarker = function(resoData, resoLatLng, portalLatLng) {
  var connProperty = {
  opacity: 0.25,
  weight: 2,
  color: '#FFA000',
  dashArray: '0,10' + (new Array(25).join(',8,4')),
  fill: false,
  clickable: false};
  connProperty.type = 'connector';
  connProperty.details = resoData;
  var conn = L.polyline([portalLatLng, resoLatLng], connProperty);
  return conn;
}

window.plugin.drawResonators.zoomListener = function() {
  var ctrl = $('.leaflet-control-layers-selector + span:contains("Resonators")').parent();
  if(window.map.getZoom() < window.RESONATOR_MIN_ZOOM) {
    window.plugin.drawResonators.levelLayerGroup.clearLayers();
    ctrl.addClass('disabled').attr('title', 'Zoom in to show those.');
  } else {
    ctrl.removeClass('disabled').attr('title', 'Select a portal to draw resos');
  };
}

var setup = function() {

  window.plugin.drawResonators.levelLayerGroup = new L.LayerGroup();

  window.addLayerGroup('Resonators', window.plugin.drawResonators.levelLayerGroup, true);

  window.addHook('portalSelected', window.plugin.drawResonators.portalSelected);
  window.addHook('portalDetailsLoaded', window.plugin.drawResonators.portalDetailsLoaded);

  window.map.on('zoomend', function() {
    window.plugin.drawResonators.zoomListener();
  });

}
// PLUGIN END //////////////////////////////////////////////////////////

@@PLUGINEND@@
<|endoftext|>


<commit_before>/**
 * Web Actions polyfill.
 * Author: Matt Giuca <mgiuca@chromium.org>
 *
 * Implements a (partial) Web Actions API for demonstration purposes. Note: This
 * API, by design, does things that aren't possible in a polyfill, so this will
 * be broken without specific browser hacks. All work-in-progress; don't get too
 * excited about it.
 */

(function() {

// Polyfill Cache.addAll.
// Not necessary in Chrome 45 with --enable-experimental-web-platform-features.
if (Cache.prototype.addAll === undefined) {
  Cache.prototype.addAll = function(urls) {
    return Promise.all(urls.map(function(url) {
      return this.add(url);
    }.bind(this)));
  }
}

// A base class that implements the EventTarget interface.
function CustomEventTarget() {
  // Map from event type to list of listeners.
  this._listeners = {};
}
CustomEventTarget.prototype = Object.create(EventTarget.prototype);

CustomEventTarget.prototype.addEventListener = function(type, listener,
                                                        useCapture) {
  var listeners = this._listeners;
  var listeners_of_type = listeners[type];
  if (listeners_of_type === undefined) {
    listeners[type] = listeners_of_type = [];
  }

  for (var i = 0; i < listeners_of_type.length; i++) {
    if (listeners_of_type[i] === listener)
      return;
  }

  listeners_of_type.push(listener);
};

CustomEventTarget.prototype.removeEventListener = function(type, listener,
                                                           useCapture) {
  var listeners = this._listeners;
  var listeners_of_type = listeners[type];
  if (listeners_of_type === undefined) {
    listeners[type] = listeners_of_type = [];
  }

  for (var i = 0; i < listeners_of_type.length; i++) {
    if (listeners_of_type[i] === listener) {
      listeners_of_type.splice(i, 1);

      if (listeners_of_type.length == 0)
        delete listeners[type];

      return;
    }
  }
};

CustomEventTarget.prototype.dispatchEvent = function(evt) {
  var listeners = this._listeners;
  var listeners_of_type = listeners[evt.type];
  if (listeners_of_type === undefined) {
    listeners[evt.type] = listeners_of_type = [];
  }

  for (var i = 0; i < listeners_of_type.length; i++) {
    var listener = listeners_of_type[i];
    if (listener.handleEvent !== undefined) {
      listener.handleEvent(evt);
    } else {
      listener.call(evt.target, evt);
    }
  }
};

// Polyfill Navigator.webActions.
if (Navigator.prototype.webActions === undefined) {
  var webActions = {};
  Navigator.prototype.webActions = webActions;

  // An Action is an object representing a web action in flight.
  // Inherit from EventTarget.
  webActions.Action = function(verb, options) {
    CustomEventTarget.call(this);
    this.verb = verb;
    this.options = options;
  };
  webActions.Action.prototype = Object.create(CustomEventTarget.prototype);

  // Performs an action with a given |verb| and |options|.
  webActions.performAction = function(verb, options) {
    return new Promise(function(resolve, reject) {
      // TODO: Implement this properly.
      // For now, just log and resolve with an empty action object.
      console.log("webActions.performAction:", verb, options);

      var action = new webActions.Action(verb, options);

      resolve(action);
    });
  };
}

})();
<commit_msg>Fix webactions-polyfill loading inside Service Worker.<commit_after>/**
 * Web Actions polyfill.
 * Author: Matt Giuca <mgiuca@chromium.org>
 *
 * Implements a (partial) Web Actions API for demonstration purposes. Note: This
 * API, by design, does things that aren't possible in a polyfill, so this will
 * be broken without specific browser hacks. All work-in-progress; don't get too
 * excited about it.
 */

(function() {

// Polyfill Cache.addAll.
// Not necessary in Chrome 45 with --enable-experimental-web-platform-features.
if (Cache.prototype.addAll === undefined) {
  Cache.prototype.addAll = function(urls) {
    return Promise.all(urls.map(function(url) {
      return this.add(url);
    }.bind(this)));
  }
}

// A base class that implements the EventTarget interface.
function CustomEventTarget() {
  // Map from event type to list of listeners.
  this._listeners = {};
}
CustomEventTarget.prototype = Object.create(EventTarget.prototype);

CustomEventTarget.prototype.addEventListener = function(type, listener,
                                                        useCapture) {
  var listeners = this._listeners;
  var listeners_of_type = listeners[type];
  if (listeners_of_type === undefined) {
    listeners[type] = listeners_of_type = [];
  }

  for (var i = 0; i < listeners_of_type.length; i++) {
    if (listeners_of_type[i] === listener)
      return;
  }

  listeners_of_type.push(listener);
};

CustomEventTarget.prototype.removeEventListener = function(type, listener,
                                                           useCapture) {
  var listeners = this._listeners;
  var listeners_of_type = listeners[type];
  if (listeners_of_type === undefined) {
    listeners[type] = listeners_of_type = [];
  }

  for (var i = 0; i < listeners_of_type.length; i++) {
    if (listeners_of_type[i] === listener) {
      listeners_of_type.splice(i, 1);

      if (listeners_of_type.length == 0)
        delete listeners[type];

      return;
    }
  }
};

CustomEventTarget.prototype.dispatchEvent = function(evt) {
  var listeners = this._listeners;
  var listeners_of_type = listeners[evt.type];
  if (listeners_of_type === undefined) {
    listeners[evt.type] = listeners_of_type = [];
  }

  for (var i = 0; i < listeners_of_type.length; i++) {
    var listener = listeners_of_type[i];
    if (listener.handleEvent !== undefined) {
      listener.handleEvent(evt);
    } else {
      listener.call(evt.target, evt);
    }
  }
};

// Polyfill Navigator.webActions.
// The prototype of |navigator| is Navigator in normal pages, WorkerNavigator in
// Web Workers. Support either case.
var navigator_proto =
    (self.WorkerNavigator !== undefined ? WorkerNavigator : Navigator)
        .prototype;
if (navigator_proto.webActions === undefined) {
  var webActions = {};
  navigator_proto.webActions = webActions;

  // An Action is an object representing a web action in flight.
  // Inherit from EventTarget.
  webActions.Action = function(verb, options) {
    CustomEventTarget.call(this);
    this.verb = verb;
    this.options = options;
  };
  webActions.Action.prototype = Object.create(CustomEventTarget.prototype);

  // Performs an action with a given |verb| and |options|.
  webActions.performAction = function(verb, options) {
    return new Promise(function(resolve, reject) {
      // TODO: Implement this properly.
      // For now, just log and resolve with an empty action object.
      console.log("webActions.performAction:", verb, options);

      var action = new webActions.Action(verb, options);

      resolve(action);
    });
  };
}

})();
<|endoftext|>


<commit_before>$(document).ready(function(){$(".options a").on("click", function(e) {e.preventDefault();if($(this).hasClass("active")) {return;}$(".options a").removeClass("active");$(this).addClass("active");var clickid = $(this).attr("id");$("#listdisplay").fadeOut(240, function(){if(clickid == "thumbnails-list"){console.log("SKIN: thumbnails view");$(this).addClass("thumbview");}else {console.log("SKIN: list view");$(this).removeClass("thumbview");}$("#listdisplay").fadeIn(200);});});});<commit_msg>Deleted<commit_after><|endoftext|>


<commit_before>'use strict';

var gulpConfig = require(__dirname + '/../gulpfile').config;

var sessionPage = require(__dirname + '/e2e/pages/session');

exports.config = {
  allScriptsTimeout: 90000,

  // Connect directly to chrome and firefox
  // Solves issues with stalled Sellenium server
  // https://github.com/angular/protractor/blob/master/docs/server-setup.md#connecting-directly-to-browser-drivers
  directConnect: true,

  specs: [
    'e2e/**/*.js'
  ],

  multiCapabilities: [{
   'browserName': 'chrome',
   'chromeOptions' : {
       args: ['--lang=en',
              '--window-size=1024,800']
     },
   }, {
   'browserName': 'chrome',
   'chromeOptions' : {
    args: ['--lang=en',
           '--window-size=350,650']
     },
  }],

  baseUrl: 'http://' + gulpConfig.serverTest.host + ':' + gulpConfig.serverTest.port + '/',

  framework: 'jasmine2',

  jasmineNodeOpts: {
    defaultTimeoutInterval: 2500000
  },

  suites: {
    session: 'e2e/session.js'
  },

  onPrepare: function() {
    var registerPage = new sessionPage.Register();

    registerPage.get();
    registerPage.register();

    return browser.driver.executeScript('return window.innerWidth >= 992;').then((desktop) => {
      global.isDesktop = desktop;
    });
  }
};
<commit_msg>Revert "Connect protractor directly with browsers"<commit_after>'use strict';

var gulpConfig = require(__dirname + '/../gulpfile').config;

var sessionPage = require(__dirname + '/e2e/pages/session');

exports.config = {
  allScriptsTimeout: 90000,

  specs: [
    'e2e/**/*.js'
  ],

  multiCapabilities: [{
   'browserName': 'chrome',
   'chromeOptions' : {
       args: ['--lang=en',
              '--window-size=1024,800']
     },
   }, {
   'browserName': 'chrome',
   'chromeOptions' : {
    args: ['--lang=en',
           '--window-size=350,650']
     },
  }],

  baseUrl: 'http://' + gulpConfig.serverTest.host + ':' + gulpConfig.serverTest.port + '/',

  framework: 'jasmine2',

  jasmineNodeOpts: {
    defaultTimeoutInterval: 2500000
  },

  suites: {
    session: 'e2e/session.js'
  },

  onPrepare: function() {
    var registerPage = new sessionPage.Register();

    registerPage.get();
    registerPage.register();

    return browser.driver.executeScript('return window.innerWidth >= 992;').then((desktop) => {
      global.isDesktop = desktop;
    });
  }
};
<|endoftext|>


<commit_before>$(function(){

  'use strict';

  var map,
      video;

  // Circle nav on the homepage.
  $('.homepage .hero a').on( 'click', function( ev ){

    var target = $( this ).attr('href');
    ev.preventDefault();
    $('html, body').animate({ scrollTop: $( target ).position().top }, 200);

  });

  // Change the underlying data link for graph when a different radio is selected
  $('#map_radios').on('change', function( ev ){
    var radio = $(this).find('input[type=radio]:checked');
    if( radio.val() === 'r' ){
      $( '#map-title' ).find('a.underlying').attr('href', 'explore#!/as_of_year=2013,2012,2011&property_type=1,2&owner_occupancy=1&action_taken=1&loan_purpose=3&lien_status=1&select=state_name,county_name,as_of_year,count&section=summary');
    } else {
      $( '#map-title' ).find('a.underlying').attr('href', 'explore#!/as_of_year=2013,2012,2011&property_type=1,2&owner_occupancy=1&action_taken=1&loan_purpose=1&lien_status=1&select=state_name,county_name,as_of_year,count&section=summary');
    }
  });

  // Map toggling on the homepage.
  map = (function(){

    var map = {};

    map.base = L.mapbox.map('map', 'cfpb.fxomkj4i').setView([39.54, -97.87], 4);

    map.layers = {
      r2013: L.mapbox.tileLayer('cfpb.6uwyiudi'),
      r2012: L.mapbox.tileLayer('cfpb.2yugzaor'),
      p2013: L.mapbox.tileLayer('cfpb.z2z3q5mi'),
      p2012: L.mapbox.tileLayer('cfpb.pbjoflxr')
    };

    map.layersLoaded = 0;

    map.firstLoad = function() {

      var selectedLayer = map.getSelectedLayer(),
          otherLayers = _.omit(  map.layers, selectedLayer );

      map.addAndHide( map.layers[ selectedLayer ] );

      $( document ).one('scroll',function( e ){
        _( otherLayers ).forEach( function( layer ){
          map.addAndHide( layer );
        });

        map.layersLoaded = 1;
      });

    };

    map.addAndHide = function(layer) {
      layer.addTo( map.base );

      // IE and MapBox don't completely get along so we only add snazzy
      // fade-in effects with non-IE browsers.

      if ( !$('body').hasClass('lt-ie9') ) {
        map.base.addLayer( layer );
        $( layer._tileContainer ).hide();
      }

    };

    // In order to get a nice fade when we toggle between layers,
    // add them before they are needed, but don't add the currently
    // hidden ones until a scroll event is fired.
    map.addLayers = function() {
      if ( map.layersLoaded ){
        _( map.layers ).forEach( function( layer ){
          addAndHide( layer );
        });
      }else{
        map.firstLoad();
      }

    };

    map.showMap = function() {

      this.addLayers();
      this.showLayer();

      $('#map-title').removeClass('hidden');

      $('#map .controls input').on( 'change', function( ev ){
        $( this ).parent().addClass('selected').siblings().removeClass('selected');
        map.showLayer();
      });

    };

    map.getSelectedLayer = function() {

      var type = $('#map .type input:checked').val(),
          year = $('#map .year input:checked').val();
      return type + year;

    };

    map.showLayer = function() {

      var selectedLayer = map.getSelectedLayer(),
          otherLayers = _.omit( map.layers, selectedLayer );

      // IE and MapBox don't completely get along so we only add snazzy
      // fade-in effects with non-IE browsers.
      if ( !$('body').hasClass('lt-ie9') ) {

        $( map.layers[ selectedLayer ]._tileContainer ).fadeIn();

        _( otherLayers ).forEach( function( layer ){
          $( layer._tileContainer ).fadeOut( 800 );
        });

      } else {

        map.base.addLayer( map.layers[ selectedLayer ] );

        _( otherLayers ).forEach( function( layer ){
          map.base.removeLayer( layer );
        });

      }

    };

    map.fixLegend = function() {

      var under30,
          over30;

      under30 = $('#map .legend-labels li').first().html();
      $('#map .legend-labels li').first().html( under30 + '< -30%' );

      over30 = $('#map .legend-labels li:nth-last-child(2)').html();
      $('#map .legend-labels li:nth-last-child(2)').html( over30.replace( 'Over 30%', '> 30%' ) );

      $('#map .my-legend .legend-title').html('Percentage Change');

      $('#map .my-legend .legend-source').hide();

    };

    map.init = function() {

      this.base.scrollWheelZoom.disable();

      map.showMap();
      $('#map-title').removeClass('hidden');

      // Ensure the correct layer is shown whenever the user zooms.
      this.base.on( 'zoomend', function(){

        this.showLayer();

      }.bind( this ));

      // Fix the darn legend.
      this.base.on( 'ready', function(){

        map.fixLegend();

      }.bind( this ));

      $('#map .help').tooltip({
        placement: 'right',
        container: 'body',
        title: function getTooltipTitle(){
          return $( this ).next('.help-text').html();
        }
      }).on('shown.bs.tooltip', function () {
        $('.tooltip').css({
          'margin-left': '15px',
          'margin-top': '6px',
          'width': '250px'
        });
      }).on('hide.bs.tooltip', function () {
        $('.tooltip').css({
          'margin-left': '0',
          'margin-top': '0',
          'width': 'auto'
        });
      });

      // IE8 doesn't hear the map 'ready' event so here's a setinterval hack.
      if ( $('body').hasClass('lt-ie9') ) {
        var checkForLegend = setInterval( function(){
          if ( $('#map .my-legend .legend-source').length ) {
            map.fixLegend();
            clearInterval( checkForLegend );
          }
        }, 1000);
      }

    };

    map.init();

  })();

  // Methods to open and close the youtube video overlay on the homepage.
  video = (function(){

    var $vid = $('#youtube'),
        $embed = $(''),
        $exit = $('#youtube .exit'),
        pos = $('.video').position().top + ( $('section.video').height() / 2 );

    return {

      isOpen: false,

      init: function() {

      },

      open: function(){
        $vid.css( 'top', pos + 'px' )
            .removeClass('hidden')
            .animate({ 'height': '100%', 'margin-top': -pos + 'px' }, 300, 'swing', function(){
              setTimeout( function(){
                $vid.append( $embed );
                $exit.show();
                onYouTubeIframeAPIReady();
              }, 500 );
            });
        $embed.css( 'height', $(window).height() - 60 + 'px')
              .css( 'width', $(window).width() - 60 + 'px');
        this.isOpen = true;
      },

      close: function(){
        $embed.remove();
        $exit.hide();
        $vid.addClass('closing');
        setTimeout( function(){
          $vid.css({ 'height': 0, 'margin-top': 0 }).addClass('hidden').removeClass('closing');
        }, 500 );
        this.isOpen = false;
      }

    };
  })();

  // Remove the video embed for now.
  video.init();

  // Video overlay.
  $('a.launch-youtube').on( 'click', function( ev ){

    ev.preventDefault();
    video.open();

  });

  // Autoplay video if requested.
  if ( window.location.hash && window.location.hash === '#video' ) {
    video.open();
  }

  // Close video overlay
  $( document ).on( 'keyup', function( ev ) {

    if ( ev.which === 27 ) {
      ev.preventDefault();
      video.close();
    }

  });

  // Close video overlay
  $( 'section.video .exit, #youtube' ).on( 'click', function( ev ) {

      ev.preventDefault();

      if ( video.isOpen ) {
        video.close();
      }

  });

});
<commit_msg>Added error handler for function call<commit_after>$(function(){

  'use strict';

  var map,
      video;

  // Circle nav on the homepage.
  $('.homepage .hero a').on( 'click', function( ev ){

    var target = $( this ).attr('href');
    ev.preventDefault();
    $('html, body').animate({ scrollTop: $( target ).position().top }, 200);

  });

  // Change the underlying data link for graph when a different radio is selected
  $('#map_radios').on('change', function( ev ){
    var radio = $(this).find('input[type=radio]:checked');
    if( radio.val() === 'r' ){
      $( '#map-title' ).find('a.underlying').attr('href', 'explore#!/as_of_year=2013,2012,2011&property_type=1,2&owner_occupancy=1&action_taken=1&loan_purpose=3&lien_status=1&select=state_name,county_name,as_of_year,count&section=summary');
    } else {
      $( '#map-title' ).find('a.underlying').attr('href', 'explore#!/as_of_year=2013,2012,2011&property_type=1,2&owner_occupancy=1&action_taken=1&loan_purpose=1&lien_status=1&select=state_name,county_name,as_of_year,count&section=summary');
    }
  });

  // Map toggling on the homepage.
  map = (function(){

    var map = {};

    map.base = L.mapbox.map('map', 'cfpb.fxomkj4i').setView([39.54, -97.87], 4);

    map.layers = {
      r2013: L.mapbox.tileLayer('cfpb.6uwyiudi'),
      r2012: L.mapbox.tileLayer('cfpb.2yugzaor'),
      p2013: L.mapbox.tileLayer('cfpb.z2z3q5mi'),
      p2012: L.mapbox.tileLayer('cfpb.pbjoflxr')
    };

    map.layersLoaded = 0;

    map.firstLoad = function() {

      var selectedLayer = map.getSelectedLayer(),
          otherLayers = _.omit(  map.layers, selectedLayer );

      map.addAndHide( map.layers[ selectedLayer ] );

      $( document ).one('scroll',function( e ){
        _( otherLayers ).forEach( function( layer ){
          map.addAndHide( layer );
        });

        map.layersLoaded = 1;
      });

    };

    map.addAndHide = function(layer) {
      layer.addTo( map.base );

      // IE and MapBox don't completely get along so we only add snazzy
      // fade-in effects with non-IE browsers.

      if ( !$('body').hasClass('lt-ie9') ) {
        map.base.addLayer( layer );
        $( layer._tileContainer ).hide();
      }

    };

    // In order to get a nice fade when we toggle between layers,
    // add them before they are needed, but don't add the currently
    // hidden ones until a scroll event is fired.
    map.addLayers = function() {
      if ( map.layersLoaded ){
        _( map.layers ).forEach( function( layer ){
          addAndHide( layer );
        });
      }else{
        map.firstLoad();
      }

    };

    map.showMap = function() {

      this.addLayers();
      this.showLayer();

      $('#map-title').removeClass('hidden');

      $('#map .controls input').on( 'change', function( ev ){
        $( this ).parent().addClass('selected').siblings().removeClass('selected');
        map.showLayer();
      });

    };

    map.getSelectedLayer = function() {

      var type = $('#map .type input:checked').val(),
          year = $('#map .year input:checked').val();
      return type + year;

    };

    map.showLayer = function() {

      var selectedLayer = map.getSelectedLayer(),
          otherLayers = _.omit( map.layers, selectedLayer );

      // IE and MapBox don't completely get along so we only add snazzy
      // fade-in effects with non-IE browsers.
      if ( !$('body').hasClass('lt-ie9') ) {

        $( map.layers[ selectedLayer ]._tileContainer ).fadeIn();

        _( otherLayers ).forEach( function( layer ){
          $( layer._tileContainer ).fadeOut( 800 );
        });

      } else {

        map.base.addLayer( map.layers[ selectedLayer ] );

        _( otherLayers ).forEach( function( layer ){
          map.base.removeLayer( layer );
        });

      }

    };

    map.fixLegend = function() {

      var under30,
          over30;

      under30 = $('#map .legend-labels li').first().html();
      $('#map .legend-labels li').first().html( under30 + '< -30%' );

      over30 = $('#map .legend-labels li:nth-last-child(2)').html();
      $('#map .legend-labels li:nth-last-child(2)').html( over30.replace( 'Over 30%', '> 30%' ) );

      $('#map .my-legend .legend-title').html('Percentage Change');

      $('#map .my-legend .legend-source').hide();

    };

    map.init = function() {

      this.base.scrollWheelZoom.disable();

      map.showMap();
      $('#map-title').removeClass('hidden');

      // Ensure the correct layer is shown whenever the user zooms.
      this.base.on( 'zoomend', function(){

        this.showLayer();

      }.bind( this ));

      // Fix the darn legend.
      this.base.on( 'ready', function(){

        map.fixLegend();

      }.bind( this ));

      $('#map .help').tooltip({
        placement: 'right',
        container: 'body',
        title: function getTooltipTitle(){
          return $( this ).next('.help-text').html();
        }
      }).on('shown.bs.tooltip', function () {
        $('.tooltip').css({
          'margin-left': '15px',
          'margin-top': '6px',
          'width': '250px'
        });
      }).on('hide.bs.tooltip', function () {
        $('.tooltip').css({
          'margin-left': '0',
          'margin-top': '0',
          'width': 'auto'
        });
      });

      // IE8 doesn't hear the map 'ready' event so here's a setinterval hack.
      if ( $('body').hasClass('lt-ie9') ) {
        var checkForLegend = setInterval( function(){
          if ( $('#map .my-legend .legend-source').length ) {
            map.fixLegend();
            clearInterval( checkForLegend );
          }
        }, 1000);
      }

    };

    map.init();

  })();

  // Methods to open and close the youtube video overlay on the homepage.
  video = (function(){

    var $vid = $('#youtube'),
        $embed = $(''),
        $exit = $('#youtube .exit'),
        pos = $('.video').position().top + ( $('section.video').height() / 2 );

    return {

      isOpen: false,

      init: function() {

      },

      open: function(){
        $vid.css( 'top', pos + 'px' )
            .removeClass('hidden')
            .animate({ 'height': '100%', 'margin-top': -pos + 'px' }, 300, 'swing', function(){
              setTimeout( function(){
                $vid.append( $embed );
                $exit.show();
                if( onYouTubeIframeAPIReady() ){
                  onYouTubeIframeAPIReady();
                }
              }, 500 );
            });
        $embed.css( 'height', $(window).height() - 60 + 'px')
              .css( 'width', $(window).width() - 60 + 'px');
        this.isOpen = true;
      },

      close: function(){
        $embed.remove();
        $exit.hide();
        $vid.addClass('closing');
        setTimeout( function(){
          $vid.css({ 'height': 0, 'margin-top': 0 }).addClass('hidden').removeClass('closing');
        }, 500 );
        this.isOpen = false;
      }

    };
  })();

  // Remove the video embed for now.
  video.init();

  // Video overlay.
  $('a.launch-youtube').on( 'click', function( ev ){

    ev.preventDefault();
    video.open();

  });

  // Autoplay video if requested.
  if ( window.location.hash && window.location.hash === '#video' ) {
    video.open();
  }

  // Close video overlay
  $( document ).on( 'keyup', function( ev ) {

    if ( ev.which === 27 ) {
      ev.preventDefault();
      video.close();
    }

  });

  // Close video overlay
  $( 'section.video .exit, #youtube' ).on( 'click', function( ev ) {

      ev.preventDefault();

      if ( video.isOpen ) {
        video.close();
      }

  });

});
<|endoftext|>


<commit_before>import { createStore } from 'redux';
import rootReducer from '../reducers';

export default function configureStoreDEV(initialState) {
  const store = createStore(rootReducer, initialState);
  if (module.hot) {
    // Enable Webpack hot module replacement for reducers
    module.hot.accept('../reducers', () => {
      const nextReducer = require('../reducers');
      store.replaceReducer(nextReducer);
    });
  }

  return store;
}
<commit_msg>improve configureStore bundling<commit_after>import { createStore } from 'redux';
import rootReducer from '../reducers';

export function configureStore(initialState) {
  return createStore(rootReducer, initialState);
}

export function configureStoreHMR(initialState) {
  const store = createStore(rootReducer, initialState);
  // Enable Webpack hot module replacement for reducers
  module.hot.accept('../reducers', () => {
    const nextReducer = require('../reducers');
    store.replaceReducer(nextReducer);
  });

  return store;
}

export default module.hot ? configureStoreHMR : configureStore;
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2012, Joyent, Inc. All rights reserved.
 */

/* Test the Boilerplate API endpoints */

var Replicator = require('../lib/index');
var REPLICATOR;

var Logger = require('bunyan');

var LOG = new Logger({
	name: 'replicator-test',
    stream: process.stdout,
    serializers: Logger.stdSerializers,
	level: 'trace'
});

var REMOTE_UFDS = {
	url: 'ldaps://10.99.99.14',
	maxConnections: 1,
	bindDN: 'cn=root',
	bindCredentials: 'secret'
};

var REPLICATOR_OPTS = {
	log: LOG,
	remoteUfds: REMOTE_UFDS
};

exports.initReplicator = function(t) {
	REPLICATOR = new Replicator(REPLICATOR_OPTS);
    t.done();
};

exports.step = function(t) {
    t.done();
};

<commit_msg>CAPI-138: accept UFDS_IP in tests<commit_after>/*
 * Copyright (c) 2012, Joyent, Inc. All rights reserved.
 */

/* Test the Boilerplate API endpoints */

var Replicator = require('../lib/index');
var REPLICATOR;

var bunyan = require('bunyan');

var LOG = bunyan.createLogger({
	name: 'replicator-test',
        stream: process.stdout,
        serializers: bunyan.stdSerializers,
	level: 'trace'
});

var REMOTE_UFDS = {
	url: 'ldaps://' + (process.env.UFDS_IP || '10.99.99.14'),
	maxConnections: 1,
	bindDN: 'cn=root',
	bindCredentials: 'secret'
};

var REPLICATOR_OPTS = {
	log: LOG,
	remoteUfds: REMOTE_UFDS
};

exports.initReplicator = function(t) {
	REPLICATOR = new Replicator(REPLICATOR_OPTS);
        t.done();
};

exports.step = function(t) {
        t.done();
};

<|endoftext|>


<commit_before>function openTag (type, closing, attr) {
  var html = ['<' + type]

  for (var prop in attr) {
    // A falsy value is used to remove the attribute.
    // EG: attr[false] to remove, attr['false'] to add
    if (attr[prop]) html.push(prop + '="' + attr[prop] + '"')
  }
  return html.join(' ') + (!closing ? ' /' : '') + '>'
}

function closeTag (type) {
  return '</' + type + '>'
}

function createElement (type, closing, attr, contents) {
  return openTag(type, closing, attr)
    + (closing ? (contents || '')
    + closeTag(type) : '')
}

module.exports = createElement
<commit_msg>remove string/createElement — dupe of helper/createElement<commit_after><|endoftext|>