var map = 0;
var info = "";
var infowindow;
var markerPos;
var infoPos;
var markerInfo;
var markers = new Array();
var infoWindows = new Array();
var restaurantes = new Array();
var pagina = 1;
var ruta = "/";
	
var orden = 0;
var ordenacion = '';

function toUrl(texto) {
	texto = texto.replace(/á/gi, "a");
	texto = texto.replace(/é/gi, "e");
	texto = texto.replace(/í/gi, "i");
	texto = texto.replace(/ó/gi, "o");
	texto = texto.replace(/ú/gi, "u");
	texto = texto.replace(/ñ/gi, "n");
	texto = texto.replace(/[^a-zA-Z0-9 ]/gi, "");
	texto = texto.replace(/ /g, "-");
	texto = texto.replace(/039/, "");
	texto = texto.replace(/acute/g, "");
	texto = texto.replace(/tilde/g, "");
	return texto.toLowerCase();
}

function sacarPos() {
	if ((typeof longitud == "undefined") && (typeof latitud == "undefined")) {
		firstRun = 1;
		if ((typeof google != "undefined") && (typeof google.gears != "undefined")) {
			var geo = google.gears.factory.create('beta.geolocation');
			function updatePosition(position) {
				latitud = position.latitude;
				longitud = position.longitude;
				posicionEncontrada(latitud, longitud);
			}
			function handleError(positionError) {
				if (google.loader.ClientLocation) {
					latitud = google.loader.ClientLocation.latitude;
					longitud = google.loader.ClientLocation.longitude;
					info = "<div class='infoWindow'>" +
						"<br>Ciudad: <b>" + google.loader.ClientLocation.address.city + "</b><br><br></div>";
					posicionEncontrada(latitud, longitud);
				} else {
					if (navigator.geolocation) {
						navigator.geolocation.getCurrentPosition(foundLocation, noLocation, {timeout: 2000});
					}
				}
			}
			try { geo.getCurrentPosition(updatePosition, handleError); }
			catch (e) {
				if (navigator.geolocation) {
					navigator.geolocation.getCurrentPosition(foundLocation, noLocation, {timeout: 2000});
				}
				else {
					if (google.loader.ClientLocation) {
						latitud = google.loader.ClientLocation.latitude;
						longitud = google.loader.ClientLocation.longitude;
						info = "<div class='infoWindow'>" +
							"<br>Ciudad: <b>" + google.loader.ClientLocation.address.city + "</b><br><br></div>";
						posicionEncontrada(latitud, longitud);
					}
					else {
						latitud = 40.4166909;
						longitud = -3.7003454;
						info = "<div class='infoWindow'>" +
							"<br>Ciudad: <b>Madrid</b><br><br></div>";
						posicionEncontrada(latitud, longitud);
					}
				}
			}
		}
		else if (navigator.geolocation) {
			navigator.geolocation.getCurrentPosition(foundLocation, noLocation, {timeout: 2000});
		}
		else if (google.loader.ClientLocation) {
			latitud = google.loader.ClientLocation.latitude;
			longitud = google.loader.ClientLocation.longitude;
			info = "<div class='infoWindow'>" +
				"<br>Ciudad: <b>" + google.loader.ClientLocation.address.city + "</b><br><br></div>";
			posicionEncontrada(latitud, longitud);
		}
		else {
			latitud = 40.4166909;
			longitud = -3.7003454;
			info = "<div class='infoWindow'>" +
				"<br>Ciudad: <b>Madrid</b><br><br></div>";
		}
	}
	if (typeof latitud != "undefined")
		posicionEncontrada(latitud, longitud);
}

function posicionEncontrada(latitud, longitud) {
	document.getElementById('coordenadas').src = "coordenadas.php?lat=" + latitud + "&lng=" + longitud;
}

function foundLocation(position) {
	if (typeof position.coords.latitude != "undefined") {
		latitud = position.coords.latitude;
		longitud = position.coords.longitude;
		posicionEncontrada(latitud, longitud, "");
	}
	else {
		latitud = 40.4166909;
		longitud = -3.7003454;
		info = "<div class='infoWindow'>" +
			"<br>Ciudad: <b>Madrid</b><br><br></div>";
		posicionEncontrada(latitud, longitud, info);
	}
}

function noLocation() {
	if (google.loader.ClientLocation) {
		latitud = google.loader.ClientLocation.latitude;
		longitud = google.loader.ClientLocation.longitude;
		info = "<div class='infoWindow'>" +
			"<br>Ciudad: <b>" + google.loader.ClientLocation.address.city + "</b><br><br></div>";
		posicionEncontrada(latitud, longitud, info);
	}
	else {
		latitud = 40.4166909;
		longitud = -3.7003454;
		info = "<div class='infoWindow'>" +
			"<br>Ciudad: <b>Madrid</b><br><br></div>";
		posicionEncontrada(latitud, longitud, info);
	}
}

function drawMap(latitud, longitud, info) {
	var point = new google.maps.LatLng(latitud, longitud);
	var myOptions = {
			scrollwheel: false,
			zoom: 16,
			draggableCursor: 'default',
			draggingCursor: 'pointer',
			center: point,
			zIndex: 2,
			mapTypeId: google.maps.MapTypeId.ROADMAP
		};
    map = new google.maps.Map(document.getElementById("map"), myOptions);
	map.mapTypeControl = false;
	google.maps.event.addListener(map, "rightclick", function(event) {
		mostrarMenuContextual(event.latLng, 1);
	});
	google.maps.event.addListener(map, "click", function(event) {
		quitarMenuContextual();
	});
	google.maps.event.addListener(map, "drag", function(event) {
		quitarMenuContextual();
	});

	markerPos = new google.maps.Marker({
		position: point,
		map: map,
		zIndex: 5,
		icon: new google.maps.MarkerImage('images/icons/map-position.png', new google.maps.Size(49, 46)),
		title: 'Title',
		content: info,
	});
    infoPos = new google.maps.InfoWindow({  
		content: info
    });
}

function drawMapRest(latitud, longitud, edit) {
	if (edit == 0)
		icono = '';
	else
		icono = 'default';
	var point = new google.maps.LatLng(latitud, longitud);
	var myOptions = {
		scrollwheel: false,
		zoom: 16,
		center: point,
		draggableCursor: icono,
		mapTypeId: google.maps.MapTypeId.ROADMAP
	};
    map = new google.maps.Map(document.getElementById("map"), myOptions);
	map.mapTypeControl = false;
    markers[0] = new google.maps.Marker({
	    position: point,
	    map: map,
	    icon: new google.maps.MarkerImage(ruta + 'images/icons/map-position-mini.png', new google.maps.Size(30, 28))
	});
    if (edit == 1) {
		google.maps.event.addListener(map, "rightclick", function(event) {
			mostrarMenuContextual(event.latLng, 2);
		});
		google.maps.event.addListener(map, "click", function(event) {
			quitarMenuContextual();
		});
		google.maps.event.addListener(map, "drag", function(event) {
			quitarMenuContextual();
		});
    }
}

function stripCharacter(words,character) {
	var spaces = words.length;
	for (var x = 1; x <= spaces; x++) {
		words = words.replace(character, "");
	}
	return words;
}

function MultiDimensionalArray(iRows,iCols) {
	var i;
	var j;
	var a = new Array(iRows);
	for (i=0; i < iRows; i++) {
		a[i] = new Array(iCols);
		for (j=0; j < iCols; j++)
			a[i][j] = "";
	}
	return(a);
}

function cambiarTab(tab) {  
	  
	for (var i = 1; i < 5; i++) {  
		if (document.getElementById('tab_' + i)) {
			document.getElementById('top_' + i).src = 'images/tab_inactivo.png';
			document.getElementById('content_' + i).style.display = 'none';  
			document.getElementById('tab_' + i).className = 'tab';
		}
	} 
	document.getElementById('top_' + tab).src = 'images/tab_activo.png';
	document.getElementById('content_' + tab).style.display = 'block';  
	document.getElementById('tab_' + tab).className = 'tab active';      
  
}

function cambiarTabLosMas(tab, ruta) {  
	  
	for (var i = 1; i < 4; i++) {  
		if (document.getElementById('losmas_' + i)) {
			document.getElementById('losmastop_' + i).src = ruta + 'images/losmastab_inactivo.png';
			document.getElementById('losmas_content_' + i).style.display = 'none';  
			document.getElementById('losmas_' + i).className = 'losmas_tab';
		}
	} 
	document.getElementById('losmastop_' + tab).src = ruta + 'images/losmastab_activo.png';
	document.getElementById('losmas_content_' + tab).style.display = 'block';  
	document.getElementById('losmas_' + tab).className = 'losmas_tab losmas_active';      
  
}

function cambiarTabFicha(tab) {  
	  
	for (var i = 1; i < 5; i++) {  
		if (document.getElementById('ficha_' + i)) {
			document.getElementById('fichatop_' + i).src = '../../images/fichatab_inactivo.png';
			document.getElementById('ficha_content_' + i).style.display = 'none';  
			document.getElementById('ficha_' + i).className = 'ficha_tab';
		}
	} 
	document.getElementById('fichatop_' + tab).src = '../../images/fichatab_activo.png';
	document.getElementById('ficha_content_' + tab).style.display = 'block';  
	document.getElementById('ficha_' + tab).className = 'ficha_tab ficha_active';      
  
}

function cambiarTabForm(tab) {  
	  
	for (var i = 1; i < 5; i++) {  
		if (document.getElementById('form_' + i)) {
			document.getElementById('formtop_' + i).src = 'images/fichatab_inactivo.png';
			document.getElementById('form_content_' + i).style.display = 'none';  
			document.getElementById('form_' + i).className = 'form_tab';
		}
	} 
	document.getElementById('formtop_' + tab).src = 'images/fichatab_activo.png';
	document.getElementById('form_content_' + tab).style.display = 'block';  
	document.getElementById('form_' + tab).className = 'form_tab form_active';      
  
}

function rellenar(form, datos) {
	form.nombre.value = datos[2];
	form.direccion.value = datos[3];
	form.cp.value = datos[4];
	form.localidad.value = datos[5];
	form.provincia.value = datos[6];
	form.telefono.value = datos[7];
	form.web.value = datos[8];
	form.email.value = datos[9];
	form.menuDelDia.value = datos[10];
	form.precioMenuDelDia.value = datos[11];
	form.menuDegustacion.value = datos[12];
	form.precioMenuDegustacion.value = datos[13];
	form.comidaRapida.value = datos[14];
	form.precioComidaRapida.value = datos[15];
	form.horario.value = datos[18];
	form.tipoCocina.value = datos[19];
	if (datos[20] == 1)
		form.parking.checked = true;
	else
		form.parking.checked = false;
	if (datos[21] == 1)
		form.terraza.checked = true;
	else
		form.terraza.checked = false;
	if (datos[22] == 1)
		form.domicilio.checked = true;
	else
		form.domicilio.checked = false;
	form.otrosServicios.value = datos[23];
	form.informacionAdicional.value = datos[24];
}

function confirmarBorrar(id) {
	var resp = confirm('¿Está seguro que desea borrar ese restaurante?');
	if (resp) {
		document.location="?del=" + id;
	}
}

function enviarUsuario(form) {
	if ((form.usuario.value == "") || (stripCharacter(form.usuario.value, " ") == "")) {
		alert('Error: No ha introducido el nombre de usuario.');
		form.usuario.focus();
	}
	else if ((form.password.value == '') || (stripCharacter(form.password.value, " ") == "")) {
		alert('Error: No ha introducido la contraseña.');
		form.password.focus();
	}
	else if ((form.password.length < 4) || (form.password.length > 16)) {
		alert('Error: La contraseña debe tener entre 4 y 16 caracteres.');
		form.password.focus();
	}
	else if ((form.email.value == '') || (stripCharacter(form.email.value, " ") == "")) {
		alert('Error: No ha introducido su dirección de correo electrónico.');
		form.email.focus();
	}
	else if ((form.localidad.value == '') || (stripCharacter(form.localidad.value, " ") == "")) {
		alert('Error: No ha introducido la localidad.');
		form.localidad.focus();
	}
	else {
		form.submit();
	}
}

function enviarRest(form) {
	if ((form.usuario.value == "") || (stripCharacter(form.usuario.value, " ") == "")) {
		alert('Error: No ha introducido el nombre de usuario.');
		form.usuario.focus();
	}
	else if ((form.password.value == '') || (stripCharacter(form.password.value, " ") == "")) {
		alert('Error: No ha introducido la contraseña.');
		form.password.focus();
	}
	else if ((form.nombre.value == "") || (stripCharacter(form.nombre.value, " ") == "")) {
		alert('Error: No ha introducido el nombre del restaurante.');
		form.nombre.focus();
	}
	else if ((form.direccion.value == '') || (stripCharacter(form.direccion.value, " ") == "")) {
		alert('Error: No ha introducido la dirección del restaurante.');
		form.direccion.focus();
	}
	else if ((form.telefono.value == '') || (stripCharacter(form.telefono.value, " ") == "")) {
		alert('Error: No ha introducido el teléfono del restaurante.');
		form.telefono.focus();
	}
	else if ((form.localidad.value == '') || (stripCharacter(form.localidad.value, " ") == "")) {
		alert('Error: No ha introducido la localidad del restaurante.');
		form.localidad.focus();
	}
	else if ((form.provincia.value == '') || (stripCharacter(form.provincia.value, " ") == "")) {
		alert('Error: No ha introducido el departamento del restaurante.');
		form.provincia.focus();
	}
	else if ((form.email.value == '') || (stripCharacter(form.email.value, " ") == "")) {
		alert('Error: No ha introducido su dirección de email.');
		form.email.focus();
	}
	else if (((form.precioMenuDelDia.value == '0.00') && (form.precioMenuDegustacion.value == '0.00') && (form.precioComidaRapida.value == '0.00') && (form.sugerencias.value == '')) || ((form.menuDelDia.value == '') && (form.menuDegustacion.value == '') && (form.comidaRapida.value == '') && (form.sugerencias.value == ''))) {
		alert('Error: Debe introducir al menos un menú o sugerencia.');
		form.menuDelDia.focus();
	}
	else {
		form.submit();
	}
}

function enviarRest2(form) {
	if ((form.nombre.value == "") || (stripCharacter(form.nombre.value, " ") == "")) {
		alert('Error: No ha introducido el nombre del restaurante.');
		form.nombre.focus();
	}
	else if ((form.direccion.value == '') || (stripCharacter(form.direccion.value, " ") == "")) {
		alert('Error: No ha introducido la dirección del restaurante.');
		form.direccion.focus();
	}
	else if ((form.telefono.value == '') || (stripCharacter(form.telefono.value, " ") == "")) {
		alert('Error: No ha introducido el teléfono del restaurante.');
		form.telefono.focus();
	}
	else if ((form.localidad.value == '') || (stripCharacter(form.localidad.value, " ") == "")) {
		alert('Error: No ha introducido la localidad del restaurante.');
		form.localidad.focus();
	}
	else if ((form.provincia.value == '') || (stripCharacter(form.provincia.value, " ") == "")) {
		alert('Error: No ha introducido el departamento del restaurante.');
		form.provincia.focus();
	}
	else if (((form.precioMenuDelDia.value == '0.00') && (form.precioMenuDegustacion.value == '0.00') && (form.precioComidaRapida.value == '0.00') && (form.sugerencias.value == '')) || ((form.menuDelDia.value == '') && (form.menuDegustacion.value == '') && (form.comidaRapida.value == '') && (form.sugerencias.value == ''))) {
		alert('Error: Debe introducir al menos un menú o sugerencia.');
		form.menuDelDia.focus();
	}
	else {
		form.submit();
	}
}

function enviarCupon(form) {
	/*if ((form.nombre.value == "") || (stripCharacter(form.nombre.value, " ") == "")) {
		alert('Error: No ha introducido el nombre del restaurante.');
		form.nombre.focus();
	}
	else if ((form.direccion.value == '') || (stripCharacter(form.direccion.value, " ") == "")) {
		alert('Error: No ha introducido la dirección del restaurante.');
		form.direccion.focus();
	}
	else if ((form.telefono.value == '') || (stripCharacter(form.telefono.value, " ") == "")) {
		alert('Error: No ha introducido el teléfono del restaurante.');
		form.telefono.focus();
	}
	else if ((form.localidad.value == '') || (stripCharacter(form.localidad.value, " ") == "")) {
		alert('Error: No ha introducido la localidad del restaurante.');
		form.localidad.focus();
	}
	else if ((form.provincia.value == '') || (stripCharacter(form.provincia.value, " ") == "")) {
		alert('Error: No ha introducido la provincia del restaurante.');
		form.provincia.focus();
	}
	else if (((form.precioMenuDelDia.value == '0.00') && (form.precioMenuDegustacion.value == '0.00') && (form.precioComidaRapida.value == '0.00')) || ((form.menuDelDia.value == '') && (form.menuDegustacion.value == '') && (form.comidaRapida.value == ''))) {
		alert('Error: Debe introducir al menos un menú.');
		form.menuDelDia.focus();
	}
	else {*/
		form.submit();
	//}
}
function enviarUsuarioCupones () {
	form = document.forms["formSuscripcion"];
	if (form.email.value == '') {
		alert("ERROR: Debe introducir una dirección de email.");
		form.email.focus();
	}
	else if (!checkEmail(form.email.value)) {
		alert("ERROR: Debe introducir una dirección de email válida.");
		form.email.focus();
	}
	else if (form.provincia.value == '') {
		alert("ERROR: Debe seleccionar un departamento.");
		form.provincia.focus();
	}
	else {
		form.submit();
	}
}

function checkEmail(email) {
	expresionRegular = /[\w-\.]{3,}@([\w-]{2,}\.)*([\w-]{2,}\.)[\w-]{2,4}/;
	return expresionRegular.test(email);
}
function clickCampo(campo) {
	campo.className = "activo";
	if ((campo.value == "Nombre restaurante") || (campo.value == "Plato"))
		campo.value = "";
}

function leaveCampo(campo) {
	if (campo.value == "") {
		campo.className = "inactivo";
		if (campo.name == "buscarNombre")
			campo.value = "Nombre restaurante";
		if (campo.name == "buscarPlato")
			campo.value = "Plato";
	}
	if ((campo.value == 'todas') || (campo.value == 'nada')) {
		campo.className = "inactivo";
	}
}

function buscar() {
	if (document.forms['formBuscar'].buscarNombre.value == "Nombre restaurante")
		document.forms['formBuscar'].buscarNombre.value = "";
	if (document.forms['formBuscar'].buscarPlato.value == "Plato")
		document.forms['formBuscar'].buscarPlato.value = "";
	document.forms['formBuscar'].submit();
}

function ordenarPorLetra(a, campo, ciudad, orden) {
	if (campo == 'nombre')
		var index = 2;
	else if (campo == 'sugerencias')
		var index = 24;
	var aux = new Array(29);
    var cont = 0;
    for (var i = 0; i < a.length; i++) {
    	if (a[i][index] != '') {
			aux = a[i];
			a[i] = a[cont];
			a[cont] = aux;
			cont++;
    	}
    }
    if (orden == 1) {
	    for (var i = 0; i < (cont - 1); i++) {
	    	for (var j = (cont - 1); j > i; j--) {
	    		if (a[i][index].toLowerCase() > a[j][index].toLowerCase()) {
	    			aux = a[j];
	    			a[j] = a[i];
	    			a[i] = aux;
	    		}
	    	}
	    }
	}
    else {
	    for (var i = 0; i < (cont - 1); i++) {
	    	for (var j = (cont - 1); j > i; j--) {
	    		if (a[i][index].toLowerCase() <= a[j][index].toLowerCase()) {
	    			aux = a[j];
	    			a[j] = a[i];
	    			a[i] = aux;
	    		}
	    	}
	    }
	}
    for (var i = cont; i < a.length; i++) {
    	for (var j = (a.length - 1); j > i; j--) {
    		if (a[i][19] > a[j][19]) {
    			aux = a[j];
    			a[j] = a[i];
    			a[i] = aux;
    		}
    	}
    }

    return a;
}

function ordenarPorNumero(a, campo, ciudad, orden) {
	if (campo == 'distancia')
		var index = 19;
	else if (campo == 'cupon')
		var index = 23;
	else if (campo == 'menuDelDia')
		var index = 12;
	else if (campo == 'menuDegustacion')
		var index = 14;
	else if (campo == 'comidaRapida')
		var index = 16;
	var aux = new Array(29);
    var cont = 0;
    for (var i = 0; i < a.length; i++) {
		if (a[i][index] > 0) {
			aux = "";
    		aux = a[i];
    		a[i] = a[cont];
    		a[cont] = aux;
    		cont++;
		}
    }
    if (orden == 1) {
	    for (var i = 0; i < (cont - 1); i++) {
	    	for (var j = (cont - 1); j > i; j--) {
	    		if (parseFloat(a[i][index]) > parseFloat(a[j][index])) {
	    			aux = "";
	    			aux = a[j];
	    			a[j] = a[i];
	    			a[i] = aux;
	    		}
	    	}
	    }
	}
    else {
	    for (var i = 0; i < (cont - 1); i++) {
	    	for (var j = (cont - 1); j > i; j--) {
	    		if (parseFloat(a[i][index]) < parseFloat(a[j][index])) {
	    			aux = "";
	    			aux = a[j];
	    			a[j] = a[i];
	    			a[i] = aux;
	    		}
	    	}
	    }
	}
    for (var i = cont; i < a.length; i++) {
    	for (var j = (a.length - 1); j > i; j--) {
    		if (a[i][19] > a[j][19]) {
    			aux = a[j];
    			a[j] = a[i];
    			a[i] = aux;
    		}
    	}
    }

    return a;
}

function ordenar(campo, ciudad) {
	if (campo != ordenacion) {
		ordenacion = campo;
		orden = 1;
	}
	else {
		if (orden == 1)
			orden = 0;
		else
			orden = 1;
	}
	var flecha = document.getElementById('flecha');
	if (flecha != null)
		flecha.parentNode.removeChild(flecha);
	var parent = document.getElementById('ord_' + campo);
	flecha = document.createElement('img');
	if (orden == 1)
		flecha.src = 'images/icons/flecha_up.png';
	else
		flecha.src = 'images/icons/flecha_down.png';
	flecha.style.border = 0;
	flecha.setAttribute('id', 'flecha');
	flecha.className = 'flecha';
	if (campo != 'cupon')
		parent.appendChild(flecha);
	if (campo == 'distancia')
		restaurantes = ordenarPorNumero(restaurantes, 'distancia', ciudad, orden);
	else if (campo == 'menuDelDia')
		restaurantes = ordenarPorNumero(restaurantes, 'menuDelDia', ciudad, orden);
	else if (campo == 'menuDegustacion')
		restaurantes = ordenarPorNumero(restaurantes, 'menuDegustacion', ciudad, orden);
	else if (campo == 'comidaRapida')
		restaurantes = ordenarPorNumero(restaurantes, 'comidaRapida', ciudad, orden);
	else if (campo == 'cupon')
		restaurantes = ordenarPorNumero(restaurantes, 'cupon', ciudad, orden);
	else if (campo == 'sugerencias')
		restaurantes = ordenarPorLetra(restaurantes, 'sugerencias', ciudad, orden);
	verPagina(1);
}

function verPagina(pag) {
	if (pag == "next")
		pag = pagina + 1;
	if (pag == "prev")
		pag = pagina - 1;
	pagina = pag;
	var total = Math.ceil(restaurantes.length / 10);
	var i = 1;
	var contador = (pag - 1) * 10;
	var table = parent.document.getElementById("listaRest");
	while (table.rows.length > 1)
		table.deleteRow(1);
	while ((contador < (pag * 10)) && (typeof restaurantes[contador] != 'undefined')) {
		if (restaurantes[contador][3] == 1)
			var logo = "<img src='images/restaurantes/" + restaurantes[contador][0] + "/logo.jpg' class='logo' />";
		else
			var logo = "<img src='images/icons/menu_boton.png' class='nologo'/>";
		var campo1 = "<div><a href='javascript:void(0);' onClick='javascript:mostrarInfo(" + (restaurantes[contador][20] + 1) + "); abrirFicha(" + contador + ", " + restaurantes[contador][3] + ");'><b>" + html_entity_decode(restaurantes[contador][2]) + "</b></a></div>" +
			"<div class='restaurante'>" +
			"<div class='logoRest'>" + logo + "</div>" +
			"<div class='direccion'>" + html_entity_decode(restaurantes[contador][4]) + " - " +  html_entity_decode(restaurantes[contador][6]) +
			"<br>Tlf: " + restaurantes[contador][8] +
			"<div class='comentariosValoracion'>" +
				"<div class='comentarios'><a href='" + ruta +"restaurante/" + restaurantes[contador][0] + "/" + toUrl(restaurantes[contador][2]) + "' title='Ver comentarios'>" + restaurantes[contador][21] + "</a></div>" +
				"<div class='valoracion'>";
				if (restaurantes[contador][22] == 0)
					campo1 += "SIN VALORACION";
				else {
					for (j = 1; j <= 5; j++) {
    					if ((restaurantes[contador][22] - (j - 1) > 0.25) && (restaurantes[contador][22] - (j - 1) < 0.75))
    						var aux = "3";
    					else if (restaurantes[contador][22] >= j)
    						var aux = "2";
    					else
    						var aux = "1";
    					campo1 += "<img src='http://www.menus.es/images/icons/valoracion_" + aux + ".png'>";
    				}
				}
				if (restaurantes[contador][19] >= 1000)
					var dist = (Math.round((restaurantes[contador][19]/1000)*100)/100) + " km";
				else
					var dist = restaurantes[contador][19] + " metros";
				campo1 += "</div></div>" +
					"<div class='distancia'>a " + dist;
				if (restaurantes[contador][23] == 1)
					campo1 += " <img src='images/icons/cupon-descuento.png' title='Dispone de Cupón descuento' alt='Dispone de Cupón descuento'>";
				campo1 += "</div>" + "</div>" + "</div>";
				
		if (restaurantes[contador][11] != '')
			var campo2 = "<div class='minimenu'><img src='images/icons/menu-dia.png' title='Dispone de Menú del Día' /><br>" + restaurantes[contador][12] + " €</div>";
		else
			var campo2 = "<div class='minimenu'>&nbsp;</div>";
		if (restaurantes[contador][13] != '')
			campo2 += "<div class='minimenu' style='margin-top: -10px;'><img src='images/icons/menu-degustacion.png' title='Dispone de Menú Degustación' style='vertical-align: -2px;' /><br>" + restaurantes[contador][14] + " €</div>";
		else
			campo2 += "<div class='minimenu'>&nbsp;</div>";
		if (restaurantes[contador][15] != '')
			campo2 += "<div class='minimenu'><img src='images/icons/comida-rapida.png' title='Dispone de Menú Comida Rápida' /><br>" + restaurantes[contador][16] + " €</div>";
		else
			campo2 += "<div class='minimenu'>&nbsp;</div>";
		if (restaurantes[contador][24] != '')
			campo2 += "<div class='minimenu'><img src='images/icons/sugerencias.png' title='Sugerencias' /></div>";
		else
			campo2 += "<div class='minimenu'>&nbsp;</div>";
		
		var campo3 = "<a href='" + ruta + "restaurante/" + restaurantes[contador][0] + "/" + toUrl(restaurantes[contador][2]) + "' title='Ver ficha'><img src='http://www.menus.es/images/icons/mas.png' style='border: 0px;'></a>"

		
		var row = table.insertRow(i);
		row.id = "tr_" + i;
		
		var col1 = row.insertCell(0);
		var col2 = row.insertCell(1);
		var col3 = row.insertCell(2);
		
		col1.innerHTML = campo1;
		col2.innerHTML = campo2;
		col3.innerHTML = campo3;
		
		col1.style.width = '300px';
		col2.style.width = '270px';
		
		contador++;
		i++;
	}
	if (restaurantes.length == 0) {
		var row = table.insertRow(1);
		var col = row.insertCell(0);
		col.innerHTML = "No se ha encontrado ningún restaurante.";
		col.colspan = 3;
		col.style.fontWeight = 'normal';
		col.style.border = '0px';
	}
	else {
		if (pag > 3)
			document.getElementById('pag_menos').style.display = '';
		else
			document.getElementById('pag_menos').style.display = 'none';
		if (pag > 1)
			document.getElementById('pag_prev').style.display = '';
		else
			document.getElementById('pag_prev').style.display = 'none';
		for (p = 1; p <= total; p++) {
			if (p == pag) {
				document.getElementById('pag_' + p).className = 'pagina-actual';
				if (total > 1)
					document.getElementById('pag_' + p).style.display = '';
			}
			else {
				document.getElementById('pag_' + p).className = 'pagina-enlace';
				if ((p > (pag - 3)) && (p < (pag + 3)))
					document.getElementById('pag_' + p).style.display = '';
				else
					document.getElementById('pag_' + p).style.display = 'none';
			}
		}
	
		if (pag < total)
			document.getElementById('pag_next').style.display = '';
		else
			document.getElementById('pag_next').style.display = 'none';
		if (pag < (total - 2))
			document.getElementById('pag_mas').style.display = '';
		else
			document.getElementById('pag_mas').style.display = 'none';
		if (noScroll == 1)
			noScroll = 0;
		else
			window.scrollTo(0, 1080);
	}
}

function mostrarMes(id, ruta) {
	if (document.getElementById('div_' + id).style.display == 'none') {
		document.getElementById('img_' + id).src = ruta + 'images/blog_down.png';
		document.getElementById('div_' + id).style.display = 'block';
	}
	else {
		document.getElementById('img_' + id).src = ruta + 'images/blog_right.png';
		document.getElementById('div_' + id).style.display = 'none';
	}
}

function mostrarLogin() {
	if (document.getElementById('div_login').style.display == 'none') {
		jQuery('#div_login').fadeIn(400);
		if (typeof (document.forms['formLogin'].user) != 'undefined')
			document.forms['formLogin'].user.focus();
	}
	else {
		jQuery('#div_login').fadeOut(400);
	}
}

function desplazar(fin) {
	salto = -30;
	if (BrowserDetect.browser == "Firefox")
		salto = -15;
	else if (BrowserDetect.browser == "Explorer")
		salto = -50;
	if (getScrollY() > fin)
		window.scrollBy(0, salto);
	else
		clearInterval(irFicha);
}

function getScrollY() {
	var scrOfX = 0, scrOfY = 0;
	if( typeof( window.pageYOffset ) == 'number' ) {
		//Netscape compliant
		scrOfY = window.pageYOffset;
	} else if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) ) {
		//DOM compliant
		scrOfY = document.body.scrollTop;
	} else if( document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) ) {
		//IE6 standards compliant mode
		scrOfY = document.documentElement.scrollTop;
	}
	return scrOfY;
}

function html_entity_decode (string, quote_style) {
    // Convert all HTML entities to their applicable characters  
    // 
    // version: 1008.1718
    // discuss at: http://phpjs.org/functions/html_entity_decode
    // +   original by: john (http://www.jd-tech.net)
    // +      input by: ger
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +    revised by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   bugfixed by: Onno Marsman
    // +   improved by: marc andreu
    // +    revised by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +      input by: Ratheous
    // +   bugfixed by: Brett Zamir (http://brett-zamir.me)
    // +      input by: Nick Kolosov (http://sammy.ru)
    // +   bugfixed by: Fox
    // -    depends on: get_html_translation_table
    // *     example 1: html_entity_decode('Kevin &amp; van Zonneveld');
    // *     returns 1: 'Kevin & van Zonneveld'
    // *     example 2: html_entity_decode('&amp;lt;');
    // *     returns 2: '&lt;'
    var hash_map = {}, symbol = '', tmp_str = '', entity = '';
    tmp_str = string.toString();
    
    if (false === (hash_map = this.get_html_translation_table('HTML_ENTITIES', quote_style))) {
        return false;
    }
 
    // fix &amp; problem
    // http://phpjs.org/functions/get_html_translation_table:416#comment_97660
    delete(hash_map['&']);
    hash_map['&'] = '&amp;';
 
    for (symbol in hash_map) {
        entity = hash_map[symbol];
        tmp_str = tmp_str.split(entity).join(symbol);
    }
    tmp_str = tmp_str.split('&#039;').join("'");
    //tmp_str = tmp_srt.replace('&amp;ntilde;', 'ñ');
    
    return tmp_str;
}

function get_html_translation_table (table, quote_style) {
    // Returns the internal translation table used by htmlspecialchars and htmlentities  
    // 
    // version: 1008.1718
    // discuss at: http://phpjs.org/functions/get_html_translation_table
    // +   original by: Philip Peterson
    // +    revised by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   bugfixed by: noname
    // +   bugfixed by: Alex
    // +   bugfixed by: Marco
    // +   bugfixed by: madipta
    // +   improved by: KELAN
    // +   improved by: Brett Zamir (http://brett-zamir.me)
    // +   bugfixed by: Brett Zamir (http://brett-zamir.me)
    // +      input by: Frank Forte
    // +   bugfixed by: T.Wild
    // +      input by: Ratheous
    // %          note: It has been decided that we're not going to add global
    // %          note: dependencies to php.js, meaning the constants are not
    // %          note: real constants, but strings instead. Integers are also supported if someone
    // %          note: chooses to create the constants themselves.
    // *     example 1: get_html_translation_table('HTML_SPECIALCHARS');
    // *     returns 1: {'"': '&quot;', '&': '&amp;', '<': '&lt;', '>': '&gt;'}
    
    var entities = {}, hash_map = {}, decimal = 0, symbol = '';
    var constMappingTable = {}, constMappingQuoteStyle = {};
    var useTable = {}, useQuoteStyle = {};
    
    // Translate arguments
    constMappingTable[0]      = 'HTML_SPECIALCHARS';
    constMappingTable[1]      = 'HTML_ENTITIES';
    constMappingQuoteStyle[0] = 'ENT_NOQUOTES';
    constMappingQuoteStyle[2] = 'ENT_COMPAT';
    constMappingQuoteStyle[3] = 'ENT_QUOTES';
 
    useTable       = !isNaN(table) ? constMappingTable[table] : table ? table.toUpperCase() : 'HTML_SPECIALCHARS';
    useQuoteStyle = !isNaN(quote_style) ? constMappingQuoteStyle[quote_style] : quote_style ? quote_style.toUpperCase() : 'ENT_COMPAT';
 
    if (useTable !== 'HTML_SPECIALCHARS' && useTable !== 'HTML_ENTITIES') {
        throw new Error("Table: "+useTable+' not supported');
        // return false;
    }
 
    entities['38'] = '&amp;';
    if (useTable === 'HTML_ENTITIES') {
        entities['160'] = '&nbsp;';
        entities['161'] = '&iexcl;';
        entities['162'] = '&cent;';
        entities['163'] = '&pound;';
        entities['164'] = '&curren;';
        entities['165'] = '&yen;';
        entities['166'] = '&brvbar;';
        entities['167'] = '&sect;';
        entities['168'] = '&uml;';
        entities['169'] = '&copy;';
        entities['170'] = '&ordf;';
        entities['171'] = '&laquo;';
        entities['172'] = '&not;';
        entities['173'] = '&shy;';
        entities['174'] = '&reg;';
        entities['175'] = '&macr;';
        entities['176'] = '&deg;';
        entities['177'] = '&plusmn;';
        entities['178'] = '&sup2;';
        entities['179'] = '&sup3;';
        entities['180'] = '&acute;';
        entities['181'] = '&micro;';
        entities['182'] = '&para;';
        entities['183'] = '&middot;';
        entities['184'] = '&cedil;';
        entities['185'] = '&sup1;';
        entities['186'] = '&ordm;';
        entities['187'] = '&raquo;';
        entities['188'] = '&frac14;';
        entities['189'] = '&frac12;';
        entities['190'] = '&frac34;';
        entities['191'] = '&iquest;';
        entities['192'] = '&Agrave;';
        entities['193'] = '&Aacute;';
        entities['194'] = '&Acirc;';
        entities['195'] = '&Atilde;';
        entities['196'] = '&Auml;';
        entities['197'] = '&Aring;';
        entities['198'] = '&AElig;';
        entities['199'] = '&Ccedil;';
        entities['200'] = '&Egrave;';
        entities['201'] = '&Eacute;';
        entities['202'] = '&Ecirc;';
        entities['203'] = '&Euml;';
        entities['204'] = '&Igrave;';
        entities['205'] = '&Iacute;';
        entities['206'] = '&Icirc;';
        entities['207'] = '&Iuml;';
        entities['208'] = '&ETH;';
        entities['209'] = '&Ntilde;';
        entities['210'] = '&Ograve;';
        entities['211'] = '&Oacute;';
        entities['212'] = '&Ocirc;';
        entities['213'] = '&Otilde;';
        entities['214'] = '&Ouml;';
        entities['215'] = '&times;';
        entities['216'] = '&Oslash;';
        entities['217'] = '&Ugrave;';
        entities['218'] = '&Uacute;';
        entities['219'] = '&Ucirc;';
        entities['220'] = '&Uuml;';
        entities['221'] = '&Yacute;';
        entities['222'] = '&THORN;';
        entities['223'] = '&szlig;';
        entities['224'] = '&agrave;';
        entities['225'] = '&aacute;';
        entities['226'] = '&acirc;';
        entities['227'] = '&atilde;';
        entities['228'] = '&auml;';
        entities['229'] = '&aring;';
        entities['230'] = '&aelig;';
        entities['231'] = '&ccedil;';
        entities['232'] = '&egrave;';
        entities['233'] = '&eacute;';
        entities['234'] = '&ecirc;';
        entities['235'] = '&euml;';
        entities['236'] = '&igrave;';
        entities['237'] = '&iacute;';
        entities['238'] = '&icirc;';
        entities['239'] = '&iuml;';
        entities['240'] = '&eth;';
        entities['241'] = '&ntilde;';
        entities['242'] = '&ograve;';
        entities['243'] = '&oacute;';
        entities['244'] = '&ocirc;';
        entities['245'] = '&otilde;';
        entities['246'] = '&ouml;';
        entities['247'] = '&divide;';
        entities['248'] = '&oslash;';
        entities['249'] = '&ugrave;';
        entities['250'] = '&uacute;';
        entities['251'] = '&ucirc;';
        entities['252'] = '&uuml;';
        entities['253'] = '&yacute;';
        entities['254'] = '&thorn;';
        entities['255'] = '&yuml;';
    }
 
    if (useQuoteStyle !== 'ENT_NOQUOTES') {
        entities['34'] = '&quot;';
    }
    if (useQuoteStyle === 'ENT_QUOTES') {
        entities['39'] = '&#039;';
    }
    entities['60'] = '&lt;';
    entities['62'] = '&gt;';
 
 
    // ascii decimals to real symbols
    for (decimal in entities) {
        symbol = String.fromCharCode(decimal);
        hash_map[symbol] = entities[decimal];
    }
    
    return hash_map;
}

function mostrarTab(index, marker) {
	document.getElementById('tab1_' + marker).style.display = 'none';
	document.getElementById('tab2_' + marker).style.display = 'none';
	document.getElementById('tab3_' + marker).style.display = 'none';
	document.getElementById('tab' + index + '_' + marker).style.display = '';
	for (var i = 1; i <= 3; i++) {
		if (i == index) {
			document.getElementById('header' + i + '_' + marker).className = 'header2';
		}
		else {
			document.getElementById('header' + i + '_' + marker).className = 'header';
		}
	}
}

function mostrarInfo (i) {
	if (infoPos)
		infoPos.close();
	for(var j = 0; j < infoWindows.length; j++) {
		if (infoWindows[j])
			infoWindows[j].close();
	}
	infoWindows[(i - 1)].open(map, markers[(i - 1)]);
	/*if (restaurantes[(i - 1)]) {
		//map.panTo(new google.maps.LatLng(restaurantes[(i - 1)][17], restaurantes[(i - 1)][18]));
	}*/
	
}

function overTR (tr) {
	tr.style.backgroundColor = '#5a6363';
	tr.style.color = '#ffffff';
}

function outTR (tr) {
	tr.style.backgroundColor = '#262c2c';
	tr.style.color = '#ffffff';
}
function overTab (tab) {
	if (tab.parentNode.className.substr(5) != 'activa') {
		tab.style.color = '#444444';
		tab.parentNode.className = 'over';
		//tab.getElementsByTagName('div')[1].style.paddingTop = '4px';
		tab.getElementsByTagName('img')[0].src = ruta + 'images/tab-izq.png';
		tab.getElementsByTagName('img')[1].src = ruta + 'images/tab-der.png';
	}
}
function outTab (tab) {
	if (tab.parentNode.className.substr(5) != 'activa') {
		tab.style.color = '#59412b';
		tab.parentNode.className = 'pest';
		//tab.getElementsByTagName('div')[1].style.paddingTop = '7px';
		tab.getElementsByTagName('img')[0].src = ruta + 'images/tab-izq2.png';
		tab.getElementsByTagName('img')[1].src = ruta + 'images/tab-der2.png';
	}
}
function overBusquedaRapida(elem) {
	elem.getElementsByTagName("div")[0].style.background="#515342";
}
function outBusquedaRapida(elem) {
	elem.getElementsByTagName("div")[0].style.background="#808661";
}
function overIMG (img, enlace) {
	img.style.opacity = '0.8';
}
function outIMG (img, enlace) {
	img.style.opacity = '1';
}
function ocultarBloque(bloque, img, ruta) {
	$('#' + bloque + '_div').slideToggle(400);
	var str = img.src;
	if (ruta == undefined)
		ruta = "";
	if (str.substr((str.length - 9), 9) != 'menos.gif') {
		$('#table_' + bloque).fadeTo(400, 1);
		img.src = ruta + 'images/menos.gif';
	}
	else {
		$('#table_' + bloque).fadeTo(400, 0.6);
		img.src = ruta + 'images/mas.gif';
	}
}
function ocultarLista(img) {
	$('#lista_div').slideToggle(400);
	var str = img.src;
	if (str.substr((str.length - 9), 9) != 'menos.gif') {
		$('#table_lista').fadeTo(400, 1);
		img.src = 'images/menos.gif';
	}
	else {
		$('#table_lista').fadeTo(400, 0.6);
		img.src = 'images/mas.gif';
	}
}
function ocultarFicha(img) {
	$('#ficha_div').slideToggle(400);
	var str = img.src;
	if (str.substr((str.length - 9), 9) != 'menos.gif') {
		$('#table_ficha').fadeTo(400, 1);
		img.src = 'images/menos.gif';
	}
	else {
		$('#table_ficha').fadeTo(400, 0.6);
		img.src = 'images/mas.gif';
	}
}
function ocultarBuscar(img) {
	$('#buscar_div').slideToggle(400);
	var str = img.src;
	if (str.substr((str.length - 9), 9) != 'menos.gif') {
		$('#table_buscar').fadeTo(400, 1);
		img.src = 'images/menos.gif';
	}
	else {
		$('#table_buscar').fadeTo(400, 0.6);
		img.src = 'images/mas.gif';
	}
}
function abrirFicha(i, mostrarImagen) {
	if (restaurantes) {
		jQuery('#ficha').fadeIn(400);
		var ficha =
			"<div class='tabbed_area'>" +
			"<div class='nombreRest'><a href='restaurante/" + restaurantes[i][0] + "/" + toUrl(html_entity_decode(restaurantes[i][2])) + "' title='Ver ficha completa'>" + html_entity_decode(restaurantes[i][2]) + "</a><span style='float: right; border: 1px solid #ffffff; margin: 5px 3px;'><a href='javascript:cerrarFicha();' style='font: 12px Verdana; color: #ffffff; padding: 2px; text-decoration: none;'>X</a></span></div>" +
			'<img src=\"images/ficha2_top.png\" width=\"342\" class=\"borde\" />' +
			'<div id=\"content\">' + 
			'<img src=\"images/ficha3_top.png\" width=\"332\" class=\"borde\" />' +
	        '<div id=\"content_1\" class=\"content\">' +
	        "<center>";
		if (mostrarImagen != 0) {
			ficha = ficha +
				'<img src=\"images/restaurantes/' + restaurantes[i][0] + '/logo.jpg\" class=\"logo\" /></center><br>';
		}
		ficha = ficha +
				'</center><span style=\"font: bold 16px Arial; color: #718681;\">Dirección: </span>' + html_entity_decode(restaurantes[i][4]) + '<br>' +
				'<span style=\"font: bold 16px Arial; color: #718681;\"> Localidad: </span>' + html_entity_decode(restaurantes[i][6]) + ' (' + html_entity_decode(restaurantes[i][7]) + ')<br>' +
				'<img src=\"images/icons/tel.png\" style=\"height: 28px; vertical-align: -4px;\"><span style=\"padding-left: 10px; font: bold 18px Arial;\">' + html_entity_decode(restaurantes[i][8]) + '</span><br>';
		if (restaurantes[i][9] != '') {
			//ficha = ficha +	'<span style=\"font: bold 16px Arial; color: #718681;\">Página Web: </span><a href="';
			ficha = ficha + '<a href="';
			if (restaurantes[i][9].substr(0,7) != 'http://')
				ficha = ficha + 'http://';
			ficha = ficha +
				restaurantes[i][9] + '" target="_blank">'; 
			if (restaurantes[i][9].substr(0,7) != 'http://')
				ficha = ficha + 'http://';
			ficha = ficha +
				restaurantes[i][9] + '</a><br>';
		}
		/*if (restaurantes[i][10] != '')
			ficha = ficha + '<b> Email: </b>' + restaurantes[i][10] + '<br>';*/
		var num1 = new Number(restaurantes[i][12]);
		var num2 = new Number(restaurantes[i][14]);
		var num3 = new Number(restaurantes[i][16]);
		restaurantes[i][11] = restaurantes[i][11].replace("A escoger entre:", "<div style='color: #b3ae86; font: bold italic 14px Arial;'>A escoger entre:</div>");
		restaurantes[i][13] = restaurantes[i][13].replace("A escoger entre:", "<div style='color: #b3ae86; font: bold italic 14px Arial;'>A escoger entre:</div>");
		restaurantes[i][15] = restaurantes[i][15].replace("A escoger entre:", "<div style='color: #b3ae86; font: bold italic 14px Arial;'>A escoger entre:</div>");
		ficha = ficha +
			'</center><div style=\"text-align: right;\"><a href=\"restaurante/' + restaurantes[i][0] + '/' + toUrl(html_entity_decode(restaurantes[i][2])) + '\" title=\"Ver ficha completa\"><img src=\"images/icons/mas-info.png\" style=\"border: 0px; margin-top: 10px; margin-bottom: -20px;\" alt=\"Más información\"></a></div>' +
			'</div><div id=\"content_2\" class=\"content\">' +  
				'<div style=\"text-align: center;\">' + html_entity_decode(restaurantes[i][11]) + '<br><center style="font-weight: normal; text-decoration: underline;">Precio del menú: <b>' + num1.toFixed(2) + ' €</b></center>' + '<br><img src=\"images/icons/pizarra-footer.png\"></div>' +
			'</div><div id=\"content_3\" class=\"content\">' +  
				'<div style=\"text-align: center;\">' + html_entity_decode(restaurantes[i][13]) + '<br><center style="font-weight: normal; text-decoration: underline;">Precio del menú: <b>' + num2.toFixed(2) + ' €</b></center>' + '<br><img src=\"images/icons/pizarra-footer.png\"></div>' +
			'</div><div id=\"content_4\" class=\"content\">' +  
				'<div style=\"text-align: center;\">' + html_entity_decode(restaurantes[i][15]) + '<br><center style="font-weight: normal; text-decoration: underline;">Precio del menú: <b>' + num3.toFixed(2) + ' €</b></center>' + '<br><img src=\"images/icons/pizarra-footer.png\"></div>' +
			'</div>' +
			'<img src=\"images/ficha3_bottom.png\" width=\"332\" class=\"borde\" />' +
			'</div>' +
			'<img src=\"images/ficha2_bottom.png\" width=\"342\" class=\"borde\" />' +
			'</div>';
		document.getElementById('ficha_datos').innerHTML = ficha;
		map.setCenter(new google.maps.LatLng(restaurantes[i][17], restaurantes[i][18]));
		irFicha = setInterval("desplazar(650);", 1);
	}
}
function cerrarFicha() {
	jQuery('#ficha').fadeOut(400);
}
function verFicha(i) {
	location.href = 'restaurante/'+ restaurantes[i][0] + '/' + restaurantes[i][2];
}
function mostrarMapa() {
	if (document.getElementById('mapaRest2').style.zIndex == -1) {
		document.getElementById('mapaRest2').style.zIndex = 5;
		document.getElementById('mapaRest').style.zIndex = 5;
		document.getElementById('mapaFondo').style.display = "none";
		jQuery('#mapaRest').slideUp(0);
		jQuery('#mapaRest').slideDown(400);
	}
	else
		jQuery('#mapaRest').slideToggle(400);
}
function irAPagina(pag) {
	document.forms['formFiltros'].action = "?pag=" + pag;
	document.forms['formFiltros'].submit();
}

function cargarRestaurantes(map) {
	contador = 0;
	var fluster = new Fluster2(map);
	while (contador < restaurantes.length) {
		var info = "<div class='infoWindow'>"
			+ "" + html_entity_decode(restaurantes[contador][2]) + "<br><br>"
			+ "<a href='restaurante/" + restaurantes[contador][0] + "/" + toUrl(html_entity_decode(restaurantes[contador][2])) + "'><b>Ver ficha completa</b></a>"
		+ "</div>";

		if (restaurantes[contador][2].search(/starbucks/i) != -1)
			imagen = "images/icons/starbucks.gif";
		else if (restaurantes[contador][2].search(/pizzam&oacute;vil/i) != -1)
			imagen = "images/icons/pizzamovil.png";
		else if (restaurantes[contador][2].search(/telepizza/i) != -1)
			imagen = "images/icons/telepizza.png";
		else if (restaurantes[contador][2].search(/mcdonald/i) != -1)
			imagen = "images/icons/mcdonalds.png";
		else if (restaurantes[contador][2].search(/burger king/i) != -1)
			imagen = "images/icons/burger-king.png";
		else if (restaurantes[contador][2].search(/foster/i) != -1)
			imagen = "images/icons/fosters-hollywood.png";
		else if (restaurantes[contador][2].search(/domino/i) != -1)
			imagen = "images/icons/dominos-pizza.png";
		else if (restaurantes[contador][2].search(/pans/i) != -1)
			imagen = "images/icons/pans-and-company.png";
		else if (restaurantes[contador][2].search(/rodilla/i) != -1)
			imagen = "images/icons/rodilla.png";
		else if (restaurantes[contador][2].search(/vips/i) != -1)
			imagen = "images/icons/grupo-vips.png";
		else if (restaurantes[contador][2].search(/pizza hut/i) != -1)
			imagen = "images/icons/pizza-hut.png";
		else
			imagen = "images/icons/map-point.png";
		
		var marker = new google.maps.Marker({
			position: new google.maps.LatLng(restaurantes[contador][17], restaurantes[contador][18]),
			icon: new google.maps.MarkerImage(imagen, new google.maps.Size(30, 27))
		});
		var infoWindow = new google.maps.InfoWindow({
			content: info
		});
		// Add the marker to the Fluster
		fluster.addMarker(marker, infoWindow, contador);
        
		contador++;
	}
	fluster.initialize();
}

/*function makeMarker(options){
	var pushPin = new google.maps.Marker({map:map});
	pushPin.setOptions(options);
	google.maps.event.addListener(pushPin, 'click', function(){
		infoWindow.setOptions(options);
		infoWindow.open(map, pushPin);
	});
	markers.push(pushPin);
	return pushPin;
}*/

function cargarDatos(tipo, destacado, buscarNombre, buscarPlato, categoria, precio) {
	//alert(tipo + " - " + destacado);
	if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
		xmlhttp=new XMLHttpRequest();
	}
	else {// code for IE6, IE5
		xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
	}
	xmlhttp.onreadystatechange=function() {
		if (xmlhttp.readyState==4 && xmlhttp.status==200) {
			restaurantes = eval(xmlhttp.responseText);

	    	noScroll = 1;
			verPagina(1);
			cargarRestaurantes(map);
			infoPos.open(map, markerPos);
			document.getElementById('paginacion').style.display = '';
			document.getElementById('total').innerHTML = ' (' + restaurantes.length + ')';
		}
	}
	if ((tipo != 0) && (destacado != 0))
		vars = "?tipo=" + tipo + "&destacado=" + destacado + "&buscarNombre=" + buscarNombre + "&buscarPlato=" + buscarPlato + "&categoria=" + categoria + "&precio=" + precio;
	else if (tipo != 0)
		vars = "?tipo=" + tipo + "&buscarNombre=" + buscarNombre + "&buscarPlato=" + buscarPlato + "&categoria=" + categoria + "&precio=" + precio;
	else if (destacado != 0)
		vars = "?destacado=" + destacado + "&buscarNombre=" + buscarNombre + "&buscarPlato=" + buscarPlato + "&categoria=" + categoria + "&precio=" + precio;
	else
		vars = "?buscarNombre=" + buscarNombre + "&buscarPlato=" + buscarPlato + "&categoria=" + categoria + "&precio=" + precio;
	xmlhttp.open("GET","includes/cargarDatos.php" + vars,true);
	xmlhttp.send();
}

val = 0;
cat = [0, 0, 0, 0, 0];
function overVal(id) {
	for (aux = 1; aux <= id; aux++)
		document.getElementById('val-' + aux).src = ruta + "images/icons/media-on.png"; 
	for (aux = id + 1; aux <= 5; aux++)
		document.getElementById('val-' + aux).src = ruta + "images/icons/media-off.png"; 
}
function outVal(id) {
	for (aux = 1; aux <= 5; aux++) {
		if (val < aux)
			document.getElementById('val-' + aux).src = ruta + "images/icons/media-off.png";
		else
			document.getElementById('val-' + aux).src = ruta + "images/icons/media-on.png";
	}
}
function clickVal(id) {
	val = id;
	for (aux = 1; aux <= 5; aux++)
		if (val < aux)
			document.getElementById('val-' + aux).src = ruta + "images/icons/media-off.png"; 
}

function overCat(cid, id) {
	for (aux = 1; aux <= id; aux++)
		document.getElementById('cat' + cid + '-' + aux).src = ruta + "images/icons/cat2-on.png"; 
	for (aux = id + 1; aux <= 5; aux++)
		document.getElementById('cat' + cid + '-' + aux).src = ruta + "images/icons/cat2-off.png"; 
}
function outCat(cid, id) {
	for (aux = 1; aux <= 5; aux++) {
		if (cat[cid] < aux)
			document.getElementById('cat' + cid + '-' + aux).src = ruta + "images/icons/cat2-off.png";
		else
			document.getElementById('cat' + cid + '-' + aux).src = ruta + "images/icons/cat2-on.png";
	}
}
function clickCat(cid, id) {
	cat[cid] = id;
	for (aux = 1; aux <= 5; aux++)
		if (cat[cid] < aux)
			document.getElementById('cat' + cid + '-' + aux).src = ruta + "images/icons/cat2-off.png"; 
}
function trim(texto) {
	return texto.replace(/^\s+/g,'').replace(/\s+$/g,'');
}
function enviarComentario() {
	if (trim(document.forms['formComentario'].comentario.value) == "") {
		alert("Debe escribir un comentario para poder enviar su valoración.");
		document.forms['formComentario'].comentario.focus();
	}
	else {
		document.forms['formComentario'].valoracion.value = val;
		document.forms['formComentario'].servicio.value = cat[1];
		document.forms['formComentario'].presentacion.value = cat[2];
		document.forms['formComentario'].calidad.value = cat[3];
		document.forms['formComentario'].accesos.value = cat[4];
		document.forms['formComentario'].submit();
	}
}
function cambiarLatLng(lat, lng) {
	document.forms['formRestaurante'].lat.value = lat;
	document.forms['formRestaurante'].lng.value = lng;
	var newPoint = new google.maps.LatLng(lat, lng);
    markers[0].setPosition(newPoint);
}
function overCupon(e, ruta) {
	e.getElementsByTagName('img')[2].src = ruta + "images/cupones/lo_llevo_over.png";
}
function outCupon(e, ruta) {
	e.getElementsByTagName('img')[2].src = ruta + "images/cupones/lo_llevo.png";
}
function verCupon(ruta, nombre) {
	var id = document.forms['formCadena'].local.options[document.forms['formCadena'].local.selectedIndex].value;
	window.parent.location = ruta + "restaurante/" + id + "/" + nombre;
}
function buscarCadena(provincia, nombre) {
	document.getElementById('cadena').style.display = '';
	document.getElementById('cadena').getElementsByTagName('iframe')[0].src = "verCadena.php?provincia=" + provincia + "&nombre=" + nombre;
}

function descargarCupon(id, registrado) {
	document.getElementById('cupon').style.display = '';
	if (registrado == 1)
		document.getElementById('cupon').getElementsByTagName('iframe')[0].src = ruta + "includes/enviarCupon.php?id=" + id;
	else
		document.getElementById('cupon').getElementsByTagName('iframe')[0].src = ruta + "includes/descargarCupon.php?id=" + id;
}

/** Buscador lista restaurantes **/
function lista_buscar() {
	form = document.forms['formFiltros'];
	if (form.nombre.value == 'Nombre del restaurante')
		form.nombre.value = '';
	if (form.calle.value == 'Calle')
		form.calle.value = '';
	if (form.localidad.value == 'Localidad')
		form.localidad.value = '';
	if (form.provincia.value == 'Departamento')
		form.provincia.value = '';
	if (form.plato.value == 'Plato')
		form.plato.value = '';
	form.submit();
}
function buscar_focus(campo) {
	campo.className='activo';
	if ((campo.name == 'nombre') && (campo.value == 'Nombre del restaurante'))
		campo.value = '';
	if ((campo.name == 'calle') && (campo.value == 'Calle'))
		campo.value = '';
	if ((campo.name == 'localidad') && (campo.value == 'Localidad'))
		campo.value = '';
	if ((campo.name == 'provincia') && (campo.value == 'Departamento'))
		campo.value = '';
	if ((campo.name == 'plato') && (campo.value == 'Plato'))
		campo.value = '';
}
function buscar_blur(campo) {
	campo.className='inactivo';
	if ((campo.name == 'nombre') && (campo.value == ''))
		campo.value = 'Nombre del restaurante';
	else if ((campo.name == 'calle') && (campo.value == ''))
		campo.value = 'Calle';
	else if ((campo.name == 'localidad') && (campo.value == ''))
		campo.value = 'Localidad';
	else if ((campo.name == 'provincia') && (campo.value == ''))
		campo.value = 'Departamento';
	else if ((campo.name == 'plato') && (campo.value == ''))
		campo.value = 'Plato';
	else
		campo.className = 'activo';
}
function buscar_over(campo) {
	if (campo.name == 'buscar')
		campo.src = 'images/buscador_buscar_over.png';
}

function buscar_out(campo) {
	if (campo.name == 'buscar')
		campo.src = 'images/buscador_buscar.png';
}

function over_ir(elem) {
	elem.src = 'images/buscador_ficha_over.png';
}
function out_ir(elem) {
	elem.src = 'images/buscador_ficha.png';
}

function resetearPosicion() {
	delete latitud;
	delete longitud;
	sacarPos();
	/*var form = document.forms["formBuscarMapa"];
	form.buscarMapaCalle.value = "";
	form.buscarMapaLocalidad.value = "";
	form.submit();*/
}

function enviarOverlay() {
	form = document.forms["formSuscripcion"];
	if ((form.email.value == "") || (form.email.value == "E-MAIL")) {
		alert("Debe introducir una dirección de email.");
		form.email.value = "";
		form.email.focus();
	}
	else if (!checkEmail(form.email.value)) {
		alert("Debe introducir una dirección de email válida.");
		form.email.focus();
	}
	else if (form.provincia.value == "") {
		alert("Debe seleccionar un departamento.");
		form.provincia.focus();
	}
	else {
		form.submit();
	}
	
}


