/* Funciones javascript de uso general */

/* autor: Francisco Sánchez */



/////////////////////////////////////////////

// CONTADOR DE CARACTERES PARA UN TEXTAREA //

/////////////////////////////////////////////



/* USO:

	<textarea name="t" cols="200" rows="20" 

	  onKeyPress="javascript:restarCaracter(document.form1.t,document.form1.in,4000);"

	  onKeyUp="javascript:muestraTotal(document.form1.t,document.form1.in,4000);"></textarea>

	  

	<input type="text" name="in" value="4000" maxlength="4" size="4" align="left" valign="top" disabled="true">

	<script>muestraTotal(document.form1.t,document.form1.in,4000);</script>

*/



function restarCaracter( textArea, inputText, numCaracteres ) {

	var tecla = window.event.keyCode;

	if ( tecla == 8 ) {

		numCaracteres++;

	} else { 

		numCaracteres--;

	}

	inputText.value = numCaracteres - textArea.value.length;

}



function muestraTotal( textArea, inputText, numCaracteres ) {

	inputText.value = numCaracteres - textArea.value.length;

}



////////////////////////

// Cambio de Imagenes //

////////////////////////

function Permut (flag,img) {

   if (document.images) {

        if (document.images[img].permloaded) {

            if (flag==1) document.images[img].src = document.images[img].perm.src

            else document.images[img].src = document.images[img].perm.oldsrc

        }

   }

}

function preloadPermut (img,adresse) {

   if (document.images) {

        img.onload = null;

        img.perm = new Image ();

        img.perm.oldsrc = img.src;

        img.perm.src = adresse;

        img.permloaded = true;

   }

}



function abrirVentana(var1) {  

	var ventana = window.open( var1, null, 'width=500,height=450,top=50,left=100,scrollbars=yes' );

	ventana.focus(); 

}   

function abrirVentanaParam(width,height,action,id)  
{  
	var ventana=window.open("",'va','width='+width+',height='+height+',top=50,left=100,scrollbars=yes');
	document.forms["av"].action=action+id;
	document.forms["av"].submit();
	ventana.focus(); 
}   

///////////

// RADIO //

///////////

/* Devuelve true si hay alguna opción seleccionada */

function isRadioSelected( r ) {

	if ( r.length != null ) { // Caso de n radio buttons

		for ( i = 0; i < r.length; i++ ) {

			if ( r[i].checked ) {

				return true;

			}

		}		

		return false;

	} else { // Caso de 1 radiobutton

		return r.checked;

	}

}



function getRadioSelected( r ) {

	if ( r.length != null ) { // caso de n radio buttons

		for ( i = 0; i < r.length; i++ ) {

			if ( r[i].checked ) {

				return r[i].value;

			}

		}

		return "-1";

	} else { // caso 1 radio button

		return r.value;

	}

}

	

///////////////

// CHECKBOX  //

///////////////



/* Realiza el submit del formulario que se le pasa 		*

 * como parámetro e invoca a una operación del servlet 	*/

function operacion(frm,operacion) {

	frm.METHOD.value = operacion;

	frm.submit();

}



/* Devuelve true si hay algun check seleccionado */

function isAnyElementChecked(frm,nombreCheck) {

	for ( i=0; i<frm.elements.length; i++ ) {

		if (( frm.elements[i].type=="checkbox" )&&( frm.elements[i].name==nombreCheck )) {

			if ( frm.elements[i].checked ) return true;

		}

	}

	return false;

}



/* marca o desmarca todos */

function setAllCheck(frm,nombreCheck,what) {

	for ( i=0; i<frm.elements.length; i++ ) {

		if (( frm.elements[i].type=="checkbox" )&&( frm.elements[i].name==nombreCheck )) {

			frm.elements[i].checked = what;

		}

	}

}



////////////

// SELECT //

////////////



/* Elimina todas las opciones del select que se le pasa como parámetro*/

function removeAllOptionsSel( sel ) {

	while( sel.length > 0 ) { 

		sel.options[0] = null; 

	}

}

	

/* Añade una nueva opción al select que se pasa como parámetro */

function addNewOptionSel( sel, text, value ) {

	var opt = new Option( text, value );

	sel.options[sel.length] = opt;

}

	

/* Selecciona la opción cuyo value se pasa como parámetro */

function selectOptionSel( sel, value ) {

	var optionSelected = 0;

	for ( var i = 0; i < sel.length; i++ ) {

		if ( sel.options[i].value == value ) { 

			optionSelected = i; 

		}

	}

	sel.options.selectedIndex = optionSelected;	

}



/* Devuelve el campo value de la opcion seleccionada del select que se *

 * pasa como parámetro 												   */				

function getValueOptionSelected( sel ) {

	var i = sel.options.selectedIndex;

	return sel.options[i].value;

}



/* Devuelve el campo text de la opcion seleccionada del select que se *

 * pasa como parámetro 												  */				

function getTextOptionSelected( sel ) {

	var i = sel.options.selectedIndex;

	return sel.options[i].text;

}

function getAllOptionsSelected(sel) {

	var str = "";

	for ( var i = 0; i < sel.options.length; i++ ) {

		var valorOpcion = sel.options[i].value;

		if ( i == 0 && sel.options[i].selected) {

			str = valorOpcion;

		} else if(sel.options[i].selected){

			str += ( "," + valorOpcion );

		}

	}

	return str;

}

/* Obtiene todos valores de un select en un string separados por comas */

function getAllOptions(sel) {

	var str = "";

	for ( var i = 0; i < sel.options.length; i++ ) {

		var valorOpcion = sel.options[i].value;

		if ( i == 0 ) {

			str = valorOpcion;

		} else {

			str += ( "," + valorOpcion );

		}

	}

	return str;

}

/* Obtiene todos valores de un select en un string separados por comas */

function getAllOptionsSpam(sel) {

	var str = "";

	for ( var i = 0; i < sel.options.length; i++ ) {

		var valorOpcion = sel.options[i].value;

		if(valorOpcion.charAt(valorOpcion.length-1) != 'ñ')//Esto es para que no se añadan a la lista los que ya existen
		{
			if ( i == 0 ) {
	
				str = valorOpcion;
	
			} else {
	
				str += ( "|" + valorOpcion );
	
			}
		}

	}

	return str;

}

/* Devuelve true si existe la opcion en el select con el value pasado como parámetro */

function existOption(sel,valor) {

	for ( var i = 0; i < sel.length; i++ ) {

		if ( valor == sel.options[i].value ) return true;

	}

	return false;

}



/* Borra la opción del select cuyo value pasamos como parámetro */

function removeOptionSel(sel,valor) {

	for ( var i = 0; i < sel.options.length; i++ ) {

		if ( valor == sel.options[i].value ) {

			sel.options[i] = null;

			return;

		}

	}

}



/* Devuelve el número de opciones seleccionadas */

function getNumOptionsSelected(sel) {

	var count = 0;

	for ( var i = 0; i < sel.options.length; i++ ) {

		if ( sel.options[i].selected ) {

			count++;

		}

	}

	return count;

}



/* Borra las opciones del select que estén seleccionadas */

function removeAllSelectedOptionsSel(sel) {

	var i = 0;	

	while( i < sel.options.length ){

		if ( sel.options[i].selected ) {

			sel.options[i] = null;

		}

		else { 

			i++;

		}

	}

}



////////////////////////////////////////////////////////////////

// FUNCIONES PARA PASAR ELEMENTOS ENTRE DOS SELECTS MULTIPLES //

////////////////////////////////////////////////////////////////

 

/* formulario    = nombre completo del formulario 				   *

 * selIncluidos  = nombre completo del select  					   *

 * seleccionados = nombre completo del input hidden del formulario */

 

function enviar( formulario, seleccionados, selIncluidos ) {

	if ( selIncluidos.options.length == 0 ) {

		alert("Debe seleccionar alguna opción");

		return;

	}

	for ( var i = 0; i < selIncluidos.length; i++ ) {

		if ( i == 0 ) {

			seleccionados.value += selIncluidos.options[i].value;

		} else {

			seleccionados.value += ( "," + selIncluidos.options[i].value );

		}

	}

	formulario.submit();

}



function deNoIncluidosAIncluidos(selNoIncluidos,selIncluidos) {

	var idIncluidos   = "";

	var descIncluidos = "";

	for ( var i=0; i < selNoIncluidos.length; i++ )	{

		if ( selNoIncluidos[i].selected == true)	{

			var opt = new Option(selNoIncluidos.options[i].text,selNoIncluidos.options[i].value);

			var j = selIncluidos.length;

			selIncluidos.options[j]   = opt;

			selNoIncluidos.options[i] = null;

			i--;

		}

	}

}



function deIncluidosANoIncluidos(selNoIncluidos,selIncluidos) {

	var idNoIncluidos   = "";

	var descNoIncluidos = "";

	for ( var i=0; i < selIncluidos.length; i++ ) {

		if ( selIncluidos[i].selected ) {

			var opt = new Option(selIncluidos.options[i].text,selIncluidos.options[i].value);

			var j = selNoIncluidos.length;

			selNoIncluidos.options[j] = opt;

			selIncluidos.options[i]   = null;

			i--;

		}

	}						

}





function Trim(orgString){

  return LTrim(RTrim(orgString))

}



function LTrim(orgString){

  return orgString.replace(/^\s+/,'')

}



function RTrim(orgString){

  return orgString.replace(/\s+$/,'')

}



function contarCarac(maxChars, ta, cont)

{

	//MaxChars: Nº máximo de caracteres

	//ta: Textarea fuente de los datos

	//cont: Textfield informador de tamaño restante

	

	cadena=ta.value;

	cont.value=maxChars - cadena.length;

	if ((maxChars - cadena.length) < 0)

	{

		ta.value=cadena.substring(0,eval(maxChars));

		cont.value=0;

	}

	return;

}



/* comprueba si el parámetro es un número */

function isANumber(isenit)

{

	return !isNaN( isenit.valueOf() );

}


