<commit_before>var CloudCmd, Util, DOM;

(function(CloudCmd, Util, DOM) {
    'use strict';

    var Info    = DOM.CurrentInfo,
        Events  = DOM.Events,
        Buffer  = DOM.Buffer,

        Chars   = [],
        KEY     = {
            BACKSPACE   : 8,
            TAB         : 9,
            ENTER       : 13,
            ESC         : 27,

            SPACE       : 32,
            PAGE_UP     : 33,
            PAGE_DOWN   : 34,
            END         : 35,
            HOME        : 36,

            LEFT        : 37,
            UP          : 38,
            RIGHT       : 39,
            DOWN        : 40,

            INSERT      : 45,
            DELETE      : 46,

            ZERO        : 48,

            A           : 65,

            C           : 67,
            D           : 68,

            G           : 71,

            O           : 79,
            Q           : 81,
            R           : 82,
            S           : 83,
            T           : 84,
            U           : 85,

            V           : 86,

            X           : 88,

            Z           : 90,

            INSERT_MAC  : 96,

            ASTERISK    : 106,
            PLUS        : 107,
            MINUS       : 109,

            F1          : 112,
            F2          : 113,
            F3          : 114,
            F4          : 115,
            F5          : 116,
            F6          : 117,
            F7          : 118,
            F8          : 119,
            F9          : 120,
            F10         : 121,

            EQUAL       : 187,
            HYPHEN      : 189,
            DOT         : 190,
            SLASH       : 191,
            TRA         : 192, /* Typewritten Reverse Apostrophe (`) */
            BACKSLASH   : 220,

            BRACKET_CLOSE: 221
        };

    KeyProto.prototype = KEY;
    CloudCmd.Key = KeyProto;

    function KeyProto() {
        var Key = this,
            Binded;

        this.isBind     = function() {
            return Binded;
        };

        this.setBind    = function() {
            Binded = true;
        };

        this.unsetBind  = function() {
            Binded = false;
        };

        this.bind   = function() {
            Events.addKey(listener);
            Binded = true;
        };

        function listener(event) {
            /* get selected file */
            var keyCode         = event.keyCode,
                alt             = event.altKey,
                ctrl            = event.ctrlKey,
                shift           = event.shiftKey,
                meta            = event.metaKey,
                keyIdentifier   = event.keyIdentifier,
                isBetween       = keyCode >= KEY.ZERO && keyCode <= KEY.Z,
                isSymbol,
                char            = '';

            if (keyIdentifier)
                char = fromCharCode(keyIdentifier);
            else
                char = event.key;

            isSymbol = ~['.', '_', '-', '+', '='].indexOf(char);

            if (!isSymbol) {
                isSymbol = getSymbol(shift, keyCode);

                if (isSymbol)
                    char = isSymbol;
            }

            /* in case buttons can be processed */
            if (Key.isBind())
                if (!alt && !ctrl && !meta && (isBetween || isSymbol))
                    setCurrentByChar(char);
                else {
                    Chars       = [];
                    switchKey(event);
                }
        }

        function getSymbol(shift, keyCode) {
            var char;

            switch (keyCode) {
            case KEY.DOT:
                char = '.';
                break;

            case KEY.HYPHEN:
                char = shift ? '_' : '-';
                break;

            case KEY.EQUAL:
                char = shift ? '+' : '=';
                break;
            }

            return char;
        }

        function fromCharCode(keyIdentifier) {
            var code    = keyIdentifier.substring(2),
                hex     = parseInt(code, 16),
                char    = String.fromCharCode(hex);

            return char;
        }

        function setCurrentByChar(char) {
            var name, isMatch, byName, firstByName,
                skipCount   = 0,
                skipN       = 0,
                setted      = false,
                current     = Info.element,
                files       = Info.files,
                escapeChar  = Util.escapeRegExp(char),
                regExp      = new RegExp('^' + escapeChar + '.*$', 'i'),
                i           = 0,
                n           = Chars.length;

            while(i < n && char === Chars[i]) {
                i++;
            }

            if (!i)
                Chars = [];

            skipN           = skipCount = i;
            Chars.push(char);

            n               = files.length;
            for (i = 0; i < n; i++) {
                current     = files[i];
                name        = DOM.getCurrentName(current);
                isMatch     = name.match(regExp);

                if (isMatch && name !== '..') {
                    byName = DOM.getCurrentByName(name);

                    if (!skipCount) {
                        setted = true;
                        DOM.setCurrentFile(byName);
                        break;
                    } else {
                        if (skipN === skipCount)
                            firstByName = byName;

                        --skipCount;
                    }
                }
            }

            if (!setted) {
                DOM.setCurrentFile(firstByName);
                Chars = [char];
            }
        }

        function switchKey(event) {
            var i, name, isSelected, isDir, prev, next,
                Operation       = CloudCmd.Operation,
                current         = Info.element,
                panel           = Info.panel,
                path            = Info.path,
                keyCode         = event.keyCode,
                alt             = event.altKey,
                shift           = event.shiftKey,
                ctrl            = event.ctrlKey,
                meta            = event.metaKey,
                ctrlMeta        = ctrl || meta;

            if (current) {
                prev            = current.previousSibling;
                next            = current.nextSibling;
            }

            switch (keyCode) {
            case Key.TAB:
                DOM.changePanel();
                event.preventDefault();
                break;

            case Key.INSERT:
                DOM .toggleSelectedFile(current)
                    .setCurrentFile(next);
                break;

            case Key.INSERT_MAC:
                DOM .toggleSelectedFile(current)
                    .setCurrentFile(next);
                break;

            case Key.DELETE:
                if (shift)
                    Operation.show('delete:silent');
                else
                    Operation.show('delete');
                break;

            case Key.ASTERISK:
                DOM.toggleAllSelectedFiles(current);
                break;

            case Key.PLUS:
                DOM.expandSelection();
                break;

            case Key.MINUS:
                DOM.shrinkSelection();
                break;

            case Key.F1:
                CloudCmd.Help.show();
                event.preventDefault();
                break;

            case Key.F2:
                DOM.renameCurrent(current);
                break;

            case Key.F3:
                if (shift)
                    CloudCmd.Markdown.show(path);
                else
                    CloudCmd.View.show();

                event.preventDefault();
                break;

            case Key.F4:
                CloudCmd.Edit.show();
                event.preventDefault();
                break;

            case Key.F5:
                Operation.show('copy');
                event.preventDefault();
                break;

            case Key.F6:
                Operation.show('move');
                event.preventDefault();
                break;

            case Key.F7:
                if (shift)
                    DOM.promptNewFile();
                else
                    DOM.promptNewDir();

                event.preventDefault();
                break;

            case Key.F8:
                Operation.show('delete');
                break;

            case Key.F9:
                CloudCmd.Menu.show();
                event.preventDefault();
                break;

            case Key.F10:
                CloudCmd.Config.show();
                event.preventDefault();
                break;

            case Key.TRA:
                DOM.Images.show.load('top');
                CloudCmd.Konsole.show();
                event.preventDefault();
                break;

            case KEY.BRACKET_CLOSE:
                DOM.Images.show.load('top');
                CloudCmd.Konsole.show();
                event.preventDefault();
                break;

            case Key.SPACE:
                isDir   = Info.isDir,
                name    = Info.name;

                if (!isDir || name === '..')
                    isSelected    = true;
                else
                    isSelected    = DOM.isSelected(current);

                Util.exec.if(isSelected, function() {
                    DOM.toggleSelectedFile(current);
                }, function(callback) {
                    DOM.loadCurrentSize(callback, current);
                });

                event.preventDefault();
                break;

            case Key.U:
                if (ctrlMeta) {
                    DOM.swapPanels();
                    event.preventDefault();
                }
                break;

            /* navigation on file table:        *
             * in case of pressing button 'up', *
             * select previous row              */
            case Key.UP:
                if (shift)
                    DOM.toggleSelectedFile(current);

                DOM.setCurrentFile(prev);
                event.preventDefault();
                break;

            /* in case of pressing button 'down', *
             * select next row                    */
            case Key.DOWN:
                if (shift)
                    DOM.toggleSelectedFile(current);

                DOM.setCurrentFile(next);
                event.preventDefault();
                break;

            case Key.LEFT:
                    if (alt) {
                        name = Info.panel.getAttribute('data-name');

                        if (name === 'js-right') {
                            DOM.duplicatePanel();
                            event.preventDefault();
                        }
                    }
                break;

            case Key.RIGHT:
                    if (alt) {
                        name = Info.panel.getAttribute('data-name');

                        if (name === 'js-left') {
                            DOM.duplicatePanel();
                            event.preventDefault();
                        }
                    }
                break;

            /* in case of pressing button 'Home',  *
             * go to top element                   */
            case Key.HOME:
                DOM.setCurrentFile(Info.first);
                event.preventDefault();
                break;

            /* in case of pressing button 'End', select last element */
            case Key.END:
                DOM.setCurrentFile(Info.last);
                event.preventDefault();
                break;

            /* если нажали клавишу page down проматываем экран */
            case Key.PAGE_DOWN:
                DOM.scrollByPages(panel, 1);

                for (i = 0; i < 30; i++) {
                    if (!current.nextSibling)
                        break;

                    current = current.nextSibling;
                }

                DOM.setCurrentFile(current);
                event.preventDefault();
                break;

            /* если нажали клавишу page up проматываем экран */
            case Key.PAGE_UP:
                DOM.scrollByPages(panel, -1);

                for (i = 0; i < 30; i++) {
                    if (!current.previousSibling)
                        break;

                    current = current.previousSibling;
                }

                DOM.setCurrentFile(current);
                event.preventDefault();
                break;

            /* open directory */
            case Key.ENTER:
                if (Info.isDir)
                    CloudCmd.loadDir({
                        path: DOM.getCurrentPath() + '/'
                    });
                break;

            case Key.BACKSPACE:
                CloudCmd.goToParentDir();
                event.preventDefault();
                break;

            case Key.BACKSLASH:
                if (ctrlMeta)
                    CloudCmd.loadDir({
                        path: '/'
                    });
                break;

            case Key.A:
                if (ctrlMeta) {
                    DOM.toggleAllSelectedFiles();
                    event.preventDefault();
                }

                break;

            case Key.G:
                if (alt)
                    DOM.goToDirectory();

                break;

            /**
             * обновляем страницу,
             * загружаем содержимое каталога
             * при этом данные берём всегда с
             * сервера, а не из кэша
             * (обновляем кэш)
             */
            case Key.R:
                if (ctrlMeta) {
                    CloudCmd.log('reloading page...\n');
                    CloudCmd.refresh();
                    event.preventDefault();
                }
                break;

            case Key.C:
                if (ctrlMeta)
                    Buffer.copy();
                break;

            case Key.X:
                if (ctrlMeta)
                    Buffer.cut();
                break;

            case Key.V:
                if (ctrlMeta)
                   Buffer.paste();
                break;

            case Key.Z:
                if (ctrlMeta)
                    Buffer.clear();
                break;

            /* чистим хранилище */
            case Key.D:
                if (ctrlMeta) {
                    CloudCmd.log('clearing storage...');

                    DOM.Storage.clear(function() {
                        CloudCmd.log('storage cleared');
                    });

                    event.preventDefault();
                }
                break;
            }
        }
    }

})(CloudCmd, Util, DOM);
<commit_msg>fix(key) double slash in path<commit_after>var CloudCmd, Util, DOM;

(function(CloudCmd, Util, DOM) {
    'use strict';

    var Info    = DOM.CurrentInfo,
        Events  = DOM.Events,
        Buffer  = DOM.Buffer,

        Chars   = [],
        KEY     = {
            BACKSPACE   : 8,
            TAB         : 9,
            ENTER       : 13,
            ESC         : 27,

            SPACE       : 32,
            PAGE_UP     : 33,
            PAGE_DOWN   : 34,
            END         : 35,
            HOME        : 36,

            LEFT        : 37,
            UP          : 38,
            RIGHT       : 39,
            DOWN        : 40,

            INSERT      : 45,
            DELETE      : 46,

            ZERO        : 48,

            A           : 65,

            C           : 67,
            D           : 68,

            G           : 71,

            O           : 79,
            Q           : 81,
            R           : 82,
            S           : 83,
            T           : 84,
            U           : 85,

            V           : 86,

            X           : 88,

            Z           : 90,

            INSERT_MAC  : 96,

            ASTERISK    : 106,
            PLUS        : 107,
            MINUS       : 109,

            F1          : 112,
            F2          : 113,
            F3          : 114,
            F4          : 115,
            F5          : 116,
            F6          : 117,
            F7          : 118,
            F8          : 119,
            F9          : 120,
            F10         : 121,

            EQUAL       : 187,
            HYPHEN      : 189,
            DOT         : 190,
            SLASH       : 191,
            TRA         : 192, /* Typewritten Reverse Apostrophe (`) */
            BACKSLASH   : 220,

            BRACKET_CLOSE: 221
        };

    KeyProto.prototype = KEY;
    CloudCmd.Key = KeyProto;

    function KeyProto() {
        var Key = this,
            Binded;

        this.isBind     = function() {
            return Binded;
        };

        this.setBind    = function() {
            Binded = true;
        };

        this.unsetBind  = function() {
            Binded = false;
        };

        this.bind   = function() {
            Events.addKey(listener);
            Binded = true;
        };

        function listener(event) {
            /* get selected file */
            var keyCode         = event.keyCode,
                alt             = event.altKey,
                ctrl            = event.ctrlKey,
                shift           = event.shiftKey,
                meta            = event.metaKey,
                keyIdentifier   = event.keyIdentifier,
                isBetween       = keyCode >= KEY.ZERO && keyCode <= KEY.Z,
                isSymbol,
                char            = '';

            if (keyIdentifier)
                char = fromCharCode(keyIdentifier);
            else
                char = event.key;

            isSymbol = ~['.', '_', '-', '+', '='].indexOf(char);

            if (!isSymbol) {
                isSymbol = getSymbol(shift, keyCode);

                if (isSymbol)
                    char = isSymbol;
            }

            /* in case buttons can be processed */
            if (Key.isBind())
                if (!alt && !ctrl && !meta && (isBetween || isSymbol))
                    setCurrentByChar(char);
                else {
                    Chars       = [];
                    switchKey(event);
                }
        }

        function getSymbol(shift, keyCode) {
            var char;

            switch (keyCode) {
            case KEY.DOT:
                char = '.';
                break;

            case KEY.HYPHEN:
                char = shift ? '_' : '-';
                break;

            case KEY.EQUAL:
                char = shift ? '+' : '=';
                break;
            }

            return char;
        }

        function fromCharCode(keyIdentifier) {
            var code    = keyIdentifier.substring(2),
                hex     = parseInt(code, 16),
                char    = String.fromCharCode(hex);

            return char;
        }

        function setCurrentByChar(char) {
            var name, isMatch, byName, firstByName,
                skipCount   = 0,
                skipN       = 0,
                setted      = false,
                current     = Info.element,
                files       = Info.files,
                escapeChar  = Util.escapeRegExp(char),
                regExp      = new RegExp('^' + escapeChar + '.*$', 'i'),
                i           = 0,
                n           = Chars.length;

            while(i < n && char === Chars[i]) {
                i++;
            }

            if (!i)
                Chars = [];

            skipN           = skipCount = i;
            Chars.push(char);

            n               = files.length;
            for (i = 0; i < n; i++) {
                current     = files[i];
                name        = DOM.getCurrentName(current);
                isMatch     = name.match(regExp);

                if (isMatch && name !== '..') {
                    byName = DOM.getCurrentByName(name);

                    if (!skipCount) {
                        setted = true;
                        DOM.setCurrentFile(byName);
                        break;
                    } else {
                        if (skipN === skipCount)
                            firstByName = byName;

                        --skipCount;
                    }
                }
            }

            if (!setted) {
                DOM.setCurrentFile(firstByName);
                Chars = [char];
            }
        }

        function switchKey(event) {
            var i, name, isSelected, isDir, prev, next,
                Operation       = CloudCmd.Operation,
                current         = Info.element,
                panel           = Info.panel,
                path            = Info.path,
                keyCode         = event.keyCode,
                alt             = event.altKey,
                shift           = event.shiftKey,
                ctrl            = event.ctrlKey,
                meta            = event.metaKey,
                ctrlMeta        = ctrl || meta;

            if (current) {
                prev            = current.previousSibling;
                next            = current.nextSibling;
            }

            switch (keyCode) {
            case Key.TAB:
                DOM.changePanel();
                event.preventDefault();
                break;

            case Key.INSERT:
                DOM .toggleSelectedFile(current)
                    .setCurrentFile(next);
                break;

            case Key.INSERT_MAC:
                DOM .toggleSelectedFile(current)
                    .setCurrentFile(next);
                break;

            case Key.DELETE:
                if (shift)
                    Operation.show('delete:silent');
                else
                    Operation.show('delete');
                break;

            case Key.ASTERISK:
                DOM.toggleAllSelectedFiles(current);
                break;

            case Key.PLUS:
                DOM.expandSelection();
                break;

            case Key.MINUS:
                DOM.shrinkSelection();
                break;

            case Key.F1:
                CloudCmd.Help.show();
                event.preventDefault();
                break;

            case Key.F2:
                DOM.renameCurrent(current);
                break;

            case Key.F3:
                if (shift)
                    CloudCmd.Markdown.show(path);
                else
                    CloudCmd.View.show();

                event.preventDefault();
                break;

            case Key.F4:
                CloudCmd.Edit.show();
                event.preventDefault();
                break;

            case Key.F5:
                Operation.show('copy');
                event.preventDefault();
                break;

            case Key.F6:
                Operation.show('move');
                event.preventDefault();
                break;

            case Key.F7:
                if (shift)
                    DOM.promptNewFile();
                else
                    DOM.promptNewDir();

                event.preventDefault();
                break;

            case Key.F8:
                Operation.show('delete');
                break;

            case Key.F9:
                CloudCmd.Menu.show();
                event.preventDefault();
                break;

            case Key.F10:
                CloudCmd.Config.show();
                event.preventDefault();
                break;

            case Key.TRA:
                DOM.Images.show.load('top');
                CloudCmd.Konsole.show();
                event.preventDefault();
                break;

            case KEY.BRACKET_CLOSE:
                DOM.Images.show.load('top');
                CloudCmd.Konsole.show();
                event.preventDefault();
                break;

            case Key.SPACE:
                isDir   = Info.isDir,
                name    = Info.name;

                if (!isDir || name === '..')
                    isSelected    = true;
                else
                    isSelected    = DOM.isSelected(current);

                Util.exec.if(isSelected, function() {
                    DOM.toggleSelectedFile(current);
                }, function(callback) {
                    DOM.loadCurrentSize(callback, current);
                });

                event.preventDefault();
                break;

            case Key.U:
                if (ctrlMeta) {
                    DOM.swapPanels();
                    event.preventDefault();
                }
                break;

            /* navigation on file table:        *
             * in case of pressing button 'up', *
             * select previous row              */
            case Key.UP:
                if (shift)
                    DOM.toggleSelectedFile(current);

                DOM.setCurrentFile(prev);
                event.preventDefault();
                break;

            /* in case of pressing button 'down', *
             * select next row                    */
            case Key.DOWN:
                if (shift)
                    DOM.toggleSelectedFile(current);

                DOM.setCurrentFile(next);
                event.preventDefault();
                break;

            case Key.LEFT:
                    if (alt) {
                        name = Info.panel.getAttribute('data-name');

                        if (name === 'js-right') {
                            DOM.duplicatePanel();
                            event.preventDefault();
                        }
                    }
                break;

            case Key.RIGHT:
                    if (alt) {
                        name = Info.panel.getAttribute('data-name');

                        if (name === 'js-left') {
                            DOM.duplicatePanel();
                            event.preventDefault();
                        }
                    }
                break;

            /* in case of pressing button 'Home',  *
             * go to top element                   */
            case Key.HOME:
                DOM.setCurrentFile(Info.first);
                event.preventDefault();
                break;

            /* in case of pressing button 'End', select last element */
            case Key.END:
                DOM.setCurrentFile(Info.last);
                event.preventDefault();
                break;

            /* если нажали клавишу page down проматываем экран */
            case Key.PAGE_DOWN:
                DOM.scrollByPages(panel, 1);

                for (i = 0; i < 30; i++) {
                    if (!current.nextSibling)
                        break;

                    current = current.nextSibling;
                }

                DOM.setCurrentFile(current);
                event.preventDefault();
                break;

            /* если нажали клавишу page up проматываем экран */
            case Key.PAGE_UP:
                DOM.scrollByPages(panel, -1);

                for (i = 0; i < 30; i++) {
                    if (!current.previousSibling)
                        break;

                    current = current.previousSibling;
                }

                DOM.setCurrentFile(current);
                event.preventDefault();
                break;

            /* open directory */
            case Key.ENTER:
                if (Info.isDir)
                    CloudCmd.loadDir({
                        path: path === '/' ? '/' : path + '/'
                    });
                break;

            case Key.BACKSPACE:
                CloudCmd.goToParentDir();
                event.preventDefault();
                break;

            case Key.BACKSLASH:
                if (ctrlMeta)
                    CloudCmd.loadDir({
                        path: '/'
                    });
                break;

            case Key.A:
                if (ctrlMeta) {
                    DOM.toggleAllSelectedFiles();
                    event.preventDefault();
                }

                break;

            case Key.G:
                if (alt)
                    DOM.goToDirectory();

                break;

            /**
             * обновляем страницу,
             * загружаем содержимое каталога
             * при этом данные берём всегда с
             * сервера, а не из кэша
             * (обновляем кэш)
             */
            case Key.R:
                if (ctrlMeta) {
                    CloudCmd.log('reloading page...\n');
                    CloudCmd.refresh();
                    event.preventDefault();
                }
                break;

            case Key.C:
                if (ctrlMeta)
                    Buffer.copy();
                break;

            case Key.X:
                if (ctrlMeta)
                    Buffer.cut();
                break;

            case Key.V:
                if (ctrlMeta)
                   Buffer.paste();
                break;

            case Key.Z:
                if (ctrlMeta)
                    Buffer.clear();
                break;

            /* чистим хранилище */
            case Key.D:
                if (ctrlMeta) {
                    CloudCmd.log('clearing storage...');

                    DOM.Storage.clear(function() {
                        CloudCmd.log('storage cleared');
                    });

                    event.preventDefault();
                }
                break;
            }
        }
    }

})(CloudCmd, Util, DOM);
<|endoftext|>


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

  $('.changeRole').click(function(event) {
    var GroupID = $(this).data("groupid");
    window.CRM.groups.promptSelection({Type:window.CRM.groups.selectTypes.Role,GroupID:GroupID},function(selection){
      window.CRM.groups.addPerson(GroupID,window.CRM.currentPersonID,selection.RoleID).done(function(){
        location.reload();
      })

    });
  });

  $(".groupRemove").click(function(event){
    var targetGroupID = event.currentTarget.dataset.groupid;
    var targetGroupName = event.currentTarget.dataset.groupname;

    bootbox.confirm({
      message: i18next.t("Are you sure you want to remove this person's membership from") + " " + targetGroupName + "?",
      buttons: {
        confirm: {
          label: i18next.t('Yes'),
            className: 'btn-success'
        },
        cancel: {
          label: i18next.t('No'),
          className: 'btn-danger'
        }
      },
      callback: function (result)
      {
        if (result)
        {
          window.CRM.groups.removePerson(targetGroupID,window.CRM.currentPersonID).done(
            function(){
              location.reload()
            }
          );
        }
      }
    });
  })

  $("#addGroup").click(function() {
    var target = window.CRM.groups.promptSelection({Type:window.CRM.groups.selectTypes.Group | window.CRM.groups.selectTypes.Role}, function(data){
      window.CRM.groups.addPerson(data.GroupID,window.CRM.currentPersonID,data.RoleID).done(function(){
          location.reload()
        }
      );
    });
  });

    $("#input-person-properties").on("select2:select", function (event) {
        promptBox = $("#prompt-box");
        promptBox.removeClass('form-group').html('');
        selected = $("#input-person-properties :selected");
        pro_prompt = selected.data('pro_prompt');
        pro_value = selected.data('pro_value');
        if (pro_prompt) {
            promptBox
                .addClass('form-group')
                .append(
                    $('').html(pro_prompt)
                )
                .append(
                    $('<textarea rows="3" class="form-control" name="PropertyValue"></textarea>').val(pro_value)
                );
        }

    });

    $('#assign-property-form').submit(function (event) {
        event.preventDefault();
        var thisForm = $(this);
        var url = thisForm.attr('action');
        var dataToSend = thisForm.serialize();

        $.ajax({
            type: 'POST',
            url: url,
            data: dataToSend,
            dataType: 'json',
            success: function (data, status, xmlHttpReq) {
                if (data && data.success) {
                    location.reload();
                }
            }
        });

    });

    $('.remove-property-btn').click(function (event) {
        event.preventDefault();
        var thisLink = $(this);
        var dataToSend = {
            PersonId: thisLink.data('person_id'),
            PropertyId: thisLink.data('property_id')
        };
        var url = window.CRM.root + '/api/properties/persons/unassign';

        bootbox.confirm(i18next.t('Are you sure you want to unassign this property?'), function (result) {
            if (result) {
                $.ajax({
                    type: 'DELETE',
                    url: url,
                    data: dataToSend,
                    dataType: 'json',
                    success: function (data, status, xmlHttpReq) {
                        if (data && data.success) {
                            location.reload();
                        }
                    }
                });
            }
        });

    });

    $('#edit-role-btn').click(function (event) {
        event.preventDefault();
        var thisLink = $(this);
        var personId = thisLink.data('person_id');
        var familyRoleId = thisLink.data('family_role_id');
        var familyRole = thisLink.data('family_role');

        $.ajax({
            type: 'GET',
            dataType: 'json',
            url: window.CRM.root + '/api/persons/roles',
            success: function (data, status, xmlHttpReq) {
                if (data.length) {
                    roles = [{text: familyRole, value: ''}];
                    for (var i=0; i < data.length; i++) {
                        if (data[i].OptionId == familyRoleId) {
                            continue;
                        }

                        roles[roles.length] = {
                            text: data[i].OptionName,
                            value: data[i].OptionId
                        };
                    }

                    bootbox.prompt({
                        title:i18next.t( 'Change role'),
                        inputType: 'select',
                        inputOptions: roles,
                        callback: function (result) {
                            if (result) {
                                $.ajax({
                                    type: 'POST',
                                    dataType: 'json',
                                    url: window.CRM.root + '/api/person/'+ personId +'/role/' +result,
                                    success: function (data, status, xmlHttpReq) {
                                        if (data.success) {
                                            location.reload();
                                        }
                                    }
                                });
                            }

                        }
                    });

                }
            }
        });

    });

   $.ajax({
       type: 'GET',
       dataType: 'json',
       url: window.CRM.root + '/api/mailchimp/person/' + window.CRM.currentPersonID,
       success: function (data, status, xmlHttpReq) {
           for (emailData of data) {
               let htmlVal = "";
               let eamilMD5 = emailData["emailMD5"];
               for (list of emailData["list"]) {
                   let listName = list["name"];
                   let listStatus = list["status"];
                   if (listStatus != 404) {
                       let listOpenRate = list["stats"]["avg_open_rate"]*100;
                       htmlVal = htmlVal + '
' + listName + " (" + listStatus + ") - " + listOpenRate + "% "+  i18next.t("open rate") + "
";
                   }
               }
               if (htmlVal === "") {
                   htmlVal = i18next.t("Not Subscribed ");
               }
               $('#'+ eamilMD5).html(htmlVal);
           }
       }
   });

});
<commit_msg>updated the AJAX calls for add/update property and remove to match new APIs<commit_after>$(document).ready(function () {

  $('.changeRole').click(function(event) {
    var GroupID = $(this).data("groupid");
    window.CRM.groups.promptSelection({Type:window.CRM.groups.selectTypes.Role,GroupID:GroupID},function(selection){
      window.CRM.groups.addPerson(GroupID,window.CRM.currentPersonID,selection.RoleID).done(function(){
        location.reload();
      })

    });
  });

  $(".groupRemove").click(function(event){
    var targetGroupID = event.currentTarget.dataset.groupid;
    var targetGroupName = event.currentTarget.dataset.groupname;

    bootbox.confirm({
      message: i18next.t("Are you sure you want to remove this person's membership from") + " " + targetGroupName + "?",
      buttons: {
        confirm: {
          label: i18next.t('Yes'),
            className: 'btn-success'
        },
        cancel: {
          label: i18next.t('No'),
          className: 'btn-danger'
        }
      },
      callback: function (result)
      {
        if (result)
        {
          window.CRM.groups.removePerson(targetGroupID,window.CRM.currentPersonID).done(
            function(){
              location.reload()
            }
          );
        }
      }
    });
  })

  $("#addGroup").click(function() {
    var target = window.CRM.groups.promptSelection({Type:window.CRM.groups.selectTypes.Group | window.CRM.groups.selectTypes.Role}, function(data){
      window.CRM.groups.addPerson(data.GroupID,window.CRM.currentPersonID,data.RoleID).done(function(){
          location.reload()
        }
      );
    });
  });

    $("#input-person-properties").on("select2:select", function (event) {
        promptBox = $("#prompt-box");
        promptBox.removeClass('form-group').html('');
        selected = $("#input-person-properties :selected");
        pro_prompt = selected.data('pro_prompt');
        pro_value = selected.data('pro_value');
        if (pro_prompt) {
            promptBox
                .addClass('form-group')
                .append(
                    $('').html(pro_prompt)
                )
                .append(
                    $('<textarea rows="3" class="form-control" name="PropertyValue"></textarea>').val(pro_value)
                );
        }

    });

    $('#assign-property-btn').click(function (event) {
        let propertyId = "";
        let value = "";
        let dataToSend = $('#assign-property-form').serializeArray();
        $.each(dataToSend, function (key, field) {
            if (field.name == "PropertyId") {
                propertyId = field.value;
            } else if (field.name == "PropertyValue") {
                value = field.value;
            }
        });
        window.CRM.APIRequest({
            method: 'POST',
            path: 'people/properties/person/'+ window.CRM.currentPersonID + '/' + propertyId,
            data: JSON.stringify({"value":  value})
        }).done(function(data) {
            location.reload();
        });
    });

    $('.remove-property-btn').click(function (event) {
        let propertyId = $(this).data('property_id');
        bootbox.confirm(i18next.t('Are you sure you want to unassign this property?'), function (result) {
            if (result) {
                window.CRM.APIRequest({
                    method: 'DELETE',
                    path: 'people/properties/person/'+ window.CRM.currentPersonID + '/' + propertyId,
                }).done(function(data) {
                    location.reload();
                });
            }
        });

    });

    $('#edit-role-btn').click(function (event) {
        event.preventDefault();
        var thisLink = $(this);
        var personId = thisLink.data('person_id');
        var familyRoleId = thisLink.data('family_role_id');
        var familyRole = thisLink.data('family_role');

        $.ajax({
            type: 'GET',
            dataType: 'json',
            url: window.CRM.root + '/api/persons/roles',
            success: function (data, status, xmlHttpReq) {
                if (data.length) {
                    roles = [{text: familyRole, value: ''}];
                    for (var i=0; i < data.length; i++) {
                        if (data[i].OptionId == familyRoleId) {
                            continue;
                        }

                        roles[roles.length] = {
                            text: data[i].OptionName,
                            value: data[i].OptionId
                        };
                    }

                    bootbox.prompt({
                        title:i18next.t( 'Change role'),
                        inputType: 'select',
                        inputOptions: roles,
                        callback: function (result) {
                            if (result) {
                                $.ajax({
                                    type: 'POST',
                                    dataType: 'json',
                                    url: window.CRM.root + '/api/person/'+ personId +'/role/' +result,
                                    success: function (data, status, xmlHttpReq) {
                                        if (data.success) {
                                            location.reload();
                                        }
                                    }
                                });
                            }

                        }
                    });

                }
            }
        });

    });

   $.ajax({
       type: 'GET',
       dataType: 'json',
       url: window.CRM.root + '/api/mailchimp/person/' + window.CRM.currentPersonID,
       success: function (data, status, xmlHttpReq) {
           for (emailData of data) {
               let htmlVal = "";
               let eamilMD5 = emailData["emailMD5"];
               for (list of emailData["list"]) {
                   let listName = list["name"];
                   let listStatus = list["status"];
                   if (listStatus != 404) {
                       let listOpenRate = list["stats"]["avg_open_rate"]*100;
                       htmlVal = htmlVal + '
' + listName + " (" + listStatus + ") - " + listOpenRate + "% "+  i18next.t("open rate") + "
";
                   }
               }
               if (htmlVal === "") {
                   htmlVal = i18next.t("Not Subscribed ");
               }
               $('#'+ eamilMD5).html(htmlVal);
           }
       }
   });

});
<|endoftext|>


<commit_before>const BinaryPjax       = require('../../../../base/binary_pjax');
const Client           = require('../../../../base/client');
const Header           = require('../../../../base/header');
const BinarySocket     = require('../../../../base/socket');
const Validation       = require('../../../../common/form_validation');
const getElementById   = require('../../../../../_common/common_functions').getElementById;
const localize         = require('../../../../../_common/localize').localize;
const State            = require('../../../../../_common/storage').State;
const isEmptyObject    = require('../../../../../_common/utility').isEmptyObject;
const showLoadingImage = require('../../../../../_common/utility').showLoadingImage;

const FinancialAssessment = (() => {
    let financial_assessment = {};
    let arr_validation       = [];

    const form_selector = '#frm_assessment';

    const onLoad = () => {
        if (Client.isJPClient()) {
            BinaryPjax.loadPreviousUrl();
        }

        $(form_selector).on('submit', (event) => {
            event.preventDefault();
            submitForm();
        });

        getFinancialAssessment();
    };

    const getFinancialAssessment = () => {
        BinarySocket.send({ get_financial_assessment: 1 }).then((response) => {
            handleForm(response.get_financial_assessment);
        });
    };

    const displayHighRiskClassification = () => {
        $('#high_risk_classification').setVisibility(Client.getRiskAssessment());
    };

    const handleForm = (response = State.getResponse('get_financial_assessment')) => {
        hideLoadingImg(true);

        financial_assessment = $.extend({}, response);

        if (isEmptyObject(financial_assessment)) {
            BinarySocket.wait('get_account_status').then(() => { displayHighRiskClassification(); });
        }

        // display Trading Experience only for financial & MT5 financial accounts
        const is_mt5_financial = /real_vanuatu_(standard|advanced|mamm_advanced)/.test(localStorage.getItem('financial_assessment_redirect'));
        $('#trading_experience_form').setVisibility(is_mt5_financial || Client.isAccountOfType('financial'));

        Object.keys(financial_assessment).forEach((key) => {
            const val = financial_assessment[key];
            $(`#${key}`).val(val);
        });

        arr_validation = [];
        $(form_selector).find('select').map(function () {
            const id = $(this).attr('id');
            arr_validation.push({ selector: `#${id}`, validations: ['req'] });
            if (financial_assessment[id] === undefined) {  // handle fields not previously set by client
                financial_assessment[id] = '';
            }
        });
        Validation.init(form_selector, arr_validation);
    };

    const submitForm = () => {
        const $btn_submit = $(`${form_selector} #btn_submit`);
        $btn_submit.attr('disabled', 'disabled');

        if (Validation.validate(form_selector)) {
            let has_changed = false;
            Object.keys(financial_assessment).forEach((key) => {
                const $key = $(`#${key}`);
                if ($key.length && $key.val() !== financial_assessment[key]) {
                    has_changed = true;
                }
            });
            if (Object.keys(financial_assessment).length === 0) has_changed = true;
            if (!has_changed) {
                showFormMessage('You did not change anything.', false);
                setTimeout(() => { $btn_submit.removeAttr('disabled'); }, 1000);
                return;
            }

            const data = { set_financial_assessment: 1 };
            showLoadingImage(getElementById('msg_form'));
            $(form_selector).find('select').each(function () {
                financial_assessment[$(this).attr('id')] = data[$(this).attr('id')] = $(this).val() || null;
            });
            BinarySocket.send(data).then((response) => {
                $btn_submit.removeAttr('disabled');
                if (response.error) {
                    showFormMessage('Sorry, an error occurred while processing your request.', false);
                } else {
                    showFormMessage('Your changes have been updated successfully.', true);
                    // need to remove financial_assessment_not_complete from status if any
                    BinarySocket.send({ get_account_status: 1 }).then(() => {
                        Header.displayAccountStatus();
                        displayHighRiskClassification();
                    });
                    getFinancialAssessment();
                }
            });
        } else {
            setTimeout(() => { $btn_submit.removeAttr('disabled'); }, 1000);
        }
    };

    const hideLoadingImg = (show_form) => {
        $('#assessment_loading').remove();
        if (show_form) {
            $(form_selector).setVisibility(1);
        }
    };

    const showFormMessage = (msg, is_success) => {
        const redirect_url = localStorage.getItem('financial_assessment_redirect');
        if (is_success && /metatrader/i.test(redirect_url)) {
            localStorage.removeItem('financial_assessment_redirect');
            $.scrollTo($('h1#heading'), 500, { offset: -10 });
            $(form_selector).setVisibility(0);
            $('#msg_main').setVisibility(1);
            BinarySocket.send({ get_account_status: 1 }).then((response_status) => {
                if (+response_status.get_account_status.prompt_client_to_authenticate && Client.isAccountOfType('financial')) {
                    $('#msg_authenticate').setVisibility(1);
                }
            });
        } else {
            $('#msg_form')
                .attr('class', is_success ? 'success-msg' : 'errorfield')
                .html(is_success ? $('<ul/>', { class: 'checked', style: 'display: inline-block;' }).append($('<li/>', { text: localize(msg) })) : localize(msg))
                .css('display', 'block')
                .delay(5000)
                .fadeOut(1000);
        }
    };

    const onUnload = () => {
        localStorage.removeItem('financial_assessment_redirect');
    };

    return {
        onLoad,
        onUnload,
    };
})();

module.exports = FinancialAssessment;
<commit_msg>Hide form if main_msg is shown<commit_after>const BinaryPjax       = require('../../../../base/binary_pjax');
const Client           = require('../../../../base/client');
const Header           = require('../../../../base/header');
const BinarySocket     = require('../../../../base/socket');
const Validation       = require('../../../../common/form_validation');
const getElementById   = require('../../../../../_common/common_functions').getElementById;
const isVisible        = require('../../../../../_common/common_functions').isVisible;
const localize         = require('../../../../../_common/localize').localize;
const State            = require('../../../../../_common/storage').State;
const isEmptyObject    = require('../../../../../_common/utility').isEmptyObject;
const showLoadingImage = require('../../../../../_common/utility').showLoadingImage;

const FinancialAssessment = (() => {
    let financial_assessment = {};
    let arr_validation       = [];

    const form_selector = '#frm_assessment';

    const onLoad = () => {
        if (Client.isJPClient()) {
            BinaryPjax.loadPreviousUrl();
        }

        $(form_selector).on('submit', (event) => {
            event.preventDefault();
            submitForm();
        });

        getFinancialAssessment();
    };

    const getFinancialAssessment = () => {
        BinarySocket.send({ get_financial_assessment: 1 }).then((response) => {
            handleForm(response.get_financial_assessment);
        });
    };

    const displayHighRiskClassification = () => {
        $('#high_risk_classification').setVisibility(Client.getRiskAssessment());
    };

    const handleForm = (response = State.getResponse('get_financial_assessment')) => {
        hideLoadingImg(!isVisible(getElementById('msg_main')));

        financial_assessment = $.extend({}, response);

        if (isEmptyObject(financial_assessment)) {
            BinarySocket.wait('get_account_status').then(() => { displayHighRiskClassification(); });
        }

        // display Trading Experience only for financial & MT5 financial accounts
        const is_mt5_financial = /real_vanuatu_(standard|advanced|mamm_advanced)/.test(localStorage.getItem('financial_assessment_redirect'));
        $('#trading_experience_form').setVisibility(is_mt5_financial || Client.isAccountOfType('financial'));

        Object.keys(financial_assessment).forEach((key) => {
            const val = financial_assessment[key];
            $(`#${key}`).val(val);
        });

        arr_validation = [];
        $(form_selector).find('select').map(function () {
            const id = $(this).attr('id');
            arr_validation.push({ selector: `#${id}`, validations: ['req'] });
            if (financial_assessment[id] === undefined) {  // handle fields not previously set by client
                financial_assessment[id] = '';
            }
        });
        Validation.init(form_selector, arr_validation);
    };

    const submitForm = () => {
        const $btn_submit = $(`${form_selector} #btn_submit`);
        $btn_submit.attr('disabled', 'disabled');

        if (Validation.validate(form_selector)) {
            let has_changed = false;
            Object.keys(financial_assessment).forEach((key) => {
                const $key = $(`#${key}`);
                if ($key.length && $key.val() !== financial_assessment[key]) {
                    has_changed = true;
                }
            });
            if (Object.keys(financial_assessment).length === 0) has_changed = true;
            if (!has_changed) {
                showFormMessage('You did not change anything.', false);
                setTimeout(() => { $btn_submit.removeAttr('disabled'); }, 1000);
                return;
            }

            const data = { set_financial_assessment: 1 };
            showLoadingImage(getElementById('msg_form'));
            $(form_selector).find('select').each(function () {
                financial_assessment[$(this).attr('id')] = data[$(this).attr('id')] = $(this).val() || null;
            });
            BinarySocket.send(data).then((response) => {
                $btn_submit.removeAttr('disabled');
                if (response.error) {
                    showFormMessage('Sorry, an error occurred while processing your request.', false);
                } else {
                    showFormMessage('Your changes have been updated successfully.', true);
                    // need to remove financial_assessment_not_complete from status if any
                    BinarySocket.send({ get_account_status: 1 }).then(() => {
                        Header.displayAccountStatus();
                        displayHighRiskClassification();
                    });
                    getFinancialAssessment();
                }
            });
        } else {
            setTimeout(() => { $btn_submit.removeAttr('disabled'); }, 1000);
        }
    };

    const hideLoadingImg = (show_form) => {
        $('#assessment_loading').remove();
        if (show_form) {
            $(form_selector).setVisibility(1);
        }
    };

    const showFormMessage = (msg, is_success) => {
        const redirect_url = localStorage.getItem('financial_assessment_redirect');
        if (is_success && /metatrader/i.test(redirect_url)) {
            localStorage.removeItem('financial_assessment_redirect');
            $.scrollTo($('h1#heading'), 500, { offset: -10 });
            $(form_selector).setVisibility(0);
            $('#msg_main').setVisibility(1);
            BinarySocket.send({ get_account_status: 1 }).then((response_status) => {
                if (+response_status.get_account_status.prompt_client_to_authenticate && Client.isAccountOfType('financial')) {
                    $('#msg_authenticate').setVisibility(1);
                }
            });
        } else {
            $('#msg_form')
                .attr('class', is_success ? 'success-msg' : 'errorfield')
                .html(is_success ? $('<ul/>', { class: 'checked', style: 'display: inline-block;' }).append($('<li/>', { text: localize(msg) })) : localize(msg))
                .css('display', 'block')
                .delay(5000)
                .fadeOut(1000);
        }
    };

    const onUnload = () => {
        localStorage.removeItem('financial_assessment_redirect');
    };

    return {
        onLoad,
        onUnload,
    };
})();

module.exports = FinancialAssessment;
<|endoftext|>


<commit_before>
// if we are in a node env
if(typeof(exports) === 'object'){
  publicObject = exports;

// if we are in the browser
}else{
  publicObject = {};
  var papersLib = publicObject;
}

if( 'undefined' !== typeof($)) publicObject.$ = $;

/**
 * Append data to DOM by calling formatter on the source data
 * then appending it to the DOM
 *
 * @param {DOMElement} recipientDomElement
 * @param {DOMElement} templateDomElement
 * @param {object} sourceData
 * @param {function} formatter
 */
publicObject.appendElem = function(sourceData,templateDomElement,recipientDomElement,formatter){

  publicObject.$(recipientDomElement).append(
    formatter(
      sourceData,
      publicObject.$(templateDomElement).clone()
    )
  );
}

<commit_msg>more pull review fixes<commit_after>
// if we are in a node env
if(typeof(exports) === 'object'){
  publicObject = exports;

// if we are in the browser
}else{
  publicObject = {};
  var papersLib = publicObject;
}

if( 'undefined' !== typeof($)) publicObject.$ = $;

/**
 * Append data to DOM by calling formatter on the source data
 * then appending it to the DOM
 *
 * @param {DOMElement} recipientDomElement
 * @param {DOMElement} templateDomElement
 * @param {object} sourceData
 * @param {function} formatter
 */
publicObject.appendElem = function(sourceData,templateDomElement,recipientDomElement,formatter){

  publicObject.$(recipientDomElement).append(
    formatter(
      sourceData,
      publicObject.$(templateDomElement).clone()
    )
  );
};

<|endoftext|>


<commit_before>angular.module('Aggie')

  .controller('ReportsShowController', [
    '$rootScope',
    '$state',
    '$scope',
    '$stateParams',
    '$window',
    'mediaOptions',
    'FlashService',
    'data',
    'incidents',
    'Report',
    'Incident',
    'incidents',
    'Tags',
    'smtcTags',
    'comments',
    'Socket',
    'Queue',
    'sources',
    'paginationOptions',
    '$translate',
    function($rootScope, $state, $scope, $stateParams, $window, mediaOptions, flash, data, incidents, Report, Incident,
             incidents, Tags, smtcTags, comments, Socket, Queue, sources, paginationOptions,  $translate) {
      $scope.incidents = incidents.results;
      $scope.incidentsById = {};
      $scope.currentPath = $rootScope.$state.current.name;
      $scope.smtcTags = smtcTags;
      $scope.smtcTagsById = {};
      $scope.comments = comments.results;
      $scope.visibleComments = new Queue(paginationOptions.perPage);
      $scope.sources = sources;
      $scope.sourcesById = {};
      console.log(comments);
      console.log(sources);
      $scope.pagination = {
        page: parseInt($stateParams.page) || 1,
        total: comments.total,
        visibleTotal: comments.total,
        perPage: paginationOptions.perPage,
        start: 0,
        end: 0
      };

      var init = function() {
        $scope.commentsById = $scope.comments.reduce(groupById, {});
        $scope.sourcesById = $scope.sources.reduce(groupById, {});
        $scope.incidentsById = $scope.incidents.reduce(groupById, {});
        $scope.smtcTagsById = $scope.smtcTags.reduce(groupById, {});

        Socket.on('stats', updateStats);
        Socket.join('stats');
        if ($scope.currentPath === 'report') {
          Socket.join('reports');
          Socket.on('report:updated', $scope.updateReport.bind($scope));
        }
        var visibleComments = paginate($scope.comments);
        $scope.visibleComments.addMany(visibleComments);

      };
      var updateStats = function(stats) {
        $scope.stats = stats;
      };

      /**
       * Saves a front-end report to the back end.
       * @param {Report} report
       */
      $scope.saveReport = function(report) {
        Report.save({ id: report._id }, report, function() {
        }, function() {
          flash.setAlertNow("Sorry, but that report couldn't be saved.");
        });
      };

      var paginate = function(items) {
        var page = $scope.pagination.page,
          perPage = $scope.pagination.perPage,
          total = $scope.pagination.total,
          start = (page - 1) * perPage,
          end = page * perPage - 1;

        $scope.pagination.start = Math.min(start + 1, total);
        $scope.pagination.end = Math.min(end + 1, total);

        return items;
      };

      var groupById = function(memo, item) {
        memo[item._id] = item;
        return memo;
      };

      var paginate = function(items) {
        var page = $scope.pagination.page,
          perPage = $scope.pagination.perPage,
          total = $scope.pagination.total,
          start = (page - 1) * perPage,
          end = page * perPage - 1;

        $scope.pagination.start = Math.min(start + 1, total);
        $scope.pagination.end = Math.min(end + 1, total);

        return items;
      };

      $scope.report = data.report;
      $scope.sources = data.sources;

      $scope.isFlagged = function(report) {
        return report.flagged;
      };
      $scope.unlinkIncident = function() {
        $scope.report._incident = '';
        Report.update({ id: $scope.report._id }, $scope.report);
      };

      $scope.markAsRead = function (report) {
        if (report.read) return;
        report.read = true;
        Report.save({id: report._id}, report);
      };

      $scope.tagsToString = Tags.tagsToString;
      $scope.markAsRead(data.report);

      $scope.updateReport = function(report) {
        angular.extend($scope.report, report);
        if (!$scope.incidentsById[report._incident]) {
          Incident.get({ id: report._incident }, function(inc) {
            incidents.results.push(inc);
            $scope.incidentsById[report._incident] = inc;
          });
        }
      };

      $scope.isFirstPage = function() {
        return $scope.pagination.page == 1;
      };

      $scope.isLastPage = function() {
        return $scope.pagination.end >= $scope.pagination.visibleTotal;
      };

      $scope.unlinkIncident = function(report) {
        report._incident = '';
        Report.update({ id: report._id }, report);
      };

      /**
       * Toggles a report's flagged property and sets its read property to true
       * @param {Report} report
       */
      $scope.toggleFlaggedComment = function(report) {
        report.flagged = !report.flagged;
        if (report.flagged) {
          report.read = report.flagged;
        }
        $scope.saveReport(report);
      };

      $scope.saveFlaggedReport = function(report) {
        Report.save({ id: report._id }, report, function() {
        }, function() {
          flash.setAlertNow("Sorry, but that report couldn't be flagged/unflagged.");
        });
      };

      $scope.toggleFlagged = function(flagged) {
        $scope.report.flagged = flagged;
        Report.toggleFlagged({ ids: $scope.report._id, flagged: flagged });
      };

      $scope.isRead = function(report) {
        return report.read;
      };

      $scope.$back = function() {
        $window.history.back();
      };
      $scope.$on('$destroy', function() {
        Socket.leave('stats');
        Socket.removeAllListeners('stats');
      });

      $scope.$on('$destroy', function() {
        Socket.leave('reports');
        Socket.removeAllListeners('reports');
        Socket.leave('stats');
        Socket.removeAllListeners('stats');
      });

      init();
    }
  ]);

// This module is for trusting crowdtangle media content so it can be displayed
// Unless crowdtangle's api returns a url for something that is untrustworthy, this shouldn't post a security risk
angular.module('Aggie')

  .filter('trusted', ['$sce', function ($sce) {
    return function(url) {
      return $sce.trustAsResourceUrl(url);
    };
  }]);
<commit_msg>Removed Logging from frontend<commit_after>angular.module('Aggie')

  .controller('ReportsShowController', [
    '$rootScope',
    '$state',
    '$scope',
    '$stateParams',
    '$window',
    'mediaOptions',
    'FlashService',
    'data',
    'incidents',
    'Report',
    'Incident',
    'incidents',
    'Tags',
    'smtcTags',
    'comments',
    'Socket',
    'Queue',
    'sources',
    'paginationOptions',
    '$translate',
    function($rootScope, $state, $scope, $stateParams, $window, mediaOptions, flash, data, incidents, Report, Incident,
             incidents, Tags, smtcTags, comments, Socket, Queue, sources, paginationOptions,  $translate) {
      $scope.incidents = incidents.results;
      $scope.incidentsById = {};
      $scope.currentPath = $rootScope.$state.current.name;
      $scope.smtcTags = smtcTags;
      $scope.smtcTagsById = {};
      $scope.comments = comments.results;
      $scope.visibleComments = new Queue(paginationOptions.perPage);
      $scope.sources = sources;
      $scope.sourcesById = {};
      $scope.pagination = {
        page: parseInt($stateParams.page) || 1,
        total: comments.total,
        visibleTotal: comments.total,
        perPage: paginationOptions.perPage,
        start: 0,
        end: 0
      };

      var init = function() {
        $scope.commentsById = $scope.comments.reduce(groupById, {});
        $scope.sourcesById = $scope.sources.reduce(groupById, {});
        $scope.incidentsById = $scope.incidents.reduce(groupById, {});
        $scope.smtcTagsById = $scope.smtcTags.reduce(groupById, {});

        Socket.on('stats', updateStats);
        Socket.join('stats');
        if ($scope.currentPath === 'report') {
          Socket.join('reports');
          Socket.on('report:updated', $scope.updateReport.bind($scope));
        }
        var visibleComments = paginate($scope.comments);
        $scope.visibleComments.addMany(visibleComments);

      };
      var updateStats = function(stats) {
        $scope.stats = stats;
      };

      /**
       * Saves a front-end report to the back end.
       * @param {Report} report
       */
      $scope.saveReport = function(report) {
        Report.save({ id: report._id }, report, function() {
        }, function() {
          flash.setAlertNow("Sorry, but that report couldn't be saved.");
        });
      };

      var paginate = function(items) {
        var page = $scope.pagination.page,
          perPage = $scope.pagination.perPage,
          total = $scope.pagination.total,
          start = (page - 1) * perPage,
          end = page * perPage - 1;

        $scope.pagination.start = Math.min(start + 1, total);
        $scope.pagination.end = Math.min(end + 1, total);

        return items;
      };

      var groupById = function(memo, item) {
        memo[item._id] = item;
        return memo;
      };

      var paginate = function(items) {
        var page = $scope.pagination.page,
          perPage = $scope.pagination.perPage,
          total = $scope.pagination.total,
          start = (page - 1) * perPage,
          end = page * perPage - 1;

        $scope.pagination.start = Math.min(start + 1, total);
        $scope.pagination.end = Math.min(end + 1, total);

        return items;
      };

      $scope.report = data.report;
      $scope.sources = data.sources;

      $scope.isFlagged = function(report) {
        return report.flagged;
      };
      $scope.unlinkIncident = function() {
        $scope.report._incident = '';
        Report.update({ id: $scope.report._id }, $scope.report);
      };

      $scope.markAsRead = function (report) {
        if (report.read) return;
        report.read = true;
        Report.save({id: report._id}, report);
      };

      $scope.tagsToString = Tags.tagsToString;
      $scope.markAsRead(data.report);

      $scope.updateReport = function(report) {
        angular.extend($scope.report, report);
        if (!$scope.incidentsById[report._incident]) {
          Incident.get({ id: report._incident }, function(inc) {
            incidents.results.push(inc);
            $scope.incidentsById[report._incident] = inc;
          });
        }
      };

      $scope.isFirstPage = function() {
        return $scope.pagination.page == 1;
      };

      $scope.isLastPage = function() {
        return $scope.pagination.end >= $scope.pagination.visibleTotal;
      };

      $scope.unlinkIncident = function(report) {
        report._incident = '';
        Report.update({ id: report._id }, report);
      };

      /**
       * Toggles a report's flagged property and sets its read property to true
       * @param {Report} report
       */
      $scope.toggleFlaggedComment = function(report) {
        report.flagged = !report.flagged;
        if (report.flagged) {
          report.read = report.flagged;
        }
        $scope.saveReport(report);
      };

      $scope.saveFlaggedReport = function(report) {
        Report.save({ id: report._id }, report, function() {
        }, function() {
          flash.setAlertNow("Sorry, but that report couldn't be flagged/unflagged.");
        });
      };

      $scope.toggleFlagged = function(flagged) {
        $scope.report.flagged = flagged;
        Report.toggleFlagged({ ids: $scope.report._id, flagged: flagged });
      };

      $scope.isRead = function(report) {
        return report.read;
      };

      $scope.$back = function() {
        $window.history.back();
      };
      $scope.$on('$destroy', function() {
        Socket.leave('stats');
        Socket.removeAllListeners('stats');
      });

      $scope.$on('$destroy', function() {
        Socket.leave('reports');
        Socket.removeAllListeners('reports');
        Socket.leave('stats');
        Socket.removeAllListeners('stats');
      });

      init();
    }
  ]);

// This module is for trusting crowdtangle media content so it can be displayed
// Unless crowdtangle's api returns a url for something that is untrustworthy, this shouldn't post a security risk
angular.module('Aggie')

  .filter('trusted', ['$sce', function ($sce) {
    return function(url) {
      return $sce.trustAsResourceUrl(url);
    };
  }]);
<|endoftext|>


<commit_before>var registries = {};
var jsonObj;

registries.convertJsonToTable = function(path) {
	var table = document.createElement("table");
	var row = createTableHeader();
	row.style.size = 20;
	table.appendChild(row);

	function createTableHeader(){
		var row = document.createElement("tr");
		var cell = document.createElement("th");
		var cellText=document.createTextNode("Name");
		cell.appendChild(cellText);
		var cell2 = document.createElement("th");
		var cellText2 = document.createTextNode("Identifier");
		cell2.appendChild(cellText2);
		var cell3 = document.createElement("th");
		var cellText3 = document.createTextNode("Description");
		cell3.appendChild(cellText3);
		var cell4 = document.createElement("th");
		var cellText4 = document.createTextNode("Children");
		cell4.appendChild(cellText4);
		row.appendChild(cell);
		row.appendChild(cell3);
		row.appendChild(cell4);
		return row;
	}

	function createTableRow(name, id, description, children, web) {
		var row = document.createElement("tr");

		var cellA = document.createElement("a");
		var attr = document.createAttribute("name");
		attr.nodeValue = name;
		cellA.setAttributeNode(attr);

		var cellText = document.createTextNode(name);
		cellA.appendChild(cellText);

		var cellP = document.createElement("p");
		var cellTextP = document.createTextNode("> " + id);
		cellP.appendChild(cellTextP);

		var attrP = document.createAttribute("class");
		attrP.nodeValue = "p_id";
		cellP.setAttributeNode(attrP);

		var cell2 = document.createElement("td");
		var cell3 = document.createElement("td");
		var cell = document.createElement("td");
		var cell4 = document.createElement("td");

		var attrCell = document.createAttribute("class");
		attrCell.nodeValue = "table_row_id";
		cell.setAttributeNode(attrCell);

		var attrCell2 = document.createAttribute("class");
		attrCell2.nodeValue = "table_row_name";
		cell2.setAttributeNode(attrCell2);

		cell2.appendChild(cellA);
		cell2.appendChild(cellP);

		var cellText3 = document.createTextNode(description);
		var attrCell3 = document.createAttribute("class");
		attrCell3.nodeValue = "table_row_desc";
		cell3.setAttributeNode(attrCell3);
		cell3.appendChild(cellText3);

		if (web) {
			var cellBr = document.createElement("br");
			cell3.appendChild(cellBr);

			var cellA = document.createElement("a");
			var attr = document.createAttribute("href");
			attr.nodeValue = web;
			cellA.setAttributeNode(attr);
			var attr2 = document.createAttribute("target");
			attr2.nodeValue = "_blank";
			cellA.setAttributeNode(attr2);

			var cellLink = document.createTextNode(web);
			cellA.appendChild(cellLink);
			cell3.appendChild(cellA);
		}

		if (children) {
			$.each(children, function(k, v) {
				var cellA = document.createElement("a");
				var attr = document.createAttribute("href");
				attr.nodeValue = "#" + v.name;
				cellA.setAttributeNode(attr);

				var cellText = document.createTextNode(v.name);
				cellA.appendChild(cellText);
				cell4.appendChild(cellA);

				var cellBr = document.createElement("br");
				cell4.appendChild(cellBr);
			});
		}

		var attrCell4 = document.createAttribute("class");
		attrCell4.nodeValue = "table_row_children";
		cell4.setAttributeNode(attrCell4);

		row.appendChild(cell2);
		row.appendChild(cell3);
		row.appendChild(cell4);
		return row;
	}

	$.getJSON(path, function(data) {
	    jsonObj = data;
	    $.each(data, function(k, v) { recursiveFunction(k, v); });

	    function recursiveFunction(k, v) {
	    	table.appendChild(createTableRow(v.name, v.identifier, v.description, v.children, v.web));
	    	if (v.children) {
		    	if(v.children instanceof Object) {
		    		$.each(v.children, function(k, v) {
		    			recursiveFunction(k, v);
		    		});
		    	}
	    	}
	    }

	});
	return table;
};

/**
*\details	this method pops up a dijit dialog which display the search results in a table
*\author		Hannes Tressel changed by Susi
*\param		widget	content element
*/
registries.displayWidget = function(widget){
	require(["dijit/Dialog", "dojo/window", "dijit/registry", "dojo/on", "dojo/keys"], function(dialog, window, registry, on, keys){
		var browserSize = window.getBox();

		if (registry.byId("SearchResultOverview")){
			registry.byId("SearchResultOverview").destroyRecursive();
		}

		new dialog({
			id: "SearchResultOverview",
			title: "",
			autofocus: false,
			style: "width:"+(browserSize.w*80)/100+"px; height:"+(browserSize.h*60)/100+"px;",
			content: widget
		}).show();
	});
}
<commit_msg>Delete registries.js<commit_after><|endoftext|>


<commit_before>/**
 * WordPress dependencies
 */
import { withSelect } from '@wordpress/data';
import { Fragment } from '@wordpress/element';
import { __, sprintf } from '@wordpress/i18n';
import { compose, createHigherOrderComponent } from '@wordpress/compose';

/**
 * Internal dependencies
 */
import { ALLOWED_TOP_LEVEL_BLOCKS } from '../constants';
import { withBlockName } from './';

const applyWithSelect = withSelect( ( select, props ) => {
	const {
		getBlockOrder,
		getBlockRootClientId,
	} = select( 'core/editor' );
	const {
		isReordering,
		getBlockOrder: getModifiedBlockOrder,
	} = select( 'amp/story' );

	if ( '' !== getBlockRootClientId( props.clientId ) ) {
		return {
			pageNumber: undefined,
		};
	}

	const currentIndex = isReordering() ? getModifiedBlockOrder().indexOf( props.clientId ) : getBlockOrder().indexOf( props.clientId );

	return {
		pageNumber: currentIndex + 1,
	};
} );

const wrapperWithSelect = compose(
	applyWithSelect,
	withBlockName,
);

/**
 * Add page number label to page blocks
 *
 * @param {Object} BlockListBlock BlockListBlock element.
 * @return {Function} Handler.
 */
export default createHigherOrderComponent(
	( BlockEdit ) => {
		return wrapperWithSelect( ( props ) => {
			const { blockName, pageNumber } = props;

			// Not a valid top level block.
			if ( ! ALLOWED_TOP_LEVEL_BLOCKS.includes( blockName ) || ! pageNumber ) {
				return <BlockEdit { ...props } />;
			}

			return (
				<Fragment>

						{
							/* translators: %s: Page number */
							sprintf( __( 'Page %s', 'amp' ), pageNumber )
						}

					<BlockEdit { ...props } />
				</Fragment>
			);
		} );
	},
	'withPageNumber'
);
<commit_msg>Hide page number for reordering<commit_after>/**
 * WordPress dependencies
 */
import { withSelect } from '@wordpress/data';
import { Fragment } from '@wordpress/element';
import { __, sprintf } from '@wordpress/i18n';
import { compose, createHigherOrderComponent } from '@wordpress/compose';

/**
 * Internal dependencies
 */
import { ALLOWED_TOP_LEVEL_BLOCKS } from '../constants';
import { withBlockName } from './';

const applyWithSelect = withSelect( ( select, props ) => {
	const {
		getBlockOrder,
		getBlockRootClientId,
	} = select( 'core/editor' );
	const {	isReordering } = select( 'amp/story' );

	if ( '' !== getBlockRootClientId( props.clientId ) ) {
		return {
			pageNumber: undefined,
		};
	}

	const currentIndex = getBlockOrder().indexOf( props.clientId );

	return {
		pageNumber: currentIndex + 1,
		isReordering: isReordering(),
	};
} );

const wrapperWithSelect = compose(
	applyWithSelect,
	withBlockName,
);

/**
 * Add page number label to page blocks
 *
 * @param {Object} BlockListBlock BlockListBlock element.
 * @return {Function} Handler.
 */
export default createHigherOrderComponent(
	( BlockEdit ) => {
		return wrapperWithSelect( ( props ) => {
			const { blockName, pageNumber, isReordering } = props;

			// Not a valid top level block.
			if ( ! ALLOWED_TOP_LEVEL_BLOCKS.includes( blockName ) || ! pageNumber ) {
				return <BlockEdit { ...props } />;
			}

			// No page numbers needed during reordering.
			if ( isReordering ) {
				return <BlockEdit { ...props } />;
			}

			return (
				<Fragment>

						{
							/* translators: %s: Page number */
							sprintf( __( 'Page %s', 'amp' ), pageNumber )
						}

					<BlockEdit { ...props } />
				</Fragment>
			);
		} );
	},
	'withPageNumber'
);
<|endoftext|>


<commit_before>function batteryNumber(spec,my){
    var that = new Sprite(64,64);
    that.image = spec.pict;

    that.playOpenBatteryAnime = function(){
        that.scaleX = 4;
        that.scaleY = 4;
        that.opacity = 0.4;
        that.tl.scaleTo(1,1,5).and().fadeIn(5);
    }

    return that;
}<commit_msg>バッテリー表示エフェクトを調整した<commit_after>function batteryNumber(spec,my){
    var that = new Sprite(64,64);
    that.image = spec.pict;

    that.playOpenBatteryAnime = function(){
        that.scaleX = 1;
        that.scaleY = 1;
        that.opacity = 0;
        that.tl.fadeIn(15).and().scaleTo(2,2,15).delay(15).scaleTo(1,1,15);
    }

    return that;
}<|endoftext|>


<commit_before>'use strict';

var pakoDeflate = require('../node_modules/pako/lib/deflate.js');
var encode64 = require('./encode64');

// 1. Encode in UTF-8
// 2. Compress using Deflate algorithm
// 3. Reencode using a transformation close to base64
module.exports.encodeSync = function(text) {
  var utf8 = text.toString('utf8');
  var deflated = pakoDeflate.deflate(utf8, {level: 9, to: 'string'});
  return encode64.encode(deflated);
};
<commit_msg>Fix utf8 enconding<commit_after>'use strict';

var pakoDeflate = require('../node_modules/pako/lib/deflate.js');
var encode64 = require('./encode64');

// 1. Encode in UTF-8
// 2. Compress using Deflate algorithm
// 3. Reencode using a transformation close to base64
module.exports.encodeSync = function(text) {
  var utf8 = unescape(encodeURIComponent(text));
  var deflated = pakoDeflate.deflate(utf8, {level: 9, to: 'string'});
  return encode64.encode(deflated);
};
<|endoftext|>


<commit_before>/* Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * Author: Perry Wong (2008) based on work by Kyle Scholz      http://kylescholz.com/
 * Copyright: 2008, 					2006-2007
 */
/**
 * Seed DataGraph with contents of an JSON tree structure.
 *
 * @author Kyle Scholz
 *
 * @version 0.3
 */
var JSONTreeLoader = function( layout ) {
	this.subscribers = new Array();
	this.layout = layout;
	this.dataGraph = layout.dataGraph;
	this.lastCrumb = null; // last node is the most recent node
}

/*
 * @param {Object} subscriber
 */
JSONTreeLoader.prototype.subscribe = function( subscriber ) {
	this.subscribers.push(subscriber);
}

/*
 *
 */
JSONTreeLoader.prototype.notify = function() {
	for( var i=0; i<this.subscribers.length; i++ ) {
		this.subscribers[i].notify();
	}
}

/*
 * Fetch JSON data for processing
 */
JSONTreeLoader.prototype.load = function( ) {
	var localScope = this;
	new Ajax.Request( '/breadcrumbs/get_currcrumb_idx', {
		method: 'get',
		onSuccess: function(transport) {
			window.CURR_CRUMB = parseInt(transport.responseText);
		},
		onFailure: function(request) {
			alert('railed to get current breadcrumb index with response ' + request);
		}
	} );
	new Ajax.Request('/breadcrumbs/get_breadcrumb',
		{
			asynchronous:false,
			method:'get',
			onFailure:function(request){ alert('failed to get breadcrumb for JSViz'); },
			onSuccess: function(request){
				localScope.handle(request);
			}
		});
}

/*
 * Process JSON data in DataGraph.
 *
 * @param {JSONHTTPRequest} request
 */
JSONTreeLoader.prototype.handle = function( request ) {
	this.JSONDoc = request.responseJSON;
	if( this.JSONDoc.length <= 0 ) {
		this.layout.view.clear();
		this.dataGraph.clear();
		this.layout.clear();
		this.notify();
		return;
	}
	else if( this.JSONDoc.length < this.dataGraph.nodes.length )
	{
		this.layout.view.clear();
		this.dataGraph.clear();
		this.layout.clear();
	}
	var root = this.JSONDoc[0];
	var params = root['params'];
	var rootNode = new DataGraphNode();

	rootNode["root"] = true;

	rootNode.text = params['controller'] + ": " + params['action'];
	rootNode.URL = this.reconstructURL(params);
	this.generateColorStrip();
	rootNode.colorStripIndex = 0;
	rootNode.isAjax = root['is_ajax'];
	rootNode["fixed"] = true;

	var idx = this.dataGraph.findNode(rootNode);
	rootNode = (idx) ? this.dataGraph.getNode(idx) : rootNode;

	if( window.CURR_CRUMB == 0 ){
		rootNode["color"] = this.colorStrip[rootNode.colorStripIndex=0];
		rootNode.current = true;
	}
	else {
		rootNode["color"] = (rootNode.colorStripIndex<5) ?
        this.colorStrip[rootNode.colorStripIndex+=1] : this.colorStrip[5];
		rootNode.current = false;
	}

	if (idx) {
		//window.debugelem = this.layout.view.nodes[rootNode.id].domElement.childNodes[0];
		this.layout.view.nodes[rootNode.id].domElement.childNodes[0].setAttribute("fill", rootNode["color"]);
	}
	else {
		this.dataGraph.addNode(rootNode);
	}

	// Add children
	var localScope = this;
	root["children"].each( function(child) {
			this.lastNodeAdded = localScope.branch(child, rootNode); // , "#90EE90" // green
		});

	this.notify();
}

/*
 * @param {Object} root
 * @param {Object} rootNode
 */
JSONTreeLoader.prototype.branch = function( root, rootNode ) {
	var child = this.JSONDoc[root];
	var params = child['params'];
	var childNode = new DataGraphNode();
	var localScope = this;

	childNode.text = params['controller'] + ": " + params['action'];
	childNode.URL = this.reconstructURL(params);
	childNode.colorStripIndex=0;
	childNode.isAjax = child['is_ajax'];

	var idx = this.dataGraph.findNode(childNode);
	childNode = (idx) ? this.dataGraph.getNode(idx) : childNode;

	if(!childNode.parent) { childNode.parent = new Array(); }
    childNode.parent.push(rootNode);

	if( window.CURR_CRUMB == root ){
		childNode["color"] = this.colorStrip[childNode.colorStripIndex=0];
		childNode.current = true;
	}
	else {
		childNode["color"] = (childNode.colorStripIndex<5) ?
        this.colorStrip[childNode.colorStripIndex+=1] : this.colorStrip[5];
		childNode.current = false;
	}
	if (idx) {
		this.layout.view.nodes[childNode.id].domElement.childNodes[0].setAttribute("fill", childNode["color"]);
		var paren = childNode.parent.last();
		var edge = this.layout.view.edges[childNode.id][paren.id] || this.layout.view.edges[paren.id][childNode.id];
		edge.domEdge.setAttribute("stroke", childNode["color"]);
	}
	else {
		this.dataGraph.addNode(childNode);
	}

	child["children"].each( function(child) {
			this.lastNodeAdded = localScope.branch(child, childNode);

		});
	return childNode;
}

JSONTreeLoader.prototype.reconstructURL = function( params ) {
	var loc = document.location;
	var action = params['action'];
	var url = loc.protocol + '//'+ loc.host + "/" + params['controller'] + '/';
	if( action != 'index' && action != 'show' ) {
		url += action + "/";
	}
	if( params['id'] )
	{
		url += parseInt(params['id']);
	}

	return url;
}

// from http://krazydad.com/makecolors.php
JSONTreeLoader.prototype.generateColorStrip = function() {
	var frequency = Math.PI/10;
	var numStops = 6; // hence phase of pi/10
	var colorString = "#";
	var rStart = 0xAD;  var rStop = 0xcc;
	var gStart = 0xD8;  var gStop = 0xcc;
	var bStart = 0xE6;  var bStop = 0xcc;

	this.colorStrip = new Array(6);
	for( i=0; i<numStops; i++ ) {
		rComponent = Math.round(Math.sin(frequency*i)*(rStop-rStart) + rStart);
		gComponent = Math.round(Math.sin(frequency*i)*(gStop-gStart) + gStart);
		bComponent = Math.round(Math.sin(frequency*i)*(bStop-bStart) + bStart);
		this.colorStrip[i+1] = colorString+rComponent.toString(16)+gComponent.toString(16)+bComponent.toString(16);
	}
	this.colorStrip[0] = "#FF82A0";
}
<commit_msg>checkin before bedtime. TODO: check that parents and children are properly set<commit_after>/* Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * Author: Perry Wong (2008) based on work by Kyle Scholz      http://kylescholz.com/
 * Copyright: 2008, 					2006-2007
 */
/**
 * Seed DataGraph with contents of an JSON tree structure.
 *
 * @author Kyle Scholz
 *
 * @version 0.3
 */
var JSONTreeLoader = function( layout ) {
	this.subscribers = new Array();
	this.layout = layout;
	this.dataGraph = layout.dataGraph;
	this.lastCrumb = null; // last node is the most recent node
}

/*
 * @param {Object} subscriber
 */
JSONTreeLoader.prototype.subscribe = function( subscriber ) {
	this.subscribers.push(subscriber);
}

/*
 *
 */
JSONTreeLoader.prototype.notify = function() {
	for( var i=0; i<this.subscribers.length; i++ ) {
		this.subscribers[i].notify();
	}
}

/*
 * Fetch JSON data for processing
 */
JSONTreeLoader.prototype.load = function( ) {
	var localScope = this;
	new Ajax.Request( '/breadcrumbs/get_currcrumb_idx', {
		method: 'get',
		onSuccess: function(transport) {
			window.CURR_CRUMB = parseInt(transport.responseText);
		},
		onFailure: function(request) {
			alert('railed to get current breadcrumb index with response ' + request);
		}
	} );
	new Ajax.Request('/breadcrumbs/get_breadcrumb',
		{
			asynchronous:false,
			method:'get',
			onFailure:function(request){ alert('failed to get breadcrumb for JSViz'); },
			onSuccess: function(request){
				localScope.handle(request);
			}
		});
}

/*
 * Process JSON data in DataGraph.
 *
 * @param {JSONHTTPRequest} request
 */
JSONTreeLoader.prototype.handle = function( request ) {
	this.JSONDoc = request.responseJSON;
	if( this.JSONDoc.length <= 0 ) {
		this.layout.view.clear();
		this.dataGraph.clear();
		this.layout.clear();
		this.notify();
		return;
	}
	else if( this.JSONDoc.length < this.dataGraph.nodes.length )
	{
		this.layout.view.clear();
		this.dataGraph.clear();
		this.layout.clear();
	}
	var root = this.JSONDoc[0];
	var params = root['params'];
	var rootNode = new DataGraphNode();

	rootNode["root"] = true;

	rootNode.text = params['controller'] + ": " + params['action'];
	rootNode.URL = this.reconstructURL(params);
	this.generateColorStrip();
	rootNode.colorStripIndex = 0;
	rootNode.isAjax = root['is_ajax'];
	rootNode["fixed"] = true;

	var idx = this.dataGraph.findNode(rootNode);
	rootNode = (idx) ? this.dataGraph.getNode(idx) : rootNode;

	if( window.CURR_CRUMB == 0 ){
		rootNode["color"] = this.colorStrip[rootNode.colorStripIndex=0];
		rootNode.current = true;
	}
	else {
		rootNode["color"] = (rootNode.colorStripIndex<5) ?
        this.colorStrip[rootNode.colorStripIndex+=1] : this.colorStrip[5];
		rootNode.current = false;
	}

	if (idx) {
		//window.debugelem = this.layout.view.nodes[rootNode.id].domElement.childNodes[0];
		this.layout.view.nodes[rootNode.id].domElement.childNodes[0].setAttribute("fill", rootNode["color"]);
	}
	else {
		this.dataGraph.addNode(rootNode);
	}

	// Add children
	var localScope = this;
	root["children"].each( function(child) {
			this.lastNodeAdded = localScope.branch(child, rootNode); // , "#90EE90" // green
		});

	this.notify();
}

/*
 * @param {Object} root
 * @param {Object} rootNode
 */
JSONTreeLoader.prototype.branch = function( root, rootNode ) {
	var child = this.JSONDoc[root];
	var params = child['params'];
	var childNode = new DataGraphNode();
	var localScope = this;

	childNode.text = params['controller'] + ": " + params['action'];
	childNode.URL = this.reconstructURL(params);
	childNode.colorStripIndex=0;
	childNode.isAjax = child['is_ajax'];

	var idx = this.dataGraph.findNode(childNode);
	childNode = (idx) ? this.dataGraph.getNode(idx) : childNode;

	if(!childNode.parent) { childNode.parent = new Array(); }
    childNode.parent.push(rootNode);
    childNode.parent = childNode.parent.uniq();

	if( window.CURR_CRUMB == root ){
		childNode["color"] = this.colorStrip[childNode.colorStripIndex=0];
		childNode.current = true;
	}
	else {
		childNode["color"] = (childNode.colorStripIndex<5) ?
        this.colorStrip[childNode.colorStripIndex+=1] : this.colorStrip[5];
		childNode.current = false;
	}
	if (idx) {
		this.layout.view.nodes[childNode.id].domElement.childNodes[0].setAttribute("fill", childNode["color"]);
		var paren = childNode.parent.last();
		var edge = this.layout.view.edges[childNode.id][paren.id] || this.layout.view.edges[paren.id][childNode.id];
		edge.domEdge.setAttribute("stroke", childNode["color"]);
	}
	else {
		this.dataGraph.addNode(childNode);
	}

	child["children"].each( function(child) {
			this.lastNodeAdded = localScope.branch(child, childNode);

		});
	return childNode;
}

JSONTreeLoader.prototype.reconstructURL = function( params ) {
	var loc = document.location;
	var action = params['action'];
	var url = loc.protocol + '//'+ loc.host + "/" + params['controller'] + '/';
	if( action != 'index' && action != 'show' ) {
		url += action + "/";
	}
	if( params['id'] )
	{
		url += parseInt(params['id']);
	}

	return url;
}

// from http://krazydad.com/makecolors.php
JSONTreeLoader.prototype.generateColorStrip = function() {
	var frequency = Math.PI/10;
	var numStops = 6; // hence phase of pi/10
	var colorString = "#";
	var rStart = 0xAD;  var rStop = 0xcc;
	var gStart = 0xD8;  var gStop = 0xcc;
	var bStart = 0xE6;  var bStop = 0xcc;

	this.colorStrip = new Array(6);
	for( i=0; i<numStops; i++ ) {
		rComponent = Math.round(Math.sin(frequency*i)*(rStop-rStart) + rStart);
		gComponent = Math.round(Math.sin(frequency*i)*(gStop-gStart) + gStart);
		bComponent = Math.round(Math.sin(frequency*i)*(bStop-bStart) + bStart);
		this.colorStrip[i+1] = colorString+rComponent.toString(16)+gComponent.toString(16)+bComponent.toString(16);
	}
	this.colorStrip[0] = "#FF82A0";
}
<|endoftext|>


<commit_before>var shell = {};
var exec = require('child_process').exec;

shell.output = function(args, word) {
  if (word != "") {
    var command = args.command.replace("%s", word);

    child = exec(command, function(error, stdout, stderr) {
      console.log(stdout);
    });
  }
}

module.exports = shell;
<commit_msg>シェル呼び出し後の処理をコールバック化<commit_after>var shell = {};
var exec = require('child_process').exec;

shell.output = function(args, word, next) {
  if (word != "") {
    var command = args.command.replace("%s", word);

    child = exec(command, function(error, stdout, stderr) {
      if (error) {
        next(true, stderr);
      } else {
        next(false, stdout);
      }
    });
  }
}

module.exports = shell;
<|endoftext|>


<commit_before>var PluginAbstract = require('./abstract.js');
var Stream = require('../stream');
var JanusError = require('../janus-error');
var util = require('util');

var serviceLocator = require('../service-locator');

function PluginStreaming(id, type, proxyConnection) {
  PluginStreaming.super_.apply(this, arguments);
  this.stream = null;
}

util.inherits(PluginStreaming, PluginAbstract);

/**
 * @param {Object} message
 * @returns {Promise}
 */
PluginStreaming.prototype.processMessage = function(message) {
  var janusMessage = message['janus'];

  if ('message' === janusMessage && 'create' === message['body']['request']) {
    return this.onCreate(message);
  }
  if ('message' === janusMessage && 'watch' === message['body']['request']) {
    return this.onWatch(message);
  }
  if ('webrtcup' === janusMessage) {
    return this.onWebrtcup(message);
  }
  if ('hangup' === janusMessage) {
    return this.onHangup(message);
  }
  if ('detach' === janusMessage) {
    return this.onHangup(message);
  }
  return Promise.resolve();
};

/**
 * @param {Object} message
 * @returns {Promise}
 */
PluginStreaming.prototype.onCreate = function(message) {
  var self = this;
  this.proxyConnection.transactions.add(message['transaction'], function(response) {
    self.stream = Stream.generate(message['body']['id'], self.proxyConnection, true);
  });
  return Promise.resolve(message);
};

/**
 * @param {Object} message
 * @returns {Promise}
 */
PluginStreaming.prototype.onRtcup = function(message) {
  var self = this;
  return serviceLocator.get('cmApiClient').publish(this.stream.channelName, this.stream.id, Date.now())
    .then(function() {
      serviceLocator.get('logger').info('adding stream', self.stream);
      serviceLocator.get('streams').add(self.stream);
    })
    .catch(function(error) {
      serviceLocator.get('logger').info('Cannot publish: ', error);
      self.stream.connection.close();
    });
};

/**
 * @param {Object} message
 * @returns {Promise}
 */
PluginStreaming.prototype.onWatch = function(message) {
  var self = this;
  this.proxyConnection.transactions.add(message['transaction'], function(response) {
    self.stream = Stream.generate(message['body']['id'], self.proxyConnection, false);
  });
  return Promise.resolve(message);
};

/**
 * @param {Object} message
 * @returns {Promise}
 */
PluginStreaming.prototype.onWebrtcup = function(message) {
  var self = this;
  return serviceLocator.get('cmApiClient').subscribe(this.stream.channelName, this.stream.id, Date.now())
    .then(function() {
      serviceLocator.get('logger').info('adding stream', self.stream);
      serviceLocator.get('streams').add(self.stream);
    })
    .catch(function(error) {
      serviceLocator.get('logger').info('Cannot subscribe: ', error);
      self.stream.connection.close();
    });
};

/**
 * @param {Object} message
 * @returns {Promise}
 */
PluginStreaming.prototype.onHangup = function(message) {
  this.proxyConnection.removePlugin(this.id);
  this.proxyConnection.close();
  return Promise.resolve(message);
};

module.exports = PluginStreaming;
<commit_msg>Use resposne of trasnsaction (instead of rtcup) to notify about publish started<commit_after>var PluginAbstract = require('./abstract.js');
var Stream = require('../stream');
var JanusError = require('../janus-error');
var util = require('util');

var serviceLocator = require('../service-locator');

function PluginStreaming(id, type, proxyConnection) {
  PluginStreaming.super_.apply(this, arguments);
  this.stream = null;
}

util.inherits(PluginStreaming, PluginAbstract);

/**
 * @param {Object} message
 * @returns {Promise}
 */
PluginStreaming.prototype.processMessage = function(message) {
  var janusMessage = message['janus'];

  if ('message' === janusMessage && 'create' === message['body']['request']) {
    return this.onCreate(message);
  }
  if ('message' === janusMessage && 'watch' === message['body']['request']) {
    return this.onWatch(message);
  }
  if ('webrtcup' === janusMessage) {
    return this.onWebrtcup(message);
  }
  if ('hangup' === janusMessage) {
    return this.onHangup(message);
  }
  if ('detach' === janusMessage) {
    return this.onHangup(message);
  }
  return Promise.resolve();
};

/**
 * @param {Object} message
 * @returns {Promise}
 */
PluginStreaming.prototype.onCreate = function(message) {
  var self = this;
  this.proxyConnection.transactions.add(message['transaction'], function(response) {
    self.stream = Stream.generate(message['body']['id'], self.proxyConnection, true);
    serviceLocator.get('cmApiClient').publish(self.stream.channelName, self.stream.id, Date.now())
      .then(function() {
        serviceLocator.get('logger').info('adding stream', self.stream);
        serviceLocator.get('streams').add(self.stream);
      })
      .catch(function(error) {
        self.stream.connection.close();
        throw new JanusError.Error('Cannot publish: ', error);
      });
  });
  return Promise.resolve(message);
};

/**
 * @param {Object} message
 * @returns {Promise}
 */
PluginStreaming.prototype.onWatch = function(message) {
  var self = this;
  this.proxyConnection.transactions.add(message['transaction'], function(response) {
    self.stream = Stream.generate(message['body']['id'], self.proxyConnection, false);
  });
  return Promise.resolve(message);
};

/**
 * @param {Object} message
 * @returns {Promise}
 */
PluginStreaming.prototype.onWebrtcup = function(message) {
  var self = this;
  return serviceLocator.get('cmApiClient').subscribe(this.stream.channelName, this.stream.id, Date.now())
    .then(function() {
      serviceLocator.get('logger').info('adding stream', self.stream);
      serviceLocator.get('streams').add(self.stream);
    })
    .catch(function(error) {
      serviceLocator.get('logger').info('Cannot subscribe: ', error);
      self.stream.connection.close();
    });
};

/**
 * @param {Object} message
 * @returns {Promise}
 */
PluginStreaming.prototype.onHangup = function(message) {
  this.proxyConnection.removePlugin(this.id);
  this.proxyConnection.close();
  return Promise.resolve(message);
};

module.exports = PluginStreaming;
<|endoftext|>