/* (C)Stephen Chalmers
* http://bytes.com/topic/javascript/answers/145532-replace-french-characters-form-input
* Strips grave, acute & circumflex accents from vowels
*/
function stripVowelAccent(str)
{
var s=str;

var rExps=[ /[\xC0-\xC2]/g, /[\xE0-\xE2]/g,
/[\xC8-\xCA]/g, /[\xE8-\xEB]/g,
/[\xCC-\xCE]/g, /[\xEC-\xEE]/g,
/[\xD2-\xD4]/g, /[\xF2-\xF4]/g,
/[\xD9-\xDB]/g, /[\xF9-\xFB]/g ];

var repChar=['A','a','E','e','I','i','O','o','U','u'];

for(var i=0; i<rExps.length; i++)
s=s.replace(rExps[i],repChar[i]);

return s;
}

/**
* Redondea un decimal, dejándolo solo los n decimales
*/
function redondea(sVal, nDec)
{	
	s = String(sVal);
	var index = s.indexOf(",");

	if(index > 0)
		s = s.substr(0,  index + nDec + 1);

	return s;
} 

function generaTablaCentrosHTML(centro)
{
	if(centro != null)
	{
		var html = '<h1>' + centro.idCentro + ' - ' + centro.nombreCentro +'</h1>';		
		html += '<p>';
		html += '<code>';
		html += '<label>Comunidad Autónoma</label> ';
		html += (centro.nombreComunidad? centro.nombreComunidad: '') + '<br/>';
		html += '<label>Provincia</label> ';
		html += (centro.nombreProvincia? centro.nombreProvincia: '') + '<br/>';		
		html += '<label>Municipio</label> ';
		html += (centro.nombreMunicipio? centro.nombreMunicipio: '') + '<br/>' ;
		html += '<label>Localidad</label> ';
		html += (centro.nombreLocalidad? centro.nombreLocalidad: '') + '<br/>';		
		html += '<label>Denominación</label> ';
		html += (centro.denominacion? centro.denominacion: '') + '<br/>' ;
		html += '<label>Depenencia</label> ';
		html += (centro.dependencia? centro.dependencia: '') + '<br/>';		
		html += '<label>Dirección</label> ';
		html += (centro.domicilio? centro.domicilio: '') + '<br/>' ;
		html += '<label>Código Postal</label> ';
		html += (centro.codPostal? centro.codPostal : '') + '<br/>';		
		html += '<label>Teléfono</label> ';
		html += (centro.telefono? centro.telefono: '') + '<br/>' ;
		html += '<label>e-mail</label> ';
		html += (centro.email? centro.email : '') + '<br/>';		
		html += '<label>Web</label> ';
		html += (centro.url? centro.url: '' )+ '<br/>';		
		
		html += '</code>\n';
		html += '</p>\n';
		
		return html;
	}
	return 'No hay información detallada del centro';	
}

function generarPaginadorCentros(pagActual, numTotalPag)
{
	html = "";
	
	if(numTotalPag > 1) 
	{
		html = "<select name='paginador' id='paginador' onchange='busquedaCentros(document.getElementById(\"paginador\").selectedIndex + 1);'>";
		for(var i=1; i<= numTotalPag; i++){						
    		html += "<option value='"+i+"' ";
    		if(pagActual == i)
    			html+="selected";
    		html += ">"+i+"</option>"; 
    	}
    	html += "</select>";
	}
	
	return html;

}


/** 
* Returns the value of the selected radio button in the radio group, null if 
* none are selected, and false if the button group doesn't exist 
* 
* @param {radio Object} or {radio id} el 
* OR 
* @param {form Object} or {form id} el 
* @param {radio group name} radioGroup 
* @see http://xavisys.com/2007/03/using-prototype-javascript-to-get-the-value-of-a-radio-group/
*/
function $RF(el, radioGroup) 
{ 
	if($(el).type && $(el).type.toLowerCase() == 'radio') 
	{ 
		var radioGroup = $(el).name;    
		el = $(el).form; 
	} 
	else if ($(el).tagName.toLowerCase() != 'form') 
	{ 
		return false; 
	} 

	var checked = $(el).getInputs('radio', radioGroup).find( 
		function(re) {return re.checked;} 
	); 

	return (checked) ? $F(checked) : null; 
}

function hideResultDivs()
{
	$('map').hide();			
	$('divListaCentrosExcel').hide();	
	$('tableListaCentros').hide();
	$('tableBodyListaCentros').update('');
}
/**
* Busqueda de centros empleando los criterios indicados en el formulario
* @param numPag - Número de página de resultados que se desea cargar. Por defecto el tamaño de página es de 25.
*/
function busquedaCentros(numPag)
{
	if(numPag == null || numPag == '')
	{
		numPag = 1;		
	}

	$('numPag').setAttribute('value', numPag);	
	
	hideResultDivs();
		
	new Ajax.Request('?do=ajax@BusquedaCentros&numPag='+numPag, {			
			method: 'post',
			
			parameters: $('formBusqueda').serialize(true),
			
			onLoading:function(transport) 
			{
				$('divLoading').show();																
			}
			,

			onSuccess: function(transport) 
			{
				$('divLoading').hide();
	

				var result = transport.responseText.evalJSON();
				var listaCentros = result['listaCentros'];
				var numTotalPag  = result['numTotalPag'];
				//Recuperamos parametros para geposicionamiento
				var latitud  = result['latitud'];
				var longitud  = result['longitud'];
				var kmlFileURL  = result['kmlFileURL'];

				
				if(listaCentros != null)
				{
					var size = listaCentros.length;
					for(var i=0; i<size; i++)
					{
						var centro = listaCentros[i];
						
						var row = new Element('tr');			
						
						var hiddenDiv = 'hiddenDiv' + i;
						
						row.setAttribute('onmouseover', 'ShowContent("'+hiddenDiv+'"); return true;');
						row.setAttribute('onmouseout', 'HideContent("'+hiddenDiv+'"); return true;');
						row.setAttribute('href', 'javascript:ShowContent("'+hiddenDiv+'")');			
						
						var txtHeaderColumn = '<a href="?do=FichaCentro&idCentro='+ centro.idCentro + '">' + centro.idCentro + '</a>';

						row.appendChild( new Element('th', { 'scope': 'row'} ).update(txtHeaderColumn) );
						row.appendChild( new Element('td').update(centro.nombreCentro) );
						row.appendChild( new Element('td').update(centro.denominacion) );

						if($RF('formBusqueda', 'tipoBusqueda') == 'Proximidad')
						{
							row.appendChild( new Element('td').update(centro.domicilio + '. ' + centro.nombreLocalidad + ' ('+ centro.nombreProvincia +')' ) );
							row.appendChild( new Element('td').update( redondea(centro.distancia, 2) ) );							
						}
						else
						{
							row.appendChild( new Element('td').update(centro.domicilio) );
							row.appendChild( new Element('td').update(centro.nombreLocalidad + ' ('+ centro.nombreProvincia +')') );

						}

						row.appendChild( new Element('div', { 'id': ''+hiddenDiv, 'style': 'display:none; position:absolute; border-style: solid; border-color: #E0E0E0; background-color: white; padding: 5px;'} )).update( generaTablaCentrosHTML(centro) );
												
						$('tableBodyListaCentros').appendChild(row);
					}
					$('tdTotalCentros').update(size + ' Centros ' + generarPaginadorCentros(numPag, numTotalPag));
										
					
					if($RF('formBusqueda', 'tipoBusqueda') == 'Proximidad')
					{
						//Carga y visualización del enlace de la exportación a excel
						$('aListaCentrosExcel').setAttribute('href', '?do=ListadoCentrosExcel&' + Form.serialize('formBusqueda') );
						$('divListaCentrosExcel').show();

						//Cambio en el título de la cabecera
						$('Distancia').update('Distancia (Km)');

						//Carga de mapa con los centros
						//alert('Latitud: '+latitud+' Longitud: '+longitud+' url: '+kmlFileURL);
						var address = $F('tipoViaRef') + ' ' + $F('direccionRef') + ' ' + $F('numeroRef')
								+ '<br/>' + $F('localidadRef') + ' (' + $F('provinciaRef') + ')';
						$('map').show();
						loadMapFromKMLFile(latitud, longitud, address, kmlFileURL, 'map') ;
						
					}
					else
					{
						//Cambio en el título de la cabecera
						$('Distancia').update('Localidad');
						
						//$('map').hide();						
						//$('divListaCentrosExcel').hide();	
					}

					$('tableListaCentros').show();
				}
			},
			
			onFailure: function(transport) 
			{

				$('divLoading').hide();

				alert(transport.responseText);	
				Form.reset('formBusqueda');					
			}
		});
}
