/*
 * Gestión de eventos - http://dean.edwards.name/my/events.js
 */

/*
 * Ejemplo:
 *
 * function foo(){
 *     alert('La página ha terminado de cargar');
 * }
 * addEvent(window, 'load', foo);
 *
 */
 
function toggleBox(szDivID, iState) // 1 visible, 0 hidden
{
    if(document.layers)	   //NN4+
    {
       document.layers[szDivID].visibility = iState ? "show" : "hide";
    }
    else if(document.getElementById)	  //gecko(NN6) + IE 5+
    {
        var obj = document.getElementById(szDivID);
        obj.style.visibility = iState ? "visible" : "hidden";
    }
    else if(document.all)	// IE 4
    {
        document.all[szDivID].style.visibility = iState ? "visible" : "hidden";
    }
}

function IsNumeric(sText){
   var ValidChars = "0123456789.";
   var IsNumber=true;
   var Char;

 
   for (i = 0; i < sText.length && IsNumber == true; i++) 
      { 
      Char = sText.charAt(i); 
      if (ValidChars.indexOf(Char) == -1) 
         {
         IsNumber = false;
         }
      }
   return IsNumber;
   
}

function getSelText()
{
    var txt = '';
     if (window.getSelection)
    {
        txt = window.getSelection();
             }
    else if (document.getSelection)
    {
        txt = document.getSelection();
            }
    else if (document.selection)
    {
        txt = document.selection.createRange().text;
            }
   // else return '';
  return txt;
}
function checkMail(x){
	var filter  = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
	return filter.test(x);
}

String.prototype.trim = function() {
a = this.replace(/^\s+/, '');
return a.replace(/\s+$/, '');
};

function abre_popup (URL,ancho,alto,scroll){
	var winl = (screen.width - ancho) / 2;
    var wint = (screen.height - alto) / 2;
    var rand_no = Math.round(100*Math.random());
     t="ventana"+rand_no; 
	newwindow=window.open(URL,t,"width="+ancho+",height="+alto+",top="+wint+",left="+winl +",scrollbars="+scroll);
	newwindow.focus();
  // if (window.focus) {}
}


function addEvent(element, type, handler) { // v2005-12-06
	// assign each event handler a unique ID
	if (!handler.$$guid) handler.$$guid = addEvent.guid++;
	// create a hash table of event types for the element
	if (!element.events) element.events = {};
	// create a hash table of event handlers for each element/event pair
	var handlers = element.events[type];
	if (!handlers) {
		handlers = element.events[type] = {};
		// store the existing event handler (if there is one)
		if (element["on" + type]) {
			handlers[0] = element["on" + type];
		}
	}
	// store the event handler in the hash table
	handlers[handler.$$guid] = handler;
	// assign a global event handler to do all the work
	element["on" + type] = handleEvent;
};
// a counter used to create unique IDs
addEvent.guid = 1;

/*
 * Ejemplo: removeEvent(window, 'load', foo);
 */
function removeEvent(element, type, handler) { // v2005-12-06
	// delete the event handler from the hash table
	if (element.events && element.events[type]) {
		delete element.events[type][handler.$$guid];
	}
};


/*
 * Funciones privadas (son utilizadas por las dos anteriores)
 */
function handleEvent(event) { // v2005-12-06
	var returnValue = true;
	// grab the event object (IE uses a global event object)
	event = event || fixEvent(window.event);
	// get a reference to the hash table of event handlers
	var handlers = this.events[event.type];
	// execute each event handler
	for (var i in handlers) {
		this.$$handleEvent = handlers[i];
		if (this.$$handleEvent(event) === false) {
			returnValue = false;
		}
	}
	return returnValue;
};
function fixEvent(event) { // v2005-12-06
	// add W3C standard event methods
	event.preventDefault = fixEvent.preventDefault;
	event.stopPropagation = fixEvent.stopPropagation;
	return event;
};
fixEvent.preventDefault = function() { // v2005-12-06
	this.returnValue = false;
};
fixEvent.stopPropagation = function() { // v2005-12-06
	this.cancelBubble = true;
};



/*
 * Añade/Quita/Busca clases CSS - http://dean.edwards.name/IE7/caveats/
 */
function addClass(element, className) { // v2004-10-24
	if (!hasClass(element, className)) {
		if (element.className) element.className += " " + className;
		else element.className = className;
	}
};
function removeClass(element, className) { // v2004-10-24
	var regexp = new RegExp("(^|\\s)" + className + "(\\s|$)");
	element.className = element.className.replace(regexp, "$2");
};
function hasClass(element, className) { // v2004-10-24
	var regexp = new RegExp("(^|\\s)" + className + "(\\s|$)");
	return regexp.test(element.className);
};


/***************************************************************************************/



/*
 * Efectos de rollover del menú del encabezado
 */
function rollover_me(id){
	var obj, entradas;
	if(document.getElementById){
		obj=document.getElementById(id);
	}

	if(obj && obj.getElementsByTagName && (entradas=obj.getElementsByTagName('div')) ){
		for(var i=0; i<entradas.length; i++){
			if(hasClass(entradas[i], 'li')){
				addEvent(entradas[i], 'mouseover', function(){
					addClass(this, 'hover');
					var a=this.getElementsByTagName('a')[0];
					window.status=a.href;
				});
				addEvent(entradas[i], 'mouseout', function(){
					removeClass(this, 'hover');
					window.status='';
				});
				addEvent(entradas[i], 'click', function(){
					var a=this.getElementsByTagName('a')[0];
					document.location.href=a.href;
				});
			}
		}
	}
}



/*
 * Procesamos los enlaces marcados como externos (rel="external")
 *
 * etiqueta (cadena): HTML para añadir al final del enlace
 * enVentanaNueva (bool): ¿establecer target="_blank"?
 */
function enlacesExternos(etiqueta, enVentanaNueva){ // v2006-09-01
	if(!document.getElementsByTagName){
		return;
	}

	var titulo='enlace externo' + (enVentanaNueva ? ', nueva ventana' : '');
	var enlaces=document.getElementsByTagName('a');
	for(var i=0; i<enlaces.length; i++){
		var a=enlaces[i];
		if(a.getAttribute('href') && a.getAttribute('rel')=='external'){
			if(etiqueta){
				a.innerHTML+=etiqueta;
			}
			if(enVentanaNueva){
				a.target='_blank';
			}
			a.title+=(a.title!='' ? ' ' : '') + '[' + titulo + ']';
		}
	}
}


/*
 * Método para cambiar una imagen por otra a partir de su identificador.
 */
function cambiarImagen(id,url){
  if (document.getElementById(id)){
    document.getElementById(id).src = url;
 
  }
}

function cambiarhref(id,url){
  if (document.getElementById(id)){
    document.getElementById(id).href = url;
 
  }
}

function ocultar_defecto(id){
  if (id=='email'){
    if (document.getElementById(id).value=='E-mail')
      document.getElementById(id).value='';
  }
}

function mostrar_defecto(id){
  if (id=='email'){
    if (document.getElementById(id).value=='')
      document.getElementById(id).value='E-mail';
  }
}

function anchura(){
	if (document.body.offsetWidth<950){
		document.getElementById('maqueta_todo').style.width='950';
	}
}



/*
 * Precarga de imágenes
 */
function precarga(){ // v2005-05-22
    var argv=precarga.arguments;
    var argc=precarga.arguments.length
    if(!document.precarga_img){
        document.precarga_img=new Array();
    }

    for(var i=0; i<argc; i++){
        var j=document.precarga_img.length;
        document.precarga_img[j]=new Image();
        document.precarga_img[j].src=argv[i];
    }
}



/*
 * Devuelve el valor seleccionado en una lista de tipo "radio"
 */
function valor_radio(lista){ // v2005-03-14
    for(i=0; i<lista.length; i++)
        if(lista[i].checked)
            return lista[i].value;
    return "";
}



function precarga_poblaciones(cod_provincia){
	var url='/lib/inc/poblaciones.inc.php?cod_provincia=' + cod_provincia;
	var opciones={
/*		onSuccess: function(){
			alert('Precarga correcta');
		},
		onFailure: function(){
			alert('Precarga errónea');
		},*/
		method: 'get',
		encoding: 'ISO-8859-1'
	};

	new Ajax.Request(url, opciones);
}
//my
function hide_by_selection(to_hide,to_check,indexcondition){
	select_to_hide=document.getElementById(to_hide);
	select_to_check=document.getElementById(to_check);
	if (select_to_check.selectedIndex==indexcondition)
		select_to_hide.style.visibility='visible';
	else
		select_to_hide.style.visibility='hidden';
}

/*esta es mia: actualiza provincia por el cp*/
function actualiza_by_cp( select_provincia, select_poblacion, c_p ){ 
   index_to_sel=0;
   		cp_tofind=c_p.value.charAt(0)+c_p.value.charAt(1);
   		for(i=1; i<select_provincia.options.length-1;i++){
			 if (select_provincia.options[i].value==cp_tofind) index_to_sel=i;
		}
  		select_provincia.selectedIndex=index_to_sel;
}

function actualizar_poblaciones(select_provincia, select_poblacion, select_distrito, c_p, usar_cp){
	var cod_provincia=select_provincia.value;
	var url;
	var opciones={
		onSuccess: function(){
		},
		onFailure: function(){
			select_poblacion.options[0]=new Option('Se ha producido un error', '');
			select_poblacion.selectedIndex=0;
		},
		onComplete: function(){
			select_provincia.removeAttribute('disabled');
			select_provincia.removeAttribute('readOnly');
			
			asignar_eventos_poblacion();
		},
		method: 'get',
		encoding: 'iso-8859-1'
	};
	// Sólo si ha cambiado el código postal se actualizan las poblaciones buscando ese código
	if (usar_cp)
		url='/lib/inc/poblaciones.inc.php?cod_provincia=' + cod_provincia + '&cp=' + c_p.value;	
	else
		url='/lib/inc/poblaciones.inc.php?cod_provincia=' + cod_provincia;	

	if(select_distrito){
		select_distrito.length=0;
		select_distrito.options[0]=new Option('<Todos los distritos>', '');
		select_distrito.selectedIndex=0;
	}

	if(cod_provincia!='' ){ 
		select_poblacion.options[0]=new Option('(Obteniendo lista, espere por favor...)', '');
		select_poblacion.selectedIndex=0;

		select_provincia.setAttribute('disabled', 'disabled');
		select_provincia.setAttribute('readOnly', 'readonly');

		select_poblacion.setAttribute('disabled', 'disabled');
		select_poblacion.setAttribute('readOnly', 'readonly');

		new Ajax.Updater(select_poblacion.parentNode, url, opciones);
	}else{
		var s=document.createElement('select');
		s.name= 'pob'; 
		s.options[0]=new Option('<Todas las poblaciones>', '');
		select_poblacion.parentNode.replaceChild(s, select_poblacion);
	}
}

function actualizar_distritos(select_poblacion, select_distrito){
	var cod_poblacion=select_poblacion.value;
	var url='/lib/inc/distritos.inc.php?cod_poblacion=' + cod_poblacion;
	var opciones={
		onSuccess: function(){
		},
		onFailure: function(){
			select_distrito.options[0]=new Option('Se ha producido un error', '');
			select_distrito.selectedIndex=0;
		},
		onComplete: function(){
			select_poblacion.removeAttribute('disabled');
			select_poblacion.removeAttribute('readOnly');

			asignar_eventos();
		},
		method: 'get',
		encoding: 'iso-8859-1'
	};
	
	
	if(cod_poblacion!=''){
		select_distrito.options[0]=new Option('(Obteniendo lista, espere por favor...)', '');
		select_distrito.selectedIndex=0;

		select_poblacion.setAttribute('disabled', 'disabled');
		select_poblacion.setAttribute('readOnly', 'readonly');

		select_distrito.setAttribute('disabled', 'disabled');
		select_distrito.setAttribute('readOnly', 'readonly');

		new Ajax.Updater(select_distrito.parentNode, url, opciones);
	}else{
		var s=document.createElement('select');
		s.name='dis';
		s.options[0]=new Option('<Todos los distritos>', '');
		select_distrito.parentNode.replaceChild(s, select_distrito);
	}
}
function actualizar_calles(text_cp, select_calle, select_provincia/*,select_poblacion, select_distrito*/){
	var cp=text_cp.value;
	var url='/lib/inc/calles.inc.php?cp=' + cp;
	var opciones={
		onSuccess: function(){
		},
		onFailure: function(){
			select_calle.options[0]=new Option('Se ha producido un error', '');
			select_calle.selectedIndex=0;
		},
		onComplete: function(){
			text_cp.removeAttribute('disabled');
			text_cp.removeAttribute('readOnly');

			asignar_eventos_poblacion();
		},
		method: 'get',
		encoding: 'iso-8859-1'
	};

	if(cp!=''){
		select_calle.options[0]=new Option('(Obteniendo lista, espere por favor...)', '');
		select_calle.selectedIndex=0;

		text_cp.setAttribute('disabled', 'disabled');
		text_cp.setAttribute('readOnly', 'readonly');

		select_calle.setAttribute('disabled', 'disabled');
		select_calle.setAttribute('readOnly', 'readonly');

		new Ajax.Updater(select_calle.parentNode, url, opciones);
		
		actualizar_provincia(cp.substring(0,2), select_provincia);
	
	}else{
		var s=document.createElement('select');
		s.name='calle';
		s.options[0]=new Option('<Todas las calles>', '');
		select_calle.parentNode.replaceChild(s, select_calle);
	}
}



function actualizar_provincia(provincia, select_provincia){
	var url='/lib/inc/provincia.inc.php?cod_provincia=' + provincia;
	var opciones={
		onSuccess: function(){
		},
		onFailure: function(){
			select_provincia.options[0]=new Option('Se ha producido un error', '');
			select_provincia.selectedIndex=0;
		},
		onComplete: function(){
			asignar_eventos_provincia();
		},
		method: 'get',
		encoding: 'iso-8859-1'
	};

	if(provincia!=''){
		select_provincia.options[0]=new Option('(Obteniendo lista, espere por favor...)', '');
		select_provincia.selectedIndex=0;

		select_provincia.setAttribute('disabled', 'disabled');
		select_provincia.setAttribute('readOnly', 'readonly');

		new Ajax.Updater(select_provincia.parentNode, url, opciones);
	}else{
		var s=document.createElement('select');
		s.name='prov';
		s.options[0]=new Option('<Todas las provincias>', '');
		select_provincia.parentNode.replaceChild(s, select_provincia);
	}
}

/*
 * Recibe una cadena de texto que contiene supuestamente un número
 * en formato español (separador decimal coma, separador de miles punto)
 * y devuelve un número de coma flotante o NaN si no hay número
 *
 * Nota: se sugiere usar isNaN(numero) para comprobar después el resultado
 */
function txt2num(txt){
	txt=txt.toString();

	// Eliminamos caracteres no deseados (incl. separador de miles)
	txt=txt.replace(/[^0-9,-]/g, '');

	// Si no tiene decimales se los ponemos
	if (txt.indexOf(',')==-1){
		txt=txt+",00";
	}

	// Convertimos la primera coma en punto
	txt=txt.replace(/,/, '.');

	// Si hubiera dos comas, eliminamos lo que hay tras la segunda
	txt=txt.replace(/,.*$/, '');

	return parseFloat(txt);
}


/*
 * Recibe un número de coma flotante y devuelve una cadena con el número
 * en formato español (separador decimal coma, separador de miles punto)
 *
 * Si no es entero se redondea a 2 decimales
 */
function num2txt(num, usar_separador_miles){

	if(isNaN(num)){
		return '';
	}

	num=num.toFixed(2);

	// Convertimos el punto en coma
	num=num.toString().replace(/\./, ',');
	
	if(usar_separador_miles){
		// Añadimos los separadores de miles
		var miles=new RegExp('(-?[0-9]+)([0-9]{3})');
		while(miles.test(num)) {
			num=num.replace(miles, '$1.$2');
		}
	}
	
	return num;
}

/*
 * Activa o desactiva la acción automática de autocompletar un formulario en el navegador.
 * Evita que salga el desplegable con los valores previos que se pusieron en ese campo.
 */
function autocompletar(activar){
	var valor=activar ? 'on' : 'off';
	
	var f=document.forms;
	for(var i=0; i<f.length; i++){
		var e=f[i].elements;
		for(var j=0; j<e.length; j++){
			e[j].setAttribute('autocomplete', valor);
		}
	}
}
autocompletar(false);