//La siguiente linea es para que cuando pulsen en el boton atras del navegador no vuelva a la pagina de atras y en vez de eso te recargue la pagina en la que estas.
//window.history.forward(1);

//Según el tipo elegido devuelve true si su formato es correcto,
//hay q tener cuidado ya que para un real no vale un entero.
function validar(val, ind)
{
    var validador = new Array();
    validador[0] = "^\\d{1,8}$";  //DNI
    validador[1] = "^(?:\\+|-)?\\d+$";  //ENTERO
    validador[2] = "^(?:\\+|-)?\\d+\\.\\d*$";  //REAL
    validador[3] = "^(0[1-9]|1\\d|2[0-3]):([0-5]\\d):([0-5]\\d)$";   //HORA
    validador[4] = "^([012][1-9]|3[01])(/|-)(0[1-9]|1[012])\2(\\d{4})$";   //FECHA
    validador[5] = "(^[0-9a-zA-Z]+(?:[._][0-9a-zA-Z]+)*)@ ([0-9a-zA-Z]+(?:[._-][0-9a-zA-Z]+)*\\.[0-9a-zA-Z]{2,3})$";   //EMAIL

    var expreg = new RegExp(validador[ind]);
    /*
    if ( (expreg.test(val)) )
        return true;
    else
        return false;
    */
    return expreg.test(val);
}

function validarReal(val) {
    cambiarComaPorPunto(val);
    if ( validar(val.value, 2) ) {
        return true;
    } else if ( validar(val.value, 1) ) {
        val.value= val.value + ".00";
        return true;
    } else {
        return false;
    }
}

//requiere un Objeto radio que devuelve true si
//hay algún elemento seleccionado.
function comprobarRadioSeleccionado(val)
{
    if(val==undefined){
        return false;
    }
    //isNaN(val)
    if(val.length==undefined){
        if (val.checked) {
            return true;
        } else {
            return false;
        }
    }

    for (i=0;i < val.length; i++)
    {
        if ( val[i].checked )
            return true;
    }
    return false;
}

function comprobarIndiceRadioSeleccionado(val)
{
    if(val==undefined){
        return -1;
    }
    
    if(val.length==undefined){
        if(val.checked)
            return 0;
        else
            return -1;
    }

    for (i=0;i < val.length; i++)
    {
        if ( val[i].checked )
            return i;
    }
    return -1;
}

function comprobarNumeroRadiosSeleccionados(val)
{
	
    if(val==undefined){
        return -1;
    }
    
    if(val.length==undefined){
        if(val.checked)
            return 1;
        else
            return -1;
    }

	numero=0;
    for (i=0;i < val.length; i++)
    {
        if ( val[i].checked )
            numero++;
    }
    return numero;
}

function comprobarObjetoRadioSeleccionado(val)
{
    if(val==undefined){
        return undefined;
    }

    if(val.length==undefined){
        if(val.checked)
            return val;
        else
            return undefined;
    }

    for (i=0;i < val.length; i++)
    {
        if ( val[i].checked )
            return val[i];
    }
    return undefined;
}


function comprobarCheckBoxSeleccionado(nombre, cont) {
    var encontrado = false;

    if ( cont > 0 )
    {
        var i= 0;

        while ( ( i < cont ) && (!encontrado) ) {
            if ( document.getElementById( "nombre" + i ).checked )
            {
                return true;
            }
            i++;
        }
    }
    return false;
}

function comprobarIndiceCheckBoxSeleccionado(nombre, cont) {
    var indi = -1;

    if ( cont > 0 )
    {
        var i= 0;

        while ( ( i < cont ) && (!encontrado) ) {
            if ( document.getElementById( "nombre" + i ).checked )
            {
                return true;
            }
            i++;
        }
    }
    return false;
}


function fijarIndiceRadioSeleccionado(val, selectedOption) {
// checks the selected radio button 
   if (val[0]) { // if the button group is an array (one button is not an array)
      for (var i=0; i<val.length; i++) {
         if (i==selectedOption) {
            val[i].checked=true;
         }
      }
   } else {
      val.checked=true; 
   }
}











function cambiarComaPorPunto(val) {
    val.value = val.value.trim().replace(",",".");
}

// Funcion que redondea un numero (value) al numero de decimales que se desee (precision)
function roundOff(value, precision)
{
        value = "" + value //convert value to string
        precision = parseInt(precision);

        var whole = "" + Math.round(value * Math.pow(10, precision));

        var decPoint = whole.length - precision;

        if(decPoint > 0) {
            result = whole.substring(0, decPoint);
            result += ".";
            result += whole.substring(decPoint, whole.length);
        } else if(decPoint < 0) {
            result = "0.00";
        } else {
            result = 0;
            result += ".";
            result += whole.substring(decPoint, whole.length);
        }
        return result;
}

function checkReadOnly(val) {
    val.checked = !val.checked;
}


function meterFechaActual(val) {
    var fecha = new Date();
    var sfecha = '';
    var valor = fecha.getDate();
    if ( valor < 10 ) {
        sfecha = sfecha + '0' + valor;
    } else {
        sfecha = sfecha + valor;
    }
    sfecha = sfecha + '/';
    valor = parseInt(fecha.getMonth()) + 1;
    if ( valor < 10 ) {
        sfecha = sfecha + '0' + valor;
    } else {
        sfecha = sfecha + valor;
    }
    sfecha = sfecha + '/';
    sfecha = sfecha + fecha.getFullYear();
    val.value= sfecha;
}

String.prototype.trim=function() {
	var i=0
	var j=this.length-1
	while (i<this.length && (this.charAt(i)==' ' || this.charCodeAt(i)==10 || this.charCodeAt(i)==13)) i++
	while (j>i && (this.charAt(j)==' ' || this.charCodeAt(j)==10 || this.charCodeAt(j)==13)) j--
	if (j>=i) return this.substring(i,j+1)
	return ''
}

function eliminarRadioSeleccionado(val)
{
    if(val==undefined){
        return false;
    }
    //isNaN(val)
    if(val.length==undefined){
        val.checked= false;
        return true;
    }

    for (i=0;i < val.length; i++)
    {
        val[i].checked= false;
    }
    return false;
}

//agregamos el atributo maxlength a los textareas limitando así su tamaño.

//comprueba el tamaño de el textarea cuándo se levanta una tecla.
function ismaxlength(){
    var obj= this;
    var mlength=obj.getAttribute? parseInt(obj.getAttribute("maxlength")) : ""
    if (obj.getAttribute && obj.value.length>mlength)
    obj.value=obj.value.substring(0,mlength)
}
/*
function ismaxlength(obj){
    var mlength=obj.getAttribute? parseInt(obj.getAttribute("maxlength")) : ""
    if (obj.getAttribute && obj.value.length>mlength)
    obj.value=obj.value.substring(0,mlength)
}*/
// registra un evento de acuerdo a IE y Firefox(DOM)
function agregarEvento(elemento, nombre_evento, funcion, captura){
    // para IE
    if (elemento.attachEvent){
        elemento.attachEvent('on' + nombre_evento, funcion);
        return true;
    } else   // para navegadores respetan Estándares DOM(Firefox,safari)
    if (elemento.addEventListener) {
        elemento.addEventListener(nombre_evento, funcion, captura);
        return true;
    } else
        return false;
}

agregarEvento(window,'load',eventos,false);

function eventos(){
    var veventos= document.getElementsByTagName("textarea");

    for ( i= 0; i < veventos.length; i++ ) {
        agregarEvento( veventos[i],'keyup', ismaxlength, false );
    }
}

/*function eventos(){
    var veventos= document.getElementsByTagName("textarea");

    for ( i= 0; i < veventos.length; i++ ) {
        agregarEvento( veventos[i],'keyup', function(){ismaxlength(veventos[i]);}, false );
    }
}*/

function openInNewTab(URL) {
	var temporalForm = document.createElement('form');
	with (temporalForm) {
		setAttribute('method', 'GET');
		setAttribute('action', URL);
		setAttribute('target', '_blank');
	}
	
	var paramsString = URL.substring(URL.indexOf('?') + 1, URL.length);
	var paramsArray = paramsString.split('&');
	for (var i = 0; i < paramsArray.length; ++i) {
		var elementIndex = paramsArray[i].indexOf('=');
		var elementName = paramsArray[i].substring(0, elementIndex);
		var elementValue = paramsArray[i].substring(elementIndex + 1, paramsArray[i].length);
		
		var temporalElement = document.createElement('input');
		with(temporalElement) {
			setAttribute('type', 'hidden');
			setAttribute('name', elementName);
			setAttribute('value', elementValue);
	}
	
	temporalForm.appendChild(temporalElement);
	}
	
	document.body.appendChild(temporalForm);
	temporalForm.submit();
	document.body.removeChild(temporalForm);
}
