<commit_before>/**
 * /assets/linker/js/story.js
 *
 * This file contains all story specified javascript functions and handlers.
 * Basically file is divided into the following sections:
 *  - Event handlers
 *  - Form handlers
 */

/**
 * Story specified global event handlers. These events are following:
 *  - storyAdd
 *  - storyEdit
 *  - storySplit
 *  - storyDelete
 */
jQuery(document).ready(function() {
    var body = jQuery("body");

    /**
     * User story add event, this opens a modal bootbox dialog with user story add form on it.
     *
     * @param   {jQuery.Event}          event       Event object
     * @param   {Number}                [projectId] Project id
     * @param   {Number}                [sprintId]  Sprint id
     * @param   {sails.helper.trigger}  [trigger]   Trigger to process after actions
     * @param   {{}}                    [formData]  Possible form data, simple key/value
     */
    body.on("storyAdd", function(event, projectId, sprintId, trigger, formData) {
        projectId = projectId || myViewModel.project().id();
        trigger = trigger || false;
        formData = formData || {};

        if (typeof sprintId === "undefined") {
            if (myViewModel.sprint().id()) {
                sprintId = myViewModel.sprint().id();
            }
        }

        jQuery.get("/Story/add", {projectId: projectId, sprintId: sprintId, formData: formData})
        .done(function(content) {
            var title = "Add new user story";
            var buttons = [
                {
                    label: "Save",
                    className: "btn-primary pull-right",
                    callback: function() {
                        var form = jQuery("#formStoryNew", modal);
                        var formItems = form.serializeJSON();

                        // Validate form and try to create new user story
                        if (validateForm(formItems, modal)) {
                            // Create new user story
                            socket.post("/Story", formItems, function(/** sails.json.story */story) {
                                if (handleSocketError(story)) {
                                    makeMessage("User story created successfully.");

                                    modal.modal("hide");

                                    handleEventTrigger(trigger);

                                    // Update client bindings
                                    myViewModel.processSocketMessage("story", "create", story.id, story);
                                }
                            });
                        }

                        return false;
                    }
                }
            ];

            // Create bootbox modal
            var modal = createBootboxDialog(title, content, buttons, trigger);

            // Make form init when dialog is opened.
            modal.on("shown.bs.modal", function() {
                initStoryForm(modal);
            });

            // Open bootbox modal
            modal.modal("show");
        })
        .fail(function(jqXhr, textStatus, error) {
            handleAjaxError(jqXhr, textStatus, error);
        });
    });

    /**
     * User story edit event, this opens a modal bootbox dialog with user story edit form on it.
     *
     * @param   {jQuery.Event}          event           Event object
     * @param   {Number}                storyId         Story id
     * @param   {sails.helper.trigger}  [trigger]       Trigger to process after actions
     * @param   {{}}                    [parameters]    Init parameters, this is passed to form init function
     */
    body.on("storyEdit", function(event, storyId, trigger, parameters) {
        trigger = trigger || false;
        parameters = parameters || {};

        jQuery.get("/Story/edit", {id: storyId})
        .done(function(content) {
            var title = "Edit user story";
            var buttons = [
                {
                    label: "Save",
                    className: "btn-primary pull-right",
                    callback: function() {
                        var form = jQuery("#formStoryEdit", modal);
                        var formItems = form.serializeJSON();

                        // Validate current form items and try to update user story data
                        if (validateForm(formItems, modal)) {
                            // Update user story
                            socket.put("/Story/" + storyId, formItems, function(/** sails.json.story */story) {
                                if (handleSocketError(story)) {
                                    makeMessage("User story updated successfully.");

                                    modal.modal("hide");

                                    handleEventTrigger(trigger);
                                }
                            });
                        }

                        return false;
                    }
                },
                {
                    label: "Split story",
                    className: "btn-warning pull-right",
                    id: "split",
                    callback: function() {
                        // Trigger story split event
                        body.trigger("storySplit", [storyId, {trigger: "storyEdit", parameters: [storyId, trigger]}]);
                    }
                },
                {
                    label: "Delete",
                    className: "btn-danger pull-right",
                    callback: function() {
                        // Trigger story delete event
                        body.trigger("storyDelete", [storyId, {trigger: "storyEdit", parameters: [storyId, trigger]}]);
                    }
                }
            ];

            // Create bootbox modal
            var modal = createBootboxDialog(title, content, buttons, trigger);

            // Make form init when dialog is opened.
            modal.on("shown.bs.modal", function() {
                initStoryForm(modal, parameters);
            });

            // Open bootbox modal
            modal.modal("show");
        })
        .fail(function(jqXhr, textStatus, error) {
            handleAjaxError(jqXhr, textStatus, error);
        });
    });

    /**
     * User story split event, this opens a modal bootbox prompt with sprint selection.
     *
     * @param   {jQuery.Event}          event       Event object
     * @param   {Number}                storyId     Story id
     * @param   {sails.helper.trigger}  [trigger]   Trigger to process after actions
     */
    body.on("storySplit", function(event, storyId, trigger) {
        trigger = trigger || false;

        var options = [];

        // Add project backlog option
        options.push({value: 0, text: "Project backlog"});

        // Iterate project sprints and add those to option lists
        jQuery.each(myViewModel.sprints(), function(key, sprint) {
            options.push({value: sprint.id(), text: sprint.formattedTitle()});
        });

        // Make prompt box
        var prompt = bootbox.prompt({
            title: "Select sprint where to add new story",
            buttons: {
                cancel: {
                    label: "Cancel",
                    className: "btn-default pull-left"
                },
                confirm: {
                    label: "Split story",
                    className: "btn-primary pull-right"
                }
            },
            inputType: "select",
            inputOptions: options,
            show: false,
            callback: function(result) {
                if (result !== null) {
                    jQuery.ajax({
                        type: "POST",
                        url: "/Story/split",
                        data: {
                            storyId: storyId,
                            sprintId: result,
                            projectId: myViewModel.project().id()
                        },
                        dataType: "json"
                    })
                    .done(function(/** sails.json.storySplit */ data) {
                        makeMessage("User story splitted successfully.");

                        prompt.modal("hide");

                        handleEventTrigger(trigger);

                        // Try to find original story from current scope
                        var story = _.find(myViewModel.stories(), function(story) {
                            return story.id() === data.storyOld.id;
                        });

                        // Client binding updates

                        // Original story in current scope, so update it
                        if (typeof story !== "undefined") {
                            myViewModel.processSocketMessage("story", "update", data.storyOld.id, data.storyOld);
                        }

                        // If new story sprint is same as current add it to current scope
                        if (data.storyNew.sprintId === myViewModel.sprint().id()) {
                            myViewModel.processSocketMessage("story", "create", data.storyNew.id, data.storyNew);
                        }
                    })
                    .fail(function(jqXhr, textStatus, error) {
                        handleAjaxError(jqXhr, textStatus, error);
                    });
                } else {
                    prompt.modal("hide");

                    handleEventTrigger(trigger);
                }

                return false;
            }
        });

        // Initialize prompt select
        prompt.on("shown.bs.modal", function() {
            initSelectPrompt(prompt);
        });

        // Open bootbox prompt modal
        prompt.modal("show");
    });

    /**
     * User story delete event, this opens a modal bootbox confirm about story delete.
     *
     * @param   {jQuery.Event}          event       Event object
     * @param   {Number}                storyId     Story id
     * @param   {sails.helper.trigger}  [trigger]   Trigger to process after actions
     */
    body.on("storyDelete", function(event, storyId, trigger) {
        trigger = trigger || false;

        // Make confirm box
        bootbox.confirm({
            title: "danger - danger - danger",
            message: "Are you sure of story delete?",
            buttons: {
                cancel: {
                    label: "Cancel",
                    className: "btn-default pull-left"
                },
                confirm: {
                    label: "Delete",
                    className: "btn-danger pull-right"
                }
            },
            callback: function(result) {
                if (result) {
                    // Delete story data
                    socket.delete("/Story/" + storyId, function(/** sails.json.story */story) {
                        if (handleSocketError(story)) {
                            makeMessage("User story deleted successfully.");

                            handleEventTrigger(trigger);
                        }
                    });
                } else {
                    handleEventTrigger(trigger);
                }
            }
        });
    });

    /**
     * Story tasks event. This will open story edit modal dialog and activates tasks tab to
     * be opened. Note that this just fires storyEdit event with specified parameters.
     *
     * @param   {jQuery.Event}          event       Event object
     * @param   {Number}                storyId     Story id
     * @param   {sails.helper.trigger}  trigger     Trigger to process after actions
     */
    body.on("storyTasks", function(event, storyId, trigger) {
        // Used parameters for form init
        var parameters = {
            activeTab: "tasks"
        };

        body.trigger("storyEdit", [storyId, trigger, parameters]);
    });
});

/**
 * Function to initialize story form.
 *
 * @param   {jQuery|$}  modal       Current modal content
 * @param   {{}}        parameters  Parameters
 */
function initStoryForm(modal, parameters) {
    parameters = parameters || {};

    if (parameters.activeTab) {
        jQuery("#" + parameters.activeTab + "Tab", modal).click();
    }

    var inputTitle = jQuery("input[name='title']", modal);

    inputTitle.focus().val(inputTitle.val());

    var slider = jQuery(".estimateSlider", modal);
    var input = slider.next("input");
    var show = jQuery(".sliderValue", modal);
    var currentValue = 0;

    // Specify fibonacci values for story sizes
    var values = [ -1, 0, 0.5, 1, 2, 3, 5, 8, 13, 20, 40, 100 ];

    jQuery.each(values, function(key, value) {
        if (value == input.val()) {
            currentValue = key;
        }
    });

    show.val(currentValue == 0 ? "???" : values[currentValue]);

    // Note that this slider only accepts fibonacci values
    slider.slider({
        min: 0,
        max: values.length - 1,
        value: currentValue,
        step: 1,
        slide: function(event, ui) {
            input.val(values[ui.value]);

            if (ui.value === 0) {
                show.val("???");
            } else {
                show.val(values[ui.value]);
            }
        }
    });
}

/**
 * Function initializes story tasks tab to use in task edit modal. Note that
 * this init can be called multiple times.
 *
 * Also note that this init is called dynamic from initTabs() function.
 *
 * @param   {jQuery|$}  modal       Current modal content
 * @param   {String}    contentId   Tab content div id
 */
function initStoryTabTasks(modal, contentId) {
    var body = jQuery("body");
    var container = modal.find(contentId);

    // Initialize action menu for stories
    initActionMenu(container, {});

    // Remove 'add new' click listeners, this prevents firing this event multiple times
    body.off("click", "[data-add-new-task='true']");

    // User wants to add new user to project
    body.on("click", "[data-add-new-task='true']", function() {
        var element = jQuery(this);
        var storyId = element.data("storyId");

        // Hide current modal
        modal.modal("hide");

        // Specify used trigger to come back to this view
        var trigger = {
            trigger: "storyEdit",
            parameters: [storyId, null, {activeTab: "tasks"}]
        };

        // Find specified story object
        var story = _.find(myViewModel.stories(), function(story) { return story.id() === storyId; });

        body.trigger("taskAdd", [story, trigger]);
    });

    // User clicks action menu link
    body.on("click", "ul.actionMenu-actions a", function() {
        var element = jQuery(this);
        var storyId = element.data("storyId");
        var taskId = element.data("taskId");
        var action = element.data("action");
        var selector = element.data("selector");

        // We have popover selector, so hide it
        if (selector) {
            jQuery(selector).popover("hide");
        }

        // Hide current modal
        modal.modal("hide");

        // Specify used trigger to come back to this view
        var trigger = {
            trigger: "storyEdit",
            parameters: [storyId, null, {activeTab: "tasks"}]
        };

        // Trigger milestone action event
        body.trigger(action, [taskId, trigger]);
    });
}
<commit_msg>Fixed duplicate story bug.<commit_after>/**
 * /assets/linker/js/story.js
 *
 * This file contains all story specified javascript functions and handlers.
 * Basically file is divided into the following sections:
 *  - Event handlers
 *  - Form handlers
 */

/**
 * Story specified global event handlers. These events are following:
 *  - storyAdd
 *  - storyEdit
 *  - storySplit
 *  - storyDelete
 */
jQuery(document).ready(function() {
    var body = jQuery("body");

    /**
     * User story add event, this opens a modal bootbox dialog with user story add form on it.
     *
     * @param   {jQuery.Event}          event       Event object
     * @param   {Number}                [projectId] Project id
     * @param   {Number}                [sprintId]  Sprint id
     * @param   {sails.helper.trigger}  [trigger]   Trigger to process after actions
     * @param   {{}}                    [formData]  Possible form data, simple key/value
     */
    body.on("storyAdd", function(event, projectId, sprintId, trigger, formData) {
        projectId = projectId || myViewModel.project().id();
        trigger = trigger || false;
        formData = formData || {};

        if (typeof sprintId === "undefined") {
            if (myViewModel.sprint().id()) {
                sprintId = myViewModel.sprint().id();
            }
        }

        jQuery.get("/Story/add", {projectId: projectId, sprintId: sprintId, formData: formData})
        .done(function(content) {
            var title = "Add new user story";
            var buttons = [
                {
                    label: "Save",
                    className: "btn-primary pull-right",
                    callback: function() {
                        var form = jQuery("#formStoryNew", modal);
                        var formItems = form.serializeJSON();

                        // Validate form and try to create new user story
                        if (validateForm(formItems, modal)) {
                            // Create new user story
                            socket.post("/Story", formItems, function(/** sails.json.story */story) {
                                if (handleSocketError(story)) {
                                    makeMessage("User story created successfully.");

                                    modal.modal("hide");

                                    handleEventTrigger(trigger);
                                }
                            });
                        }

                        return false;
                    }
                }
            ];

            // Create bootbox modal
            var modal = createBootboxDialog(title, content, buttons, trigger);

            // Make form init when dialog is opened.
            modal.on("shown.bs.modal", function() {
                initStoryForm(modal);
            });

            // Open bootbox modal
            modal.modal("show");
        })
        .fail(function(jqXhr, textStatus, error) {
            handleAjaxError(jqXhr, textStatus, error);
        });
    });

    /**
     * User story edit event, this opens a modal bootbox dialog with user story edit form on it.
     *
     * @param   {jQuery.Event}          event           Event object
     * @param   {Number}                storyId         Story id
     * @param   {sails.helper.trigger}  [trigger]       Trigger to process after actions
     * @param   {{}}                    [parameters]    Init parameters, this is passed to form init function
     */
    body.on("storyEdit", function(event, storyId, trigger, parameters) {
        trigger = trigger || false;
        parameters = parameters || {};

        jQuery.get("/Story/edit", {id: storyId})
        .done(function(content) {
            var title = "Edit user story";
            var buttons = [
                {
                    label: "Save",
                    className: "btn-primary pull-right",
                    callback: function() {
                        var form = jQuery("#formStoryEdit", modal);
                        var formItems = form.serializeJSON();

                        // Validate current form items and try to update user story data
                        if (validateForm(formItems, modal)) {
                            // Update user story
                            socket.put("/Story/" + storyId, formItems, function(/** sails.json.story */story) {
                                if (handleSocketError(story)) {
                                    makeMessage("User story updated successfully.");

                                    modal.modal("hide");

                                    handleEventTrigger(trigger);
                                }
                            });
                        }

                        return false;
                    }
                },
                {
                    label: "Split story",
                    className: "btn-warning pull-right",
                    id: "split",
                    callback: function() {
                        // Trigger story split event
                        body.trigger("storySplit", [storyId, {trigger: "storyEdit", parameters: [storyId, trigger]}]);
                    }
                },
                {
                    label: "Delete",
                    className: "btn-danger pull-right",
                    callback: function() {
                        // Trigger story delete event
                        body.trigger("storyDelete", [storyId, {trigger: "storyEdit", parameters: [storyId, trigger]}]);
                    }
                }
            ];

            // Create bootbox modal
            var modal = createBootboxDialog(title, content, buttons, trigger);

            // Make form init when dialog is opened.
            modal.on("shown.bs.modal", function() {
                initStoryForm(modal, parameters);
            });

            // Open bootbox modal
            modal.modal("show");
        })
        .fail(function(jqXhr, textStatus, error) {
            handleAjaxError(jqXhr, textStatus, error);
        });
    });

    /**
     * User story split event, this opens a modal bootbox prompt with sprint selection.
     *
     * @param   {jQuery.Event}          event       Event object
     * @param   {Number}                storyId     Story id
     * @param   {sails.helper.trigger}  [trigger]   Trigger to process after actions
     */
    body.on("storySplit", function(event, storyId, trigger) {
        trigger = trigger || false;

        var options = [];

        // Add project backlog option
        options.push({value: 0, text: "Project backlog"});

        // Iterate project sprints and add those to option lists
        jQuery.each(myViewModel.sprints(), function(key, sprint) {
            options.push({value: sprint.id(), text: sprint.formattedTitle()});
        });

        // Make prompt box
        var prompt = bootbox.prompt({
            title: "Select sprint where to add new story",
            buttons: {
                cancel: {
                    label: "Cancel",
                    className: "btn-default pull-left"
                },
                confirm: {
                    label: "Split story",
                    className: "btn-primary pull-right"
                }
            },
            inputType: "select",
            inputOptions: options,
            show: false,
            callback: function(result) {
                if (result !== null) {
                    jQuery.ajax({
                        type: "POST",
                        url: "/Story/split",
                        data: {
                            storyId: storyId,
                            sprintId: result,
                            projectId: myViewModel.project().id()
                        },
                        dataType: "json"
                    })
                    .done(function(/** sails.json.storySplit */ data) {
                        makeMessage("User story splitted successfully.");

                        prompt.modal("hide");

                        handleEventTrigger(trigger);

                        // Try to find original story from current scope
                        var story = _.find(myViewModel.stories(), function(story) {
                            return story.id() === data.storyOld.id;
                        });

                        // Client binding updates

                        // Original story in current scope, so update it
                        if (typeof story !== "undefined") {
                            myViewModel.processSocketMessage("story", "update", data.storyOld.id, data.storyOld);
                        }

                        // If new story sprint is same as current add it to current scope
                        if (data.storyNew.sprintId === myViewModel.sprint().id()) {
                            myViewModel.processSocketMessage("story", "create", data.storyNew.id, data.storyNew);
                        }
                    })
                    .fail(function(jqXhr, textStatus, error) {
                        handleAjaxError(jqXhr, textStatus, error);
                    });
                } else {
                    prompt.modal("hide");

                    handleEventTrigger(trigger);
                }

                return false;
            }
        });

        // Initialize prompt select
        prompt.on("shown.bs.modal", function() {
            initSelectPrompt(prompt);
        });

        // Open bootbox prompt modal
        prompt.modal("show");
    });

    /**
     * User story delete event, this opens a modal bootbox confirm about story delete.
     *
     * @param   {jQuery.Event}          event       Event object
     * @param   {Number}                storyId     Story id
     * @param   {sails.helper.trigger}  [trigger]   Trigger to process after actions
     */
    body.on("storyDelete", function(event, storyId, trigger) {
        trigger = trigger || false;

        // Make confirm box
        bootbox.confirm({
            title: "danger - danger - danger",
            message: "Are you sure of story delete?",
            buttons: {
                cancel: {
                    label: "Cancel",
                    className: "btn-default pull-left"
                },
                confirm: {
                    label: "Delete",
                    className: "btn-danger pull-right"
                }
            },
            callback: function(result) {
                if (result) {
                    // Delete story data
                    socket.delete("/Story/" + storyId, function(/** sails.json.story */story) {
                        if (handleSocketError(story)) {
                            makeMessage("User story deleted successfully.");

                            handleEventTrigger(trigger);
                        }
                    });
                } else {
                    handleEventTrigger(trigger);
                }
            }
        });
    });

    /**
     * Story tasks event. This will open story edit modal dialog and activates tasks tab to
     * be opened. Note that this just fires storyEdit event with specified parameters.
     *
     * @param   {jQuery.Event}          event       Event object
     * @param   {Number}                storyId     Story id
     * @param   {sails.helper.trigger}  trigger     Trigger to process after actions
     */
    body.on("storyTasks", function(event, storyId, trigger) {
        // Used parameters for form init
        var parameters = {
            activeTab: "tasks"
        };

        body.trigger("storyEdit", [storyId, trigger, parameters]);
    });
});

/**
 * Function to initialize story form.
 *
 * @param   {jQuery|$}  modal       Current modal content
 * @param   {{}}        parameters  Parameters
 */
function initStoryForm(modal, parameters) {
    parameters = parameters || {};

    if (parameters.activeTab) {
        jQuery("#" + parameters.activeTab + "Tab", modal).click();
    }

    var inputTitle = jQuery("input[name='title']", modal);

    inputTitle.focus().val(inputTitle.val());

    var slider = jQuery(".estimateSlider", modal);
    var input = slider.next("input");
    var show = jQuery(".sliderValue", modal);
    var currentValue = 0;

    // Specify fibonacci values for story sizes
    var values = [ -1, 0, 0.5, 1, 2, 3, 5, 8, 13, 20, 40, 100 ];

    jQuery.each(values, function(key, value) {
        if (value == input.val()) {
            currentValue = key;
        }
    });

    show.val(currentValue == 0 ? "???" : values[currentValue]);

    // Note that this slider only accepts fibonacci values
    slider.slider({
        min: 0,
        max: values.length - 1,
        value: currentValue,
        step: 1,
        slide: function(event, ui) {
            input.val(values[ui.value]);

            if (ui.value === 0) {
                show.val("???");
            } else {
                show.val(values[ui.value]);
            }
        }
    });
}

/**
 * Function initializes story tasks tab to use in task edit modal. Note that
 * this init can be called multiple times.
 *
 * Also note that this init is called dynamic from initTabs() function.
 *
 * @param   {jQuery|$}  modal       Current modal content
 * @param   {String}    contentId   Tab content div id
 */
function initStoryTabTasks(modal, contentId) {
    var body = jQuery("body");
    var container = modal.find(contentId);

    // Initialize action menu for stories
    initActionMenu(container, {});

    // Remove 'add new' click listeners, this prevents firing this event multiple times
    body.off("click", "[data-add-new-task='true']");

    // User wants to add new user to project
    body.on("click", "[data-add-new-task='true']", function() {
        var element = jQuery(this);
        var storyId = element.data("storyId");

        // Hide current modal
        modal.modal("hide");

        // Specify used trigger to come back to this view
        var trigger = {
            trigger: "storyEdit",
            parameters: [storyId, null, {activeTab: "tasks"}]
        };

        // Find specified story object
        var story = _.find(myViewModel.stories(), function(story) { return story.id() === storyId; });

        body.trigger("taskAdd", [story, trigger]);
    });

    // User clicks action menu link
    body.on("click", "ul.actionMenu-actions a", function() {
        var element = jQuery(this);
        var storyId = element.data("storyId");
        var taskId = element.data("taskId");
        var action = element.data("action");
        var selector = element.data("selector");

        // We have popover selector, so hide it
        if (selector) {
            jQuery(selector).popover("hide");
        }

        // Hide current modal
        modal.modal("hide");

        // Specify used trigger to come back to this view
        var trigger = {
            trigger: "storyEdit",
            parameters: [storyId, null, {activeTab: "tasks"}]
        };

        // Trigger milestone action event
        body.trigger(action, [taskId, trigger]);
    });
}
<|endoftext|>


<commit_before>$(document).ready(function(){
    var body = $("body");
    var csrfToken = $('meta[name="csrf-token"]').attr("content");

    /**  account/register */
    var yzmFlag = false;    //是否正在获取验证码的标志
    $(".get_yzm").click(function(){
        if(yzmFlag){    //如过正在获取，则不允许再点击
            alert("60秒内请勿重复点击");
            return false;
        }
        yzmFlag = true;
        var mobile = $(".mobile").val();
        var leftTime = 60;
        $this = $(this);
        $this.removeClass("btn-primary").addClass("btn-default");
        $this.text(leftTime + "秒后可重新获取");
        var setIntervalResult = setInterval(function(){ //60秒内最多发一条
            if(leftTime <= 0){
                window.clearInterval(setIntervalResult);
                $this.text("获取验证码");
                $this.removeClass("btn-default").addClass("btn-primary");
                yzmFlag = false;
            }else{
                $this.text(--leftTime + "秒后可重新获取");
            }
        },1000);
        $.post("?r=account/get-yzm",{_csrf: csrfToken,mobile:mobile},function(data){
            if(data == true){
                alert("发送成功");
            }else{
                alert(data);    //调试用，上线后不应该弹出
            }
        });
    });

    /** practice/index */
    var pay_modal = $("#pay_modal");

    var redirect_url = "";

    $(".show_modal").click(function(){
        if(pay_modal.length==0){
            redirect($(this).data("href"));
        }else{
            redirect_url = $(this).data("href");
            pay_modal.modal('show');
        }
    });

    $(".show_modal_restart").click(function(){
        var r = confirm("重新开始将重置顺序练习进度");
        if(r == true){
            if(pay_modal.length==0){
                redirect($(this).data("href"));
            }else{
                redirect_url = $(this).data("href");
                pay_modal.modal('show');
            }
        }
        return false;
    });

    var pay_click_flag = false;
    $(".pay_click").click(function(){
        if(pay_click_flag){
            alert("正在支付，请勿频繁点击");
            return false;
        }
        pay_click_flag = true;
        $.post("?r=account/pay", {_csrf: csrfToken},function(data){
            if(data!=true){
                alert(data);
            }else{
                alert("支付成功");
                pay_modal.modal('hide');
                if(redirect_url){
                    redirect(redirect_url);
                }
            }
            pay_click_flag = false;
        });
    });

    $(".pay_redirect").click(function(){
        redirect($(this).data("href"));
    });

    function redirect(url){
        $(".loading").show();
        window.location.href=url;
    }

    /** practice/test */
    $(".loading").hide();

    var questionNumber; //题号，获取当前题号，用于显示上下一题
    var minNumber = parseInt($("input[name=minNumber]").val()); //当前显示的最小题号
    var maxNumber = parseInt($("input[name=maxNumber]").val()); //当前显示的最大题号

    //var testLibraries = $(".test_library");

    var examFlag = $("input[name=examFlag]").val(); //模拟考试的标志

    if(examFlag){   //如果是模拟考试
        questionNumber = 0;
        //模拟考试倒计时
        var TOTAL_TIME = 150;    //总时间
        var leftTime = 150;    //剩余时间
        var setIntervalResult = setInterval(function(){ //每分钟减一
            if(leftTime == 0){
                window.clearInterval(setIntervalResult);
                over();
            }
            $(".time").text(leftTime--);
        },60000);
    }else{
        questionNumber= $("input[name=currentNumber]").val();
        var currentTestLibraryId = $("input[name=currentTestLibraryId]").val(); //当前题目的testLibraryId，用于判断是否要记录当前做到哪一题
    }
    //显示第一题
    $(".test_library_"+questionNumber).show();
    var defaultOnceNumber = 10;  //需要与params-local.php中保持一致
    //显示上一题
    var minNumberFlag = false;
    body.on("click",".previous_text_library",function(){
        if(minNumber == questionNumber){
            alert("题目还没加载出来，请稍后点击");
        }else{
            $(".test_library_"+questionNumber).hide();
            $(".test_library_"+(--questionNumber)).show();
        }
        if(examFlag != 'examFlag') {   //非模拟考试
            if ((minNumber + 5) >= questionNumber) {    //当前题号达到一定值时需要去ajax获取数据
                if (minNumberFlag) {  //避免点击后还没请求完再次请求
                    return false;
                } else {
                    minNumberFlag = true;
                    $.post("?r=practice/get-data", {_csrf: csrfToken,minNumber: minNumber}, function (data) {
                        body.append(data);
                        minNumber = (minNumber - defaultOnceNumber < 0) ? 0 : minNumber - defaultOnceNumber;
                        minNumberFlag = false;
                    });
                }
            }
        }
    });
    //显示下一题
    var maxNumberFlag = false;
    var totalNumber = parseInt($("input[name=totalNumber]").val());
    body.on("click",".next_test_library",function(){
        if(maxNumber == questionNumber){
            alert("题目还没加载出来，请稍后点击");
        }else{
            $(".test_library_"+questionNumber).hide();
            $(".test_library_"+(++questionNumber)).show();
        }
        if(examFlag != 'examFlag') {    //非模拟考试情况下执行
            if((maxNumber-5) <= questionNumber){    //当前题号达到一定值时需要去ajax获取数据
                if(maxNumberFlag){  //避免点击后还没请求完再次请求
                    return false;
                }else{
                    maxNumberFlag = true;
                    $.post("?r=practice/get-data",{_csrf: csrfToken,maxNumber:maxNumber},function(data){
                        body.append(data);
                        maxNumber = (maxNumber+defaultOnceNumber > totalNumber) ? totalNumber : maxNumber+defaultOnceNumber;
                        maxNumberFlag = false;
                    });
                }
            }
            var id = $(this).data("id");
            if(id > currentTestLibraryId){  //当前点击的题目的id号大于当前题目id号才提交记录
                var csrfToken = $('meta[name="csrf-token"]').attr("content");
                var answerType = $("input[name=answer_type_" + id + "]").val();
                $.post("?r=practice/next", {_csrf: csrfToken, type: answerType, testLibraryId: id});
            }
        }
    });

    //最后一题点击后
    $(".over_test_library").click(function(){
        if(examFlag != 'examFlag') {    //非模拟考试情况下执行
            var id = $(this).data("id");
            if(id > currentTestLibraryId){  //当前点击的题目的id号大于当前题目id号才提交记录

                var answerType = $("input[name=answer_type_" + id + "]").val();
                $.post("?r=practice/next", {_csrf: csrfToken, type: answerType, testLibraryId: id});
            }
        }
        over();
    });

    var result = [];    //存放结果，是一个json数组
    $("input[type=radio]").click(function(){
        var id = $(this).data("id");
        var testType = $(this).data("testtype");
        var preType = $(this).data("pretype");
        var value = $(this).val();
        var trueAnswer;
        var answerType = 0; //0错误，1正确
        if(testType == 4 ){ //案例题
            var testLibraryId = id.split("_")[0];
            var number = id.split("_")[1];
            trueAnswer = $(".true_answer_"+testLibraryId).text();
            var trueAnswers = trueAnswer.split(" ");
            if(value == trueAnswers[number]){
                answerType = 1;
            }else{
                answerType = 0;
            }
            $(".user_answer_"+id).text(value);
        }else{
            trueAnswer = $(".true_answer_"+id).text();
            if(value == trueAnswer){
                answerType = 1;
                $(".answer_type_" + id).text("答案正确");
            }else{
                answerType = 0;
                $(".answer_type_" + id).text("答案错误");
            }
            $(".user_answer_"+id).text(value);
        }
        result.push({testLibraryId:id,answerType:answerType,testType:testType,preType:preType});
    });

    $("input[type=checkbox]").click(function(){
        var id = $(this).data("id");
        var testType = $(this).data("testtype");
        var preType = $(this).data("pretype");
        var value = "";
        $("input[name=input_question_"+id+"]:checked").each(function(){
            value += $(this).val();
        });
        if(testType == 4 ){ //案例题
            var testLibraryId = id.split("_")[0];
            var number = id.split("_")[1];
            trueAnswer = $(".true_answer_"+testLibraryId).text();
            var trueAnswers = trueAnswer.split(" ");
            if(value == trueAnswers[number]){
                answerType = 1;
            }else{
                answerType = 0;
            }
            $(".user_answer_"+id).text(value);
        }else{
            var trueAnswer = $(".true_answer_"+id).text();
            var answerType = 0;
            if(value == trueAnswer){
                answerType = 1; //0错误，1正确
                $(".answer_type_" + id).text("答案正确");
            }else{
                answerType = 0; //0错误，1正确
                $(".answer_type_" + id).text("答案错误");
            }
            $(".user_answer_"+id).text(value);
        }

        result.push({testLibraryId:id,answerType:answerType,testType:testType,preType:preType});

    });

    $(".btn_over").click(function(){
        over();
    });

    $(".show_answer").click(function(){
        var id = $(this).data('id');
        $(".answer_show_" + id).show(200);
    });

    $(".add_collection").click(function(){
        var id = $(this).data('id');
        var csrfToken = $('meta[name="csrf-token"]').attr("content");
        var $this = $(this);
        if($this.hasClass("btn-danger")){
            $this.removeClass("btn-danger").addClass("btn-primary");
        }else{
            $this.removeClass("btn-primary").addClass("btn-danger");
        }
        $.post("?r=practice/collection", {_csrf: csrfToken, testLibraryId: id},function(data){
            if(data == 'delete'){
                $this.removeClass("btn-danger").addClass("btn-primary");
            }else if(data == 'collected'){
                $this.removeClass("btn-primary").addClass("btn-danger");
            }else{
                alert("返回值无效，收藏失败");
            }
        });
    });

    function over(){
        if(examFlag) {   //如果是模拟考试
            post("?r=exam/over",JSON.stringify(result),TOTAL_TIME-leftTime);
        }else{
            post("?r=practice/over",JSON.stringify(result),null);
        }
    }

    function post(URL, jsonArray, time) {
        var temp = document.createElement("form");
        temp.action = URL;
        temp.method = "post";
        temp.style.display = "none";
        var opt = document.createElement("textarea");
        opt.name = '_csrf';
        opt.value = csrfToken;
        temp.appendChild(opt);
        opt = document.createElement("textarea");
        opt.name = 'result';
        opt.value = jsonArray;
        temp.appendChild(opt);
        if(time!=null){
            opt = document.createElement("textarea");
            opt.name = 'time';
            opt.value = time;
            temp.appendChild(opt);
        }
        document.body.appendChild(temp);
        temp.submit();
        return temp;
    }

    /** 支付界面相关 */
    $(".wxPay").click(function(){
        $(".loading").show();
        var money = $("#rechargeform-money").val();
        if(isNaN(money)){
            alert("充值金额必须为数字");
            return false;
        }
        $.post("?r=account/recharge",{_csrf: csrfToken,money:money},function(data){
            body.append(data);
            $(".loading").hide();
        });
    });

});
<commit_msg>微信端   支付接口测试<commit_after>$(document).ready(function(){
    var body = $("body");
    var csrfToken = $('meta[name="csrf-token"]').attr("content");

    /**  account/register */
    var yzmFlag = false;    //是否正在获取验证码的标志
    $(".get_yzm").click(function(){
        if(yzmFlag){    //如过正在获取，则不允许再点击
            alert("60秒内请勿重复点击");
            return false;
        }
        yzmFlag = true;
        var mobile = $(".mobile").val();
        var leftTime = 60;
        $this = $(this);
        $this.removeClass("btn-primary").addClass("btn-default");
        $this.text(leftTime + "秒后可重新获取");
        var setIntervalResult = setInterval(function(){ //60秒内最多发一条
            if(leftTime <= 0){
                window.clearInterval(setIntervalResult);
                $this.text("获取验证码");
                $this.removeClass("btn-default").addClass("btn-primary");
                yzmFlag = false;
            }else{
                $this.text(--leftTime + "秒后可重新获取");
            }
        },1000);
        $.post("?r=account/get-yzm",{_csrf: csrfToken,mobile:mobile},function(data){
            if(data == true){
                alert("发送成功");
            }else{
                alert(data);    //调试用，上线后不应该弹出
            }
        });
    });

    /** practice/index */
    var pay_modal = $("#pay_modal");

    var redirect_url = "";

    $(".show_modal").click(function(){
        if(pay_modal.length==0){
            redirect($(this).data("href"));
        }else{
            redirect_url = $(this).data("href");
            pay_modal.modal('show');
        }
    });

    $(".show_modal_restart").click(function(){
        var r = confirm("重新开始将重置顺序练习进度");
        if(r == true){
            if(pay_modal.length==0){
                redirect($(this).data("href"));
            }else{
                redirect_url = $(this).data("href");
                pay_modal.modal('show');
            }
        }
        return false;
    });

    var pay_click_flag = false;
    $(".pay_click").click(function(){
        if(pay_click_flag){
            alert("正在支付，请勿频繁点击");
            return false;
        }
        pay_click_flag = true;
        $.post("?r=account/pay", {_csrf: csrfToken},function(data){
            if(data!=true){
                alert(data);
            }else{
                alert("支付成功");
                pay_modal.modal('hide');
                if(redirect_url){
                    redirect(redirect_url);
                }
            }
            pay_click_flag = false;
        });
    });

    $(".pay_redirect").click(function(){
        redirect($(this).data("href"));
    });

    function redirect(url){
        $(".loading").show();
        window.location.href=url;
    }

    /** practice/test */
    $(".loading").hide();

    var questionNumber; //题号，获取当前题号，用于显示上下一题
    var minNumber = parseInt($("input[name=minNumber]").val()); //当前显示的最小题号
    var maxNumber = parseInt($("input[name=maxNumber]").val()); //当前显示的最大题号

    //var testLibraries = $(".test_library");

    var examFlag = $("input[name=examFlag]").val(); //模拟考试的标志

    if(examFlag){   //如果是模拟考试
        questionNumber = 0;
        //模拟考试倒计时
        var TOTAL_TIME = 150;    //总时间
        var leftTime = 150;    //剩余时间
        var setIntervalResult = setInterval(function(){ //每分钟减一
            if(leftTime == 0){
                window.clearInterval(setIntervalResult);
                over();
            }
            $(".time").text(leftTime--);
        },60000);
    }else{
        questionNumber= $("input[name=currentNumber]").val();
        var currentTestLibraryId = $("input[name=currentTestLibraryId]").val(); //当前题目的testLibraryId，用于判断是否要记录当前做到哪一题
    }
    //显示第一题
    $(".test_library_"+questionNumber).show();
    var defaultOnceNumber = 10;  //需要与params-local.php中保持一致
    //显示上一题
    var minNumberFlag = false;
    body.on("click",".previous_text_library",function(){
        if(minNumber == questionNumber){
            alert("题目还没加载出来，请稍后点击");
        }else{
            $(".test_library_"+questionNumber).hide();
            $(".test_library_"+(--questionNumber)).show();
        }
        if(examFlag != 'examFlag') {   //非模拟考试
            if ((minNumber + 5) >= questionNumber) {    //当前题号达到一定值时需要去ajax获取数据
                if (minNumberFlag) {  //避免点击后还没请求完再次请求
                    return false;
                } else {
                    minNumberFlag = true;
                    $.post("?r=practice/get-data", {_csrf: csrfToken,minNumber: minNumber}, function (data) {
                        body.append(data);
                        minNumber = (minNumber - defaultOnceNumber < 0) ? 0 : minNumber - defaultOnceNumber;
                        minNumberFlag = false;
                    });
                }
            }
        }
    });
    //显示下一题
    var maxNumberFlag = false;
    var totalNumber = parseInt($("input[name=totalNumber]").val());
    body.on("click",".next_test_library",function(){
        if(maxNumber == questionNumber){
            alert("题目还没加载出来，请稍后点击");
        }else{
            $(".test_library_"+questionNumber).hide();
            $(".test_library_"+(++questionNumber)).show();
        }
        if(examFlag != 'examFlag') {    //非模拟考试情况下执行
            if((maxNumber-5) <= questionNumber){    //当前题号达到一定值时需要去ajax获取数据
                if(maxNumberFlag){  //避免点击后还没请求完再次请求
                    return false;
                }else{
                    maxNumberFlag = true;
                    $.post("?r=practice/get-data",{_csrf: csrfToken,maxNumber:maxNumber},function(data){
                        body.append(data);
                        maxNumber = (maxNumber+defaultOnceNumber > totalNumber) ? totalNumber : maxNumber+defaultOnceNumber;
                        maxNumberFlag = false;
                    });
                }
            }
            var id = $(this).data("id");
            if(id > currentTestLibraryId){  //当前点击的题目的id号大于当前题目id号才提交记录
                var csrfToken = $('meta[name="csrf-token"]').attr("content");
                var answerType = $("input[name=answer_type_" + id + "]").val();
                $.post("?r=practice/next", {_csrf: csrfToken, type: answerType, testLibraryId: id});
            }
        }
    });

    //最后一题点击后
    $(".over_test_library").click(function(){
        if(examFlag != 'examFlag') {    //非模拟考试情况下执行
            var id = $(this).data("id");
            if(id > currentTestLibraryId){  //当前点击的题目的id号大于当前题目id号才提交记录

                var answerType = $("input[name=answer_type_" + id + "]").val();
                $.post("?r=practice/next", {_csrf: csrfToken, type: answerType, testLibraryId: id});
            }
        }
        over();
    });

    var result = [];    //存放结果，是一个json数组
    $("input[type=radio]").click(function(){
        var id = $(this).data("id");
        var testType = $(this).data("testtype");
        var preType = $(this).data("pretype");
        var value = $(this).val();
        var trueAnswer;
        var answerType = 0; //0错误，1正确
        if(testType == 4 ){ //案例题
            var testLibraryId = id.split("_")[0];
            var number = id.split("_")[1];
            trueAnswer = $(".true_answer_"+testLibraryId).text();
            var trueAnswers = trueAnswer.split(" ");
            if(value == trueAnswers[number]){
                answerType = 1;
            }else{
                answerType = 0;
            }
            $(".user_answer_"+id).text(value);
        }else{
            trueAnswer = $(".true_answer_"+id).text();
            if(value == trueAnswer){
                answerType = 1;
                $(".answer_type_" + id).text("答案正确");
            }else{
                answerType = 0;
                $(".answer_type_" + id).text("答案错误");
            }
            $(".user_answer_"+id).text(value);
        }
        result.push({testLibraryId:id,answerType:answerType,testType:testType,preType:preType});
    });

    $("input[type=checkbox]").click(function(){
        var id = $(this).data("id");
        var testType = $(this).data("testtype");
        var preType = $(this).data("pretype");
        var value = "";
        $("input[name=input_question_"+id+"]:checked").each(function(){
            value += $(this).val();
        });
        if(testType == 4 ){ //案例题
            var testLibraryId = id.split("_")[0];
            var number = id.split("_")[1];
            trueAnswer = $(".true_answer_"+testLibraryId).text();
            var trueAnswers = trueAnswer.split(" ");
            if(value == trueAnswers[number]){
                answerType = 1;
            }else{
                answerType = 0;
            }
            $(".user_answer_"+id).text(value);
        }else{
            var trueAnswer = $(".true_answer_"+id).text();
            var answerType = 0;
            if(value == trueAnswer){
                answerType = 1; //0错误，1正确
                $(".answer_type_" + id).text("答案正确");
            }else{
                answerType = 0; //0错误，1正确
                $(".answer_type_" + id).text("答案错误");
            }
            $(".user_answer_"+id).text(value);
        }

        result.push({testLibraryId:id,answerType:answerType,testType:testType,preType:preType});

    });

    $(".btn_over").click(function(){
        over();
    });

    $(".show_answer").click(function(){
        var id = $(this).data('id');
        $(".answer_show_" + id).show(200);
    });

    $(".add_collection").click(function(){
        var id = $(this).data('id');
        var csrfToken = $('meta[name="csrf-token"]').attr("content");
        var $this = $(this);
        if($this.hasClass("btn-danger")){
            $this.removeClass("btn-danger").addClass("btn-primary");
        }else{
            $this.removeClass("btn-primary").addClass("btn-danger");
        }
        $.post("?r=practice/collection", {_csrf: csrfToken, testLibraryId: id},function(data){
            if(data == 'delete'){
                $this.removeClass("btn-danger").addClass("btn-primary");
            }else if(data == 'collected'){
                $this.removeClass("btn-primary").addClass("btn-danger");
            }else{
                alert("返回值无效，收藏失败");
            }
        });
    });

    function over(){
        if(examFlag) {   //如果是模拟考试
            post("?r=exam/over",JSON.stringify(result),TOTAL_TIME-leftTime);
        }else{
            post("?r=practice/over",JSON.stringify(result),null);
        }
    }

    function post(URL, jsonArray, time) {
        var temp = document.createElement("form");
        temp.action = URL;
        temp.method = "post";
        temp.style.display = "none";
        var opt = document.createElement("textarea");
        opt.name = '_csrf';
        opt.value = csrfToken;
        temp.appendChild(opt);
        opt = document.createElement("textarea");
        opt.name = 'result';
        opt.value = jsonArray;
        temp.appendChild(opt);
        if(time!=null){
            opt = document.createElement("textarea");
            opt.name = 'time';
            opt.value = time;
            temp.appendChild(opt);
        }
        document.body.appendChild(temp);
        temp.submit();
        return temp;
    }

    /** 支付界面相关 */
    $(".wxPay").click(function(){
        $(".loading").show();
        var money = $("#rechargeform-money").val();
        if(isNaN(money)){
            alert("充值金额必须为数字");
            return false;
        }
        $.ajax({
            url:"?r=account/recharge",
            timeout: 6000,
            type: "post",
            data: {_csrf: csrfToken,money:money},
            success: function(data) {
                body.append(data);
                $(".loading").hide();
            },
            complete : function(XMLHttpRequest,status){
                if(status=='timeout'){
                    $(".loading").hide();
                    alert("请求超时，请稍后再试");
                }
            }
        });
    });

});
<|endoftext|>


<commit_before>// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

import * as wasm from "aarch64-esr-web";

wasm.init()

const esr = document.getElementById("esr");
esr.oninput = () => {
    if (esr.value.length > 0) {
        wasm.decode_esr(esr.value)
    }
};
<commit_msg>Keep ESR value in URL hash.<commit_after>// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

import * as wasm from "aarch64-esr-web";

wasm.init()

const esr = document.getElementById("esr");
esr.oninput = () => {
    if (esr.value.length > 0) {
        wasm.decode_esr(esr.value)
    }
    window.location.hash = esr.value
};

if (window.location.hash) {
    esr.value = window.location.hash.substring(1)
    wasm.decode_esr(esr.value)
}
<|endoftext|>


<commit_before>import React from 'react';
import DocumentTitle from 'react-document-title';

import AppBar from 'material-ui/lib/app-bar';
import RaisedButton from 'material-ui/lib/raised-button';
import {Spacing} from 'material-ui/lib/styles';
import {darkWhite, grey200, grey400} from 'material-ui/lib/styles/colors';
import { connect } from 'react-redux';

import ThemeManager from 'material-ui/lib/styles/theme-manager';
import MediaMeterTheme from '../theme';

import ControllableAppLeftNav from './AppLeftNav';
import FullWidthSection from '../components/FullWidthSection';
import leftNavVisibility from './actions';

const App = React.createClass({

  propTypes: {
    location: React.PropTypes.object.isRequired,
    handleTouchTapLeftIconButton: React.PropTypes.func,
    handleRequestChangeList: React.PropTypes.func
  },

  contextTypes: {
    router: React.PropTypes.object.isRequired,
    store: React.PropTypes.object.isRequired
  },

  //the key passed through context must be called "muiTheme"
  childContextTypes : {
    muiTheme: React.PropTypes.object
  },

  getChildContext() {
    return {
      muiTheme: ThemeManager.getMuiTheme(MediaMeterTheme)
    };
  },

  getStyles() {
    const styles = {
      root: {
        paddingTop: Spacing.desktopKeylineIncrement,
        minHeight: 400
      },
      content: {
        margin: Spacing.desktopGutter
      },
      footer: {
        backgroundColor: grey200,
        textAlign: 'center'
      },
      a: {
        color: grey400
      },
      p: {
        margin: '0 auto',
        padding: 0,
        text: grey400,
        maxWidth: 356
      },
      iconButton: {
        color: darkWhite
      }
    };

    return styles;
  },

  handleRequestChangeListProxy(event, value) {
    this.context.router.push(value);
    this.props.handleRequestChangeList();
  },

  render() {
    const {
      location,
      children
    } = this.props;

    const router = this.context.router;
    const styles = this.getStyles();
    const title = "MediaMeter";
    const leftNavOpen = this.context.store.getState().leftNavVisibility;

    return (

        <DocumentTitle title={title} />
        <AppBar
          onLeftIconButtonTouchTap={this.props.handleTouchTapLeftIconButton}
          title={title}
          zDepth={0}
          style={styles.appBar}
        />
        <ControllableAppLeftNav
          style={styles.leftNav}
          location={location}
          docked={false}
          onRequestChangeList={this.handleRequestChangeListProxy}
        />
        <FullWidthSection style={styles.footer}>

            {'Created by '}

              MIT Center for Civic Media

            {' and '}

              Berkman Center for Internet and Society at Harvard University
            .

        </FullWidthSection>

    );
  }

});

const mapStateToProps = (state) => {
  return {
  };
};

const mapDispatchToProps = (dispatch) => {
  return {
    handleTouchTapLeftIconButton: (open) => {
      dispatch(leftNavVisibility(true));
    },
    handleRequestChangeList: () => {
      dispatch(leftNavVisibility(false));
    }
  };
};

const ControllableApp = connect(
  mapStateToProps,
  mapDispatchToProps
)(App);

export default ControllableApp;
<commit_msg>fixed child rendering<commit_after>import React from 'react';
import DocumentTitle from 'react-document-title';

import AppBar from 'material-ui/lib/app-bar';
import RaisedButton from 'material-ui/lib/raised-button';
import {Spacing} from 'material-ui/lib/styles';
import {darkWhite, grey200, grey400} from 'material-ui/lib/styles/colors';
import { connect } from 'react-redux';

import ThemeManager from 'material-ui/lib/styles/theme-manager';
import MediaMeterTheme from '../theme';

import ControllableAppLeftNav from './AppLeftNav';
import FullWidthSection from '../components/FullWidthSection';
import leftNavVisibility from './actions';

const App = React.createClass({

  propTypes: {
    children: React.PropTypes.node,
    location: React.PropTypes.object.isRequired,
    handleTouchTapLeftIconButton: React.PropTypes.func,
    handleRequestChangeList: React.PropTypes.func
  },

  contextTypes: {
    router: React.PropTypes.object.isRequired,
    store: React.PropTypes.object.isRequired
  },

  //the key passed through context must be called "muiTheme"
  childContextTypes : {
    muiTheme: React.PropTypes.object
  },

  getChildContext() {
    return {
      muiTheme: ThemeManager.getMuiTheme(MediaMeterTheme)
    };
  },

  getStyles() {
    const styles = {
      root: {
        minHeight: 400
      },
      content: {
        margin: Spacing.desktopGutter
      },
      footer: {
        backgroundColor: grey200,
        textAlign: 'center'
      },
      a: {
        color: grey400
      },
      p: {
        margin: '0 auto',
        padding: 0,
        text: grey400,
        maxWidth: 356
      },
      iconButton: {
        color: darkWhite
      }
    };

    return styles;
  },

  handleRequestChangeListProxy(event, value) {
    this.context.router.push(value);
    this.props.handleRequestChangeList();
  },

  render() {
    const {
      location,
      children
    } = this.props;

    const router = this.context.router;
    const styles = this.getStyles();
    const title = "MediaMeter";
    const leftNavOpen = this.context.store.getState().leftNavVisibility;

    return (

        <DocumentTitle title={title} />
        <AppBar
          onLeftIconButtonTouchTap={this.props.handleTouchTapLeftIconButton}
          title={title}
          zDepth={0}
          style={styles.appBar}
        />

            {children}

        <ControllableAppLeftNav
          style={styles.leftNav}
          location={location}
          docked={false}
          onRequestChangeList={this.handleRequestChangeListProxy}
        />
        <FullWidthSection style={styles.footer}>

            {'Created by '}

              MIT Center for Civic Media

            {' and '}

              Berkman Center for Internet and Society at Harvard University
            .

        </FullWidthSection>

    );
  }

});

const mapStateToProps = (state) => {
  return {
  };
};

const mapDispatchToProps = (dispatch) => {
  return {
    handleTouchTapLeftIconButton: (open) => {
      dispatch(leftNavVisibility(true));
    },
    handleRequestChangeList: () => {
      dispatch(leftNavVisibility(false));
    }
  };
};

const ControllableApp = connect(
  mapStateToProps,
  mapDispatchToProps
)(App);

export default ControllableApp;
<|endoftext|>


<commit_before>var setupExtendedSplashScreen, updateSplashScreenPositioning,
    splashScreen, splashScreenEl, splashScreenImageEl,
    isWindows = navigator.appVersion.indexOf("Windows Phone 8.1") === -1;

WinJS.Application.addEventListener("activated", function (e) {
    if (e.detail.kind === Windows.ApplicationModel.Activation.ActivationKind.launch) {
        splashScreen = e.detail.splashScreen;

        // Listen for window resize events to reposition the extended splash screen image accordingly.
        // This is important to ensure that the extended splash screen is formatted properly in response to snapping, unsnapping, rotation, etc...
        window.addEventListener("resize", updateSplashPositioning, false);

        var previousExecutionState = e.detail.previousExecutionState;
        var state = Windows.ApplicationModel.Activation.ApplicationExecutionState;
        if (previousExecutionState === state.notRunning
            || previousExecutionState === state.terminated
            || previousExecutionState === state.closedByUser) {
            setupExtendedSplashScreen();
        }
    }
}, false);

setupExtendedSplashScreen = function () {
    splashScreenEl = document.getElementById("extendedSplashScreen");
    splashScreenImageEl = (splashScreenEl && splashScreenEl.querySelector(".extendedSplashImage"));
    splashLoadingEl = (splashScreenEl && splashScreenEl.querySelector(".loading-progress"));

    if (!splashScreen || !splashScreenEl || !splashScreenImageEl) { return; }

    var imgSrc = "/images/splashScreen.png"
    if (isWindows) {
        imgSrc = "/images/SplashScreen.png"
    }

    splashScreenImageEl.setAttribute("src", imgSrc);

    updateSplashPositioning();

    // Once the extended splash screen is setup, apply the CSS style that will make the extended splash screen visible.
    splashScreenEl.style.display = "block";
};

updateSplashPositioning = function () {
    if (!splashScreen || !splashScreenImageEl) { return; }
    // Position the extended splash screen image in the same location as the system splash screen image.
    if (isWindows) {
        splashScreenImageEl.style.top = splashScreen.imageLocation.y + "px";
        splashScreenImageEl.style.left = splashScreen.imageLocation.x + "px";
        splashScreenImageEl.style.height = splashScreen.imageLocation.height + "px";
        splashScreenImageEl.style.width = splashScreen.imageLocation.width + "px";
    } else {
        var curOrientation = Windows.Devices.Sensors.SimpleOrientationSensor.getDefault().getCurrentOrientation();
        if (curOrientation == Windows.Devices.Sensors.SimpleOrientation.rotated270DegreesCounterclockwise || curOrientation == Windows.Devices.Sensors.SimpleOrientation.rotated90DegreesCounterclockwise) {
            splashScreenImageEl.src = "/images/splashscreenRotated.png";
        } else {
            splashScreenImageEl.src = "/images/splashscreen.png";

        }
        splashScreenImageEl.style.width = "100%";
        splashScreenImageEl.style.height = "100%";
    }

    if (splashLoadingEl) {
        if (isWindows) {
            splashLoadingEl.style.top = (splashScreen.imageLocation.y + splashScreen.imageLocation.height + 20) + "px";
        } else {
            splashLoadingEl.style.top = (window.innerHeight * 0.8) + "px";
        }
    }
};
<commit_msg>[windows] new change to phone extended splashscreen image<commit_after>var setupExtendedSplashScreen, updateSplashScreenPositioning,
    splashScreen, splashScreenEl, splashScreenImageEl,
    isWindows = navigator.appVersion.indexOf("Windows Phone 8.1") === -1;

WinJS.Application.addEventListener("activated", function (e) {
    if (e.detail.kind === Windows.ApplicationModel.Activation.ActivationKind.launch) {
        splashScreen = e.detail.splashScreen;

        // Listen for window resize events to reposition the extended splash screen image accordingly.
        // This is important to ensure that the extended splash screen is formatted properly in response to snapping, unsnapping, rotation, etc...
        window.addEventListener("resize", updateSplashPositioning, false);

        var previousExecutionState = e.detail.previousExecutionState;
        var state = Windows.ApplicationModel.Activation.ApplicationExecutionState;
        if (previousExecutionState === state.notRunning
            || previousExecutionState === state.terminated
            || previousExecutionState === state.closedByUser) {
            setupExtendedSplashScreen();
        }
    }
}, false);

setupExtendedSplashScreen = function () {
    splashScreenEl = document.getElementById("extendedSplashScreen");
    splashScreenImageEl = (splashScreenEl && splashScreenEl.querySelector(".extendedSplashImage"));
    splashLoadingEl = (splashScreenEl && splashScreenEl.querySelector(".loading-progress"));

    if (!splashScreen || !splashScreenEl || !splashScreenImageEl) { return; }

    var imgSrc = "/images/splashScreenPhone.png"
    if (isWindows) {
        imgSrc = "/images/SplashScreen.png"
    }

    splashScreenImageEl.setAttribute("src", imgSrc);

    updateSplashPositioning();

    // Once the extended splash screen is setup, apply the CSS style that will make the extended splash screen visible.
    splashScreenEl.style.display = "block";
};

updateSplashPositioning = function () {
    if (!splashScreen || !splashScreenImageEl) { return; }
    // Position the extended splash screen image in the same location as the system splash screen image.
    if (isWindows) {
        splashScreenImageEl.style.top = splashScreen.imageLocation.y + "px";
        splashScreenImageEl.style.left = splashScreen.imageLocation.x + "px";
        splashScreenImageEl.style.height = splashScreen.imageLocation.height + "px";
        splashScreenImageEl.style.width = splashScreen.imageLocation.width + "px";
    } else {
        var curOrientation = Windows.Devices.Sensors.SimpleOrientationSensor.getDefault().getCurrentOrientation();
        if (curOrientation == Windows.Devices.Sensors.SimpleOrientation.rotated270DegreesCounterclockwise || curOrientation == Windows.Devices.Sensors.SimpleOrientation.rotated90DegreesCounterclockwise) {
            splashScreenImageEl.src = "/images/splashscreenRotated.png";
        } else {
            splashScreenImageEl.src = "/images/splashScreenPhone.png";

        }
        splashScreenImageEl.style.width = "100%";
        splashScreenImageEl.style.height = "100%";
    }

    if (splashLoadingEl) {
        if (isWindows) {
            splashLoadingEl.style.top = (splashScreen.imageLocation.y + splashScreen.imageLocation.height + 20) + "px";
        } else {
            splashLoadingEl.style.top = (window.innerHeight * 0.8) + "px";
        }
    }
};
<|endoftext|>


<commit_before>import React from 'react';
import markdown from './README.mdx';
import AuthLayout,{BackgroundContent} from './AuthLayout';
import Button from './../Button';
import TextInput from './../TextInput';
import Text from './../Text';
import Link from './../Link';
import FormGroup from './../FormGroup';
import Icon from './../Icon';
import { iconArrowLeft, iconWfpLogoStandardBlackEn } from '@wfp/icons';

export default {
  title: 'Components/Content Related/AuthLayout',
  component: AuthLayout,
  subcomponents: { BackgroundContent },
  parameters: {
    componentSubtitle: 'Component',
    status: 'released',
    mdx: markdown,
  },
};

export const Regular = (args) => (
  <AuthLayout {...args}>
    <FormGroup style={{width:'80%'}}>
        <Button icon={iconArrowLeft} iconReverse kind="tertiary" style={{marginBottom:'3rem'}}>
        Back to lorem
        </Button>
        <TextInput
            labelText="The labelText"
            name="inputname"
            placeholder="placeholder"
        />
        <TextInput
            labelText="The labelText"
            name="inputname"
            placeholder="placeholder"
        />

            <Link href="https://www.wfp.org">
            Another link
            </Link>
            <Button kind="primary" style={{marginLeft:'2rem'}}>
            Register
            </Button>

    </FormGroup>
  </AuthLayout>
);

Regular.args ={
    backgroundContent:(
        <BackgroundContent style={{
            background: 'linear-gradient(0.13deg, #357DB6 0.17%, #5DB2C2 99.95%)',
            width:'100%',
            height:'100vh',
            color:'#fff',
            padding:'3rem'}}>
            <Icon
                icon={iconWfpLogoStandardBlackEn}
                description="WFP"
                fill="#fff"
                style={{marginBottom:'4rem'}} />
            <Text kind="h1">Lorem ipsum dolor sit amet, consetetur sadipscing elitr,diam nonumy eirmod.</Text>

- Author

        </BackgroundContent>
    )
}

export const WithImage = (args) => (
    <AuthLayout {...args}>
      <FormGroup style={{width:'80%'}}>
          <Button icon={iconArrowLeft} iconReverse kind="tertiary" style={{marginBottom:'3rem'}}>
          Back to lorem
          </Button>
          <TextInput
              labelText="The labelText"
              name="inputname"
              placeholder="placeholder"
          />
          <TextInput
              labelText="The labelText"
              name="inputname"
              placeholder="placeholder"
          />

              <Link href="https://www.wfp.org">
              Another link
              </Link>
              <Button kind="primary" style={{marginLeft:'2rem'}}>
              Register
              </Button>

      </FormGroup>
    </AuthLayout>
  );

  WithImage.args = {
    image: 'http://www1.wfp.org/sites/default/files/images/yemen-hero-min.jpg'
}
<commit_msg>docs(authLayout): changed back button used in example from tertiary to secondary<commit_after>import React from 'react';
import markdown from './README.mdx';
import AuthLayout,{BackgroundContent} from './AuthLayout';
import Button from './../Button';
import TextInput from './../TextInput';
import Text from './../Text';
import Link from './../Link';
import FormGroup from './../FormGroup';
import Icon from './../Icon';
import { iconArrowLeft, iconWfpLogoStandardBlackEn } from '@wfp/icons';

export default {
  title: 'Components/Content Related/AuthLayout',
  component: AuthLayout,
  subcomponents: { BackgroundContent },
  parameters: {
    componentSubtitle: 'Component',
    status: 'released',
    mdx: markdown,
  },
};

export const Regular = (args) => (
  <AuthLayout {...args}>
    <FormGroup style={{width:'80%'}}>
        <Button icon={iconArrowLeft} iconReverse kind="secondary" style={{marginBottom:'3rem'}}>
        Back to lorem
        </Button>
        <TextInput
            labelText="The labelText"
            name="inputname"
            placeholder="placeholder"
        />
        <TextInput
            labelText="The labelText"
            name="inputname"
            placeholder="placeholder"
        />

            <Link href="https://www.wfp.org">
            Another link
            </Link>
            <Button kind="primary" style={{marginLeft:'2rem'}}>
            Register
            </Button>

    </FormGroup>
  </AuthLayout>
);

Regular.args ={
    backgroundContent:(
        <BackgroundContent style={{
            background: 'linear-gradient(0.13deg, #357DB6 0.17%, #5DB2C2 99.95%)',
            width:'100%',
            height:'100vh',
            color:'#fff',
            padding:'3rem'}}>
            <Icon
                icon={iconWfpLogoStandardBlackEn}
                description="WFP"
                fill="#fff"
                style={{marginBottom:'4rem'}} />
            <Text kind="h1">Lorem ipsum dolor sit amet, consetetur sadipscing elitr,diam nonumy eirmod.</Text>

- Author

        </BackgroundContent>
    )
}

export const WithImage = (args) => (
    <AuthLayout {...args}>
      <FormGroup style={{width:'80%'}}>
          <Button icon={iconArrowLeft} iconReverse kind="secondary" style={{marginBottom:'3rem'}}>
          Back to lorem
          </Button>
          <TextInput
              labelText="The labelText"
              name="inputname"
              placeholder="placeholder"
          />
          <TextInput
              labelText="The labelText"
              name="inputname"
              placeholder="placeholder"
          />

              <Link href="https://www.wfp.org">
              Another link
              </Link>
              <Button kind="primary" style={{marginLeft:'2rem'}}>
              Register
              </Button>

      </FormGroup>
    </AuthLayout>
  );

  WithImage.args = {
    image: 'http://www1.wfp.org/sites/default/files/images/yemen-hero-min.jpg'
}
<|endoftext|>


<commit_before>import { Selector } from 'testcafe';

fixture `"Contact" form request submit verification`
  .page `https://www-test.adtechmedia.io/`;

test('Check "Contact" form request can be submitted by user with valid data', async t => {
  const contactTopMenuLink = await Selector('.clearfix > li:nth-child(5) > a');

  await t
    .resizeWindow(1920, 1080)
    .expect(contactTopMenuLink.exists).ok()
    .hover(contactTopMenuLink)
    .click(contactTopMenuLink)

  const pageElementContact = await Selector('#contact:nth-child(1) > form > h1');

  await t
    .expect(pageElementContact.with({
      selectorTimeout: 5000,
      visibilityCheck: true,
    }).visible).ok()
    .expect(pageElementContact.innerText).eql('Contact')

  const contactFormModal = await Selector('.contact-form')
  const contactFormNamelField = await Selector('#name-field')
  const contactFormPhoneField = await Selector('#phone-field')
  const contactFormEmailField = await Selector('#email-field')
  const contactFormMessageField = await Selector('#message-field');

  await t
    .expect(contactFormNamelField.with({
      selectorTimeout: 5000,
      visibilityCheck: true,
    }).visible).ok();

  await t
    .typeText(contactFormNamelField, 'Alexandr Vozicov')
    .typeText(contactFormPhoneField, '999 999 9999')
    .typeText(contactFormEmailField, 'avozicov@mitocgroup.com')
    .typeText(contactFormMessageField, 'Automation Testing Contact Form submit')

  const contactFormSubmitButton = await Selector('#contact-button');

  await t
    .hover(contactFormSubmitButton)
    .click(contactFormSubmitButton, { speed: 0.5 });
});
<commit_msg>Fix contactUs form assertion issue and minify code<commit_after>import { Selector } from 'testcafe';

fixture`"Contact" form request submit verification`
  .page`https://www-test.adtechmedia.io/contact/`;

test('Check "Contact" form request can be submitted by user with valid data', async t => {
  const contactFormModal = await Selector('.contact-form');

  await t
    .resizeWindow(1920, 1080)
    .expect(contactFormModal.exists).ok();

  const contactFormNamelField = await Selector('#name-field');
  const contactFormPhoneField = await Selector('#phone-field');
  const contactFormEmailField = await Selector('#email-field');
  const contactFormMessageField = await Selector('#message-field');

  await t
    .expect(contactFormNamelField.exists).ok()
    .expect(contactFormPhoneField.exists).ok()
    .expect(contactFormEmailField.exists).ok()
    .expect(contactFormMessageField.exists).ok();

  await t
    .typeText(contactFormNamelField, 'Alexandr Vozicov')
    .typeText(contactFormPhoneField, '999 999 9999')
    .typeText(contactFormEmailField, 'avozicov@mitocgroup.com')
    .typeText(contactFormMessageField, 'Automation Testing Contact Form submit');

  const contactFormSubmitButton = await Selector('#contact-button');

  await t
    .hover(contactFormSubmitButton)
    .click(contactFormSubmitButton, { speed: 0.5 });
});<|endoftext|>


<commit_before>'use strict';
var fs = require('fs');
var path = require('path');
var child_process = require('child_process');

// running on pre-4.0 is hard, somewhat different test scheme
if (process.version < 'v4') process.exit(0);

var nodeRoot = process.argv[2];
var testRoot = path.join(nodeRoot, 'test/parallel');
var testFiles = fs.readdirSync(testRoot).filter(function (filename) {
  return filename.indexOf('test-http') === 0;
});

var failedTests = [];
var numSuccesses = 0;
testFiles.forEach(function (filename) {
  var testModulePath = path.join(testRoot, filename);
  try {
    child_process.execFileSync('node', [
      '--allow-natives-syntax',
      '--expose_gc',
      'run-node-http-test.js',
      testModulePath
    ], { stdio: 'ignore' });
    console.log('✓ ' + filename);
    numSuccesses++;
  } catch (e) {
    // non-zero exit code -> test failure
    failedTests.push(filename);
    console.log('X ' + filename + ' - error!');
  }
});

console.log('Finished, failures: ' + failedTests.length + ', successes: ' + numSuccesses);

// pipeline-flood is a harness issue with how it expects argvs
// header response splitting is something about becoming more strict on allowed chars in headers
// not worried about either one; they also fail without our instrumentation
var knownFailures = [
  'test-http-pipeline-flood.js',
  'test-http-header-response-splitting.js'
];

var didPass = failedTests.every(function (filename) {
  return knownFailures.indexOf(filename) !== -1;
});
if (!didPass) {
  console.log('Some unexpected failures, failing...');
  process.exit(1);
} else {
  console.log('All failures were known/expected, passing...');
  process.exit(0);
}
<commit_msg>Update Node flags for v8.X instrumentation tests<commit_after>'use strict';
var fs = require('fs');
var path = require('path');
var child_process = require('child_process');

// running on pre-4.0 is hard, somewhat different test scheme
if (process.version < 'v4') process.exit(0);

var nodeRoot = process.argv[2];
var testRoot = path.join(nodeRoot, 'test/parallel');
var testFiles = fs.readdirSync(testRoot).filter(function (filename) {
  return filename.indexOf('test-http') === 0;
});

var defaultFlags = [
  '--allow-natives-syntax',
  '--expose-gc',
  '--expose-internals'
];

if (process.version >= 'v8') defaultFlags.push('--expose-http2');

var failedTests = [];
var numSuccesses = 0;
testFiles.forEach(function (filename) {
  var testModulePath = path.join(testRoot, filename);
  var singleTestFlags = defaultFlags.concat([
    'run-node-http-test.js',
    testModulePath
  ]);

  // this is the only test, that actually asserts the lack of http2 flag
  // therefore we have to remove it from the process we are about to run
  if (filename === 'test-http2-noflag.js') {
    singleTestFlags = singleTestFlags.filter(function (flag) {
      return flag !== '--expose-http2';
    });
  }

  try {
    child_process.execFileSync('node', singleTestFlags, { stdio: 'ignore' });
    console.log('✓ ' + filename);
    numSuccesses++;
  } catch (e) {
    // non-zero exit code -> test failure
    failedTests.push(filename);
    console.log('X ' + filename + ' - error!');
  }
});

console.log('Finished, failures: ' + failedTests.length + ', successes: ' + numSuccesses);

// pipeline-flood is a harness issue with how it expects argvs
// header response splitting is something about becoming more strict on allowed chars in headers
// not worried about either one; they also fail without our instrumentation
var knownFailures = [
  'test-http-pipeline-flood.js',
  'test-http-header-response-splitting.js'
];

var didPass = failedTests.every(function (filename) {
  return knownFailures.indexOf(filename) !== -1;
});
if (!didPass) {
  console.log('Some unexpected failures, failing...');
  process.exit(1);
} else {
  console.log('All failures were known/expected, passing...');
  process.exit(0);
}
<|endoftext|>


<commit_before>"use strict";
var controller, urac, oauth;
var assert = require('assert');
var shell = require('shelljs');
var sampleData = require("soajs.mongodb.data/modules/examples");

describe("importing sample data", function() {
	it("do import", function(done) {
		shell.pushd(sampleData.dir);
		shell.exec("chmod +x " + sampleData.shell, function(code) {
			assert.equal(code, 0);
			shell.exec(sampleData.shell, function(code) {
				assert.equal(code, 0);
				shell.popd();
				done();
			});
		});
	});

	after(function(done) {
		console.log('test data imported.');
		setTimeout(function() {
			controller = require("soajs.controller");
            setTimeout(function() {
                oauth = require("soajs.oauth");
                urac = require("soajs.urac");
                require ("./example01.test.js");
                require ("./example02.test.js");
                require ("./example03.ten1.test.js");
                require ("./example03.test.js");
                require ("./example04.test.js");
                require ("./example04.test2.js");
                done();
            },500);
		}, 1000);
	});
});<commit_msg>incremented timeout value to 2 sec<commit_after>"use strict";
var controller, urac, oauth;
var assert = require('assert');
var shell = require('shelljs');
var sampleData = require("soajs.mongodb.data/modules/examples");

describe("importing sample data", function() {
	it("do import", function(done) {
		shell.pushd(sampleData.dir);
		shell.exec("chmod +x " + sampleData.shell, function(code) {
			assert.equal(code, 0);
			shell.exec(sampleData.shell, function(code) {
				assert.equal(code, 0);
				shell.popd();
				done();
			});
		});
	});

	after(function(done) {
		console.log('test data imported.');
		setTimeout(function() {
			controller = require("soajs.controller");
            setTimeout(function() {
                oauth = require("soajs.oauth");
                urac = require("soajs.urac");
                require ("./example01.test.js");
                require ("./example02.test.js");
                require ("./example03.ten1.test.js");
                require ("./example03.test.js");
                require ("./example04.test.js");
                require ("./example04.test2.js");
                done();
            },500);
		}, 2000);
	});
});<|endoftext|>


<commit_before>module.exports = {

//---------------------------------------------------------------------
// Action Name
//
// This is the name of the action displayed in the editor.
//---------------------------------------------------------------------

name: "Change Prefix",

//---------------------------------------------------------------------
// Action Section
//
// This is the section the action will fall into.
//---------------------------------------------------------------------

section: "Bot Client Control",

//---------------------------------------------------------------------
// Action Subtitle
//
// This function generates the subtitle displayed next to the name.
//---------------------------------------------------------------------

subtitle: function(data) {
	return `Change Prefix`;
},

//---------------------------------------------------------------------
	 // DBM Mods Manager Variables (Optional but nice to have!)
	 //
	 // These are variables that DBM Mods Manager uses to show information
	 // about the mods for people to see in the list.
	 //---------------------------------------------------------------------

	 // Who made the mod (If not set, defaults to "DBM Mods")
	 author: "EliteArtz & General Wrex",

	 // The version of the mod (Defaults to 1.0.0)
	 version: "1.9.1", // original 1.8.4 | re-added in 1.9.1 ~ Danno3817

	 // A short description to show on the mod line for this mod (Must be on a single line)
	 short_description: "Change Prefix from Bot",

	 // If it depends on any other mods by name, ex: WrexMODS if the mod uses something from WrexMods

	 //---------------------------------------------------------------------

//---------------------------------------------------------------------
// Action Storage Function
//
// Stores the relevant variable info for the editor.
//---------------------------------------------------------------------

//variableStorage: function(data, varType) {},

//---------------------------------------------------------------------
// Action Fields
//
// These are the fields for the action. These fields are customized
// by creating elements with corresponding IDs in the HTML. These
// are also the names of the fields stored in the action's JSON data.
//---------------------------------------------------------------------

fields: ["pprefix"],

//---------------------------------------------------------------------
// Command HTML
//
// This function returns a string containing the HTML used for
// editting actions.
//
// The "isEvent" parameter will be true if this action is being used
// for an event. Due to their nature, events lack certain information,
// so edit the HTML to reflect this.
//
// The "data" parameter stores constants for select elements to use.
// Each is an array: index 0 for commands, index 1 for events.
// The names are: sendTargets, members, roles, channels,
//                messages, servers, variables
//---------------------------------------------------------------------

html: function(isEvent, data) {
	return `

		Mod Info:

		Made by EliteArtz

        Thanks to:

        General Wrex for helping with scripting

    Change Prefix to:

	<textarea id="pprefix" class="round" style="width: 40%; resize: none;" type="textarea" rows="1" cols="20"></textarea>

`;
},

//---------------------------------------------------------------------
// Action Editor Init Code
//
// When the HTML is first applied to the action editor, this code
// is also run. This helps add modifications or setup reactionary
// functions for the DOM elements.
//---------------------------------------------------------------------

init: function() {},

//---------------------------------------------------------------------
// Action Bot Function
//
// This is the function for the action within the Bot's Action class.
// Keep in mind event calls won't have access to the "msg" parameter,
// so be sure to provide checks for variable existance.
//---------------------------------------------------------------------

action: function (cache) {
    const data = cache.actions[cache.index];

    try {

        var prefix = this.evalMessage(data.pprefix, cache);
        if (prefix) {
            this.getDBM().Files.data.settings.tag = prefix;
            this.getDBM().Files.saveData("settings", function () { console.log("Prefix changed to " + prefix) });
        } else {
            console.log(prefix + " is not valid! Try again!");
        }
    } catch (err) {
        console.log("ERROR!" + err.stack ? err.stack : err);
    }
    this.callNextAction(cache);
},

//---------------------------------------------------------------------
// Action Bot Mod
//
// Upon initialization of the bot, this code is run. Using the bot's
// DBM namespace, one can add/modify existing functions if necessary.
// In order to reduce conflictions between mods, be sure to alias
// functions you wish to overwrite.
//---------------------------------------------------------------------

mod: function(DBM) {
}

}; // End of module
<commit_msg>Update Change Prefix<commit_after>module.exports = {

//---------------------------------------------------------------------
// Action Name
//
// This is the name of the action displayed in the editor.
//---------------------------------------------------------------------

name: "Change Global Prefix",

//---------------------------------------------------------------------
// Action Section
//
// This is the section the action will fall into.
//---------------------------------------------------------------------

section: "Bot Client Control",

//---------------------------------------------------------------------
// Action Subtitle
//
// This function generates the subtitle displayed next to the name.
//---------------------------------------------------------------------

subtitle: function(data) {
	return `Change Prefix`;
},

//---------------------------------------------------------------------
	 // DBM Mods Manager Variables (Optional but nice to have!)
	 //
	 // These are variables that DBM Mods Manager uses to show information
	 // about the mods for people to see in the list.
	 //---------------------------------------------------------------------

	 // Who made the mod (If not set, defaults to "DBM Mods")
	 author: "EliteArtz & General Wrex",

	 // The version of the mod (Defaults to 1.0.0)
	 version: "1.9.1", // original 1.8.4 | re-added in 1.9.1 ~ Danno3817

	 // A short description to show on the mod line for this mod (Must be on a single line)
	 short_description: "Change Prefix from Bot",

	 // If it depends on any other mods by name, ex: WrexMODS if the mod uses something from WrexMods

	 //---------------------------------------------------------------------

//---------------------------------------------------------------------
// Action Storage Function
//
// Stores the relevant variable info for the editor.
//---------------------------------------------------------------------

//variableStorage: function(data, varType) {},

//---------------------------------------------------------------------
// Action Fields
//
// These are the fields for the action. These fields are customized
// by creating elements with corresponding IDs in the HTML. These
// are also the names of the fields stored in the action's JSON data.
//---------------------------------------------------------------------

fields: ["pprefix"],

//---------------------------------------------------------------------
// Command HTML
//
// This function returns a string containing the HTML used for
// editting actions.
//
// The "isEvent" parameter will be true if this action is being used
// for an event. Due to their nature, events lack certain information,
// so edit the HTML to reflect this.
//
// The "data" parameter stores constants for select elements to use.
// Each is an array: index 0 for commands, index 1 for events.
// The names are: sendTargets, members, roles, channels,
//                messages, servers, variables
//---------------------------------------------------------------------

html: function(isEvent, data) {
	return `

		Mod Info:

		Made by EliteArtz

        Thanks to:

        General Wrex for helping with scripting

    Change Prefix to:

	<textarea id="pprefix" class="round" style="width: 40%; resize: none;" type="textarea" rows="1" cols="20"></textarea>

`;
},

//---------------------------------------------------------------------
// Action Editor Init Code
//
// When the HTML is first applied to the action editor, this code
// is also run. This helps add modifications or setup reactionary
// functions for the DOM elements.
//---------------------------------------------------------------------

init: function() {},

//---------------------------------------------------------------------
// Action Bot Function
//
// This is the function for the action within the Bot's Action class.
// Keep in mind event calls won't have access to the "msg" parameter,
// so be sure to provide checks for variable existance.
//---------------------------------------------------------------------

action: function (cache) {
    const data = cache.actions[cache.index];

    try {

        var prefix = this.evalMessage(data.pprefix, cache);
        if (prefix) {
            this.getDBM().Files.data.settings.tag = prefix;
            this.getDBM().Files.saveData("settings", function () { console.log("Prefix changed to " + prefix) });
        } else {
            console.log(prefix + " is not valid! Try again!");
        }
    } catch (err) {
        console.log("ERROR!" + err.stack ? err.stack : err);
    }
    this.callNextAction(cache);
},

//---------------------------------------------------------------------
// Action Bot Mod
//
// Upon initialization of the bot, this code is run. Using the bot's
// DBM namespace, one can add/modify existing functions if necessary.
// In order to reduce conflictions between mods, be sure to alias
// functions you wish to overwrite.
//---------------------------------------------------------------------

mod: function(DBM) {
}

}; // End of module
<|endoftext|>