function css_load(csss, path)
{
	var mask;
	switch (navigator.appName)
	{
	case "Microsoft Internet Explorer":
		mask = "ie";
		break;
	case "Netscape":
		mask = "ns";
		break;
	default:
		mask = "ie";
		break;
	}
	mask = "ie";
	if (path == null)
		path = "../_dhtml";
	
	if (path.substr(path.length - 1) != "/")
		path += "/";
	csss = csss.split(",");
	for(var cnt = 0; cnt < csss.length; cnt++)
		document.write("<link rel=\"stylesheet\" type=\"text/css\" href=\"" + path + mask + "_" + csss[cnt] + ".css\">");
}

//Es podria fusionar en algun moment amb css_load
function navigator_detect()
{
	var mask;
	
	switch (navigator.appName)
	{
	case "Microsoft Internet Explorer":
		mask = "";
		break;
	case "Netscape":
		mask = "ff";
		break;
	default:
		mask = "";
		break;
	}	
	if(mask != "")
		{		
		document.write("<LINK rel=\"stylesheet\" type=\"text/css\" href=\"/WEBSRP/_dhtml/dir_" + mask + "_style.css\">");
		}
}

function abrir_ventana(pagina, anchura, altura, vtoolbar, vlocation, vdirectories, vstatus, vmenubar, vscrollbars, vresizable)
{
	//ABRE UNA VENTANA NUEVA CON LOS DATOS Y CARACTERISTICAS ESPECIFICADOS
	var anchurapantalla;
	var alturapantalla;
	var posicionx;
	var posiciony;
	
	anchurapantalla=screen.width;
	alturapantalla=screen.height;

	if(anchurapantalla>screen.width)
		{
		anchurapantalla=screen.width;
		}
	if(alturapantalla>screen.height)
		{
		alturapantalla=screen.height;
		}
	posicionx=(anchurapantalla/2)-(anchura/2);
	posiciony=(alturapantalla/2)-(altura/2);
	control = window.open(pagina,'ventana'+anchura,'toolbar='+vtoolbar+',location='+vlocation+',directories='+vdirectories+',status=' + vstatus + ', menubar='+vmenubar+',scrollbars='+vscrollbars+',resizable='+vresizable+', width='+anchura+',height='+altura+',top='+posiciony+',left='+posicionx+'');
	control.focus();
}
	
function abrir_ventana_destacado(pagina, anchura, altura, vtoolbar, vlocation, vdirectories, vstatus, vmenubar, vscrollbars, vresizable)
{
	abrir_ventana(pagina, anchura, altura, vtoolbar, vlocation, vdirectories, vstatus, vmenubar, vscrollbars, vresizable);
}

// Funcions per validar NIF

function calcularNIF(dni) {
	var letras, numero;
	//Número introduït no és vàlid
	if (!/^\d{8}$/.test(dni)) 
		return '';
	letras = 'TRWAGMYFPDXBNJZSQVHLCKE';
	numero = dni%23;
	return letras.substring(numero, numero + 1);
}

function validarNIF(nif) {
	var lletraNIF, dni, lletra;
	//Si és una tarjeta de residència substituïm la x inicial per un 0
	if (nif.substring(0, 1).toUpperCase() == 'X')
	{
		nif = PadLeft(nif.substring(1, nif.length), 9, '0');
	}
	else if (nif.substring(0, 1).toUpperCase() == 'Y')
	{
		nif = PadLeft(nif.substring(1, nif.length), 9, '1');
	}
	else if (nif.substring(0, 1).toUpperCase() == 'Z')
	{
		nif = PadLeft(nif.substring(1, nif.length), 9, '2');
	}
	lletraNIF = nif.substring(8, 9).toUpperCase();
	dni = nif.substring(0, 8);
	lletra = calcularNIF(dni);
	//NIF introduït no és vàlid
	if ((lletra == '') || (lletra != lletraNIF))
		return false;
	return true;
}


//Funció per validar un valor amb array d'expressions regulars
//Si hi ha un valor que validi amb una expressió regular (OR), aleshores és correcte 
function validar(regularExpressions, valor) 
{
	var valor = valor.toLowerCase();
	for (var i = 0; i < regularExpressions.length; i++)
	{
		var y = new RegExp(regularExpressions[i], "gi");
		if (y.test(valor) == true)
			return true;
	}
	return false;
}

/**
* Validació d'una compte corrent
* 
* Comprova un número de compte corrent
*
* IN:  cc1	 string	 Primers vuit dígits de la compte corrente (entitat.oficina)
* IN:  cc2  string  Últims deu dígits de la compte corrent (#compte)
* IN:  dc   string  Dígits de control
* OUT:      bool    compte vàlid? 
*/
function calcularDC(cc1, cc2)
{
	var arrWeights = new Array(1,2,4,8,5,10,9,7,3,6);	// vector de pesos
    var dc1=0, dc2=0;
    
    /*
    * Càlcul del primer dígit de control
    */
   	for (i=(cc1.length-1);i>=0;i--) dc1 += arrWeights[i+2] * cc1.charAt(i);
    dc1 = 11 - (dc1 % 11);
  	if (11 == dc1) dc1 = 0;
   	if (10 == dc1) dc1 = 1;
    
   	/*
   	* Càlcul del segon dígit de control
   	*/
   	for (i=(cc2.length-1);i>=0;i--) dc2 += arrWeights[i] * cc2.charAt(i);
    dc2 = 11 - (dc2 % 11);
   	if (11 == dc2) dc2 = 0;
    if (10 == dc2) dc2 = 1;
    
    /*
    * Comprovar la coincidència i retornar el resultat
    */
    return (10*dc1+dc2);	// Javascript infereix tipus sencer per dc1 i dc2
}

function validarCC(cc1, cc2, cc3, cc4)
{
	return (cc3 == calcularDC(cc1+cc2, cc4));      		
}

function validarLocalitzador(cc1, cc2, cc3)
{
	return (cc3 == calcularDC(PadLeft(cc1,8,'0'), PadLeft(cc2,10,'0')));      		
}

//Funcios de digit control que estaven a WebSRP
/*
function calcularDC(cc1, cc2, dc)
{
	var arrWeights = new Array(1,2,4,8,5,10,9,7,3,6);	// vector de pesos
    var dc1=0, dc2=0;
    
    //
    // Càlcul del primer dígit de control
    //
   	for (i=7;i>=0;i--) dc1 += arrWeights[i+2] * cc1.charAt(i);
    dc1 = 11 - (dc1 % 11);
  	if (11 == dc1) dc1 = 0;
   	if (10 == dc1) dc1 = 1;
    
   	//
   	// Càlcul del segon dígit de control
   	//
   	for (i=9;i>=0;i--) dc2 += arrWeights[i] * cc2.charAt(i);
    dc2 = 11 - (dc2 % 11);
   	if (11 == dc2) dc2 = 0;
    if (10 == dc2) dc2 = 1;
    
    //
    //Comprovar la coincidència i retornar el resultat
    //
    return (10*dc1+dc2 == dc);	// Javascript infereix tipus sencer per dc1 i dc2
}

function validarCC(cc1, cc2, cc3, cc4)
{
	return calcularDC(cc1+cc2, cc4, cc3);      		
}
*/

//Funció per treure espais a dreta i esquerra
function Value_Trim(Value)
 {
	var Length;
	Length = Value.length;

	for(Cnt = 0; Cnt < Value.length && Value.charAt(Cnt) == " "; Cnt++);
	Value = Value.substr(Cnt);

	for(Cnt = Value.length - 1; Cnt >= 0 && Value.charAt(Cnt) == " "; Cnt--);
	Value = Value.substring(0, Cnt + 1);

	return(Value);
 }
 
 function PadLeft(cadena, longitud, caracter)
 {
	var longCadena = cadena.length;
	var sTmp;
	sTmp = "";
	if (longCadena >= longitud)
	{
		return cadena;
	}
	sTmp = cadena
	for (cnt = 0; cnt < longitud - longCadena; cnt++)
	{
		sTmp = caracter + sTmp;
	}
	return sTmp;
 }
 
//Funcions per verificar targetes de crèdit
 
/*
There are three functions in this set for credit card validation.
The main function is:
validateCard(cardNumber,cardType,cardMonth,cardYear)
	parameters:
		all paramaters are string values.
		Month & Year come from the select input fields in the form, so they are defined.
		cardType can be:
			'a' for American Express
			'd' for Discover
			'm' for MasterCard
			'v' for Visa
	description:
		this function will check string length, valid characters, specific credit card prefixes and test
		the Mod 10 (LUHN Formula) for validating possible credit card numbers. this function can only
		authorize that the given card data is potentially valid. You would still need to run actual
		card validation routines to verify the actual account.
	returns:
		this function returns true if the card number could be valid for the card type and expiration date.
		false otherwise.	
supporting functions:
mod10( cardNumber )
	parameters:
		this function takes the text string card number and runs the Mod 10 formula on its respective digits.
	description:
		Mod 10 is the check digit formula for the supported cards these functions attempt to validate.
	returns:
		this function returns true if the number passes the check digit test.
		false otherwise.
expired( cardMonth, cardYear )
	parameters:
		this function takes the text string values given by the html form.
	description:
		this function basically will check to make sure todays date is less than the expiration date the user inputs.
		this function is not locked into using 2 digit dates.
	returns:
		this fucntion returns true if the card is expired.
		false otherwise.
*/

function mod10( cardNumber ) { // LUHN Formula for validation of credit card numbers.
	var ar = new Array( cardNumber.length );
	var i = 0,sum = 0;

    for( i = 0; i < cardNumber.length; ++i ) {
    	ar[i] = parseInt(cardNumber.charAt(i));
    }
    for( i = ar.length -2; i >= 0; i-=2 ) { // you have to start from the right, and work back.
    	ar[i] *= 2;							 // every second digit starting with the right most (check digit)
    	if( ar[i] > 9 ) ar[i]-=9;			 // will be doubled, and summed with the skipped digits.
    }										 // if the double digit is > 9, ADD those individual digits together 
    for( i = 0; i < ar.length; ++i ) {
        sum += ar[i];						 // if the sum is divisible by 10 mod10 succeeds
    }
    return (((sum%10)==0)?true:false);
}

function expired( month, year ) {
    var now = new Date();							// this function is designed to be Y2K compliant.
    var expiresIn = new Date(year,month,0,0,0);		// create an expired on date object with valid thru expiration date
    expiresIn.setMonth(expiresIn.getMonth()+1);		// adjust the month, to first day, hour, minute & second of expired month
    if( now.getTime() < expiresIn.getTime() ) return false;
    return true;									// then we get the miliseconds, and do a long integer comparison
}

function validateCard(cardNumber,cardType,cardMonth,cardYear) {
	if( cardNumber.length == 0 ) {						//most of these checks are self explanitory
        alert("Please enter a valid card number.");
        return false;				
    }
    for( var i = 0; i < cardNumber.length; ++i ) {		// make sure the number is all digits.. (by design)
        var c = cardNumber.charAt(i);
        if( c < '0' || c > '9' ) {
            alert("Please enter a valid card number. Use only digits. do not use spaces or hyphens.");
            return false;
        }
	}
	var length = cardNumber.length;			//perform card specific length and prefix tests
	switch( cardType ) {
		case 'a':
			if( length != 15 ) {
				alert("Please enter a valid American Express Card number.");
				return;
			}
            var prefix = parseInt( cardNumber.substring(0,2));
            if( prefix != 34 && prefix != 37 ) {
                alert("Please enter a valid American Express Card number.");
                return;
            }
            break;
        case 'd':
            if( length != 16 ) {
                alert("Please enter a valid Discover Card number.");
                return;
            }
			var prefix = parseInt( cardNumber.substring(0,4));
            if( prefix != 6011 ) {
                alert("Please enter a valid Discover Card number.");
                return;
            }
            break;
		case 'm':
            if( length != 16 ) {
                alert("Please enter a valid MasterCard number.");
                return;
            }
			var prefix = parseInt( cardNumber.substring(0,2));
            if( prefix < 51 || prefix > 55) {
                alert("Please enter a valid MasterCard Card number.");
                return;
            }
            break;
		case 'v':
            if( length != 16 && length != 13 ) {
                alert("Please enter a valid Visa Card number.");
                return;
            }
            var prefix = parseInt( cardNumber.substring(0,1));
            if( prefix != 4 ) {
                alert("Please enter a valid Visa Card number.");
                return;
            }
            break;
	}
    if( !mod10( cardNumber ) ) { 		// run the check digit algorithm
        alert("Sorry! this is not a valid credit card number.");
        return false;
    }
    if( expired( cardMonth, cardYear ) ) {							// check if entered date is already expired.
        alert("Sorry! The expiration date you have entered would make this card invalid.");
        return false;
    }
	return true; // at this point card has not been proven to be invalid
}
