<commit_before>/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */;

jQuery(document).ready(function () {
    $(".manage_blocks").sortable({
        items: '.ma_block:not(.inactive)',
        stop: function (event, ui) {
            console.log("New position: " + ui.item.index());
        }
    });
    $(".manage_blocks").disableSelection();
});

(function ($) {
    var title = "

";
    var buttonClass = 'm_action';
   // var inactive = "

   // <input type=\"text\" placeholder=\"Type a name of behavior\" class=\"newInput\">
   //

   //

Add new action

";
    var containerclass = 'ma_block';
    var boxclass = 'm_slide';
    var textwrapperclass = 'm_text';
    //

    var ethogram;

    var method = {
        initialize: function (params) {

            self.ethogram = $(this);
            var inactive = $('
', {class:containerclass+' inactive'})
                    .prepend($('
', {class:boxclass}))
                    .prepend($('
', {class:textwrapperclass})
                    .prepend($('<input/>',{type:'text', class:'newInput', placeholder:'Type a name of behavior'})))
                    .after($('
', {class:'m_buttons'}));

            $(self.ethogram).prepend(inactive);

            $.ajax({url: params.url}).done(method.buildEhtogram);

            //method.inactiveTrigger($(".ma_block.inactive:last"));

//            var initializedelement = $(".ma_block.inactive > .m_slide > .m_text > input", this);
            //          initializedelement.on('keydown', function () {
            //            method.cloneInactive(this);
            //      }).enterKey();
            return this;
        },
        buildEhtogram: function (data) {

            $.each(data, method.addContainer);

        },
        addContainer: function (container, containervalues) {
            var collapseButton = $('', {class: 'collapseL'}).on('click', function () {
            });
            var deleteButton = $('', {class: 'delete'}).on('click', function () {
                method.editContainer({id: container.id, action: 'delete'});
            });
            var editButton = $('', {class: 'edit'}).on('click', function () {
            });
            var buttonsRow = $('
', {class: 'm_title_edit'})
                    .prepend(editButton)
                    .prepend(deleteButton)
                    .prepend(collapseButton);

            var containerelement = $('
', {class: containerclass}).prependTo(self.ethogram);

            //add button and make tiles sortable;

            var newActionButton = $('
', {class: buttonClass})
                    .text('New Behavior')
                    .on('click', function () {
                                    console.log('.' + buttonClass, containerelement);
                        $('
', {class: textwrapperclass}).insertBefore($(this))
                                .prepend($('<input>', {type: 'text', class: 'newInput'}))
                                .prepend($('', {class: 'delete'}).on('click', function(){
                                    $(this).closest('div').remove()
                        }));
                    });
            //createa a button that adds an empty text field
            newActionButton.prependTo($('
', {class: boxclass}).sortable({
                connectWith: "." + boxclass,
                items: 'div:not(.m_action)'}).prependTo(containerelement));
            $(title).prependTo(containerelement)
                    .find('.m_title')
                    .text(containervalues.name).after(buttonsRow);

            $.each(containervalues.values, function (i, value) {
                method.addBehavior(value, containerelement)
            })
            return this;

        },
        addBehavior: function (behavior, containerelement) {

            var deleteButton = $('', {class: 'delete'}).on('click', function () {

            });
            var editButton = $('', {class: 'edit'}).on('click', function () {
                console.log(behavior.id)
            });
            var buttonWrapper = $('
', {class: textwrapperclass})
                    .prependTo($('.' + boxclass, containerelement));
            $('<input/>', {type: 'text', placeholder: behavior.name, class: 'newInput'}).
                    prependTo(buttonWrapper)
                    .after(editButton)
                    .after(deleteButton);

            return this;

        },
        editContainer: function (params) {

        },
        inactiveTrigger: function (element) {
            $(".m_text > input", element).on('keypress', function () {

                method.cloneInactive(this);

                return this;
            })
        },
        cloneInactive: function (initializedelement) {

            var element = $(".ma_block.inactive:last");
            var newelement = $(element).clone().appendTo('.manage_blocks');
            $(".m_text > input", element).off('keypress').on('keypress', function () {
                if (event.which === 13) {
                    var savebutton = $(".m_action", element);
                    $(savebutton).click();
                }
            });
            method.inactiveTrigger(newelement);
            method.activateContainer(element);

            return this;
        },
        activateContainer: function (element) {

            element.removeClass("inactive");
            var savebutton = $(".m_action", element);
            var deletebutton = $(".m_text .delete", element);
            var editbutton = $(".m_text .edit", element);
            $(deletebutton).on('click', function () {
                $(element).remove()
            });
            $(editbutton).hide();
            $(savebutton).unwrap().text("Save").on('click', function () {
                var textval = $(".m_text > input", element).val();
                method.saveContainer({subject: textval, position: element.index()});
                method.addTitle(element, textval);
            });

            return this;
        },
        saveContainer: function (values) {

            $.post("ethogramcontainer", values, function (data) {

            });

            return this;
        },
        addTitleOLD: function (element, textval) {

            var newelement = $(element).prepend(title);
            $(".m_action", element).remove();
            $(".m_title", newelement).text(textval);

            $(".m_text", element).remove();
            var addbehavior = $(".m_slide", element).prepend(button);
            $(".m_slide", element).sortable({
                connectWith: ".m_slide",
                items: 'div:not(.m_action)'});

            $(".m_action", addbehavior).on('click', function () {
                $(".m_action", element).before(field)
            });
            $(".m_title_edit > .delete", element).on('click', function () {
                $(element).remove();
            });
            $(".m_title_edit > .edit", element).on('click', function () {
                var text = $(".m_title", element).text();
                $(".m_title", element).remove();
                $(".m_title_wrapper", element).prepend(field);
            });
            return this;
        }
    };

    $.fn.ethogram = function (call) {
        if (method[call]) {
            return method[call].apply(this, Array.prototype.slice.call(arguments, 1));
        } else if (typeof call === 'object' || !call) {
            return method.initialize.apply(this, arguments);
        } else {
            $.error('Method ' + call + ' not found in jQuery.test');
        }
    };
    $.fn.enterKey = function (fnc) {
        return this.each(function () {
            $(this).keypress(function (ev) {
                var keycode = (ev.keyCode ? ev.keyCode : ev.which);
                if (keycode == '13') {
                    fnc.call(this, ev);
                }
            })
        })
    }
})(jQuery);

<commit_msg>Even More changes to ethogram<commit_after>/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */;

jQuery(document).ready(function () {
    $(".manage_blocks").sortable({
        items: '.ma_block:not(.inactive)',
        stop: function (event, ui) {
            console.log("New position: " + ui.item.index());
        }
    });
    $(".manage_blocks").disableSelection();
});

(function ($) {
    var title = "

";
    var buttonClass = 'm_action';
   // var inactive = "

   // <input type=\"text\" placeholder=\"Type a name of behavior\" class=\"newInput\">
   //

   //

Add new action

";
    var containerclass = 'ma_block';
    var boxclass = 'm_slide';
    var textwrapperclass = 'm_text';
    //

    var ethogram;

    var method = {
        initialize: function (params) {

            self.ethogram = $(this);
            var inactive = $('
', {class:containerclass+' inactive'})
                    //.prepend($('
', {class:boxclass}))
                    .prepend($('
', {class:textwrapperclass})
                    .prepend($('<input/>',{type:'text', class:'newInput', placeholder:'Type a name of behavior'})))
                    ;

            $(self.ethogram).prepend(inactive);

            $.ajax({url: params.url}).done(method.buildEhtogram);

            //method.inactiveTrigger($(".ma_block.inactive:last"));

//            var initializedelement = $(".ma_block.inactive > .m_slide > .m_text > input", this);
            //          initializedelement.on('keydown', function () {
            //            method.cloneInactive(this);
            //      }).enterKey();
            return this;
        },
        buildEhtogram: function (data) {

            $.each(data, method.addContainer);

        },
        addContainer: function (container, containervalues) {
            var collapseButton = $('', {class: 'collapseL'}).on('click', function () {
            });
            var deleteButton = $('', {class: 'delete'}).on('click', function () {
                method.editContainer({id: container.id, action: 'delete'});
            });
            var editButton = $('', {class: 'edit'}).on('click', function () {
            });
            var buttonsRow = $('
', {class: 'm_title_edit'})
                    .prepend(editButton)
                    .prepend(deleteButton)
                    .prepend(collapseButton);

            var containerelement = $('
', {class: containerclass}).prependTo(self.ethogram);

            //add button and make tiles sortable;

            var newActionButton = $('
', {class: buttonClass})
                    .text('New Behavior')
                    .on('click', function () {
                                    console.log('.' + buttonClass, containerelement);
                        $('
', {class: textwrapperclass}).insertBefore($(this))
                                .prepend($('<input>', {type: 'text', class: 'newInput'}))
                                .prepend($('', {class: 'delete'}).on('click', function(){
                                    $(this).closest('div').remove()
                        }));
                    });
            //createa a button that adds an empty text field
            newActionButton.prependTo($('
', {class: boxclass}).sortable({
                connectWith: "." + boxclass,
                items: 'div:not(.m_action)'}).prependTo(containerelement));
            $(title).prependTo(containerelement)
                    .find('.m_title')
                    .text(containervalues.name).after(buttonsRow);

            $.each(containervalues.values, function (i, value) {
                method.addBehavior(value, containerelement)
            })
            return this;

        },
        addBehavior: function (behavior, containerelement) {

            var deleteButton = $('', {class: 'delete'}).on('click', function () {

            });
            var editButton = $('', {class: 'edit'}).on('click', function () {
                console.log(behavior.id)
            });
            var buttonWrapper = $('
', {class: textwrapperclass})
                    .prependTo($('.' + boxclass, containerelement));
            $('<input/>', {type: 'text', placeholder: behavior.name, class: 'newInput'}).
                    prependTo(buttonWrapper)
                    .after(editButton)
                    .after(deleteButton);

            return this;

        },
        editContainer: function (params) {

        },
        inactiveTrigger: function (element) {
            $(".m_text > input", element).on('keypress', function () {

                method.cloneInactive(this);

                return this;
            })
        },
        cloneInactive: function (initializedelement) {

            var element = $(".ma_block.inactive:last");
            var newelement = $(element).clone().appendTo('.manage_blocks');
            $(".m_text > input", element).off('keypress').on('keypress', function () {
                if (event.which === 13) {
                    var savebutton = $(".m_action", element);
                    $(savebutton).click();
                }
            });
            method.inactiveTrigger(newelement);
            method.activateContainer(element);

            return this;
        },
        activateContainer: function (element) {

            element.removeClass("inactive");
            var savebutton = $(".m_action", element);
            var deletebutton = $(".m_text .delete", element);
            var editbutton = $(".m_text .edit", element);
            $(deletebutton).on('click', function () {
                $(element).remove()
            });
            $(editbutton).hide();
            $(savebutton).unwrap().text("Save").on('click', function () {
                var textval = $(".m_text > input", element).val();
                method.saveContainer({subject: textval, position: element.index()});
                method.addTitle(element, textval);
            });

            return this;
        },
        saveContainer: function (values) {

            $.post("ethogramcontainer", values, function (data) {

            });

            return this;
        },
        addTitleOLD: function (element, textval) {

            var newelement = $(element).prepend(title);
            $(".m_action", element).remove();
            $(".m_title", newelement).text(textval);

            $(".m_text", element).remove();
            var addbehavior = $(".m_slide", element).prepend(button);
            $(".m_slide", element).sortable({
                connectWith: ".m_slide",
                items: 'div:not(.m_action)'});

            $(".m_action", addbehavior).on('click', function () {
                $(".m_action", element).before(field)
            });
            $(".m_title_edit > .delete", element).on('click', function () {
                $(element).remove();
            });
            $(".m_title_edit > .edit", element).on('click', function () {
                var text = $(".m_title", element).text();
                $(".m_title", element).remove();
                $(".m_title_wrapper", element).prepend(field);
            });
            return this;
        }
    };

    $.fn.ethogram = function (call) {
        if (method[call]) {
            return method[call].apply(this, Array.prototype.slice.call(arguments, 1));
        } else if (typeof call === 'object' || !call) {
            return method.initialize.apply(this, arguments);
        } else {
            $.error('Method ' + call + ' not found in jQuery.test');
        }
    };
    $.fn.enterKey = function (fnc) {
        return this.each(function () {
            $(this).keypress(function (ev) {
                var keycode = (ev.keyCode ? ev.keyCode : ev.which);
                if (keycode == '13') {
                    fnc.call(this, ev);
                }
            })
        })
    }
})(jQuery);

<|endoftext|>


<commit_before>/**
 * Geo-OV - applicatie voor het registreren van KAR meldpunten
 *
 * Copyright (C) 2009-2013 B3Partners B.V.
 *
 * 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/>.
 */
/**
 * Class for representing the currently selected trafficsystem
 *
 *
 */
Ext.define("nl.b3p.kar.Overview",{
    editor : null,
    domId : null,
    tree : null,
    heightOffset:null,
    constructor : function (editor,domId){
        this.editor = editor;
        this.domId = domId;
        this.heightOffset = 75;
        this.editor.on("activeRseqUpdated",this.updateOverview,this);
        this.editor.on("activeRseqChanged",this.updateOverview,this);
        this.editor.on('selectedObjectChanged',this.updateSelection,this);

        var panel = Ext.getCmp("rseqInfoPanel");
        panel.on('collapse',this.updateSize,this);
        panel.on('expand',this.updateSize,this);
        panel.on('resize',this.updateSize,this);

        this.editor.olc.highlight.events.register('featurehighlighted',this,function (evt){
            if (this.isPoint(evt.feature)){
                this.highlight(evt.feature.data.id);
            }
        });
        this.editor.olc.highlight.events.register('featureunhighlighted',this,function (evt){
            if (this.isPoint(evt.feature)){
                this.unhighlight(evt.feature.data.id);
            }
        });
    },
    updateOverview : function (rseq){
        Ext.get("context_vri").setHTML(rseq == null ? "" :
                (rseq.description + " (" + rseq.karAddress + ")"));
        Ext.get("rseqOptions").setVisible(rseq != null);
        var memoIcon = Ext.get("memo_vri");
        if (rseq.memo && rseq.memo != ""){
            memoIcon.setVisible(true);
        } else{
            memoIcon.setVisible(false);
        }

        var overzicht = Ext.get("overzicht");
        var tree = Ext.get("tree");
        if (tree){
            tree.remove();
        }
        var root = this.createRootNode(rseq.getOverviewJSON());
        var store = Ext.create('Ext.data.TreeStore',root);
        this.tree = Ext.create('Ext.tree.Panel',{
            border : false,
            header : false,
            id : "tree",
            selModel : {
                mode : "MULTI"
            },
            height :Ext.get("rseqInfoPanel-body").getHeight() - this.heightOffset,
            store : store,
            rootVisible : false,
            renderTo : overzicht,
            listeners : {
                scope : this,
                select : function (tree,record){
                    if (record.raw.type == "point"){
                        var id = record.raw.pointId;
                        var vectorLayer = this.editor.olc.vectorLayer;
                        var features = vectorLayer.getFeaturesByAttribute("id",id);
                        if (features != null && features.length > 0){
                            var feature = features[0];
                            this.editor.setSelectedObject(feature);
                        }
                    }
                },
                itemmouseenter : function (tree,record){
                    if (record.raw.type == "point"){
                        var id = record.raw.pointId;
                        var vectorLayer = this.editor.olc.vectorLayer;
                        var features = vectorLayer.getFeaturesByAttribute("id",id);
                        if (features != null && features.length > 0){
                            var feat = features[0];
                            if (feat.renderIntent != "select"){
                                feat.renderIntent = "temporary";
                                vectorLayer.redraw();
                            }
                        }
                    }
                },
                itemmouseleave : function (tree,record){
                    if (record.raw.type == "point"){
                        var id = record.raw.pointId;
                        var currentSelectedObject = this.editor.selectedObject;
                        if (currentSelectedObject == null || currentSelectedObject.getId() != id){
                            var vectorLayer = this.editor.olc.vectorLayer;
                            var features = vectorLayer.getFeaturesByAttribute("id",id);
                            if (features != null && features.length > 0){
                                var feat = features[0];
                                feat.renderIntent = "default";
                                vectorLayer.redraw();
                            }
                        }
                    }
                },
                itemcontextmenu : function (view,record,item,index,event,eOpts){
                    var type = record.raw.type;
                    if (type != "signalGroup" && type != "movement"){
                        this.editor.contextMenu.show(event.xy[0],event.xy[1],false);
                    }
                }
            }
        });
        this.editor.helpPanel.updateHelpPanel();
    },
    updateSelection : function (point){
        if (this.tree != null){
            var sm = this.tree.getSelectionModel();
            if (point != null && point instanceof Point){
                this.unhighlight(point.getId());
                var root = this.tree.getRootNode();
                var nodes = new Array();
                this.findChildrenByPointId(root,point.getId(),nodes);
                sm.select(nodes,false,true);
            } else{
                sm.deselectAll();
            }
        }
    },
    highlight : function (id){
        if (this.tree != null){
            var view = this.tree.getView();
            var root = this.tree.getRootNode();
            var nodes = new Array();
            this.findChildrenByPointId(root,id,nodes);
            for (var i = 0;i < nodes.length;i++){
                var myNode = this.tree.getStore().getNodeById(nodes[i].internalId);
                var nodeElement = view.getNode(myNode);
                Ext.get(nodeElement).addCls(view.overItemCls);
            }
        }
    },
    unhighlight : function (id){
        if (this.tree != null){
            var view = this.tree.getView();
            var root = this.tree.getRootNode();
            var nodes = new Array();
            this.findChildrenByPointId(root,id,nodes);
            for (var i = 0;i < nodes.length;i++){
                var myNode = this.tree.getStore().getNodeById(nodes[i].internalId);
                var nodeElement = view.getNode(myNode);
                Ext.get(nodeElement).removeCls(view.overItemCls);
            }
        }
    },
    createRootNode : function (json){
        var store = {
            root : {
                expanded : true,
                children : []
            }
        };
        for (var key in json){
            var signalGroup = json[key];
            var bewegingen = new Array();
            for (var bKey in signalGroup){
                var mv = signalGroup[bKey];
                var mvNode = this.createMovementNode(mv,bKey);
                bewegingen.push(mvNode);
            }
            var node = {
                text : "Signaalgroep " + key,
                id : Ext.id(),//"sign-" + key,
                expanded : true,
                iconCls : "noTreeIcon",
                type : "signalGroup",
                children : bewegingen
            };
            store.root.children.push(node);
        }

        return store;
    },
    createMovementNode : function (json,key){
        var points = new Array();
        for (var i = 0;i < json.points.length;i++){
            var pt = this.createPointNode(json.points[i]);
            points.push(pt);
        }
        var label = this.getBewegingLabel(this.editor.activeRseq.getMovementById(json.id));
        var node = {
            text : label,
            id : Ext.id(),//"mvmt-" + json.id,
            expanded : true,
            icon : karTheme.richting,
            iconCls : 'overviewTree',
            type : "movement",
            children : points
        };
        return node;

    },
    createPointNode : function (point){
        var node = {
            text : point.getLabel(),
            id : Ext.id(),
            leaf : true,
            pointId : point.getId(),
            type : "point",
            iconCls : 'overviewTree',
            icon : this.getIconForPoint(point)
        };
        return node;
    },
    getIconForPoint : function (point){
        switch (point.getType()){
            case "ACTIVATION_1" :
                return karTheme.inmeldPunt;
                break;
            case "ACTIVATION_2" :
                return karTheme.uitmeldPunt;
                break;
            case "ACTIVATION_3" :
                return karTheme.voorinmeldPunt;
                break;
            case "BEGIN" :
                return karTheme.startPunt;
                break;
            case "END" :
                return karTheme.eindPunt;
                break;
        }

    },
    getBewegingLabel : function (mvmnt){
        var begin = null;
        var eind = null;
        for (var i = 0;i < mvmnt.maps.length;i++){
            var map = mvmnt.maps[i];
            var point = this.editor.activeRseq.getPointById(map.pointId);
            if (point.getType() == "END"){
                eind = point.getLabel();
            }

            if (point.getType() == "ACTIVATION_1"){
                begin = point.getLabel();
            }
            if (begin == null){
                if (point.getType() == "ACTIVATION_2"){
                    begin = point.getLabel();
                }
            }
        }

        var label = "Van " + begin + " naar " + eind;
        return label;
    },
    updateSize : function (){
        if (this.tree != null){
            var ov = Ext.get("rseqInfoPanel-body");
            this.tree.setHeight(ov.getHeight()- this.heightOffset);
        }
    },
    findChildrenByPointId : function (record,pointId,result){
        var me = this;
        record.eachChild(function (child){
            if (child.raw.pointId == pointId){
                result.push(child);
            }
            if (child.hasChildNodes()){
                me.findChildrenByPointId(child,pointId,result);
            }
        });
    },
    isPoint : function (object){
        if ((object.cluster == null || object.cluster == undefined) && object.data.type != "CROSSING" && object.data.type != "GUARD" && object.data.type != "BAR"){
            return true;
        } else{
            return false;
        }
    }
});<commit_msg>label correction<commit_after>/**
 * Geo-OV - applicatie voor het registreren van KAR meldpunten
 *
 * Copyright (C) 2009-2013 B3Partners B.V.
 *
 * 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/>.
 */
/**
 * Class for representing the currently selected trafficsystem
 *
 *
 */
Ext.define("nl.b3p.kar.Overview",{
    editor : null,
    domId : null,
    tree : null,
    heightOffset:null,
    constructor : function (editor,domId){
        this.editor = editor;
        this.domId = domId;
        this.heightOffset = 75;
        this.editor.on("activeRseqUpdated",this.updateOverview,this);
        this.editor.on("activeRseqChanged",this.updateOverview,this);
        this.editor.on('selectedObjectChanged',this.updateSelection,this);

        var panel = Ext.getCmp("rseqInfoPanel");
        panel.on('collapse',this.updateSize,this);
        panel.on('expand',this.updateSize,this);
        panel.on('resize',this.updateSize,this);

        this.editor.olc.highlight.events.register('featurehighlighted',this,function (evt){
            if (this.isPoint(evt.feature)){
                this.highlight(evt.feature.data.id);
            }
        });
        this.editor.olc.highlight.events.register('featureunhighlighted',this,function (evt){
            if (this.isPoint(evt.feature)){
                this.unhighlight(evt.feature.data.id);
            }
        });
    },
    updateOverview : function (rseq){
        Ext.get("context_vri").setHTML(rseq == null ? "" :
                (rseq.description + " (" + rseq.karAddress + ")"));
        Ext.get("rseqOptions").setVisible(rseq != null);
        var memoIcon = Ext.get("memo_vri");
        if (rseq.memo && rseq.memo != ""){
            memoIcon.setVisible(true);
        } else{
            memoIcon.setVisible(false);
        }

        var overzicht = Ext.get("overzicht");
        var tree = Ext.get("tree");
        if (tree){
            tree.remove();
        }
        var root = this.createRootNode(rseq.getOverviewJSON());
        var store = Ext.create('Ext.data.TreeStore',root);
        this.tree = Ext.create('Ext.tree.Panel',{
            border : false,
            header : false,
            id : "tree",
            selModel : {
                mode : "MULTI"
            },
            height :Ext.get("rseqInfoPanel-body").getHeight() - this.heightOffset,
            store : store,
            rootVisible : false,
            renderTo : overzicht,
            listeners : {
                scope : this,
                select : function (tree,record){
                    if (record.raw.type == "point"){
                        var id = record.raw.pointId;
                        var vectorLayer = this.editor.olc.vectorLayer;
                        var features = vectorLayer.getFeaturesByAttribute("id",id);
                        if (features != null && features.length > 0){
                            var feature = features[0];
                            this.editor.setSelectedObject(feature);
                        }
                    }
                },
                itemmouseenter : function (tree,record){
                    if (record.raw.type == "point"){
                        var id = record.raw.pointId;
                        var vectorLayer = this.editor.olc.vectorLayer;
                        var features = vectorLayer.getFeaturesByAttribute("id",id);
                        if (features != null && features.length > 0){
                            var feat = features[0];
                            if (feat.renderIntent != "select"){
                                feat.renderIntent = "temporary";
                                vectorLayer.redraw();
                            }
                        }
                    }
                },
                itemmouseleave : function (tree,record){
                    if (record.raw.type == "point"){
                        var id = record.raw.pointId;
                        var currentSelectedObject = this.editor.selectedObject;
                        if (currentSelectedObject == null || currentSelectedObject.getId() != id){
                            var vectorLayer = this.editor.olc.vectorLayer;
                            var features = vectorLayer.getFeaturesByAttribute("id",id);
                            if (features != null && features.length > 0){
                                var feat = features[0];
                                feat.renderIntent = "default";
                                vectorLayer.redraw();
                            }
                        }
                    }
                },
                itemcontextmenu : function (view,record,item,index,event,eOpts){
                    var type = record.raw.type;
                    if (type != "signalGroup" && type != "movement"){
                        this.editor.contextMenu.show(event.xy[0],event.xy[1],false);
                    }
                }
            }
        });
        this.editor.helpPanel.updateHelpPanel();
    },
    updateSelection : function (point){
        if (this.tree != null){
            var sm = this.tree.getSelectionModel();
            if (point != null && point instanceof Point){
                this.unhighlight(point.getId());
                var root = this.tree.getRootNode();
                var nodes = new Array();
                this.findChildrenByPointId(root,point.getId(),nodes);
                sm.select(nodes,false,true);
            } else{
                sm.deselectAll();
            }
        }
    },
    highlight : function (id){
        if (this.tree != null){
            var view = this.tree.getView();
            var root = this.tree.getRootNode();
            var nodes = new Array();
            this.findChildrenByPointId(root,id,nodes);
            for (var i = 0;i < nodes.length;i++){
                var myNode = this.tree.getStore().getNodeById(nodes[i].internalId);
                var nodeElement = view.getNode(myNode);
                Ext.get(nodeElement).addCls(view.overItemCls);
            }
        }
    },
    unhighlight : function (id){
        if (this.tree != null){
            var view = this.tree.getView();
            var root = this.tree.getRootNode();
            var nodes = new Array();
            this.findChildrenByPointId(root,id,nodes);
            for (var i = 0;i < nodes.length;i++){
                var myNode = this.tree.getStore().getNodeById(nodes[i].internalId);
                var nodeElement = view.getNode(myNode);
                Ext.get(nodeElement).removeCls(view.overItemCls);
            }
        }
    },
    createRootNode : function (json){
        var store = {
            root : {
                expanded : true,
                children : []
            }
        };
        for (var key in json){
            var signalGroup = json[key];
            var bewegingen = new Array();
            for (var bKey in signalGroup){
                var mv = signalGroup[bKey];
                var mvNode = this.createMovementNode(mv,bKey);
                bewegingen.push(mvNode);
            }
            var node = {
                text : "Signaalgroep " + key,
                id : Ext.id(),//"sign-" + key,
                expanded : true,
                iconCls : "noTreeIcon",
                type : "signalGroup",
                children : bewegingen
            };
            store.root.children.push(node);
        }

        return store;
    },
    createMovementNode : function (json,key){
        var points = new Array();
        for (var i = 0;i < json.points.length;i++){
            var pt = this.createPointNode(json.points[i]);
            points.push(pt);
        }
        var label = this.getBewegingLabel(this.editor.activeRseq.getMovementById(json.id));
        var node = {
            text : label,
            id : Ext.id(),//"mvmt-" + json.id,
            expanded : true,
            icon : karTheme.richting,
            iconCls : 'overviewTree',
            type : "movement",
            children : points
        };
        return node;

    },
    createPointNode : function (point){
        var node = {
            text : point.getLabel(),
            id : Ext.id(),
            leaf : true,
            pointId : point.getId(),
            type : "point",
            iconCls : 'overviewTree',
            icon : this.getIconForPoint(point)
        };
        return node;
    },
    getIconForPoint : function (point){
        switch (point.getType()){
            case "ACTIVATION_1" :
                return karTheme.inmeldPunt;
                break;
            case "ACTIVATION_2" :
                return karTheme.uitmeldPunt;
                break;
            case "ACTIVATION_3" :
                return karTheme.voorinmeldPunt;
                break;
            case "BEGIN" :
                return karTheme.startPunt;
                break;
            case "END" :
                return karTheme.eindPunt;
                break;
        }

    },
    getBewegingLabel : function (mvmnt){
        var begin = null;
        var eind = null;
        for (var i = 0;i < mvmnt.maps.length;i++){
            var map = mvmnt.maps[i];
            var point = this.editor.activeRseq.getPointById(map.pointId);
            if (point.getType() == "END"){
                eind = point.getLabel();
            }

            if (point.getType() == "ACTIVATION_1"){
                begin = point.getLabel();
            }
            if (begin == null){
                if (point.getType() == "ACTIVATION_2"){
                    begin = point.getLabel();
                }
            }
        }

        var label = "Van " + begin + " naar " + eind;
        if(label == 'Van  naar '){
            label = '';
        }

        return label;
    },
    updateSize : function (){
        if (this.tree != null){
            var ov = Ext.get("rseqInfoPanel-body");
            this.tree.setHeight(ov.getHeight()- this.heightOffset);
        }
    },
    findChildrenByPointId : function (record,pointId,result){
        var me = this;
        record.eachChild(function (child){
            if (child.raw.pointId == pointId){
                result.push(child);
            }
            if (child.hasChildNodes()){
                me.findChildrenByPointId(child,pointId,result);
            }
        });
    },
    isPoint : function (object){
        if ((object.cluster == null || object.cluster == undefined) && object.data.type != "CROSSING" && object.data.type != "GUARD" && object.data.type != "BAR"){
            return true;
        } else{
            return false;
        }
    }
});<|endoftext|>


<commit_before>/**
 * UserController
 * @namespace crowdsource.worker.controllers
 */
(function () {
    'use strict';

    angular
        .module('crowdsource.user.controllers')
        .controller('UserController', UserController);

    UserController.$inject = ['$state', '$scope', '$window', '$mdToast', '$mdDialog', '$q', 'Authentication', 'User', 'Payment'];

    /**
     * @namespace UserController
     */

    function UserController($state, $scope, $window, $mdToast, $mdDialog, $q, Authentication, User, Payment) {
        var vm = this;

        var userAccount = Authentication.getAuthenticatedAccount();

        var PlaceService = new google.maps.places.AutocompleteService();

        vm.initialize = initialize;
        vm.update = update;
        vm.paypal_payment = paypal_payment;
        vm.searchText = null;
        vm.jobTitleSearch = jobTitleSearch;
        vm.addressSearch = addressSearch;
        vm.paypal_payment = paypal_payment;
        vm.aws_account = null;
        vm.create_or_update_aws = create_or_update_aws;
        vm.removeAWSAccount = removeAWSAccount;
        vm.awsAccountEdit = false;
        vm.AWSError = null;
        vm.autocompleteError = false;

        activate();

        initialize();

        function initialize() {
            vm.genders = [
                {key: "M", value: "Male"},
                {key: "F", value: "Female"},
                {key: "O", value: "Other"}
            ];
            vm.ethnicities = [
                {key: "white", value: "White"},
                {key: "hispanic", value: "Hispanic"},
                {key: "black", value: "Black"},
                {key: "islander", value: "Native Hawaiian or Other Pacific Islander"},
                {key: "indian", value: "Indian"},
                {key: "asian", value: "Asian"},
                {key: "native", value: "Native American or Alaska Native"},
                {key: "mixed", value: "Mixed Race"},
                {key: "other", value: "Other"}
            ];
            vm.incomes = [
                {key: 'less_1k', value: 'Less than $1,000'},
                {key: '1k', value: '$1,000 - $1,999'},
                {key: '2.5k', value: '$2,500 - $4,999'},
                {key: '5k', value: '$5,000 - $7,499'},
                {key: '7.5k', value: '$7,500 - $9,999'},
                {key: '10k', value: '$10,000 - $14,999'},
                {key: '15k', value: '$15,000 - $24,999'},
                {key: '25k', value: '$25,000 - $39,999'},
                {key: '40k', value: '$40,000 - $59,999'},
                {key: '60k', value: '$60,000 - $74,999'},
                {key: '75k', value: '$75,000 - $99,999'},
                {key: '100k', value: '$100,000 - $149,999'},
                {key: '150k', value: '$150,000 - $199,999'},
                {key: '200k', value: '$200,000 - $299,999'},
                {key: '300k_more', value: '$300,000 or more'}
            ];
            vm.educations = [
                {key: 'some_high', value: 'Some High School, No Degree'},
                {key: 'high', value: 'High School Degree or Equivalent'},
                {key: 'some_college', value: 'Some College, No Degree'},
                {key: 'associates', value: 'Associates Degree'},
                {key: 'bachelors', value: 'Bachelors Degree'},
                {key: 'masters', value: 'Graduate Degree, Masters'},
                {key: 'doctorate', value: 'Graduate Degree, Doctorate'}
            ];

            //User.getCountries().then(function (response) {
            //    vm.countries = _.sortBy(response[0], 'name');
            //});
            //
            //User.getCities().then(function (response) {
            //    vm.cities = _.sortBy(response[0], 'name');
            //});

            User.getJobTitles().then(function (response) {
                vm.job_titles = response.data;
            });

            getProfile();
        }

        function addressSearch(address) {
            var deferred = $q.defer();
            getResults(address).then(
                function (predictions) {
                    var results = [];
                    for (var i = 0, prediction; prediction = predictions[i]; i++) {
                        results.push(prediction);
                    }
                    deferred.resolve(results);
                }
            );
            return deferred.promise;
        }

        function getResults(address) {
            var deferred = $q.defer();
            if (address) {
                PlaceService.getPlacePredictions({input: address}, function (data) {
                    deferred.resolve(data);
                });
            } else {
                deferred.resolve('');
            }
            return deferred.promise;
        }

        function getProfile() {
            User.getProfile(userAccount.username)
                .then(function (data) {
                    var user = data[0];
                    if (user.hasOwnProperty('financial_accounts') && user.financial_accounts) {
                        user.financial_accounts = _.filter(user.financial_accounts.map(function (account) {
                            var mapping = {
                                'general': 'general',
                                'requester': 'Deposits',
                                'worker': 'Earnings'
                            };

                            account.type = mapping[account.type];
                            return account;
                        }), function (account) {
                            return account.type != 'general';
                        });
                    }
                    vm.user = angular.copy(user);

                    if (user.birthday) {
                        vm.user.birthday = new Date(user.birthday);
                    } else {
                        vm.user.birthday = null;
                    }

                    vm.user.gender = _.find(vm.genders, function (gender) {
                        return gender.key == vm.user.gender;
                    });

                    vm.user.ethnicity = _.find(vm.ethnicities, function (ethnicity) {
                        return ethnicity.key == vm.user.ethnicity;
                    });

                    vm.user.income = _.find(vm.incomes, function (income) {
                        return income.key == vm.user.income;
                    });
                    vm.user.education = _.find(vm.educations, function (education) {
                        return education.key == vm.user.education;
                    });

                    vm.user.workerId = user.id;     // Make worker id specific
                    var address = [];
                    if (vm.user.address) {
                        if (user.address.street) {
                            address.push(vm.user.address.street);
                        }
                        if (vm.user.address.city) {
                            address.push(vm.user.address.city.name);
                            if (vm.user.address.city.state_code) {
                                address.push(vm.user.address.city.state_code);
                            }
                            if (vm.user.address.city.country) {
                                address.push(vm.user.address.city.country.name);
                            }
                        }
                    }
                    //if (vm.user.address && vm.user.address.city) {
                    //    console.log(vm.user.address.city);
                    //    address.push(vm.user.address.city.name);
                    //
                    //    vm.city = _.find(vm.cities, function (city) {
                    //        return city.id == vm.user.address.city.id;
                    //    });
                    //}

                    //if (vm.user.address && vm.user.address.country) {
                    //    console.log(vm.user.address.country);
                    //    address.push(vm.user.address.country.name);
                    //
                    //    vm.country = _.find(vm.countries, function (country) {
                    //        return country.id == vm.user.address.country.id;
                    //    });
                    //}

                    vm.user.address_text = address.join(", ");
                });
        }

        function jobTitleSearch(query) {
            return query ? _.filter(vm.job_titles, function (job_title) {
                return (angular.lowercase(job_title).indexOf(angular.lowercase(query)) !== -1)
            }) : [];
        }

        function update() {
            var user = angular.copy(vm.user);
            if (vm.addressSearchValue !== "" && vm.user.address_text === null) {
                vm.autocompleteError = true;
                return;
            }
            if (vm.addressSearchValue !== "" && vm.user.address_text.place_id !== undefined) {
                var service = new google.maps.places.PlacesService(document.getElementById('node'));
                service.getDetails({placeId:vm.user.address_text.place_id}, function(result, status) {
                    console.log(result);
                    var street_number = "";
                    var street = "";
                    user.location = {};
                    for (var i = 0; i < result.address_components.length; i++) {
                        if (result.address_components[i].types.includes("locality")) {
                            user.location.city = result.address_components[i].long_name;
                        }
                        if (result.address_components[i].types.includes("country")) {
                            user.location.country = result.address_components[i].long_name;
                            user.location.country_code = result.address_components[i].short_name;
                        }
                        if (result.address_components[i].types.includes("administrative_area_level_1")) {
                            user.location.state = result.address_components[i].long_name;
                            user.location.state_code = result.address_components[i].short_name;
                        }
                        if (result.address_components[i].types.includes("street_number")) {
                            var street_number = result.address_components[i].long_name;
                        }
                        if (result.address_components[i].types.includes("route")) {
                            var street = result.address_components[i].long_name;
                        }
                    }
                    if (user.location.city === undefined || user.location.country === undefined) {
                        vm.autocompleteError = true;
                        return;
                    }
                    vm.autocompleteError = false;

                    if (street_number === "" && street !== "") {
                        user.location.address = street;
                    } else if (street_number !== "" && street !== "") {
                        user.location.address = street_number.concat(" ").concat(street);
                    } else {
                        user.location.address = "";
                    }

                    if (user.gender) {
                        user.gender = user.gender.key;
                    }

                    if (user.ethnicity) {
                        user.ethnicity = user.ethnicity.key;
                    }

                    if (user.income) {
                        user.income = user.income.key;
                    }

                    if (user.education) {
                        user.education = user.education.key;
                    }
                    console.log(user);
                    User.updateProfile(userAccount.username, user)
                    .then(function (data) {
                        getProfile();
                        vm.edit = false;
                        $mdToast.showSimple('Profile updated');
                        });
                });
            } else {
                if (vm.addressSearchValue === "") {
                    user.location = {};
                }
                if (user.gender) {
                    user.gender = user.gender.key;
                }
                if (user.ethnicity) {
                    user.ethnicity = user.ethnicity.key;
                }

                if (user.income) {
                    user.income = user.income.key;
                }

                if (user.education) {
                    user.education = user.education.key;
                }
                User.updateProfile(userAccount.username, user)
                .then(function (data) {
                    getProfile();
                    vm.edit = false;
                    $mdToast.showSimple('Profile updated');
                    });
            }
        }

        function activate() {
            User.get_aws_account().then(
                function success(response) {
                    vm.aws_account = response[0];
                },
                function error(response) {

                }
            );
        }

        function create_or_update_aws() {
            if (vm.aws_account.client_secret == null || vm.aws_account.client_id == null) {
                $mdToast.showSimple('Client key and secret are required');
            }
            User.create_or_update_aws(vm.aws_account).then(
                function success(response) {
                    vm.aws_account = response[0];
                    vm.awsAccountEdit = false;
                    vm.AWSError = null;
                },
                function error(response) {
                    vm.AWSError = 'Invalid keys, please try again.';
                }
            ).finally(function () {

            });
        }

        function removeAWSAccount() {
            User.removeAWSAccount().then(
                function success(response) {
                    vm.aws_account = null;
                    vm.awsAccountEdit = false;
                },
                function error(response) {

                }
            ).finally(function () {

            });
        }

        function paypal_payment($event) {
            $mdDialog.show({
                clickOutsideToClose: false,
                preserveScope: false,
                targetEvent: $event,
                templateUrl: '/static/templates/payment/payment.html',
                locals: {
                    dialog: $mdDialog
                },
                controller: DialogController
            });

            function DialogController($scope, dialog) {

                $scope.payment_in_progress = false;

                $scope.payment_methods = [
                    {name: 'Paypal', method: 'paypal'},
                    {name: 'Credit Card', method: 'credit_card'}
                ];

                $scope.card_types = [
                    {name: 'Visa', type: 'visa'},
                    {name: 'MasterCard', type: 'mastercard'},
                    {name: 'Discover', type: 'discover'},
                    {name: 'American Express', type: 'american_express'}
                ];

                $scope.payment = {
                    amount: 1.00,
                    method: 'paypal',
                    type: 'self'
                };

                $scope.$watch('payment.method', function (newValue, oldValue) {
                    if (newValue != oldValue && newValue == 'paypal') {
                        if ($scope.payment.hasOwnProperty('credit_card')) {
                            delete $scope.payment.credit_card;
                        }
                    }
                });

                $scope.pay = function () {
                    $scope.payment_in_progress = true;

                    var data = angular.copy($scope.payment);

                    if (data.method == 'credit_card') {
                        data.credit_card.number = '' + data.credit_card.number;
                    }

                    Payment.create(data).then(
                        function success(response) {
                            if (data.method == 'credit_card') {
                                $mdToast.showSimple(response.message);
                                $state.go('profile');
                            } else {
                                $window.location.href = response[0].redirect_url;
                            }
                        },
                        function error(response) {
                            $mdToast.showSimple('Error during payment. Please try again.');
                        }
                    ).finally(function () {
                        $scope.payment_in_progress = false;
                    });
                };

                $scope.hide = function () {
                    dialog.hide();
                };
                $scope.cancel = function () {
                    dialog.cancel();
                };

            }
        }
    }
})();
<commit_msg>Replaced details result for loop with _.filter<commit_after>/**
 * UserController
 * @namespace crowdsource.worker.controllers
 */
(function () {
    'use strict';

    angular
        .module('crowdsource.user.controllers')
        .controller('UserController', UserController);

    UserController.$inject = ['$state', '$scope', '$window', '$mdToast', '$mdDialog', '$q', 'Authentication', 'User', 'Payment'];

    /**
     * @namespace UserController
     */

    function UserController($state, $scope, $window, $mdToast, $mdDialog, $q, Authentication, User, Payment) {
        var vm = this;

        var userAccount = Authentication.getAuthenticatedAccount();

        var PlaceService = new google.maps.places.AutocompleteService();

        vm.initialize = initialize;
        vm.update = update;
        vm.paypal_payment = paypal_payment;
        vm.searchText = null;
        vm.jobTitleSearch = jobTitleSearch;
        vm.addressSearch = addressSearch;
        vm.paypal_payment = paypal_payment;
        vm.aws_account = null;
        vm.create_or_update_aws = create_or_update_aws;
        vm.removeAWSAccount = removeAWSAccount;
        vm.awsAccountEdit = false;
        vm.AWSError = null;
        vm.autocompleteError = false;

        activate();

        initialize();

        function initialize() {
            vm.genders = [
                {key: "M", value: "Male"},
                {key: "F", value: "Female"},
                {key: "O", value: "Other"}
            ];
            vm.ethnicities = [
                {key: "white", value: "White"},
                {key: "hispanic", value: "Hispanic"},
                {key: "black", value: "Black"},
                {key: "islander", value: "Native Hawaiian or Other Pacific Islander"},
                {key: "indian", value: "Indian"},
                {key: "asian", value: "Asian"},
                {key: "native", value: "Native American or Alaska Native"},
                {key: "mixed", value: "Mixed Race"},
                {key: "other", value: "Other"}
            ];
            vm.incomes = [
                {key: 'less_1k', value: 'Less than $1,000'},
                {key: '1k', value: '$1,000 - $1,999'},
                {key: '2.5k', value: '$2,500 - $4,999'},
                {key: '5k', value: '$5,000 - $7,499'},
                {key: '7.5k', value: '$7,500 - $9,999'},
                {key: '10k', value: '$10,000 - $14,999'},
                {key: '15k', value: '$15,000 - $24,999'},
                {key: '25k', value: '$25,000 - $39,999'},
                {key: '40k', value: '$40,000 - $59,999'},
                {key: '60k', value: '$60,000 - $74,999'},
                {key: '75k', value: '$75,000 - $99,999'},
                {key: '100k', value: '$100,000 - $149,999'},
                {key: '150k', value: '$150,000 - $199,999'},
                {key: '200k', value: '$200,000 - $299,999'},
                {key: '300k_more', value: '$300,000 or more'}
            ];
            vm.educations = [
                {key: 'some_high', value: 'Some High School, No Degree'},
                {key: 'high', value: 'High School Degree or Equivalent'},
                {key: 'some_college', value: 'Some College, No Degree'},
                {key: 'associates', value: 'Associates Degree'},
                {key: 'bachelors', value: 'Bachelors Degree'},
                {key: 'masters', value: 'Graduate Degree, Masters'},
                {key: 'doctorate', value: 'Graduate Degree, Doctorate'}
            ];

            //User.getCountries().then(function (response) {
            //    vm.countries = _.sortBy(response[0], 'name');
            //});
            //
            //User.getCities().then(function (response) {
            //    vm.cities = _.sortBy(response[0], 'name');
            //});

            User.getJobTitles().then(function (response) {
                vm.job_titles = response.data;
            });

            getProfile();
        }

        function addressSearch(address) {
            var deferred = $q.defer();
            getResults(address).then(
                function (predictions) {
                    var results = [];
                    for (var i = 0, prediction; prediction = predictions[i]; i++) {
                        results.push(prediction);
                    }
                    deferred.resolve(results);
                }
            );
            return deferred.promise;
        }

        function getResults(address) {
            var deferred = $q.defer();
            if (address) {
                PlaceService.getPlacePredictions({input: address}, function (data) {
                    deferred.resolve(data);
                });
            } else {
                deferred.resolve('');
            }
            return deferred.promise;
        }

        function getProfile() {
            User.getProfile(userAccount.username)
                .then(function (data) {
                    var user = data[0];
                    if (user.hasOwnProperty('financial_accounts') && user.financial_accounts) {
                        user.financial_accounts = _.filter(user.financial_accounts.map(function (account) {
                            var mapping = {
                                'general': 'general',
                                'requester': 'Deposits',
                                'worker': 'Earnings'
                            };

                            account.type = mapping[account.type];
                            return account;
                        }), function (account) {
                            return account.type != 'general';
                        });
                    }
                    vm.user = angular.copy(user);

                    if (user.birthday) {
                        vm.user.birthday = new Date(user.birthday);
                    } else {
                        vm.user.birthday = null;
                    }

                    vm.user.gender = _.find(vm.genders, function (gender) {
                        return gender.key == vm.user.gender;
                    });

                    vm.user.ethnicity = _.find(vm.ethnicities, function (ethnicity) {
                        return ethnicity.key == vm.user.ethnicity;
                    });

                    vm.user.income = _.find(vm.incomes, function (income) {
                        return income.key == vm.user.income;
                    });
                    vm.user.education = _.find(vm.educations, function (education) {
                        return education.key == vm.user.education;
                    });

                    vm.user.workerId = user.id;     // Make worker id specific
                    var address = [];
                    if (vm.user.address) {
                        if (user.address.street) {
                            address.push(vm.user.address.street);
                        }
                        if (vm.user.address.city) {
                            address.push(vm.user.address.city.name);
                            if (vm.user.address.city.state_code) {
                                address.push(vm.user.address.city.state_code);
                            }
                            if (vm.user.address.city.country) {
                                address.push(vm.user.address.city.country.name);
                            }
                        }
                    }
                    //if (vm.user.address && vm.user.address.city) {
                    //    console.log(vm.user.address.city);
                    //    address.push(vm.user.address.city.name);
                    //
                    //    vm.city = _.find(vm.cities, function (city) {
                    //        return city.id == vm.user.address.city.id;
                    //    });
                    //}

                    //if (vm.user.address && vm.user.address.country) {
                    //    console.log(vm.user.address.country);
                    //    address.push(vm.user.address.country.name);
                    //
                    //    vm.country = _.find(vm.countries, function (country) {
                    //        return country.id == vm.user.address.country.id;
                    //    });
                    //}

                    vm.user.address_text = address.join(", ");
                });
        }

        function jobTitleSearch(query) {
            return query ? _.filter(vm.job_titles, function (job_title) {
                return (angular.lowercase(job_title).indexOf(angular.lowercase(query)) !== -1)
            }) : [];
        }

        function update() {
            var user = angular.copy(vm.user);
            if (vm.addressSearchValue !== "" && vm.user.address_text === null) {
                vm.autocompleteError = true;
                return;
            }
            if (vm.addressSearchValue !== "" && vm.user.address_text.place_id !== undefined) {
                var service = new google.maps.places.PlacesService(document.getElementById('node'));
                service.getDetails({placeId:vm.user.address_text.place_id}, function(result, status) {
                    var street_number = "";
                    var street = "";
                    user.location = {};
                    var city = _.find(result.address_components,
                        function(address_component){ return address_component.types.includes("locality") });
                    if (city !== undefined) {
                        user.location.city = city.long_name
                    }

                    var country = _.find(result.address_components,
                        function(address_component){ return address_component.types.includes("country") });
                    if (city !== undefined) {
                        user.location.country = country.long_name;
                        user.location.country_code = country.short_name;
                    }

                    var state = _.find(result.address_components,
                        function(address_component){ return address_component.types.includes("administrative_area_level_1") });
                    if (state !== undefined) {
                        user.location.state = state.long_name;
                        user.location.state_code = state.short_name;
                    }

                    var street_number_component = _.find(result.address_components,
                        function(address_component){ return address_component.types.includes("street_number") });
                    if (street_number_component !== undefined) {
                        street_number = street_number_component.long_name;
                    }

                    var street_component = _.find(result.address_components,
                        function(address_component){ return address_component.types.includes("route") });
                    if (street_component !== undefined) {
                        street = street_component.long_name;
                    }

                    if (user.location.city === undefined || user.location.country === undefined) {
                        vm.autocompleteError = true;
                        return;
                    }
                    vm.autocompleteError = false;

                    if (street_number === "" && street !== "") {
                        user.location.address = street;
                    } else if (street_number !== "" && street !== "") {
                        user.location.address = street_number.concat(" ").concat(street);
                    } else {
                        user.location.address = "";
                    }

                    if (user.gender) {
                        user.gender = user.gender.key;
                    }

                    if (user.ethnicity) {
                        user.ethnicity = user.ethnicity.key;
                    }

                    if (user.income) {
                        user.income = user.income.key;
                    }

                    if (user.education) {
                        user.education = user.education.key;
                    }
                    User.updateProfile(userAccount.username, user)
                    .then(function (data) {
                        getProfile();
                        vm.edit = false;
                        $mdToast.showSimple('Profile updated');
                        });
                });
            } else {
                if (vm.addressSearchValue === "") {
                    user.location = {};
                }
                if (user.gender) {
                    user.gender = user.gender.key;
                }
                if (user.ethnicity) {
                    user.ethnicity = user.ethnicity.key;
                }

                if (user.income) {
                    user.income = user.income.key;
                }

                if (user.education) {
                    user.education = user.education.key;
                }
                User.updateProfile(userAccount.username, user)
                .then(function (data) {
                    getProfile();
                    vm.edit = false;
                    $mdToast.showSimple('Profile updated');
                    });
            }
        }

        function activate() {
            User.get_aws_account().then(
                function success(response) {
                    vm.aws_account = response[0];
                },
                function error(response) {

                }
            );
        }

        function create_or_update_aws() {
            if (vm.aws_account.client_secret == null || vm.aws_account.client_id == null) {
                $mdToast.showSimple('Client key and secret are required');
            }
            User.create_or_update_aws(vm.aws_account).then(
                function success(response) {
                    vm.aws_account = response[0];
                    vm.awsAccountEdit = false;
                    vm.AWSError = null;
                },
                function error(response) {
                    vm.AWSError = 'Invalid keys, please try again.';
                }
            ).finally(function () {

            });
        }

        function removeAWSAccount() {
            User.removeAWSAccount().then(
                function success(response) {
                    vm.aws_account = null;
                    vm.awsAccountEdit = false;
                },
                function error(response) {

                }
            ).finally(function () {

            });
        }

        function paypal_payment($event) {
            $mdDialog.show({
                clickOutsideToClose: false,
                preserveScope: false,
                targetEvent: $event,
                templateUrl: '/static/templates/payment/payment.html',
                locals: {
                    dialog: $mdDialog
                },
                controller: DialogController
            });

            function DialogController($scope, dialog) {

                $scope.payment_in_progress = false;

                $scope.payment_methods = [
                    {name: 'Paypal', method: 'paypal'},
                    {name: 'Credit Card', method: 'credit_card'}
                ];

                $scope.card_types = [
                    {name: 'Visa', type: 'visa'},
                    {name: 'MasterCard', type: 'mastercard'},
                    {name: 'Discover', type: 'discover'},
                    {name: 'American Express', type: 'american_express'}
                ];

                $scope.payment = {
                    amount: 1.00,
                    method: 'paypal',
                    type: 'self'
                };

                $scope.$watch('payment.method', function (newValue, oldValue) {
                    if (newValue != oldValue && newValue == 'paypal') {
                        if ($scope.payment.hasOwnProperty('credit_card')) {
                            delete $scope.payment.credit_card;
                        }
                    }
                });

                $scope.pay = function () {
                    $scope.payment_in_progress = true;

                    var data = angular.copy($scope.payment);

                    if (data.method == 'credit_card') {
                        data.credit_card.number = '' + data.credit_card.number;
                    }

                    Payment.create(data).then(
                        function success(response) {
                            if (data.method == 'credit_card') {
                                $mdToast.showSimple(response.message);
                                $state.go('profile');
                            } else {
                                $window.location.href = response[0].redirect_url;
                            }
                        },
                        function error(response) {
                            $mdToast.showSimple('Error during payment. Please try again.');
                        }
                    ).finally(function () {
                        $scope.payment_in_progress = false;
                    });
                };

                $scope.hide = function () {
                    dialog.hide();
                };
                $scope.cancel = function () {
                    dialog.cancel();
                };

            }
        }
    }
})();
<|endoftext|>


<commit_before>/*jslint browser: true*/
/*global define window*/

define(['orion/URITemplate', 'domReady!'], function(URITemplate, document) {
	var pluginsData = [
		{	name: "JS Beautify",
			description: 'Cleans up the formatting of your JavaScript code using jsbeautifier.',
			versions: {
				"0.2|0.3|0.4|0.5": ["/0.2/plugins/beautify/jsbeautify.html", "https://github.com/mamacdon/mamacdon.github.com/tree/master/m6/beautify"]
			}
		},
		{	name: "Uglify",
			description: 'Minifies your JavaScript code using uglify-js.',
			versions: {
				/*"0.2 M6/M7": ["/m6/uglify/uglify-plugin.html", "https://github.com/mamacdon/mamacdon.github.com/tree/master/m6/uglify"],*/
				"0.2|0.3|0.4|0.5": ["/0.2/plugins/uglify/uglify-plugin.html", "https://github.com/mamacdon/mamacdon.github.com/tree/master/0.2/plugins/uglify"]
			}
		},
		{	name: "CSSLint",
			description: 'Provides validation and style tips on your CSS files using CSS Lint. (Included with Orion by default starting in 0.4)',
			versions: {
				"0.2": ["/0.2/plugins/csslint/csslintPlugin.html", "https://github.com/mamacdon/mamacdon.github.com/tree/master/0.2/plugins/csslint"],
				"0.3": ["/0.3/plugins/csslint/csslintPlugin.html", "https://github.com/mamacdon/mamacdon.github.com/tree/master/0.3/plugins/csslint"]
			}
		},
		{	name: "reverse",
			description: 'A minimal plugin example used as part of a tutorial.',
			versions: {
				"0.2|0.3": ["/0.2/plugins/reverse/reversePlugin.html", "https://github.com/mamacdon/mamacdon.github.com/tree/master/0.2/plugins/reverse"]
			}
		},
		{	name: "Bugzilla",
			description: 'A Bugzilla integration plugin for Orion.',
			versions: {
				"0.3|0.4|0.5": ["/0.3/plugins/bugzilla/plugin.html", "https://github.com/mamacdon/mamacdon.github.com/tree/master/0.3/plugins/bugzilla"]
			}
		},
		//{	name: "language.js",
		//	description: 'Provides content assist suggestions JavaScript identifiers using language.js.',
		//	experimental: true,
		//	versions: {
		//		"0.2": [
		//			"/0.2/plugins/language/languagejsPlugin.html",
		//			"https://github.com/mamacdon/mamacdon.github.com/tree/master/0.2/plugins/language/"
		//		],
		//		"0.3": [
		//			"/0.2/plugins/language/languagejsPlugin.html",
		//			"https://github.com/mamacdon/mamacdon.github.com/tree/master/0.2/plugins/language/"
		//		]
		//	}
		//},
		{	name: "JavaScript hierarchical outline",
			description: 'Provides a simple tree view of the functions in a JavaScript file.',
			experimental: true,
			versions: {
				"0.3|0.4|0.5": ["http://mamacdon.github.com/outliner/outlinerPlugin.html", "https://github.com/mamacdon/outliner"]
			}
		},
		{	name: "Nonymous outline",
			description: 'Provides a tree view of JavaScript functions using the \"Function-Object Consumption\" algorithm to generate meaningful names for anonymous functions.',
			experimental: true,
			versions: {
				"0.3|0.4|0.5": ["http://johnjbarton.github.com/outliner/nonymousPlugin.html", "https://github.com/johnjbarton/outliner"]
			}
		},
		{	name: "CodeMirror highlighting",
			description: 'Uses CodeMirror modes to highlight your code.',
			experimental: true,
			versions: {
				"0.4|0.5": ["http://mamacdon.github.com/orion-codemirror/codeMirrorPlugin.html", "https://github.com/mamacdon/orion-codemirror"]
			}
		},
		{	name: "HTML Outline",
			description: 'Provides a hierarchical outline of the elements in an HTML file.',
			versions: {
				"0.4|0.5": ["http://jarthorn.github.com/html-tools/htmlOutlinePlugin.html", "https://github.com/jarthorn/html-tools"]
			}
		},
		{	name: "Esprima outline",
			description: 'Uses the esprima JavaScript parser to provide a detailed outline of your JavaScript code.',
			versions: {
				"0.4|0.5": ["http://aclement.github.com/esprima-outline/esprimaOutlinerPlugin.html", "https://github.com/aclement/esprima-outline"]
			}
		},
		{
			name: "Esprima content assist",
			description: "Offers completion and type inference for JavaScript files.",
			versions: {
				"0.4|0.5": ["http://aeisenberg.github.com/esprimaContentAssist/esprimaJsContentAssistPlugin.html", "https://github.com/aeisenberg/esprimaContentAssist"]
			}
		},
		{	name: "Amazon S3 filesystem",
			description: "Provides access to an Amazon S3 bucket as a filesystem. See README for installation instructions.",
			versions: {
				"0.4|0.5": [null, "https://github.com/mamacdon/orion-s3/"]
			}
		}
		];

	var TARGET = "target", VERSION = "version";

	(function() {
		// Turn 'pluginsData' JSON structure into objects with behavior.
		(function unmarshallPlugins() {
			function Plugin(source) {
				var keys = Object.keys(source);
				for (var i=0; i < keys.length; i++) {
					this[keys[i]] = source[keys[i]];
				}
			}
			Plugin.prototype = {
				getDescription: function() { return this.description; },
				getInstallURL: function(version) {
					var ver = this.getVersion(version);
					return (ver && ver[0]) || null;
				},
				getSourceURL: function(version) {
					var ver = this.getVersion(version);
					return (ver && ver[1]) || null;
				},
				getName: function() { return this.name; },
				getVersion: function(versionId) {
					var keys = Object.keys(this.versions);
					for (var i=0; i < keys.length; i++) {
						var ver = keys[i];
						if (ver.split("|").indexOf(versionId) !== -1) {
							return this.versions[ver];
						}
					}
					return null;
				},
				getVersionIds: function() {
					var versions = Object.keys(this.versions);
					var keys = [];
					for (var i=0; i < versions.length; i++) {
						var vs = versions[i].split("|");
						for (var j=0; j < vs.length; j++) {
							keys.push(vs[j]);
						}
					}
					return keys;
				}
			};
			for (var i = 0; i < pluginsData.length; i++) {
				pluginsData[i] = new Plugin(pluginsData[i]);
			}
		}());
		function getPluginsMatching(predicate) {
			var plugins = [];
			for (var i=0; i < pluginsData.length; i++) {
				var plugin = pluginsData[i];
				if (predicate(plugin)) {
					plugins.push(plugin);
				}
			}
			return plugins;
		}
		function getAllVersions(/**Plugin[]*/ plugins) {
			var versions = {};
			for (var i=0; i < plugins.length; i++) {
				var versionIds = plugins[i].getVersionIds();
				for (var j=0; j < versionIds.length; j++) {
					versions[versionIds[j]] = null;
				}
			}
			return Object.keys(versions);
		}
		function parseParameters() {
			var params = {};
			var hash = window.location.hash && window.location.hash.substr(1);
			if (hash) {
				var array = hash.split(/\?|,|&|(=)/);
				for (var i=0; i < array.length; i++) {
					var key = array[i];
					if (key && array[i + 1] === "=") {
						params[key] = array[i + 2];
						i++;
					}
				}
			}
			return params;
		}
		function createTbody(table, plugins, params) {
			function createHeaderRow(table, versions) {
				var headerRow = table.insertRow(-1);
				var th = document.createElement("th");
				th.innerHTML = "";
				headerRow.appendChild(th);
				if (params[VERSION]) {
					th = document.createElement("th");
					th.innerHTML = "";
					headerRow.appendChild(th);
				} else {
					for (var i=0; i < versions.length; i++) {
						th = document.createElement("th");
						th.innerHTML = "Orion " + versions[i];
						headerRow.appendChild(th);
					}
				}
			}
			function getQualifiedInstallURL(target, /**Plugin*/ plugin, versionId) {
				function qualify(url) {
					var a = document.createElement('a');
					a.href = url;
					return a.href;
				}
				var url = plugin.getInstallURL(versionId);
				return new URITemplate(target + "#{,resource,params*}").expand({
					resource: "",
					params: {
						category: "plugins",
						installPlugin: qualify(url)
					}
				});
			}
			function generatePluginCell(cell, plugin, versionId) {
				var html = "";
				var pluginVersion = plugin.getVersion(versionId);
				if (params[TARGET] && pluginVersion) {
					var url = getQualifiedInstallURL(params[TARGET], plugin, versionId);
					html = 'Install';
				} else {
					if (pluginVersion) {
						var installURL = plugin.getInstallURL(versionId), sourceURL = plugin.getSourceURL(versionId);
						if (installURL) {
							html = '
Plugin
';
						}
						if (sourceURL) {
							html += '
Source
';
						}
					} else {
						html = "–";
						cell.title = "Not available for Orion " + versionId;
					}
				}
				cell.innerHTML = html;
			}

			var versions = getAllVersions(plugins);
			createHeaderRow(table, versions);
			plugins.sort(function(p1, p2) {
				return p1.getName().toLowerCase().localeCompare(p2.getName().toLowerCase());
			});
			for (var i=0; i < plugins.length; i++) {
				var plugin = plugins[i];
				var row = table.insertRow(-1);
				var desc = row.insertCell(-1);
				desc.innerHTML = '
' + plugin.getName() + '
' +
						'
' + plugin.getDescription() + '
';
				var cell, versionId;
				if (params[VERSION]) {
					cell = row.insertCell(-1);
					cell.className = "dl";
					versionId = params[VERSION];
					generatePluginCell(cell, plugin, versionId);
				} else {
					for (var j=0; j < versions.length; j++) {
						cell = row.insertCell(-1);
						cell.className = "dl";
						versionId = versions[j];
						generatePluginCell(cell, plugin, versionId);
					}
				}
			}
		}
		function createTable() {
			var table = document.getElementById("pluginTable");
			while (table.firstChild) {
				table.removeChild(table.firstChild);
			}
			var params = parseParameters();
			createTbody(table, getPluginsMatching(function(plugin) {
					// If VERSION is provided, only show plugins with that version defined.
					// If TARGET is provided, only show plugins with an install URL for the version.
					var versionId = params[VERSION], target = params[TARGET];
					var versionMatch = !versionId || plugin.getVersion(versionId);
					var installMatch = !versionId || !target || plugin.getInstallURL(versionId);
					return versionMatch && installMatch;
				}), params);
		}
		// Initialization starts here
		window.addEventListener("hashchange", createTable, false);

		createTable();
	}());
});
<commit_msg>Small cleanup<commit_after>/*jslint browser: true*/
/*global define window*/

define(['orion/URITemplate', 'domReady!'], function(URITemplate, document) {
	var pluginsData = [
		{	name: "JS Beautify",
			description: 'Cleans up the formatting of your JavaScript code using jsbeautifier.',
			versions: {
				"0.2|0.3|0.4|0.5": ["/0.2/plugins/beautify/jsbeautify.html", "https://github.com/mamacdon/mamacdon.github.com/tree/master/m6/beautify"]
			}
		},
		{	name: "Uglify",
			description: 'Minifies your JavaScript code using uglify-js.',
			versions: {
				/*"0.2 M6/M7": ["/m6/uglify/uglify-plugin.html", "https://github.com/mamacdon/mamacdon.github.com/tree/master/m6/uglify"],*/
				"0.2|0.3|0.4|0.5": ["/0.2/plugins/uglify/uglify-plugin.html", "https://github.com/mamacdon/mamacdon.github.com/tree/master/0.2/plugins/uglify"]
			}
		},
		{	name: "CSSLint",
			description: 'Provides validation and style tips on your CSS files using CSS Lint. (Included with Orion by default starting in 0.4)',
			versions: {
				"0.2": ["/0.2/plugins/csslint/csslintPlugin.html", "https://github.com/mamacdon/mamacdon.github.com/tree/master/0.2/plugins/csslint"],
				"0.3": ["/0.3/plugins/csslint/csslintPlugin.html", "https://github.com/mamacdon/mamacdon.github.com/tree/master/0.3/plugins/csslint"]
			}
		},
		{	name: "reverse",
			description: 'A minimal plugin example used as part of a tutorial.',
			versions: {
				"0.2|0.3": ["/0.2/plugins/reverse/reversePlugin.html", "https://github.com/mamacdon/mamacdon.github.com/tree/master/0.2/plugins/reverse"]
			}
		},
		{	name: "Bugzilla",
			description: 'A Bugzilla integration plugin for Orion.',
			versions: {
				"0.3|0.4|0.5": ["/0.3/plugins/bugzilla/plugin.html", "https://github.com/mamacdon/mamacdon.github.com/tree/master/0.3/plugins/bugzilla"]
			}
		},
		//{	name: "language.js",
		//	description: 'Provides content assist suggestions JavaScript identifiers using language.js.',
		//	experimental: true,
		//	versions: {
		//		"0.2|0.3": ["/0.2/plugins/language/languagejsPlugin.html", "https://github.com/mamacdon/mamacdon.github.com/tree/master/0.2/plugins/language/"],
		//	}
		//},
		{	name: "JavaScript hierarchical outline",
			description: 'Provides a simple tree view of the functions in a JavaScript file.',
			experimental: true,
			versions: {
				"0.3|0.4|0.5": ["http://mamacdon.github.com/outliner/outlinerPlugin.html", "https://github.com/mamacdon/outliner"]
			}
		},
		{	name: "Nonymous outline",
			description: 'Provides a tree view of JavaScript functions using the \"Function-Object Consumption\" algorithm to generate meaningful names for anonymous functions.',
			experimental: true,
			versions: {
				"0.3|0.4|0.5": ["http://johnjbarton.github.com/outliner/nonymousPlugin.html", "https://github.com/johnjbarton/outliner"]
			}
		},
		{	name: "CodeMirror highlighting",
			description: 'Uses CodeMirror modes to highlight your code.',
			experimental: true,
			versions: {
				"0.4|0.5": ["http://mamacdon.github.com/orion-codemirror/codeMirrorPlugin.html", "https://github.com/mamacdon/orion-codemirror"]
			}
		},
		{	name: "HTML Outline",
			description: 'Provides a hierarchical outline of the elements in an HTML file.',
			versions: {
				"0.4|0.5": ["http://jarthorn.github.com/html-tools/htmlOutlinePlugin.html", "https://github.com/jarthorn/html-tools"]
			}
		},
		{	name: "Esprima outline",
			description: 'Uses the esprima JavaScript parser to provide a detailed outline of your JavaScript code.',
			versions: {
				"0.4|0.5": ["http://aclement.github.com/esprima-outline/esprimaOutlinerPlugin.html", "https://github.com/aclement/esprima-outline"]
			}
		},
		{
			name: "Esprima content assist",
			description: "Offers completion and type inference for JavaScript files.",
			versions: {
				"0.4|0.5": ["http://aeisenberg.github.com/esprimaContentAssist/esprimaJsContentAssistPlugin.html", "https://github.com/aeisenberg/esprimaContentAssist"]
			}
		},
		{	name: "Amazon S3 filesystem",
			description: "Provides access to an Amazon S3 bucket as a filesystem. See README for installation instructions.",
			versions: {
				"0.4|0.5": [null, "https://github.com/mamacdon/orion-s3/"]
			}
		}
		];

	var TARGET = "target", VERSION = "version";

	(function() {
		// Turn 'pluginsData' JSON structure into objects with behavior.
		(function unmarshallPlugins() {
			function Plugin(source) {
				var keys = Object.keys(source);
				for (var i=0; i < keys.length; i++) {
					this[keys[i]] = source[keys[i]];
				}
			}
			Plugin.prototype = {
				getDescription: function() { return this.description; },
				getInstallURL: function(version) {
					var ver = this.getVersion(version);
					return (ver && ver[0]) || null;
				},
				getSourceURL: function(version) {
					var ver = this.getVersion(version);
					return (ver && ver[1]) || null;
				},
				getName: function() { return this.name; },
				getVersion: function(versionId) {
					var keys = Object.keys(this.versions);
					for (var i=0; i < keys.length; i++) {
						var ver = keys[i];
						if (ver.split("|").indexOf(versionId) !== -1) {
							return this.versions[ver];
						}
					}
					return null;
				},
				getVersionIds: function() {
					var versions = Object.keys(this.versions);
					var keys = [];
					for (var i=0; i < versions.length; i++) {
						var vs = versions[i].split("|");
						for (var j=0; j < vs.length; j++) {
							keys.push(vs[j]);
						}
					}
					return keys;
				}
			};
			for (var i = 0; i < pluginsData.length; i++) {
				pluginsData[i] = new Plugin(pluginsData[i]);
			}
		}());
		function getPluginsMatching(predicate) {
			var plugins = [];
			for (var i=0; i < pluginsData.length; i++) {
				var plugin = pluginsData[i];
				if (predicate(plugin)) {
					plugins.push(plugin);
				}
			}
			return plugins;
		}
		function getAllVersions(/**Plugin[]*/ plugins) {
			var versions = {};
			for (var i=0; i < plugins.length; i++) {
				var versionIds = plugins[i].getVersionIds();
				for (var j=0; j < versionIds.length; j++) {
					versions[versionIds[j]] = null;
				}
			}
			return Object.keys(versions);
		}
		function parseParameters() {
			var params = {};
			var hash = window.location.hash && window.location.hash.substr(1);
			if (hash) {
				var array = hash.split(/\?|,|&|(=)/);
				for (var i=0; i < array.length; i++) {
					var key = array[i];
					if (key && array[i + 1] === "=") {
						params[key] = array[i + 2];
						i++;
					}
				}
			}
			return params;
		}
		function createTbody(table, plugins, params) {
			function createHeaderRow(table, versions) {
				var headerRow = table.insertRow(-1);
				var th = document.createElement("th");
				th.innerHTML = "";
				headerRow.appendChild(th);
				if (params[VERSION]) {
					th = document.createElement("th");
					th.innerHTML = "";
					headerRow.appendChild(th);
				} else {
					for (var i=0; i < versions.length; i++) {
						th = document.createElement("th");
						th.innerHTML = "Orion " + versions[i];
						headerRow.appendChild(th);
					}
				}
			}
			function getQualifiedInstallURL(target, /**Plugin*/ plugin, versionId) {
				function qualify(url) {
					var a = document.createElement('a');
					a.href = url;
					return a.href;
				}
				var url = plugin.getInstallURL(versionId);
				return new URITemplate(target + "#{,resource,params*}").expand({
					resource: "",
					params: {
						category: "plugins",
						installPlugin: qualify(url)
					}
				});
			}
			function generatePluginCell(cell, plugin, versionId) {
				var html = "";
				var pluginVersion = plugin.getVersion(versionId);
				if (params[TARGET] && pluginVersion) {
					var url = getQualifiedInstallURL(params[TARGET], plugin, versionId);
					html = 'Install';
				} else {
					if (pluginVersion) {
						var installURL = plugin.getInstallURL(versionId), sourceURL = plugin.getSourceURL(versionId);
						if (installURL) {
							html = '
Plugin
';
						}
						if (sourceURL) {
							html += '
Source
';
						}
					} else {
						html = "–";
						cell.title = "Not available for Orion " + versionId;
					}
				}
				cell.innerHTML = html;
			}

			var versions = getAllVersions(plugins);
			createHeaderRow(table, versions);
			plugins.sort(function(p1, p2) {
				return p1.getName().toLowerCase().localeCompare(p2.getName().toLowerCase());
			});
			for (var i=0; i < plugins.length; i++) {
				var plugin = plugins[i];
				var row = table.insertRow(-1);
				var desc = row.insertCell(-1);
				desc.innerHTML = '
' + plugin.getName() + '
' +
						'
' + plugin.getDescription() + '
';
				var cell, versionId;
				if (params[VERSION]) {
					cell = row.insertCell(-1);
					cell.className = "dl";
					versionId = params[VERSION];
					generatePluginCell(cell, plugin, versionId);
				} else {
					for (var j=0; j < versions.length; j++) {
						cell = row.insertCell(-1);
						cell.className = "dl";
						versionId = versions[j];
						generatePluginCell(cell, plugin, versionId);
					}
				}
			}
		}
		function createTable() {
			var table = document.getElementById("pluginTable");
			while (table.firstChild) {
				table.removeChild(table.firstChild);
			}
			var params = parseParameters();
			createTbody(table, getPluginsMatching(function(plugin) {
					// If VERSION is provided, only show plugins with that version defined.
					// If TARGET is provided, only show plugins with an install URL for the version.
					var versionId = params[VERSION], target = params[TARGET];
					var versionMatch = !versionId || plugin.getVersion(versionId);
					var installMatch = !versionId || !target || plugin.getInstallURL(versionId);
					return versionMatch && installMatch;
				}), params);
		}
		// Initialization starts here
		window.addEventListener("hashchange", createTable, false);

		createTable();
	}());
});
<|endoftext|>


<commit_before>var express = require('express');
var app = express();

app.get('/', function(req, res){
  res.send('hello world');
});

app.listen(3000);
<commit_msg>Remove superfluous files<commit_after><|endoftext|>