<commit_before>var appConf = require('../conf/appConfig.json');
var express = require('express');
var router = express.Router();

var log4js = require('log4js');
log4js.configure('./conf/log4js.json');
var logger = log4js.getLogger("index");

var sensorData = require('../lib/sensorData')(appConf, log4js);

// Remember, in Express 4, '/' is the root under which this route is mounted, so does not
// necessarily correspond to the absolute root of the domain.
//
router.get('/', function (req, res) {
    logger.debug('Serving / --> index.hjs');
    res.render('index', {title: 'Welcome to the empty server'});
});

router.get('/sensordata/:sensorname', function (req, res) {
    var sensorname = req.params.sensorname;
    var limit = req.query.limit || 100;
    logger.debug('Serving /sensordata', sensorname, limit);
    sensorData(sensorname, limit).then(function(res) { res.json(res); });
});

module.exports = router;
<commit_msg>bugfix<commit_after>var appConf = require('../conf/appConfig.json');
var express = require('express');
var router = express.Router();

var log4js = require('log4js');
log4js.configure('./conf/log4js.json');
var logger = log4js.getLogger("index");

var sensorData = require('../lib/sensorData')(appConf, log4js);

// Remember, in Express 4, '/' is the root under which this route is mounted, so does not
// necessarily correspond to the absolute root of the domain.
//
router.get('/', function (req, res) {
    logger.debug('Serving / --> index.hjs');
    res.render('index', {title: 'Welcome to the empty server'});
});

router.get('/sensordata/:sensorname', function (req, res) {
    var sensorname = req.params.sensorname;
    var limit = req.query.limit || 100;
    logger.debug('Serving /sensordata', sensorname, limit);
    sensorData(sensorname, limit).then(function(result) { res.json(result); });
});

module.exports = router;
<|endoftext|>


<commit_before>'use strict';

const electron = require('electron');
const app = electron.app;
const BrowserWindow = electron.BrowserWindow;
const Menu = require('menu');
const globalShortcut = electron.globalShortcut;

const windowStateKeeper = require('electron-window-state');

let mainWindow;

function focus_webview() {
  mainWindow.webContents.executeJavaScript('document.getElementById("overcast_webview").focus();');
}

app.on('ready', function() {
  // Initial window state
  let mainWindowState = windowStateKeeper({
    defaultWidth: 352,
    defaultHeight: 556
  });

  // Create the browser window.
  mainWindow = new BrowserWindow({
    x: mainWindowState.x,
    y: mainWindowState.y,
    width: mainWindowState.width,
    height: mainWindowState.height,
    minWidth: 298,
    minHeight: 502,
    titleBarStyle: 'hidden-inset',
    title: 'Fog'
  });

  // Add listeners to check for window maximization and save state
  mainWindowState.manage(mainWindow);

  // Load the index.html of the app and focus on webview
  mainWindow.loadURL('file://' + __dirname + '/index.html')
  focus_webview();

  // Media keys shortcuts
  globalShortcut.register('MediaPreviousTrack', function() { mainWindow.webContents.send('media_keys', 'seekbackbutton') });
  globalShortcut.register('MediaNextTrack', function() { mainWindow.webContents.send('media_keys', 'seekforwardbutton') });
  globalShortcut.register('MediaPlayPause', function() { mainWindow.webContents.send('media_keys', 'playpausebutton'); });

  // Main app menu
  let name = electron.app.getName();
  let template = [
    {
      label: 'Application',
      submenu: [
        { label: 'About ' + name, role: 'about' },
        { type: 'separator' },
        { label: 'Hide ' + name, accelerator: 'Command+H', role: 'hide' },
        { label: 'Hide Others', accelerator: 'Command+Shift+H', role: 'hideothers' },
        { type: 'separator' },
        { label: 'Quit', accelerator: 'Command+Q', click: function() {app.quit();} }
      ]
    }, {
      label: 'Edit',
      submenu: [
        { label: 'Undo', accelerator: 'Command+Z', role: 'undo' },
        { label: 'Redo', accelerator: 'Shift+Command+Z', role: 'redo' },
        { type: 'separator' },
        { label: 'Cut', accelerator: 'Command+X', role: 'cut' },
        { label: 'Copy', accelerator: 'Command+C', role: 'copy' },
        { label: 'Paste', accelerator: 'Command+V', role: 'paste' },
        { label: 'Select All', accelerator: 'Command+A', role: 'selectall' }
      ]
    }, {
      label: 'View',
      submenu: [
        { label: 'Reload', accelerator: 'Command+R', click: function(item,focusedWindow) {if (focusedWindow) focusedWindow.webContents.executeJavaScript('document.getElementById("overcast_webview").reload()');} }
      ]
    }, {
      label: 'Window',
      submenu: [
        { label: 'Minimize', accelerator: 'Command+M', role: 'minimize' },
        { label: 'Close', accelerator: 'Command+W', role: 'hide' }
      ]
    }, {
      label: 'Help',
      role: 'help',
      submenu: [
        { label: 'View Website', click: function() { require('electron').shell.openExternal('https://github.com/vitorgalvao/fog/') } },
        { type: 'separator' },
        { label: 'Toggle Developer Tools', click: function(item,focusedWindow) {if (focusedWindow) focusedWindow.toggleDevTools();} }
      ]
    }
  ];

  Menu.setApplicationMenu(Menu.buildFromTemplate(template));

  // Focus on webview when focusing on window, so we can use keyboard shortcuts
  app.on('browser-window-focus', function() {
    focus_webview();
  });

  // Prevent app from exiting (hide it instead) when window is closed (i.e. when we press the red close button)
  mainWindow.on('close', function(event) {
    if (!mainWindow.forceClose) { // Unless we really told the app to quit
      event.preventDefault();
      mainWindow.hide();
    }
  });

  app.on('before-quit', function() {
    globalShortcut.unregisterAll();
    mainWindow.forceClose = true;
  });

  app.on('activate', function() {
    mainWindow.show();
  });
});
<commit_msg>make command+w close window instead of hiding<commit_after>'use strict';

const electron = require('electron');
const app = electron.app;
const BrowserWindow = electron.BrowserWindow;
const Menu = require('menu');
const globalShortcut = electron.globalShortcut;

const windowStateKeeper = require('electron-window-state');

let mainWindow;

function focus_webview() {
  mainWindow.webContents.executeJavaScript('document.getElementById("overcast_webview").focus();');
}

app.on('ready', function() {
  // Initial window state
  let mainWindowState = windowStateKeeper({
    defaultWidth: 352,
    defaultHeight: 556
  });

  // Create the browser window.
  mainWindow = new BrowserWindow({
    x: mainWindowState.x,
    y: mainWindowState.y,
    width: mainWindowState.width,
    height: mainWindowState.height,
    minWidth: 298,
    minHeight: 502,
    titleBarStyle: 'hidden-inset',
    title: 'Fog'
  });

  // Add listeners to check for window maximization and save state
  mainWindowState.manage(mainWindow);

  // Load the index.html of the app and focus on webview
  mainWindow.loadURL('file://' + __dirname + '/index.html')
  focus_webview();

  // Media keys shortcuts
  globalShortcut.register('MediaPreviousTrack', function() { mainWindow.webContents.send('media_keys', 'seekbackbutton') });
  globalShortcut.register('MediaNextTrack', function() { mainWindow.webContents.send('media_keys', 'seekforwardbutton') });
  globalShortcut.register('MediaPlayPause', function() { mainWindow.webContents.send('media_keys', 'playpausebutton'); });

  // Main app menu
  let name = electron.app.getName();
  let template = [
    {
      label: 'Application',
      submenu: [
        { label: 'About ' + name, role: 'about' },
        { type: 'separator' },
        { label: 'Hide ' + name, accelerator: 'Command+H', role: 'hide' },
        { label: 'Hide Others', accelerator: 'Command+Shift+H', role: 'hideothers' },
        { type: 'separator' },
        { label: 'Quit', accelerator: 'Command+Q', click: function() {app.quit();} }
      ]
    }, {
      label: 'Edit',
      submenu: [
        { label: 'Undo', accelerator: 'Command+Z', role: 'undo' },
        { label: 'Redo', accelerator: 'Shift+Command+Z', role: 'redo' },
        { type: 'separator' },
        { label: 'Cut', accelerator: 'Command+X', role: 'cut' },
        { label: 'Copy', accelerator: 'Command+C', role: 'copy' },
        { label: 'Paste', accelerator: 'Command+V', role: 'paste' },
        { label: 'Select All', accelerator: 'Command+A', role: 'selectall' }
      ]
    }, {
      label: 'View',
      submenu: [
        { label: 'Reload', accelerator: 'Command+R', click: function(item,focusedWindow) {if (focusedWindow) focusedWindow.webContents.executeJavaScript('document.getElementById("overcast_webview").reload()');} }
      ]
    }, {
      label: 'Window',
      role: 'window',
      submenu: [
        { label: 'Minimize', accelerator: 'Command+M', role: 'minimize' },
        { label: 'Close', accelerator: 'Command+W', role: 'close' }
      ]
    }, {
      label: 'Help',
      role: 'help',
      submenu: [
        { label: 'View Website', click: function() { require('electron').shell.openExternal('https://github.com/vitorgalvao/fog/') } },
        { type: 'separator' },
        { label: 'Toggle Developer Tools', click: function(item,focusedWindow) {if (focusedWindow) focusedWindow.toggleDevTools();} }
      ]
    }
  ];

  Menu.setApplicationMenu(Menu.buildFromTemplate(template));

  // Focus on webview when focusing on window, so we can use keyboard shortcuts
  app.on('browser-window-focus', function() {
    focus_webview();
  });

  // Prevent app from exiting (hide it instead) when window is closed (i.e. when we press the red close button)
  mainWindow.on('close', function(event) {
    if (!mainWindow.forceClose) { // Unless we really told the app to quit
      event.preventDefault();
      mainWindow.hide();
    }
  });

  app.on('before-quit', function() {
    globalShortcut.unregisterAll();
    mainWindow.forceClose = true;
  });

  app.on('activate', function() {
    mainWindow.show();
  });
});
<|endoftext|>


<commit_before>dynForm = {
    jsonSchema : {
	    title : trad.addOrganization,
	    icon : "group",
	    type : "object",
	    onLoads : {
	    	//pour creer un subevnt depuis un event existant
	    	onload : function(){
	    		dyFInputs.setHeader("bg-green");
    	   	},
	    	sub : function(){

				if(typeof currentKFormType == "undefined" || currentKFormType == "" ||
				  currentKFormType == "null" || currentKFormType == null){
					currentKFormType = "organization";
				}else{
					$("#ajaxFormModal .typeselect").addClass("hidden");
				}
	    		//console.log("onLoads Sub currentKFormType", currentKFormType, contextData, contextData.id);
                var typeName = (typeof currentKFormType != "undefined" && currentKFormType!=null) ? trad["add"+currentKFormType] : elementObj.dynForm.jsonSchema.title;
                var typeIcon = (typeof currentKFormType != "undefined" && currentKFormType!=null) ? typeObj[currentKFormType].icon : elementObj.dynForm.jsonSchema.icon;

                $("#ajax-modal-modal-title").html(
                        " "+typeName);

                $("#ajax-modal .modal-header").removeClass("bg-dark bg-red bg-purple bg-green bg-green-poi bg-orange bg-turq bg-yellow bg-url");
				$("#ajax-modal .infocustom p").removeClass("text-dark text-red text-purple text-green text-green-poi text-orange text-turq text-yellow text-url");

                if(typeof currentKFormType != "undefined" && typeObj[currentKFormType] && typeObj[currentKFormType].color){
                	//alert("dyn" + typeObj[currentKFormType].color);
                    $("#ajax-modal .modal-header").addClass("bg-"+typeObj[currentKFormType].color);
                    $("#ajax-modal .infocustom p").addClass("text-"+typeObj[currentKFormType].color);
                }else{
                	$("#ajax-modal .modal-header").addClass("bg-dark");
                    $("#ajax-modal .infocustom p").addClass("text-dark");
                }

	    		if(contextData && contextData.type && contextData.id ){
	    			//console.log("HERE WE ARE");
    				$('#ajaxFormModal #parentId').val(contextData.id);
	    			$("#ajaxFormModal #parentType").val( contextData.type );

	    		 	$("#ajax-modal-modal-title").append(
	    		 		"
"+tradDynForm.speakingas+" : "+
	    		 														contextData.name+
	    		 														"" );
	    		}else if(userConnected){
					$('#ajaxFormModal #parentId').val( userId );
					$("#ajaxFormModal #parentType").val( "citoyens" );
					$("#ajax-modal-modal-title").append(
	    		 		"
"+tradDynForm.speakingas+" : "+
	    		 														userConnected.name+
	    		 														"" );
    			}
	    	},
	    },
	    beforeBuild : function(){
	    	dyFObj.setMongoId('organizations', function(){
	    		uploadObj.gotoUrl = '#page.type.organizations.id.'+uploadObj.id;
	    	});

	    },
	    beforeSave : function(){
	    	if (typeof $("#ajaxFormModal #description").code === 'function' )
	    		$("#ajaxFormModal #description").val( $("#ajaxFormModal #description").code() );
	    },
	    afterSave : function(){
			if( $('.fine-uploader-manual-trigger').fineUploader('getUploads').length > 0 )
		    	$('.fine-uploader-manual-trigger').fineUploader('uploadStoredFiles');
		    else {
	          dyFObj.closeForm();
	          urlCtrl.loadByHash( uploadObj.gotoUrl );
	        }
	    },
	    properties : {
	    	info : {
                inputType : "custom",
                html:"
"+
                		//"Faire connaître votre Organisation n'a jamais été aussi simple !
" +
					    tradDynForm["infocreateorganization"]+" ...
" +
					 "
",
            },
	        name : dyFInputs.name("organization"),
	        similarLink : dyFInputs.similarLink,
	        type : dyFInputs.inputSelect(tradDynForm["organizationType"], tradDynForm["organizationType"], organizationTypes, { required : true }),
            role : dyFInputs.inputSelect(	tradDynForm["yourrole"],
            								tradDynForm["whichrole"]+" ?",
            								{ admin : trad.administrator, member : trad.Member, creator : trad.justCitizen },
            								{ required : true } ),
            tags : dyFInputs.tags(),
            location : dyFInputs.location,
	        image : dyFInputs.image(),
            email : dyFInputs.text(),
	        shortDescription : dyFInputs.textarea(tradDynForm["shortDescription"], "...",{ maxlength: 140 }),
	        url : dyFInputs.inputUrl(),
            "preferences[publicFields]" : dyFInputs.inputHidden([]),
            "preferences[privateFields]" : dyFInputs.inputHidden([]),
            "preferences[isOpenData]" : dyFInputs.inputHidden(true),
            "preferences[isOpenEdition]" : dyFInputs.inputHidden(true)
	    }
	}
};<commit_msg>test trad<commit_after>dynForm = {
    jsonSchema : {
	    title : trad.addOrganization,
	    icon : "group",
	    type : "object",
	    onLoads : {
	    	//pour creer un subevnt depuis un event existant
	    	onload : function(){
	    		dyFInputs.setHeader("bg-green");
    	   	},
	    	sub : function(){

				if(typeof currentKFormType == "undefined" || currentKFormType == "" ||
				  currentKFormType == "null" || currentKFormType == null){
					currentKFormType = "organization";
				}else{
					$("#ajaxFormModal .typeselect").addClass("hidden");
				}
	    		//console.log("onLoads Sub currentKFormType", currentKFormType, contextData, contextData.id);
                var typeName = (typeof currentKFormType != "undefined" && currentKFormType!=null) ? trad["add"+currentKFormType] : elementObj.dynForm.jsonSchema.title;
                var typeIcon = (typeof currentKFormType != "undefined" && currentKFormType!=null) ? typeObj[currentKFormType].icon : elementObj.dynForm.jsonSchema.icon;

                $("#ajax-modal-modal-title").html(
                        " "+typeName);

                $("#ajax-modal .modal-header").removeClass("bg-dark bg-red bg-purple bg-green bg-green-poi bg-orange bg-turq bg-yellow bg-url");
				$("#ajax-modal .infocustom p").removeClass("text-dark text-red text-purple text-green text-green-poi text-orange text-turq text-yellow text-url");

                if(typeof currentKFormType != "undefined" && typeObj[currentKFormType] && typeObj[currentKFormType].color){
                	//alert("dyn" + typeObj[currentKFormType].color);
                    $("#ajax-modal .modal-header").addClass("bg-"+typeObj[currentKFormType].color);
                    $("#ajax-modal .infocustom p").addClass("text-"+typeObj[currentKFormType].color);
                }else{
                	$("#ajax-modal .modal-header").addClass("bg-dark");
                    $("#ajax-modal .infocustom p").addClass("text-dark");
                }

	    		if(contextData && contextData.type && contextData.id ){
	    			//console.log("HERE WE ARE");
    				$('#ajaxFormModal #parentId').val(contextData.id);
	    			$("#ajaxFormModal #parentType").val( contextData.type );

	    		 	$("#ajax-modal-modal-title").append(
	    		 		"
"+tradDynForm.speakingas+" : "+
	    		 														contextData.name+
	    		 														"" );
	    		}else if(userConnected){
					$('#ajaxFormModal #parentId').val( userId );
					$("#ajaxFormModal #parentType").val( "citoyens" );
					$("#ajax-modal-modal-title").append(
	    		 		"
"+tradDynForm.speakingas+" : "+
	    		 														userConnected.name+
	    		 														"" );
    			}
	    	},
	    },
	    beforeBuild : function(){
	    	dyFObj.setMongoId('organizations', function(){
	    		uploadObj.gotoUrl = '#page.type.organizations.id.'+uploadObj.id;
	    	});

	    },
	    beforeSave : function(){
	    	if (typeof $("#ajaxFormModal #description").code === 'function' )
	    		$("#ajaxFormModal #description").val( $("#ajaxFormModal #description").code() );
	    },
	    afterSave : function(){
			if( $('.fine-uploader-manual-trigger').fineUploader('getUploads').length > 0 )
		    	$('.fine-uploader-manual-trigger').fineUploader('uploadStoredFiles');
		    else {
	          dyFObj.closeForm();
	          urlCtrl.loadByHash( uploadObj.gotoUrl );
	        }
	    },
	    properties : {
	    	info : {
                inputType : "custom",
                html:"
"+
                		//"Faire connaître votre Organisation n'a jamais été aussi simple !
" +
					    tradDynForm["infocreateorganization"]+" ...
" +
					 "
",
            },
	        name : dyFInputs.name("organization"),
	        similarLink : dyFInputs.similarLink,
	        type : dyFInputs.inputSelect(tradDynForm["organizationType"], tradDynForm["organizationType"], organizationTypes, { required : true }),
	        type : dyFInputs.inputSelect(tradDynForm["organizationType"], tradDynForm["organizationType"], organizationTypes, { required : true }),
            role : dyFInputs.inputSelect(	tradDynForm["yourrole"],
            								tradDynForm["whichrole"]+" ?",
            								{ admin : trad.administrator, member : trad.Member, creator : trad.justCitizen },
            								{ required : true } ),
            tags : dyFInputs.tags(),
            location : dyFInputs.location,
	        image : dyFInputs.image(),
            email : dyFInputs.text(),
	        shortDescription : dyFInputs.textarea(tradDynForm["shortDescription"], "...",{ maxlength: 140 }),
	        url : dyFInputs.inputUrl(),
            "preferences[publicFields]" : dyFInputs.inputHidden([]),
            "preferences[privateFields]" : dyFInputs.inputHidden([]),
            "preferences[isOpenData]" : dyFInputs.inputHidden(true),
            "preferences[isOpenEdition]" : dyFInputs.inputHidden(true)
	    }
	}
};<|endoftext|>


<commit_before>$.fn.romoSelectDropdown = function(optionElemsParent) {
  return $.map(this, function(element) {
    return new RomoSelectDropdown(element, optionElemsParent);
  });
}

var RomoSelectDropdown = function(element, optionElemsParent) {
  this.elem = $(element);

  this.filterHiddenClass  = 'romo-select-filter-hidden';
  this.optionElemSelector = ':not(.'+this.filterHiddenClass+')';
  this.optionElemsParent  = (optionElemsParent || this.elem.find('.romo-select-dropdown-options-parent'));

  this.doInit();
  this._bindElem();

  if (this.elem.attr('id') !== undefined) {
    $('label[for="'+this.elem.attr('id')+'"]').on('click', $.proxy(function(e) {
      this.elem.focus();
    }, this));
  }

  this.elem.trigger('selectDropdown:ready', [this]);
}

RomoSelectDropdown.prototype.bodyElem = function() {
  return this.romoOptionListDropdown.bodyElem();
}

RomoSelectDropdown.prototype.popupElem = function() {
  return this.romoOptionListDropdown.popupElem();
}

RomoSelectDropdown.prototype.selectedItemElem = function() {
  return this.romoOptionListDropdown.selectedItemElem();
}

RomoSelectDropdown.prototype.selectedItemValue = function() {
  return this.romoOptionListDropdown.selectedItemValue();
}

RomoSelectDropdown.prototype.selectedItemText = function() {
  return this.romoOptionListDropdown.selectedItemText();
}

RomoSelectDropdown.prototype.optionFilterValue = function() {
  return this.romoOptionListDropdown.optionFilterValue();
}

RomoSelectDropdown.prototype.optItemElems = function() {
  return this.romoOptionListDropdown.optItemElems();
}

RomoSelectDropdown.prototype.optgroupItemElems = function() {
  return this.romoOptionListDropdown.optgroupItemElems();
}

RomoSelectDropdown.prototype.doInit = function() {
  // override as needed
}

RomoSelectDropdown.prototype.doSetSelectedItem = function(newValue) {
  this.romoOptionListDropdown.doSetSelectedItem(newValue);
}

/* private */

RomoSelectDropdown.prototype._bindElem = function() {
  this.elem.attr('data-romo-option-list-focus-style-class', 'romo-select-focus');

  if (this.elem.data('romo-select-dropdown-no-filter') !== undefined) {
    this.elem.attr('data-romo-option-list-dropdown-no-filter', this.elem.data('romo-select-dropdown-no-filter'));
  }
  if (this.elem.data('romo-select-dropdown-filter-placeholder') !== undefined) {
    this.elem.attr('data-romo-option-list-dropdown-filter-placeholder', this.elem.data('romo-select-dropdown-filter-placeholder'));
  }
  if (this.elem.data('romo-select-dropdown-filter-indicator') !== undefined) {
    this.elem.attr('data-romo-option-list-dropdown-filter-indicator', this.elem.data('romo-select-dropdown-filter-indicator'));
  }
  if (this.elem.data('romo-select-dropdown-filter-indicator-width-px') !== undefined) {
    this.elem.attr('data-romo-option-list-dropdown-filter-indicator-width-px', this.elem.data('romo-select-dropdown-filter-indicator-width-px'));
  }
  if (this.elem.data('romo-select-dropdown-open-on-focus') !== undefined) {
    this.elem.attr('data-romo-option-list-dropdown-open-on-focus', this.elem.data('romo-select-dropdown-open-on-focus'));
  }

  this.elem.on('romoOptionListDropdown:dropdown:toggle', $.proxy(function(e, dropdown) {
    this.elem.trigger('selectDropdown:dropdown:toggle', [dropdown, this]);
  }, this));
  this.elem.on('romoOptionListDropdown:dropdown:popupOpen', $.proxy(function(e, dropdown) {
    this.elem.trigger('selectDropdown:dropdown:popupOpen', [dropdown, this]);
  }, this));
  this.elem.on('romoOptionListDropdown:dropdown:popupClose', $.proxy(function(e, dropdown) {
    this.elem.trigger('selectDropdown:dropdown:popupClose', [dropdown, this]);
  }, this));
  this.elem.on('romoOptionListDropdown:itemSelected', $.proxy(function(e, itemValue, itemDisplayText, romoOptionListDropdown) {
    this.elem.trigger('selectDropdown:itemSelected', [itemValue, itemDisplayText, this]);
  }, this));
  this.elem.on('romoOptionListDropdown:newItemSelected', $.proxy(function(e, itemValue, itemDisplayText, romoOptionListDropdown) {
    this.elem.trigger('selectDropdown:newItemSelected', [itemValue, itemDisplayText, this]);
  }, this));
  this.elem.on('romoOptionListDropdown:change', $.proxy(function(e, newValue, prevValue, romoOptionListDropdown) {
    this.elem.trigger('selectDropdown:change', [newValue, prevValue, this]);
  }, this));

  this.elem.on('selectDropdown:triggerToggle', $.proxy(function(e) {
    this.elem.trigger('romoOptionListDropdown:triggerToggle', []);
  }, this));
  this.elem.on('selectDropdown:triggerPopupOpen', $.proxy(function(e) {
    this.elem.trigger('romoOptionListDropdown:triggerPopupOpen', []);
  }, this));
  this.elem.on('selectDropdown:triggerPopupClose', $.proxy(function(e) {
    this.elem.trigger('romoOptionListDropdown:triggerPopupClose', []);
  }, this));

  this.romoOptionListDropdown = this.elem.romoOptionListDropdown()[0];

  this.elem.on('romoOptionListDropdown:filterChange', $.proxy(function(e, filterValue, romoOptionListDropdown) {
    var elems    = this.optionElemsParent.find('option');
    var wbFilter = new RomoWordBoundaryFilter(filterValue, elems, function(elem) {
      // The romo word boundary filter by default considers a space, "-" and "_"
      // as word boundaries.  We want to also consider other non-word characters
      // (such as ":", "/", ".", "?", "=", "&") as word boundaries as well.
      return elem[0].textContent.replace(/\W/g, ' ');
    });

    wbFilter.matchingElems.removeClass(this.filterHiddenClass);
    wbFilter.notMatchingElems.addClass(this.filterHiddenClass);
    this._setListItems();

    if (filterValue !== '') {
      this.romoOptionListDropdown.elem.trigger('romoOptionListDropdown:triggerListOptionsUpdate', [this.optItemElems().first()]);
    } else {
      this.elem.trigger('romoOptionListDropdown:triggerListOptionsUpdate', [this.selectedItemElem()]);
    }
  }, this));

  this._sanitizeOptions();
  this._setListItems();
  this.elem.trigger('romoOptionListDropdown:triggerListOptionsUpdate', [this.selectedItemElem()]);
}

RomoSelectDropdown.prototype._sanitizeOptions = function() {
  // set any options without a value to value=""
  // all options are required to have a value for things to work
  // this and the select component assume value attrs for all options
  $.each(this.optionElemsParent.find('OPTION'), $.proxy(function(idx, optionNode) {
    var optElem = $(optionNode);
    if (optElem.attr('value') === undefined) {
      optElem.attr('value', '');
    }
  }, this));
}

RomoSelectDropdown.prototype._setListItems = function() {
  var optElems = this.optionElemsParent.children(this.optionElemSelector);
  var items    = this._buildOptionListItems(optElems).concat(this._buildCustomOptionItems());
  this.romoOptionListDropdown.doSetListItems(items);
}

RomoSelectDropdown.prototype._buildOptionListItems = function(optionElems) {
  var list = [];

  $.each(optionElems, $.proxy(function(idx, optionNode) {
    if (optionNode.tagName === "OPTION") {
      list.push(this._buildOptionItem($(optionNode)));
    } else if (optionNode.tagName === "OPTGROUP") {
      var optGroupItem = this._buildOptGroupItem($(optionNode));
      if (optGroupItem.items.length !== 0) {
        list.push(optGroupItem);
      }
    }
  }, this));

  return list;
}

RomoSelectDropdown.prototype._buildOptionItem = function(optionElem) {
  var item = {}

  item['type']        = 'option';
  item['value']       = (optionElem.attr('value') || '');
  item['displayText'] = (optionElem.text().trim() || '');
  item['displayHtml'] = (optionElem.text().trim() || ' ');

  if (optionElem.prop('selected')) {
    item['selected'] = true;
  }
  if (optionElem.attr('disabled') !== undefined) {
    item['disabled'] = true;
  }

  return item;
}

RomoSelectDropdown.prototype._buildOptGroupItem = function(optGroupElem) {
  var item = {};

  item['type']  = 'optgroup';
  item['label'] = optGroupElem.attr('label');
  item['items'] = this._buildOptionListItems(optGroupElem.children(this.optionElemSelector));

  return item;
}

RomoSelectDropdown.prototype._buildCustomOptionItems = function() {
  var items = [];

  var value = this.romoOptionListDropdown.optionFilterValue();
  if (value !== '' && this.elem.data('romo-select-dropdown-custom-option') === true) {
    var prompt = this.elem.data('romo-select-dropdown-custom-option-prompt');
    if (prompt !== undefined) {
      items.push({
        'type':  'optgroup',
        'label': prompt,
        'items': [this._buildCustomOptionItem(value)]
      });
    } else {
      items.push(this._buildCustomOptionItem(value));
    }
  }

  return items;
}

RomoSelectDropdown.prototype._buildCustomOptionItem = function(value) {
  return {
    'type':        'option',
    'value':       value,
    'displayText': value,
    'displayHtml': value
  };
}

Romo.onInitUI(function(e) {
  Romo.initUIElems(e, '[data-romo-select-dropdown-auto="true"]').romoSelectDropdown();
});
<commit_msg>fix custom options on selects: add custom option markup<commit_after>$.fn.romoSelectDropdown = function(optionElemsParent) {
  return $.map(this, function(element) {
    return new RomoSelectDropdown(element, optionElemsParent);
  });
}

var RomoSelectDropdown = function(element, optionElemsParent) {
  this.elem = $(element);

  this.filterHiddenClass  = 'romo-select-filter-hidden';
  this.optionElemSelector = ':not(.'+this.filterHiddenClass+')';
  this.optionElemsParent  = (optionElemsParent || this.elem.find('.romo-select-dropdown-options-parent'));

  this.doInit();
  this._bindElem();

  if (this.elem.attr('id') !== undefined) {
    $('label[for="'+this.elem.attr('id')+'"]').on('click', $.proxy(function(e) {
      this.elem.focus();
    }, this));
  }

  this.elem.trigger('selectDropdown:ready', [this]);
}

RomoSelectDropdown.prototype.bodyElem = function() {
  return this.romoOptionListDropdown.bodyElem();
}

RomoSelectDropdown.prototype.popupElem = function() {
  return this.romoOptionListDropdown.popupElem();
}

RomoSelectDropdown.prototype.selectedItemElem = function() {
  return this.romoOptionListDropdown.selectedItemElem();
}

RomoSelectDropdown.prototype.selectedItemValue = function() {
  return this.romoOptionListDropdown.selectedItemValue();
}

RomoSelectDropdown.prototype.selectedItemText = function() {
  return this.romoOptionListDropdown.selectedItemText();
}

RomoSelectDropdown.prototype.optionFilterValue = function() {
  return this.romoOptionListDropdown.optionFilterValue();
}

RomoSelectDropdown.prototype.optItemElems = function() {
  return this.romoOptionListDropdown.optItemElems();
}

RomoSelectDropdown.prototype.optgroupItemElems = function() {
  return this.romoOptionListDropdown.optgroupItemElems();
}

RomoSelectDropdown.prototype.doInit = function() {
  // override as needed
}

RomoSelectDropdown.prototype.doSetSelectedItem = function(newValue) {
  this.romoOptionListDropdown.doSetSelectedItem(newValue);
}

/* private */

RomoSelectDropdown.prototype._bindElem = function() {
  this.elem.attr('data-romo-option-list-focus-style-class', 'romo-select-focus');

  if (this.elem.data('romo-select-dropdown-no-filter') !== undefined) {
    this.elem.attr('data-romo-option-list-dropdown-no-filter', this.elem.data('romo-select-dropdown-no-filter'));
  }
  if (this.elem.data('romo-select-dropdown-filter-placeholder') !== undefined) {
    this.elem.attr('data-romo-option-list-dropdown-filter-placeholder', this.elem.data('romo-select-dropdown-filter-placeholder'));
  }
  if (this.elem.data('romo-select-dropdown-filter-indicator') !== undefined) {
    this.elem.attr('data-romo-option-list-dropdown-filter-indicator', this.elem.data('romo-select-dropdown-filter-indicator'));
  }
  if (this.elem.data('romo-select-dropdown-filter-indicator-width-px') !== undefined) {
    this.elem.attr('data-romo-option-list-dropdown-filter-indicator-width-px', this.elem.data('romo-select-dropdown-filter-indicator-width-px'));
  }
  if (this.elem.data('romo-select-dropdown-open-on-focus') !== undefined) {
    this.elem.attr('data-romo-option-list-dropdown-open-on-focus', this.elem.data('romo-select-dropdown-open-on-focus'));
  }

  this.elem.on('romoOptionListDropdown:dropdown:toggle', $.proxy(function(e, dropdown) {
    this.elem.trigger('selectDropdown:dropdown:toggle', [dropdown, this]);
  }, this));
  this.elem.on('romoOptionListDropdown:dropdown:popupOpen', $.proxy(function(e, dropdown) {
    this.elem.trigger('selectDropdown:dropdown:popupOpen', [dropdown, this]);
  }, this));
  this.elem.on('romoOptionListDropdown:dropdown:popupClose', $.proxy(function(e, dropdown) {
    this.elem.trigger('selectDropdown:dropdown:popupClose', [dropdown, this]);
  }, this));
  this.elem.on('romoOptionListDropdown:itemSelected', $.proxy(function(e, itemValue, itemDisplayText, romoOptionListDropdown) {
    this.elem.trigger('selectDropdown:itemSelected', [itemValue, itemDisplayText, this]);
  }, this));
  this.elem.on('romoOptionListDropdown:newItemSelected', $.proxy(function(e, itemValue, itemDisplayText, romoOptionListDropdown) {
    var custOptElem = this.optionElemsParent.find('OPTION[data-romo-select-dropdown-custom-option="true"]');
    if (this.optionElemsParent.find('OPTION[value="'+itemValue+'"]').length === 0){
      // a custom value is being selected. add a custom option elem and update its value/text
      if (custOptElem.length === 0) {
        this.optionElemsParent.append('<option data-romo-select-dropdown-custom-option="true"></option>');
        custOptElem = this.optionElemsParent.find('OPTION[data-romo-select-dropdown-custom-option="true"]');
      }
      custOptElem.attr('value', itemValue);
      custOptElem.text(itemDisplayText);
    } else if (custOptElem.length !== 0) {
      // a non custom value is being selected. remove any existing custom option
      custOptElem.remove();
    }
    this.elem.trigger('selectDropdown:newItemSelected', [itemValue, itemDisplayText, this]);
  }, this));
  this.elem.on('romoOptionListDropdown:change', $.proxy(function(e, newValue, prevValue, romoOptionListDropdown) {
    this.elem.trigger('selectDropdown:change', [newValue, prevValue, this]);
  }, this));

  this.elem.on('selectDropdown:triggerToggle', $.proxy(function(e) {
    this.elem.trigger('romoOptionListDropdown:triggerToggle', []);
  }, this));
  this.elem.on('selectDropdown:triggerPopupOpen', $.proxy(function(e) {
    this.elem.trigger('romoOptionListDropdown:triggerPopupOpen', []);
  }, this));
  this.elem.on('selectDropdown:triggerPopupClose', $.proxy(function(e) {
    this.elem.trigger('romoOptionListDropdown:triggerPopupClose', []);
  }, this));

  this.romoOptionListDropdown = this.elem.romoOptionListDropdown()[0];

  this.elem.on('romoOptionListDropdown:filterChange', $.proxy(function(e, filterValue, romoOptionListDropdown) {
    var elems    = this.optionElemsParent.find('OPTION');
    var wbFilter = new RomoWordBoundaryFilter(filterValue, elems, function(elem) {
      // The romo word boundary filter by default considers a space, "-" and "_"
      // as word boundaries.  We want to also consider other non-word characters
      // (such as ":", "/", ".", "?", "=", "&") as word boundaries as well.
      return elem[0].textContent.replace(/\W/g, ' ');
    });

    wbFilter.matchingElems.removeClass(this.filterHiddenClass);
    wbFilter.notMatchingElems.addClass(this.filterHiddenClass);
    this._setListItems();

    if (filterValue !== '') {
      this.romoOptionListDropdown.elem.trigger('romoOptionListDropdown:triggerListOptionsUpdate', [this.optItemElems().first()]);
    } else {
      this.elem.trigger('romoOptionListDropdown:triggerListOptionsUpdate', [this.selectedItemElem()]);
    }
  }, this));

  this._sanitizeOptions();
  this._setListItems();
  this.elem.trigger('romoOptionListDropdown:triggerListOptionsUpdate', [this.selectedItemElem()]);
}

RomoSelectDropdown.prototype._sanitizeOptions = function() {
  // set any options without a value to value=""
  // all options are required to have a value for things to work
  // this and the select component assume value attrs for all options
  $.each(this.optionElemsParent.find('OPTION'), $.proxy(function(idx, optionNode) {
    var optElem = $(optionNode);
    if (optElem.attr('value') === undefined) {
      optElem.attr('value', '');
    }
  }, this));
}

RomoSelectDropdown.prototype._setListItems = function() {
  var optElems = this.optionElemsParent.children(this.optionElemSelector);
  var items    = this._buildOptionListItems(optElems).concat(this._buildCustomOptionItems());
  this.romoOptionListDropdown.doSetListItems(items);
}

RomoSelectDropdown.prototype._buildOptionListItems = function(optionElems) {
  var list = [];

  $.each(optionElems, $.proxy(function(idx, optionNode) {
    if (optionNode.tagName === "OPTION") {
      list.push(this._buildOptionItem($(optionNode)));
    } else if (optionNode.tagName === "OPTGROUP") {
      var optGroupItem = this._buildOptGroupItem($(optionNode));
      if (optGroupItem.items.length !== 0) {
        list.push(optGroupItem);
      }
    }
  }, this));

  return list;
}

RomoSelectDropdown.prototype._buildOptionItem = function(optionElem) {
  var item = {}

  item['type']        = 'option';
  item['value']       = (optionElem.attr('value') || '');
  item['displayText'] = (optionElem.text().trim() || '');
  item['displayHtml'] = (optionElem.text().trim() || ' ');

  if (optionElem.prop('selected')) {
    item['selected'] = true;
  }
  if (optionElem.attr('disabled') !== undefined) {
    item['disabled'] = true;
  }

  return item;
}

RomoSelectDropdown.prototype._buildOptGroupItem = function(optGroupElem) {
  var item = {};

  item['type']  = 'optgroup';
  item['label'] = optGroupElem.attr('label');
  item['items'] = this._buildOptionListItems(optGroupElem.children(this.optionElemSelector));

  return item;
}

RomoSelectDropdown.prototype._buildCustomOptionItems = function() {
  var items = [];

  var value = this.romoOptionListDropdown.optionFilterValue();
  if (value !== '' && this.elem.data('romo-select-dropdown-custom-option') === true) {
    var prompt = this.elem.data('romo-select-dropdown-custom-option-prompt');
    if (prompt !== undefined) {
      items.push({
        'type':  'optgroup',
        'label': prompt,
        'items': [this._buildCustomOptionItem(value)]
      });
    } else {
      items.push(this._buildCustomOptionItem(value));
    }
  }

  return items;
}

RomoSelectDropdown.prototype._buildCustomOptionItem = function(value) {
  return {
    'type':        'option',
    'value':       value,
    'displayText': value,
    'displayHtml': value
  };
}

Romo.onInitUI(function(e) {
  Romo.initUIElems(e, '[data-romo-select-dropdown-auto="true"]').romoSelectDropdown();
});
<|endoftext|>


<commit_before>setInterval(() => {
  var a = new Date();
  if (a.getDay() < 6 && a.getHours() > 6 && a.getHours() < 20) {
    chrome.power.requestKeepAwake("display");
  } else {
    chrome.power.releaseKeepAwake();
  }
}, 60 * 1000);
<commit_msg>Keep system awake always<commit_after>chrome.power.requestKeepAwake("display");
<|endoftext|>


<commit_before>/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */

/**
 * A directive for displaying an arbitrary login form.
 */
angular.module('login').directive('guacLogin', [function guacLogin() {

    // Login directive
    var directive = {
        restrict    : 'E',
        replace     : true,
        templateUrl : 'app/login/templates/login.html'
    };

    // Login directive scope
    directive.scope = {

        /**
         * An optional instructional message to display within the login
         * dialog.
         *
         * @type TranslatableMessage
         */
        helpText : '=',

        /**
         * The login form or set of fields. This will be displayed to the user
         * to capture their credentials.
         *
         * @type Field[]
         */
        form : '=',

        /**
         * A map of all field name/value pairs that have already been provided.
         * If not null, the user will be prompted to continue their login
         * attempt using only the fields which remain.
         */
        values : '='

    };

    // Controller for login directive
    directive.controller = ['$scope', '$injector',
        function loginController($scope, $injector) {

        // Required types
        var Error = $injector.get('Error');
        var Field = $injector.get('Field');

        // Required services
        var $rootScope            = $injector.get('$rootScope');
        var $route                = $injector.get('$route');
        var authenticationService = $injector.get('authenticationService');
        var requestService        = $injector.get('requestService');

        /**
         * A description of the error that occurred during login, if any.
         *
         * @type TranslatableMessage
         */
        $scope.loginError = null;

        /**
         * All form values entered by the user, as parameter name/value pairs.
         *
         * @type Object.<String, String>
         */
        $scope.enteredValues = {};

        /**
         * All form fields which have not yet been filled by the user.
         *
         * @type Field[]
         */
        $scope.remainingFields = [];

        /**
         * Whether an authentication attempt has been submitted. This will be
         * set to true once credentials have been submitted and will only be
         * reset to false once the attempt has been fully processed, including
         * rerouting the user to the requested page if the attempt succeeded.
         *
         * @type Boolean
         */
        $scope.submitted = false;

        /**
         * The field that is most relevant to the user.
         *
         * @type Field
         */
        $scope.relevantField = null;

        /**
         * Returns whether a previous login attempt is continuing.
         *
         * @return {Boolean}
         *     true if a previous login attempt is continuing, false otherwise.
         */
        $scope.isContinuation = function isContinuation() {

            // The login is continuing if any parameter values are provided
            for (var name in $scope.values)
                return true;

            return false;

        };

        // Ensure provided values are included within entered values, even if
        // they have no corresponding input fields
        $scope.$watch('values', function resetEnteredValues(values) {
            angular.extend($scope.enteredValues, values || {});
        });

        // Update field information when form is changed
        $scope.$watch('form', function resetRemainingFields(fields) {

            // If no fields are provided, then no fields remain
            if (!fields) {
                $scope.remainingFields = [];
                return;
            }

            // Filter provided fields against provided values
            $scope.remainingFields = fields.filter(function isRemaining(field) {
                return !(field.name in $scope.values);
            });

            // Set default values for all unset fields
            angular.forEach($scope.remainingFields, function setDefault(field) {
                if (!$scope.enteredValues[field.name])
                    $scope.enteredValues[field.name] = '';
            });

            $scope.relevantField = getRelevantField();

        });

        /**
         * Submits the currently-specified username and password to the
         * authentication service, redirecting to the main view if successful.
         */
        $scope.login = function login() {

            // Authentication is now in progress
            $scope.submitted = true;

            // Start with cleared status
            $scope.loginError = null;

            // Attempt login once existing session is destroyed
            authenticationService.authenticate($scope.enteredValues)

            // Retry route upon success (entered values will be cleared only
            // after route change has succeeded as this can take time)
            .then(function loginSuccessful() {
                $route.reload();
            })

            // Reset upon failure
            ['catch'](requestService.createErrorCallback(function loginFailed(error) {

                // Initial submission is complete and has failed
                $scope.submitted = false;

                // Clear out passwords if the credentials were rejected for any reason
                if (error.type !== Error.Type.INSUFFICIENT_CREDENTIALS) {

                    // Flag generic error for invalid login
                    if (error.type === Error.Type.INVALID_CREDENTIALS)
                        $scope.loginError = {
                            'key' : 'LOGIN.ERROR_INVALID_LOGIN'
                        };

                    // Display error if anything else goes wrong
                    else
                        $scope.loginError = error.translatableMessage;

                    // Clear all remaining fields that are not username fields
                    angular.forEach($scope.remainingFields, function clearEnteredValueIfPassword(field) {

                        // If field is not username field, delete it.
                        if (field.type !== Field.Type.USERNAME && field.name in $scope.enteredValues)
                            delete $scope.enteredValues[field.name];

                    });
                }

            }));

        };

        /**
         * Returns the field most relevant to the user given the current state
         * of the login process. This will normally be the first empty field.
         *
         * @return {Field}
         *     The field most relevant, null if there is no single most relevant
         *     field.
         */
        var getRelevantField = function getRelevantField() {

            for (var i = 0; i < $scope.remainingFields.length; i++) {
                var field = $scope.remainingFields[i];
                if (!$scope.enteredValues[field.name])
                    return field;
            }

            return null;

        };

        // Reset state after authentication and routing have succeeded
        $rootScope.$on('$routeChangeSuccess', function routeChanged() {
            $scope.enteredValues = {};
            $scope.submitted = false;
        });

    }];

    return directive;

}]);
<commit_msg>GUACAMOLE-1152: Ensure field values accurately represent login state.<commit_after>/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */

/**
 * A directive for displaying an arbitrary login form.
 */
angular.module('login').directive('guacLogin', [function guacLogin() {

    // Login directive
    var directive = {
        restrict    : 'E',
        replace     : true,
        templateUrl : 'app/login/templates/login.html'
    };

    // Login directive scope
    directive.scope = {

        /**
         * An optional instructional message to display within the login
         * dialog.
         *
         * @type TranslatableMessage
         */
        helpText : '=',

        /**
         * The login form or set of fields. This will be displayed to the user
         * to capture their credentials.
         *
         * @type Field[]
         */
        form : '=',

        /**
         * A map of all field name/value pairs that have already been provided.
         * If not null, the user will be prompted to continue their login
         * attempt using only the fields which remain.
         */
        values : '='

    };

    // Controller for login directive
    directive.controller = ['$scope', '$injector',
        function loginController($scope, $injector) {

        // Required types
        var Error = $injector.get('Error');
        var Field = $injector.get('Field');

        // Required services
        var $rootScope            = $injector.get('$rootScope');
        var $route                = $injector.get('$route');
        var authenticationService = $injector.get('authenticationService');
        var requestService        = $injector.get('requestService');

        /**
         * The initial value for all login fields. Note that this value must
         * not be null. If null, empty fields may not be submitted back to the
         * server at all, causing the request to misrepresent true login state.
         *
         * For example, if a user receives an insufficient credentials error
         * due to their password expiring, failing to provide that new password
         * should result in the user submitting their username, original
         * password, and empty new password. If only the username and original
         * password are sent, the invalid password reset request will be
         * indistinguishable from a normal login attempt.
         *
         * @constant
         * @type String
         */
        var DEFAULT_FIELD_VALUE = '';

        /**
         * A description of the error that occurred during login, if any.
         *
         * @type TranslatableMessage
         */
        $scope.loginError = null;

        /**
         * All form values entered by the user, as parameter name/value pairs.
         *
         * @type Object.<String, String>
         */
        $scope.enteredValues = {};

        /**
         * All form fields which have not yet been filled by the user.
         *
         * @type Field[]
         */
        $scope.remainingFields = [];

        /**
         * Whether an authentication attempt has been submitted. This will be
         * set to true once credentials have been submitted and will only be
         * reset to false once the attempt has been fully processed, including
         * rerouting the user to the requested page if the attempt succeeded.
         *
         * @type Boolean
         */
        $scope.submitted = false;

        /**
         * The field that is most relevant to the user.
         *
         * @type Field
         */
        $scope.relevantField = null;

        /**
         * Returns whether a previous login attempt is continuing.
         *
         * @return {Boolean}
         *     true if a previous login attempt is continuing, false otherwise.
         */
        $scope.isContinuation = function isContinuation() {

            // The login is continuing if any parameter values are provided
            for (var name in $scope.values)
                return true;

            return false;

        };

        // Ensure provided values are included within entered values, even if
        // they have no corresponding input fields
        $scope.$watch('values', function resetEnteredValues(values) {
            angular.extend($scope.enteredValues, values || {});
        });

        // Update field information when form is changed
        $scope.$watch('form', function resetRemainingFields(fields) {

            // If no fields are provided, then no fields remain
            if (!fields) {
                $scope.remainingFields = [];
                return;
            }

            // Filter provided fields against provided values
            $scope.remainingFields = fields.filter(function isRemaining(field) {
                return !(field.name in $scope.values);
            });

            // Set default values for all unset fields
            angular.forEach($scope.remainingFields, function setDefault(field) {
                if (!$scope.enteredValues[field.name])
                    $scope.enteredValues[field.name] = DEFAULT_FIELD_VALUE;
            });

            $scope.relevantField = getRelevantField();

        });

        /**
         * Submits the currently-specified username and password to the
         * authentication service, redirecting to the main view if successful.
         */
        $scope.login = function login() {

            // Authentication is now in progress
            $scope.submitted = true;

            // Start with cleared status
            $scope.loginError = null;

            // Attempt login once existing session is destroyed
            authenticationService.authenticate($scope.enteredValues)

            // Retry route upon success (entered values will be cleared only
            // after route change has succeeded as this can take time)
            .then(function loginSuccessful() {
                $route.reload();
            })

            // Reset upon failure
            ['catch'](requestService.createErrorCallback(function loginFailed(error) {

                // Initial submission is complete and has failed
                $scope.submitted = false;

                // Clear out passwords if the credentials were rejected for any reason
                if (error.type !== Error.Type.INSUFFICIENT_CREDENTIALS) {

                    // Flag generic error for invalid login
                    if (error.type === Error.Type.INVALID_CREDENTIALS)
                        $scope.loginError = {
                            'key' : 'LOGIN.ERROR_INVALID_LOGIN'
                        };

                    // Display error if anything else goes wrong
                    else
                        $scope.loginError = error.translatableMessage;

                    // Reset all remaining fields to default values, but
                    // preserve any usernames
                    angular.forEach($scope.remainingFields, function clearEnteredValueIfPassword(field) {
                        if (field.type !== Field.Type.USERNAME && field.name in $scope.enteredValues)
                            $scope.enteredValues[field.name] = DEFAULT_FIELD_VALUE;
                    });
                }

            }));

        };

        /**
         * Returns the field most relevant to the user given the current state
         * of the login process. This will normally be the first empty field.
         *
         * @return {Field}
         *     The field most relevant, null if there is no single most relevant
         *     field.
         */
        var getRelevantField = function getRelevantField() {

            for (var i = 0; i < $scope.remainingFields.length; i++) {
                var field = $scope.remainingFields[i];
                if (!$scope.enteredValues[field.name])
                    return field;
            }

            return null;

        };

        // Reset state after authentication and routing have succeeded
        $rootScope.$on('$routeChangeSuccess', function routeChanged() {
            $scope.enteredValues = {};
            $scope.submitted = false;
        });

    }];

    return directive;

}]);
<|endoftext|>


<commit_before>CATARSE.ProjectsNewView = Backbone.View.extend({
  initialize: function() {
    $('#header header nav.actions ul li.submit_project').addClass('selected');
    $('#add_reward').click(function(e){
      e.preventDefault()
      var new_reward = '

' + $($('.reward')[0]).html() + '
'
      new_reward = new_reward.replace(/\_0\_/g, '_' + rewards_id + '_')
      new_reward = new_reward.replace(/\[0\]/g, '[' + rewards_id + ']')
      new_reward = $(new_reward)
      new_reward.find('input').val(null)
      new_reward.find('.private').val("1").removeAttr('checked')
      new_reward.find('textarea').html(null)
      new_reward.find('input').numeric(false)
      new_reward.find('input, textarea').removeClass('ok').removeClass('error')
      $('#rewards_wrapper').append(new_reward)
      new_reward.find('textarea').focus()
      new_reward.find('.reward_expires_at').removeClass('hasDatepicker');
      new_reward.find('.reward_expires_at').datepicker({
        altFormat: 'dd/mm/yy',
        onSelect: everything_ok
      });

      rewards_count++
      rewards_id++
    })

    // A better selector for the cities
    $('#project_category_id').select2();

    function format (user) {
      if (user.loading) return user.name;

      var markup = "
" +
        "

" +
        "
" + user.name + "

";

      return markup;
    }

    function formatSelection (user) {
      return user.name;
    }

    $('#project_leader_id').select2({
      ajax: {
        url: "/users.json",
        dataType: 'json',
        delay: 500,
        data: function (params) {
          return {
            q: params.term,
            page: params.page
          };
        },
        processResults: function (data, params) {
          params.page = params.page || 1;

          return {
            results: data.items,
            pagination: {
              more: (params.page * 10) < data.total_count
            }
          };
        },
        cache: true
      },
      escapeMarkup: function (markup) { return markup; },
      minimumInputLength: 0,
      templateResult: format,
      templateSelection: formatSelection
    }).on("select2:select", function(e) {
        if ($('#project_leader_bio').val() == '') {
         $('#project_leader_bio').val(e.params.data.bio);
       }
    });

    $('#add_dynamic_field').click(function(e){
      e.preventDefault()
      var new_dynamic_field = '

' + $($('.dynamic_field')[0]).html() + '
'
      new_dynamic_field = new_dynamic_field.replace(/\_0\_/g, '_' + dynamic_fields_id + '_')
      new_dynamic_field = new_dynamic_field.replace(/\[0\]/g, '[' + dynamic_fields_id + ']')
      new_dynamic_field = $(new_dynamic_field)
      new_dynamic_field.find('input').val(null)
      new_dynamic_field.find('input[type=checkbox]').attr('checked', false)
      new_dynamic_field.find('input, textarea').removeClass('ok').removeClass('error')
      $('#dynamic_fields_wrapper').append(new_dynamic_field)
      new_dynamic_field.find('textarea').focus()

      dynamic_fields_count++
      dynamic_fields_id++
    })

    // When clicking on a past location, set it as the event location
    $('span.past-location').click(function(e) {
      var past_location = e.currentTarget.innerText;
      $('#project_location').val(past_location);
    })

    var video_valid = null
    everything_ok = function(){
      var all_ok = true
      if(video_valid == null) {
        all_ok = false
        verify_video()
      }
      if(!ok('#project_name'))
        all_ok = false
      if(!video_ok())
        all_ok = false
      if(!ok('#project_about'))
        all_ok = false
      if(!headline_ok())
        all_ok = false
      if(!ok('#project_category_id'))
        all_ok = false
      if(!goal_ok())
        all_ok = false
      if(!expires_at_ok())
        all_ok = false
      if(!rewards_ok())
        all_ok = false
      if(!dynamic_fields_ok())
        all_ok = false
      if(!accepted_terms())
        all_ok = false
      if(!ok('#project_when_short'))
        all_ok = false
      if(!ok('#project_when_long'))
        all_ok = false
      if(!ok('#project_location'))
        all_ok = false
      $('#project_image_url, #project_leader_id, #project_leader_bio').addClass('ok')
      if(all_ok){
        $('#project_submit').attr('disabled', false)
      } else {
        $('#project_submit').attr('disabled', true)
      }
    }
    ok = function(id){
      var value = $(id).val()
      if(value && value.length > 0){
        $(id).addClass("ok").removeClass("error")
        return true
      } else {
        $(id).addClass("error").removeClass("ok")
        return false
      }
    }
    verify_video = function(){
      video_valid = false
      $('#project_video_url').val($('#project_video_url').val().replace("https", "http"))
      if(/http:\/\/(www\.)?vimeo.com\/(\d+)/.test($('#project_video_url').val())) {
        $('#project_video_url').removeClass("ok").removeClass("error").addClass('loading')
        $.get('/projects/vimeo/?url='+$('#project_video_url').val(), function(r){
          $('#project_video_url').removeClass("loading")
          if(r.id==false){
            video_valid = false
          } else {
            video_valid = true
          }
          everything_ok()
        })
      } else {
				if($('#project_video_url').val() == ""){
					video_valid = true;
				 $('#project_video_url').removeClass("ok").removeClass("error").addClass('ok')
				}
			}
      everything_ok()
    }
    video_ok = function(){
      if(video_valid){
        $('#project_video_url').addClass("ok").removeClass("error")
        return true
      } else {
        if(!$('#project_video_url').hasClass('loading'))
          $('#project_video_url').addClass("error").removeClass("ok")
        return false
      }
    }
    headline_ok = function(){
      var value = $('#project_headline').val()
      if(value && value.length > 0 && value.length <= 140){
        $('#project_headline').addClass("ok").removeClass("error")
        return true
      } else {
        $('#project_headline').addClass("error").removeClass("ok")
        return false
      }
    }
    goal_ok = function(){
      var value = $('#project_goal').val()
      if(/^(\d+)$/.test(value) && parseInt(value) > 0){
        $('#project_goal').addClass("ok").removeClass("error")
        return true
      } else {
        $('#project_goal').addClass("error").removeClass("ok")
        return false
      }
    }
    expires_at_ok = function(){
      var value = /^(\d{2})\/(\d{2})\/(\d{4})?$/.exec($('#project_expires_at').val())
      if(value && value.length == 4) {
        var year = parseFloat(value[3])
        var month = parseFloat(value[2])-1
        var day = parseFloat(value[1])
        var date = new Date(year, month, day)
        var current_date = new Date()
        if(((day==date.getDate()) && (month==date.getMonth()) && (year==date.getFullYear())) && date > current_date){
          $('#project_expires_at').addClass("ok").removeClass("error")
          return true
        } else {
          $('#project_expires_at').addClass("error").removeClass("ok")
          return false
        }
      } else {
        $('#project_expires_at').addClass("error").removeClass("ok")
        return false
      }
    }
    rewards_ok = function(){
      var okey = true
      $('.reward input').each(function(){
        if(/^(\d+)$/.test($(this).val())){
          if(/minimum_value/.test($(this).attr('id'))){
            if(parseInt($(this).val()) >= 0) {
              $(this).addClass("ok").removeClass("error")
            } else {
              $(this).addClass("error").removeClass("ok")
              okey = false
            }
          } else {
            $(this).addClass("ok").removeClass("error")
          }
        } else {
          if(/maximum_backers/.test($(this).attr('id')) && (!$(this).val())){
            $(this).addClass("ok").removeClass("error")
          } else if(/private/.test($(this).attr('id')) && (!$(this).val()) || $(this).attr('id') === undefined || /expires_at/.test($(this).attr('id')) && (!$(this).val() || /expires_at/.test($(this).attr('id')) && $(this).val() )){
            $(this).addClass("ok").removeClass("error")
          }else {
            $(this).addClass("error").removeClass("ok")
            okey = false
            console.log($(this).attr('id'));
          }
        }
      })
      $('.reward textarea').each(function(){
        if($(this).val() && $(this).val().length > 0){
          $(this).addClass("ok").removeClass("error")
        } else {
          $(this).addClass("error").removeClass("ok")
          okey = false
        }
      })
      return okey
    }

    dynamic_fields_ok = function(){
      if(!$('#has_dynamic_fields').is(':checked')){
        $('.dynamic_field input').each(function(){
          if(/input_name/.test($(this).attr('id'))){
              $(this).addClass("ok").removeClass("error")
          }
        })
        return true
      }
      var okey = true
      $('.dynamic_field input').each(function(){
          if(/input_name/.test($(this).attr('id'))){
             if($(this).val() && $(this).val().length > 0){
              $(this).addClass("ok").removeClass("error")
            } else {
              $(this).addClass("error").removeClass("ok")
              okey = false
            }
          }
      })
      return okey
    }

    accepted_terms = function(){
      return $('#accept').is(':checked')
    }
    $('#project_name').keyup(everything_ok)
    $('#project_video_url').keyup(function(){ video_valid = false; everything_ok() })
    $('#project_video_url').timedKeyup(verify_video)
    $('#project_about').keyup(everything_ok)
    $('#project_category_id').change(everything_ok)
    $('#project_goal').keyup(everything_ok)
    $('#project_expires_at').keyup(everything_ok)
    $('#project_headline').keyup(everything_ok)
    $('#project_when_short').keyup(everything_ok)
    $('#project_when_long').keyup(everything_ok)
    $('#project_location').keyup(everything_ok)
    $('#project_image_url').keyup(everything_ok)
    $('#project_leader_id').keyup(everything_ok)
    $('#project_leader_bio').keyup(everything_ok)
    $('#accept').click(everything_ok)
    $('.reward input,.reward textarea').live('keyup', everything_ok)
    $('.dynamic_field input').live('keyup', everything_ok)
    $('.dynamic_field input').live('keyup', function(){
      $('#has_dynamic_fields').attr('checked', true)
    })
    $('#has_dynamic_fields').click(everything_ok)

    $('#project_goal').numeric(false)
    $('.reward input').numeric(false)
    $('#project_expires_at, .reward_expires_at').datepicker({
      altFormat: 'dd/mm/yy',
      onSelect: everything_ok
    })
    $('#ui-datepicker-div').css('display', 'none')
    $('input,textarea,select').live('focus', function(){
      $('p.inline-hints').hide()
      $(this).next('p.inline-hints').show()
      $('.boolean p.inline-hints').show()
    })
    $('.reward').live('mouseover', function(){
      $('.remove_reward').hide()
      if(rewards_count > 1){
        $(this).find('.remove_reward').show()
      }
    })
    $('.reward').live('mouseout', function(){
      $(this).find('.remove_reward').hide()
    })
    $('.remove_reward').live('click', function(e){
      e.preventDefault()
      if(rewards_count > 1){
        reward = $(this).parentsUntil('.reward').parent()
        reward.remove()
        rewards_count--
      }
    })

    $('.dynamic_field').live('mouseover', function(){
      $('.remove_dynamic_field').hide()
      if(dynamic_fields_count > 1){
        $(this).find('.remove_dynamic_field').show()
      }
    })
    $('.dynamic_field').live('mouseout', function(){
      $(this).find('.remove_dynamic_field').hide()
    })
    $('.remove_dynamic_field').live('click', function(e){
      e.preventDefault()
      if(dynamic_fields_count > 1){
        dynamic_field = $(this).parentsUntil('.dynamic_field').parent()
        dynamic_field.remove()
        dynamic_fields_count--
        dynamic_fields_id--
      }
    })

    $('#project_name').focus()
    $('textarea').maxlength()
  }
})
<commit_msg>Fix creating project with youtube videos<commit_after>CATARSE.ProjectsNewView = Backbone.View.extend({
  initialize: function() {
    $('#header header nav.actions ul li.submit_project').addClass('selected');
    $('#add_reward').click(function(e){
      e.preventDefault()
      var new_reward = '

' + $($('.reward')[0]).html() + '
'
      new_reward = new_reward.replace(/\_0\_/g, '_' + rewards_id + '_')
      new_reward = new_reward.replace(/\[0\]/g, '[' + rewards_id + ']')
      new_reward = $(new_reward)
      new_reward.find('input').val(null)
      new_reward.find('.private').val("1").removeAttr('checked')
      new_reward.find('textarea').html(null)
      new_reward.find('input').numeric(false)
      new_reward.find('input, textarea').removeClass('ok').removeClass('error')
      $('#rewards_wrapper').append(new_reward)
      new_reward.find('textarea').focus()
      new_reward.find('.reward_expires_at').removeClass('hasDatepicker');
      new_reward.find('.reward_expires_at').datepicker({
        altFormat: 'dd/mm/yy',
        onSelect: everything_ok
      });

      rewards_count++
      rewards_id++
    })

    // A better selector for the cities
    $('#project_category_id').select2();

    function format (user) {
      if (user.loading) return user.name;

      var markup = "
" +
        "

" +
        "
" + user.name + "

";

      return markup;
    }

    function formatSelection (user) {
      return user.name;
    }

    $('#project_leader_id').select2({
      ajax: {
        url: "/users.json",
        dataType: 'json',
        delay: 500,
        data: function (params) {
          return {
            q: params.term,
            page: params.page
          };
        },
        processResults: function (data, params) {
          params.page = params.page || 1;

          return {
            results: data.items,
            pagination: {
              more: (params.page * 10) < data.total_count
            }
          };
        },
        cache: true
      },
      escapeMarkup: function (markup) { return markup; },
      minimumInputLength: 0,
      templateResult: format,
      templateSelection: formatSelection
    }).on("select2:select", function(e) {
        if ($('#project_leader_bio').val() == '') {
         $('#project_leader_bio').val(e.params.data.bio);
       }
    });

    $('#add_dynamic_field').click(function(e){
      e.preventDefault()
      var new_dynamic_field = '

' + $($('.dynamic_field')[0]).html() + '
'
      new_dynamic_field = new_dynamic_field.replace(/\_0\_/g, '_' + dynamic_fields_id + '_')
      new_dynamic_field = new_dynamic_field.replace(/\[0\]/g, '[' + dynamic_fields_id + ']')
      new_dynamic_field = $(new_dynamic_field)
      new_dynamic_field.find('input').val(null)
      new_dynamic_field.find('input[type=checkbox]').attr('checked', false)
      new_dynamic_field.find('input, textarea').removeClass('ok').removeClass('error')
      $('#dynamic_fields_wrapper').append(new_dynamic_field)
      new_dynamic_field.find('textarea').focus()

      dynamic_fields_count++
      dynamic_fields_id++
    })

    // When clicking on a past location, set it as the event location
    $('span.past-location').click(function(e) {
      var past_location = e.currentTarget.innerText;
      $('#project_location').val(past_location);
    })

    var video_valid = null
    everything_ok = function(){
      var all_ok = true
      if(video_valid == null) {
        all_ok = false
        verify_video()
      }
      if(!ok('#project_name'))
        all_ok = false
      if(!video_ok())
        all_ok = false
      if(!ok('#project_about'))
        all_ok = false
      if(!headline_ok())
        all_ok = false
      if(!ok('#project_category_id'))
        all_ok = false
      if(!goal_ok())
        all_ok = false
      if(!expires_at_ok())
        all_ok = false
      if(!rewards_ok())
        all_ok = false
      if(!dynamic_fields_ok())
        all_ok = false
      if(!accepted_terms())
        all_ok = false
      if(!ok('#project_when_short'))
        all_ok = false
      if(!ok('#project_when_long'))
        all_ok = false
      if(!ok('#project_location'))
        all_ok = false
      $('#project_image_url, #project_leader_id, #project_leader_bio').addClass('ok')
      if(all_ok){
        $('#project_submit').attr('disabled', false)
      } else {
        $('#project_submit').attr('disabled', true)
      }
    }
    ok = function(id){
      var value = $(id).val()
      if(value && value.length > 0){
        $(id).addClass("ok").removeClass("error")
        return true
      } else {
        $(id).addClass("error").removeClass("ok")
        return false
      }
    }
    verify_video = function(){
      video_valid = false
      if(/https?:\/\/(www\.)?vimeo.com\/(\d+)|https?:\/\/(www\.)?youtube\.com|https?:\/\/(www\.)?youtu\.?be\/.+/.test($('#project_video_url').val())) {
        video_valid = true
        everything_ok()
      } else {
        if($('#project_video_url').val() == "") {
          video_valid = true
          $('#project_video_url').removeClass("ok").removeClass("error").addClass('ok')
         }
         everything_ok()
      }
    }

    video_ok = function(){
      if(video_valid){
        $('#project_video_url').addClass("ok").removeClass("error")
        return true
      } else {
        if(!$('#project_video_url').hasClass('loading'))
          $('#project_video_url').addClass("error").removeClass("ok")
        return false
      }
    }

    headline_ok = function(){
      var value = $('#project_headline').val()
      if(value && value.length > 0 && value.length <= 140){
        $('#project_headline').addClass("ok").removeClass("error")
        return true
      } else {
        $('#project_headline').addClass("error").removeClass("ok")
        return false
      }
    }
    goal_ok = function(){
      var value = $('#project_goal').val()
      if(/^(\d+)$/.test(value) && parseInt(value) > 0){
        $('#project_goal').addClass("ok").removeClass("error")
        return true
      } else {
        $('#project_goal').addClass("error").removeClass("ok")
        return false
      }
    }
    expires_at_ok = function(){
      var value = /^(\d{2})\/(\d{2})\/(\d{4})?$/.exec($('#project_expires_at').val())
      if(value && value.length == 4) {
        var year = parseFloat(value[3])
        var month = parseFloat(value[2])-1
        var day = parseFloat(value[1])
        var date = new Date(year, month, day)
        var current_date = new Date()
        if(((day==date.getDate()) && (month==date.getMonth()) && (year==date.getFullYear())) && date > current_date){
          $('#project_expires_at').addClass("ok").removeClass("error")
          return true
        } else {
          $('#project_expires_at').addClass("error").removeClass("ok")
          return false
        }
      } else {
        $('#project_expires_at').addClass("error").removeClass("ok")
        return false
      }
    }
    rewards_ok = function(){
      var okey = true
      $('.reward input').each(function(){
        if(/^(\d+)$/.test($(this).val())){
          if(/minimum_value/.test($(this).attr('id'))){
            if(parseInt($(this).val()) >= 0) {
              $(this).addClass("ok").removeClass("error")
            } else {
              $(this).addClass("error").removeClass("ok")
              okey = false
            }
          } else {
            $(this).addClass("ok").removeClass("error")
          }
        } else {
          if(/maximum_backers/.test($(this).attr('id')) && (!$(this).val())){
            $(this).addClass("ok").removeClass("error")
          } else if(/private/.test($(this).attr('id')) && (!$(this).val()) || $(this).attr('id') === undefined || /expires_at/.test($(this).attr('id')) && (!$(this).val() || /expires_at/.test($(this).attr('id')) && $(this).val() )){
            $(this).addClass("ok").removeClass("error")
          }else {
            $(this).addClass("error").removeClass("ok")
            okey = false
            console.log($(this).attr('id'));
          }
        }
      })
      $('.reward textarea').each(function(){
        if($(this).val() && $(this).val().length > 0){
          $(this).addClass("ok").removeClass("error")
        } else {
          $(this).addClass("error").removeClass("ok")
          okey = false
        }
      })
      return okey
    }

    dynamic_fields_ok = function(){
      if(!$('#has_dynamic_fields').is(':checked')){
        $('.dynamic_field input').each(function(){
          if(/input_name/.test($(this).attr('id'))){
              $(this).addClass("ok").removeClass("error")
          }
        })
        return true
      }
      var okey = true
      $('.dynamic_field input').each(function(){
          if(/input_name/.test($(this).attr('id'))){
             if($(this).val() && $(this).val().length > 0){
              $(this).addClass("ok").removeClass("error")
            } else {
              $(this).addClass("error").removeClass("ok")
              okey = false
            }
          }
      })
      return okey
    }

    accepted_terms = function(){
      return $('#accept').is(':checked')
    }
    $('#project_name').keyup(everything_ok)
    $('#project_video_url').keyup(function(){ video_valid = false; everything_ok() })
    $('#project_video_url').timedKeyup(verify_video)
    $('#project_about').keyup(everything_ok)
    $('#project_category_id').change(everything_ok)
    $('#project_goal').keyup(everything_ok)
    $('#project_expires_at').keyup(everything_ok)
    $('#project_headline').keyup(everything_ok)
    $('#project_when_short').keyup(everything_ok)
    $('#project_when_long').keyup(everything_ok)
    $('#project_location').keyup(everything_ok)
    $('#project_image_url').keyup(everything_ok)
    $('#project_leader_id').keyup(everything_ok)
    $('#project_leader_bio').keyup(everything_ok)
    $('#accept').click(everything_ok)
    $('.reward input,.reward textarea').live('keyup', everything_ok)
    $('.dynamic_field input').live('keyup', everything_ok)
    $('.dynamic_field input').live('keyup', function(){
      $('#has_dynamic_fields').attr('checked', true)
    })
    $('#has_dynamic_fields').click(everything_ok)

    $('#project_goal').numeric(false)
    $('.reward input').numeric(false)
    $('#project_expires_at, .reward_expires_at').datepicker({
      altFormat: 'dd/mm/yy',
      onSelect: everything_ok
    })
    $('#ui-datepicker-div').css('display', 'none')
    $('input,textarea,select').live('focus', function(){
      $('p.inline-hints').hide()
      $(this).next('p.inline-hints').show()
      $('.boolean p.inline-hints').show()
    })
    $('.reward').live('mouseover', function(){
      $('.remove_reward').hide()
      if(rewards_count > 1){
        $(this).find('.remove_reward').show()
      }
    })
    $('.reward').live('mouseout', function(){
      $(this).find('.remove_reward').hide()
    })
    $('.remove_reward').live('click', function(e){
      e.preventDefault()
      if(rewards_count > 1){
        reward = $(this).parentsUntil('.reward').parent()
        reward.remove()
        rewards_count--
      }
    })

    $('.dynamic_field').live('mouseover', function(){
      $('.remove_dynamic_field').hide()
      if(dynamic_fields_count > 1){
        $(this).find('.remove_dynamic_field').show()
      }
    })
    $('.dynamic_field').live('mouseout', function(){
      $(this).find('.remove_dynamic_field').hide()
    })
    $('.remove_dynamic_field').live('click', function(e){
      e.preventDefault()
      if(dynamic_fields_count > 1){
        dynamic_field = $(this).parentsUntil('.dynamic_field').parent()
        dynamic_field.remove()
        dynamic_fields_count--
        dynamic_fields_id--
      }
    })

    $('#project_name').focus()
    $('textarea').maxlength()
  }
})
<|endoftext|>


<commit_before>'use strict';

module.exports = {
  env: { es6: true },
  extends: ['eslint:recommended'],
  root: true,
  rules: {
    'accessor-pairs': 'error',
    'array-bracket-spacing': ['error', 'never'],
    'array-callback-return': 'error',
    'arrow-parens': ['error', 'as-needed'],
    'arrow-spacing': 'error',
    'block-spacing': ['error', 'never'],
    'brace-style': 'error',
    'comma-dangle': ['error', 'always-multiline'],
    'comma-spacing': 'error',
    'comma-style': 'error',
    'computed-property-spacing': 'error',
    curly: 'error',
    'dot-location': ['error', 'property'],
    'dot-notation': 'error',
    'eol-last': 'error',
    eqeqeq: 'error',
    'func-call-spacing': 'error',
    indent: ['error', 2, {
      CallExpression: { arguments: 1 },
      FunctionDeclaration: { body: 1, parameters: 1 },
      FunctionExpression: { body: 1, parameters: 1 },
      MemberExpression: 1,
      SwitchCase: 1,
    }],
    'key-spacing': 'error',
    'keyword-spacing': 'error',
    'linebreak-style': ['error', 'unix'],
    'lines-around-directive': 'error',
    'max-len': ['error', 128],
    'max-statements-per-line': 'error',
    'new-parens': 'error',
    'no-caller': 'error',
    'no-catch-shadow': 'error',
    'no-console': 'error',
    'no-duplicate-imports': 'error',
    'no-else-return': 'error',
    'no-eval': 'error',
    'no-extra-bind': 'error',
    'no-extra-label': 'error',
    'no-extra-parens': ['error', 'all', { nestedBinaryExpressions: false }],
    'no-floating-decimal': 'error',
    'no-global-assign': 'error',
    'no-implied-eval': 'error',
    'no-label-var': 'error',
    'no-lone-blocks': 'error',
    'no-lonely-if': 'error',
    'no-mixed-operators': 'error',
    'no-multi-spaces': 'error',
    'no-new': 'error',
    'no-new-func': 'error',
    'no-new-object': 'error',
    'no-new-require': 'error',
    'no-octal-escape': 'error',
    'no-process-exit': 'error',
    'no-proto': 'error',
    'no-prototype-builtins': 'error',
    'no-restricted-properties': ['error', { object: 'describe', property: 'only' }, { object: 'it', property: 'only' }],
    'no-script-url': 'error',
    'no-self-compare': 'error',
    'no-sequences': 'error',
    'no-shadow': 'error',
    'no-tabs': 'error',
    'no-template-curly-in-string': 'error',
    'no-trailing-spaces': 'error',
    'no-unneeded-ternary': 'error',
    'no-unsafe-negation': 'error',
    'no-unused-expressions': 'error',
    'no-unused-vars': 'error',
    'no-useless-call': 'error',
    'no-useless-computed-key': 'error',
    'no-useless-concat': 'error',
    'no-useless-constructor': 'error',
    'no-useless-escape': 'error',
    'no-useless-return': 'error',
    'no-var': 'error',
    'no-void': 'error',
    'no-whitespace-before-property': 'error',
    'no-with': 'error',
    'object-curly-spacing': ['error', 'always'],
    'object-shorthand': 'error',
    'operator-assignment': 'error',
    'padded-blocks': ['error', 'never'],
    'prefer-arrow-callback': 'error',
    'prefer-const': 'error',
    'prefer-numeric-literals': 'error',
    'prefer-rest-params': 'error',
    'prefer-spread': 'error',
    'quote-props': ['error', 'as-needed'],
    quotes: ['error', 'single', 'avoid-escape'],
    semi: ['error', 'always'],
    'semi-spacing': 'error',
    'space-before-blocks': 'error',
    'space-before-function-paren': 'error',
    'space-in-parens': 'error',
    'space-infix-ops': 'error',
    'space-unary-ops': 'error',
    'spaced-comment': 'error',
    strict: ['error', 'global'],
    'template-curly-spacing': 'error',
    'unicode-bom': 'error',
    'valid-typeof': ['error', { requireStringLiterals: true }],
    'wrap-iife': 'error',
    yoda: 'error',
  },
};
<commit_msg>Update: disable max-len (#5)<commit_after>'use strict';

module.exports = {
  env: { es6: true },
  extends: ['eslint:recommended'],
  root: true,
  rules: {
    'accessor-pairs': 'error',
    'array-bracket-spacing': ['error', 'never'],
    'array-callback-return': 'error',
    'arrow-parens': ['error', 'as-needed'],
    'arrow-spacing': 'error',
    'block-spacing': ['error', 'never'],
    'brace-style': 'error',
    'comma-dangle': ['error', 'always-multiline'],
    'comma-spacing': 'error',
    'comma-style': 'error',
    'computed-property-spacing': 'error',
    curly: 'error',
    'dot-location': ['error', 'property'],
    'dot-notation': 'error',
    'eol-last': 'error',
    eqeqeq: 'error',
    'func-call-spacing': 'error',
    indent: ['error', 2, {
      CallExpression: { arguments: 1 },
      FunctionDeclaration: { body: 1, parameters: 1 },
      FunctionExpression: { body: 1, parameters: 1 },
      MemberExpression: 1,
      SwitchCase: 1,
    }],
    'key-spacing': 'error',
    'keyword-spacing': 'error',
    'linebreak-style': ['error', 'unix'],
    'lines-around-directive': 'error',
    'max-statements-per-line': 'error',
    'new-parens': 'error',
    'no-caller': 'error',
    'no-catch-shadow': 'error',
    'no-console': 'error',
    'no-duplicate-imports': 'error',
    'no-else-return': 'error',
    'no-eval': 'error',
    'no-extra-bind': 'error',
    'no-extra-label': 'error',
    'no-extra-parens': ['error', 'all', { nestedBinaryExpressions: false }],
    'no-floating-decimal': 'error',
    'no-global-assign': 'error',
    'no-implied-eval': 'error',
    'no-label-var': 'error',
    'no-lone-blocks': 'error',
    'no-lonely-if': 'error',
    'no-mixed-operators': 'error',
    'no-multi-spaces': 'error',
    'no-new': 'error',
    'no-new-func': 'error',
    'no-new-object': 'error',
    'no-new-require': 'error',
    'no-octal-escape': 'error',
    'no-process-exit': 'error',
    'no-proto': 'error',
    'no-prototype-builtins': 'error',
    'no-restricted-properties': ['error', { object: 'describe', property: 'only' }, { object: 'it', property: 'only' }],
    'no-script-url': 'error',
    'no-self-compare': 'error',
    'no-sequences': 'error',
    'no-shadow': 'error',
    'no-tabs': 'error',
    'no-template-curly-in-string': 'error',
    'no-trailing-spaces': 'error',
    'no-unneeded-ternary': 'error',
    'no-unsafe-negation': 'error',
    'no-unused-expressions': 'error',
    'no-unused-vars': 'error',
    'no-useless-call': 'error',
    'no-useless-computed-key': 'error',
    'no-useless-concat': 'error',
    'no-useless-constructor': 'error',
    'no-useless-escape': 'error',
    'no-useless-return': 'error',
    'no-var': 'error',
    'no-void': 'error',
    'no-whitespace-before-property': 'error',
    'no-with': 'error',
    'object-curly-spacing': ['error', 'always'],
    'object-shorthand': 'error',
    'operator-assignment': 'error',
    'padded-blocks': ['error', 'never'],
    'prefer-arrow-callback': 'error',
    'prefer-const': 'error',
    'prefer-numeric-literals': 'error',
    'prefer-rest-params': 'error',
    'prefer-spread': 'error',
    'quote-props': ['error', 'as-needed'],
    quotes: ['error', 'single', 'avoid-escape'],
    semi: ['error', 'always'],
    'semi-spacing': 'error',
    'space-before-blocks': 'error',
    'space-before-function-paren': 'error',
    'space-in-parens': 'error',
    'space-infix-ops': 'error',
    'space-unary-ops': 'error',
    'spaced-comment': 'error',
    strict: ['error', 'global'],
    'template-curly-spacing': 'error',
    'unicode-bom': 'error',
    'valid-typeof': ['error', { requireStringLiterals: true }],
    'wrap-iife': 'error',
    yoda: 'error',
  },
};
<|endoftext|>