<commit_before>//Object that controls Checkbox Feed Status

function Checky(opts) {
    this.feed_selection   = opts.feed_selection;
    this.check_feed_id    = opts.check_feed_id;
    this.category_feed_id = opts.category_feed_id;
    this.click_all        = opts.click_all;
    this.checky_bar       = opts.checky_bar;
}

Checky.prototype.init = function() {

    var me = this;
    $(document).delegate(me.feed_selection, 'change', function(e) {
        var mode        = $(this).val();
        var checkFeed   = $(me.check_feed_id);
        var categoryFeed = $(me.category_feed_id);
        var ifChecked   = checkFeed.is(':checked');
        var currentUrl  = $(location).attr('href');
        var baseUrl     = $(this).attr('base-url');
        var checkyBar   = $('.checky-bar');
        var collection  = new Array();
        var exam_collection = new Array();

        if (ifChecked && mode != 'none') {

            var conf, color, parent_id;

            if (mode == 'restore' || mode == 'inbox') {
                conf     = confirm("Are you sure you want to restore these feedbacks?");
            }

            if (mode == 'remove') {
                conf  = confirm("Are you sure you want to permanently remove these feedbacks?");
            }

            if (mode == 'publish') {
                conf     = confirm("Are you sure want to publish these feedbacks?");
            }

            if (mode == 'feature') {
                conf     = confirm("Are you sure want to feature these feedbacks?");
            }

            if (mode == 'delete') {
                conf     = confirm("Are you sure want to delete these feedbacks?");
            }

            if (conf) {
                checkFeed.each(function() {
                    if ($(this).is(':checked')) {
                        if ( $('#' + $(this).val()).is(":hidden") == false ) {

                            var my_parent  = $(this).parents('div.feedback-group')
                            var my_ratings = $(this).siblings('.feed-ratings').val();
                            var my_perm = $(this).siblings('.perm-state').val();
                            var feed_unit  = '#' + $(this).val();

                            var data = {
                                "feedid": $(this).val()
                              , "contactid": $(this).siblings('.contact-feed-id').val()
                              , "siteid": $(this).siblings('.site-feed-id').val()
                              , "rating": $(this).siblings('.feed-ratings').val()
                              , "parent_id": my_parent.attr('id')
                              , "perm": my_perm
                              , "mode": mode
                              , "total_units": my_parent.attr('data-total')
                            };

                            //console.log(window.location.pathname.match(/published|contacts/g));
                            if(my_ratings != 'POOR' && my_perm == 1) {
                                //console.log("all can pass");
                                process_feedbacks(collection, data, feed_unit);
                            }

                            if(my_ratings == 'POOR' && (mode == 'delete' || mode == 'restore' || mode == 'remove')) {
                                //console.log("poor rated feeds cannot pass");
                                process_feedbacks(collection, data, feed_unit);
                            }

                            if((my_ratings != 'POOR' && my_perm == 3/*(my_perm == 2 || my_perm == 3)*/) && (mode == 'delete' || mode == 'restore' || mode == 'remove')) {
                                //console.log("private and limited feeds cannot pass");
                                process_feedbacks(collection, data, feed_unit);
                            }
                            exam_collection.push(data);
                        }
                    }
                });

                var limited_perm_feeds = exam_collection.filter(function(el) {
                    return (el.perm == 3 || el.perm == 2) && (el.mode == 'publish' || el.mode == 'feature');
                });

                var poor_feeds = exam_collection.filter(function(el) {
                    return el.rating == 'POOR' && (el.mode == 'publish' || el.mode == 'feature');
                });

                /*
                var restricted_feeds = exam_collection.filter(function(el) {
                    return (el.perm == 3 || el.perm == 2 || el.rating == 'POOR') && (el.mode == 'publish' || el.mode == 'feature');
                });
                */

                //console.log(limited_perm_feeds);
                //console.log(poor_feeds);
                //console.log(restricted_feeds);
                if(limited_perm_feeds.length > 0 && poor_feeds.length > 0) {
                    confirm("Warning: There are feedback that have been marked as private/limited and poor and will not be processed.");
                }

                if(limited_perm_feeds.length > 0 && poor_feeds.length == 0) {
                    if(limited_perm_feeds.length == 1) {
                        confirm("Warning: This feedback has been marked as private/limited and will not be processed.");
                    } else {
                        confirm("Warning: There are feedback that has been marked as private/limited and will not be processed.");
                    }
                }

                if(poor_feeds.length > 0 && limited_perm_feeds.length == 0) {
                    if(poor_feeds.length == 1) {
                        confirm("Warning: This feedback has been rated as poor and will not be processed.");
                    } else {
                        confirm("Warning: There is feedback that has been rated as poor and will not be processed.");
                    }
                }

                $("option:first", this).prop("selected", true);
                if(collection.length > 0) {
                    /*
                    $.ajax({
                        type: "POST"
                      , data: {
                          'col': mode
                        , 'feed_ids': collection
                        }
                      , url: $(this).attr("hrefaction")
                      , dataType: "json"
                      , beforeSend: function() {
                          var myStatus = new Status();
                          myStatus.notify("Processing...", 1000);
                      }
                      , success: function(msg) {

                          $.ajax({url: "/feedback/bust_hostfeed_data"});

                          for(var key in msg.ui) {
                              $('#' + key).hide();
                          }

                          var message = msg.message;

                          checkyBar.css({
                              'background': '#fef1b5'
                            , 'width': '200px'
                            , 'right': '35%'
                            , 'top': '15%'
                            , 'text-align': 'center'
                            , 'padding': '5px'
                            , 'font-weight': 'bold'
                          }).html(message).show();

                          //this is for clicking to make this mothafucka vanish
                          mouse_is_inside = false;
                       }
                    });
                    */
                }

            }

            $(this).val("none");
            $('.click-all').attr('checked', false);
            checkFeed.attr('checked', false);
        } else {
            $('.click-all').attr('checked', false);
        }
    });
}

Checky.prototype.clickAll = function() {
    var me = this;
    $(document).delegate(me.click_all, 'click', function(e) {
        if (this.checked) {
            $(me.check_feed_id).prop("checked", true);
            $(me.click_all).prop("checked", true);
        } else {
            $(me.check_feed_id).prop("checked", false);
            $(me.click_all).prop("checked", false);
        }
    });
}

function process_feedbacks(collection, data, units) {
    collection.push(data);
    //units to vanished
    $(units).fadeOut(300, function() { $(this).hide(); });
}
<commit_msg>are you going to leave?<commit_after>//Object that controls Checkbox Feed Status

function Checky(opts) {
    this.feed_selection   = opts.feed_selection;
    this.check_feed_id    = opts.check_feed_id;
    this.category_feed_id = opts.category_feed_id;
    this.click_all        = opts.click_all;
    this.checky_bar       = opts.checky_bar;
}

Checky.prototype.init = function() {

    var me = this;
    $(document).delegate(me.feed_selection, 'change', function(e) {
        var mode        = $(this).val();
        var checkFeed   = $(me.check_feed_id);
        var categoryFeed = $(me.category_feed_id);
        var ifChecked   = checkFeed.is(':checked');
        var currentUrl  = $(location).attr('href');
        var baseUrl     = $(this).attr('base-url');
        var checkyBar   = $('.checky-bar');
        var collection  = new Array();
        var exam_collection = new Array();

        if (ifChecked && mode != 'none') {

            var conf, color, parent_id;

            if (mode == 'restore' || mode == 'inbox') {
                conf     = confirm("Are you sure you want to restore these feedbacks?");
            }

            if (mode == 'remove') {
                conf  = confirm("Are you sure you want to permanently remove these feedbacks?");
            }

            if (mode == 'publish') {
                conf     = confirm("Are you sure want to publish these feedbacks?");
            }

            if (mode == 'feature') {
                conf     = confirm("Are you sure want to feature these feedbacks?");
            }

            if (mode == 'delete') {
                conf     = confirm("Are you sure want to delete these feedbacks?");
            }

            if (conf) {
                checkFeed.each(function() {
                    if ($(this).is(':checked')) {
                        if ( $('#' + $(this).val()).is(":hidden") == false ) {

                            var my_parent  = $(this).parents('div.feedback-group')
                            var my_ratings = $(this).siblings('.feed-ratings').val();
                            var my_perm = $(this).siblings('.perm-state').val();
                            var feed_unit  = '#' + $(this).val();

                            var data = {
                                "feedid": $(this).val()
                              , "contactid": $(this).siblings('.contact-feed-id').val()
                              , "siteid": $(this).siblings('.site-feed-id').val()
                              , "rating": $(this).siblings('.feed-ratings').val()
                              , "parent_id": my_parent.attr('id')
                              , "perm": my_perm
                              , "mode": mode
                              , "total_units": my_parent.attr('data-total')
                            };

                            //console.log(window.location.pathname.match(/published|contacts/g));
                            if(my_ratings != 'POOR' && my_perm == 1) {
                                //console.log("all can pass");
                                process_feedbacks(collection, data, feed_unit);
                            }

                            if(my_ratings == 'POOR' && (mode == 'delete' || mode == 'restore' || mode == 'remove')) {
                                //console.log("poor rated feeds cannot pass");
                                process_feedbacks(collection, data, feed_unit);
                            }

                            if((my_ratings != 'POOR' && my_perm == 3/*(my_perm == 2 || my_perm == 3)*/) && (mode == 'delete' || mode == 'restore' || mode == 'remove')) {
                                //console.log("private and limited feeds cannot pass");
                                process_feedbacks(collection, data, feed_unit);
                            }
                            exam_collection.push(data);
                        }
                    }
                });

                var limited_perm_feeds = exam_collection.filter(function(el) {
                    return (el.perm == 3 || el.perm == 2) && (el.mode == 'publish' || el.mode == 'feature');
                });

                var poor_feeds = exam_collection.filter(function(el) {
                    return el.rating == 'POOR' && (el.mode == 'publish' || el.mode == 'feature');
                });

                if(limited_perm_feeds.length > 0 && poor_feeds.length > 0) {
                    confirm("Warning: There are feedback that have been marked as private/limited and poor and will not be processed.");
                }

                if(limited_perm_feeds.length > 0 && poor_feeds.length == 0) {
                    if(limited_perm_feeds.length == 1) {
                        confirm("Warning: This feedback has been marked as private/limited and will not be processed.");
                    } else {
                        confirm("Warning: There are feedback that has been marked as private/limited and will not be processed.");
                    }
                }

                if(poor_feeds.length > 0 && limited_perm_feeds.length == 0) {
                    if(poor_feeds.length == 1) {
                        confirm("Warning: This feedback has been rated as poor and will not be processed.");
                    } else {
                        confirm("Warning: There is feedback that has been rated as poor and will not be processed.");
                    }
                }

                $("option:first", this).prop("selected", true);
                if(collection.length > 0) {
                    /*
                    $.ajax({
                        type: "POST"
                      , data: {
                          'col': mode
                        , 'feed_ids': collection
                        }
                      , url: $(this).attr("hrefaction")
                      , dataType: "json"
                      , beforeSend: function() {
                          var myStatus = new Status();
                          myStatus.notify("Processing...", 1000);
                      }
                      , success: function(msg) {

                          $.ajax({url: "/feedback/bust_hostfeed_data"});

                          for(var key in msg.ui) {
                              $('#' + key).hide();
                          }

                          var message = msg.message;

                          checkyBar.css({
                              'background': '#fef1b5'
                            , 'width': '200px'
                            , 'right': '35%'
                            , 'top': '15%'
                            , 'text-align': 'center'
                            , 'padding': '5px'
                            , 'font-weight': 'bold'
                          }).html(message).show();

                          //this is for clicking to make this mothafucka vanish
                          mouse_is_inside = false;
                       }
                    });
                    */
                }

            }

            $(this).val("none");
            $('.click-all').attr('checked', false);
            checkFeed.attr('checked', false);
        } else {
            $('.click-all').attr('checked', false);
        }
    });
}

Checky.prototype.clickAll = function() {
    var me = this;
    $(document).delegate(me.click_all, 'click', function(e) {
        if (this.checked) {
            $(me.check_feed_id).prop("checked", true);
            $(me.click_all).prop("checked", true);
        } else {
            $(me.check_feed_id).prop("checked", false);
            $(me.click_all).prop("checked", false);
        }
    });
}

function process_feedbacks(collection, data, units) {
    collection.push(data);
    //units to vanished
    $(units).fadeOut(300, function() { $(this).hide(); });
}
<|endoftext|>


<commit_before>/*global expect, describe, it, beforeEach, spyOn, afterEach, runs, waitsFor */
/*global Backbone, jQuery, zeit*/
(function ($) {
    "use strict";

    describe("VariantEditor", function () {
        beforeEach(function() {
            var self = this,
                flag = false;

            // Create temporary DOM
            this.editor_container = $(
                '
');
            this.preview_container = $('
');
            $('body').append(this.editor_container);
            $('body').append(this.preview_container);

            // Mock AJAX calls to return hard coded response
            spyOn($, 'ajax').andCallFake(function (options) {
                var d = $.Deferred(),
                    response = {
                        focus_x: 0.5,
                        focus_y: 0.5,
                        zoom: 0.3,
                        brightness: 0.5,
                        contrast: 0.5,
                        saturation: 0.5,
                        sharpness: 0.5,
                        is_default: true,
                        url: '/fanstatic/zeit.content.image.test/master_image.jpg'
                    };
                d.resolve(response);
                options.success(response);
                return d.promise();
            });

            // Setup Editor and wait that it was rendered
            self.preview = new zeit.content.image.browser.VariantList();
            self.variant = new zeit.content.image.Variant({'id': 'square'});
            zeit.content.image.VARIANTS.add(self.variant);
            zeit.content.image.VARIANTS.trigger('reset');

            self.view = new zeit.content.image.browser.VariantEditor();

            runs(function() {
                self.view.on('render', function() {
                    flag = true;
                });
                self.view.prepare();
            });

            waitsFor(function () {
                return flag;
            }, "VariantEditor did not render", 500);
        });

        afterEach(function () {
            this.editor_container.remove();
            this.preview_container.remove();
        });

        it("should display circle relative to given focus point", function () {
            var self = this;
            runs(function() {
                expect(self.view.focuspoint.position()).toEqual({left: 110, top: 62});
            });
        });

        it("should save focus point after drag", function () {
            var self = this;
            runs(function() {
                var spy = spyOn(Backbone.Model.prototype, "save").andCallThrough();
                self.view.focuspoint.css('left', '55px');
                self.view.focuspoint.css('top', '31px');
                self.view.focuspoint.trigger('dragstop');
                expect(spy).toHaveBeenCalledWith(
                    {"focus_x": 0.25, "focus_y": 0.25, "zoom": 0.3}
                );
            });
        });

        it("should display stored zoom value on load", function() {
            var self = this;
            runs(function() {
                // Since we want to inverse the default zoom-bar behaviour of
                // jqueryui, we also must expect the inverse value, i.e. 100-X
                expect(self.view.zoom_bar.slider('value')).toEqual(100 - 30);
            });
        });

        it("should store zoom value on change", function() {
            var self = this;
            runs(function() {
                var spy = spyOn(Backbone.Model.prototype, "save").andCallThrough();
                // Since we want to inverse the default zoom-bar behaviour of
                // jqueryui, we also must set the inverse value, i.e. 100-X
                self.view.zoom_bar.slider('value', 100 - 60);
                self.view.zoom_bar.trigger('slidestop');
                expect(spy).toHaveBeenCalledWith(
                    {"focus_x": 0.5, "focus_y": 0.5, "zoom": 0.6}
                );
            });
        });

        it("should have 4 different image enhancements", function() {
            var self = this;
            runs(function() {
                expect(self.view.image_enhancements.length).toBe(4);
            });
        });

        it("should display value of enhancements on load", function() {
            var self = this;
            runs(function() {
                $.each(self.view.image_enhancements, function(i, name) {
                    var input = self.view[name + '_input'],
                        bar = self.view[name + '_bar'];

                    expect(input.val()).toEqual('-100');
                    expect(bar.slider("value")).toEqual(-100);
                });
            });
        });

        it("should store enhancement when changing slider", function() {
            var self = this;
            runs(function() {
                var spy = spyOn(Backbone.Model.prototype, "set").andCallThrough();
                $.each(self.view.image_enhancements, function(i, name) {
                    var bar = self.view[name + '_bar'];
                    bar.slider("value", 100);
                    bar.trigger("slidestop");
                    expect(spy).toHaveBeenCalledWith(name, 1.5);
                });
            });
        });

        it("should store enhancement when changing input field", function() {
            var self = this;
            runs(function() {
                var spy = spyOn(Backbone.Model.prototype, "set").andCallThrough();
                $.each(self.view.image_enhancements, function(i, name) {
                    var input_field = self.view[name + '_input'];
                    input_field.val(100);
                    input_field.trigger("blur");
                    expect(spy).toHaveBeenCalledWith(name, 1.5);
                });
            });
        });

        it("should switch back to default variant on save", function() {
            var self = this;
            runs(function() {
                self.view.switch_focus(
                    self.variant, self.preview.model_views[self.variant.id]);
                expect(self.view.current_model.id).toBe('square');
                $('input[value=Speichern]').click();
                expect(self.view.current_model.id).toBe('default');
            });
        });

        it("should switch back to default variant on delete", function() {
            var self = this;
            runs(function() {
                self.view.switch_focus(
                    self.variant, self.preview.model_views[self.variant.id]);
                expect(self.view.current_model.id).toBe('square');
                $('input[value=Verwerfen]').click();
                expect(self.view.current_model.id).toBe('default');
            });
        });

        it("should call destroy on every variant on reset", function() {
            var self = this,
                spy = spyOn(Backbone.Model.prototype, "destroy").andCallThrough();
            $("input[value='Alle Formate zurücksetzen']").click();
            expect(spy.calls.length).toEqual(1);
        });

        it("should update images of all variants on reset", function() {
            var self = this,
                image = self.preview_container.find('img.preview'),
                image_url = image.attr('src');
            $("input[value='Alle Formate zurücksetzen']").click();
            expect(image.attr('src')).not.toBe(image_url);
        });

        it("should update master image on save", function() {
            var self = this,
                image = self.editor_container.find('img.editor'),
                image_url = image.attr('src');
            self.view.save();
            expect(image.attr('src')).not.toBe(image_url);
        });
    });
}(jQuery));
<commit_msg>re DEV-826: Extract Jasmine test configuration to setUp method, to prepare splitting tests by purpose.<commit_after>/*global expect, describe, it, beforeEach, spyOn, afterEach, runs, waitsFor */
/*global Backbone, jQuery, zeit*/
(function ($) {
    "use strict";

    var editor_container,
        preview_container,
        setUp = function() {
            var editor, preview, variant,
                flag = false;

            // Create temporary DOM
            editor_container = $(
                '
');
            preview_container = $('
');
            $('body').append(editor_container);
            $('body').append(preview_container);

            // Mock AJAX calls to return hard coded response
            spyOn($, 'ajax').andCallFake(function (options) {
                var d = $.Deferred(),
                    response = {
                        focus_x: 0.5,
                        focus_y: 0.5,
                        zoom: 0.3,
                        brightness: 0.5,
                        contrast: 0.5,
                        saturation: 0.5,
                        sharpness: 0.5,
                        is_default: true,
                        url: '/fanstatic/zeit.content.image.test/master_image.jpg'
                    };
                d.resolve(response);
                options.success(response);
                return d.promise();
            });

            // Setup Editor and wait that it was rendered
            preview = new zeit.content.image.browser.VariantList();
            variant = new zeit.content.image.Variant({'id': 'square'});
            zeit.content.image.VARIANTS.add(variant);
            zeit.content.image.VARIANTS.trigger('reset');

            editor = new zeit.content.image.browser.VariantEditor();

            runs(function() {
                editor.on('render', function() {
                    flag = true;
                });
                editor.prepare();
            });

            waitsFor(function () {
                return flag;
            }, "VariantEditor did not render", 500);

            return {editor: editor, preview: preview, variant: variant};
        };

    describe("VariantEditor", function () {
        beforeEach(function() {
            var self = this,
                result = setUp();
            self.view = result.editor;
            self.preview = result.preview;
            self.variant = result.variant;
        });

        afterEach(function () {
            editor_container.remove();
            preview_container.remove();
        });

        it("should display circle relative to given focus point", function () {
            var self = this;
            runs(function() {
                expect(self.view.focuspoint.position()).toEqual({left: 110, top: 62});
            });
        });

        it("should save focus point after drag", function () {
            var self = this;
            runs(function() {
                var spy = spyOn(Backbone.Model.prototype, "save").andCallThrough();
                self.view.focuspoint.css('left', '55px');
                self.view.focuspoint.css('top', '31px');
                self.view.focuspoint.trigger('dragstop');
                expect(spy).toHaveBeenCalledWith(
                    {"focus_x": 0.25, "focus_y": 0.25, "zoom": 0.3}
                );
            });
        });

        it("should display stored zoom value on load", function() {
            var self = this;
            runs(function() {
                // Since we want to inverse the default zoom-bar behaviour of
                // jqueryui, we also must expect the inverse value, i.e. 100-X
                expect(self.view.zoom_bar.slider('value')).toEqual(100 - 30);
            });
        });

        it("should store zoom value on change", function() {
            var self = this;
            runs(function() {
                var spy = spyOn(Backbone.Model.prototype, "save").andCallThrough();
                // Since we want to inverse the default zoom-bar behaviour of
                // jqueryui, we also must set the inverse value, i.e. 100-X
                self.view.zoom_bar.slider('value', 100 - 60);
                self.view.zoom_bar.trigger('slidestop');
                expect(spy).toHaveBeenCalledWith(
                    {"focus_x": 0.5, "focus_y": 0.5, "zoom": 0.6}
                );
            });
        });

        it("should have 4 different image enhancements", function() {
            var self = this;
            runs(function() {
                expect(self.view.image_enhancements.length).toBe(4);
            });
        });

        it("should display value of enhancements on load", function() {
            var self = this;
            runs(function() {
                $.each(self.view.image_enhancements, function(i, name) {
                    var input = self.view[name + '_input'],
                        bar = self.view[name + '_bar'];

                    expect(input.val()).toEqual('-100');
                    expect(bar.slider("value")).toEqual(-100);
                });
            });
        });

        it("should store enhancement when changing slider", function() {
            var self = this;
            runs(function() {
                var spy = spyOn(Backbone.Model.prototype, "set").andCallThrough();
                $.each(self.view.image_enhancements, function(i, name) {
                    var bar = self.view[name + '_bar'];
                    bar.slider("value", 100);
                    bar.trigger("slidestop");
                    expect(spy).toHaveBeenCalledWith(name, 1.5);
                });
            });
        });

        it("should store enhancement when changing input field", function() {
            var self = this;
            runs(function() {
                var spy = spyOn(Backbone.Model.prototype, "set").andCallThrough();
                $.each(self.view.image_enhancements, function(i, name) {
                    var input_field = self.view[name + '_input'];
                    input_field.val(100);
                    input_field.trigger("blur");
                    expect(spy).toHaveBeenCalledWith(name, 1.5);
                });
            });
        });

        it("should switch back to default variant on save", function() {
            var self = this;
            runs(function() {
                self.view.switch_focus(
                    self.variant, self.preview.model_views[self.variant.id]);
                expect(self.view.current_model.id).toBe('square');
                $('input[value=Speichern]').click();
                expect(self.view.current_model.id).toBe('default');
            });
        });

        it("should switch back to default variant on delete", function() {
            var self = this;
            runs(function() {
                self.view.switch_focus(
                    self.variant, self.preview.model_views[self.variant.id]);
                expect(self.view.current_model.id).toBe('square');
                $('input[value=Verwerfen]').click();
                expect(self.view.current_model.id).toBe('default');
            });
        });

        it("should call destroy on every variant on reset", function() {
            var self = this,
                spy = spyOn(Backbone.Model.prototype, "destroy").andCallThrough();
            $("input[value='Alle Formate zurücksetzen']").click();
            expect(spy.calls.length).toEqual(1);
        });

        it("should update images of all variants on reset", function() {
            var self = this,
                image = self.preview.$('img.preview'),
                image_url = image.attr('src');
            $("input[value='Alle Formate zurücksetzen']").click();
            expect(image.attr('src')).not.toBe(image_url);
        });

        it("should update master image on save", function() {
            var self = this,
                image = self.view.$('img.editor'),
                image_url = image.attr('src');
            self.view.save();
            expect(image.attr('src')).not.toBe(image_url);
        });
    });
}(jQuery));
<|endoftext|>


<commit_before>improc.filteR = {

/*
Filter definitions for improc.js list of filters are given in wiki  */

    gblur:

    embross:
    embross2:
    sharpen:
    edge:
    edge2:
    redfilter:
    greenfilter:
    bluefilter:
    Grayscale:
    imageflip:

}<commit_msg>function signatures<commit_after>improc.filteR = {

/*
Filter definitions for improc.js list of filters are given in wiki  */

    gblur: function()
    {
    }

    embross: function()
    {
}
    embross2: function()
{
}
    sharpen: function()
{
}

    edge: function()
{
}
    edge2: function()
{
}

    redfilter:
    greenfilter:
    bluefilter:
    Grayscale:
    imageflip:
    snoweffect:
    invert:

}<|endoftext|>


<commit_before>var pushCharacter = function(character) {}

var calculate = function() {}

var buttons = document.querySelectorAll(".button");

for (var i = 0; i < buttons.length; i++) {
    buttons[i].onclick = pushCharacter(buttons[i].innerHTML);
}<commit_msg>Indications for the calculator<commit_after>var input = /* Use document.querySelector("element") to target the input */;
var pushCharacter = function(character) {
    /* This will push the character to the input.value */
    input.value = input.value + /* Guess what */;
}

var calculate = function() {
    /* Set input.value to eval(input.value).toString() */
}

var buttons = document.querySelectorAll(".button");

for (var i = 0; i < buttons.length; i++) {
    buttons[i].onclick = pushCharacter(buttons[i].innerHTML);
}
<|endoftext|>


<commit_before>import Immutable from 'immutable';

import Dispatcher from '../dispatcher';
import TimelineConstants from '../constants/TimelineConstants';
import bzAPI from '../utils/bzAPI';
import githubAPI from '../utils/githubAPI.js';
import edwinAPI from '../utils/edwinAPI.js';
import BugStore from '../stores/BugStore.js';
import UserStore from '../stores/UserStore.js';
import PromiseExt from '../utils/PromiseExt.js';
import ProgressActions from '../actions/ProgressActions.js';

/**
 * Fetch bugs from the API, and dispatch an event to replace the bugs
 * in the store with the new bugs.
 * @param {Object} query Bugzilla API query.
 * @promises {undefined} Signals completion with no data.
 */
export function loadBugs(teamSlug, query) {
  const user = UserStore.getAll();

  ProgressActions.startTask('Load bugs');

  if (user.get('loggedIn')) {
    query.api_key = user.get('apiKey');
  }

  return bzAPI.getBugs(query)
  .then(newBugs => {
    Dispatcher.dispatch({
      type: TimelineConstants.ActionTypes.SET_RAW_BUGS,
      team: teamSlug,
      newBugs,
    });

    let idsForCommentTags = BugStore.getAll(teamSlug)
      .filter(bug => bug.get('state') !== TimelineConstants.BugStates.NOT_READY)
      .map(bug => bug.get('id'));

    return loadCommentTags(idsForCommentTags);
  })
  .then(() => {
    // Pull all the bug ids we need for blocker bugs
    return loadBlockerBugs(BugStore.getBlockerBugIds(teamSlug));
  })
  .then(() => ProgressActions.endTask('Load bugs'))
  // signal completion
  .then(() => undefined);
}

/**
 * Fetch PRs from the API, and dispatch an event to replace the PRs
 * in the store with the new PRs.
 * @param  {string} repo A repo name like "mythmon/edwin".
 * @promises {undefined} Signals completion with no data.
 */
export function loadPRs(repos) {
  ProgressActions.startTask('Load PRs');
  Promise.all(repos.map(repo => githubAPI.getPRs(repo)))
  .then(prLists => {
    let flattened = [];
    for (let prList of prLists) {
      flattened = flattened.concat(prList);
    }
    Dispatcher.dispatch({
      type: TimelineConstants.ActionTypes.SET_RAW_PRS,
      newPRs: flattened,
    });
  })
  .then(() => ProgressActions.endTask('Load PRs'))
  // signal completion
  .then(() => undefined);
}

/**
 * Fetch Teams from the API, and dispatch an event to replace the teams
 * in the store with the new ones.
 * @promise {undefined} Signals copmletion with no data.
 */
export function loadTeams() {
  ProgressActions.startTask('Load teams');
  return edwinAPI.getTeams()
  .then(newTeams => {
    Dispatcher.dispatch({
      type: TimelineConstants.ActionTypes.SET_RAW_TEAMS,
      newTeams,
    });
  })
  .then(() => ProgressActions.endTask('Load teams'))
  // signal completion
  .then(() => undefined);
}

/**
 * Get all comment tags for all `bugs`, and fire events for each.
 * @param {Array<Immutable.Map>} An array of immutable.js objects representing
 * the bugs to get comment tags for.
 */
export function loadCommentTags(bugIds) {
  let params = {};

  const user = UserStore.getAll();

  ProgressActions.startTask('Load comments');
  if (user.get('loggedIn')) {
    params.api_key = user.get('apiKey');
  }

  let commentPromises = bugIds.map(bugId => (
    bzAPI.getBugComments(bugId, params)
    .then(comments => {
      return {bugId, commentId: comments[0].id, tags: comments[0].tags};
    })
  )).toJS();

  return PromiseExt.allResolves(commentPromises)
  .then(commentSpecs => {
    Dispatcher.dispatch({
      type: TimelineConstants.ActionTypes.SET_COMMENT_TAGS,
      commentSpecs,
    });
  })
  .then(() => ProgressActions.endTask('Load comments'));
}

/**
 * Fetch data for blocker bugs.
 * @param {Array<Immutable.List>} List of bug ids
 */
export function loadBlockerBugs(bugIds) {
  if (bugIds.size > 0) {
    let bugQuery = {id: Array.from(bugIds).join(',')};
    const user = UserStore.getAll();
    ProgressActions.startTask('Load blockers');

    if (user.get('loggedIn')) {
      query.api_key = user.get('apiKey');
    }

    return bzAPI.getBugs(bugQuery)
    .then(newBugs => {
      Dispatcher.dispatch({
        type: TimelineConstants.ActionTypes.SET_BLOCKER_BUGS,
        newBugs,
      });
    })
    .then(() => ProgressActions.endTask('Load blockers'));
  } else {
    return Promise.resolve();
  }
}

export function grabBug(bugId) {
  const user = UserStore.getAll();

  if (!user.get('loggedIn')) {
    throw new Error("Can't grab bugs without being loggd in.");
  }

  const assigned_to = user.get('username');
  const api_key = user.get('apiKey');

  bzAPI.modifyBug(bugId, {
    status: 'ASSIGNED',
    assigned_to,
    api_key,
  })
  .then(() => {
    Dispatcher.dispatch({
      type: TimelineConstants.ActionTypes.ASSIGN_BUG,
      assigned_to,
      bugId,
    });
  });
}

export function setInternalSort(bugId, sortOrder) {
  Dispatcher.dispatch({
    type: TimelineConstants.ActionTypes.BUG_SET_INTERNAL_SORT,
    bugId,
    sortOrder,
  });
}

export function commitSortOrder() {
  const user = UserStore.getAll();
  if (!user.get('loggedIn')) {
    throw new Error("Can't sort bugs without being loggd in.");
  }
  const apiKey = user.get('apiKey');

  const oldBugMap = BugStore.getMap();
  Dispatcher.dispatch({
    type: TimelineConstants.ActionTypes.BUGS_COMMIT_SORT_ORDER,
  });

  /* `dispatch` is syncronous, so all the bugs have correct comment tags
   * now to represent the order they should be in. Compare the new comment
   * tags with the old comment tags, and commit any diffs to the server.
   * This would be easier if we could just directly update the comment
   * tags, but the bugzilla API doesn't work that way.
   */
  let promises = [];
  const newBugMap = BugStore.getMap();

  for (let [bugId, oldBug] of oldBugMap) {
    const newBug = newBugMap.get(bugId);
    const oldCommentTags = oldBug.get('comment_tags', new Immutable.Set());
    const newCommentTags = newBug.get('comment_tags', new Immutable.Set());
    const toAdd = newCommentTags.subtract(oldCommentTags);
    const toRemove = oldCommentTags.subtract(newCommentTags);

    if (toRemove.count() > 0 || toAdd.count() > 0) {
      promises.push(bzAPI.updateCommentTags({
        commentId: oldBug.get('comment_zero_id'),
        add: toAdd.toJS(),
        remove: toRemove.toJS(),
        apiKey,
      }));
    }
  }

  return Promise.all(promises);
}

export default {
  loadBugs,
  loadPRs,
  loadTeams,
  loadCommentTags,
  grabBug,
  setInternalSort,
  commitSortOrder,
};
<commit_msg>Fix ReferenceError<commit_after>import Immutable from 'immutable';

import Dispatcher from '../dispatcher';
import TimelineConstants from '../constants/TimelineConstants';
import bzAPI from '../utils/bzAPI';
import githubAPI from '../utils/githubAPI.js';
import edwinAPI from '../utils/edwinAPI.js';
import BugStore from '../stores/BugStore.js';
import UserStore from '../stores/UserStore.js';
import PromiseExt from '../utils/PromiseExt.js';
import ProgressActions from '../actions/ProgressActions.js';

/**
 * Fetch bugs from the API, and dispatch an event to replace the bugs
 * in the store with the new bugs.
 * @param {Object} query Bugzilla API query.
 * @promises {undefined} Signals completion with no data.
 */
export function loadBugs(teamSlug, query) {
  const user = UserStore.getAll();

  ProgressActions.startTask('Load bugs');

  if (user.get('loggedIn')) {
    query.api_key = user.get('apiKey');
  }

  return bzAPI.getBugs(query)
  .then(newBugs => {
    Dispatcher.dispatch({
      type: TimelineConstants.ActionTypes.SET_RAW_BUGS,
      team: teamSlug,
      newBugs,
    });

    let idsForCommentTags = BugStore.getAll(teamSlug)
      .filter(bug => bug.get('state') !== TimelineConstants.BugStates.NOT_READY)
      .map(bug => bug.get('id'));

    return loadCommentTags(idsForCommentTags);
  })
  .then(() => {
    // Pull all the bug ids we need for blocker bugs
    return loadBlockerBugs(BugStore.getBlockerBugIds(teamSlug));
  })
  .then(() => ProgressActions.endTask('Load bugs'))
  // signal completion
  .then(() => undefined);
}

/**
 * Fetch PRs from the API, and dispatch an event to replace the PRs
 * in the store with the new PRs.
 * @param  {string} repo A repo name like "mythmon/edwin".
 * @promises {undefined} Signals completion with no data.
 */
export function loadPRs(repos) {
  ProgressActions.startTask('Load PRs');
  Promise.all(repos.map(repo => githubAPI.getPRs(repo)))
  .then(prLists => {
    let flattened = [];
    for (let prList of prLists) {
      flattened = flattened.concat(prList);
    }
    Dispatcher.dispatch({
      type: TimelineConstants.ActionTypes.SET_RAW_PRS,
      newPRs: flattened,
    });
  })
  .then(() => ProgressActions.endTask('Load PRs'))
  // signal completion
  .then(() => undefined);
}

/**
 * Fetch Teams from the API, and dispatch an event to replace the teams
 * in the store with the new ones.
 * @promise {undefined} Signals copmletion with no data.
 */
export function loadTeams() {
  ProgressActions.startTask('Load teams');
  return edwinAPI.getTeams()
  .then(newTeams => {
    Dispatcher.dispatch({
      type: TimelineConstants.ActionTypes.SET_RAW_TEAMS,
      newTeams,
    });
  })
  .then(() => ProgressActions.endTask('Load teams'))
  // signal completion
  .then(() => undefined);
}

/**
 * Get all comment tags for all `bugs`, and fire events for each.
 * @param {Array<Immutable.Map>} An array of immutable.js objects representing
 * the bugs to get comment tags for.
 */
export function loadCommentTags(bugIds) {
  let params = {};

  const user = UserStore.getAll();

  ProgressActions.startTask('Load comments');
  if (user.get('loggedIn')) {
    params.api_key = user.get('apiKey');
  }

  let commentPromises = bugIds.map(bugId => (
    bzAPI.getBugComments(bugId, params)
    .then(comments => {
      return {bugId, commentId: comments[0].id, tags: comments[0].tags};
    })
  )).toJS();

  return PromiseExt.allResolves(commentPromises)
  .then(commentSpecs => {
    Dispatcher.dispatch({
      type: TimelineConstants.ActionTypes.SET_COMMENT_TAGS,
      commentSpecs,
    });
  })
  .then(() => ProgressActions.endTask('Load comments'));
}

/**
 * Fetch data for blocker bugs.
 * @param {Array<Immutable.List>} List of bug ids
 */
export function loadBlockerBugs(bugIds) {
  if (bugIds.size > 0) {
    let bugQuery = {id: Array.from(bugIds).join(',')};
    const user = UserStore.getAll();
    ProgressActions.startTask('Load blockers');

    if (user.get('loggedIn')) {
      bugQuery.api_key = user.get('apiKey');
    }

    return bzAPI.getBugs(bugQuery)
    .then(newBugs => {
      Dispatcher.dispatch({
        type: TimelineConstants.ActionTypes.SET_BLOCKER_BUGS,
        newBugs,
      });
    })
    .then(() => ProgressActions.endTask('Load blockers'));
  } else {
    return Promise.resolve();
  }
}

export function grabBug(bugId) {
  const user = UserStore.getAll();

  if (!user.get('loggedIn')) {
    throw new Error("Can't grab bugs without being loggd in.");
  }

  const assigned_to = user.get('username');
  const api_key = user.get('apiKey');

  bzAPI.modifyBug(bugId, {
    status: 'ASSIGNED',
    assigned_to,
    api_key,
  })
  .then(() => {
    Dispatcher.dispatch({
      type: TimelineConstants.ActionTypes.ASSIGN_BUG,
      assigned_to,
      bugId,
    });
  });
}

export function setInternalSort(bugId, sortOrder) {
  Dispatcher.dispatch({
    type: TimelineConstants.ActionTypes.BUG_SET_INTERNAL_SORT,
    bugId,
    sortOrder,
  });
}

export function commitSortOrder() {
  const user = UserStore.getAll();
  if (!user.get('loggedIn')) {
    throw new Error("Can't sort bugs without being loggd in.");
  }
  const apiKey = user.get('apiKey');

  const oldBugMap = BugStore.getMap();
  Dispatcher.dispatch({
    type: TimelineConstants.ActionTypes.BUGS_COMMIT_SORT_ORDER,
  });

  /* `dispatch` is syncronous, so all the bugs have correct comment tags
   * now to represent the order they should be in. Compare the new comment
   * tags with the old comment tags, and commit any diffs to the server.
   * This would be easier if we could just directly update the comment
   * tags, but the bugzilla API doesn't work that way.
   */
  let promises = [];
  const newBugMap = BugStore.getMap();

  for (let [bugId, oldBug] of oldBugMap) {
    const newBug = newBugMap.get(bugId);
    const oldCommentTags = oldBug.get('comment_tags', new Immutable.Set());
    const newCommentTags = newBug.get('comment_tags', new Immutable.Set());
    const toAdd = newCommentTags.subtract(oldCommentTags);
    const toRemove = oldCommentTags.subtract(newCommentTags);

    if (toRemove.count() > 0 || toAdd.count() > 0) {
      promises.push(bzAPI.updateCommentTags({
        commentId: oldBug.get('comment_zero_id'),
        add: toAdd.toJS(),
        remove: toRemove.toJS(),
        apiKey,
      }));
    }
  }

  return Promise.all(promises);
}

export default {
  loadBugs,
  loadPRs,
  loadTeams,
  loadCommentTags,
  grabBug,
  setInternalSort,
  commitSortOrder,
};
<|endoftext|>


<commit_before>/* global formatUsage:true, formatError:true */
/* exported formatUsage, formatError */

// Rocket.Chat's version of highlight.js that formats blocks of code between
// triple-backticks doesn't support a "plaintext" non-highlighted mode, so
// we fake it with the "diff" language that it does support
formatUsage = text => `\`\`\`diff\n${text}\`\`\``

formatError = msg => {
  return msg.toString()
    // ensure prefixed with bold 'Error:'
    .replace(/(^Error: )?(.*)/, '**Error:** $2')
    // preformat commands or solo options
    .replace(/(\W)((\/\w+)(\s+\-{1,2}[\w_-]+)*|\-{1,2}[\w_-]+)/g, '$1`$2`')
    // make sure nothing got doubly-preformatted
    .replace(/``/g, '`')
}
<commit_msg>too clever by half, and broken -- @bundacia veto<commit_after>/* global formatUsage:true, formatError:true */
/* exported formatUsage, formatError */

// Rocket.Chat's version of highlight.js that formats blocks of code between
// triple-backticks doesn't support a "plaintext" non-highlighted mode, so
// we fake it with the "diff" language that it does support
formatUsage = text => `\`\`\`diff\n${text}\`\`\``

formatError = msg => {
  return msg.toString()
    // ensure prefixed with bold 'Error:'
    .replace(/(^Error: )?(.*)/, '**Error:** $2')
}
<|endoftext|>


<commit_before>/*
*** CUSTOM JS ***
*/

cryLoader();
playSong();

function cryLoader() {
    var i;
    for (i=1; i <= 9; i++) {
        var file_num = '00' + i;
        file_num = file_num.substr(file_num.length - 3, 3);
        audio_id = 'cry-' + file_num + '';

        //load audio
        document.getElementById('cry-wrap').innerHTML += '<audio id='+ audio_id +'><source src="assets/cries/mp3/'+ file_num +'.mp3" type="audio/mpeg"></audio>';

        //load buttons
        document.getElementById('cry-wrap').innerHTML += "<button onclick='document.getElementById(\""+ audio_id +"\").play();'></button>";

        //load draggable images
        document.getElementById('draggable-items').innerHTML += "";
    }
}

function formatFile(file) {

}

function playSong() {
    document.getElementById("play-all").onclick = function() {
        (function myLoop (i) {
            setTimeout(function () {
                console.log(i);
                var file_num = '00' + i;
                file_num = file_num.substr(file_num.length - 3, 3);
                audio_id = 'cry-' + file_num + '';
                document.getElementById(audio_id).play();
                if (++i <= 5) {
                    myLoop(i);
                }
            }, 1000)
        } ) (1);
    };
}

function getDroppedItems() {
    var grid = document.getElementById("drop-grid"),
        descendents = grid.getElementsByTagName("div");

    (function myLoop (i) {
        setTimeout(function () {
            item = descendents[i];
            item_id = item.children[0].getAttribute('id');
            audio_id = 'cry-' + item_id + '';
            console.log(audio_id);
            document.getElementById(audio_id).play();

            if (item.tagName === 'mew') {

            }

            if (++i < descendents.length) {
                myLoop(i);
            }
        }, 1000)
    } ) (0);
}

function resetItems() {
    var items = document.getElementsByClassName('drag-item');
    for (var i = 0; i < items.length; ++i) {
        var item = items[i];
        document.getElementById("draggable-items").appendChild(item);
    }
}

/*** DRAG & DROP ***/
function allowDrop(ev) {
    ev.preventDefault();
}
function drag(ev) {
    ev.dataTransfer.setData("text", ev.target.id);
}
function drop(ev) {
    ev.preventDefault();
    var data = ev.dataTransfer.getData("text");
    ev.target.appendChild(document.getElementById(data));
}<commit_msg>cleanup<commit_after>/*
*** CUSTOM JS ***
*/

cryLoader();
playSong();

function cryLoader() {
    var i;
    for (i=1; i <= 9; i++) {
        var file_num = "00" + i;
        file_num = file_num.substr(file_num.length - 3, 3);
        audio_id = "cry-" + file_num + "";

        //load audio
        document.getElementById('cry-wrap').innerHTML += '<audio id='+ audio_id +'><source src="assets/cries/mp3/'+ file_num +'.mp3" type="audio/mpeg"></audio>';

        //load buttons
        document.getElementById('cry-wrap').innerHTML += "<button onclick='document.getElementById(\""+ audio_id +"\").play();'></button>";

        //load draggable images
        document.getElementById('draggable-items').innerHTML += "";
    }
}

function formatFile(file) {

}

function playSong() {
    document.getElementById("play-all").onclick = function() {
        (function myLoop (i) {
            setTimeout(function () {
                console.log(i);
                var file_num = "00" + i;
                file_num = file_num.substr(file_num.length - 3, 3);
                audio_id = "cry-" + file_num + "";
                document.getElementById(audio_id).play();
                if (++i <= 5) {
                    myLoop(i);
                }
            }, 1000)
        } ) (1);
    };
}

function getDroppedItems() {
    var grid = document.getElementById("drop-grid"),
        descendents = grid.getElementsByTagName("div");

    (function myLoop (i) {
        setTimeout(function () {
            item = descendents[i];
            item_id = item.children[0].getAttribute("id");
            audio_id = "cry-" + item_id + "";
            console.log(audio_id);
            document.getElementById(audio_id).play();

            if (item.tagName === "mew") {

            }

            if (++i < descendents.length) {
                myLoop(i);
            }
        }, 1000)
    } ) (0);
}

function resetItems() {
    var items = document.getElementsByClassName("drag-item");
    for (var i = 0; i < items.length; ++i) {
        var item = items[i];
        document.getElementById("draggable-items").appendChild(item);
    }
}

/*** DRAG & DROP ***/
function allowDrop(ev) {
    ev.preventDefault();
}
function drag(ev) {
    ev.dataTransfer.setData("text", ev.target.id);
}
function drop(ev) {
    ev.preventDefault();
    var data = ev.dataTransfer.getData("text");
    ev.target.appendChild(document.getElementById(data));
}
<|endoftext|>


<commit_before>'use strict';
const request = require('request');
const core = require('./../core/core.js');

/**
 * CREDENTIALS
 **/
const VALIDATION_TOKEN = process.env.FACEBOOK_VALIDATION_TOKEN;
const PAGE_ACCESS_TOKEN = process.env.FACEBOOK_PAGE_ACCESS_TOKEN;

/*
* Fonction appelé par Facbook pour checker le serveur
*/
function webhook(req, res) {
    return req.query['hub.mode'] === 'subscribe' && req.query['hub.verify_token'] === VALIDATION_TOKEN;
}

/*
* Fonction appelé par les routes lors de la reception d'un message
*/
function receivedMessage(req, res) {
    var data = req.body;
    if (data.object === 'page') {
        //Message reçu de Facebook
        data.entry.forEach(function(entry) {
            var pageID = entry.id;
            var timeOfEvent = entry.time;
            entry.messaging.forEach(function(event) {
                if (event.message) {
                    console.log("Event received : ", JSON.stringify(event));
                    extractMessage(event);
                }
            });
        });
    } else {
        //Pour tester via CURL
        extractMessage(req.body);
    }
}
/*
* Fonction qui permet de traiter un message reçu
*/
function extractMessage(event) {
    console.log(JSON.stringify(event));
    var senderID = event.sender.id;
    var recipientID = event.recipient.id;
    var timeOfMessage = event.timestamp;
    var message = event.message;
    request({
        uri: 'https://graph.facebook.com/' + senderID,
        qs: { access_token: PAGE_ACCESS_TOKEN },
        method: 'GET'
    }, function (error, response, body) {
        if (!error && response.statusCode == 200) {
            console.log("Received message from Facebook for user %d at %d with message:",
            senderID, timeOfMessage);
            console.log(JSON.stringify(message));

            var messageId = message.mid;
            var messageText = message.text;
            var messageAttachments = message.attachments;

            var message = {
                channel: "Facebook",
                senderID: senderID,
                timestamp: timeOfMessage,
                text: messageText,
                first_name: body.first_name,
                last_name: body.last_name
            };
            /*
            *   Coordonnées
            */
            if(messageAttachments != undefined && messageAttachments.payload != undefined && messageAttachments.payload.coordinates != undefined) {
                message["location"] = coordinates;
            }

            core.receivedMessage(message);
        } else {
            console.error("Unable to get name of user.");
            console.error(response);
            console.error(error);
        }
    });
}

/*
* Fonction appelé par le core pour envoyer un message sur la channel Facebook
*/
function sendMessage(message) {
    switch(message.type) {
        case "text":
            sendTextMessage(message);
        break;
        case "quickreply":
            sendQuickReplyMessage(message);
        break;
    }
}

/*
* Fonction appelé par le core pour envoyer des messages sur la channel Facebook
*/
function sendMessages(messages) {
    for(var i=0;i<messages.length;i++) {
        sendMessage(messages[i]);
    }
}

/*
* Fonction qui envoie un message de type text
*/
function sendTextMessage(message) {
    console.log("Messages sended : ", JSON.stringify(message));
    if(message.senderID != undefined && message.text != undefined) {
        var messageData = {
            recipient: {
                id: message.senderID
            },
            message: {
                text: message.text
            }
        };
        callSendAPI(messageData);
    }
}

/*
* Fonction qui envoie un message de type quickreply
*/
function sendQuickReplyMessage(message) {
    console.log("Messages sended : ", JSON.stringify(message));
    if(message.senderID != undefined && message.text != undefined) {
        var messageData = {
            recipient: {
                id: message.senderID
            },
            message: {
                text: message.text,
                quick_replies: []
            }
        };
        for(var i=0;i<message.choices.length;i++) {
            var quickreply = {
                content_type: "text",
                title: message.choices[i],
                payload: message.choices[i]
            };
            messageData.message.quick_replies.push(quickreply);
        }
        callSendAPI(messageData);
    }
}

/*
* Fonction qui envoie un message audio/file/image/video
*/
function sendFileMessage(message) {
    console.log("Messages sended : ", JSON.stringify(message));
    if(message.senderID != undefined && message.text != undefined) {
        var messageData = {
            recipient: {
                id: message.senderID
            },
            message: {
                attachment:{
                    type: message.type,
                    payload: {
                        url: message.text
                    }
                }
            }
        };
        callSendAPI(messageData);
    }
}

/*
* Fonction qui appel l'API messages de Facebook
*/
function callSendAPI(messageData) {
    console.log("Messages sended via API : ", JSON.stringify(messageData));
    request({
        uri: 'https://graph.facebook.com/v2.6/me/messages',
        qs: { access_token: PAGE_ACCESS_TOKEN },
        method: 'POST',
        json: messageData
    }, function (error, response, body) {
        if (!error && response.statusCode == 200) {
            var recipientId = body.recipient_id;
            var messageId = body.message_id;

            console.log("Successfully sent generic message with id %s to recipient %s",
                messageId, recipientId);
        } else {
            console.error("Unable to send message.");
            console.error(response);
            console.error(error);
        }
    });
}

exports.webhook = webhook
exports.receivedMessage = receivedMessage
exports.sendMessage = sendMessage
exports.sendMessages = sendMessages<commit_msg>résolution bug<commit_after>'use strict';
const request = require('request');
const core = require('./../core/core.js');

/**
 * CREDENTIALS
 **/
const VALIDATION_TOKEN = process.env.FACEBOOK_VALIDATION_TOKEN;
const PAGE_ACCESS_TOKEN = process.env.FACEBOOK_PAGE_ACCESS_TOKEN;

/*
* Fonction appelé par Facbook pour checker le serveur
*/
function webhook(req, res) {
    return req.query['hub.mode'] === 'subscribe' && req.query['hub.verify_token'] === VALIDATION_TOKEN;
}

/*
* Fonction appelé par les routes lors de la reception d'un message
*/
function receivedMessage(req, res) {
    var data = req.body;
    if (data.object === 'page') {
        //Message reçu de Facebook
        data.entry.forEach(function(entry) {
            var pageID = entry.id;
            var timeOfEvent = entry.time;
            entry.messaging.forEach(function(event) {
                if (event.message) {
                    console.log("Event received : ", JSON.stringify(event));
                    extractMessage(event);
                }
            });
        });
    } else {
        //Pour tester via CURL
        extractMessage(req.body);
    }
}
/*
* Fonction qui permet de traiter un message reçu
*/
function extractMessage(event) {
    console.log(JSON.stringify(event));
    var senderID = event.sender.id;
    var recipientID = event.recipient.id;
    var timeOfMessage = event.timestamp;
    var message = event.message;
    request({
        uri: 'https://graph.facebook.com/' + senderID,
        qs: { access_token: PAGE_ACCESS_TOKEN },
        method: 'GET'
    }, function (error, response, body) {
        if (!error && response.statusCode == 200) {
            console.log("Received message from Facebook for user %d at %d with message:",
            senderID, timeOfMessage);
            console.log(JSON.stringify(message));

            var messageText = message.text;
            var messageAttachments = message.attachments;

            var message = {
                channel: "Facebook",
                senderID: senderID,
                timestamp: timeOfMessage,
                text: messageText,
                first_name: body.first_name,
                last_name: body.last_name
            };
            /*
            *   Coordonnées
            */
            if(messageAttachments != undefined && messageAttachments.payload != undefined && messageAttachments.payload.coordinates != undefined) {
                message["location"] = coordinates;
            }

            core.receivedMessage(message);
        } else {
            console.error("Unable to get name of user.");
            console.error(response);
            console.error(error);
        }
    });
}

/*
* Fonction appelé par le core pour envoyer un message sur la channel Facebook
*/
function sendMessage(message) {
    switch(message.type) {
        case "text":
            sendTextMessage(message);
        break;
        case "quickreply":
            sendQuickReplyMessage(message);
        break;
    }
}

/*
* Fonction appelé par le core pour envoyer des messages sur la channel Facebook
*/
function sendMessages(messages) {
    for(var i=0;i<messages.length;i++) {
        sendMessage(messages[i]);
    }
}

/*
* Fonction qui envoie un message de type text
*/
function sendTextMessage(message) {
    console.log("Messages sended : ", JSON.stringify(message));
    if(message.senderID != undefined && message.text != undefined) {
        var messageData = {
            recipient: {
                id: message.senderID
            },
            message: {
                text: message.text
            }
        };
        callSendAPI(messageData);
    }
}

/*
* Fonction qui envoie un message de type quickreply
*/
function sendQuickReplyMessage(message) {
    console.log("Messages sended : ", JSON.stringify(message));
    if(message.senderID != undefined && message.text != undefined) {
        var messageData = {
            recipient: {
                id: message.senderID
            },
            message: {
                text: message.text,
                quick_replies: []
            }
        };
        for(var i=0;i<message.choices.length;i++) {
            var quickreply = {
                content_type: "text",
                title: message.choices[i],
                payload: message.choices[i]
            };
            messageData.message.quick_replies.push(quickreply);
        }
        callSendAPI(messageData);
    }
}

/*
* Fonction qui envoie un message audio/file/image/video
*/
function sendFileMessage(message) {
    console.log("Messages sended : ", JSON.stringify(message));
    if(message.senderID != undefined && message.text != undefined) {
        var messageData = {
            recipient: {
                id: message.senderID
            },
            message: {
                attachment:{
                    type: message.type,
                    payload: {
                        url: message.text
                    }
                }
            }
        };
        callSendAPI(messageData);
    }
}

/*
* Fonction qui appel l'API messages de Facebook
*/
function callSendAPI(messageData) {
    console.log("Messages sended via API : ", JSON.stringify(messageData));
    request({
        uri: 'https://graph.facebook.com/v2.6/me/messages',
        qs: { access_token: PAGE_ACCESS_TOKEN },
        method: 'POST',
        json: messageData
    }, function (error, response, body) {
        if (!error && response.statusCode == 200) {
            var recipientId = body.recipient_id;
            var messageId = body.message_id;

            console.log("Successfully sent generic message with id %s to recipient %s",
                messageId, recipientId);
        } else {
            console.error("Unable to send message.");
            console.error(response);
            console.error(error);
        }
    });
}

exports.webhook = webhook
exports.receivedMessage = receivedMessage
exports.sendMessage = sendMessage
exports.sendMessages = sendMessages<|endoftext|>


<commit_before>/** Global variables for processing.js access **/
var waveSpeed = 3;
var timestep = 0.3
var w = 0.3;
var w2 = 0.45;
var playing = false;

/** Page setup **/
$(document).ready(function() {
    $("#speed-slider").slider({min: -5, max: 5, step: 0.1, slide: setAnimSpeed,
                           value: timestep});
    $("#wave1-w-slider").slider({min: 0, max: 0.6, step: 0.03, slide: setW1,
                           value: w});
    $("#wave2-w-slider").slider({min: 0, max: 0.6, step: 0.03, slide: setW2,
                           value: w2});
    $("#play").click(function() {
        var processing = Processing.getInstanceById("wave-sum-sim");
        if (playing) {
            processing.noLoop();
            $("#play").html("Play");
        } else {
            processing.loop();
            processing.draw();
            $("#play").html("Pause");
        }
        playing = !playing;
    });
});

function setAnimSpeed(event, ui) {
    timestep = ui.value;
}

function setW1(event, ui) {
    w = ui.value;
}

function setW2(event, ui) {
    w2 = ui.value;
}<commit_msg>Expand range of wave sum simulator.<commit_after>/** Global variables for processing.js access **/
var waveSpeed = 3;
var timestep = 0.3
var w = 0.3;
var w2 = 0.45;
var playing = false;

/** Page setup **/
$(document).ready(function() {
    $("#speed-slider").slider({min: -5, max: 5, step: 0.1, slide: setAnimSpeed,
                           value: timestep});
    $("#wave1-w-slider").slider({min: 0, max: 1, step: 0.03, slide: setW1,
                           value: w});
    $("#wave2-w-slider").slider({min: 0, max: 1, step: 0.03, slide: setW2,
                           value: w2});
    $("#play").click(function() {
        var processing = Processing.getInstanceById("wave-sum-sim");
        if (playing) {
            processing.noLoop();
            $("#play").html("Play");
        } else {
            processing.loop();
            processing.draw();
            $("#play").html("Pause");
        }
        playing = !playing;
    });
});

function setAnimSpeed(event, ui) {
    timestep = ui.value;
}

function setW1(event, ui) {
    w = ui.value;
}

function setW2(event, ui) {
    w2 = ui.value;
}<|endoftext|>


<commit_before>'use strict';

const head = document['head'] || document.getElementsByTagName("head")[0] || root;
const header = $('#header');
const initialHeadHeight = header.innerHeight();
const tocNav = $('#toc');
const headerFixPosition = $('.nav-hero-container').innerHeight();
const stickyElement = $('.sticky-element');
const stickyElementPosition = headerFixPosition; // Sticky element top-offset (154px)
const goTopBtn = $('#go-top-btn');
const copyrightEl = $('.copyright');
const isFaqPage = $('body').is('.faq');
const topOffset = 12; // Offset from the `header` navigation
const scrollToOffset = initialHeadHeight + topOffset;

/** Code color variables */
const $colorSelector = $('.color-selector a');
const $selectorDark = $('.color.dark');
const $selectorLight = $('.color.light');
const colorDark = 'dark';
const colorLight = 'light';
const baseStylesUrl = '/libs/prettify/skins/';
const darkStylesUrl = baseStylesUrl + 'dark-theme-prettify.css?refresh';
const lightStylesUrl = baseStylesUrl + 'light-theme-prettify.css?refresh';

$(function() {
    changeCodeColor();
    initPrettyprint();
    openHeaderMenuOnMobile();
    addExternalClass();
    initTocTocify();
    showScrollTopBtn();
    fixStickyElement();

    if (isFaqPage) {
        expandItemOnHashChange();
        preventDefaultScroll();
    }
});

jQuery(window).on('load', function() {
    ifCookiesExist();
    setStickyElMaxHeight();
    scrollToAnchor();
});

window.onhashchange = function() {
    if (isFaqPage) {
        expandItemOnHashChange();
        scrollToAnchor();
    }
};

window.onscroll = function() {
    fixStickyElement();
    fixHead();
    setStickyElMaxHeight();
    showScrollTopBtn();
};

$(window).resize(function() {
    resizeStickyElHeightWithWindow();
    ifCookiesExist();
    fixHead();
});

function changeCodeColor() {
    const cookieValue = Cookies.get('colorPref');

    if (cookieValue == null) {
        setDefaultCookieValue();
    } else {
        colorDark === cookieValue && setDarkTheme();
        colorLight === cookieValue && setLightTheme();
    }

    $selectorDark.click(function() {
        setDarkTheme();
    });

    $selectorLight.click(function() {
        setLightTheme();
    })
}

function setDefaultCookieValue() {
    Cookies.set('colorPref', colorDark);
    setDarkTheme();
}

function loadPrettifyStyles(stylesLink) {
    const $prettifyStyleSheets = $('#prettify-styles');

    if ($prettifyStyleSheets.length) {
        $prettifyStyleSheets.attr('href', stylesLink);
    } else {
        const link = document.createElement('link');
        link.rel = 'stylesheet';
        link.id = 'prettify-styles';
        link.type = 'text/css';
        link.href = stylesLink;
        head.appendChild(link);
    }
}

function makeSelectorActive(selector, color) {
    $colorSelector.removeClass('active');
    selector.addClass('active');
    Cookies.set('colorPref', color);
}

function setDarkTheme() {
    loadPrettifyStyles(darkStylesUrl);
    makeSelectorActive($selectorDark, colorDark);
}

function setLightTheme() {
    loadPrettifyStyles(lightStylesUrl);
    makeSelectorActive($selectorLight, colorLight);
}

/**
 * Inits pretty-print scripts.
 *
 * @see {@link https://github.com/google/code-prettify/blob/master/docs/getting_started.md code-prettify}
 */
function initPrettyprint() {
    $('pre').addClass('prettyprint');
    $.getScript("/libs/prettify/run_prettify.js", function(){});
    $.getScript("/libs/prettify/lang-css.js", function(){});
    $.getScript("/libs/prettify/lang-go.js", function(){});
    $.getScript("/libs/prettify/lang-proto.js", function(){});
    $.getScript("/libs/prettify/lang-swift.js", function(){});
    $.getScript("/libs/prettify/lang-yaml.js", function(){});
}

/**
 * Opens header menu on mobile device.
 */
function openHeaderMenuOnMobile() {
    $('#nav-icon-menu').click(function(){
        $(this).toggleClass('open');
        $('body').toggleClass('navigation-opened');
    });
}

/**
 * Adds the `external` class to every outbound link on the site.
 *
 *
The css will add a small right arrow after the link.
 */
function addExternalClass() {
    $('a').filter(function() {
        return this.hostname && this.hostname !== location.hostname;
    }).addClass('external');
}

/**
 * Inits `toc` navigation if a page has more than 2 headers.
 *
 * @see {@link http://gregfranko.com/jquery.tocify.js/ Toc Tocify}
 */
function initTocTocify() {
    const docsContainer = $('.docs-content-text');
    const headersQuantity = docsContainer.find('h2, h3, h4');

    if (headersQuantity.length >= 3) {
        tocNav.tocify({
            context: docsContainer,
            selectors: 'h2, h3, h4',
            showAndHide: false,
            scrollTo: scrollToOffset,
            extendPage: false,
            hashGenerator: 'pretty',
            smoothScroll: false
        });
    }
}

/**
 * Fix sticky element on page while scrolling.
 */
function fixStickyElement() {
    if (stickyElement.length) {
        if (window.pageYOffset > stickyElementPosition) {
            stickyElement.addClass('sticky');
        }
        else {
            stickyElement.removeClass('sticky');
        }
    }
}

/**
 * Makes header navigation sticky on scroll.
 *
 *
The header will not be sticky if the `header` has `hide-sticky-header` class. But it
 * still working on mobile devices. Used for all `docs` pages.
 */
function fixHead() {
    const stickyHeaderHidden = header.hasClass('hide-sticky-header');
    const mobileSize = 640;
    const mobileWindow = $(window).width() <= mobileSize;
    const desktopWindow = $(window).width() > mobileSize;
    const headerExistAndNotHidden = header.length && !stickyHeaderHidden;
    const headerOnMobile = header.length && mobileWindow;
    const headerHiddedAndNotMobile = header.length && stickyHeaderHidden && desktopWindow;

    if (headerExistAndNotHidden || headerOnMobile) {
        if (window.pageYOffset > headerFixPosition) {
            header.addClass('not-top'); // When the navigation below offset
            header.addClass('pinned'); // When the navigation below hero section
            header.removeClass('unpinned');
        } else {
            header.removeClass('pinned');
            header.addClass('unpinned');
        }
        /** Determines the header at the top of the page. */
        if (window.pageYOffset < initialHeadHeight) {
            returnToInitialState();
        }
    }

    if (headerHiddedAndNotMobile) {
        returnToInitialState();
    }
}

/**
 * Returns header classes to the initial state.
 */
function returnToInitialState() {
    header.removeClass('not-top');
    header.removeClass('unpinned');
}

/**
 * Sets max-height for the sticky element depends on the scroll position.
 */
function setStickyElMaxHeight() {
    if (stickyElement.length) {
        const elHeights = calcStickyElHeight();

        /**
         * Determines that the max-height value is less than browser window when the scroll
         * position at the top of the page.
         */
        if (elHeights.maxHeight < elHeights.initialHeight) {
            $(stickyElement).css('max-height', elHeights.maxHeight);
        } else {
            $(stickyElement).css('max-height', elHeights.initialHeight);
        }
    }
}

/**
 * Calculates a sticky element heights to make sure that it always fits on the page.
 *
 * @return {Object} an object with initial and calculated heights.
 * {number} initialHeight initial element max-height when the scroll at the top
 *          or at the middle of the page
 * {number} maxHeight max height that dynamically changes on scroll at the bottom of the page
 */
function calcStickyElHeight() {
    const windowHeight = $(window).height();
    const scrollPosition = $(window).scrollTop();
    const footerTopPoint = $('.footer').position().top;
    const cookieContainerHeight = $('#cookieChoiceInfo').innerHeight();
    /**
     * The distance from the element to the footer top point.
     * The value is the same as `docs-content-text` has.
     */
    const contentMarginBottom = 32;

    const initialHeight = windowHeight - stickyElementPosition + contentMarginBottom - cookieContainerHeight;
    const maxHeight = footerTopPoint - scrollPosition - stickyElementPosition + contentMarginBottom;

    return {initialHeight, maxHeight};
}

/**
 * Changes the height of the `.sticky-element` when changing the height of the window.
 */
function resizeStickyElHeightWithWindow() {
    if ($(window).height() > 600) {
        setStickyElMaxHeight();
    }
}

/**
 * Expands FAQ item on hash change.
 */
function expandItemOnHashChange() {
    if ('onhashchange' in window) {
        $(location.hash).collapse('show');
    }
}

/**
 * Prevents default scroll behavior and prevents double click on the same hash for the FAQ page.
 */
function preventDefaultScroll() {
    $('.anchor-link').click(function(event) {
        const anchor = $(this).attr('href');
        const x = window.pageXOffset;
        const y = window.pageYOffset;
        event.preventDefault();
        window.location.hash = anchor;
        window.scrollTo(x, y);
    });
}

/**
 * Scrolls to the anchor.
 */
function scrollToAnchor() {
    const anchor = location.hash;
    let offset = -scrollToOffset;

    if (isFaqPage) {
        offset = -150; // Top offset for the FAQ page target element
    }

    if ($(anchor).length) {
        $(window).scrollTo($(anchor), 500, {offset: offset});
    }
}

/**
 * Adds additional padding values if the `cookieChoiceInfo` exist on the page.
 */
function ifCookiesExist() {
    const cookieInfo = $('#cookieChoiceInfo');
    const cookieAgreeBtn = $('#cookieChoiceDismiss');
    const cookieContainerHeight = cookieInfo.innerHeight();
    const marginBottom = 10; // A bottom margin for the `Go to Top` button
    const copyrightPaddingBottom = 24; // A bottom padding for the `Copyright` div element

    if(cookieInfo.length){
        $(goTopBtn).css('bottom', cookieContainerHeight + marginBottom);
        $(copyrightEl).css('padding-bottom', cookieContainerHeight + copyrightPaddingBottom);

        /**
         * Removes additional padding values on the `Agree` button click.
         */
        $(cookieAgreeBtn).click(function(){
            $(goTopBtn).css('bottom', marginBottom);
            $(copyrightEl).css('padding-bottom', copyrightPaddingBottom);
        });
    } else {
        $(goTopBtn).css('bottom', marginBottom);
        $(copyrightEl).css('padding-bottom', copyrightPaddingBottom);
    }
}

/**
 * Shows `Go to Top` button when the scroll position is 1500px.
 */
function showScrollTopBtn() {
    if ($(this).scrollTop() > 1500 ) {
        $(goTopBtn).show();

    } else {
        $(goTopBtn).hide();
    }
}

/**
 * Scrolls to the top of the page.
 */
function topFunction() {
    $('html, body').stop().animate({scrollTop: 0}, 500, 'swing');
    return false;
}
<commit_msg>Create a constant for the cookie name<commit_after>'use strict';

const head = document['head'] || document.getElementsByTagName("head")[0] || root;
const header = $('#header');
const initialHeadHeight = header.innerHeight();
const tocNav = $('#toc');
const headerFixPosition = $('.nav-hero-container').innerHeight();
const stickyElement = $('.sticky-element');
const stickyElementPosition = headerFixPosition; // Sticky element top-offset (154px)
const goTopBtn = $('#go-top-btn');
const copyrightEl = $('.copyright');
const isFaqPage = $('body').is('.faq');
const topOffset = 12; // Offset from the `header` navigation
const scrollToOffset = initialHeadHeight + topOffset;

/** Code color variables */
const $colorSelector = $('.color-selector a');
const $selectorDark = $('.color.dark');
const $selectorLight = $('.color.light');
const colorDark = 'dark';
const colorLight = 'light';
const cookieColorName = 'themeColor';
const baseStylesUrl = '/libs/prettify/skins/';
const darkStylesUrl = baseStylesUrl + 'dark-theme-prettify.css?refresh';
const lightStylesUrl = baseStylesUrl + 'light-theme-prettify.css?refresh';

$(function() {
    changeCodeColor();
    initPrettyprint();
    openHeaderMenuOnMobile();
    addExternalClass();
    initTocTocify();
    showScrollTopBtn();
    fixStickyElement();

    if (isFaqPage) {
        expandItemOnHashChange();
        preventDefaultScroll();
    }
});

jQuery(window).on('load', function() {
    ifCookiesExist();
    setStickyElMaxHeight();
    scrollToAnchor();
});

window.onhashchange = function() {
    if (isFaqPage) {
        expandItemOnHashChange();
        scrollToAnchor();
    }
};

window.onscroll = function() {
    fixStickyElement();
    fixHead();
    setStickyElMaxHeight();
    showScrollTopBtn();
};

$(window).resize(function() {
    resizeStickyElHeightWithWindow();
    ifCookiesExist();
    fixHead();
});

function changeCodeColor() {
    const cookieValue = Cookies.get(cookieColorName);

    if (cookieValue == null) {
        setDefaultCookieValue();
    } else {
        colorDark === cookieValue && setDarkTheme();
        colorLight === cookieValue && setLightTheme();
    }

    $selectorDark.click(function() {
        setDarkTheme();
    });

    $selectorLight.click(function() {
        setLightTheme();
    })
}

function setDefaultCookieValue() {
    Cookies.set(cookieColorName, colorDark);
    setDarkTheme();
}

function loadPrettifyStyles(stylesLink) {
    const $prettifyStyleSheets = $('#prettify-styles');

    if ($prettifyStyleSheets.length) {
        $prettifyStyleSheets.attr('href', stylesLink);
    } else {
        const link = document.createElement('link');
        link.rel = 'stylesheet';
        link.id = 'prettify-styles';
        link.type = 'text/css';
        link.href = stylesLink;
        head.appendChild(link);
    }
}

function makeSelectorActive(selector, color) {
    $colorSelector.removeClass('active');
    selector.addClass('active');
    Cookies.set(cookieColorName, color);
}

function setDarkTheme() {
    loadPrettifyStyles(darkStylesUrl);
    makeSelectorActive($selectorDark, colorDark);
}

function setLightTheme() {
    loadPrettifyStyles(lightStylesUrl);
    makeSelectorActive($selectorLight, colorLight);
}

/**
 * Inits pretty-print scripts.
 *
 * @see {@link https://github.com/google/code-prettify/blob/master/docs/getting_started.md code-prettify}
 */
function initPrettyprint() {
    $('pre').addClass('prettyprint');
    $.getScript("/libs/prettify/run_prettify.js", function(){});
    $.getScript("/libs/prettify/lang-css.js", function(){});
    $.getScript("/libs/prettify/lang-go.js", function(){});
    $.getScript("/libs/prettify/lang-proto.js", function(){});
    $.getScript("/libs/prettify/lang-swift.js", function(){});
    $.getScript("/libs/prettify/lang-yaml.js", function(){});
}

/**
 * Opens header menu on mobile device.
 */
function openHeaderMenuOnMobile() {
    $('#nav-icon-menu').click(function(){
        $(this).toggleClass('open');
        $('body').toggleClass('navigation-opened');
    });
}

/**
 * Adds the `external` class to every outbound link on the site.
 *
 *
The css will add a small right arrow after the link.
 */
function addExternalClass() {
    $('a').filter(function() {
        return this.hostname && this.hostname !== location.hostname;
    }).addClass('external');
}

/**
 * Inits `toc` navigation if a page has more than 2 headers.
 *
 * @see {@link http://gregfranko.com/jquery.tocify.js/ Toc Tocify}
 */
function initTocTocify() {
    const docsContainer = $('.docs-content-text');
    const headersQuantity = docsContainer.find('h2, h3, h4');

    if (headersQuantity.length >= 3) {
        tocNav.tocify({
            context: docsContainer,
            selectors: 'h2, h3, h4',
            showAndHide: false,
            scrollTo: scrollToOffset,
            extendPage: false,
            hashGenerator: 'pretty',
            smoothScroll: false
        });
    }
}

/**
 * Fix sticky element on page while scrolling.
 */
function fixStickyElement() {
    if (stickyElement.length) {
        if (window.pageYOffset > stickyElementPosition) {
            stickyElement.addClass('sticky');
        }
        else {
            stickyElement.removeClass('sticky');
        }
    }
}

/**
 * Makes header navigation sticky on scroll.
 *
 *
The header will not be sticky if the `header` has `hide-sticky-header` class. But it
 * still working on mobile devices. Used for all `docs` pages.
 */
function fixHead() {
    const stickyHeaderHidden = header.hasClass('hide-sticky-header');
    const mobileSize = 640;
    const mobileWindow = $(window).width() <= mobileSize;
    const desktopWindow = $(window).width() > mobileSize;
    const headerExistAndNotHidden = header.length && !stickyHeaderHidden;
    const headerOnMobile = header.length && mobileWindow;
    const headerHiddedAndNotMobile = header.length && stickyHeaderHidden && desktopWindow;

    if (headerExistAndNotHidden || headerOnMobile) {
        if (window.pageYOffset > headerFixPosition) {
            header.addClass('not-top'); // When the navigation below offset
            header.addClass('pinned'); // When the navigation below hero section
            header.removeClass('unpinned');
        } else {
            header.removeClass('pinned');
            header.addClass('unpinned');
        }
        /** Determines the header at the top of the page. */
        if (window.pageYOffset < initialHeadHeight) {
            returnToInitialState();
        }
    }

    if (headerHiddedAndNotMobile) {
        returnToInitialState();
    }
}

/**
 * Returns header classes to the initial state.
 */
function returnToInitialState() {
    header.removeClass('not-top');
    header.removeClass('unpinned');
}

/**
 * Sets max-height for the sticky element depends on the scroll position.
 */
function setStickyElMaxHeight() {
    if (stickyElement.length) {
        const elHeights = calcStickyElHeight();

        /**
         * Determines that the max-height value is less than browser window when the scroll
         * position at the top of the page.
         */
        if (elHeights.maxHeight < elHeights.initialHeight) {
            $(stickyElement).css('max-height', elHeights.maxHeight);
        } else {
            $(stickyElement).css('max-height', elHeights.initialHeight);
        }
    }
}

/**
 * Calculates a sticky element heights to make sure that it always fits on the page.
 *
 * @return {Object} an object with initial and calculated heights.
 * {number} initialHeight initial element max-height when the scroll at the top
 *          or at the middle of the page
 * {number} maxHeight max height that dynamically changes on scroll at the bottom of the page
 */
function calcStickyElHeight() {
    const windowHeight = $(window).height();
    const scrollPosition = $(window).scrollTop();
    const footerTopPoint = $('.footer').position().top;
    const cookieContainerHeight = $('#cookieChoiceInfo').innerHeight();
    /**
     * The distance from the element to the footer top point.
     * The value is the same as `docs-content-text` has.
     */
    const contentMarginBottom = 32;

    const initialHeight = windowHeight - stickyElementPosition + contentMarginBottom - cookieContainerHeight;
    const maxHeight = footerTopPoint - scrollPosition - stickyElementPosition + contentMarginBottom;

    return {initialHeight, maxHeight};
}

/**
 * Changes the height of the `.sticky-element` when changing the height of the window.
 */
function resizeStickyElHeightWithWindow() {
    if ($(window).height() > 600) {
        setStickyElMaxHeight();
    }
}

/**
 * Expands FAQ item on hash change.
 */
function expandItemOnHashChange() {
    if ('onhashchange' in window) {
        $(location.hash).collapse('show');
    }
}

/**
 * Prevents default scroll behavior and prevents double click on the same hash for the FAQ page.
 */
function preventDefaultScroll() {
    $('.anchor-link').click(function(event) {
        const anchor = $(this).attr('href');
        const x = window.pageXOffset;
        const y = window.pageYOffset;
        event.preventDefault();
        window.location.hash = anchor;
        window.scrollTo(x, y);
    });
}

/**
 * Scrolls to the anchor.
 */
function scrollToAnchor() {
    const anchor = location.hash;
    let offset = -scrollToOffset;

    if (isFaqPage) {
        offset = -150; // Top offset for the FAQ page target element
    }

    if ($(anchor).length) {
        $(window).scrollTo($(anchor), 500, {offset: offset});
    }
}

/**
 * Adds additional padding values if the `cookieChoiceInfo` exist on the page.
 */
function ifCookiesExist() {
    const cookieInfo = $('#cookieChoiceInfo');
    const cookieAgreeBtn = $('#cookieChoiceDismiss');
    const cookieContainerHeight = cookieInfo.innerHeight();
    const marginBottom = 10; // A bottom margin for the `Go to Top` button
    const copyrightPaddingBottom = 24; // A bottom padding for the `Copyright` div element

    if(cookieInfo.length){
        $(goTopBtn).css('bottom', cookieContainerHeight + marginBottom);
        $(copyrightEl).css('padding-bottom', cookieContainerHeight + copyrightPaddingBottom);

        /**
         * Removes additional padding values on the `Agree` button click.
         */
        $(cookieAgreeBtn).click(function(){
            $(goTopBtn).css('bottom', marginBottom);
            $(copyrightEl).css('padding-bottom', copyrightPaddingBottom);
        });
    } else {
        $(goTopBtn).css('bottom', marginBottom);
        $(copyrightEl).css('padding-bottom', copyrightPaddingBottom);
    }
}

/**
 * Shows `Go to Top` button when the scroll position is 1500px.
 */
function showScrollTopBtn() {
    if ($(this).scrollTop() > 1500 ) {
        $(goTopBtn).show();

    } else {
        $(goTopBtn).hide();
    }
}

/**
 * Scrolls to the top of the page.
 */
function topFunction() {
    $('html, body').stop().animate({scrollTop: 0}, 500, 'swing');
    return false;
}
<|endoftext|>