<commit_before>(function(){

    xtag.register('x-ribbon', {
        extends: 'div',
        lifecycle: {
            created: function() {
                this.startRibbon = document.createElement('div')
                this.endRibbon = document.createElement('div')
                this.nCards = 0;
                this.uniqueIndex = 0;
                this.wrapperForm = document.createElement('form')

                this.wrapperForm.setAttribute('id', this.id+'Wrapper');
                this.wrapperForm.setAttribute('class', 'ribbonWrapper');
                this.appendChild(this.wrapperForm);

                this.startRibbon.setAttribute('id', this.id+'StartRibbon');
                this.startRibbon.setAttribute('class', 'ribbon');
                this.startRibbon.setAttribute('style', 'border-radius: 1em 0em 0em 1em')
                this.wrapperForm.appendChild(this.startRibbon);

                this.endRibbon.setAttribute('id', this.id+'EndRibbon');
                this.endRibbon.setAttribute('class', 'ribbon');
                this.endRibbon.setAttribute('style', 'border-radius: 0em 1em 1em 0em')
                this.wrapperForm.appendChild(this.endRibbon);

                this.startRibbon.onclick = function(){
                    if(this.nCards == 0)
                        this.spawnCard(this.endRibbon)
                    else{
                        this.newNode(this.startRibbon.nextSibling);
                        this.spawnCard(this.startRibbon.nextSibling);
                    }
                }.bind(this);

                this.endRibbon.onclick = function(){
                    if(this.nCards == 0)
                        this.spawnCard(this.endRibbon)
                    else{
                        this.spawnCard(this.endRibbon);
                        this.newNode(this.endRibbon.previousSibling);
                    }
                }.bind(this);
            },

            inserted: function() {},
            removed: function() {},
            attributeChanged: function() {}
        },
        events: {

        },
        accessors: {

        },
        methods: {
            'spawnCard' : function(nextNode){
                var card = document.createElement('div');

                card.setAttribute('class', 'ribbonCard');
                this.cardConfig(card);
                this.wrapperForm.insertBefore(card, nextNode)

                this.nCards++;
                this.uniqueIndex++;
                this.wrapperForm.onchange();

            },

            'newNode' : function(nextNode){
                var ribbon = document.createElement('div');

                ribbon.setAttribute('class', 'ribbon');
                this.wrapperForm.insertBefore(ribbon, nextNode);
                ribbon.onclick = function(xRibbon){
                    xRibbon.newNode(this);
                    xRibbon.spawnCard(this);
                }.bind(ribbon, this);

            },

            'cardConfig' : function(targetElement){
                var remove = document.createElement('input'),
                    moveLater = document.createElement('input'),
                    moveEarlier = document.createElement('input'),
                    timingWrap = document.createElement('div'),
                    sortWrap = document.createElement('div'),
                    timeLabel = document.createElement('label'),
                    duration = document.createElement('input'),
                    durationUnits = document.createElement('select'),
                    unitOption, units = ['ms', 's', 'min'], unitScale = [1, 1000, 60000],
                    durationSummary = document.createElement('span'),
                    list = document.createElement('ul'),
                    detail = document.createElement('input'),
                    listItem, ppgOption, ppgLabel,
                    ppgName = ['Beam On', 'Wildcard 1', 'Wildcard 2', 'Wildcard 3', 'Sync Clocks', 'Clear Scalars', 'Move Tape', 'HPGe Trigger', 'SCEPTAR Trigger', 'Si(Li) Trigger', 'LaBr3 Trigger', 'DESCANT Trigger', 'ZDS Trigger', 'Wildcard 4', 'Wildcard 5', 'Wildcard 6'],
                    ppgCode = [0x1, 0x2, 0x4, 0x8, 0x10, 0x20, 0x40, 0x80, 0x100, 0x200, 0x400, 0x800, 0x1000, 0x2000, 0x4000, 0x8000],
                    i;

                timingWrap.setAttribute('class', 'summary');
                timingWrap.setAttribute('id', 'timingWrap');
                targetElement.appendChild(timingWrap);

                sortWrap.setAttribute('class', 'PPGcardSorting');
                timingWrap.appendChild(sortWrap);

                moveEarlier.value = 'Earlier';
                moveEarlier.setAttribute('class', 'stdin');
                moveEarlier.setAttribute('type', 'button');
                moveEarlier.onclick = this.shuffleCardEarlier.bind(this, targetElement);
                sortWrap.appendChild(moveEarlier);

                remove.value = 'Remove';
                remove.setAttribute('class', 'stdin');
                remove.setAttribute('type', 'button');
                remove.onclick = this.deleteCard.bind(this, targetElement);
                sortWrap.appendChild(remove);

                moveLater.value = 'Later';
                moveLater.setAttribute('class', 'stdin');
                moveLater.setAttribute('type', 'button');
                moveLater.onclick = this.shuffleCardLater.bind(this, targetElement);
                sortWrap.appendChild(moveLater);

                timeLabel.innerHTML = 'Duration:';
                timingWrap.appendChild(timeLabel);
                duration.setAttribute('class', 'stdin');
                duration.setAttribute('type', 'number');
                duration.setAttribute('value', 0);
                duration.setAttribute('step', 'any');
                timingWrap.appendChild(duration);
                durationUnits.setAttribute('class', 'stdin');
                durationUnits.setAttribute('id', 'units' + this.uniqueIndex)
                timingWrap.appendChild(durationUnits);
                for(i=0; i<units.length; i++){
                    unitOption = document.createElement('option');
                    unitOption.innerHTML = units[i];
                    unitOption.value = unitScale[i];
                    durationUnits.appendChild(unitOption);
                }

                durationSummary.setAttribute('id', 'durationSummary');
                durationSummary.setAttribute('class', 'summary');
                targetElement.appendChild(durationSummary);

                targetElement.appendChild(list);

                for(i=0; i<ppgName.length; i++){
                    listItem = document.createElement('li');
                    list.appendChild(listItem);

                    ppgOption = document.createElement('input');
                    ppgOption.setAttribute('type', 'checkbox');
                    ppgOption.setAttribute('class', 'summary');
                    ppgOption.setAttribute('id', 'uID' + this.uniqueIndex + 'ppg' + ppgCode[i].toString(16));
                    ppgOption.value = ppgCode[i];
                    listItem.appendChild(ppgOption);

                    ppgLabel = document.createElement('label');
                    ppgLabel.innerHTML = ppgName[i];
                    ppgLabel.setAttribute('for', 'uID' + this.uniqueIndex + 'ppg' + ppgCode[i].toString(16));
                    listItem.appendChild(ppgLabel);
                }

                detail.value = 'Edit';
                detail.setAttribute('class', 'stdin');
                detail.setAttribute('type', 'button');
                detail.onclick = function(target, self){
                    var checkboxes = target.querySelectorAll('input[type="checkbox"]'),
                        timingUI = target.querySelectorAll('div#timingWrap'),
                        durationSummary = target.querySelectorAll('span#durationSummary'),
                        duration = parseFloat(target.querySelectorAll('input[type="number"]')[0].value),
                        durationScale = parseFloat(selected(target.querySelectorAll('input[type="select"]')[0].id)),
                        i;

                    if(self.value == 'Edit'){
                        for(i=0; i<checkboxes.length; i++){
                            checkboxes[i].setAttribute('class', 'edit');
                        }
                        timingUI[0].setAttribute('class', 'edit');
                        durationSummary[0].setAttribute('class', 'edit');
                        self.value = 'Summary';
                    } else {
                        for(i=0; i<checkboxes.length; i++){
                            checkboxes[i].setAttribute('class', 'summary');
                        }
                        timingUI[0].setAttribute('class', 'summary');
                        durationSummary[0].setAttribute('class', 'summary');

                        if(duration%60000 == 0){
                            durationSummary[0].innerHTML = 'Duration: ' + duration / 60000 + ' min';
                        }
                        else if(duration%1000 == 0){
                            durationSummary[0].innerHTML = 'Duration: ' + duration / 1000 + ' s';
                        } else{
                            durationSummary[0].innerHTML = 'Duration: ' + duration + ' ms';
                        }

                        self.value = 'Edit';
                    }
                }.bind(null, targetElement, detail);
                targetElement.appendChild(detail);

            },

            'deleteCard' : function(target){
                if(target.nextSibling.id !== this.id + 'EndRibbon')
                    target.nextSibling.remove();
                else
                    target.previousSibling.remove();
                target.remove();
                this.nCards--;
                this.wrapperForm.onchange();
            },

            'shuffleCardLater' : function(target){
                if(target.nextSibling.id == this.id+'EndRibbon')
                    return //can't go any later

                this.wrapperForm.insertBefore(target.nextSibling, target.nextSibling.nextSibling.nextSibling);
                this.wrapperForm.insertBefore(target, target.nextSibling.nextSibling.nextSibling);
                this.wrapperForm.onchange();
            },

            'shuffleCardEarlier' : function(target){
                if(target.previousSibling.id == this.id+'StartRibbon')
                    return //can't go any later

                this.wrapperForm.insertBefore(target.previousSibling, target.previousSibling.previousSibling);
                this.wrapperForm.insertBefore(target, target.previousSibling.previousSibling);
                this.wrapperForm.onchange();
            }
        },

    });

})();

<commit_msg>cycle detail toggle<commit_after>(function(){

    xtag.register('x-ribbon', {
        extends: 'div',
        lifecycle: {
            created: function() {
                this.startRibbon = document.createElement('div')
                this.endRibbon = document.createElement('div')
                this.nCards = 0;
                this.uniqueIndex = 0;
                this.wrapperForm = document.createElement('form')

                this.wrapperForm.setAttribute('id', this.id+'Wrapper');
                this.wrapperForm.setAttribute('class', 'ribbonWrapper');
                this.appendChild(this.wrapperForm);

                this.startRibbon.setAttribute('id', this.id+'StartRibbon');
                this.startRibbon.setAttribute('class', 'ribbon');
                this.startRibbon.setAttribute('style', 'border-radius: 1em 0em 0em 1em')
                this.wrapperForm.appendChild(this.startRibbon);

                this.endRibbon.setAttribute('id', this.id+'EndRibbon');
                this.endRibbon.setAttribute('class', 'ribbon');
                this.endRibbon.setAttribute('style', 'border-radius: 0em 1em 1em 0em')
                this.wrapperForm.appendChild(this.endRibbon);

                this.startRibbon.onclick = function(){
                    if(this.nCards == 0)
                        this.spawnCard(this.endRibbon)
                    else{
                        this.newNode(this.startRibbon.nextSibling);
                        this.spawnCard(this.startRibbon.nextSibling);
                    }
                }.bind(this);

                this.endRibbon.onclick = function(){
                    if(this.nCards == 0)
                        this.spawnCard(this.endRibbon)
                    else{
                        this.spawnCard(this.endRibbon);
                        this.newNode(this.endRibbon.previousSibling);
                    }
                }.bind(this);
            },

            inserted: function() {},
            removed: function() {},
            attributeChanged: function() {}
        },
        events: {

        },
        accessors: {

        },
        methods: {
            'spawnCard' : function(nextNode){
                var card = document.createElement('div');

                card.setAttribute('class', 'ribbonCard');
                this.cardConfig(card);
                this.wrapperForm.insertBefore(card, nextNode)

                this.nCards++;
                this.uniqueIndex++;
                this.wrapperForm.onchange();

            },

            'newNode' : function(nextNode){
                var ribbon = document.createElement('div');

                ribbon.setAttribute('class', 'ribbon');
                this.wrapperForm.insertBefore(ribbon, nextNode);
                ribbon.onclick = function(xRibbon){
                    xRibbon.newNode(this);
                    xRibbon.spawnCard(this);
                }.bind(ribbon, this);

            },

            'cardConfig' : function(targetElement){
                var remove = document.createElement('input'),
                    moveLater = document.createElement('input'),
                    moveEarlier = document.createElement('input'),
                    timingWrap = document.createElement('div'),
                    sortWrap = document.createElement('div'),
                    timeLabel = document.createElement('label'),
                    duration = document.createElement('input'),
                    durationUnits = document.createElement('select'),
                    unitOption, units = ['ms', 's', 'min'], unitScale = [1, 1000, 60000],
                    durationSummary = document.createElement('span'),
                    list = document.createElement('ul'),
                    detail = document.createElement('input'),
                    listItem, ppgOption, ppgLabel,
                    ppgName = ['Beam On', 'Wildcard 1', 'Wildcard 2', 'Wildcard 3', 'Sync Clocks', 'Clear Scalars', 'Move Tape', 'HPGe Trigger', 'SCEPTAR Trigger', 'Si(Li) Trigger', 'LaBr3 Trigger', 'DESCANT Trigger', 'ZDS Trigger', 'Wildcard 4', 'Wildcard 5', 'Wildcard 6'],
                    ppgCode = [0x1, 0x2, 0x4, 0x8, 0x10, 0x20, 0x40, 0x80, 0x100, 0x200, 0x400, 0x800, 0x1000, 0x2000, 0x4000, 0x8000],
                    i;

                timingWrap.setAttribute('class', 'summary');
                timingWrap.setAttribute('id', 'timingWrap');
                targetElement.appendChild(timingWrap);

                sortWrap.setAttribute('class', 'PPGcardSorting');
                timingWrap.appendChild(sortWrap);

                moveEarlier.value = 'Earlier';
                moveEarlier.setAttribute('class', 'stdin');
                moveEarlier.setAttribute('type', 'button');
                moveEarlier.onclick = this.shuffleCardEarlier.bind(this, targetElement);
                sortWrap.appendChild(moveEarlier);

                remove.value = 'Remove';
                remove.setAttribute('class', 'stdin');
                remove.setAttribute('type', 'button');
                remove.onclick = this.deleteCard.bind(this, targetElement);
                sortWrap.appendChild(remove);

                moveLater.value = 'Later';
                moveLater.setAttribute('class', 'stdin');
                moveLater.setAttribute('type', 'button');
                moveLater.onclick = this.shuffleCardLater.bind(this, targetElement);
                sortWrap.appendChild(moveLater);

                timeLabel.innerHTML = 'Duration:';
                timingWrap.appendChild(timeLabel);
                duration.setAttribute('class', 'stdin');
                duration.setAttribute('type', 'number');
                duration.setAttribute('value', 0);
                duration.setAttribute('step', 'any');
                timingWrap.appendChild(duration);
                durationUnits.setAttribute('class', 'stdin');
                durationUnits.setAttribute('id', 'units' + this.uniqueIndex)
                timingWrap.appendChild(durationUnits);
                for(i=0; i<units.length; i++){
                    unitOption = document.createElement('option');
                    unitOption.innerHTML = units[i];
                    unitOption.value = unitScale[i];
                    durationUnits.appendChild(unitOption);
                }

                durationSummary.setAttribute('id', 'durationSummary');
                durationSummary.setAttribute('class', 'summary');
                targetElement.appendChild(durationSummary);

                targetElement.appendChild(list);

                for(i=0; i<ppgName.length; i++){
                    listItem = document.createElement('li');
                    list.appendChild(listItem);

                    ppgOption = document.createElement('input');
                    ppgOption.setAttribute('type', 'checkbox');
                    ppgOption.setAttribute('class', 'summary');
                    ppgOption.setAttribute('id', 'uID' + this.uniqueIndex + 'ppg' + ppgCode[i].toString(16));
                    ppgOption.value = ppgCode[i];
                    listItem.appendChild(ppgOption);

                    ppgLabel = document.createElement('label');
                    ppgLabel.innerHTML = ppgName[i];
                    ppgLabel.setAttribute('for', 'uID' + this.uniqueIndex + 'ppg' + ppgCode[i].toString(16));
                    listItem.appendChild(ppgLabel);
                }

                detail.value = 'Edit';
                detail.setAttribute('class', 'stdin');
                detail.setAttribute('type', 'button');
                detail.onclick = function(target, self){
                    var checkboxes = target.querySelectorAll('input[type="checkbox"]'),
                        timingUI = target.querySelectorAll('div#timingWrap'),
                        durationSummary = target.querySelectorAll('span#durationSummary'),
                        duration = parseFloat(target.querySelectorAll('input[type="number"]')[0].value),
                        durationScale = parseFloat(selected(target.querySelectorAll('select')[0].id)),
                        i;

                    if(self.value == 'Edit'){
                        for(i=0; i<checkboxes.length; i++){
                            checkboxes[i].setAttribute('class', 'edit');
                        }
                        timingUI[0].setAttribute('class', 'edit');
                        durationSummary[0].setAttribute('class', 'edit');
                        self.value = 'Summary';
                    } else {
                        for(i=0; i<checkboxes.length; i++){
                            checkboxes[i].setAttribute('class', 'summary');
                        }
                        timingUI[0].setAttribute('class', 'summary');
                        durationSummary[0].setAttribute('class', 'summary');

                        if(duration%60000 == 0){
                            durationSummary[0].innerHTML = 'Duration: ' + duration / 60000 + ' min';
                        }
                        else if(duration%1000 == 0){
                            durationSummary[0].innerHTML = 'Duration: ' + duration / 1000 + ' s';
                        } else{
                            durationSummary[0].innerHTML = 'Duration: ' + duration + ' ms';
                        }

                        self.value = 'Edit';
                    }
                }.bind(null, targetElement, detail);
                targetElement.appendChild(detail);

            },

            'deleteCard' : function(target){
                if(target.nextSibling.id !== this.id + 'EndRibbon')
                    target.nextSibling.remove();
                else
                    target.previousSibling.remove();
                target.remove();
                this.nCards--;
                this.wrapperForm.onchange();
            },

            'shuffleCardLater' : function(target){
                if(target.nextSibling.id == this.id+'EndRibbon')
                    return //can't go any later

                this.wrapperForm.insertBefore(target.nextSibling, target.nextSibling.nextSibling.nextSibling);
                this.wrapperForm.insertBefore(target, target.nextSibling.nextSibling.nextSibling);
                this.wrapperForm.onchange();
            },

            'shuffleCardEarlier' : function(target){
                if(target.previousSibling.id == this.id+'StartRibbon')
                    return //can't go any later

                this.wrapperForm.insertBefore(target.previousSibling, target.previousSibling.previousSibling);
                this.wrapperForm.insertBefore(target, target.previousSibling.previousSibling);
                this.wrapperForm.onchange();
            }
        },

    });

})();

<|endoftext|>


<commit_before>"use strict";

(function () {
    if (typeof Breinify !== 'object') {
        return;
    }

    var $ = Breinify.UTL._jquery();
    var overload = Breinify.plugins._overload();

    var prefixValidation = Breinify.UTL.constants.errors.prefix.validation;
    var prefixApi = Breinify.UTL.constants.errors.prefix.api;

    var popupPrefix = "breinify-popup";
    var alertMePrefix = 'breinify-alert-me';

    var minHtml = "

×

";
    var minCss = "";

    var defaultPages = {
        'loading': '',
        'success': '',
        'error': '',
        'setAlert': '' +
        '
' +
        '
You are about to set an alert to be informed via text message when  will be available at  within the next  days. Setting an alert does not reserve the product, it notifies you when it is available.
' +
        '
Please provide the following information:
' +
        '
' +
        '
Mobile Number:
  ' +
        '
<input style="font-size:inherit;font-family:inherit;color:#000;box-sizing:border-box;max-width:450px;width:100%;height:40px;padding: 0 8px;background-color:#fff;border-radius:5px;border:1px solid #999999" id=\"' + alertMePrefix + '-mobile-number\" type=\"text\" placeholder=\"(xxx) xxx-xxxx\" autocomplete=\"off\" maxlength=\"14\" data-alert-me-visualize-error=\"false\">
' +
        '
' +
        '
' +
        '
Alert-Time (when available):
  ' +
        '
<select style="-moz-appearance:none;-webkit-appearance:none;font-size:inherit;font-family:inherit;color:#000;box-sizing:border-box;max-width:450px;width:100%;height:40px;padding: 0 8px;background:#fff no-repeat 98% 50%;border-radius:5px;border:1px solid #999999" id=\"' + alertMePrefix + '-alert-time\">' +
        '           <option value=\"0|24|-1\">anytime, as soon as available</option>' +
        '           <option value=\"9|18|-1\">between 9:00am - 6:00pm</option>' +
        '           <option value=\"9|12|-1\">between 9:00am - noon</option>' +
        '           <option value=\"12|18|-1\">between noon - 6:00pm</option>' +
        '           <option value=\"9|18|0\">between 9:00am - 6:00pm (weekdays only)</option>' +
        '           <option value=\"9|18|1\">between 9:00am - 6:00pm (weekends only)</option>' +
        '           <option value=\"9|12|0\">between 9:00am - noon (weekdays only)</option>' +
        '           <option value=\"9|12|1\">between 9:00am - noon (weekends only)</option>' +
        '           <option value=\"12|18|0\">between noon - 6:00pm (weekdays only)</option>' +
        '           <option value=\"12|18|1\">between noon - 6:00pm (weekends only)</option>' +
        '       </select>
' +
        '
' +
        '
By setting this alert, you confirm that the entered mobile number is yours and that you consent to receive text messages to inform you about the alert. By providing your mobile number and signing up for alerts you agree to receive text messages that may be deemed marketing under applicable law, and that these messages may be sent using an autodialer. Your consent is not a condition of any purchase. Setting an alert is not a reservation of a product.
' +
        '
' +
        '       <button id=\"' + alertMePrefix + '-set-alert\" style=\"min-width:150px;width:50%;white-space:nowrap;cursor:pointer;line-height:25px;font-size:14px;border-radius:4px;border-color:#de0000;background:#de0000;color:#fff;\" type=\"submit\" title=\"Set Alert\" disabled=\"\">Set Alert</button>' +
        '
' +
        '
'
    };

    var UiPopup = function UiPopup() {
    };

    UiPopup.prototype.init = function (id, options) {
        var _self = this;
        var $body = $('body');

        // general settings to keep
        this.currentPageNr = 0;
        this.$pages = [];
        this.id = id;
        this.options = $.extend(true, {
            showClose: true,
            showFooter: true,
            header: null,
            maxWidth: null,
            bindings: null
        }, options);

        // make sure we have the minimal CSS needed
        if ($('#' + popupPrefix + '-style').length === 0) {
            $body.append(minCss);
        }

        // check if the element with this id exists
        var $el = $('#' + id);
        if ($el.length === 0) {
            var $minHtml = $(minHtml);
            $minHtml.attr('id', id);
            $body.append($minHtml);
            this.$popup = $minHtml;
        } else {
            this.$popup = $el;
        }

        // check if we show close
        var $close = this.$popup.find('.' + popupPrefix + '-close');
        if (this.getOption('showClose', true) === true) {
            $close.show();
            $close.click(function () {
                _self.hide();
            });
        } else {
            $close.hide()
        }

        // check if we show the footer
        var $footer = this.$popup.find('.' + popupPrefix + '-footer');
        if (this.getOption('showFooter', true) === true) {
            $footer.show();
        } else {
            $footer.hide()
        }

        // check the maxWidth
        var maxWidth = this.getOption('maxWidth', null);
        if (typeof maxWidth === 'number') {
            maxWidth = maxWidth + 'px';
        }
        if (typeof maxWidth === 'string') {
            var $content = this.$popup.find('.' + popupPrefix + '-content');
            $content.css('maxWidth', maxWidth);
        }

        // use some setters
        this.setBindings(null);
        this.setHeader(null);

        this.id = id;
    };

    UiPopup.prototype.css = function (selector, css) {
        var $el = this.$popup.find(selector);
        $el.css($.isPlainObject(css) ? css : {});

        return css;
    };

    UiPopup.prototype.find = function (selector) {
        return this.$popup.find(selector);
    };

    UiPopup.prototype.setBindings = function (bindings) {
        this.bindings = $.isPlainObject(bindings) ? bindings : this.getOption('bindings', {});
    };

    UiPopup.prototype.setBindings = function (bindings) {
        this.bindings = $.isPlainObject(bindings) ? bindings : this.getOption('bindings', {});
    };

    UiPopup.prototype.show = function (pageNr) {
        pageNr = this.validatePage(typeof pageNr === 'number' ? pageNr : 1);
        this.showPage(pageNr);
    };

    UiPopup.prototype.hide = function (id) {
        $('html')
            .css('marginRight', '')
            .css('overflow', '');

        this.$popup.hide();
    };

    UiPopup.prototype.addPage = function (page) {
        var $pagesContainer = this.$popup.find('.' + popupPrefix + '-pages');
        var $page = $('
' + page + '
');

        var pageNr = this.$pages.push($page);
        $page.attr('data-pageNr', pageNr);
        $page.hide();

        $pagesContainer.append($page);

        return $page;
    };

    UiPopup.prototype.showNextPage = function () {
        this.showPage(this.currentPageNr + 1);
    };

    UiPopup.prototype.showPrevPage = function () {
        if (this.currentPageNr <= 1) {
            return;
        } else {
            this.showPage(this.currentPageNr - 1);
        }
    };

    UiPopup.prototype.showPage = function (pageNr) {
        pageNr = this.validatePage(pageNr);

        if (this.currentPageNr !== 0) {
            var $currentPage = this.$pages[this.currentPageNr - 1];
            this._resetBindings($currentPage);
            $currentPage.hide();
        }

        // set the current-page it will become affective now
        this.currentPageNr = pageNr;
        if (pageNr > 0) {
            var $page = this.$pages[pageNr - 1];
            this._applyBindings($page);
            $page.show();
        }

        $('html')
            .css('marginRight', '15px')
            .css('overflow', 'hidden');

        this.$popup.show();
    };

    UiPopup.prototype._applyBindings = function ($el) {
        var _self = this;

        var $placeholders = $el.find('[data-breinify-placeholder]');
        var popupPlaceholders = {
            popup: {
                currentPageNr: this.currentPageNr,
                totalPageNr: this.$pages.length
            }
        };
        $placeholders.each(function () {
            var $placeholderEl = $(this);
            var placeholder = $placeholderEl.attr('data-breinify-placeholder');

            var value;
            if (placeholder.indexOf('popup.') === 0) {
                value = Breinify.UTL.getNestedByPath(popupPlaceholders, placeholder);
            } else {
                value = Breinify.UTL.getNestedByPath(_self.bindings, placeholder);
            }

            $placeholderEl.text(value);
        });
    };

    UiPopup.prototype._resetBindings = function ($el) {
        var $placeholder = $el.find('[data-breinify-placeholder!=""]');
    };

    UiPopup.prototype.validatePage = function (pageNr) {
        if (typeof pageNr === 'number') {
            return Math.max(0, Math.min(this.$pages.length, pageNr));
        } else {
            return this.currentPageNr;
        }
    };

    UiPopup.prototype.setHeader = function (header) {
        if (typeof header !== 'string') {
            header = this.getOption('header', '');
        }

        var $header = this.$popup.find('.' + popupPrefix + '-header>div:first');
        $header.html(header);
    };

    UiPopup.prototype.getOption = function (option, def) {
        var val = this.options[option];
        if (typeof val === 'undefined' || val === null) {
            return def;
        } else {
            return val;
        }
    };

    // bind the module
    Breinify.plugins._add('uiPopup', {

        addDefaultPage: function (id) {
            var page = defaultPages[id];
            if (typeof page !== 'string') {
                return null;
            } else {
                return '' + page;
            }
        },

        create: function (id, options) {
            var popup = new UiPopup();
            popup.init(id, options);

            return popup;
        }
    });
})();<commit_msg>added addDefaultPage<commit_after>"use strict";

(function () {
    if (typeof Breinify !== 'object') {
        return;
    }

    var $ = Breinify.UTL._jquery();
    var overload = Breinify.plugins._overload();

    var prefixValidation = Breinify.UTL.constants.errors.prefix.validation;
    var prefixApi = Breinify.UTL.constants.errors.prefix.api;

    var popupPrefix = "breinify-popup";
    var alertMePrefix = 'breinify-alert-me';

    var minHtml = "

×

";
    var minCss = "";

    var defaultPages = {
        'loading': '',
        'success': '',
        'error': '',
        'setAlert': '' +
        '
' +
        '
You are about to set an alert to be informed via text message when  will be available at  within the next  days. Setting an alert does not reserve the product, it notifies you when it is available.
' +
        '
Please provide the following information:
' +
        '
' +
        '
Mobile Number:
  ' +
        '
<input style="font-size:inherit;font-family:inherit;color:#000;box-sizing:border-box;max-width:450px;width:100%;height:40px;padding: 0 8px;background-color:#fff;border-radius:5px;border:1px solid #999999" id=\"' + alertMePrefix + '-mobile-number\" type=\"text\" placeholder=\"(xxx) xxx-xxxx\" autocomplete=\"off\" maxlength=\"14\" data-alert-me-visualize-error=\"false\">
' +
        '
' +
        '
' +
        '
Alert-Time (when available):
  ' +
        '
<select style="-moz-appearance:none;-webkit-appearance:none;font-size:inherit;font-family:inherit;color:#000;box-sizing:border-box;max-width:450px;width:100%;height:40px;padding: 0 8px;background:#fff no-repeat 98% 50%;border-radius:5px;border:1px solid #999999" id=\"' + alertMePrefix + '-alert-time\">' +
        '           <option value=\"0|24|-1\">anytime, as soon as available</option>' +
        '           <option value=\"9|18|-1\">between 9:00am - 6:00pm</option>' +
        '           <option value=\"9|12|-1\">between 9:00am - noon</option>' +
        '           <option value=\"12|18|-1\">between noon - 6:00pm</option>' +
        '           <option value=\"9|18|0\">between 9:00am - 6:00pm (weekdays only)</option>' +
        '           <option value=\"9|18|1\">between 9:00am - 6:00pm (weekends only)</option>' +
        '           <option value=\"9|12|0\">between 9:00am - noon (weekdays only)</option>' +
        '           <option value=\"9|12|1\">between 9:00am - noon (weekends only)</option>' +
        '           <option value=\"12|18|0\">between noon - 6:00pm (weekdays only)</option>' +
        '           <option value=\"12|18|1\">between noon - 6:00pm (weekends only)</option>' +
        '       </select>
' +
        '
' +
        '
By setting this alert, you confirm that the entered mobile number is yours and that you consent to receive text messages to inform you about the alert. By providing your mobile number and signing up for alerts you agree to receive text messages that may be deemed marketing under applicable law, and that these messages may be sent using an autodialer. Your consent is not a condition of any purchase. Setting an alert is not a reservation of a product.
' +
        '
' +
        '       <button id=\"' + alertMePrefix + '-set-alert\" style=\"min-width:150px;width:50%;white-space:nowrap;cursor:pointer;line-height:25px;font-size:14px;border-radius:4px;border-color:#de0000;background:#de0000;color:#fff;\" type=\"submit\" title=\"Set Alert\" disabled=\"\">Set Alert</button>' +
        '
' +
        '
'
    };

    var UiPopup = function UiPopup() {
    };

    UiPopup.prototype.init = function (id, options) {
        var _self = this;
        var $body = $('body');

        // general settings to keep
        this.currentPageNr = 0;
        this.$pages = [];
        this.id = id;
        this.options = $.extend(true, {
            showClose: true,
            showFooter: true,
            header: null,
            maxWidth: null,
            bindings: null
        }, options);

        // make sure we have the minimal CSS needed
        if ($('#' + popupPrefix + '-style').length === 0) {
            $body.append(minCss);
        }

        // check if the element with this id exists
        var $el = $('#' + id);
        if ($el.length === 0) {
            var $minHtml = $(minHtml);
            $minHtml.attr('id', id);
            $body.append($minHtml);
            this.$popup = $minHtml;
        } else {
            this.$popup = $el;
        }

        // check if we show close
        var $close = this.$popup.find('.' + popupPrefix + '-close');
        if (this.getOption('showClose', true) === true) {
            $close.show();
            $close.click(function () {
                _self.hide();
            });
        } else {
            $close.hide()
        }

        // check if we show the footer
        var $footer = this.$popup.find('.' + popupPrefix + '-footer');
        if (this.getOption('showFooter', true) === true) {
            $footer.show();
        } else {
            $footer.hide()
        }

        // check the maxWidth
        var maxWidth = this.getOption('maxWidth', null);
        if (typeof maxWidth === 'number') {
            maxWidth = maxWidth + 'px';
        }
        if (typeof maxWidth === 'string') {
            var $content = this.$popup.find('.' + popupPrefix + '-content');
            $content.css('maxWidth', maxWidth);
        }

        // use some setters
        this.setBindings(null);
        this.setHeader(null);

        this.id = id;
    };

    UiPopup.prototype.css = function (selector, css) {
        var $el = this.$popup.find(selector);
        $el.css($.isPlainObject(css) ? css : {});

        return css;
    };

    UiPopup.prototype.find = function (selector) {
        return this.$popup.find(selector);
    };

    UiPopup.prototype.setBindings = function (bindings) {
        this.bindings = $.isPlainObject(bindings) ? bindings : this.getOption('bindings', {});
    };

    UiPopup.prototype.setBindings = function (bindings) {
        this.bindings = $.isPlainObject(bindings) ? bindings : this.getOption('bindings', {});
    };

    UiPopup.prototype.show = function (pageNr) {
        pageNr = this.validatePage(typeof pageNr === 'number' ? pageNr : 1);
        this.showPage(pageNr);
    };

    UiPopup.prototype.hide = function (id) {
        $('html')
            .css('marginRight', '')
            .css('overflow', '');

        this.$popup.hide();
    };

    UiPopup.prototype.addPage = function (page) {
        var $pagesContainer = this.$popup.find('.' + popupPrefix + '-pages');
        var $page = $('
' + page + '
');

        var pageNr = this.$pages.push($page);
        $page.attr('data-pageNr', pageNr);
        $page.hide();

        $pagesContainer.append($page);

        return $page;
    };

    UiPopup.prototype.addDefaultPage = function (id) {
        var page = defaultPages[id];
        if (typeof page === 'string') {
            return this.addPage(page);
        } else {
            return null;
        }
    };

    UiPopup.prototype.showNextPage = function () {
        this.showPage(this.currentPageNr + 1);
    };

    UiPopup.prototype.showPrevPage = function () {
        if (this.currentPageNr <= 1) {
            return;
        } else {
            this.showPage(this.currentPageNr - 1);
        }
    };

    UiPopup.prototype.showPage = function (pageNr) {
        pageNr = this.validatePage(pageNr);

        if (this.currentPageNr !== 0) {
            var $currentPage = this.$pages[this.currentPageNr - 1];
            this._resetBindings($currentPage);
            $currentPage.hide();
        }

        // set the current-page it will become affective now
        this.currentPageNr = pageNr;
        if (pageNr > 0) {
            var $page = this.$pages[pageNr - 1];
            this._applyBindings($page);
            $page.show();
        }

        $('html')
            .css('marginRight', '15px')
            .css('overflow', 'hidden');

        this.$popup.show();
    };

    UiPopup.prototype._applyBindings = function ($el) {
        var _self = this;

        var $placeholders = $el.find('[data-breinify-placeholder]');
        var popupPlaceholders = {
            popup: {
                currentPageNr: this.currentPageNr,
                totalPageNr: this.$pages.length
            }
        };
        $placeholders.each(function () {
            var $placeholderEl = $(this);
            var placeholder = $placeholderEl.attr('data-breinify-placeholder');

            var value;
            if (placeholder.indexOf('popup.') === 0) {
                value = Breinify.UTL.getNestedByPath(popupPlaceholders, placeholder);
            } else {
                value = Breinify.UTL.getNestedByPath(_self.bindings, placeholder);
            }

            $placeholderEl.text(value);
        });
    };

    UiPopup.prototype._resetBindings = function ($el) {
        var $placeholder = $el.find('[data-breinify-placeholder!=""]');
    };

    UiPopup.prototype.validatePage = function (pageNr) {
        if (typeof pageNr === 'number') {
            return Math.max(0, Math.min(this.$pages.length, pageNr));
        } else {
            return this.currentPageNr;
        }
    };

    UiPopup.prototype.setHeader = function (header) {
        if (typeof header !== 'string') {
            header = this.getOption('header', '');
        }

        var $header = this.$popup.find('.' + popupPrefix + '-header>div:first');
        $header.html(header);
    };

    UiPopup.prototype.getOption = function (option, def) {
        var val = this.options[option];
        if (typeof val === 'undefined' || val === null) {
            return def;
        } else {
            return val;
        }
    };

    // bind the module
    Breinify.plugins._add('uiPopup', {

        create: function (id, options) {
            var popup = new UiPopup();
            popup.init(id, options);

            return popup;
        }
    });
})();<|endoftext|>


<commit_before><commit_msg>Handle sort and data format through js (task #4928)<commit_after><|endoftext|>


<commit_before><commit_msg>RemplirListSprint devient une fonction global qui prend des arguments pour cibler<commit_after><|endoftext|>


<commit_before>require("node-jsx").install(
  {
    "extension":  ".jsx",
    "harmony":    true
  }
);

// Adds `Promise.promisify`
require('prfun');

var fs                      = require("fs");

fs = {
  "exists":                 // Can't use Promisify because fs.exists doesn't have an error callback
                            function (path) {
                              return new Promise(
                                function (resolve) {
                                  return require("fs").exists(path, resolve);
                                }
                              );
                            },

  "readFile":               Promise.promisify(fs.readFile)
};

var path                    = require("path");

var React                   = require("react/addons");
var ReactRouter             = require("react-router");
var mach                    = require("mach");
var Lazy                    = require("lazy.js");
var Webpack                 = require("webpack");
var WebpackDevServer        = require("webpack-dev-server");

var webpackSettingsGetter   = require("./webpackSettingsGetter.js");
var curryRoutesWithSettings = require("./curryRoutesWithSettings.js");

function Ambidex (argumentDict) {
  var self = this;

  var  rejectInitializationPromise;
  var resolveInitializationPromise;

  var initializationPromise = new Promise(
    function (resolve, reject) {
      rejectInitializationPromise = function (error) {
        console.error(error.stack);
        reject(error);
      };

      resolveInitializationPromise = resolve;
    }
  );

  try {
    if (self === global)
      throw new Error("You forgot the `new` in `new Ambidex(…)`!");

    if (!argumentDict || !arguments.length === 1)
      throw new Error("Ambidex requires an argument dictionary to be passed in.");

    self._initFromArgumentDict(argumentDict);

    var settings  = self._get("settings");

    self._verifyPaths(

    ).then(
      () => {
              self._initStack();
              self._initWebpack();

              if (self._get("shouldServeImmediately")) {
                process.title = settings.SHORT_NAME;
                self._startServing().then(
                  () => resolveInitializationPromise(self)
                );

              } else {
                resolveInitializationPromise(self);
              }
            }
    ).catch(
      error =>  rejectInitializationPromise(error)
    );

    return initializationPromise;

  } catch (error) {
    rejectInitializationPromise(error);
  }
}

Ambidex.prototype._has = function (key) {
  return this.hasOwnProperty("_" + key);
};

Ambidex.prototype._get = function (key) {
  return this["_" + key];
};

Ambidex.prototype._set = function (key, value) {
  this["_" + key] = value;
}

Ambidex.prototype._initFromArgumentDict = function (argumentDict) {
  var self = this;

  var requiredArguments = [
    "settings"
  ];

  var defaultsForOptionalArguments = {
    "shouldServeImmediately":   true,
    "middlewareInjector":       undefined
  };

  var optionalArguments = Object.keys(defaultsForOptionalArguments);

  Lazy(argumentDict).each(
    function (value, key) {
      if (
           Lazy(requiredArguments).contains(key)
        || Lazy(optionalArguments).contains(key)
      ) {
        self._set(key, value);

      } else {
        console.warn("Ambidex doesn't know what to do with {\"" + key + "\": " + value + "}");
      }
    }
  );

  requiredArguments.forEach(
    function (key) {
      if (!self._has(key)) {
        throw new Error("Ambidex requires `" + key + "` to be passed into its constructor");
      }
    }
  );

  // TODO: validate settings

  optionalArguments.forEach(
    function (key) {
      if (
           !self._has(key)
        && defaultsForOptionalArguments[key] !== undefined
      ) {
        self._set(key, defaultsForOptionalArguments[key]);
      }
    }
  );
};

Ambidex.prototype._verifyPaths = function () {
  /*  - Converts all FILESYSTEM_PATHS to absolute,
   *  - Makes sure they all exist,
   *  - Stores them on self with `self._set("routesPath", FILESYSTEM_PATHS["ROUTES"])`, and
   *  - `self.set("routes, require(ROUTES_PATH))`
   */

  var self      = this;
  var settings  = self._get("settings");
  var paths     = settings.FILESYSTEM_PATHS;

  [
    "BASE",
    "BUNDLES",
  ].forEach(
    (key) =>  paths[key] = paths[key].endsWith("/")
                ? settings.FILESYSTEM_PATHS[key]
                : settings.FILESYSTEM_PATHS[key] + "/"
  );

  var basePath  = paths["BASE"];

  return Promise.all(
    Lazy(paths).omit("BASE").map(
      (path, name) =>   {
                          path = path.startsWith("/")
                            ? path
                            : basePath + path;

                          return fs.exists(path).then(
                            pathIsValid =>  {
                                              if (pathIsValid) {
                                                self._set(name.toLowerCase() + "Path", path);

                                              } else {
                                                throw new Error("Ambidex could not find `" + path + "`.  Make sure routes.FILESYSTEM_PATHS[\"BASE\"] and [\"" + name + "\"] are set correctly.");
                                              }
                                            }
                          );
                        }
    ).toArray()
  ).then(
    () => {
            self._set("basePath", basePath)

            self._set(
              "scaffoldPath",
              self._get("scaffoldPath") || __dirname + "/Scaffold.jsx"
            );

            self._set(
              "routes",

              curryRoutesWithSettings(
                require(self._get("routesPath")),
                settings
              )
            );
          }
  );
};

Ambidex.prototype._initWebpack = function () {
  var self      = this;
  var settings  = self._get("settings");

  var webpackSettingsOptions  = {
    "paths":    {
                  "JSX":      __dirname + "/render.client.js",
                  "BASE":     self._get("basePath"),
                  "STYLES":   self._get("stylesPath"),
                  "BUNDLES":  self._get("bundlesPath"),
                }
  };

  if (settings.ENABLE_HOT_MODULE_REPLACEMENT) {
    webpackSettingsOptions.devServerOrigin = "http://" + settings.HOST + ":" + settings.WEBPACK_PORT;

  } else {
    webpackSettingsOptions.minimizeFileSize = true;
  }

  if (settings.SERVER_ONLY_MODULE_NAMES)
    webpackSettingsOptions.ignoredModuleNames = settings.SERVER_ONLY_MODULE_NAMES;

  // server settings are passed in when self._routes is defined

  webpackSettingsOptions.constants = Lazy(
    {
      "__ambidexSettings":    settings,
      "__ambidexRoutesPath":  self._get("routesPath"),
    }
  ).map(
    // Webpack `eval`s its constants, so we have to stringify them first
    (value, key) => [key, JSON.stringify(value)]
  ).toObject();

  self._webpackSettings = webpackSettingsGetter(webpackSettingsOptions);

  self.webpack      = new Webpack(self._webpackSettings);
  self.webpack.run  = Promise.promisify(self.webpack.run);

  if (settings.ENABLE_HOT_MODULE_REPLACEMENT) {
    self.stack.use(
      app => request => request.call(app).then(
                          function (response) {
                            response.headers["Access-Control-Allow-Origin"] = request.protocol + "//" + settings.HOST + ":" + settings.WEBPACK_PORT;
                            return response;
                          }
                        )
    );
  } else {
    self._webpackRan = self.webpack.run().then(
      (stats) =>  {
                    console.log(stats.toString());

                    var bundlesPath = self._get("bundlesPath");

                    return [
                      stats,

                      fs.readFile(
                        path.resolve(bundlesPath, "styles.js")
                      ),

                      fs.readFile(
                        path.resolve(bundlesPath, "jsx.js")
                      )
                    ];
                  }
    ).then(
      promises => Promise.all(promises)

    ).then(
      (resolvedPromises) => {
                              self._styleHTML  = resolvedPromises[1];
                              self._scriptHTML = resolvedPromises[2];

                              // pass webpackStats through, since our other return values (HTML) are already exposed on self
                              return resolvedPromises[0];
                            }
    ).catch(
      function (error) {
        console.error("Error packing bundles with Webpack:");
        console.error(error.stack);
      }
    );
  }
};

Ambidex.prototype._initStack = function () {
  var self = this;

  self.stack = new mach.stack();
  self.stack.use(mach.logger);
  self.stack.use(mach.gzip);
  self.stack.use(mach.charset, "utf-8");

  var middlewareInjector = self._get("middlewareInjector");
  if (middlewareInjector) {
    middlewareInjector(self.stack);
  }

  self.stack.route(
    "*",
    self._getRequestProcessor()
  );
};

// mach will hijack the `this` binding of a request processor
// so we return a closure to preserve access to `self`
Ambidex.prototype._getRequestProcessor = function () {
  var self      = this;
  var settings  = self._get("settings");
  var routes    = self._get("routes");

  return function (connection) {
    var styleProp  = {};
    var scriptProp = {};

    var bundlesURL = self._webpackSettings.output.publicPath;

    if (settings.ENABLE_HOT_MODULE_REPLACEMENT) {
      styleProp.src  = bundlesURL + "styles.js";
      scriptProp.src = bundlesURL + "jsx.js";

    } else {
      // Inline the source if we aren't using Hot Module Replacement to reduce
      // unneccesary requests
      styleProp.__html  = self._styleHTML;
      scriptProp.__html = self._scriptHTML;
    }

    return Promise.all(
      [
//         ReactRouter.renderRoutesToString(
//           routes,
//           request.path
//         ),

        // If webpack is running, block til it's ready to return
        self._webpackRan
      ]
    ).then(
      function (resolvedPromises) {
//          var renderedResult = resolvedPromises.shift();

        return connection.html(
          [
            "<!DOCTYPE html>",

            // Running ReactRouter against the <html> element is buggy,
            // so we only render <Main> (which mounts to the <body>) with
            // ReactRouter and do the rest as static markup with <Scaffold>
            React.renderComponentToStaticMarkup(
              require(self._get("scaffoldPath"))(
                {
                  "favIconSrc": settings.FAV_ICON_URL,
                  "style":      styleProp,
                  "script":     scriptProp,
//                    "body":       {
//                                    "__html":   renderedResult.html
//                                  }
                }
              )
            )
          ].join("\n")
        );
      }
    ).catch(
      function (error) {
        console.error(error.stack);

        return {
          "status":   error.httpStatus,
          "content": "ReactRouter errored."
        };
      }
    )
  }
};

Ambidex.prototype._startServing = function () {
  var self = this;

  return Promise.all(
    [
      self._startServingWebpack(),
      self._startServingStack(),
    ]
  );
};

Ambidex.prototype._startServingStack = function () {
  var self      = this;
  var settings  = self._get("settings");

  // mach.serve isn't async, but we make a promise anyway because Webpack is, and we want to be consistent.
  return new Promise(
    function (resolve, reject) {

      try {
        mach.serve(
          self.stack,
          settings.VM_PORT || settings.PORT
        );

        resolve();

      } catch (error) {
        reject(error);
      }
    }
  );
};

Ambidex.prototype._startServingWebpack = function () {
  var self      = this;
  var settings  = self._get("settings");

  if (settings.ENABLE_HOT_MODULE_REPLACEMENT) {
    WebpackDevServer.prototype.listen = Promise.promisify(WebpackDevServer.prototype.listen);

    self.webpackDevServer = new WebpackDevServer(
      self.webpack,
      {
        "hot":        true,
        "publicPath": self._webpackSettings.output.publicPath
      }
    );

    return self.webpackDevServer.listen(
      settings.WEBPACK_PORT,
      settings.HOST
    ).then(
      function (result) {
        console.info("Started Webpack Dev Server on " + settings.HOST + ":" + settings.WEBPACK_PORT + "…");
      }
    );
  } else {
    return null;
  }
};

module.exports = Ambidex;
<commit_msg>Don't use script/styleProp until webpack has run<commit_after>require("node-jsx").install(
  {
    "extension":  ".jsx",
    "harmony":    true
  }
);

// Adds `Promise.promisify`
require('prfun');

var fs                      = require("fs");

fs = {
  "exists":                 // Can't use Promisify because fs.exists doesn't have an error callback
                            function (path) {
                              return new Promise(
                                function (resolve) {
                                  return require("fs").exists(path, resolve);
                                }
                              );
                            },

  "readFile":               Promise.promisify(fs.readFile)
};

var path                    = require("path");

var React                   = require("react/addons");
var ReactRouter             = require("react-router");
var mach                    = require("mach");
var Lazy                    = require("lazy.js");
var Webpack                 = require("webpack");
var WebpackDevServer        = require("webpack-dev-server");

var webpackSettingsGetter   = require("./webpackSettingsGetter.js");
var curryRoutesWithSettings = require("./curryRoutesWithSettings.js");

function Ambidex (argumentDict) {
  var self = this;

  var  rejectInitializationPromise;
  var resolveInitializationPromise;

  var initializationPromise = new Promise(
    function (resolve, reject) {
      rejectInitializationPromise = function (error) {
        console.error(error.stack);
        reject(error);
      };

      resolveInitializationPromise = resolve;
    }
  );

  try {
    if (self === global)
      throw new Error("You forgot the `new` in `new Ambidex(…)`!");

    if (!argumentDict || !arguments.length === 1)
      throw new Error("Ambidex requires an argument dictionary to be passed in.");

    self._initFromArgumentDict(argumentDict);

    var settings  = self._get("settings");

    self._verifyPaths(

    ).then(
      () => {
              self._initStack();
              self._initWebpack();

              if (self._get("shouldServeImmediately")) {
                process.title = settings.SHORT_NAME;
                self._startServing().then(
                  () => resolveInitializationPromise(self)
                );

              } else {
                resolveInitializationPromise(self);
              }
            }
    ).catch(
      error =>  rejectInitializationPromise(error)
    );

    return initializationPromise;

  } catch (error) {
    rejectInitializationPromise(error);
  }
}

Ambidex.prototype._has = function (key) {
  return this.hasOwnProperty("_" + key);
};

Ambidex.prototype._get = function (key) {
  return this["_" + key];
};

Ambidex.prototype._set = function (key, value) {
  this["_" + key] = value;
}

Ambidex.prototype._initFromArgumentDict = function (argumentDict) {
  var self = this;

  var requiredArguments = [
    "settings"
  ];

  var defaultsForOptionalArguments = {
    "shouldServeImmediately":   true,
    "middlewareInjector":       undefined
  };

  var optionalArguments = Object.keys(defaultsForOptionalArguments);

  Lazy(argumentDict).each(
    function (value, key) {
      if (
           Lazy(requiredArguments).contains(key)
        || Lazy(optionalArguments).contains(key)
      ) {
        self._set(key, value);

      } else {
        console.warn("Ambidex doesn't know what to do with {\"" + key + "\": " + value + "}");
      }
    }
  );

  requiredArguments.forEach(
    function (key) {
      if (!self._has(key)) {
        throw new Error("Ambidex requires `" + key + "` to be passed into its constructor");
      }
    }
  );

  // TODO: validate settings

  optionalArguments.forEach(
    function (key) {
      if (
           !self._has(key)
        && defaultsForOptionalArguments[key] !== undefined
      ) {
        self._set(key, defaultsForOptionalArguments[key]);
      }
    }
  );
};

Ambidex.prototype._verifyPaths = function () {
  /*  - Converts all FILESYSTEM_PATHS to absolute,
   *  - Makes sure they all exist,
   *  - Stores them on self with `self._set("routesPath", FILESYSTEM_PATHS["ROUTES"])`, and
   *  - `self.set("routes, require(ROUTES_PATH))`
   */

  var self      = this;
  var settings  = self._get("settings");
  var paths     = settings.FILESYSTEM_PATHS;

  [
    "BASE",
    "BUNDLES",
  ].forEach(
    (key) =>  paths[key] = paths[key].endsWith("/")
                ? settings.FILESYSTEM_PATHS[key]
                : settings.FILESYSTEM_PATHS[key] + "/"
  );

  var basePath  = paths["BASE"];

  return Promise.all(
    Lazy(paths).omit("BASE").map(
      (path, name) =>   {
                          path = path.startsWith("/")
                            ? path
                            : basePath + path;

                          return fs.exists(path).then(
                            pathIsValid =>  {
                                              if (pathIsValid) {
                                                self._set(name.toLowerCase() + "Path", path);

                                              } else {
                                                throw new Error("Ambidex could not find `" + path + "`.  Make sure routes.FILESYSTEM_PATHS[\"BASE\"] and [\"" + name + "\"] are set correctly.");
                                              }
                                            }
                          );
                        }
    ).toArray()
  ).then(
    () => {
            self._set("basePath", basePath)

            self._set(
              "scaffoldPath",
              self._get("scaffoldPath") || __dirname + "/Scaffold.jsx"
            );

            self._set(
              "routes",

              curryRoutesWithSettings(
                require(self._get("routesPath")),
                settings
              )
            );
          }
  );
};

Ambidex.prototype._initWebpack = function () {
  var self      = this;
  var settings  = self._get("settings");

  var webpackSettingsOptions  = {
    "paths":    {
                  "JSX":      __dirname + "/render.client.js",
                  "BASE":     self._get("basePath"),
                  "STYLES":   self._get("stylesPath"),
                  "BUNDLES":  self._get("bundlesPath"),
                }
  };

  if (settings.ENABLE_HOT_MODULE_REPLACEMENT) {
    webpackSettingsOptions.devServerOrigin = "http://" + settings.HOST + ":" + settings.WEBPACK_PORT;

  } else {
    webpackSettingsOptions.minimizeFileSize = true;
  }

  if (settings.SERVER_ONLY_MODULE_NAMES)
    webpackSettingsOptions.ignoredModuleNames = settings.SERVER_ONLY_MODULE_NAMES;

  // server settings are passed in when self._routes is defined

  webpackSettingsOptions.constants = Lazy(
    {
      "__ambidexSettings":    settings,
      "__ambidexRoutesPath":  self._get("routesPath"),
    }
  ).map(
    // Webpack `eval`s its constants, so we have to stringify them first
    (value, key) => [key, JSON.stringify(value)]
  ).toObject();

  self._webpackSettings = webpackSettingsGetter(webpackSettingsOptions);

  self.webpack      = new Webpack(self._webpackSettings);
  self.webpack.run  = Promise.promisify(self.webpack.run);

  if (settings.ENABLE_HOT_MODULE_REPLACEMENT) {
    self.stack.use(
      app => request => request.call(app).then(
                          function (response) {
                            response.headers["Access-Control-Allow-Origin"] = request.protocol + "//" + settings.HOST + ":" + settings.WEBPACK_PORT;
                            return response;
                          }
                        )
    );
  } else {
    self._webpackRan = self.webpack.run().then(
      (stats) =>  {
                    console.log(stats.toString());

                    var bundlesPath = self._get("bundlesPath");

                    return [
                      stats,

                      fs.readFile(
                        path.resolve(bundlesPath, "styles.js")
                      ),

                      fs.readFile(
                        path.resolve(bundlesPath, "jsx.js")
                      )
                    ];
                  }
    ).then(
      promises => Promise.all(promises)

    ).then(
      (resolvedPromises) => {
                              self._styleHTML  = resolvedPromises[1];
                              self._scriptHTML = resolvedPromises[2];

                              // pass webpackStats through, since our other return values (HTML) are already exposed on self
                              return resolvedPromises[0];
                            }
    ).catch(
      function (error) {
        console.error("Error packing bundles with Webpack:");
        console.error(error.stack);
      }
    );
  }
};

Ambidex.prototype._initStack = function () {
  var self = this;

  self.stack = new mach.stack();
  self.stack.use(mach.logger);
  self.stack.use(mach.gzip);
  self.stack.use(mach.charset, "utf-8");

  var middlewareInjector = self._get("middlewareInjector");
  if (middlewareInjector) {
    middlewareInjector(self.stack);
  }

  self.stack.route(
    "*",
    self._getRequestProcessor()
  );
};

// mach will hijack the `this` binding of a request processor
// so we return a closure to preserve access to `self`
Ambidex.prototype._getRequestProcessor = function () {
  var self      = this;
  var settings  = self._get("settings");
  var routes    = self._get("routes");

  return function (connection) {
    var styleProp  = {};
    var scriptProp = {};

    var bundlesURL = self._webpackSettings.output.publicPath;

    return Promise.all(
      [
//         ReactRouter.renderRoutesToString(
//           routes,
//           request.path
//         ),

        // If webpack is running, block til it's ready to return
        self._webpackRan
      ]
    ).then(
      function (resolvedPromises) {
//         var renderedResult = resolvedPromises.shift();

        if (settings.ENABLE_HOT_MODULE_REPLACEMENT) {
          styleProp.src  = bundlesURL + "styles.js";
          scriptProp.src = bundlesURL + "jsx.js";

        } else {
          // Inline the source if we aren't using Hot Module Replacement to reduce
          // unneccesary requests
          styleProp.__html  = self._styleHTML;
          scriptProp.__html = self._scriptHTML;
        }

        return connection.html(
          [
            "<!DOCTYPE html>",

            // Running ReactRouter against the <html> element is buggy,
            // so we only render <Main> (which mounts to the <body>) with
            // ReactRouter and do the rest as static markup with <Scaffold>
            React.renderComponentToStaticMarkup(
              require(self._get("scaffoldPath"))(
                {
                  "favIconSrc": settings.FAV_ICON_URL,
                  "style":      styleProp,
                  "script":     scriptProp,
//                   "body":       {
//                                   "__html":   renderedResult.html
//                                 }
                }
              )
            )
          ].join("\n")
        );
      }
    ).catch(
      function (error) {
        console.error(error.stack);

        return {
          "status":   error.httpStatus,
          "content": "ReactRouter errored."
        };
      }
    )
  }
};

Ambidex.prototype._startServing = function () {
  var self = this;

  return Promise.all(
    [
      self._startServingWebpack(),
      self._startServingStack(),
    ]
  );
};

Ambidex.prototype._startServingStack = function () {
  var self      = this;
  var settings  = self._get("settings");

  // mach.serve isn't async, but we make a promise anyway because Webpack is, and we want to be consistent.
  return new Promise(
    function (resolve, reject) {

      try {
        mach.serve(
          self.stack,
          settings.VM_PORT || settings.PORT
        );

        resolve();

      } catch (error) {
        reject(error);
      }
    }
  );
};

Ambidex.prototype._startServingWebpack = function () {
  var self      = this;
  var settings  = self._get("settings");

  if (settings.ENABLE_HOT_MODULE_REPLACEMENT) {
    WebpackDevServer.prototype.listen = Promise.promisify(WebpackDevServer.prototype.listen);

    self.webpackDevServer = new WebpackDevServer(
      self.webpack,
      {
        "hot":        true,
        "publicPath": self._webpackSettings.output.publicPath
      }
    );

    return self.webpackDevServer.listen(
      settings.WEBPACK_PORT,
      settings.HOST
    ).then(
      function (result) {
        console.info("Started Webpack Dev Server on " + settings.HOST + ":" + settings.WEBPACK_PORT + "…");
      }
    );
  } else {
    return null;
  }
};

module.exports = Ambidex;
<|endoftext|>


<commit_before>import React from 'react';
import {StateNavigator} from 'navigation';
import {NavigationHandler} from 'navigation-react';
import {NavigationStack} from 'navigation-react-native';
import {Linking} from 'react-native';
import Grid from './Grid';
import Detail from './Detail';

const colors = [
  'maroon', 'red', 'crimson', 'orange', 'brown', 'sienna', 'olive',
  'purple', 'fuchsia', 'indigo', 'green', 'navy', 'blue', 'teal', 'black'
];

const stateNavigator = new StateNavigator([
  {key: 'grid'},
  {key: 'detail', trackCrumbTrail: true},
]);

const { grid, detail } = stateNavigator.states;
grid.renderScene = () => <Grid colors={colors}/>;
detail.renderScene = (data) => <Detail colors={colors} {...data}/>;

stateNavigator.navigate('grid');

/*detail.truncateCrumbTrail = (state, data, crumbs) => (
  crumbs.slice(-1)[0].state === detail ? crumbs.slice(0, -1) : crumbs
);*/

const openLink = (url) => {
  if (url) {
    var color = url.split('=')[1];
    var {state, data} = stateNavigator.stateContext;
    if (state === detail) {
      const {filter, search} = data;
      const suffix = search ? '_search' : '';
      const matched = !filter || color.indexOf(filter.toLowerCase()) !== -1;
      const name = matched ? color + suffix : null;
      stateNavigator.navigate('detail', {color, name, filter, search});
    } else {
      stateNavigator.navigate('detail', {color, name: color});
    }
  }
};

Linking.getInitialURL().then(openLink);
Linking.addEventListener('url', ({url}) => openLink(url));

const App = () => (
  <NavigationHandler stateNavigator={stateNavigator}>
    <NavigationStack sharedElements={(_, {name}) => name && [name]} />
  </NavigationHandler>
);
export default App;
<commit_msg>Reverted accidental change<commit_after>import React from 'react';
import {StateNavigator} from 'navigation';
import {NavigationHandler} from 'navigation-react';
import {NavigationStack} from 'navigation-react-native';
import {Linking} from 'react-native';
import Grid from './Grid';
import Detail from './Detail';

const colors = [
  'maroon', 'red', 'crimson', 'orange', 'brown', 'sienna', 'olive',
  'purple', 'fuchsia', 'indigo', 'green', 'navy', 'blue', 'teal', 'black'
];

const stateNavigator = new StateNavigator([
  {key: 'grid'},
  {key: 'detail', trackCrumbTrail: true},
]);

const { grid, detail } = stateNavigator.states;
grid.renderScene = () => <Grid colors={colors}/>;
detail.renderScene = (data) => <Detail colors={colors} {...data}/>;

stateNavigator.navigate('grid');

detail.truncateCrumbTrail = (state, data, crumbs) => (
  crumbs.slice(-1)[0].state === detail ? crumbs.slice(0, -1) : crumbs
);

const openLink = (url) => {
  if (url) {
    var color = url.split('=')[1];
    var {state, data} = stateNavigator.stateContext;
    if (state === detail) {
      const {filter, search} = data;
      const suffix = search ? '_search' : '';
      const matched = !filter || color.indexOf(filter.toLowerCase()) !== -1;
      const name = matched ? color + suffix : null;
      stateNavigator.navigate('detail', {color, name, filter, search});
    } else {
      stateNavigator.navigate('detail', {color, name: color});
    }
  }
};

Linking.getInitialURL().then(openLink);
Linking.addEventListener('url', ({url}) => openLink(url));

const App = () => (
  <NavigationHandler stateNavigator={stateNavigator}>
    <NavigationStack sharedElements={(_, {name}) => name && [name]} />
  </NavigationHandler>
);
export default App;
<|endoftext|>


<commit_before><commit_msg>Added incoming number on js side<commit_after><|endoftext|>


<commit_before>class Point {
  constructor(x, y) {
    this.x = x;
    this.y = y;
  }
}

class Size {
  constructor(width, height) {
    this.width = width;
    this.height = height;
  }
}

class Keyboard {
  constructor(element) {
    this.element = element;

    this.keyMap = {};

    this.element.addEventListener('keydown', this);
    this.element.addEventListener('keyup', this);
  }

  handleEvent(event) {
    this.keyMap[ event.key ] = event.type === 'keydown';
  }
}

class Game {
  constructor(canvas) {
    this.canvas = canvas;

    this.controls = new Keyboard(canvas);

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

    this.running = true;
    this.shimu = new Entity(new Point(50, 50), new Size(10, 10), 'red');

    this.boundTick = () => this.tick();
  }

  start() {
    this.running = true;
    requestAnimationFrame(this.boundTick);
  }

  tick() {
    this.shimu.draw(this.ctx);

    if (this.running) {
      requestAnimationFrame(this.boundTick);
    }
  }
}

class Entity {
  constructor(point, size, color) {
    this.point = point;
    this.size = size;
    this.color = color;
  }

  draw(ctx) {
    ctx.fillStyle = String(this.color);
    ctx.fillRect(this.point.x, this.point.y, this.size.width, this.size.height);
  }
}

function start(canvas) {
  game = new Game(canvas);

  game.start();
}

var Shimu = {
  start: start,
};
<commit_msg>Added Guns and basic bullets.<commit_after>
class Point {
  constructor(x, y) {
    this.x = x;
    this.y = y;
  }

  move(dx, dy) {
    this.x += dx;
    this.y += dy;
  }
}

class Size {
  constructor(width, height) {
    this.width = width;
    this.height = height;
  }
}

class Keyboard {
  constructor(element) {
    this.element = element;

    this.keyMap = {};

    this.element.addEventListener('keydown', this);
    this.element.addEventListener('keyup', this);
  }

  handleEvent(event) {
    this.keyMap[ event.key ] = event.type === 'keydown';
  }
}

class Game {
  constructor(canvas) {
    this.canvas = canvas;

    this.controls = new Keyboard(canvas);

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

    this.running = true;
    this.shimu = new Entity(new Point(50, 50), new Size(10, 10), 'red');

    this.boundTick = () => this.tick();
  }

  start() {
    this.running = true;
    requestAnimationFrame(this.boundTick);
  }

  tick() {
    this.shimu.draw(this.ctx);

    if (this.running) {
      requestAnimationFrame(this.boundTick);
    }
  }
}

class Gun {
  constructor(game, owner, projectile, reticule) {
    this.game = game;
    this.owner = owner;
    this.projectileConstructor = projectile;
    this.reticule = reticule;
  }

  fire() {
    const bullet = new this.projectileConstructor(owner, reticule);
  }
}

class Bullet extends Entity {
  constructor(owner, reticule) {
    super(owner.point, 2, 'gray');
    this.direction = {x: 1, y = 0};
    this.owner = owner;
  }

  tick() {
    this.point.move(this.direction);
  }
}

class Entity {
  constructor(point, size, color) {
    this.point = point;
    this.size = size;
    this.color = color;
  }

  draw(ctx) {
    ctx.fillStyle = String(this.color);
    ctx.fillRect(this.point.x, this.point.y, this.size.width, this.size.height);
  }
}

function start(canvas) {
  game = new Game(canvas);

  game.start();
}

var Shimu = {
  start: start,
};
<|endoftext|>


<commit_before><commit_msg>removed dummy data (index, type, id) from header, and unused more vert items icon<commit_after><|endoftext|>


<commit_before>const rp = require('request-promise');
const covert = require('../../covert.js');
const updateGuildInfo = require('../events/update-guild-info.js');
const messageDefaultChannel = require('../utilities/message-default-channel.js');

module.exports = function(guild, bot_auth){

	/*
	const sendWelcomeMessage = prefix => {
		let escaped_prefix = prefix.replace(/[^a-zA-Z0-9]/g, '\\$&');
		messageDefaultChannel(guild, `This server can now use stickers! Type **${escaped_prefix}commands** to get started.`);
	}
	*/

	rp({
		method: 'POST',
		uri: `${covert.app_url}/api/guilds/`,
		body: {
			id: guild.id,
			guildName: guild.name,
			icon: guild.icon || null
		},
		headers: {Authorization: bot_auth},
		json: true
	})
	.then(() => {
		console.log(`Guild ${guild.id} added!`);
		// sendWelcomeMessage('$');
		updateGuildInfo(guild, bot_auth);
	})
	.catch(err => {

		if(err.statusCode != 409){
			console.error(err.message);
			return;
		}

		//Re-Activate guild, as it already exists within database
		rp({
			method: 'PATCH',
			uri: `${covert.app_url}/api/guilds/${guild.id}`,
			body: {isActive: true},
			headers: {Authorization: bot_auth},
			json: true
		})
		.then(res => {
			console.log(`Guild ${guild.id} activated!`);
			sendWelcomeMessage(res.commandPrefix);
			updateGuildInfo(guild, bot_auth);
		})
		.catch(err => {
			console.error(err.message);
		});

	});
}<commit_msg>Remove call to undefined function<commit_after>const rp = require('request-promise');
const covert = require('../../covert.js');
const updateGuildInfo = require('../events/update-guild-info.js');
const messageDefaultChannel = require('../utilities/message-default-channel.js');

module.exports = function(guild, bot_auth){

	/*
	const sendWelcomeMessage = prefix => {
		let escaped_prefix = prefix.replace(/[^a-zA-Z0-9]/g, '\\$&');
		messageDefaultChannel(guild, `This server can now use stickers! Type **${escaped_prefix}commands** to get started.`);
	}
	*/

	rp({
		method: 'POST',
		uri: `${covert.app_url}/api/guilds/`,
		body: {
			id: guild.id,
			guildName: guild.name,
			icon: guild.icon || null
		},
		headers: {Authorization: bot_auth},
		json: true
	})
	.then(() => {
		console.log(`Guild ${guild.id} added!`);
		// sendWelcomeMessage('$');
		updateGuildInfo(guild, bot_auth);
	})
	.catch(err => {

		if(err.statusCode != 409){
			console.error(err.message);
			return;
		}

		//Re-Activate guild, as it already exists within database
		rp({
			method: 'PATCH',
			uri: `${covert.app_url}/api/guilds/${guild.id}`,
			body: {isActive: true},
			headers: {Authorization: bot_auth},
			json: true
		})
		.then(res => {
			console.log(`Guild ${guild.id} activated!`);
			// sendWelcomeMessage(res.commandPrefix);
			updateGuildInfo(guild, bot_auth);
		})
		.catch(err => {
			console.error(err.message);
		});

	});
}<|endoftext|>


<commit_before><commit_msg>Stops preventing default action for keydown events that aren't used<commit_after><|endoftext|>


<commit_before>const settings = require('./../../settings.json');
module.exports = async function (message) {
    if (message.author.bot) return;//ignore if its a verified bot account

    if (!message.guild) return;//ignore if DM

    let muted = message.member.roles.find(function (r) {
        if (r.name.toLowerCase().includes('mute') && !r.name.toLowerCase().includes('non') && !r.name.toLowerCase().includes('test'))
            return r
    })
    if (muted && message.deletable) {
        message.delete();
        message.channel.overwritePermissions(muted, { 'SEND_MESSAGES': false }, "Muted").catch(() => console.log("i tried my best"));
    }
    if (message.channel.name.toLowerCase().includes("bot") || message.channel.name.toLowerCase().includes("command") || message.channel.name.toLowerCase().includes("test")) return;

    if (settings.slowmov && message.channel.deletable && !message.member.permissions.has("MANAGE_MESSAGES") && message.channel.messages) {
        let messages = message.channel.messages.filter(m => m.author.id == message.author.id).filter(m => m.createdTimestamp > Date.now() - 12000);
        if (messages.size > 3) {
            let duration = 10000;
            if (settings.muted) {
                let is_muted = settings.muted.find(function (t) {
                    if ((t.id == message.author.id) && (t.time > (Date.now() - 5000)))
                        return t;
                });
                if (is_muted)
                    return;//settings.muted.push({ id: message.author.id, time: Date.now() });
                is_muted = settings.muted.filter(function (t) {
                    if ((t.id == message.author.id) && (t.time > (Date.now() - 900000)))
                        return t;
                });
                if (is_muted.length > 0)
                    duration = (is_muted.length + 1) * duration;
            }
            message.channel.overwritePermissions(message.author, { 'SEND_MESSAGES': false }, "Muted");
            let mm = await message.reply("You have been muted for " + (duration / 1000) + " seconds by slowmov for sending messages too fast. Please calm down");
            settings.muted.push({ id: message.author.id, time: Date.now() })
            setTimeout(() => {
                mm.delete();
                let p = message.channel.permissionOverwrites.get(message.author.id);
                if (p)
                    p.delete();
            }, duration)
        }
    }

}
<commit_msg>Update slowmov.js<commit_after>const settings = require('./../../settings.json');
module.exports = async function (message) {
    if (message.author.bot) return;//ignore if its a verified bot account

    if (!message.guild || message.member == null) return;//ignore if DM

    let muted = message.member.roles.find(function (r) {
        if (r.name.toLowerCase().includes('mute') && !r.name.toLowerCase().includes('non') && !r.name.toLowerCase().includes('test'))
            return r
    })
    if (muted && message.deletable) {
        message.delete();
        message.channel.overwritePermissions(muted, { 'SEND_MESSAGES': false }, "Muted").catch(() => console.log("i tried my best"));
    }
    if (message.channel.name.toLowerCase().includes("bot") || message.channel.name.toLowerCase().includes("command") || message.channel.name.toLowerCase().includes("test")) return;

    if (settings.slowmov && message.channel.deletable && !message.member.permissions.has("MANAGE_MESSAGES") && message.channel.messages) {
        let messages = message.channel.messages.filter(m => m.author.id == message.author.id).filter(m => m.createdTimestamp > Date.now() - 12000);
        if (messages.size > 3) {
            let duration = 10000;
            if (settings.muted) {
                let is_muted = settings.muted.find(function (t) {
                    if ((t.id == message.author.id) && (t.time > (Date.now() - 5000)))
                        return t;
                });
                if (is_muted)
                    return;//settings.muted.push({ id: message.author.id, time: Date.now() });
                is_muted = settings.muted.filter(function (t) {
                    if ((t.id == message.author.id) && (t.time > (Date.now() - 900000)))
                        return t;
                });
                if (is_muted.length > 0)
                    duration = (is_muted.length + 1) * duration;
            }
            message.channel.overwritePermissions(message.author, { 'SEND_MESSAGES': false }, "Muted");
            let mm = await message.reply("You have been muted for " + (duration / 1000) + " seconds by slowmov for sending messages too fast. Please calm down");
            settings.muted.push({ id: message.author.id, time: Date.now() })
            setTimeout(() => {
                mm.delete();
                let p = message.channel.permissionOverwrites.get(message.author.id);
                if (p)
                    p.delete();
            }, duration)
        }
    }

}
<|endoftext|>


<commit_before><commit_msg>Collapse drawer on logout<commit_after><|endoftext|>