
//Elimina los espacios de la derecha
String.prototype.lTrim = function()
{
	var mascara = /\s*((\S+\s*)*)/;

	return this.replace( mascara, "$1" );
}

//Elimina los espacios de la izquierda
String.prototype.rTrim = function()
{
	var mascara = /((\s*\S+)*)\s*/;

	return this.replace( mascara, "$1" );
}

//Elimina los espacios de la izquierda y derecha
String.prototype.trim = function()
{
  return this.lTrim().rTrim();
}






/* ========================================================= < String.prototype.tieneLongitudCero() >
	Parámetros:
		this: es el propio objeto String que invoca a la función

	Prototipo String para comprobar si la cadena tiene longitud cero.
================================================================================================== */
String.prototype.tieneLongitudCero = function()
{
	if ( this.trim().length == 0 ) return true;
	return false;
}






/* ======================================================= < String.prototype.caracteresCorrectos() >
	Parámetros:
		this: es el propio objeto String que invoca a la función
		arrayCaracteres: array con los carécteres válidos que puede tener el String

	Función que devuelve true si cada uno de los carácteres del objeto String es igual a alguno de
	los carácteres de del array, en caso contrario devuelve false.

	NOTA: arrayCaracteres no necesita contener carácteres en minúsculas porque dichos carácteres se
	comparan convirtiéndose previamente a mayúsuclas.
================================================================================================== */
String.prototype.caracteresCorrectos = function( arrayCaracteres )
{
	for ( var i = 0 ; i < this.length ; i ++ )
	{
		for ( var j = 0 ; ( j < arrayCaracteres.length ) && ( this.charAt( i ).toUpperCase() != arrayCaracteres.charAt( j ).toUpperCase() ) ; j ++ )
		{
			if ( j == ( arrayCaracteres.length - 1 ) ) return false;
		}
	}

	return true;
}






/* ========================================================== < String.prototype.numeroCaracteres() >
	Parámetros:
		this: es el propio objeto String que invoca a la función
		caracter: carácter que se pretende contar del String

	Prototipo String para contar el número de carácteres que contiene la cadena iguales al carácter
	recibido.
================================================================================================== */
String.prototype.numeroCaracteres = function( caracter )
{
  var cantidad = 0;

  for ( var i = 0 ; i < this.length ; i ++ )
  {
    if ( this.charAt( i ) == caracter ) cantidad ++;
  }

  return cantidad;
}






String.prototype.getIntBase10 = function() { return ( parseInt( this, 10 ) ); } //........... decimal






/* ============================================================ < String.prototype.esNumeroEntero() >
	Parámetros:
		this: es el propio objeto String que invoca a la función

	Prototipo String para comprobar si la cadena está en formato número entero no decimal.
================================================================================================== */
String.prototype.esNumeroEntero = function()
{
	if ( this.tieneLongitudCero() ) return false;

	if ( ! this.caracteresCorrectos( "0123456789" ) ) return false;

	return true;
}

String.prototype.esPrecio = function()
{
	if ( this.tieneLongitudCero() ) return false;

	if ( ! this.caracteresCorrectos( "0123456789.," ) ) return false;

	return true;
}
/* ================================================================== < String.prototype.esMoneda() >
	Parámetros:
		this: es el propio objeto String que invoca a la función

	Prototipo String para comprobar si la cadena está en formato moneda.
================================================================================================== */
String.prototype.esMoneda = function()
{
	if ( this.tieneLongitudCero() ) return false;

	var numeroConvertido = this.replace( /,/g, '.' ); //................ reemplaza coma por punto

	if ( ! numeroConvertido.caracteresCorrectos( "0123456789." ) ) return false;

	if ( numeroConvertido.numeroCaracteres( '.' ) > 1 ) return false; //... ¿hay más de una coma?
	
	return true;
}


/* ================================================================== < String.prototype.esTexto() >
	Parámetros:
		this: es el propio objeto String que invoca a la función

	Prototipo String para comprobar si la cadena está en formato texto.
================================================================================================= */
String.prototype.esTexto = function()
{
	if ( ! this.caracteresCorrectos( "ABCDEFGHIJKLMNÑOPQRSTUVWXYZÁÉÍÓÚ%&/()!¡¿?[]{}@#+-ç€*ºª-_:;,. " ) ) return false;
	return true;
}






function CIFNIFCorrecto( elementValue, elementName )
{
	var i, suma = 0, cifnif = elementValue.toUpperCase(), num_aux, letra_correcta = false;

	if ( cifnif.trim() == '' ) //............................................... Comprobación General
	{
		alert( "Por favor, introduzca un valor en el campo \"" + elementName + "\"." );
		return false;
	}

	for( i = 1 ; i < 7 ; i += 2 ) //............................................ Comprobación del CIF
	{
		suma = suma + cifnif.substring( i + 1 , i + 2 ).toString().getIntBase10();
		num_aux = cifnif.substring( i, i + 1 ).toString().getIntBase10();
		suma = suma + "0246813579".substring( num_aux, num_aux + 1 ).toString().getIntBase10();
	}

	num_aux = cifnif.substring( i, i + 1 ).toString().getIntBase10();
	suma = suma + "0246813579".substring( num_aux, num_aux + 1 ).toString().getIntBase10();
	suma = 10 - ( suma % 10 );

	for ( i = 0 ; i < 12 && letra_correcta == false ; i ++ )
	{
		if ( cifnif.substring( 0, 1 ) == "ABCDEFGHNPQS".substring( i, i + 1 ) ) letra_correcta = true;
	}

	if ( letra_correcta == true ) //.................................................. 1º TIPO DE CIF
	{
		if ( cifnif.substring( 8, 9 ) == String.fromCharCode( 64 + suma ) || cifnif.substring( 8, 9 ) == suma.toString().substring( suma.toString().length - 1, suma.toString().length ) )
		return true;
	}
	else //........................................................................... 2º TIPO DE CIF
	{
		for ( i = 0 ; i < 3 && letra_correcta == false ; i ++ )
		{
			if ( cifnif.substring( 0, 1 ) == "KLM".substring( i, i + 1 ) ) letra_correcta = true;
		}

		if ( letra_correcta == true )
		{
			if ( cifnif.substring( 8, 9 ) == ( 64 + suma ) ) return true;
		}
	}

	for( i = 0 ; i < 26 && letra_correcta == false ; i ++ ) //.................. Comprobación del NIF
	{
		if ( cifnif.substring( 8, 9 ) == "ABCDEFGHIJKLMNOPQRSTUVWXYZ".substring( i, i + 1 ) ) letra_correcta = true;
	}

	if ( letra_correcta == true ) //............................................................. NIF
	{
		if ( cifnif.substring( 0, 1 ) == 'X' ) cifnif.substring( 0, 1 ) = '0'; // NIE, cambia X por 0

		num_aux = ( cifnif.substring( 0, 8 ) % 23 ).toString().getIntBase10();
		if ( cifnif.substring( 8, 9 ) == "TRWAGMYFPDXBNJZSQVHLCKE".substring( num_aux, num_aux + 1 ) ) return true;
	}

	alert( "Por favor, introduzca un CIF o NIF válido en el campo \"" + elementName + "\"." );
	return false;
}






function emailCorrecto( elementValue, elementName )
{
	//.......................................................................... Comprobación General
	var intPosArroba, intPosPunto;

	intPosArroba = elementValue.indexOf( '@' , 0 );
	intPosPunto = elementValue.indexOf( '.', intPosArroba );

	if ( elementValue.trim() == '' || intPosArroba == -1 || elementValue.numeroCaracteres( '@' ) > 1 || intPosPunto == -1 ||
	 	 elementValue.substring( intPosArroba + 1, elementValue.length ).numeroCaracteres( '.' ) > 1 )
	{
		alert( "Por favor, escriba el \"" + elementName + "\" en el formato siguiente: cuenta@servidor.dominio" );
		return false;
	}

	//.......................................... Comprobación de número de caracteres en campo e-Mail
	var strNombre = elementValue.substring( 0, intPosArroba );
	var strGestor = elementValue.substring( intPosArroba + 1, intPosPunto );
	var strDominio = elementValue.substring( intPosPunto + 1, elementValue.length );

	if ( strNombre.length < 2 || strNombre.length > 80 || strGestor.length < 2 || strGestor.length > 20 || strDominio.length < 2 || strDominio.length > 6 )
	{
		alert( "Por favor, escriba el \"" + elementName + "\" en el formato siguiente: cuenta@servidor.dominio, donde:\n    \"cuenta\"   [entre 2 y 80 caracteres],\n    \"servidor\" [entre 2 y 20 caracteres],\n    \"dominio\"  [entre 2 y   6 caracteres]" );
		return false;
	}

	//.................................................... Comprobación de caracteres en campo e-Mail
	//................................................................. ¿nombre empiez por una letra?
	if ( ! elementValue.substring( 0, 1 ).caracteresCorrectos( "ABCDEFGHIJKLMNOPQRSTUVWXYZ" ) )
	{
		alert( "Por favor, escriba el \"" + elementName + "\" en el formato siguiente: cuenta@servidor.dominio, donde:\n    \"cuenta\" debe empezar por una letra\nEj: a3@gmail.com" );
		return false;
	}

	//..................................................................... ¿nombre no acabar en '.'?
	if ( elementValue.charAt( intPosArroba - 1 ) == '.' )
	{
		alert( "Por favor, escriba el \"" + elementName + "\" en el formato siguiente: cuenta@servidor.dominio, donde:\n    \"cuenta\" no puede acabar en \".\"\nEj: a.c@gmail.com" );
		return false;
	}

	//............................................... ¿contiene letras, números, '.', '-', '_' o '@'?
	if ( ! elementValue.caracteresCorrectos( "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789.-_@" ) )
	{
		alert( "Ha introducido carácteres no válidos en el campo \"" + elementName + "\"." );
		return false;
	}

	if ( ! dominioCorrecto( strDominio ) )
	{
		alert( "Ha introducido un dominio no válido en el campo \"" + elementName + "\". (cuenta@servidor.dominio)" );
		return false;
	}

	return true;
}

function dominioCorrecto( domain )
{
	var arrayDominios = new Array( "AC","AD","AE","AERO","AF","AG","AI","AL","AM","AN","AO","AQ","AR","ARPA","AS","AT","AU","AW","AX","AZ","BA","BB","BD","BE","BF","BG","BH","BI","BIZ","BJ","BM","BN","BO","BR","BS","BT","BV","BW","BY","BZ","CA","CAT","CC","CD","CF","CG","CH","CI","CK","CL","CM","CN","CO","COM","COOP","CR","CU","CV","CX","CY","CZ","DE","DJ","DK","DM","DO","DZ","EC","EDU","EE","EG","ER","ES","ET","EU","FI","FJ","FK","FM","FO","FR","GA","GB","GD","GE","GF","GG","GH","GI","GL","GM","GN","GOV","GP","GQ","GR","GS","GT","GU","GW","GY","HK","HM","HN","HR","HT","HU","ID","IE","IL","IM","IN","INFO","INT","IO","IQ","IR","IS","IT","JE","JM","JO","JOBS","JP","KE","KG","KH","KI","KM","KN","KR","KW","KY","KZ","LA","LB","LC","LI","LK","LR","LS","LT","LU","LV","LY","MA","MC","MD","MG","MH","MIL","MK","ML","MM","MN","MO","MOBI","MP","MQ","MR","MS","MT","MU","MUSEUM","MV","MW","MX","MY","MZ","NA","NAME","NC","NE","NET","NF","NG","NI","NL","NO","NP","NR","NU","NZ","OM","ORG","PA","PE","PF","PG","PH","PK","PL","PM","PN","PR","PRO","PS","PT","PW","PY","QA","RE","RO","RU","RW","SA","SB","SC","SD","SE","SG","SH","SI","SJ","SK","SL","SM","SN","SO","SR","ST","SU","SV","SY","SZ","TC","TD","TF","TG","TH","TJ","TK","TL","TM","TN","TO","TP","TR","TRAVEL","TT","TV","TW","TZ","UA","UG","UK","UM","US","UY","UZ","VA","VC","VE","VG","VI","VN","VU","WF","WS","YE","YT","YU","ZA","ZM","ZW" );

	for ( i = 0 ; i < arrayDominios.length ; i ++ )
	{
		if ( arrayDominios[ i ] == domain.toUpperCase() ) return true;
	}

	return false;
}

