document.onkeypress = fKeyPress;
window.onresize = fredimencionar;

function fredimencionar() {
}

function fKeyPress(e){
	//me dice cual fue el objeto que recibio el onclick;
	if ( window.event != null){					//IE4+;
		eventobj = window.event.srcElement;
		dKey = window.event.keyCode;}
	else if ( e != null ){ 						//N4+ o W3C compatibles;
		eventobj = e.target;
		dKey = e.keyCode;}
	else
		return;

	if (eventobj.getAttribute("tipo")){
		if (eventobj.getAttribute("tipo") == "Fecha"){
			mascara(eventobj,"-",patronFecha,true);
		}
		
		if (eventobj.getAttribute("tipo") == "Hora"){
			mascara(eventobj,":",patronHora,true);
		}
		if (eventobj.getAttribute("tipo") == "Numero"){
			formatNumber(eventobj);
		}
	}
		
		
	if(dKey == 13) {
		// Eventos para pasar al siguiente campo (NEXT);
		if (document.getElementById(eventobj.id).getAttribute("next")){
		    var dnext = document.getElementById(eventobj.id).getAttribute("next");
			if (fValidarObjetos(eventobj)){
				if(document.getElementById(dnext).tagName == "INPUT")
				{
					document.getElementById(dnext).select();
				}
				document.getElementById(dnext).focus();
			}
			else
			{
				document.getElementById(eventobj.id).select();
				document.getElementById(eventobj.id).focus();
			}
		}
		//evento disparar alguna funcion con el enter;
		if(document.getElementById(eventobj.id).getAttribute("function"))
		{
		    eval(document.getElementById(eventobj.id).getAttribute("function") + '(' + eventobj.id + ')');
		}
	}
}

function fValidarObjetos(obj)
{
	if (obj.getAttribute("tipo") == "Fecha"){
		if (ValidarFecha(obj.value))
		{
		    return true;
		}
		else
		{
		    return false;
		}
	}
	return true;
}


function ValidarFecha(Cadena){
    var Fecha = new String(Cadena); 	// Crea un string;
    var RealFecha = new Date(); // Para sacar la fecha de hoy;
	// Cadena Año;
    var Ano = new String(Fecha.substring(Fecha.lastIndexOf("-") + 1, Fecha.length));
	// Cadena Mes;
    var Mes = new String(Fecha.substring(Fecha.indexOf("-") + 1, Fecha.lastIndexOf("-")));
	// Cadena Día;
    var Dia = new String(Fecha.substring(0, Fecha.indexOf("-")));

	// Valido el año;
	if (isNaN(Ano) || Ano.length<4 || parseFloat(Ano)<1900){
	    alert('Año inválido');
	    return false;
	}
	// Valido el Mes;
	if (isNaN(Mes) || parseFloat(Mes)<1 || parseFloat(Mes)>12){
	    alert('Mes inválido');
	    return false;
	}
	// Valido el Dia;
	if (isNaN(Dia) || parseInt(Dia, 10)<1 || parseInt(Dia, 10)>31){
	    alert('Día inválido');
	    return false;
	}
	if (Mes==4 || Mes==6 || Mes==9 || Mes==11 || Mes==2) {
		if (Mes==2 && Dia > 28 || Dia>30) {
		    alert('Día inválido');
		    return false;
		}
	}
	return true;	
}

function formatNumber(input)
{
	//elimina los puntos;
	var num = input.value.replace(/\,/g,"");
	if(!isNaN(num)){
	    num = num.toString().split("").reverse().join("").replace(/(?=\d*\,?)(\d{3})/g,'$1,');
	    num = num.split("").reverse().join("").replace(/^[\,]/,"");
	    input.value = num;
	}
	else{ alert('Solo se permiten numeros');
		input.value = input.value.replace(/[^\d\.]*/g,"");
	}
}


var patronFecha = new Array(2, 2, 4);
var patronHora = new Array(2, 2);
var patronTelefono = new Array(4, 4);

function mascara(d,sep,pat,nums){
	if(d.valant != d.value){
	    val = d.value;
	    largo = val.length;
	    val = val.split(sep);
	    val2 = '';
		for(r=0;r<val.length;r++){
		    val2 += val[r];
		}
		if(nums){
			for(z=0;z<val2.length;z++){
				if(isNaN(val2.charAt(z))){
				    letra = new RegExp(val2.charAt(z), "g");
				    val2 = val2.replace(letra, "");
				}
			}
		}
		val = '';
		val3 = new Array();
		for(s=0; s<pat.length; s++){
		    val3[s] = val2.substring(0, pat[s]);
		    val2 = val2.substr(pat[s]);
		}
		for(q=0;q<val3.length; q++){
			if(q ==0){
			    val = val3[q];
			}
			else{
			    if (val3[q] != "") {
			        val += sep + val3[q];
			    }
			}
		}
		d.value = val;
		d.valant = val;
	}
}


function CambiarString(String,CaracterA,CaracterB){
	var resultado = "";
	var largo = String.length;
	for (largoString = 0; largoString < largo ; largoString ++)
	{
	    var finalstring = largoString + 1;
	    letra = String.substring(largoString, finalstring);
		if (letra == CaracterA )
		{
			resultado = resultado + CaracterB;
		}
		else{
			resultado = resultado + letra ;
		}
	}
	return resultado;
}

function getVar(name)
         {
         get_string = document.location.search;         
         return_value = '';

         do { //This loop is made to catch all instances of any get variable;
             name_index = get_string.indexOf(name + '=');

             if (name_index != -1) {
                 get_string = get_string.substr(name_index + name.length + 1, get_string.length - name_index);

                 end_of_value = get_string.indexOf('&');
                 if (end_of_value != -1)
                     value = get_string.substr(0, end_of_value);
                 else
                     value = get_string;

                 if (return_value == '' || value == '')
                     return_value += value;
                 else
                     return_value += ', ' + value;
             }
         } while (name_index != -1)
            
         //Restores all the blank spaces;
         space = return_value.indexOf('+');
         while (space != -1) {
             return_value = return_value.substr(0, space) + ' ' +
              return_value.substr(space + 1, return_value.length);

             space = return_value.indexOf('+');
         }
         return(return_value);        
}



function padNmb(nStr, nLen) {
    var sRes = String(nStr);
    var sCeros = "0000000000";
    return sCeros.substr(0, nLen - sRes.length) + sRes;
}

function stringToSeconds(tiempo) {
    var sep1 = tiempo.indexOf(":");
    var sep2 = tiempo.lastIndexOf(":");
    var hor = tiempo.substr(0, sep1);
    var min = tiempo.substr(sep1 + 1, sep2 - sep1 - 1);
    var sec = tiempo.substr(sep2 + 1);
    return (Number(sec) + (Number(min) * 60) + (Number(hor) * 3600));
}

function esPar(numero) {
    resto = numero % 2;
    if ((resto == 0) && (numero != 0)) {
        return true;
    } else {
        return false;
    }
}

function secondsToTime(secs) {
    var hor = Math.floor(secs / 3600);
    var min = Math.floor((secs - (hor * 3600)) / 60);
    var sec = secs - (hor * 3600) - (min * 60);
    if (hor < 0) {
        if (hor == -1) {
            hor = 23;
        }
        if (hor == -2) {
            hor = 22;
        }
        if (hor == -3) {
            hor = 21;
        }
    }
    return padNmb(hor, 2) + ":" + padNmb(min, 2) + ":" + padNmb(sec, 2);
}

function substractTimes(t1, t2) {
    var secs1 = stringToSeconds(t1);
    var secs2 = stringToSeconds(t2);
    var secsDif = secs1 - secs2;
    return secondsToTime(secsDif);
}

function calcT3(fch) {
    var hor = fHourMin("h", fch);
    var min = fHourMin("m", fch);
    var hora = hor + ":" + min + ":00";
    var resHor = "3:00:00";
    return substractTimes(hora, resHor);
}