<commit_before>/**
 * Output widget to vizualize DomainAnnotation object.
 * Pavel Novichkov <psnovichkov@lbl.gov>
 * @public
 */

(function($, undefined) {
    $.KBWidget({
        name: 'kbaseDomainAnnotation',
        parent: 'kbaseAuthenticatedWidget',
        version: '0.0.2',
        options: {
            domainAnnotationID: null,
            workspaceID: null,
            domainAnnotationVer: null,
            kbCache: null,
            workspaceURL: "https://kbase.us/services/ws/",  //"http://dev04.berkeley.kbase.us:7058",
            loadingImage: "static/kbase/images/ajax-loader.gif",
            height: null,
        },
        token: null,

        // Data for vizualization
        domainAnnotationData: null,
        genomeRef: null,
        genomeId: null,
        genomeName: null,
        domainModelSetRef: null,
        domainModelSetName: null,
        domainAccession2Description: {},
        annotatedGenesCount: 0,
        annotatedDomainsCount: 0,

        init: function(options) {
            this._super(options);

            // TEMPORARY
            if(this.options.domainAnnotationID == null){
                this.options.domainAnnotationID = 12;
                this.options.workspaceID = 2959;
                this.options.domainAnnotationVer = 8;
            }

            // Create a message pain
            this.$messagePane = $("
").addClass("kbwidget-message-pane kbwidget-hide-message");
            this.$elem.append(this.$messagePane);

            // Let's go...
            this.render();

            return this;
        },

        render: function(){
            var self = this;
            self.pref = this.uuid();
            self.loading(true);

            var container = this.$elem;
            var kbws = new Workspace(self.wsUrl, {'token': self.token});

            //self.options.workspaceID + "/" + self.options.domainAnnotationID;
            //kbws.get_objects([{ref: domainAnnotationRef}], function(data) {

            var domainAnnotationRef = self.buildObjectIdentity(this.options.workspaceID, this.options.domainAnnotationID, this.options.domainAnnotationVer);
            kbws.get_objects([domainAnnotationRef], function(data) {

                self.domainAnnotationData = data[0].data;
                self.genomeRef = self.domainAnnotationData.genome_ref;
                self.domainModelSetRef = self.domainAnnotationData.used_dms_ref;

                // Job to get properties of AnnotationDomain object: name and id of the annotated genome
                var jobGetDomainAnnotationProperties = kbws.get_object_subset(
                    [
                        { 'ref':self.genomeRef, 'included':['/id'] },
                        { 'ref':self.genomeRef, 'included':['/scientific_name'] }
                    ],
                    function(data){
                        self.genomeId = data[0].data.id;
                        self.genomeName = data[1].data.scientific_name;
                    },
                    function(error){
                        self.clientError(error);
                    }
                );

                var jobGetDomainModelSet =  kbws.get_objects(
                    [{ref: self.domainModelSetRef}],
                    function(data) {
                        self.domainSetName = data[0].data.set_name;
                        self.domainAccession2Description = data[0].data.domain_accession_to_description;
                    },
                    function(error){
                        self.clientError(error);
                    }
                );

                // Launch jobs and vizualize data once they are done
                $.when.apply($, [jobGetDomainAnnotationProperties, jobGetDomainModelSet]).done( function(){
                    self.loading(false);
                    self.prepareVizData();

                    ///////////////////////////////////// Instantiating Tabs ////////////////////////////////////////////
                    container.empty();
                    var tabPane = $('
');
                    container.append(tabPane);
                    tabPane.kbaseTabs({canDelete : true, tabs : []});

                    ///////////////////////////////////// Overview table ////////////////////////////////////////////
                    var tabOverview = $("
");
                    tabPane.kbaseTabs('addTab', {tab: 'Overview', content: tabOverview, canDelete : false, show: true});
                    var tableOver = $('
');
                    tabOverview.append(tableOver);
                    tableOver
                        .append( self.makeRow(
                            'Annotated genome',
                            $('').append(self.genomeName).css('font-style', 'italic') ) )
                        .append( self.makeRow(
                            'Domain models set',
                            self.domainSetName ) )
                        .append( self.makeRow(
                            'Annotated genes',
                            self.annotatedGenesCount ) )
                        .append( self.makeRow(
                            'Annotated domains',
                            self.annotatedDomainsCount) );

                    ///////////////////////////////////// Domains table ////////////////////////////////////////////
                    var tabDomains = $("
");
                    tabPane.kbaseTabs('addTab', {tab: 'Domains', content: tabDomains, canDelete : false, show: false});
                    var tableDomains = $('
');
                    tabDomains.append(tableDomains);
                    var domainTableSettings = {
                        "sPaginationType": "full_numbers",
                        "iDisplayLength": 10,
                        "aaData": [],
                        "aaSorting": [[ 2, "asc" ], [0, "asc"]],
                        "aoColumns": [
                                      { "sTitle": "Domain", 'mData': 'id'},
                                      { "sTitle": "Description", 'mData': 'description'},
                                      { "sTitle": "#Genes", 'mData': 'geneCount'},
                                      { "sTitle": "Genes", 'mData': 'geneRefs'},
                        ],
                        "oLanguage": {
                                    "sEmptyTable": "No domains found!",
                                    "sSearch": "Search: "
                        },
                        'fnDrawCallback': events
                    };

                    var domainsTableData = [];
                    var domains = self.domains;
                    for(var domainId in domains){
                        var domain = domains[domainId];

                        // Build concatenated list of gene references
                        var geneRefs = "";
                        for(var i = 0; i < domain.genes.length; i++){
                            gene = domain.genes[i];
                            if( i > 0 ) {
                                geneRefs += '
';
                            }
                            geneRefs += '' + gene['geneId'] + '';
                        }

                        // add table data row
                        domainsTableData.push(
                            {
                                //id: '' + domainId + '',
                                id: domainId,
                                description: domain.description,
                                geneCount: domain.genes.length,
                                geneRefs: geneRefs
                            }
                        );
                    };
                    domainTableSettings.aaData = domainsTableData;
                    tableDomains.dataTable(domainTableSettings);

                    ///////////////////////////////////// Events ////////////////////////////////////////////

                    function events() {
                        $('.show-gene'+self.pref).unbind('click');
                        $('.show-gene'+self.pref).click(function() {
                            var id = $(this).attr('data-id');
                            var contigId = $(this).attr('data-contigId');
                            var geneIndex = $(this).attr('data-geneIndex');

                            if (tabPane.kbaseTabs('hasTab', id)) {
                                tabPane.kbaseTabs('showTab', id);
                                return;
                            }

                            ////////////////////////////// Build Gene Domains table //////////////////////////////
                            var tabContent = $("
");
                            var tableGeneDomains = $('
');
                            tabContent.append(tableGeneDomains);
                            var geneDomainTableSettings = {
                                "sPaginationType": "full_numbers",
                                "iDisplayLength": 10,
                                "aaData": [],
                                "aaSorting": [[ 3, "asc" ], [5, "desc"]],
                                "aoColumns": [
                                    {sTitle: "Domain", mData: "domainId"},
                                    {sTitle: "Description", mData: "domainDescription", sWidth:"30%"},
                                    {sTitle: "Location", mData: "image"},
                                    {sTitle: "Start", mData: "domainStart"},
                                    {sTitle: "End", mData: "domainEnd"},
                                    {sTitle: "eValue", mData: "eValue"},
                                ],
                                "oLanguage": {
                                    "sEmptyTable": "No domains found!",
                                    "sSearch": "Search: "
                                }
                            };
                            var geneDomainsTableData = [];

                            var gene = self.domainAnnotationData.data[contigId][geneIndex];
                            var geneId = gene[0];
                            var geneStart = gene[1];
                            var geneEnd = gene[2];
                            var domainsInfo = gene[4];
                            for(var domainId in domainsInfo){
                                var domainsArray = domainsInfo[domainId];
                                for(var i = 0 ; i < domainsArray.length; i++){
                                    var domainStart = domainsArray[i][0];
                                    var domainEnd = domainsArray[i][1];
                                    var eValue = domainsArray[i][2];
/*
                                    var domainSignature = domainId + "_" + domainStart + "_" + domainEnd;
                                    if(uniqueDomains[domainSignature] == undefined){
                                        uniqueDomains[domainSignature] = "";
                                    } else {
                                        // Because we might have several SAME domain annotations that came from
                                        // different DomainAnnotation objects linked to a given genome
                                        continue;
                                    }
*/

                                    var domainImgWidth = (domainEnd - domainStart)*100/(geneEnd - geneStart);
                                    var  domainImgleftShift = (domainStart)*100/(geneEnd - geneStart);

                                    geneDomainsTableData.push({
                                        'contigId' : contigId,
                                        'geneId' : geneId,
                                        'geneStart' : geneStart,
                                        'geneEnd' : geneEnd,
                                        'domainId' : domainId,
                                        'domainDescription' : self.domainAccession2Description[domainId],
                                        'domainStart': Math.round(domainStart/3),
                                        'domainEnd' : Math.round(domainEnd/3),
                                        'eValue' : eValue,
                                        'image' :
                                                '
'
                                                + '
'
                                                + '

'
                                                + '
'
                                    });
                                }
                            }
                            geneDomainTableSettings.aaData = geneDomainsTableData;
                            tableGeneDomains.dataTable(geneDomainTableSettings);
                            tabPane.kbaseTabs('addTab', {tab: id, content: tabContent, canDelete : true, show: true});
                        });
                    };
                });
            });
        },

        prepareVizData: function(){
            var self = this;

            var dad = self.domainAnnotationData;

            var domains = {};
            var domainsCount = 0;
            var genesCount = 0;

            for(var contigId in dad.data){

                var genesArray = dad.data[contigId];
                for(var i = 0 ; i < genesArray.length; i++){
                    var geneId = genesArray[i][0];
//                    var geneStart = genesArray[i][1];
//                    var geneEnd = genesArray[i][2];
                    var domainsInfo = genesArray[i][4];
                    if( $.isEmptyObject(domainsInfo)) continue;

                    // If we have somthing in domainsIno, then the gene was anntoated
                    genesCount ++;
                    for(var domainId in domainsInfo){
                        var domainData = domains[domainId];
                        if(typeof domainData === 'undefined'){
                            domainData = {
                                id: domainId,
                                description: self.domainAccession2Description[domainId],
                                genes: []
                            };
                            domains[domainId] = domainData;
                            domainsCount++;
                        }

                        domainData.genes.push(
                            {
                                geneId: geneId,
                                contigId: contigId,
                                geneIndex: i
                            }
                        );
                    }
                }
                self.domains = domains;
                self.annotatedDomainsCount = domainsCount;
                self.annotatedGenesCount = genesCount;
            }
        },

        makeRow: function(name, value) {
            var $row = $("
")
                       .append($("").css('width','20%').append(name))
                       .append($("").append(value));
            return $row;
        },

        getData: function() {
            return {
                type: 'DomainAnnotation',
                id: this.options.domainAnnotationID,
                workspace: this.options.workspaceID,
                title: 'Domain Annotation'
            };
        },

        loading: function(isLoading) {
            if (isLoading)
                this.showMessage("");
            else
                this.hideMessage();
        },

        showMessage: function(message) {
            var span = $("").append(message);

            this.$messagePane.append(span);
            this.$messagePane.show();
        },

        hideMessage: function() {
            this.$messagePane.hide();
            this.$messagePane.empty();
        },
        uuid: function() {
            return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g,
                function(c) {
                    var r = Math.random()*16|0, v = c == 'x' ? r : (r&0x3|0x8);
                    return v.toString(16);
                });
        },
        buildObjectIdentity: function(workspaceID, objectID, objectVer, wsRef) {
            var obj = {};
            if (wsRef) {
                obj['ref'] = wsRef;
            } else {
                if (/^\d+$/.exec(workspaceID))
                    obj['wsid'] = workspaceID;
                else
                    obj['workspace'] = workspaceID;

                // same for the id
                if (/^\d+$/.exec(objectID))
                    obj['objid'] = objectID;
                else
                    obj['name'] = objectID;

                if (objectVer)
                    obj['ver'] = objectVer;
            }
            return obj;
        },
        clientError: function(error){
            this.loading(false);
            this.showMessage(error.error.error);
        }

    });
})( jQuery );<commit_msg>Because a lot changes in the previous commit, the major version should be incremented.<commit_after>/**
 * Output widget to vizualize DomainAnnotation object.
 * Pavel Novichkov <psnovichkov@lbl.gov>
 * @public
 */

(function($, undefined) {
    $.KBWidget({
        name: 'kbaseDomainAnnotation',
        parent: 'kbaseAuthenticatedWidget',
        version: '1.0.1',
        options: {
            domainAnnotationID: null,
            workspaceID: null,
            domainAnnotationVer: null,
            kbCache: null,
            workspaceURL: "https://kbase.us/services/ws/",  //"http://dev04.berkeley.kbase.us:7058",
            loadingImage: "static/kbase/images/ajax-loader.gif",
            height: null,
        },
        token: null,

        // Data for vizualization
        domainAnnotationData: null,
        genomeRef: null,
        genomeId: null,
        genomeName: null,
        domainModelSetRef: null,
        domainModelSetName: null,
        domainAccession2Description: {},
        annotatedGenesCount: 0,
        annotatedDomainsCount: 0,

        init: function(options) {
            this._super(options);

            // TEMPORARY
            if(this.options.domainAnnotationID == null){
                this.options.domainAnnotationID = 12;
                this.options.workspaceID = 2959;
                this.options.domainAnnotationVer = 8;
            }

            // Create a message pain
            this.$messagePane = $("
").addClass("kbwidget-message-pane kbwidget-hide-message");
            this.$elem.append(this.$messagePane);

            // Let's go...
            this.render();

            return this;
        },

        render: function(){
            var self = this;
            self.pref = this.uuid();
            self.loading(true);

            var container = this.$elem;
            var kbws = new Workspace(self.wsUrl, {'token': self.token});

            //self.options.workspaceID + "/" + self.options.domainAnnotationID;
            //kbws.get_objects([{ref: domainAnnotationRef}], function(data) {

            var domainAnnotationRef = self.buildObjectIdentity(this.options.workspaceID, this.options.domainAnnotationID, this.options.domainAnnotationVer);
            kbws.get_objects([domainAnnotationRef], function(data) {

                self.domainAnnotationData = data[0].data;
                self.genomeRef = self.domainAnnotationData.genome_ref;
                self.domainModelSetRef = self.domainAnnotationData.used_dms_ref;

                // Job to get properties of AnnotationDomain object: name and id of the annotated genome
                var jobGetDomainAnnotationProperties = kbws.get_object_subset(
                    [
                        { 'ref':self.genomeRef, 'included':['/id'] },
                        { 'ref':self.genomeRef, 'included':['/scientific_name'] }
                    ],
                    function(data){
                        self.genomeId = data[0].data.id;
                        self.genomeName = data[1].data.scientific_name;
                    },
                    function(error){
                        self.clientError(error);
                    }
                );

                var jobGetDomainModelSet =  kbws.get_objects(
                    [{ref: self.domainModelSetRef}],
                    function(data) {
                        self.domainSetName = data[0].data.set_name;
                        self.domainAccession2Description = data[0].data.domain_accession_to_description;
                    },
                    function(error){
                        self.clientError(error);
                    }
                );

                // Launch jobs and vizualize data once they are done
                $.when.apply($, [jobGetDomainAnnotationProperties, jobGetDomainModelSet]).done( function(){
                    self.loading(false);
                    self.prepareVizData();

                    ///////////////////////////////////// Instantiating Tabs ////////////////////////////////////////////
                    container.empty();
                    var tabPane = $('
');
                    container.append(tabPane);
                    tabPane.kbaseTabs({canDelete : true, tabs : []});

                    ///////////////////////////////////// Overview table ////////////////////////////////////////////
                    var tabOverview = $("
");
                    tabPane.kbaseTabs('addTab', {tab: 'Overview', content: tabOverview, canDelete : false, show: true});
                    var tableOver = $('
');
                    tabOverview.append(tableOver);
                    tableOver
                        .append( self.makeRow(
                            'Annotated genome',
                            $('').append(self.genomeName).css('font-style', 'italic') ) )
                        .append( self.makeRow(
                            'Domain models set',
                            self.domainSetName ) )
                        .append( self.makeRow(
                            'Annotated genes',
                            self.annotatedGenesCount ) )
                        .append( self.makeRow(
                            'Annotated domains',
                            self.annotatedDomainsCount) );

                    ///////////////////////////////////// Domains table ////////////////////////////////////////////
                    var tabDomains = $("
");
                    tabPane.kbaseTabs('addTab', {tab: 'Domains', content: tabDomains, canDelete : false, show: false});
                    var tableDomains = $('
');
                    tabDomains.append(tableDomains);
                    var domainTableSettings = {
                        "sPaginationType": "full_numbers",
                        "iDisplayLength": 10,
                        "aaData": [],
                        "aaSorting": [[ 2, "asc" ], [0, "asc"]],
                        "aoColumns": [
                                      { "sTitle": "Domain", 'mData': 'id'},
                                      { "sTitle": "Description", 'mData': 'description'},
                                      { "sTitle": "#Genes", 'mData': 'geneCount'},
                                      { "sTitle": "Genes", 'mData': 'geneRefs'},
                        ],
                        "oLanguage": {
                                    "sEmptyTable": "No domains found!",
                                    "sSearch": "Search: "
                        },
                        'fnDrawCallback': events
                    };

                    var domainsTableData = [];
                    var domains = self.domains;
                    for(var domainId in domains){
                        var domain = domains[domainId];

                        // Build concatenated list of gene references
                        var geneRefs = "";
                        for(var i = 0; i < domain.genes.length; i++){
                            gene = domain.genes[i];
                            if( i > 0 ) {
                                geneRefs += '
';
                            }
                            geneRefs += '' + gene['geneId'] + '';
                        }

                        // add table data row
                        domainsTableData.push(
                            {
                                //id: '' + domainId + '',
                                id: domainId,
                                description: domain.description,
                                geneCount: domain.genes.length,
                                geneRefs: geneRefs
                            }
                        );
                    };
                    domainTableSettings.aaData = domainsTableData;
                    tableDomains.dataTable(domainTableSettings);

                    ///////////////////////////////////// Events ////////////////////////////////////////////

                    function events() {
                        $('.show-gene'+self.pref).unbind('click');
                        $('.show-gene'+self.pref).click(function() {
                            var id = $(this).attr('data-id');
                            var contigId = $(this).attr('data-contigId');
                            var geneIndex = $(this).attr('data-geneIndex');

                            if (tabPane.kbaseTabs('hasTab', id)) {
                                tabPane.kbaseTabs('showTab', id);
                                return;
                            }

                            ////////////////////////////// Build Gene Domains table //////////////////////////////
                            var tabContent = $("
");
                            var tableGeneDomains = $('
');
                            tabContent.append(tableGeneDomains);
                            var geneDomainTableSettings = {
                                "sPaginationType": "full_numbers",
                                "iDisplayLength": 10,
                                "aaData": [],
                                "aaSorting": [[ 3, "asc" ], [5, "desc"]],
                                "aoColumns": [
                                    {sTitle: "Domain", mData: "domainId"},
                                    {sTitle: "Description", mData: "domainDescription", sWidth:"30%"},
                                    {sTitle: "Location", mData: "image"},
                                    {sTitle: "Start", mData: "domainStart"},
                                    {sTitle: "End", mData: "domainEnd"},
                                    {sTitle: "eValue", mData: "eValue"},
                                ],
                                "oLanguage": {
                                    "sEmptyTable": "No domains found!",
                                    "sSearch": "Search: "
                                }
                            };
                            var geneDomainsTableData = [];

                            var gene = self.domainAnnotationData.data[contigId][geneIndex];
                            var geneId = gene[0];
                            var geneStart = gene[1];
                            var geneEnd = gene[2];
                            var domainsInfo = gene[4];
                            for(var domainId in domainsInfo){
                                var domainsArray = domainsInfo[domainId];
                                for(var i = 0 ; i < domainsArray.length; i++){
                                    var domainStart = domainsArray[i][0];
                                    var domainEnd = domainsArray[i][1];
                                    var eValue = domainsArray[i][2];
/*
                                    var domainSignature = domainId + "_" + domainStart + "_" + domainEnd;
                                    if(uniqueDomains[domainSignature] == undefined){
                                        uniqueDomains[domainSignature] = "";
                                    } else {
                                        // Because we might have several SAME domain annotations that came from
                                        // different DomainAnnotation objects linked to a given genome
                                        continue;
                                    }
*/

                                    var domainImgWidth = (domainEnd - domainStart)*100/(geneEnd - geneStart);
                                    var  domainImgleftShift = (domainStart)*100/(geneEnd - geneStart);

                                    geneDomainsTableData.push({
                                        'contigId' : contigId,
                                        'geneId' : geneId,
                                        'geneStart' : geneStart,
                                        'geneEnd' : geneEnd,
                                        'domainId' : domainId,
                                        'domainDescription' : self.domainAccession2Description[domainId],
                                        'domainStart': Math.round(domainStart/3),
                                        'domainEnd' : Math.round(domainEnd/3),
                                        'eValue' : eValue,
                                        'image' :
                                                '
'
                                                + '
'
                                                + '

'
                                                + '
'
                                    });
                                }
                            }
                            geneDomainTableSettings.aaData = geneDomainsTableData;
                            tableGeneDomains.dataTable(geneDomainTableSettings);
                            tabPane.kbaseTabs('addTab', {tab: id, content: tabContent, canDelete : true, show: true});
                        });
                    };
                });
            });
        },

        prepareVizData: function(){
            var self = this;

            var dad = self.domainAnnotationData;

            var domains = {};
            var domainsCount = 0;
            var genesCount = 0;

            for(var contigId in dad.data){

                var genesArray = dad.data[contigId];
                for(var i = 0 ; i < genesArray.length; i++){
                    var geneId = genesArray[i][0];
//                    var geneStart = genesArray[i][1];
//                    var geneEnd = genesArray[i][2];
                    var domainsInfo = genesArray[i][4];
                    if( $.isEmptyObject(domainsInfo)) continue;

                    // If we have somthing in domainsIno, then the gene was anntoated
                    genesCount ++;
                    for(var domainId in domainsInfo){
                        var domainData = domains[domainId];
                        if(typeof domainData === 'undefined'){
                            domainData = {
                                id: domainId,
                                description: self.domainAccession2Description[domainId],
                                genes: []
                            };
                            domains[domainId] = domainData;
                            domainsCount++;
                        }

                        domainData.genes.push(
                            {
                                geneId: geneId,
                                contigId: contigId,
                                geneIndex: i
                            }
                        );
                    }
                }
                self.domains = domains;
                self.annotatedDomainsCount = domainsCount;
                self.annotatedGenesCount = genesCount;
            }
        },

        makeRow: function(name, value) {
            var $row = $("
")
                       .append($("").css('width','20%').append(name))
                       .append($("").append(value));
            return $row;
        },

        getData: function() {
            return {
                type: 'DomainAnnotation',
                id: this.options.domainAnnotationID,
                workspace: this.options.workspaceID,
                title: 'Domain Annotation'
            };
        },

        loading: function(isLoading) {
            if (isLoading)
                this.showMessage("");
            else
                this.hideMessage();
        },

        showMessage: function(message) {
            var span = $("").append(message);

            this.$messagePane.append(span);
            this.$messagePane.show();
        },

        hideMessage: function() {
            this.$messagePane.hide();
            this.$messagePane.empty();
        },
        uuid: function() {
            return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g,
                function(c) {
                    var r = Math.random()*16|0, v = c == 'x' ? r : (r&0x3|0x8);
                    return v.toString(16);
                });
        },
        buildObjectIdentity: function(workspaceID, objectID, objectVer, wsRef) {
            var obj = {};
            if (wsRef) {
                obj['ref'] = wsRef;
            } else {
                if (/^\d+$/.exec(workspaceID))
                    obj['wsid'] = workspaceID;
                else
                    obj['workspace'] = workspaceID;

                // same for the id
                if (/^\d+$/.exec(objectID))
                    obj['objid'] = objectID;
                else
                    obj['name'] = objectID;

                if (objectVer)
                    obj['ver'] = objectVer;
            }
            return obj;
        },
        clientError: function(error){
            this.loading(false);
            this.showMessage(error.error.error);
        }

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


<commit_before><commit_msg>Fixed M121 Lab2.1<commit_after><|endoftext|>


<commit_before>const restrictedGlobals = [
  'addEventListener',
  'blur',
  'close',
  'closed',
  'confirm',
  'defaultStatus',
  'defaultstatus',
  'event',
  'external',
  'find',
  'focus',
  'frameElement',
  'frames',
  'history',
  'innerHeight',
  'innerWidth',
  'length',
  'location',
  'locationbar',
  'menubar',
  'moveBy',
  'moveTo',
  'name',
  'onblur',
  'onerror',
  'onfocus',
  'onload',
  'onresize',
  'onunload',
  'open',
  'opener',
  'opera',
  'outerHeight',
  'outerWidth',
  'pageXOffset',
  'pageYOffset',
  'parent',
  'print',
  'removeEventListener',
  'resizeBy',
  'resizeTo',
  'screen',
  'screenLeft',
  'screenTop',
  'screenX',
  'screenY',
  'scroll',
  'scrollbars',
  'scrollBy',
  'scrollTo',
  'scrollX',
  'scrollY',
  'self',
  'status',
  'statusbar',
  'stop',
  'toolbar',
  'top',
];

module.exports = {
  env: {
    browser: true,
    es6: true,
    jquery: true,
  },
  globals: {
    module: true,
    require: true,
  },
  parserOptions: {
    ecmaFeatures: {
      experimentalObjectRestSpread: true,
    },
    ecmaVersion: 2015,
    sourceType: 'module',
  },
  rules: {
    'accessor-pairs': 'off',
    'array-bracket-newline': ['error'],
    'array-bracket-spacing': ['error', 'never'],
    'array-callback-return': 'error',
    'array-element-newline': 'off',
    'arrow-body-style': 'error',
    'arrow-parens': ['error', 'as-needed'],
    'arrow-spacing': 'error',
    'block-scoped-var': 'off',
    'block-spacing': 'error',
    'brace-style': ['error', '1tbs', { allowSingleLine: true }],
    'callback-return': 'off',
    'camelcase': 'error',
    'capitalized-comments': 'off',
    'class-methods-use-this': 'off',
    'comma-dangle': ['error', 'always-multiline'],
    'comma-spacing': 'error',
    'comma-style': 'error',
    'complexity': ['warn', 10],
    'computed-property-spacing': 'error',
    'consistent-return': 'error',
    'consistent-this': 'off',
    'constructor-super': 'error',
    'curly': 'error',
    'default-case': ['error', { commentPattern: '^no default$' }],
    'dot-location': ['error', 'property'],
    'dot-notation': 'error',
    'eol-last': 'error',
    'eqeqeq': ['error', 'allow-null'],
    'for-direction': 'off',
    'func-call-spacing': 'error',
    'func-name-matching': 'warn',
    'func-names': 'off',
    'func-style': 'off',
    'function-paren-newline': ['error', 'multiline'],
    'generator-star-spacing': ['error', { after: true, before: false }],
    'getter-return': 'warn',
    'global-require': 'off',
    'guard-for-in': 'off',
    'handle-callback-err': 'off',
    'id-blacklist': 'off',
    'id-length': 'off',
    'id-match': 'off',
    'indent': ['error', 2, { SwitchCase: 1 }],
    'init-declarations': 'off',
    'key-spacing': 'error',
    'keyword-spacing': 'error',
    'line-comment-position': ['error', { position: 'above' }],
    'linebreak-style': 'error',
    'lines-around-comment': 'off',
    'lines-around-directive': 'off',
    'max-depth': ['error', 4],
    'max-len': ['warn', 180, 2, { ignoreComments: false, ignoreUrls: true }],
    'max-lines': 'off',
    'max-nested-callbacks': 'off',
    'max-params': 'off',
    'max-statements': ['warn', 20],
    'max-statements-per-line': ['error', { max: 1 }],
    'multiline-ternary': 'off',
    'new-cap': 'off',
    'new-parens': 'off',
    'newline-after-var': 'off',
    'newline-before-return': 'off',
    'newline-per-chained-call': ['error', { ignoreChainWithDepth: 4 }],
    'no-alert': 'error',
    'no-array-constructor': 'error',
    'no-await-in-loop': 'error',
    'no-bitwise': 'warn',
    'no-buffer-constructor': 'warn',
    'no-caller': 'error',
    'no-case-declarations': 'error',
    'no-catch-shadow': 'off',
    'no-class-assign': 'error',
    'no-compare-neg-zero': 'error',
    'no-cond-assign': 'error',
    'no-confusing-arrow': 'off',
    'no-console': 'error',
    'no-const-assign': 'error',
    'no-constant-condition': 'error',
    'no-continue': 'off',
    'no-control-regex': 'error',
    'no-debugger': 'error',
    'no-delete-var': 'error',
    'no-div-regex': 'off',
    'no-dupe-args': 'error',
    'no-dupe-class-members': 'error',
    'no-dupe-keys': 'error',
    'no-duplicate-case': 'error',
    'no-duplicate-imports': 'error',
    'no-else-return': 'error',
    'no-empty': 'error',
    'no-empty-character-class': 'error',
    'no-empty-function': ['error', { allow: ['arrowFunctions', 'functions', 'methods'] }],
    'no-empty-pattern': 'error',
    'no-eq-null': 'off',
    'no-eval': 'error',
    'no-ex-assign': 'error',
    'no-extend-native': 'error',
    'no-extra-bind': 'error',
    'no-extra-boolean-cast': 'error',
    'no-extra-label': 'error',
    'no-extra-parens': ['error', 'all', { ignoreJSX: 'multi-line' }],
    'no-extra-semi': 'error',
    'no-fallthrough': 'error',
    'no-floating-decimal': 'error',
    'no-func-assign': 'error',
    'no-global-assign': 'error',
    'no-implicit-coercion': 'off',
    'no-implicit-globals': 'off',
    'no-implied-eval': 'error',
    'no-inline-comments': 'off',
    'no-inner-declarations': 'error',
    'no-invalid-regexp': 'error',
    'no-invalid-this': 'off',
    'no-irregular-whitespace': 'error',
    'no-iterator': 'off',
    'no-label-var': 'off',
    'no-labels': 'error',
    'no-lone-blocks': 'error',
    'no-lonely-if': 'error',
    'no-loop-func': 'error',
    'no-magic-numbers': 'off',
    'no-mixed-operators': 'off',
    'no-mixed-requires': 'off',
    'no-mixed-spaces-and-tabs': 'error',
    'no-multi-assign': 'error',
    'no-multi-spaces': 'error',
    'no-multi-str': 'error',
    'no-multiple-empty-lines': ['error', { max: 1, maxBOF: 0 }],
    'no-native-reassign': 'error',
    'no-negated-condition': 'off',
    'no-negated-in-lhs': 'error',
    'no-nested-ternary': 'error',
    'no-new': 'off',
    'no-new-func': 'error',
    'no-new-object': 'error',
    'no-new-require': 'off',
    'no-new-symbol': 'error',
    'no-new-wrappers': 'error',
    'no-obj-calls': 'error',
    'no-octal': 'error',
    'no-octal-escape': 'error',
    'no-param-reassign': 'error',
    'no-path-concat': 'off',
    'no-plusplus': 'off',
    'no-process-env': 'off',
    'no-process-exit': 'off',
    'no-proto': 'error',
    'no-prototype-builtins': 'off',
    'no-redeclare': 'error',
    'no-regex-spaces': 'error',
    'no-restricted-globals': ['error'].concat(restrictedGlobals),
    'no-restricted-imports': 'off',
    'no-restricted-modules': 'off',
    'no-restricted-properties': 'off',
    'no-restricted-syntax': 'off',
    'no-return-assign': 'error',
    'no-return-await': 'error',
    'no-script-url': 'error',
    'no-self-assign': 'error',
    'no-self-compare': 'error',
    'no-sequences': 'error',
    'no-shadow': 'error',
    'no-shadow-restricted-names': 'error',
    'no-sparse-arrays': 'error',
    'no-sync': 'off',
    'no-tabs': 'error',
    'no-template-curly-in-string': 'error',
    'no-ternary': 'off',
    'no-this-before-super': 'error',
    'no-throw-literal': 'error',
    'no-trailing-spaces': 'error',
    'no-undef': 'error',
    'no-undef-init': 'off',
    'no-undefined': 'off',
    'no-underscore-dangle': 'warn',
    'no-unexpected-multiline': 'error',
    'no-unmodified-loop-condition': 'off',
    'no-unneeded-ternary': ['error', { defaultAssignment: false }],
    'no-unreachable': 'error',
    'no-unsafe-finally': 'error',
    'no-unsafe-negation': 'error',
    'no-unused-expressions': ['error', { allowShortCircuit: true, allowTernary: true }],
    'no-unused-labels': 'error',
    'no-unused-vars': ['error', { args: 'none', ignoreRestSiblings: true }],
    'no-use-before-define': ['error', { functions: false }],
    'no-useless-call': 'off',
    'no-useless-computed-key': 'error',
    'no-useless-concat': 'error',
    'no-useless-constructor': 'error',
    'no-useless-escape': 'error',
    'no-useless-rename': 'error',
    'no-useless-return': 'error',
    'no-var': 'error',
    'no-void': 'off',
    'no-warning-comments': 'warn',
    'no-whitespace-before-property': 'error',
    'no-with': 'error',
    'nonblock-statement-body-position': 'off',
    'object-curly-newline': ['error', { consistent: true }],
    'object-curly-spacing': ['error', 'always'],
    'object-property-newline': ['error', { allowMultiplePropertiesPerLine: true }],
    'object-shorthand': ['error', 'always', { avoidExplicitReturnArrows: true, avoidQuotes: true }],
    'one-var': ['error', 'never'],
    'one-var-declaration-per-line': 'error',
    'operator-assignment': 'off',
    'operator-linebreak': 'error',
    'padded-blocks': ['error', 'never'],
    'padding-line-between-statements': 'off',
    'prefer-arrow-callback': 'warn',
    'prefer-const': ['error', { destructuring: 'any', ignoreReadBeforeAssign: true }],
    'prefer-destructuring': 'error',
    'prefer-numeric-literals': 'error',
    'prefer-promise-reject-errors': 'error',
    'prefer-reflect': 'off',
    'prefer-rest-params': 'error',
    'prefer-spread': 'error',
    'prefer-template': 'warn',
    'quote-props': ['error', 'as-needed'],
    'quotes': ['error', 'single'],
    'radix': 'error',
    'require-await': 'error',
    'require-jsdoc': 'off',
    'require-yield': 'error',
    'rest-spread-spacing': 'error',
    'semi': ['error', 'always'],
    'semi-spacing': 'error',
    'semi-style': 'off',
    'sort-imports': 'off',
    'sort-keys': 'off',
    'sort-vars': 'off',
    'space-before-blocks': 'error',
    'space-before-function-paren': ['error', 'never'],
    'space-in-parens': 'error',
    'space-infix-ops': 'error',
    'space-unary-ops': 'error',
    'spaced-comment': 'error',
    'strict': ['error', 'never'],
    'switch-colon-spacing': 'error',
    'symbol-description': 'error',
    'template-curly-spacing': 'error',
    'template-tag-spacing': 'error',
    'unicode-bom': 'error',
    'use-isnan': 'error',
    'valid-jsdoc': 'off',
    'valid-typeof': 'error',
    'vars-on-top': 'off',
    'wrap-iife': 'off',
    'wrap-regex': 'off',
    'yield-star-spacing': ['error', 'after'],
    'yoda': 'error',
  },
};
<commit_msg>remove jquery env<commit_after>const restrictedGlobals = [
  'addEventListener',
  'blur',
  'close',
  'closed',
  'confirm',
  'defaultStatus',
  'defaultstatus',
  'event',
  'external',
  'find',
  'focus',
  'frameElement',
  'frames',
  'history',
  'innerHeight',
  'innerWidth',
  'length',
  'location',
  'locationbar',
  'menubar',
  'moveBy',
  'moveTo',
  'name',
  'onblur',
  'onerror',
  'onfocus',
  'onload',
  'onresize',
  'onunload',
  'open',
  'opener',
  'opera',
  'outerHeight',
  'outerWidth',
  'pageXOffset',
  'pageYOffset',
  'parent',
  'print',
  'removeEventListener',
  'resizeBy',
  'resizeTo',
  'screen',
  'screenLeft',
  'screenTop',
  'screenX',
  'screenY',
  'scroll',
  'scrollbars',
  'scrollBy',
  'scrollTo',
  'scrollX',
  'scrollY',
  'self',
  'status',
  'statusbar',
  'stop',
  'toolbar',
  'top',
];

module.exports = {
  env: {
    browser: true,
    es6: true,
  },
  globals: {
    module: true,
    require: true,
  },
  parserOptions: {
    ecmaFeatures: {
      experimentalObjectRestSpread: true,
    },
    ecmaVersion: 2015,
    sourceType: 'module',
  },
  rules: {
    'accessor-pairs': 'off',
    'array-bracket-newline': ['error'],
    'array-bracket-spacing': ['error', 'never'],
    'array-callback-return': 'error',
    'array-element-newline': 'off',
    'arrow-body-style': 'error',
    'arrow-parens': ['error', 'as-needed'],
    'arrow-spacing': 'error',
    'block-scoped-var': 'off',
    'block-spacing': 'error',
    'brace-style': ['error', '1tbs', { allowSingleLine: true }],
    'callback-return': 'off',
    'camelcase': 'error',
    'capitalized-comments': 'off',
    'class-methods-use-this': 'off',
    'comma-dangle': ['error', 'always-multiline'],
    'comma-spacing': 'error',
    'comma-style': 'error',
    'complexity': ['warn', 10],
    'computed-property-spacing': 'error',
    'consistent-return': 'error',
    'consistent-this': 'off',
    'constructor-super': 'error',
    'curly': 'error',
    'default-case': ['error', { commentPattern: '^no default$' }],
    'dot-location': ['error', 'property'],
    'dot-notation': 'error',
    'eol-last': 'error',
    'eqeqeq': ['error', 'allow-null'],
    'for-direction': 'off',
    'func-call-spacing': 'error',
    'func-name-matching': 'warn',
    'func-names': 'off',
    'func-style': 'off',
    'function-paren-newline': ['error', 'multiline'],
    'generator-star-spacing': ['error', { after: true, before: false }],
    'getter-return': 'warn',
    'global-require': 'off',
    'guard-for-in': 'off',
    'handle-callback-err': 'off',
    'id-blacklist': 'off',
    'id-length': 'off',
    'id-match': 'off',
    'indent': ['error', 2, { SwitchCase: 1 }],
    'init-declarations': 'off',
    'key-spacing': 'error',
    'keyword-spacing': 'error',
    'line-comment-position': ['error', { position: 'above' }],
    'linebreak-style': 'error',
    'lines-around-comment': 'off',
    'lines-around-directive': 'off',
    'max-depth': ['error', 4],
    'max-len': ['warn', 180, 2, { ignoreComments: false, ignoreUrls: true }],
    'max-lines': 'off',
    'max-nested-callbacks': 'off',
    'max-params': 'off',
    'max-statements': ['warn', 20],
    'max-statements-per-line': ['error', { max: 1 }],
    'multiline-ternary': 'off',
    'new-cap': 'off',
    'new-parens': 'off',
    'newline-after-var': 'off',
    'newline-before-return': 'off',
    'newline-per-chained-call': ['error', { ignoreChainWithDepth: 4 }],
    'no-alert': 'error',
    'no-array-constructor': 'error',
    'no-await-in-loop': 'error',
    'no-bitwise': 'warn',
    'no-buffer-constructor': 'warn',
    'no-caller': 'error',
    'no-case-declarations': 'error',
    'no-catch-shadow': 'off',
    'no-class-assign': 'error',
    'no-compare-neg-zero': 'error',
    'no-cond-assign': 'error',
    'no-confusing-arrow': 'off',
    'no-console': 'error',
    'no-const-assign': 'error',
    'no-constant-condition': 'error',
    'no-continue': 'off',
    'no-control-regex': 'error',
    'no-debugger': 'error',
    'no-delete-var': 'error',
    'no-div-regex': 'off',
    'no-dupe-args': 'error',
    'no-dupe-class-members': 'error',
    'no-dupe-keys': 'error',
    'no-duplicate-case': 'error',
    'no-duplicate-imports': 'error',
    'no-else-return': 'error',
    'no-empty': 'error',
    'no-empty-character-class': 'error',
    'no-empty-function': ['error', { allow: ['arrowFunctions', 'functions', 'methods'] }],
    'no-empty-pattern': 'error',
    'no-eq-null': 'off',
    'no-eval': 'error',
    'no-ex-assign': 'error',
    'no-extend-native': 'error',
    'no-extra-bind': 'error',
    'no-extra-boolean-cast': 'error',
    'no-extra-label': 'error',
    'no-extra-parens': ['error', 'all', { ignoreJSX: 'multi-line' }],
    'no-extra-semi': 'error',
    'no-fallthrough': 'error',
    'no-floating-decimal': 'error',
    'no-func-assign': 'error',
    'no-global-assign': 'error',
    'no-implicit-coercion': 'off',
    'no-implicit-globals': 'off',
    'no-implied-eval': 'error',
    'no-inline-comments': 'off',
    'no-inner-declarations': 'error',
    'no-invalid-regexp': 'error',
    'no-invalid-this': 'off',
    'no-irregular-whitespace': 'error',
    'no-iterator': 'off',
    'no-label-var': 'off',
    'no-labels': 'error',
    'no-lone-blocks': 'error',
    'no-lonely-if': 'error',
    'no-loop-func': 'error',
    'no-magic-numbers': 'off',
    'no-mixed-operators': 'off',
    'no-mixed-requires': 'off',
    'no-mixed-spaces-and-tabs': 'error',
    'no-multi-assign': 'error',
    'no-multi-spaces': 'error',
    'no-multi-str': 'error',
    'no-multiple-empty-lines': ['error', { max: 1, maxBOF: 0 }],
    'no-native-reassign': 'error',
    'no-negated-condition': 'off',
    'no-negated-in-lhs': 'error',
    'no-nested-ternary': 'error',
    'no-new': 'off',
    'no-new-func': 'error',
    'no-new-object': 'error',
    'no-new-require': 'off',
    'no-new-symbol': 'error',
    'no-new-wrappers': 'error',
    'no-obj-calls': 'error',
    'no-octal': 'error',
    'no-octal-escape': 'error',
    'no-param-reassign': 'error',
    'no-path-concat': 'off',
    'no-plusplus': 'off',
    'no-process-env': 'off',
    'no-process-exit': 'off',
    'no-proto': 'error',
    'no-prototype-builtins': 'off',
    'no-redeclare': 'error',
    'no-regex-spaces': 'error',
    'no-restricted-globals': ['error'].concat(restrictedGlobals),
    'no-restricted-imports': 'off',
    'no-restricted-modules': 'off',
    'no-restricted-properties': 'off',
    'no-restricted-syntax': 'off',
    'no-return-assign': 'error',
    'no-return-await': 'error',
    'no-script-url': 'error',
    'no-self-assign': 'error',
    'no-self-compare': 'error',
    'no-sequences': 'error',
    'no-shadow': 'error',
    'no-shadow-restricted-names': 'error',
    'no-sparse-arrays': 'error',
    'no-sync': 'off',
    'no-tabs': 'error',
    'no-template-curly-in-string': 'error',
    'no-ternary': 'off',
    'no-this-before-super': 'error',
    'no-throw-literal': 'error',
    'no-trailing-spaces': 'error',
    'no-undef': 'error',
    'no-undef-init': 'off',
    'no-undefined': 'off',
    'no-underscore-dangle': 'warn',
    'no-unexpected-multiline': 'error',
    'no-unmodified-loop-condition': 'off',
    'no-unneeded-ternary': ['error', { defaultAssignment: false }],
    'no-unreachable': 'error',
    'no-unsafe-finally': 'error',
    'no-unsafe-negation': 'error',
    'no-unused-expressions': ['error', { allowShortCircuit: true, allowTernary: true }],
    'no-unused-labels': 'error',
    'no-unused-vars': ['error', { args: 'none', ignoreRestSiblings: true }],
    'no-use-before-define': ['error', { functions: false }],
    'no-useless-call': 'off',
    'no-useless-computed-key': 'error',
    'no-useless-concat': 'error',
    'no-useless-constructor': 'error',
    'no-useless-escape': 'error',
    'no-useless-rename': 'error',
    'no-useless-return': 'error',
    'no-var': 'error',
    'no-void': 'off',
    'no-warning-comments': 'warn',
    'no-whitespace-before-property': 'error',
    'no-with': 'error',
    'nonblock-statement-body-position': 'off',
    'object-curly-newline': ['error', { consistent: true }],
    'object-curly-spacing': ['error', 'always'],
    'object-property-newline': ['error', { allowMultiplePropertiesPerLine: true }],
    'object-shorthand': ['error', 'always', { avoidExplicitReturnArrows: true, avoidQuotes: true }],
    'one-var': ['error', 'never'],
    'one-var-declaration-per-line': 'error',
    'operator-assignment': 'off',
    'operator-linebreak': 'error',
    'padded-blocks': ['error', 'never'],
    'padding-line-between-statements': 'off',
    'prefer-arrow-callback': 'warn',
    'prefer-const': ['error', { destructuring: 'any', ignoreReadBeforeAssign: true }],
    'prefer-destructuring': 'error',
    'prefer-numeric-literals': 'error',
    'prefer-promise-reject-errors': 'error',
    'prefer-reflect': 'off',
    'prefer-rest-params': 'error',
    'prefer-spread': 'error',
    'prefer-template': 'warn',
    'quote-props': ['error', 'as-needed'],
    'quotes': ['error', 'single'],
    'radix': 'error',
    'require-await': 'error',
    'require-jsdoc': 'off',
    'require-yield': 'error',
    'rest-spread-spacing': 'error',
    'semi': ['error', 'always'],
    'semi-spacing': 'error',
    'semi-style': 'off',
    'sort-imports': 'off',
    'sort-keys': 'off',
    'sort-vars': 'off',
    'space-before-blocks': 'error',
    'space-before-function-paren': ['error', 'never'],
    'space-in-parens': 'error',
    'space-infix-ops': 'error',
    'space-unary-ops': 'error',
    'spaced-comment': 'error',
    'strict': ['error', 'never'],
    'switch-colon-spacing': 'error',
    'symbol-description': 'error',
    'template-curly-spacing': 'error',
    'template-tag-spacing': 'error',
    'unicode-bom': 'error',
    'use-isnan': 'error',
    'valid-jsdoc': 'off',
    'valid-typeof': 'error',
    'vars-on-top': 'off',
    'wrap-iife': 'off',
    'wrap-regex': 'off',
    'yield-star-spacing': ['error', 'after'],
    'yoda': 'error',
  },
};
<|endoftext|>


<commit_before>var _URL = window.URL || window.webkitURL;

var acceptedTypes = {
    'image/png': true,
    'image/jpeg': true,
    'image/gif': true
};

/**
 * CreatorPage is the UI component object that encapsulates all JavaScript page
 * interactions on the create new floor plan page.
 *
 * @constructor
 * @param {jQuery selector} floorLabel is the input field for the floor label
 * @param {jQuery selector} submitButton is the submission button
 * @param {jQuery selector} imageHolder is the drop zone for the img floorplan
 */
var CreatorPage = function(floorLabel, submitButton, imageHolder) {
    var that = this;

    this.imageFile = null;

    // set child elements
    this.children = {};
    this.children.imageHolder = imageHolder;
    this.children.floorLabel = floorLabel;
    this.children.submitButton = submitButton;
    this.children.canvas = null;

    // set holder callbacks
    this.children.imageHolder.on('dragover', function(e) {
        e.preventDefault();
        e.stopPropagation();
        that.children.imageHolder.addClass('hover');
    });

    this.children.imageHolder.on('dragend', function(e) {
        e.preventDefault();
        e.stopPropagation();
        that.children.imageHolder.removeClass('hover');
    });

    this.children.imageHolder.on('drop', function(e) {
        e.preventDefault();
        e.stopPropagation();
        that.children.imageHolder.removeClass('hover');
        if (that.imageFile === null) {
            // image file not set yet.
            if (e.originalEvent.dataTransfer.files.length === 1) {
                that.setImage(e.originalEvent.dataTransfer.files[0]);
            }
        } else {
            // image file already set. should ask if want to replace
            // note that canvas needs to be replaced as well.
        }
    });

    this.children.submitButton.on('click', function(e) {
        that.publish();
    });
};

CreatorPage.prototype.uploadImage = function(file) {
    $.ajax({
        url: '/up',
        type: 'POST',
        processData: false,
        contentType: 'application/octet-stream',
        beforeSend: function(request) {
            request.setRequestHeader("X-File-Name", file.name);
        },
        data: file
    });
};

CreatorPage.prototype.setImage = function(file) {
    this.previewFile(file);
    this.imageFile = file;
    this.children.imageHolder.addClass('solidified');
    // add canvas
};

CreatorPage.prototype.previewFile = function(file) {
    var that = this;
    if (file && acceptedTypes[file.type] === true) {
        var reader = new FileReader();
        reader.onload = function (event) {
            var image = new Image();
            //image.src = event.target.result;
            //image.className = 'floor-img';
            //that.children.imageHolder.html("");
            //that.children.imageHolder.append(image);
            var svg = $('<svg id="img-canvas">');

            image.onload = function() {
                svg.css('background-image', 'url(' + event.target.result + ')');
                svg.attr('height', this.height);
                svg.attr('width', this.width);

                that.children.imageHolder.html('');
                that.children.imageHolder.append(svg);
            };

            image.src = _URL.createObjectURL(file);
        };

        reader.readAsDataURL(file);
    }  else {
        console.log('Not an acceptable file type!');
        console.log(file);
    }
};

CreatorPage.prototype.attachCanvas = function() {
};

CreatorPage.prototype.publish = function() {
    var floorLabelText = this.children.floorLabel.val();
    this.disableUI();
    if (floorLabelText.length > 0) {
        if (this.imageFile !== null) {
            // upload the image to server
            //this.uploadImage(this.imageFile);
            console.log(floorLabelText);
            console.log(this.imageFile);
        } else {
            alert("Please drop in a floorplan image");
            this.enableUI();
        }
    } else {
        alert("Please enter a floor label");
        this.enableUI();
        this.children.floorLabel.focus();
    }
};

CreatorPage.prototype.flashDropzone = function() {
    //TODO: flash the drop zone
};

CreatorPage.prototype.disableUI = function() {
    this.children.floorLabel.attr('disabled', 'disabled');
    this.children.submitButton.attr('disabled', 'disabled');
};

CreatorPage.prototype.enableUI = function() {
    this.children.floorLabel.removeAttr('disabled');
    this.children.submitButton.removeAttr('disabled');
};
<commit_msg>css hack for re-rendering.<commit_after>var _URL = window.URL || window.webkitURL;

var acceptedTypes = {
    'image/png': true,
    'image/jpeg': true,
    'image/gif': true
};

/**
 * CreatorPage is the UI component object that encapsulates all JavaScript page
 * interactions on the create new floor plan page.
 *
 * @constructor
 * @param {jQuery selector} floorLabel is the input field for the floor label
 * @param {jQuery selector} submitButton is the submission button
 * @param {jQuery selector} imageHolder is the drop zone for the img floorplan
 */
var CreatorPage = function(floorLabel, submitButton, imageHolder) {
    var that = this;

    this.imageFile = null;

    // set child elements
    this.children = {};
    this.children.imageHolder = imageHolder;
    this.children.floorLabel = floorLabel;
    this.children.submitButton = submitButton;
    this.children.canvas = null;

    // set holder callbacks
    this.children.imageHolder.on('dragover', function(e) {
        e.preventDefault();
        e.stopPropagation();
        that.children.imageHolder.addClass('hover');
    });

    this.children.imageHolder.on('dragend', function(e) {
        e.preventDefault();
        e.stopPropagation();
        that.children.imageHolder.removeClass('hover');
    });

    this.children.imageHolder.on('drop', function(e) {
        e.preventDefault();
        e.stopPropagation();
        that.children.imageHolder.removeClass('hover');
        if (that.imageFile === null) {
            // image file not set yet.
            if (e.originalEvent.dataTransfer.files.length === 1) {
                that.setImage(e.originalEvent.dataTransfer.files[0]);
            }
        } else {
            // image file already set. should ask if want to replace
            // note that canvas needs to be replaced as well.
        }
    });

    this.children.submitButton.on('click', function(e) {
        that.publish();
    });
};

CreatorPage.prototype.uploadImage = function(file) {
    $.ajax({
        url: '/up',
        type: 'POST',
        processData: false,
        contentType: 'application/octet-stream',
        beforeSend: function(request) {
            request.setRequestHeader("X-File-Name", file.name);
        },
        data: file,
        success: this.submitData.bind(this)
    });
};

CreatorPage.prototype.submitData = function(response) {
    // send img file name & floor label & zone info
};

CreatorPage.prototype.setImage = function(file) {
    this.previewFile(file);
    this.imageFile = file;
    this.children.imageHolder.addClass('solidified');
    // add canvas
};

CreatorPage.prototype.previewFile = function(file) {
    var that = this;
    if (file && acceptedTypes[file.type] === true) {
        var reader = new FileReader();
        reader.onload = function (event) {
            var image = new Image();
            //image.src = event.target.result;
            //image.className = 'floor-img';
            //that.children.imageHolder.html("");
            //that.children.imageHolder.append(image);
            var svg = $('<svg id="img-canvas">');

            image.onload = function() {
                svg.css('background-image', 'url(' + event.target.result + ')');
                svg.attr('height', this.height);
                svg.attr('width', this.width);

                that.children.imageHolder.html('');
                that.children.imageHolder.append(svg);

                // needed hack to re-render the drop space
                that.children.imageHolder.css('background', 'transparent');
            };

            image.src = _URL.createObjectURL(file);
        };

        reader.readAsDataURL(file);
    }  else {
        console.log('Not an acceptable file type!');
        console.log(file);
    }
};

CreatorPage.prototype.publish = function() {
    var floorLabelText = this.children.floorLabel.val();
    this.disableUI();
    if (floorLabelText.length > 0) {
        if (this.imageFile !== null) {
            // upload the image to server
            this.uploadImage(this.imageFile);
            console.log(floorLabelText);
            console.log(this.imageFile);
        } else {
            alert("Please drop in a floorplan image");
            this.enableUI();
        }
    } else {
        alert("Please enter a floor label");
        this.enableUI();
        this.children.floorLabel.focus();
    }
};

CreatorPage.prototype.flashDropzone = function() {
    //TODO: flash the drop zone
};

CreatorPage.prototype.disableUI = function() {
    this.children.floorLabel.attr('disabled', 'disabled');
    this.children.submitButton.attr('disabled', 'disabled');
};

CreatorPage.prototype.enableUI = function() {
    this.children.floorLabel.removeAttr('disabled');
    this.children.submitButton.removeAttr('disabled');
};
<|endoftext|>


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

	var current_file_id = 0;
	var prev_count_files = 0;
	var all_files = [];
	var locked = false;
  	var waiting = 0;

	function noopHandler(evt) {
		evt.stopPropagation();
		evt.preventDefault();
	}

	function drop(evt) {

		noopHandler(evt);

		var files = evt.dataTransfer.files;
		var count = files.length;

		if ( count > 0 ) {

			prev_count_files = all_files.length;

			if ( $("#dropzoneLabel").length != 0 )
				$("#dropzone").html('');

			for ( var i = prev_count_files + waiting, j = 0; i < prev_count_files + files.length + waiting; i++, j++ ) {
				$("#dropzone").append('

' + files[j].name + '

Waiting...

');
			}

          	waiting += count;

			if ( ! locked ) {
              	waiting -= count;
				all_files.push.apply(all_files, files);
				handleNextFile();
			}
		}
	}

	function handleReaderLoad(evt) {

		var current_file = {};

		current_file.name = all_files[current_file_id].name;
		current_file.type = all_files[current_file_id].type;
		current_file.contents = evt.target.result;

		$.post('/upload', JSON.stringify(current_file), function(data) {
			all_files[current_file_id] = 1;
			$(".file." + current_file_id + " .progress").html("Uploaded");
			current_file_id++;
			handleNextFile();
		});
	}

	function handleNextFile() {

		if ( current_file_id < all_files.length ) {

			locked = true;

			var current_file = all_files[current_file_id];

			$(".file." + current_file_id + " .progress").html("Processing...");

			var reader = new FileReader();
			reader.onload = handleReaderLoad;
			reader.readAsDataURL(current_file);
		} else {
			locked = false;
		}
	}

	var dropzone = document.getElementById("dropzone");
	dropzone.addEventListener("dragenter", noopHandler, false);
	dropzone.addEventListener("dragexit", noopHandler, false);
	dropzone.addEventListener("dragover", noopHandler, false);
	dropzone.addEventListener("drop", drop, false);
});<commit_msg>The JS code run in the browser is improved.<commit_after>;(function($, window) {

	"use strict";

	var document = window.document;

	$(document).ready(function() {

		var all_files = [],
			current_file_id = 0,
			locked = false,
			prev_count_files = 0,
			waiting = 0,
			drop, dropzone, handleNextFile, handleReaderLoad, noopHandler;

		noopHandler = function(evt) {
			evt.stopPropagation();
			evt.preventDefault();
		};

		drop = function(evt) {

			noopHandler(evt);

			var files = evt.dataTransfer.files,
				count = files.length,
				i, j;

			if ( count > 0 ) {

				prev_count_files = all_files.length;

				if ( $("#dropzoneLabel").length !== 0 ) {
					$("#dropzone").html('');
				}

				for ( i = prev_count_files + waiting, j = 0; i < prev_count_files + files.length + waiting; i++, j++ ) {
					$("#dropzone").append('

' + files[j].name + '

Waiting...

');
				}

				waiting += count;

				if ( ! locked ) {
					waiting -= count;
					all_files.push.apply(all_files, files);
					handleNextFile();
				}
			}
		};

		handleReaderLoad = function(evt) {

			var current_file = {};

			current_file.name = all_files[current_file_id].name;
			current_file.type = all_files[current_file_id].type;
			current_file.contents = evt.target.result;

			$.post('/upload', JSON.stringify(current_file), function(data, textStatus, jqXHR) {

				if ( jqXHR.status == 200 ) {
					$(".file." + current_file_id + " .progress").html("Uploaded");
				} else {
					$(".file." + current_file_id + " .progress").html("Failed");
				}

				all_files[current_file_id] = 1;
				current_file_id++;
				handleNextFile();
			});
		};

		handleNextFile = function() {

			if ( current_file_id < all_files.length ) {

				locked = true;

				$(".file." + current_file_id + " .progress").html("Uploading...");

				var current_file = all_files[current_file_id],
					reader = new FileReader();

				reader.onload = handleReaderLoad;
				reader.readAsDataURL(current_file);

			} else {
				locked = false;
			}
		};

		dropzone = document.getElementById("dropzone");
		dropzone.addEventListener("dragenter", noopHandler, false);
		dropzone.addEventListener("dragexit", noopHandler, false);
		dropzone.addEventListener("dragover", noopHandler, false);
		dropzone.addEventListener("drop", drop, false);
	});

}(jQuery, window));<|endoftext|>


<commit_before>const socket = io('https://noters.ir:8143');
var player, nobat, name , clicked = false;
$('form').submit(function () {
    name = $("#nameInp").val();
    var mode = $("#modeSel").val();
    socket.emit('game', {
        name: name,
        mode: mode
    });
    return false;
});

socket.on('waitG', () => {
    player = 1;
    $("#sendBtn").html("please wait for second player ...");
    $("#sendBtn").css('color', 'red');
    $("#sendBtn").prop('disabled', true);
});

socket.on('startG', (data) => {
    if (player) {
        player = data.p1;
    } else {
        player = data.p2;
    }
    $("#sendBtn").html("after 7 seconds, game willbe starting");
    $("#sendBtn").css('color', 'black');
    $("#sendBtn").prop('disabled', true);
    setTimeout(() => {
        $("#body").empty();
        $("#head").empty();
        $("head").append(`
            <meta charset="utf-8">
            <meta name="viewport" content="initial-scale=1.0">
            <title>game</title>
            <link href="http://fonts.googleapis.com/css?family=Raleway:300,400,400,100" rel="stylesheet" type="text/css">
            <link rel="stylesheet" href="css/standardize.css">
            <link rel="stylesheet" href="css/game-grid.css">
            <link rel="stylesheet" href="css/game.css">`);
        $("#body").append(`

                <button id="0" class="_button _button-1 js-btn-g-v"></button>
                <button id="1" class="_button _button-2 js-btn-g-v"></button>
                <button id="2" class="_button _button-3 js-btn-g-v"></button>
                <button id="3" class="_button _button-4 js-btn-g-v"></button>
                <button id="4" class="_button _button-5 js-btn-g-v"></button>
                <button id="5" class="_button _button-6 js-btn-g-v"></button>
                <button id="6" class="_button _button-7 js-btn-g-v"></button>
                <button id="7" class="_button _button-8 js-btn-g-v"></button>
                <button id="8" class="_button _button-9 js-btn-g-v"></button>

you are : ${player==0?'x':'o'}

${player==0?'you\'r':'his/m'} turn.

                <button class="_button _button-10" id="btnCancel">cancel</button>

`);
        $("#body").attr('class', 'container container-1 clearfix');
    }, 7 * 1000);
});

$("body").on('click', '#btns', function (e) {
    if (!clicked) {
        var number = parseInt($(e.target).attr('id'));
        if (isNaN(number)) return;
        socket.emit('btn', {
            name: name,
            i: parseInt(number / 3),
            j: number % 3
        });
        clicked = true;
    } else {}
});

$("body").on('click', '#btnCancel', () => {
    if (confirm('are you sure?')) {
        socket.emit('disconnecting', 'by user');
        window.open('', '_self').close();
        window.close();
        close();
        $("#body").empty();
        $("#head").empty();
        $("head").append(`<link rel="stylesheet" href="css/index.css">`);
        $("#body").append(`<p class="text">Good Bye</p>`);
    }
});

socket.on('btnR', (r) => {
    if (r.r == true) {
        $("#" + r.num).html(r.p == 0 ? 'x' : 'o');
        $("#turn").html((r.p == player ? 'his/m' : 'you\'r') + " turn.");
    } else {
        alert("its his/m turn or select disable button.");
    }
    clicked = false;
})

socket.on('win', (data) => {
    $("#body").empty();
    $("#head").empty();
    $("head").append(`<link rel="stylesheet" href="css/index.css">`);
    if (player == data.winner) {
        $("#body").append(`<p class="text">YOU WON</p><p class="text">you'r rating is ${data.rating}</p>`);
    } else {
        $("#body").append(`<p class="text">GAME OVER</p>`);
    }
})

socket.on('equ', (data) => {
    $("#body").empty();
    $("#head").empty();
    $("head").append(`<link rel="stylesheet" href="css/index.css">`);
    $("#body").append(`<p class="text">YOU EQUATED</p><p class="text">you'r rating is ${data.players[player]} </p>`);
})

socket.on('dis', () => {
    $("#body").empty();
    $("#head").empty();
    $("head").append(`<link rel="stylesheet" href="css/index.css">`);
    $("#body").append(`<p class="text">DISCONNECTION</br>YOU WON</br>(but not saved in rating.)</p>`);
})
<commit_msg>Update indexj.js<commit_after>const socket = io('https://noters.ir');
var player, nobat, name , clicked = false;
$('form').submit(function () {
    name = $("#nameInp").val();
    var mode = $("#modeSel").val();
    socket.emit('game', {
        name: name,
        mode: mode
    });
    return false;
});

socket.on('waitG', () => {
    player = 1;
    $("#sendBtn").html("please wait for second player ...");
    $("#sendBtn").css('color', 'red');
    $("#sendBtn").prop('disabled', true);
});

socket.on('startG', (data) => {
    if (player) {
        player = data.p1;
    } else {
        player = data.p2;
    }
    $("#sendBtn").html("after 7 seconds, game willbe starting");
    $("#sendBtn").css('color', 'black');
    $("#sendBtn").prop('disabled', true);
    setTimeout(() => {
        $("#body").empty();
        $("#head").empty();
        $("head").append(`
            <meta charset="utf-8">
            <meta name="viewport" content="initial-scale=1.0">
            <title>game</title>
            <link href="http://fonts.googleapis.com/css?family=Raleway:300,400,400,100" rel="stylesheet" type="text/css">
            <link rel="stylesheet" href="css/standardize.css">
            <link rel="stylesheet" href="css/game-grid.css">
            <link rel="stylesheet" href="css/game.css">`);
        $("#body").append(`

                <button id="0" class="_button _button-1 js-btn-g-v"></button>
                <button id="1" class="_button _button-2 js-btn-g-v"></button>
                <button id="2" class="_button _button-3 js-btn-g-v"></button>
                <button id="3" class="_button _button-4 js-btn-g-v"></button>
                <button id="4" class="_button _button-5 js-btn-g-v"></button>
                <button id="5" class="_button _button-6 js-btn-g-v"></button>
                <button id="6" class="_button _button-7 js-btn-g-v"></button>
                <button id="7" class="_button _button-8 js-btn-g-v"></button>
                <button id="8" class="_button _button-9 js-btn-g-v"></button>

you are : ${player==0?'x':'o'}

${player==0?'you\'r':'his/m'} turn.

                <button class="_button _button-10" id="btnCancel">cancel</button>

`);
        $("#body").attr('class', 'container container-1 clearfix');
    }, 7 * 1000);
});

$("body").on('click', '#btns', function (e) {
    if (!clicked) {
        var number = parseInt($(e.target).attr('id'));
        if (isNaN(number)) return;
        socket.emit('btn', {
            name: name,
            i: parseInt(number / 3),
            j: number % 3
        });
        clicked = true;
    } else {}
});

$("body").on('click', '#btnCancel', () => {
    if (confirm('are you sure?')) {
        socket.emit('disconnecting', 'by user');
        window.open('', '_self').close();
        window.close();
        close();
        $("#body").empty();
        $("#head").empty();
        $("head").append(`<link rel="stylesheet" href="css/index.css">`);
        $("#body").append(`<p class="text">Good Bye</p>`);
    }
});

socket.on('btnR', (r) => {
    if (r.r == true) {
        $("#" + r.num).html(r.p == 0 ? 'x' : 'o');
        $("#turn").html((r.p == player ? 'his/m' : 'you\'r') + " turn.");
    } else {
        alert("its his/m turn or select disable button.");
    }
    clicked = false;
})

socket.on('win', (data) => {
    $("#body").empty();
    $("#head").empty();
    $("head").append(`<link rel="stylesheet" href="css/index.css">`);
    if (player == data.winner) {
        $("#body").append(`<p class="text">YOU WON</p><p class="text">you'r rating is ${data.rating}</p>`);
    } else {
        $("#body").append(`<p class="text">GAME OVER</p>`);
    }
})

socket.on('equ', (data) => {
    $("#body").empty();
    $("#head").empty();
    $("head").append(`<link rel="stylesheet" href="css/index.css">`);
    $("#body").append(`<p class="text">YOU EQUATED</p><p class="text">you'r rating is ${data.players[player]} </p>`);
})

socket.on('dis', () => {
    $("#body").empty();
    $("#head").empty();
    $("head").append(`<link rel="stylesheet" href="css/index.css">`);
    $("#body").append(`<p class="text">DISCONNECTION</br>YOU WON</br>(but not saved in rating.)</p>`);
})
<|endoftext|>


<commit_before>IONUX = {
  Dashboard: {},
  Templates: {},
  Interactions: {},
  Models:{},
  Collections:{},
  Views: {},
  Router: {},
  init: function(){

    // HACK - temporarily disable salt.css on init;
    $('.salt').prop('disabled', true);

    var router = new IONUX.Router();
    IONUX.ROUTER = router;
    IONUX.setup_ajax_error();

    // Bootstrap navigation menu
    $.ajax({
      async: false,
      url: '/ui/navigation/',
      success: function(resp) {
        new IONUX.Views.ViewControls().render().el;

        // MAPS Sidebar (initially shown)
        IONUX.Dashboard.Observatories = new IONUX.Collections.Observatories(resp.data.observatories)
        new IONUX.Views.ObservatorySelector({collection: IONUX.Dashboard.Observatories, title: 'Site'}).render().el;
        new IONUX.Views.MapFilter().render().el;

        // RESOURCES Sidebar (initially hidden)
        IONUX.Dashboard.Orgs = new IONUX.Collections.Orgs(resp.data.orgs);
        new IONUX.Views.OrgSelector({collection: IONUX.Dashboard.Orgs, title: 'Facility'}).render().el;
        new IONUX.Views.ListFilter().render().el;

        new IONUX.Views.DataAssetFilter().render().el;
        new IONUX.Views.DPFilterActions({el: '#map-filter-heading'});
        // new IONUX.Views.AssetFilterActions({el: '#map-filter-heading'});

        $.ajax({
            url: '/get_data_product_group_list/',
            success: function(resp, resp2) {
              new IONUX.Views.DataProductFilter({group_list: resp.data}).render().el;
              $('#left .map-view').show();
            }
        });
      },
      complete: function(resp){
        // Wrapper initially hidden to prevent unformed content from appearing while
        // API calls being made to draw the dashboard;
        $('.wrapper').show();
        Backbone.history.start({pushState:true, hashChange: false});
        // router.handle_navigation();
        // return router;
      },
    });

    IONUX.SESSION_MODEL = new IONUX.Models.Session();
    IONUX.SESSION_MODEL.fetch({
      success: function(resp) {
        new IONUX.Views.Topbar({model: IONUX.SESSION_MODEL}).render().el
        new IONUX.Views.Search().render().el;
        new IONUX.Views.DashboardActions();
        new IONUX.Views.HelpMenu({model: IONUX.SESSION_MODEL}).render().el;

        // nag popup!
        if (IONUX.SESSION_MODEL.get('is_logged_in') && !IONUX.SESSION_MODEL.get('is_registered'))
          router.user_profile();

        // Enable session polling for updated roles, possibly UI version changes.
        // IONUX.SESSION_MODEL.start_polling();
      }
    });

    router.handle_navigation();
    return router;
  },
  setup_ajax_error: function(){
    $(document).ajaxError(function(evt, resp){
      try {
        var json_obj = JSON.parse(resp['responseText'])
        var error_obj = null;
        if (_.isArray(json_obj.data)) {
          error_obj = _.pluck(_.compact(json_obj.data), 'GatewayError');
        } else {
          error_obj = [json_obj.data.GatewayError];
        }
      } catch(err) {
        // not all errors are JSON or GatewayErrors.. still support them
        error_obj = [{Message:resp['responseText']}]
      }

      $('#spinner').remove();

      var open_modal = $('.modal-ooi').is(':visible') ? true : false;
      if (open_modal) $('#action-modal').modal('hide').remove();

      var force_logout = _.any(_.compact(_.pluck(error_obj, 'NeedLogin')));

      new IONUX.Views.Error({error_objs:error_obj,open_modal:open_modal, force_logout:force_logout}).render().el;
    });
  },
  is_logged_in: function(){
    return IONUX.SESSION_MODEL.get('is_logged_in');
  },
  is_owner: function(){
    var user_id = IONUX.SESSION_MODEL.get('user_id');
    var owner_match = _.findWhere(MODEL_DATA.owners, {_id: user_id}) ? true : false;
    return owner_match;
  },
  Spinner: {
    large: {
      lines: 13,
      length: 7,
      width: 4,
      radius: 10,
      corners: 1,
      rotate: 0,
      color: '#999',
      speed: 1,
      trail: 60,
      shadow: false,
      hwaccel: false,
      className: 'spinner',
      zIndex: 2e9,
      top: 'auto',
      left: 'auto'
    }
  },
  EditResourceBlacklist: []
}
<commit_msg>Render appropriate actionmenu based on page type (dashboard or facepage).<commit_after>IONUX = {
  Dashboard: {},
  Templates: {},
  Interactions: {},
  Models:{},
  Collections:{},
  Views: {},
  Router: {},
  init: function(){

    // HACK - temporarily disable salt.css on init;
    $('.salt').prop('disabled', true);

    var router = new IONUX.Router();
    IONUX.ROUTER = router;
    IONUX.setup_ajax_error();

    // Bootstrap navigation menu
    $.ajax({
      async: false,
      url: '/ui/navigation/',
      success: function(resp) {
        new IONUX.Views.ViewControls().render().el;

        // MAPS Sidebar (initially shown)
        IONUX.Dashboard.Observatories = new IONUX.Collections.Observatories(resp.data.observatories)
        new IONUX.Views.ObservatorySelector({collection: IONUX.Dashboard.Observatories, title: 'Site'}).render().el;
        new IONUX.Views.MapFilter().render().el;

        // RESOURCES Sidebar (initially hidden)
        IONUX.Dashboard.Orgs = new IONUX.Collections.Orgs(resp.data.orgs);
        new IONUX.Views.OrgSelector({collection: IONUX.Dashboard.Orgs, title: 'Facility'}).render().el;
        new IONUX.Views.ListFilter().render().el;

        new IONUX.Views.DataAssetFilter().render().el;
        new IONUX.Views.DPFilterActions({el: '#map-filter-heading'});

        // new IONUX.Views.AssetFilterActions({el: '#map-filter-heading'});

        $.ajax({
            url: '/get_data_product_group_list/',
            success: function(resp, resp2) {
              new IONUX.Views.DataProductFilter({group_list: resp.data}).render().el;
              $('#left .map-view').show();
            }
        });
      },
      complete: function(resp){
        // Wrapper initially hidden to prevent unformed content from appearing while
        // API calls being made to draw the dashboard;
        $('.wrapper').show();
        Backbone.history.start({pushState:true, hashChange: false});
        // router.handle_navigation();
        // return router;
      },
    });

    IONUX.SESSION_MODEL = new IONUX.Models.Session();
    IONUX.SESSION_MODEL.fetch({
      success: function(resp) {
        new IONUX.Views.Topbar({model: IONUX.SESSION_MODEL}).render().el
        new IONUX.Views.Search().render().el;

        // Check if on dashboard or facepage, render appropriate menu.
        if (_.contains(window.location.href.split('/'), 'face')) {
          new IONUX.Views.ViewActions();
        } else {
          new IONUX.Views.DashboardActions();
        };

        new IONUX.Views.HelpMenu({model: IONUX.SESSION_MODEL}).render().el;

        // nag popup!
        if (IONUX.SESSION_MODEL.get('is_logged_in') && !IONUX.SESSION_MODEL.get('is_registered'))
          router.user_profile();

        // Enable session polling for updated roles, possibly UI version changes.
        // IONUX.SESSION_MODEL.start_polling();
      }
    });

    router.handle_navigation();
    return router;
  },
  setup_ajax_error: function(){
    $(document).ajaxError(function(evt, resp){
      try {
        var json_obj = JSON.parse(resp['responseText'])
        var error_obj = null;
        if (_.isArray(json_obj.data)) {
          error_obj = _.pluck(_.compact(json_obj.data), 'GatewayError');
        } else {
          error_obj = [json_obj.data.GatewayError];
        }
      } catch(err) {
        // not all errors are JSON or GatewayErrors.. still support them
        error_obj = [{Message:resp['responseText']}]
      }

      $('#spinner').remove();

      var open_modal = $('.modal-ooi').is(':visible') ? true : false;
      if (open_modal) $('#action-modal').modal('hide').remove();

      var force_logout = _.any(_.compact(_.pluck(error_obj, 'NeedLogin')));

      new IONUX.Views.Error({error_objs:error_obj,open_modal:open_modal, force_logout:force_logout}).render().el;
    });
  },
  is_logged_in: function(){
    return IONUX.SESSION_MODEL.get('is_logged_in');
  },
  is_owner: function(){
    var user_id = IONUX.SESSION_MODEL.get('user_id');
    var owner_match = _.findWhere(MODEL_DATA.owners, {_id: user_id}) ? true : false;
    return owner_match;
  },
  Spinner: {
    large: {
      lines: 13,
      length: 7,
      width: 4,
      radius: 10,
      corners: 1,
      rotate: 0,
      color: '#999',
      speed: 1,
      trail: 60,
      shadow: false,
      hwaccel: false,
      className: 'spinner',
      zIndex: 2e9,
      top: 'auto',
      left: 'auto'
    }
  },
  EditResourceBlacklist: []
}
<|endoftext|>