/*------------------------------------------------------------------------------------------------------------------------------ 
 											Funcións de uso xeral
-------------------------------------------------------------------------------------------------------------------------------*/
/*
	Función a chamar tras cargar a páxina.
	Serve para facer unha precarga de imaxes e intentar evitar ese pequeno retardo
	que temos cando se pasa o ratón por enriba.
	sigue sin funcionar ben isto
	Preload das imaxes do menu
	e preload das imaxes de catálogo
	
*/

function preparaFotosCatalogo(){
	// Comprobo si cargar imaxes do catálogo
	for(x=0; x<totalFotosPrecarga; x++)preCargaImaxe(x);
}

/*
	Funcións para facer un preload das imaxes do catálogo

*/
function preCargaImaxe(indice){
	//alert("pci");
		tmp = str_pad(arrayFotos[indice], 10, "0", 'STR_PAD_LEFT');
		foto = carpetaCatalogo + tmp + '.jpg';
		arrayImaxes[indice] = new Image(); // Obxecto imaxe
		arrayImaxes[indice].src = foto; // fai o preload
		preloader(arrayImaxes[indice], indice);
		
	
}



function preloader(imaxeObj, indice){
	
	
	if (imaxeObj.complete){
		// Cambiar estado do botón do calendario (xGetElementById)
		targ = "fecha" + arrayFotos[indice];
		try{
			xGetElementById(targ).className= "fecha"
		}catch(e){}
		
		//fotoActualPrecarga++;
		//if(fotoActualPrecarga<totalFotosPrecarga)preCargaImaxe();
		//document.write("cargada" + fotoActualPrecarga + ", ");
	}else{
		// Caso contrario pon un preloader
		setTimeout(bind(true, "preloader", [imaxeObj, indice]), 10);
	}
	
}




/*
	Función para poder facer setTimeout pasando valores
	(http://fn-js.info/snippets/bind)
	uso: setTimeout(bind(a, "c", [3]), 3000);
	sendo a o obxecto, c o método e entre corchetes os parámetros do método
	Si o usamos no contexto actual/raíz, cambiar obxecto por true!
	
*/
function bind(obj, fun, args) {
  return function() {
    if (obj === true)
      obj = this;
    var f = typeof fun === "string" ? obj[fun] : fun;

    return f.apply(obj, Array.prototype.slice.call(args || [])
        .concat(Array.prototype.slice.call(arguments)));
  };
}




// 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) {
	recibido = 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=>' + recibido); 
	
	return e;
}







/*
	Función análoga ao str_pad de php
*/
function str_pad (input, pad_length, pad_string, pad_type){
	input = String (input);
	pad_string = pad_string != null ? pad_string : " ";
	if (pad_string.length > 0){
		var padi = 0;
		pad_type = pad_type != null ? pad_type : "STR_PAD_RIGHT";
		pad_length = parseInt (pad_length);
		switch (pad_type){
			case "STR_PAD_BOTH":
				input = str_pad (input
						   , input.length + Math.ceil ((pad_length - input.length) / 2.0)
						   , pad_string, "STR_PAD_RIGHT");
		 		// break;  // kein break!
		  	case "STR_PAD_LEFT":
				var buffer = "";
				for (var i = 0, z = pad_length - input.length; i < z; ++i){
					buffer += pad_string.charAt(padi); // [padi] IE 6.x bug
			  		if (++padi == pad_string.length)padi = 0;
				}
				input = buffer + input;
			break;
		  
		  	default:
				for (var i = 0, z = pad_length - input.length; i < z; ++i){
					input += pad_string.charAt(padi);
					if (++padi == pad_string.length)padi = 0;
				}
			break;
		}
	}
	return input;
}

// Escapara retornos de carro
function nl2br( str ) {
    // http://kevin.vanzonneveld.net
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Philip Peterson
    // *     example 1: nl2br('Kevin\nvan\nZonneveld');
    // *     returns 1: 'Kevin<br/>\nvan<br/>\nZonneveld'
 
    return str.replace(/([^>])\n/g, '$1<br />\n');
}


// Escapar caracteres raros con barra invertida
function addslashes( str ) {
    // http://kevin.vanzonneveld.net
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Ates Goral (http://magnetiq.com)
    // +   improved by: marrtins
    // *     example 1: addslashes("kevin's birthday");
    // *     returns 1: "kevin\'s birthday"
 
    return str.replace('/(["\'\])/g', "\\$1").replace('/\0/g', "\\0");
}
function stripslashes( str ) {
    // http://kevin.vanzonneveld.net
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Ates Goral (http://magnetiq.com)
    // +      fixed by: Mick@el
    // +   improved by: marrtins
    // *     example 1: stripslashes('Kevin\'s code');
    // *     returns 1: "Kevin's code"
 
    return str.replace('/\0/g', '0').replace('/\(.)/g', '$1');
}






/*
	Abre unha janela cunha foto
*/
function janelaFoto(url){
	
	try{
		if (typeof ventanaFoto.document == "object")ventanaFoto.close()
	}catch (e){
		
	}
	
	
	ancho = 60; alto = 45; // por defecto
	
	// Coordenadas da janela (no centro da pantalla
	leftPosition = (screen.width) ? (screen.width - ancho) / 2:100; 
	topPosition = (screen.height) ? (screen.height - alto) / 2:100;
	
	settings='width='+ancho+',height='+alto+',top='+topPosition+',left='+leftPosition+',scrollbars=' + scroll + ', location=no, directories=no, status=no, menubar=no, toolbar=no, resizable=no';
	
	ventanaFoto = window.open('popFoto.php?foto=' + url, "Foto", settings)
	
}


/*----------------------------------------------
 			Redimensiona e centra unha janela
----------------------------------------------*/// 
function centrarJanela(ancho, alto){
	LeftPosition = (screen.width) ?(screen.width - ancho) / 2:100;
	TopPosition = (screen.height) ?(screen.height - alto)/ 2:100;	
	
	resizeTo(ancho,alto);
	moveTo(LeftPosition,TopPosition);
	
}








// 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) {
  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 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)
	}	
}



// Función para borrar un formulario (void)
//----------------------------------------------=
function borrarFormulario(id){
	
	lonxitudeForm = xGetElementByid(id).elements.length;
	
	for(x = 0; x < lonxitudeForm; x++){
		xGetElementByid(id).elements[x].value = '';	
	}
	
}



// 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
}





// Comproba que se escolleu un campo válido nun <select>. 
// Recibe o valor do campo e o valor que NON debe ter para ser válido.
//-----------------------------------------------------------
function compSelect(q,valor){
	if( q == valor )return false;
	else return true;
}




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

function getURL(url){
	document.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)>=4)) { 
      //var url="http://www.lagardebesada.com/"; 
      //var titulo=":: Bodega Lagar De Besada ::: ALBARIÑOS"; 
      window.external.AddFavorite(url,titulo); 
	  
}else 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);
}


