<commit_before>/*
 * Licensed to Jasig under one or more contributor license
 * agreements. See the NOTICE file distributed with this work
 * for additional information regarding copyright ownership.
 * Jasig licenses this file to you 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:
 *
 * http://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.
 */

/**
 * The TabManger component houses the tab renaming functionality. This
 * component is a custom wrapper for the fluid simple text inline editor component.
 * The TabManger component is most likely a temporary solution as wrapping the
 * the fluid simple text inline editor component is somewhat overkill. As work continues
 * on enhancing uPortal's Tab management, the TabManger component will most likely
 * be renamed to house forthcoming tab management features.
 *
 * For more information on planned tab management options, please see the below url:
 * https://wiki.jasig.org/display/UPC/Manage+Tabs
 *
 * -------------------
 * Available selectors
 * -------------------
 *
 * ----------------
 * Available events
 * ----------------
 *
 * ---------------------------
 * Other Configuration Options
 * ---------------------------
 *
 */

"use strict";
var up = up || {};

(function ($, fluid) {

    /**
     * Set up the textEditButton.  Append a background image with appropriate
     * descriptive text to the button.
     *
     * @return {jQuery} The accessible button located after the display text
     */
    fluid.inlineEdit.setupTextEditButton = function (that) {
        var opts = that.options;
        var textEditButton = that.locate("textEditButton");

        if (textEditButton.length === 0) {
            var markup = $("");
            markup.addClass(opts.styles.textEditButton);

            /**
             * Set text for the button and listen
             * for modelChanged to keep it updated
             */
            fluid.inlineEdit.updateTextEditButton(markup, that.model.value || opts.defaultViewText, opts.strings.textEditButton);
            that.events.modelChanged.addListener(function () {
                fluid.inlineEdit.updateTextEditButton(markup, that.model.value || opts.defaultViewText, opts.strings.textEditButton);
            });

            that.locate("text").after(markup);

            // Refresh the textEditButton with the newly appended options
            textEditButton = that.locate("textEditButton");
        }
        return textEditButton;
    };

    /**
     * Private. Initializes the fluid.inlineEditor component to be used with
     * the active portal tab, as long as the active tab is editable.
     *
     * @param {Object} that- reference to an instance of the TabManger component.
     */
    var editTabHandler = function (that) {
        var edit, remove, text, gripper, editorOptions, numOfPortlets;

        // Cache DOM elements.
        edit = that.locate("edit");
        remove = that.locate("remove");
        gripper = that.locate("grabHandle");

        if (edit.length > 0) {
            // Initialize & configure fluid.inlineEdit component.
            that.inlineEditor = fluid.inlineEdits(that.container, {
                selectors: {
                    text: that.options.selectors.text,
                    edit: that.options.selectors.edit
                },
                listeners: {
                    afterBeginEdit: function () {
                        // Hide gripper & remove icon.
                        remove.hide();
                        gripper.hide();
                    },
                    afterFinishEdit: function (newValue, oldValue, editNode, viewNode) {
                        // Show gripper & remove icon.
                        remove.show();
                        gripper.filter(".active").show();

                        // Fire afterFinishEdit event.
                        that.events.onTabEdit.fire(newValue, oldValue, editNode, viewNode);
                    }
                },
                submitOnEnter: that.options.submitOnEnter
            });

            // Mouseenter event listener. Give focus to the
            // tab name on mouseenter. The mouseenter event
            // only triggers its handler on the element to which
            // it is bound.
            text = that.locate("text");
            text.bind("mouseenter", function () {
                text.css("cursor", "text");
                text.focus();
            });

            // Mouseleave event listener. Remove focus from
            // the tab name on mouseleave. The mouseleave event
            // only triggers its handler on the element to which
            // it is bound.
            text.bind("mouseleave", function () {
                text.css("cursor", "pointer");
                text.blur();
            });

            // Trigger edit mode.
            numOfPortlets = parseInt(that.options.numberOfPortlets);
            if (numOfPortlets === 0 && text.text() === that.options.addTabLabel) {
                text.trigger("click");
            }//end:if.
        }//end:if.
    };//end:function.

    /**
     * Private. Fires the onRemove event when the 'remove' icon is clicked. Passes a
     * reference to the onRemove listener.
     *
     * @param {Object} that- reference to an instance of the TabManger component.
     */
    var removeTabHandler = function (that) {
        var remove;
        remove = that.locate("remove");
        remove.bind("click", function () {
            that.events.onTabRemove.fire(this);
        });
    };//end: function.

    /**
     * Private. Fires the onAddTab event when the 'Add Tab' link is clicked. Passes new
     * tab configurations to the onAddTab listener.
     *
     * @param {Object} that- reference to an instance of the TabManger component.
     */
    var addTabHandler = function (that) {
        var add, tabGroup;
        add = that.locate("add");
        tabGroup = that.container.find(that.options.selectors.tabGroup).text();
        add.bind("click", function () {
            that.events.onTabAdd.fire(that.options.addTabLabel, that.options.addTabWidths, tabGroup);
        });
    };//end: function.

    /**
     * Private. Initializes & configures the fluid.reorderLayout component
     * based upon the TabManager options.
     *
     * @param {Object} that- reference to an instance of the TabManger component.
     */
    var moveTabHandler = function (that) {
        // Initialize & configure fluid.reorderLayout component.
        that.reorderLayout = fluid.reorderLayout(that.container, {
            selectors: {
                columns: that.options.selectors.columns,
                modules: that.options.selectors.modules,
                lockedModules: that.options.selectors.lockedModules,
                grabHandle: (that.options.tabContext === "header") ? that.options.selectors.grabHandle : ""
            },
            styles: {
                defaultStyle: "fl-reorderer-" + that.options.tabContext + "-movable-default",
                selected: "fl-reorderer-" + that.options.tabContext + "-movable-selected",
                dragging: "fl-reorderer-" + that.options.tabContext + "-movable-dragging",
                mouseDrag: "fl-reorderer-" + that.options.tabContext + "-movable-dragging",
                hover: "fl-reorderer-" + that.options.tabContext + "-movable-hover",
                dropMarker: "fl-reorderer-" + that.options.tabContext + "-dropMarker",
                avatar: "fl-reorderer-" + that.options.tabContext + "-avatar"
            },
            listeners: {
                afterMove: function (item, requestedPosition, movables) {
                    var tab, tabShortId, method, targetTab, targetTabShortId, tabPosition, listItems;

                    // Capture moved tab & set defaults.
                    tab = $(item);
                    tabShortId = up.defaultNodeIdExtractor(tab);
                    method = that.options.insertBefore;
                    targetTab = null;
                    targetTabShortId = null;
                    tabPosition = 1;
                    listItems = that.locate("tabListItems");

                    // Determine when tab is the last tab and
                    // calculate the targetTab and targetTabShortId.
                    if (tab.is(":last-child")) {
                        method = that.options.appendAfter;
                        targetTab = tab.prev();
                        targetTabShortId = tab.prev().attr("id").split("_")[1];
                    } else {
                        targetTab = tab.next();
                        targetTabShortId = tab.next().attr("id").split("_")[1];
                    }//end:if.

                    // Calculate tab position and apply styles based upon
                    // tab position.
                    $.each(listItems, function (idx, obj) {
                        var li = $(obj);

                        // Find position of moved item.
                        if (li.attr("id") === tab.attr("id")) {
                            tabPosition = (idx + 1);
                        }//end:if.

                        if (listItems.length === 1) {
                            // Apply & remove styles for a single tab.
                            li.removeClass(that.options.styles.firstTab).removeClass(that.options.styles.lastTab).addClass(that.options.styles.singleTab);
                        } else if (idx === 0) {
                            // Apply & remove styles for the first tab.
                            li.removeClass(that.options.styles.singleTab).removeClass(that.options.styles.lastTab).addClass(that.options.styles.firstTab);
                        } else if (idx === (listItems.length - 1)) {
                            // Apply & remove styles for the last tab.
                            li.removeClass(that.options.styles.singleTab).removeClass(that.options.styles.firstTab).addClass(that.options.styles.lastTab);
                        } else {
                            // Apply & remove styles for all other tabs.
                            li.removeClass(that.options.styles.singleTab).removeClass(that.options.styles.lastTab).removeClass(that.options.styles.firstTab);
                        }//end:if.
                    });//end:loop.

                    // Fire afterTabMove event.
                    that.events.onTabMove.fire(tabShortId, method, targetTabShortId, tabPosition);
                }
            }
        });
    };//end: function.

    /**
     * Private. Evaluates the list of tabs for the last instance of a 'locked' tab.
     * Once found, this function adds a 'locked' class to all previously rendered tabs
     * and it also hides the drag & drop grab handle from 'locked' tabs.
     *
     * @param {Object} that- reference to an instance of the TabManger component.
     */
    var manageLockedTabs = function (that) {
        var tabList, lastLockedTab;

        // Find the last instance of a locked tab and add a 'locked' class name
        // to all previous tabs. Hide all drag & drop grab handles from 'locked' tabs.
        tabList = that.locate("tabList");
        lastLockedTab = tabList.find(that.options.selectors.lockedModules + ":last");

        if (lastLockedTab.length > 0) {
            lastLockedTab.find(that.options.selectors.grabHandle).hide();
            lastLockedTab.prevAll()
                         .addClass(that.options.styles.lockedTab)
                         .find(that.options.selectors.grabHandle).hide();
        }//end:if.

        // Initialize drag & drop.
        moveTabHandler(that);
    };//end:function.

    /**
     * Private. Executes initialization functions for the TabManager component.
     *
     * @param {Object} that- reference to an instance of the TabManger component.
     */
    var initialize = function (that) {
        editTabHandler(that);
        removeTabHandler(that);
        addTabHandler(that);
        manageLockedTabs(that);
    };//end:function.

    /**
     * Creator function for the TabManger component.
     *
     * @param {Object} container - reference to HTML DOM element by ID.
     * @param {Object} options - reference to object containing all configurations.
     -------------------------------------------------------*/
    up.TabManager = function (container, options) {
        var that;
        that = fluid.initView("up.TabManager", container, options);

        initialize(that);
        return that;
    };//end:component.

    /**
     * Defaults function for the TabManger component.
     -------------------------------------------------------*/
    fluid.defaults("up.TabManager", {
        selectors: {
            text: ".flc-inlineEdit-text",
            edit: ".flc-inlineEditable",
            remove: ".portal-navigation-delete",
            add: ".portal-navigation-add",
            columns: ".flc-reorderer-column",
            modules: ".movable",
            lockedModules: ".locked",
            grabHandle: ".portal-navigation-gripper",
            tabList: "#portalNavigationList",
            tabListItems: ".portal-navigation",
            tabGroup: "#activeTabGroup"
        },
        events: {
            onTabEdit: null,
            onTabRemove: null,
            onTabAdd: null,
            onTabMove: null
        },
        styles: {
            lockedTab: "locked",
            singleTab: "single",
            firstTab: "first",
            lastTab: "last"
        },
        addTabLabel: "My Tab",
        addTabWidths: [50, 50],
        insertBefore: "insertBefore",
        appendAfter: "appendAfter",
        tabContext: "header",
        numberOfPortlets: 0,
        submitOnEnter: true
    });
})(jQuery, fluid);<commit_msg>Ousted longtime notorious antagonistic tooltip...<commit_after>/*
 * Licensed to Jasig under one or more contributor license
 * agreements. See the NOTICE file distributed with this work
 * for additional information regarding copyright ownership.
 * Jasig licenses this file to you 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:
 *
 * http://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.
 */

/**
 * The TabManger component houses the tab renaming functionality. This
 * component is a custom wrapper for the fluid simple text inline editor component.
 * The TabManger component is most likely a temporary solution as wrapping the
 * the fluid simple text inline editor component is somewhat overkill. As work continues
 * on enhancing uPortal's Tab management, the TabManger component will most likely
 * be renamed to house forthcoming tab management features.
 *
 * For more information on planned tab management options, please see the below url:
 * https://wiki.jasig.org/display/UPC/Manage+Tabs
 *
 * -------------------
 * Available selectors
 * -------------------
 *
 * ----------------
 * Available events
 * ----------------
 *
 * ---------------------------
 * Other Configuration Options
 * ---------------------------
 *
 */

"use strict";
var up = up || {};

(function ($, fluid) {

    /**
     * Set up the textEditButton.  Append a background image with appropriate
     * descriptive text to the button.
     *
     * @return {jQuery} The accessible button located after the display text
     */
    fluid.inlineEdit.setupTextEditButton = function (that) {
        var opts = that.options;
        var textEditButton = that.locate("textEditButton");

        if (textEditButton.length === 0) {
            var markup = $("");
            markup.addClass(opts.styles.textEditButton);

            /**
             * Set text for the button and listen
             * for modelChanged to keep it updated
             */
            fluid.inlineEdit.updateTextEditButton(markup, that.model.value || opts.defaultViewText, opts.strings.textEditButton);
            that.events.modelChanged.addListener(function () {
                fluid.inlineEdit.updateTextEditButton(markup, that.model.value || opts.defaultViewText, opts.strings.textEditButton);
            });

            that.locate("text").after(markup);

            // Refresh the textEditButton with the newly appended options
            textEditButton = that.locate("textEditButton");
        }
        return textEditButton;
    };

    /**
     * Private. Initializes the fluid.inlineEditor component to be used with
     * the active portal tab, as long as the active tab is editable.
     *
     * @param {Object} that- reference to an instance of the TabManger component.
     */
    var editTabHandler = function (that) {
        var edit, remove, text, gripper, editorOptions, numOfPortlets;

        // Cache DOM elements.
        edit = that.locate("edit");
        remove = that.locate("remove");
        gripper = that.locate("grabHandle");

        if (edit.length > 0) {
            // Initialize & configure fluid.inlineEdit component.
            that.inlineEditor = fluid.inlineEdits(that.container, {
                selectors: {
                    text: that.options.selectors.text,
                    edit: that.options.selectors.edit
                },
                listeners: {
                    afterBeginEdit: function () {
                        // Hide gripper & remove icon.
                        remove.hide();
                        gripper.hide();
                    },
                    afterFinishEdit: function (newValue, oldValue, editNode, viewNode) {
                        // Show gripper & remove icon.
                        remove.show();
                        gripper.filter(".active").show();

                        // Fire afterFinishEdit event.
                        that.events.onTabEdit.fire(newValue, oldValue, editNode, viewNode);
                    }
                },
                submitOnEnter: that.options.submitOnEnter,
                useTooltip: false
            });

            // Mouseenter event listener. Give focus to the
            // tab name on mouseenter. The mouseenter event
            // only triggers its handler on the element to which
            // it is bound.
            text = that.locate("text");
            text.bind("mouseenter", function () {
                text.css("cursor", "text");
                text.focus();
            });

            // Mouseleave event listener. Remove focus from
            // the tab name on mouseleave. The mouseleave event
            // only triggers its handler on the element to which
            // it is bound.
            text.bind("mouseleave", function () {
                text.css("cursor", "pointer");
                text.blur();
            });

            // Trigger edit mode.
            numOfPortlets = parseInt(that.options.numberOfPortlets);
            if (numOfPortlets === 0 && text.text() === that.options.addTabLabel) {
                text.trigger("click");
            }//end:if.
        }//end:if.
    };//end:function.

    /**
     * Private. Fires the onRemove event when the 'remove' icon is clicked. Passes a
     * reference to the onRemove listener.
     *
     * @param {Object} that- reference to an instance of the TabManger component.
     */
    var removeTabHandler = function (that) {
        var remove;
        remove = that.locate("remove");
        remove.bind("click", function () {
            that.events.onTabRemove.fire(this);
        });
    };//end: function.

    /**
     * Private. Fires the onAddTab event when the 'Add Tab' link is clicked. Passes new
     * tab configurations to the onAddTab listener.
     *
     * @param {Object} that- reference to an instance of the TabManger component.
     */
    var addTabHandler = function (that) {
        var add, tabGroup;
        add = that.locate("add");
        tabGroup = that.container.find(that.options.selectors.tabGroup).text();
        add.bind("click", function () {
            that.events.onTabAdd.fire(that.options.addTabLabel, that.options.addTabWidths, tabGroup);
        });
    };//end: function.

    /**
     * Private. Initializes & configures the fluid.reorderLayout component
     * based upon the TabManager options.
     *
     * @param {Object} that- reference to an instance of the TabManger component.
     */
    var moveTabHandler = function (that) {
        // Initialize & configure fluid.reorderLayout component.
        that.reorderLayout = fluid.reorderLayout(that.container, {
            selectors: {
                columns: that.options.selectors.columns,
                modules: that.options.selectors.modules,
                lockedModules: that.options.selectors.lockedModules,
                grabHandle: (that.options.tabContext === "header") ? that.options.selectors.grabHandle : ""
            },
            styles: {
                defaultStyle: "fl-reorderer-" + that.options.tabContext + "-movable-default",
                selected: "fl-reorderer-" + that.options.tabContext + "-movable-selected",
                dragging: "fl-reorderer-" + that.options.tabContext + "-movable-dragging",
                mouseDrag: "fl-reorderer-" + that.options.tabContext + "-movable-dragging",
                hover: "fl-reorderer-" + that.options.tabContext + "-movable-hover",
                dropMarker: "fl-reorderer-" + that.options.tabContext + "-dropMarker",
                avatar: "fl-reorderer-" + that.options.tabContext + "-avatar"
            },
            listeners: {
                afterMove: function (item, requestedPosition, movables) {
                    var tab, tabShortId, method, targetTab, targetTabShortId, tabPosition, listItems;

                    // Capture moved tab & set defaults.
                    tab = $(item);
                    tabShortId = up.defaultNodeIdExtractor(tab);
                    method = that.options.insertBefore;
                    targetTab = null;
                    targetTabShortId = null;
                    tabPosition = 1;
                    listItems = that.locate("tabListItems");

                    // Determine when tab is the last tab and
                    // calculate the targetTab and targetTabShortId.
                    if (tab.is(":last-child")) {
                        method = that.options.appendAfter;
                        targetTab = tab.prev();
                        targetTabShortId = tab.prev().attr("id").split("_")[1];
                    } else {
                        targetTab = tab.next();
                        targetTabShortId = tab.next().attr("id").split("_")[1];
                    }//end:if.

                    // Calculate tab position and apply styles based upon
                    // tab position.
                    $.each(listItems, function (idx, obj) {
                        var li = $(obj);

                        // Find position of moved item.
                        if (li.attr("id") === tab.attr("id")) {
                            tabPosition = (idx + 1);
                        }//end:if.

                        if (listItems.length === 1) {
                            // Apply & remove styles for a single tab.
                            li.removeClass(that.options.styles.firstTab).removeClass(that.options.styles.lastTab).addClass(that.options.styles.singleTab);
                        } else if (idx === 0) {
                            // Apply & remove styles for the first tab.
                            li.removeClass(that.options.styles.singleTab).removeClass(that.options.styles.lastTab).addClass(that.options.styles.firstTab);
                        } else if (idx === (listItems.length - 1)) {
                            // Apply & remove styles for the last tab.
                            li.removeClass(that.options.styles.singleTab).removeClass(that.options.styles.firstTab).addClass(that.options.styles.lastTab);
                        } else {
                            // Apply & remove styles for all other tabs.
                            li.removeClass(that.options.styles.singleTab).removeClass(that.options.styles.lastTab).removeClass(that.options.styles.firstTab);
                        }//end:if.
                    });//end:loop.

                    // Fire afterTabMove event.
                    that.events.onTabMove.fire(tabShortId, method, targetTabShortId, tabPosition);
                }
            }
        });
    };//end: function.

    /**
     * Private. Evaluates the list of tabs for the last instance of a 'locked' tab.
     * Once found, this function adds a 'locked' class to all previously rendered tabs
     * and it also hides the drag & drop grab handle from 'locked' tabs.
     *
     * @param {Object} that- reference to an instance of the TabManger component.
     */
    var manageLockedTabs = function (that) {
        var tabList, lastLockedTab;

        // Find the last instance of a locked tab and add a 'locked' class name
        // to all previous tabs. Hide all drag & drop grab handles from 'locked' tabs.
        tabList = that.locate("tabList");
        lastLockedTab = tabList.find(that.options.selectors.lockedModules + ":last");

        if (lastLockedTab.length > 0) {
            lastLockedTab.find(that.options.selectors.grabHandle).hide();
            lastLockedTab.prevAll()
                         .addClass(that.options.styles.lockedTab)
                         .find(that.options.selectors.grabHandle).hide();
        }//end:if.

        // Initialize drag & drop.
        moveTabHandler(that);
    };//end:function.

    /**
     * Private. Executes initialization functions for the TabManager component.
     *
     * @param {Object} that- reference to an instance of the TabManger component.
     */
    var initialize = function (that) {
        editTabHandler(that);
        removeTabHandler(that);
        addTabHandler(that);
        manageLockedTabs(that);
    };//end:function.

    /**
     * Creator function for the TabManger component.
     *
     * @param {Object} container - reference to HTML DOM element by ID.
     * @param {Object} options - reference to object containing all configurations.
     -------------------------------------------------------*/
    up.TabManager = function (container, options) {
        var that;
        that = fluid.initView("up.TabManager", container, options);

        initialize(that);
        return that;
    };//end:component.

    /**
     * Defaults function for the TabManger component.
     -------------------------------------------------------*/
    fluid.defaults("up.TabManager", {
        selectors: {
            text: ".flc-inlineEdit-text",
            edit: ".flc-inlineEditable",
            remove: ".portal-navigation-delete",
            add: ".portal-navigation-add",
            columns: ".flc-reorderer-column",
            modules: ".movable",
            lockedModules: ".locked",
            grabHandle: ".portal-navigation-gripper",
            tabList: "#portalNavigationList",
            tabListItems: ".portal-navigation",
            tabGroup: "#activeTabGroup"
        },
        events: {
            onTabEdit: null,
            onTabRemove: null,
            onTabAdd: null,
            onTabMove: null
        },
        styles: {
            lockedTab: "locked",
            singleTab: "single",
            firstTab: "first",
            lastTab: "last"
        },
        addTabLabel: "My Tab",
        addTabWidths: [50, 50],
        insertBefore: "insertBefore",
        appendAfter: "appendAfter",
        tabContext: "header",
        numberOfPortlets: 0,
        submitOnEnter: true
    });
})(jQuery, fluid);<|endoftext|>


<commit_before>// Use your access token from your studio profile page
// https://studio.whenhub.com/account
var access_token = '<<YOUR ACCESS TOKEN>>';

// Highlight correct nav item
$('.active').removeClass();
$('.third-item').addClass('active');

//Get Schedules and set up table
var scheduleData = JSON.stringify(false);

var xhr = new XMLHttpRequest();
xhr.withCredentials = true;

xhr.addEventListener("readystatechange", function () {
    if (this.readyState === 4) {
        var jsonResponse = JSON.parse(this.responseText);

        for (i = 0; i < jsonResponse.length; i++) {
            if (i < 6){
                if(i == 0) {
                    $('.nav-tabs').append(
                        '
' + jsonResponse[i].name + '
'
                    );
                    if (jsonResponse[i].description== undefined){
                        $('.tab-content').append(
                            '
'+
                            '
This schedule does not have a description.
' +
                            '
Events
' +
                            '
'
                        );

                    }else{
                        $('.tab-content').append(
                            '
'+
                            '
' + jsonResponse[i].description + '
' +
                            '
Events
' +
                            '
'
                        );
                    }
                }
                else {
                    $('.nav-tabs').append(
                        '
' + jsonResponse[i].name + '
'
                    );
                    if (jsonResponse[i].description== undefined){
                        $('.tab-content').append(
                            '
' +
                            '
This schedule does not have a description.
' +
                            '
Events
' +
                            '
'
                        );
                    }else{
                        $('.tab-content').append(
                            '
' +
                            '
' + jsonResponse[i].description + '
' +
                            '
Events
' +
                            '
'
                        );
                    }
                }
            }else {
                break;
            }

            // Get events for each schedule
            var scheduleMedia = JSON.stringify(false);

            var xhr = new XMLHttpRequest();
            xhr.withCredentials = true;

            xhr.addEventListener("readystatechange", function () {
                if (this.readyState === this.DONE) {
                    var scheduleDetails = JSON.parse(this.responseText);
                    var index = $("a:contains(" + scheduleDetails.name + ")").attr('href').charAt(1);

                    if (scheduleDetails.events.length != 0){
                        for (x=0; x < scheduleDetails.events.length; x++){
                            $('#' + index).append(

                                '
' +
                                '
' +
                                '
'+ (x + 1) + '. ' + scheduleDetails.events[x].name + '
' +
                                '
Start Date: ' + scheduleDetails.events[x].when.startDate + '
' +
                                '
Number of media items: ' + scheduleDetails.events[x].media.length + '
' +

                                '
' +
                                '
'

                            );
                        }
                    }else if (scheduleDetails.events.length == 0){
                        $('#' + index).append(
                            '
This schedule does not have any events!
'
                        );
                    }
                    console.log(scheduleDetails)
                }
            });

            xhr.open("GET", "https://api.whenhub.com/api/schedules/" + jsonResponse[i].id + "?filter[include]=media&filter[include][events]=media");
            xhr.setRequestHeader("authorization", accsss_token);

            xhr.send(scheduleMedia);

        }
    }
});

xhr.open("GET", "https://api.whenhub.com/api/users/me/schedules");

xhr.setRequestHeader("authorization", accsss_token);

xhr.send(scheduleData);<commit_msg>Fix access token variables<commit_after>// Use your access token from your studio profile page
// https://studio.whenhub.com/account
var access_token = '<<YOUR ACCESS TOKEN>>';

// Highlight correct nav item
$('.active').removeClass();
$('.third-item').addClass('active');

//Get Schedules and set up table
var scheduleData = JSON.stringify(false);

var xhr = new XMLHttpRequest();
xhr.withCredentials = true;

xhr.addEventListener("readystatechange", function () {
    if (this.readyState === 4) {
        var jsonResponse = JSON.parse(this.responseText);

        for (i = 0; i < jsonResponse.length; i++) {
            if (i < 6){
                if(i == 0) {
                    $('.nav-tabs').append(
                        '
' + jsonResponse[i].name + '
'
                    );
                    if (jsonResponse[i].description== undefined){
                        $('.tab-content').append(
                            '
'+
                            '
This schedule does not have a description.
' +
                            '
Events
' +
                            '
'
                        );

                    }else{
                        $('.tab-content').append(
                            '
'+
                            '
' + jsonResponse[i].description + '
' +
                            '
Events
' +
                            '
'
                        );
                    }
                }
                else {
                    $('.nav-tabs').append(
                        '
' + jsonResponse[i].name + '
'
                    );
                    if (jsonResponse[i].description== undefined){
                        $('.tab-content').append(
                            '
' +
                            '
This schedule does not have a description.
' +
                            '
Events
' +
                            '
'
                        );
                    }else{
                        $('.tab-content').append(
                            '
' +
                            '
' + jsonResponse[i].description + '
' +
                            '
Events
' +
                            '
'
                        );
                    }
                }
            }else {
                break;
            }

            // Get events for each schedule
            var scheduleMedia = JSON.stringify(false);

            var xhr = new XMLHttpRequest();
            xhr.withCredentials = true;

            xhr.addEventListener("readystatechange", function () {
                if (this.readyState === this.DONE) {
                    var scheduleDetails = JSON.parse(this.responseText);
                    var index = $("a:contains(" + scheduleDetails.name + ")").attr('href').charAt(1);

                    if (scheduleDetails.events.length != 0){
                        for (x=0; x < scheduleDetails.events.length; x++){
                            $('#' + index).append(

                                '
' +
                                '
' +
                                '
'+ (x + 1) + '. ' + scheduleDetails.events[x].name + '
' +
                                '
Start Date: ' + scheduleDetails.events[x].when.startDate + '
' +
                                '
Number of media items: ' + scheduleDetails.events[x].media.length + '
' +

                                '
' +
                                '
'

                            );
                        }
                    }else if (scheduleDetails.events.length == 0){
                        $('#' + index).append(
                            '
This schedule does not have any events!
'
                        );
                    }
                    console.log(scheduleDetails)
                }
            });

            xhr.open("GET", "https://api.whenhub.com/api/schedules/" + jsonResponse[i].id + "?filter[include]=media&filter[include][events]=media");
            xhr.setRequestHeader("authorization", access_token);

            xhr.send(scheduleMedia);

        }
    }
});

xhr.open("GET", "https://api.whenhub.com/api/users/me/schedules");

xhr.setRequestHeader("authorization", access_token);

xhr.send(scheduleData);<|endoftext|>


<commit_before>/******************************************************************************
 *	Copyright (c) 2004 Actuate Corporation and others.
 *	All rights reserved. This program and the accompanying materials
 *	are made available under the terms of the Eclipse Public License v1.0
 *	which accompanies this distribution, and is available at
 *		http://www.eclipse.org/legal/epl-v10.html
 *
 *	Contributors:
 *		Actuate Corporation - Initial implementation.
 *****************************************************************************/

/**
 *	BirtParameterDialog
 *	...
 */
BirtParameterDialog = Class.create( );

BirtParameterDialog.prototype = Object.extend( new AbstractParameterDialog( ),
{
	/**
	 *	Parameter dialog working state. Whether embedded inside
	 *	designer dialog.
	 */
	__mode : 'frameset',

	/**
	 *	Identify the parameter is null.
	 */
	__isnull : '__isnull',

	/**
	 *	Initialization routine required by "ProtoType" lib.
	 *	@return, void
	 */
	initialize : function( id, mode )
	{
		this.initializeBase( id );
		this.__mode = mode;

		if ( this.__mode == 'parameter' )
		{
			// Hide dialog title bar if embedded in designer.
			var paramDialogTitleBar = $( id + 'dialogTitleBar' );
			paramDialogTitleBar.style.display = 'none';
		}
	},

	/**
	 *	Binding data to the dialog UI. Data includes zoom scaling factor.
	 *	@data, data DOM tree (schema TBD)
	 *	@return, void
	 */
	__bind : function( data )
	{
		if ( !data )
		{
			return;
		}

		var cascadeParamObj = data.getElementsByTagName( 'CascadeParameter' );
		var confirmObj = data.getElementsByTagName( 'Confirmation' );
		if ( cascadeParamObj.length > 0 )
		{
			this.__propogateCascadeParameter( data );
		}
		else if ( confirmObj.length > 0 )
		{
			this.__close( );
		}
	},

	/**
	 *	Intall the event handlers for cascade parameter.
	 *
	 *	@table_param, container table object.
	 *	@counter, index of possible cascade parameter.
	 *	@return, void
	 */
	__install_cascade_parameter_event_handler : function( table_param, counter )
	{
		var oSC = table_param.getElementsByTagName( "select" );
		var matrix = new Array( );
		var m = 0;

		var oTRC = table_param.getElementsByTagName( "TR" );
		for( var i = 0; i < oTRC.length - 1; i++ )
		{
			var oSelect = oTRC[i].getElementsByTagName( "select" );
			var oInput = oTRC[i].getElementsByTagName( "input" );
			var oCascadeFlag = "";

			if ( oInput && oInput.length > 0 )
			{
				var oLastInput = oInput[oInput.length - 1];
				if ( oLastInput.name == "isCascade" )
					oCascadeFlag = oLastInput.value;
			}

			// find select items to install event listener
			if( oSelect.length > 0 && oCascadeFlag == "true" )
			{
				Event.observe( oSelect[0], 'change', this.__neh_click_select_closure, false );
				if( !matrix[m] )
				{
					matrix[m] = {};
				}
				matrix[m].name = oSelect[0].id.substr( 0, oSelect[0].id.length - 10 );
				matrix[m++].value = oSelect[0].value;
			}
		}

		this.__cascadingParameter[counter] = matrix;
	},

	/**
	 *	Collect parameters, include five cases appear in Birt1.0 Viewer.
	 *
	 *	@return, void
	 */
	collect_parameter : function( )
	{
		// Clear parameter array
		this.__parameter = new Array( );

		var k = 0;
		//oTRC[i] is

 section
		var oTRC = document.getElementById( "parameter_table" ).getElementsByTagName( "TR" );
		for( var i = 0; i < oTRC.length; i++ )
		{
			if( !this.__parameter[k] )
			{
				this.__parameter[k] = { };
			}

			//input element collection
			var oIEC = oTRC[i].getElementsByTagName( "input" );
			//select element collection
			var oSEC = oTRC[i].getElementsByTagName( "select" );
			//avoid group parameter
			var oTable = oTRC[i].getElementsByTagName( "table" );
			if( oTable.length > 0 || ( oSEC.length == 0 && oIEC.length == 0 ) || ( oIEC.length == 1 && oIEC[0].type == 'submit' ) )
			{
				continue;
			}

			if( oSEC.length == 1 && oIEC.length <= 2 )
			{
				// deal with "select" parameter
				if( oIEC.length > 0 )
				{
					this.__parameter[k].name = oIEC[0].name;
				}
				else
				{
					this.__parameter[k].name = oSEC[0].name;
				}
				this.__parameter[k].value = oSEC[0].options[oSEC[0].selectedIndex].value;
				k++;
			}

			if( oSEC.length == 0 && ( oIEC.length == 1 || oIEC.length == 2 ) )
			{
				var temp = {};
				var tempDef = null;
				if( oIEC.length == 1 )
				{
					temp = oIEC[0]
				}
				else if( oIEC[0].type == 'hidden' )
				{
					tempDef = oIEC[0]
					temp = oIEC[1];
				}
				else
				{
					continue;
				}

				if( temp.type == 'text' || temp.type == 'password' )
				{
					// deal with "text" parameter
					this.__parameter[k].name = temp.name;
					// if the parameter neither has a value nor a default value, error
					if( birtUtility.trim( temp.value ) == '' )
					{
						if( tempDef )
						{
							temp.focus( );
							alert( temp.name + ' cannot be blank' );
							return false;
						}
						else
						{
							this.__parameter[k].value = temp.value;
						}
					}
					else
					{
						this.__parameter[k].value = temp.value;
					}
					k++;
				}
				else if( temp.type == 'checkbox' )
				{
					// deal with checkbox
					this.__parameter[k].name = temp.value;
					temp.checked?this.__parameter[k].value = 'true':this.__parameter[k].value = 'false';
					k++;
				}
				else
				{
					//handle more cases
				}
			}
			else if( oSEC.length <= 1 && oIEC.length > 2 )
			{
				for( var j = 0; j < oIEC.length; j++ )
				{
					// deal with radio
					if( oIEC[j].type == 'radio' && oIEC[j].checked )
					{
						if( oIEC[j+1] && ( oIEC[j+1].type == 'text' || oIEC[j+1].type == 'password' ) )
						{
							//Check if allow blank
							var temp = oIEC[j+2];
							if ( temp && temp.id == 'isNotBlank' && temp.value == 'true' )
							{
								if ( birtUtility.trim( oIEC[j+1].value ) == '' )
								{
									oIEC[j+1].focus( );
									alert( temp.name + ' cannot be blank' );
									return false;
								}
							}

							// deal with radio box with textarea or password area
							if( oIEC[j+1].name && oIEC[j+1].value )
							{
								this.__parameter[k].name = oIEC[j+1].name
								this.__parameter[k].value = oIEC[j+1].value;
								k++;
							}
							else
							{
								this.__parameter[k].name = oIEC[j].value
								this.__parameter[k].value = oIEC[j+1].value;
								//oIEC[j+1].value = "";
								k++;
							}
						}
						else if( oSEC[0] )
						{
							// deal with "select" parameter
							if ( oSEC[0].selectedIndex == -1 )
							{
								oSEC[0].focus( );
								alert( oIEC[j].value + " should have a value" );
								return false;
							}

							var temp = oSEC[0].options[oSEC[0].selectedIndex].text;
							if ( !temp )
							{
								oSEC[0].focus( );
								alert( oIEC[j].value + " should have a value" );
								return false;
							}

							// Check if select 'Null Value' option
							if( temp && temp != 'Null Value' )
							{
								this.__parameter[k].name = oIEC[j].value;
								this.__parameter[k].value = oSEC[0].options[oSEC[0].selectedIndex].value;
								k++;
							}
							else
							{
								this.__parameter[k].name = this.__isnull;
								this.__parameter[k].value = oIEC[j].value;
								k++;
							}
						}
						else if( !oIEC[j+1] && !oIEC[j].name )
						{
							//deal with common radio with null value
							this.__parameter[k].name = this.__isnull;
							this.__parameter[k].value = oIEC[j-1].name;
							k++;
						}
						else
						{
							//deal with common radio
							this.__parameter[k].name = oIEC[j].name;
							this.__parameter[k].value = oIEC[j].value;
							k++;
						}
					}
				}
			}
		}
		return true;
	},

	/**
	 *	Handle clicking on okRun.
	 *
	 *	@event, incoming browser native event
	 *	@return, void
	 */
	__okPress : function( )
	{
		if( birtParameterDialog.collect_parameter( ) )
		{
			if ( this.__mode == 'parameter' )
			{
				birtEventDispatcher.broadcastEvent( birtEvent.__E_CACHE_PARAMETER );
			}
			else if ( this.__mode == 'run' )
			{
				this.__doSubmit( );
			}
			else
			{
				birtEventDispatcher.broadcastEvent( birtEvent.__E_CHANGE_PARAMETER );
				this.__l_hide( );
			}
		}
	},

	/**
	 *	Override cancel button click.
	 */
	__neh_cancel : function( )
	{
		if ( this.__mode == 'parameter' )
		{
			this.__cancel();
		}
		else
		{
			this.__l_hide( );
		}
	},

	/**
	 *	Handle submit form with current parameters.
	 *
	 *	@return, void
	 */
	__doSubmit : function( )
	{
		var action = window.location.href;

		var divObj = document.createElement( "DIV" );
		document.body.appendChild( divObj );
		divObj.style.display = "none";

		var formObj = document.createElement( "FORM" );
		divObj.appendChild( formObj );

		if ( this.__parameter != null )
		{
			for( var i = 0; i < this.__parameter.length; i++ )
			{
				var param = document.createElement( "INPUT" );
				formObj.appendChild( param );
				param.TYPE = "HIDDEN";
				param.name = this.__parameter[i].name;
				param.value = this.__parameter[i].value;

				//replace the URL parameter
				var reg = new RegExp( "&" + param.name + "[^&]*&*", "g" );
				action = action.replace( reg, "&" );
			}
		}

		formObj.action = action;
		formObj.method = "post";

		this.__l_hide( );
		formObj.submit( );
	},

	/**
	 *	Caching parameters success, close window.
	 *
	 *	@return, void
	 */
	__close : function( )
	{
		if ( BrowserUtility.__isIE( ) )
		{
			window.opener = null;
			window.close( );
		}
		else
		{
			window.status = "close";
		}
	},

	/**
	 *	Click 'Cancel', close window.
	 *
	 *	@return, void
	 */
	__cancel : function( )
	{
		window.status = "cancel";
	},

	/**
	Called right before element is shown
	*/
	__preShow: function()
	{
		// disable the toolbar buttons
		birtUtility.setButtonsDisabled ( "toolbar", true );

		// disable the Navigation Bar buttons
		birtUtility.setButtonsDisabled ( "navigationBar", true );
	},

	/**
	Called before element is hidden
	*/
	__preHide: function()
	{
		// enable the toolbar buttons
		birtUtility.setButtonsDisabled ( "toolbar", false );

		// enable the Navigation Bar buttons
		birtUtility.setButtonsDisabled ( "navigationBar", false );
	}
}
);<commit_msg>Fix Bugzilla  Bug 146512<commit_after>/******************************************************************************
 *	Copyright (c) 2004 Actuate Corporation and others.
 *	All rights reserved. This program and the accompanying materials
 *	are made available under the terms of the Eclipse Public License v1.0
 *	which accompanies this distribution, and is available at
 *		http://www.eclipse.org/legal/epl-v10.html
 *
 *	Contributors:
 *		Actuate Corporation - Initial implementation.
 *****************************************************************************/

/**
 *	BirtParameterDialog
 *	...
 */
BirtParameterDialog = Class.create( );

BirtParameterDialog.prototype = Object.extend( new AbstractParameterDialog( ),
{
	/**
	 *	Parameter dialog working state. Whether embedded inside
	 *	designer dialog.
	 */
	__mode : 'frameset',

	/**
	 *	Identify the parameter is null.
	 */
	__isnull : '__isnull',

	/**
	 *	Initialization routine required by "ProtoType" lib.
	 *	@return, void
	 */
	initialize : function( id, mode )
	{
		this.__mode = mode;

		if ( this.__mode == 'parameter' )
		{
			// Hide dialog title bar if embedded in designer.
			var paramDialogTitleBar = $( id + 'dialogTitleBar' );
			paramDialogTitleBar.style.display = 'none';
		}

	    this.initializeBase( id );
	},

	/**
	 *	Binding data to the dialog UI. Data includes zoom scaling factor.
	 *	@data, data DOM tree (schema TBD)
	 *	@return, void
	 */
	__bind : function( data )
	{
		if ( !data )
		{
			return;
		}

		var cascadeParamObj = data.getElementsByTagName( 'CascadeParameter' );
		var confirmObj = data.getElementsByTagName( 'Confirmation' );
		if ( cascadeParamObj.length > 0 )
		{
			this.__propogateCascadeParameter( data );
		}
		else if ( confirmObj.length > 0 )
		{
			this.__close( );
		}
	},

	/**
	 *	Intall the event handlers for cascade parameter.
	 *
	 *	@table_param, container table object.
	 *	@counter, index of possible cascade parameter.
	 *	@return, void
	 */
	__install_cascade_parameter_event_handler : function( table_param, counter )
	{
		var oSC = table_param.getElementsByTagName( "select" );
		var matrix = new Array( );
		var m = 0;

		var oTRC = table_param.getElementsByTagName( "TR" );
		for( var i = 0; i < oTRC.length; i++ )
		{
			var oSelect = oTRC[i].getElementsByTagName( "select" );
			var oInput = oTRC[i].getElementsByTagName( "input" );
			var oCascadeFlag = "";

			if ( oInput && oInput.length > 0 )
			{
				var oLastInput = oInput[oInput.length - 1];
				if ( oLastInput.name == "isCascade" )
					oCascadeFlag = oLastInput.value;
			}

			// find select items to install event listener
			if( oSelect.length > 0 && oCascadeFlag == "true" )
			{
				if ( i < oTRC.length - 1 )
				{
					Event.observe( oSelect[0], 'change', this.__neh_click_select_closure, false );
				}

				if( !matrix[m] )
				{
					matrix[m] = {};
				}
				matrix[m].name = oSelect[0].id.substr( 0, oSelect[0].id.length - 10 );
				matrix[m++].value = oSelect[0].value;
			}
		}

		this.__cascadingParameter[counter] = matrix;
	},

	/**
	 *	Collect parameters, include five cases appear in Birt1.0 Viewer.
	 *
	 *	@return, void
	 */
	collect_parameter : function( )
	{
		// Clear parameter array
		this.__parameter = new Array( );

		var k = 0;
		//oTRC[i] is

 section
		var oTRC = document.getElementById( "parameter_table" ).getElementsByTagName( "TR" );
		for( var i = 0; i < oTRC.length; i++ )
		{
			if( !this.__parameter[k] )
			{
				this.__parameter[k] = { };
			}

			//input element collection
			var oIEC = oTRC[i].getElementsByTagName( "input" );
			//select element collection
			var oSEC = oTRC[i].getElementsByTagName( "select" );
			//avoid group parameter
			var oTable = oTRC[i].getElementsByTagName( "table" );
			if( oTable.length > 0 || ( oSEC.length == 0 && oIEC.length == 0 ) || ( oIEC.length == 1 && oIEC[0].type == 'submit' ) )
			{
				continue;
			}

			if( oSEC.length == 1 && oIEC.length <= 3 )
			{
				// Check if select 'Null Value' option
				var temp = oSEC[0].options[oSEC[0].selectedIndex].text;
				if( temp && temp == 'Null Value' )
				{
					this.__parameter[k].name = this.__isnull;
					if ( oIEC.length > 0 )
						this.__parameter[k].value = oIEC[0].name;
					else
						this.__parameter[k].value = oSEC[0].name;
					k++;
					continue;
				}

				// deal with "select" parameter
				if( oIEC.length > 0 )
				{
					this.__parameter[k].name = oIEC[0].name;
				}
				else
				{
					this.__parameter[k].name = oSEC[0].name;
				}
				this.__parameter[k].value = oSEC[0].options[oSEC[0].selectedIndex].value;
				k++;
			}

			if( oSEC.length == 0 && ( oIEC.length == 1 || oIEC.length == 2 ) )
			{
				var temp = {};
				var tempDef = null;
				if( oIEC.length == 1 )
				{
					temp = oIEC[0]
				}
				else if( oIEC[0].type == 'hidden' )
				{
					tempDef = oIEC[0]
					temp = oIEC[1];
				}
				else
				{
					continue;
				}

				if( temp.type == 'text' || temp.type == 'password' )
				{
					// deal with "text" parameter
					this.__parameter[k].name = temp.name;
					// if the parameter neither has a value nor a default value, error
					if( birtUtility.trim( temp.value ) == '' )
					{
						if( tempDef )
						{
							temp.focus( );
							alert( temp.name + ' cannot be blank' );
							return false;
						}
						else
						{
							this.__parameter[k].value = temp.value;
						}
					}
					else
					{
						this.__parameter[k].value = temp.value;
					}
					k++;
				}
				else if( temp.type == 'checkbox' )
				{
					// deal with checkbox
					this.__parameter[k].name = temp.value;
					temp.checked?this.__parameter[k].value = 'true':this.__parameter[k].value = 'false';
					k++;
				}
				else
				{
					//handle more cases
				}
			}
			else if( oSEC.length <= 1 && oIEC.length > 3 )
			{
				for( var j = 0; j < oIEC.length; j++ )
				{
					// deal with radio
					if( oIEC[j].type == 'radio' && oIEC[j].checked )
					{
						if( oIEC[j+1] && ( oIEC[j+1].type == 'text' || oIEC[j+1].type == 'password' ) )
						{
							//Check if allow blank
							var temp = oIEC[j+2];
							if ( temp && temp.id == 'isNotBlank' && temp.value == 'true' )
							{
								if ( birtUtility.trim( oIEC[j+1].value ) == '' )
								{
									oIEC[j+1].focus( );
									alert( temp.name + ' cannot be blank' );
									return false;
								}
							}

							// deal with radio box with textarea or password area
							if( oIEC[j+1].name && oIEC[j+1].value )
							{
								this.__parameter[k].name = oIEC[j+1].name
								this.__parameter[k].value = oIEC[j+1].value;
								k++;
							}
							else
							{
								this.__parameter[k].name = oIEC[j].value
								this.__parameter[k].value = oIEC[j+1].value;
								//oIEC[j+1].value = "";
								k++;
							}
						}
						else if( oSEC[0] )
						{
							// deal with "select" parameter
							if ( oSEC[0].selectedIndex == -1 )
							{
								oSEC[0].focus( );
								alert( oIEC[j].value + " should have a value" );
								return false;
							}

							var temp = oSEC[0].options[oSEC[0].selectedIndex].text;
							if ( !temp )
							{
								oSEC[0].focus( );
								alert( oIEC[j].value + " should have a value" );
								return false;
							}

							// Check if select 'Null Value' option
							if( temp && temp != 'Null Value' )
							{
								this.__parameter[k].name = oIEC[j].value;
								this.__parameter[k].value = oSEC[0].options[oSEC[0].selectedIndex].value;
								k++;
							}
							else
							{
								this.__parameter[k].name = this.__isnull;
								this.__parameter[k].value = oIEC[j].value;
								k++;
							}
						}
						else if( !oIEC[j+1] && !oIEC[j].name )
						{
							//deal with common radio with null value
							this.__parameter[k].name = this.__isnull;
							this.__parameter[k].value = oIEC[j-1].name;
							k++;
						}
						else
						{
							//deal with common radio
							this.__parameter[k].name = oIEC[j].name;
							this.__parameter[k].value = oIEC[j].value;
							k++;
						}
					}
				}
			}
		}
		return true;
	},

	/**
	 *	Handle clicking on okRun.
	 *
	 *	@event, incoming browser native event
	 *	@return, void
	 */
	__okPress : function( )
	{
		if( birtParameterDialog.collect_parameter( ) )
		{
			if ( this.__mode == 'parameter' )
			{
				birtEventDispatcher.broadcastEvent( birtEvent.__E_CACHE_PARAMETER );
			}
			else if ( this.__mode == 'run' )
			{
				this.__doSubmit( );
			}
			else
			{
				birtEventDispatcher.broadcastEvent( birtEvent.__E_CHANGE_PARAMETER );
				this.__l_hide( );
			}
		}
	},

	/**
	 *	Override cancel button click.
	 */
	__neh_cancel : function( )
	{
		if ( this.__mode == 'parameter' )
		{
			this.__cancel();
		}
		else
		{
			this.__l_hide( );
		}
	},

	/**
	 *	Handle submit form with current parameters.
	 *
	 *	@return, void
	 */
	__doSubmit : function( )
	{
		var action = window.location.href;

		var divObj = document.createElement( "DIV" );
		document.body.appendChild( divObj );
		divObj.style.display = "none";

		var formObj = document.createElement( "FORM" );
		divObj.appendChild( formObj );

		if ( this.__parameter != null )
		{
			for( var i = 0; i < this.__parameter.length; i++ )
			{
				var param = document.createElement( "INPUT" );
				formObj.appendChild( param );
				param.TYPE = "HIDDEN";
				param.name = this.__parameter[i].name;
				param.value = this.__parameter[i].value;

				//replace the URL parameter
				var reg = new RegExp( "&" + param.name + "[^&]*&*", "g" );
				action = action.replace( reg, "&" );
			}
		}

		formObj.action = action;
		formObj.method = "post";

		this.__l_hide( );
		formObj.submit( );
	},

	/**
	 *	Caching parameters success, close window.
	 *
	 *	@return, void
	 */
	__close : function( )
	{
		if ( BrowserUtility.__isIE( ) )
		{
			window.opener = null;
			window.close( );
		}
		else
		{
			window.status = "close";
		}
	},

	/**
	 *	Click 'Cancel', close window.
	 *
	 *	@return, void
	 */
	__cancel : function( )
	{
		window.status = "cancel";
	},

	/**
	Called right before element is shown
	*/
	__preShow: function()
	{
		// disable the toolbar buttons
		birtUtility.setButtonsDisabled ( "toolbar", true );

		// disable the Navigation Bar buttons
		birtUtility.setButtonsDisabled ( "navigationBar", true );
	},

	/**
	Called before element is hidden
	*/
	__preHide: function()
	{
		// enable the toolbar buttons
		birtUtility.setButtonsDisabled ( "toolbar", false );

		// enable the Navigation Bar buttons
		birtUtility.setButtonsDisabled ( "navigationBar", false );
	}
}
);<|endoftext|>


<commit_before>import { resolve } from 'rsvp';
import Service from '@ember/service';
import { module, test } from 'qunit';
import { setupRenderingTest } from 'ember-qunit';
import { render, find, findAll, fillIn } from '@ember/test-helpers';
import hbs from 'htmlbars-inline-precompile';
import setupMirage from 'ember-cli-mirage/test-support/setup-mirage';

module('Integration | Component | ilios users', function(hooks) {
  setupRenderingTest(hooks);
  setupMirage(hooks);

  test('it renders', async function(assert) {
    const title = '.users .title';
    await render(hbs`<IliosUsers />`);
    assert.dom(title).hasText('Users');
  });

  test('param passing', async function(assert) {
    assert.expect(2);

    const query = '.user-search input';
    const value = 'nothing';
    this.set('value', value);
    await render(hbs`<IliosUsers
      @query={{value}}
      @limit={{25}}
      @offset={{25}}
      @setQuery={{action (mut value) value="target.value"}}
    />`);

    assert.equal(find(query).value.trim(), 'nothing');
    await fillIn(query, 'test');
    assert.equal(this.get('value'), 'test');
  });

  test('add user form renders when configured to', async function(assert) {
    assert.expect(4);
    const { apiVersion } = this.owner.resolveRegistration('config:environment');
    assert.ok(apiVersion);
    this.server.get('application/config', function() {
      return { config: {
        type: 'form',
        userSearchType: 'form',
        apiVersion
      }};
    });
    const school = this.server.create('school');
    const user = this.server.create('user', {
      school
    });
    const userModel = await this.owner.lookup('service:store').find('user', user.id);

    const currentUserMock = Service.extend({
      model: resolve(userModel),
      getRolesInSchool() {
        return [];
      }
    });
    this.owner.register('service:currentUser', currentUserMock);

    this.set('nothing', parseInt);
    await render(hbs`<IliosUsers
      @setShowNewUserForm={{action nothing}}
      @transitionToUser={{action nothing}}
      @setSearchTerms={{action nothing}}
      @showNewUserForm={{true}}
    />`);
    const form = '.new-user-form';
    const blocks = `${form} .item`;
    const directorySearchBox = '.new-directory-user-search-tools';
    assert.dom(form).exists({ count: 1 }, 'the user search form is present');
    assert.ok(findAll(blocks).length > 4, 'there are many form fields for adding a new user');
    assert.dom(directorySearchBox).doesNotExist('the directory form search form is not present');
  });

  test('directory search renders when configured to', async function(assert) {
    assert.expect(4);
    const { apiVersion } = this.owner.resolveRegistration('config:environment');
    assert.ok(apiVersion);
    this.server.get('application/config', function() {
      return { config: {
        type: 'form',
        userSearchType: 'ldap',
        apiVersion
      }};
    });

    const school = this.server.create('school');
    const user = this.server.create('user', {
      school
    });
    const userModel = await this.owner.lookup('service:store').find('user', user.id);

    const currentUserMock = Service.extend({
      model: resolve(userModel),
      getRolesInSchool() {
        return [];
      }
    });
    this.owner.register('service:currentUser', currentUserMock);

    this.set('nothing', parseInt);

    await render(hbs`<IliosUsers
      @setShowNewUserForm={{action nothing}}
      @transitionToUser={{action nothing}}
      @setSearchTerms={{action nothing}}
      @showNewUserForm={{true}}
    />`);
    const form = '.new-user-form';
    const blocks = `${form} .item`;
    const directorySearchBox = '.new-directory-user-search-tools';
    assert.dom(form).doesNotExist('the user search form is not present');
    assert.dom(blocks).doesNotExist('there are no form fields for adding a new user');
    assert.dom(directorySearchBox).exists({ count: 1 }, 'the directory form search form is present');
  });
});
<commit_msg>updates test coverage.<commit_after>import { resolve } from 'rsvp';
import Service from '@ember/service';
import { module, test } from 'qunit';
import { setupRenderingTest } from 'ember-qunit';
import { render, find, findAll, fillIn } from '@ember/test-helpers';
import hbs from 'htmlbars-inline-precompile';
import setupMirage from 'ember-cli-mirage/test-support/setup-mirage';

module('Integration | Component | ilios users', function(hooks) {
  setupRenderingTest(hooks);
  setupMirage(hooks);

  test('it renders', async function(assert) {
    const title = '.users .title';
    await render(hbs`<IliosUsers
      @limit=25
      @offset=25
      @query=""
      @searchTerms={{array}}
      @setQuery={{noop}}
      @setLimit={{noop}}
      @setOffset={{noop}}
      @setShowNewUserForm={{noop}}
      @setShowBulkNewUserForm={{noop}}
      @setSearchTerms={{noop}}
      @transitionToUser={{noop}}
    />`);
    assert.dom(title).hasText('Users');
  });

  test('param passing', async function(assert) {
    assert.expect(2);

    const query = '.user-search input';
    const value = 'nothing';
    const newValue = 'test';
    this.set('value', value);
    this.set('setQuery', query => {
      assert.equal(query, newValue);
    });
    await render(hbs`<IliosUsers
      @limit=25
      @offset=25
      @query={{this.value}}
      @searchTerms={{array}}
      @setQuery={{this.setQuery}}
      @setLimit={{noop}}
      @setOffset={{noop}}
      @setShowNewUserForm={{noop}}
      @setShowBulkNewUserForm={{noop}}
      @setSearchTerms={{noop}}
      @transitionToUser={{noop}}
    />`);

    assert.equal(find(query).value.trim(), value);
    await fillIn(query, newValue);
  });

  test('add user form renders when configured to', async function(assert) {
    assert.expect(4);
    const { apiVersion } = this.owner.resolveRegistration('config:environment');
    assert.ok(apiVersion);
    this.server.get('application/config', function() {
      return { config: {
        type: 'form',
        userSearchType: 'form',
        apiVersion
      }};
    });
    const school = this.server.create('school');
    const user = this.server.create('user', {
      school
    });
    const userModel = await this.owner.lookup('service:store').find('user', user.id);

    const currentUserMock = Service.extend({
      model: resolve(userModel),
      getRolesInSchool() {
        return [];
      }
    });
    this.owner.register('service:currentUser', currentUserMock);
    await render(hbs`<IliosUsers
      @showNewUserForm={{true}}
      @searchTerms={{array}}
      @setQuery={{noop}}
      @setLimit={{noop}}
      @setOffset={{noop}}
      @setShowNewUserForm={{noop}}
      @setShowBulkNewUserForm={{noop}}
      @setSearchTerms={{noop}}
      @transitionToUser={{noop}}
    />`);
    const form = '.new-user-form';
    const blocks = `${form} .item`;
    const directorySearchBox = '.new-directory-user-search-tools';
    assert.dom(form).exists({ count: 1 }, 'the user search form is present');
    assert.ok(findAll(blocks).length > 4, 'there are many form fields for adding a new user');
    assert.dom(directorySearchBox).doesNotExist('the directory form search form is not present');
  });

  test('directory search renders when configured to', async function(assert) {
    assert.expect(4);
    const { apiVersion } = this.owner.resolveRegistration('config:environment');
    assert.ok(apiVersion);
    this.server.get('application/config', function() {
      return { config: {
        type: 'form',
        userSearchType: 'ldap',
        apiVersion
      }};
    });

    const school = this.server.create('school');
    const user = this.server.create('user', {
      school
    });
    const userModel = await this.owner.lookup('service:store').find('user', user.id);

    const currentUserMock = Service.extend({
      model: resolve(userModel),
      getRolesInSchool() {
        return [];
      }
    });
    this.owner.register('service:currentUser', currentUserMock);

    this.set('nothing', parseInt);

    await render(hbs`<IliosUsers
      @showNewUserForm={{true}}
      @searchTerms={{array}}
      @setQuery={{noop}}
      @setLimit={{noop}}
      @setOffset={{noop}}
      @setShowNewUserForm={{noop}}
      @setShowBulkNewUserForm={{noop}}
      @setSearchTerms={{noop}}
      @transitionToUser={{noop}}
    />`);
    const form = '.new-user-form';
    const blocks = `${form} .item`;
    const directorySearchBox = '.new-directory-user-search-tools';
    assert.dom(form).doesNotExist('the user search form is not present');
    assert.dom(blocks).doesNotExist('there are no form fields for adding a new user');
    assert.dom(directorySearchBox).exists({ count: 1 }, 'the directory form search form is present');
  });
});
<|endoftext|>


<commit_before>//  Geometries
Map.setCenter(-88, 41.8, 9)
function multi(feature){
  //  Reduce number of vertices in geometry; the number is to specify maximum error in meters
  var simple = feature.simplify(1000);
  //  Find centroid of geometry
  var center = simple.centroid();
  //  Create buffer around geometry; the number represents the width of buffer in meters
  var buff = center.buffer(500);
  //  return variable from function
  return buff}
//  Load Feature Collection of the dissolved boundary of Chicago stored in assets
var Chic=ee.FeatureCollection('users/tirthankar25/chicago_diss');
//  Load Feature Collection of the neighborhood-scale Chicago data stored in assets
//  var Chic_coll=ee.FeatureCollection('users/tirthankar25/chicago');
//  Map function over Feature Collection
//  var Res=Chic_coll.map(multi);
//  Add the layer to the map
// Map.addLayer(Res)
Map.addLayer(Chic, {},'Chicago dissolved')
//  Find the rectangle that emcompasses the southernmost, westernmost, easternmost, and northernmost
//  points of the feature
//  var bound = Chic.geometry().bounds();
//  Find the polygon covering the extremities of the feature
//  var convex = Chic.geometry().convexHull();
//  Map.addLayer(bound, {},'Chicago bounds');
//  Map.addLayer(convex, {},'Chicago convex hull');
//  Find the area common to two or more features
//  var Intersect=bound.intersection(convex,100);
//  Map.addLayer(Intersect, {},'Bound and convex intersection');
//  Find the area encompassing two or more features; number is the maximum error in meters
//  var Union=bound.union(convex,100);
//  Map.addLayer(Union, {},'Bound and convex union');
//  Find area of feature
//  var Ar=Chic.geometry().area();
//  Find length of line geometry
//  var length=Chic.geometry().length();
//  Find permeter of feature
//  var peri=Chic.geometry().perimeter();
//  print (peri)
//  Features
//  Create Geometry
var var_Geometry=ee.Geometry.Polygon(0,0, 40,30, 20, 20, 0, 0);
//  Create Feature from Geometry
var var_Feature = ee.Feature(var_Geometry, {Name: ["Feature name","Supreme"], Size: [500, 1000]});
//  Get values of a property
//  var Arr=var_Feature.get('Size');
//  print (Arr)
//  Select a subset of properties and rename them
var var_Featurenew = var_Feature.select(["Name"], ["Descriptor"]);
print(var_Featurenew)
//  Images
Map.setCenter(-88, 41.8, 9)
var Raw = ee.ImageCollection('MODIS/006/MYD11A2');
var ROI = ee.FeatureCollection('users/tirthankar25/chicago');
print(Raw)
var bandsel=Raw.select(0)
//  var bandsel=Raw.select('LST_Day_1km')
//  var filtered=Raw.filterDate('2002-12-30','2004-4-27');
//  print(filtered)
//  var limited=Raw.limit(50);
//  print(limited)
//  print(bandsel)
var mean=bandsel.mean();
Map.addLayer(mean);
//  var clipped=mean.clip(ROI);
//  var calculate=clipped.multiply(.02).subtract(273.15);
//  Map.addLayer(calculate,{min: 30, max: 40, palette: ['blue', 'green', 'red']},'LST')
//  var mask=calculate.gt(30.8)
//  Map.addLayer(mask,{},"mask")
//  var Masked=clipped.mask(mask)
//  Map.addLayer(Masked,{min: 20, max: 30, palette: ['blue', 'green', 'red']},'LST_masked')
//  var filtered=Raw.filterDate('2002-12-30','2004-4-27');
//  print(filtered)
//  Image to table example
var urban=ee.FeatureCollection('users/tirthankar25/chicago');
//  Function to find mean of pixels in region of interest
var regions = function(image){ return image.reduceRegions({collection: urban, reducer: ee.Reducer.mean(), scale: 1000, }); }
//  Load image
var image=ee.ImageCollection('MODIS/MYD13A1').filterDate('2002-07-08', '2017-07-08').mean().select("NDVI");
print(image)
//  .select("Albedo_BSA_shortwave").multiply(.001)
//  .select('avg_rad')
//  .select('cf_cvg')
//  .select('ET').multiply(.1)
var Final = regions(image);
//  var Final=Final.select(['mean','nbhd_code', 'nbhd'],['Albedo','nbhd_code', 'nbhd']);
//  Export image
Export.table.toDrive({
collection: Final,  description: 'NDVI_all',  fileFormat: 'CSV'});
//  Timelapse example (based on google API example)
var TheGEOMETRY = ee.Geometry.Rectangle([55.1, 25, 55.4, 25.4]);
Map.addLayer(TheGEOMETRY)
var AllIMAGES   = ee.ImageCollection('LANDSAT/LT05/C01/T1_TOA')
//  Filter row and path such that they cover Dubai.
.filter(ee.Filter.eq('WRS_PATH', 160))
  .filter(ee.Filter.eq('WRS_ROW', 43))
   // Filter cloudy scenes
  .filter(ee.Filter.lt('CLOUD_COVER', 30))
  // Get required years of imagery.
  .filterDate('1984-01-01','2012-12-30')
  // Select 3-band imagery for the video.
  .select(['B4', 'B3', 'B2'])
  //  Make the data 8 bit
  .map(function(image) {
  return image.multiply(512).uint8()});
Export.video.toDrive({
  collection: AllIMAGES,
  //  Name of file
  description: 'Dubai_timelapse',
  //  Quality of video
  dimensions: 720,
  //  FPS of video
  framesPerSecond: 8,
  //  Region of export
  region: TheGEOMETRY});
<commit_msg>Update Sample.js<commit_after>//  Geometries
Map.setCenter(-88, 41.8, 9);
function multi(feature){
  //  Reduce number of vertices in geometry; the number is to specify maximum error in meters
  var simple = feature.simplify(1000);
  //  Find centroid of geometry
  var center = simple.centroid();
  //  Create buffer around geometry; the number represents the width of buffer in meters
  var buff = center.buffer(500);
  //  return variable from function
  return buff}
//  Load Feature Collection of the dissolved boundary of Chicago stored in assets
var Chic=ee.FeatureCollection('users/tirthankar25/chicago_diss');
//  Load Feature Collection of the neighborhood-scale Chicago data stored in assets
//  var Chic_coll=ee.FeatureCollection('users/tirthankar25/chicago');
//  Map function over Feature Collection
//  var Res=Chic_coll.map(multi);
//  Add the layer to the map
// Map.addLayer(Res);
Map.addLayer(Chic, {},'Chicago dissolved');
//  Find the rectangle that emcompasses the southernmost, westernmost, easternmost, and northernmost
//  points of the feature
//  var bound = Chic.geometry().bounds();
//  Find the polygon covering the extremities of the feature
//  var convex = Chic.geometry().convexHull();
//  Map.addLayer(bound, {},'Chicago bounds');
//  Map.addLayer(convex, {},'Chicago convex hull');
//  Find the area common to two or more features
//  var Intersect=bound.intersection(convex,100);
//  Map.addLayer(Intersect, {},'Bound and convex intersection');
//  Find the area encompassing two or more features; number is the maximum error in meters
//  var Union=bound.union(convex,100);
//  Map.addLayer(Union, {},'Bound and convex union');
//  Find area of feature
//  var Ar=Chic.geometry().area();
//  Find length of line geometry
//  var length=Chic.geometry().length();
//  Find permeter of feature
//  var peri=Chic.geometry().perimeter();
//  print (peri)
//  Features
//  Create Geometry
var var_Geometry=ee.Geometry.Polygon(0,0, 40,30, 20, 20, 0, 0);
//  Create Feature from Geometry
var var_Feature = ee.Feature(var_Geometry, {Name: ["Feature name","Supreme"], Size: [500, 1000]});
//  Get values of a property
//  var Arr=var_Feature.get('Size');
//  print (Arr);
//  Select a subset of properties and rename them
var var_Featurenew = var_Feature.select(["Name"], ["Descriptor"]);
print(var_Featurenew)
//  Images
Map.setCenter(-88, 41.8, 9);
var Raw = ee.ImageCollection('MODIS/006/MYD11A2');
var ROI = ee.FeatureCollection('users/tirthankar25/chicago');
print(Raw);
var bandsel=Raw.select(0);
//  var bandsel=Raw.select('LST_Day_1km');
//  var filtered=Raw.filterDate('2002-12-30','2004-4-27');
//  print(filtered);
//  var limited=Raw.limit(50);
//  print(limited);
//  print(bandsel);
var mean=bandsel.mean();
Map.addLayer(mean);
//  var clipped=mean.clip(ROI);
//  var calculate=clipped.multiply(.02).subtract(273.15);
//  Map.addLayer(calculate,{min: 30, max: 40, palette: ['blue', 'green', 'red']},'LST');
//  var mask=calculate.gt(30.8);
//  Map.addLayer(mask,{},"mask");
//  var Masked=clipped.mask(mask);
//  Map.addLayer(Masked,{min: 20, max: 30, palette: ['blue', 'green', 'red']},'LST_masked');
//  var filtered=Raw.filterDate('2002-12-30','2004-4-27');
//  print(filtered);
//  Image to table example
var urban=ee.FeatureCollection('users/tirthankar25/chicago');
//  Function to find mean of pixels in region of interest
var regions = function(image){ return image.reduceRegions({collection: urban, reducer: ee.Reducer.mean(), scale: 1000, }); };
//  Load image
var image=ee.ImageCollection('MODIS/MYD13A1').filterDate('2002-07-08', '2017-07-08').mean().select("NDVI");
print(image)
//  .select("Albedo_BSA_shortwave").multiply(.001);
//  .select('avg_rad');
//  .select('cf_cvg');
//  .select('ET').multiply(.1);
var Final = regions(image);
//  var Final=Final.select(['mean','nbhd_code', 'nbhd'],['Albedo','nbhd_code', 'nbhd']);
//  Export image
Export.table.toDrive({
collection: Final,  description: 'NDVI_all',  fileFormat: 'CSV'});
//  Timelapse example (based on google API example);
var TheGEOMETRY = ee.Geometry.Rectangle([55.1, 25, 55.4, 25.4]);
Map.addLayer(TheGEOMETRY);
var AllIMAGES   = ee.ImageCollection('LANDSAT/LT05/C01/T1_TOA')
//  Filter row and path such that they cover Dubai.
.filter(ee.Filter.eq('WRS_PATH', 160))
  .filter(ee.Filter.eq('WRS_ROW', 43))
   // Filter cloudy scenes
  .filter(ee.Filter.lt('CLOUD_COVER', 30))
  // Get required years of imagery.
  .filterDate('1984-01-01','2012-12-30')
  // Select 3-band imagery for the video.
  .select(['B4', 'B3', 'B2'])
  //  Make the data 8 bit
  .map(function(image) {
  return image.multiply(512).uint8()});
Export.video.toDrive({
  collection: AllIMAGES,
  //  Name of file
  description: 'Dubai_timelapse',
  //  Quality of video
  dimensions: 720,
  //  FPS of video
  framesPerSecond: 8,
  //  Region of export
  region: TheGEOMETRY});
<|endoftext|>


<commit_before>import React, {Component, PropTypes} from 'react'
import {connect} from 'react-redux'
import {bindActionCreators} from 'redux'

import DatabaseDropdown from 'shared/components/DatabaseDropdown'

import {writeData} from 'src/data_explorer/apis'
import {publishAutoDismissingNotification} from 'shared/dispatchers'
import {errorThrown as errorThrownAction} from 'shared/actions/errors'

class WriteDataForm extends Component {
  constructor(props) {
    super(props)
    this.state = {
      selectedDatabase: null,
    }

    this.handleSelectDatabase = ::this.handleSelectDatabase
    this.handleStartEdit = ::this.handleStartEdit
    this.handleError = ::this.handleError
    this.handleWrite = ::this.handleWrite
  }

  handleSelectDatabase(item) {
    this.setState({selectedDatabase: item.text})
  }

  handleStartEdit() {}

  handleError(error) {
    const {errorThrown} = this.props
    errorThrown(error)
  }

  handleWrite() {
    const {onClose, source, notify} = this.props
    const {selectedDatabase} = this.state
    writeData(source, selectedDatabase, this.editor.value).then(() => {
      notify('success', 'Data was written successfully')
      onClose()
    })
  }

  render() {
    const {onClose} = this.props
    const {selectedDatabase} = this.state

    return (

Write Data To

            <DatabaseDropdown
              onSelectDatabase={this.handleSelectDatabase}
              database={selectedDatabase}
              onStartEdit={this.handleStartEdit}
              onErrorThrown={this.handleError}
            />

          <textarea
            className="query-editor--field"
            autoComplete="off"
            spellCheck="false"
            placeholder="<tag_key>=<tag_value>,<tag_key>=<tag_value>"
            ref={editor => this.editor = editor}
          />

            Uses InfluxDB Line Protocol -

              Docs

            <button className="btn btn-primary" onClick={this.handleWrite}>
              Write
            </button>

    )
  }
}

const {func, shape, string} = PropTypes

WriteDataForm.propTypes = {
  source: shape({
    links: shape({
      proxy: string.isRequired,
      self: string.isRequired,
      queries: string.isRequired,
    }).isRequired,
  }).isRequired,
  notify: func.isRequired,
  errorThrown: func.isRequired,
  onClose: func.isRequired,
}

const mapDispatchToProps = dispatch => ({
  notify: bindActionCreators(publishAutoDismissingNotification, dispatch),
  errorThrown: bindActionCreators(errorThrownAction, dispatch),
})

export default connect(null, mapDispatchToProps)(WriteDataForm)
<commit_msg>remove unused method<commit_after>import React, {Component, PropTypes} from 'react'
import {connect} from 'react-redux'
import {bindActionCreators} from 'redux'

import DatabaseDropdown from 'shared/components/DatabaseDropdown'

import {writeData} from 'src/data_explorer/apis'
import {publishAutoDismissingNotification} from 'shared/dispatchers'
import {errorThrown as errorThrownAction} from 'shared/actions/errors'

class WriteDataForm extends Component {
  constructor(props) {
    super(props)
    this.state = {
      selectedDatabase: null,
    }

    this.handleSelectDatabase = ::this.handleSelectDatabase
    this.handleError = ::this.handleError
    this.handleWrite = ::this.handleWrite
  }

  handleSelectDatabase(item) {
    this.setState({selectedDatabase: item.text})
  }

  handleError(error) {
    const {errorThrown} = this.props
    errorThrown(error)
  }

  handleWrite() {
    const {onClose, source, notify} = this.props
    const {selectedDatabase} = this.state
    writeData(source, selectedDatabase, this.editor.value).then(() => {
      notify('success', 'Data was written successfully')
      onClose()
    })
  }

  render() {
    const {onClose} = this.props
    const {selectedDatabase} = this.state

    return (

Write Data To

            <DatabaseDropdown
              onSelectDatabase={this.handleSelectDatabase}
              database={selectedDatabase}
              onStartEdit={() => {}}
              onErrorThrown={this.handleError}
            />

          <textarea
            className="query-editor--field"
            autoComplete="off"
            spellCheck="false"
            placeholder="<tag_key>=<tag_value>,<tag_key>=<tag_value>"
            ref={editor => this.editor = editor}
          />

            Uses InfluxDB Line Protocol -

              Docs

            <button className="btn btn-primary" onClick={this.handleWrite}>
              Write
            </button>

    )
  }
}

const {func, shape, string} = PropTypes

WriteDataForm.propTypes = {
  source: shape({
    links: shape({
      proxy: string.isRequired,
      self: string.isRequired,
      queries: string.isRequired,
    }).isRequired,
  }).isRequired,
  notify: func.isRequired,
  errorThrown: func.isRequired,
  onClose: func.isRequired,
}

const mapDispatchToProps = dispatch => ({
  notify: bindActionCreators(publishAutoDismissingNotification, dispatch),
  errorThrown: bindActionCreators(errorThrownAction, dispatch),
})

export default connect(null, mapDispatchToProps)(WriteDataForm)
<|endoftext|>


<commit_before>var _ = require('underscore');
var Backbone = require('backbone');
var LegendDefinitionsCollection = require('../../../../../../../javascripts/cartodb3/data/legends/legend-definitions-collection');
var LayerDefinitionModel = require('../../../../../../../javascripts/cartodb3/data/layer-definition-model');
var LegendFactory = require('../../../../../../../javascripts/cartodb3/editor/layers/layer-content-views/legend/legend-factory');
var ConfigModel = require('../../../../../../../javascripts/cartodb3/data/config-model');
var Validations = require('../../../../../../../javascripts/cartodb3/editor/layers/layer-content-views/legend/legend-validations');

function getSuccessResponse (id, type) {
  var success = _.clone(TestResponses.save.success);
  success.responseText = _.template(success.responseText)({
    id: id,
    type: type
  });

  return success;
}

var TestResponses = {
  save: {
    success: {
      'status': '200',
      'content-type': 'application/json',
      responseText: '{"created_at":"2016-09-30T07:57:15+00:00","id":"<%= id %>","layer_id":"l-1","title":"","type":"<%= type %>","definition": {"color":"#fabada", "prefix":"", "suffix": "" }}'
    }
  },
  destroy: {
    success: {
      status: 204
    }
  }
};

describe('editor/layers/layer-content-view/legend/legend-factory', function () {
  beforeEach(function () {
    jasmine.Ajax.install();

    this.configModel = new ConfigModel({
      base_url: '/u/pepe'
    });

    this.layerDefinitionModel = new LayerDefinitionModel({
      id: 'l-1',
      fetched: true,
      options: {
        type: 'CartoDB',
        table_name: 'foo',
        cartocss: 'asd',
        source: 'a0'
      }
    }, {
      parse: true,
      configModel: this.configModel
    });

    this.layerDefinitionsCollection = new Backbone.Collection();
    this.layerDefinitionsCollection.add(this.layerDefinitionModel);

    this.legendDefinitionsCollection = new LegendDefinitionsCollection([], {
      layerDefinitionsCollection: this.layerDefinitionsCollection,
      configModel: this.configModel,
      vizId: 'v-123'
    });

    spyOn(Validations, 'bubble').and.returnValue(true);
    spyOn(Validations, 'choropleth').and.returnValue(true);
    spyOn(Validations, 'category').and.returnValue(true);

    LegendFactory.init(this.legendDefinitionsCollection);
  });

  afterEach(function () {
    jasmine.Ajax.uninstall();
  });

  it('create legend', function () {
    LegendFactory.createLegend(this.layerDefinitionModel, 'bubble');
    jasmine.Ajax.requests.mostRecent().respondWith(getSuccessResponse(1, 'bubble'));

    LegendFactory.createLegend(this.layerDefinitionModel, 'choropleth');
    jasmine.Ajax.requests.mostRecent().respondWith(getSuccessResponse(2, 'choropleth'));

    LegendFactory.createLegend(this.layerDefinitionModel, 'category');
    jasmine.Ajax.requests.mostRecent().respondWith(getSuccessResponse(3, 'category'));

    expect(this.legendDefinitionsCollection.length).toBe(3);
    expect(this.legendDefinitionsCollection.at(0).get('type')).toBe('bubble');
    expect(this.legendDefinitionsCollection.at(1).get('type')).toBe('choropleth');
    expect(this.legendDefinitionsCollection.at(2).get('type')).toBe('category');
  });

  it('remove legend', function () {
    LegendFactory.createLegend(this.layerDefinitionModel, 'bubble');
    jasmine.Ajax.requests.mostRecent().respondWith(getSuccessResponse(1, 'bubble'));

    LegendFactory.createLegend(this.layerDefinitionModel, 'choropleth');
    jasmine.Ajax.requests.mostRecent().respondWith(getSuccessResponse(2, 'choropleth'));

    LegendFactory.createLegend(this.layerDefinitionModel, 'category');
    jasmine.Ajax.requests.mostRecent().respondWith(getSuccessResponse(3, 'category'));

    LegendFactory.removeLegend(this.layerDefinitionModel, 'bubble');
    jasmine.Ajax.requests.mostRecent().respondWith(TestResponses.destroy.success);

    expect(this.legendDefinitionsCollection.length).toBe(2);
    expect(this.legendDefinitionsCollection.at(0).get('type')).toBe('choropleth');
    expect(this.legendDefinitionsCollection.at(1).get('type')).toBe('category');
  });

  it('remove all legends', function () {
    LegendFactory.createLegend(this.layerDefinitionModel, 'bubble');
    jasmine.Ajax.requests.mostRecent().respondWith(getSuccessResponse(1, 'bubble'));

    LegendFactory.createLegend(this.layerDefinitionModel, 'choropleth');
    jasmine.Ajax.requests.mostRecent().respondWith(getSuccessResponse(2, 'choropleth'));

    LegendFactory.createLegend(this.layerDefinitionModel, 'category');
    jasmine.Ajax.requests.mostRecent().respondWith(getSuccessResponse(3, 'category'));

    LegendFactory.removeAllLegend(this.layerDefinitionModel);
    expect(this.legendDefinitionsCollection.length).toBe(0);
  });
});
<commit_msg>Tests.<commit_after>var _ = require('underscore');
var Backbone = require('backbone');
var LegendDefinitionsCollection = require('../../../../../../../javascripts/cartodb3/data/legends/legend-definitions-collection');
var LayerDefinitionModel = require('../../../../../../../javascripts/cartodb3/data/layer-definition-model');
var LegendFactory = require('../../../../../../../javascripts/cartodb3/editor/layers/layer-content-views/legend/legend-factory');
var ConfigModel = require('../../../../../../../javascripts/cartodb3/data/config-model');
var Validations = require('../../../../../../../javascripts/cartodb3/editor/layers/layer-content-views/legend/legend-validations');

function getSuccessResponse (id, type, title) {
  var success = _.clone(TestResponses.save.success);
  success.responseText = _.template(success.responseText)({
    id: id,
    type: type,
    title: title || ''
  });

  return success;
}

var TestResponses = {
  save: {
    success: {
      'status': '200',
      'content-type': 'application/json',
      responseText: '{"created_at":"2016-09-30T07:57:15+00:00","id":"<%= id %>","layer_id":"l-1","title":"<%= title %>","type":"<%= type %>","definition": {"color":"#fabada", "prefix":"", "suffix": "" }}'
    }
  },
  destroy: {
    success: {
      status: 204
    }
  }
};

describe('editor/layers/layer-content-view/legend/legend-factory', function () {
  beforeEach(function () {
    jasmine.Ajax.install();

    this.configModel = new ConfigModel({
      base_url: '/u/pepe'
    });

    this.layerDefinitionModel = new LayerDefinitionModel({
      id: 'l-1',
      fetched: true,
      options: {
        type: 'CartoDB',
        table_name: 'foo',
        cartocss: 'asd',
        source: 'a0'
      }
    }, {
      parse: true,
      configModel: this.configModel
    });

    this.layerDefinitionsCollection = new Backbone.Collection();
    this.layerDefinitionsCollection.add(this.layerDefinitionModel);

    this.legendDefinitionsCollection = new LegendDefinitionsCollection([], {
      layerDefinitionsCollection: this.layerDefinitionsCollection,
      configModel: this.configModel,
      vizId: 'v-123'
    });

    spyOn(Validations, 'bubble').and.returnValue(true);
    spyOn(Validations, 'choropleth').and.returnValue(true);
    spyOn(Validations, 'category').and.returnValue(true);

    LegendFactory.init(this.legendDefinitionsCollection);
  });

  afterEach(function () {
    jasmine.Ajax.uninstall();
  });

  it('create legend', function () {
    LegendFactory.createLegend(this.layerDefinitionModel, 'bubble');
    jasmine.Ajax.requests.mostRecent().respondWith(getSuccessResponse(1, 'bubble'));

    LegendFactory.createLegend(this.layerDefinitionModel, 'choropleth');
    jasmine.Ajax.requests.mostRecent().respondWith(getSuccessResponse(2, 'choropleth'));

    LegendFactory.createLegend(this.layerDefinitionModel, 'category');
    jasmine.Ajax.requests.mostRecent().respondWith(getSuccessResponse(3, 'category'));

    expect(this.legendDefinitionsCollection.length).toBe(3);
    expect(this.legendDefinitionsCollection.at(0).get('type')).toBe('bubble');
    expect(this.legendDefinitionsCollection.at(1).get('type')).toBe('choropleth');
    expect(this.legendDefinitionsCollection.at(2).get('type')).toBe('category');
  });

  it('update an existent legend', function () {
    LegendFactory.createLegend(this.layerDefinitionModel, 'bubble', {title: 'foo'});
    jasmine.Ajax.requests.mostRecent().respondWith(getSuccessResponse(1, 'bubble'));

    var model = this.legendDefinitionsCollection.findByLayerDefModelAndType(this.layerDefinitionModel, 'bubble');
    spyOn(model, 'set').and.callThrough();

    LegendFactory.createLegend(this.layerDefinitionModel, 'bubble', {title: 'bar'});
    expect(model.set).toHaveBeenCalledWith({title: 'bar'});
  });

  it('remove legend', function () {
    LegendFactory.createLegend(this.layerDefinitionModel, 'bubble');
    jasmine.Ajax.requests.mostRecent().respondWith(getSuccessResponse(1, 'bubble'));

    LegendFactory.createLegend(this.layerDefinitionModel, 'choropleth');
    jasmine.Ajax.requests.mostRecent().respondWith(getSuccessResponse(2, 'choropleth'));

    LegendFactory.createLegend(this.layerDefinitionModel, 'category');
    jasmine.Ajax.requests.mostRecent().respondWith(getSuccessResponse(3, 'category'));

    LegendFactory.removeLegend(this.layerDefinitionModel, 'bubble');
    jasmine.Ajax.requests.mostRecent().respondWith(TestResponses.destroy.success);

    expect(this.legendDefinitionsCollection.length).toBe(2);
    expect(this.legendDefinitionsCollection.at(0).get('type')).toBe('choropleth');
    expect(this.legendDefinitionsCollection.at(1).get('type')).toBe('category');
  });

  it('remove all legends', function () {
    LegendFactory.createLegend(this.layerDefinitionModel, 'bubble');
    jasmine.Ajax.requests.mostRecent().respondWith(getSuccessResponse(1, 'bubble'));

    LegendFactory.createLegend(this.layerDefinitionModel, 'choropleth');
    jasmine.Ajax.requests.mostRecent().respondWith(getSuccessResponse(2, 'choropleth'));

    LegendFactory.createLegend(this.layerDefinitionModel, 'category');
    jasmine.Ajax.requests.mostRecent().respondWith(getSuccessResponse(3, 'category'));

    LegendFactory.removeAllLegend(this.layerDefinitionModel);
    expect(this.legendDefinitionsCollection.length).toBe(0);
  });
});
<|endoftext|>