<commit_before>/*!
 * Nestable jQuery Plugin - Copyright (c) 2012 David Bushell - http://dbushell.com/
 * Dual-licensed under the BSD or MIT licenses
 */
;(function($, window, document, undefined)
{
    var hasTouch = 'ontouchstart' in window;

    /**
     * Detect CSS pointer-events property
     * events are normally disabled on the dragging element to avoid conflicts
     * https://github.com/ausi/Feature-detection-technique-for-pointer-events/blob/master/modernizr-pointerevents.js
     */
    var hasPointerEvents = (function()
    {
        var el    = document.createElement('div'),
            docEl = document.documentElement;
        if (!('pointerEvents' in el.style)) {
            return false;
        }
        el.style.pointerEvents = 'auto';
        el.style.pointerEvents = 'x';
        docEl.appendChild(el);
        var supports = window.getComputedStyle && window.getComputedStyle(el, '').pointerEvents === 'auto';
        docEl.removeChild(el);
        return !!supports;
    })();

    var eStart  = hasTouch ? 'touchstart'  : 'mousedown',
        eMove   = hasTouch ? 'touchmove'   : 'mousemove',
        eEnd    = hasTouch ? 'touchend'    : 'mouseup';
        eCancel = hasTouch ? 'touchcancel' : 'mouseup';

    var defaults = {
            listNodeName    : 'ol',
            itemNodeName    : 'li',
            rootClass       : 'dd',
            listClass       : 'dd-list',
            itemClass       : 'dd-item',
            dragClass       : 'dd-dragel',
            handleClass     : 'dd-handle',
            collapsedClass  : 'dd-collapsed',
            placeClass      : 'dd-placeholder',
            noDragClass     : 'dd-nodrag',
            emptyClass      : 'dd-empty',
            expandBtnHTML   : '<button data-action="expand" type="button">Expand</button>',
            collapseBtnHTML : '<button data-action="collapse" type="button">Collapse</button>',
            group           : 0,
            maxDepth        : 5,
            threshold       : 20
        };

    function Plugin(element, options)
    {
        this.w  = $(window);
        this.el = $(element);
        this.options = $.extend({}, defaults, options);
        this.init();
    }

    Plugin.prototype = {

        init: function()
        {
            var list = this;

            list.reset();

            list.el.data('nestable-group', this.options.group);

            list.placeEl = $('
');

            $.each(this.el.find(list.options.itemNodeName), function(k, el) {
                list.setParent($(el));
            });

            list.el.on('click', 'button', function(e) {
                if (list.dragEl || (!hasTouch && e.button !== 0)) {
                    return;
                }
                var target = $(e.currentTarget),
                    action = target.data('action'),
                    item   = target.parent(list.options.itemNodeName);
                if (action === 'collapse') {
                    list.collapseItem(item);
                }
                if (action === 'expand') {
                    list.expandItem(item);
                }
            });

            var onStartEvent = function(e)
            {
                var handle = $(e.target);
                if (!handle.hasClass(list.options.handleClass)) {
                    if (handle.closest('.' + list.options.noDragClass).length) {
                        return;
                    }
                    handle = handle.closest('.' + list.options.handleClass);
                }
                if (!handle.length || list.dragEl || (!hasTouch && e.button !== 0) || (hasTouch && e.touches.length !== 1)) {
                    return;
                }
                e.preventDefault();
                list.dragStart(hasTouch ? e.touches[0] : e);
            };

            var onMoveEvent = function(e)
            {
                if (list.dragEl) {
                    e.preventDefault();
                    list.dragMove(hasTouch ? e.touches[0] : e);
                }
            };

            var onEndEvent = function(e)
            {
                if (list.dragEl) {
                    e.preventDefault();
                    list.dragStop(hasTouch ? e.touches[0] : e);
                }
            };

            if (hasTouch) {
                list.el[0].addEventListener(eStart, onStartEvent, false);
                window.addEventListener(eMove, onMoveEvent, false);
                window.addEventListener(eEnd, onEndEvent, false);
                window.addEventListener(eCancel, onEndEvent, false);
            } else {
                list.el.on(eStart, onStartEvent);
                list.w.on(eMove, onMoveEvent);
                list.w.on(eEnd, onEndEvent);
            }

        },

        serialize: function()
        {
            var data,
                depth = 0,
                list  = this;
                step  = function(level, depth)
                {
                    var array = [ ],
                        items = level.children(list.options.itemNodeName);
                    items.each(function()
                    {
                        var li   = $(this),
                            item = $.extend({}, li.data()),
                            sub  = li.children(list.options.listNodeName);
                        if (sub.length) {
                            item.children = step(sub, depth + 1);
                        }
                        array.push(item);
                    });
                    return array;
                };
            data = step(list.el.find(list.options.listNodeName).first(), depth);
            return data;
        },

        serialise: function()
        {
            return this.serialize();
        },

        reset: function()
        {
            this.mouse = {
                offsetX   : 0,
                offsetY   : 0,
                startX    : 0,
                startY    : 0,
                lastX     : 0,
                lastY     : 0,
                nowX      : 0,
                nowY      : 0,
                distX     : 0,
                distY     : 0,
                dirAx     : 0,
                dirX      : 0,
                dirY      : 0,
                lastDirX  : 0,
                lastDirY  : 0,
                distAxX   : 0,
                distAxY   : 0
            };
            this.moving     = false;
            this.dragEl     = null;
            this.dragRootEl = null;
            this.dragDepth  = 0;
            this.hasNewRoot = false;
            this.pointEl    = null;
        },

        expandItem: function(li)
        {
            li.removeClass(this.options.collapsedClass);
            li.children('[data-action="expand"]').hide();
            li.children('[data-action="collapse"]').show();
            li.children(this.options.listNodeName).show();
        },

        collapseItem: function(li)
        {
            var lists = li.children(this.options.listNodeName);
            if (lists.length) {
                li.addClass(this.options.collapsedClass);
                li.children('[data-action="collapse"]').hide();
                li.children('[data-action="expand"]').show();
                li.children(this.options.listNodeName).hide();
            }
        },

        expandAll: function()
        {
            var list = this;
            list.el.find(list.options.itemNodeName).each(function() {
                list.expandItem($(this));
            });
        },

        collapseAll: function()
        {
            var list = this;
            list.el.find(list.options.itemNodeName).each(function() {
                list.collapseItem($(this));
            });
        },

        setParent: function(li)
        {
            if (li.children(this.options.listNodeName).length) {
                li.prepend($(this.options.expandBtnHTML));
                li.prepend($(this.options.collapseBtnHTML));
            }
            li.children('[data-action="expand"]').hide();
        },

        unsetParent: function(li)
        {
            li.removeClass(this.options.collapsedClass);
            li.children('[data-action]').remove();
            li.children(this.options.listNodeName).remove();
        },

        dragStart: function(e)
        {
            var mouse    = this.mouse,
                target   = $(e.target),
                dragItem = target.closest(this.options.itemNodeName);

            this.placeEl.css('height', dragItem.height());

            mouse.offsetX = e.offsetX !== undefined ? e.offsetX : e.pageX - target.offset().left;
            mouse.offsetY = e.offsetY !== undefined ? e.offsetY : e.pageY - target.offset().top;
            mouse.startX = mouse.lastX = e.pageX;
            mouse.startY = mouse.lastY = e.pageY;

            this.dragRootEl = this.el;

            this.dragEl = $(document.createElement(this.options.listNodeName)).addClass(this.options.listClass + ' ' + this.options.dragClass);
            this.dragEl.css('width', dragItem.width());

            // fix for zepto.js
            //dragItem.after(this.placeEl).detach().appendTo(this.dragEl);
            dragItem.after(this.placeEl);
            dragItem[0].parentNode.removeChild(dragItem[0]);
            dragItem.appendTo(this.dragEl);

            $(document.body).append(this.dragEl);
            this.dragEl.css({
                'left' : e.pageX - mouse.offsetX,
                'top'  : e.pageY - mouse.offsetY
            });
            // total depth of dragging item
            var i, depth,
                items = this.dragEl.find(this.options.itemNodeName);
            for (i = 0; i < items.length; i++) {
                depth = $(items[i]).parents(this.options.listNodeName).length;
                if (depth > this.dragDepth) {
                    this.dragDepth = depth;
                }
            }
        },

        dragStop: function(e)
        {
            // fix for zepto.js
            //this.placeEl.replaceWith(this.dragEl.children(this.options.itemNodeName + ':first').detach());
            var el = this.dragEl.children(this.options.itemNodeName).first();
            el[0].parentNode.removeChild(el[0]);
            this.placeEl.replaceWith(el);

            this.dragEl.remove();
            this.el.trigger('change');
            if (this.hasNewRoot) {
                this.dragRootEl.trigger('change');
            }
            this.reset();
        },

        dragMove: function(e)
        {
            var list, parent, prev, next, depth,
                opt   = this.options,
                mouse = this.mouse;

            this.dragEl.css({
                'left' : e.pageX - mouse.offsetX,
                'top'  : e.pageY - mouse.offsetY
            });

            // mouse position last events
            mouse.lastX = mouse.nowX;
            mouse.lastY = mouse.nowY;
            // mouse position this events
            mouse.nowX  = e.pageX;
            mouse.nowY  = e.pageY;
            // distance mouse moved between events
            mouse.distX = mouse.nowX - mouse.lastX;
            mouse.distY = mouse.nowY - mouse.lastY;
            // direction mouse was moving
            mouse.lastDirX = mouse.dirX;
            mouse.lastDirY = mouse.dirY;
            // direction mouse is now moving (on both axis)
            mouse.dirX = mouse.distX === 0 ? 0 : mouse.distX > 0 ? 1 : -1;
            mouse.dirY = mouse.distY === 0 ? 0 : mouse.distY > 0 ? 1 : -1;
            // axis mouse is now moving on
            var newAx   = Math.abs(mouse.distX) > Math.abs(mouse.distY) ? 1 : 0;

            // do nothing on first move
            if (!mouse.moving) {
                mouse.dirAx  = newAx;
                mouse.moving = true;
                return;
            }

            // calc distance moved on this axis (and direction)
            if (mouse.dirAx !== newAx) {
                mouse.distAxX = 0;
                mouse.distAxY = 0;
            } else {
                mouse.distAxX += Math.abs(mouse.distX);
                if (mouse.dirX !== 0 && mouse.dirX !== mouse.lastDirX) {
                    mouse.distAxX = 0;
                }
                mouse.distAxY += Math.abs(mouse.distY);
                if (mouse.dirY !== 0 && mouse.dirY !== mouse.lastDirY) {
                    mouse.distAxY = 0;
                }
            }
            mouse.dirAx = newAx;

            /**
             * move horizontal
             */
            if (mouse.dirAx && mouse.distAxX >= opt.threshold) {
                // reset move distance on x-axis for new phase
                mouse.distAxX = 0;
                prev = this.placeEl.prev(opt.itemNodeName);
                // increase horizontal level if previous sibling exists and is not collapsed
                if (mouse.distX > 0 && prev.length && !prev.hasClass(opt.collapsedClass)) {
                    // cannot increase level when item above is collapsed
                    list = prev.find(opt.listNodeName).last();
                    // check if depth limit has reached
                    depth = this.placeEl.parents(opt.listNodeName).length;
                    if (depth + this.dragDepth <= opt.maxDepth) {
                        // create new sub-level if one doesn't exist
                        if (!list.length) {
                            list = $('<' + opt.listNodeName + '/>').addClass(opt.listClass);
                            list.append(this.placeEl);
                            prev.append(list);
                            this.setParent(prev);
                        } else {
                            // else append to next level up
                            list = prev.children(opt.listNodeName).last();
                            list.append(this.placeEl);
                        }
                    }
                }
                // decrease horizontal level
                if (mouse.distX < 0) {
                    // we can't decrease a level if an item preceeds the current one
                    next = this.placeEl.next(opt.itemNodeName);
                    if (!next.length) {
                        parent = this.placeEl.parent();
                        this.placeEl.closest(opt.itemNodeName).after(this.placeEl);
                        if (!parent.children().length) {
                            this.unsetParent(parent.parent());
                        }
                    }
                }
            }

            var isEmpty = false;

            // find list item under cursor
            if (!hasPointerEvents) {
                this.dragEl[0].style.visibility = 'hidden';
            }
            this.pointEl = $(document.elementFromPoint(e.pageX - document.body.scrollLeft, e.pageY - (window.pageYOffset || document.documentElement.scrollTop)));
            if (!hasPointerEvents) {
                this.dragEl[0].style.visibility = 'visible';
            }
            if (this.pointEl.hasClass(opt.handleClass)) {
                this.pointEl = this.pointEl.parent(opt.itemNodeName);
            }
            if (this.pointEl.hasClass(opt.emptyClass)) {
                isEmpty = true;
            }
            else if (!this.pointEl.length || !this.pointEl.hasClass(opt.itemClass)) {
                return;
            }

            // find parent list of item under cursor
            var pointElRoot = this.pointEl.closest('.' + opt.rootClass),
                isNewRoot   = this.dragRootEl.data('nestable-id') !== pointElRoot.data('nestable-id');

            /**
             * move vertical
             */
            if (!mouse.dirAx || isNewRoot || isEmpty) {
                // check if groups match if dragging over new root
                if (isNewRoot && opt.group !== pointElRoot.data('nestable-group')) {
                    return;
                }
                // check depth limit
                depth = this.dragDepth - 1 + this.pointEl.parents(opt.listNodeName).length;
                if (depth > opt.maxDepth) {
                    return;
                }
                var before = e.pageY < (this.pointEl.offset().top + this.pointEl.height() / 2);
                    parent = this.placeEl.parent();
                // if empty create new list to replace empty placeholder
                if (isEmpty) {
                    list = $(document.createElement(opt.listNodeName)).addClass(opt.listClass);
                    list.append(this.placeEl);
                    this.pointEl.replaceWith(list);
                }
                else if (before) {
                    this.pointEl.before(this.placeEl);
                }
                else {
                    this.pointEl.after(this.placeEl);
                }
                if (!parent.children().length) {
                    this.unsetParent(parent.parent());
                }
                if (!this.dragRootEl.find(opt.itemNodeName).length) {
                    this.dragRootEl.append('
');
                }
                // parent root list has changed
                if (isNewRoot) {
                    this.dragRootEl = pointElRoot;
                    this.hasNewRoot = this.el[0] !== this.dragRootEl[0];
                }
            }
        }

    };

    $.fn.nestable = function(params)
    {
        var lists  = this,
            retval = this;

        lists.each(function()
        {
            var plugin = $(this).data("nestable");

            if (!plugin) {
                $(this).data("nestable", new Plugin(this, params));
                $(this).data("nestable-id", new Date().getTime());
            } else {
                if (typeof params === 'string' && typeof plugin[params] === 'function') {
                    retval = plugin[params]();
                }
            }
        });

        return retval || lists;
    };

})(window.jQuery || window.Zepto, window, document);
<commit_msg>remove dev notes<commit_after>/*!
 * Nestable jQuery Plugin - Copyright (c) 2012 David Bushell - http://dbushell.com/
 * Dual-licensed under the BSD or MIT licenses
 */
;(function($, window, document, undefined)
{
    var hasTouch = 'ontouchstart' in window;

    /**
     * Detect CSS pointer-events property
     * events are normally disabled on the dragging element to avoid conflicts
     * https://github.com/ausi/Feature-detection-technique-for-pointer-events/blob/master/modernizr-pointerevents.js
     */
    var hasPointerEvents = (function()
    {
        var el    = document.createElement('div'),
            docEl = document.documentElement;
        if (!('pointerEvents' in el.style)) {
            return false;
        }
        el.style.pointerEvents = 'auto';
        el.style.pointerEvents = 'x';
        docEl.appendChild(el);
        var supports = window.getComputedStyle && window.getComputedStyle(el, '').pointerEvents === 'auto';
        docEl.removeChild(el);
        return !!supports;
    })();

    var eStart  = hasTouch ? 'touchstart'  : 'mousedown',
        eMove   = hasTouch ? 'touchmove'   : 'mousemove',
        eEnd    = hasTouch ? 'touchend'    : 'mouseup';
        eCancel = hasTouch ? 'touchcancel' : 'mouseup';

    var defaults = {
            listNodeName    : 'ol',
            itemNodeName    : 'li',
            rootClass       : 'dd',
            listClass       : 'dd-list',
            itemClass       : 'dd-item',
            dragClass       : 'dd-dragel',
            handleClass     : 'dd-handle',
            collapsedClass  : 'dd-collapsed',
            placeClass      : 'dd-placeholder',
            noDragClass     : 'dd-nodrag',
            emptyClass      : 'dd-empty',
            expandBtnHTML   : '<button data-action="expand" type="button">Expand</button>',
            collapseBtnHTML : '<button data-action="collapse" type="button">Collapse</button>',
            group           : 0,
            maxDepth        : 5,
            threshold       : 20
        };

    function Plugin(element, options)
    {
        this.w  = $(window);
        this.el = $(element);
        this.options = $.extend({}, defaults, options);
        this.init();
    }

    Plugin.prototype = {

        init: function()
        {
            var list = this;

            list.reset();

            list.el.data('nestable-group', this.options.group);

            list.placeEl = $('
');

            $.each(this.el.find(list.options.itemNodeName), function(k, el) {
                list.setParent($(el));
            });

            list.el.on('click', 'button', function(e) {
                if (list.dragEl || (!hasTouch && e.button !== 0)) {
                    return;
                }
                var target = $(e.currentTarget),
                    action = target.data('action'),
                    item   = target.parent(list.options.itemNodeName);
                if (action === 'collapse') {
                    list.collapseItem(item);
                }
                if (action === 'expand') {
                    list.expandItem(item);
                }
            });

            var onStartEvent = function(e)
            {
                var handle = $(e.target);
                if (!handle.hasClass(list.options.handleClass)) {
                    if (handle.closest('.' + list.options.noDragClass).length) {
                        return;
                    }
                    handle = handle.closest('.' + list.options.handleClass);
                }
                if (!handle.length || list.dragEl || (!hasTouch && e.button !== 0) || (hasTouch && e.touches.length !== 1)) {
                    return;
                }
                e.preventDefault();
                list.dragStart(hasTouch ? e.touches[0] : e);
            };

            var onMoveEvent = function(e)
            {
                if (list.dragEl) {
                    e.preventDefault();
                    list.dragMove(hasTouch ? e.touches[0] : e);
                }
            };

            var onEndEvent = function(e)
            {
                if (list.dragEl) {
                    e.preventDefault();
                    list.dragStop(hasTouch ? e.touches[0] : e);
                }
            };

            if (hasTouch) {
                list.el[0].addEventListener(eStart, onStartEvent, false);
                window.addEventListener(eMove, onMoveEvent, false);
                window.addEventListener(eEnd, onEndEvent, false);
                window.addEventListener(eCancel, onEndEvent, false);
            } else {
                list.el.on(eStart, onStartEvent);
                list.w.on(eMove, onMoveEvent);
                list.w.on(eEnd, onEndEvent);
            }

        },

        serialize: function()
        {
            var data,
                depth = 0,
                list  = this;
                step  = function(level, depth)
                {
                    var array = [ ],
                        items = level.children(list.options.itemNodeName);
                    items.each(function()
                    {
                        var li   = $(this),
                            item = $.extend({}, li.data()),
                            sub  = li.children(list.options.listNodeName);
                        if (sub.length) {
                            item.children = step(sub, depth + 1);
                        }
                        array.push(item);
                    });
                    return array;
                };
            data = step(list.el.find(list.options.listNodeName).first(), depth);
            return data;
        },

        serialise: function()
        {
            return this.serialize();
        },

        reset: function()
        {
            this.mouse = {
                offsetX   : 0,
                offsetY   : 0,
                startX    : 0,
                startY    : 0,
                lastX     : 0,
                lastY     : 0,
                nowX      : 0,
                nowY      : 0,
                distX     : 0,
                distY     : 0,
                dirAx     : 0,
                dirX      : 0,
                dirY      : 0,
                lastDirX  : 0,
                lastDirY  : 0,
                distAxX   : 0,
                distAxY   : 0
            };
            this.moving     = false;
            this.dragEl     = null;
            this.dragRootEl = null;
            this.dragDepth  = 0;
            this.hasNewRoot = false;
            this.pointEl    = null;
        },

        expandItem: function(li)
        {
            li.removeClass(this.options.collapsedClass);
            li.children('[data-action="expand"]').hide();
            li.children('[data-action="collapse"]').show();
            li.children(this.options.listNodeName).show();
        },

        collapseItem: function(li)
        {
            var lists = li.children(this.options.listNodeName);
            if (lists.length) {
                li.addClass(this.options.collapsedClass);
                li.children('[data-action="collapse"]').hide();
                li.children('[data-action="expand"]').show();
                li.children(this.options.listNodeName).hide();
            }
        },

        expandAll: function()
        {
            var list = this;
            list.el.find(list.options.itemNodeName).each(function() {
                list.expandItem($(this));
            });
        },

        collapseAll: function()
        {
            var list = this;
            list.el.find(list.options.itemNodeName).each(function() {
                list.collapseItem($(this));
            });
        },

        setParent: function(li)
        {
            if (li.children(this.options.listNodeName).length) {
                li.prepend($(this.options.expandBtnHTML));
                li.prepend($(this.options.collapseBtnHTML));
            }
            li.children('[data-action="expand"]').hide();
        },

        unsetParent: function(li)
        {
            li.removeClass(this.options.collapsedClass);
            li.children('[data-action]').remove();
            li.children(this.options.listNodeName).remove();
        },

        dragStart: function(e)
        {
            var mouse    = this.mouse,
                target   = $(e.target),
                dragItem = target.closest(this.options.itemNodeName);

            this.placeEl.css('height', dragItem.height());

            mouse.offsetX = e.offsetX !== undefined ? e.offsetX : e.pageX - target.offset().left;
            mouse.offsetY = e.offsetY !== undefined ? e.offsetY : e.pageY - target.offset().top;
            mouse.startX = mouse.lastX = e.pageX;
            mouse.startY = mouse.lastY = e.pageY;

            this.dragRootEl = this.el;

            this.dragEl = $(document.createElement(this.options.listNodeName)).addClass(this.options.listClass + ' ' + this.options.dragClass);
            this.dragEl.css('width', dragItem.width());

            dragItem.after(this.placeEl);
            dragItem[0].parentNode.removeChild(dragItem[0]);
            dragItem.appendTo(this.dragEl);

            $(document.body).append(this.dragEl);
            this.dragEl.css({
                'left' : e.pageX - mouse.offsetX,
                'top'  : e.pageY - mouse.offsetY
            });
            // total depth of dragging item
            var i, depth,
                items = this.dragEl.find(this.options.itemNodeName);
            for (i = 0; i < items.length; i++) {
                depth = $(items[i]).parents(this.options.listNodeName).length;
                if (depth > this.dragDepth) {
                    this.dragDepth = depth;
                }
            }
        },

        dragStop: function(e)
        {
            var el = this.dragEl.children(this.options.itemNodeName).first();
            el[0].parentNode.removeChild(el[0]);
            this.placeEl.replaceWith(el);

            this.dragEl.remove();
            this.el.trigger('change');
            if (this.hasNewRoot) {
                this.dragRootEl.trigger('change');
            }
            this.reset();
        },

        dragMove: function(e)
        {
            var list, parent, prev, next, depth,
                opt   = this.options,
                mouse = this.mouse;

            this.dragEl.css({
                'left' : e.pageX - mouse.offsetX,
                'top'  : e.pageY - mouse.offsetY
            });

            // mouse position last events
            mouse.lastX = mouse.nowX;
            mouse.lastY = mouse.nowY;
            // mouse position this events
            mouse.nowX  = e.pageX;
            mouse.nowY  = e.pageY;
            // distance mouse moved between events
            mouse.distX = mouse.nowX - mouse.lastX;
            mouse.distY = mouse.nowY - mouse.lastY;
            // direction mouse was moving
            mouse.lastDirX = mouse.dirX;
            mouse.lastDirY = mouse.dirY;
            // direction mouse is now moving (on both axis)
            mouse.dirX = mouse.distX === 0 ? 0 : mouse.distX > 0 ? 1 : -1;
            mouse.dirY = mouse.distY === 0 ? 0 : mouse.distY > 0 ? 1 : -1;
            // axis mouse is now moving on
            var newAx   = Math.abs(mouse.distX) > Math.abs(mouse.distY) ? 1 : 0;

            // do nothing on first move
            if (!mouse.moving) {
                mouse.dirAx  = newAx;
                mouse.moving = true;
                return;
            }

            // calc distance moved on this axis (and direction)
            if (mouse.dirAx !== newAx) {
                mouse.distAxX = 0;
                mouse.distAxY = 0;
            } else {
                mouse.distAxX += Math.abs(mouse.distX);
                if (mouse.dirX !== 0 && mouse.dirX !== mouse.lastDirX) {
                    mouse.distAxX = 0;
                }
                mouse.distAxY += Math.abs(mouse.distY);
                if (mouse.dirY !== 0 && mouse.dirY !== mouse.lastDirY) {
                    mouse.distAxY = 0;
                }
            }
            mouse.dirAx = newAx;

            /**
             * move horizontal
             */
            if (mouse.dirAx && mouse.distAxX >= opt.threshold) {
                // reset move distance on x-axis for new phase
                mouse.distAxX = 0;
                prev = this.placeEl.prev(opt.itemNodeName);
                // increase horizontal level if previous sibling exists and is not collapsed
                if (mouse.distX > 0 && prev.length && !prev.hasClass(opt.collapsedClass)) {
                    // cannot increase level when item above is collapsed
                    list = prev.find(opt.listNodeName).last();
                    // check if depth limit has reached
                    depth = this.placeEl.parents(opt.listNodeName).length;
                    if (depth + this.dragDepth <= opt.maxDepth) {
                        // create new sub-level if one doesn't exist
                        if (!list.length) {
                            list = $('<' + opt.listNodeName + '/>').addClass(opt.listClass);
                            list.append(this.placeEl);
                            prev.append(list);
                            this.setParent(prev);
                        } else {
                            // else append to next level up
                            list = prev.children(opt.listNodeName).last();
                            list.append(this.placeEl);
                        }
                    }
                }
                // decrease horizontal level
                if (mouse.distX < 0) {
                    // we can't decrease a level if an item preceeds the current one
                    next = this.placeEl.next(opt.itemNodeName);
                    if (!next.length) {
                        parent = this.placeEl.parent();
                        this.placeEl.closest(opt.itemNodeName).after(this.placeEl);
                        if (!parent.children().length) {
                            this.unsetParent(parent.parent());
                        }
                    }
                }
            }

            var isEmpty = false;

            // find list item under cursor
            if (!hasPointerEvents) {
                this.dragEl[0].style.visibility = 'hidden';
            }
            this.pointEl = $(document.elementFromPoint(e.pageX - document.body.scrollLeft, e.pageY - (window.pageYOffset || document.documentElement.scrollTop)));
            if (!hasPointerEvents) {
                this.dragEl[0].style.visibility = 'visible';
            }
            if (this.pointEl.hasClass(opt.handleClass)) {
                this.pointEl = this.pointEl.parent(opt.itemNodeName);
            }
            if (this.pointEl.hasClass(opt.emptyClass)) {
                isEmpty = true;
            }
            else if (!this.pointEl.length || !this.pointEl.hasClass(opt.itemClass)) {
                return;
            }

            // find parent list of item under cursor
            var pointElRoot = this.pointEl.closest('.' + opt.rootClass),
                isNewRoot   = this.dragRootEl.data('nestable-id') !== pointElRoot.data('nestable-id');

            /**
             * move vertical
             */
            if (!mouse.dirAx || isNewRoot || isEmpty) {
                // check if groups match if dragging over new root
                if (isNewRoot && opt.group !== pointElRoot.data('nestable-group')) {
                    return;
                }
                // check depth limit
                depth = this.dragDepth - 1 + this.pointEl.parents(opt.listNodeName).length;
                if (depth > opt.maxDepth) {
                    return;
                }
                var before = e.pageY < (this.pointEl.offset().top + this.pointEl.height() / 2);
                    parent = this.placeEl.parent();
                // if empty create new list to replace empty placeholder
                if (isEmpty) {
                    list = $(document.createElement(opt.listNodeName)).addClass(opt.listClass);
                    list.append(this.placeEl);
                    this.pointEl.replaceWith(list);
                }
                else if (before) {
                    this.pointEl.before(this.placeEl);
                }
                else {
                    this.pointEl.after(this.placeEl);
                }
                if (!parent.children().length) {
                    this.unsetParent(parent.parent());
                }
                if (!this.dragRootEl.find(opt.itemNodeName).length) {
                    this.dragRootEl.append('
');
                }
                // parent root list has changed
                if (isNewRoot) {
                    this.dragRootEl = pointElRoot;
                    this.hasNewRoot = this.el[0] !== this.dragRootEl[0];
                }
            }
        }

    };

    $.fn.nestable = function(params)
    {
        var lists  = this,
            retval = this;

        lists.each(function()
        {
            var plugin = $(this).data("nestable");

            if (!plugin) {
                $(this).data("nestable", new Plugin(this, params));
                $(this).data("nestable-id", new Date().getTime());
            } else {
                if (typeof params === 'string' && typeof plugin[params] === 'function') {
                    retval = plugin[params]();
                }
            }
        });

        return retval || lists;
    };

})(window.jQuery || window.Zepto, window, document);
<|endoftext|>


<commit_before>    Ext.application({

      launch: function () {

        Ext.Viewport.add({

          xtype: 'grid',

          title: 'Tutorial List',

          columns: [

            {text: 'S.No', width: 50, dataIndex: 'sno'},

            {text: 'Name', width: '100%', dataIndex: 'name'}

          ],

          data: data,

          listeners: {

            click: onClick

         }

        });

      }

    });

    function onClick() {

      alert("Something");

    };

    var data = [

      { sno:'1', name: 'What is Ext.js?', link:'./what-is-extjs' }

    ]
<commit_msg>Update app.js<commit_after>    Ext.application({

      launch: function () {

        Ext.Viewport.add({

          xtype: 'grid',

          title: 'Tutorials List',

          columns: [

            {text: 'S.No', width: 50, dataIndex: 'sno'},

            {text: 'Name', width: '100%', dataIndex: 'name'}

          ],

          data: data,

          listeners: {

            click: onClick

         }

        });

      }

    });

    function onClick() {

      alert("Something");

    };

    var data = [

      { sno:'1', name: 'What is Ext.js?', link:'./what-is-extjs' }

    ]
<|endoftext|>


<commit_before>/**
 * @module
 * @public
 * @description
 * This module provides advanced support for extending change detection.
 */
<commit_msg>feat(pipe): reexported pipes to genereate docs<commit_after>/**
 * @module
 * @public
 * @description
 * This module provides advanced support for extending change detection.
 */

export {PromisePipe} from './src/change_detection/pipes/promise_pipe';
export {UpperCasePipe} from './src/change_detection/pipes/uppercase_pipe';
export {LowerCasePipe} from './src/change_detection/pipes/lowercase_pipe';
export {ObservablePipe} from './src/change_detection/pipes/observable_pipe';
export {JsonPipe} from './src/change_detection/pipes/json_pipe';
export {IterableChanges} from './src/change_detection/pipes/iterable_changes';
export {KeyValueChanges} from './src/change_detection/pipes/keyvalue_changes';
<|endoftext|>


<commit_before>import Vue from 'vue'
import Router from 'vue-router'

const About = () => import('~/pages/about.vue').then(m => m.default || m)
const CollectionsSlug = () => import('~/pages/collections/_slug.vue').then(m => m.default || m)
const Dapps = () => import('~/pages/dapps/index.vue').then(m => m.default || m)
const DappsNew = () => import('~/pages/dapps/new.vue').then(m => m.default || m)
const DappsNewConfirmation = () => import('~/pages/dapps/new/confirmation.vue').then(m => m.default || m)
const DappsSlug = () => import('~/pages/dapps/_slug.vue').then(m => m.default || m)
const DappsSlugDirect = () => import('~/pages/dapps/_slug_direct.vue').then(m => m.default || m)
const Events = () => import('~/pages/events/index.vue').then(m => m.default || m)
const EventsNew = () => import('~/pages/events/new.vue').then(m => m.default || m)
const EventsNewConfirmation = () => import('~/pages/events/new/confirmation.vue').then(m => m.default || m)
const EventsSlug = () => import('~/pages/events/_slug.vue').then(m => m.default || m)
const EventsSlugPopup = () => import('~/pages/events/_slug/popup.vue').then(m => m.default || m)
const Home = () => import('~/pages/home.vue').then(m => m.default || m)
const Placeholder = () => import('~/components/shared/Placeholder.vue').then(m => m.default || m)
const Terms = () => import('~/pages/terms.vue').then(m => m.default || m)
const What = () => import('~/pages/what.vue').then(m => m.default || m)

Vue.use(Router)

if (process.client) {
  window.history.scrollRestoration = 'manual'
}
const scrollBehavior = function (to, from, savedPosition) {
  if (savedPosition) {
    return savedPosition
  } else {
    let position = {}
    if (to.matched.length < 2) {
      position = { x: 0, y: 0 }
    } else if (to.matched.some(r => r.components.default.options.scrollToTop)) {
      position = { x: 0, y: 0 }
    }
    if (to.hash) {
      position = { selector: to.hash }
    }
    return position
  }
}

export function createRouter () {
  return new Router({
    mode: 'history',
    base: '/',
    linkActiveClass: 'nuxt-link-active',
    linkExactActiveClass: 'nuxt-link-exact-active',
    scrollBehavior,
    routes: [
      {
        path: '/',
        component: Home,
        name: 'home'
      },
      {
        path: '/about',
        component: About,
        name: 'about'
      },
      {
        path: '/collections/:slug',
        component: CollectionsSlug,
        name: 'collections-slug'
      },
      {
        path: '/events/submit/new',
        component: EventsNew,
        name: 'events-new'
      },
      {
        path: '/events/submit/new/confirmation',
        component: EventsNewConfirmation,
        name: 'events-new-confirmation'
      },
      {
        path: '/events/:slug',
        component: EventsSlug,
        name: 'events-slug'
      },
      // the root /events route goes after other /events/{params} routes, so that a direct GET to any other /events/{params} will render before /events child routes
      {
        path: '/events',
        component: Events,
        children: [
          {
            path: '',
            component: Placeholder,
            name: 'events'
          },
          {
            path: 'tagged/:tags',
            component: Placeholder,
            name: 'events-tagged-tags',
            children: [
              {
                path: 'category/:category',
                component: Placeholder,
                name: 'events-tagged-tags-category-category'
              }
            ]
          },
          {
            path: 'category/:category',
            component: Placeholder,
            name: 'events-category-category'
          },
          {
            path: ':slug',
            component: EventsSlugPopup,
            name: 'events-slug-popup'
          }
        ]
      },
      {
        path: '/dapps/submit/new',
        component: DappsNew,
        name: 'dapps-new'
      },
      {
        path: '/dapps/new/form',
        redirect: { name: 'dapps-new' }
      },
      {
        path: '/dapps/submit/new/confirmation',
        component: DappsNewConfirmation,
        name: 'dapps-new-confirmation'
      },
      {
        path: '/dapps/:slug',
        component: DappsSlugDirect,
        name: 'dapps-slug-direct'
      },
      {
        path: '/dapps/:slug',
        component: DappsSlug,
        name: 'dapps-slug'
      },
      {
        path: '/tab/:tab',
        redirect: {
          name: 'dapps-tab'
        }
      },
      {
        path: '/tagged/:tags',
        redirect: {
          name: 'dapps-tags'
        }
      },
      {
        path: '/tagged/:tags/tab/:tab',
        redirect: {
          name: 'dapps-tab-tags'
        }
      },
      // the root /dapps route goes after other /dapps/{params} routes, so that a direct GET to any other /dapps/{params} will render before /dapps child routes
      {
        path: '/dapps',
        component: Dapps,
        name: 'dapps',
        children: [
          {
            path: 'tab/:tab',
            component: Placeholder,
            name: 'dapps-tab'
          },
          {
            path: 'tagged/:tags',
            component: Placeholder,
            name: 'dapps-tags'
          },
          {
            path: 'tagged/:tags/tab/:tab',
            component: Placeholder,
            name: 'dapps-tab-tags'
          }
        ]
      },
      {
        path: '/terms',
        component: Terms,
        name: 'terms'
      },
      {
        path: '/whats-a-dapp',
        component: What,
        name: 'what'
      }
    ],
    fallback: false
  })
}
<commit_msg>Remove events scroll false (#216)<commit_after>import Vue from 'vue'
import Router from 'vue-router'

const About = () => import('~/pages/about.vue').then(m => m.default || m)
const CollectionsSlug = () => import('~/pages/collections/_slug.vue').then(m => m.default || m)
const Dapps = () => import('~/pages/dapps/index.vue').then(m => m.default || m)
const DappsNew = () => import('~/pages/dapps/new.vue').then(m => m.default || m)
const DappsNewConfirmation = () => import('~/pages/dapps/new/confirmation.vue').then(m => m.default || m)
const DappsSlug = () => import('~/pages/dapps/_slug.vue').then(m => m.default || m)
const DappsSlugDirect = () => import('~/pages/dapps/_slug_direct.vue').then(m => m.default || m)
const Events = () => import('~/pages/events/index.vue').then(m => m.default || m)
const EventsNew = () => import('~/pages/events/new.vue').then(m => m.default || m)
const EventsNewConfirmation = () => import('~/pages/events/new/confirmation.vue').then(m => m.default || m)
const EventsSlug = () => import('~/pages/events/_slug.vue').then(m => m.default || m)
const EventsSlugPopup = () => import('~/pages/events/_slug/popup.vue').then(m => m.default || m)
const Home = () => import('~/pages/home.vue').then(m => m.default || m)
const Placeholder = () => import('~/components/shared/Placeholder.vue').then(m => m.default || m)
const Terms = () => import('~/pages/terms.vue').then(m => m.default || m)
const What = () => import('~/pages/what.vue').then(m => m.default || m)

Vue.use(Router)

if (process.client) {
  window.history.scrollRestoration = 'manual'
}
const scrollBehavior = function (to, from, savedPosition) {
  if (savedPosition) {
    return savedPosition
  } else {
    let position = {}
    if (to.matched.length < 2) {
      position = { x: 0, y: 0 }
    } else if (to.matched.some(r => r.components.default.options.scrollToTop)) {
      position = { x: 0, y: 0 }
    }
    if (to.hash) {
      position = { selector: to.hash }
    }
    return position
  }
}

export function createRouter () {
  return new Router({
    mode: 'history',
    base: '/',
    linkActiveClass: 'nuxt-link-active',
    linkExactActiveClass: 'nuxt-link-exact-active',
    scrollBehavior,
    routes: [
      {
        path: '/',
        component: Home,
        name: 'home'
      },
      {
        path: '/about',
        component: About,
        name: 'about'
      },
      {
        path: '/collections/:slug',
        component: CollectionsSlug,
        name: 'collections-slug'
      },
      {
        path: '/events/submit/new',
        component: EventsNew,
        name: 'events-new'
      },
      {
        path: '/events/submit/new/confirmation',
        component: EventsNewConfirmation,
        name: 'events-new-confirmation'
      },
      {
        path: '/events/:slug',
        component: EventsSlug,
        name: 'events-slug'
      },
      // the root /events route goes after other /events/{params} routes, so that a direct GET to any other /events/{params} will render before /events child routes
      {
        path: '/events',
        component: Events,
        name: 'events',
        children: [
          {
            path: 'tagged/:tags',
            component: Placeholder,
            name: 'events-tagged-tags',
            children: [
              {
                path: 'category/:category',
                component: Placeholder,
                name: 'events-tagged-tags-category-category'
              }
            ]
          },
          {
            path: 'category/:category',
            component: Placeholder,
            name: 'events-category-category'
          },
          {
            path: ':slug',
            component: EventsSlugPopup,
            name: 'events-slug-popup'
          }
        ]
      },
      {
        path: '/dapps/submit/new',
        component: DappsNew,
        name: 'dapps-new'
      },
      {
        path: '/dapps/new/form',
        redirect: { name: 'dapps-new' }
      },
      {
        path: '/dapps/submit/new/confirmation',
        component: DappsNewConfirmation,
        name: 'dapps-new-confirmation'
      },
      {
        path: '/dapps/:slug',
        component: DappsSlugDirect,
        name: 'dapps-slug-direct'
      },
      {
        path: '/dapps/:slug',
        component: DappsSlug,
        name: 'dapps-slug'
      },
      {
        path: '/tab/:tab',
        redirect: {
          name: 'dapps-tab'
        }
      },
      {
        path: '/tagged/:tags',
        redirect: {
          name: 'dapps-tags'
        }
      },
      {
        path: '/tagged/:tags/tab/:tab',
        redirect: {
          name: 'dapps-tab-tags'
        }
      },
      // the root /dapps route goes after other /dapps/{params} routes, so that a direct GET to any other /dapps/{params} will render before /dapps child routes
      {
        path: '/dapps',
        component: Dapps,
        name: 'dapps',
        children: [
          {
            path: 'tab/:tab',
            component: Placeholder,
            name: 'dapps-tab'
          },
          {
            path: 'tagged/:tags',
            component: Placeholder,
            name: 'dapps-tags'
          },
          {
            path: 'tagged/:tags/tab/:tab',
            component: Placeholder,
            name: 'dapps-tab-tags'
          }
        ]
      },
      {
        path: '/terms',
        component: Terms,
        name: 'terms'
      },
      {
        path: '/whats-a-dapp',
        component: What,
        name: 'what'
      }
    ],
    fallback: false
  })
}
<|endoftext|>


<commit_before>/* Simple 2D point class. */
var Point = function(x, y) {
  this.x = x;
  this.y = y;
}

/* Creates a new point between two existing points in the given direction. */
function bend (p1, p2, direction) {
  var xLength = p2.x - p1.x;
  var yLength = p2.y - p1.y;

  var angle = direction * Math.PI / 4;

  var newX = (xLength * Math.cos(angle) - yLength * Math.sin(angle))
             * 0.707106781 + p1.x;
  var newY = (xLength * Math.sin(angle) + yLength * Math.cos(angle))
             * 0.707106781 + p1.y;

  return new Point(newX, newY);
}

/* Progresses the fractal, increasing the detail. */
function step (points) {
  for (var i = 1; i < points.length; i+=2) {
    var newPoint = bend(points[i - 1], points[i],
                   parseInt(i / 2) % 2 === 0 ? 1 : -1);
    points.splice(i, 0, newPoint);
  }
}

/* Regresses the fractal, decreasing the detail. */
function stepBack (points) {
  if (points.length <= 2)
    return;
  // Remove every second point from the list.
  for (var i = 1; i < points.length; i++) {
    points.splice(i, 1);
  }
}

/* Draws a segment of the fractal in the given color. */
function drawSegment (p1, p2, context, color) {
  context.strokeStyle = color || 'rgb(255, 0, 0)';
  context.beginPath();
  context.moveTo(p1.x, p1.y);
  context.lineTo(p2.x, p2.y);
  context.stroke();
}

/* Draws the fractal curve. */
function drawCurve(points, context, canvas) {
  context.clearRect(0, 0, canvas.width, canvas.height);
  for (var i = 1; i < points.length; i++) {
    drawSegment(points[i - 1], points[i], context);
  }
}

/* Draws the fractal curve with fancier coloring. */
function drawCurveWithColor(points, context, canvas) {
  var colorStep = 255 / points.length;

  context.clearRect(0, 0, canvas.width, canvas.height);
  for (var i = 1; i < points.length; i++) {
    drawSegment(points[i - 1], points[i], context, '#'
        + Math.min(Math.floor((i - 1) * colorStep + 50), 255).toString(16)
        + '0000');
  }
}

// Canvas.
var c = document.getElementById('dragon');
var ctx = c.getContext('2d');

c.width = c.offsetWidth;
c.height = c.offsetHeight;

// Initial set up.
var points = [new Point(c.width * 2 / 7, c.height * 2 / 5),
              new Point(c.width * 6 / 7, c.height * 2 / 5)];
drawCurveWithColor(points, ctx, c);

// Key listener.
document.addEventListener('keydown', function(event) {
  if (event.keyCode === 39) {
    step(points);
    drawCurveWithColor(points, ctx, c);
  } else if (event.keyCode === 37) {
    stepBack(points);
    drawCurveWithColor(points, ctx, c);
  }
});

// Mouse listener.
c.addEventListener('click', function() {
  step(points);
  drawCurveWithColor(points, ctx, c);
});
<commit_msg>Dragon fractal now has max iteration.<commit_after>var MAX_ITER = 16;

/* Simple 2D point class. */
var Point = function(x, y) {
  this.x = x;
  this.y = y;
}

/* Creates a new point between two existing points in the given direction. */
function bend (p1, p2, direction) {
  var xLength = p2.x - p1.x;
  var yLength = p2.y - p1.y;

  var angle = direction * Math.PI / 4;

  var newX = (xLength * Math.cos(angle) - yLength * Math.sin(angle))
             * 0.707106781 + p1.x;
  var newY = (xLength * Math.sin(angle) + yLength * Math.cos(angle))
             * 0.707106781 + p1.y;

  return new Point(newX, newY);
}

/* Progresses the fractal, increasing the detail. */
function step (points) {
  for (var i = 1; i < points.length; i+=2) {
    var newPoint = bend(points[i - 1], points[i],
                   parseInt(i / 2) % 2 === 0 ? 1 : -1);
    points.splice(i, 0, newPoint);
  }
  ++iter;
}

/* Regresses the fractal, decreasing the detail. */
function stepBack (points) {
  if (points.length <= 2)
    return;
  // Remove every second point from the list.
  for (var i = 1; i < points.length; i++) {
    points.splice(i, 1);
  }
  --iter;
}

/* Draws a segment of the fractal in the given color. */
function drawSegment (p1, p2, context, color) {
  context.strokeStyle = color || 'rgb(255, 0, 0)';
  context.beginPath();
  context.moveTo(p1.x, p1.y);
  context.lineTo(p2.x, p2.y);
  context.stroke();
}

/* Draws the fractal curve. */
function drawCurve(points, context, canvas) {
  context.clearRect(0, 0, canvas.width, canvas.height);
  for (var i = 1; i < points.length; i++) {
    drawSegment(points[i - 1], points[i], context);
  }
}

/* Draws the fractal curve with fancier coloring. */
function drawCurveWithColor(points, context, canvas) {
  var colorStep = 255 / points.length;

  context.clearRect(0, 0, canvas.width, canvas.height);
  for (var i = 1; i < points.length; i++) {
    drawSegment(points[i - 1], points[i], context, '#'
        + Math.min(Math.floor((i - 1) * colorStep + 50), 255).toString(16)
        + '0000');
  }
}

// Canvas.
var c = document.getElementById('dragon');
var ctx = c.getContext('2d');

c.width = c.offsetWidth;
c.height = c.offsetHeight;

// Initial set up.
var points = [new Point(c.width * 2 / 7, c.height * 2 / 5),
              new Point(c.width * 6 / 7, c.height * 2 / 5)];
drawCurveWithColor(points, ctx, c);

var iter = 0;

// Key listener.
document.addEventListener('keydown', function(event) {
  if (event.keyCode === 39 && iter < MAX_ITER) {
    step(points);
    drawCurveWithColor(points, ctx, c);
  } else if (event.keyCode === 37 && iter > 0) {
    stepBack(points);
    drawCurveWithColor(points, ctx, c);
  }
});

// Mouse listener.
c.addEventListener('click', function() {
  if (iter < MAX_ITER) {
    step(points);
    drawCurveWithColor(points, ctx, c);
  }
});
<|endoftext|>


<commit_before>'use strict';

angular.module('squareteam.app')
  .directive('stOrganizationCreate', function () {
    return {
      scope: {
        forUser : '@',
        membersChooser : '@',
        redirectPath : '@'
      },
      templateUrl: 'scripts/directives/templates/storganizationcreate.html',
      restrict: 'E',
      replace: true,
      controller: function($scope, $element, $attrs, $location, $http, OrganizationRessource, ApiErrors) {

        function onError (response) {
          if (response.error instanceof ApiErrors.Api) {
            angular.forEach(response.error.getErrors(), function(errorText) {
              if (errorText === 'Name has already been taken') {
                $scope.createOrganizationForm.name.$setValidity('unique', false);
              }
            });
          } else {
            $scope.serverBusy = true;
          }
        }

        $scope.create = function() {
          $scope.serverBusy = false;
          $scope.createOrganizationForm.name.$setValidity('unique', true);

          var organization = OrganizationRessource.save({}, $scope.organization, function() {
            function redirectOnFinish () {
              $location.path($scope.redirectPath || '/home');
            }

            if ($scope.forUser) {
              $http.post('apis://members', {
                'organization_id' : organization.id,
                'user_id' : $scope.forUser,
                'admin'   : 1
              }).then(function() {
                redirectOnFinish();
              }, onError);
            } else {
              redirectOnFinish();
            }
          },onError);
        };
      }
    };
  });<commit_msg>feat(st-organization-create): add support for user-ids array<commit_after>'use strict';

angular.module('squareteam.app')
  .directive('stOrganizationCreate', function () {
    return {
      scope: {
        // list of user ids
        //  TODO : $scope.forUsers should be a array of object like : [{ id : 1 , admin : true }, ...]
        forUsers : '=',
        redirectPath : '@'
      },
      templateUrl: 'scripts/directives/templates/storganizationcreate.html',
      restrict: 'E',
      replace: true,
      controller: function($scope, $element, $attrs, $location, $http, OrganizationRessource, ApiErrors) {

        function onError (response) {
          if (response.error instanceof ApiErrors.Api) {
            angular.forEach(response.error.getErrors(), function(errorText) {
              if (errorText === 'Name has already been taken') {
                $scope.createOrganizationForm.name.$setValidity('unique', false);
              }
            });
          } else {
            $scope.serverBusy = true;
          }
        }

        $scope.create = function() {
          $scope.serverBusy = false;
          $scope.createOrganizationForm.name.$setValidity('unique', true);

          var organization = OrganizationRessource.save({}, $scope.organization, function() {
            function redirectOnFinish () {
              $location.path($scope.redirectPath || '/home');
            }

            if ($scope.forUsers && $scope.forUsers.length) {
              // API DO NOT SUPPORT BATCH FOR NOW..
              //
              // $.map($scope.forUsers, function(userId) {
              //   return {
              //     'organization_id' : organization.id,
              //     'user_id' : userId,
              //     'admin'   : 1
              //   };
              // }.bind(this))
              var data = {
                'organization_id' : organization.id,
                'user_id' : $scope.forUsers[0],
                'admin'   : 1
              };
              $http.post('apis://members', data).then(function() {
                redirectOnFinish();
              }, onError);
            } else {
              redirectOnFinish();
            }
          },onError);
        };
      }
    };
  });<|endoftext|>


<commit_before>import React from 'react';
import BaseLayout from '../containers/BaseLayout';
import Info from '../components/SchoolInfo';
import AlumnusCard from '../components/AlumnusCard';

export default () => (
  <BaseLayout>
    <Info/>

2017

          <AlumnusCard />

          <AlumnusCard />

          <AlumnusCard />

          <AlumnusCard />

  </BaseLayout>
);
<commit_msg>Refractor alumni to use only tachyons classes<commit_after>import React from 'react';
import BaseLayout from '../containers/BaseLayout';
import Info from '../components/SchoolInfo';
import AlumnusCard from '../components/AlumnusCard';

function Alumni() {
  return (
    <BaseLayout>
      <Info />

2017

            <AlumnusCard />

            <AlumnusCard />

            <AlumnusCard />

            <AlumnusCard />

    </BaseLayout>
  )
}

export default Alumni
<|endoftext|>


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

import Concept from '../Concept';
import Pit from '../Pit';

import { initFlag } from '../../actions/flag';

import './index.css';

const Detail = React.createClass({
  propTypes: {
    concept: PropTypes.object.isRequired,
    conceptRelations: PropTypes.array.isRequired,
  },

  getInitialState() {
    return {
      showPits: false,
    };
  },

  render() {
    const { concept, conceptRelations } = this.props;
    const { showPits } = this.state;

    return (

{concept.name}

{concept.type}

        <button onClick={this.handleFlag}>Flag</button>

        <button onClick={this.handlePitsToggle}>{showPits ? 'Hide' : 'Show'} pit details</button>

        {showPits ?

            {concept.pits.map((pit) =>

                <Pit pit={pit}/>

            )}

 : null
        }

Relations

        {conceptRelations.length ?

                Name
                Relation Type

              {conceptRelations.map((relation) =>

                  <Concept concept={relation.concept}/>
                  {relation.type}

              )}

 : null}

    );
  },
  handlePitsToggle() {
    this.setState({
      showPits: !this.state.showPits,
    });
  },
  handleFlag() {
    this.props.dispatch(initFlag(this.props.concept));
  },
});

export default connect(
  (state) => (state)
)(Detail);
<commit_msg>Remove tnl: on detail view type<commit_after>import React, { PropTypes } from 'react';
import { connect } from 'react-redux';

import Concept from '../Concept';
import Pit from '../Pit';

import { initFlag } from '../../actions/flag';

import './index.css';

const Detail = React.createClass({
  propTypes: {
    concept: PropTypes.object.isRequired,
    conceptRelations: PropTypes.array.isRequired,
  },

  getInitialState() {
    return {
      showPits: false,
    };
  },

  render() {
    const { concept, conceptRelations } = this.props;
    const { showPits } = this.state;

    return (

{concept.name}

{concept.type.replace('tnl:', '')}

        <button onClick={this.handleFlag}>Flag</button>

        <button onClick={this.handlePitsToggle}>{showPits ? 'Hide' : 'Show'} pit details</button>

        {showPits ?

            {concept.pits.map((pit) =>

                <Pit pit={pit}/>

            )}

 : null
        }

Relations

        {conceptRelations.length ?

                Name
                Relation Type

              {conceptRelations.map((relation) =>

                  <Concept concept={relation.concept}/>
                  {relation.type}

              )}

 : null}

    );
  },
  handlePitsToggle() {
    this.setState({
      showPits: !this.state.showPits,
    });
  },
  handleFlag() {
    this.props.dispatch(initFlag(this.props.concept));
  },
});

export default connect(
  (state) => (state)
)(Detail);
<|endoftext|>


<commit_before>// test the models

'use strict';

var assert = require('assert');
var Tag = require('../app/models/tag.js');
var Sender = require('../app/models/sender.js');
var Document = require('../app/models/document.js');
var User = require('../app/models/user.js');
var database = require('../app/config/database');
var mongoose = require('mongoose');
var logger = require('../app/util/logger');
var MasterDataService = require('../app/services/masterDataService');
var DocumentService = require('../app/services/documentService');
var UserService = require('../app/services/userService');

var uristring = database.uri + '_integration';
console.log(uristring);
if(mongoose.connection.readyState !== 1) {
  mongoose.connect(uristring, function (err) {
    if (err) {
      console.log('ERROR connecting to: ' + uristring + '. ' + err);
      return;
    }
  });
}

// use JSON testdata
/*jshint multistr: true */
var testData = '{\
  "_id": -1,\
  "title": "TEST",\
  "fileName": "20050714Bewerbung.pdf",\
  "amount": "1",\
  "senders": [\
      {\
          "name": "Sender1",\
          "_id": -1\
      }\
  ],\
  "tags": [\
      {\
          "name": "Tag1",\
          "_id": -1\
      }\
  ],\
  "originalFilename": "20050714Bewerbung.pdf",\
  "tempFilename": "dEOqGvoe.pdf",\
  "size": 37415\
}';
var testDocument = JSON.parse(testData);

describe('MongoDB', function() {
  describe('module', function() {
    it('should be imported', function(done) {
      var mongoose = require('mongoose');
      assert(mongoose, 'Could not import!');
      done();
    });
  });
});

describe('Backend', function() {

  before(function(done) {
    // clean house before starting tests
    User.remove({}, function(err) {
      if(err) {
        console.log(err);
      }

      Tag.remove({}, function(err) {
        if(err) {
          console.log(err);
        }

        Sender.remove({}, function(err) {
          if(err) {
            console.log(err);
          }

          Document.remove({}, function(err) {
            if(err) {
              console.log(err);
            }

            var sender = new Sender({name: 'testsender'});
            sender.save(function (err) {
              assert(!err, err);

              var tag = new Tag({name: 'testtag'});
              tag.save(function (err) {
                assert(!err, err);

                done();
              });
            });
          });
        });
      });
    });
  });

  // close the mongo connection - not strictly necessary but
  // keep your  house clean
  after(function(done) {
    // clean house before starting tests
    User.remove({}, function(err) {
      if(err) {
        console.log(err);
      }

      Tag.remove({}, function(err) {
        if(err) {
          console.log(err);
        }

        Sender.remove({}, function(err) {
          if(err) {
            console.log(err);
          }

          Document.remove({}, function(err) {
            if(err) {
              console.log(err);
            }
            mongoose.connection.close();
            done();
          });
        });
      });
    });
  });

  describe('Users', function() {
    it('should save a new user', function(done) {
      var user = new User({displayName: 'Test User', email: 'test@example.com'});

      user.save(function(err) {
        assert(!err, err);
        User.findOne({}).exec(function(err, foundUser) {
          assert(!err, err);
          foundUser.token = { a: 'b', c: { aa: 'bb', c: 'cc', d: 'dd'}};

          foundUser.save(function(err) {

            User.findOne({}).exec(function(err, foundUser) {
              assert(!err, err);
              console.log(foundUser);

              assert.equal(foundUser.token.a, 'b', 'User object path does not match b!');
              assert.equal(foundUser.token.c.c, 'cc', 'User object path does not match cc!');

              done();
            });
          });
        });

      });

    });

    it('find a user by email', function(done) {
      var user = new User({displayName: 'Test User', email: 'test@example.com'});

      user.save(function(err) {
        assert(!err, err);

        var userService = new UserService();

        userService.findUserByEmail('test@example.com').then(function(user) {
          assert(user, 'No user!');
          assert.equal(user.email, 'test@example.com', 'Wrong email!');
          done();
        })
        .catch(function(error) {
          console.log(error.stack);
          // Handle any error from all above steps
          assert(!error, 'Error thrown!');
        })
        .done();

      });
    });

    it('update the user token', function(done) {
      var user = new User({displayName: 'Test User', email: 'test@example.com'});

      user.save(function(err, u) {
        assert(!err, err);

        var userService = new UserService()
          , token = {}
          , profile = {};

        profile.a = 1;

        token.val = 1;
        token.a = 'b';

        userService.setTokenAndProfile(u._id, token, profile).then(function() {
          return userService.findUserById(u._id);
        }).then(function(user) {
          assert(user, 'No user!');
          logger.logDump('## TOKEN ##', user.token);

        }).catch(function(error) {
          console.log(error.stack);
          // Handle any error from all above steps
          assert(!error, 'Error thrown!');
        }).done();

        userService.findUserByEmail('test@example.com').then(function(user) {
          assert(user, 'No user!');
          assert.equal(user.email, 'test@example.com', 'Wrong email!');
          done();
        })
          .catch(function(error) {
            console.log(error.stack);
            // Handle any error from all above steps
            assert(!error, 'Error thrown!');
          })
          .done();

      });
    });

  });

  describe('Senders', function() {

    it('instantiate a new sender', function() {
      var sender = new Sender({name: 'testsender'});
      assert(sender, 'No sender!');
      assert.equal(sender.name, 'testsender', 'Sender has no name!');
    });

    it('should support basic crud operations', function(done) {
      var sender = new Sender({name: 'testsender'});
      assert(sender, 'No sender!');
      assert.equal(sender.name, 'testsender', 'Sender has no name!');

      sender.save(function (err) {
        assert(!err, err);

        // find the entry again
        Sender.findOne({}).exec(function (err, foundSender) {

          console.log(foundSender);

          assert(!err, err);
          assert.equal(foundSender.name, 'testsender', 'Sender has no name!');
          console.info('Found sender ' + foundSender.toString());
          done();
        });

      });

    });

  });

  describe('Tags', function() {

    it('instantiate a new tag', function() {
      var tag = new Tag({name: 'testtag'});
      assert(tag, 'No tag!');
      assert.equal(tag.name, 'testtag', 'Tag has no name!');
    });

    it('should support basic crud operations', function(done) {
      var tag = new Tag({name: 'testtag'});
      assert(tag, 'No tag!');
      assert.equal(tag.name, 'testtag', 'Tag has no name!');

      tag.save(function (err) {
        assert(!err, err);

        // find the entry again
        Tag.findOne({}).exec(function (err, foundTag) {
          assert(!err, err);
          assert.equal(foundTag.name, 'testtag', 'Tag has no name!');
          console.info('Found tag ' + foundTag.toString());
          done();
        });

      });
    });
  });

  describe('Documents', function() {
    it('instantiate a new document', function() {
      var doc = new Document({title: 'testdocument'});

      assert(doc, 'No doc!');
      assert.equal(doc.title, 'testdocument', 'Doc has no title!');
    });

    it('should support basic crud operations', function(done) {
      var doc = new Document({title: 'testdocument'});

      assert(doc, 'No doc!');
      assert.equal(doc.title, 'testdocument', 'Doc has no title!');

      doc.fileName = 'test.pdf';

      var tag = new Tag({ name: 'testtag1'});
      tag.save(function(err){
        assert(!err, err);
        console.log('use tagId: ' + tag._id);
        doc.tags.push(tag._id);

        doc.save(function(err) {
          assert(!err, err);

          assert.notEqual(doc.alternativeId, '', 'Pre save magic did not work!');

          Document.findOne({ title: 'testdocument'}).exec(function (err, foundDoc) {
            assert(!err, err);
            assert.equal(foundDoc.title, 'testdocument', 'Document has no name!');
            console.info('Found document ' + foundDoc.toString());

            // use the reference to find the selected tag
            var objectId = doc.tags[0];
            Tag.findOne( { _id: objectId }).exec(function(err, foundTag) {
              assert(!err, err);
              assert(foundTag, 'Tag not found');
              assert.equal(foundTag.name, 'testtag1', 'Tag name does not match!');

              console.info('Found tag ' + foundTag.toString());
            });

            done();
          });
        });

      });
    });
  });

  describe('Services', function() {
    it('should handle a list of senders', function(done) {
      var objectList = [],
          dataService = new MasterDataService();

      objectList.push({ _id: -1, name: 'Sender1' }); // new one
      // find the entry
      Sender.findOne({name: 'testsender'}).exec(function (err, foundSender) {
        assert(!err, err);
        objectList.push(foundSender);

        dataService.createAndGetSenders(objectList).then(function(senderList) {
          assert(senderList, 'No senders returned !' );
          console.log(senderList);
          assert.equal(senderList.length, 2, 'Number of senders');

          assert.notEqual(senderList[0]._id, -1, 'Wrong id');
          assert.equal(senderList[1].name, 'testsender', 'Wrong name');

          done();
        })
        .catch(function(error) {
          console.log(error.stack);
          // Handle any error from all above steps
          assert(!error, 'Error thrown!');
        })
        .done();

      });

    });

    it('should handle a list of tags', function(done) {
      var objectList = [],
          dataService = new MasterDataService();

      objectList.push({ _id: -1, name: 'Tag1' }); // new one
      // find the entry
      Tag.findOne({name: 'testtag'}).exec(function (err, foundTag) {
        assert(!err, err);
        objectList.push(foundTag);

        dataService.createAndGetTags(objectList).then(function(tagList) {
          assert(tagList, 'No tags returned !' );
          assert.equal(tagList.length, 2, 'Number of tags');

          assert.notEqual(tagList[0]._id, -1, 'Wrong id');
          assert.equal(tagList[1].name, 'testtag', 'Wrong name');

          done();
        })
        .catch(function(error) {
          console.log(error.stack);
          // Handle any error from all above steps
          assert(!error, 'Error thrown!');
        })
        .done();

      });
    });

    it('should save a NEW document object', function(done) {
        var documentService = new DocumentService(),
            dataService = new MasterDataService(),
            tagList,
            senderList;

        dataService.createAndGetTags(testDocument.tags).then(function(list) {
          tagList = list;

          assert(list, 'No tags supplied');

          return dataService.createAndGetSenders(testDocument.senders);
        })
        .then(function(list) {
          senderList = list;

          assert(list, 'No senders supplied');

          testDocument.tags = tagList;
          testDocument.senders = senderList;

          return documentService.save(testDocument);
        })
        .then(function(doc) {
          assert(doc, 'No document returned !' );
          assert.equal(doc.title, 'TEST', 'Wrong title');
          assert.equal(doc.senders.length, 1, 'Wrong number of senders');

          console.log('\n' + doc);
          logger.dump(doc);

          done();
        })
       .catch(function(error) {
          console.log(error.stack);
          // Handle any error from all above steps
          assert(!error, 'Error thrown!');
        })
        .done();

      });

      it('should update a document object', function(done) {
        var documentService = new DocumentService(),
            dataService = new MasterDataService(),
            tagList,
            senderList;

        Document.findOne({title: 'TEST'}).exec(function (err, foundDoc) {
          assert(!err, err);

          testDocument._id = foundDoc._id;
          testDocument.title = foundDoc.title;
          testDocument.amount = foundDoc.amount;

          dataService.createAndGetTags(testDocument.tags).then(function(list) {
            tagList = list;

            assert(list, 'No tags supplied');

            return dataService.createAndGetSenders(testDocument.senders);
          })
          .then(function(list) {
            senderList = list;

            assert(list, 'No senders supplied');

            testDocument.tags = tagList;
            testDocument.senders = senderList;

            return documentService.save(testDocument);
          })
          .then(function(doc) {
            assert(doc, 'No document returned !' );
            assert.equal(doc.title, 'TEST', 'Wrong title');
            assert.equal(doc.senders.length, 1, 'Wrong number of senders');

            console.log('\n' + doc);
            logger.dump(doc);

            done();
          })
         .catch(function(error) {
            console.log(error.stack);
            // Handle any error from all above steps
            assert(!error, 'Error thrown!');
          })
          .done();

        });

      });
  });

});
<commit_msg>Add auth for mongo<commit_after>// test the models

'use strict';

var assert = require('assert');
var Tag = require('../app/models/tag.js');
var Sender = require('../app/models/sender.js');
var Document = require('../app/models/document.js');
var User = require('../app/models/user.js');
var database = require('../app/config/database');
var mongoose = require('mongoose');
var logger = require('../app/util/logger');
var MasterDataService = require('../app/services/masterDataService');
var DocumentService = require('../app/services/documentService');
var UserService = require('../app/services/userService');

var uristring = database.uri + '_integration';
console.log(uristring);
if(mongoose.connection.readyState !== 1) {
  mongoose.connect(uristring, { user: 'mydms', pass: 'mydms'}, function (err) {
    if (err) {
      console.log('ERROR connecting to: ' + uristring + '. ' + err);
      return;
    }
  });
}

// use JSON testdata
/*jshint multistr: true */
var testData = '{\
  "_id": -1,\
  "title": "TEST",\
  "fileName": "20050714Bewerbung.pdf",\
  "amount": "1",\
  "senders": [\
      {\
          "name": "Sender1",\
          "_id": -1\
      }\
  ],\
  "tags": [\
      {\
          "name": "Tag1",\
          "_id": -1\
      }\
  ],\
  "originalFilename": "20050714Bewerbung.pdf",\
  "tempFilename": "dEOqGvoe.pdf",\
  "size": 37415\
}';
var testDocument = JSON.parse(testData);

describe('MongoDB', function() {
  describe('module', function() {
    it('should be imported', function(done) {
      var mongoose = require('mongoose');
      assert(mongoose, 'Could not import!');
      done();
    });
  });
});

describe('Backend', function() {

  before(function(done) {
    // clean house before starting tests
    User.remove({}, function(err) {
      if(err) {
        console.log(err);
      }

      Tag.remove({}, function(err) {
        if(err) {
          console.log(err);
        }

        Sender.remove({}, function(err) {
          if(err) {
            console.log(err);
          }

          Document.remove({}, function(err) {
            if(err) {
              console.log(err);
            }

            var sender = new Sender({name: 'testsender'});
            sender.save(function (err) {
              assert(!err, err);

              var tag = new Tag({name: 'testtag'});
              tag.save(function (err) {
                assert(!err, err);

                done();
              });
            });
          });
        });
      });
    });
  });

  // close the mongo connection - not strictly necessary but
  // keep your  house clean
  after(function(done) {
    // clean house before starting tests
    User.remove({}, function(err) {
      if(err) {
        console.log(err);
      }

      Tag.remove({}, function(err) {
        if(err) {
          console.log(err);
        }

        Sender.remove({}, function(err) {
          if(err) {
            console.log(err);
          }

          Document.remove({}, function(err) {
            if(err) {
              console.log(err);
            }
            mongoose.connection.close();
            done();
          });
        });
      });
    });
  });

  describe('Users', function() {
    it('should save a new user', function(done) {
      var user = new User({displayName: 'Test User', email: 'test@example.com'});

      user.save(function(err) {
        assert(!err, err);
        User.findOne({}).exec(function(err, foundUser) {
          assert(!err, err);
          foundUser.token = { a: 'b', c: { aa: 'bb', c: 'cc', d: 'dd'}};

          foundUser.save(function(err) {

            User.findOne({}).exec(function(err, foundUser) {
              assert(!err, err);
              console.log(foundUser);

              assert.equal(foundUser.token.a, 'b', 'User object path does not match b!');
              assert.equal(foundUser.token.c.c, 'cc', 'User object path does not match cc!');

              done();
            });
          });
        });

      });

    });

    it('find a user by email', function(done) {
      var user = new User({displayName: 'Test User', email: 'test@example.com'});

      user.save(function(err) {
        assert(!err, err);

        var userService = new UserService();

        userService.findUserByEmail('test@example.com').then(function(user) {
          assert(user, 'No user!');
          assert.equal(user.email, 'test@example.com', 'Wrong email!');
          done();
        })
        .catch(function(error) {
          console.log(error.stack);
          // Handle any error from all above steps
          assert(!error, 'Error thrown!');
        })
        .done();

      });
    });

    it('update the user token', function(done) {
      var user = new User({displayName: 'Test User', email: 'test@example.com'});

      user.save(function(err, u) {
        assert(!err, err);

        var userService = new UserService()
          , token = {}
          , profile = {};

        profile.a = 1;

        token.val = 1;
        token.a = 'b';

        userService.setProfile(u._id, profile).then(function() {
          return userService.findUserById(u._id);
        }).then(function(user) {
          assert(user, 'No user!');
          logger.logDump('## PROFILE ##', user.profile);

        }).catch(function(error) {
          console.log(error.stack);
          // Handle any error from all above steps
          assert(!error, 'Error thrown!');
        }).done();

        userService.findUserByEmail('test@example.com').then(function(user) {
          assert(user, 'No user!');
          assert.equal(user.email, 'test@example.com', 'Wrong email!');
          done();
        })
          .catch(function(error) {
            console.log(error.stack);
            // Handle any error from all above steps
            assert(!error, 'Error thrown!');
          })
          .done();

      });
    });

  });

  describe('Senders', function() {

    it('instantiate a new sender', function() {
      var sender = new Sender({name: 'testsender'});
      assert(sender, 'No sender!');
      assert.equal(sender.name, 'testsender', 'Sender has no name!');
    });

    it('should support basic crud operations', function(done) {
      var sender = new Sender({name: 'testsender'});
      assert(sender, 'No sender!');
      assert.equal(sender.name, 'testsender', 'Sender has no name!');

      sender.save(function (err) {
        assert(!err, err);

        // find the entry again
        Sender.findOne({}).exec(function (err, foundSender) {

          console.log(foundSender);

          assert(!err, err);
          assert.equal(foundSender.name, 'testsender', 'Sender has no name!');
          console.info('Found sender ' + foundSender.toString());
          done();
        });

      });

    });

  });

  describe('Tags', function() {

    it('instantiate a new tag', function() {
      var tag = new Tag({name: 'testtag'});
      assert(tag, 'No tag!');
      assert.equal(tag.name, 'testtag', 'Tag has no name!');
    });

    it('should support basic crud operations', function(done) {
      var tag = new Tag({name: 'testtag'});
      assert(tag, 'No tag!');
      assert.equal(tag.name, 'testtag', 'Tag has no name!');

      tag.save(function (err) {
        assert(!err, err);

        // find the entry again
        Tag.findOne({}).exec(function (err, foundTag) {
          assert(!err, err);
          assert.equal(foundTag.name, 'testtag', 'Tag has no name!');
          console.info('Found tag ' + foundTag.toString());
          done();
        });

      });
    });
  });

  describe('Documents', function() {
    it('instantiate a new document', function() {
      var doc = new Document({title: 'testdocument'});

      assert(doc, 'No doc!');
      assert.equal(doc.title, 'testdocument', 'Doc has no title!');
    });

    it('should support basic crud operations', function(done) {
      var doc = new Document({title: 'testdocument'});

      assert(doc, 'No doc!');
      assert.equal(doc.title, 'testdocument', 'Doc has no title!');

      doc.fileName = 'test.pdf';

      var tag = new Tag({ name: 'testtag1'});
      tag.save(function(err){
        assert(!err, err);
        console.log('use tagId: ' + tag._id);
        doc.tags.push(tag._id);

        doc.save(function(err) {
          assert(!err, err);

          assert.notEqual(doc.alternativeId, '', 'Pre save magic did not work!');

          Document.findOne({ title: 'testdocument'}).exec(function (err, foundDoc) {
            assert(!err, err);
            assert.equal(foundDoc.title, 'testdocument', 'Document has no name!');
            console.info('Found document ' + foundDoc.toString());

            // use the reference to find the selected tag
            var objectId = doc.tags[0];
            Tag.findOne( { _id: objectId }).exec(function(err, foundTag) {
              assert(!err, err);
              assert(foundTag, 'Tag not found');
              assert.equal(foundTag.name, 'testtag1', 'Tag name does not match!');

              console.info('Found tag ' + foundTag.toString());
            });

            done();
          });
        });

      });
    });
  });

  describe('Services', function() {
    it('should handle a list of senders', function(done) {
      var objectList = [],
          dataService = new MasterDataService();

      objectList.push({ _id: -1, name: 'Sender1' }); // new one
      // find the entry
      Sender.findOne({name: 'testsender'}).exec(function (err, foundSender) {
        assert(!err, err);
        objectList.push(foundSender);

        dataService.createAndGetSenders(objectList).then(function(senderList) {
          assert(senderList, 'No senders returned !' );
          console.log(senderList);
          assert.equal(senderList.length, 2, 'Number of senders');

          assert.notEqual(senderList[0]._id, -1, 'Wrong id');
          assert.equal(senderList[1].name, 'testsender', 'Wrong name');

          done();
        })
        .catch(function(error) {
          console.log(error.stack);
          // Handle any error from all above steps
          assert(!error, 'Error thrown!');
        })
        .done();

      });

    });

    it('should handle a list of tags', function(done) {
      var objectList = [],
          dataService = new MasterDataService();

      objectList.push({ _id: -1, name: 'Tag1' }); // new one
      // find the entry
      Tag.findOne({name: 'testtag'}).exec(function (err, foundTag) {
        assert(!err, err);
        objectList.push(foundTag);

        dataService.createAndGetTags(objectList).then(function(tagList) {
          assert(tagList, 'No tags returned !' );
          assert.equal(tagList.length, 2, 'Number of tags');

          assert.notEqual(tagList[0]._id, -1, 'Wrong id');
          assert.equal(tagList[1].name, 'testtag', 'Wrong name');

          done();
        })
        .catch(function(error) {
          console.log(error.stack);
          // Handle any error from all above steps
          assert(!error, 'Error thrown!');
        })
        .done();

      });
    });

    it('should save a NEW document object', function(done) {
        var documentService = new DocumentService(),
            dataService = new MasterDataService(),
            tagList,
            senderList;

        dataService.createAndGetTags(testDocument.tags).then(function(list) {
          tagList = list;

          assert(list, 'No tags supplied');

          return dataService.createAndGetSenders(testDocument.senders);
        })
        .then(function(list) {
          senderList = list;

          assert(list, 'No senders supplied');

          testDocument.tags = tagList;
          testDocument.senders = senderList;

          return documentService.save(testDocument);
        })
        .then(function(doc) {
          assert(doc, 'No document returned !' );
          assert.equal(doc.title, 'TEST', 'Wrong title');
          assert.equal(doc.senders.length, 1, 'Wrong number of senders');

          console.log('\n' + doc);
          logger.dump(doc);

          done();
        })
       .catch(function(error) {
          console.log(error.stack);
          // Handle any error from all above steps
          assert(!error, 'Error thrown!');
        })
        .done();

      });

      it('should update a document object', function(done) {
        var documentService = new DocumentService(),
            dataService = new MasterDataService(),
            tagList,
            senderList;

        Document.findOne({title: 'TEST'}).exec(function (err, foundDoc) {
          assert(!err, err);

          testDocument._id = foundDoc._id;
          testDocument.title = foundDoc.title;
          testDocument.amount = foundDoc.amount;

          dataService.createAndGetTags(testDocument.tags).then(function(list) {
            tagList = list;

            assert(list, 'No tags supplied');

            return dataService.createAndGetSenders(testDocument.senders);
          })
          .then(function(list) {
            senderList = list;

            assert(list, 'No senders supplied');

            testDocument.tags = tagList;
            testDocument.senders = senderList;

            return documentService.save(testDocument);
          })
          .then(function(doc) {
            assert(doc, 'No document returned !' );
            assert.equal(doc.title, 'TEST', 'Wrong title');
            assert.equal(doc.senders.length, 1, 'Wrong number of senders');

            console.log('\n' + doc);
            logger.dump(doc);

            done();
          })
         .catch(function(error) {
            console.log(error.stack);
            // Handle any error from all above steps
            assert(!error, 'Error thrown!');
          })
          .done();

        });

      });
  });

});
<|endoftext|>


<commit_before>module.exports = function(app, database) {
// -----------------------------------------------------------
  // TODO
  // prepend authentication to all routes

  // TODO
  // use permissions - [ user, administrator ]
  //
  // all routes may be used by administrator
  //
  // only specific routes may be used by user

  // set up routes
// -----------------------------------------------------------
  app.use('/', require('./routes/index'));                                       // title page
  app.use('/angular_test', require('./routes/angular_test'));                    // angular test page
  app.use('/search', require('./routes/search'));                                // generic search api
  app.use('/mac_count', require('./routes/mac_count'));                          // generic api for mac address count
  app.use('/roaming/most_provided', require('./routes/roaming_most_provided'));  // generic api for institutions most providing roaming
  app.use('/roaming/most_used', require('./routes/roaming_most_used'));          // generic api for institutions most using roaming
  app.use('/invalid_records', require('./routes/invalid_records'));              // api for invalid records
  app.use('/failed_logins', require('./routes/failed_logins'));                  // generic api for failed logins
  // TODO
  //app.use('/mac_identifier', require('./routes/mac_identifier'));              // TODO
  //app.use('/lost_devices', require('./routes/lost_device'));              // TODO
  // app.use('/stats', require('./routes/stats'));   // TODO

// -----------------------------------------------------------
  // login routing is defined separately
  // see auth.js
  // TODO
  // metadata url

  // saml test
  app.use('/auth_fail', require('./routes/auth_fail'));
  //app.use('/login/callback', require('./routes/callback'));
}
<commit_msg>new routes structure<commit_after>module.exports = function(app, database) {
// -----------------------------------------------------------
  // TODO
  // prepend authentication to all routes

  // TODO
  // use permissions - [ user, administrator ]
  //
  // all routes may be used by administrator
  //
  // only specific routes may be used by user

  // set up routes
// -----------------------------------------------------------
  app.use('/', require('./routes/index'));                                       // title page
  app.use('/api/search', require('./routes/search'));                                // generic search api
  app.use('/api/mac_count', require('./routes/mac_count'));                          // generic api for mac address count
  app.use('/api/roaming/most_provided', require('./routes/roaming_most_provided'));  // generic api for institutions most providing roaming
  app.use('/api/roaming/most_used', require('./routes/roaming_most_used'));          // generic api for institutions most using roaming
  app.use('/api/invalid_records', require('./routes/invalid_records'));              // api for invalid records
  app.use('/api/failed_logins', require('./routes/failed_logins'));                  // generic api for failed logins
  // TODO
  //app.use('/api/mac_identifier', require('./routes/mac_identifier'));              // TODO
  //app.use('/api/lost_devices', require('./routes/lost_device'));              // TODO
  // app.use('/api/stats', require('./routes/stats'));   // TODO

// -----------------------------------------------------------
  // login routing is defined separately
  // see auth.js
  // TODO
  // metadata url

  // saml test
  app.use('/auth_fail', require('./routes/auth_fail'));
  //app.use('/login/callback', require('./routes/callback'));
}
<|endoftext|>