<commit_before>'use strict';

function completely(config) {
    config = config || {};
    config.confirmKeys = config.confirmKeys || [39, 35, 9] // right, end, tab
    config.caseSensitive = config.caseSensitive || false    // autocomplete case sensitive

    var fontSize = '';
    var fontFamily = '';

    var wrapper = document.createElement('div');
    wrapper.style.position = 'relative';
    wrapper.style.outline = '0';
    wrapper.style.border = '0';
    wrapper.style.margin = '0';
    wrapper.style.padding = '0';

    var dropDown = document.createElement('div');
    dropDown.className = 'autocomplete dropdown';
    dropDown.style.position = 'absolute';
    dropDown.style.visibility = 'hidden';

    var spacer;
    var leftSide; // <-- it will contain the leftSide part of the textfield (the bit that was already autocompleted)
    var createDropDownController = function (elem, rs) {
        var rows = [];
        var ix = 0;
        var oldIndex = -1;

        var onMouseOver = function () { this.style.outline = '1px solid #ddd'; }
        var onMouseOut = function () { this.style.outline = '0'; }
        var onMouseDown = function () { p.hide(); p.onmouseselection(this.__hint, p.rs); }

        var p = {
            rs: rs,
            hide: function () {
                elem.style.visibility = 'hidden';
                //rs.hideDropDown();
            },
            refresh: function (token, array) {
                elem.style.visibility = 'hidden';
                ix = 0;
                elem.innerHTML = '';
                var vph = (window.innerHeight || document.documentElement.clientHeight);
                var rect = elem.parentNode.getBoundingClientRect();
                var distanceToTop = rect.top - 6;                        // heuristic give 6px
                var distanceToBottom = vph - rect.bottom - 6;  // distance from the browser border.

                rows = [];
                for (var i = 0; i < array.length; i++) {

                    if (  (config.caseSensitive && array[i].indexOf(token) !== 0)
                        ||(!config.caseSensitive && array[i].toLowerCase().indexOf(token.toLowerCase()) !== 0)) { continue; }

                    var divRow = document.createElement('div');
                    divRow.className = 'item';
                    //divRow.style.color = config.color;
                    divRow.onmouseover = onMouseOver;
                    divRow.onmouseout = onMouseOut;
                    divRow.onmousedown = onMouseDown;
                    divRow.__hint = array[i];
                    divRow.innerHTML = token + '' + array[i].substring(token.length) + '';
                    rows.push(divRow);
                    elem.appendChild(divRow);
                }
                if (rows.length === 0) {
                    return; // nothing to show.
                }
                if (rows.length === 1 && (   (token.toLowerCase() === rows[0].__hint.toLowerCase() && !config.caseSensitive)
                                           ||(token === rows[0].__hint && config.caseSensitive))){
                    return; // do not show the dropDown if it has only one element which matches what we have just displayed.
                }

                if (rows.length < 2) return;
                p.highlight(0);

                if (distanceToTop > distanceToBottom * 3) {        // Heuristic (only when the distance to the to top is 4 times more than distance to the bottom
                    elem.style.maxHeight = distanceToTop + 'px';  // we display the dropDown on the top of the input text
                    elem.style.top = '';
                    elem.style.bottom = '100%';
                } else {
                    elem.style.top = '100%';
                    elem.style.bottom = '';
                    elem.style.maxHeight = distanceToBottom + 'px';
                }
                elem.style.visibility = 'visible';
            },
            highlight: function (index) {
                if (oldIndex != -1 && rows[oldIndex]) {
                    rows[oldIndex].className = "item";
                }
                rows[index].className = "item hover";
                oldIndex = index;
            },
            move: function (step) { // moves the selection either up or down (unless it's not possible) step is either +1 or -1.
                if (elem.style.visibility === 'hidden') return ''; // nothing to move if there is no dropDown. (this happens if the user hits escape and then down or up)
                if (ix + step === -1 || ix + step === rows.length) return rows[ix].__hint; // NO CIRCULAR SCROLLING.
                ix += step;
                p.highlight(ix);
                return rows[ix].__hint;//txtShadow.value = uRows[uIndex].__hint ;
            },
            onmouseselection: function () { } // it will be overwritten.
        };
        return p;
    }

    function setEndOfContenteditable(contentEditableElement) {
        var range, selection;
        if (document.createRange)//Firefox, Chrome, Opera, Safari, IE 9+
        {
            range = document.createRange();//Create a range (a range is a like the selection but invisible)
            range.selectNodeContents(contentEditableElement);//Select the entire contents of the element with the range
            range.collapse(false);//collapse the range to the end point. false means collapse to end rather than the start
            selection = window.getSelection();//get the selection object (allows you to change selection)
            selection.removeAllRanges();//remove any selections already made
            selection.addRange(range);//make the range you have just created the visible selection
        }
        else if (document.selection)//IE 8 and lower
        {
            range = document.body.createTextRange();//Create a range (a range is a like the selection but invisible)
            range.moveToElementText(contentEditableElement);//Select the entire contents of the element with the range
            range.collapse(false);//collapse the range to the end point. false means collapse to end rather than the start
            range.select();//Select the range (make it the visible selection
        }
    }

    function calculateWidthForText(text) {
        if (spacer === undefined) { // on first call only.
            spacer = document.createElement('span');
            spacer.style.visibility = 'hidden';
            spacer.style.position = 'fixed';
            spacer.style.outline = '0';
            spacer.style.margin = '0';
            spacer.style.padding = '0';
            spacer.style.border = '0';
            spacer.style.left = '0';
            spacer.style.whiteSpace = 'pre';
            spacer.style.fontSize = fontSize;
            spacer.style.fontFamily = fontFamily;
            spacer.style.fontWeight = 'normal';
            document.body.appendChild(spacer);
        }

        // Used to encode an HTML string into a plain text.
        // taken from http://stackoverflow.com/questions/1219860/javascript-jquery-html-encoding
        spacer.innerHTML = String(text).replace(/&/g, '&')
            .replace(/"/g, '"')
            .replace(/'/g, ''')
            .replace(/</g, '<')
            .replace(/>/g, '>');
        return spacer.getBoundingClientRect().right;
    }

    var rs = {
        onArrowDown: function () { }, // defaults to no action.
        onArrowUp: function () { },   // defaults to no action.
        onEnter: function () { },     // defaults to no action.
        onTab: function () { },       // defaults to no action.
        startFrom: 0,
        options: [],
        element: null,
        elementHint: null,
        elementStyle: null,
        wrapper: wrapper,      // Only to allow  easy access to the HTML elements to the final user (possibly for minor customizations)
        show: function (element, startPos, options) {
            this.startFrom = startPos;
            this.wrapper.remove();
            if (this.elementHint) {
                this.elementHint.remove();
                this.elementHint = null;
            }

            if (fontSize == '') {
                fontSize = window.getComputedStyle(element).getPropertyValue('font-size');
            }
            if (fontFamily == '') {
                fontFamily = window.getComputedStyle(element).getPropertyValue('font-family');
            }

            var w = element.getBoundingClientRect().right - element.getBoundingClientRect().left;
            dropDown.style.marginLeft = '0';
            dropDown.style.marginTop = element.getBoundingClientRect().height + 'px';
            this.options = options;

            if (this.element != element) {
                this.element = element;
                this.elementStyle = {
                    zIndex: this.element.style.zIndex,
                    position: this.element.style.position,
                    backgroundColor: this.element.style.backgroundColor,
                    borderColor: this.element.style.borderColor
                }
            }

            this.element.style.zIndex = 3;
            this.element.style.position = 'relative';
            this.element.style.backgroundColor = 'transparent';
            this.element.style.borderColor = 'transparent';

            this.elementHint = element.cloneNode();
            this.elementHint.className = 'autocomplete hint';
            this.elementHint.style.zIndex = 2;
            this.elementHint.style.position = 'absolute';
            this.elementHint.onfocus = function () { this.element.focus(); }.bind(this);

            if (this.element.addEventListener) {
                this.element.removeEventListener("keydown", keyDownHandler);
                this.element.addEventListener("keydown", keyDownHandler, false);
                this.element.removeEventListener("blur", onBlurHandler);
                this.element.addEventListener("blur", onBlurHandler, false);
            }

            wrapper.appendChild(this.elementHint);
            wrapper.appendChild(dropDown);
            element.parentElement.appendChild(wrapper);

            this.repaint(element);
        },
        setText: function (text) {
            this.element.innerText = text;
        },
        getText: function () {
            return this.element.innerText;
        },
        hideDropDown: function () {
            this.wrapper.remove();
            if (this.elementHint) {
                this.elementHint.remove();
                this.elementHint = null;
                dropDownController.hide();
                this.element.style.zIndex = this.elementStyle.zIndex;
                this.element.style.position = this.elementStyle.position;
                this.element.style.backgroundColor = this.elementStyle.backgroundColor;
                this.element.style.borderColor = this.elementStyle.borderColor;
            }

        },
        repaint: function (element) {
            var text = element.innerText;
            text = text.replace('\n', '');

            var startFrom = this.startFrom;
            var options = this.options;
            var optionsLength = this.options.length;

            // breaking text in leftSide and token.

            var token = text.substring(this.startFrom);
            leftSide = text.substring(0, this.startFrom);

            for (var i = 0; i < optionsLength; i++) {
                var opt = this.options[i];
                if (   (!config.caseSensitive && opt.toLowerCase().indexOf(token.toLowerCase()) === 0)
                    || (config.caseSensitive && opt.indexOf(token) === 0)) {   // <-- how about upperCase vs. lowercase
                    this.elementHint.innerText = leftSide + token + opt.substring(token.length);
                    this.elementHint.realInnerText = leftSide + opt;
                    break;
                }
            }
            // moving the dropDown and refreshing it.
            dropDown.style.left = calculateWidthForText(leftSide) + 'px';
            dropDownController.refresh(token, this.options);
            this.elementHint.style.width = calculateWidthForText(this.elementHint.innerText) + 10 + 'px'
            var wasDropDownHidden = (dropDown.style.visibility == 'hidden');
            if (!wasDropDownHidden)
                this.elementHint.style.width = calculateWidthForText(this.elementHint.innerText) + dropDown.clientWidth + 'px';
        }
    };

    var dropDownController = createDropDownController(dropDown, rs);

    var keyDownHandler = function (e) {
        //console.log("Keydown:" + e.keyCode);
        e = e || window.event;
        var keyCode = e.keyCode;

        if (this.elementHint == null) return;

        if (keyCode == 33) { return; } // page up (do nothing)
        if (keyCode == 34) { return; } // page down (do nothing);

        if (keyCode == 27) { //escape
            rs.hideDropDown();
            rs.element.focus();
            e.preventDefault();
            e.stopPropagation();
            return;
        }

        var text = this.element.innerText;
        text = text.replace('\n', '');
        var startFrom = this.startFrom;

        if (config.confirmKeys.indexOf(keyCode) >= 0) { //  (autocomplete triggered)
            if (keyCode == 9) {
                if (this.elementHint.innerText.length == 0) {
                    rs.onTab();
                }
            }
            if (this.elementHint.innerText.length > 0) { // if there is a hint
                if (this.element.innerText != this.elementHint.realInnerText) {
                    this.element.innerText = this.elementHint.realInnerText;
                    rs.hideDropDown();
                    setEndOfContenteditable(this.element);
                    if (keyCode == 9) {
                        rs.element.focus();
                        e.preventDefault();
                        e.stopPropagation();
                    }
                }
            }
            return;
        }

        if (keyCode == 13) {       // enter  (autocomplete triggered)
            if (this.elementHint.innerText.length == 0) { // if there is a hint
                rs.onEnter();
            } else {
                var wasDropDownHidden = (dropDown.style.visibility == 'hidden');
                dropDownController.hide();

                if (wasDropDownHidden) {
                    rs.hideDropDown();
                    rs.element.focus();
                    rs.onEnter();
                    return;
                }

                this.element.innerText = this.elementHint.realInnerText;
                rs.hideDropDown();
                setEndOfContenteditable(this.element);
                e.preventDefault();
                e.stopPropagation();
            }
            return;
        }

        if (keyCode == 40) {     // down
            var token = text.substring(this.startFrom);
            var m = dropDownController.move(+1);
            if (m == '') { rs.onArrowDown(); }
            this.elementHint.innerText = leftSide + token + m.substring(token.length);
            this.elementHint.realInnerText = leftSide + m;
            e.preventDefault();
            e.stopPropagation();
            return;
        }

        if (keyCode == 38) {    // up
            var token = text.substring(this.startFrom);
            var m = dropDownController.move(-1);
            if (m == '') { rs.onArrowUp(); }
            this.elementHint.innerText = leftSide + token + m.substring(token.length);
            this.elementHint.realInnerText = leftSide + m;
            e.preventDefault();
            e.stopPropagation();
            return;
        }

    }.bind(rs);

    var onBlurHandler = function (e) {
        rs.hideDropDown();
        //console.log("Lost focus.");
    }.bind(rs);

    dropDownController.onmouseselection = function (text, rs) {
        rs.element.innerText = rs.elementHint.innerText = leftSide + text;
        rs.hideDropDown();
        window.setTimeout(function () {
            rs.element.focus();
            setEndOfContenteditable(rs.element);
        }, 1);
    };

    return rs;
}

module.exports = completely;<commit_msg>Dropdown items casing issue<commit_after>'use strict';

function completely(config) {
    config = config || {};
    config.confirmKeys = config.confirmKeys || [39, 35, 9] // right, end, tab
    config.caseSensitive = config.caseSensitive || false    // autocomplete case sensitive

    var fontSize = '';
    var fontFamily = '';

    var wrapper = document.createElement('div');
    wrapper.style.position = 'relative';
    wrapper.style.outline = '0';
    wrapper.style.border = '0';
    wrapper.style.margin = '0';
    wrapper.style.padding = '0';

    var dropDown = document.createElement('div');
    dropDown.className = 'autocomplete dropdown';
    dropDown.style.position = 'absolute';
    dropDown.style.visibility = 'hidden';

    var spacer;
    var leftSide; // <-- it will contain the leftSide part of the textfield (the bit that was already autocompleted)
    var createDropDownController = function (elem, rs) {
        var rows = [];
        var ix = 0;
        var oldIndex = -1;

        var onMouseOver = function () { this.style.outline = '1px solid #ddd'; }
        var onMouseOut = function () { this.style.outline = '0'; }
        var onMouseDown = function () { p.hide(); p.onmouseselection(this.__hint, p.rs); }

        var p = {
            rs: rs,
            hide: function () {
                elem.style.visibility = 'hidden';
                //rs.hideDropDown();
            },
            refresh: function (token, array) {
                elem.style.visibility = 'hidden';
                ix = 0;
                elem.innerHTML = '';
                var vph = (window.innerHeight || document.documentElement.clientHeight);
                var rect = elem.parentNode.getBoundingClientRect();
                var distanceToTop = rect.top - 6;                        // heuristic give 6px
                var distanceToBottom = vph - rect.bottom - 6;  // distance from the browser border.

                rows = [];
                for (var i = 0; i < array.length; i++) {

                    if (  (config.caseSensitive && array[i].indexOf(token) !== 0)
                        ||(!config.caseSensitive && array[i].toLowerCase().indexOf(token.toLowerCase()) !== 0)) { continue; }

                    var divRow = document.createElement('div');
                    divRow.className = 'item';
                    //divRow.style.color = config.color;
                    divRow.onmouseover = onMouseOver;
                    divRow.onmouseout = onMouseOut;
                    divRow.onmousedown = onMouseDown;
                    divRow.__hint = array[i];
                    divRow.innerHTML = array[i].substring(0, token.length) + '' + array[i].substring(token.length) + '';
                    rows.push(divRow);
                    elem.appendChild(divRow);
                }
                if (rows.length === 0) {
                    return; // nothing to show.
                }
                if (rows.length === 1 && (   (token.toLowerCase() === rows[0].__hint.toLowerCase() && !config.caseSensitive)
                                           ||(token === rows[0].__hint && config.caseSensitive))){
                    return; // do not show the dropDown if it has only one element which matches what we have just displayed.
                }

                if (rows.length < 2) return;
                p.highlight(0);

                if (distanceToTop > distanceToBottom * 3) {        // Heuristic (only when the distance to the to top is 4 times more than distance to the bottom
                    elem.style.maxHeight = distanceToTop + 'px';  // we display the dropDown on the top of the input text
                    elem.style.top = '';
                    elem.style.bottom = '100%';
                } else {
                    elem.style.top = '100%';
                    elem.style.bottom = '';
                    elem.style.maxHeight = distanceToBottom + 'px';
                }
                elem.style.visibility = 'visible';
            },
            highlight: function (index) {
                if (oldIndex != -1 && rows[oldIndex]) {
                    rows[oldIndex].className = "item";
                }
                rows[index].className = "item hover";
                oldIndex = index;
            },
            move: function (step) { // moves the selection either up or down (unless it's not possible) step is either +1 or -1.
                if (elem.style.visibility === 'hidden') return ''; // nothing to move if there is no dropDown. (this happens if the user hits escape and then down or up)
                if (ix + step === -1 || ix + step === rows.length) return rows[ix].__hint; // NO CIRCULAR SCROLLING.
                ix += step;
                p.highlight(ix);
                return rows[ix].__hint;//txtShadow.value = uRows[uIndex].__hint ;
            },
            onmouseselection: function () { } // it will be overwritten.
        };
        return p;
    }

    function setEndOfContenteditable(contentEditableElement) {
        var range, selection;
        if (document.createRange)//Firefox, Chrome, Opera, Safari, IE 9+
        {
            range = document.createRange();//Create a range (a range is a like the selection but invisible)
            range.selectNodeContents(contentEditableElement);//Select the entire contents of the element with the range
            range.collapse(false);//collapse the range to the end point. false means collapse to end rather than the start
            selection = window.getSelection();//get the selection object (allows you to change selection)
            selection.removeAllRanges();//remove any selections already made
            selection.addRange(range);//make the range you have just created the visible selection
        }
        else if (document.selection)//IE 8 and lower
        {
            range = document.body.createTextRange();//Create a range (a range is a like the selection but invisible)
            range.moveToElementText(contentEditableElement);//Select the entire contents of the element with the range
            range.collapse(false);//collapse the range to the end point. false means collapse to end rather than the start
            range.select();//Select the range (make it the visible selection
        }
    }

    function calculateWidthForText(text) {
        if (spacer === undefined) { // on first call only.
            spacer = document.createElement('span');
            spacer.style.visibility = 'hidden';
            spacer.style.position = 'fixed';
            spacer.style.outline = '0';
            spacer.style.margin = '0';
            spacer.style.padding = '0';
            spacer.style.border = '0';
            spacer.style.left = '0';
            spacer.style.whiteSpace = 'pre';
            spacer.style.fontSize = fontSize;
            spacer.style.fontFamily = fontFamily;
            spacer.style.fontWeight = 'normal';
            document.body.appendChild(spacer);
        }

        // Used to encode an HTML string into a plain text.
        // taken from http://stackoverflow.com/questions/1219860/javascript-jquery-html-encoding
        spacer.innerHTML = String(text).replace(/&/g, '&')
            .replace(/"/g, '"')
            .replace(/'/g, ''')
            .replace(/</g, '<')
            .replace(/>/g, '>');
        return spacer.getBoundingClientRect().right;
    }

    var rs = {
        onArrowDown: function () { }, // defaults to no action.
        onArrowUp: function () { },   // defaults to no action.
        onEnter: function () { },     // defaults to no action.
        onTab: function () { },       // defaults to no action.
        startFrom: 0,
        options: [],
        element: null,
        elementHint: null,
        elementStyle: null,
        wrapper: wrapper,      // Only to allow  easy access to the HTML elements to the final user (possibly for minor customizations)
        show: function (element, startPos, options) {
            this.startFrom = startPos;
            this.wrapper.remove();
            if (this.elementHint) {
                this.elementHint.remove();
                this.elementHint = null;
            }

            if (fontSize == '') {
                fontSize = window.getComputedStyle(element).getPropertyValue('font-size');
            }
            if (fontFamily == '') {
                fontFamily = window.getComputedStyle(element).getPropertyValue('font-family');
            }

            var w = element.getBoundingClientRect().right - element.getBoundingClientRect().left;
            dropDown.style.marginLeft = '0';
            dropDown.style.marginTop = element.getBoundingClientRect().height + 'px';
            this.options = options;

            if (this.element != element) {
                this.element = element;
                this.elementStyle = {
                    zIndex: this.element.style.zIndex,
                    position: this.element.style.position,
                    backgroundColor: this.element.style.backgroundColor,
                    borderColor: this.element.style.borderColor
                }
            }

            this.element.style.zIndex = 3;
            this.element.style.position = 'relative';
            this.element.style.backgroundColor = 'transparent';
            this.element.style.borderColor = 'transparent';

            this.elementHint = element.cloneNode();
            this.elementHint.className = 'autocomplete hint';
            this.elementHint.style.zIndex = 2;
            this.elementHint.style.position = 'absolute';
            this.elementHint.onfocus = function () { this.element.focus(); }.bind(this);

            if (this.element.addEventListener) {
                this.element.removeEventListener("keydown", keyDownHandler);
                this.element.addEventListener("keydown", keyDownHandler, false);
                this.element.removeEventListener("blur", onBlurHandler);
                this.element.addEventListener("blur", onBlurHandler, false);
            }

            wrapper.appendChild(this.elementHint);
            wrapper.appendChild(dropDown);
            element.parentElement.appendChild(wrapper);

            this.repaint(element);
        },
        setText: function (text) {
            this.element.innerText = text;
        },
        getText: function () {
            return this.element.innerText;
        },
        hideDropDown: function () {
            this.wrapper.remove();
            if (this.elementHint) {
                this.elementHint.remove();
                this.elementHint = null;
                dropDownController.hide();
                this.element.style.zIndex = this.elementStyle.zIndex;
                this.element.style.position = this.elementStyle.position;
                this.element.style.backgroundColor = this.elementStyle.backgroundColor;
                this.element.style.borderColor = this.elementStyle.borderColor;
            }

        },
        repaint: function (element) {
            var text = element.innerText;
            text = text.replace('\n', '');

            var startFrom = this.startFrom;
            var options = this.options;
            var optionsLength = this.options.length;

            // breaking text in leftSide and token.

            var token = text.substring(this.startFrom);
            leftSide = text.substring(0, this.startFrom);

            for (var i = 0; i < optionsLength; i++) {
                var opt = this.options[i];
                if (   (!config.caseSensitive && opt.toLowerCase().indexOf(token.toLowerCase()) === 0)
                    || (config.caseSensitive && opt.indexOf(token) === 0)) {   // <-- how about upperCase vs. lowercase
                    this.elementHint.innerText = leftSide + token + opt.substring(token.length);
                    this.elementHint.realInnerText = leftSide + opt;
                    break;
                }
            }
            // moving the dropDown and refreshing it.
            dropDown.style.left = calculateWidthForText(leftSide) + 'px';
            dropDownController.refresh(token, this.options);
            this.elementHint.style.width = calculateWidthForText(this.elementHint.innerText) + 10 + 'px'
            var wasDropDownHidden = (dropDown.style.visibility == 'hidden');
            if (!wasDropDownHidden)
                this.elementHint.style.width = calculateWidthForText(this.elementHint.innerText) + dropDown.clientWidth + 'px';
        }
    };

    var dropDownController = createDropDownController(dropDown, rs);

    var keyDownHandler = function (e) {
        //console.log("Keydown:" + e.keyCode);
        e = e || window.event;
        var keyCode = e.keyCode;

        if (this.elementHint == null) return;

        if (keyCode == 33) { return; } // page up (do nothing)
        if (keyCode == 34) { return; } // page down (do nothing);

        if (keyCode == 27) { //escape
            rs.hideDropDown();
            rs.element.focus();
            e.preventDefault();
            e.stopPropagation();
            return;
        }

        var text = this.element.innerText;
        text = text.replace('\n', '');
        var startFrom = this.startFrom;

        if (config.confirmKeys.indexOf(keyCode) >= 0) { //  (autocomplete triggered)
            if (keyCode == 9) {
                if (this.elementHint.innerText.length == 0) {
                    rs.onTab();
                }
            }
            if (this.elementHint.innerText.length > 0) { // if there is a hint
                if (this.element.innerText != this.elementHint.realInnerText) {
                    this.element.innerText = this.elementHint.realInnerText;
                    rs.hideDropDown();
                    setEndOfContenteditable(this.element);
                    if (keyCode == 9) {
                        rs.element.focus();
                        e.preventDefault();
                        e.stopPropagation();
                    }
                }
            }
            return;
        }

        if (keyCode == 13) {       // enter  (autocomplete triggered)
            if (this.elementHint.innerText.length == 0) { // if there is a hint
                rs.onEnter();
            } else {
                var wasDropDownHidden = (dropDown.style.visibility == 'hidden');
                dropDownController.hide();

                if (wasDropDownHidden) {
                    rs.hideDropDown();
                    rs.element.focus();
                    rs.onEnter();
                    return;
                }

                this.element.innerText = this.elementHint.realInnerText;
                rs.hideDropDown();
                setEndOfContenteditable(this.element);
                e.preventDefault();
                e.stopPropagation();
            }
            return;
        }

        if (keyCode == 40) {     // down
            var token = text.substring(this.startFrom);
            var m = dropDownController.move(+1);
            if (m == '') { rs.onArrowDown(); }
            this.elementHint.innerText = leftSide + token + m.substring(token.length);
            this.elementHint.realInnerText = leftSide + m;
            e.preventDefault();
            e.stopPropagation();
            return;
        }

        if (keyCode == 38) {    // up
            var token = text.substring(this.startFrom);
            var m = dropDownController.move(-1);
            if (m == '') { rs.onArrowUp(); }
            this.elementHint.innerText = leftSide + token + m.substring(token.length);
            this.elementHint.realInnerText = leftSide + m;
            e.preventDefault();
            e.stopPropagation();
            return;
        }

    }.bind(rs);

    var onBlurHandler = function (e) {
        rs.hideDropDown();
        //console.log("Lost focus.");
    }.bind(rs);

    dropDownController.onmouseselection = function (text, rs) {
        rs.element.innerText = rs.elementHint.innerText = leftSide + text;
        rs.hideDropDown();
        window.setTimeout(function () {
            rs.element.focus();
            setEndOfContenteditable(rs.element);
        }, 1);
    };

    return rs;
}

module.exports = completely;<|endoftext|>


<commit_before>
/*
 * vim: ts=4:sw=4:expandtab
 */
;(function() {
    'use strict';
    window.Whisper = window.Whisper || {};

    function destroyExpiredMessages() {
        // Load messages that have expired and destroy them
        var expired = new Whisper.MessageCollection();
        expired.on('add', function(message) {
            console.log('message', message.get('sent_at'), 'expired');
            message.destroy();
            message.getConversation().trigger('expired', message);
        });
        expired.on('reset', checkExpiringMessages);

        expired.fetchExpired();
    }

    var timeout;
    function checkExpiringMessages() {
        // Look up the next expiring message and set a timer to destroy it
        var expiring = new Whisper.MessageCollection();
        expiring.once('add', function(next) {
            var expires_at = next.get('expires_at');
            console.log('next message expires', new Date(expires_at));

            var wait = expires_at - Date.now();
            if (wait < 0) { wait = 0; }

            clearTimeout(timeout);
            timeout = setTimeout(destroyExpiredMessages, wait);
        });
        expiring.fetchNextExpiring();
    }

    Whisper.ExpiringMessagesListener = {
        init: function(events) {
            checkExpiringMessages();
            events.on('timetravel', checkExpiringMessages);
        },
        update: checkExpiringMessages
    };

    var TimerOption = Backbone.Model.extend({
      getName: function() {
        return i18n([
          'timerOption', this.get('time'), this.get('unit'),
        ].join('_')) || moment.duration(this.get('time'), this.get('unit')).humanize();
      },
      getAbbreviated: function() {
        return i18n([
          'timerOption', this.get('time'), this.get('unit'), 'abbreviated'
        ].join('_'));
      }
    });
    Whisper.ExpirationTimerOptions = new (Backbone.Collection.extend({
      model: TimerOption,
      getName: function(seconds) {
        if (!seconds) {
          seconds = 0;
        }
        var o = this.findWhere({seconds: seconds});
        if (o) { return o.getName(); }
        else {
          return [seconds, 'seconds'].join(' ');
        }
      },
      getAbbreviated: function(seconds) {
        if (!seconds) {
          seconds = 0;
        }
        var o = this.findWhere({seconds: seconds});
        if (o) { return o.getAbbreviated(); }
        else {
          return [seconds, 's'].join('');
        }
      }
    }))([
        [ 0,  'seconds'  ],
        [ 5,  'seconds'  ],
        [ 10, 'seconds'  ],
        [ 30, 'seconds'  ],
        [ 1,  'minute'   ],
        [ 5,  'minutes'  ],
        [ 30, 'minutes'  ],
        [ 1,  'hour'     ],
        [ 6,  'hours'    ],
        [ 12, 'hours'    ],
        [ 1,  'day'      ],
        [ 1,  'week'     ],
    ].map(function(o) {
      var duration = moment.duration(o[0], o[1]); // 5, 'seconds'
      return {
        time: o[0],
        unit: o[1],
        seconds: duration.asSeconds()
      };
    }));

})();
<commit_msg>Use ISO format in log message<commit_after>
/*
 * vim: ts=4:sw=4:expandtab
 */
;(function() {
    'use strict';
    window.Whisper = window.Whisper || {};

    function destroyExpiredMessages() {
        // Load messages that have expired and destroy them
        var expired = new Whisper.MessageCollection();
        expired.on('add', function(message) {
            console.log('message', message.get('sent_at'), 'expired');
            message.destroy();
            message.getConversation().trigger('expired', message);
        });
        expired.on('reset', checkExpiringMessages);

        expired.fetchExpired();
    }

    var timeout;
    function checkExpiringMessages() {
        // Look up the next expiring message and set a timer to destroy it
        var expiring = new Whisper.MessageCollection();
        expiring.once('add', function(next) {
            var expires_at = next.get('expires_at');
            console.log('next message expires', new Date(expires_at).toISOString());

            var wait = expires_at - Date.now();
            if (wait < 0) { wait = 0; }

            clearTimeout(timeout);
            timeout = setTimeout(destroyExpiredMessages, wait);
        });
        expiring.fetchNextExpiring();
    }

    Whisper.ExpiringMessagesListener = {
        init: function(events) {
            checkExpiringMessages();
            events.on('timetravel', checkExpiringMessages);
        },
        update: checkExpiringMessages
    };

    var TimerOption = Backbone.Model.extend({
      getName: function() {
        return i18n([
          'timerOption', this.get('time'), this.get('unit'),
        ].join('_')) || moment.duration(this.get('time'), this.get('unit')).humanize();
      },
      getAbbreviated: function() {
        return i18n([
          'timerOption', this.get('time'), this.get('unit'), 'abbreviated'
        ].join('_'));
      }
    });
    Whisper.ExpirationTimerOptions = new (Backbone.Collection.extend({
      model: TimerOption,
      getName: function(seconds) {
        if (!seconds) {
          seconds = 0;
        }
        var o = this.findWhere({seconds: seconds});
        if (o) { return o.getName(); }
        else {
          return [seconds, 'seconds'].join(' ');
        }
      },
      getAbbreviated: function(seconds) {
        if (!seconds) {
          seconds = 0;
        }
        var o = this.findWhere({seconds: seconds});
        if (o) { return o.getAbbreviated(); }
        else {
          return [seconds, 's'].join('');
        }
      }
    }))([
        [ 0,  'seconds'  ],
        [ 5,  'seconds'  ],
        [ 10, 'seconds'  ],
        [ 30, 'seconds'  ],
        [ 1,  'minute'   ],
        [ 5,  'minutes'  ],
        [ 30, 'minutes'  ],
        [ 1,  'hour'     ],
        [ 6,  'hours'    ],
        [ 12, 'hours'    ],
        [ 1,  'day'      ],
        [ 1,  'week'     ],
    ].map(function(o) {
      var duration = moment.duration(o[0], o[1]); // 5, 'seconds'
      return {
        time: o[0],
        unit: o[1],
        seconds: duration.asSeconds()
      };
    }));

})();
<|endoftext|>


<commit_before>"use strict";

var winston = require("winston"),
    common = require("winston/lib/winston/common"),
    cycle = require("cycle"),
    uuid = require("node-uuid"),
    util = require("util"),
    request = require ("request-json"),
    _ = require("lodash"),
    Groonga,
    createTable,
    createQuery,
    createField,
    postData,
    client,
    createUID,
    logMsgUID;

// ### function Groonga (options)
// #### @options {Object} Options for this instance.
// Constructor function for the Console transport object responsible
// for making arbitrary HTTP requests whenever log messages and metadata
// are received.
Groonga = exports.Groonga = function (options) {
    this.name = "groonga";
    this.protocol = options.protocol || "http";
    this.host = options.host || "localhost";
    this.port = options.port || 1060;
    this.severity = options.severity || "info";
    this.table = options.table || "logs";
};

// Inherit from `winston.Transport`.
util.inherits(Groonga, winston.Transport);

// Expose the name of this Transport on the prototype
Groonga.prototype.name = "groonga";

// Define a getter so that `winston.transports.Couchdb`
// is available and thus backwards compatible.
winston.Transport.Groonga = Groonga;

//
// ### function log (level, msg, [meta], callback)
// #### @level {string} Level at which to log the message.
// #### @msg {string} Message to log
// #### @meta {Object} **Optional** Additional metadata to attach
// #### @callback {function} Continuation to respond to when complete.
// Core logging method exposed to Winston. Metadata is optional.
//
Groonga.prototype.log = function (level, msg, meta, callback) {
    var self,
        params;
    if (this.silent) {
        return callback && callback(null, true);
    }
    self = this;
    params = common.clone(cycle.decycle(meta)) || {};
    params.timestamp = (new Date ().getTime () / 1000).toFixed (0);
    params.message = msg;
    params.level = level;
    createTable(params, this);

    if (callback) {
        callback(null, true);
    }
};

// Creates and returns a random seeded UID to be added to the _key column in Groonga.
createUID = function () {
    return uuid.v4();
};

// Creates a column in Groonga with the specified name when called upon.
createField = function (keys, groonga) {
    _.forEach(keys, function (key, i) {
        var fieldType = "ShortText";
        if (key === "timestamp") {
            fieldType = "Time";
        }
        client.get("/d/column_create?table=" + groonga.table + "&name=" + key + "&type=" + fieldType, function (err) {
            if (err) {
                console.log(err);
            } else {
                client.get("/d/column_create?table=" + groonga.table + "Lex&name=" + key + "_index&flags=COLUMN_INDEX|WITH_POSITION&type=" + groonga.table + "&source=" + key, function (err) {
                    if (err) {
                        console.log (err);
                    }
                });
            }
        });
    });
};

// Posts the log data to Groonga.
postData = function (params, groonga, q) {
    client.post("/d/load?table=" + groonga.table, q, function (err) {
        if (err) {
            console.log("could not write");
        }
    });
};

// Builds the query string to log data to Groonga.
createQuery = function (params, groonga) {
    var existingFields,
        q = [],
        needsCreated = [],
        promise;
    logMsgUID = createUID();
    q[0] = {
        _key: logMsgUID.toString()
    };

    // Gets the columns that can be posted to in Groonga.
    client.get("/d/select?table=" + groonga.table , function (err, res, body) {
        if (!err) {
            existingFields = body[1][0][1];
            _.forEach(params, function (n, key) {
                q[0][key] = params[key].toString();
                // Checks to make sure column exists.
                if (!_.has (_.invert (_.flattenDeep(existingFields)), key)) {
                    // create field
                    needsCreated.push(key);
                }
            });
            if (needsCreated.length > 0) {
                // This promise trys to create the columns in Groonga
                //  and checks to see if the column creation was successful.
                promise = new Promise(function (resolve, reject) {
                    var counter = 0,
                        checkFields;
                    checkFields = function () {
                        var exists = [],
                        fieldCount = 0,
                        timer;
                        client.get("/d/select?table=" + groonga.table , function (err, res, body) {
                            if (!err) {
                                exists = body[1][0][1];
                                _.forEach(params, function (n, key) {
                                    if (_.has (_.invert (_.flattenDeep(exists)), key)) {
                                        fieldCount += 1;
                                        if (fieldCount === Object.keys(params).length) {
                                            resolve(true);
                                            return false;
                                        } else if (fieldCount !== Object.keys(params).length && counter < 20) {
                                            if (timer !== undefined) {
                                                clearTimeout(timer);
                                            }
                                            timer = setTimeout(function () {
                                                checkFields();
                                            }, 50);
                                        } else {
                                            reject(true);
                                            return false;
                                        }
                                    }
                                });
                            }
                        });
                        counter += 1;
                    };
                    createField(needsCreated, groonga);
                    checkFields();
                });
                promise.then(function () {
                    // If the Promise of creating columns was successful post the data.
                    postData(params, groonga, q);
                }).catch(function (error) {
                    // If the Promise was unsuccessful try to post what data there is
                    //  and let the user know data could be missing
                    console.log(error);
                    postData(params, groonga, q);
                    console.log("Something went wrong check your Groonga.");
                });
            } else {
                postData(params, groonga, q);
            }
        } else {
            console.log("problem with groonga, can not log");
        }
    });
};

// Trys to create a table in Groonga with the name
//  specified if it does not exist.
createTable = function (params, groonga) {
    var existingTables = [];
    client = request.createClient(groonga.protocol + "://" + groonga.host + ":" + groonga.port);
    client.get("/d/table_list", function (err, res, body) {
        if (!err) {
            _.forEach (body[1], function (n, key) {
                if (_.isNumber (body[1][key][0])) {
                    existingTables.push (body[1][key][1]);
                }
            });
            if (_.findIndex (existingTables, function (c) {
                    return c === groonga.table;
                }) >= 0) {
                // do nothing the table exists
                createQuery (params, groonga);
            } else {
                // create table
                client.get ("/d/table_create?name=" + groonga.table + "&flags=TABLE_HASH_KEY&key_type=ShortText", function (err, res, body) {
                    if (!err) {
                        createQuery (params, groonga);
                    }
                });
                // create index table
                client.get ("/d/table_create?name=" + groonga.table + "Lex&flags=TABLE_PAT_KEY&key_type=ShortText&default_tokenizer=TokenBigram&normalizer=NormalizerAuto", function (err) {
                    if (err) {
                        console.log(err);
                    }
                });
            }
        }
    });
};
<commit_msg>fix for undefined values when checking for field existances.<commit_after>"use strict";

var winston = require("winston"),
    common = require("winston/lib/winston/common"),
    cycle = require("cycle"),
    uuid = require("node-uuid"),
    util = require("util"),
    request = require ("request-json"),
    _ = require("lodash"),
    Groonga,
    createTable,
    createQuery,
    createField,
    postData,
    client,
    createUID,
    logMsgUID;

// ### function Groonga (options)
// #### @options {Object} Options for this instance.
// Constructor function for the Console transport object responsible
// for making arbitrary HTTP requests whenever log messages and metadata
// are received.
Groonga = exports.Groonga = function (options) {
    this.name = "groonga";
    this.protocol = options.protocol || "http";
    this.host = options.host || "localhost";
    this.port = options.port || 1060;
    this.severity = options.severity || "info";
    this.table = options.table || "logs";
};

// Inherit from `winston.Transport`.
util.inherits(Groonga, winston.Transport);

// Expose the name of this Transport on the prototype
Groonga.prototype.name = "groonga";

// Define a getter so that `winston.transports.Couchdb`
// is available and thus backwards compatible.
winston.Transport.Groonga = Groonga;

//
// ### function log (level, msg, [meta], callback)
// #### @level {string} Level at which to log the message.
// #### @msg {string} Message to log
// #### @meta {Object} **Optional** Additional metadata to attach
// #### @callback {function} Continuation to respond to when complete.
// Core logging method exposed to Winston. Metadata is optional.
//
Groonga.prototype.log = function (level, msg, meta, callback) {
    var self,
        params;
    if (this.silent) {
        return callback && callback(null, true);
    }
    self = this;
    params = common.clone(cycle.decycle(meta)) || {};
    params.timestamp = (new Date ().getTime () / 1000).toFixed (0);
    params.message = msg;
    params.level = level;
    createTable(params, this);

    if (callback) {
        callback(null, true);
    }
};

// Creates and returns a random seeded UID to be added to the _key column in Groonga.
createUID = function () {
    return uuid.v4();
};

// Creates a column in Groonga with the specified name when called upon.
createField = function (keys, groonga) {
    _.forEach(keys, function (key, i) {
        var fieldType = "ShortText";
        if (key === "timestamp") {
            fieldType = "Time";
        }
        client.get("/d/column_create?table=" + groonga.table + "&name=" + key + "&type=" + fieldType, function (err) {
            if (err) {
                console.log(err);
            } else {
                client.get("/d/column_create?table=" + groonga.table + "Lex&name=" + key + "_index&flags=COLUMN_INDEX|WITH_POSITION&type=" + groonga.table + "&source=" + key, function (err) {
                    if (err) {
                        console.log (err);
                    }
                });
            }
        });
    });
};

// Posts the log data to Groonga.
postData = function (params, groonga, q) {
    client.post("/d/load?table=" + groonga.table, q, function (err) {
        if (err) {
            console.log("could not write");
        }
    });
};

// Builds the query string to log data to Groonga.
createQuery = function (params, groonga) {
    var existingFields,
        q = [],
        needsCreated = [],
        promise;
    logMsgUID = createUID();
    q[0] = {
        _key: logMsgUID.toString()
    };

    // Gets the columns that can be posted to in Groonga.
    client.get("/d/select?table=" + groonga.table , function (err, res, body) {
        if (!err) {
            existingFields = body[1][0][1];
            _.forEach(params, function (n, key) {
                if(_.isUndefined(n)){
                    n = "undefined";
                }
                q[0][key] = n.toString();
                // Checks to make sure column exists.
                if (!_.has (_.invert (_.flattenDeep(existingFields)), key)) {
                    // create field
                    needsCreated.push(key);
                }
            });
            if (needsCreated.length > 0) {
                // This promise trys to create the columns in Groonga
                //  and checks to see if the column creation was successful.
                promise = new Promise(function (resolve, reject) {
                    var counter = 0,
                        checkFields;
                    checkFields = function () {
                        var exists = [],
                        fieldCount = 0,
                        timer;
                        client.get("/d/select?table=" + groonga.table , function (err, res, body) {
                            if (!err) {
                                exists = body[1][0][1];
                                _.forEach(params, function (n, key) {
                                    if (_.has (_.invert (_.flattenDeep(exists)), key)) {
                                        fieldCount += 1;
                                        if (fieldCount === Object.keys(params).length) {
                                            resolve(true);
                                            return false;
                                        } else if (fieldCount !== Object.keys(params).length && counter < 20) {
                                            if (timer !== undefined) {
                                                clearTimeout(timer);
                                            }
                                            timer = setTimeout(function () {
                                                checkFields();
                                            }, 50);
                                        } else {
                                            reject(true);
                                            return false;
                                        }
                                    }
                                });
                            }
                        });
                        counter += 1;
                    };
                    createField(needsCreated, groonga);
                    checkFields();
                });
                promise.then(function () {
                    // If the Promise of creating columns was successful post the data.
                    postData(params, groonga, q);
                }).catch(function (error) {
                    // If the Promise was unsuccessful try to post what data there is
                    //  and let the user know data could be missing
                    console.log(error);
                    postData(params, groonga, q);
                    console.log("Something went wrong check your Groonga.");
                });
            } else {
                postData(params, groonga, q);
            }
        } else {
            console.log("problem with groonga, can not log");
        }
    });
};

// Trys to create a table in Groonga with the name
//  specified if it does not exist.
createTable = function (params, groonga) {
    var existingTables = [];
    client = request.createClient(groonga.protocol + "://" + groonga.host + ":" + groonga.port);
    client.get("/d/table_list", function (err, res, body) {
        if (!err) {
            _.forEach (body[1], function (n, key) {
                if (_.isNumber (body[1][key][0])) {
                    existingTables.push (body[1][key][1]);
                }
            });
            if (_.findIndex (existingTables, function (c) {
                    return c === groonga.table;
                }) >= 0) {
                // do nothing the table exists
                createQuery (params, groonga);
            } else {
                // create table
                client.get ("/d/table_create?name=" + groonga.table + "&flags=TABLE_HASH_KEY&key_type=ShortText", function (err, res, body) {
                    if (!err) {
                        createQuery (params, groonga);
                    }
                });
                // create index table
                client.get ("/d/table_create?name=" + groonga.table + "Lex&flags=TABLE_PAT_KEY&key_type=ShortText&default_tokenizer=TokenBigram&normalizer=NormalizerAuto", function (err) {
                    if (err) {
                        console.log(err);
                    }
                });
            }
        }
    });
};
<|endoftext|>


<commit_before>(function ($) {
    $.widget("roicp.treeview", {
        mySelf: null,
        executeExpandPaths: false,
        countExpandPathsItens: 0,
        testCounter:0,

        options: {
            source: null,
            pathsToExpand: null,

            // callbacks
            onCompleted: null,
            onNodeExpanded: null,
            onNodeColapsed: null,
            onNodeCreated: null
        },

        _create: function () {
            mySelf = this;
            executeExpandPaths = true;
            countExpandPathsItens = 0;
            testCounter = 0;

            mySelf._countExpandPathsItens(mySelf.options.pathsToExpand);
            mySelf._getChildrenNodes(0, mySelf.element, mySelf._getChildrenNodesCompleted);
        },

        _getChildrenNodes: function (itemId, baseElement, funcCallback) {
            if (typeof mySelf.options.source === "string") {
                $.ajax({
                    type: "POST",
                    contentType: "application/json; charset=utf-8",
                    url: mySelf.options.source,
                    data: "{ 'upperId':'" + itemId + "' }",
                    dataType: "json",
                    success: function (data) {
                        funcCallback(itemId, baseElement, data);
                    },
                    error: function () {
                        alert("An error occurred when trying to obtain the nodes");
                    }
                });
            };
        },

        _getChildrenNodesCompleted: function (itemId, parentElement, data) {
            if (data != null && data.length > 0) {
                var childTreeTag = $("<ul />");
                childTreeTag.addClass("treeview");

                mySelf._createNode(data, childTreeTag);

                childTreeTag.appendTo(parentElement);

                mySelf._trigger("onCompleted", null, {});

                if (executeExpandPaths) {
                    mySelf._expandNodesInExpandPaths(mySelf.options.pathsToExpand);
                }
            }
        },

        _expandNode: function (itemNodeId) {
            var currentNode = mySelf.element.find("li[id='" + itemNodeId + "']").first();

            mySelf._switchCssClass(currentNode.children(".scontainer-expand"));

            mySelf._getChildrenNodes(itemNodeId, currentNode, mySelf._getChildrenNodesCompleted);

            mySelf._trigger("onNodeExpanded", null, {});
        },

        _collapseNode: function (itemNodeId) {
            var currentNode = mySelf.element.find("li[id='" + itemNodeId + "']").first();

            mySelf._switchCssClass(currentNode.children(".scontainer-collapse"));

            currentNode.children("ul").remove();

            mySelf._trigger("onNodeColapsed", null, {});
        },

        _createNode: function (dataSource, parentElement) {
            for (var i = 0; i < dataSource.length; i++) {
                var item = dataSource[i];
                var hitPosition;

                if (dataSource.length == 1) {
                    hitPosition = "hit-single";
                } else {
                    switch (i) {
                        case 0:
                            hitPosition = "hit-first";
                            break;
                        case dataSource.length - 1:
                            hitPosition = "hit-last";
                            break;
                        default:
                            hitPosition = "";
                            break;
                    }
                }

                // Create the base node li tag
                var nodeInnerTag = $("<li />");
                nodeInnerTag.attr("id", item.Id);
                nodeInnerTag.addClass("node-bg-vimage");
                nodeInnerTag.addClass("without-child-node");

                if (item.HasChild) {
                    nodeInnerTag.removeClass("without-child-node").addClass("with-child-node");
                }

                if (hitPosition == "hit-last" || hitPosition == "hit-single") {
                    nodeInnerTag.removeClass("node-bg-vimage");
                }

                // Create the span hit area (where the plus and minus sign appears)
                var nodeSpanHit = $("<span />");
                nodeSpanHit.attr("id", item.Id);
                nodeSpanHit.addClass("no-hit-area");

                if (item.HasChild) {
                    nodeSpanHit.removeClass("no-hit-area").addClass("scontainer-expand").addClass("hit-area");

                    nodeSpanHit.bind("click", function () {
                        executeExpandPaths = false;
                        mySelf._expandNode($(this).attr("id"));
                    });
                }

                nodeSpanHit.addClass(hitPosition);
                nodeSpanHit.appendTo(nodeInnerTag);

                // Create a span to be used as a render node container.
                // The content of this container could be overridden by a custom _renderItem method.
                var spanText = $("<span />");
                spanText.addClass("scontainer-node-render-container");
                spanText.data("treeview-render-container-item", item);
                mySelf._renderItem(spanText, item);
                spanText.appendTo(nodeInnerTag);

                // Attaching the new node to the parent element
                nodeInnerTag.appendTo(parentElement);

                mySelf._trigger("onNodeCreated", null, {});
            }
        },

        _renderItem: function (spanText, item) {
            var spanName = $("<span />");
            spanName.addClass("scontainer-node-text");
            spanName.html(item.Name);
            spanName.appendTo(spanText);
        },

        _switchCssClass: function (workNode) {
            workNode.unbind('click');

            if (workNode.hasClass("scontainer-collapse")) {
                workNode.removeClass("scontainer-collapse").addClass("scontainer-expand");

                workNode.bind("click", function () {
                    executeExpandPaths = false;
                    mySelf._expandNode($(this).attr("id"));
                });
            } else {
                if (workNode.hasClass("scontainer-expand")) {
                    workNode.removeClass("scontainer-expand").addClass("scontainer-collapse");

                    workNode.bind("click", function () {
                        mySelf._collapseNode($(this).attr("id"));
                    });
                }
            }
        },

        _countExpandPathsItens: function (itens) {
            if ($.isArray(itens)) {
                for (var i = 0; i < itens.length; i++) {
                    countExpandPathsItens += itens[i].length;
                }
            }
        },

        _expandNodesInExpandPaths: function (itens) {
            if ($.isArray(itens)) {
                for (var i = 0; i < itens.length; i++) {
                    var currentItem = itens[i];

                    if ($.isArray(currentItem)) {
                        mySelf._expandNodesInExpandPaths(currentItem);
                    } else {
                        var lastItem = $(itens).last()[0];
                        var currentNode = mySelf.element.find("li[id='" + currentItem + "']").first();

                        if (lastItem != currentItem) {
                            if (currentNode.children(".scontainer-expand").length > 0) {
                                mySelf._expandNode(currentItem);
                            }
                        }else {
                            currentNode.children(".scontainer-node-render-container").first().addClass("scontainer-node-highlight");
                        }
                    }
                };
            }
        },

        _setOption: function (key, value) {
            mySelf._super(key, value);

            if (key === "source") {
                mySelf._getChildrenNodes(0, mySelf.element, mySelf._getChildrenNodesCompleted);
            }

            if (key === "expandPaths") {
                mySelf._expandNodesInExpandPaths(mySelf.options.expandPaths);
            }
        },

        destroy: function () {
            mySelf.element.html("");
            $.Widget.prototype.destroy.call(this);
        }
    });
})(jQuery);<commit_msg>preparing for create examples<commit_after>var Treeview = (function () {
    function treeview(element, options) {
        this.myObject = $(element);
        this.myObject.empty();

        this.options = options;

        this.renderItem = this.options.renderItem || this.renderItem;

        if (this.options.loadNodesOnDemand) {
            this.getChildrenNodes = this.options.getChildrenNodes || this.getChildrenNodes;
            this.getChildrenNodes(0, this.myObject, $.proxy(this.getChildrenNodesSuccess, this));
        } else {
            this.getAllNodes();
        }
    }

    treeview.prototype = {
        getChildrenNodes: function (itemId, baseElement, funcCallback) {
            var baseDataToSend = { upperId: itemId };
            var dataToSend = $.extend(true, baseDataToSend, this.options.dataToSend);
            dataToSend = dataToSend == null ? "" : this.convertToString(dataToSend);

            $.ajax({
                type: this.options.ajaxVerb,
                contentType: "application/json; charset=utf-8",
                url: this.options.sourceUrl,
                data: dataToSend,
                dataType: "json",
                success: function (data) {
                    funcCallback(itemId, baseElement, data);
                },
                error: function (jqXhr, textStatus, errorThrown) {
                    console.log("An error occurred when trying to obtain the nodes\n\njqXhr>" + jqXhr + "\n\ntextStatus>" + textStatus + "\n\nerrorThrown>" + errorThrown);
                }
            });
        },
        getChildrenNodesSuccess: function (itemId, parentElement, data) {
            if (data != null && data.length > 0) {
                var childTreeTag = $("<ul />").addClass("treeview").appendTo(parentElement);

                this.createNodeArray(data, childTreeTag);

                this.bindCheckboxes();

                if (this.options.onCompleted)
                    this.options.onCompleted(childTreeTag, this.myObject);
            }
        },

        getAllNodes: function () {
            var baseDataToSend = {};
            var dataToSend = $.extend(true, baseDataToSend, this.options.dataToSend);
            dataToSend = dataToSend == null ? "" : this.convertToString(dataToSend);

            var mySelf = this;
            $.ajax({
                type: this.options.ajaxVerb,
                contentType: "application/json; charset=utf-8",
                url: this.options.sourceUrl,
                data: dataToSend,
                dataType: "json",
                success: function (data) {
                    mySelf.getAllNodesSuccess(data, mySelf.myObject);
                },
                error: function (jqXhr, textStatus, errorThrown) {
                    console.log("An error occurred when trying to obtain the nodes\n\njqXhr>" + jqXhr + "\n\ntextStatus>" + textStatus + "\n\nerrorThrown>" + errorThrown);
                }
            });
        },
        getAllNodesSuccess: function (treeNode, parentElement) {
            if (treeNode != null) {
                var childTreeTag = $("<ul />").addClass("treeview").appendTo(parentElement);

                if ($.isArray(treeNode)) {
                    this.createNodeArray(treeNode, childTreeTag);
                } else {
                    this.createNode(treeNode, childTreeTag, "hit-single");
                }

                this.bindCheckboxes();
            }
        },
        createNodeArray: function (dataSource, parentElement) {
            for (var i = 0; i < dataSource.length; i++) {
                var item = dataSource[i];
                var hitPosition;

                if (dataSource.length == 1) {
                    hitPosition = "hit-single";
                } else {
                    switch (i) {
                        case 0:
                            hitPosition = "hit-first";
                            break;
                        case dataSource.length - 1:
                            hitPosition = "hit-last";
                            break;
                        default:
                            hitPosition = "";
                            break;
                    }
                }

                this.createNode(item, parentElement, hitPosition);
            }
        },
        createNode: function (item, parentElement, hitPosition) {
            // Create the base node li tag
            var nodeInnerTag = $("<li />");
            nodeInnerTag.attr("id", item.Id);
            nodeInnerTag.data("item", item);
            nodeInnerTag.addClass("node-bg-vimage");

            // Create the span hit area (where the plus and minus sign appears)
            var nodeSpanHit = $("<span />");
            nodeSpanHit.attr("id", item.Id);
            nodeSpanHit.addClass(hitPosition);
            nodeSpanHit.appendTo(nodeInnerTag);

            if (item.HasChild) {
                nodeInnerTag.addClass("with-child-node");

                nodeSpanHit.addClass("scontainer-expand");
                nodeSpanHit.addClass("hit-area");

                var mySelf = this;
                nodeSpanHit.click(function () {
                    mySelf.expandNode($(this).attr("id"));
                });
            } else {
                nodeInnerTag.addClass("without-child-node");

                nodeSpanHit.addClass("no-hit-area");
            }

            if (hitPosition == "hit-last" || hitPosition == "hit-single") {
                nodeInnerTag.removeClass("node-bg-vimage");
            }

            // Create a span to be used as a render node container.
            // The content of this container could be overridden by a custom _renderItem method.
            var spanText = $("<span />");
            spanText.addClass("scontainer-node-render-container");
            spanText.appendTo(nodeInnerTag);

            this.renderItem(spanText, item);

            // Attaching the new node to the parent element
            nodeInnerTag.appendTo(parentElement);

            if (this.options.onNodeCreated)
                this.options.onNodeCreated(nodeInnerTag, parentElement, this.myObject);

            // Expand child nodes
            if (item.HasChild && !this.options.loadNodesOnDemand) {
                this.switchCssClass(nodeInnerTag.children(".scontainer-expand"));

                this.getAllNodesSuccess(item.Children, nodeInnerTag);
            }
        },

        expandNode: function (itemNodeId) {
            var currentNode = this.getCurrentNodeById(itemNodeId);

            this.switchCssClass(currentNode.children(".scontainer-expand"));

            if (this.options.loadNodesOnDemand) {
                this.getChildrenNodes(itemNodeId, currentNode, $.proxy(this.getChildrenNodesSuccess, this));
            } else {
                this.getAllNodesSuccess(currentNode.data("item").Children, currentNode);
            }

            if (this.options.onNodeExpanded)
                this.options.onNodeExpanded(currentNode, this.myObject);
        },
        collapseNode: function (itemNodeId) {
            var currentNode = this.getCurrentNodeById(itemNodeId);

            this.switchCssClass(currentNode.children(".scontainer-collapse"));

            currentNode.children("ul").remove();

            if (this.options.onNodeColapsed)
                this.options.onNodeColapsed(currentNode, this.myObject);
        },

        renderItem: function (spanText, item) {
            if (this.options.showCheckbox) {
                var checkbox = $("<input />").attr("type", "checkbox").attr("value", item.Id).addClass("node-checkbox");
                checkbox.appendTo(spanText);

                if (this.options.checkboxesName)
                    checkbox.attr("name", this.options.checkboxesName);
            }

            var spanName = $("<span />");
            spanName.addClass("scontainer-node-text");
            spanName.html(item.Name);
            spanName.appendTo(spanText);
        },

        switchCssClass: function (workNode) {
            workNode.off('click');

            var mySelf = this;
            if (workNode.hasClass("scontainer-collapse")) {
                workNode.removeClass("scontainer-collapse").addClass("scontainer-expand");

                workNode.click(function () {
                    mySelf.expandNode($(this).attr("id"));
                });
            } else {
                if (workNode.hasClass("scontainer-expand")) {
                    workNode.removeClass("scontainer-expand").addClass("scontainer-collapse");

                    workNode.click(function () {
                        mySelf.collapseNode($(this).attr("id"));
                    });
                }
            }
        },
        convertToString: function (obj) {
            if (typeof JSON != "undefined") {
                return JSON.stringify(obj);
            }

            var arr = [];
            $.each(obj, function (key, val) {
                var next = key + ": ";
                next += $.isPlainObject(val) ? this.convertToString(val) : val;
                arr.push(next);
            });

            return "{ " + arr.join(", ") + " }";
        },
        getCurrentNodeById: function (nodeId) {
            return this.myObject.find("li[id='" + nodeId + "']").first();
        },

        bindCheckboxes: function () {
            var checkboxes = this.myObject.find("input[type='checkbox']");
            checkboxes.off("change");

            var mySelf = this;
            checkboxes.change(function () {
                var currentIsChecked = $(this).prop("checked");
                var container = $(this).parents("li").first();

                container.find("input[type='checkbox']").prop({ checked: currentIsChecked });

                mySelf.checkSiblingsState(container, currentIsChecked);
            });
        },
        checkSiblingsState: function (currentContainer, currentIsChecked) {
            var parent = currentContainer.parents("li").first();
            var siblingsState = true;

            var mySelf = this;
            currentContainer.siblings().each(function () {
                var siblingIsChecked = mySelf.getCurrentNodeCheckbox($(this)).prop("checked");
                return siblingsState = (siblingIsChecked === currentIsChecked);
            });

            if (siblingsState) {
                this.getCurrentNodeCheckbox(parent).prop({ checked: currentIsChecked });
                this.checkSiblingsState(parent);
            } else {
                this.getCurrentNodeCheckbox(currentContainer.parents("li")).prop({ checked: false });
            }
        },
        getCurrentNodeCheckbox: function (element) {
            return element.children(".scontainer-node-render-container").children('input[type="checkbox"]');
        }
    };

    return treeview;
})();

(function ($) {
    $.fn.treeview = function (options) {
        var defaults = {
            sourceUrl: "",
            dataToSend: null,
            ajaxVerb: "GET",
            onCompleted: null,
            onNodeExpanded: null,
            onNodeColapsed: null,
            onNodeCreated: null,
            renderItem: null,
            getChildrenNodes: null,
            showCheckbox: false,
            checkboxesName: null,
            loadNodesOnDemand: true
        };

        var settings = $.extend({}, defaults, options);

        this.each(function () {
            return new Treeview(this, settings);
        });
    };
})(jQuery);<|endoftext|>


<commit_before>import React from 'react'
import {
  Provider,
  Heading,
  Lead,
  Container,
  Flex,
  Box,
  Text,
  Subhead,
  Link as A
} from 'rebass'
import theme, { colors, cx, mx } from '../theme'
import { Head } from 'react-static'
import Nav from '../components/Nav'
import CTA from '../components/CTA'
import Icon from '../components/Icon'
import Footer from '../components/Footer'

const Section = Flex.extend.attrs({
  is: 'section',
  align: 'center',
  justify: 'center',
  direction: 'column',
  color: 'white',
  py: [4, 5],
  px: 3
})`
  background-color: ${props => cx(props.hues[1])};
  background-image: linear-gradient(16deg,
    ${props => cx(props.hues[0])} 0%,
    ${props => cx(props.hues[1])} 50%,
    ${props => cx(props.hues[2])} 100%);
  text-align: center;

  h2 img {
    display: inline-block;
  }
`
const One = props => (

)
const Two = props => (

)
const Three = props => (

)
const Four = props => (

)

const Modules = Flex.extend.attrs({
  wrap: true,
  justify: 'center',
  mt: 3,
  color: 'white'
})``

const ModuleBase = Flex.extend.attrs({
  w: [1, 1 / 3],
  py: 3,
  px: 2,
  direction: 'column',
  align: 'center'
})`
  img {
    width: 3rem !important;
    height: 3rem !important;
    flex-shrink: 0;
  }

  ${mx[1]} {
    max-width: 20rem;
  }
`

const ModuleHeading = Subhead.extend.attrs({
  mt: 0,
  mb: 1,
  f: 3,
  color: 'white'
})``
const ModuleBody = Text.extend.attrs({ my: 0, f: 2, color: 'white' })`
  line-height: 1.5;
  position: relative;
`
const ModuleDivider = Box.extend.attrs({ w: 64, bg: 'white', mt: 3 })`
  width: 64px;
  height: 6px;
`

const Module = ({ icon, heading, body, ...props }) => (
  <ModuleBase>
    <Icon name={icon} fill="white" />
    <ModuleHeading children={heading} />
    <ModuleBody children={body} />
    <ModuleDivider />
  </ModuleBase>
)

const CTASection = Box.extend.attrs({
  is: 'section',
  px: 3,
  my: [3, 5]
})`
  text-align: center;
`

export default () => (
  <Provider theme={theme}>

      <title>Start – Hack Club</title>

    <One>

      <Heading is="h1" f={[5, 6]} mt={[4, 5]}>
        Let’s get your Hack Club started.
      </Heading>
      <Heading f={[3, 4]} my={2} style={{ fontWeight: 'normal' }}>
        The awesome coding club at your high school is coming soon.
      </Heading>
    </One>
    <Two>
      <Heading f={[4, 5]}>
        HQ provides the resources you’ll need to{' '}
        <Icon name="directions_run" fill="white" size={36} />.
      </Heading>
      <Modules>
        <Module
          icon="forum"
          heading="Online community"
          body="Join our Slack and meet thousands of other club leaders and members."
        />
        <Module
          icon="chrome_reader_mode"
          heading="Curriculum"
          body="Give your members dozens of tutorials for making websites, apps, and games."
        />
        <Module
          icon="voice_chat"
          heading="Mentorship"
          body="Talk to our team for guidance and assistance whenever you need help."
        />
        <Module
          icon="description"
          heading="Structure & guidelines"
          body="Learn from hundreds of other clubs—we’ve got advice, docs, and experience."
        />
        <Module
          icon="local_activity"
          heading="Local events"
          body="Attend hackathons, workshops, and other events from Hack Clubs nearby."
        />
        <Module
          icon="wallpaper"
          heading="Marketing"
          body="Get stickers, posters, and ideas for spreading the word about your club."
        />
      </Modules>
    </Two>

  </Provider>
)
<commit_msg>Shorten<commit_after>import React from 'react'
import {
  Provider,
  Heading,
  Lead,
  Container,
  Flex,
  Box,
  Text,
  Subhead,
  Link as A
} from 'rebass'
import theme, { colors, cx, mx } from '../theme'
import { Head } from 'react-static'
import Nav from '../components/Nav'
import CTA from '../components/CTA'
import Icon from '../components/Icon'
import Footer from '../components/Footer'

const Section = Flex.extend.attrs({
  is: 'section',
  align: 'center',
  justify: 'center',
  direction: 'column',
  color: 'white',
  py: [4, 5],
  px: 3
})`
  background-color: ${props => cx(props.hues[1])};
  background-image: linear-gradient(16deg,
    ${props => cx(props.hues[0])} 0%,
    ${props => cx(props.hues[1])} 50%,
    ${props => cx(props.hues[2])} 100%);
  text-align: center;

  h2 img {
    display: inline-block;
  }
`
const One = props => (

)
const Two = props => (

)
const Three = props => (

)
const Four = props => (

)

const Modules = Flex.extend.attrs({
  wrap: true,
  justify: 'center',
  mt: 3,
  color: 'white'
})``

const ModuleBase = Flex.extend.attrs({
  w: [1, 1 / 3],
  py: 3,
  px: 2,
  direction: 'column',
  align: 'center'
})`
  img {
    width: 3rem !important;
    height: 3rem !important;
    flex-shrink: 0;
  }

  ${mx[1]} {
    max-width: 20rem;
  }
`

const ModuleHeading = Subhead.extend.attrs({ mt: 0, mb: 1, f: 3 })``
const ModuleBody = Text.extend.attrs({ my: 0, f: 2 })`
  line-height: 1.5;
  position: relative;
`
const ModuleDivider = Box.extend.attrs({ w: 64, bg: 'white', mt: 3 })`
  width: 64px;
  height: 6px;
`

const Module = ({ icon, heading, body, ...props }) => (
  <ModuleBase>
    <Icon name={icon} fill="white" />
    <ModuleHeading children={heading} />
    <ModuleBody children={body} />
    <ModuleDivider />
  </ModuleBase>
)

const CTASection = Box.extend.attrs({ is: 'section', px: 3, my: [3, 5] })`
  text-align: center;
`

export default () => (
  <Provider theme={theme}>

      <title>Start – Hack Club</title>

    <One>

      <Heading is="h1" f={[5, 6]} mt={[4, 5]}>
        Let’s get your Hack Club started.
      </Heading>
      <Heading f={[3, 4]} my={2} style={{ fontWeight: 'normal' }}>
        The awesome coding club at your high school is coming soon.
      </Heading>
    </One>
    <Two>
      <Heading f={[4, 5]}>
        HQ provides the resources you’ll need to{' '}
        <Icon name="directions_run" fill="white" size={36} />.
      </Heading>
      <Modules>
        <Module
          icon="forum"
          heading="Online community"
          body="Join our Slack and meet thousands of other club leaders and members."
        />
        <Module
          icon="chrome_reader_mode"
          heading="Curriculum"
          body="Give your members dozens of tutorials for making websites, apps, and games."
        />
        <Module
          icon="voice_chat"
          heading="Mentorship"
          body="Talk to our team for guidance and assistance whenever you need help."
        />
        <Module
          icon="description"
          heading="Structure & guidelines"
          body="Learn from hundreds of other clubs—we’ve got advice, docs, and experience."
        />
        <Module
          icon="local_activity"
          heading="Local events"
          body="Attend hackathons, workshops, and other events from Hack Clubs nearby."
        />
        <Module
          icon="wallpaper"
          heading="Marketing"
          body="Get stickers, posters, and ideas for spreading the word about your club."
        />
      </Modules>
    </Two>

  </Provider>
)
<|endoftext|>


<commit_before>export default DS.RESTAdapter.extend({

  //db: new PouchDB('http://localhost:5984/ember-todo'),

  _init: function (type) {
    var self = this;
    if (!this.db || typeof this.db !== 'object') {
      throw new Error('Please set the `db` property on the adapter.');
    }

    this._schema = this._schema || [];

    var singular = type.typeKey;
    var plural = Ember.String.pluralize(type.typeKey);

    // check that we haven't already registered this model
    for (var i = 0, len = this._schema.length; i < len; i++) {
      var currentSchemaDef = this._schema[i];
      if (currentSchemaDef.singular === singular) {
        return;
      }
    }

    var schemaDef = {
      singular: singular,
      plural: plural
    };

    // else it's new, so update
    this._schema.push(schemaDef);

    // check all the subtypes
    type.eachRelationship(function (_, rel) {
      if (rel.kind !== 'belongsTo' && rel.kind !== 'hasMany') {
        // TODO: support inverse as well
        return; // skip
      }
      var relDef = {};
      relDef[rel.kind] = rel.type.typeKey;
      if (!schemaDef.relations) {
        schemaDef.relations = {};
      }
      schemaDef.relations[rel.key] = relDef;
      self._init(rel.type);
    });

    this.db.setSchema(this._schema);
  },

  _recordToData: function (store, type, record) {
    var data = {};
    var serializer = store.serializerFor(type.typeKey);

    serializer.serializeIntoHash(data, type, record, { includeId: true });

    data = data[type.typeKey];

    // ember sets it to null automatically. don't need it.
    if (data.rev === null) {
      delete data.rev;
    }

    return data;
  },

  findAll: function(store, type /*, sinceToken */) {
    // TODO: use sinceToken
    this._init(type);
    return this.db.rel.find(type.typeKey);
  },

  findMany: function(store, type, ids) {
    this._init(type);
    return this.db.rel.find(type.typeKey, ids);
  },

  find: function (store, type, id) {
    this._init(type);
    return this.db.rel.find(type.typeKey, id);
  },

  createRecord: function(store, type, record) {
    this._init(type);
    var data = this._recordToData(store, type, record);
    return this.db.rel.save(type.typeKey, data);
  },

  updateRecord: function (store, type, record) {
    this._init(type);
    var data = this._recordToData(store, type, record);
    return this.db.rel.save(type.typeKey, data);
  },

  deleteRecord: function (store, type, record) {
    this._init(type);
    var data = this._recordToData(store, type, record);
    return this.db.rel.del(type.typeKey, data).then(function () {
      return ''; // ember doesn't like getting a json response of {deleted: true}
    });
  }
});
<commit_msg>fix empty payload<commit_after>export default DS.RESTAdapter.extend({

  //db: new PouchDB('http://localhost:5984/ember-todo'),

  _init: function (type) {
    var self = this;
    if (!this.db || typeof this.db !== 'object') {
      throw new Error('Please set the `db` property on the adapter.');
    }

    this._schema = this._schema || [];

    var singular = type.typeKey;
    var plural = Ember.String.pluralize(type.typeKey);

    // check that we haven't already registered this model
    for (var i = 0, len = this._schema.length; i < len; i++) {
      var currentSchemaDef = this._schema[i];
      if (currentSchemaDef.singular === singular) {
        return;
      }
    }

    var schemaDef = {
      singular: singular,
      plural: plural
    };

    // else it's new, so update
    this._schema.push(schemaDef);

    // check all the subtypes
    type.eachRelationship(function (_, rel) {
      if (rel.kind !== 'belongsTo' && rel.kind !== 'hasMany') {
        // TODO: support inverse as well
        return; // skip
      }
      var relDef = {};
      relDef[rel.kind] = rel.type.typeKey;
      if (!schemaDef.relations) {
        schemaDef.relations = {};
      }
      schemaDef.relations[rel.key] = relDef;
      self._init(rel.type);
    });

    this.db.setSchema(this._schema);
  },

  _recordToData: function (store, type, record) {
    var data = {};
    var serializer = store.serializerFor(type.typeKey);

    serializer.serializeIntoHash(data, type, record, { includeId: true });

    data = data[type.typeKey];

    // ember sets it to null automatically. don't need it.
    if (data.rev === null) {
      delete data.rev;
    }

    return data;
  },

  findAll: function(store, type /*, sinceToken */) {
    // TODO: use sinceToken
    this._init(type);
    return this.db.rel.find(type.typeKey);
  },

  findMany: function(store, type, ids) {
    this._init(type);
    return this.db.rel.find(type.typeKey, ids);
  },

  find: function (store, type, id) {
    this._init(type);
    return this.db.rel.find(type.typeKey, id).then(function (payload) {
      // Ember Data chokes on empty payload, this function throws
      // an error when the requested data is not found
      if (typeof payload === 'object' && payload !== null) {
        for (var type in payload) {
          if (payload.hasOwnProperty(type)) {
            var results = payload[type];
            if (results && results.length > 0) {
              return payload;
            }
          }
        }
        throw new Error('Not found: type "' + type.typeKey +
          '" with id "' + id + '"');
      }
      return payload;
    });
  },

  createRecord: function(store, type, record) {
    this._init(type);
    var data = this._recordToData(store, type, record);
    return this.db.rel.save(type.typeKey, data);
  },

  updateRecord: function (store, type, record) {
    this._init(type);
    var data = this._recordToData(store, type, record);
    return this.db.rel.save(type.typeKey, data);
  },

  deleteRecord: function (store, type, record) {
    this._init(type);
    var data = this._recordToData(store, type, record);
    return this.db.rel.del(type.typeKey, data).then(function () {
      return ''; // ember doesn't like getting a json response of {deleted: true}
    });
  }
});
<|endoftext|>


<commit_before>$ = jQuery  = require('jquery')
moment      = require('moment')
momenttz    = require('moment-timezone')
extend_impl = require('extend')
Handlebars  = require('handlebars')
URI         = require('URIjs')
ss          = require('simple-statistics')
inflection  = require('inflection')
d3          = require('d3')
bootbox     = require('bootbox')
Color       = require('color')
Holder      = require('holderjs')
marked      = require('marked')
hljs        = require('highlight.js')
Mousetrap   = require('mousetrap')
bean        = require('bean')
bootstrap   = require('bootstrap')
select2     = require('select2')
store       = require('store')
growl       = require('bootstrap-growl')
datatables  = require('datatables')
saveAs      = require('filesaver.js')
Promise     = require('bluebird')
humanize_duration = require('humanize-duration')
<commit_msg>Need to update the require() call for bootstrap-growl-legacy as well<commit_after>$ = jQuery  = require('jquery')
moment      = require('moment')
momenttz    = require('moment-timezone')
extend_impl = require('extend')
Handlebars  = require('handlebars')
URI         = require('URIjs')
ss          = require('simple-statistics')
inflection  = require('inflection')
d3          = require('d3')
bootbox     = require('bootbox')
Color       = require('color')
Holder      = require('holderjs')
marked      = require('marked')
hljs        = require('highlight.js')
Mousetrap   = require('mousetrap')
bean        = require('bean')
bootstrap   = require('bootstrap')
select2     = require('select2')
store       = require('store')
growl       = require('bootstrap-growl-legacy')
datatables  = require('datatables')
saveAs      = require('filesaver.js')
Promise     = require('bluebird')
humanize_duration = require('humanize-duration')
<|endoftext|>