<commit_before>Ext.namespace('Vps.Component');
Vps.Component.Pages = Ext.extend(Ext.Panel, {
    initComponent : function()
    {
        this.treePanel = new Vps.Auto.SyncTreePanel({
            controllerUrl: '/admin/component/pages',
            title       : 'Seitenbaum',
            region      : 'west',
            split       : true,
            width       : 300,
            collapsible : true,
            minSize     : 200,
            maxSize     : 600,
            tbar        : []
        });
        this.contentTabPanel = new Ext.TabPanel({
            region      : 'center'
        });

        this.layout = 'border';
        this.actions = {};
        this.items = [this.treePanel, this.contentTabPanel];
        Vps.Component.Pages.superclass.initComponent.call(this);

        this.treePanel.on('loaded', this.onTreePanelLoaded, this);
        this.on('editcomponent', this.loadComponent, this);
        this.setupEditform();

        this.editActions = {};
    },

    setupEditform : function ()
    {
    	this.editDialog = new Vps.Component.PageEdit({
            width: 400,
            height: 400,
            controllerUrl: '/admin/component/pageEdit'
        });
        this.editDialog.on('datachange', function(test) {
            this.treePanel.tree.root.reload();
        }, this);
    },

    onTreePanelLoaded : function(tree)
    {
        this.pageButtonMenu = new Ext.menu.Menu({
            items    : [
                '-',
                this.getAction('properties'),
                this.getAction('add'),
                this.getAction('delete'),
                this.getAction('visible'),
                this.getAction('makeHome'),
                this.getAction('preview')
            ]
        });
        this.pageButton = new Ext.Toolbar.Button({
            cls     : 'x-btn-text-icon bmenu',
            text    : trlVps('Page'),
            menu    : this.pageButtonMenu,
            icon    : '/assets/silkicons/page.png',
            disabled: true
        });

        this.treePanel.getTopToolbar().add(
            this.pageButton,
            '->',
            this.treePanel.getAction('reload')
        );

        this.contextMenu = new Ext.menu.Menu({
             items: [
                '-',
                this.getAction('properties'),
                this.getAction('add'),
                this.getAction('delete'),
                this.getAction('visible'),
                this.getAction('makeHome'),
                this.getAction('preview'),
                '-',
                this.getAction('expand'),
                this.getAction('collapse')
            ]
        });

        tree.on('click', this.treeSelectionchange, this);
        tree.on('contextmenu', function (node) {
            node.select();
            this.treeSelectionchange(node);
            this.contextMenu.show(node.ui.getAnchor());
        }, this);

        tree.on('dblclick', function (o, e) {
        	if (o.attributes.allowed) {
				var action;
	            for (var i in this.editActions) {
	                if (!this.editActions[i].isHidden()) {
	                    action = this.editActions[i];
	                }
	            }
				if (action) {
					action.execute(action.initialConfig);
				}
        	}
        }, this);
    },

    treeSelectionchange : function (node) {
        if (node) {
            this.pageButton.enable();
            for (var i in this.editActions) {
                this.editActions[i].hide();
            }
            if (!node.attributes.allowed) {
            	this.pageButton.disable();
            } else {
            	this.pageButton.enable();
            }

            if (node.attributes.type != 'default' || !node.attributes.allowed) {
                this.getAction('properties').disable();
                this.getAction('delete').disable();
                this.getAction('visible').disable();
                this.getAction('makeHome').disable();
                this.getAction('add').disable();
                this.getAction('preview').disable();
            } else {
                this.getAction('properties').enable();
                this.getAction('delete').enable();
                this.getAction('visible').enable();
                this.getAction('makeHome').enable();
                this.getAction('add').enable();
                this.getAction('preview').enable();
            }
			if (node.attributes.type == 'category' && node.attributes.allowed) {
				this.getAction('add').enable();
			}
            node.attributes.data.editComponents.each(function(component) {
                if (!this.editActions[component.componentClass]) {
                    this.editActions[component.componentClass] = new Ext.Action({
                        text    : trlVps('Edit {0}', [component.componentName]),
                        handler : function (o, e) {
                            var node = this.treePanel.tree.getSelectionModel().getSelectedNode();
                            node.attributes.data.editComponents.each(function(component) {
                                if (component.componentClass == o.componentClass) {
                                    this.fireEvent('editcomponent', {
                                        id: component.dbId,
                                        cls: component.componentClass,
                                        text: node.text + ' - ' + component.componentName
                                    });
                                    return false;
                                }
                            }, this);
                        },
                        icon    : component.componentIcon,
                        cls     : 'x-btn-text-icon',
                        scope   : this,
                        disabled : !node.attributes.allowed,
                        componentClass: component.componentClass
                    });
                    this.contextMenu.insert(0, new Ext.menu.Item(this.editActions[component.componentClass]));
                    this.pageButtonMenu.insert(0, new Ext.menu.Item(this.editActions[component.componentClass]));
                }
                this.editActions[component.componentClass].show();
            }, this);
        }
    },

    loadComponent: function(data)
    {
        var panel = this.contentTabPanel.getItem('page'+data.id);
        if (!panel) {
            panel = this.createComponentPanel(data);
            this.contentTabPanel.add(panel);
        }
        this.contentTabPanel.setActiveTab(panel);

        panel.applyBaseParams({
            id: data.id
        });
        panel.load({
            componentClass: data.cls
        });
    },

    createComponentPanel: function(data)
    {
        var panel = new Vps.Component.ComponentPanel({
            id          : 'page'+data.id,
            title       : data.text,
            region      : 'center',
            closable    : true,
            autoLoad    : false,
            componentEditUrl : this.componentEditUrl
        });
        return panel;
    },

    getAction : function(type)
    {
        if (this.actions[type]) return this.actions[type];

        if (type == 'properties') {
            this.actions[type] = new Ext.Action({
                text    : trlVps('Properties of selected Page'),
                handler : function () {
                    this.editDialog.getAutoForm().setBaseParams({});
                    this.editDialog.showEdit(this.treePanel.tree.selModel.selNode.id);
                },
                icon    : '/assets/silkicons/page_gear.png',
                cls     : 'x-btn-text-icon',
                scope   : this
            });
        } else if (type == 'add') {
            this.actions[type] = new Ext.Action({
                text    : trlVps('Add new Subpage'),
                handler : function () {
                    this.editDialog.getAutoForm().setBaseParams({
                        parent_id: this.treePanel.tree.selModel.selNode.id,
                        domain: this.treePanel.tree.selModel.selNode.attributes.domain,
                        category: this.treePanel.tree.selModel.selNode.attributes.category
                    });
                    this.editDialog.showAdd();
                },
                icon    : '/assets/silkicons/page_add.png',
                cls     : 'x-btn-text-icon',
                scope   : this
            });
        } else if (type == 'delete') {
            this.actions[type] = new Ext.Action({
                text    : trlVps('Delete selected Page'),
                handler : this.treePanel.onDelete,
                icon    : '/assets/silkicons/page_delete.png',
                cls     : 'x-btn-text-icon',
                scope   : this.treePanel
            });
        } else if (type == 'visible') {
            this.actions[type] = new Ext.Action({
                text    : trlVps('Toggle Visibility of selected Page'),
                handler : this.treePanel.onVisible,
                icon    : '/assets/silkicons/page_red.png',
                cls     : 'x-btn-text-icon',
                scope   : this.treePanel
            });
        } else if (type == 'makeHome') {
            this.actions[type] = new Ext.Action({
                text    : trlVps('Make selected Page Homepage'),
                handler : function (o, e) {
                    Ext.Ajax.request({
                        url: '/admin/component/pages/json-make-home',
                        success: function(r) {
                            response = Ext.decode(r.responseText);
                            var oldhome = this.treePanel.tree.getNodeById(response.oldhome);
                            oldhome.attributes.visible = response.oldhomeVisible;
                            this.treePanel.setVisible(oldhome);
                            var home = this.treePanel.tree.getNodeById(response.home);
                            home.ui.iconNode.style.backgroundImage = 'url(/assets/silkicons/application_home.png)';
                        },
                        params: {id: this.treePanel.tree.getSelectionModel().getSelectedNode().id },
                        scope: this
                    });
                },
                icon    : '/assets/silkicons/application_home.png',
                cls     : 'x-btn-text-icon',
                scope   : this
            });
        } else if (type == 'expand') {
            this.actions[type] = new Ext.Action({
                text    : trlVps('Expand here'),
                handler : function () { this.treePanel.tree.getSelectionModel().getSelectedNode().expand(true); },
                icon    : '/assets/silkicons/bullet_add.png',
                cls     : 'x-btn-text-icon',
                scope   : this
            });
        } else if (type == 'collapse') {
            this.actions[type] = new Ext.Action({
                text    : trlVps('Collapse here'),
                handler : function () { this.treePanel.tree.getSelectionModel().getSelectedNode().collapse(true); },
                icon    : '/assets/silkicons/bullet_delete.png',
                cls     : 'x-btn-text-icon',
                scope   : this
            });
        } else if (type == 'preview') {
            this.actions[type] = new Ext.Action({
                text    : trlVps('Open Preview'),
                handler : function () {
                    window.open('/admin/component/pages/open-preview?page_id='+
                                this.treePanel.getSelectedId());
                },
                icon    : '/assets/silkicons/page_white_magnify.png',
                cls     : 'x-btn-text-icon',
                scope   : this
            });
        } else {
            throw 'unknown action-type: ' + type;
        }
        return this.actions[type];
    }

});
Ext.reg('vps.component.pages', Vps.Component.Pages);
<commit_msg>Toolbar gleich befÃ¼llen - nicht erst nach dem rendern. Behebt bug bei dem das untere ende der scrollbar nicht sichtbar war, bzw. erst nach resize vom window<commit_after>Ext.namespace('Vps.Component');
Vps.Component.Pages = Ext.extend(Ext.Panel, {
    initComponent : function()
    {
        this.actions = {};

        this.pageButtonMenu = new Ext.menu.Menu({
            items    : [
                '-',
                this.getAction('properties'),
                this.getAction('add'),
                this.getAction('delete'),
                this.getAction('visible'),
                this.getAction('makeHome'),
                this.getAction('preview')
            ]
        });
        this.pageButton = new Ext.Toolbar.Button({
            cls     : 'x-btn-text-icon bmenu',
            text    : trlVps('Page'),
            menu    : this.pageButtonMenu,
            icon    : '/assets/silkicons/page.png',
            disabled: true
        });

        this.treePanel = new Vps.Auto.SyncTreePanel({
            controllerUrl: '/admin/component/pages',
            title       : trlVps('Seitenbaum'),
            region      : 'west',
            split       : true,
            width       : 300,
            collapsible : true,
            minSize     : 200,
            maxSize     : 600,
            autoScroll: true,
            tbar: [this.pageButton, '->']
        });
        this.treePanel.getTopToolbar().add(this.treePanel.getAction('reload'));

        this.contentTabPanel = new Ext.TabPanel({
            region      : 'center'
        });
        this.contentTabPanel.on('render', function() {
            this.contentTabPanel.strip.setHeight(24);
        }, this);

        this.layout = 'border';
        this.items = [this.treePanel, this.contentTabPanel];

        Vps.Component.Pages.superclass.initComponent.call(this);

        this.treePanel.on('loaded', this.onTreePanelLoaded, this);
        this.on('editcomponent', this.loadComponent, this);
        this.setupEditform();

        this.editActions = {};
    },
    setupEditform : function ()
    {
       this.editDialog = new Vps.Component.PageEdit({
            width: 400,
            height: 400,
            controllerUrl: '/admin/component/pageEdit'
        });
        this.editDialog.on('datachange', function(test) {
            this.treePanel.tree.root.reload();
        }, this);
    },

    onTreePanelLoaded : function(tree)
    {
        this.contextMenu = new Ext.menu.Menu({
             items: [
                '-',
                this.getAction('properties'),
                this.getAction('add'),
                this.getAction('delete'),
                this.getAction('visible'),
                this.getAction('makeHome'),
                this.getAction('preview'),
                '-',
                this.getAction('expand'),
                this.getAction('collapse')
            ]
        });

        tree.on('click', this.treeSelectionchange, this);
        tree.on('contextmenu', function (node) {
            node.select();
            this.treeSelectionchange(node);
            this.contextMenu.show(node.ui.getAnchor());
        }, this);

        tree.on('dblclick', function (o, e) {
        	if (o.attributes.allowed) {
				var action;
	            for (var i in this.editActions) {
	                if (!this.editActions[i].isHidden()) {
	                    action = this.editActions[i];
	                }
	            }
				if (action) {
					action.execute(action.initialConfig);
				}
        	}
        }, this);

    },

    treeSelectionchange : function (node) {
        if (node) {
            this.pageButton.enable();
            for (var i in this.editActions) {
                this.editActions[i].hide();
            }
            if (!node.attributes.allowed) {
            	this.pageButton.disable();
            } else {
            	this.pageButton.enable();
            }

            if (node.attributes.type != 'default' || !node.attributes.allowed) {
                this.getAction('properties').disable();
                this.getAction('delete').disable();
                this.getAction('visible').disable();
                this.getAction('makeHome').disable();
                this.getAction('add').disable();
                this.getAction('preview').disable();
            } else {
                this.getAction('properties').enable();
                this.getAction('delete').enable();
                this.getAction('visible').enable();
                this.getAction('makeHome').enable();
                this.getAction('add').enable();
                this.getAction('preview').enable();
            }
			if (node.attributes.type == 'category' && node.attributes.allowed) {
				this.getAction('add').enable();
			}
            node.attributes.data.editComponents.each(function(component) {
                if (!this.editActions[component.componentClass]) {
                    this.editActions[component.componentClass] = new Ext.Action({
                        text    : trlVps('Edit {0}', [component.componentName]),
                        handler : function (o, e) {
                            var node = this.treePanel.tree.getSelectionModel().getSelectedNode();
                            node.attributes.data.editComponents.each(function(component) {
                                if (component.componentClass == o.componentClass) {
                                    this.fireEvent('editcomponent', {
                                        id: component.dbId,
                                        cls: component.componentClass,
                                        text: node.text + ' - ' + component.componentName
                                    });
                                    return false;
                                }
                            }, this);
                        },
                        icon    : component.componentIcon,
                        cls     : 'x-btn-text-icon',
                        scope   : this,
                        disabled : !node.attributes.allowed,
                        componentClass: component.componentClass
                    });
                    this.contextMenu.insert(0, new Ext.menu.Item(this.editActions[component.componentClass]));
                    this.pageButtonMenu.insert(0, new Ext.menu.Item(this.editActions[component.componentClass]));
                }
                this.editActions[component.componentClass].show();
            }, this);
        }
    },

    loadComponent: function(data)
    {
        var panel = this.contentTabPanel.getItem('page'+data.id);
        if (!panel) {
            panel = this.createComponentPanel(data);
            this.contentTabPanel.add(panel);
        }
        this.contentTabPanel.setActiveTab(panel);

        panel.applyBaseParams({
            id: data.id
        });
        panel.load({
            componentClass: data.cls
        });
    },

    createComponentPanel: function(data)
    {
        var panel = new Vps.Component.ComponentPanel({
            id          : 'page'+data.id,
            title       : data.text,
            closable    : true,
            autoLoad    : false,
            componentEditUrl : this.componentEditUrl
        });
        return panel;
    },

    getAction : function(type)
    {
        if (this.actions[type]) return this.actions[type];

        if (type == 'properties') {
            this.actions[type] = new Ext.Action({
                text    : trlVps('Properties of selected Page'),
                handler : function () {
                    this.editDialog.getAutoForm().setBaseParams({});
                    this.editDialog.showEdit(this.treePanel.tree.selModel.selNode.id);
                },
                icon    : '/assets/silkicons/page_gear.png',
                cls     : 'x-btn-text-icon',
                scope   : this
            });
        } else if (type == 'add') {
            this.actions[type] = new Ext.Action({
                text    : trlVps('Add new Subpage'),
                handler : function () {
                    this.editDialog.getAutoForm().setBaseParams({
                        parent_id: this.treePanel.tree.selModel.selNode.id,
                        domain: this.treePanel.tree.selModel.selNode.attributes.domain,
                        category: this.treePanel.tree.selModel.selNode.attributes.category
                    });
                    this.editDialog.showAdd();
                },
                icon    : '/assets/silkicons/page_add.png',
                cls     : 'x-btn-text-icon',
                scope   : this
            });
        } else if (type == 'delete') {
            this.actions[type] = new Ext.Action({
                text    : trlVps('Delete selected Page'),
                handler : function() {
                    this.treePanel.onDelete();
                },
                icon    : '/assets/silkicons/page_delete.png',
                cls     : 'x-btn-text-icon',
                scope   : this
            });
        } else if (type == 'visible') {
            this.actions[type] = new Ext.Action({
                text    : trlVps('Toggle Visibility of selected Page'),
                handler : function() {
                    this.treePanel.onVisible();
                },
                icon    : '/assets/silkicons/page_red.png',
                cls     : 'x-btn-text-icon',
                scope   : this
            });
        } else if (type == 'makeHome') {
            this.actions[type] = new Ext.Action({
                text    : trlVps('Make selected Page Homepage'),
                handler : function (o, e) {
                    Ext.Ajax.request({
                        url: '/admin/component/pages/json-make-home',
                        success: function(r) {
                            response = Ext.decode(r.responseText);
                            var oldhome = this.treePanel.tree.getNodeById(response.oldhome);
                            oldhome.attributes.visible = response.oldhomeVisible;
                            this.treePanel.setVisible(oldhome);
                            var home = this.treePanel.tree.getNodeById(response.home);
                            home.ui.iconNode.style.backgroundImage = 'url(/assets/silkicons/application_home.png)';
                        },
                        params: {id: this.treePanel.tree.getSelectionModel().getSelectedNode().id },
                        scope: this
                    });
                },
                icon    : '/assets/silkicons/application_home.png',
                cls     : 'x-btn-text-icon',
                scope   : this
            });
        } else if (type == 'expand') {
            this.actions[type] = new Ext.Action({
                text    : trlVps('Expand here'),
                handler : function () { this.treePanel.tree.getSelectionModel().getSelectedNode().expand(true); },
                icon    : '/assets/silkicons/bullet_add.png',
                cls     : 'x-btn-text-icon',
                scope   : this
            });
        } else if (type == 'collapse') {
            this.actions[type] = new Ext.Action({
                text    : trlVps('Collapse here'),
                handler : function () { this.treePanel.tree.getSelectionModel().getSelectedNode().collapse(true); },
                icon    : '/assets/silkicons/bullet_delete.png',
                cls     : 'x-btn-text-icon',
                scope   : this
            });
        } else if (type == 'preview') {
            this.actions[type] = new Ext.Action({
                text    : trlVps('Open Preview'),
                handler : function () {
                    window.open('/admin/component/pages/open-preview?page_id='+
                                this.treePanel.getSelectedId());
                },
                icon    : '/assets/silkicons/page_white_magnify.png',
                cls     : 'x-btn-text-icon',
                scope   : this
            });
        } else {
            throw 'unknown action-type: ' + type;
        }
        return this.actions[type];
    }

});
<|endoftext|>


<commit_before>function setBackToDefault(formType){
		if(formType == "pca"){
			document.getElementById("variancePercentile").value = "70.0";
		}
		else {document.getElementById("variancePercentile").value = "95.0";}
		document.getElementById("geneList").value = "none";

	}

function checkNull(text, checkName){
	if(text.value == "")	{
		scroll(0,0);
		text.focus();
		text.style.border = "2px solid red";
		alert("Please Fill in a Unique Query Name");
		return false;
	}
	if (!checkIsURLSafe(text)){

		alert("Please enter a query name without any special characters such as !@#$%^&*()+=[]\';,./{}|\":<>?");
		return false;
	}
	if (checkName == "true")
		return checkQueryName();
	else
		return true;
}

function checkIsURLSafe(textField){
	var iChars = "!@#$%^&*()+=[]\';,./{}|\":<>?";
	var text = textField.value;

	for (var i = 0; i < text.length; i++) {
		if (iChars.indexOf(text.charAt(i)) != -1)
		{
			return false;
		}
	}
	return true;
}

function clearSpecialCharacters(textField) {
	var text = textField.value;

	re = /\$|,|@|#|~|`|\%|\*|\^|\&|\(|\)|\+|\=|\[|\-|\_|\]|\[|\}|\{|\;|\:|\'|\"|\<|\>|\?|\||\\|\!|\$|\./g;
          // remove special characters like "$" and "," etc...
	text = text.replace(re, "");
	textField.value = text;
}

function spawnx(url,winw,winh, name) {

  var w = window.open(url, name,
      "screenX=0,screenY=0,status=yes,toolbar=no,menubar=no,location=no,width=" + winw + ",height=" + winh +
      ",scrollbars=yes,resizable=yes");

	//check for pop-up blocker
	if (w==null || typeof(w)=="undefined") {
		alert("You have pop-ups blocked.  Please click the highlighted link at the top of this page to view the report.  You may disable your pop-up blocker for this site to avoid doing this in the future.");
		/*
		if(document.all) {
			  document.all.popup.visible = "true";
			  document.all.popup.className = "pop";
		      document.all.popup.innerText = "You have pop-ups blocked.  Click here to view the report.";

		    } else {
			  document.getElementById('popup').visible = "true";
			  document.getElementById('popup').className= "pop";
		      document.getElementById('popup').innerHTML = "You have pop-ups blocked.  Click here to view the report.";
		}
		*/
		document.write("

You have pop-ups blocked.  Click here to view the report.");
		//scroll(0, 8000);
	} else {
		w.focus();

	}
}

function spawn(url,winw,winh) {
  var w = window.open(url, "_blank",
      "screenX=0,screenY=0,status=yes,toolbar=no,menubar=no,location=no,width=" + winw + ",height=" + winh +
      ",scrollbars=yes,resizable=yes");
}

function deleteRow(queryNum){
//get elements body and table
 var mybody=document.getElementsByTagName("body").item(0);
 var mytable=mybody.getElementsByTagName("table").item(0);

 //show warning if user has deleted all but one row
 if (mytable.rows.length == 2){
 alert('Deleting any more rows will create an invalid query');
 }
 //delete rows by finding the row id and the row's index
 else {
  var thisTR = document.getElementById(queryNum);
  var thisTRIndex = thisTR.rowIndex;
  mytable.deleteRow(thisTRIndex);
   }
 }

 function onRadio(formElement,i){

   //selected index of the selected
	var element = formElement.name;

	 if(element == "tumorType" || formElement == "tumorType"){
	    document.forms[0].tumorGrade.options.length = 1;
	        myOption1 = new Option("I","one");
		    myOption2 = new Option("II","two");
		    myOption3 = new Option("III","three");
		    myOption4 = new Option("IV","four");

		if(i == "ALL"){
		 document.forms[0].tumorGrade.options[1] = myOption1;
	     document.forms[0].tumorGrade.options[2] = myOption2;
	     document.forms[0].tumorGrade.options[3] = myOption3;
	     document.forms[0].tumorGrade.options[4] = myOption4;
	     }
	    if(i == "ASTROCYTOMA"){
	     document.forms[0].tumorGrade.options[1] = myOption2;
	     document.forms[0].tumorGrade.options[2] = myOption3;
	     }
	    if(i == "GBM"){
	     document.forms[0].tumorGrade.options[1] = myOption4;
	     }
	    if(i == "OLIG"){
	     document.forms[0].tumorGrade.options[1] = myOption2;
	     document.forms[0].tumorGrade.options[2] = myOption3;
	     }
	    if(i == "MIXED"){
	     document.forms[0].tumorGrade.options[1] = myOption1;
	     document.forms[0].tumorGrade.options[2] = myOption2;
	     document.forms[0].tumorGrade.options[3] = myOption3;
	     }
	  }

	  if(element == "isAllGenesQuery"){
	   if(i == 0){
	    document.forms[0].allGeneQuery.disabled = true;
	    checkToggle(formElement, "qrows");
	    }
	   if(i == 1){
	    document.forms[0].allGeneQuery.disabled = false;
	    checkToggle(formElement, "qrows");
	    }
	   }

	  if(element == "sampleGroup"){
	    if(i == 0){
	    document.forms[0].sampleFile.disabled = true;
	    document.forms[0].sampleList.disabled = false;
	    }
	    if(i == 1){
	    document.forms[0].sampleList.value = "";
	    document.forms[0].sampleList.disabled = true;
	    document.forms[0].sampleFile.disabled = false;
	    }
	  }

	  if(element == "plot"){
	  document.forms[0].quickSearchType.options.length = 1;

	 	document.forms[0].quickSearchType.disabled = false;
	  	document.forms[0].quickSearchName.disabled = false;
	  	document.getElementById("quickSearchName").disabled = false;
	  	document.getElementById("baselineGroupName").disabled = false;

	  	if(i==0)	{
	  		document.getElementById("baselineGroupName").disabled = true;
	  	}

	  if(i==3)	{
	  	//disable the fields since this is a sample
	  	document.forms[0].quickSearchType.disabled = true;
	  	document.getElementById("quickSearchName").value = "";
	  	document.getElementById("quickSearchName").disabled = true;
	  	document.getElementById("baselineGroupName").disabled = true;
	  	//document.forms[0].quickSearchName.disabled = true;
	  }
	  else if (i == 2){
	      myOption = new Option();
//	      myOption2 = new Option();
	      myOption.text = "Gene Keyword";
//		  myOption2.text = "SNP Probe set ID";
	      document.forms[0].quickSearchType.options[0] = myOption;
//	      document.forms[0].quickSearchType.options[1] = myOption2;
		  }
	     else /*if(i != 2)*/ {
	      myOption = new Option();
		  myOption.text = "Gene Keyword";
	      document.forms[0].quickSearchType.options[0] = myOption;
	     }
	   }

	  if(element == "geneGroup"){
	      if (i == 0){

		  document.forms[0].geneList.disabled = false;
		  document.forms[0].geneType.disabled = false;
		  document.forms[0].geneFile.disabled = true;
		  document.forms[0].geneList.focus();
		  }
	      if (i == 1) {

	      document.forms[0].geneList.value = "";
	      document.forms[0].geneList.disabled = true;
		  document.forms[0].geneFile.disabled = false;
		  document.forms[0].geneFile.focus();
	      }
	   }

	   if(element == "cloneId"){
	      if (i == 0){
	      document.forms[0].cloneListSpecify.disabled = false;
		  document.forms[0].cloneList.disabled = false;
		  document.forms[0].cloneListFile.disabled = true;
 		  document.forms[0].cloneListSpecify.focus();

		  }
	      if (i == 1) {
	      document.forms[0].cloneListSpecify.value = "";
		  document.forms[0].cloneListSpecify.disabled = true;
		  document.forms[0].cloneListFile.disabled = false;
	      //document.forms[0].cloneListFile.focus();
	      }
	   }
	   if(element == "snpId"){
	      if (i == 0){
	        document.forms[0].snpListSpecify.disabled = false;
	        document.forms[0].snpList.disabled = false;
			document.forms[0].snpListSpecify.focus();
			document.forms[0].snpListFile.value = "";
	        document.forms[0].snpListFile.disabled = true;
	      }
	      if (i == 1){
	        document.forms[0].snpListSpecify.value = "";
	        document.forms[0].snpListSpecify.disabled = true;
	        document.forms[0].snpListFile.disabled = false;
			//document.forms[0].snpListFile.focus();
	      }
	   }

  }

 function alertUser(where){

if(confirm("This will eliminate all data currently entered in the form and will not add a query"))
{
	if (where == 'menu')
		location.href='menu.do';
	if (where == 'analysisHome')
		location.href='analysisHome.do';
}

 }

function hideLoadingMessage(){
	if(document.getElementById('spnLoading') != null)
			document.getElementById('spnLoading').style.display = "none" ;
}

function checkToggle(box, id)	{
	if(box.value == 'false')
		toggleDiv(id, false);
	else
		toggleDiv(id, true);
}

function toggleDiv(id, state)	{
		if(state)
		    document.getElementById(id).style.display = "none";
		else
			document.getElementById(id).style.display = "block";
}

function preMove(test, fbox, tbox)	{

	if(test)	{
		move(fbox, tbox);
	}
	else	{
		//alert("Invalid Selection");
	}
}

function move(fbox, tbox) {

	var arrFbox = new Array();
	var arrTbox = new Array();
	var arrLookup = new Array();
	var i;
	for(i = 0; i < tbox.options.length; i++) {
		arrLookup[tbox.options[i].text] = tbox.options[i].value;
		arrTbox[i] = tbox.options[i].text;
	}
	var fLength = 0;
	var tLength = arrTbox.length;
	for(i = 0; i < fbox.options.length; i++) {
		arrLookup[fbox.options[i].text] = fbox.options[i].value;
		if (fbox.options[i].selected && fbox.options[i].value != "") {
			arrTbox[tLength] = fbox.options[i].text;
			tLength++;
		}
		else {
			arrFbox[fLength] = fbox.options[i].text;
			fLength++;
		}
	}
	//arrFbox.sort();
	//arrTbox.sort();
	fbox.length = 0;
	tbox.length = 0;
	var c;
	for(c = 0; c < arrFbox.length; c++) {
		var no = new Option();
		no.value = arrLookup[arrFbox[c]];
		no.text = arrFbox[c];
		fbox[c] = no;
	}
	for(c = 0; c < arrTbox.length; c++) {
		var no = new Option();
		no.value = arrLookup[arrTbox[c]];
		no.text = arrTbox[c];
		tbox[c] = no;
	}
}

function saveMe(tbox,fbox) {

	var strValues = "";

	//if(tbox == null || fbox == null || !tbox.length || !fbox.length){

	if(tbox == null || fbox == null || !tbox.length){
		return;
	}

	var boxLength = 0;
	if(tbox.length)	{ boxLength = tbox.length; }

	var fboxLength = 0;
	if(fbox.length) { fboxLength = fbox.length;}

	var count = 0;
	if (boxLength != 0) {

		for (i = 0; i < boxLength; i++) {
			if (count == 0) {
				strValues = tbox.options[i].value;
			}
			else {
				strValues = strValues + "," + tbox.options[i].value;
			}
			count++;
		}
	}

	var posOfAllSamples=strValues.indexOf("REST OF ALL SAMPLES")
	var posOfAllGliomas=strValues.indexOf("REST OF ALL GLIOMAS")

	if (strValues.length == 0) {
		alert("You have not made any selections");
	}
	else if (posOfAllSamples >= 0 && posOfAllGliomas >= 0) {
		alert("You cannot perform class comparison with overlapping groups.  Therefore you cannot select both 'REST OF ALL SAMPLES' AND 'REST OF ALL GLIOMAS'.  Please select one or the other.")
	}
	else {

		//alert("Here are your values you've selected:\r\n" + strValues);
		for(i=0; i < boxLength; i++)
		{
		    tbox.options[i].selected = true;

		}

	}
}

function toggleSDiv(divId,aId){

			var divId = divId;
			var aId1 = aId;

			var div = document.getElementById(divId);
			var a = document.getElementById(aId);

			if(div.className == 'divHide'){
				div.className = 'divShow';
				a.innerHTML = ' - ';
				}
			else {
				div.className = 'divHide';
				a.innerHTML = ' + ';
				}
			}

function HelpWrapper(topic)	{
	var ta = "";
	switch(topic)	{
		case  "Clinical":
			ta = "Clinical_report";
			break;
		case "clinicalPlot":
			ta = "Clinical_plot";
			break;
		case "Gene Expression Sample":
			ta = "Gene_Expression_Sample";
			break;
		case "Gene Expression Disease":
			ta = "Gene_Expression_Disease";
			break;
		case "Copy Number":
			ta = "Copy_Number_Sample";
			break;
		default:
			ta= "Clinical";
			break;
	}

	try	{
		Help.popHelp(ta);
	}
	catch(err){alert(err);}
}

<commit_msg>Added onRadioSimpleSearch() to replace part of onRadio()<commit_after>function setBackToDefault(formType){
		if(formType == "pca"){
			document.getElementById("variancePercentile").value = "70.0";
		}
		else {document.getElementById("variancePercentile").value = "95.0";}
		document.getElementById("geneList").value = "none";

	}

function checkNull(text, checkName){
	if(text.value == "")	{
		scroll(0,0);
		text.focus();
		text.style.border = "2px solid red";
		alert("Please Fill in a Unique Query Name");
		return false;
	}
	if (!checkIsURLSafe(text)){

		alert("Please enter a query name without any special characters such as !@#$%^&*()+=[]\';,./{}|\":<>?");
		return false;
	}
	if (checkName == "true")
		return checkQueryName();
	else
		return true;
}

function checkIsURLSafe(textField){
	var iChars = "!@#$%^&*()+=[]\';,./{}|\":<>?";
	var text = textField.value;

	for (var i = 0; i < text.length; i++) {
		if (iChars.indexOf(text.charAt(i)) != -1)
		{
			return false;
		}
	}
	return true;
}

function clearSpecialCharacters(textField) {
	var text = textField.value;

	re = /\$|,|@|#|~|`|\%|\*|\^|\&|\(|\)|\+|\=|\[|\-|\_|\]|\[|\}|\{|\;|\:|\'|\"|\<|\>|\?|\||\\|\!|\$|\./g;
          // remove special characters like "$" and "," etc...
	text = text.replace(re, "");
	textField.value = text;
}

function spawnx(url,winw,winh, name) {

  var w = window.open(url, name,
      "screenX=0,screenY=0,status=yes,toolbar=no,menubar=no,location=no,width=" + winw + ",height=" + winh +
      ",scrollbars=yes,resizable=yes");

	//check for pop-up blocker
	if (w==null || typeof(w)=="undefined") {
		alert("You have pop-ups blocked.  Please click the highlighted link at the top of this page to view the report.  You may disable your pop-up blocker for this site to avoid doing this in the future.");
		/*
		if(document.all) {
			  document.all.popup.visible = "true";
			  document.all.popup.className = "pop";
		      document.all.popup.innerText = "You have pop-ups blocked.  Click here to view the report.";

		    } else {
			  document.getElementById('popup').visible = "true";
			  document.getElementById('popup').className= "pop";
		      document.getElementById('popup').innerHTML = "You have pop-ups blocked.  Click here to view the report.";
		}
		*/
		document.write("

You have pop-ups blocked.  Click here to view the report.");
		//scroll(0, 8000);
	} else {
		w.focus();

	}
}

function spawn(url,winw,winh) {
  var w = window.open(url, "_blank",
      "screenX=0,screenY=0,status=yes,toolbar=no,menubar=no,location=no,width=" + winw + ",height=" + winh +
      ",scrollbars=yes,resizable=yes");
}

function deleteRow(queryNum){
//get elements body and table
 var mybody=document.getElementsByTagName("body").item(0);
 var mytable=mybody.getElementsByTagName("table").item(0);

 //show warning if user has deleted all but one row
 if (mytable.rows.length == 2){
 alert('Deleting any more rows will create an invalid query');
 }
 //delete rows by finding the row id and the row's index
 else {
  var thisTR = document.getElementById(queryNum);
  var thisTRIndex = thisTR.rowIndex;
  mytable.deleteRow(thisTRIndex);
   }
 }

 function onRadioSimpleSearch(id) {

	 if (id == "geneExpPlot" || id == "samplePlotRadio")	{
	  		document.getElementById("baselineGroupName").disabled = true;

	 } else if (id == "kapMaiPlotGE" || id == "kapMaiPlotCN")	{

		 document.getElementById("baselineGroupName").disabled = false;

	 }
 }

 function onRadio(formElement,i){

   //selected index of the selected
	var element = formElement.name;

	 if(element == "tumorType" || formElement == "tumorType"){
	    document.forms[0].tumorGrade.options.length = 1;
	        myOption1 = new Option("I","one");
		    myOption2 = new Option("II","two");
		    myOption3 = new Option("III","three");
		    myOption4 = new Option("IV","four");

		if(i == "ALL"){
		 document.forms[0].tumorGrade.options[1] = myOption1;
	     document.forms[0].tumorGrade.options[2] = myOption2;
	     document.forms[0].tumorGrade.options[3] = myOption3;
	     document.forms[0].tumorGrade.options[4] = myOption4;
	     }
	    if(i == "ASTROCYTOMA"){
	     document.forms[0].tumorGrade.options[1] = myOption2;
	     document.forms[0].tumorGrade.options[2] = myOption3;
	     }
	    if(i == "GBM"){
	     document.forms[0].tumorGrade.options[1] = myOption4;
	     }
	    if(i == "OLIG"){
	     document.forms[0].tumorGrade.options[1] = myOption2;
	     document.forms[0].tumorGrade.options[2] = myOption3;
	     }
	    if(i == "MIXED"){
	     document.forms[0].tumorGrade.options[1] = myOption1;
	     document.forms[0].tumorGrade.options[2] = myOption2;
	     document.forms[0].tumorGrade.options[3] = myOption3;
	     }
	  }

	  if(element == "isAllGenesQuery"){
	   if(i == 0){
	    document.forms[0].allGeneQuery.disabled = true;
	    checkToggle(formElement, "qrows");
	    }
	   if(i == 1){
	    document.forms[0].allGeneQuery.disabled = false;
	    checkToggle(formElement, "qrows");
	    }
	   }

	  if(element == "sampleGroup"){
	    if(i == 0){
	    document.forms[0].sampleFile.disabled = true;
	    document.forms[0].sampleList.disabled = false;
	    }
	    if(i == 1){
	    document.forms[0].sampleList.value = "";
	    document.forms[0].sampleList.disabled = true;
	    document.forms[0].sampleFile.disabled = false;
	    }
	  }

	  if(element == "geneGroup"){
	      if (i == 0){

		  document.forms[0].geneList.disabled = false;
		  document.forms[0].geneType.disabled = false;
		  document.forms[0].geneFile.disabled = true;
		  document.forms[0].geneList.focus();
		  }
	      if (i == 1) {

	      document.forms[0].geneList.value = "";
	      document.forms[0].geneList.disabled = true;
		  document.forms[0].geneFile.disabled = false;
		  document.forms[0].geneFile.focus();
	      }
	   }

	   if(element == "cloneId"){
	      if (i == 0){
	      document.forms[0].cloneListSpecify.disabled = false;
		  document.forms[0].cloneList.disabled = false;
		  document.forms[0].cloneListFile.disabled = true;
 		  document.forms[0].cloneListSpecify.focus();

		  }
	      if (i == 1) {
	      document.forms[0].cloneListSpecify.value = "";
		  document.forms[0].cloneListSpecify.disabled = true;
		  document.forms[0].cloneListFile.disabled = false;
	      //document.forms[0].cloneListFile.focus();
	      }
	   }
	   if(element == "snpId"){
	      if (i == 0){
	        document.forms[0].snpListSpecify.disabled = false;
	        document.forms[0].snpList.disabled = false;
			document.forms[0].snpListSpecify.focus();
			document.forms[0].snpListFile.value = "";
	        document.forms[0].snpListFile.disabled = true;
	      }
	      if (i == 1){
	        document.forms[0].snpListSpecify.value = "";
	        document.forms[0].snpListSpecify.disabled = true;
	        document.forms[0].snpListFile.disabled = false;
			//document.forms[0].snpListFile.focus();
	      }
	   }

  }

 function alertUser(where){

if(confirm("This will eliminate all data currently entered in the form and will not add a query"))
{
	if (where == 'menu')
		location.href='menu.do';
	if (where == 'analysisHome')
		location.href='analysisHome.do';
}

 }

function hideLoadingMessage(){
	if(document.getElementById('spnLoading') != null)
			document.getElementById('spnLoading').style.display = "none" ;
}

function checkToggle(box, id)	{
	if(box.value == 'false')
		toggleDiv(id, false);
	else
		toggleDiv(id, true);
}

function toggleDiv(id, state)	{
		if(state)
		    document.getElementById(id).style.display = "none";
		else
			document.getElementById(id).style.display = "block";
}

function preMove(test, fbox, tbox)	{

	if(test)	{
		move(fbox, tbox);
	}
	else	{
		//alert("Invalid Selection");
	}
}

function move(fbox, tbox) {

	var arrFbox = new Array();
	var arrTbox = new Array();
	var arrLookup = new Array();
	var i;
	for(i = 0; i < tbox.options.length; i++) {
		arrLookup[tbox.options[i].text] = tbox.options[i].value;
		arrTbox[i] = tbox.options[i].text;
	}
	var fLength = 0;
	var tLength = arrTbox.length;
	for(i = 0; i < fbox.options.length; i++) {
		arrLookup[fbox.options[i].text] = fbox.options[i].value;
		if (fbox.options[i].selected && fbox.options[i].value != "") {
			arrTbox[tLength] = fbox.options[i].text;
			tLength++;
		}
		else {
			arrFbox[fLength] = fbox.options[i].text;
			fLength++;
		}
	}
	//arrFbox.sort();
	//arrTbox.sort();
	fbox.length = 0;
	tbox.length = 0;
	var c;
	for(c = 0; c < arrFbox.length; c++) {
		var no = new Option();
		no.value = arrLookup[arrFbox[c]];
		no.text = arrFbox[c];
		fbox[c] = no;
	}
	for(c = 0; c < arrTbox.length; c++) {
		var no = new Option();
		no.value = arrLookup[arrTbox[c]];
		no.text = arrTbox[c];
		tbox[c] = no;
	}
}

function saveMe(tbox,fbox) {

	var strValues = "";

	//if(tbox == null || fbox == null || !tbox.length || !fbox.length){

	if(tbox == null || fbox == null || !tbox.length){
		return;
	}

	var boxLength = 0;
	if(tbox.length)	{ boxLength = tbox.length; }

	var fboxLength = 0;
	if(fbox.length) { fboxLength = fbox.length;}

	var count = 0;
	if (boxLength != 0) {

		for (i = 0; i < boxLength; i++) {
			if (count == 0) {
				strValues = tbox.options[i].value;
			}
			else {
				strValues = strValues + "," + tbox.options[i].value;
			}
			count++;
		}
	}

	var posOfAllSamples=strValues.indexOf("REST OF ALL SAMPLES")
	var posOfAllGliomas=strValues.indexOf("REST OF ALL GLIOMAS")

	if (strValues.length == 0) {
		alert("You have not made any selections");
	}
	else if (posOfAllSamples >= 0 && posOfAllGliomas >= 0) {
		alert("You cannot perform class comparison with overlapping groups.  Therefore you cannot select both 'REST OF ALL SAMPLES' AND 'REST OF ALL GLIOMAS'.  Please select one or the other.")
	}
	else {

		//alert("Here are your values you've selected:\r\n" + strValues);
		for(i=0; i < boxLength; i++)
		{
		    tbox.options[i].selected = true;

		}

	}
}

function toggleSDiv(divId,aId){

			var divId = divId;
			var aId1 = aId;

			var div = document.getElementById(divId);
			var a = document.getElementById(aId);

			if(div.className == 'divHide'){
				div.className = 'divShow';
				a.innerHTML = ' - ';
				}
			else {
				div.className = 'divHide';
				a.innerHTML = ' + ';
				}
			}

function HelpWrapper(topic)	{
	var ta = "";
	switch(topic)	{
		case  "Clinical":
			ta = "Clinical_report";
			break;
		case "clinicalPlot":
			ta = "Clinical_plot";
			break;
		case "Gene Expression Sample":
			ta = "Gene_Expression_Sample";
			break;
		case "Gene Expression Disease":
			ta = "Gene_Expression_Disease";
			break;
		case "Copy Number":
			ta = "Copy_Number_Sample";
			break;
		default:
			ta= "Clinical";
			break;
	}

	try	{
		Help.popHelp(ta);
	}
	catch(err){alert(err);}
}

<|endoftext|>


<commit_before>const DEFAULT_PORT = 3000

const debug = require('debug')
// const warn = debug('SYSTEM:warn')
const info = debug('SYSTEM:info')
const error = debug('SYSTEM:error')

export default class App {

    app = null
    httpServer = null

    constructor() {
        // 实例化1个 Koa 对象
        this.app = ((Koa) => new Koa())(require('koa'))
    }

    instance() {
        return this.app
    }

    run(port = DEFAULT_PORT) {

        const http = require('http')
        const server = this.httpServer = http.createServer(this.app.callback())

        // http 服务监听

        server.on('error', onError)
        server.on('listening', onListening)

        function onError(err) {

            if (err.syscall !== 'listen') {
                throw err
            }

            // handle specific listen errors with friendly messages
            switch (err.code) {
                case 'EACCES':
                    error(port + ' requires elevated privileges !!!')
                    process.exit(1)
                    break
                case 'EADDRINUSE':
                    error(port + ' is already in use !!!')
                    process.exit(1)
                    break
                default:
                    throw err
            }
        }

        function onListening() {
            info(`SYSTEM listening on ${port} √ `)
        }

        server.listen(port)
    }
}
<commit_msg>mark todo<commit_after>const DEFAULT_PORT = 3000

const debug = require('debug')
// const warn = debug('SYSTEM:warn')
const info = debug('SYSTEM:info')
const error = debug('SYSTEM:error')

export default class App {

    app = null
    httpServer = null

    constructor() {
        // 实例化1个 Koa 对象
        this.app = ((Koa) => new Koa())(require('koa'))
    }

    instance() {
        return this.app
    }

    run(port = DEFAULT_PORT) {

        const http = require('http')
        const server = this.httpServer = http.createServer(this.app.callback())

        // http 服务监听

        server.on('error', onError)
        server.on('listening', onListening)

        function onError(err) {

            if (err.syscall !== 'listen') {
                throw err
            }

            // handle specific listen errors with friendly messages
            switch (err.code) {
                case 'EACCES':
                    error(port + ' requires elevated privileges !!!')
                    process.exit(1)
                    break
                case 'EADDRINUSE':
                    error(port + ' is already in use !!!')
                    process.exit(1)
                    break
                default:
                    throw err
            }
        }

        function onListening() {
            info(`SYSTEM listening on ${port} √ `)
        }

        server.listen(port)
    }
}

/*
const createApp = () => {}
const createServer = () => {}
const run = (port) => {
    const app = createApp()
    const server = createServer(app)
    server.listen(port)
}
 */<|endoftext|>


<commit_before>/** This is a cookie handling library from: http://code.google.com/p/cookies/wiki/License **/
(function(global){"use strict";var document=global.document,Object=global.Object,JSON=global.JSON,jaaulde=global.jaaulde=(global.jaaulde||{});jaaulde.utils=jaaulde.utils||{};jaaulde.utils.cookies=(function(){var defaultOptions,resolveOptions,assembleOptionsString,isNaN,trim,parseCookies,Constructor;defaultOptions={expiresAt:null,path:'/',domain:null,secure:false};resolveOptions=function(options){var returnValue,expireDate;if(typeof options!=='object'||options===null){returnValue=defaultOptions}else{returnValue={expiresAt:defaultOptions.expiresAt,path:defaultOptions.path,domain:defaultOptions.domain,secure:defaultOptions.secure};if(typeof options.expiresAt==='object'&&options.expiresAt instanceof Date){returnValue.expiresAt=options.expiresAt}else if(typeof options.hoursToLive==='number'&&options.hoursToLive!==0){expireDate=new global.Date();expireDate.setTime(expireDate.getTime()+(options.hoursToLive*60*60*1000));returnValue.expiresAt=expireDate}if(typeof options.path==='string'&&options.path!==''){returnValue.path=options.path}if(typeof options.domain==='string'&&options.domain!==''){returnValue.domain=options.domain}if(options.secure===true){returnValue.secure=options.secure}}return returnValue};assembleOptionsString=function(options){options=resolveOptions(options);return((typeof options.expiresAt==='object'&&options.expiresAt instanceof Date?'; expires='+options.expiresAt.toGMTString():'')+'; path='+options.path+(typeof options.domain==='string'?'; domain='+options.domain:'')+(options.secure===true?'; secure':''))};trim=global.String.prototype.trim?function(data){return global.String.prototype.trim.call(data)}:(function(){var trimLeft,trimRight;trimLeft=/^\s+/;trimRight=/\s+$/;return function(data){return data.replace(trimLeft,'').replace(trimRight,'')}}());isNaN=(function(){var rdigit=/\d/,isNaN=global.isNaN;return function(obj){return(obj===null||!rdigit.test(obj)||isNaN(obj))}}());parseCookies=(function(){var parseJSON,rbrace;parseJSON=JSON&&JSON.parse?function(data){var returnValue=null;if(typeof data==='string'&&data!==''){data=trim(data);if(data!==''){try{returnValue=JSON.parse(data)}catch(e1){returnValue=null}}}return returnValue}:function(){return null};rbrace=/^(?:\{.*\}|\[.*\])$/;return function(){var cookies,splitOnSemiColons,cookieCount,i,splitOnEquals,name,rawValue,value;cookies={};splitOnSemiColons=document.cookie.split(';');cookieCount=splitOnSemiColons.length;for(i=0;i<cookieCount;i=i+1){splitOnEquals=splitOnSemiColons[i].split('=');name=trim(splitOnEquals.shift());if(splitOnEquals.length>=1){rawValue=splitOnEquals.join('=')}else{rawValue=''}try{value=decodeURIComponent(rawValue)}catch(e2){value=rawValue}try{value=value==='true'?true:value==='false'?false:!isNaN(value)?parseFloat(value):rbrace.test(value)?parseJSON(value):value}catch(e3){}cookies[name]=value}return cookies}}());Constructor=function(){};Constructor.prototype.get=function(cookieName){var returnValue,item,cookies;cookies=parseCookies();if(typeof cookieName==='string'){returnValue=(typeof cookies[cookieName]!=='undefined')?cookies[cookieName]:null}else if(typeof cookieName==='object'&&cookieName!==null){returnValue={};for(item in cookieName){if(Object.prototype.hasOwnProperty.call(cookieName,item)){if(typeof cookies[cookieName[item]]!=='undefined'){returnValue[cookieName[item]]=cookies[cookieName[item]]}else{returnValue[cookieName[item]]=null}}}}else{returnValue=cookies}return returnValue};Constructor.prototype.filter=function(cookieNameRegExp){var cookieName,returnValue,cookies;returnValue={};cookies=parseCookies();if(typeof cookieNameRegExp==='string'){cookieNameRegExp=new RegExp(cookieNameRegExp)}for(cookieName in cookies){if(Object.prototype.hasOwnProperty.call(cookies,cookieName)&&cookieName.match(cookieNameRegExp)){returnValue[cookieName]=cookies[cookieName]}}return returnValue};Constructor.prototype.set=function(cookieName,value,options){if(typeof options!=='object'||options===null){options={}}if(typeof value==='undefined'||value===null){value='';options.hoursToLive=-8760}else{value=value===true?'true':value===false?'false':!isNaN(value)?''+value:value;if(typeof value!=='string'){if(typeof JSON==='object'&&JSON!==null&&typeof JSON.stringify==='function'){value=JSON.stringify(value)}else{throw new Error('cookies.set() received value which could not be serialized.');}}}var optionsString=assembleOptionsString(options);document.cookie=cookieName+'='+encodeURIComponent(value)+optionsString};Constructor.prototype.del=function(cookieName,options){var allCookies,name;allCookies={};if(typeof options!=='object'||options===null){options={}}if(typeof cookieName==='boolean'&&cookieName===true){allCookies=this.get()}else if(typeof cookieName==='string'){allCookies[cookieName]=true}for(name in allCookies){if(Object.prototype.hasOwnProperty.call(allCookies,name)&&typeof name==='string'&&name!==''){this.set(name,null,options)}}};Constructor.prototype.test=function(){var returnValue,testName,testValue;testName='cookiesCT';testValue='data';this.set(testName,testValue);if(this.get(testName)===testValue){this.del(testName);returnValue=true}return returnValue};Constructor.prototype.setOptions=function(options){if(typeof options!=='object'){options=null}defaultOptions=resolveOptions(options)};return new Constructor()}())}(window));

function t2w() {
  jaaulde.utils.cookies.set('disclaimer_accepted', 'true');
  location.reload();
}

function getHTTPObject() {
  var http = false;
  if (XMLHttpRequest) {
    try {http = new XMLHttpRequest();}
    catch (e) {http = false;}
  } else if(typeof ActiveXObject != 'undefined') {
    try {http = new ActiveXObject("Msxml2.tplHTTP");}
    catch (e) {
      try {http = new ActiveXObject("Microsoft.tplHTTP");}
      catch (E) {http = false;}
    }
  }
  return http;
}

function handler() {
  if(http.readyState == 4 && http.status == 200) {
    show_hide_notification_form()
  }
}

function sendNotification() {
  var by = document.getElementById('by').value;
  var url = document.getElementById('url').value;
  var comment = document.getElementById('comment').value;
  var params = "by="+by+"&url="+url+"&comment="+comment;

  http.open("POST", "/antanistaticmap/notification", true);

  http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

  http.onreadystatechange = handler;

  http.send(params);
}

function show_hide_tor2web_header(status) {
  if(status == true) {
    document.getElementById("tor2web-visible").style.display = 'none';
    document.getElementById("tor2web-hidden").style.display = 'block';
    jaaulde.utils.cookies.set('tor2web_header_hidden', 'true');
  } else {
    document.getElementById("tor2web-hidden").style.display = 'none';
    document.getElementById("tor2web-visible").style.display = 'block';
    jaaulde.utils.cookies.set('tor2web_header_hidden', 'false');
  }
}

function show_hide_notification_form() {
  if(tor2web_notification_form_visible == true) {
    tor2web_notification_form_visible = false;
    document.getElementById("tor2web_notification_form").style.display = 'block';
  } else {
    tor2web_notification_form_visible = true;
    document.getElementById("tor2web_notification_form").style.display = 'none';
  }
}

var tor2web_notification_form_visible = true;
var http = getHTTPObject();

var banner = '' +
'' +
'
' +
'
' +
'
' +
'      ' +
'
' +
'
' +
'
tor2web.org does not host this content; the service is simply a proxy connecting Internet users to content hosted inside the Tor network.
' +
'
Please be aware that when you access this site through a Tor2web proxy you are not anonymous. To obtain anonymity, you are strongly advised to download the Tor Browser Bundle and access this content over Tor.
' +
'
Please send us your feedback and if you have concerns with this content, send us an abuse notice.
' +
'
<t:transparent t:render="mirror" />
' +
'
' +
'
' +
'      <fieldset>' +
'        <legend>Notification:</legend>' +
'        BY:' +
'
<input type="text" id="by" name="by" />
' +
'        URL:' +
'
<input type="text" id="url" name="url" readonly="readonly" />
' +
'        COMMENT:' +
'
<textarea type="text" id="comment" name="comment" rows="10" cols="20"></textarea>
' +
'
<input type="button" value="Send" onclick="sendNotification()" />
' +
'      </fieldset>' +
'
' +
'

' +
'
' +
'      hide Tor2web header' +
'
' +
'
' +
'
' +
'
' +
'      show Tor2web header' +
'
' +
'
' +
'
';

window.onload = function() {
  if(document.getElementById('tor2web') != null) {

    document.getElementById('url').value = document.location;

  } else {

    document.body.innerHTML = banner + "
" + document.body.innerHTML + "
";

    if(jaaulde.utils.cookies.get('tor2web_header_hidden') && jaaulde.utils.cookies.get('tor2web_header_hidden') == true) {
      show_hide_tor2web_header(true);
    }

  }
}
<commit_msg>fixed header injection twice bug<commit_after>/** This is a cookie handling library from: http://code.google.com/p/cookies/wiki/License **/
(function(global){"use strict";var document=global.document,Object=global.Object,JSON=global.JSON,jaaulde=global.jaaulde=(global.jaaulde||{});jaaulde.utils=jaaulde.utils||{};jaaulde.utils.cookies=(function(){var defaultOptions,resolveOptions,assembleOptionsString,isNaN,trim,parseCookies,Constructor;defaultOptions={expiresAt:null,path:'/',domain:null,secure:false};resolveOptions=function(options){var returnValue,expireDate;if(typeof options!=='object'||options===null){returnValue=defaultOptions}else{returnValue={expiresAt:defaultOptions.expiresAt,path:defaultOptions.path,domain:defaultOptions.domain,secure:defaultOptions.secure};if(typeof options.expiresAt==='object'&&options.expiresAt instanceof Date){returnValue.expiresAt=options.expiresAt}else if(typeof options.hoursToLive==='number'&&options.hoursToLive!==0){expireDate=new global.Date();expireDate.setTime(expireDate.getTime()+(options.hoursToLive*60*60*1000));returnValue.expiresAt=expireDate}if(typeof options.path==='string'&&options.path!==''){returnValue.path=options.path}if(typeof options.domain==='string'&&options.domain!==''){returnValue.domain=options.domain}if(options.secure===true){returnValue.secure=options.secure}}return returnValue};assembleOptionsString=function(options){options=resolveOptions(options);return((typeof options.expiresAt==='object'&&options.expiresAt instanceof Date?'; expires='+options.expiresAt.toGMTString():'')+'; path='+options.path+(typeof options.domain==='string'?'; domain='+options.domain:'')+(options.secure===true?'; secure':''))};trim=global.String.prototype.trim?function(data){return global.String.prototype.trim.call(data)}:(function(){var trimLeft,trimRight;trimLeft=/^\s+/;trimRight=/\s+$/;return function(data){return data.replace(trimLeft,'').replace(trimRight,'')}}());isNaN=(function(){var rdigit=/\d/,isNaN=global.isNaN;return function(obj){return(obj===null||!rdigit.test(obj)||isNaN(obj))}}());parseCookies=(function(){var parseJSON,rbrace;parseJSON=JSON&&JSON.parse?function(data){var returnValue=null;if(typeof data==='string'&&data!==''){data=trim(data);if(data!==''){try{returnValue=JSON.parse(data)}catch(e1){returnValue=null}}}return returnValue}:function(){return null};rbrace=/^(?:\{.*\}|\[.*\])$/;return function(){var cookies,splitOnSemiColons,cookieCount,i,splitOnEquals,name,rawValue,value;cookies={};splitOnSemiColons=document.cookie.split(';');cookieCount=splitOnSemiColons.length;for(i=0;i<cookieCount;i=i+1){splitOnEquals=splitOnSemiColons[i].split('=');name=trim(splitOnEquals.shift());if(splitOnEquals.length>=1){rawValue=splitOnEquals.join('=')}else{rawValue=''}try{value=decodeURIComponent(rawValue)}catch(e2){value=rawValue}try{value=value==='true'?true:value==='false'?false:!isNaN(value)?parseFloat(value):rbrace.test(value)?parseJSON(value):value}catch(e3){}cookies[name]=value}return cookies}}());Constructor=function(){};Constructor.prototype.get=function(cookieName){var returnValue,item,cookies;cookies=parseCookies();if(typeof cookieName==='string'){returnValue=(typeof cookies[cookieName]!=='undefined')?cookies[cookieName]:null}else if(typeof cookieName==='object'&&cookieName!==null){returnValue={};for(item in cookieName){if(Object.prototype.hasOwnProperty.call(cookieName,item)){if(typeof cookies[cookieName[item]]!=='undefined'){returnValue[cookieName[item]]=cookies[cookieName[item]]}else{returnValue[cookieName[item]]=null}}}}else{returnValue=cookies}return returnValue};Constructor.prototype.filter=function(cookieNameRegExp){var cookieName,returnValue,cookies;returnValue={};cookies=parseCookies();if(typeof cookieNameRegExp==='string'){cookieNameRegExp=new RegExp(cookieNameRegExp)}for(cookieName in cookies){if(Object.prototype.hasOwnProperty.call(cookies,cookieName)&&cookieName.match(cookieNameRegExp)){returnValue[cookieName]=cookies[cookieName]}}return returnValue};Constructor.prototype.set=function(cookieName,value,options){if(typeof options!=='object'||options===null){options={}}if(typeof value==='undefined'||value===null){value='';options.hoursToLive=-8760}else{value=value===true?'true':value===false?'false':!isNaN(value)?''+value:value;if(typeof value!=='string'){if(typeof JSON==='object'&&JSON!==null&&typeof JSON.stringify==='function'){value=JSON.stringify(value)}else{throw new Error('cookies.set() received value which could not be serialized.');}}}var optionsString=assembleOptionsString(options);document.cookie=cookieName+'='+encodeURIComponent(value)+optionsString};Constructor.prototype.del=function(cookieName,options){var allCookies,name;allCookies={};if(typeof options!=='object'||options===null){options={}}if(typeof cookieName==='boolean'&&cookieName===true){allCookies=this.get()}else if(typeof cookieName==='string'){allCookies[cookieName]=true}for(name in allCookies){if(Object.prototype.hasOwnProperty.call(allCookies,name)&&typeof name==='string'&&name!==''){this.set(name,null,options)}}};Constructor.prototype.test=function(){var returnValue,testName,testValue;testName='cookiesCT';testValue='data';this.set(testName,testValue);if(this.get(testName)===testValue){this.del(testName);returnValue=true}return returnValue};Constructor.prototype.setOptions=function(options){if(typeof options!=='object'){options=null}defaultOptions=resolveOptions(options)};return new Constructor()}())}(window));

function t2w() {
  jaaulde.utils.cookies.set('disclaimer_accepted', 'true');
  location.reload();
}

function getHTTPObject() {
  var http = false;
  if (XMLHttpRequest) {
    try {http = new XMLHttpRequest();}
    catch (e) {http = false;}
  } else if(typeof ActiveXObject != 'undefined') {
    try {http = new ActiveXObject("Msxml2.tplHTTP");}
    catch (e) {
      try {http = new ActiveXObject("Microsoft.tplHTTP");}
      catch (E) {http = false;}
    }
  }
  return http;
}

function handler() {
  if(http.readyState == 4 && http.status == 200) {
    show_hide_notification_form()
  }
}

function sendNotification() {
  var by = document.getElementById('by').value;
  var url = document.getElementById('url').value;
  var comment = document.getElementById('comment').value;
  var params = "by="+by+"&url="+url+"&comment="+comment;

  http.open("POST", "/antanistaticmap/notification", true);

  http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

  http.onreadystatechange = handler;

  http.send(params);
}

function show_hide_tor2web_header(status) {
  if(status == true) {
    document.getElementById("tor2web-visible").style.display = 'none';
    document.getElementById("tor2web-hidden").style.display = 'block';
    jaaulde.utils.cookies.set('tor2web_header_hidden', 'true');
  } else {
    document.getElementById("tor2web-hidden").style.display = 'none';
    document.getElementById("tor2web-visible").style.display = 'block';
    jaaulde.utils.cookies.set('tor2web_header_hidden', 'false');
  }
}

function show_hide_notification_form() {
  if(tor2web_notification_form_visible == true) {
    tor2web_notification_form_visible = false;
    document.getElementById("tor2web_notification_form").style.display = 'block';
  } else {
    tor2web_notification_form_visible = true;
    document.getElementById("tor2web_notification_form").style.display = 'none';
  }
}

var tor2web_notification_form_visible = true;
var http = getHTTPObject();

window.onload = function() {
  if(document.getElementById('tor2web') != null) {

    document.getElementById('url').value = document.location;

  } else {

    if(jaaulde.utils.cookies.get('tor2web_header_hidden') && jaaulde.utils.cookies.get('tor2web_header_hidden') == true) {
      show_hide_tor2web_header(true);
    }

  }
}
<|endoftext|>


<commit_before>let aDefault = {
    'ho-oh': 'hooh',
    'bounty': 'porygonz-shiny',
    'tech': 'vileplume',
    'lectro': 'noivern',
    'ngb': 'ampharos',
    'amph': 'ampharos-mega',
    'fable': 'flygon-shiny',
    'thane': 'absol',
    'semper': 'flygon',
    'monk': 'weavile',
    'baru': 'arcanine',
    'ace': 'suicune',
    'quote': 'sableye',
    'stall': 'sableye-mega',
    'surv': 'zorua-shiny',
    'josh': 'staraptor',
    'luc': 'lucario',
    'flare': 'flareon',
    'fluffy': 'leafeon',
    'fug': 'rayquaza',
    'sol': 'solrock',
    'cell': 'gengar',
    'dom': 'charizard',
    'hiccup': 'spinda',
    'runtime': 'lapras',
    'curtis': 'reuniclus',
    'type: null': 'typenull',
    'type null': 'typenull',
    'mr. mime': 'mrmime',
    'mr mime': 'mrmime',
    'mime jr.': 'mimejr',
    'mime jr': 'mimejr',
    'tapu koko': 'tapukoko',
    'tapu lele': 'tapulele',
    'tapu bulu': 'tapubulu',
    'tapu fini': 'tapufini'
}

let custom = {
    'matt': 'meowstic',
    'erebus': 'meowstic',
    'blue': 'popplio',
    'emily': 'luxio',
    'hound': 'houndoom',
    'zytom': 'lurantis',
    'jenn': 'bellossom',
    'skul': 'totodile',
    'orn': 'decidueye-shiny',
    'jordan': 'dewott',
    'mene': 'cosmog',
    'minty': 'archeops',
    'sapph': 'glaceon',
    'swed': 'vaporeon',
    'pally': 'lilligant',
    'thirst': 'lilligant'
}

exports.aliases = (id) => {
    let toReturn = aDefault;
    if (id != 111504456838819840) toReturn = Object.assign(aDefault, custom);
    console.log(`111504456838819840\n${id}`);
    return toReturn;
}<commit_msg>please please please<commit_after>let aDefault = {
    'ho-oh': 'hooh',
    'bounty': 'porygonz-shiny',
    'tech': 'vileplume',
    'lectro': 'noivern',
    'ngb': 'ampharos',
    'amph': 'ampharos-mega',
    'fable': 'flygon-shiny',
    'thane': 'absol',
    'semper': 'flygon',
    'monk': 'weavile',
    'baru': 'arcanine',
    'ace': 'suicune',
    'quote': 'sableye',
    'stall': 'sableye-mega',
    'surv': 'zorua-shiny',
    'josh': 'staraptor',
    'luc': 'lucario',
    'flare': 'flareon',
    'fluffy': 'leafeon',
    'fug': 'rayquaza',
    'sol': 'solrock',
    'cell': 'gengar',
    'dom': 'charizard',
    'hiccup': 'spinda',
    'runtime': 'lapras',
    'curtis': 'reuniclus',
    'type: null': 'typenull',
    'type null': 'typenull',
    'mr. mime': 'mrmime',
    'mr mime': 'mrmime',
    'mime jr.': 'mimejr',
    'mime jr': 'mimejr',
    'tapu koko': 'tapukoko',
    'tapu lele': 'tapulele',
    'tapu bulu': 'tapubulu',
    'tapu fini': 'tapufini'
}

let custom = {
    'matt': 'meowstic',
    'erebus': 'meowstic',
    'blue': 'popplio',
    'emily': 'luxio',
    'hound': 'houndoom',
    'zytom': 'lurantis',
    'jenn': 'bellossom',
    'skul': 'totodile',
    'orn': 'decidueye-shiny',
    'jordan': 'dewott',
    'mene': 'cosmog',
    'minty': 'archeops',
    'sapph': 'glaceon',
    'swed': 'vaporeon',
    'pally': 'lilligant',
    'thirst': 'lilligant'
}

exports.aliases = (id) => {
    if (id == 111504456838819840) {
        return toReturn;
    } else {
        return Object.assign(aDefault, custom);
    }
}<|endoftext|>


<commit_before>

define(function (require) {
	l10n = require("webL10n");
    FoodChain.activity = require("sugar-web/activity/activity");
	var radioButtonsGroup = require("sugar-web/graphics/radiobuttonsgroup");
    var datastore = require("sugar-web/datastore");
	var app = null;

    // Manipulate the DOM only when it is ready.
    require(['domReady!'], function (doc) {
		// Initialize the activity
		FoodChain.activity.setup();

		// Initialize buttons
		var languageRadio = new radioButtonsGroup.RadioButtonsGroup([
			document.getElementById("en-button"),
			document.getElementById("fr-button")]
		);
		document.getElementById("en-button").onclick = function() {
			l10n.language.code = "en";
			FoodChain.setLocale();
		};
		document.getElementById("fr-button").onclick = function() {
			l10n.language.code = "fr";
			FoodChain.setLocale();
		};

		// Wait for locale load
		window.addEventListener('localized', function() {
			// Init activity
			if (app == null) {
				// Init sound component
				FoodChain.sound = new FoodChain.Audio();
				FoodChain.sound.renderInto(document.getElementById("header"));

				// Create and display first screen
				FoodChain.context.home = app = new FoodChain.App().renderInto(document.getElementById("body"));
				FoodChain.setLocale();

				// Load context
				FoodChain.loadContext(function() {
					app.playGame({
						name: FoodChain.context.game.replace("FoodChain.", ""),
						level: FoodChain.context.level
					});
				});
			} else {
				// Just change locale
				FoodChain.setLocale();
			}
		}, false);
    });

});
<commit_msg>Fix async loading issue on FoodChain activity<commit_after>

define(function (require) {
	l10n = require("webL10n");
    var activity = require("sugar-web/activity/activity");
	var radioButtonsGroup = require("sugar-web/graphics/radiobuttonsgroup");
    var datastore = require("sugar-web/datastore");
	var app = null;

    // Manipulate the DOM only when it is ready.
    require(['domReady!'], function (doc) {
		// Initialize the activity
		FoodChain.activity = activity;
		FoodChain.activity.setup();

		// Initialize buttons
		var languageRadio = new radioButtonsGroup.RadioButtonsGroup([
			document.getElementById("en-button"),
			document.getElementById("fr-button")]
		);
		document.getElementById("en-button").onclick = function() {
			l10n.language.code = "en";
			FoodChain.setLocale();
		};
		document.getElementById("fr-button").onclick = function() {
			l10n.language.code = "fr";
			FoodChain.setLocale();
		};

		// Wait for locale load
		window.addEventListener('localized', function() {
			// Init activity
			if (app == null) {
				// Init sound component
				FoodChain.sound = new FoodChain.Audio();
				FoodChain.sound.renderInto(document.getElementById("header"));

				// Create and display first screen
				FoodChain.context.home = app = new FoodChain.App().renderInto(document.getElementById("body"));
				FoodChain.setLocale();

				// Load context
				FoodChain.loadContext(function() {
					app.playGame({
						name: FoodChain.context.game.replace("FoodChain.", ""),
						level: FoodChain.context.level
					});
				});
			} else {
				// Just change locale
				FoodChain.setLocale();
			}
		}, false);
    });

});
<|endoftext|>


<commit_before>import Ember from 'ember';

const { Mixin, get, tryInvoke } = Ember;

export default Mixin.create({
  NON_ATTRIBUTE_BOUND_PROPS: ['class', 'classNames'],
  concatenatedProperties: ['NON_ATTRIBUTE_BOUND_PROPS'],
  didReceiveAttrs() {
    this._super(...arguments);
    let $element = tryInvoke(this, '$element') || this.$();

    for (let key in this.attrs) {
      if (this.NON_ATTRIBUTE_BOUND_PROPS.indexOf(key) === -1) {
        $element.attr(key, get(this, key));
      }
    }
  }
});
<commit_msg>fixup! Fix ignored modifier in ons-button<commit_after>import Ember from 'ember';

const { Mixin, get, tryInvoke } = Ember;

export default Mixin.create({
  NON_ATTRIBUTE_BOUND_PROPS: ['class', 'classNames'],
  concatenatedProperties: ['NON_ATTRIBUTE_BOUND_PROPS'],

  _updateDynamicBoundProperties() {
    this._super(...arguments);
    let $element = tryInvoke(this, '$element') || this.$();

    for (let key in this.attrs) {
      if (this.NON_ATTRIBUTE_BOUND_PROPS.indexOf(key) === -1) {
        $element.attr(key, get(this, key));
      }
    }
  },

  didUpdateAttrs() {
    this._super(...arguments);
    this._updateDynamicBoundProperties();
  },

  didInsertElement() {
    this._super(...arguments);
    this._updateDynamicBoundProperties();
  }
});
<|endoftext|>


<commit_before>import Ember from 'ember';
import layout from './template';

/**
 * @name        FilterContentComponent
 * @description component that applys a simple filter to a specified content model
 *              based on basic matching
 * @extends     external:Ember.Component
 */
export default Ember.Component.extend({

  /* properties
  ------------------------ */

  /**
   * @name        classNames
   * @description class names applied to the component DOM object
   * @type        {array.<string>}
   */
  classNames: ['filter-content'],

  /**
   * @name        content
   * @description the content passed in to be filtered
   * @type        {(array|object)}
   */
  content: [],

  /**
   * @name        debounceFilter
   * @description debounced call to `applyFilter`
   * @type        {Ember.run.later}
   */
  debounceFilter: null,

  /**
   * @name        layout
   * @description component layout
   */
  layout,

  /**
   * @name        properties
   * @description a space-delimited string of dot-notated properties to match
   *              against when filtering
   * @type        {string}
   */
  properties: '',

  /**
   * @name        query
   * @description the query string being filtered against
   * @type        {string}
   */
  query: '',

  /**
   * @name        timeout
   * @description time in milliseconds to debounce `applyFilter`
   * @type        {(number|string)}
   */
  timeout: 420,

  /* computed
  ------------------------ */

  /**
   * @name        filterableProperties
   * @description normalize `properties` and return them as an array
   * @returns     {array} an array of normalized property indices
   */
  normalizedProperties: Ember.computed ('properties', function () {

    try {

      var properties = this.get ('properties') || '';

      return !properties ? [] : properties
        // replace invalid characters
        .replace (/[^\w\s\@\.\-]+/g, '')
        // replace multiple periods with single periods
        .replace (/[\.]{2,}/g, '.')
        // normalize delimiter to single spaces
        .replace (/(\.+)?\s\1?/g, ' ')
        .split (/\s+/g)
        // remove empty items
        .filter (z => z !== '');

      } catch (exception) {

        if (window.console) { window.console.error ('normalizedProperties', exception); }
      }
  }),

  /**
   * @name        queryComputed
   * @description the string being matched against 'contentComputed' replaces
   *              forward slashes to prevent error
   * @returns     {string}
   * @todo        is there a better solution for forward slashes?
   */
  normalizedQuery: Ember.computed('query', function () {

    try {

      var query = this.get ('query');

      return Ember.isPresent(query) ? query.replace(/\\+/g, '') : '';

    } catch (exception) {

      if (window.console) { window.console.error ('normalizedQuery', exception); }
    }
  }),

  /* observers
  ------------------------ */

  /**
   * @name        setFilterTimer
   * @description an observer that passes `debounceFilter` to `Ember.run.later`
   */
  setFilterTimer: Ember.observer ('content', 'normalizedProperties', 'normalizedQuery', function () {

    try {

      // Ember.run.cancel (this.get ('debounceFilter'));
      this.set('debounceFilter', Ember.run.debounce (this, this.applyFilter, Number.parseInt (this.get ('timeout'), 10), false));

    } catch (exception) {

      if (window.console) { window.console.error ('setFilterTimer', exception); }
    }
  }),

  /* methods
  ------------------------ */

  /**
   * @name        applyFilter
   * @description filters for `query` against value(s) of `properties` in `content`
   */
  applyFilter () {

    try {

      var content = this.get ('content') || [];
      var matched = false;
      var properties = this.get ('normalizedProperties') || [];
      var propertiesTmp = [];
      var query = this.get ('normalizedQuery') || '';
      var values = [];

      if (!content || !properties) { return content ? content : []; }

      if (content.length && properties.length && !!query) {

        content = content.filter (item => {

          matched = false;
          propertiesTmp = properties.slice (0);

          propertiesTmp.forEach (prop => {

            values = values.concat (this.getContentProps (item, prop) || []);
          });

          while (matched === false && values.length) {

            matched = this.isMatch(values.shift (), query) ? true : false;
          }

          values = [];
          return matched;
        });
      }

      this.set('filteredContent', content);

    } catch (exception) {

      if (window.console) { window.console.error ('applyFilter', exception); }
    }
  },

  /**
   * @name        getContentProps
   * @description returns an array of values from `item` at dot notated `property`
   * @param       {(array|object)} item
   * @param       {string} property dot notated index
   * @returns     {array} an array of values matching `property`'s index
   */
  getContentProps (item, property, inception = 0) {

    try {

      var propArr = property.split (/\.+/g);// (/\.?\@each\.?/g);
      var prop = '';
      var values = [];
      var z = [];

      if (!propArr.length) { return []; }
      if (inception > 100) { throw `recursing too far, limit is 100 levels`; }

      prop = propArr.shift ();

      // get array items
      if (prop === '@each') {

        if (item.forEach) {

          item.forEach (i => values = values.concat (propArr.length ? this.getContentProps (i, propArr.join ('.'), ++inception) : i));
        }

      // get item property
      } else {

        z = Ember.get (item, prop) || [];
        values = values.concat (propArr.length ? this.getContentProps (z, propArr.join ('.'), ++inception) : z);
      }

      return values && !!values.length ? values : [];

    } catch (exception) {

      if (window.console) { window.console.error ('getContentProps', exception); }
    }
  },

  /**
   * @name        init
   * @description n/a
   */
  init () {

    this._super ();
    this.applyFilter ();
  },

  /**
   * @name        isMatch
   * @todo        seems like this would fail if either value was 'false', should
   *              probably fix this if that's the case...
   * @description checks if valueA and valueB match; passed values are sloppily
   *              coerced to strings
   * @param       {(number|string)} valueA
   * @param       {(number|string)} valueA
   * @returns     {boolean} whether there was a match between the passed values
   */
  isMatch (valueA, valueB) {

    try {

      var matched = false;
      var typeA = Ember.typeOf (valueA);
      var typeB = Ember.typeOf (valueB);

      typeA = (typeA === 'undefined' || typeA === 'null' || typeA === 'number' || typeA === 'string' || typeA === 'boolean');
      typeB = (typeB === 'undefined' || typeB === 'null' || typeB === 'number' || typeB === 'string' || typeB === 'boolean');

      if (typeA && typeB) {

        valueA = Ember.inspect (valueA).toLowerCase ();
        valueB = Ember.inspect (valueB).toLowerCase ();
        matched = valueA.match (valueB) !== null;
      }

      return matched;

    } catch (exception) {

      if (window.console) { window.console.error ('isMatch', exception); }
    }
  },

  /**
   * @name        willDestroy
   * @todo        this may be elligible for deprecation
   * @description runs before the component is destroyed and tears things down
   */
  willDestroy () {

    this._super ();
    Ember.run.cancel (this.get ('debounceFilter'));
  }
});
<commit_msg>Refactored and renamed isMatch:<commit_after>import Ember from 'ember';
import layout from './template';

/**
 * @name        FilterContentComponent
 * @description component that applys a simple filter to a specified content model
 *              based on basic matching
 * @extends     external:Ember.Component
 */
export default Ember.Component.extend({

  /* properties
  ------------------------ */

  /**
   * @name        classNames
   * @description class names applied to the component DOM object
   * @type        {array.<string>}
   */
  classNames: ['filter-content'],

  /**
   * @name        content
   * @description the content passed in to be filtered
   * @type        {(array|object)}
   */
  content: [],

  /**
   * @name        debounceFilter
   * @description debounced call to `applyFilter`
   * @type        {Ember.run.later}
   */
  debounceFilter: null,

  /**
   * @name        layout
   * @description component layout
   */
  layout,

  /**
   * @name        properties
   * @description a space-delimited string of dot-notated properties to match
   *              against when filtering
   * @type        {string}
   */
  properties: '',

  /**
   * @name        query
   * @description the query string being filtered against
   * @type        {string}
   */
  query: '',

  /**
   * @name        timeout
   * @description time in milliseconds to debounce `applyFilter`
   * @type        {(number|string)}
   */
  timeout: 420,

  /* computed
  ------------------------ */

  /**
   * @name        filterableProperties
   * @description normalize `properties` and return them as an array
   * @returns     {array} an array of normalized property indices
   */
  normalizedProperties: Ember.computed ('properties', function () {

    try {

      var properties = this.get ('properties') || '';

      return !properties ? [] : properties
        // replace invalid characters
        .replace (/[^\w\s\@\.\-]+/g, '')
        // replace multiple periods with single periods
        .replace (/[\.]{2,}/g, '.')
        // normalize delimiter to single spaces
        .replace (/(\.+)?\s\1?/g, ' ')
        .split (/\s+/g)
        // remove empty items
        .filter (z => z !== '');

      } catch (exception) {

        if (window.console) { window.console.error ('normalizedProperties', exception); }
      }
  }),

  /**
   * @name        queryComputed
   * @description the string being matched against 'contentComputed' replaces
   *              forward slashes to prevent error
   * @returns     {string}
   * @todo        is there a better solution for forward slashes?
   */
  normalizedQuery: Ember.computed('query', function () {

    try {

      var query = this.get ('query');

      return Ember.isPresent(query) ? query.replace(/\\+/g, '') : '';

    } catch (exception) {

      if (window.console) { window.console.error ('normalizedQuery', exception); }
    }
  }),

  /* observers
  ------------------------ */

  /**
   * @name        setFilterTimer
   * @description an observer that passes `debounceFilter` to `Ember.run.later`
   */
  setFilterTimer: Ember.observer ('content', 'normalizedProperties', 'normalizedQuery', function () {

    try {

      // Ember.run.cancel (this.get ('debounceFilter'));
      this.set('debounceFilter', Ember.run.debounce (this, this.applyFilter, Number.parseInt (this.get ('timeout'), 10), false));

    } catch (exception) {

      if (window.console) { window.console.error ('setFilterTimer', exception); }
    }
  }),

  /* methods
  ------------------------ */

  /**
   * @name        aContainsB
   * @description checks if a contains a match for b; passed values are sloppily
   *              coerced to strings
   * @param       {(number|string)} a
   * @param       {(number|string)} b
   * @returns     {boolean} whether there was a match between the passed values
   */
  aContainsB (a, b) {

    try {

      var matched = false;
      var matchTypes = ['boolean', 'number', 'string'];

      if (matchTypes.indexOf (Ember.typeOf (a)) !== -1 && matchTypes.indexOf (Ember.typeOf (b)) !== -1) {

        matched = Ember.inspect (a).toLowerCase ().match (Ember.inspect (b).toLowerCase ()) !== null;
      }

      return matched;

    } catch (exception) {

      if (window.console) { window.console.error ('aContainsB', exception); }
    }
  },

  /**
   * @name        applyFilter
   * @description filters for `query` against value(s) of `properties` in `content`
   */
  applyFilter () {

    try {

      var content = this.get ('content') || [];
      var matched = false;
      var properties = this.get ('normalizedProperties') || [];
      var propertiesTmp = [];
      var query = this.get ('normalizedQuery') || '';
      var values = [];

      if (!content || !properties) { return content ? content : []; }

      if (content.length && properties.length && !!query) {

        content = content.filter (item => {

          matched = false;
          propertiesTmp = properties.slice (0);

          propertiesTmp.forEach (prop => {

            values = values.concat (this.getContentProps (item, prop) || []);
          });

          while (matched === false && values.length) {

            matched = this.aContainsB(values.shift (), query) ? true : false;
          }

          values = [];
          return matched;
        });
      }

      this.set('filteredContent', content);

    } catch (exception) {

      if (window.console) { window.console.error ('applyFilter', exception); }
    }
  },

  /**
   * @name        getContentProps
   * @description returns an array of values from `item` at dot notated `property`
   * @param       {(array|object)} item
   * @param       {string} property dot notated index
   * @returns     {array} an array of values matching `property`'s index
   */
  getContentProps (item, property, inception = 0) {

    try {

      var propArr = property.split (/\.+/g);// (/\.?\@each\.?/g);
      var prop = '';
      var values = [];
      var z = [];

      if (!propArr.length) { return []; }
      if (inception > 100) { throw `recursing too far, limit is 100 levels`; }

      prop = propArr.shift ();

      // get array items
      if (prop === '@each') {

        if (item.forEach) {

          item.forEach (i => values = values.concat (propArr.length ? this.getContentProps (i, propArr.join ('.'), ++inception) : i));
        }

      // get item property
      } else {

        z = Ember.get (item, prop) || [];
        values = values.concat (propArr.length ? this.getContentProps (z, propArr.join ('.'), ++inception) : z);
      }

      return values && !!values.length ? values : [];

    } catch (exception) {

      if (window.console) { window.console.error ('getContentProps', exception); }
    }
  },

  /**
   * @name        init
   * @description n/a
   */
  init () {

    this._super ();
    this.applyFilter ();
  },

  /**
   * @name        willDestroy
   * @todo        this may be elligible for deprecation
   * @description runs before the component is destroyed and tears things down
   */
  willDestroy () {

    this._super ();
    Ember.run.cancel (this.get ('debounceFilter'));
  }
});
<|endoftext|>


<commit_before>const mix = require('laravel-mix');

/**
 * Compile CSS
 */
mix.sass('resources/scss/admin.scss', 'public/css', { implementation: require('node-sass') });
mix.sass('resources/scss/public.scss', 'public/css', { implementation: require('node-sass') });

/**
 * Compile JS
 */
mix.js('resources/js/admin.js', 'public/js');
mix.js('resources/js/public.js', 'public/js');

/**
 * Copy font-awesome files
 */
mix.copy('node_modules/font-awesome/fonts', 'public/fonts');

/**
 * Copy CKEditor main files
 */
mix.copy('node_modules/ckeditor/ckeditor.js', 'public/components/ckeditor/ckeditor.js');
mix.copy('node_modules/ckeditor/contents.css', 'public/components/ckeditor/contents.css');

/**
 * Copy CKEditor lang files
 */
mix.copy('node_modules/ckeditor/lang/fr.js', 'public/components/ckeditor/lang/fr.js');
mix.copy('node_modules/ckeditor/lang/es.js', 'public/components/ckeditor/lang/es.js');
mix.copy('node_modules/ckeditor/lang/nl.js', 'public/components/ckeditor/lang/nl.js');
mix.copy('node_modules/ckeditor/lang/en.js', 'public/components/ckeditor/lang/en.js');

/**
 * Copy CKEditor plugins files
 */
var plugins = [
    'dialogadvtab',
    'div',
    'image',
    'image2',
    'justify',
    'link',
    'magicline',
    'panelbutton',
    'pastefromword',
    'scayt',
    'showblocks',
    'specialchar',
    'table',
    'tableselection',
    'widget',
    'wsc',
];
plugins.forEach(function(plugin) {
    mix.copy('node_modules/ckeditor/plugins/' + plugin, 'public/components/ckeditor/plugins/' + plugin);
});

/**
 * Copy CKEditor skins files
 */
mix.copy('node_modules/ckeditor/skins', 'public/components/ckeditor/skins');

/**
 * Versioning process
 */
mix.version();

/**
 * BrowserSync
 */
mix.browserSync('typicms.test');

/**
 * Options
 */
mix.options({
    processCssUrls: false,
    autoprefixer: {
        enabled: true,
        options: {
            grid: true,
            browsers: ['last 10 versions'],
        },
    },
});

/**
 * Source maps
 */
// if (!mix.inProduction()) {
//     mix.webpackConfig({
//         devtool: 'source-map',
//     }).sourceMaps();
// }
<commit_msg>autoprefixer config<commit_after>const mix = require('laravel-mix');

/**
 * Compile CSS
 */
mix.sass('resources/scss/admin.scss', 'public/css', { implementation: require('node-sass') });
mix.sass('resources/scss/public.scss', 'public/css', { implementation: require('node-sass') });

/**
 * Compile JS
 */
mix.js('resources/js/admin.js', 'public/js');
mix.js('resources/js/public.js', 'public/js');

/**
 * Copy font-awesome files
 */
mix.copy('node_modules/font-awesome/fonts', 'public/fonts');

/**
 * Copy CKEditor main files
 */
mix.copy('node_modules/ckeditor/ckeditor.js', 'public/components/ckeditor/ckeditor.js');
mix.copy('node_modules/ckeditor/contents.css', 'public/components/ckeditor/contents.css');

/**
 * Copy CKEditor lang files
 */
mix.copy('node_modules/ckeditor/lang/fr.js', 'public/components/ckeditor/lang/fr.js');
mix.copy('node_modules/ckeditor/lang/es.js', 'public/components/ckeditor/lang/es.js');
mix.copy('node_modules/ckeditor/lang/nl.js', 'public/components/ckeditor/lang/nl.js');
mix.copy('node_modules/ckeditor/lang/en.js', 'public/components/ckeditor/lang/en.js');

/**
 * Copy CKEditor plugins files
 */
var plugins = [
    'dialogadvtab',
    'div',
    'image',
    'image2',
    'justify',
    'link',
    'magicline',
    'panelbutton',
    'pastefromword',
    'scayt',
    'showblocks',
    'specialchar',
    'table',
    'tableselection',
    'widget',
    'wsc',
];
plugins.forEach(function(plugin) {
    mix.copy('node_modules/ckeditor/plugins/' + plugin, 'public/components/ckeditor/plugins/' + plugin);
});

/**
 * Copy CKEditor skins files
 */
mix.copy('node_modules/ckeditor/skins', 'public/components/ckeditor/skins');

/**
 * Versioning process
 */
mix.version();

/**
 * BrowserSync
 */
mix.browserSync('typicms.test');

/**
 * Options
 */
mix.options({
    processCssUrls: false,
    autoprefixer: {
        options: {
            overrideBrowserslist: ['last 10 versions'],
        },
    },
});

/**
 * Source maps
 */
// if (!mix.inProduction()) {
//     mix.webpackConfig({
//         devtool: 'source-map',
//     }).sourceMaps();
// }
<|endoftext|>