<commit_before>/*  VELOCI - Web application for management races
	Copyright (C) 2014: Adrián Pérez López

	This program is free software: you can redistribute it and/or modify
	it under the terms of the GNU Affero General Public License as published by
	the Free Software Foundation, either version 3 of the License, or
	(at your option) any later version.

	This program is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	GNU Affero General Public License for more details.

	You should have received a copy of the GNU Affero General Public License
	along with this program.  If not, see [http://www.gnu.org/licenses/]. */

$('#registerModal').click( function() {
	$('#registerModal').modal();
});

$('#loginModal').click( function() {
	$('#loginModal').modal();
});

function generarCalendario(dia, mes) {
	var request;
    request = $.ajax({
        url: "/calendar.php",
        type: "GET",
        //data: {val: campo.value}
    });

    request.done(function(response, textStatus, jqXHR) {
		carreras = JSON.parse(response);
		dia = new Array();
		mes = new Array();
		for (var i = 0; i < carreras.length; i++) {
			arreglo = carreras[i]['fecha'].substr(5,10);
			dia[i] = arreglo[3] + "" + arreglo[4];
			mes[i] = arreglo[0] + "" + arreglo[1];
			console.log(carreras[i]['nombre'] + " dia " + dia[i] + " mes " + mes[i]);
		};
		return [
			dia, mes
		];
    });
	var fecha = new Date();
	var dias = new Array('L', 'M', 'X', 'J', 'V', 'S', 'D');
	var diasMes = new Array('31', '28', '31', '30', '31', '30', '31', '31', '30', '31', '30', '31');

	if (dia != null) {
		fecha.setDate(dia);
		hoy = dia;
	} else {
		var hoy = fecha.getDate();
	}

	if (mes != null) {
		mes--;
		fecha.setMonth(mes);
	} else {
		mes = fecha.getMonth();
	}

	// Localizo el día del comienzo del mes
	fecha.setDate(1);
	var diaUno = fecha.getDay();

	// Inicializo variables
	var i = 1;
	var j = 1;
	var cadena = "";

	cadena = "

"
	while (i <= 7) {
		cadena += "" + dias[i-1] + "	";
		i++;
	}
	cadena +="

";

	i = 0;
	while(i < diaUno-1) {
		cadena += "	";
		i++;
	}

	while (j <= diasMes[mes]) {
		if (i == 7) {
			cadena += "

";
			i = 0;
		};
		console.log(j + " vs " + dia[i]);
		if(j == dia[i])
			cadena += "" + j + "	";
		else
			cadena += "" + j + "	";

		j++;
		i++;
	}

	while (i < 7) {
		cadena += "	";
		i++;
	}

	cadena += "
"

	document.getElementById('calendario').innerHTML = cadena;
}

function compruebaNombre(campo) {
    var request;
    request = $.ajax({
        url: "/ajax.php",
        type: "GET",
        data: {tipo: 1, val: campo.value}
    });

    request.done(function(response, textStatus, jqXHR)
    {
        document.getElementById(campo.name).className = response;
        if (response == "form-group has-error") {
        	document.getElementById('errorUsuario').innerHTML = "Nombre de usuario ya registrado.";
        } else {
        	document.getElementById('errorUsuario').innerHTML = "";
        };
    });
}

function veNotificacion(usuario, notificacion) {
    var request;
    request = $.ajax({
        url: "/ajax.php",
        type: "GET",
        data: {tipo: 2, idUsuario: usuario, idNotificacion: notificacion}
    });
}

function veNotificacionAdmin(notificacion) {
    var request;
    request = $.ajax({
        url: "/ajax.php",
        type: "GET",
        data: {tipo: 3, idNotificacion: notificacion}
    });
}

function seleccionado(ruta, clase) {
	var radios = document.getElementsByClassName(clase);
	var botones = document.getElementsByClassName('btn-action');
	var error = true;

	for (var i = 0; i < radios.length; i++) {
		if (radios[i].checked) {
			for (var j = 0; j <= botones.length; j++) {
				var boton = botones[j];
				var fin = ruta.lastIndexOf("/");
				var enlace = ruta.substr(0, fin) + "/" + radios[i].value;
				boton.href = enlace;
			};
			error = false;
		};
	};

	if (error = true) {
		alert("Debe seleccionar un registro para continuar");
	}
}

function seleccion(radio) {
	var co = document.getElementById("co");
	co.value = radio.value;
}

function responder(idComentario, usuario) {
	document.getElementById('tcomentarios').innerHTML = " Responder a " + usuario
	+ "<button class='btn btn-danger pull-right btn-sm' onclick='cancelaRespuesta()'>Cancelar respuesta</button>";
	document.getElementById('responde').value = idComentario;
}

function cancelaRespuesta() {
	document.getElementById('tcomentarios').innerHTML = " Nuevo comentario
";
	document.getElementById('responde').value = 0;
}

function cambiarRuta(ruta) {
	var formulario = document.getElementById('v');
	formulario.action = ruta;
	formulario.submit();
}

function editarAsistencia(boton, piloto, carrera) {
	boton.parentNode.innerHTML = "<select name=" + piloto + "-" + carrera + ">" +
	"<option value='0'>Selección</option>" +
	"<option value='1'>Asiste</option>" +
	"<option value='2'>Justifica falta</option>" +
	"<option value='3'>Falta sin justificar</option>" +
	"<option value='4'>Sanción</option></select>";
}

function validarRegistro(myform) {
	var elementos = myform.elements.length;
	error = validar(myform.elements[0], 'errorUsuario', 'El nombre de usuario debe tener 4 caracteres o más', 1) ? false : true;

	console.log(error);

	return false;
}

function validar(campo, c_error, error, tipo) {
	var ayuda = document.getElementById(c_error);
	var rerror = true;

	switch(tipo) {
		case 1: // Nombre de usuario 4 caracteres o más
			if (campo.value.length <= 3) {
				document.getElementById('inputUsuario').className = "form-group has-error";
				ayuda.innerHTML = error;
			} else {
				document.getElementById('inputUsuario').className = "form-group has-success";
				rerror = false;
			};
		break;

		case 2: // Que las 2 contraseñas se correspondan en el formulario y cumplan el patrón
			if (campo.value.length <= 5) {
				document.getElementById('inputPassword1').className = "form-group has-error";
				ayuda.innerHTML = error;
			} else {
				document.getElementById('inputPassword1').className = "form-group has-success";
				ayuda.innerHTML = "";
				rerror = false;
			};
		break;

		case 3: // Comprobación de que el campo2 de contraseña coincide con el primero
			var pass1 = document.getElementById('pass1').value;
			console.log(campo.value + " = " + pass1);
			if (campo.value == pass1) {
				document.getElementById('inputPassword2').className = "form-group has-success";
				ayuda.innerHTML = "Las contraseñas coinciden";
				rerror = false;
			} else {
				document.getElementById('inputPassword2').className = "form-group has-error";
				ayuda.innerHTML = error;
			};
		break;

		case 4: // Comprobación de que el nombre es Nombre + Apellido
			var patron = /^[a-zA-Z]$/;
			if (patron.test(campo.value)) {
				document.getElementById('inputNombreCompleto').className = "form-group has-success";
				ayuda.innerHTML = "";
				rerror = false;
			} else {
				document.getElementById('inputNombreCompleto').className = "form-group has-error";
				ayuda.innerHTML = error;
			};
		break;

		case 5: // Comprobación de email
			var patron = /^([a-zA-Z0-9_.-])+@(([a-zA-Z0-9-])+.)+([a-zA-Z0-9]{2,4})+$/;;
			if (patron.test(campo.value)) {
				document.getElementById('inputEmail').className = "form-group has-success";
				ayuda.innerHTML = "";
				rerror = false;
			} else {
				document.getElementById('inputEmail').className = "form-group has-error";
				ayuda.innerHTML = error;
			};
		break;
	}

	return rerror;
}

function soloTexto(e) {
	tecla = (document.all) ? e.keyCode : e.which;
	if (tecla == 8) return true;
    if (e.ctrlKey && tecla == 86) { return true;}
    if (e.ctrlKey && tecla == 67) { return true;}
    if (e.ctrlKey && tecla == 88) { return true;}

    patron = /[a-zA-Z]/; //patron

    te = String.fromCharCode(tecla);
    return patron.test(te);
}

function rellenarSelect() {
	var myselect = document.getElementById('inputVueltas');
	for (var i = 2 ; i < 70; i++) {
		myselect.innerHTML += "<option value='" + i + "'>" + i + "</option>";
	};
}<commit_msg>Improved name function<commit_after>/*  VELOCI - Web application for management races
	Copyright (C) 2014: Adrián Pérez López

	This program is free software: you can redistribute it and/or modify
	it under the terms of the GNU Affero General Public License as published by
	the Free Software Foundation, either version 3 of the License, or
	(at your option) any later version.

	This program is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	GNU Affero General Public License for more details.

	You should have received a copy of the GNU Affero General Public License
	along with this program.  If not, see [http://www.gnu.org/licenses/]. */

$('#registerModal').click( function() {
	$('#registerModal').modal();
});

$('#loginModal').click( function() {
	$('#loginModal').modal();
});

function generarCalendario(dia, mes) {
	var request;
    request = $.ajax({
        url: "/calendar.php",
        type: "GET",
        //data: {val: campo.value}
    });

    request.done(function(response, textStatus, jqXHR) {
		carreras = JSON.parse(response);
		dia = new Array();
		mes = new Array();
		for (var i = 0; i < carreras.length; i++) {
			arreglo = carreras[i]['fecha'].substr(5,10);
			dia[i] = arreglo[3] + "" + arreglo[4];
			mes[i] = arreglo[0] + "" + arreglo[1];
			console.log(carreras[i]['nombre'] + " dia " + dia[i] + " mes " + mes[i]);
		};
		return [
			dia, mes
		];
    });
	var fecha = new Date();
	var dias = new Array('L', 'M', 'X', 'J', 'V', 'S', 'D');
	var diasMes = new Array('31', '28', '31', '30', '31', '30', '31', '31', '30', '31', '30', '31');

	if (dia != null) {
		fecha.setDate(dia);
		hoy = dia;
	} else {
		var hoy = fecha.getDate();
	}

	if (mes != null) {
		mes--;
		fecha.setMonth(mes);
	} else {
		mes = fecha.getMonth();
	}

	// Localizo el día del comienzo del mes
	fecha.setDate(1);
	var diaUno = fecha.getDay();

	// Inicializo variables
	var i = 1;
	var j = 1;
	var cadena = "";

	cadena = "

"
	while (i <= 7) {
		cadena += "" + dias[i-1] + "	";
		i++;
	}
	cadena +="

";

	i = 0;
	while(i < diaUno-1) {
		cadena += "	";
		i++;
	}

	while (j <= diasMes[mes]) {
		if (i == 7) {
			cadena += "

";
			i = 0;
		};
		console.log(j + " vs " + dia[i]);
		if(j == dia[i])
			cadena += "" + j + "	";
		else
			cadena += "" + j + "	";

		j++;
		i++;
	}

	while (i < 7) {
		cadena += "	";
		i++;
	}

	cadena += "
"

	document.getElementById('calendario').innerHTML = cadena;
}

function compruebaNombre(campo) {
    var request;
    request = $.ajax({
        url: "/ajax.php",
        type: "GET",
        data: {tipo: 1, val: campo.value}
    });

    request.done(function(response, textStatus, jqXHR)
    {
        document.getElementById(campo.name).className = response;
        if (response == "form-group has-error") {
        	document.getElementById('errorUsuario').innerHTML = "Nombre de usuario ya registrado.";
        } else {
        	document.getElementById('errorUsuario').innerHTML = "";
        };
    });
}

function veNotificacion(usuario, notificacion) {
    var request;
    request = $.ajax({
        url: "/ajax.php",
        type: "GET",
        data: {tipo: 2, idUsuario: usuario, idNotificacion: notificacion}
    });
}

function veNotificacionAdmin(notificacion) {
    var request;
    request = $.ajax({
        url: "/ajax.php",
        type: "GET",
        data: {tipo: 3, idNotificacion: notificacion}
    });
}

function seleccionado(ruta, clase) {
	var radios = document.getElementsByClassName(clase);
	var botones = document.getElementsByClassName('btn-action');
	var error = true;

	for (var i = 0; i < radios.length; i++) {
		if (radios[i].checked) {
			for (var j = 0; j <= botones.length; j++) {
				var boton = botones[j];
				var fin = ruta.lastIndexOf("/");
				var enlace = ruta.substr(0, fin) + "/" + radios[i].value;
				boton.href = enlace;
			};
			error = false;
		};
	};

	if (error = true) {
		alert("Debe seleccionar un registro para continuar");
	}
}

function seleccion(radio) {
	var co = document.getElementById("co");
	co.value = radio.value;
}

function responder(idComentario, usuario) {
	document.getElementById('tcomentarios').innerHTML = " Responder a " + usuario
	+ "<button class='btn btn-danger pull-right btn-sm' onclick='cancelaRespuesta()'>Cancelar respuesta</button>";
	document.getElementById('responde').value = idComentario;
}

function cancelaRespuesta() {
	document.getElementById('tcomentarios').innerHTML = " Nuevo comentario
";
	document.getElementById('responde').value = 0;
}

function cambiarRuta(ruta) {
	var formulario = document.getElementById('v');
	formulario.action = ruta;
	formulario.submit();
}

function editarAsistencia(boton, piloto, carrera) {
	boton.parentNode.innerHTML = "<select name=" + piloto + "-" + carrera + ">" +
	"<option value='0'>Selección</option>" +
	"<option value='1'>Asiste</option>" +
	"<option value='2'>Justifica falta</option>" +
	"<option value='3'>Falta sin justificar</option>" +
	"<option value='4'>Sanción</option></select>";
}

function validarRegistro(myform) {
	var elementos = myform.elements.length;
	error = validar(myform.elements[0], 'errorUsuario', 'El nombre de usuario debe tener 4 caracteres o más', 1) ? false : true;

	console.log(error);

	return false;
}

function validar(campo, c_error, error, tipo) {
	var ayuda = document.getElementById(c_error);
	var rerror = true;

	switch(tipo) {
		case 1: // Nombre de usuario 4 caracteres o más
			if (campo.value.length <= 3) {
				document.getElementById('inputUsuario').className = "form-group has-error";
				ayuda.innerHTML = error;
			} else {
				document.getElementById('inputUsuario').className = "form-group has-success";
				rerror = false;
			};
		break;

		case 2: // Que las 2 contraseñas se correspondan en el formulario y cumplan el patrón
			if (campo.value.length <= 5) {
				document.getElementById('inputPassword1').className = "form-group has-error";
				ayuda.innerHTML = error;
			} else {
				document.getElementById('inputPassword1').className = "form-group has-success";
				ayuda.innerHTML = "";
				rerror = false;
			};
		break;

		case 3: // Comprobación de que el campo2 de contraseña coincide con el primero
			var pass1 = document.getElementById('pass1').value;
			console.log(campo.value + " = " + pass1);
			if (campo.value == pass1) {
				document.getElementById('inputPassword2').className = "form-group has-success";
				ayuda.innerHTML = "Las contraseñas coinciden";
				rerror = false;
			} else {
				document.getElementById('inputPassword2').className = "form-group has-error";
				ayuda.innerHTML = error;
			};
		break;

		case 4: // Comprobación de que el nombre es Nombre + Apellido
			var patron = /^([a-z ñáéíóú]{2,60}\s[a-z ñáéíóú]{2,60})$/i;
			if (patron.test(campo.value)) {
				document.getElementById('inputNombreCompleto').className = "form-group has-success";
				ayuda.innerHTML = "";
				rerror = false;
			} else {
				document.getElementById('inputNombreCompleto').className = "form-group has-error";
				ayuda.innerHTML = error;
			};
		break;

		case 5: // Comprobación de email
			var patron = /^([a-zA-Z0-9_.-])+@(([a-zA-Z0-9-])+.)+([a-zA-Z0-9]{2,4})+$/;;
			if (patron.test(campo.value)) {
				document.getElementById('inputEmail').className = "form-group has-success";
				ayuda.innerHTML = "";
				rerror = false;
			} else {
				document.getElementById('inputEmail').className = "form-group has-error";
				ayuda.innerHTML = error;
			};
		break;
	}

	return rerror;
}

function soloTexto(e) {
	tecla = (document.all) ? e.keyCode : e.which;
	if (tecla == 8) return true;
    if (e.ctrlKey && tecla == 86) { return true;}
    if (e.ctrlKey && tecla == 67) { return true;}
    if (e.ctrlKey && tecla == 88) { return true;}

    patron = /[a-zA-Z ñáéíóú{4, 30}]/; //patron

    te = String.fromCharCode(tecla);
    return patron.test(te);
}

function rellenarSelect() {
	var myselect = document.getElementById('inputVueltas');
	for (var i = 2 ; i < 70; i++) {
		myselect.innerHTML += "<option value='" + i + "'>" + i + "</option>";
	};
}<|endoftext|>


<commit_before>// Copyright 2013-2020, University of Colorado Boulder

/**
 * AquaRadioButtonGroup creates a group of AquaRadioButtons and manages their layout.
 *
 * @author Sam Reid (PhET Interactive Simulations)
 * @author Chris Malley (PixelZoom, Inc.)
 */

import merge from '../../phet-core/js/merge.js';
import HStrut from '../../scenery/js/nodes/HStrut.js';
import LayoutBox from '../../scenery/js/nodes/LayoutBox.js';
import Node from '../../scenery/js/nodes/Node.js';
import radioButtonSoundPlayerFactory from '../../tambo/js/radioButtonSoundPlayerFactory.js';
import Tandem from '../../tandem/js/Tandem.js';
import AquaRadioButton from './AquaRadioButton.js';
import EnabledComponent from './EnabledComponent.js';
import sun from './sun.js';

// a11y - An id for each instance of AquaRadioButtonGroup, passed to individual buttons in the group.
// Each button in a radio button group must have the same "name" attribute to be considered in a group, otherwise
// arrow keys will navigate all radio type inputs in the document.
let instanceCount = 0;

// constants
// to prefix instanceCount in case there are different kinds of "groups"
const CLASS_NAME = 'AquaRadioButtonGroup';

/**
 * @mixes EnabledComponent
 */
class AquaRadioButtonGroup extends LayoutBox {

  /**
   * @param {Property} property
   * @param {Object[]} items - Each item describes a radio button, and is an object with these properties:
   *    node: Node, // label for the button
   *    value: *, // value associated with the button
   *    [tandemName: Tandem], // optional tandem for PhET-iO
   *    [labelContent: string] // optional label for a11y
   * @param {Object} [options]
   * @constructor
   */
  constructor( property, items, options ) {

    instanceCount++;

    options = merge( {

      // {Object|null} options passed to constructor of the AquaRadioButtons
      radioButtonOptions: null,

      // Dilation of pointer areas for each radio button.
      // These are not part of radioButtonOptions because AquaRadioButton has no pointerArea options.
      // X dilation is ignored for orientation === 'horizontal'.
      // Y dilation is ignored for orientation === 'vertical'.
      touchAreaXDilation: 0,
      touchAreaYDilation: 0,
      mouseAreaXDilation: 0,
      mouseAreaYDilation: 0,

      // supertype options
      orientation: 'vertical', // Aqua radio buttons are typically vertical, rarely horizontal
      spacing: 3, // space between each button, perpendicular to options.orientation

      // phet-io
      tandem: Tandem.REQUIRED,
      phetioComponentOptions: {
        visibleProperty: { phetioFeatured: true }
      },

      // PDOM
      tagName: 'ul',
      ariaRole: 'radiogroup',
      groupFocusHighlight: true
    }, options );

    // Determine the max item width
    const maxItemWidth = _.maxBy( items, item => item.node.width ).node.width;

    // Create a radio button for each item
    const radioButtons = [];
    for ( let i = 0; i < items.length; i++ ) {

      const item = items[ i ];

      // Content for the radio button.
      // For vertical orientation, add an invisible strut, so that buttons have uniform width.
      const content = ( options.orientation === 'vertical' ) ?
                      new Node( { children: [ new HStrut( maxItemWidth ), item.node ] } ) :
                      item.node;

      const radioButton = new AquaRadioButton( property, item.value, content,
        merge( {}, options.radioButtonOptions, {
          tandem: item.tandemName ? options.tandem.createTandem( item.tandemName ) : Tandem.REQUIRED,
          labelContent: item.labelContent || null,
          soundPlayer: radioButtonSoundPlayerFactory.getRadioButtonSoundPlayer( i ),
          a11yNameAttribute: CLASS_NAME + instanceCount
        } ) );

      // set pointer areas
      if ( options.orientation === 'vertical' ) {
        radioButton.mouseArea = radioButton.localBounds.dilatedXY( options.mouseAreaXDilation, options.spacing / 2 );
        radioButton.touchArea = radioButton.localBounds.dilatedXY( options.touchAreaXDilation, options.spacing / 2 );
      }
      else {
        radioButton.mouseArea = radioButton.localBounds.dilatedXY( options.spacing / 2, options.mouseAreaYDilation );
        radioButton.touchArea = radioButton.localBounds.dilatedXY( options.spacing / 2, options.touchAreaYDilation );
      }

      radioButtons.push( radioButton );
    }

    // Verify that the client hasn't set options that we will be overwriting.
    assert && assert( !options.children, 'AquaRadioButtonGroup sets children' );
    options.children = radioButtons;

    super( options );

    this.initializeEnabledComponent( options );

    // Add linked element after the radio button is instrumented
    this.addLinkedElement( property, {
      tandem: options.tandem.createTandem( 'property' )
    } );

    // @private
    this.disposeAquaRadioButtonGroup = () => {
      for ( let i = 0; i < radioButtons.length; i++ ) {
        radioButtons[ i ].dispose();
      }
    };

    // @private
    this.radioButtons = radioButtons;
  }

  /**
   * @public
   * @override
   */
  dispose() {
    this.disposeAquaRadioButtonGroup();
    this.disposeEnabledComponent();
    super.dispose();
  }

  /**
   * Gets the radio button that corresponds to the specified value.
   * @param {*} value
   * @returns {AquaRadioButton}
   */
  getButton( value ) {
    const button = _.find( this.radioButtons, radioButton => radioButton.value === value );
    assert && assert( button, `no radio button found for value ${value}` );
    return button;
  }
}

EnabledComponent.mixInto( AquaRadioButtonGroup );

sun.register( 'AquaRadioButtonGroup', AquaRadioButtonGroup );
export default AquaRadioButtonGroup;<commit_msg>AquaRadioButtonGroup uses aria-labelledby, see #567<commit_after>// Copyright 2013-2020, University of Colorado Boulder

/**
 * AquaRadioButtonGroup creates a group of AquaRadioButtons and manages their layout.
 *
 * @author Sam Reid (PhET Interactive Simulations)
 * @author Chris Malley (PixelZoom, Inc.)
 */

import merge from '../../phet-core/js/merge.js';
import AccessiblePeer from '../../scenery/js/accessibility/AccessiblePeer.js';
import HStrut from '../../scenery/js/nodes/HStrut.js';
import LayoutBox from '../../scenery/js/nodes/LayoutBox.js';
import Node from '../../scenery/js/nodes/Node.js';
import radioButtonSoundPlayerFactory from '../../tambo/js/radioButtonSoundPlayerFactory.js';
import Tandem from '../../tandem/js/Tandem.js';
import AquaRadioButton from './AquaRadioButton.js';
import EnabledComponent from './EnabledComponent.js';
import sun from './sun.js';

// a11y - An id for each instance of AquaRadioButtonGroup, passed to individual buttons in the group.
// Each button in a radio button group must have the same "name" attribute to be considered in a group, otherwise
// arrow keys will navigate all radio type inputs in the document.
let instanceCount = 0;

// constants
// to prefix instanceCount in case there are different kinds of "groups"
const CLASS_NAME = 'AquaRadioButtonGroup';

/**
 * @mixes EnabledComponent
 */
class AquaRadioButtonGroup extends LayoutBox {

  /**
   * @param {Property} property
   * @param {Object[]} items - Each item describes a radio button, and is an object with these properties:
   *    node: Node, // label for the button
   *    value: *, // value associated with the button
   *    [tandemName: Tandem], // optional tandem for PhET-iO
   *    [labelContent: string] // optional label for a11y
   * @param {Object} [options]
   * @constructor
   */
  constructor( property, items, options ) {

    instanceCount++;

    options = merge( {

      // {Object|null} options passed to constructor of the AquaRadioButtons
      radioButtonOptions: null,

      // Dilation of pointer areas for each radio button.
      // These are not part of radioButtonOptions because AquaRadioButton has no pointerArea options.
      // X dilation is ignored for orientation === 'horizontal'.
      // Y dilation is ignored for orientation === 'vertical'.
      touchAreaXDilation: 0,
      touchAreaYDilation: 0,
      mouseAreaXDilation: 0,
      mouseAreaYDilation: 0,

      // supertype options
      orientation: 'vertical', // Aqua radio buttons are typically vertical, rarely horizontal
      spacing: 3, // space between each button, perpendicular to options.orientation

      // phet-io
      tandem: Tandem.REQUIRED,
      phetioComponentOptions: {
        visibleProperty: { phetioFeatured: true }
      },

      // PDOM
      tagName: 'ul',
      ariaRole: 'radiogroup',
      groupFocusHighlight: true
    }, options );

    // Determine the max item width
    const maxItemWidth = _.maxBy( items, item => item.node.width ).node.width;

    // Create a radio button for each item
    const radioButtons = [];
    for ( let i = 0; i < items.length; i++ ) {

      const item = items[ i ];

      // Content for the radio button.
      // For vertical orientation, add an invisible strut, so that buttons have uniform width.
      const content = ( options.orientation === 'vertical' ) ?
                      new Node( { children: [ new HStrut( maxItemWidth ), item.node ] } ) :
                      item.node;

      const radioButton = new AquaRadioButton( property, item.value, content,
        merge( {}, options.radioButtonOptions, {
          tandem: item.tandemName ? options.tandem.createTandem( item.tandemName ) : Tandem.REQUIRED,
          labelContent: item.labelContent || null,
          soundPlayer: radioButtonSoundPlayerFactory.getRadioButtonSoundPlayer( i ),
          a11yNameAttribute: CLASS_NAME + instanceCount
        } ) );

      // set pointer areas
      if ( options.orientation === 'vertical' ) {
        radioButton.mouseArea = radioButton.localBounds.dilatedXY( options.mouseAreaXDilation, options.spacing / 2 );
        radioButton.touchArea = radioButton.localBounds.dilatedXY( options.touchAreaXDilation, options.spacing / 2 );
      }
      else {
        radioButton.mouseArea = radioButton.localBounds.dilatedXY( options.spacing / 2, options.mouseAreaYDilation );
        radioButton.touchArea = radioButton.localBounds.dilatedXY( options.spacing / 2, options.touchAreaYDilation );
      }

      radioButtons.push( radioButton );
    }

    // Verify that the client hasn't set options that we will be overwriting.
    assert && assert( !options.children, 'AquaRadioButtonGroup sets children' );
    options.children = radioButtons;

    super( options );

    // PDOM - this node's primary sibling is aria-labelledby its own label so the label content is read whenever
    // a member of the group receives focus
    this.addAriaLabelledbyAssociation( {
      thisElementName: AccessiblePeer.PRIMARY_SIBLING,
      otherNode: this,
      otherElementName: AccessiblePeer.LABEL_SIBLING
    } );

    this.initializeEnabledComponent( options );

    // Add linked element after the radio button is instrumented
    this.addLinkedElement( property, {
      tandem: options.tandem.createTandem( 'property' )
    } );

    // @private
    this.disposeAquaRadioButtonGroup = () => {
      for ( let i = 0; i < radioButtons.length; i++ ) {
        radioButtons[ i ].dispose();
      }
    };

    // @private
    this.radioButtons = radioButtons;
  }

  /**
   * @public
   * @override
   */
  dispose() {
    this.disposeAquaRadioButtonGroup();
    this.disposeEnabledComponent();
    super.dispose();
  }

  /**
   * Gets the radio button that corresponds to the specified value.
   * @param {*} value
   * @returns {AquaRadioButton}
   */
  getButton( value ) {
    const button = _.find( this.radioButtons, radioButton => radioButton.value === value );
    assert && assert( button, `no radio button found for value ${value}` );
    return button;
  }
}

EnabledComponent.mixInto( AquaRadioButtonGroup );

sun.register( 'AquaRadioButtonGroup', AquaRadioButtonGroup );
export default AquaRadioButtonGroup;<|endoftext|>


<commit_before>$.getScript('/socket.io/socket.io.js', function() {
  apos.socket = io.connect(window.location.host);
  apos.emit('socketReady');
});<commit_msg>make it synchronous<commit_after>$.ajax({
    async:false,
    type:'GET',
    url: '/socket.io/socket.io.js',
    data:null,
    dataType:'script',
    error: function(xhr, textStatus, errorThrown) {
      console.error('apostrophe-websockets failed to load socket.io asset.');
    },
    success: function() {
      apos.socket = io.connect(window.location.host);
    }
});<|endoftext|>


<commit_before>/*========================================================================

   This file is part of the GOsa project -  http://gosa-project.org

   Copyright:
      (C) 2010-2017 GONICUS GmbH, Germany, http://www.gonicus.de

   License:
      LGPL-2.1: http://www.gnu.org/licenses/lgpl-2.1.html

   See the LICENSE file in the project's top-level directory for details.

======================================================================== */

/**
 * Dialog for editing dashboard widgets
 */
qx.Class.define("gosa.ui.dialogs.EditDashboardWidget", {
  extend: gosa.ui.dialogs.Dialog,

  construct: function(widget) {
    this.base(arguments, this.tr("Edit dashboard widget"));

    this.__selectionValues = {};
    this.__initialValues = {};
    var initForm = {};

    // form
    var form = this.__form = new qx.ui.form.Form();

    // add the form items
    var options = gosa.data.DashboardController.getWidgetOptions(widget);
    if (options.settings) {
      Object.getOwnPropertyNames(options.settings.properties).forEach(function(propertyName) {
        var typeSettings = options.settings.properties[propertyName];
        var type, title = propertyName;
        var mandatory = (options.settings.mandatory && options.settings.mandatory.indexOf(propertyName) >= 0);

        if (qx.lang.Type.isObject(typeSettings)) {
          type = typeSettings.type.toLowerCase();
          if (typeSettings.title) {
            title = typeSettings.title;
            if (title.translate) {
              // trigger the translation
              title = title.translate();
            }
          }
        } else {
          type = typeSettings.toLowerCase();
        }
        var formItem, value = widget.get(propertyName);
        if (!value && typeSettings.defaultValue) {
          value = typeSettings.defaultValue;
        }

        var validator = null;
        switch (type) {

          case "json":
            value = qx.lang.Json.stringify(value);
            formItem = new qx.ui.form.TextArea();
            validator = this.validationWrapper("string", mandatory);
            break;

          case "number":
            formItem = new qx.ui.form.Spinner();
            validator = this.validationWrapper(type, mandatory);
            break;

          case "selection":
            var selectBox = new qx.ui.form.SelectBox();
            var selectionController = new qx.data.controller.List(null, selectBox);
            selectionController.setDelegate({
              bindItem: function(controller, item, index) {
                controller.bindProperty("label", "label", null, item, index);
                controller.bindProperty("data", "model", null, item, index);
                controller.bindProperty("icon", "icon", null, item, index);
              }
            });
            var data = new qx.data.Array();

            if (!typeSettings.defaultValue && (!options.settings.mandatory || options.settings.mandatory.indexOf(propertyName) === -1)) {
              data.push({label: "-", data: null});
            }

            if (typeSettings.provider === "RPC" && typeSettings.method) {
              // retrieve data from rpc
              gosa.io.Rpc.getInstance().cA(typeSettings.method).then(function(result) {

                for (var key in result) {
                  if (result.hasOwnProperty(key)) {
                    var keyValue = typeSettings.key === "KEY" ? key : result[key][typeSettings.key];
                    var entry = { data: keyValue, label: result[key][typeSettings.value]};
                    if (typeSettings.icon) {
                      entry.icon = result[key][typeSettings.icon]
                    }
                    data.push(entry);
                  }
                }
                var selectionModel = qx.data.marshal.Json.createModel(data.toArray());
                selectionController.setModel(selectionModel);
              }, this);
            } else if (typeSettings.provider === "custom" && typeSettings.options) {
              data.append(typeSettings.options);
              var selectionModel = qx.data.marshal.Json.createModel(data.toArray());
              selectionController.setModel(selectionModel);
            }

            selectBox.addListener("changeSelection", function() {
              if (selectBox.getModelSelection().length) {
                var selectedValue = selectBox.getModelSelection().getItem(0);
                if (selectedValue) {
                  this.__selectionValues[propertyName] = selectedValue;
                }
              }
            }, this);
            formItem = selectBox;
            break;

          default:
            // default (used for e.g. string type)
            formItem = new qx.ui.form.TextArea();
            validator = this.validationWrapper(type, mandatory);
            break;
        }
        if (mandatory) {
          formItem.setRequired(true);
        }
        this.addFormItem(formItem, title, validator, propertyName);
        this.__initialValues[propertyName] = value === null ? "" : value;
        if (value !== null) {
          initForm[propertyName] = value;
        }
      }, this);
    }

    // create the view
    this.addElement(new gosa.ui.form.renderer.Single(form));

    var controller = new qx.data.controller.Form(null, form);
    var model = this.__model = controller.createModel();

    // fill the model with initial values
    model.set(initForm);

    // buttons
    var saveButton = gosa.ui.base.Buttons.getOkButton();
    saveButton.setAppearance("button-primary");
    saveButton.setEnabled(false);
    this.addButton(saveButton);
    var cancelButton = gosa.ui.base.Buttons.getCancelButton();
    this.addButton(cancelButton);

    this.bind("savable", saveButton, "enabled");

    // serialization and reset /////////
    saveButton.addListener("execute", function() {
      if (form.validate()) {
        if (this.isModified()) {
          Object.getOwnPropertyNames(this.__initialValues).forEach(function(prop) {
            var value = this.__selectionValues[prop] || this.__model.get(prop);
            widget.set(prop, value);
          }, this);
          this.fireEvent("modified");
        }
        this.close();
      }
    }, this);
    cancelButton.addListener("execute", function() {
      if (this.isModified()) {
        var dialog = new gosa.ui.dialogs.Confirmation(this.tr("Unsaved changes"), this.tr("Do you want to discard those changes?"), "warning");
        dialog.addListenerOnce("confirmed", function(ev) {
          if (ev.getData() === true) {
            form.reset();
            this.close();
          }
        }, this);
        dialog.open();
      } else {
        form.reset();
        this.close();
      }
    }, this);

  },

  /*
  *****************************************************************************
     EVENTS
  *****************************************************************************
  */
  events : {
    "modified": "qx.event.type.Event"
  },

  /*
  *****************************************************************************
     PROPERTIES
  *****************************************************************************
  */
  properties : {
    modified: {
      check: "Boolean",
      init: false,
      event: "changeModified",
      apply: "_checkSavability"
    },

    /**
     * Determines if this form can be save (is modified and valid)
     */
    savable: {
      check: "Boolean",
      init: false,
      event: "changeSavable"
    }
  },

  /*
  *****************************************************************************
     MEMBERS
  *****************************************************************************
  */
  members : {
    __initialValues: null,
    __selectionValues: null,
    __model: null,
    __form: null,

    validationWrapper: function(type, mandatory, errorMessage) {
      var checkFunction = "check"+qx.lang.String.firstUp(type);
      if (qx.util.Validate[checkFunction]) {
        if (mandatory === true) {
          // use normal validator (also check empty values)
          return function(value) {
            qx.util.Validate[checkFunction](value, null, errorMessage);
          }
        } else {
          // use do not validate empty values
          return function(value) {
            if (value !== null && value !== undefined && value !== "") {
              qx.util.Validate[checkFunction](value, null, errorMessage);
            }
          }
        }
      }
      return null;
    },

    addFormItem: function(item, label, validator, name) {
      item.setUserData("property", name);
      this.__form.add(item, label, validator, name);
      if (item instanceof qx.ui.form.SelectBox) {
        item.addListener("changeSelection", this.checkModification, this);
      } else {
        item.setLiveUpdate(true);
        item.addListener("changeValue", this.checkModification, this);
      }
    },

    _checkSavability: function() {
      this.setSavable(this.isModified() && this.__form.validate());
    },

    /**
     * Check form for modifications
     * @return {Boolean} true if something has been modified
     */
    checkModification: function(ev) {
      var item = ev.getTarget();
      var prop = item.getUserData("property");
      var value = null;
      if (item instanceof qx.ui.form.SelectBox) {
        if (item.getSelection().length) {
          value = item.getSelection()[0].getUserData("key");
        }
      } else {
        value = item.getValue();
      }
      this._checkSavability();
      this.setModified(value != this.__initialValues[prop]);
    }
  },

  /*
  *****************************************************************************
     DESTRUCTOR
  *****************************************************************************
  */
  destruct : function() {
    this._disposeObjects("__initialValues", "__selectionValues", "__model", "__form");
  }

});
<commit_msg>use min/max value settings for numbers<commit_after>/*========================================================================

   This file is part of the GOsa project -  http://gosa-project.org

   Copyright:
      (C) 2010-2017 GONICUS GmbH, Germany, http://www.gonicus.de

   License:
      LGPL-2.1: http://www.gnu.org/licenses/lgpl-2.1.html

   See the LICENSE file in the project's top-level directory for details.

======================================================================== */

/**
 * Dialog for editing dashboard widgets
 */
qx.Class.define("gosa.ui.dialogs.EditDashboardWidget", {
  extend: gosa.ui.dialogs.Dialog,

  construct: function(widget) {
    this.base(arguments, this.tr("Edit dashboard widget"));

    this.__selectionValues = {};
    this.__initialValues = {};
    var initForm = {};

    // form
    var form = this.__form = new qx.ui.form.Form();

    // add the form items
    var options = gosa.data.DashboardController.getWidgetOptions(widget);
    if (options.settings) {
      Object.getOwnPropertyNames(options.settings.properties).forEach(function(propertyName) {
        var typeSettings = options.settings.properties[propertyName];
        var type, title = propertyName;
        var mandatory = (options.settings.mandatory && options.settings.mandatory.indexOf(propertyName) >= 0);

        if (qx.lang.Type.isObject(typeSettings)) {
          type = typeSettings.type.toLowerCase();
          if (typeSettings.title) {
            title = typeSettings.title;
            if (title.translate) {
              // trigger the translation
              title = title.translate();
            }
          }
        } else {
          type = typeSettings.toLowerCase();
        }
        var formItem, value = widget.get(propertyName);
        if (!value && typeSettings.defaultValue) {
          value = typeSettings.defaultValue;
        }

        var validator = null;
        switch (type) {

          case "json":
            value = qx.lang.Json.stringify(value);
            formItem = new qx.ui.form.TextArea();
            validator = this.validationWrapper("string", mandatory);
            break;

          case "number":
            var min = typeSettings.hasOwnProperty("minValue") ? typeSettings.minValue : null;
            var max = typeSettings.hasOwnProperty("maxValue") ? typeSettings.maxValue : null;
            formItem = new qx.ui.form.Spinner(min, value, max);
            validator = this.validationWrapper(type, mandatory);
            break;

          case "selection":
            var selectBox = new qx.ui.form.SelectBox();
            var selectionController = new qx.data.controller.List(null, selectBox);
            selectionController.setDelegate({
              bindItem: function(controller, item, index) {
                controller.bindProperty("label", "label", null, item, index);
                controller.bindProperty("data", "model", null, item, index);
                controller.bindProperty("icon", "icon", null, item, index);
              }
            });
            var data = new qx.data.Array();

            if (!typeSettings.defaultValue && (!options.settings.mandatory || options.settings.mandatory.indexOf(propertyName) === -1)) {
              data.push({label: "-", data: null});
            }

            if (typeSettings.provider === "RPC" && typeSettings.method) {
              // retrieve data from rpc
              gosa.io.Rpc.getInstance().cA(typeSettings.method).then(function(result) {

                for (var key in result) {
                  if (result.hasOwnProperty(key)) {
                    var keyValue = typeSettings.key === "KEY" ? key : result[key][typeSettings.key];
                    var entry = { data: keyValue, label: result[key][typeSettings.value]};
                    if (typeSettings.icon) {
                      entry.icon = result[key][typeSettings.icon]
                    }
                    data.push(entry);
                  }
                }
                var selectionModel = qx.data.marshal.Json.createModel(data.toArray());
                selectionController.setModel(selectionModel);
              }, this);
            } else if (typeSettings.provider === "custom" && typeSettings.options) {
              data.append(typeSettings.options);
              var selectionModel = qx.data.marshal.Json.createModel(data.toArray());
              selectionController.setModel(selectionModel);
            }

            selectBox.addListener("changeSelection", function() {
              if (selectBox.getModelSelection().length) {
                var selectedValue = selectBox.getModelSelection().getItem(0);
                if (selectedValue) {
                  this.__selectionValues[propertyName] = selectedValue;
                }
              }
            }, this);
            formItem = selectBox;
            break;

          default:
            // default (used for e.g. string type)
            formItem = new qx.ui.form.TextArea();
            validator = this.validationWrapper(type, mandatory);
            break;
        }
        if (mandatory) {
          formItem.setRequired(true);
        }
        this.addFormItem(formItem, title, validator, propertyName);
        this.__initialValues[propertyName] = value === null ? "" : value;
        if (value !== null) {
          initForm[propertyName] = value;
        }
      }, this);
    }

    // create the view
    this.addElement(new gosa.ui.form.renderer.Single(form));

    var controller = new qx.data.controller.Form(null, form);
    var model = this.__model = controller.createModel();

    // fill the model with initial values
    model.set(initForm);

    // buttons
    var saveButton = gosa.ui.base.Buttons.getOkButton();
    saveButton.setAppearance("button-primary");
    saveButton.setEnabled(false);
    this.addButton(saveButton);
    var cancelButton = gosa.ui.base.Buttons.getCancelButton();
    this.addButton(cancelButton);

    this.bind("savable", saveButton, "enabled");

    // serialization and reset /////////
    saveButton.addListener("execute", function() {
      if (form.validate()) {
        if (this.isModified()) {
          Object.getOwnPropertyNames(this.__initialValues).forEach(function(prop) {
            var value = this.__selectionValues[prop] || this.__model.get(prop);
            widget.set(prop, value);
          }, this);
          this.fireEvent("modified");
        }
        this.close();
      }
    }, this);
    cancelButton.addListener("execute", function() {
      if (this.isModified()) {
        var dialog = new gosa.ui.dialogs.Confirmation(this.tr("Unsaved changes"), this.tr("Do you want to discard those changes?"), "warning");
        dialog.addListenerOnce("confirmed", function(ev) {
          if (ev.getData() === true) {
            form.reset();
            this.close();
          }
        }, this);
        dialog.open();
      } else {
        form.reset();
        this.close();
      }
    }, this);

  },

  /*
  *****************************************************************************
     EVENTS
  *****************************************************************************
  */
  events : {
    "modified": "qx.event.type.Event"
  },

  /*
  *****************************************************************************
     PROPERTIES
  *****************************************************************************
  */
  properties : {
    modified: {
      check: "Boolean",
      init: false,
      event: "changeModified",
      apply: "_checkSavability"
    },

    /**
     * Determines if this form can be save (is modified and valid)
     */
    savable: {
      check: "Boolean",
      init: false,
      event: "changeSavable"
    }
  },

  /*
  *****************************************************************************
     MEMBERS
  *****************************************************************************
  */
  members : {
    __initialValues: null,
    __selectionValues: null,
    __model: null,
    __form: null,

    validationWrapper: function(type, mandatory, errorMessage) {
      var checkFunction = "check"+qx.lang.String.firstUp(type);
      if (qx.util.Validate[checkFunction]) {
        if (mandatory === true) {
          // use normal validator (also check empty values)
          return function(value) {
            qx.util.Validate[checkFunction](value, null, errorMessage);
          }
        } else {
          // use do not validate empty values
          return function(value) {
            if (value !== null && value !== undefined && value !== "") {
              qx.util.Validate[checkFunction](value, null, errorMessage);
            }
          }
        }
      }
      return null;
    },

    addFormItem: function(item, label, validator, name) {
      item.setUserData("property", name);
      this.__form.add(item, label, validator, name);
      if (item instanceof qx.ui.form.SelectBox) {
        item.addListener("changeSelection", this.checkModification, this);
      } else {
        if (item.setLiveUpdate) {
          item.setLiveUpdate(true);
        }
        item.addListener("changeValue", this.checkModification, this);
      }
    },

    _checkSavability: function() {
      this.setSavable(this.isModified() && this.__form.validate());
    },

    /**
     * Check form for modifications
     * @return {Boolean} true if something has been modified
     */
    checkModification: function(ev) {
      var item = ev.getTarget();
      var prop = item.getUserData("property");
      var value = null;
      if (item instanceof qx.ui.form.SelectBox) {
        if (item.getSelection().length) {
          value = item.getSelection()[0].getUserData("key");
        }
      } else {
        value = item.getValue();
      }
      this._checkSavability();
      this.setModified(value != this.__initialValues[prop]);
    }
  },

  /*
  *****************************************************************************
     DESTRUCTOR
  *****************************************************************************
  */
  destruct : function() {
    this._disposeObjects("__initialValues", "__selectionValues", "__model", "__form");
  }

});
<|endoftext|>


<commit_before>"use strict";

var
  View = require('atom').View,
  inherits = require('./utils').inherits;

var PlainMessageView = function (params) {
  this.message = params.message;
  this.raw = params.raw || false;
  this.className = params.className || undefined;

  View.apply(this, arguments);
};

inherits(PlainMessageView, View);

PlainMessageView.content = function () {
  this.div({
    class: 'plain-message'
  });
};

PlainMessageView.prototype.initialize = function () {
  if (this.raw) {
    this.html(this.message);
  } else {
    this.text(this.message);
  }

  if (this.className) {
    this.addClass(this.className);
  }
};

PlainMessageView.prototype.getSummary = function () {
  return {
    summary: this.message,
    className: this.className
  };
};

module.exports = PlainMessageView;
<commit_msg>fix summary raw<commit_after>"use strict";

var
  View = require('atom').View,
  inherits = require('./utils').inherits;

var PlainMessageView = function (params) {
  this.message = params.message;
  this.raw = params.raw || false;
  this.className = params.className || undefined;

  View.apply(this, arguments);
};

inherits(PlainMessageView, View);

PlainMessageView.content = function () {
  this.div({
    class: 'plain-message'
  });
};

PlainMessageView.prototype.initialize = function () {
  if (this.raw) {
    this.html(this.message);
  } else {
    this.text(this.message);
  }

  if (this.className) {
    this.addClass(this.className);
  }
};

PlainMessageView.prototype.getSummary = function () {
  return {
    summary: this.message,
    className: this.className,
    rawSummary: this.raw,
  };
};

module.exports = PlainMessageView;
<|endoftext|>


<commit_before>function trapNavigation() {
    $(function () {
        // only attach these events on metadata entry pages
        if ($('body.metadata_entry_pages_find_or_create').length < 1) {
            return;
        }

        var someThingsThatNeedToBeDoneFirst = function () {
            $.ajax({
                type: 'GET',
                async: false,
                url: '/stash/ajax_wait'
            }).done(function () {
                console.log('wait a second for ajax to complete');
                waitAjax();
                console.log('ajax completed');
            });
        };

        $('a, #dashboard_path, #upload_path').on('click', onWithPrecondition(someThingsThatNeedToBeDoneFirst));

        // blocks until all ajax connections are closed
        var waitAjax = function () {
            if ($.active < 1) {
                return;
            } else {
                setTimeout(waitAjax, 100); // check again in 100 ms
            }
        }
    });
}

// see https://stackoverflow.com/questions/7610871/how-to-trigger-an-event-after-using-event-preventdefault
function onWithPrecondition(callback) {
    var isDone = false;

    return function (e) {
        if (isDone === true) {
            isDone = false;
            return;
        }

        // preventing default and re-triggering events seems to be problematic with security in Safari and no longer works
        // e.preventDefault();

        callback.apply(this, arguments);

        isDone = true;

        // $(this).click();
    }
}
<commit_msg>Simplifying code for ajax click waits.<commit_after>function trapNavigation() {
    $(function () {
        // only attach these events on metadata entry pages
        if ($('body.metadata_entry_pages_find_or_create').length < 1) {
            return;
        }

        // blocks until all ajax connections are closed
        var waitAjax = function () {
            if ($.active < 1) {
                return;
            } else {
                setTimeout(waitAjax, 100); // check again in 100 ms
            }
        }

        var waitForMyAjaxClicks = function () {
            $.ajax({
                type: 'GET',
                async: false,
                url: '/stash/ajax_wait'
            }).done(function () {
                waitAjax();
            });
        };

        $('a, #dashboard_path, #upload_path').on('click', waitForMyAjaxClicks);
    });
}

// see https://stackoverflow.com/questions/7610871/how-to-trigger-an-event-after-using-event-preventdefault
// may need to use in the future.
<|endoftext|>


<commit_before>var doc = require('doc-js'),
    EventEmitter = require('events').EventEmitter,
    interact = require('interact-js'),
    crel = require('crel'),
    venfix = require('venfix');

function Flap(element){
    this.render(element);
    this.bind();
    setTimeout(this.init.bind(this),10);
}
Flap.prototype = Object.create(EventEmitter.prototype);

Flap.prototype.constructor = Flap;
Flap.prototype.distance = 0;
Flap.prototype.state = 'closed';
Flap.prototype.width = 280;
Flap.prototype.side = 'left';
Flap.prototype.gutter = 20;

Flap.prototype.render = function(element){
    this.element = element || crel('div',
        crel('div')
    );

    this.content = this.element.childNodes[0];
    this.element.flap = this;
};
Flap.prototype.bind = function(){
    var flap = this,
        delegateTarget = this.delegateTarget || document;

    // Allow starting the drag on a delegate target
    interact.on('start', delegateTarget, flap._start.bind(flap));

    // Still use document for the other events for robustness.
    interact.on('drag', document, flap._drag.bind(flap));
    interact.on('end', document, flap._end.bind(flap));

    doc(this.element).on('click', flap._activate.bind(flap));
};
Flap.prototype.init = function(){
    this.enable();
    this.emit('ready');
};
Flap.prototype.enable = function(){
    this.enabled = true;

    this.element.style.position = 'fixed';
    this.element.style.top = '0px';
    this.element.style.bottom = '0px';
    this.close();

    this.content.style[venfix('boxSizing')] = 'border-box';
    this.content.style.width = this.width + 'px';
    this.content.style.position = 'absolute';
    this.content.style.top = '0px';
    this.content.style.bottom = '0px';
    this.content.style.width = this.width + 'px';
    this.content.style['overflow-x'] = 'hidden';
    this.content.style['overflow-y'] = 'auto';

    if(this.side === 'left'){
        this.element.style.left = '0px';
        this.content.style.left = '0px';
    }else if(this.side === 'right'){
        this.element.style.right = '0px';
        this.content.style.left = '100%';
    }
    this.update();
};
Flap.prototype.disable = function(){
    this.enabled = false;

    this.element.style.position = null;
    this.element.style.top = null;
    this.element.style.bottom = null;
    this.element.style.width = null;
    this.element.style[venfix('pointerEvents')] = null;

    this.content.style[venfix('boxSizing')] = null;
    this.content.style[venfix('transform')] = null;
    this.content.style.width = null;
    this.content.style.position = null;
    this.content.style.top = null;
    this.content.style.bottom = null;
    this.content.style.width = null;
    this.content.style['overflow-x'] = null;
    this.content.style['overflow-y'] = null;

    this.element.style.left = null;
    this.content.style.left = null;
    this.element.style.right = null;
    this.content.style.left = null;
    this.update();
};
Flap.prototype._isValidInteraction = function(interaction){
    if(this.constructor.openFlap){
        return this.constructor.openFlap === this;
    }
    if(this.distance){
        return true;
    }
    if(this.side === 'left'){
        return interaction.pageX < this.distance + this.gutter;
    }else if(this.side === 'right'){
        return interaction.pageX > window.innerWidth - this.gutter;
    }
};
Flap.prototype._start = function(interaction){
    var flap = this;

    if(!this.enabled){
        return;
    }

    if(this._isValidInteraction(interaction)){
        this._setOpen();
    }
};
Flap.prototype._drag = function(interaction){
    var flap = this;

    if(this.constructor.openFlap === this){
        var angle = interaction.getCurrentAngle(true);
        if(angle && !this.beingTouched && ((angle > 45 && angle < 135) || (angle < -45 && angle > -135))){
            this.constructor.openFlap = null;
            return;
        }

        interaction.preventDefault();

        flap.beingTouched = true;
        flap.startDistance = flap.startDistance || flap.distance;
        if(flap.side === 'left'){
            flap.distance = flap.startDistance + interaction.pageX - interaction.lastStart.pageX;
        }else{
            flap.distance = flap.startDistance - interaction.pageX + interaction.lastStart.pageX;
        }
        flap.distance = Math.max(Math.min(flap.distance, flap.width), 0);
        flap.update();
        flap.speed = flap.distance - flap.oldDistance;
        flap.oldDistance = flap.distance;
    }
};
Flap.prototype._end = function(interaction){
    if(this.constructor.openFlap !== this){
        return;
    }

    this.startDistance = null;
    this.beingTouched = false;

    var direction = 'close';

    if(Math.abs(this.speed) >= 3){
        direction = this.speed < 0 ? 'close' : 'open';
    }else if(this.distance < this.width / 2){
        direction = 'close';
    }else{
        direction = 'open';
    }

    this.settle(direction);
};
Flap.prototype._activate = function(event){
    if(!this.enabled){
        return;
    }
    if(
        !doc(event.target).closest(this.content) &&
        this.constructor.openFlap === this
    ){
        event.preventDefault();
        this.beingTouched = false;
        this.settle('close');
    }
};
Flap.prototype._setOpen = function(){
    if(this.constructor.openFlap !== this){
        var flap = this;
        this.constructor.openFlap = this;
        this.element.style['width'] = '100%';
        this.state = 'open';
        this.emit('open');

        // This prevents the flap from screwing up
        // events on elements that may be under the swipe zone
        this._pointerEventTimeout = setTimeout(function(){
            flap.element.style[venfix('pointerEvents')] = 'all';
        },500);
    }
};
Flap.prototype._setClosed = function(){
    this.constructor.openFlap = null;
    clearTimeout(this._pointerEventTimeout);
    this.element.style[venfix('pointerEvents')] = 'none';
    this.element.style['width'] = this.gutter + 'px';
    this.state = 'closed';
    this.emit('close');
};
Flap.prototype.update = function(interaction){
    var flap = this;

    if(this.distance > 0){
        this._setOpen();
    }

    if(this.side === 'left'){
        this.displayPosition = flap.distance - flap.width;
    }else if(this.side === 'right'){
        this.displayPosition = -flap.distance;
    }

    if(flap.distance != flap.lastDistance){
        requestAnimationFrame(function(){
            flap.updateStyle(flap.displayPosition);
            flap.emit('move');
            flap.lastDistance = flap.distance;
        });
    }
};
Flap.prototype.updateStyle = function(displayPosition){
    this.content.style[venfix('transform')] = 'translate3d(' + (displayPosition) + 'px,0,0)';
};
Flap.prototype.settle = function(direction){
    var flap = this;

    if(this.beingTouched){
        return;
    }
    if(this.distance < 0){
        this.distance = 0;
        this._setClosed();
        this.update();
        return;
    }else if(this.distance > this.width){
        this.distance = this.width;
        this.update();
        return;
    }

    requestAnimationFrame(function(){
        var step = flap.tween(direction);
        flap.distance += direction === 'close' ? -step : step;
        flap.update();
        flap.settle(direction);
    });
};
Flap.prototype.tween = function(direction){
    return (this.width - this.distance) / 4 + 2;
};
Flap.prototype.percentOpen = function(){
    return parseInt(100 / this.width * this.distance);
};
Flap.prototype.open = function(){
    if(!this.enabled){
        return;
    }
    this.settle('open');
};
Flap.prototype.close = function(){
    if(!this.enabled){
        return;
    }
    this.settle('close');
};
module.exports = Flap;<commit_msg>Added settle event<commit_after>var doc = require('doc-js'),
    EventEmitter = require('events').EventEmitter,
    interact = require('interact-js'),
    crel = require('crel'),
    venfix = require('venfix');

function Flap(element){
    this.render(element);
    this.bind();
    setTimeout(this.init.bind(this),10);
}
Flap.prototype = Object.create(EventEmitter.prototype);

Flap.prototype.constructor = Flap;
Flap.prototype.distance = 0;
Flap.prototype.state = 'closed';
Flap.prototype.width = 280;
Flap.prototype.side = 'left';
Flap.prototype.gutter = 20;

Flap.prototype.render = function(element){
    this.element = element || crel('div',
        crel('div')
    );

    this.content = this.element.childNodes[0];
    this.element.flap = this;
};
Flap.prototype.bind = function(){
    var flap = this,
        delegateTarget = this.delegateTarget || document;

    // Allow starting the drag on a delegate target
    interact.on('start', delegateTarget, flap._start.bind(flap));

    // Still use document for the other events for robustness.
    interact.on('drag', document, flap._drag.bind(flap));
    interact.on('end', document, flap._end.bind(flap));

    doc(this.element).on('click', flap._activate.bind(flap));
};
Flap.prototype.init = function(){
    this.enable();
    this.emit('ready');
};
Flap.prototype.enable = function(){
    this.enabled = true;

    this.element.style.position = 'fixed';
    this.element.style.top = '0px';
    this.element.style.bottom = '0px';
    this.close();

    this.content.style[venfix('boxSizing')] = 'border-box';
    this.content.style.width = this.width + 'px';
    this.content.style.position = 'absolute';
    this.content.style.top = '0px';
    this.content.style.bottom = '0px';
    this.content.style.width = this.width + 'px';
    this.content.style['overflow-x'] = 'hidden';
    this.content.style['overflow-y'] = 'auto';

    if(this.side === 'left'){
        this.element.style.left = '0px';
        this.content.style.left = '0px';
    }else if(this.side === 'right'){
        this.element.style.right = '0px';
        this.content.style.left = '100%';
    }
    this.update();
};
Flap.prototype.disable = function(){
    this.enabled = false;

    this.element.style.position = null;
    this.element.style.top = null;
    this.element.style.bottom = null;
    this.element.style.width = null;
    this.element.style[venfix('pointerEvents')] = null;

    this.content.style[venfix('boxSizing')] = null;
    this.content.style[venfix('transform')] = null;
    this.content.style.width = null;
    this.content.style.position = null;
    this.content.style.top = null;
    this.content.style.bottom = null;
    this.content.style.width = null;
    this.content.style['overflow-x'] = null;
    this.content.style['overflow-y'] = null;

    this.element.style.left = null;
    this.content.style.left = null;
    this.element.style.right = null;
    this.content.style.left = null;
    this.update();
};
Flap.prototype._isValidInteraction = function(interaction){
    if(this.constructor.openFlap){
        return this.constructor.openFlap === this;
    }
    if(this.distance){
        return true;
    }
    if(this.side === 'left'){
        return interaction.pageX < this.distance + this.gutter;
    }else if(this.side === 'right'){
        return interaction.pageX > window.innerWidth - this.gutter;
    }
};
Flap.prototype._start = function(interaction){
    var flap = this;

    if(!this.enabled){
        return;
    }

    if(this._isValidInteraction(interaction)){
        this._setOpen();
    }
};
Flap.prototype._drag = function(interaction){
    var flap = this;

    if(this.constructor.openFlap === this){
        var angle = interaction.getCurrentAngle(true);
        if(angle && !this.beingTouched && ((angle > 45 && angle < 135) || (angle < -45 && angle > -135))){
            this.constructor.openFlap = null;
            return;
        }

        interaction.preventDefault();

        flap.beingTouched = true;
        flap.startDistance = flap.startDistance || flap.distance;
        if(flap.side === 'left'){
            flap.distance = flap.startDistance + interaction.pageX - interaction.lastStart.pageX;
        }else{
            flap.distance = flap.startDistance - interaction.pageX + interaction.lastStart.pageX;
        }
        flap.distance = Math.max(Math.min(flap.distance, flap.width), 0);
        flap.update();
        flap.speed = flap.distance - flap.oldDistance;
        flap.oldDistance = flap.distance;
    }
};
Flap.prototype._end = function(interaction){
    if(this.constructor.openFlap !== this){
        return;
    }

    this.startDistance = null;
    this.beingTouched = false;

    var direction = 'close';

    if(Math.abs(this.speed) >= 3){
        direction = this.speed < 0 ? 'close' : 'open';
    }else if(this.distance < this.width / 2){
        direction = 'close';
    }else{
        direction = 'open';
    }

    this.settle(direction);
};
Flap.prototype._activate = function(event){
    if(!this.enabled){
        return;
    }
    if(
        !doc(event.target).closest(this.content) &&
        this.constructor.openFlap === this
    ){
        event.preventDefault();
        this.beingTouched = false;
        this.settle('close');
    }
};
Flap.prototype._setOpen = function(){
    if(this.constructor.openFlap !== this){
        var flap = this;
        this.constructor.openFlap = this;
        this.element.style['width'] = '100%';
        this.state = 'open';
        this.emit('open');

        // This prevents the flap from screwing up
        // events on elements that may be under the swipe zone
        this._pointerEventTimeout = setTimeout(function(){
            flap.element.style[venfix('pointerEvents')] = 'all';
        },500);
    }
};
Flap.prototype._setClosed = function(){
    this.constructor.openFlap = null;
    clearTimeout(this._pointerEventTimeout);
    this.element.style[venfix('pointerEvents')] = 'none';
    this.element.style['width'] = this.gutter + 'px';
    this.state = 'closed';
    this.emit('close');
};
Flap.prototype.update = function(interaction){
    var flap = this;

    if(this.distance > 0){
        this._setOpen();
    }

    if(this.side === 'left'){
        this.displayPosition = flap.distance - flap.width;
    }else if(this.side === 'right'){
        this.displayPosition = -flap.distance;
    }

    if(flap.distance != flap.lastDistance){
        requestAnimationFrame(function(){
            flap.updateStyle(flap.displayPosition);
            flap.emit('move');
            flap.lastDistance = flap.distance;
        });
    }
};
Flap.prototype.updateStyle = function(displayPosition){
    this.content.style[venfix('transform')] = 'translate3d(' + (displayPosition) + 'px,0,0)';
};
Flap.prototype.settle = function(direction){
    var flap = this;

    if(this.beingTouched){
        return;
    }
    if(this.distance < 0){
        this.distance = 0;
        this._setClosed();
        this.update();
        this.emit('settle');
        return;
    }else if(this.distance > this.width){
        this.distance = this.width;
        this.update();
        this.emit('settle');
        return;
    }

    requestAnimationFrame(function(){
        var step = flap.tween(direction);
        flap.distance += direction === 'close' ? -step : step;
        flap.update();
        flap.settle(direction);
    });
};
Flap.prototype.tween = function(direction){
    return (this.width - this.distance) / 4 + 2;
};
Flap.prototype.percentOpen = function(){
    return parseInt(100 / this.width * this.distance);
};
Flap.prototype.open = function(){
    if(!this.enabled){
        return;
    }
    this.settle('open');
};
Flap.prototype.close = function(){
    if(!this.enabled){
        return;
    }
    this.settle('close');
};
module.exports = Flap;<|endoftext|>


<commit_before>// @flow

import {
  TabNavigator as TabNav,
  NavigationScreenRouteConfig,
} from 'react-navigation'
import * as c from '../colors'

type ComponentType = (
  screens: {[key: string]: NavigationScreenRouteConfig},
  options: any, // I don't know how to type this better…
  // the package provides a bunch of types… but it doesn't even use some
  // of them??? and none seem to be the combination of args to the second
  // arg of TabNavigator.
) => TabNav

export const TabNavigator: ComponentType = (screens, options) => TabNav(
  screens,
  {
    tabBarOptions: {
      activeTintColor: c.mandarin,
      backBehavior: 'none',
      ...(options.tabBarOptions || {}),
    },
    ...options,
  },
)
<commit_msg>pass backBehavior in the correct location<commit_after>// @flow

import {
  TabNavigator as TabNav,
  NavigationScreenRouteConfig,
} from 'react-navigation'
import * as c from '../colors'

type ComponentType = (
  screens: {[key: string]: NavigationScreenRouteConfig},
  options: any, // I don't know how to type this better…
  // the package provides a bunch of types… but it doesn't even use some
  // of them??? and none seem to be the combination of args to the second
  // arg of TabNavigator.
) => TabNav

export const TabNavigator: ComponentType = (screens, options) => TabNav(
  screens,
  {
    backBehavior: 'none',
    tabBarOptions: {
      activeTintColor: c.mandarin,
      ...(options.tabBarOptions || {}),
    },
    ...options,
  },
)
<|endoftext|>


<commit_before>// Copyright 2016, University of Colorado Boulder

/**
 * Wrapper type for scenery's Focus region.
 *
 * @author Sam Reid (PhET Interactive Simulations)
 * @author Jesse Greenberg (PhET Interactive Simulations)
 */
define( function( require ) {
  'use strict';

  // modules
  var scenery = require( 'SCENERY/scenery' );

  // phet-io modules
  var assertInstanceOf = require( 'ifphetio!PHET_IO/assertions/assertInstanceOf' );
  var phetioInherit = require( 'ifphetio!PHET_IO/phetioInherit' );
  var TObject = require( 'ifphetio!PHET_IO/types/TObject' );

  /**
   * Wrapper type for phet/sun's Faucet class.
   * @param {Object} focus - the focus region which has {display,trail}
   * @param {string} phetioID - the unique tandem assigned to the focus
   * @constructor
   */
  function TFocus( focus, phetioID ) {
    TObject.call( this, focus, phetioID );
    assertInstanceOf( focus, Object );
  }

  phetioInherit( TObject, 'TFocus', TFocus, {}, {

    /**
     * Convert the focus region to a plain JS object for serialization.
     * @param {Object} focus - the focus region which has {display,trail}
     * @returns {Object} - the serialized object
     */
    toStateObject: function( focus ) {

      // If nothing is focused, the focus is nulls
      if ( focus === null ) {
        return null;
      }
      else {
        return focus.trail.indices;
      }
    },

    /**
     * Convert the serialized instance back to a focus object
     * @param {number[]} indices
     * @returns {Object} with {display,trail}
     */
    fromStateObject: function( indices ) {

      if ( indices === null ) {

        // support unfocused
        return null;
      }
      else {

        // Follow the path of children based on their indices, starting from the root of the display.
        // There is always one more node in Trail than indices, representing the root node.
        var currentNode = phet.joist.sim.display.rootNode;
        var nodes = [ currentNode ];
        for ( var i = 0; i < indices.length; i++ ) {
          var index = indices[ i ];
          currentNode = currentNode.children[ index ];
          nodes.push( currentNode );
        }

        return { display: phet.joist.sim.display, trail: new phet.scenery.Trail( nodes ) };
      }
    },

    documentation: 'A wrapper type for the instance in the simulation which currently has keyboard focus.'
  } );

  scenery.register( 'TFocus', TFocus );

  return TFocus;
} );<commit_msg>Check for Focus type, see https://github.com/phetsims/joist/issues/434<commit_after>// Copyright 2016, University of Colorado Boulder

/**
 * Wrapper type for scenery's Focus region.
 *
 * @author Sam Reid (PhET Interactive Simulations)
 * @author Jesse Greenberg (PhET Interactive Simulations)
 */
define( function( require ) {
  'use strict';

  // modules
  var scenery = require( 'SCENERY/scenery' );

  // phet-io modules
  var assertInstanceOf = require( 'ifphetio!PHET_IO/assertions/assertInstanceOf' );
  var phetioInherit = require( 'ifphetio!PHET_IO/phetioInherit' );
  var TObject = require( 'ifphetio!PHET_IO/types/TObject' );

  /**
   * Wrapper type for phet/sun's Faucet class.
   * @param {Object} focus - the focus region which has {display,trail}
   * @param {string} phetioID - the unique tandem assigned to the focus
   * @constructor
   */
  function TFocus( focus, phetioID ) {
    TObject.call( this, focus, phetioID );
    assertInstanceOf( focus, phet.scenery.Focus );
  }

  phetioInherit( TObject, 'TFocus', TFocus, {}, {

    /**
     * Convert the focus region to a plain JS object for serialization.
     * @param {Object} focus - the focus region which has {display,trail}
     * @returns {Object} - the serialized object
     */
    toStateObject: function( focus ) {

      // If nothing is focused, the focus is nulls
      if ( focus === null ) {
        return null;
      }
      else {
        return focus.trail.indices;
      }
    },

    /**
     * Convert the serialized instance back to a focus object
     * @param {number[]} indices
     * @returns {Object} with {display,trail}
     */
    fromStateObject: function( indices ) {

      if ( indices === null ) {

        // support unfocused
        return null;
      }
      else {

        // Follow the path of children based on their indices, starting from the root of the display.
        // There is always one more node in Trail than indices, representing the root node.
        var currentNode = phet.joist.sim.display.rootNode;
        var nodes = [ currentNode ];
        for ( var i = 0; i < indices.length; i++ ) {
          var index = indices[ i ];
          currentNode = currentNode.children[ index ];
          nodes.push( currentNode );
        }

        return { display: phet.joist.sim.display, trail: new phet.scenery.Trail( nodes ) };
      }
    },

    documentation: 'A wrapper type for the instance in the simulation which currently has keyboard focus.'
  } );

  scenery.register( 'TFocus', TFocus );

  return TFocus;
} );<|endoftext|>


<commit_before>(function () {

    var filtersAreDirty = false;

    linz.addDeleteConfirmation();
    linz.addDisabledBtnAlert();

    /* FILTERS */

    if ($('.selectedFilters').val().length > 0) {
        toggleFilterBox('show');
    }

    $('[data-sort-field]').click(function () {

        var sort = $('.selectedSort').val(),
            sortField = $(this).attr('data-sort-field');

        if (sort === sortField) {
            sortField = '-' + sortField;
        }

        // update hidden sort field in the filter form
        $('.selectedSort').val(sortField);

        filtersAreDirty = true;

        triggerSubmit();

        return true;

    });

    $('form.filters button[type="submit"]').click(function (event) {

        // reset the pagination if required
        if (filtersAreDirty || event.isTrigger === undefined) {
            $('input.page').val(1);
        }

    });

    $('.control-addFilter').click(function () {

        var filter = $(this),
            filterText = filter.html(),
            filterVal = filter.attr('data-filter-field'),
            filterFormControl = filter.siblings('.controlField').html(),
            aFilters;

        if (linz.isTemplateSupported()) {

            var content = document.querySelector('#filter').content.cloneNode(true);

            // update template with filter content
            content.querySelector('.filter-name').textContent = filterText;
            content.querySelector('.filter-control').innerHTML = content.querySelector('.filter-control').innerHTML + filterFormControl;
            content.querySelector('.fa-times').setAttribute('data-filter-field', $(this).attr('data-filter-field'));
            document.querySelector('.filter-list').appendChild(document.importNode(content, true));

        } else {

            // fallback support for browsers that don't support html5 template tag
            var filterOption = $('#filter').clone();
            filterOption.find('.filter-name').html(filterText);
            filterOption.find('.filter-control').append(filterFormControl);
            filterOption.find('.fa-times').attr('data-filter-field',$(this).attr('data-filter-field'));
            $('.filter-list').append(filterOption.html());

        }

        // determine if a multiselect was added to the dom, if so, apply the plugin
        $('.multiselect', $('.filter-list').children().last()).multiselect({
            buttonContainer: '
'
        });

        // determine if radio or checkboxes were added to the dom, if so, apply a plugin
         $('input[type="radio"],input[type="checkbox"]', $('.filter-list').children().last()).not(function (item, el) {
                return ($(this).closest('.multiselect-container').length === 1) ? true : false;
            }).iCheck({
            checkboxClass: 'icheckbox_square-green',
            radioClass: 'iradio_square-green'
        });

        // hide dropdown for 'Add filter'
        $(this).parents('li.dropdown').removeClass('open');

        var selectedFilters = $('.selectedFilters').val();

        if (selectedFilters) {
            aFilters = $('.selectedFilters').val().split();
        } else {
            aFilters = [];
        }

        // only add the filter once
        if (aFilters.indexOf(filterVal) < 0) {
            aFilters.push(filterVal);
        }

        $('.selectedFilters').val(aFilters.join());

        filtersAreDirty = true;

        toggleFilterBox('show');

        assignRemoveButton();
        linz.loadDatepicker();

        return false;

    });

    assignRemoveButton();

    /* PAGINATION */

    $('select.pagination').change(function () {
        $('input.page').val($(this).val());
        triggerSubmit();
    });

    /* PAGE SIZE */

    $('select.pagination-size').change(function () {
        $('input.pageSize').val($(this).val());
        filtersAreDirty = true;
        triggerSubmit();
    });

    /* GROUP ACTIONS */

    $('input[data-linz-control="checked-all"]').on('ifToggled', function () {

        var isChecked = $(this).is(':checked');

        $('input[data-linz-control="checked-record"]').prop('checked',isChecked);
        $('input[data-linz-control="checked-record"]').iCheck('update');

    });

    // bind event for check-all checkbox to show group action buttons
    $('input[data-linz-control="checked-all"]').on('ifToggled', function () {

        if ($(this).is(':checked')) {
            return $('.group-actions').show();
        }

        $('.group-actions').hide();

    });

    // bind event to checkboxes to show group action buttons when checked
    $('input[data-linz-control="checked-record"]').on('ifToggled', function () {

        if ($(this).is(':checked')) {
            return $('.group-actions').show();
        }

        // check if any of the other checkboxes are checked
        if ($('input[data-linz-control="checked-record"]:checked').length) {
            return;
        }

        // since none are checked, let's close group action buttons
        $('.group-actions').hide();

    });

    // bind group action buttons
    $('[data-linz-control="group-action"]').click(function () {

        var queryObj = $(this),
            url = queryObj.attr('href');

        $('#groupActionModal').modal().find('.modal-dialog').load(url, function () {
            console.log('helllo');
        });

       return false;
    });

    // bind model save button and update the selected ids to modal form
    $('#groupActionModal').on('shown.bs.modal', function (e) {

        var selectedIDs = [],
            _this = this;

        $('input[data-linz-control="checked-record"]:checked').each(function () {
            selectedIDs.push($(this).val());
        });

        // add selected IDs to hidden field
        $(_this).find('[data-group-action="ids"]').val(selectedIDs);

        // add form validation
        $(_this).find('form').bootstrapValidator({});

    });

    function removeFomList (list, value, separator) {
        separator = separator || ",";
        var values = list.split(separator);

        for(var i = 0 ; i < values.length ; i++) {
            if(values[i] === value) {
                values.splice(i, 1);
                return values.join(separator);
            }
        }

        return list;

    }

    function assignRemoveButton (queryObj) {

        // remove all event listener
        $('.fa-times').unbind();

        // re-assign listeners including any new ones added to DOM after page load
        $('.fa-times').click(function () {

            var filteredField = $(this).attr('data-filter-field'),
                selectedFilters = $('.selectedFilters').val(),
                numOfSameFilters = $('.fa-times[data-filter-field=' + filteredField + ']').length;

            filtersAreDirty = true;

            // ensure there are no multiple filters on the same field, before removing it from the list
            if (numOfSameFilters <= 1) {

                selectedFilters = removeFomList(selectedFilters, filteredField)

                $('.selectedFilters').val(selectedFilters);

                if (selectedFilters.length <= 0) {
                    toggleFilterBox();
                    // since there are no filters, let's post the form to clear all filters except the sorting
                    // submit the form and reset the pagination
                    triggerSubmit();
                }

            }

            $(this).parents('.form-group').remove();
        });
    }

    function toggleFilterBox(showOrHide) {
        if (showOrHide) {
            $('.filters').show();
        } else {
            $('.filters').hide();
        }
    }

    // trigger a click of the 'filter' button
    function triggerSubmit () {

        // click the button
        $('.filters').find(':submit').click();

    }

})();
<commit_msg>Fixed js issue for filter box not closing after a filter selection.<commit_after>(function () {

    var filtersAreDirty = false;

    linz.addDeleteConfirmation();
    linz.addDisabledBtnAlert();

    /* FILTERS */

    if ($('.selectedFilters').val().length > 0) {
        toggleFilterBox('show');
    }

    $('[data-sort-field]').click(function () {

        var sort = $('.selectedSort').val(),
            sortField = $(this).attr('data-sort-field');

        if (sort === sortField) {
            sortField = '-' + sortField;
        }

        // update hidden sort field in the filter form
        $('.selectedSort').val(sortField);

        filtersAreDirty = true;

        triggerSubmit();

        return true;

    });

    $('form.filters button[type="submit"]').click(function (event) {

        // reset the pagination if required
        if (filtersAreDirty || event.isTrigger === undefined) {
            $('input.page').val(1);
        }

    });

    $('.control-addFilter').click(function () {

        var filter = $(this),
            filterText = filter.html(),
            filterVal = filter.attr('data-filter-field'),
            filterFormControl = filter.siblings('.controlField').html(),
            aFilters;

        if (linz.isTemplateSupported()) {

            var content = document.querySelector('#filter').content.cloneNode(true);

            // update template with filter content
            content.querySelector('.filter-name').textContent = filterText;
            content.querySelector('.filter-control').innerHTML = content.querySelector('.filter-control').innerHTML + filterFormControl;
            content.querySelector('.fa-times').setAttribute('data-filter-field', $(this).attr('data-filter-field'));
            document.querySelector('.filter-list').appendChild(document.importNode(content, true));

        } else {

            // fallback support for browsers that don't support html5 template tag
            var filterOption = $('#filter').clone();
            filterOption.find('.filter-name').html(filterText);
            filterOption.find('.filter-control').append(filterFormControl);
            filterOption.find('.fa-times').attr('data-filter-field',$(this).attr('data-filter-field'));
            $('.filter-list').append(filterOption.html());

        }

        // determine if a multiselect was added to the dom, if so, apply the plugin
        $('.multiselect', $('.filter-list').children().last()).multiselect({
            buttonContainer: '
'
        });

        // determine if radio or checkboxes were added to the dom, if so, apply a plugin
         $('input[type="radio"],input[type="checkbox"]', $('.filter-list').children().last()).not(function (item, el) {
                return ($(this).closest('.multiselect-container').length === 1) ? true : false;
            }).iCheck({
            checkboxClass: 'icheckbox_square-green',
            radioClass: 'iradio_square-green'
        });

        // hide dropdown for 'Add filter'
        $(this).parents('.dropdown').removeClass('open');

        var selectedFilters = $('.selectedFilters').val();

        if (selectedFilters) {
            aFilters = $('.selectedFilters').val().split();
        } else {
            aFilters = [];
        }

        // only add the filter once
        if (aFilters.indexOf(filterVal) < 0) {
            aFilters.push(filterVal);
        }

        $('.selectedFilters').val(aFilters.join());

        filtersAreDirty = true;

        toggleFilterBox('show');

        assignRemoveButton();
        linz.loadDatepicker();

        return false;

    });

    assignRemoveButton();

    /* PAGINATION */

    $('select.pagination').change(function () {
        $('input.page').val($(this).val());
        triggerSubmit();
    });

    /* PAGE SIZE */

    $('select.pagination-size').change(function () {
        $('input.pageSize').val($(this).val());
        filtersAreDirty = true;
        triggerSubmit();
    });

    /* GROUP ACTIONS */

    $('input[data-linz-control="checked-all"]').on('ifToggled', function () {

        var isChecked = $(this).is(':checked');

        $('input[data-linz-control="checked-record"]').prop('checked',isChecked);
        $('input[data-linz-control="checked-record"]').iCheck('update');

    });

    // bind event for check-all checkbox to show group action buttons
    $('input[data-linz-control="checked-all"]').on('ifToggled', function () {

        if ($(this).is(':checked')) {
            return $('.group-actions').show();
        }

        $('.group-actions').hide();

    });

    // bind event to checkboxes to show group action buttons when checked
    $('input[data-linz-control="checked-record"]').on('ifToggled', function () {

        if ($(this).is(':checked')) {
            return $('.group-actions').show();
        }

        // check if any of the other checkboxes are checked
        if ($('input[data-linz-control="checked-record"]:checked').length) {
            return;
        }

        // since none are checked, let's close group action buttons
        $('.group-actions').hide();

    });

    // bind group action buttons
    $('[data-linz-control="group-action"]').click(function () {

        var queryObj = $(this),
            url = queryObj.attr('href');

        $('#groupActionModal').modal().find('.modal-dialog').load(url, function () {
            console.log('helllo');
        });

       return false;
    });

    // bind model save button and update the selected ids to modal form
    $('#groupActionModal').on('shown.bs.modal', function (e) {

        var selectedIDs = [],
            _this = this;

        $('input[data-linz-control="checked-record"]:checked').each(function () {
            selectedIDs.push($(this).val());
        });

        // add selected IDs to hidden field
        $(_this).find('[data-group-action="ids"]').val(selectedIDs);

        // add form validation
        $(_this).find('form').bootstrapValidator({});

    });

    function removeFomList (list, value, separator) {
        separator = separator || ",";
        var values = list.split(separator);

        for(var i = 0 ; i < values.length ; i++) {
            if(values[i] === value) {
                values.splice(i, 1);
                return values.join(separator);
            }
        }

        return list;

    }

    function assignRemoveButton (queryObj) {

        // remove all event listener
        $('.fa-times').unbind();

        // re-assign listeners including any new ones added to DOM after page load
        $('.fa-times').click(function () {

            var filteredField = $(this).attr('data-filter-field'),
                selectedFilters = $('.selectedFilters').val(),
                numOfSameFilters = $('.fa-times[data-filter-field=' + filteredField + ']').length;

            filtersAreDirty = true;

            // ensure there are no multiple filters on the same field, before removing it from the list
            if (numOfSameFilters <= 1) {

                selectedFilters = removeFomList(selectedFilters, filteredField)

                $('.selectedFilters').val(selectedFilters);

                if (selectedFilters.length <= 0) {
                    toggleFilterBox();
                    // since there are no filters, let's post the form to clear all filters except the sorting
                    // submit the form and reset the pagination
                    triggerSubmit();
                }

            }

            $(this).parents('.form-group').remove();
        });
    }

    function toggleFilterBox(showOrHide) {
        if (showOrHide) {
            $('.filters').show();
        } else {
            $('.filters').hide();
        }
    }

    // trigger a click of the 'filter' button
    function triggerSubmit () {

        // click the button
        $('.filters').find(':submit').click();

    }

})();
<|endoftext|>


<commit_before>/*
	MIT License http://www.opensource.org/licenses/mit-license.php
	Author Tobias Koppers @sokra
*/
var path = require("path");

function RequestShortener(directory) {
	var parentDirectory = path.dirname(directory);
	if(/[\/\\]$/.test(directory)) directory = directory.substr(0, directory.length - 1);
	if(directory) {
		var currentDirectoryRegExp = directory.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
		currentDirectoryRegExp = new RegExp("^" + currentDirectoryRegExp + "|(!)" + currentDirectoryRegExp, "g");

		this.currentDirectoryRegExp = currentDirectoryRegExp;
	}

	if(/[\/\\]$/.test(parentDirectory)) parentDirectory = parentDirectory.substr(0, parentDirectory.length - 1);
	if(parentDirectory && parentDirectory !== directory) {
		var parentDirectoryRegExp = parentDirectory.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
		parentDirectoryRegExp = new RegExp("^" + parentDirectoryRegExp + "|(!)" + parentDirectoryRegExp, "g");

		this.parentDirectoryRegExp = parentDirectoryRegExp;
	}

	if(__dirname.length >= 2) {
		var buildins = path.join(__dirname, "..");
		var buildinsAsModule = currentDirectoryRegExp.test(buildins);
		var buildinsRegExp = buildins.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
		buildinsRegExp = new RegExp("^" + buildinsRegExp + "|(!)" + buildinsRegExp, "g");

		this.buildinsAsModule = buildinsAsModule;
		this.buildinsRegExp = buildinsRegExp;
	}

	this.node_modulesRegExp = /\/node_modules\//g;
	this.index_jsRegExp = /\/index.js(!|\?|\(query\))/g;
}
module.exports = RequestShortener;

RequestShortener.prototype.shorten = function(request) {
	if(!request)
		return request;
	if(this.buildinsAsModule && this.buildinsRegExp)
		request = request.replace(this.buildinsRegExp, "!(webpack)");
	if(this.currentDirectoryRegExp)
		request = request.replace(this.currentDirectoryRegExp, "!.");
	if(this.parentDirectoryRegExp)
		request = request.replace(this.parentDirectoryRegExp, "!..");
	if(!this.buildinsAsModule && this.buildinsRegExp)
		request = request.replace(this.buildinsRegExp, "!(webpack)");
	request = request.replace(/\\/g, "/");
	request = request.replace(this.node_modulesRegExp, "/~/");
	request = request.replace(this.index_jsRegExp, "$1");
	return request.replace(/^!|!$/, "");
};
<commit_msg>fixes #266<commit_after>/*
	MIT License http://www.opensource.org/licenses/mit-license.php
	Author Tobias Koppers @sokra
*/
var path = require("path");

function RequestShortener(directory) {
	var parentDirectory = path.dirname(directory);
	if(/[\/\\]$/.test(directory)) directory = directory.substr(0, directory.length - 1);
	if(directory) {
		var currentDirectoryRegExp = directory.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
		currentDirectoryRegExp = new RegExp("^" + currentDirectoryRegExp + "|(!)" + currentDirectoryRegExp, "g");

		this.currentDirectoryRegExp = currentDirectoryRegExp;
	}

	if(/[\/\\]$/.test(parentDirectory)) parentDirectory = parentDirectory.substr(0, parentDirectory.length - 1);
	if(parentDirectory && parentDirectory !== directory) {
		var parentDirectoryRegExp = parentDirectory.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
		parentDirectoryRegExp = new RegExp("^" + parentDirectoryRegExp + "|(!)" + parentDirectoryRegExp, "g");

		this.parentDirectoryRegExp = parentDirectoryRegExp;
	}

	if(__dirname.length >= 2) {
		var buildins = path.join(__dirname, "..");
		var buildinsAsModule = currentDirectoryRegExp && currentDirectoryRegExp.test(buildins);
		var buildinsRegExp = buildins.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
		buildinsRegExp = new RegExp("^" + buildinsRegExp + "|(!)" + buildinsRegExp, "g");

		this.buildinsAsModule = buildinsAsModule;
		this.buildinsRegExp = buildinsRegExp;
	}

	this.node_modulesRegExp = /\/node_modules\//g;
	this.index_jsRegExp = /\/index.js(!|\?|\(query\))/g;
}
module.exports = RequestShortener;

RequestShortener.prototype.shorten = function(request) {
	if(!request)
		return request;
	if(this.buildinsAsModule && this.buildinsRegExp)
		request = request.replace(this.buildinsRegExp, "!(webpack)");
	if(this.currentDirectoryRegExp)
		request = request.replace(this.currentDirectoryRegExp, "!.");
	if(this.parentDirectoryRegExp)
		request = request.replace(this.parentDirectoryRegExp, "!..");
	if(!this.buildinsAsModule && this.buildinsRegExp)
		request = request.replace(this.buildinsRegExp, "!(webpack)");
	request = request.replace(/\\/g, "/");
	request = request.replace(this.node_modulesRegExp, "/~/");
	request = request.replace(this.index_jsRegExp, "$1");
	return request.replace(/^!|!$/, "");
};
<|endoftext|>