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)
}

var message="";
function clickIE() {
	if (document.all) {
		(message);
		return false;
	}
}

function clickNS(e) {
  if(document.layers||(document.getElementById&&!document.all)) {
    if (e.which==1||e.which==2||e.which==3) {(message);return false;}
  }
}

function disableselect(e){
	if(!e)
		e = window.event;
	if(e.target)
		e.target.focus();
	return false;
}

function reEnable(e){
	if(!e)
	  e = window.event;

	if(e.target)
		e.target.focus();
	return true;
}

function goBack(action,validation){
	setAction(action);
	bCancel = !validation;
}

function setAction(action){
	var input = document.getElementById('action');
	input.value=action;
}

function doAction(action){
	setAction(action);
	document.getElementById('form').submit();
}

function doClosePopUp() {
	this.window.close();
}


/*@deprecated. La dejo para que no peten las clases que anteriormente la usaban el buscarFocus original.*/
function buscarFocusBackup(tagName,clase){
		var primerElemento = true;
		var elemento1;
		var el = new Array();
		var elementos = document.getElementsByTagName(tagName);
		var tcl = " "+clase+" ";
		for(i=0,j=0; i<elementos.length; i++) {
			var test = " " + elementos[i].className + " ";
			if (test.indexOf(tcl) != -1){
				if(primerElemento == true){
					elemento1 = elementos[i];
					primerElemento = false;
				}				
			}
		}
		if(elemento1 != null){
			elemento1.focus();
			ponerMiniIcono(elemento1);
		}
	
}



/* En caso de error permite buscar que campo es el primer en ser erroneo y le asigna el foco. */
function buscarFocus(tagName,clase){
	var form = document.getElementById('form');
	if(form)
		buscarFocoEnForm(form);		
	else
		buscarFocusBackup(tagName,clase);
}


function buscarFocoEnForm(form){
	/*recorremos las labels para ponerle el icono*/
	
	if(form != null){		  			
		var isFirst = true;
		var element;
		for(var i=0; i < form.elements.length; i++){
			if(form.elements[i].className == "texteError"){				  
				ponerMiniIcono(form.elements[i]);
				if(isFirst){
					element = form.elements[i];
					isFirst = false;
				}
			}
		}
		if(element != null){
			if(element.type!='hidden')
				element.focus();
			else{
				if(document.getElementById(element.id + 'Foco'))
					document.getElementById(element.id + 'Foco').focus();
			}
		}
	}
}

/* Busca el foco al cargar la pagina. 
Utilizado para cuando el primer campo no tiene porque ser un input
Deberia unificarse con buscarFocusBackup */
function buscarFocoInicial(){
	var form = document.getElementById('form');
	if(form != null){		  			
		var isFirst = true;
		var element;
		for(var i=0; i < form.elements.length; i++){
			if(form.elements[i].className == "texte"){				  
				if(isFirst){
					element.focus();
					return true;
				}
			}
		}
	}
}

function ponerIconos(tagName,clase){
		var el = new Array();
		var elementos = document.getElementsByTagName(tagName);
		var tcl = " "+clase+" ";
		var primerCaso = false;
		
		for(i=0,j=0; i<elementos.length; i++) {
			var test = " " + elementos[i].className + " ";
			if (test.indexOf(tcl) != -1){		
				if(primerCaso ==false){
					elementos[i].focus();
					primerCaso = true;
				}
				elementos[i].className="texte";		
				ponerMiniIcono(elementos[i]);
			}
		}		
}

function ponerMiniIcono(elemento){  
  var parent = elemento.parentNode;
  var foundLabel = false; 
  var parentNodes;


   while(!foundLabel){
  	if(parent && !parent.nodeName != "BODY"){
	    parentNodes = parent.childNodes;    	
    	for(var k=0; (k < parentNodes.length && !foundLabel); k++){
	      if(parentNodes[k].nodeName=="LABEL" && !hasMiniAviso(parentNodes[k])) {
	      var check = false;
	      var idx=-1;
	        for (var i=0; i < parentNodes[k].childNodes.length; i++) {
	        	try {
			      	if (parentNodes[k].childNodes[i].type == 'radio' && parentNodes[k].childNodes[i].checked == true) {
			      		check = true;
			      		idx = i;			      		
	    		  	}
	    	  	} catch (err) {
	    	  	}
	    	}
      		parentNodes[k].innerHTML="<img class=\"miniAviso\" src=\"img/icona-mini-avis.gif\"/>" + parentNodes[k].innerHTML;
      		if (check && idx >= 0) {
	      		parentNodes[k].childNodes[idx+1].checked = check;
      		}
		 	foundLabel = true;
		 }
    	}
    	if(!foundLabel){
      		parent = parent.parentNode;
      	}
    }else{break;}
  }
}

function hasMiniAviso(doc){
	var images = doc.getElementsByTagName("img");
	for(var k=0 ; k < images.length; k++ )
		if(images[k].className == "miniAviso")
			return true;
	return false;
}

function quitarMiniAvisos(form){  
  var imagenes = document.images;
  var imagesOut = new Array();
  var inputs = form.elements;
  
  for(var idx=0; idx < imagenes.length; idx++){    
     if(imagenes[idx].className == "miniAviso"){
       imagesOut.push(imagenes[idx]);
     }
  }
  
  while(imagesOut.length > 0){
    var element = imagesOut.shift();
    element.parentNode.removeChild(element);    
  }
  
  for(var idx=0; idx < inputs.length; idx++)
    if(inputs[idx].type)
      if(inputs[idx].className == "texteError" || inputs[idx].className == "texte")
        inputs[idx].className = "texte validado";
}

function soloNumeros(evento){	
	if (!evento && window.event) {
		evento = window.event;
	}
	if (evento) {
     	var tecla=evento.keyCode;
     	if(tecla==0)
     		tecla = evento.charCode;
      	//if (ctrl && tecla==67) { evento.keyCode=0; evento.returnValue=false;}
     	if ((tecla <48 || tecla >57) && tecla!=8) { 
     		if(window.event){
     			//IE
     			evento.keyCode=0; 
     			evento.returnValue=false;
     		}else{
     			//Firefox
     			evento.preventDefault();
     			//evento.charCode=0; 
     		}
     	}
	}
}

/*Para mostrar las validaciones javascript*/
var mensaje ="";
var array_msgValidacion = Array();
function mostrarValidaciones(form){
	if(mensaje!=""){
		var divServidor = document.getElementById("valServidor");
		if(divServidor !=null )
			divServidor.style.display = 'none';
		document.getElementById("errores").className = "avis";
		recorrerMensajes();
		document.getElementById("errores").innerHTML ="<span><ul class=\"listaErrores\">" + mensaje + "</ul></span>";
		mensaje = "";
    	array_msgValidacion = Array();
    			
		buscarFocoEnForm(form);	
		return false;
	}else{
		return true;
	}
}

function mostrarValidacionesLogin(){
	if(mensaje!=""){
		var divServidor = document.getElementById("valServidor");
		if(divServidor !=null )
			divServidor.style.display = 'none';
		document.getElementById("errores").innerHTML ="<span><ul class=\"listaErrores\">" + mensaje + "</ul></span>";
		mensaje = "";
		return false;
	}else{
		return true;
	}
}


function modificarURLBuscarVia() {
	var nombreVia = document.getElementById("nombreVia").value;
	var texto = '<p class="controls">'+
					'<a id="yellow" class="botons" href="/es/OficinaVirtual/SeleccionVia.gas?action=busquedaResultados&nombreVia='+nombreVia+'">'+
						'<span>Buscar</span>'+
					'</a>'+
				'</p>';
	document.getElementById("divBotonBuscar").innerHTML = texto;
	return true;
}

function habilitarOtro(habilitar,idCampo){

	if(habilitar){
		document.getElementById(idCampo).disabled =false;
	}else{
		document.getElementById(idCampo).disabled = true;
		document.getElementById(idCampo).value="";
	}
}

function bloquearCtrVP(name){
	 var inputs = document.getElementsByTagName("input");
	 for(var i=0; i < inputs.length; i++){
    if(inputs[i].name.toLowerCase().indexOf(name)==0){
		inputs[i].onkeydown=function(evento){
	    //Si el navegador es IE, evento valdra nulo
		if (!evento && window.event){
			evento = window.event;
  		}
		if (evento) {
			var ctrl=evento.ctrlKey;
	      	var tecla=evento.keyCode;
	    
	      	if (ctrl && tecla==67) { 
	      		//IE
     			if(window.event){
     				evento.returnValue=false;
     			//Firefox
     			}else{     			
     				evento.preventDefault();
	     		}
	      	}
	      	
			if (ctrl && tecla==86) {
				//IE
     			if(window.event){
     				evento.returnValue=false;
     			//Firefox
     			}else{     			
     				evento.preventDefault();
     			}
     		}     	
      	}
		};
   	}  
 }	 
}

function bloquearBotonDrh(name){
	var inputs = document.getElementsByTagName("input");
	for(var i=0; i < inputs.length; i++){
    	if(inputs[i].name.toLowerCase().indexOf(name)==0){   
		 inputs[i].onmousedown=disableselect
    	 inputs[i].onclick=reEnable
	     inputs[i].onselectstart=new Function ("return false")
	     }
	}
}

function onLoadBody(){
	bloquearCtrVP("rep");
	bloquearBotonDrh("rep");
}

function send(form, disable){
	if(disable == true)
		deshabilitarBotones(form, true);
	quitarMiniAvisos(form);
	var nombreFormulario = form.name;
	var inicial =nombreFormulario.substring(0,1).toUpperCase();
	var resto = nombreFormulario.substring(1,nombreFormulario.length);
	eval('validate'+inicial+resto+'(form)');
	var validacion = mostrarValidaciones(form);	
	if(validacion == true && document.getElementById("mask")){
		document.getElementById("mask").style.width = document.getElementById("marc").offsetWidth+"px";
		document.getElementById("mask").style.height = document.getElementById("marc").offsetHeight+"px";
	}else if(document.getElementById("valServidor")){
		document.getElementById("valServidor").style.display="none";
	}
	if(validacion != true){
		if(disable == true)
			deshabilitarBotones(form, false);
	}
	return validacion;
}

function openWindow(url, width, height, scrollbars) {
  var centroVertical = parseInt((window.screen.width/2)) - 325 ;		
  var centroHorizontal = parseInt((window.screen.height/2)) - 300;
  var w = window.open(url,'_blank','width=' + width + ', height=' + height + ',resizable=yes,menubar=no,location=no,scrollbars=' + scrollbars + ',screenX='+centroVertical+',screenY='+centroHorizontal);
  w.focus();
  return w;
}

function openPopup(url, width, height){
	openWindow(url, width, height, 'no');
}

function openWindowComplert(url,width,height){
  var centroVertical = parseInt((window.screen.width/2)) - 325 ;		
  var centroHorizontal = parseInt((window.screen.height/2)) - 300;
  var w = window.open(url,'_blank','width=' + width + ', height=' + height + ',directories=yes,resizable=yes,toolbars=yes,menubar=yes,location=yes,scrollbars=yes,screenX='+centroVertical+',screenY='+centroHorizontal);
  w.focus();
  return w;
}

function hiddeElement(id,ok){
	if(ok)
		document.getElementById(id).style.display='none';
	else
		document.getElementById(id).style.display='';
}


/** METODOS PARA LA VALIDACION CLIENTE Y ORDENAR LOS ERRORES**/

function recorrerMensajes(){
	mensaje='';
	  for(var idx=0; idx < array_msgValidacion.length; idx++){
	  		if(array_msgValidacion[idx]!=null && array_msgValidacion[idx]!=''){
	  			mensaje += '<li>' + array_msgValidacion[idx] + '</li>';
	  		}
	  }
	  return mensaje;
}

function agregarError(field, msg){
	var mayusculas = new Array ("NIF", "CIF", "NIE", "Plan", "Ahorro");
	var pos = retornaPosicion(field);
	
	/**FORMATEO DEL ERROR**/
	msg = msg.toLowerCase();
	var partes = msg.split('.');
	var msgNuevo = '';
	for(i=0;i<partes.length;i++){
		if(partes[i].substring(0,1)!=null && partes[i].substring(0,1)!=''){
			partes[i]=partes[i].replace(/^\s*|\s*$/g,"");
			msgNuevo =  msgNuevo + partes[i].substring(0,1).toUpperCase() +  partes[i].substring(1).toLowerCase() + '. ';
		}
	}
	if(msgNuevo!='')
		msg = msgNuevo
		
		
	/* Se buscan los elementos del array que iran en mayusculas*/
	for(i=0;i<mayusculas.length;i++){
		msg = msg.replace(mayusculas[i].toLowerCase(),mayusculas[i]);
	}
		
	array_msgValidacion[pos]=msg;
}

function retornaPosicion(field){
		var primerElemento = true;
		var elemento1;
		var listaTemporal = new Array();
		var cuentaPosicion = 0;
		var elementos = document.getElementsByTagName('*');
		var tcl = " texte";
		for(i=0,j=0; i<elementos.length; i++) {
			var test = " " + elementos[i].className + " ";
			if (test.indexOf(tcl) != -1){
				if(elementos[i].name == field.name)
					return cuentaPosicion;
				cuentaPosicion++;	
			}
		}
}

function deshabilitarBotones(form, estado){
	var botons = form.getElementsByTagName("button");
	if (botons != null) {
		for(var i = 0; i < botons.length; i++) {
			var boton = botons[i];
			if (boton.type && boton.type.toLowerCase() == "submit"){
				boton.disabled=estado;	
			}
		}
	}
}	