<commit_before>/*globals define, console*/
/**
 * @author nabana / https://github.com/nabana
 * @author lattmann / https://github.com/lattmann
 */

define([
    'js/Dialogs/Projects/ProjectsDialog',
    'js/Dialogs/Commit/CommitDialog',
    'js/Dialogs/ProjectRepository/ProjectRepositoryDialog'], function (
    ProjectsDialog,
    CommitDialog,
    ProjectRepositoryDialog
) {
    "use strict";

    var ProjectNavigatorController = function ($scope, gmeClient) {

        var self = this;

        self.$scope = $scope;
        self.gmeClient = gmeClient;

        // internal data representation for fast access to objects
        self.projects = {};
        self.root = {
            id: 'root',
            label: 'GME',
//            isSelected: true,
            itemClass: 'gme-root',
            menu: []
        };

        // navigation items in the navigator list
        self.navIdRoot = 0;
        self.navIdProject = 1;
        self.navIdBranch = 2;

        self.initialize();
    };

    ProjectNavigatorController.prototype.update = function () {
        if (!this.$scope.$$phase) {
            this.$scope.$apply();
        }
    };

    ProjectNavigatorController.prototype.initialize = function () {
        var self = this,
            newProject;

        // initialize model structure for view
        self.$scope.navigator = {
            items: [],
            separator: true
        };

        if (self.gmeClient) {
            self.initWithClient();

            newProject = function (data) {
                var pd = new ProjectsDialog(self.gmeClient);
                pd.show();
            };

        } else {
            self.initTestData();

            newProject = function (data) {
                self.addProject('New project ' + Math.floor(Math.random() * 10000));
            };
        }

        // initialize root menu
        // projects section is mandatory
        self.root.menu = [
            {
                section: 'top',
                items: [
                    {
                        id: 'newProkect',
                        label: 'New project ...',
                        iconClass: 'glyphicon glyphicon-plus',
                        action: newProject,
                        actionData: {}
                    },
                    {
                        id: 'importProject',
                        label: 'Import project ...',
                        iconClass: 'glyphicon glyphicon-import',
                        action: newProject,
                        actionData: {}
                    }
                ]
            },
            {
                section: 'projects',
                items: [],
                showAllItems: function () {
                    console.log('Show all items...');
                }
            },
            {
                section: 'preferences',
                items: [
                    {
                        id: 'showPreferences',
                        label: 'Show preferences',
                        action: function () {
                            console.log('Show preferences');
                        },
                        menu: [
                            {
                                items: [
                                    {
                                        id: 'preferences 1',
                                        label: 'Preferences 1'
                                    },
                                    {
                                        id: 'preferences 2',
                                        label: 'Preferences 2'
                                    },
                                    {
                                        id: 'preferences 3',
                                        label: 'Preferences 3',
                                        menu: [
                                            {
                                                items: [
                                                    {
                                                        id: 'sub_preferences 1',
                                                        label: 'Sub preferences 1'
                                                    },
                                                    {
                                                        id: 'sub_preferences 2',
                                                        label: 'Sub preferences 2'
                                                    }
                                                ]
                                            }
                                        ]
                                    }
                                ]
                            }
                        ]
                    }
                ]

            }
        ];

        // only root is selected by default
        self.$scope.navigator = {
            items: [
                self.root
            ],
            separator: true
        };
    };

    ProjectNavigatorController.prototype.initTestData = function () {
        var self = this;

        self.dummyProjectsGenerator('Project', 10);

        // debug
        console.log(self.$scope.items);

        self.update();
    };

    ProjectNavigatorController.prototype.initWithClient = function () {
        var self = this;

        // register all event listeners on gmeClient
        self.gmeClient.addEventListener("PROJECT_OPENED", function (client, projectId) {
            self.selectProject({projectId: projectId});
            self.updateBranchList(projectId);
        });

        self.gmeClient.addEventListener("PROJECT_CLOESED", function (client, projectId) {
            self.selectProject({});
        });

        self.gmeClient.addEventListener("SERVER_PROJECT_CREATED", function (client, projectId) {
            console.log('SERVER_PROJECT_CREATED', projectId);
            self.addProject(projectId);
        });

        self.gmeClient.addEventListener("SERVER_PROJECT_DELETED", function (client, projectId) {
            console.log('SERVER_PROJECT_DELETED', projectId);
            self.removeProject(projectId);
        });

        self.gmeClient.addEventListener("BRANCH_CHANGED", function (client, branchId) {
            self.selectBranch({projectId: self.gmeClient.getActiveProjectName(), branchId: branchId});
        });

        self.gmeClient.addEventListener("SERVER_BRANCH_CREATED", function (client, parameters) {
            console.log('SERVER_BRANCH_CREATED', parameters);
            self.addBranch(parameters.project, parameters.branch);
        });

        self.gmeClient.addEventListener("SERVER_BRANCH_UPDATED", function (client, parameters) {
            console.log('SERVER_BRANCH_UPDATED', parameters);
            // TODO: update branch information
        });

        self.gmeClient.addEventListener("SERVER_BRANCH_DELETED", function (client, parameters) {
            console.log('SERVER_BRANCH_DELETED', parameters);
            self.removeBranch(parameters.project, parameters.branch);
        });

        // get project list
        self.updateProjectList();
    };

    ProjectNavigatorController.prototype.updateProjectList = function () {
        var self = this;

        // FIXME: get read=only/viewable/available project?!
        self.gmeClient.getFullProjectListAsync(function (err, projectList) {
            var projectId;

            if (err) {
                console.error(err);
                return;
            }

            // clear project list
            self.projects = {};

            for (projectId in projectList) {
                if (projectList.hasOwnProperty(projectId)) {
                    self.addProject(projectId);
                }
            }
        });
    };

    ProjectNavigatorController.prototype.updateBranchList = function (projectId) {
        var self = this,
            i;

        if (projectId === self.gmeClient.getActiveProjectName()) {
            // FIXME: can we get branches for the a given project???
            self.gmeClient.getBranchesAsync(function (err, branchList) {
                if (err) {
                    console.error(err);
                    return;
                }

                // clear branches list
                self.projects[projectId].branches = [];

                for (i = 0; i < branchList.length; i += 1) {
                    self.addBranch(projectId, branchList[i].name);
                }
            });
        }
    };

    ProjectNavigatorController.prototype.addProject = function (projectId) {
        var self = this,
            i,
            showHistory,
            showAllBranches,
            selectProject;

        if (self.gmeClient) {
            showHistory = function (data) {
                var prd;
                if (self.gmeClient.getActiveProjectName() === data.projectId) {
                    prd = new ProjectRepositoryDialog(self.gmeClient);
                    prd.show();
                } else {
                    self.selectProject({projectId: projectId}, function (err) {
                        if (err) {
                            // TODO: handle errors
                            return;
                        };

                        var dialog = new ProjectRepositoryDialog(self.gmeClient);
                        dialog.show();
                    });
                }
            };

            showAllBranches = function (data) {
                console.error('showAllBranches: gmeClient version is not implemented yet.', data);
            };
        } else {
            // test version
            showHistory = function (data) {
                console.log('showHistory: ', data);
            };

            showAllBranches = function (data) {
                console.log('showAllBranches: ', data);
            };
        }

        selectProject = function (data) {
            self.selectProject(data);
        };

        // create a new project object
        self.projects[projectId] = {
            id: projectId,
            label: projectId,
            //isSelected: i === selectedItem,
            branches: {},
            action: selectProject,
            actionData: {
                projectId: projectId
            },
            menu: [
                {
                    section: 'top',
                    items: [
                        {
                            id: 'showHistory',
                            label: 'Show history',
                            iconClass: 'glyphicon glyphicon-time',
                            action: showHistory,
                            actionData: {
                                projectId: projectId
                            }
                        }

                    ]
                },
                {
                    section: 'branches',
                    items: [],
                    showAllItems: showAllBranches
                }
            ]
        };

        if (self.gmeClient) {
            self.updateBranchList(projectId);
        } else {
            self.dummyBranchGenerator('Branch', 10, projectId);
        }

        for (i = 0; i < self.root.menu.length; i += 1) {

            // find the projects section in the menu items
            if (self.root.menu[i].section === 'projects') {

                // convert indexed projects to an array
                self.root.menu[i].items = self.mapToArray(self.projects);
                break;
            }
        }

        self.update();
    };

    ProjectNavigatorController.prototype.addBranch = function (projectId, branchId) {
        var self = this,
            i,
            selectBranch,
            exportBranch,
            createCommitMessage;

        if (self.gmeClient) {
            exportBranch = function (data) {
                var url = self.gmeClient.getDumpURL({
                    project: data.projectId,
                    branch: data.branchId,
                    output: data.projectId + '_' + data.branchId
                });

                if (url) {
                    window.location = url;
                } else {
                    console.error('Failed to get project dump url for ', data);
                }
            };

            createCommitMessage = function (data) {
                self.selectBranch(data, function (err) {
                    var cd;

                    if (err) {
                       // TODO: log error
                       return;
                    }

                    cd = new CommitDialog(self.gmeClient);
                    cd.show();
                });
            };
        } else {
            // test version
            exportBranch = function (data) {
                console.log('exportBranch: ', data);
            };

            createCommitMessage = function (data) {
                console.log('createCommitMessage: ', data);
            };
        }

        selectBranch = function (data) {
            self.selectBranch(data);
        };

        // create the new branch structure
        self.projects[projectId].branches[branchId] = {
            id: branchId,
            label: branchId,
            properties: {
                hashTag: '34535435',
                lastCommiter: 'petike',
                lastCommitTime: new Date()
            },
            action: selectBranch,
            actionData: {
                projectId: projectId,
                branchId: branchId
            },
            //itemTemplate: 'branch-selector-template',
            menu: [
                {
                    items: [
                        {
                            id: 'exportBranch',
                            label: 'Export branch',
                            iconClass: 'glyphicon glyphicon-export',
                            action: exportBranch,
                            actionData: {
                                projectId: projectId,
                                branchId: branchId
                            }
                        },
                        {
                            id: 'createCommitMessage',
                            label: 'Create commit message',
                            iconClass: 'glyphicon glyphicon-tag',
                            action: createCommitMessage,
                            actionData: {
                                projectId: projectId,
                                branchId: branchId
                            }
                        }
                    ]

                }
            ]
        };

        for (i = 0; i < self.projects[projectId].menu.length; i += 1) {

            // find the branches section in the menu items
            if (self.projects[projectId].menu[i].section === 'branches') {

                // convert indexed branches to an array
                self.projects[projectId].menu[i].items = self.mapToArray(self.projects[projectId].branches);
                break;
            }
        }

        self.update();
    };

    ProjectNavigatorController.prototype.removeProject = function (projectId, callback) {
        var self = this,
            i;

        if (self.projects.hasOwnProperty(projectId)) {
            delete self.projects[projectId];

            for (i = 0; i < self.root.menu.length; i += 1) {

                // find the projects section in the menu items
                if (self.root.menu[i].section === 'projects') {

                    // convert indexed projects to an array
                    self.root.menu[i].items = self.mapToArray(self.projects);
                    break;
                }
            }

            self.update();
        }
    };

    ProjectNavigatorController.prototype.removeBranch = function (projectId, branchId) {
        var self = this,
            i;

        if (self.projects.hasOwnProperty(projectId) && self.projects[projectId].branches.hasOwnProperty(branchId)) {
            delete self.projects[projectId].branches[branchId];

            for (i = 0; i < self.projects[projectId].menu.length; i += 1) {

                // find the branches section in the menu items
                if (self.projects[projectId].menu[i].section === 'branches') {

                    // convert indexed branches to an array
                    self.projects[projectId].menu[i].items = self.mapToArray(self.projects[projectId].branches);
                    break;
                }
            }

            self.update();
        }
    };

    ProjectNavigatorController.prototype.selectProject = function (data, callback) {
        this.selectBranch(data, callback);
    };

    ProjectNavigatorController.prototype.selectBranch = function (data, callback) {
        var self = this,
            projectId = data.projectId,
            branchId = data.branchId;

        callback = callback || function () {};

        if (projectId || projectId === '') {
            // FIXME: what if projects do not contain projectId anymore?
            self.$scope.navigator.items[self.navIdProject] = self.projects[projectId];

            if (self.gmeClient) {
                if (projectId !== self.gmeClient.getActiveProjectName()) {
                    self.gmeClient.selectProjectAsync(projectId, function (err) {
                        if (err) {
                            console.log(err);
                            callback(err);
                            return;
                        }

                        if (branchId && branchId !== self.gmeClient.getActualBranch()) {
                            self.gmeClient.selectBranchAsync(branchId, function (err) {
                                if (err) {
                                    console.log(err);
                                    callback(err);
                                    return;
                                }

                                callback(null);
                            });
                        } else {
                            callback(null);
                        }
                    });

                    // we cannot select branch if the project is not open
                    // we will get a project open event
                    return;
                }
            }

            if (branchId || branchId === '') {
                // set selected branch
                self.$scope.navigator.items[self.navIdBranch] = self.projects[projectId].branches[branchId];

                if (self.gmeClient) {
                    if (branchId !== self.gmeClient.getActualBranch()) {
                        self.gmeClient.selectBranchAsync(branchId, function (err) {
                            if (err) {
                                console.log(err);
                                callback(err);
                                return;
                            }

                            callback(null);
                        });

                        // we will get a branch status changed event
                        return;
                    }
                }
            } else {
                // remove branch element
                self.$scope.navigator.items.splice(self.navIdBranch, 1);
            }
        } else {
            // remove project and branch elements
            self.$scope.navigator.items.splice(self.navIdProject, 2);
        }

        callback(null);
        self.update();
    };

    ProjectNavigatorController.prototype.dummyProjectsGenerator = function (name, maxCount) {
        var self = this,
            i,
            id,
            count;

        count = Math.max(Math.round(Math.random() * maxCount), 3);

        for (i = 0; i < count; i += 1) {
            id = name + '_' + i;
            self.addProject(id);
        }
    };

    ProjectNavigatorController.prototype.dummyBranchGenerator = function (name, maxCount, projectId) {
        var self = this,
            i,
            id,
            count;

        count = Math.max(Math.round(Math.random() * maxCount), 3);

        for (i = 0; i < count; i += 1) {
            id = name + '_' + i;
            self.addBranch(projectId, id);
        }
    };

    ProjectNavigatorController.prototype.mapToArray = function (hashMap) {
        var keys = Object.keys(hashMap),
            values = keys.map(function (v) { return hashMap[v]; });

        return values;
    };

    return ProjectNavigatorController;
});
<commit_msg>Implement delete project.<commit_after>/*globals define, console*/
/**
 * @author nabana / https://github.com/nabana
 * @author lattmann / https://github.com/lattmann
 */

define([
    'js/Dialogs/Projects/ProjectsDialog',
    'js/Dialogs/Commit/CommitDialog',
    'js/Dialogs/ProjectRepository/ProjectRepositoryDialog'], function (
    ProjectsDialog,
    CommitDialog,
    ProjectRepositoryDialog
) {
    "use strict";

    var ProjectNavigatorController = function ($scope, gmeClient) {

        var self = this;

        self.$scope = $scope;
        self.gmeClient = gmeClient;

        // internal data representation for fast access to objects
        self.projects = {};
        self.root = {
            id: 'root',
            label: 'GME',
//            isSelected: true,
            itemClass: 'gme-root',
            menu: []
        };

        // navigation items in the navigator list
        self.navIdRoot = 0;
        self.navIdProject = 1;
        self.navIdBranch = 2;

        self.initialize();
    };

    ProjectNavigatorController.prototype.update = function () {
        if (!this.$scope.$$phase) {
            this.$scope.$apply();
        }
    };

    ProjectNavigatorController.prototype.initialize = function () {
        var self = this,
            newProject;

        // initialize model structure for view
        self.$scope.navigator = {
            items: [],
            separator: true
        };

        if (self.gmeClient) {
            self.initWithClient();

            newProject = function (data) {
                var pd = new ProjectsDialog(self.gmeClient);
                pd.show();
            };

        } else {
            self.initTestData();

            newProject = function (data) {
                self.addProject('New project ' + Math.floor(Math.random() * 10000));
            };
        }

        // initialize root menu
        // projects section is mandatory
        self.root.menu = [
            {
                section: 'top',
                items: [
                    {
                        id: 'newProkect',
                        label: 'New project ...',
                        iconClass: 'glyphicon glyphicon-plus',
                        action: newProject,
                        actionData: {}
                    },
                    {
                        id: 'importProject',
                        label: 'Import project ...',
                        iconClass: 'glyphicon glyphicon-import',
                        action: newProject,
                        actionData: {}
                    }
                ]
            },
            {
                section: 'projects',
                items: [],
                showAllItems: function () {
                    console.log('Show all items...');
                }
            },
            {
                section: 'preferences',
                items: [
                    {
                        id: 'showPreferences',
                        label: 'Show preferences',
                        action: function () {
                            console.log('Show preferences');
                        },
                        menu: [
                            {
                                items: [
                                    {
                                        id: 'preferences 1',
                                        label: 'Preferences 1'
                                    },
                                    {
                                        id: 'preferences 2',
                                        label: 'Preferences 2'
                                    },
                                    {
                                        id: 'preferences 3',
                                        label: 'Preferences 3',
                                        menu: [
                                            {
                                                items: [
                                                    {
                                                        id: 'sub_preferences 1',
                                                        label: 'Sub preferences 1'
                                                    },
                                                    {
                                                        id: 'sub_preferences 2',
                                                        label: 'Sub preferences 2'
                                                    }
                                                ]
                                            }
                                        ]
                                    }
                                ]
                            }
                        ]
                    }
                ]

            }
        ];

        // only root is selected by default
        self.$scope.navigator = {
            items: [
                self.root
            ],
            separator: true
        };
    };

    ProjectNavigatorController.prototype.initTestData = function () {
        var self = this;

        self.dummyProjectsGenerator('Project', 10);

        // debug
        console.log(self.$scope.items);

        self.update();
    };

    ProjectNavigatorController.prototype.initWithClient = function () {
        var self = this;

        // register all event listeners on gmeClient
        self.gmeClient.addEventListener("PROJECT_OPENED", function (client, projectId) {
            self.selectProject({projectId: projectId});
            self.updateBranchList(projectId);
        });

        self.gmeClient.addEventListener("PROJECT_CLOESED", function (client, projectId) {
            self.selectProject({});
        });

        self.gmeClient.addEventListener("SERVER_PROJECT_CREATED", function (client, projectId) {
            console.log('SERVER_PROJECT_CREATED', projectId);
            self.addProject(projectId);
        });

        self.gmeClient.addEventListener("SERVER_PROJECT_DELETED", function (client, projectId) {
            console.log('SERVER_PROJECT_DELETED', projectId);
            self.removeProject(projectId);
        });

        self.gmeClient.addEventListener("BRANCH_CHANGED", function (client, branchId) {
            self.selectBranch({projectId: self.gmeClient.getActiveProjectName(), branchId: branchId});
        });

        self.gmeClient.addEventListener("SERVER_BRANCH_CREATED", function (client, parameters) {
            console.log('SERVER_BRANCH_CREATED', parameters);
            self.addBranch(parameters.project, parameters.branch);
        });

        self.gmeClient.addEventListener("SERVER_BRANCH_UPDATED", function (client, parameters) {
            console.log('SERVER_BRANCH_UPDATED', parameters);
            // TODO: update branch information
        });

        self.gmeClient.addEventListener("SERVER_BRANCH_DELETED", function (client, parameters) {
            console.log('SERVER_BRANCH_DELETED', parameters);
            self.removeBranch(parameters.project, parameters.branch);
        });

        // get project list
        self.updateProjectList();
    };

    ProjectNavigatorController.prototype.updateProjectList = function () {
        var self = this;

        // FIXME: get read=only/viewable/available project?!
        self.gmeClient.getFullProjectListAsync(function (err, projectList) {
            var projectId;

            if (err) {
                console.error(err);
                return;
            }

            // clear project list
            self.projects = {};

            for (projectId in projectList) {
                if (projectList.hasOwnProperty(projectId)) {
                    self.addProject(projectId);
                }
            }
        });
    };

    ProjectNavigatorController.prototype.updateBranchList = function (projectId) {
        var self = this,
            i;

        if (projectId === self.gmeClient.getActiveProjectName()) {
            // FIXME: can we get branches for the a given project???
            self.gmeClient.getBranchesAsync(function (err, branchList) {
                if (err) {
                    console.error(err);
                    return;
                }

                // clear branches list
                self.projects[projectId].branches = [];

                for (i = 0; i < branchList.length; i += 1) {
                    self.addBranch(projectId, branchList[i].name);
                }
            });
        }
    };

    ProjectNavigatorController.prototype.addProject = function (projectId) {
        var self = this,
            i,
            showHistory,
            showAllBranches,
            deleteProject,
            selectProject;

        if (self.gmeClient) {
            showHistory = function (data) {
                var prd;
                if (self.gmeClient.getActiveProjectName() === data.projectId) {
                    prd = new ProjectRepositoryDialog(self.gmeClient);
                    prd.show();
                } else {
                    self.selectProject({projectId: projectId}, function (err) {
                        if (err) {
                            // TODO: handle errors
                            return;
                        };

                        var dialog = new ProjectRepositoryDialog(self.gmeClient);
                        dialog.show();
                    });
                }
            };

            deleteProject =  function (data) {
                self.gmeClient.deleteProjectAsync(data.projectId, function (err) {
                    if (err) {
                        console.error(err);
                        return;
                    }
                });
            };

            showAllBranches = function (data) {
                console.error('showAllBranches: gmeClient version is not implemented yet.', data);
            };
        } else {
            // test version
            showHistory = function (data) {
                console.log('showHistory: ', data);
            };

            deleteProject =  function (data) {
                self.removeProject(data.projectId);
            };

            showAllBranches = function (data) {
                console.log('showAllBranches: ', data);
            };
        }

        selectProject = function (data) {
            self.selectProject(data);
        };

        // create a new project object
        self.projects[projectId] = {
            id: projectId,
            label: projectId,
            //isSelected: i === selectedItem,
            branches: {},
            action: selectProject,
            actionData: {
                projectId: projectId
            },
            menu: [
                {
                    section: 'top',
                    items: [
                        {
                            id: 'deleteProject',
                            label: 'Delete project',
                            iconClass: 'glyphicon glyphicon-remove',
                            action: deleteProject,
                            actionData: {
                                projectId: projectId
                            }
                        },
                        {
                            id: 'showHistory',
                            label: 'Show history',
                            iconClass: 'glyphicon glyphicon-time',
                            action: showHistory,
                            actionData: {
                                projectId: projectId
                            }
                        }

                    ]
                },
                {
                    section: 'branches',
                    items: [],
                    showAllItems: showAllBranches
                }
            ]
        };

        if (self.gmeClient) {
            self.updateBranchList(projectId);
        } else {
            self.dummyBranchGenerator('Branch', 10, projectId);
        }

        for (i = 0; i < self.root.menu.length; i += 1) {

            // find the projects section in the menu items
            if (self.root.menu[i].section === 'projects') {

                // convert indexed projects to an array
                self.root.menu[i].items = self.mapToArray(self.projects);
                break;
            }
        }

        self.update();
    };

    ProjectNavigatorController.prototype.addBranch = function (projectId, branchId) {
        var self = this,
            i,
            selectBranch,
            exportBranch,
            createBranch,
            deleteBranch,
            createCommitMessage;

        if (self.gmeClient) {
            exportBranch = function (data) {
                var url = self.gmeClient.getDumpURL({
                    project: data.projectId,
                    branch: data.branchId,
                    output: data.projectId + '_' + data.branchId
                });

                if (url) {
                    window.location = url;
                } else {
                    console.error('Failed to get project dump url for ', data);
                }
            };

            createBranch = function (data) {
                console.error('createBranch: not implemented yet', data);
            };

            deleteBranch = function (data) {
                console.error('deleteBranch: not implemented yet', data);
            };

            createCommitMessage = function (data) {
                self.selectBranch(data, function (err) {
                    var cd;

                    if (err) {
                       // TODO: log error
                       return;
                    }

                    cd = new CommitDialog(self.gmeClient);
                    cd.show();
                });
            };
        } else {
            // test version
            exportBranch = function (data) {
                console.log('exportBranch: ', data);
            };

            createBranch = function (data) {
                console.log('createBranch: ', data);
                self.addBranch(data.projectId, data.branchId + ' _copy');
                self.selectProject({projectId: data.projectId, branchId: data.branchId + '_copy'});
            };

            deleteBranch = function (data) {
                self.removeBranch(data.projectId, data.branchId);
                self.selectProject(data);
            };

            createCommitMessage = function (data) {
                console.log('createCommitMessage: ', data);
            };
        }

        selectBranch = function (data) {
            self.selectBranch(data);
        };

        // create the new branch structure
        self.projects[projectId].branches[branchId] = {
            id: branchId,
            label: branchId,
            properties: {
                hashTag: '34535435',
                lastCommiter: 'petike',
                lastCommitTime: new Date()
            },
            action: selectBranch,
            actionData: {
                projectId: projectId,
                branchId: branchId
            },
            //itemTemplate: 'branch-selector-template',
            menu: [
                {
                    items: [
                        {
                            id: 'createBranch',
                            label: 'Create branch',
                            iconClass: 'glyphicon glyphicon-plus',
                            action: createBranch,
                            actionData: {
                                projectId: projectId,
                                branchId: branchId
                            }
                        },
                        {
                            id: 'deleteBranch',
                            label: 'Delete branch',
                            iconClass: 'glyphicon glyphicon-remove',
                            action: deleteBranch,
                            actionData: {
                                projectId: projectId,
                                branchId: branchId
                            }
                        },
                        {
                            id: 'exportBranch',
                            label: 'Export branch',
                            iconClass: 'glyphicon glyphicon-export',
                            action: exportBranch,
                            actionData: {
                                projectId: projectId,
                                branchId: branchId
                            }
                        },
                        {
                            id: 'createCommitMessage',
                            label: 'Create commit message',
                            iconClass: 'glyphicon glyphicon-tag',
                            action: createCommitMessage,
                            actionData: {
                                projectId: projectId,
                                branchId: branchId
                            }
                        }
                    ]

                }
            ]
        };

        for (i = 0; i < self.projects[projectId].menu.length; i += 1) {

            // find the branches section in the menu items
            if (self.projects[projectId].menu[i].section === 'branches') {

                // convert indexed branches to an array
                self.projects[projectId].menu[i].items = self.mapToArray(self.projects[projectId].branches);
                break;
            }
        }

        self.update();
    };

    ProjectNavigatorController.prototype.removeProject = function (projectId, callback) {
        var self = this,
            i;

        if (self.projects.hasOwnProperty(projectId)) {
            delete self.projects[projectId];

            for (i = 0; i < self.root.menu.length; i += 1) {

                // find the projects section in the menu items
                if (self.root.menu[i].section === 'projects') {

                    // convert indexed projects to an array
                    self.root.menu[i].items = self.mapToArray(self.projects);
                    break;
                }
            }

            self.selectProject({});

            self.update();
        }
    };

    ProjectNavigatorController.prototype.removeBranch = function (projectId, branchId) {
        var self = this,
            i;

        if (self.projects.hasOwnProperty(projectId) && self.projects[projectId].branches.hasOwnProperty(branchId)) {
            delete self.projects[projectId].branches[branchId];

            for (i = 0; i < self.projects[projectId].menu.length; i += 1) {

                // find the branches section in the menu items
                if (self.projects[projectId].menu[i].section === 'branches') {

                    // convert indexed branches to an array
                    self.projects[projectId].menu[i].items = self.mapToArray(self.projects[projectId].branches);
                    break;
                }
            }

            self.selectProject({projectId: projectId});

            self.update();
        }
    };

    ProjectNavigatorController.prototype.selectProject = function (data, callback) {
        this.selectBranch(data, callback);
    };

    ProjectNavigatorController.prototype.selectBranch = function (data, callback) {
        var self = this,
            projectId = data.projectId,
            branchId = data.branchId;

        callback = callback || function () {};

        if (projectId || projectId === '') {
            // FIXME: what if projects do not contain projectId anymore?
            self.$scope.navigator.items[self.navIdProject] = self.projects[projectId];

            if (self.gmeClient) {
                if (projectId !== self.gmeClient.getActiveProjectName()) {
                    self.gmeClient.selectProjectAsync(projectId, function (err) {
                        if (err) {
                            console.log(err);
                            callback(err);
                            return;
                        }

                        if (branchId && branchId !== self.gmeClient.getActualBranch()) {
                            self.gmeClient.selectBranchAsync(branchId, function (err) {
                                if (err) {
                                    console.log(err);
                                    callback(err);
                                    return;
                                }

                                callback(null);
                            });
                        } else {
                            callback(null);
                        }
                    });

                    // we cannot select branch if the project is not open
                    // we will get a project open event
                    return;
                }
            }

            if (branchId || branchId === '') {
                // set selected branch
                self.$scope.navigator.items[self.navIdBranch] = self.projects[projectId].branches[branchId];

                if (self.gmeClient) {
                    if (branchId !== self.gmeClient.getActualBranch()) {
                        self.gmeClient.selectBranchAsync(branchId, function (err) {
                            if (err) {
                                console.log(err);
                                callback(err);
                                return;
                            }

                            callback(null);
                        });

                        // we will get a branch status changed event
                        return;
                    }
                }
            } else {
                // remove branch element
                self.$scope.navigator.items.splice(self.navIdBranch, 1);
            }
        } else {
            // remove project and branch elements
            self.$scope.navigator.items.splice(self.navIdProject, 2);
        }

        callback(null);
        self.update();
    };

    ProjectNavigatorController.prototype.dummyProjectsGenerator = function (name, maxCount) {
        var self = this,
            i,
            id,
            count;

        count = Math.max(Math.round(Math.random() * maxCount), 3);

        for (i = 0; i < count; i += 1) {
            id = name + '_' + i;
            self.addProject(id);
        }
    };

    ProjectNavigatorController.prototype.dummyBranchGenerator = function (name, maxCount, projectId) {
        var self = this,
            i,
            id,
            count;

        count = Math.max(Math.round(Math.random() * maxCount), 3);

        for (i = 0; i < count; i += 1) {
            id = name + '_' + i;
            self.addBranch(projectId, id);
        }
    };

    ProjectNavigatorController.prototype.mapToArray = function (hashMap) {
        var keys = Object.keys(hashMap),
            values = keys.map(function (v) { return hashMap[v]; });

        return values;
    };

    return ProjectNavigatorController;
});
<|endoftext|>


<commit_before>import AjaxClient from "../../../js/utils/AjaxClient";
import { newsBoardSourceTypes } from "./../../utils/Constants";

export const PAGINATED_FETCHED_FEEDS = "PAGINATED_FETCHED_FEEDS";
export const NEWSBOARD_CURRENT_TAB = "NEWSBOARD_CURRENT_TAB";
export const CLEAR_NEWS_BOARD_FEEDS = "CLEAR_NEWS_BOARD_FEEDS";

export const paginatedFeeds = feeds => ({
    "type": PAGINATED_FETCHED_FEEDS, feeds
});

export const newsBoardTabSwitch = currentTab => ({
    "type": NEWSBOARD_CURRENT_TAB, currentTab
});

export const clearFeeds = () => ({
    "type": CLEAR_NEWS_BOARD_FEEDS
});

export function displayFeedsByPage(pageIndex, sourceType, callback = () => {}) {
    let ajax = AjaxClient.instance("/fetch-all-feeds", true);
    const headers = {
        "Accept": "application/json",
        "Content-Type": "application/json"
    };
    return async dispatch => {
        try {
            let feeds = await ajax.post(headers, { "offset": pageIndex, "sourceType": handleSourceType(sourceType) });
            let result = {
                "docsLength": 0
            };
            if (feeds.docs.length > 0) { //eslint-disable-line no-magic-numbers
                dispatch(paginatedFeeds(feeds.docs));
                result.docsLength = feeds.docs.length;
            }
            let defaultPageSize = 25;
            result.hasMoreFeeds = feeds.docs.length === defaultPageSize;
            callback(result); //eslint-disable-line callback-return
        } catch(err) {
            dispatch(paginatedFeeds([]));
        }
    };
}

function handleSourceType(sourceType) {
    switch (sourceType) {
    case newsBoardSourceTypes.trending:
        return newsBoardSourceTypes.trending;
    case newsBoardSourceTypes.web:
        return newsBoardSourceTypes.web;
    case newsBoardSourceTypes.facebook:
        return newsBoardSourceTypes.facebook;
    case newsBoardSourceTypes.twitter:
        return newsBoardSourceTypes.twitter;
    default:
        return "";
    }
}
<commit_msg>[Dur/SSL] removed sourcetype validation on client side<commit_after>import AjaxClient from "../../../js/utils/AjaxClient";

export const PAGINATED_FETCHED_FEEDS = "PAGINATED_FETCHED_FEEDS";
export const NEWSBOARD_CURRENT_TAB = "NEWSBOARD_CURRENT_TAB";
export const CLEAR_NEWS_BOARD_FEEDS = "CLEAR_NEWS_BOARD_FEEDS";

export const paginatedFeeds = feeds => ({
    "type": PAGINATED_FETCHED_FEEDS, feeds
});

export const newsBoardTabSwitch = currentTab => ({
    "type": NEWSBOARD_CURRENT_TAB, currentTab
});

export const clearFeeds = () => ({
    "type": CLEAR_NEWS_BOARD_FEEDS
});

export function displayFeedsByPage(pageIndex, sourceType, callback = () => {}) {
    let ajax = AjaxClient.instance("/fetch-all-feeds", true);
    const headers = {
        "Accept": "application/json",
        "Content-Type": "application/json"
    };
    return async dispatch => {
        try {
            let feeds = await ajax.post(headers, { "offset": pageIndex, "sourceType": sourceType });
            let result = {
                "docsLength": 0
            };
            if (feeds.docs.length > 0) { //eslint-disable-line no-magic-numbers
                dispatch(paginatedFeeds(feeds.docs));
                result.docsLength = feeds.docs.length;
            }
            let defaultPageSize = 25;
            result.hasMoreFeeds = feeds.docs.length === defaultPageSize;
            callback(result); //eslint-disable-line callback-return
        } catch(err) {
            dispatch(paginatedFeeds([]));
        }
    };
}

<|endoftext|>


<commit_before>/**
 * Plugin for Manager module, which handles organisms population in
 * nature simulation mode. It's related to DOS language.
 *
 * Events od Manager:
 *   TODO:
 *   ORGANISM(org) Fires after one organism has processed
 *
 * Depends on:
 *   manager/Manager
 *
 * @author flatline
 */
const BaseOrganisms = require('./../Organisms');
const Organism      = require('./Organism');
const Config        = require('./../../../../share/Config').Config;
const OConfig       = require('./../Config');
const EVENTS        = require('./../../../../share/Events').EVENTS;
const Helper        = require('./../../../../../../common/src/Helper');
const DIR           = require('./../../../../../../common/src/Directions').DIR;

const EMPTY         = 0;
const ENERGY        = 1;
const ORGANISM      = 2;

class Organisms extends BaseOrganisms {
    constructor(manager) {
        super(manager);
        this._onStepInCb = this._onStepIn.bind(this);
        this.manager.on(EVENTS.STEP_IN, this._onStepInCb);
    }

    destroy() {
        this.manager.off(EVENTS.STEP_IN, this._onStepInCb);
        this._onStepInCb = null;
        super.destroy();
    }

    /**
     * Compares two organisms and returns more fit one
     * @param {Organism} org1
     * @param {Organism} org2
     * @return {Organism}
     * @override
     */
    compare(org1, org2) {
        return org1.fitness() > org2.fitness();
    }

    /**
     * Is called before cloning of organism
     * @param {Organism} org
     * @override
     */
    onBeforeClone(org) {
        return org.energy > 1;
    }

    /**
     * Is called after cloning of organism
     * @param {Organism} org Parent organism
     * @param {Organism} child Child organism
     * @override
     */
    onClone(org, child) {
        let energy = (((org.energy * org.cloneEnergyPercent) + 0.5) << 1) >>> 1; // analog of Math.round()
        org.grabEnergy(energy);
        child.grabEnergy(child.energy - energy);
    }

    addOrgHandlers(org) {
        super.addOrgHandlers(org);
        org.on(EVENTS.GET_ENERGY, this._onGetEnergy.bind(this));
        org.on(EVENTS.EAT, this._onEat.bind(this));
        org.on(EVENTS.STEP, this._onStep.bind(this));
        org.on(EVENTS.CHECK_AT, this._onCheckAt.bind(this));
    }

    /**
     * Creates instance of an organism
     * @param {Array} args Custom organism arguments
     * @return {Organism} Organism instance
     * @override
     */
    createEmptyOrg(...args) {
        return new Organism(...args);
    }

    /**
     * Is called after organism has created
     * @param {Organism} org
     * @override
     */
    onAfterCreateOrg(org) {
        this.manager.positions[org.posId] = org;
    }

    /**
     * Is called after organism has killed
     * @param {Organism} org Killed organism
     * @override
     */
    onAfterKillOrg(org) {
        delete this.manager.positions[org.posId];
    }

    /**
     * Is called after moving of organism is done. Updates this.manager.positions
     * map with a new position of organism
     * @param {Number} x1 Start X position
     * @param {Number} y1 Start Y position
     * @param {Number} x2 End X position
     * @param {Number} y2 End Y position
     * @param {Organism} org Organism, which is moving
     * @returns {Boolean}
     * @override
     */
    onAfterMove(x1, y1, x2, y2, org) {
        if (x1 !== x2 || y1 !== y2) {
            delete this.manager.positions[Helper.posId(x1, y1)];
            this.manager.positions[Helper.posId(x2, y2)] = org;
        }

        return true;
    }

    _onGetEnergy(org, x, y, ret) {
        if (x < 0 || y < 0 || !Number.isInteger(x) || !Number.isInteger(y)) {return}
        const posId = Helper.posId(x, y);

        if (typeof(this.manager.positions[posId]) === 'undefined') {
            ret.ret = this.manager.world.getDot(x, y)
        } else {
            ret.ret = this.manager.positions[posId].energy;
        }
    }

    _onEat(org, x, y, ret) {
        const world = this.manager.world;
        const positions = this.manager.positions;
        let   dir;

        [x, y, dir] = Helper.normalize(x, y);

        const posId = Helper.posId(x, y);
        if (typeof(positions[posId]) === 'undefined') {
            ret.ret = world.grabDot(x, y, ret.ret);
        } else {
            ret.ret = ret.ret < 0 ? 0 : (ret.ret > positions[posId].energy ? positions[posId].energy : ret.ret);
            positions[posId].grabEnergy(ret.ret);
        }
    }

    _onStep(org, x1, y1, x2, y2, ret) {
        if (org.alive === false) {return}
        const man = this.manager;
        let   dir;

        [x2, y2, dir] = Helper.normalize(x2, y2);
        //
        // Organism has moved, but still is within the current world (client)
        //
        if (dir === DIR.NO) {
            ret.x = x2;
            ret.y = y2;
            ret.ret = +this.move(x1, y1, x2, y2, org);
            return;
        }
        //
        // Current organism try to move out of the world.
        // We have to pass him to the server to another
        // client (Manager). Changing x,y two times is needed
        // for serializing correct coordinates for destination
        // world and correct removing in current world
        //
        if (man.activeAround[dir]) {
            org.x = x2;
            org.y = y2;
            man.fire(EVENTS.STEP_OUT, x2, y2, dir, org);
            org.x = x1;
            org.y = y1;
            org.destroy();
            return;
        }
        //
        // Organism try to go outside of the world, but there is no
        // activated client on that side. So this is a border for him.
        // In this case coordinates (x,y) should stay the same
        //
        if (man.isDistributed() || Config.worldCyclical === false) {
            ret.x = x1;
            ret.y = y1;
            ret.ret = +this.move(x1, y1, x1, y1, org);
            return;
        }

        ret.x = x2;
        ret.y = y2;
        ret.ret = +this.move(x1, y1, x2, y2, org);
    }

    /**
     * Is called if organism step in from the server or other client (Manager/World).
     * If step in position is not free or maximum organisms are in the world, then
     * organism die at the moment.
     * @param {Number} x Current org X position
     * @param {Number} y Current org Y position
     * @param {String} orgJson Organism's serialized json
     * @private
     */
    _onStepIn(x, y, orgJson) {
        if (this.manager.world.isFree(x, y) && this.organisms.size < OConfig.orgMaxOrgs && this.createOrg({x, y})) {
            const org = this.organisms.last.val;
            org.unserialize(orgJson);
            org.grabEnergy(OConfig.orgStepEnergySpendPercent);
        }
    }

    _onCheckAt(x, y, ret) {
        let dir;

        [x, y, dir] = Helper.normalize(x, y);
        if (typeof(this.manager.positions[Helper.posId(x, y)]) === 'undefined') {
            ret.ret = this.manager.world.getDot(x, y) > 0 ? ENERGY : EMPTY;
        } else {
            ret.ret = ORGANISM;
        }
    }
}

module.exports = Organisms;<commit_msg>fixed issue with one organism on the world<commit_after>/**
 * Plugin for Manager module, which handles organisms population in
 * nature simulation mode. It's related to DOS language.
 *
 * Events od Manager:
 *   TODO:
 *   ORGANISM(org) Fires after one organism has processed
 *
 * Depends on:
 *   manager/Manager
 *
 * @author flatline
 */
const BaseOrganisms = require('./../Organisms');
const Organism      = require('./Organism');
const Config        = require('./../../../../share/Config').Config;
const OConfig       = require('./../Config');
const EVENTS        = require('./../../../../share/Events').EVENTS;
const Helper        = require('./../../../../../../common/src/Helper');
const DIR           = require('./../../../../../../common/src/Directions').DIR;

const EMPTY         = 0;
const ENERGY        = 1;
const ORGANISM      = 2;

class Organisms extends BaseOrganisms {
    constructor(manager) {
        super(manager);
        this._onStepInCb = this._onStepIn.bind(this);
        this.manager.on(EVENTS.STEP_IN, this._onStepInCb);
    }

    destroy() {
        this.manager.off(EVENTS.STEP_IN, this._onStepInCb);
        this._onStepInCb = null;
        super.destroy();
    }

    /**
     * Compares two organisms and returns more fit one
     * @param {Organism} org1
     * @param {Organism} org2
     * @return {Organism}
     * @override
     */
    compare(org1, org2) {
        return org1.fitness() > org2.fitness();
    }

    /**
     * Is called before cloning of organism
     * @param {Organism} org
     * @override
     */
    onBeforeClone(org) {
        return org.energy > 1;
    }

    /**
     * Is called after cloning of organism
     * @param {Organism} org Parent organism
     * @param {Organism} child Child organism
     * @override
     */
    onClone(org, child) {
        let energy = (((org.energy * org.cloneEnergyPercent) + 0.5) << 1) >>> 1; // analog of Math.round()
        //
        // This is vary special case, when organisms cheating by creating
        // ancestors and put all energy into them at the same time resetting
        // their iterations property and make them immortal
        //
        if (energy === org.energy) {
            energy--;
        }
        org.grabEnergy(energy);
        child.grabEnergy(child.energy - energy);
    }

    addOrgHandlers(org) {
        super.addOrgHandlers(org);
        org.on(EVENTS.GET_ENERGY, this._onGetEnergy.bind(this));
        org.on(EVENTS.EAT, this._onEat.bind(this));
        org.on(EVENTS.STEP, this._onStep.bind(this));
        org.on(EVENTS.CHECK_AT, this._onCheckAt.bind(this));
    }

    /**
     * Creates instance of an organism
     * @param {Array} args Custom organism arguments
     * @return {Organism} Organism instance
     * @override
     */
    createEmptyOrg(...args) {
        return new Organism(...args);
    }

    /**
     * Is called after organism has created
     * @param {Organism} org
     * @override
     */
    onAfterCreateOrg(org) {
        this.manager.positions[org.posId] = org;
    }

    /**
     * Is called after organism has killed
     * @param {Organism} org Killed organism
     * @override
     */
    onAfterKillOrg(org) {
        delete this.manager.positions[org.posId];
    }

    /**
     * Is called after moving of organism is done. Updates this.manager.positions
     * map with a new position of organism
     * @param {Number} x1 Start X position
     * @param {Number} y1 Start Y position
     * @param {Number} x2 End X position
     * @param {Number} y2 End Y position
     * @param {Organism} org Organism, which is moving
     * @returns {Boolean}
     * @override
     */
    onAfterMove(x1, y1, x2, y2, org) {
        if (x1 !== x2 || y1 !== y2) {
            delete this.manager.positions[Helper.posId(x1, y1)];
            this.manager.positions[Helper.posId(x2, y2)] = org;
        }

        return true;
    }

    _onGetEnergy(org, x, y, ret) {
        if (x < 0 || y < 0 || !Number.isInteger(x) || !Number.isInteger(y)) {return}
        const posId = Helper.posId(x, y);

        if (typeof(this.manager.positions[posId]) === 'undefined') {
            ret.ret = this.manager.world.getDot(x, y)
        } else {
            ret.ret = this.manager.positions[posId].energy;
        }
    }

    _onEat(org, x, y, ret) {
        const world = this.manager.world;
        const positions = this.manager.positions;
        let   dir;

        [x, y, dir] = Helper.normalize(x, y);

        const posId = Helper.posId(x, y);
        if (typeof(positions[posId]) === 'undefined') {
            ret.ret = world.grabDot(x, y, ret.ret);
        } else {
            ret.ret = ret.ret < 0 ? 0 : (ret.ret > positions[posId].energy ? positions[posId].energy : ret.ret);
            positions[posId].grabEnergy(ret.ret);
        }
    }

    _onStep(org, x1, y1, x2, y2, ret) {
        if (org.alive === false) {return}
        const man = this.manager;
        let   dir;

        [x2, y2, dir] = Helper.normalize(x2, y2);
        //
        // Organism has moved, but still is within the current world (client)
        //
        if (dir === DIR.NO) {
            ret.x = x2;
            ret.y = y2;
            ret.ret = +this.move(x1, y1, x2, y2, org);
            return;
        }
        //
        // Current organism try to move out of the world.
        // We have to pass him to the server to another
        // client (Manager). Changing x,y two times is needed
        // for serializing correct coordinates for destination
        // world and correct removing in current world
        //
        if (man.activeAround[dir]) {
            org.x = x2;
            org.y = y2;
            man.fire(EVENTS.STEP_OUT, x2, y2, dir, org);
            org.x = x1;
            org.y = y1;
            org.destroy();
            return;
        }
        //
        // Organism try to go outside of the world, but there is no
        // activated client on that side. So this is a border for him.
        // In this case coordinates (x,y) should stay the same
        //
        if (man.isDistributed() || Config.worldCyclical === false) {
            ret.x = x1;
            ret.y = y1;
            ret.ret = +this.move(x1, y1, x1, y1, org);
            return;
        }

        ret.x = x2;
        ret.y = y2;
        ret.ret = +this.move(x1, y1, x2, y2, org);
    }

    /**
     * Is called if organism step in from the server or other client (Manager/World).
     * If step in position is not free or maximum organisms are in the world, then
     * organism die at the moment.
     * @param {Number} x Current org X position
     * @param {Number} y Current org Y position
     * @param {String} orgJson Organism's serialized json
     * @private
     */
    _onStepIn(x, y, orgJson) {
        if (this.manager.world.isFree(x, y) && this.organisms.size < OConfig.orgMaxOrgs && this.createOrg({x, y})) {
            const org = this.organisms.last.val;
            org.unserialize(orgJson);
            org.grabEnergy(OConfig.orgStepEnergySpendPercent);
        }
    }

    _onCheckAt(x, y, ret) {
        let dir;

        [x, y, dir] = Helper.normalize(x, y);
        if (typeof(this.manager.positions[Helper.posId(x, y)]) === 'undefined') {
            ret.ret = this.manager.world.getDot(x, y) > 0 ? ENERGY : EMPTY;
        } else {
            ret.ret = ORGANISM;
        }
    }
}

module.exports = Organisms;<|endoftext|>


<commit_before>var WorkbenchLogin = new function() {

    var form = document.getElementById('login_form');

    this.initializeForm = function(loginType) {
        switchLoginTypeTo(form['loginType_' + loginType]);

        if (wbLoginConfig.customServerUrl === "") {
            buildServerUrl();
        } else {
            form.serverUrl.value = wbLoginConfig.customServerUrl;
        }

        bindEvent(form.loginType_std, "click", function () {switchLoginTypeTo(this)});
        bindEvent(form.loginType_adv, "click", function () {switchLoginTypeTo(this)});
        bindEvent(form.loginType_oauth, "click", function () {switchLoginTypeTo(this)});

        bindEvent(form.un, "keyup", toggleUsernamePasswordSessionDisabled);
        bindEvent(form.pw, "keyup", toggleUsernamePasswordSessionDisabled);
        bindEvent(form.sid, "keyup", toggleUsernamePasswordSessionDisabled);
        bindEvent(form.sid, "keyup", fuzzyServerUrlSelect);

        bindEvent(form.un, "change", toggleUsernamePasswordSessionDisabled);
        bindEvent(form.pw, "change", toggleUsernamePasswordSessionDisabled);
        bindEvent(form.sid, "change", toggleUsernamePasswordSessionDisabled);
        bindEvent(form.sid, "change", fuzzyServerUrlSelect);

        bindEvent(form.pw, "keypress", checkCaps); // must be keypress, not keyup

        bindEvent(form.inst, "keyup", buildServerUrl);
        bindEvent(form.api, "keyup", buildServerUrl);

        bindEvent(form.inst, "change", buildServerUrl);
        bindEvent(form.api, "change", buildServerUrl);
    };

    function switchLoginTypeTo(typeElem) {
        typeElem.checked = true;

        var divs = document.getElementsByTagName("div");
        for (var i = 0; i < divs.length; i++) {
            if (divs[i].className.indexOf("loginType") >= 0) {
                if (divs[i].className.indexOf(typeElem.id) >= 0) {
                    divs[i].style.display = "block";
                } else {
                    divs[i].style.display = "none";
                }
            }
        }

        switch (typeElem.id) {
            case "loginType_oauth":
                form.loginBtn.value = "Login with Salesforce";
                break;
            default:
                form.loginBtn.value = "Login";
        }

        // remove focus from login type controls
        setFocus();
    }

    function setFocus() {
        if (form.un.value == null || form.un.value == "") {
            form.un.focus();
        } else {
            form.pw.focus();
        }
    }

    function checkCaps(event) {
        var key = 0;
        var shifted = false;

        // IE
        if ( document.all ) {
            key = event.keyCode;
        // Everything else
        } else {
            key = event.which;
        }

        shifted = event.shiftKey;

        var pwcaps = document.getElementById('pwcaps');

        var upper = (key >= 65 && key <= 90);
        var lower = (key >= 97 && key <= 122);

        if ( (upper && !shifted) || (lower && shifted) ) {
            pwcaps.style.visibility='visible';
        } else if ( (lower && !shifted) || (upper && shifted) ) {
            pwcaps.style.visibility='hidden';
        }
    }

    function toggleUsernamePasswordSessionDisabled() {
        if (form.sid.value) {
            form.un.disabled = true;
            form.pw.disabled = true;
        } else {
            form.un.disabled = false;
            form.pw.disabled = false;
        }

        if (form.un.value || form.pw.value) {
            form.sid.disabled = true;
        } else {
            form.sid.disabled = false;
        }
    }

    function fuzzyServerUrlSelect() {
        var sid = form.sid.value
        var sidIndex = sid.indexOf('00D');

        if (sidIndex > -1) {
            var serverId = sid.substring(sidIndex + 3, sidIndex + 4);
            var inst = wbLoginConfig.serverIdMap[serverId];
            if (inst != null) {
                form.inst.value = inst;
                buildServerUrl();
            }
        }
    }

    function buildServerUrl() {
        form.serverUrl.value = 'http' +
                                (wbLoginConfig.useHTTPS && (form.inst.value.search(/localhost/i) == -1) ? 's' : '') +
                                '://' +
                                form.inst.value +
                                '.salesforce.com/services/Soap/u/' +
                                form.api.value;
    }

    function bindEvent(el, eventName, eventHandler) {
        if (el.addEventListener){
            el.addEventListener(eventName, eventHandler, false);
        } else if (el.attachEvent){
            el.attachEvent("on"+eventName, eventHandler);
        }
    }
};
<commit_msg>error on bad loginType due to name change<commit_after>var WorkbenchLogin = new function() {

    var form = document.getElementById('login_form');

    this.initializeForm = function(loginType) {
        var loginTypeElem = form['loginType_' + loginType];
        if (loginTypeElem === undefined) {
            alert("Unknown login type '" + loginType + "'. Check configuration!");
            return;
        }
        switchLoginTypeTo(loginTypeElem);

        if (wbLoginConfig.customServerUrl === "") {
            buildServerUrl();
        } else {
            form.serverUrl.value = wbLoginConfig.customServerUrl;
        }

        bindEvent(form.loginType_std, "click", function () {switchLoginTypeTo(this)});
        bindEvent(form.loginType_adv, "click", function () {switchLoginTypeTo(this)});
        bindEvent(form.loginType_oauth, "click", function () {switchLoginTypeTo(this)});

        bindEvent(form.un, "keyup", toggleUsernamePasswordSessionDisabled);
        bindEvent(form.pw, "keyup", toggleUsernamePasswordSessionDisabled);
        bindEvent(form.sid, "keyup", toggleUsernamePasswordSessionDisabled);
        bindEvent(form.sid, "keyup", fuzzyServerUrlSelect);

        bindEvent(form.un, "change", toggleUsernamePasswordSessionDisabled);
        bindEvent(form.pw, "change", toggleUsernamePasswordSessionDisabled);
        bindEvent(form.sid, "change", toggleUsernamePasswordSessionDisabled);
        bindEvent(form.sid, "change", fuzzyServerUrlSelect);

        bindEvent(form.pw, "keypress", checkCaps); // must be keypress, not keyup

        bindEvent(form.inst, "keyup", buildServerUrl);
        bindEvent(form.api, "keyup", buildServerUrl);

        bindEvent(form.inst, "change", buildServerUrl);
        bindEvent(form.api, "change", buildServerUrl);
    };

    function switchLoginTypeTo(typeElem) {
        typeElem.checked = true;

        var divs = document.getElementsByTagName("div");
        for (var i = 0; i < divs.length; i++) {
            if (divs[i].className.indexOf("loginType") >= 0) {
                if (divs[i].className.indexOf(typeElem.id) >= 0) {
                    divs[i].style.display = "block";
                } else {
                    divs[i].style.display = "none";
                }
            }
        }

        switch (typeElem.id) {
            case "loginType_oauth":
                form.loginBtn.value = "Login with Salesforce";
                break;
            default:
                form.loginBtn.value = "Login";
        }

        // remove focus from login type controls
        setFocus();
    }

    function setFocus() {
        if (form.un.value == null || form.un.value == "") {
            form.un.focus();
        } else {
            form.pw.focus();
        }
    }

    function checkCaps(event) {
        var key = 0;
        var shifted = false;

        // IE
        if ( document.all ) {
            key = event.keyCode;
        // Everything else
        } else {
            key = event.which;
        }

        shifted = event.shiftKey;

        var pwcaps = document.getElementById('pwcaps');

        var upper = (key >= 65 && key <= 90);
        var lower = (key >= 97 && key <= 122);

        if ( (upper && !shifted) || (lower && shifted) ) {
            pwcaps.style.visibility='visible';
        } else if ( (lower && !shifted) || (upper && shifted) ) {
            pwcaps.style.visibility='hidden';
        }
    }

    function toggleUsernamePasswordSessionDisabled() {
        if (form.sid.value) {
            form.un.disabled = true;
            form.pw.disabled = true;
        } else {
            form.un.disabled = false;
            form.pw.disabled = false;
        }

        if (form.un.value || form.pw.value) {
            form.sid.disabled = true;
        } else {
            form.sid.disabled = false;
        }
    }

    function fuzzyServerUrlSelect() {
        var sid = form.sid.value
        var sidIndex = sid.indexOf('00D');

        if (sidIndex > -1) {
            var serverId = sid.substring(sidIndex + 3, sidIndex + 4);
            var inst = wbLoginConfig.serverIdMap[serverId];
            if (inst != null) {
                form.inst.value = inst;
                buildServerUrl();
            }
        }
    }

    function buildServerUrl() {
        form.serverUrl.value = 'http' +
                                (wbLoginConfig.useHTTPS && (form.inst.value.search(/localhost/i) == -1) ? 's' : '') +
                                '://' +
                                form.inst.value +
                                '.salesforce.com/services/Soap/u/' +
                                form.api.value;
    }

    function bindEvent(el, eventName, eventHandler) {
        if (el.addEventListener){
            el.addEventListener(eventName, eventHandler, false);
        } else if (el.attachEvent){
            el.attachEvent("on"+eventName, eventHandler);
        }
    }
};
<|endoftext|>


<commit_before>import {LitElement, html} from "lit";
import UtilsNew from "./../../core/utilsNew.js";
import Region from "../../core/bioinfo/region.js";
import GenomeBrowser from "../../genome-browser/genome-browser.js";

import FeatureTrack from "../../genome-browser/tracks/feature-track.js";
import GeneOverviewTrack from "../../genome-browser/tracks/gene-overview-track.js";
import GeneTrack from "../../genome-browser/tracks/gene-track.js";
import SequenceTrack from "../../genome-browser/tracks/sequence-track.js";
import VariantTrack from "../../genome-browser/tracks/variant-track.js";
import OpenCGAVariantTrack from "../../genome-browser/tracks/opencga-variant-track.js";

export default class GenomeBrowserComponent extends LitElement {

    constructor() {
        super();
        this.#init();
    }

    createRenderRoot() {
        return this;
    }

    static get properties() {
        return {
            opencgaSession: {
                type: Object,
            },
            region: {
                type: Object,
            },
            species: {
                type: String,
            },
            tracks: {
                type: Array,
            },
            active: {
                type: Boolean,
            },
            config: {
                type: Object,
            },
        };
    }

    #init() {
        this._prefix = UtilsNew.randomString(8);

        this.genomeBrowser = null;
        this.active = true;
        this.species = "hsapiens";
        this.config = this.getDefaultConfig();
    }

    updated(changedProperties) {
        if (changedProperties.has("opencgaSession")) {
            this.opencgaSessionObserver();
        }

        if (changedProperties.has("region")) {
            this.regionObserver();
        }

        if (changedProperties.has("active")) {
            this.activeObserver();
        }
    }

    opencgaSessionObserver() {
        if (this.genomeBrowser) {
            this.genomeBrowser.destroy();
            this.initGenomeBrowser();
        }
    }

    activeObserver() {
        if (this.active && !this.genomeBrowser) {
            // const parent = this.querySelector(`div#${this._prefix}GenomeBrowser`);
            // const width = parent.getBoundingClientRect().width;
            // this.genomeBrowser.setWidth(width);
            this.initGenomeBrowser();
        }
    }

    regionObserver() {
        if (this.genomeBrowser) {
            this.genomeBrowser.setRegion(this.region);
        }
    }

    initGenomeBrowser() {
        const parent = this.querySelector(`div#${this._prefix}GenomeBrowser`);
        const config = {
            ...this.getDefaultConfig(),
            ...this.config,
        };

        this.genomeBrowser = new GenomeBrowser(parent, {
            width: parent.getBoundingClientRect().width || 100,
            region: new Region(this.region),
            resizable: true,
            ...config,
        });

        // When GB is ready add tracks and draw
        this.genomeBrowser.on("ready", () => {
            this.genomeBrowser.addOverviewTracks(this.getOverviewTracks());
            this.genomeBrowser.addTracks(this.getDetailTracks());
            this.genomeBrowser.draw();
        });
    }

    // Get only overview tracks
    getOverviewTracks() {
        return this.parseTracks(this.tracks.filter(track => !!track.overview));
    }

    // Get only detail tracks
    getDetailTracks() {
        return this.parseTracks(this.tracks.filter(track => !track.overview));
    }

    parseTracks(tracks) {
        return tracks.map(track => {
            switch (track.type || "feature") {
                case "sequence":
                    return new SequenceTrack({
                        cellBaseClient: this.config.cellBaseClient,
                        ...track.config,
                    });
                case "gene":
                    return new GeneTrack({
                        cellBaseClient: this.config.cellBaseClient,
                        ...track.config,
                    });
                case "gene-overview":
                    return new GeneOverviewTrack({
                        cellBaseClient: this.config.cellBaseClient,
                        ...track.config,
                    });
                case "variant":
                    return new VariantTrack({
                        cellBaseClient: this.config.cellBaseClient,
                        ...track.config,
                    });
                case "opencga-variant":
                    return new OpenCGAVariantTrack({
                        opencgaClient: this.opencgaSession.opencgaClient,
                        opencgaStudy: this.opencgaSession.study.fqn,
                        ...track.config,
                    });
                default:
                    return new FeatureTrack({
                        cellBaseClient: this.config.cellBaseClient,
                        ...track.config,
                    });
            }
        });
    }

    render() {
        return html`

        `;
    }

    getDefaultConfig() {
        return {};
    }

}

customElements.define("new-genome-browser", GenomeBrowserComponent);
<commit_msg>wc: improve properties observers in GB component #TASK-438<commit_after>import {LitElement, html} from "lit";
import UtilsNew from "./../../core/utilsNew.js";
import Region from "../../core/bioinfo/region.js";
import GenomeBrowser from "../../genome-browser/genome-browser.js";

import FeatureTrack from "../../genome-browser/tracks/feature-track.js";
import GeneOverviewTrack from "../../genome-browser/tracks/gene-overview-track.js";
import GeneTrack from "../../genome-browser/tracks/gene-track.js";
import SequenceTrack from "../../genome-browser/tracks/sequence-track.js";
import VariantTrack from "../../genome-browser/tracks/variant-track.js";
import OpenCGAVariantTrack from "../../genome-browser/tracks/opencga-variant-track.js";

export default class GenomeBrowserComponent extends LitElement {

    constructor() {
        super();
        this.#init();
    }

    createRenderRoot() {
        return this;
    }

    static get properties() {
        return {
            opencgaSession: {
                type: Object,
            },
            region: {
                type: Object,
            },
            species: {
                type: String,
            },
            tracks: {
                type: Array,
            },
            active: {
                type: Boolean,
            },
            config: {
                type: Object,
            },
        };
    }

    #init() {
        this._prefix = UtilsNew.randomString(8);

        this.genomeBrowser = null;
        this.active = true;
        this.species = "hsapiens";
        this.tracks = [];
        this.config = this.getDefaultConfig();
    }

    updated(changedProperties) {
        if (changedProperties.has("opencgaSession" || changedProperties.has("config") || changedProperties.has("tracks"))) {
            this.opencgaSessionOrConfigObserver();
        }

        if (changedProperties.has("region") || changedProperties.has("active")) {
            this.propertyObserver();
        }
    }

    opencgaSessionOrConfigObserver() {
        if (this.opencgaSession && this.config && this.tracks) {
            if (this.genomeBrowser) {
                this.genomeBrowser.destroy();
                this.genomeBrowser = null;
            }

            // Check the active property to initialize genomebrowser
            if (this.active) {
                this.initGenomeBrowser();
            }
        }
    }

    propertyObserver() {
        if (this.active) {
            // Check for no genomebrowser instance ready
            if (!this.genomeBrowser) {
                return this.initGenomeBrowser();
            }

            // Check if region has been provided and is different from current region
            if (this.region && !this.genomeBrowser.region.equals(new Region(this.region))) {
                this.genomeBrowser.setRegion(this.region);
            }
        }
    }

    initGenomeBrowser() {
        const parent = this.querySelector(`div#${this._prefix}GenomeBrowser`);
        const config = {
            ...this.getDefaultConfig(),
            ...this.config,
        };

        this.genomeBrowser = new GenomeBrowser(parent, {
            width: parent.getBoundingClientRect().width || 100,
            region: new Region(this.region),
            resizable: true,
            ...config,
        });

        // When GB is ready add tracks and draw
        this.genomeBrowser.on("ready", () => {
            this.genomeBrowser.addOverviewTracks(this.getOverviewTracks());
            this.genomeBrowser.addTracks(this.getDetailTracks());
            this.genomeBrowser.draw();
        });
    }

    // Get only overview tracks
    getOverviewTracks() {
        return this.parseTracks(this.tracks.filter(track => !!track.overview));
    }

    // Get only detail tracks
    getDetailTracks() {
        return this.parseTracks(this.tracks.filter(track => !track.overview));
    }

    parseTracks(tracks) {
        return tracks.map(track => {
            switch (track.type) {
                case "sequence":
                    return new SequenceTrack({
                        cellBaseClient: this.config.cellBaseClient,
                        ...track.config,
                    });
                case "gene":
                    return new GeneTrack({
                        cellBaseClient: this.config.cellBaseClient,
                        ...track.config,
                    });
                case "gene-overview":
                    return new GeneOverviewTrack({
                        cellBaseClient: this.config.cellBaseClient,
                        ...track.config,
                    });
                case "variant":
                    return new VariantTrack({
                        cellBaseClient: this.config.cellBaseClient,
                        ...track.config,
                    });
                case "opencga-variant":
                    return new OpenCGAVariantTrack({
                        opencgaClient: this.opencgaSession.opencgaClient,
                        opencgaStudy: this.opencgaSession.study.fqn,
                        ...track.config,
                    });
                default:
                    return new FeatureTrack({
                        cellBaseClient: this.config.cellBaseClient,
                        ...track.config,
                    });
            }
        });
    }

    render() {
        return html`

        `;
    }

    getDefaultConfig() {
        return {};
    }

}

customElements.define("new-genome-browser", GenomeBrowserComponent);
<|endoftext|>


<commit_before>App.IndexRoute = Ember.Route.extend({
    beforeModel: function() {
        this.transitionTo('library');
    }
});

App.BookRoute = Ember.Route.extend({
    model: function(params) {
        return Ember.$.getJSON('/api/book/'+params.book_id).then(function(data){
            console.log(data.book);
            return data.book;
        });
    }
});

App.EditRoute = Ember.Route.extend({
    model: function(params) {
        return Ember.$.getJSON('/api/book/'+params.book_id).then(function(data){
            console.log(data.book);
            return data.book;
        });
    },
    setupController: function(controller, model) {
        controller.set('id', model.id);
        controller.set('title', model.title);
        controller.set('subtitle', model.subtitle);
        controller.set('authors', model.authors.join(','));
        controller.set('description', model.description);
        controller.set('cover', model.cover);
        controller.set('genres', model.genres.join(','));
        controller.set('positiveResponse', null);
        controller.set('negativeResponse', null);
    }
});

App.LibraryRoute = Ember.Route.extend({
    model: function(){
        return Ember.$.getJSON('/api/books/').then(function(data) {
            var chunks = [];

            while (data.books.length > 0) {
                chunks.push(data.books.splice(0,6))
            }

            return chunks;
        });
    }
});

App.SettingsRoute = Ember.Route.extend({
    model: function(){
        return Ember.$.getJSON('/api/settings/').then(function(data) {
            return data.settings;
            console.log(data);
        });
    },
    setupController: function(controller, model) {
        controller.set('realname', model.realname);
        controller.set('emailadd', model.email_address);
    }
});

App.AuthorRoute = Ember.Route.extend({
    model: function(params){
        return Ember.$.getJSON('/api/books/author/'+params.author_id).then(function(data) {
            var chunks = [];

            while (data.books.length > 0) {
                chunks.push(data.books.splice(0,6))
            }

            return {
                chunks: chunks,
                author: params.author_id
            }
        });
    }
});

App.GenreRoute = Ember.Route.extend({
    model: function(params){
        return Ember.$.getJSON('/api/books/genre/'+params.genre_id).then(function(data) {
            var chunks = [];

            while (data.books.length > 0) {
                chunks.push(data.books.splice(0,6))
            }

            return {
                chunks: chunks,
                author: params.genre_id
            }
        });
    }
});
<commit_msg>Use setProperties in place of set in edit to set a hash<commit_after>App.IndexRoute = Ember.Route.extend({
    beforeModel: function() {
        this.transitionTo('library');
    }
});

App.BookRoute = Ember.Route.extend({
    model: function(params) {
        return Ember.$.getJSON('/api/book/'+params.book_id).then(function(data){
            console.log(data.book);
            return data.book;
        });
    }
});

App.EditRoute = Ember.Route.extend({
    model: function(params) {
        return Ember.$.getJSON('/api/book/'+params.book_id).then(function(data){
            console.log(data.book);
            return data.book;
        });
    },
    setupController: function(controller, model) {
        controller.setProperties({
            id: model.id,
            title: model.title,
            subtitle: model.subtitle,
            authors: model.authors.join(','),
            description: model.description,
            cover: model.cover,
            genres: model.genres,
            positiveResponse: null,
            negativeResponse: null
        });
    }
});

App.LibraryRoute = Ember.Route.extend({
    model: function(){
        return Ember.$.getJSON('/api/books/').then(function(data) {
            var chunks = [];

            while (data.books.length > 0) {
                chunks.push(data.books.splice(0,6))
            }

            return chunks;
        });
    }
});

App.SettingsRoute = Ember.Route.extend({
    model: function(){
        return Ember.$.getJSON('/api/settings/').then(function(data) {
            return data.settings;
            console.log(data);
        });
    },
    setupController: function(controller, model) {
        controller.set('realname', model.realname);
        controller.set('emailadd', model.email_address);
    }
});

App.AuthorRoute = Ember.Route.extend({
    model: function(params){
        return Ember.$.getJSON('/api/books/author/'+params.author_id).then(function(data) {
            var chunks = [];

            while (data.books.length > 0) {
                chunks.push(data.books.splice(0,6))
            }

            return {
                chunks: chunks,
                author: params.author_id
            }
        });
    }
});

App.GenreRoute = Ember.Route.extend({
    model: function(params){
        return Ember.$.getJSON('/api/books/genre/'+params.genre_id).then(function(data) {
            var chunks = [];

            while (data.books.length > 0) {
                chunks.push(data.books.splice(0,6))
            }

            return {
                chunks: chunks,
                author: params.genre_id
            }
        });
    }
});
<|endoftext|>


<commit_before>app.controller('ChatController', function ($rootScope, $scope, $stateParams, $state, user, bunkerData) {
	var self = this;

	this.rooms = bunkerData.rooms;

	bunkerData.$promise.then(selectRoom);
	$rootScope.$on('roomIdChanged', selectRoom);

	function selectRoom() {

		if (!_.any(self.rooms, {id: $rootScope.roomId})) {
			// Functionality to allow users to join a room by entering it's URL
			self.rooms.push({id: $rootScope.roomId})
		}

		_.each(self.rooms, function (room) {
			room.$selected = room.id == $rootScope.roomId;
		});
	}
});
<commit_msg>don't push a blank room unless rooms have come back<commit_after>app.controller('ChatController', function ($rootScope, $scope, $stateParams, $state, user, bunkerData) {
	var self = this;

	this.rooms = bunkerData.rooms;

	bunkerData.$promise.then(selectRoom);
	$rootScope.$on('roomIdChanged', selectRoom);

	function selectRoom() {

		if (bunkerData.$resolved && !_.any(self.rooms, {id: $rootScope.roomId})) {
			// Functionality to allow users to join a room by entering it's URL
			self.rooms.push({id: $rootScope.roomId})
		}

		_.each(self.rooms, function (room) {
			room.$selected = room.id == $rootScope.roomId;
		});
	}
});
<|endoftext|>