/*
*	Diego Esneider Cortes Serna
*	2009
*/

//Retorna true si todos los campos estan correctamente llenados y no falta ningun campo obligatorio.
//false en caso contrario.
function validarCampos()
{
	var band=true;
	perderFoco();
	jQuery.each($(".diegoe87-validaciones-v1_0-error-caracteres-no-permitidos"), function(){
		band=false;
	});
	return band;
}

//Valida si una cadena es de solo numeros.
//Caracteres validos: 0123456789
function validarNumero(valor){
	if (/^\d+$/.test(valor))
		return true;
	else
		return false;
}

//Valida si una cadena es de solo letras.
//Caracteres validos: abcdefghijklmnñopqrstuvxyz
function validarTexto(valor){
	if (/^[a-zA-ZñáéíóúÑÁÉÍÓÚ´\ ]+$/.test(valor))
		return true; 
	else
		return false;
}

function validarCorreoElectronico(valor){
	//if (/^[A-Za-z][A-Za-z0-9_.]*@[A-Za-z0-9_]+\.[A-Za-z0-9_.]+[A-za-z]$/.test(valor)) //FALTA validar el guion
	if (/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(valor))
		return true; 
	else
		return false;
}

function validarContrasenia(valor){
	//if(valor == "12345")
		//return true;
	if (/[a-zA-Z\d\+\-\*]{6}/.test(valor))
		if (/[\+\-\*]+/.test(valor))
			if (/[\d]+/.test(valor))
				if (/[a-zA-Z]+/.test(valor))
					return true; 
				else
					return false; 
			else
				return false; 
		else
			return false;
	else
		return false;
}

function validarAlfanumerico(valor){
	if (/[\w\-\.\ ]+$/.test(valor))
		return true; 
	else
		return false;
}

function validarAlfanumericoExtendido(valor){
	if (/^[\w\ \b\s\r\-\.\,\?\:\;\"\'\!\(\)\¿\¡\@\#\$\%\+\*\<\>\&\[\]\{\}ñáéíóúÑÁÉÍÓÚ/´]+$/.test(valor))
		return true; 
	else
		return false;
}
//c == '.' || c == '_' || c == '-' || c == ',' || c == '?'  || c == ':' || c == ';' || c == '\"' || c == '\'' || c == '!' || c == '¿' || c == '¡' || c == '(' || c == ')'

function esNumero(codigo){
	var c = String.fromCharCode(codigo);
	//if (/^\d+$/.test(c) || codigo == 0 || codigo == 8 || codigo == 32) // Se permite el espacio
	if (/^\d+$/.test(c) || codigo == 0 || codigo == 8 || codigo == 13)
		return true;
	else
		return false;
}

function esLetra(codigo){
	var c = String.fromCharCode(codigo);
	if (/[a-zA-Z|ñáéíóúÑÁÉÍÓÚ´]/.test(c) || codigo == 0 || codigo == 8 || codigo == 32 || codigo == 13)
		return true; 
	else
		return false;
}

function esCaracterContrasenia(codigo){
	var c = String.fromCharCode(codigo);
	if (esLetra(codigo) || esNumero(codigo) || c == '*' || c == '+' || c == '-')
		return true; 
	else
		return false;
}

function esCaracterAlfanumerico(codigo){
	var c = String.fromCharCode(codigo);
	if (esLetra(codigo) || esNumero(codigo) || c == '.' || c == '_' || c == '-')
		return true; 
	else
		return false;
}

function esCaracterAlfanumericoExtendido(codigo){
	var c = String.fromCharCode(codigo);
	if (esLetra(codigo) || esNumero(codigo) || c == '.' || c == '_' || c == '-' || c == ',' || c == '?'  || c == ':' || c == ';' || c == '\"' || c == '\'' || c == '!' || c == '¿' || c == '¡' || c == '(' || c == ')' || c == '@' || c == '#' || c == '$' || c == '%' || c == '+' || c == '*' || c == '<' || c == '>' || c == '&' || c == '/' || c == '[' || c == ']' || c == '{' || c == '}')
		return true; 
	else
		return false;
}

function esCaracterCorreoElectronico(codigo){
	var c = String.fromCharCode(codigo);
	if (esLetra(codigo) || esNumero(codigo) || c == '@' || c == '.' || c == '-' || c == '_')
		return true; 
	else
		return false;
}

//Hace que todos lo campos de texto y textarea pierdan foco.
function perderFoco(){
	jQuery.each($("textarea.obligatorio, input.obligatorio, textarea.opcional, input.opcional"), function(){
		$(this).blur();
	});
}

$(document).ready(function(){
    $("textarea.obligatorio, input.obligatorio").focus(function () {
			$(this).css({'border' : 'thin #FF0000 solid', 'background-color' : '#FF8080'});
	});
	
	$("textarea.obligatorio, input.obligatorio").blur(function () {
		$(this).css({'border' : 'thin #FF0000 solid', 'background-color' : '#FF8080'});
		if(!$(this).hasClass("diegoe87-validaciones-v1_0-error-caracteres-no-permitidos"))
			$(this).addClass("diegoe87-validaciones-v1_0-error-caracteres-no-permitidos");
			
		band = true;
		if($(this).hasClass("texto"))
			band = validarTexto($(this).val());
		else
			if($(this).hasClass("numero"))
				band = validarNumero($(this).val());
			else
				if($(this).hasClass("contrasenia"))
					band = validarContrasenia($(this).val());
				else
					if($(this).hasClass("alfanumerico"))
						band = validarAlfanumerico($(this).val());
					else
						if($(this).hasClass("alfanumericoExtendido"))
							band = validarAlfanumericoExtendido($(this).val());
						else
							if($(this).hasClass("correoElectronico"))
								band = validarCorreoElectronico($(this).val());
	
		if( jQuery.trim($(this).val()) != "" && band)
		{
			$(this).css({'border' : '', 'background-color' : ''});
			$(this).removeClass("diegoe87-validaciones-v1_0-error-caracteres-no-permitidos");
		}
	});
	
	$("textarea.opcional, input.opcional").focus(function () {
			$(this).css({'border' : 'thin #FFFF00 solid', 'background-color' : '#FFFF62'});
    });

	$("textarea.opcional, input.opcional").blur(function () {
		$(this).css({'border' : 'thin #FFFF00 solid', 'background-color' : '#FFFF62'});
		if(!$(this).hasClass("diegoe87-validaciones-v1_0-error-caracteres-no-permitidos"))
			$(this).addClass("diegoe87-validaciones-v1_0-error-caracteres-no-permitidos");
			
		band = true;
		if($(this).hasClass("texto"))
			band = validarTexto($(this).val());
		else
			if($(this).hasClass("numero"))
				band = validarNumero($(this).val());
			else
				if($(this).hasClass("contrasenia"))
					band = validarContrasenia($(this).val());
				else	
					if($(this).hasClass("alfanumerico"))
						band = validarAlfanumerico($(this).val());
					else
						if($(this).hasClass("alfanumericoExtendido"))
							band = validarAlfanumericoExtendido($(this).val());
						else
							if($(this).hasClass("correoElectronico"))
								band = validarCorreoElectronico($(this).val());
							
		if( jQuery.trim($(this).val()) == "" || band)
		{
			$(this).css({'border' : '', 'background-color' : ''});
			$(this).removeClass("diegoe87-validaciones-v1_0-error-caracteres-no-permitidos");
		}
    });
	
	$("textarea.texto, input.texto").keypress(function (e) {
		if(esLetra(e.which))
			return true;
		else
			return false
	});
	
	$("textarea.numero, input.numero").keypress(function (e) {
		if(esNumero(e.which))
			return true;
		else
			return false
	});
	
	$("textarea.contrasenia, input.contrasenia").keypress(function (e) {
		if(esCaracterContrasenia(e.which))
			return true;
		else
			return false
	});
	
	$("textarea.direccion, input.direccion").keypress(function (e) {
		if(esCaracterDireccion(e.which))
			return true;
		else
			return false
	});
	
	$("textarea.correoElectronico, input.correoElectronico").keypress(function (e) {
		if(esCaracterCorreoElectronico(e.which))
			return true;
		else
			return false
	});
	
	$("textarea.alfanumerico, input.alfanumerico").keypress(function (e) {
		if(esCaracterAlfanumerico(e.which))
			return true;
		else
			return false
	});
	
	$("textarea.alfanumericoExtendido, input.alfanumericoExtendido").keypress(function (e) {
		if(esCaracterAlfanumericoExtendido(e.which))
			return true;
		else
			return false
	});
 });


function base64_decode( data ) {
    var b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
    var o1, o2, o3, h1, h2, h3, h4, bits, i = 0, ac = 0, dec = "", tmp_arr = [];
 
    if (!data) {
        return data;
    }
 
    data += '';
 
    do {  // unpack four hexets into three octets using index points in b64
        h1 = b64.indexOf(data.charAt(i++));
        h2 = b64.indexOf(data.charAt(i++));
        h3 = b64.indexOf(data.charAt(i++));
        h4 = b64.indexOf(data.charAt(i++));
 
        bits = h1<<18 | h2<<12 | h3<<6 | h4;
 
        o1 = bits>>16 & 0xff;
        o2 = bits>>8 & 0xff;
        o3 = bits & 0xff;
 
        if (h3 == 64) {
            tmp_arr[ac++] = String.fromCharCode(o1);
        } else if (h4 == 64) {
            tmp_arr[ac++] = String.fromCharCode(o1, o2);
        } else {
            tmp_arr[ac++] = String.fromCharCode(o1, o2, o3);
        }
    } while (i < data.length);
 
    dec = tmp_arr.join('');
    dec = this.utf8_decode(dec);
    return dec;
}

function utf8_decode ( str_data ) {
    var tmp_arr = [], i = 0, ac = 0, c1 = 0, c2 = 0, c3 = 0;
 
    str_data += '';
 
    while ( i < str_data.length ) {
        c1 = str_data.charCodeAt(i);
        if (c1 < 128) {
            tmp_arr[ac++] = String.fromCharCode(c1);
            i++;
        } else if ((c1 > 191) && (c1 < 224)) {
            c2 = str_data.charCodeAt(i+1);
            tmp_arr[ac++] = String.fromCharCode(((c1 & 31) << 6) | (c2 & 63));
            i += 2;
        } else {
            c2 = str_data.charCodeAt(i+1);
            c3 = str_data.charCodeAt(i+2);
            tmp_arr[ac++] = String.fromCharCode(((c1 & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
            i += 3;
        }
    }
 
    return tmp_arr.join('');
}
