var progressbar;
var map;
var arrMarkers = new Array();
var num = 0;
var arrDireccionesMapa = new Array();

function loadMap() {
  if (GBrowserIsCompatible()) {
	  map = new GMap2(document.getElementById("map"));
	  //map.enableScrollWheelZoom();
		mostrarDirecciones();
  }
}

function mostrarDirecciones(){
		var progressbarOptions = {width: 150, loadstring: 'Cargando...'};								
		progressbar = new ProgressbarControl(map, progressbarOptions);								
		progressbar.start(arrDireccionesMapa.length);
    boundsBares = new GLatLngBounds();  

	  var redIcon1 = new GIcon(G_DEFAULT_ICON);
    redIcon1.image = "images/botella-ico.gif";
	  redIcon1.iconSize = new GSize(23, 23);  
	  redIcon1.shadow = "images/sombra.gif";
		redIcon1.shadowSize = new GSize(23, 23);    

		if(arrDireccionesMapa.length>0){
        var point;
        for(i=0;i<arrDireccionesMapa.length;i++){
          point = eval("new GLatLng " + arrDireccionesMapa[i].coordenadas +";");
          boundsBares.extend(point);						
          arrMarkers[arrMarkers.length] = new createMarker(point, redIcon1, arrDireccionesMapa[i].contenido);
        }
        // ESTO ES PARA QUE CENTRE EL MAPA TENIENDO EN CUENTA TODOS LOS PUNTOS          
        map.setCenter(boundsBares.getCenter());
        map.setZoom(map.getBoundsZoomLevel(boundsBares));
    }else{
	    //CENTRA EL MAPA EN ESPAÑA
	    map.setCenter(new google.maps.LatLng(40.212441,-5.009766), 5);
	  }
		var extLargeMapControl = new ExtLargeMapControl({type : "small"});
		map.addControl(extLargeMapControl);              
		map.addControl(new GMapTypeControl());

  	num = 0;
  	overlays(arrMarkers.length);
}

/*CARGO LOS MARKERS*/
function overlays(total){
		if(total>0){
			progressbar.updateLoader(1);
			map.addOverlay(arrMarkers[num]);
	   	num++
		}

    if(num<total){
    	setTimeout('overlays('+total+');', 50);
    }else{
    	progressbar.remove();
    }
}
/*CREA MARKER Y BURBUJA*/
function createMarker(point, icon, html){
      var mark = new GMarker(point, icon);
      if(html!=""){
          GEvent.addListener(mark, "click", function() {
				      mark.openExtInfoWindow(map, "simple_example_window", html, {beakOffset: 0}); 
          });
      }
      return mark;
}

function bar(id_bar, coordenadas, nombre, direccion, numero, habituales, productos, foto, lnkBar){
	this.id_bar = id_bar;
	this.coordenadas = coordenadas;
	this.contenido = document.getElementById('templateFicha').innerHTML;
	if(foto!=""){
		this.contenido = this.contenido.replace("@@foto@@","<img class=\"left\" src=\"uploads/bares/bar_" + id_bar + "_thumb." + foto + "\" title=\"foto del bar " + nombre + "\" />");
	}else{
		this.contenido = this.contenido.replace("@@foto@@","<img class=\"left\" src=\"images/default_bar.jpg\" title=\"\" />");
	}
	this.contenido = this.contenido.replace("@@nombre@@", nombre);
	this.contenido = this.contenido.replace("@@direccion@@", direccion);
	this.contenido = this.contenido.replace("@@numero@@", numero);
	this.contenido = this.contenido.replace("@@habituales@@", habituales);
	this.contenido = this.contenido.replace("@@productos@@", productos);
	this.contenido = this.contenido.replace("@@lnkBar@@",lnkBar);
}

function agregarLocal(){
	window.location.href = strURLSite + 'agregar_local.php';
}

// ******************* BUSQUEDA ***********************
function irAPagina(pagina,params){
	ajax_content_exe("resultado_busqueda_paginas.php?pagactual=" + pagina + "&" + params, "divPaginas", "mostrarMapaPaginado()");
}

function mostrarMapaPaginado(){
	if(document.getElementById('hidScriptMapa')!=null){
		for(i=0; i<arrMarkers.length; i++){
			map.removeOverlay(arrMarkers[i]);
		}
		arrMarkers = new Array();
		eval(document.getElementById('hidScriptMapa').value);
		mostrarDirecciones();
	}
}

function buscar(){
	var frm = document.anadir_bar;
	if(frm.txtBuscar.value != ""){
		window.location.href = strURLSite + "buscador/" + frm.txtBuscar.value + "/";
	}else{
		window.location.href = strURLSite + "buscador/_/tipo=2";
		//showAlert("Debe escribir un texto para buscar.");
	}
}

function buscarAvanzada(){
	var frm = document.busquedaAvanzada;
	if(document.anadir_bar.txtBuscar.value != ""){
		frm.action = "buscador/" + document.anadir_bar.txtBuscar.value + "/";
		frm.submit();
	}else{
		frm.action = "buscador/_/";
		frm.submit();
	}
}

function verBusquedaAvanzada(){
	if(document.getElementById('popup-hover-busqueda').style.display == ''){
		document.getElementById('popup-hover-busqueda').style.display = "none";
	}else{
		document.getElementById('popup-hover-busqueda').style.display = "";
	}
}

// ******************* AYUDA ********************
var idPreguntaActiva = 0;
function verRespuesta(idPregunta){
	if(idPreguntaActiva!=0){
		document.getElementById('lnkPregunta' + idPreguntaActiva).className = "";
		document.getElementById('divRespuesta' + idPreguntaActiva).style.display = "none";
	}
	idPreguntaActiva = idPregunta;
	document.getElementById('lnkPregunta' + idPreguntaActiva).className = "active";
	document.getElementById('divRespuesta' + idPreguntaActiva).style.display = "";
	//Cufon.refresh('a');
}
function cerrarRespuesta(){
	document.getElementById('divRespuesta' + idPreguntaActiva).style.display = "none";
}

// ******************* REGISTRO ************************
function registrar(){
	var frm = document.registro;
  var strError = "";
  var objCheck;

  objCheck = new check("registro");
  objCheck.checkEmail("email", "Email", 2, 100, false);
  objCheck.checkString("confirmarContrasena", "Confirmar Contraseña", 2, 50, false);
  objCheck.checkString("movil", "Teléfono Móvil", 2, 30, true);
  objCheck.checkString("apellidos1", "Apellidos", 2, 35, true);
  objCheck.checkString("apellidos2", "Apellidos", 2, 35, true);
  objCheck.checkString("contrasena", "Contraseña", 2, 35, false);
  objCheck.checkString("telFijo", "Teléfono Fijo", 2, 30, true);
  objCheck.checkString("nombre", "Nombre", 2, 35, true);
  objCheck.checkString("apodo", "Apodo", 2, 35, false);
  objCheck.checkDate("txtFechaNacimiento", "Fecha de Nacimiento", true);
  objCheck.checkString("numero", "Número", 0, 10, true);
  objCheck.checkString("provincia", "Provincia", 2, 50, true);
  objCheck.checkString("codigo", "Código postal", 2, 10, true);
  objCheck.checkString("dni", "DNI", 2, 20, true);
  objCheck.checkString("direccion", "Dirección", 2, 200, true);
  objCheck.checkString("restoDireccion", "Resto Dirección", 2, 100, true);
  objCheck.checkString("localidad", "Localidad", 2, 40, true);
  objCheck.checkString("txtpais", "País", 2, 35, true);
  strError = objCheck.toString();
  
  if(frm.contrasena.value!=frm.confirmarContrasena.value){
  	strError += "Las contraseñas no coinciden.\n";
  }
  if(!frm.chkCondiciones.checked){
  	strError += "Debe leer y aceptar las bases legales.";
  }
  
  if (strError == "") {
    frm.hidRegistro.value = 1;
    frm.submit ();
  } else {
    showAlert (strError.replace(/\n/g,'<br/>'));
  }
}

// ******************* PERFIL ************************
function guardarPerfil(){
	var frm = document.registro;
  var strError = "";
  var objCheck;

  objCheck = new check("registro");
  objCheck.checkEmail("email", "Email", 2, 100, false);
  objCheck.checkString("confirmarContrasena", "Confirmar Contraseña", 2, 50, false);
  objCheck.checkString("movil", "Teléfono Móvil", 2, 30, true);
  objCheck.checkString("apellidos1", "Apellidos", 2, 35, true);
  objCheck.checkString("apellidos2", "Apellidos", 2, 35, true);
  objCheck.checkString("contrasena", "Contraseña", 2, 35, false);
  objCheck.checkString("telFijo", "Teléfono Fijo", 2, 30, true);
  objCheck.checkString("nombre", "Nombre", 2, 35, true);
  objCheck.checkDate("txtFechaNacimiento", "Fecha de Nacimiento", true);
  objCheck.checkString("numero", "Número", 0, 10, true);
  objCheck.checkString("provincia", "Provincia", 2, 50, true);
  objCheck.checkString("codigo", "Código postal", 2, 10, true);
  objCheck.checkString("dni", "DNI", 2, 20, true);
  objCheck.checkString("direccion", "Dirección", 2, 200, true);
  objCheck.checkString("restoDireccion", "Resto Dirección", 2, 100, true);
  objCheck.checkString("localidad", "Localidad", 2, 40, true);
  objCheck.checkString("txtpais", "País", 2, 35, true);
  strError = objCheck.toString();
  
  if(frm.contrasena.value!=frm.confirmarContrasena.value){
  	strError += "Las contraseñas no coinciden.";
  }
  
  if (strError == "") {
    frm.hidModifica.value = 1;
    frm.submit ();
  } else {
    showAlert (strError.replace(/\n/g,'<br/>'));
  }
}

function updateFoto(id_reg, extension, bar){
	if(bar==1){
		$$('#imgAvatar')[0].update('<img src="uploads/bares/bar_'+id_reg+'_thumb.' + extension + '" align="avatar-usuario" />');
		document.getElementById('hidFoto').value = extension;		
	}else{
		$$('#imgAvatar')[0].update('<img src="uploads/usuarios/usuario_'+id_reg+'.' + extension + '" align="avatar-usuario" />');
		document.getElementById('hidFoto').value ='http://www.quierounaestrella.com/uploads/usuarios/usuario_'+id_reg+'.' + extension;
	}
	document.getElementById('hidSitioEG').value = 0;		
}

// ******************* CONTACTO ************************
function enviarMensaje(){
	var frm = document.enviarMensaje;
  var strError = "";
  var objCheck;

  objCheck = new check("enviarMensaje");
  objCheck.checkString("nombre", "Nombre", 2, 35, false);
  objCheck.checkString("apellidos1", "Apellidos", 2, 35, true);
  objCheck.checkString("apellidos2", "Apellidos", 2, 35, true);
  objCheck.checkEmail("email", "Email", 2, 100, false);
  objCheck.checkString("telefono", "Teléfono", 2, 30, true);
  objCheck.checkString("asunto", "Asunto", 2, 100, true);
  objCheck.checkString("texto", "texto", 2, 1000, false);
  strError = objCheck.toString();
  
  if (strError == "") {
    frm.hidEnviar.value = 1;
    frm.submit ();
  } else {
    showAlert (strError.replace(/\n/g,'<br/>'));
  }
}

// ****************** AGREGAR LOCAL ********************

function inicializaMapaAgregarLocal(){
	if(document.getElementById("hidCoordenadas").value!=""){
		point = eval("new GLatLng " + document.getElementById("hidCoordenadas").value +";");
		map.addOverlay(new GMarker(point));
		map.setCenter(point, 14);
	}
	GEvent.addListener(map, "click", function(marker, point){
			map.clearOverlays();
			if (marker) {
				map.removeOverlay(marker);
			}else{
				map.addOverlay(new GMarker(point));
				document.getElementById("hidCoordenadas").value	= point.toString();
			}
	}				
	);
}

function guardarLocal(){
	var frm = document.agregar_local;
  var strError = "";
  var objCheck;

  objCheck = new check("agregar_local");
  objCheck.checkEmail("email", "Email", 2, 100, true);
  objCheck.checkString("movil", "Teléfono Móvil", 2, 30, true);
  objCheck.checkString("telFijo", "Teléfono Fijo", 2, 30, true);
  objCheck.checkString("nombre", "Nombre", 2, 35, false);
  objCheck.checkString("direccion", "Dirección", 2, 200, false);
  objCheck.checkString("resto_direccion", "Resto Dirección", 2, 100, true);
  objCheck.checkString("numero", "Número", 0, 10, false);
  objCheck.checkString("codigo", "Código postal", 2, 10, true);
  objCheck.checkString("provincia", "Provincia", 2, 50, false);
  objCheck.checkString("localidad", "Localidad", 2, 40, false);
  objCheck.checkString("txtpais", "País", 2, 35, false);
  objCheck.checkString("hidCoordenadas", "Localización", 2, 50, false);
  strError = objCheck.toString();
  
  var bChecked = false;
  var arrChk = document.getElementsByName("chkProducto[]");
  if(!arrChk.length) bChecked = true;
  for(i=0;i<arrChk.length;i++){
  	if(arrChk[i].checked){
  		bChecked = true;
  		break;
  	}
  }
  if(!bChecked) strError += "Debe disponer al menos de un producto.\n";
  
  if (strError == "") {
    frm.hidEnviar.value = 1;
    frm.submit ();
  } else {
    showAlert (strError.replace(/\n/g,'<br/>'));
  }
}

function posicionar(){
	var frm = document.agregar_local;
	var direccion = frm.direccion.value + "," + frm.numero.value + "," + frm.codigo.value + "," + frm.provincia.value;
	showAddress(direccion);
}

function showAddress(address) {
  if(address!=""){
  	geocoder = new GClientGeocoder();
    if (geocoder) {
      geocoder.getLatLng(
        address,
        function(point) {
          if (!point) {
            alert("No se encontro la dirección " + address + " \nPor favor, ingrese una nueva dirección o busquela en el mapa.");
           	var pointAux = new GLatLng(40,-4);
            map.setCenter(pointAux,6);
          } else {
            map.setCenter(point, 15);
            var marker = new GMarker(point);
            map.addOverlay(marker);
            document.getElementById("hidCoordenadas").value = point.toString();	             							        	
          }
        }
      );
    }
	}
}

// ******************* FICHA BAR **********************
function soy_habitual(id_bar, id_usuario, habitual){
	simple_ajax("ajaxHabitual.php","GET","hidIdUsuario=" + id_usuario + "&hidIdBar=" + id_bar + "&habitual=" + habitual);
}

function irAPaginaFichaBar(pagina,params){
	ajax_content_exe("ficha_bar_fotos.php?pagactual=" + pagina + "&" + params, "divGaleria", "generarLightbox()");
}

function irAPaginaHabituales(pagina,params){
	ajax_content_exe("ficha_bar_habituales.php?pagactual=" + pagina + "&reducido=0&" + params, "divHabituales");
}
function irAPaginaComentarios(pagina,params){
	ajax_content_exe("ficha_bar_comentarios.php?pagactual=" + pagina + "&" + params, "divComentarios");
}
function mostrarHabitualesReducido(params){
	ajax_content_exe("ficha_bar_habituales.php?pagactual=0&reducido=1&" + params, "divHabituales");
}

function generarLightbox(){
	if(document.getElementById('hidScriptLB')!=null){
		eval(document.getElementById('hidScriptLB').value);
	}
}

function cambiarMes(mes,anio,id_bar){
	ajax_content_exe("calendario_eventos.php?mes=" + mes + "&anio=" + anio + "&id_bar=" + id_bar, "divCalendario");
}

function desplegarEvento(dia){
	document.getElementById('divEventos').innerHTML = document.getElementById('evDia'+dia).innerHTML;
	mostrar('divEventoGral');
}

function verFormEvento(){
	mostrar('divEventoAgregar');
}

function modificarLocal(id_bar){
	window.location.href = strURLSite + 'modificar_local.php?id=' + id_bar;
}

function agregarEvento(){
	var frm = document.agregar_eventos;
  var strError = "";
  var objCheck;

  objCheck = new check("agregar_eventos");
  objCheck.checkDate("elegir_dia", "Día", false);
  objCheck.checkString("titulo", "Título", 2, 60, false);
  objCheck.checkString("descripcion", "Descripción", 5, 255, false);
  strError = objCheck.toString();
  
  if (strError == "") {
    frm.hidGuardarEvento.value = 1;
    frm.submit ();
  } else {
    showAlert (strError.replace(/\n/g,'<br/>'));
  }
}

function enviarComentario(){
	var frm = document.anadir_comentario;
  var strError = "";
  var objCheck;

  objCheck = new check("anadir_comentario");
  objCheck.checkString("texto", "Texto", 2, 3000, false);
  strError = objCheck.toString();
  if (strError == "") {
    frm.hidEnviaComentario.value = 1;
    frm.submit ();
  } else {
    showAlert (strError.replace(/\n/g,'<br/>'));
  }
}

function loginInterno(){
	var frm = document.frmLoginInterno;
  var strError = "";
  var objCheck;

  objCheck = new check("frmLoginInterno");
  objCheck.checkString("txtUsuario2", "Usuario", 2, 50, false);
  objCheck.checkString("txtContrasenia2", "Contraseña", 2, 50, false);
  strError = objCheck.toString();
  if (strError == "") {
    frm.hidLogin.value = 2;
    frm.submit ();
  } else {
    showAlert (strError.replace(/\n/g,'<br/>'));
  }
}

function agregar_foto(){
	
}

function desplegarTooltip(idProducto) {
	var curleft = 0;
 	var curtop = 0;
 	var strPropGlobo;

 	var objDiv = document.getElementById("divTooltip" + idProducto);
 	var isIE = (document.all ? true : false);
 	var objA = document.getElementById('imgChapa' + idProducto);
 	
 	//obtengo la posicion del objeto
 	curleft = posX(objA);
 	curtop	= posY(objA);
 	
 	//le cargo el estilo
 	if(isIE) {
	 	objDiv.style.zIndex = 3;
	 	objDiv.style.position = 'absolute';
	 	objDiv.style.left = (curleft-25);
	 	objDiv.style.top = (curtop+30);
	} else {
		strPropGlobo = 'z-index:3; position:absolute; left:' + (curleft-25) + 'px; top:' + (curtop+30) + 'px;';
		objDiv.setAttribute('style',strPropGlobo);
	}
 	
 	//lo hago aparecer
 	objDiv.style.display = '';
}

function posX(obj) {
	var curleft = 0;
	if(obj.offsetParent) {
      while(1) {
        curleft += obj.offsetLeft;
        if(!obj.offsetParent)
          break;
        obj = obj.offsetParent;
      }
  } else if(obj.x) {
      curleft += obj.x;
  }
  return curleft;
}
	
function posY(obj) {
	var curtop = 0;
	if(obj.offsetParent) {
    while(1) {
      curtop += obj.offsetTop;
      if(!obj.offsetParent)
        break;
      obj = obj.offsetParent;
    }
	} else if(obj.y) {
    curtop += obj.y;
  }
  return curtop;
}

// ****************** FICHA USUARIO **************
function irAPaginaHabitualesUsuario(pagina,params){
	ajax_content_exe("ficha_usuario_habituales.php?pagactual=" + pagina + "&reducido=0&" + params, "divHabituales");
}
function mostrarHabitualesUsuarioReducido(params){
	ajax_content_exe("ficha_usuario_habituales.php?pagactual=0&reducido=1&" + params, "divHabituales");
}
function irAPaginaFichaUsuario(pagina,params){
	ajax_content_exe("ficha_usuario_fotos.php?pagactual=" + pagina + "&" + params, "divGaleria", "generarLightbox()");
}
function verRSS(id_usuario){
	ajax_content_exe("ajaxRSS.php?rss=1&id_usuario=" + id_usuario, "divGaleria");
}
function irAPaginaComentariosUsuario(pagina,params){
	ajax_content_exe("ficha_usuario_comentarios.php?pagactual=" + pagina + "&" + params, "divComentarios");
}
function twitter(id_usuario, usuario){
	ajax_content_exe("ajaxRSS.php?rss=0&id_usuario=" + id_usuario, "divGaleria", "getTwits('" + usuario + "')");
}
function getTwits(usuario){
	getTwitters('tweet',{ 
		id: usuario,
		count: 5,
		enableLinks: true,
		ignoreReplies: true,
		clearContents: true,
		template: '<img height="16" width="16" src="%user_profile_image_url%" align="left" /> <a href="http://twitter.com/%user_screen_name%" class="prefix">%user_name%</a>: <span class="status">"%text%"</span> <a href="http://twitter.com/%user_screen_name%/statuses/%id%" class="time">%time%</a><div class="clearfix"></div>'
		});
}
function flickr(id_usuario){
	ajax_content_exe("ajaxRSS.php?rss=2&id_usuario=" + id_usuario, "divGaleria");
}

// ******************* RECORDAR ************************
function recordar(){
	var frm = document.registro;
  var strError = "";
  var objCheck;

  objCheck = new check("registro");
  objCheck.checkEmail("email", "Email", 2, 100, false);
  strError = objCheck.toString();
  
  if (strError == "") {
    frm.hidRecordar.value = 1;
    frm.submit ();
  } else {
    showAlert (strError.replace(/\n/g,'<br/>'));
  }
}


// ******************* GENERALES ***********************
function login(){
	var frm = document.frmLogin;
  var strError = "";
  var objCheck;

  objCheck = new check("frmLogin");
  objCheck.checkString("txtUsuario1", "Usuario", 2, 50, false);
  objCheck.checkString("txtContrasenia1", "Contraseña", 2, 50, false);
  strError = objCheck.toString();
  if (strError == "") {
    frm.hidLogin.value = 1;
    frm.submit ();
  } else {
    showAlert (strError.replace(/\n/g,'<br/>'));
  }
}

function showAlert(strTexto, ancho, titulo){
	if(ancho==undefined) ancho = 320;
	if(titulo==undefined) titulo = "MENSAJE";
	
	var conf = {imageBase:'images'};
	$D.addClass(document.body, 'yui-skin-sam');

	// Instantiate a Panel from markup
	showImgPanel = new YAHOO.widget.Panel("showImgPanel", { width:ancho.toString() + "px", visible:false,draggable:true,close:true,modal:true, constraintoviewport:true } );

	var showImgPanelCloseHandler = function(e, o){
		o.hide();
	};
	$E.on(showImgPanel.body, 'click', showImgPanelCloseHandler, showImgPanel);

	showImgPanel.setHeader(titulo); 
	showImgPanel.setBody(strTexto); 
	showImgPanel.render(document.body); 
	showImgPanel.show(); 
	showImgPanel.center();
}

function reemplazar(){
	Cufon.replace('a');
	Cufon.replace('h1');
	Cufon.replace('p');
	Cufon.replace('li');
	Cufon.replace('label');
	Cufon.replace('.bases-completas');
	Cufon.replace('div.publicidad-chica-central');
	Cufon.replace('div.publicidad-chica');
	Cufon.replace('div.publicidad-grande');
	Cufon.replace('.replace');
}

function ocultar(div){
	document.getElementById(div).style.display = 'none';
}
function mostrar(div){
	document.getElementById(div).style.display = '';
}
function comprobarSesion(strCallback){
	simple_ajax("ajaxComprobarSesion.php", "GET", "callback=" + strCallback);
}
function mostrarLoginAjax(){
	if(window.ActiveXObject){
		var req = new ActiveXObject("Microsoft.XMLHTTP");
	}else if(window.XMLHttpRequest){
		var req = new XMLHttpRequest();
	}

	req.onreadystatechange = function (){
		if(req.readyState == 4){
			showAlert(req.responseText,410, "Es necesario estar identificado");
		}
	}
	req.open('GET', "ajaxFormLogin.php", true);
	req.send(null);
}

function loginLightbox(){
	var frm = document.frmLoginLightbox;
  var strError = "";
  var objCheck;

  objCheck = new check("frmLoginLightbox");
  objCheck.checkString("txtUsuario3", "Usuario", 2, 50, false);
  objCheck.checkString("txtContrasenia3", "Contraseña", 2, 50, false);
  strError = objCheck.toString();
  if (strError == "") {
    frm.hidLogin.value = 3;
    frm.submit ();
  } else {
    showAlert (strError.replace(/\n/g,'<br/>'));
  }
}

function verRedEstrella(){
	if(document.getElementById('popup-hover').style.display==''){
		ocultar('popup-hover');
	}else{
		mostrar('popup-hover');
	}
}
