<commit_before>/**
 * @author Dmytro Zemlianskyi from Ubrainians for imCode
 * 23.04.19
 */
define(
    'imcms-temporal-data-tab-builder',
    [
        'imcms-super-admin-tab', 'imcms-bem-builder', 'imcms-i18n-texts', 'imcms-temporal-data-rest-api',
        'imcms-components-builder', 'jquery'
    ],
    function (SuperAdminTab, BEM, texts, temporalDataApi, components, $) {

        texts = texts.superAdmin.temporalContent;

        const LOADING_INTERVAL = 2000;
        const TIME_PER_ONE_REINDEX = 45;
        const TIME_PER_ONE_RECACHE = 500;
        const DISABLED_BUTTON_CLASS_NAME = 'imcms-button--disabled';

        function buildActions($button, $date, $loading, $success) {
            return new BEM({
                block: 'actions',
                elements: {
                    'button': $button,
                    'date': $date,
                    'loading': $loading,
                    'success': $success,
                },
            }).buildBlockStructure('<div>');
        }

        class DateLabel {
            constructor(dateRequest, title) {
                this.dateRequest = dateRequest;
                this.title = title;
                this.$label = $('<div>', {
                    class: 'imcms-label',
                    text: title + ':',
                });

                this.updateDate();
            }

            updateDate() {
                this.dateRequest().done(dateString => {
                    this.$label.text(this.title + ': ' + dateString);
                })
            }

            getLabel() {
                return this.$label;
            }
        }

        class TimeLabel {
            constructor(title) {
                this.title = title;
                this.$label = $('<div>', {
                    class: 'imcms-label',
                    text: title + ': ',
                });
            }

            setMillis(millis) {
                this.$label.text(this.title + ': ' + this.millisToTimeString(millis));
            }

            millisToTimeString(millis) {
                let seconds = (millis / 1000);
                let minutes = seconds / 60;
                let hours = minutes / 60;

                seconds = seconds % 60;
                minutes = minutes % 60;

                const correctS = this.numberToCorrectString(Math.round(seconds));
                const correctM = this.numberToCorrectString(Math.round(minutes));
                const correctH = Math.round(hours);

                return correctH + ':' + correctM + ':' + correctS;
            }

            numberToCorrectString(number) {
                return number < 10 ? '0' + number : '' + number;
            }

            getLabel() {
                return this.$label;
            }
        }

        function buildLoadingAnimation() {
            return $('<div>', {
                class: 'loading-animation',
                style: 'display: none',
            });
        }

        function buildSuccessAnimation() {
            return $('<div>', {
                class: 'success-animation',
                style: 'display: none',
            });
        }

        function deleteCacheRequest(request, date, $loading, $success) {
            $success.hide();
            $loading.show();
            request().done(() => {
                date.updateDate();
                $loading.hide();
                $success.show();
            });
        }

        function buildReindexRow() {
            function buildReindexTitleMessage() {
                return components.texts.titleText('<div>', texts.actions.rebuildIndex, {});
            }

            function init($button, date) {
                temporalDataApi.getAmountOfIndexedDocuments().done(currentAmount => {
                    if (currentAmount !== -1) {
                        $button
                            .attr('disabled', '')
                            .text(texts.indexing)
                            .addClass(DISABLED_BUTTON_CLASS_NAME);

                        const interval = setInterval(
                            () => disableButtonWhileIndexing($button, date, interval),
                            LOADING_INTERVAL
                        );
                    }
                });
            }

            function disableButtonWhileIndexing($button, date, interval) {
                temporalDataApi.getAmountOfIndexedDocuments().done(currentAmount => {
                    if (currentAmount === -1) {
                        clearInterval(interval);
                        date.updateDate();
                        $button
                            .removeAttr('disabled')
                            .removeClass(DISABLED_BUTTON_CLASS_NAME)
                            .text(texts.init);
                    }
                });
            }

            function buildReindexActions() {
                const $loading = buildLoadingAnimation();
                const $success = buildSuccessAnimation();

                const lastUpdate = new DateLabel(temporalDataApi.getDateDocumentIndex, texts.lastUpdate);
                const timeLeft = new TimeLabel(texts.timeLeft);
                timeLeft.getLabel().hide();

                const $button = components.buttons.warningButton({
                    'class': 'imcms-buttons imcms-form__field',
                    text: texts.initIndexing,
                    click: () => reindexRequest($button, $loading, $success, lastUpdate, timeLeft),
                });

                init($button, lastUpdate);

                return new BEM({
                    block: 'actions',
                    elements: {
                        'button': $button,
                        'date': lastUpdate.getLabel(),
                        'loading': $loading,
                        'success': $success,
                        'time': timeLeft.getLabel(),
                    },
                }).buildBlockStructure('<div>');
            }

            function reindexRequest($button, $loading, $success, date, time) {
                $button
                    .attr('disabled', '')
                    .text(texts.indexing)
                    .addClass(DISABLED_BUTTON_CLASS_NAME);
                $success.hide();

                temporalDataApi.getAmountOfIndexedDocuments().done(currentAmount => {
                    if (currentAmount === -1) {
                        $loading.text('0%');
                        $loading.show();

                        temporalDataApi.rebuildDocumentIndex().done(totalAmount => {
                            time.setMillis(calculateTimeByAmount(totalAmount, 0, TIME_PER_ONE_REINDEX));
                            time.getLabel().show();

                            const interval = setInterval(
                                () => updateLoading($button, $loading, $success, interval, totalAmount, date, time),
                                LOADING_INTERVAL
                            );
                        });
                    } else {
                        const interval = setInterval(
                            () => disableButtonWhileIndexing($button, date, interval),
                            LOADING_INTERVAL
                        );
                    }
                });
            }

            function updateLoading($button, $loading, $success, interval, totalAmount, date, time) {
                temporalDataApi.getAmountOfIndexedDocuments().done(currentAmount => {

                    if (currentAmount === -1) {
                        clearInterval(interval);
                        date.updateDate();
                        $button
                            .removeAttr('disabled')
                            .removeClass(DISABLED_BUTTON_CLASS_NAME)
                            .text(texts.initIndexing);
                        $loading.hide();
                        $success.show();
                        time.getLabel().hide();

                        return;
                    }

                    time.setMillis(calculateTimeByAmount(totalAmount, currentAmount, TIME_PER_ONE_REINDEX));
                    const percent = getPercent(totalAmount, currentAmount);
                    $loading.text(percent + '%');
                });
            }

            function calculateTimeByAmount(totalAmount, currentAmount, timePerOne) {
                return (totalAmount - currentAmount) * timePerOne;
            }

            function getPercent(totalAmount, currentAmount) {
                return Math.round(100 / totalAmount * currentAmount);
            }

            return new BEM({
                block: 'imcms-content-action-row',
                elements: {
                    'action-title': buildReindexTitleMessage(),
                    'actions': buildReindexActions(),
                }
            }).buildBlockStructure('<div>');
        }

        function buildPublicDocumentCacheRow() {
            function buildPublicDocumentCacheTitleMessage() {
                return components.texts.titleText('<div>', texts.actions.deletePublicDocCache, {});
            }

            function buildPublicDocumentActions() {
                const $loading = buildLoadingAnimation();
                const $success = buildSuccessAnimation();

                const lastUpdate = new DateLabel(temporalDataApi.getDateRemoveDocumentCache, texts.lastDeleteCache);

                const $button = components.buttons.warningButton({
                    'class': 'imcms-buttons imcms-form__field',
                    text: texts.init,
                    click: () => deleteCacheRequest(temporalDataApi.deletePublicDocumentCache, lastUpdate, $loading, $success),
                });

                return buildActions($button, lastUpdate.getLabel(), $loading, $success);
            }

            return new BEM({
                block: 'imcms-content-action-row',
                elements: {
                    'action-title': buildPublicDocumentCacheTitleMessage(),
                    'actions': buildPublicDocumentActions(),
                }
            }).buildBlockStructure('<div>');
        }

        function buildStaticContentRow() {
            function buildStaticContenTitleMessage() {
                return components.texts.titleText('<div>', texts.actions.deleteStaticCache, {});
            }

            function buildInitDeleteStaticContentActions() {
                const $loading = buildLoadingAnimation();
                const $success = buildSuccessAnimation();

                const lastUpdate = new DateLabel(temporalDataApi.getDateRemoveStaticContentCache, texts.lastDeleteCache);

                const $button = components.buttons.warningButton({
                    'class': 'imcms-buttons imcms-form__field',
                    text: texts.init,
                    click: () => deleteCacheRequest(temporalDataApi.deleteStaticContentCache, lastUpdate, $loading, $success),
                });

                return buildActions($button, lastUpdate.getLabel(), $loading, $success);
            }

            return new BEM({
                block: 'imcms-content-action-row',
                elements: {
                    'action-title': buildStaticContenTitleMessage(),
                    'actions': buildInitDeleteStaticContentActions(),
                }
            }).buildBlockStructure('<div>');
        }

        function buildOtherContentRow() {
            function buildOtherContentTitleMessage() {
                return components.texts.titleText('<div>', texts.actions.deleteOtherCache, {});
            }

            function buildInitDeleteOtherContentActions() {
                const $loading = buildLoadingAnimation();
                const $success = buildSuccessAnimation();

                const lastUpdate = new DateLabel(temporalDataApi.getDateRemoveOtherContentCache, texts.lastDeleteCache);

                const $button = components.buttons.warningButton({
                    'class': 'imcms-buttons imcms-form__field',
                    text: texts.init,
                    click: () => deleteCacheRequest(temporalDataApi.deleteOtherContentCache, lastUpdate, $loading, $success),
                });

                return buildActions($button, lastUpdate.getLabel(), $loading, $success);
            }

            return new BEM({
                block: 'imcms-content-action-row',
                elements: {
                    'action-title': buildOtherContentTitleMessage(),
                    'actions': buildInitDeleteOtherContentActions(),
                }
            }).buildBlockStructure('<div>');
        }

        function buildReCacheRow() {
            function buildReCacheTitleMessage() {
                return components.texts.titleText('<div>', texts.actions.buildCacheDocument, {});
            }

            function init($button, date) {
                temporalDataApi.getAmountOfCachedDocuments().done(currentAmount => {
                    if (currentAmount !== -1) {
                        $button
                            .attr('disabled', '')
                            .text(texts.caching)
                            .addClass(DISABLED_BUTTON_CLASS_NAME);

                        const interval = setInterval(
                            () => disableButtonWhileCaching($button, date, interval),
                            LOADING_INTERVAL
                        );
                    }
                });
            }

            function disableButtonWhileCaching($button, date, interval) {
                temporalDataApi.getAmountOfCachedDocuments().done(currentAmount => {
                    if (currentAmount === -1) {
                        clearInterval(interval);
                        date.updateDate();
                        $button
                            .removeAttr('disabled')
                            .removeClass(DISABLED_BUTTON_CLASS_NAME)
                            .text(texts.init);
                    }
                });
            }

            function buildReCacheActions() {
                const $loading = buildLoadingAnimation();
                const $success = buildSuccessAnimation();

                const lastUpdate = new DateLabel(temporalDataApi.getDateReCacheDocuments, texts.lastBuildCache);
                const timeLeft = new TimeLabel(texts.timeLeft);
                timeLeft.getLabel().hide();

                const $button = components.buttons.warningButton({
                    'class': 'imcms-buttons imcms-form__field',
                    text: texts.initCaching,
                    click: () => buildCacheRequest($button, $loading, $success, lastUpdate, timeLeft),
                });

                init($button, lastUpdate);

                return new BEM({
                    block: 'actions',
                    elements: {
                        'button': $button,
                        'date': lastUpdate.getLabel(),
                        'loading': $loading,
                        'success': $success,
                        'time': timeLeft.getLabel(),
                    },
                }).buildBlockStructure('<div>');
            }

            function buildCacheRequest($button, $loading, $success, date, time) {
                $button
                    .attr('disabled', '')
                    .text(texts.caching)
                    .addClass(DISABLED_BUTTON_CLASS_NAME);
                $success.hide();

                temporalDataApi.getAmountOfCachedDocuments().done(currentAmount => {
                    if (currentAmount === -1) {
                        $loading.text('0%');
                        $loading.show();
                        temporalDataApi.getTotalForCachingDocIdsAndAlias().done(totalAmount => {
                            time.setMillis(calculateTimeByAmount(totalAmount, 0, TIME_PER_ONE_RECACHE));
                            time.getLabel().show();

                            temporalDataApi.addDocumentsInCache().done(); //setInterval 2 sec?

                            const interval = setInterval(
                                () => updateLoading($button, $loading, $success, interval, totalAmount, date, time),
                                LOADING_INTERVAL
                            );
                        });

                    } else {
                        const interval = setInterval(
                            () => disableButtonWhileCaching($button, date, interval),
                            LOADING_INTERVAL
                        );
                    }
                });
            }

            function updateLoading($button, $loading, $success, interval, totalAmount, date, time) {
                temporalDataApi.getAmountOfCachedDocuments().done(currentAmount => {

                    if (currentAmount === -1) {
                        clearInterval(interval);
                        date.updateDate();
                        $button
                            .removeAttr('disabled')
                            .removeClass(DISABLED_BUTTON_CLASS_NAME)
                            .text(texts.initCaching);
                        $loading.hide();
                        $success.show();
                        time.getLabel().hide();

                        return;
                    }

                    time.setMillis(calculateTimeByAmount(totalAmount, currentAmount, TIME_PER_ONE_RECACHE));
                    let percent = getPercent(totalAmount, currentAmount);
                    $loading.text(percent + '%');
                });
            }

            function calculateTimeByAmount(totalAmount, currentAmount, timePerOne) {
                return (totalAmount - currentAmount) * timePerOne;
            }

            function getPercent(totalAmount, currentAmount) {
                return Math.round(100 / totalAmount * currentAmount);
            }

            return new BEM({
                block: 'imcms-content-action-row',
                elements: {
                    'action-title': buildReCacheTitleMessage(),
                    'actions': buildReCacheActions(),
                }
            }).buildBlockStructure('<div>');
        }

        return new SuperAdminTab(texts.name, [
            buildReindexRow(),
            buildPublicDocumentCacheRow(),
            buildStaticContentRow(),
            buildOtherContentRow(),
            buildReCacheRow()
        ]);
    }
);
<commit_msg>Issue IMCMS-505: Button for recache - Change time re-cache<commit_after>/**
 * @author Dmytro Zemlianskyi from Ubrainians for imCode
 * 23.04.19
 */
define(
    'imcms-temporal-data-tab-builder',
    [
        'imcms-super-admin-tab', 'imcms-bem-builder', 'imcms-i18n-texts', 'imcms-temporal-data-rest-api',
        'imcms-components-builder', 'jquery'
    ],
    function (SuperAdminTab, BEM, texts, temporalDataApi, components, $) {

        texts = texts.superAdmin.temporalContent;

        const LOADING_INTERVAL = 2000;
        const TIME_PER_ONE_REINDEX = 45;
        const TIME_PER_ONE_RECACHE = 3000;
        const DISABLED_BUTTON_CLASS_NAME = 'imcms-button--disabled';

        function buildActions($button, $date, $loading, $success) {
            return new BEM({
                block: 'actions',
                elements: {
                    'button': $button,
                    'date': $date,
                    'loading': $loading,
                    'success': $success,
                },
            }).buildBlockStructure('<div>');
        }

        class DateLabel {
            constructor(dateRequest, title) {
                this.dateRequest = dateRequest;
                this.title = title;
                this.$label = $('<div>', {
                    class: 'imcms-label',
                    text: title + ':',
                });

                this.updateDate();
            }

            updateDate() {
                this.dateRequest().done(dateString => {
                    this.$label.text(this.title + ': ' + dateString);
                })
            }

            getLabel() {
                return this.$label;
            }
        }

        class TimeLabel {
            constructor(title) {
                this.title = title;
                this.$label = $('<div>', {
                    class: 'imcms-label',
                    text: title + ': ',
                });
            }

            setMillis(millis) {
                this.$label.text(this.title + ': ' + this.millisToTimeString(millis));
            }

            millisToTimeString(millis) {
                let seconds = (millis / 1000);
                let minutes = seconds / 60;
                let hours = minutes / 60;

                seconds = seconds % 60;
                minutes = minutes % 60;

                const correctS = this.numberToCorrectString(Math.round(seconds));
                const correctM = this.numberToCorrectString(Math.round(minutes));
                const correctH = Math.round(hours);

                return correctH + ':' + correctM + ':' + correctS;
            }

            numberToCorrectString(number) {
                return number < 10 ? '0' + number : '' + number;
            }

            getLabel() {
                return this.$label;
            }
        }

        function buildLoadingAnimation() {
            return $('<div>', {
                class: 'loading-animation',
                style: 'display: none',
            });
        }

        function buildSuccessAnimation() {
            return $('<div>', {
                class: 'success-animation',
                style: 'display: none',
            });
        }

        function deleteCacheRequest(request, date, $loading, $success) {
            $success.hide();
            $loading.show();
            request().done(() => {
                date.updateDate();
                $loading.hide();
                $success.show();
            });
        }

        function buildReindexRow() {
            function buildReindexTitleMessage() {
                return components.texts.titleText('<div>', texts.actions.rebuildIndex, {});
            }

            function init($button, date) {
                temporalDataApi.getAmountOfIndexedDocuments().done(currentAmount => {
                    if (currentAmount !== -1) {
                        $button
                            .attr('disabled', '')
                            .text(texts.indexing)
                            .addClass(DISABLED_BUTTON_CLASS_NAME);

                        const interval = setInterval(
                            () => disableButtonWhileIndexing($button, date, interval),
                            LOADING_INTERVAL
                        );
                    }
                });
            }

            function disableButtonWhileIndexing($button, date, interval) {
                temporalDataApi.getAmountOfIndexedDocuments().done(currentAmount => {
                    if (currentAmount === -1) {
                        clearInterval(interval);
                        date.updateDate();
                        $button
                            .removeAttr('disabled')
                            .removeClass(DISABLED_BUTTON_CLASS_NAME)
                            .text(texts.init);
                    }
                });
            }

            function buildReindexActions() {
                const $loading = buildLoadingAnimation();
                const $success = buildSuccessAnimation();

                const lastUpdate = new DateLabel(temporalDataApi.getDateDocumentIndex, texts.lastUpdate);
                const timeLeft = new TimeLabel(texts.timeLeft);
                timeLeft.getLabel().hide();

                const $button = components.buttons.warningButton({
                    'class': 'imcms-buttons imcms-form__field',
                    text: texts.initIndexing,
                    click: () => reindexRequest($button, $loading, $success, lastUpdate, timeLeft),
                });

                init($button, lastUpdate);

                return new BEM({
                    block: 'actions',
                    elements: {
                        'button': $button,
                        'date': lastUpdate.getLabel(),
                        'loading': $loading,
                        'success': $success,
                        'time': timeLeft.getLabel(),
                    },
                }).buildBlockStructure('<div>');
            }

            function reindexRequest($button, $loading, $success, date, time) {
                $button
                    .attr('disabled', '')
                    .text(texts.indexing)
                    .addClass(DISABLED_BUTTON_CLASS_NAME);
                $success.hide();

                temporalDataApi.getAmountOfIndexedDocuments().done(currentAmount => {
                    if (currentAmount === -1) {
                        $loading.text('0%');
                        $loading.show();

                        temporalDataApi.rebuildDocumentIndex().done(totalAmount => {
                            time.setMillis(calculateTimeByAmount(totalAmount, 0, TIME_PER_ONE_REINDEX));
                            time.getLabel().show();

                            const interval = setInterval(
                                () => updateLoading($button, $loading, $success, interval, totalAmount, date, time),
                                LOADING_INTERVAL
                            );
                        });
                    } else {
                        const interval = setInterval(
                            () => disableButtonWhileIndexing($button, date, interval),
                            LOADING_INTERVAL
                        );
                    }
                });
            }

            function updateLoading($button, $loading, $success, interval, totalAmount, date, time) {
                temporalDataApi.getAmountOfIndexedDocuments().done(currentAmount => {

                    if (currentAmount === -1) {
                        clearInterval(interval);
                        date.updateDate();
                        $button
                            .removeAttr('disabled')
                            .removeClass(DISABLED_BUTTON_CLASS_NAME)
                            .text(texts.initIndexing);
                        $loading.hide();
                        $success.show();
                        time.getLabel().hide();

                        return;
                    }

                    time.setMillis(calculateTimeByAmount(totalAmount, currentAmount, TIME_PER_ONE_REINDEX));
                    const percent = getPercent(totalAmount, currentAmount);
                    $loading.text(percent + '%');
                });
            }

            function calculateTimeByAmount(totalAmount, currentAmount, timePerOne) {
                return (totalAmount - currentAmount) * timePerOne;
            }

            function getPercent(totalAmount, currentAmount) {
                return Math.round(100 / totalAmount * currentAmount);
            }

            return new BEM({
                block: 'imcms-content-action-row',
                elements: {
                    'action-title': buildReindexTitleMessage(),
                    'actions': buildReindexActions(),
                }
            }).buildBlockStructure('<div>');
        }

        function buildPublicDocumentCacheRow() {
            function buildPublicDocumentCacheTitleMessage() {
                return components.texts.titleText('<div>', texts.actions.deletePublicDocCache, {});
            }

            function buildPublicDocumentActions() {
                const $loading = buildLoadingAnimation();
                const $success = buildSuccessAnimation();

                const lastUpdate = new DateLabel(temporalDataApi.getDateRemoveDocumentCache, texts.lastDeleteCache);

                const $button = components.buttons.warningButton({
                    'class': 'imcms-buttons imcms-form__field',
                    text: texts.init,
                    click: () => deleteCacheRequest(temporalDataApi.deletePublicDocumentCache, lastUpdate, $loading, $success),
                });

                return buildActions($button, lastUpdate.getLabel(), $loading, $success);
            }

            return new BEM({
                block: 'imcms-content-action-row',
                elements: {
                    'action-title': buildPublicDocumentCacheTitleMessage(),
                    'actions': buildPublicDocumentActions(),
                }
            }).buildBlockStructure('<div>');
        }

        function buildStaticContentRow() {
            function buildStaticContenTitleMessage() {
                return components.texts.titleText('<div>', texts.actions.deleteStaticCache, {});
            }

            function buildInitDeleteStaticContentActions() {
                const $loading = buildLoadingAnimation();
                const $success = buildSuccessAnimation();

                const lastUpdate = new DateLabel(temporalDataApi.getDateRemoveStaticContentCache, texts.lastDeleteCache);

                const $button = components.buttons.warningButton({
                    'class': 'imcms-buttons imcms-form__field',
                    text: texts.init,
                    click: () => deleteCacheRequest(temporalDataApi.deleteStaticContentCache, lastUpdate, $loading, $success),
                });

                return buildActions($button, lastUpdate.getLabel(), $loading, $success);
            }

            return new BEM({
                block: 'imcms-content-action-row',
                elements: {
                    'action-title': buildStaticContenTitleMessage(),
                    'actions': buildInitDeleteStaticContentActions(),
                }
            }).buildBlockStructure('<div>');
        }

        function buildOtherContentRow() {
            function buildOtherContentTitleMessage() {
                return components.texts.titleText('<div>', texts.actions.deleteOtherCache, {});
            }

            function buildInitDeleteOtherContentActions() {
                const $loading = buildLoadingAnimation();
                const $success = buildSuccessAnimation();

                const lastUpdate = new DateLabel(temporalDataApi.getDateRemoveOtherContentCache, texts.lastDeleteCache);

                const $button = components.buttons.warningButton({
                    'class': 'imcms-buttons imcms-form__field',
                    text: texts.init,
                    click: () => deleteCacheRequest(temporalDataApi.deleteOtherContentCache, lastUpdate, $loading, $success),
                });

                return buildActions($button, lastUpdate.getLabel(), $loading, $success);
            }

            return new BEM({
                block: 'imcms-content-action-row',
                elements: {
                    'action-title': buildOtherContentTitleMessage(),
                    'actions': buildInitDeleteOtherContentActions(),
                }
            }).buildBlockStructure('<div>');
        }

        function buildReCacheRow() {
            function buildReCacheTitleMessage() {
                return components.texts.titleText('<div>', texts.actions.buildCacheDocument, {});
            }

            function init($button, date) {
                temporalDataApi.getAmountOfCachedDocuments().done(currentAmount => {
                    if (currentAmount !== -1) {
                        $button
                            .attr('disabled', '')
                            .text(texts.caching)
                            .addClass(DISABLED_BUTTON_CLASS_NAME);

                        const interval = setInterval(
                            () => disableButtonWhileCaching($button, date, interval),
                            LOADING_INTERVAL
                        );
                    }
                });
            }

            function disableButtonWhileCaching($button, date, interval) {
                temporalDataApi.getAmountOfCachedDocuments().done(currentAmount => {
                    if (currentAmount === -1) {
                        clearInterval(interval);
                        date.updateDate();
                        $button
                            .removeAttr('disabled')
                            .removeClass(DISABLED_BUTTON_CLASS_NAME)
                            .text(texts.init);
                    }
                });
            }

            function buildReCacheActions() {
                const $loading = buildLoadingAnimation();
                const $success = buildSuccessAnimation();

                const lastUpdate = new DateLabel(temporalDataApi.getDateReCacheDocuments, texts.lastBuildCache);
                const timeLeft = new TimeLabel(texts.timeLeft);
                timeLeft.getLabel().hide();

                const $button = components.buttons.warningButton({
                    'class': 'imcms-buttons imcms-form__field',
                    text: texts.initCaching,
                    click: () => buildCacheRequest($button, $loading, $success, lastUpdate, timeLeft),
                });

                init($button, lastUpdate);

                return new BEM({
                    block: 'actions',
                    elements: {
                        'button': $button,
                        'date': lastUpdate.getLabel(),
                        'loading': $loading,
                        'success': $success,
                        'time': timeLeft.getLabel(),
                    },
                }).buildBlockStructure('<div>');
            }

            function buildCacheRequest($button, $loading, $success, date, time) {
                $button
                    .attr('disabled', '')
                    .text(texts.caching)
                    .addClass(DISABLED_BUTTON_CLASS_NAME);
                $success.hide();

                temporalDataApi.getAmountOfCachedDocuments().done(currentAmount => {
                    if (currentAmount === -1) {
                        $loading.text('0%');
                        $loading.show();
                        temporalDataApi.getTotalForCachingDocIdsAndAlias().done(totalAmount => {
                            time.setMillis(calculateTimeByAmount(totalAmount, 0, TIME_PER_ONE_RECACHE));
                            time.getLabel().show();

                            temporalDataApi.addDocumentsInCache().done(); //setInterval 2 sec?

                            const interval = setInterval(
                                () => updateLoading($button, $loading, $success, interval, totalAmount, date, time),
                                LOADING_INTERVAL
                            );
                        });

                    } else {
                        const interval = setInterval(
                            () => disableButtonWhileCaching($button, date, interval),
                            LOADING_INTERVAL
                        );
                    }
                });
            }

            function updateLoading($button, $loading, $success, interval, totalAmount, date, time) {
                temporalDataApi.getAmountOfCachedDocuments().done(currentAmount => {

                    if (currentAmount === -1) {
                        clearInterval(interval);
                        date.updateDate();
                        $button
                            .removeAttr('disabled')
                            .removeClass(DISABLED_BUTTON_CLASS_NAME)
                            .text(texts.initCaching);
                        $loading.hide();
                        $success.show();
                        time.getLabel().hide();

                        return;
                    }

                    time.setMillis(calculateTimeByAmount(totalAmount, currentAmount, TIME_PER_ONE_RECACHE));
                    let percent = getPercent(totalAmount, currentAmount);
                    $loading.text(percent + '%');
                });
            }

            function calculateTimeByAmount(totalAmount, currentAmount, timePerOne) {
                return (totalAmount - currentAmount) * timePerOne;
            }

            function getPercent(totalAmount, currentAmount) {
                return Math.round(100 / totalAmount * currentAmount);
            }

            return new BEM({
                block: 'imcms-content-action-row',
                elements: {
                    'action-title': buildReCacheTitleMessage(),
                    'actions': buildReCacheActions(),
                }
            }).buildBlockStructure('<div>');
        }

        return new SuperAdminTab(texts.name, [
            buildReindexRow(),
            buildPublicDocumentCacheRow(),
            buildStaticContentRow(),
            buildOtherContentRow(),
            buildReCacheRow()
        ]);
    }
);
<|endoftext|>


<commit_before>/* Facebook like page*/

(function(d, s, id) {
    var js, fjs = d.getElementsByTagName(s)[0];
    if (d.getElementById(id)) return;
    js = d.createElement(s); js.id = id;
    js.src = "//connect.facebook.net/fr_FR/sdk.js#xfbml=1&version=v2.4&appId=1534300023482847";
    fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));

/* Google analytics */

(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
        (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
    m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-67287154-1', 'auto');
ga('send', 'pageview');

/* iframe loading function*/
function IFrameScroll(link){
    window.galleryIframe.location=link;
    window.location.hash='galleryIframe';
}

/* Navigation bar */

document.getElementById("nav").innerHTML =
    '
'+
    ''+
    '
'+
    '<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">'+
    'Toggle navigation'+
    ''+
    ''+
    ''+
    '</button>'+
    ''+
    'Feed Southern Africa'+
    '
'+
    ''+
    '
'+
    '
'+
    '
HOME
'+
    '
ABOUT
'+
    '
PROGRAMS
'+
    '
JOIN
'+
    '
RATES
'+
    '
CONTACT
'+
    '
'+
    'Gallery '+
    '
'+
    '
Program-1
'+
    '
Program-2
'+
    '
'+
    '
'+
    '
'+
    '
'+
    '
'
;

/* Footer */

document.getElementById("footer").innerHTML = '
'+
    '
'+
    '
'+
    '
' +
    '
' +
    '
' +
    'Feed Southern Africa' +
    '' +
    '
' +
    '
' +
    '
' +
    '
'+
    '
'+
    '
 ' +
    '©  ' + new Date().getFullYear() + ' Feed Southern Africa. All rights reserved.' +
    '
'+
    '
'+
    '
'+
    '
';

<commit_msg>iframe loading func update<commit_after>/* Facebook like page*/

(function(d, s, id) {
    var js, fjs = d.getElementsByTagName(s)[0];
    if (d.getElementById(id)) return;
    js = d.createElement(s); js.id = id;
    js.src = "//connect.facebook.net/fr_FR/sdk.js#xfbml=1&version=v2.4&appId=1534300023482847";
    fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));

/* Google analytics */

(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
        (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
    m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-67287154-1', 'auto');
ga('send', 'pageview');

/* iframe loading function*/
function IFrameScroll(link){
    window.galleryIframe.location=link;
    window.location.hash='galleryIframe';
}

/* Navigation bar */

document.getElementById("nav").innerHTML =
    '
'+
    ''+
    '
'+
    '<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">'+
    'Toggle navigation'+
    ''+
    ''+
    ''+
    '</button>'+
    ''+
    'Feed Southern Africa'+
    '
'+
    ''+
    '
'+
    '
'+
    '
HOME
'+
    '
ABOUT
'+
    '
PROGRAMS
'+
    '
JOIN
'+
    '
RATES
'+
    '
CONTACT
'+
    '
'+
    'Gallery '+
    '
'+
    '
Program-1
'+
    '
Program-2
'+
    '
'+
    '
'+
    '
'+
    '
'+
    '
'
;

/* Footer */

document.getElementById("footer").innerHTML = '
'+
    '
'+
    '
'+
    '
' +
    '
' +
    '
' +
    'Feed Southern Africa' +
    '' +
    '
' +
    '
' +
    '
' +
    '
'+
    '
'+
    '
 ' +
    '©  ' + new Date().getFullYear() + ' Feed Southern Africa. All rights reserved.' +
    '
'+
    '
'+
    '
'+
    '
';

<|endoftext|>


<commit_before>jQuery(document).ready(function($) {

    $('.ui.sidebar').sidebar({

    }).sidebar('attach events', '.xwc-menu');

    $('.popup').popup({
        setFluidWidth: false,
        position: 'bottom right',
        inline: true
    });

    var regexHtml = /.*\.html/i;
    var regexMd = /.*\.md/i;

    var converter = new showdown.Converter();

    $.getJSON("data/articles.json", function(data) {
        $.each(data.articles, function(i, item) {
            if (!item.hasOwnProperty("hidden") || !item.hidden) {
                $('.ui.menu.sidebar').append($('').attr({
                    "data-href": item.path,
                    "data-category": item.category,
                    "data-date": item.date,
                    "data-time": item.time
                }).text(item.name));
            }
        });

        $('.ui.menu.sidebar a.item').click(function(event) {

            $(this).parent().find('a.item').removeClass('active');
            $(this).addClass('active');

            $('.xwc-title').text($(this).text());
            $('.xwc-datetime').text($(this).attr('data-date') + " " + $(this).attr('data-time'));
            $('.xwc-category').text($(this).attr('data-category'));
            var url = $(this).attr('data-href');

            $('.xwc-content').empty();

            if (regexHtml.test(url)) {
                $.get(url, function(data) {
                    $('.xwc-content').html(data);
                });
            } else if (regexMd.test(url)) {
                $.get(url, function(data) {
                    $('
').html(converter.makeHtml(data)).appendTo('.xwc-content');
                });
            }

            $('pre code').each(function(i, block) {
                hljs.highlightBlock(block);
            });
        });

    });
});
<commit_msg>highlightBlock after load content from server<commit_after>jQuery(document).ready(function($) {

    $('.ui.sidebar').sidebar({

    }).sidebar('attach events', '.xwc-menu');

    $('.popup').popup({
        setFluidWidth: false,
        position: 'bottom right',
        inline: true
    });

    var regexHtml = /.*\.html/i;
    var regexMd = /.*\.md/i;

    var converter = new showdown.Converter();

    $.getJSON("data/articles.json", function(data) {
        $.each(data.articles, function(i, item) {
            if (!item.hasOwnProperty("hidden") || !item.hidden) {
                $('.ui.menu.sidebar').append($('').attr({
                    "data-href": item.path,
                    "data-category": item.category,
                    "data-date": item.date,
                    "data-time": item.time
                }).text(item.name));
            }
        });

        $('.ui.menu.sidebar a.item').click(function(event) {

            $(this).parent().find('a.item').removeClass('active');
            $(this).addClass('active');

            $('.xwc-title').text($(this).text());
            $('.xwc-datetime').text($(this).attr('data-date') + " " + $(this).attr('data-time'));
            $('.xwc-category').text($(this).attr('data-category'));
            var url = $(this).attr('data-href');

            $('.xwc-content').empty();

            if (regexHtml.test(url)) {
                $.get(url, function(data) {
                    $('.xwc-content').html(data);
                    // highlight code block
                    $('pre code').each(function(i, block) {
                        hljs.highlightBlock(block);
                    });
                });
            } else if (regexMd.test(url)) {
                $.get(url, function(data) {
                    $('
').html(converter.makeHtml(data)).appendTo('.xwc-content');
                    // highlight code block
                    $('pre code').each(function(i, block) {
                        hljs.highlightBlock(block);
                    });
                });
            }

        });

    });
});
<|endoftext|>


<commit_before>Ext4.define('Kwf.Ext4.Menu', {
    extend: 'Ext.toolbar.Toolbar',
    uses: [
        'Ext.toolbar.Fill',
        'Ext.toolbar.Spacer'
    ],

    controllerUrl: '/kwf/user/menu',
    changeUserTpl: ['<tpl for=".">',
                        '<div class="x4-combo-list-item changeuser-list-item<tpl if="locked != 0"> changeuser-locked</tpl>">',
                            '
{lastname} {firstname}
',
                            '{email} ({role})',
                        '
',
                      '</tpl>'],
    initComponent : function()
    {
        this.addEvents(
            'menuevent'
        );
        this.callParent(arguments);

    },
    afterRender: function() {
        this.callParent(arguments);
        this.reload();
    },
    reload: function()
    {
        Ext4.Ajax.request({
            url: this.controllerUrl+'/json-data',
            method: 'GET',
            params: this.params,
            success: this.loadMenu,
            scope: this
        });
    },
    _processMenus: function(menus)
    {
        var menuItems = [];
        for (var i=0; i<menus.length; i++) {
            var m = menus[i];
            var subMenu = m.menuConfig;
            if (m.type == 'dropdown') {
                var childMenuItems = this._processMenus(m.children);
                var menu = new Ext4.menu.Menu({
                    items: childMenuItems
                });
                subMenu.menu = menu;
            } else if (m.type == 'url') {
                subMenu.href = m.url;
                subMenu.handler = function(o, e) {
                    e.stopEvent();
                    var cb = function() {
                        if (top != window) {
                            top.location.href = o.href;
                        } else {
                            location.href = o.href;
                        }
                    };
                    cb();
//                     if (!Kwf.currentViewport || !Kwf.currentViewport.mabySubmit) {
//                         cb();
//                     } else {
//                         if (Kwf.currentViewport.mabySubmit({
//                             callback: cb,
//                             scope: this
//                         })) {
//                             cb();
//                         }
//                     }
                };
                subMenu.scope = this;
            } else if (m.type == 'separator') {
                subMenu = '-';
            } else {
                throw "unknown menu-type: "+m.type;
            }

            menuItems.push(subMenu);
        }
        return menuItems;
    },
    loadMenu: function(response, options)
    {
        var result = Ext4.JSON.decode(response.responseText);

        this.items.each(function(i) {
            i.destroy();
        });
        var menuItems = this._processMenus(result.menus);
        Ext4.each(menuItems, function(menuItem) {
            if (menuItem.icon && menuItem.text) {
                menuItem.cls = 'x-btn-text-icon';
            } else if (menuItem.icon) {
                menuItem.cls = 'x-btn-icon';
            }
            this.add(menuItem);
        }, this);
        this.add(new Ext4.toolbar.Fill());
        this.loadingAnim = this.add({
            xtype: 'component',
            cls: Ext4.baseCSSPrefix + 'mask-msg-text ext4-maincontroller-loading',
            height: 16,
            width: 16,
            renderTpl: '

',
            style: 'display:none'
        });

        /*
        TODO: port rest of this file to ext4

        this.showUserMenu = new Ext4.Button({
            id: 'userMenu',
            tooltip: trlKwf('Show User Menu'),
            cls: 'x-btn-icon',
            icon: '/assets/silkicons/bullet_arrow_down.png',
            handler: function() {
                if (!this.userToolbar.isVisible()) {
                    this.showUserMenu.btnEl.setStyle('background-image', 'url(/assets/silkicons/bullet_arrow_up.png)');
                    this.userToolbar.show();
                } else {
                    this.showUserMenu.btnEl.setStyle('background-image', 'url(/assets/silkicons/bullet_arrow_down.png)');
                    this.userToolbar.hide();
                }
            },
            scope: this
        });
        this.add(this.showUserMenu);

        if (result.changeUser) {
            var changeUser = new Kwf.Form.ComboBox({
                store: {
                    url: '/kwf/user/changeUser/json-data'
                },
                mode: 'remote',
                editable: true,
                forceSelection: true,
                pageSize: 10,
                triggerAction: 'all',
                width: 120,
                maxHeight: 350,
                listWidth: 280,
                tpl: new Ext4.XTemplate(
                        this.changeUserTpl
                      )
            });
            changeUser.on('render', function(combo) {
                combo.setRawValue(result.fullname);
            }, this, {delay: 10});
            changeUser.on('select', function(combo, record, index) {
                Ext4.Ajax.request({
                    url: '/kwf/user/changeUser/json-change-user',
                    params: { userId: record.id },
                    success: function() {
                        location.href = '/kwf/welcome';
                    },
                    scope: this
                });
            }, this);
            this.add(changeUser);
            this.add(' ');
            this.add(' ');
            this.add('-');
        }

        this.userToolbar = new Ext4.Toolbar({
            renderTo: this.el,
            style: 'position:absolute;right:0'
        });

        if (result.fullname && result.userSelfControllerUrl) {
            this.userToolbar.add({
                id: 'currentUser',
                text: result.fullname,
                cls: 'x-btn-text-icon',
                icon: '/assets/silkicons/user.png',
                disabled: !result.userId,
                handler: function() {
                    var dlg = new Kwf.Auto.Form.Window({
                        formConfig: {
                            controllerUrl: result.userSelfControllerUrl
                        }
                    });
                    dlg.on('datachange', function() {
                        this.reload();
                    }, this);
                    dlg.showEdit(result.userId);
                },
                scope: this
            });
        }
        if (result.showLogout) {
            this.userToolbar.add({
                cls: 'x-btn-icon',
                tooltip: trlKwf('Logout'),
                icon: '/assets/silkicons/door_out.png',
                handler: function() {
                    Ext4.Ajax.request({
                        url : '/kwf/user/login/json-logout-user',
                        success : function(form, action) {
                            //nicht reload, weil user nach erneutem login vielleicht
                            //die aktuelle seite gar nicht mehr sehen darf
                            location.href = '/kwf/welcome';
                        },
                        scope: this
                    });
                },
                scope: this
            });
        }
        this.userToolbar.add({
            cls: 'x-btn-icon',
            icon: '/assets/kwf/images/information.png',
            tooltip: trlKwf('Information'),
            handler: function() {
                var about = new Kwf.About();
                about.show();
            },
            scope: this
        });

        this.userToolbar.hide();

        if (result.frontendUrls.length == 1) {
            //single frontend urls
            this.add({
                tooltip: trlKwf('Open frontend in a new window'),
                cls: 'x-btn-icon',
                icon: '/assets/silkicons/world.png',
                handler: function() {
                    window.open(result.frontendUrls[0].href);
                },
                scope: this
            });
        } else if (result.frontendUrls.length > 1) {
            //multiple frontend urls
            var frontendItems = [];
            result.frontendUrls.each(function(url) {
                frontendItems.push({
                    text: url.text,
                    cls: 'x-btn-text-icon',
                    icon: '/assets/silkicons/world.png',
                    tooltip: trlKwf('Open frontend in a new window'),
                    handler: function(options) {
                        window.open(options.url.href);
                    },
                    url: url,
                    scope: this
                });
            }, this);
            this.add({
                tooltip: trlKwf('Open frontend in a new window'),
                cls: 'x-btn-icon',
                icon: '/assets/silkicons/world.png',
                menu: new Ext4.menu.Menu({
                    items: frontendItems
                })
            });
        }
        */
    }
});
<commit_msg>Ext4 Menu: add logout button<commit_after>Ext4.define('Kwf.Ext4.Menu', {
    extend: 'Ext.toolbar.Toolbar',
    uses: [
        'Ext.toolbar.Fill',
        'Ext.toolbar.Spacer'
    ],

    controllerUrl: '/kwf/user/menu',
    changeUserTpl: ['<tpl for=".">',
                        '<div class="x4-combo-list-item changeuser-list-item<tpl if="locked != 0"> changeuser-locked</tpl>">',
                            '
{lastname} {firstname}
',
                            '{email} ({role})',
                        '
',
                      '</tpl>'],
    initComponent : function()
    {
        this.addEvents(
            'menuevent'
        );
        this.callParent(arguments);

    },
    afterRender: function() {
        this.callParent(arguments);
        this.reload();
    },
    reload: function()
    {
        Ext4.Ajax.request({
            url: this.controllerUrl+'/json-data',
            method: 'GET',
            params: this.params,
            success: this.loadMenu,
            scope: this
        });
    },
    _processMenus: function(menus)
    {
        var menuItems = [];
        for (var i=0; i<menus.length; i++) {
            var m = menus[i];
            var subMenu = m.menuConfig;
            if (m.type == 'dropdown') {
                var childMenuItems = this._processMenus(m.children);
                var menu = new Ext4.menu.Menu({
                    items: childMenuItems
                });
                subMenu.menu = menu;
            } else if (m.type == 'url') {
                subMenu.href = m.url;
                subMenu.handler = function(o, e) {
                    e.stopEvent();
                    var cb = function() {
                        if (top != window) {
                            top.location.href = o.href;
                        } else {
                            location.href = o.href;
                        }
                    };
                    cb();
//                     if (!Kwf.currentViewport || !Kwf.currentViewport.mabySubmit) {
//                         cb();
//                     } else {
//                         if (Kwf.currentViewport.mabySubmit({
//                             callback: cb,
//                             scope: this
//                         })) {
//                             cb();
//                         }
//                     }
                };
                subMenu.scope = this;
            } else if (m.type == 'separator') {
                subMenu = '-';
            } else {
                throw "unknown menu-type: "+m.type;
            }

            menuItems.push(subMenu);
        }
        return menuItems;
    },
    loadMenu: function(response, options)
    {
        var result = Ext4.JSON.decode(response.responseText);

        this.items.each(function(i) {
            i.destroy();
        });
        var menuItems = this._processMenus(result.menus);
        Ext4.each(menuItems, function(menuItem) {
            if (menuItem.icon && menuItem.text) {
                menuItem.cls = 'x-btn-text-icon';
            } else if (menuItem.icon) {
                menuItem.cls = 'x-btn-icon';
            }
            this.add(menuItem);
        }, this);
        this.add(new Ext4.toolbar.Fill());
        this.loadingAnim = this.add({
            xtype: 'component',
            cls: Ext4.baseCSSPrefix + 'mask-msg-text ext4-maincontroller-loading',
            height: 16,
            width: 16,
            renderTpl: '

',
            style: 'display:none'
        });

        /*
        TODO: port rest of this file to ext4

        this.showUserMenu = new Ext4.Button({
            id: 'userMenu',
            tooltip: trlKwf('Show User Menu'),
            cls: 'x-btn-icon',
            icon: '/assets/silkicons/bullet_arrow_down.png',
            handler: function() {
                if (!this.userToolbar.isVisible()) {
                    this.showUserMenu.btnEl.setStyle('background-image', 'url(/assets/silkicons/bullet_arrow_up.png)');
                    this.userToolbar.show();
                } else {
                    this.showUserMenu.btnEl.setStyle('background-image', 'url(/assets/silkicons/bullet_arrow_down.png)');
                    this.userToolbar.hide();
                }
            },
            scope: this
        });
        this.add(this.showUserMenu);

        if (result.changeUser) {
            var changeUser = new Kwf.Form.ComboBox({
                store: {
                    url: '/kwf/user/changeUser/json-data'
                },
                mode: 'remote',
                editable: true,
                forceSelection: true,
                pageSize: 10,
                triggerAction: 'all',
                width: 120,
                maxHeight: 350,
                listWidth: 280,
                tpl: new Ext4.XTemplate(
                        this.changeUserTpl
                      )
            });
            changeUser.on('render', function(combo) {
                combo.setRawValue(result.fullname);
            }, this, {delay: 10});
            changeUser.on('select', function(combo, record, index) {
                Ext4.Ajax.request({
                    url: '/kwf/user/changeUser/json-change-user',
                    params: { userId: record.id },
                    success: function() {
                        location.href = '/kwf/welcome';
                    },
                    scope: this
                });
            }, this);
            this.add(changeUser);
            this.add(' ');
            this.add(' ');
            this.add('-');
        }

        this.userToolbar = new Ext4.Toolbar({
            renderTo: this.el,
            style: 'position:absolute;right:0'
        });

        if (result.fullname && result.userSelfControllerUrl) {
            this.userToolbar.add({
                id: 'currentUser',
                text: result.fullname,
                cls: 'x-btn-text-icon',
                icon: '/assets/silkicons/user.png',
                disabled: !result.userId,
                handler: function() {
                    var dlg = new Kwf.Auto.Form.Window({
                        formConfig: {
                            controllerUrl: result.userSelfControllerUrl
                        }
                    });
                    dlg.on('datachange', function() {
                        this.reload();
                    }, this);
                    dlg.showEdit(result.userId);
                },
                scope: this
            });
        }
        */
        if (result.showLogout) {
            this.add({
                cls: 'x-btn-icon',
                tooltip: trlKwf('Logout'),
                icon: '/assets/silkicons/door_out.png',
                handler: function() {
                    Ext4.Ajax.request({
                        url : '/kwf/user/login/json-logout-user',
                        success : function(form, action) {
                            //nicht reload, weil user nach erneutem login vielleicht
                            //die aktuelle seite gar nicht mehr sehen darf
                            location.href = '/kwf/welcome';
                        },
                        scope: this
                    });
                },
                scope: this
            });
        }
        /*
        this.userToolbar.add({
            cls: 'x-btn-icon',
            icon: '/assets/kwf/images/information.png',
            tooltip: trlKwf('Information'),
            handler: function() {
                var about = new Kwf.About();
                about.show();
            },
            scope: this
        });

        this.userToolbar.hide();

        if (result.frontendUrls.length == 1) {
            //single frontend urls
            this.add({
                tooltip: trlKwf('Open frontend in a new window'),
                cls: 'x-btn-icon',
                icon: '/assets/silkicons/world.png',
                handler: function() {
                    window.open(result.frontendUrls[0].href);
                },
                scope: this
            });
        } else if (result.frontendUrls.length > 1) {
            //multiple frontend urls
            var frontendItems = [];
            result.frontendUrls.each(function(url) {
                frontendItems.push({
                    text: url.text,
                    cls: 'x-btn-text-icon',
                    icon: '/assets/silkicons/world.png',
                    tooltip: trlKwf('Open frontend in a new window'),
                    handler: function(options) {
                        window.open(options.url.href);
                    },
                    url: url,
                    scope: this
                });
            }, this);
            this.add({
                tooltip: trlKwf('Open frontend in a new window'),
                cls: 'x-btn-icon',
                icon: '/assets/silkicons/world.png',
                menu: new Ext4.menu.Menu({
                    items: frontendItems
                })
            });
        }
        */
    }
});
<|endoftext|>


<commit_before>//Global variables
var selected_team = null
var selected_individual = null
var settings_key = null

var loader = ''
var loading_message = '
Loading...
'

function getUrlVars()
{
    var vars = [], hash;
    var hashes = document.referrer.slice(document.referrer.indexOf('?') + 1).split('&');
    for(var i = 0; i < hashes.length; i++)
    {
        hash = hashes[i].split('=');
        vars.push(hash[0]);
        vars[hash[0]] = hash[1];
    }
    return vars;
}

function rpcGet(data, callback){
    var url = '/rpc?' + $.param(data)
    $.getJSON(url, function(data){
        callback(data)
    })
}

function loadTeams(){
    $("#designate_message").fadeIn()
    $("#designate").css("height", "auto")
    $("#designate_label").html("Select one:")
    $("#designate").html(loading_message)

    selected_team = null
    selected_individual = null

    var params = {action: "pub_allTeams", arg0:JSON.stringify(settings_key)}
    rpcGet(params, function(data){
        $("#designate").html("")

        $.each(data, function(entry_number, data) {
            var name_json = data[0]
            var key_json = data[1]

            var div = '<input type="button" class="button black team" style="margin-right:10px" data-id="key" value="name">'
            $("#designate").append(div.replace("name", name_json).replace("key", key_json))
        });
    })
}

function loadIndividuals(team_key){
    $("#designate_label").html("Select one:")
    $("#designate").css("height", "300px")
    $("#designate").css("overflow", "auto")
    $("#designate").html(loading_message)

    selected_individual = null

    var params = {action: "pub_teamInfo", arg0: JSON.stringify(team_key)}
    rpcGet(params, function(data){

        $("#designate").html("")

        var back_button = '
<-- Back' + loader
        $("#designate").append(back_button)

        var ul = '

'
        $("#designate").append(ul)

        var odd = true
        $.each(data, function(entry_number, data) {
            var name_json = data[0]
            var pic_json = data[1]
            var key_json = data[2]

            //To fix the weird spacing issues, use a special 'odd' style
            if (odd == true){
                var li = '

'
                odd = false
            }
            else{
                var li = '

'
                odd = true
            }
            var pic = ''
            var name = '
name
'
            var readmore = '<button class="read_more button small">Designate</button>'

            $("#members_list").append(li.replace("key", key_json))
            $("[data-id=" + key_json + "]").append(pic.replace("image_url", pic_json))
            $("[data-id=" + key_json + "]").append(name.replace("name", name_json))
            $("[data-id=" + key_json + "]").append(readmore)
        });
    })
}

function showInfo(team_key, individual_key){
    $("#loading_gif").show()
    $("#designate_label").html("Your donation will be designated to:")
    var params = {action: "pub_individualInfo", arg0: JSON.stringify(team_key), arg1: JSON.stringify(individual_key)}

    rpcGet(params, function(data){
        if (data == null){
            $("#designate_label").html("Designate donation?")
            $("#loading_gif").hide()
        }
        else{
            var photo_url = data[0]
            var name = data[1]
            var description = data[2]
            var percentage = data[3]
            var message = data[4]

            $("#info_container img").attr("src", photo_url)
            $("#info_name").text(name)
            $("#info_description").text(description)

            $("#info_progressbar div").css("width", percentage + "%")
            $("#info_message").text(message)

            $("#designate").hide()
            $("#info_container").fadeIn()

            $("#loading_gif").hide()
        }

    })
}

function hideInfo(){
    $("#info_container").hide()
    $("#designate").fadeIn()
}

function submitForm(){
    var price_object = $(".radio_amount:checked")

    if ($("#custom").is(":checked") == true) {
        //console.log("Custom is checked.")
        var new_val = $("#custom_donation").val()

        //Formatting new value for sending to PayPal
        new_val = new_val.replace("$", "")
        new_val = new_val.replace(",", "")
        new_val = parseFloat(new_val)
        new_val = new_val.toFixed(2)
        new_val = new_val.toString()

        $("#custom").val(new_val)
        price_object = $("#custom")
    }

    //If the donor has chosen to cover the donation costs
    if ($("#cover_trans").attr("checked") == "checked") {
        //console.log("Covering transaction")
        var current_price = price_object.val()
        current_price = parseFloat(current_price)
        var new_price = current_price

        var addition = (.022 * new_price)
        new_price += addition

        do{
            addition = (.022 * addition)
            new_price += addition
        }
        while (addition > 0)

        new_price += .31

        new_price = new_price.toFixed(2)
        new_price = new_price.toString()

        price_object.val(new_price)
    }

    //Embed individual designation info as well as
    //other specials notes as JSON into the purpose field

    var other_notes = $("#other_notes").val()
    if (other_notes == ""){
        other_notes = null
    }

    var cover_trans = $("#cover_trans").is(":checked")
    var email_subscr = $("#email_subscr").is(":checked")

    var to_send = [selected_team, selected_individual, other_notes, cover_trans, email_subscr]
    var encoded = $.toJSON(to_send)
    $("input[name=custom]").val(encoded)

    parent.donate_form.submit();
}

$(document).ready(function() {

    settings_key = $("#settings_key").val()

    //Function to check if an element exists
    jQuery.fn.exists = function() {
        return jQuery(this).length > 0;
    }

    $("#designate #start_designate").click(function(){
        loadTeams()
    })

    $("#designate").delegate(".team", "click", function(){
        selected_team = $(this).attr("data-id")
        loadIndividuals(selected_team)
    })

    $("#members_list .read_more").live("click", function(event){
        event.preventDefault()

        selected_individual = $(this).parent().attr("data-id")
        showInfo(selected_team, selected_individual)
    })

    $("#custom_donation").click(function() {
        //console.log("Button clicked")
        $('input[name="a3"]').filter("[id='custom']").attr("checked", "checked");
        $('input[name="amount"]').filter("[id='custom']").attr("checked", "checked");
    });

    //When donation duration is switched, change appropriate values
    $("input[name='donation_duration']").change(function() {
        var checked_val = $("input[name='donation_duration']:checked").val()
        if (checked_val == "monthly") {
            //Change to monthly
            $("#duration").val("M")
            $("#donation_type").val("_xclick-subscriptions")
            $(".money_select").attr("name", "a3")
            $("#donation_name").val("Recurring Donation | Global Hope India")
        }
        else if (checked_val == "weekly") {
            //Change to weekly
            $("#duration").val("W")
            $("#donation_type").val("_xclick-subscriptions")
            $(".money_select").attr("name", "a3")
            $("#donation_name").val("Recurring Donation | Global Hope India")
        }
        else if (checked_val == "onetime") {
            //Change to one-time
            $("#donation_type").val("_donations")
            $(".money_select").attr("name", "amount")
            $("#donation_name").val("One-Time Donation | Global Hope India")
        }
    });

    $("#donate_form").submit(function() {
        submitForm()
    })

    $("#back_button").live("click", function(){
        loadTeams()
    })

    $("#backtolist_button").click(function(e){
        $("#designate_label").html("Select one:")
        hideInfo()
    })

    // Check if team & individual keys are embedded in URL
    var url_params = getUrlVars()
    var team_key = url_params['t']
    var individual_key = url_params['i']

    if (team_key != null && individual_key != null){
        $("#designate").css("height", "300px")
        $("#designate").css("overflow", "auto")

        selected_team = team_key
        selected_individual = individual_key

        showInfo(team_key, individual_key)

        $("#backtolist_button").hide()
    }

    //Set up AJAX
    $.ajaxSetup({
        error: function(jqXHR, exception) {
            if (jqXHR.status === 0) {
                alert("I couldn't connect to the Internet. Check your connection.")
            } else if (jqXHR.status == 404) {
                alert("Whoops! I couldn't find that page.")
            } else if (jqXHR.status == 500) {
                alert("Uh oh! The server's not playing nice right now. Try again later.")
            } else if (exception === 'parsererror') {
                alert("Uh oh! The server gave me something I don't understand. Try again later.")
            } else if (exception === 'timeout') {
                alert("undone", "Hmm... the server's not responding. Try your request again.")
            } else {
                alert("Uh oh, something happened but I don't know what it is - " + jqXHR.responseText)
            }
        }
    });
});<commit_msg>Cleared out selected indictators on back button press<commit_after>//Global variables
var selected_team = null
var selected_individual = null
var settings_key = null

var loader = ''
var loading_message = '
Loading...
'

function getUrlVars()
{
    var vars = [], hash;
    var hashes = document.referrer.slice(document.referrer.indexOf('?') + 1).split('&');
    for(var i = 0; i < hashes.length; i++)
    {
        hash = hashes[i].split('=');
        vars.push(hash[0]);
        vars[hash[0]] = hash[1];
    }
    return vars;
}

function rpcGet(data, callback){
    var url = '/rpc?' + $.param(data)
    $.getJSON(url, function(data){
        callback(data)
    })
}

function loadTeams(){
    $("#designate_message").fadeIn()
    $("#designate").css("height", "auto")
    $("#designate_label").html("Select one:")
    $("#designate").html(loading_message)

    selected_team = null
    selected_individual = null

    var params = {action: "pub_allTeams", arg0:JSON.stringify(settings_key)}
    rpcGet(params, function(data){
        $("#designate").html("")

        $.each(data, function(entry_number, data) {
            var name_json = data[0]
            var key_json = data[1]

            var div = '<input type="button" class="button black team" style="margin-right:10px" data-id="key" value="name">'
            $("#designate").append(div.replace("name", name_json).replace("key", key_json))
        });
    })
}

function loadIndividuals(team_key){
    $("#designate_label").html("Select one:")
    $("#designate").css("height", "300px")
    $("#designate").css("overflow", "auto")
    $("#designate").html(loading_message)

    selected_individual = null

    var params = {action: "pub_teamInfo", arg0: JSON.stringify(team_key)}
    rpcGet(params, function(data){

        $("#designate").html("")

        var back_button = '
<-- Back' + loader
        $("#designate").append(back_button)

        var ul = '

'
        $("#designate").append(ul)

        var odd = true
        $.each(data, function(entry_number, data) {
            var name_json = data[0]
            var pic_json = data[1]
            var key_json = data[2]

            //To fix the weird spacing issues, use a special 'odd' style
            if (odd == true){
                var li = '

'
                odd = false
            }
            else{
                var li = '

'
                odd = true
            }
            var pic = ''
            var name = '
name
'
            var readmore = '<button class="read_more button small">Designate</button>'

            $("#members_list").append(li.replace("key", key_json))
            $("[data-id=" + key_json + "]").append(pic.replace("image_url", pic_json))
            $("[data-id=" + key_json + "]").append(name.replace("name", name_json))
            $("[data-id=" + key_json + "]").append(readmore)
        });
    })
}

function showInfo(team_key, individual_key){
    $("#loading_gif").show()
    $("#designate_label").html("Your donation will be designated to:")
    var params = {action: "pub_individualInfo", arg0: JSON.stringify(team_key), arg1: JSON.stringify(individual_key)}

    rpcGet(params, function(data){
        if (data == null){
            $("#designate_label").html("Designate donation?")
            $("#loading_gif").hide()
        }
        else{
            var photo_url = data[0]
            var name = data[1]
            var description = data[2]
            var percentage = data[3]
            var message = data[4]

            $("#info_container img").attr("src", photo_url)
            $("#info_name").text(name)
            $("#info_description").text(description)

            $("#info_progressbar div").css("width", percentage + "%")
            $("#info_message").text(message)

            $("#designate").hide()
            $("#info_container").fadeIn()

            $("#loading_gif").hide()
        }

    })
}

function hideInfo(){
    $("#info_container").hide()
    $("#designate").fadeIn()
}

function submitForm(){
    var price_object = $(".radio_amount:checked")

    if ($("#custom").is(":checked") == true) {
        //console.log("Custom is checked.")
        var new_val = $("#custom_donation").val()

        //Formatting new value for sending to PayPal
        new_val = new_val.replace("$", "")
        new_val = new_val.replace(",", "")
        new_val = parseFloat(new_val)
        new_val = new_val.toFixed(2)
        new_val = new_val.toString()

        $("#custom").val(new_val)
        price_object = $("#custom")
    }

    //If the donor has chosen to cover the donation costs
    if ($("#cover_trans").attr("checked") == "checked") {
        //console.log("Covering transaction")
        var current_price = price_object.val()
        current_price = parseFloat(current_price)
        var new_price = current_price

        var addition = (.022 * new_price)
        new_price += addition

        do{
            addition = (.022 * addition)
            new_price += addition
        }
        while (addition > 0)

        new_price += .31

        new_price = new_price.toFixed(2)
        new_price = new_price.toString()

        price_object.val(new_price)
    }

    //Embed individual designation info as well as
    //other specials notes as JSON into the purpose field

    var other_notes = $("#other_notes").val()
    if (other_notes == ""){
        other_notes = null
    }

    var cover_trans = $("#cover_trans").is(":checked")
    var email_subscr = $("#email_subscr").is(":checked")

    var to_send = [selected_team, selected_individual, other_notes, cover_trans, email_subscr]
    var encoded = $.toJSON(to_send)
    $("input[name=custom]").val(encoded)

    parent.donate_form.submit();
}

$(document).ready(function() {

    settings_key = $("#settings_key").val()

    //Function to check if an element exists
    jQuery.fn.exists = function() {
        return jQuery(this).length > 0;
    }

    $("#designate #start_designate").click(function(){
        loadTeams()
    })

    $("#designate").delegate(".team", "click", function(){
        selected_team = $(this).attr("data-id")
        loadIndividuals(selected_team)
    })

    $("#members_list .read_more").live("click", function(event){
        event.preventDefault()

        selected_individual = $(this).parent().attr("data-id")
        showInfo(selected_team, selected_individual)
    })

    $("#custom_donation").click(function() {
        //console.log("Button clicked")
        $('input[name="a3"]').filter("[id='custom']").attr("checked", "checked");
        $('input[name="amount"]').filter("[id='custom']").attr("checked", "checked");
    });

    //When donation duration is switched, change appropriate values
    $("input[name='donation_duration']").change(function() {
        var checked_val = $("input[name='donation_duration']:checked").val()
        if (checked_val == "monthly") {
            //Change to monthly
            $("#duration").val("M")
            $("#donation_type").val("_xclick-subscriptions")
            $(".money_select").attr("name", "a3")
            $("#donation_name").val("Recurring Donation | Global Hope India")
        }
        else if (checked_val == "weekly") {
            //Change to weekly
            $("#duration").val("W")
            $("#donation_type").val("_xclick-subscriptions")
            $(".money_select").attr("name", "a3")
            $("#donation_name").val("Recurring Donation | Global Hope India")
        }
        else if (checked_val == "onetime") {
            //Change to one-time
            $("#donation_type").val("_donations")
            $(".money_select").attr("name", "amount")
            $("#donation_name").val("One-Time Donation | Global Hope India")
        }
    });

    $("#donate_form").submit(function() {
        submitForm()
    })

    $("#back_button").live("click", function(){
        selected_team = null
        loadTeams()
    })

    $("#backtolist_button").click(function(e){
        $("#designate_label").html("Select one:")
        hideInfo()
        selected_individual = null
    })

    // Check if team & individual keys are embedded in URL
    var url_params = getUrlVars()
    var team_key = url_params['t']
    var individual_key = url_params['i']

    if (team_key != null && individual_key != null){
        $("#designate").css("height", "300px")
        $("#designate").css("overflow", "auto")

        selected_team = team_key
        selected_individual = individual_key

        showInfo(team_key, individual_key)

        $("#backtolist_button").hide()
    }

    //Set up AJAX
    $.ajaxSetup({
        error: function(jqXHR, exception) {
            if (jqXHR.status === 0) {
                alert("I couldn't connect to the Internet. Check your connection.")
            } else if (jqXHR.status == 404) {
                alert("Whoops! I couldn't find that page.")
            } else if (jqXHR.status == 500) {
                alert("Uh oh! The server's not playing nice right now. Try again later.")
            } else if (exception === 'parsererror') {
                alert("Uh oh! The server gave me something I don't understand. Try again later.")
            } else if (exception === 'timeout') {
                alert("undone", "Hmm... the server's not responding. Try your request again.")
            } else {
                alert("Uh oh, something happened but I don't know what it is - " + jqXHR.responseText)
            }
        }
    });
});<|endoftext|>