/*------------------------------------------------------------------------------------------------------------------------------ 
 											Funcións de uso xeral
-------------------------------------------------------------------------------------------------------------------------------*/




// Función para referenciar os obxectos dun formulario polo seu id, mellor que polo array elemnts.
// Funcionará con case que todos os browsers novos
function xGetElementById(e) {
	
	capa = e;
	
	if(typeof(e)!='string') return e;
	
	if(document.getElementById) e = document.getElementById(e);
	
	else if(document.all) e=document.all[e];
	
	else e=null;
	
	if(e == null)alert('Error identificando elementos por su id=>' + capa); 
	
	return e;
}


/*
	Función para referenciar obxectos polo seu id, entre distionso frames (iframe tamen
*/

function iframe_xGetElementById(e){
	
	capa = e;
	
	if(typeof(e)!='string') return e;
	
	if(parent.document.getElementById) e = parent.document.getElementById(e);
	
	else if(parent.document.all) e = parent.document.all[e];
	
	else e=null;
	
	if(e == null)alert('Error identificando elementos por su id=>' + capa); 
	
	return e;
	
}



/*
		Función para referenciar os obxectos polo seu id. OLLO: entre distintas ventanas 
*/
function popup_xGetElementById(e) {
			
		if(typeof(e) != 'string') return e;
		
		if(window.opener.document.getElementById) e = window.opener.document.getElementById(e);
		
		else if(window.opener.document.all) e = window.opener.document.all[e];
		
		else {
			//e = null; // Si envias un numero en vez de un string, devolve null
			//alert('Tu navegador no soporta DOM Level 2 Core. Error identificando elementos por su id'); 
		}
		
		return e;
	}






/*
	Funciónpara crear elementos DOM de texto
	Uso:
	var nodoAtributos = new Array('href', 'http://www.w3c.org', 'title', 'Ir a la web del World Wide Web Consortium');
	var nodoEnlace = createDOMElement('a', 'World Wide Web Consortium', nodoAtributos);
	
	e engadese no html con (por exemplo)
	var htmlBody = document.getElementsByTagName('body')[0];
	htmlBody.appendChild(nodoEnlace);
	
*/

function createDOMElement(elementType, elementText, elementAttributes){
	var newElement = document.createElement(elementType);
	
	if (elementText){
		newElement.appendChild(document.createTextNode(elementText));
	}
	
	if (elementAttributes && elementAttributes.length > 0){
		
		for (var i = 0; i < elementAttributes.length; i = i+2){
			
			newElement.setAttribute(elementAttributes[i],elementAttributes[i+1]);
			
		}
	}
	
	return newElement;
}



// Comproba si e un nº tde telefono válido. Devolve false si no é váldo
//----------------------------------------------------------------------
function validaTelefono(str){
	var patron = new RegExp("[0-9]{9,}","gi");
	return patron.test(str);

	
}



// Comproba que unha dir. de email sexa correcta. Devolve false en caso de error
//-------------------------------------------------------------------------------
function validaEmail(str){
	if (/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,4})+$/.test(str)) return true; // email OK
	else return false;
}


// Comproba DNI. Devolve False en caso de erro.
function validaDNI(dni) {
  dni = dni.toUpperCase()	
  numero = dni.substr(0,dni.length-1);
  let = dni.substr(dni.length-1,1);
  numero = numero % 23;
  letra='TRWAGMYFPDXBNJZSQVHLCKET';
  letra=letra.substring(numero,numero+1);
  if (letra!=let)return false; 
  else return true;
}


/*
	Función para validsar dous campos password e verificar que son iguales
	campo 1 --> password
	campo 2 -->  repite password
	obligatorio --> si 1, os 2 campos poden estar vacíos e si é así, devolvese true
*/
function validaPassword(campo1, campo2, obligatorio){
	
	c1 = xGetElementById(campo1).value;
	c2 = xGetElementById(campo2).value
	
	if(!obligatorio && vacio(c1) && vacio(c2))return true; // Contraseña non é obligatoria. Si vacía, devolve true
	if(!vacio(c1) && !vacio(c2) && c1==c2 && c1.length >=5)return true
	return false;
		
	
}

/*
	Función que recibe un strin e dinos si pode ser unha imaxe jpeg (pola extensión
	-----------------------------------------------------------------------------
																	 
*/
function validaFoto(cadena){

	var patron = new RegExp(".jp[eg]{0,1}$","gi"); // *.jpeg ou *.jpg
	if(patron.test(cadena))return true; // Formato válido
	else return false;
}


// Función para restrinxir só a caracteres alfanumericos
//-----------------------------------------------------------------------------
function caracteresValidos(str, min,max) {
	str = str.replace(/^\s*|\s*$/g,""); // Faille un trim á cadena
	tmp = "^[a-zA-Z0-9_]{" + min + "," + max + "}$";
	var patron = new RegExp(tmp);
	//var patron = new RegExp("[a-x]{9,}","gi");
	return patron.test(str);
	
}



// Func. q pide confirmación sobre unha acción.(void)
// si popUp true, si aceptar abre un popUp coa url dada
//------------------------------------------------------
function confirmar(texto,url, popUp){
	var res = window.confirm(texto);
	if (res ){
		if(popUp)janelaEditar(url);
		else document.location.href=url; //redirecciona(url,0)
	}	
}





/* Busca caracteres que no sean espacio en blanco nunha cadea
--------------------------------------------------------------*/
function vacio(q) {
	for ( i = 0; i < q.length; i++ )if ( q.charAt(i) != " " ) return false;
	return true
}



/* Contador de caracteres
	campo --> campo cuios caracteres queres limitar
	maxlimit --> máximo de caracteres
	countfield (opcional) indica un campo noi que poñer os caracteres que restan para chegar ao limite

------------------------------------------------------------------------------------------------------*/
function contaCaracteres(campo, limite, countfield) {
	if (xGetElementById(campo).value.length > limite)xGetElementById(campo).value = xGetElementById(campo).value.substring(0, limite);
	else if(countfield != null ){
		//alert(xGetElementById(countfield).innerHTML);
		xGetElementById(countfield).innerHTML = limite - xGetElementById(campo).value.length + " caracteres restantes";
		
	}
}
	



/*	Prototype para comprobar si un valor está nun array
-----------------------------------------------------------*/
Array.prototype.inArray = function (value){

	if(!this.length > 0)return -1;	
	for (w=0; w < this.length; w++){
		if (this[w] == value){
			// O valor está no array
			return w;		
		}
	}
	// O valor NON está no array
	return -1;
};


/* Devolve array en forma de cadena
------------------------------------------------------*/
function implode(matris, separador){
	
	if(separador == "")separador = "|"; 
	var imploded = matris[0];
	for (i = 1; i<matris.length; i++) imploded += separador + matris[i];
	return imploded
}





/*
	Función para ordenar numeros
	usase así:
	document.write(arr.sort(sortNumber));
	sendo arr un array de numeros	
*/
function sortNumber(a,b){
	return a - b;
}





/*Elimina espacios ao final e ao principio de unha cadena*/
function trim(str){
	str = str.replace(/^\s*|\s*$/g,"");
	return str;
}


/* Recibe un valor e comproba si o select seleccionado coincide con ese valor. Devolve true si o indice seleccionado e e válido.
---------------------------------------------------------------------------------------------------------------------*/
function compSelect(q,valor){
	if( q == valor ) return false;
	else return true
}


/*	Función que me da o valor (valor apuntado por value="") do elemento actualmente seleccionado nun campo select (flag = undefined)
	ou o indice do elemento seleccionado (flag = true)
----------------------------------------------------------------------------------------------------*/
function dameValorSelect(id, flag){
	
	if(!flag) return xGetElementById(id).options[xGetElementById(id).selectedIndex].value;
	else return xGetElementById(id).selectedIndex;
	
	
}

/*	Función que cambia o valor seleccionado nun campo select.
	Recibe o valor a poñer como seleccionado e o nome do campo select
--------------------------------------------------------------------*/
function selectActualiza(nomeSelect, valor){
	
	lonx = xGetElementById(nomeSelect).length; // elementos do select
	
	for (var j=0; j < lonx; j++)if(xGetElementById(nomeSelect).options[j].value == valor) xGetElementById(nomeSelect).selectedIndex=j;
	
}



// Redirección(void)
//----------------------------------------------
function redirecciona(url,tempo){
	if(tempo>0)	setTimeout("document.location.href='" + url + "';", tempo); else document.location.href=''+url+'';
}





/* Sacar a URL actual sin cadena de busqueda
----------------------------------------------*/
function SELF(){
	//url = document.location.href.substring(0,document.location.href.length-location.search.length); // Metodo 1
	url = window.location.href.substring(0, window.location.href.length - window.location.search.length); // Metodo 2
	//url = document.location.protocol + "//" + document.location.host + document.location.pathname; // Metodo 3
	
	return url;
}


/* Función para cambiar de páxina mediante un campo de texto no que metes a páxina
	á que queres ir. Esta función comproba si o nº de páxina é válido (< totalPaxinas)
	e si é así redirixe á páxina de marras
	busqueda: cadena que ven despois de ? pero sin nº de páxina
*/
function cambiaPaxina(totalPaxinas, busqueda){
	if( xGetElementById('gotoPageNum').value > totalPaxinas ||  xGetElementById('gotoPageNum').value < 1 || isNaN(xGetElementById('gotoPageNum').value)){
		
		// Non vale
		xGetElementById('gotoPageNum').value = "#"
		
	}else{
		// Si vale
		url = SELF() + "?" +  busqueda + "&paxina=" + Math.floor(Math.abs(xGetElementById('gotoPageNum').value)); 
		window.location.href= url;
	}
	
}



// Cerrar ventana(void)
//----------------------------------------------
function cerrarse(){
	window.close();
}


// Texto da barra de estado(void)
//----------------------------------------------
function estatus(s){
	window.status = s;
}



// Engadir páxina a favoritos(void)
//----------------------------------------------
function favoritos(url,titulo) {
   
if ((navigator.appName=="Microsoft Internet Explorer") && (parseInt(navigator.appVersion, 10)>=4)) { 
      //var url="http://www.lagardebesada.com/"; 
      //var titulo=":: Bodega Lagar De Besada ::: ALBARIÑOS"; 
      window.external.AddFavorite(url,titulo); 
	  
}else if(navigator.appName == "Netscape") 
	alert ("Presione Crtl+D para agregar este sitio a favoritos"); 

}


// Convertir en páxina de inicio (só IE) (void)
//----------------------------------------------
function pdeinicio(url) {
	document.body.style.behavior="url(#default#homepage)"; 
	document.body.setHomePage(url);
}

