<commit_before>'use strict';

const SPACE_BETWEEN_MENU_ICONS = 20;
const ONE_SECOND = 1.0;
const ANIMATION_TIME = ONE_SECOND / 4;
const MENU_DISTANCE_FROM_PLAYER = 150;

function PlayerMenu(world) {
    this.__init__(world);
}

function MenuIcon(icon_type, world, row, player_menu) {
    this.__init__(icon_type, world, row, player_menu);
}

function global_save() {
    l('PERFORM A GLOBAL SAVE!');

    GUI_TYPING_INTERFACE.add_server_message('Saving changes to the server! TODO : Get a response back!');

    MANAGER_WORLD.world_home.prepare_for_save();

    // Any changes to entities will be saved.
    MANAGER_ENTITY.update_server_and_database();
}

function go_to_settings_world() {
    MANAGER_WORLD.set_current_world(MANAGER_WORLD.world_settings);
}

function go_to_home_world() {
    MANAGER_WORLD.set_current_world(MANAGER_WORLD.world_home);
}

function create_entity_wall() {
    l('Creating entity wall!');
    MANAGER_WORLD.world_home.create_entity_wall_command_entered();
}

function exit_function() {
    if (MANAGER_WORLD.current_world === MANAGER_WORLD.world_login) {
        // TODO : remove this or refactor
        window.close();
    } else {
        l('TODO : regular log out functionality');
    }
}

function toggle_fullscreen() {
    MANAGER_RENDERER.toggle_fullscreen();
}

MenuIcon.prototype = {

    _display_utility_wall: function(utility_wall_to_display) {
        if (utility_wall_to_display === this.teleport_wall) {
            this.teleport_wall.show();
            this._hide_utility_wall(this.create_wall);
        } else if (utility_wall_to_display === this.create_wall) {
            this.create_wall.show();
            this._hide_utility_wall(this.teleport_wall);
        }
    },

    _hide_utility_wall: function(utility_wall_to_hide) {
        if (is_defined(utility_wall_to_hide)) {
            utility_wall_to_hide.hide();
        }
    },

    /*__   __   ___      ___  ___
     /  ` |__) |__   /\   |  |__
     \__, |  \ |___ /~~\  |  |___ */
    display_create_options: function() {
        this._display_utility_wall(this.create_wall);
    },

    hide_create_options: function() {
        this._hide_utility_wall(this.create_wall);
    },

    /*___  ___       ___  __   __   __  ___
       |  |__  |    |__  |__) /  \ |__)  |
       |  |___ |___ |___ |    \__/ |  \  |  */
    display_teleport_worlds: function() {
        this._display_utility_wall(this.teleport_wall);
    },

    hide_teleport_worlds: function() {
        this._hide_utility_wall(this.teleport_wall);
    },

    __init__: function(icon_type, world, row, player_menu) {
        // Inherit from Attachmentable.
        Attachmentable.call(this);

        this._icon_type = icon_type;
        this._player_menu = player_menu;

        this.function_to_bind = null;
        this.function_look_at_bind = null;
        this.function_look_away_bind = null;

        this.world = world;
        this.row = row;

        var utiltiy_wall_width = 120;
        var icon_width = 16 / utiltiy_wall_width;

        switch (this._icon_type) {
            case ICON_WRENCH:
                this.icon_label = 'create';
                this.function_look_at_bind = this.display_create_options.bind(this);
                //this.function_look_away_bind = this.hide_create_options.bind(this);

                this.create_wall = new FloatingWall(utiltiy_wall_width, 200, new THREE.Vector3(0, 0, 0), new THREE.Vector3(0, 0, 0), this.world, false, 0);
                this.create_wall.add_floating_2d_text(0, 1, 'Create a...', TYPE_CONSTANT, 0);

                this.create_wall.add_floating_2d_text(0, icon_width, ICON_INFORMATION, TYPE_ICON, 2);
                var create_floating_2D_text_button = this.create_wall.add_floating_2d_text(icon_width, 1, 'Floating Text', TYPE_BUTTON, 2);
                // TODO : create_floating_2D_text_button.set_engage_function();

                this.create_wall.add_floating_2d_text(0, icon_width, ICON_MENU_LIST, TYPE_ICON, 3);
                var create_entity_wall_button = this.create_wall.add_floating_2d_text(icon_width, 1, 'Entity Group', TYPE_BUTTON, 3);
                // TODO : create_entity_wall_button.set_engage_function();

                this.create_wall.add_floating_2d_text(0, icon_width, ICON_IMPORT, TYPE_ICON, 4);
                var create_floating_picture_button = this.create_wall.add_floating_2d_text(icon_width, 1, 'Picture', TYPE_BUTTON, 4);
                // TODO : create_floating_picture_button.set_engage_function();

                this.create_wall.add_floating_2d_text(0, icon_width, ICON_MOVIE, TYPE_ICON, 5);
                var create_floating_video_button = this.create_wall.add_floating_2d_text(icon_width, 1, 'YouTube Video', TYPE_BUTTON, 5);
                // TODO : create_floating_video_button.set_engage_function();

                this.create_wall.hide();
                break;
            case ICON_SAVE:
                this.icon_label = 'save';
                this.function_to_bind = global_save;
                break;
            case ICON_TELEPORT:
                this.icon_label = 'teleport';
                this.function_look_at_bind = this.display_teleport_worlds.bind(this);
                //this.function_look_away_bind = this.hide_teleport_worlds.bind(this);

                this.teleport_wall = new FloatingWall(utiltiy_wall_width, 200, new THREE.Vector3(0, 0, 0), new THREE.Vector3(0, 0, 0), this.world, false, 0);
                // TODO : Need to dynamically load all shared worlds that the player has.
                this.teleport_wall.add_floating_2d_text(0, 1, 'Teleport To...', TYPE_CONSTANT, 0);

                // TODO : Also dynamically only load the worlds that are available.

                this.teleport_wall.add_floating_2d_text(0, icon_width, ICON_SETTINGS, TYPE_ICON, 2);
                var settings_button = this.teleport_wall.add_floating_2d_text(icon_width, 1, 'Settings', TYPE_BUTTON, 2);
                settings_button.set_engage_function(go_to_settings_world);

                this.teleport_wall.add_floating_2d_text(0, icon_width, ICON_HOME, TYPE_ICON, 3);
                var home_button = this.teleport_wall.add_floating_2d_text(icon_width, 1, 'Home', TYPE_BUTTON, 3);
                home_button.set_engage_function(go_to_home_world);

                this.teleport_wall.add_floating_2d_text(0, icon_width, ICON_EXIT, TYPE_ICON, 4);
                var exit_button = this.teleport_wall.add_floating_2d_text(icon_width, 1, 'Exit', TYPE_BUTTON, 4);
                exit_button.set_engage_function(exit_function);

                this.teleport_wall.hide();
                break;
            case ICON_MULTI_PLAYER:
                this.icon_label = 'online';
                break;
            case ICON_FULLSCREEN:
                this.icon_label = 'fullscreen';
                this.function_to_bind = toggle_fullscreen;
                break;
        }

        this.icon = get_new_floating_icon(icon_type, this.world);
        var label = this.icon.add_floating_2D_text();

        // Refactor this so that it's attached to the icon.
        this.floating_label = new Floating2DText(100, this.icon_label, TYPE_BUTTON, this.world);
        this.floating_label.set_engage_function(this.function_to_bind);
        this.floating_label.set_look_at_function(this.function_look_at_bind);
        this.floating_label.set_look_away_function(this.function_look_away_bind);

        //this.object3D.add(this.icon);

        this.world.add_to_scene(this.object3D);

        // Inherit from Interactive.
        //Interactive.call(this);
        // Inherit from Visibility.
        //Visibility.call(this);

        this.world.interactive_objects.push(this.floating_label);
    },

    _set_utility_wall_position_and_normal: function(utility_wall, horizontal_shift) {
        if (is_defined(utility_wall)) {
            var player_position = CURRENT_PLAYER.get_position();
            var utility_wall_position = new THREE.Vector3(this.object3D.position.x + this.left_right.x * horizontal_shift * 3 + this.normal.x * 30,
                                                           this.object3D.position.y,
                                                           this.object3D.position.z + this.left_right.z * horizontal_shift * 3 + this.normal.z * 30);
            var utility_wall_look_at = new THREE.Vector3(player_position.x - utility_wall_position.x, 0, player_position.z - utility_wall_position.z);
            utility_wall_look_at.normalize();
            utility_wall.set_position_and_normal(utility_wall_position, utility_wall_look_at, false);
        }
    },

    set_position_and_normal: function(position, nx, nz) {
        this.y_position = position.y + SPACE_BETWEEN_MENU_ICONS * 2;
        this.object3D.position.set(position.x, this.y_position, position.z);
        this.object3D.lookAt(new THREE.Vector3(position.x + nx * 5, this.y_position, position.z + nz * 5));

        // TODO : Delete this?
        this.normal = new THREE.Vector3(nx, 0, nz);

        this.left_right = get_left_right_unit_vector(nx, nz);

        var horizontal_shift = 60;

        this.floating_label.update_position_and_normal(new THREE.Vector3(this.object3D.position.x + this.left_right.x * horizontal_shift, this.object3D.position.y, this.object3D.position.z + this.left_right.z * horizontal_shift), this.normal);

        this._set_utility_wall_position_and_normal(this.teleport_wall, horizontal_shift);
        this._set_utility_wall_position_and_normal(this.create_wall, horizontal_shift);
    },

    update_y_position: function(y_offset) {
        this.object3D.position.y = this.y_position - y_offset;
        this.floating_label.object3D.position.y = this.y_position - y_offset;
    },

};

PlayerMenu.prototype = {

    __init__: function(world) {
        this.world = world;

        // TODO : Make a better design for the temp values.
        var temp_position = new Vector3(-10000, -10000, -10000);
        var temp_normal   = new Vector3(0, 0, 0);
        this._player_menu = new FloatingWall(100, 200, temp_position, temp_normal, this.world);
        this._player_menu.make_base_wall_invisible();

        this.total_delta = 0;
    },

    set_to_invisible: function() {
        this.visible = false;
        if (is_defined(this.icons)) {
            for (var i = 0; i < this.icons.length; i++) {
                this.icons[i].set_to_invisible();
            }
        }
    },

    set_to_visible: function() {
        this.visible = true;
        this.total_delta = 0;

        var pp = CURRENT_PLAYER.get_position();
        var pd = CURRENT_PLAYER.get_direction();

        var start_position = new THREE.Vector3(pp.x + pd.x * MENU_DISTANCE_FROM_PLAYER, pp.y + pd.y * MENU_DISTANCE_FROM_PLAYER, pp.z + pd.z * MENU_DISTANCE_FROM_PLAYER);

        for (var i = 0; i < this.icons.length; i++) {
            this.icons[i].set_position_and_normal(start_position, -pd.x, -pd.z);
            this.icons[i].set_to_visible();
        }
    },

    is_visible: function() {
        return this.visible;
    },

    update: function(delta) {
        this.total_delta += delta;
        if (this.total_delta >= ANIMATION_TIME) {
            this.percentage = 1.0;
        } else {
            this.percentage = this.total_delta / ANIMATION_TIME;
        }

        // TODO : Refactor this!!!!
        if (is_defined(this.icons)) {
            for (var i = 0; i < this.icons.length; i++) {
                if (this.icons[i].row !== 0) {
                    var this_icons_max_delta = this.time_needed_for_each_row * this.icons[i].row;
                    if (this.percentage < this_icons_max_delta) {
                        this.icons[i].update_y_position(this.percentage * this.total_distance);
                    } else {
                        this.icons[i].update_y_position(this_icons_max_delta * this.total_distance);
                    }
                }
            }
        }

    },

    _add_menu_icon: function(icon, list_of_icons_not_to_load) {
        if (!is_defined(this.icons)) {
            this.icons = [];
        }
        if (!list_of_icons_not_to_load.contains(icon)) {
            this.icons.push(new MenuIcon(icon, this.world, this.icons.length, this));
        }
    },

    // This function gets called once per player menu object.
    load_icon_textures: function(list_of_icons_not_to_load) {
        this._add_menu_icon(ICON_WRENCH      , list_of_icons_not_to_load);
        this._add_menu_icon(ICON_SAVE        , list_of_icons_not_to_load);
        this._add_menu_icon(ICON_TELEPORT    , list_of_icons_not_to_load);
        this._add_menu_icon(ICON_MULTI_PLAYER, list_of_icons_not_to_load);
        this._add_menu_icon(ICON_FULLSCREEN  , list_of_icons_not_to_load);

        this.time_needed_for_each_row = ONE_SECOND / (this.icons.length);
        this.total_distance = this.icons.length * SPACE_BETWEEN_MENU_ICONS;

        this.set_to_invisible();
    }

};
<commit_msg>broad refactoring 12<commit_after>'use strict';

const SPACE_BETWEEN_MENU_ICONS = 20;
const ONE_SECOND = 1.0;
const ANIMATION_TIME = ONE_SECOND / 4;
const MENU_DISTANCE_FROM_PLAYER = 150;

function PlayerMenu(world) {
    this.__init__(world);
}

function MenuIcon(icon_type, world, row, player_menu) {
    this.__init__(icon_type, world, row, player_menu);
}

function global_save() {
    l('PERFORM A GLOBAL SAVE!');

    GUI_TYPING_INTERFACE.add_server_message('Saving changes to the server! TODO : Get a response back!');

    MANAGER_WORLD.world_home.prepare_for_save();

    // Any changes to entities will be saved.
    MANAGER_ENTITY.update_server_and_database();
}

function go_to_settings_world() {
    MANAGER_WORLD.set_current_world(MANAGER_WORLD.world_settings);
}

function go_to_home_world() {
    MANAGER_WORLD.set_current_world(MANAGER_WORLD.world_home);
}

function create_entity_wall() {
    l('Creating entity wall!');
    MANAGER_WORLD.world_home.create_entity_wall_command_entered();
}

function exit_function() {
    if (MANAGER_WORLD.current_world === MANAGER_WORLD.world_login) {
        // TODO : remove this or refactor
        window.close();
    } else {
        l('TODO : regular log out functionality');
    }
}

function toggle_fullscreen() {
    MANAGER_RENDERER.toggle_fullscreen();
}

MenuIcon.prototype = {

    _display_utility_wall: function(utility_wall_to_display) {
        if (utility_wall_to_display === this.teleport_wall) {
            this.teleport_wall.show();
            this._hide_utility_wall(this.create_wall);
        } else if (utility_wall_to_display === this.create_wall) {
            this.create_wall.show();
            this._hide_utility_wall(this.teleport_wall);
        }
    },

    _hide_utility_wall: function(utility_wall_to_hide) {
        if (is_defined(utility_wall_to_hide)) {
            utility_wall_to_hide.hide();
        }
    },

    /*__   __   ___      ___  ___
     /  ` |__) |__   /\   |  |__
     \__, |  \ |___ /~~\  |  |___ */
    display_create_options: function() {
        this._display_utility_wall(this.create_wall);
    },

    hide_create_options: function() {
        this._hide_utility_wall(this.create_wall);
    },

    /*___  ___       ___  __   __   __  ___
       |  |__  |    |__  |__) /  \ |__)  |
       |  |___ |___ |___ |    \__/ |  \  |  */
    display_teleport_worlds: function() {
        this._display_utility_wall(this.teleport_wall);
    },

    hide_teleport_worlds: function() {
        this._hide_utility_wall(this.teleport_wall);
    },

    __init__: function(icon_type, world, row, player_menu) {
        // Inherit from Attachmentable.
        Attachmentable.call(this);

        this._icon_type = icon_type;
        this._player_menu = player_menu;

        this.function_to_bind = null;
        this.function_look_at_bind = null;
        this.function_look_away_bind = null;

        this.world = world;
        this.row = row;

        var utiltiy_wall_width = 120;
        var icon_width = 16 / utiltiy_wall_width;

        switch (this._icon_type) {
            case ICON_WRENCH:
                this.icon_label = 'create';
                this.function_look_at_bind = this.display_create_options.bind(this);
                //this.function_look_away_bind = this.hide_create_options.bind(this);

                this.create_wall = new FloatingWall(utiltiy_wall_width, 200, new THREE.Vector3(0, 0, 0), new THREE.Vector3(0, 0, 0), this.world, false, 0);
                this.create_wall.add_floating_2d_text(0, 1, 'Create a...', TYPE_CONSTANT, 0);

                this.create_wall.add_floating_2d_text(0, icon_width, ICON_INFORMATION, TYPE_ICON, 2);
                var create_floating_2D_text_button = this.create_wall.add_floating_2d_text(icon_width, 1, 'Floating Text', TYPE_BUTTON, 2);
                // TODO : create_floating_2D_text_button.set_engage_function();

                this.create_wall.add_floating_2d_text(0, icon_width, ICON_MENU_LIST, TYPE_ICON, 3);
                var create_entity_wall_button = this.create_wall.add_floating_2d_text(icon_width, 1, 'Entity Group', TYPE_BUTTON, 3);
                // TODO : create_entity_wall_button.set_engage_function();

                this.create_wall.add_floating_2d_text(0, icon_width, ICON_IMPORT, TYPE_ICON, 4);
                var create_floating_picture_button = this.create_wall.add_floating_2d_text(icon_width, 1, 'Picture', TYPE_BUTTON, 4);
                // TODO : create_floating_picture_button.set_engage_function();

                this.create_wall.add_floating_2d_text(0, icon_width, ICON_MOVIE, TYPE_ICON, 5);
                var create_floating_video_button = this.create_wall.add_floating_2d_text(icon_width, 1, 'YouTube Video', TYPE_BUTTON, 5);
                // TODO : create_floating_video_button.set_engage_function();

                this.create_wall.hide();
                break;
            case ICON_SAVE:
                this.icon_label = 'save';
                this.function_to_bind = global_save;
                break;
            case ICON_TELEPORT:
                this.icon_label = 'teleport';
                this.function_look_at_bind = this.display_teleport_worlds.bind(this);
                //this.function_look_away_bind = this.hide_teleport_worlds.bind(this);

                this.teleport_wall = new FloatingWall(utiltiy_wall_width, 200, new THREE.Vector3(0, 0, 0), new THREE.Vector3(0, 0, 0), this.world, false, 0);
                // TODO : Need to dynamically load all shared worlds that the player has.
                this.teleport_wall.add_floating_2d_text(0, 1, 'Teleport To...', TYPE_CONSTANT, 0);

                // TODO : Also dynamically only load the worlds that are available.

                this.teleport_wall.add_floating_2d_text(0, icon_width, ICON_SETTINGS, TYPE_ICON, 2);
                var settings_button = this.teleport_wall.add_floating_2d_text(icon_width, 1, 'Settings', TYPE_BUTTON, 2);
                settings_button.set_engage_function(go_to_settings_world);

                this.teleport_wall.add_floating_2d_text(0, icon_width, ICON_HOME, TYPE_ICON, 3);
                var home_button = this.teleport_wall.add_floating_2d_text(icon_width, 1, 'Home', TYPE_BUTTON, 3);
                home_button.set_engage_function(go_to_home_world);

                this.teleport_wall.add_floating_2d_text(0, icon_width, ICON_EXIT, TYPE_ICON, 4);
                var exit_button = this.teleport_wall.add_floating_2d_text(icon_width, 1, 'Exit', TYPE_BUTTON, 4);
                exit_button.set_engage_function(exit_function);

                this.teleport_wall.hide();
                break;
            case ICON_MULTI_PLAYER:
                this.icon_label = 'online';
                break;
            case ICON_FULLSCREEN:
                this.icon_label = 'fullscreen';
                this.function_to_bind = toggle_fullscreen;
                break;
        }

        this.icon = get_new_floating_icon(icon_type, this.world);
        var label = this.icon.add_floating_2D_text();

        // Refactor this so that it's attached to the icon.
        this.floating_label = new Floating2DText(100, this.icon_label, TYPE_BUTTON, this.world);
        this.floating_label.set_engage_function(this.function_to_bind);
        this.floating_label.set_look_at_function(this.function_look_at_bind);
        this.floating_label.set_look_away_function(this.function_look_away_bind);

        //this.object3D.add(this.icon);

        this.world.add_to_scene(this.object3D);

        // Inherit from Interactive.
        //Interactive.call(this);
        // Inherit from Visibility.
        //Visibility.call(this);

        this.world.interactive_objects.push(this.floating_label);
    },

    _set_utility_wall_position_and_normal: function(utility_wall, horizontal_shift) {
        if (is_defined(utility_wall)) {
            var player_position = CURRENT_PLAYER.get_position();
            var utility_wall_position = new THREE.Vector3(this.object3D.position.x + this.left_right.x * horizontal_shift * 3 + this.normal.x * 30,
                                                           this.object3D.position.y,
                                                           this.object3D.position.z + this.left_right.z * horizontal_shift * 3 + this.normal.z * 30);
            var utility_wall_look_at = new THREE.Vector3(player_position.x - utility_wall_position.x, 0, player_position.z - utility_wall_position.z);
            utility_wall_look_at.normalize();
            utility_wall.set_position_and_normal(utility_wall_position, utility_wall_look_at, false);
        }
    },

    set_position_and_normal: function(position, nx, nz) {
        this.y_position = position.y + SPACE_BETWEEN_MENU_ICONS * 2;
        this.object3D.position.set(position.x, this.y_position, position.z);
        this.object3D.lookAt(new THREE.Vector3(position.x + nx * 5, this.y_position, position.z + nz * 5));

        // TODO : Delete this?
        this.normal = new THREE.Vector3(nx, 0, nz);

        this.left_right = get_left_right_unit_vector(nx, nz);

        var horizontal_shift = 60;

        this.floating_label.update_position_and_normal(new THREE.Vector3(this.object3D.position.x + this.left_right.x * horizontal_shift, this.object3D.position.y, this.object3D.position.z + this.left_right.z * horizontal_shift), this.normal);

        this._set_utility_wall_position_and_normal(this.teleport_wall, horizontal_shift);
        this._set_utility_wall_position_and_normal(this.create_wall, horizontal_shift);
    },

    update_y_position: function(y_offset) {
        this.object3D.position.y = this.y_position - y_offset;
        this.floating_label.object3D.position.y = this.y_position - y_offset;
    },

};

PlayerMenu.prototype = {

    __init__: function(world) {
        this.world = world;

        // TODO : Make a better design for the temp values.
        var temp_position = new THREE.Vector3(-10000, -10000, -10000);
        var temp_normal   = new THREE.Vector3(0, 0, 0);
        this._player_menu = new FloatingWall(100, 200, temp_position, temp_normal, this.world);
        this._player_menu.make_base_wall_invisible();

        this.total_delta = 0;
    },

    set_to_invisible: function() {
        this.visible = false;
        if (is_defined(this.icons)) {
            for (var i = 0; i < this.icons.length; i++) {
                this.icons[i].set_to_invisible();
            }
        }
    },

    set_to_visible: function() {
        this.visible = true;
        this.total_delta = 0;

        var pp = CURRENT_PLAYER.get_position();
        var pd = CURRENT_PLAYER.get_direction();

        var start_position = new THREE.Vector3(pp.x + pd.x * MENU_DISTANCE_FROM_PLAYER, pp.y + pd.y * MENU_DISTANCE_FROM_PLAYER, pp.z + pd.z * MENU_DISTANCE_FROM_PLAYER);

        for (var i = 0; i < this.icons.length; i++) {
            this.icons[i].set_position_and_normal(start_position, -pd.x, -pd.z);
            this.icons[i].set_to_visible();
        }
    },

    is_visible: function() {
        return this.visible;
    },

    update: function(delta) {
        this.total_delta += delta;
        if (this.total_delta >= ANIMATION_TIME) {
            this.percentage = 1.0;
        } else {
            this.percentage = this.total_delta / ANIMATION_TIME;
        }

        // TODO : Refactor this!!!!
        if (is_defined(this.icons)) {
            for (var i = 0; i < this.icons.length; i++) {
                if (this.icons[i].row !== 0) {
                    var this_icons_max_delta = this.time_needed_for_each_row * this.icons[i].row;
                    if (this.percentage < this_icons_max_delta) {
                        this.icons[i].update_y_position(this.percentage * this.total_distance);
                    } else {
                        this.icons[i].update_y_position(this_icons_max_delta * this.total_distance);
                    }
                }
            }
        }

    },

    _add_menu_icon: function(icon, list_of_icons_not_to_load) {
        if (!is_defined(this.icons)) {
            this.icons = [];
        }
        if (!list_of_icons_not_to_load.contains(icon)) {
            this.icons.push(new MenuIcon(icon, this.world, this.icons.length, this));
        }
    },

    // This function gets called once per player menu object.
    load_icon_textures: function(list_of_icons_not_to_load) {
        this._add_menu_icon(ICON_WRENCH      , list_of_icons_not_to_load);
        this._add_menu_icon(ICON_SAVE        , list_of_icons_not_to_load);
        this._add_menu_icon(ICON_TELEPORT    , list_of_icons_not_to_load);
        this._add_menu_icon(ICON_MULTI_PLAYER, list_of_icons_not_to_load);
        this._add_menu_icon(ICON_FULLSCREEN  , list_of_icons_not_to_load);

        this.time_needed_for_each_row = ONE_SECOND / (this.icons.length);
        this.total_distance = this.icons.length * SPACE_BETWEEN_MENU_ICONS;

        this.set_to_invisible();
    }

};
<|endoftext|>


<commit_before>import Controller from './Controller';
import RequestFormView from '../views/requestForm';
import Racks from '../collections/Racks';
import Request from '../models/Request';
import { FetchAction as RequestFetchAction } from '../actions/api/request';
import { FetchAction as RacksFetchAction } from '../actions/api/racks';

class ReqeustFormController extends Controller {

    showView(store, edit) {
        this.setView(new RequestFormView({store, edit}));
        app.showView(this.view);
    }

    initialize({store, requestId = ''}) {
        app.showPageLoader();
        this.title(`${requestId ? 'Edit' : 'New'} Request`);
        this.store = store;

        const racksPromise = this.store.dispatch(RacksFetchAction.trigger());
        if (requestId) {
            const requestPromise = this.store.dispatch(RequestFetchAction.trigger(requestId));
            requestPromise.then(() => {
                this.showView(store, true);
            });
        } else {
            this.showView(store, false);
        }
    }
}

export default ReqeustFormController;
<commit_msg>more four spaces to two spaces<commit_after>import Controller from './Controller';
import RequestFormView from '../views/requestForm';
import Racks from '../collections/Racks';
import Request from '../models/Request';
import { FetchAction as RequestFetchAction } from '../actions/api/request';
import { FetchAction as RacksFetchAction } from '../actions/api/racks';

class ReqeustFormController extends Controller {

  showView(store, edit) {
    this.setView(new RequestFormView({store, edit}));
    app.showView(this.view);
  }

  initialize({store, requestId = ''}) {
    app.showPageLoader();
    this.title(`${requestId ? 'Edit' : 'New'} Request`);
    this.store = store;

    const racksPromise = this.store.dispatch(RacksFetchAction.trigger());
    if (requestId) {
      const requestPromise = this.store.dispatch(RequestFetchAction.trigger(requestId));
      requestPromise.then(() => {
        this.showView(store, true);
      });
    } else {
      this.showView(store, false);
    }
  }
}

export default ReqeustFormController;
<|endoftext|>


<commit_before>var self = require("sdk/self");
var data = self.data;
var addOnPrefs = require("sdk/simple-prefs").prefs;
var ui = require('sdk/ui');
var tabs = require("sdk/tabs");

var storage = require("./storage");
var constants = require("./constants");
var requestHelper = require("./request-helper");
var tracking = require("./tracking");
var service = require("./service");
var panel = require("sdk/panel");
var notifications = require("sdk/notifications");
var trackingHelper = require("./tracking");

exports.loadDatawake = loadDatawake;
exports.resetIcon = resetIcon;
exports.activeIcon = activeIcon;
exports.notifyError = notifyError;
exports.getFeaturesForPanel = getFeaturesForPanel;

var datawakeButton;
var sideBar;
var loginPanel;
var badgeForTab = {};

var authHelper = require("./auth-helper");
var signedIn = false;
var userInfo = null;
var workerArray = [];

/**
 * Load and start datawake components
 */
function loadDatawake() {

  // attach panels (logon panel and main panel) to the datawake action button
  attachActionButton();

  // set up the tracker on the current / initial tab
  trackingHelper.setUpTab(tabs.activeTab);

  // set up a new tab listener to add the tracker to each new tab
  tabs.on("open", function(tab) {
    var datawakeInfo = storage.getRecentlyUsedDatawakeInfo();
    storage.setDatawakeInfo(tab.id, datawakeInfo);
    trackingHelper.setUpTab(tab);
  });

  // touch the datawake info for this tab so that it is the most recently used
  // and get set the button icon for on / off
  tabs.on("activate", function(tab) {
    var datawakeInfoForTab = storage.getDatawakeInfo(tab.id);
    if (datawakeInfoForTab != null && datawakeInfoForTab.isDatawakeOn) {
      activeIcon();
    } else {
      resetIcon();
    }
  });
}

/**
 * Clear all datawake state.
 * used on signout
 */
function clearAllState() {
  if (sideBar) {
    sideBar.destroy();
    sideBar = null;
  }
  if (loginPanel) {
    loginPanel.destory();
    loginPanel = null;
  }
  storage.clear();
  userInfo = null;
  signedIn = false;
}

/**
 * Creates the Datawake Widgets and attaches a panel for the search contents.
 */
function attachActionButton() {

  datawakeButton = ui.ActionButton({
    id: "datawake-widget",
    label: "Datawake Widget",
    icon: data.url("img/waveicon38_bw.png"),
    onClick: onToggle
  });
}

/**
 * Handles the button when the panel's hide even is triggered.
 */
function handleHide() {
  datawakeButton.state('window', {
    checked: false
  });
}

/**
 * Sets up the required information when the ToggleButton is clicked.
 * Opens the login or datawake panel as needed
 * @param state The state of the ToggleButton.
 */
function onToggle(state) {

  // load the main datawake panel
  if (signedIn) {
    launchDatawakePanel();
  }
  // load the login panel
  else {
    launchLoginPanel();
  }

}

function attachWorker(worker) {
  workerArray.push(worker);
}

function detachWorker(worker) {
  var index = workerArray.indexOf(worker);
  if (index != -1) {
    workerArray.splice(index, 1);
  }
}

function launchDatawakePanel() {
  var datawakeInfo = storage.getDatawakeInfo(tabs.activeTab.id);
  if (sideBar != null || sideBar != undefined) {
    sideBar.destroy();
  }

  sideBar = require("sdk/ui/sidebar").Sidebar({
    id: 'datawake-prefetch',
    title: 'Datawake Prefetch',
    url: require("sdk/self").data.url("html/datawake-widget-panel.html"),
    onReady: function(worker) {
      attachWorker(worker);
      // emitTrailEntities(worker, "memex", "trail")
      // emitTrailBasedLinks(worker, "memex", "trail")
      worker.port.emit("ready", {
        starUrl: data.url("css/icons/"),
        datawakeInfo: datawakeInfo,
        useDomainFeatures: addOnPrefs.useDomainFeatures,
        useLookahead: addOnPrefs.useLookahead,
        useRanking: addOnPrefs.useRanking,
        versionNumber: self.version,
        current_url: tabs.activeTab.url,
        pageVisits: badgeForTab[tabs.activeTab.id]
      });

      worker.port.on("refreshEntities", function(domainAndTrail) {
        emitTrailEntities(worker, domainAndTrail.domain, domainAndTrail.trail)
      });
      worker.port.on("refreshWebPages", function(domainAndTrail) {
        emitTrailBasedLinks(worker, domainAndTrail.domain, domainAndTrail.trail)
      });
    },
    onDetach: detachWorker,
    onAttach: function(worker) {
      attachWorker(worker);
      worker.port.emit("ready", {
        starUrl: data.url("css/icons/"),
        datawakeInfo: datawakeInfo,
        useDomainFeatures: addOnPrefs.useDomainFeatures,
        useLookahead: addOnPrefs.useLookahead,
        useRanking: addOnPrefs.useRanking,
        versionNumber: self.version,
        current_url: tabs.activeTab.url,
        pageVisits: badgeForTab[tabs.activeTab.id]
      });
    }
  })
  sideBar.show();
}

function emitTrailEntities(worker, domain, trail) {
  var post_url = addOnPrefs.datawakeDeploymentUrl + "/trails/entities";
  var post_data = JSON.stringify({
    domain: domain,
    trail: trail
  });
  requestHelper.post(post_url, post_data, function(response) {
    console.log("Trail Based Entities Retrieved")
    console.log(response.json)
    worker.port.emit("trailEntities", response.json);
  });
}

function emitTrailBasedLinks(worker, domain, trail) {
  var post_url = addOnPrefs.datawakeDeploymentUrl + "/trails/links";
  var post_data = JSON.stringify({
    domain: domain,
    trail: trail
  });
  requestHelper.post(post_url, post_data, function(response) {
    console.log("Trail Bases Links Retrieved");
    console.log(response.json);
    worker.port.emit("trailLinks", response.json);
  });
}

/**
 *
 */
function getFeaturesForPanel(datawakeinfo) {
  if (sideBar) {
    if (constants.isValidUrl(tabs.activeTab.url)) {

      service.getEntities(tabs.activeTab.url, function(response) {
        if (response.status != 200) notifyError("Error getting features for this url.")
        else sideBar.port.emit("features", response.json);
      });

      service.getDomainExtractedEntities(datawakeinfo.team.id, datawakeinfo.domain.id, tabs.activeTab.url, function(response) {
        if (response.status != 200) notifyError("Error getting domain features for this url.")
        else sideBar.port.emit("domain_features", response.json);
      });

      // get manually labeled features
      loadManualFeatures(datawakeinfo);

      // get list of features marked as invalid
      emitMarkedEntities(datawakeinfo);

    }
  }
}

/**
 * Changes the team and resets domain and trail for a tab,
 * and fetches valid domains for this team.
 * @param tabId
 * @param newteam
 * @param callback, function handles response for /domains call to the server.
 * @returns The altered datawakeinfo object
 */
function changeTeam(tabId, newteam, callback) {
  var info = storage.getDatawakeInfo(tabId)
  if (!info.team || info.team.id != newteam.id) {
    info.team = newteam
    info.domain = null;
    info.trail = null;
    info.isDatawakeOn = false;
    storage.setDatawakeInfo(tabId, info)

    service.getDomains(info.team.id, function(response) {
      if (response.status == 200) {
        var domains = response.json;
        callback(domains);
      } else {
        //TODO handle the error
        console.error("ERROR GETTING DOMAINS ");
        console.error(response);
      }
    })
  }
  return info;
}

function changeDomain(tabId, newdomain, callback) {
  var info = storage.getDatawakeInfo(tabId)
  if (!info.domain || info.domain.id != newdomain.id) {
    info.domain = newdomain
    info.trail = null;
    info.isDatawakeOn = false;
    storage.setDatawakeInfo(tabId, info)

    service.getTrails(info.team.id, info.domain.id, function(response) {
      if (response.status == 200) {
        var trails = response.json;
        callback(trails);
      } else {
        console.error("ERROR GETTING trails ");
        console.error(response);
      }
    })
  }
  return info;
}

/**
 * Marks an entity as invalid
 * @param entity Object(entity_value, entity_type, domain)
 */
function markInvalid(data) {
  var post_url = addOnPrefs.datawakeDeploymentUrl + "/feedback/invalid_feature";
  requestHelper.post(post_url, JSON.stringify(data), function(response) {
    sideBar.port.emit("marked", data.feature_value);
  });
}

function emitMarkedEntities(datawakeinfo) {
  var post_url = addOnPrefs.datawakeDeploymentUrl + "/feedback/get_invalid_features";
  var post_obj = {
    team_id: datawakeinfo.team.id,
    domain_id: datawakeinfo.domain.id,
    trail_id: datawakeinfo.trail.id
  }
  requestHelper.post(post_url, JSON.stringify(post_obj), function(response) {
    if (response.status != 200) {
      notifyError("Error retrieving invalid features for this trail.")
    } else {
      sideBar.port.emit("markedFeatures", response.json);
    }

  });
}

/**
 * Emits feedback entities
 * @param domain domainName
 */
function loadManualFeatures(info) {
  var post_url = addOnPrefs.datawakeDeploymentUrl + "/feedback/manual_features";
  var post_data = JSON.stringify({
    team_id: info.team.id,
    domain_id: info.domain.id,
    trail_id: info.trail.id,
    url: tabs.activeTab.url
  });
  requestHelper.post(post_url, post_data, function(response) {
    if (response.status != 200) {
      notifyError("Error getting manual features for this url.")
    } else {
      sideBar.port.emit("manualFeatures", response.json);
    }

  });
}

function openExternalTool(externalUrlObject) {
  console.log("Opening External Tool");
  tabs.open(externalUrlObject.externalUrl);
}

/**
 * Emits Rank information to the panel attached to the widget.
 * @param datawakeInfo The datawake info associated with the current tab.
 */
function emitRanks(datawakeInfo) {
  var url = addOnPrefs.datawakeDeploymentUrl + "/ranks/get";
  var post_data = JSON.stringify({
    team_id: datawakeInfo.team.id,
    domain_id: datawakeInfo.domain.id,
    trail_id: datawakeInfo.trail.id,
    url: tabs.activeTab.url
  });
  requestHelper.post(url, post_data, function(response) {
    var rank = response.json.rank;
    var rankingInfo = {};
    rankingInfo.ranking = rank;
    if (sideBar) sideBar.port.emit("ranking", rankingInfo);
  });
}

/**
 * Sets the rank that the user rated the page.
 * @param rank_data
 */
function setUrlRank(rank_data) {
  rank_data.url = tabs.activeTab.url;
  var url = addOnPrefs.datawakeDeploymentUrl + "/ranks/set";
  console.debug("Posting Rank..");
  requestHelper.post(url, JSON.stringify(rank_data), function(response) {
    if (response.json.success) {
      console.debug("Successfully set rank..");
    }
  });
}

function activeIcon() {
  datawakeButton.icon = data.url("img/waveicon38.png");
}

function resetIcon() {
  datawakeButton.icon = data.url("img/waveicon38_bw.png");
}

function notifyError(message) {
  notifications.notify({
    title: "Datawake Error",
    text: message,
    iconURL: self.data.url("img/waveicon38.png"),
  });
}

/**
 * When the user is not signed in and clicks on the datawake button
 * we show the login panel.
 */
function launchLoginPanel() {

  if (loginPanel != null && loginPanel != undefined) {
    loginPanel.destroy()
  }

  loginPanel = panel.Panel({
    contentURL: data.url("html/login-panel.html"),
    onHide: handleHide,
    contentScriptOptions: {
      authType: authHelper.authType()
    }
  });

  loginPanel.port.on("signIn", function() {
    authHelper.signIn(function(response) {
      signedIn = true;
      userInfo = response.json
        //loginPanel.port.emit("sendUserInfo", response.json);
      loginPanel.destroy()
      loginPanel = null;
      notifications.notify({
        title: "Datawake Sign On",
        text: "Sign On Successful.  Click the datawake button to begin.",
        iconURL: self.data.url("img/waveicon38.png"),
        onClick: function(data) {
          console.log("clicked it")
          launchDatawakePanel()
        }
      });
    });
  });

  loginPanel.port.on("signOut", function() {
    authHelper.signOut(function(response) {
      clearAllState()
    });
  });
  loginPanel.show();
}<commit_msg>removing unused code<commit_after>var self = require("sdk/self");
var data = self.data;
var addOnPrefs = require("sdk/simple-prefs").prefs;
var ui = require('sdk/ui');
var tabs = require("sdk/tabs");

var storage = require("./storage");
var constants = require("./constants");
var requestHelper = require("./request-helper");
var tracking = require("./tracking");
var service = require("./service");
var panel = require("sdk/panel");
var notifications = require("sdk/notifications");
var trackingHelper = require("./tracking");

exports.loadDatawake = loadDatawake;
exports.resetIcon = resetIcon;
exports.activeIcon = activeIcon;
exports.notifyError = notifyError;
exports.getFeaturesForPanel = getFeaturesForPanel;

var datawakeButton;
var sideBar;
var loginPanel;
var badgeForTab = {};

var authHelper = require("./auth-helper");
var signedIn = false;
var userInfo = null;
var workerArray = [];

/**
 * Load and start datawake components
 */
function loadDatawake() {

  // attach panels (logon panel and main panel) to the datawake action button
  attachActionButton();

  // set up a new tab listener to add the tracker to each new tab
  tabs.on("open", function(tab) {
    var datawakeInfo = storage.getRecentlyUsedDatawakeInfo();
    storage.setDatawakeInfo(tab.id, datawakeInfo);
    // trackingHelper.setUpTab(tab);
  });

  // touch the datawake info for this tab so that it is the most recently used
  // and get set the button icon for on / off
  tabs.on("activate", function(tab) {
    var datawakeInfoForTab = storage.getDatawakeInfo(tab.id);
    if (datawakeInfoForTab != null && datawakeInfoForTab.isDatawakeOn) {
      activeIcon();
    } else {
      resetIcon();
    }
  });
}

/**
 * Clear all datawake state.
 * used on signout
 */
function clearAllState() {
  if (sideBar) {
    sideBar.destroy();
    sideBar = null;
  }
  if (loginPanel) {
    loginPanel.destory();
    loginPanel = null;
  }
  storage.clear();
  userInfo = null;
  signedIn = false;
}

/**
 * Creates the Datawake Widgets and attaches a panel for the search contents.
 */
function attachActionButton() {

  datawakeButton = ui.ActionButton({
    id: "datawake-widget",
    label: "Datawake Widget",
    icon: data.url("img/waveicon38_bw.png"),
    onClick: onToggle
  });
}

/**
 * Handles the button when the panel's hide even is triggered.
 */
function handleHide() {
  datawakeButton.state('window', {
    checked: false
  });
}

/**
 * Sets up the required information when the ToggleButton is clicked.
 * Opens the login or datawake panel as needed
 * @param state The state of the ToggleButton.
 */
function onToggle(state) {

  // load the main datawake panel
  if (signedIn) {
    launchDatawakePanel();
  }
  // load the login panel
  else {
    launchLoginPanel();
  }

}

function attachWorker(worker) {
  workerArray.push(worker);
}

function detachWorker(worker) {
  var index = workerArray.indexOf(worker);
  if (index != -1) {
    workerArray.splice(index, 1);
  }
}

function launchDatawakePanel() {
  var datawakeInfo = storage.getDatawakeInfo(tabs.activeTab.id);
  if (sideBar != null || sideBar != undefined) {
    sideBar.destroy();
  }

  sideBar = require("sdk/ui/sidebar").Sidebar({
    id: 'datawake-prefetch',
    title: 'Datawake Prefetch',
    url: require("sdk/self").data.url("html/datawake-widget-panel.html"),
    onReady: function(worker) {
      attachWorker(worker);
      worker.port.emit("ready", {
        // starUrl: data.url("css/icons/"),
        datawakeInfo: datawakeInfo,
        useDomainFeatures: addOnPrefs.useDomainFeatures,
        useLookahead: addOnPrefs.useLookahead,
        // useRanking: addOnPrefs.useRanking,
        versionNumber: self.version,
        current_url: tabs.activeTab.url,
        pageVisits: badgeForTab[tabs.activeTab.id]
      });

      worker.port.on("refreshEntities", function(domainAndTrail) {
        emitTrailEntities(worker, domainAndTrail.domain, domainAndTrail.trail)
      });
      worker.port.on("refreshWebPages", function(domainAndTrail) {
        emitTrailBasedLinks(worker, domainAndTrail.domain, domainAndTrail.trail)
      });
    },
    onDetach: detachWorker,
    onAttach: function(worker) {
      attachWorker(worker);
      worker.port.emit("ready", {
        starUrl: data.url("css/icons/"),
        datawakeInfo: datawakeInfo,
        useDomainFeatures: addOnPrefs.useDomainFeatures,
        useLookahead: addOnPrefs.useLookahead,
        useRanking: addOnPrefs.useRanking,
        versionNumber: self.version,
        current_url: tabs.activeTab.url,
        pageVisits: badgeForTab[tabs.activeTab.id]
      });
    }
  })
  sideBar.show();
}

function emitTrailEntities(worker, domain, trail) {
  var post_url = addOnPrefs.datawakeDeploymentUrl + "/trails/entities";
  var post_data = JSON.stringify({
    domain: domain,
    trail: trail
  });
  requestHelper.post(post_url, post_data, function(response) {
    worker.port.emit("trailEntities", response.json);
  });
}

function emitTrailBasedLinks(worker, domain, trail) {
  var post_url = addOnPrefs.datawakeDeploymentUrl + "/trails/links";
  var post_data = JSON.stringify({
    domain: domain,
    trail: trail
  });
  requestHelper.post(post_url, post_data, function(response) {
    worker.port.emit("trailLinks", response.json);
  });
}

/**
 *
 */
function getFeaturesForPanel(datawakeinfo) {
  if (sideBar) {
    if (constants.isValidUrl(tabs.activeTab.url)) {

      service.getEntities(tabs.activeTab.url, function(response) {
        if (response.status != 200) notifyError("Error getting features for this url.")
        else sideBar.port.emit("features", response.json);
      });

      service.getDomainExtractedEntities(datawakeinfo.team.id, datawakeinfo.domain.id, tabs.activeTab.url, function(response) {
        if (response.status != 200) notifyError("Error getting domain features for this url.")
        else sideBar.port.emit("domain_features", response.json);
      });

      // get manually labeled features
      loadManualFeatures(datawakeinfo);

      // get list of features marked as invalid
      emitMarkedEntities(datawakeinfo);

    }
  }
}

function activeIcon() {
  datawakeButton.icon = data.url("img/waveicon38.png");
}

function resetIcon() {
  datawakeButton.icon = data.url("img/waveicon38_bw.png");
}

function notifyError(message) {
  notifications.notify({
    title: "Datawake Error",
    text: message,
    iconURL: self.data.url("img/waveicon38.png"),
  });
}

/**
 * When the user is not signed in and clicks on the datawake button
 * we show the login panel.
 */
function launchLoginPanel() {

  if (loginPanel != null && loginPanel != undefined) {
    loginPanel.destroy()
  }

  loginPanel = panel.Panel({
    contentURL: data.url("html/login-panel.html"),
    onHide: handleHide,
    contentScriptOptions: {
      authType: authHelper.authType()
    }
  });

  loginPanel.port.on("signIn", function() {
    authHelper.signIn(function(response) {
      signedIn = true;
      userInfo = response.json
        //loginPanel.port.emit("sendUserInfo", response.json);
      loginPanel.destroy()
      loginPanel = null;
      notifications.notify({
        title: "Datawake Sign On",
        text: "Sign On Successful.  Click the datawake button to begin.",
        iconURL: self.data.url("img/waveicon38.png"),
        onClick: function(data) {
          console.log("clicked it")
          launchDatawakePanel()
        }
      });
    });
  });

  loginPanel.port.on("signOut", function() {
    authHelper.signOut(function(response) {
      clearAllState()
    });
  });
  loginPanel.show();
}<|endoftext|>


<commit_before>//used for the media picker dialog
angular.module("umbraco")
    .controller("Umbraco.Overlays.MediaPickerController",
        function ($scope, mediaResource, umbRequestHelper, entityResource, $log, mediaHelper, eventsService, treeService, $element, $timeout, $cookies, $cookieStore) {

            var dialogOptions = $scope.model;

            $scope.onlyImages = dialogOptions.onlyImages;
            $scope.showDetails = dialogOptions.showDetails;
            $scope.multiPicker = (dialogOptions.multiPicker && dialogOptions.multiPicker !== "0") ? true : false;
            $scope.startNodeId = dialogOptions.startNodeId ? dialogOptions.startNodeId : -1;
            $scope.cropSize = dialogOptions.cropSize;
            $scope.lastOpenedNode = $cookieStore.get("umbLastOpenedMediaNodeId");
            $scope.acceptedFileTypes = mediaHelper.formatFileTypes(Umbraco.Sys.ServerVariables.umbracoSettings.imageFileTypes);
            $scope.maxFileSize = Umbraco.Sys.ServerVariables.umbracoSettings.maxFileSize + "KB";

            $scope.model.selectedImages = [];

            //preload selected item
            $scope.target = undefined;
            if(dialogOptions.currentTarget){
                $scope.target = dialogOptions.currentTarget;
            }

            $scope.dragLeave = function(el, event){
                $scope.activeDrag = false;
            };

            $scope.dragEnter = function(el, event){
                $scope.activeDrag = true;
            };

            $scope.submitFolder = function() {

               if ($scope.newFolderName) {

                  mediaResource
                     .addFolder($scope.newFolderName, $scope.currentFolder.id)
                     .then(function(data) {

                        //we've added a new folder so lets clear the tree cache for that specific item
                        treeService.clearCache({
                           cacheKey: "__media", //this is the main media tree cache key
                           childrenOf: data.parentId //clear the children of the parent
                        });

                        $scope.gotoFolder(data);

                        $scope.showFolderInput = false;

                        $scope.newFolderName = "";

                     });

               } else {
                  $scope.showFolderInput = false;
               }

            };

            $scope.gotoFolder = function(folder) {

                if(!folder){
                    folder = {id: -1, name: "Media", icon: "icon-folder"};
                }

                if (folder.id > 0) {
                    entityResource.getAncestors(folder.id, "media")
                        .then(function(anc) {
                            // anc.splice(0,1);
                            $scope.path = _.filter(anc, function (f) {
                                return f.path.indexOf($scope.startNodeId) !== -1;
                            });
                        });
                }
                else {
                    $scope.path = [];
                }

                //mediaResource.rootMedia()
                mediaResource.getChildren(folder.id)
                   .then(function(data) {
                      $scope.searchTerm = "";
                      $scope.images = data.items ? data.items : [];

                      // set already selected images to selected
                      for (var folderImageIndex = 0; folderImageIndex < $scope.images.length; folderImageIndex++) {

                         var folderImage = $scope.images[folderImageIndex];
                         var imageIsSelected = false;

                         for (var selectedImageIndex = 0; selectedImageIndex < $scope.model.selectedImages.length; selectedImageIndex++) {
                            var selectedImage = $scope.model.selectedImages[selectedImageIndex];

                            if(folderImage.key === selectedImage.key) {
                               imageIsSelected = true;
                            }
                         }

                         if(imageIsSelected) {
                            folderImage.cssclass = "selected";
                         }
                      }

                   });

                $scope.currentFolder = folder;

                // for some reason i cannot set cookies with cookieStore
                document.cookie="umbLastOpenedMediaNodeId=" + folder.id;

            };

            $scope.clickHandler = function(image, ev, select) {
                ev.preventDefault();

                if (image.isFolder && !select) {
                    $scope.gotoFolder(image);
                }else{
                    eventsService.emit("dialogs.mediaPicker.select", image);

                    //we have 3 options add to collection (if multi) show details, or submit it right back to the callback
                    if ($scope.multiPicker) {
                        selectImage(image);
                    }else if($scope.showDetails) {

                        $scope.target = image;
                        $scope.target.url = mediaHelper.resolveFile(image);

                        $scope.openDetailsDialog();

                    }else{
                       $scope.model.selectedImages.push(image);
                       $scope.model.submit($scope.model);
                    }
                }
            };

            function selectImage(image) {

               if($scope.model.selectedImages.length > 0) {

                  var selectImage = false;

                  for (var i = 0; i < $scope.model.selectedImages.length; i++) {

                     var selectedImage = $scope.model.selectedImages[i];

                     if(image.key === selectedImage.key) {
                        image.cssclass = "";
                        $scope.model.selectedImages.splice(i, 1);
                        selectImage = false;
                     } else {
                        selectImage = true;
                     }

                  }

                  if(selectImage) {
                     image.cssclass = "selected";
                     $scope.model.selectedImages.push(image);
                  }

               } else {
                  $scope.model.selectedImages.push(image);
                  image.cssclass = "selected";
               }

            }

            $scope.onUploadComplete = function () {
                $scope.gotoFolder($scope.currentFolder);
            };

            $scope.onFilesQueue = function(){
                $scope.activeDrag = false;
            };

            //default root item
            if (!$scope.target) {

               if($scope.lastOpenedNode) {

                  entityResource.getById($scope.lastOpenedNode, "media")
                     .then(function(node){

                        // make sure that las opened node is on the same path as start node
                        var nodePath = node.path.split(",");

                        if(nodePath.indexOf($scope.startNodeId) !== -1) {
                           $scope.gotoFolder({id: $scope.lastOpenedNode, name: "Media", icon: "icon-folder"});
                        } else {
                           $scope.gotoFolder({id: $scope.startNodeId, name: "Media", icon: "icon-folder"});
                        }

                     });

               } else {

                  $scope.gotoFolder({id: $scope.startNodeId, name: "Media", icon: "icon-folder"});

               }

            }

            $scope.openDetailsDialog = function() {

               $scope.mediaPickerDetailsOverlay = {};
               $scope.mediaPickerDetailsOverlay.show = true;

               $scope.mediaPickerDetailsOverlay.submit = function(model) {

                  $scope.model.selectedImages.push($scope.target);
                  $scope.model.submit($scope.model);

                  $scope.mediaPickerDetailsOverlay.show = false;
                  $scope.mediaPickerDetailsOverlay = null;

               };

               $scope.mediaPickerDetailsOverlay.close = function(oldModel) {
                  $scope.mediaPickerDetailsOverlay.show = false;
                  $scope.mediaPickerDetailsOverlay = null;
               };

            };

        });
<commit_msg>Fixes: U4-4051 Bug when querying for root node with the remembered node id<commit_after>//used for the media picker dialog
angular.module("umbraco")
    .controller("Umbraco.Overlays.MediaPickerController",
        function ($scope, mediaResource, umbRequestHelper, entityResource, $log, mediaHelper, eventsService, treeService, $element, $timeout, $cookies, $cookieStore) {

            var dialogOptions = $scope.model;

            $scope.onlyImages = dialogOptions.onlyImages;
            $scope.showDetails = dialogOptions.showDetails;
            $scope.multiPicker = (dialogOptions.multiPicker && dialogOptions.multiPicker !== "0") ? true : false;
            $scope.startNodeId = dialogOptions.startNodeId ? dialogOptions.startNodeId : -1;
            $scope.cropSize = dialogOptions.cropSize;
            $scope.lastOpenedNode = $cookieStore.get("umbLastOpenedMediaNodeId");
            $scope.acceptedFileTypes = mediaHelper.formatFileTypes(Umbraco.Sys.ServerVariables.umbracoSettings.imageFileTypes);
            $scope.maxFileSize = Umbraco.Sys.ServerVariables.umbracoSettings.maxFileSize + "KB";

            $scope.model.selectedImages = [];

            //preload selected item
            $scope.target = undefined;
            if(dialogOptions.currentTarget){
                $scope.target = dialogOptions.currentTarget;
            }

            $scope.dragLeave = function(el, event){
                $scope.activeDrag = false;
            };

            $scope.dragEnter = function(el, event){
                $scope.activeDrag = true;
            };

            $scope.submitFolder = function() {

               if ($scope.newFolderName) {

                  mediaResource
                     .addFolder($scope.newFolderName, $scope.currentFolder.id)
                     .then(function(data) {

                        //we've added a new folder so lets clear the tree cache for that specific item
                        treeService.clearCache({
                           cacheKey: "__media", //this is the main media tree cache key
                           childrenOf: data.parentId //clear the children of the parent
                        });

                        $scope.gotoFolder(data);

                        $scope.showFolderInput = false;

                        $scope.newFolderName = "";

                     });

               } else {
                  $scope.showFolderInput = false;
               }

            };

            $scope.gotoFolder = function(folder) {

                if(!folder){
                    folder = {id: -1, name: "Media", icon: "icon-folder"};
                }

                if (folder.id > 0) {
                    entityResource.getAncestors(folder.id, "media")
                        .then(function(anc) {
                            // anc.splice(0,1);
                            $scope.path = _.filter(anc, function (f) {
                                return f.path.indexOf($scope.startNodeId) !== -1;
                            });
                        });
                }
                else {
                    $scope.path = [];
                }

                //mediaResource.rootMedia()
                mediaResource.getChildren(folder.id)
                   .then(function(data) {
                      $scope.searchTerm = "";
                      $scope.images = data.items ? data.items : [];

                      // set already selected images to selected
                      for (var folderImageIndex = 0; folderImageIndex < $scope.images.length; folderImageIndex++) {

                         var folderImage = $scope.images[folderImageIndex];
                         var imageIsSelected = false;

                         for (var selectedImageIndex = 0; selectedImageIndex < $scope.model.selectedImages.length; selectedImageIndex++) {
                            var selectedImage = $scope.model.selectedImages[selectedImageIndex];

                            if(folderImage.key === selectedImage.key) {
                               imageIsSelected = true;
                            }
                         }

                         if(imageIsSelected) {
                            folderImage.cssclass = "selected";
                         }
                      }

                   });

                $scope.currentFolder = folder;

                // for some reason i cannot set cookies with cookieStore
                document.cookie="umbLastOpenedMediaNodeId=" + folder.id;

            };

            $scope.clickHandler = function(image, ev, select) {
                ev.preventDefault();

                if (image.isFolder && !select) {
                    $scope.gotoFolder(image);
                }else{
                    eventsService.emit("dialogs.mediaPicker.select", image);

                    //we have 3 options add to collection (if multi) show details, or submit it right back to the callback
                    if ($scope.multiPicker) {
                        selectImage(image);
                    }else if($scope.showDetails) {

                        $scope.target = image;
                        $scope.target.url = mediaHelper.resolveFile(image);

                        $scope.openDetailsDialog();

                    }else{
                       $scope.model.selectedImages.push(image);
                       $scope.model.submit($scope.model);
                    }
                }
            };

            function selectImage(image) {

               if($scope.model.selectedImages.length > 0) {

                  var selectImage = false;

                  for (var i = 0; i < $scope.model.selectedImages.length; i++) {

                     var selectedImage = $scope.model.selectedImages[i];

                     if(image.key === selectedImage.key) {
                        image.cssclass = "";
                        $scope.model.selectedImages.splice(i, 1);
                        selectImage = false;
                     } else {
                        selectImage = true;
                     }

                  }

                  if(selectImage) {
                     image.cssclass = "selected";
                     $scope.model.selectedImages.push(image);
                  }

               } else {
                  $scope.model.selectedImages.push(image);
                  image.cssclass = "selected";
               }

            }

            $scope.onUploadComplete = function () {
                $scope.gotoFolder($scope.currentFolder);
            };

            $scope.onFilesQueue = function(){
                $scope.activeDrag = false;
            };

            //default root item
            if (!$scope.target) {

               if($scope.lastOpenedNode && $scope.lastOpenedNode !== -1) {

                  entityResource.getById($scope.lastOpenedNode, "media")
                     .then(function(node){

                        // make sure that las opened node is on the same path as start node
                        var nodePath = node.path.split(",");

                        if(nodePath.indexOf($scope.startNodeId.toString()) !== -1) {
                           $scope.gotoFolder({id: $scope.lastOpenedNode, name: "Media", icon: "icon-folder"});
                        } else {
                           $scope.gotoFolder({id: $scope.startNodeId, name: "Media", icon: "icon-folder"});
                        }

                    }, function (err) {
                        $scope.gotoFolder({id: $scope.startNodeId, name: "Media", icon: "icon-folder"});
                    });

               } else {

                  $scope.gotoFolder({id: $scope.startNodeId, name: "Media", icon: "icon-folder"});

               }

            }

            $scope.openDetailsDialog = function() {

               $scope.mediaPickerDetailsOverlay = {};
               $scope.mediaPickerDetailsOverlay.show = true;

               $scope.mediaPickerDetailsOverlay.submit = function(model) {

                  $scope.model.selectedImages.push($scope.target);
                  $scope.model.submit($scope.model);

                  $scope.mediaPickerDetailsOverlay.show = false;
                  $scope.mediaPickerDetailsOverlay = null;

               };

               $scope.mediaPickerDetailsOverlay.close = function(oldModel) {
                  $scope.mediaPickerDetailsOverlay.show = false;
                  $scope.mediaPickerDetailsOverlay = null;
               };

            };

        });
<|endoftext|>


<commit_before>/*
 * This program is part of the OpenLMIS logistics management information system platform software.
 * Copyright © 2013 VillageReach
 *
 * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more details.
 * You should have received a copy of the GNU Affero General Public License along with this program.  If not, see http://www.gnu.org/licenses.  For additional information contact info@OpenLMIS.org.
 */

describe("Supervisory Node Search Controller", function () {

  var scope, $httpBackend, ctrl, navigateBackService, location, messageService;
  beforeEach(module('openlmis'));

  beforeEach(inject(function ($rootScope, _$httpBackend_, $controller, _navigateBackService_, $location, _messageService_) {
    scope = $rootScope.$new();
    $httpBackend = _$httpBackend_;
    scope.query = "Nod";
    navigateBackService = _navigateBackService_;
    navigateBackService.query = '';
    location = $location;
    ctrl = $controller;
    messageService = _messageService_;
    ctrl('SupervisoryNodeSearchController', {$scope: scope, messageService: messageService});
  }));

  it('should get all supervisory nodes in a page depending on search criteria when three characters are entered in search', function () {
    var supervisoryNode = {"code": "N1", "name": "Node 1", "parent": 2};
    var pagination = {"page" : 1, "pageSize" : 10, "numberOfPages" : 10, "totalRecords" : 100};
    var response = {"supervisoryNodes": [supervisoryNode], "pagination" : pagination};
    scope.query = "Nod";
    scope.selectedSearchOption.value = 'parent';
    scope.currentPage = 1;
    $httpBackend.when('GET', '/search-supervisory-nodes.json?page=1&param=' + scope.query + '&parent=true' ).respond(response);
    scope.showSupervisoryNodeSearchResults();
    $httpBackend.flush();

    expect(scope.supervisoryNodeList).toEqual([supervisoryNode]);
    expect(scope.pagination).toEqual(pagination);
  });

/*  it('should filter supervisory nodes when more than 3 characters are entered for search with first 3 characters matching previous search', function () {
    scope.previousQuery = "Nod";
    scope.query = "Node";
    var supervisoryNode = {"code": "N1", "name": "Node 1", "parent": 2};
    scope.supervisoryNodeList = [supervisoryNode];

    scope.showSupervisoryNodeSearchResults();

    expect(scope.filteredNodes).toEqual([supervisoryNode]);
  });*/
});<commit_msg>|#1465| Riya| fixing jasmine spec for search supervisory node controller<commit_after>/*
 * This program is part of the OpenLMIS logistics management information system platform software.
 * Copyright © 2013 VillageReach
 *
 * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more details.
 * You should have received a copy of the GNU Affero General Public License along with this program.  If not, see http://www.gnu.org/licenses.  For additional information contact info@OpenLMIS.org.
 */

describe("Supervisory Node Search Controller", function () {

  var scope, $httpBackend, ctrl, navigateBackService, location, messageService;
  beforeEach(module('openlmis'));

  beforeEach(inject(function ($rootScope, _$httpBackend_, $controller, _navigateBackService_, $location, _messageService_) {
    scope = $rootScope.$new();
    $httpBackend = _$httpBackend_;
    scope.query = "Nod";
    navigateBackService = _navigateBackService_;
    navigateBackService.query = '';
    location = $location;
    ctrl = $controller;
    messageService = _messageService_;
    ctrl('SupervisoryNodeSearchController', {$scope: scope, messageService: messageService});
  }));

  it('should get all supervisory nodes in a page depending on search criteria when three characters are entered in search', function () {
    var supervisoryNode = {"code": "N1", "name": "Node 1", "parent": 2};
    var pagination = {"page" : 1, "pageSize" : 10, "numberOfPages" : 10, "totalRecords" : 100};
    var response = {"supervisoryNodes": [supervisoryNode], "pagination" : pagination};
    scope.query = "Nod";
    scope.selectedSearchOption.value = 'parent';
    scope.currentPage = 1;
    $httpBackend.when('GET', '/search-supervisory-nodes.json?page=1&param=' + scope.query + '&parent=true' ).respond(response);
    scope.search();
    $httpBackend.flush();

    expect(scope.supervisoryNodeList).toEqual([supervisoryNode]);
    expect(scope.pagination).toEqual(pagination);
  });

/*  it('should filter supervisory nodes when more than 3 characters are entered for search with first 3 characters matching previous search', function () {
    scope.previousQuery = "Nod";
    scope.query = "Node";
    var supervisoryNode = {"code": "N1", "name": "Node 1", "parent": 2};
    scope.supervisoryNodeList = [supervisoryNode];

    scope.showSupervisoryNodeSearchResults();

    expect(scope.filteredNodes).toEqual([supervisoryNode]);
  });*/
});<|endoftext|>


<commit_before>import { toQueryString, getUrlVars, sleep } from './utils.js';

window.visualize = visualize; // Add function to global scope.

/**
 * Get the simulation metadata encoded as a query string, iterate over all rounds and visualize
 * the real and estimated board state at each round (with a 1000 ms delay between two consecutive rounds).
 */
async function visualize() {
    const realBoardElementId = 'real-board-table';
    const estimatedBoardElementId = 'estimated-board-table';
    var simulation = getUrlVars();
    var mainHeader = document.getElementById('simulation-visualization-header');
    var roundHeader = document.getElementById('current-round-header');
    var delay;
    mainHeader.innerText = 'Visualizing Simulation\n' + simulation.id;
    var params = {};
    params['simulationId'] = simulation.id;
    for (var round = 0; round < simulation.roundsNum; round++) {
        roundHeader.innerText = 'Current Round: ' + round;
        params['round'] = round;

        // Request real board state.
        params['isReal'] = true;
        await fetchReadBoardState(params, realBoardElementId);

        // Request estimated board state.
        params['isReal'] = false;
        await fetchReadBoardState(params, estimatedBoardElementId);

        // Delay.
        delay = 1/document.getElementById('speed-controller').value;
        await sleep(delay);
    }
}

/**
 * Fetch board state from servlet by given parameters, and update an HTML table corresponding to given
 * board element id to visualize the board's state.
 * @param {Object} params is an object storing parameters for http request.
 * @param {String} boardElementId is the id of the html table element to be updated.
 */
async function fetchReadBoardState(params, boardElementId) {
    const queryString = toQueryString(params);
    fetch(`/read-board-state?${queryString}`)
    .then(response => response.json())
    .then(boardState => visualizeBoardState(boardState.array, boardElementId));
}

/**
 * Given a board state and an id of an html table element, update the table to display the board state.
 * @param {String[][]} board is the board state to visualize.
 * @param {String} tableId is the id of the html table element to be updated.
 */
function visualizeBoardState(board, tableId) {

    // Set table and table body
    var boardTable = document.getElementById(tableId);
    var boardTableBody = document.createElement('tbody');

    // Change cells' classes according to board.
    board.forEach(function(rowData) {

        var row = document.createElement('tr');
        row.classList.add('board-tr')

        rowData.forEach(function(cellData) {
            var cell = document.createElement('td');
            cell.classList.add('board-td');
            var beaconsIdsInsideCell = extractBeaconsIds(cellData);
            cell.setAttribute('title', beaconsIdsInsideCell.join(","));

            var beaconOnFocus = document.getElementById("beacon-id").value;
            if (beaconOnFocus != "" && beaconsIdsInsideCell.includes(beaconOnFocus)) {
                cell.classList.add('board-td-contains-wanted-beacon');
            } else {
                cell.classList.add(determineCellClass(cellData));
            }
            row.appendChild(cell);
        });

        boardTableBody.appendChild(row);
    });

    // Clear last state of table (if table body exists).
    var oldTableBodies = boardTable.tBodies;
    if (oldTableBodies.length > 0) {
        boardTable.removeChild(oldTableBodies[0]);
    }

    // Append updated table body.
    boardTable.appendChild(boardTableBody);
}

/**
 * return the css class name representing the correct state of the cell (empty/contains beacons/observers only).
 * @param {String[]} agents a list of agents ids located in the same cell of the board.
 * @returns {String} the correct css class name.
 */
function determineCellClass(agents) {
    if (agents.length === 0) { return 'board-td-empty'; }
    for (var i = 0; i < agents.length; i++) {
        if (agents[i].charAt(0) === 'B') { return 'board-td-contains-beacon'; }
    }
    return 'board-td-observers-only';
}

/**
 * Returns a sorted list of all the beacons' ids in the given list.
 * @param {String[]} agents is a list of agents ids located in the same cell of the board.
 */
function extractBeaconsIds(agents) {
    var beaconsIds = agents.filter(agent => agent.charAt(0) === 'B')
                    .map(agent => agent.slice(6));
    return beaconsIds.sort((a, b) => parseInt(a) - parseInt(b));
}<commit_msg>Refactoring the cells' update.<commit_after>import { toQueryString, getUrlVars, sleep } from './utils.js';

window.visualize = visualize; // Add function to global scope.

/**
 * Get the simulation metadata encoded as a query string, iterate over all rounds and visualize
 * the real and estimated board state at each round (with a 1000 ms delay between two consecutive rounds).
 */
async function visualize() {
    const realBoardElementId = 'real-board-table';
    const estimatedBoardElementId = 'estimated-board-table';
    var simulation = getUrlVars();
    var mainHeader = document.getElementById('simulation-visualization-header');
    var roundHeader = document.getElementById('current-round-header');
    var delay;
    mainHeader.innerText = 'Visualizing Simulation\n' + simulation.id;
    var params = {};
    params['simulationId'] = simulation.id;
    for (var round = 0; round < simulation.roundsNum; round++) {
        roundHeader.innerText = 'Current Round: ' + round;
        params['round'] = round;

        // Request real board state.
        params['isReal'] = true;
        await fetchReadBoardState(params, realBoardElementId);

        // Request estimated board state.
        params['isReal'] = false;
        await fetchReadBoardState(params, estimatedBoardElementId);

        // Delay.
        delay = 1/document.getElementById('speed-controller').value;
        await sleep(delay);
    }
}

/**
 * Fetch board state from servlet by given parameters, and update an HTML table corresponding to given
 * board element id to visualize the board's state.
 * @param {Object} params is an object storing parameters for http request.
 * @param {String} boardElementId is the id of the html table element to be updated.
 */
async function fetchReadBoardState(params, boardElementId) {
    const queryString = toQueryString(params);
    fetch(`/read-board-state?${queryString}`)
    .then(response => response.json())
    .then(boardState => visualizeBoardState(boardState.array, boardElementId));
}

/**
 * Given a board state and an id of an html table element, update the table to display the board state.
 * @param {String[][]} board is the board state to visualize.
 * @param {String} tableId is the id of the html table element to be updated.
 */
function visualizeBoardState(board, tableId) {

    // Set table and table body
    var boardTable = document.getElementById(tableId);
    var boardTableBody = document.createElement('tbody');

    // Change cells' classes according to board.
    board.forEach(function(rowData) {

        var row = document.createElement('tr');
        row.classList.add('board-tr')

        rowData.forEach(function(cellData) {
            var cell = document.createElement('td');
            cell.classList.add('board-td');
            updateCell(cell, cellData);
            row.appendChild(cell);
        });

        boardTableBody.appendChild(row);
    });

    // Clear last state of table (if table body exists).
    var oldTableBodies = boardTable.tBodies;
    if (oldTableBodies.length > 0) {
        boardTable.removeChild(oldTableBodies[0]);
    }

    // Append updated table body.
    boardTable.appendChild(boardTableBody);
}

/**
 * Update the cell according to the agents inside it.
 * @param {HTMLTableDataCellElement} cell is an HTML element from type <td>, representing a cell on the board.
 * @param {String[]} agents is a list of agents ids located inside the cell.
 */
function updateCell(cell, agents) {
    var beaconsIdsInsideCell = extractBeaconsIds(agents);
    cell.setAttribute('title', beaconsIdsInsideCell.join(","));

    var beaconToFocusOn = document.getElementById("beacon-id").value;
    var isBeaconToFocusOnInCell = beaconToFocusOn != "" && beaconsIdsInsideCell.includes(beaconToFocusOn);
    cell.classList.add(determineCellClass(agents, beaconsIdsInsideCell.length, isBeaconToFocusOnInCell));
}

/**
 * return the css class name representing the correct state of the cell (empty/contains beacons/observers only).
 * @param {String[]} agents a list of agents ids located in the same cell of the board.
 * @returns {String} the correct css class name.
 */
function determineCellClass(agents, numberOfBeacons, isBeaconToFocusOnInCell) {
    if (agents.length === 0) {
        return 'board-td-empty';
    }
    if (isBeaconToFocusOnInCell) {
        return 'board-td-contains-wanted-beacon';
    }
    if (numberOfBeacons > 0) {
       return 'board-td-contains-beacon';
    }
    return 'board-td-observers-only';
}

/**
 * Returns a sorted list of all the beacons' ids in the given list.
 * @param {String[]} agents is a list of agents ids located in the same cell of the board.
 */
function extractBeaconsIds(agents) {
    var beaconsIds = agents.filter(agent => agent.charAt(0) === 'B')
                    .map(agent => agent.slice(6));
    return beaconsIds.sort((a, b) => parseInt(a) - parseInt(b));
}<|endoftext|>


<commit_before>$(function() {

	var submitButtonClicked = function(){
		$("#xml_editor_div").html("");
		$("#workflow_diagram").html("");
		$("#xml_editor_pre").html("");
		$("#errorMessage").html("");
		$("#waiting_image").show();

		var formData = new FormData($("#fileform")[0]);
		$.ajax({
			url: vo.contextRoot + "api/upload_xml"
			, type: 'POST'
			, data: formData
			, cache: false
			, contentType: false
			, processData: false
			, complete: function(jqXHR, textStatus){
				var res = $.parseJSON(jqXHR.responseText);
				drawXmlEditor(res.xml, res.lineNumber, res.columnNumber);
				$("#span_identifiedNamespace").html(res.identifiedNamespace);

				if(!res.succeeded){
					$("#errorMessage").html(res.errorMessage);
					return;
				}
				$("#waiting_image").hide();
				drawDiagram(res);

			}
		});
	};

	var onWindowResize = function(){
		var editorHeight = window.innerHeight - $("#workflow_diagram").offset().top;
		$("#xml_editor_div").height(editorHeight);
		$("#workflow_diagram").height(editorHeight);
	};

	var weightedNodes;

	function drawDiagram(res){
		weightedNodes = {};
		var editorWidth = $(document).width() / 2;
		onWindowResize();
		var canvas1 = new wfjs.Canvas("workflow_diagram", editorWidth, 2000);
		var unsortedNodes = res.nodes;

		// Set weightedNodes wihtout sortOrder
		for(var nodeIndex = 0; nodeIndex < unsortedNodes.length; nodeIndex++){
			var node = unsortedNodes[nodeIndex];
			weightedNodes[node.name] = { to : node.to , type: node.type };
		}

		addSortOrderToWeightedNodes("start", 0);

		// Invert the index TODO pretty bad logic.
		var sortedNodeNames = [];
		for(var key in weightedNodes){

			var notAdded = true;
			for(var i = 0; i < sortedNodeNames.length; i++){
				if(weightedNodes[key].sortOrder < sortedNodeNames[i].sortOrder){
					sortedNodeNames.splice(i, 0, {name: key, sortOrder: weightedNodes[key].sortOrder});
					notAdded = false;
					break;
				}
			}

			if(notAdded){
				sortedNodeNames.push({name: key, sortOrder: weightedNodes[key].sortOrder});
			}
		}

		var yPos = 40;
		// Generates svg circles
		for(var i = 0; i < sortedNodeNames.length; i++){
			// how many same sort order there are?
			var sameSortCount = 1
			for(; i + sameSortCount < sortedNodeNames.length ;sameSortCount++){
				if(sortedNodeNames[i].sortOrder != sortedNodeNames[i + sameSortCount].sortOrder){
					break;
				}
			}

			for(var j = 0; j < sameSortCount; j++){
				var node;
				var xPos = (editorWidth/(sameSortCount + 1) * (j+1));
				if(weightedNodes[sortedNodeNames[i + j].name].type == "KILL"){
					node = new wfjs.CircleNode(canvas1, xPos, yPos, sortedNodeNames[i + j].name, { stroke: "red", fill: "red" });
				}else if(weightedNodes[sortedNodeNames[i + j].name].type == "DECISION"){
					node = new wfjs.DiamondNode(canvas1, xPos, yPos, sortedNodeNames[i + j].name);
				}else if(weightedNodes[sortedNodeNames[i + j].name].type == "START" || weightedNodes[sortedNodeNames[i + j].name].type == "END"){
					node = new wfjs.CircleNode(canvas1, xPos, yPos, sortedNodeNames[i + j].name, { stroke: "grey", fill: "grey" });
				}else{
					node = new wfjs.CircleNode(canvas1, xPos, yPos, sortedNodeNames[i + j].name, { stroke: "blue", fill: "yellow" });
				}

				// TODO fix this
				if(node.show !== undefined)
					node.show();

				weightedNodes[sortedNodeNames[i + j].name].node = node;

				if(j > 0){
					i++;
				}
			}

			yPos += 80;

		}

// TODO resize svg

		// Add svg lines
		for(var key in weightedNodes){
			var node = weightedNodes[key];
			for(var i = 0; i < node.to.length; i++){
				node.node.connectTo(weightedNodes[node.to[i]].node);
			}
		}

	}

	function addSortOrderToWeightedNodes(currentKey, parentSortOrder){
		if(weightedNodes[currentKey].sortOrder === undefined){
			weightedNodes[currentKey].sortOrder = (parentSortOrder + 1);
		}
		for(var i = 0; i < weightedNodes[currentKey].to.length; i++){
			addSortOrderToWeightedNodes(weightedNodes[currentKey].to[i], parentSortOrder + 1);
		}
	}

	function drawXmlEditor(xmlArray, lineNumber, columnNumber){
		// Tokenize
		var tokens = [];
		for(var rawLineIndex = 0; rawLineIndex <  xmlArray.length; rawLineIndex++){
			var rawLine = xmlArray[rawLineIndex];
			for(var i = 0; i < rawLine.length; i++){
				var achar = rawLine.charAt(i);
				if(achar == "<"){
					tokens.push({lineNum : rawLineIndex + 1, type: "tagstart", value : "<"});
				}else if(achar == ">"){
					tokens.push({lineNum : rawLineIndex + 1, type: "tagend", value : ">"});
				}else{
					var start = i;
					for(; i < rawLine.length - 1; i++){
						if(rawLine.charAt(i + 1) == "<" || rawLine.charAt(i + 1) == ">")
							break;
					}
					var chunk = rawLine.substring(start, i + 1).replace(/ /g, " ").replace(/\t/g, "    ");
					tokens.push({lineNum : rawLineIndex + 1, type: "elementcontent", value : chunk});
				}
			}
		}

		// Make editor table
		var editor = "
";
		editor += "
";
		editor += "Uploaded XML	";

		var currentLineNum = 0;
		var tokensIndex = 0;
		while(tokensIndex < tokens.length){
			currentLineNum = tokens[tokensIndex].lineNum;
			editor += "
";
			editor += "
";
			// Line Number
			if(currentLineNum == lineNumber){
				editor += "" + (currentLineNum) + "	";
				editor += "";
			}else{
				editor += "" + (currentLineNum) + "	";
				editor += "";
			}

			// Line Content
			while(tokensIndex < tokens.length && currentLineNum == tokens[tokensIndex].lineNum){
				editor += "" + tokens[tokensIndex].value + "";
				tokensIndex++;
			}
			editor += "	";

		}
		editor += "
";

		editor += "
";
		$("#xml_editor_div").html(editor);
	}

	$("#submitButton").click(submitButtonClicked);
	$(window).resize(onWindowResize);

}); // End of JQuery Initialization

<commit_msg>fluctuate xpos<commit_after>$(function() {

	var submitButtonClicked = function(){
		$("#xml_editor_div").html("");
		$("#workflow_diagram").html("");
		$("#xml_editor_pre").html("");
		$("#errorMessage").html("");
		$("#waiting_image").show();

		var formData = new FormData($("#fileform")[0]);
		$.ajax({
			url: vo.contextRoot + "api/upload_xml"
			, type: 'POST'
			, data: formData
			, cache: false
			, contentType: false
			, processData: false
			, complete: function(jqXHR, textStatus){
				var res = $.parseJSON(jqXHR.responseText);
				drawXmlEditor(res.xml, res.lineNumber, res.columnNumber);
				$("#span_identifiedNamespace").html(res.identifiedNamespace);

				if(!res.succeeded){
					$("#errorMessage").html(res.errorMessage);
					return;
				}
				$("#waiting_image").hide();
				drawDiagram(res);

			}
		});
	};

	var onWindowResize = function(){
		var editorHeight = window.innerHeight - $("#workflow_diagram").offset().top;
		$("#xml_editor_div").height(editorHeight);
		$("#workflow_diagram").height(editorHeight);
	};

	var weightedNodes;

	function drawDiagram(res){
		weightedNodes = {};
		var editorWidth = $(document).width() / 2;
		onWindowResize();
		var canvas1 = new wfjs.Canvas("workflow_diagram", editorWidth, 2000);
		var unsortedNodes = res.nodes;

		// Set weightedNodes wihtout sortOrder
		for(var nodeIndex = 0; nodeIndex < unsortedNodes.length; nodeIndex++){
			var node = unsortedNodes[nodeIndex];
			weightedNodes[node.name] = { to : node.to , type: node.type };
		}

		addSortOrderToWeightedNodes("start", 0);

		// Invert the index TODO pretty bad logic.
		var sortedNodeNames = [];
		for(var key in weightedNodes){

			var notAdded = true;
			for(var i = 0; i < sortedNodeNames.length; i++){
				if(weightedNodes[key].sortOrder < sortedNodeNames[i].sortOrder){
					sortedNodeNames.splice(i, 0, {name: key, sortOrder: weightedNodes[key].sortOrder});
					notAdded = false;
					break;
				}
			}

			if(notAdded){
				sortedNodeNames.push({name: key, sortOrder: weightedNodes[key].sortOrder});
			}
		}

		var yPos = 40;
		// Generates svg nodes
		for(var i = 0; i < sortedNodeNames.length; i++){
			// how many same sort order there are?
			var sameSortCount = 1
			for(; i + sameSortCount < sortedNodeNames.length ;sameSortCount++){
				if(sortedNodeNames[i].sortOrder != sortedNodeNames[i + sameSortCount].sortOrder){
					break;
				}
			}

			for(var j = 0; j < sameSortCount; j++){
				var node;
				// Add some random number to fluctuate x-position
				var xPos = (editorWidth/(sameSortCount + 1) * (j+1)) + Math.floor((Math.random()*20)+1);
				if(weightedNodes[sortedNodeNames[i + j].name].type == "KILL"){
					node = new wfjs.CircleNode(canvas1, xPos, yPos, sortedNodeNames[i + j].name, { stroke: "red", fill: "red" });
				}else if(weightedNodes[sortedNodeNames[i + j].name].type == "DECISION"){
					node = new wfjs.DiamondNode(canvas1, xPos, yPos, sortedNodeNames[i + j].name);
				}else if(weightedNodes[sortedNodeNames[i + j].name].type == "START" || weightedNodes[sortedNodeNames[i + j].name].type == "END"){
					node = new wfjs.CircleNode(canvas1, xPos, yPos, sortedNodeNames[i + j].name, { stroke: "grey", fill: "grey" });
				}else{
					node = new wfjs.CircleNode(canvas1, xPos, yPos, sortedNodeNames[i + j].name, { stroke: "blue", fill: "yellow" });
				}

				// TODO fix this
				if(node.show !== undefined)
					node.show();

				weightedNodes[sortedNodeNames[i + j].name].node = node;

				if(j > 0){
					i++;
				}
			}

			yPos += 85;

		}

// TODO resize svg

		// Add svg lines
		for(var key in weightedNodes){
			var node = weightedNodes[key];
			for(var i = 0; i < node.to.length; i++){
				node.node.connectTo(weightedNodes[node.to[i]].node);
			}
		}

	}

	function addSortOrderToWeightedNodes(currentKey, parentSortOrder){
		if(weightedNodes[currentKey].sortOrder === undefined){
			weightedNodes[currentKey].sortOrder = (parentSortOrder + 1);
		}
		for(var i = 0; i < weightedNodes[currentKey].to.length; i++){
			addSortOrderToWeightedNodes(weightedNodes[currentKey].to[i], parentSortOrder + 1);
		}
	}

	function drawXmlEditor(xmlArray, lineNumber, columnNumber){
		// Tokenize
		var tokens = [];
		for(var rawLineIndex = 0; rawLineIndex <  xmlArray.length; rawLineIndex++){
			var rawLine = xmlArray[rawLineIndex];
			for(var i = 0; i < rawLine.length; i++){
				var achar = rawLine.charAt(i);
				if(achar == "<"){
					tokens.push({lineNum : rawLineIndex + 1, type: "tagstart", value : "<"});
				}else if(achar == ">"){
					tokens.push({lineNum : rawLineIndex + 1, type: "tagend", value : ">"});
				}else{
					var start = i;
					for(; i < rawLine.length - 1; i++){
						if(rawLine.charAt(i + 1) == "<" || rawLine.charAt(i + 1) == ">")
							break;
					}
					var chunk = rawLine.substring(start, i + 1).replace(/ /g, " ").replace(/\t/g, "    ");
					tokens.push({lineNum : rawLineIndex + 1, type: "elementcontent", value : chunk});
				}
			}
		}

		// Make editor table
		var editor = "
";
		editor += "
";
		editor += "Uploaded XML	";

		var currentLineNum = 0;
		var tokensIndex = 0;
		while(tokensIndex < tokens.length){
			currentLineNum = tokens[tokensIndex].lineNum;
			editor += "
";
			editor += "
";
			// Line Number
			if(currentLineNum == lineNumber){
				editor += "" + (currentLineNum) + "	";
				editor += "";
			}else{
				editor += "" + (currentLineNum) + "	";
				editor += "";
			}

			// Line Content
			while(tokensIndex < tokens.length && currentLineNum == tokens[tokensIndex].lineNum){
				editor += "" + tokens[tokensIndex].value + "";
				tokensIndex++;
			}
			editor += "	";

		}
		editor += "
";

		editor += "
";
		$("#xml_editor_div").html(editor);
	}

	$("#submitButton").click(submitButtonClicked);
	$(window).resize(onWindowResize);

}); // End of JQuery Initialization

<|endoftext|>


<commit_before>import 'react-native';

import Database from '../';

it('addAll', () => {
  var db = new Database();
  db.switchDb('mongrov', 'test');
  // lets reset the db
  db.reset();
  db.remotefiles.addAll(null);
  expect(db.remotefiles.list).toHaveLength(0);
  db.remotefiles.addAll({});
  expect(db.remotefiles.list).toHaveLength(0);
  db.remotefiles.deleteAll();
  const objs = {
    1: 'https://mongrov.redflock.net/group/idc',
    abc: 'https://mongrov.redflock.net',
    xyz: 'https://www.google.com',
    4: 'https://www.gmail.com',
    5: null,
  };
  db.remotefiles.addAll(objs);
  expect(db.remotefiles.list).toHaveLength(5);
  db.remotefiles.findById(null);
  db.remotefiles.findById('xyz');
  db.remotefiles.deleteAll();
});
<commit_msg> refractor remote file manager<commit_after>import 'react-native';

import Database from '../';

it('addAll', () => {
  var db = new Database();
  db.switchDb('mongrov', 'test');
  // lets reset the db
  db.reset();
  db.remotefiles.addAll(null);
  expect(db.remotefiles.list).toHaveLength(0);
  db.remotefiles.addAll({});
  expect(db.remotefiles.list).toHaveLength(0);
  expect(db.remotefiles.cacheList).toMatchObject({});
  db.remotefiles.deleteAll();
  let objs = {
    1: 'https://mongrov.redflock.net/group/idc',
    abc: 'https://mongrov.redflock.net',
    xyz: 'https://www.google.com',
    4: 'https://www.gmail.com',
    5: null,
  };
  db.remotefiles.addAll(objs);
  expect(db.remotefiles.list).toHaveLength(5);

  // null value will be replaced by empty string
  objs = {
    1: 'https://mongrov.redflock.net/group/idc',
    abc: 'https://mongrov.redflock.net',
    xyz: 'https://www.google.com',
    4: 'https://www.gmail.com',
    5: '',
  };
  expect(db.remotefiles.cacheList).toMatchObject(objs);
  expect(db.remotefiles.findById('xyz')).not.toBeNull();
  // try to search id which is not present
  expect(db.remotefiles.findById(null)).toBeNull();
  expect(db.remotefiles.findById('lmn')).toBeNull();
  db.remotefiles.deleteAll();
});

it('cacheList', () => {
  var db = new Database();
  db.switchDb('mongrov', 'test');
  // lets reset the db
  db.reset();
  // initial it should be empty
  expect(db.remotefiles.cacheList).toMatchObject({});

  // after populated cachelist should have the same
  const objs = {
    1: 'https://mongrov.redflock.net/group/idc',
    abc: 'https://mongrov.redflock.net',
    xyz: 'https://www.google.com',
    4: 'https://www.gmail.com',
    5: '',
  };
  db.remotefiles.addAll(objs);
  expect(db.remotefiles.cacheList).toMatchObject(objs);
});
<|endoftext|>