// JavaScript Document
// Funciones en javascript
raiz = '/guia/';

function trim(cadena){
	for(i=0; i<cadena.length; )	{
		if(cadena.charAt(i)==" ")
			cadena=cadena.substring(i+1, cadena.length);
		else
			break;
	}
	for(i=cadena.length-1; i>=0; i=cadena.length-1)	{
		if(cadena.charAt(i)==" ")
			cadena=cadena.substring(0,i);
		else
			break;
	}	
	return cadena;
}

function GetFileExtension(Filename) {
	var I = Filename.lastIndexOf(".");
	return (I > -1) ? Filename.substring(I + 1, Filename.length).toLowerCase() : "";
} 

function aleatorio(inferior,superior){
    numPosibilidades = superior - inferior
    aleat = Math.random() * numPosibilidades
    aleat = Math.round(aleat)
    return parseInt(inferior) + aleat
} 

function desabilitarEnter(e) {
	tecla=(document.all) ? e.keyCode : e.which;
  if(tecla==13) return false;
}

/*---------------------------------------------------
		INGRESO
----------------------------------------------------*/
// Oculta y muestra el formulario de login dependiendo si escogio o no facebook
function verFormularioIngreso(){
	if (document.getElementById('cuentaIngreso1').checked){
		div = document.getElementById('uyp');
		div.style.display="";
	}else {
		div = document.getElementById('uyp');
		div.style.display="none"
	}
}
function login(){
	if (document.getElementById('cuentaIngreso2').checked){
		conectarFacebook();
	}else {
		if (document.getElementById('cuentaIngreso1').checked){
		conectarUsuario();
		}
	}
}
function ingresar(modo){
	actual = document.location.href;
	window.location.href=raiz+"/usuario/ingresar.php?mod="+modo+"&actual="+actual;
}
/*---------------------------------------------------------*/



// Valida password y confirmacion al activar cuenta
function activarCuenta(){
	patPassword = /^\w{4,16}$/; 
	if (trim(document.getElementById('passwordActivacion').value).length < 4){
		document.getElementById('errorValidacion').innerHTML = 'El password debe tener mas de 3 caracteres';
	}else {
		if (!trim(document.getElementById('passwordActivacion').value).match(patPassword)){
			document.getElementById('errorValidacion').innerHTML = 'El password debe ser alfanumerico (solo numeros y/o letras), con longitud entre 4 y 16 caracteres';
		}else{
			if (document.getElementById('passwordActivacion').value != document.getElementById('confirmacionActivacion').value){
				document.getElementById('errorValidacion').innerHTML = 'El password y su confirmacion no coinciden';
			}else{
				document.activarCuenta.action = "activarCuenta.php?mod=activacion";
				document.activarCuenta.submit();
			}
		}
	}	
}
function activarCuentaEnter(e) {
  tecla = document.all ? e.keyCode : e.which;
  if(tecla==13) activarCuenta();
} 

// Valida password y confirmacion al generar nuevo password
function guardarNuevoPassword(){
	patPassword = /^\w{4,16}$/; 
	if (trim(document.getElementById('passwordActivacion').value).length < 4){
		document.getElementById('errorValidacion').innerHTML = 'El password debe tener mas de 3 caracteres';
	}else {
		if (!trim(document.getElementById('passwordActivacion').value).match(patPassword)){
			document.getElementById('errorValidacion').innerHTML = 'El password debe ser alfanumerico (solo numeros y/o letras), con longitud entre 4 y 16 caracteres';
		}else{
			if (document.getElementById('passwordActivacion').value != document.getElementById('confirmacionActivacion').value){
				document.getElementById('errorValidacion').innerHTML = 'El password y su confirmacion no coinciden';
			}else{
				document.nuevoPassword.action = "recuperarPassword.php?mod=recuperar&accion=guardar";
				document.nuevoPassword.submit();
			}
		}
	}	
}
function guardarNuevoPasswordEnter(e) {
  tecla = document.all ? e.keyCode : e.which;
  if(tecla==13) activarCuenta();
} 


// Editar el perfil (Usuario sin facebook)
function editarPerfil(){
	if( trim(document.perfil.nombre.value) == ""){
		document.getElementById('errorPerfil').innerHTML = 'El nombre no puede ser vacio';
	}else if( trim(document.perfil.apellido.value) == ""){
		document.getElementById('errorPerfil').innerHTML = 'El apellido no puede ser vacio';
	}else {
		document.perfil.action = "../actualizarPerfil.php";
		document.perfil.submit();
	}
}

/*
** EDITAR IMAGEN (Usuario no facebook)
*/
// Oculta y muestra el formulario de login dependiendo si escogio o no facebook
function verCambiarImagen(){
	if (document.getElementById('accion1').checked){
		div = document.getElementById('eci');
		div.style.display="";
	}else {
		div = document.getElementById('eci');
		div.style.display="none"
	}
}
function editarImagen(){
	if (document.getElementById('accion1').checked){
		subirImagen();
	}else {
		if (document.getElementById('accion2').checked){
		eliminarImagen();
		}
	}
}
function eliminarImagen(){
	if (confirm("Eliminara su imagen de perfil, desea continuar?")){
		document.editarImagen.action = "cambiarImagen.php?mod=eliminar";
		document.editarImagen.submit();
		document.getElementById('cambioImagen').innerHTML = '<div align="center"><br /><img src="'+raiz+'images/loader_mediano.gif" /></div>';
	}
}
function subirImagen(){
	Ext = GetFileExtension(document.editarImagen.imagen.value); 
	if (Ext != "jpeg" && Ext != "jpg" && Ext != "png" && Ext != "gif") { 
		document.getElementById('errorImagen').innerHTML = 'La imagen no se encuentra en el formato requerido. Recuerde el archivo debe tener extencion .gif, .jpg o .png y debe ser menor de 1 mb.';
	}else if (confirm("Cambiara su imagen de perfil, desea continuar?")){
		document.editarImagen.action = "cambiarImagen.php?mod=cambiar";
		document.editarImagen.submit();
		document.getElementById('cambioImagen').innerHTML = '<div align="center"><br /><img src="'+raiz+'images/loader_mediano.gif" /></div>';
	}
}





/*
** VALIDACIONES GESTION DE LUGAR O NEGOCIO
*/

// Valida y envial el formulario de crear lugar
function cargarCrearLugarNegocio(){
	window.location = ""+raiz+"usuario/lugar/crearLugar.php";
}
function crearLugarNegocio(){
	var patMail=/(^[\-_\.a-zA-Z0-9]+)@((([0-9]{1,3}\.){3}([0-9]{1,3})((:[0-9])*))|(([a-zA-Z0-9\-]+)(\.[a-zA-Z]{2,})+(\.[a-zA-Z]{2})?((:[0-9])*)))/;
	var patUrl = /^((http)(s)?:\/\/){0,1}\w+(\.\w+)*(-\w+)?\.([a-z]{2,3}|info|mobi|aero|asia|name)(:\d{2,5})?(\/)?((\/).+)?$/;
	document.getElementById('errorNuevoLugar').innerHTML = '<div align="center"><br /><img src="'+raiz+'images/loader.gif" /></div>';
	if( trim(document.nuevoLugar.nombre.value) == ""){
		document.getElementById('errorNuevoLugar').innerHTML = '<p class="error"><strong>El nombre no puede ser vacio</strong></p>';
	}else if( trim(document.nuevoLugar.descripcion.value) == ""){
		document.getElementById('errorNuevoLugar').innerHTML = '<p class="error"><strong>La descripcion no puede ser vacio</strong></p>';
	}else if( trim(document.nuevoLugar.descripcion.value).length > 300){
		document.getElementById('errorNuevoLugar').innerHTML = '<p class="error"><strong>La descripcion es mayor a 300 caracteres. La descripcion debe menor a 300 caracteres.</strong></p>';
	}else if(document.nuevoLugar.municipio.value==0){
		document.getElementById('errorNuevoLugar').innerHTML = '<p class="error"><strong>Debe seleccionar la ciudad o municipio en la cual se encuentra su negocio</strong></p';
	}else if(document.nuevoLugar.categoria.value==0){
		document.getElementById('errorNuevoLugar').innerHTML = '<p class="error"><strong>Debe seleccionar la categoria en la cual se encuentra su negocio</strong></p>';
	}else if( trim(document.nuevoLugar.pagina.value) != ""){
		if (!trim(document.nuevoLugar.pagina.value).match(patUrl)){
			document.getElementById('errorNuevoLugar').innerHTML = '<p class="error"><strong>La direccion del sitio web no es valida</strong></p>';
		}else if(document.nuevoLugar.correo.value.search(patMail) == -1){
			document.getElementById('errorNuevoLugar').innerHTML = '<p class="error"><strong>El formato del correo de confirmaci&oacute;n no es correcto</strong></p>';
		}else {
			var url=""+raiz+"usuario/confirmarUsuario.php?correo="+document.nuevoLugar.correo.value; 
			new Ajax.Request( url , {method: 'get',onSuccess: function(transport) {
				if( transport.responseText == 'ok' ){	
					document.nuevoLugar.action = raiz+"usuario/lugar/crearLugar.php?mod=crear";
					document.nuevoLugar.submit();
					document.getElementById('negocioDeUsuario').innerHTML = '<div align="center"><br /><img src="'+raiz+'images/loader_grande.gif" /></div>';
				}else{
					document.getElementById('errorNuevoLugar').innerHTML = '<p class="error"><strong>'+transport.responseText+'</strong></p>';
				}
			}});			
		}
	}else if(document.nuevoLugar.correo.value.search(patMail) == -1){
			document.getElementById('errorNuevoLugar').innerHTML = '<p class="error"><strong>El formato del correo de confirmaci&oacute;n no es correcto</strong></p>';
	}else {
		var url=""+raiz+"usuario/confirmarUsuario.php?correo="+document.nuevoLugar.correo.value; 
		new Ajax.Request( url , {method: 'get',onSuccess: function(transport) {
			if( transport.responseText == 'ok' ){	
				document.nuevoLugar.action = raiz+"usuario/lugar/crearLugar.php?mod=crear";
				document.nuevoLugar.submit();
				document.getElementById('negocioDeUsuario').innerHTML = '<div align="center"><br /><img src="'+raiz+'images/loader_grande.gif" /></div>';
			}else{
				document.getElementById('errorNuevoLugar').innerHTML = '<p class="error"><strong>'+transport.responseText+'</strong></p>';
			}
		}});			
	}
}
// Valida y envial el formulario de editar lugar
function editarLugarNegocio(){
	var patUrl = /^((http)(s)?:\/\/){0,1}\w+(\.\w+)*(-\w+)?\.([a-z]{2,3}|info|mobi|aero|asia|name)(:\d{2,5})?(\/)?((\/).+)?$/;
	document.getElementById('errorEditarLugar').innerHTML = '<div align="center"><br /><img src="'+raiz+'images/loader.gif" /></div>';
	if( trim(document.editarLugar.nombre.value) == ""){
		document.getElementById('errorEditarLugar').innerHTML = '<p class="error"><strong>El nombre no puede ser vacio</strong></p>';
	}else if( trim(document.editarLugar.descripcion.value) == ""){
		document.getElementById('errorEditarLugar').innerHTML = '<p class="error"><strong>La descripcion no puede ser vacio</strong></p>';
	}else if( trim(document.editarLugar.descripcion.value).length > 300){
		document.getElementById('errorEditarLugar').innerHTML = '<p class="error"><strong>La descripcion es mayor a 300 caracteres. La descripcion debe ser menor 300 caracteres.</strong></p>';
	}else if( trim(document.editarLugar.pagina.value) != ""){
		if (!trim(document.editarLugar.pagina.value).match(patUrl)){
			document.getElementById('errorEditarLugar').innerHTML = '<p class="error"><strong>La direccion del sitio web no es valida</strong></p>';
		}else {
			document.editarLugar.action = raiz+"usuario/lugar/editarLugar.php?mod=editar";
			document.editarLugar.submit();
			document.getElementById('negocioDeUsuario').innerHTML = '<div align="center"><br /><img src="'+raiz+'images/loader_grande.gif" /></div>';
		}
	}else {
		document.editarLugar.action = raiz+"usuario/lugar/editarLugar.php?mod=editar";
		document.editarLugar.submit();
		document.getElementById('negocioDeUsuario').innerHTML = '<div align="center"><br /><img src="'+raiz+'images/loader_grande.gif" /></div>';
	}
}

// Valida y envial el formulario de editar lugar para nueva confirmacion
function cargarConfirmacionLugarNegocio(){
	window.location = ""+raiz+"usuario/lugar/editarConfirmacionLugar.php";
}
function editarConfirmacionNegocio(){
	var patMail=/(^[\-_\.a-zA-Z0-9]+)@((([0-9]{1,3}\.){3}([0-9]{1,3})((:[0-9])*))|(([a-zA-Z0-9\-]+)(\.[a-zA-Z]{2,})+(\.[a-zA-Z]{2})?((:[0-9])*)))/;
	var patUrl = /^((http)(s)?:\/\/){0,1}\w+(\.\w+)*(-\w+)?\.([a-z]{2,3}|info|mobi|aero|asia|name)(:\d{2,5})?(\/)?((\/).+)?$/;
	document.getElementById('errorEditarLugar').innerHTML = '<div align="center"><br /><img src="'+raiz+'images/loader.gif" /></div>';
	if( trim(document.editarLugar.nombre.value) == ""){
		document.getElementById('errorEditarLugar').innerHTML = '<p class="error"><strong>El nombre no puede ser vacio</strong></p>';
	}else if( trim(document.editarLugar.descripcion.value) == ""){
		document.getElementById('errorEditarLugar').innerHTML = '<p class="error"><strong>La descripcion no puede ser vacio</strong></p>';
	}else if( trim(document.editarLugar.descripcion.value).length > 300){
		document.getElementById('errorEditarLugar').innerHTML = '<p class="error"><strong>La descripcion es mayor a 300 caracteres. La descripcion debe estar entre 50 y 300 caracteres.</strong></p>';
	}else if( trim(document.editarLugar.descripcion.value).length < 50){
		document.getElementById('errorEditarLugar').innerHTML = '<p class="error"><strong>La descripcion es menor a 50 caracteres. La descripcion debe estar entre 50 y 300 caracteres.</strong></p>';
	}else if( trim(document.editarLugar.pagina.value) != ""){
		if (!trim(document.editarLugar.pagina.value).match(patUrl)){
			document.getElementById('errorEditarLugar').innerHTML = '<p class="error"><strong>La direccion del sitio web no es valida</strong></p>';
		}else  if(document.editarLugar.correo.value.search(patMail) == -1){
			document.getElementById('errorEditarLugar').innerHTML = '<p class="error"><strong>El formato del correo de confirmaci&oacute;n no es correcto</strong></p>';
		}else {
			var url=""+raiz+"usuario/confirmarUsuario.php?correo="+document.editarLugar.correo.value; 
			new Ajax.Request( url , {method: 'get',onSuccess: function(transport) {
				if( transport.responseText == 'ok' ){	
					document.editarLugar.action = raiz+"usuario/lugar/crearLugar.php?mod=editar";
					document.editarLugar.submit();
					document.getElementById('negocioDeUsuario').innerHTML = '<div align="center"><br /><img src="'+raiz+'images/loader_grande.gif" /></div>';
				}else{
					document.getElementById('errorEditarLugar').innerHTML = '<p class="error"><strong>'+transport.responseText+'</strong></p>';
				}
			}});
		}
	}else if(document.editarLugar.correo.value.search(patMail) == -1){
			document.getElementById('errorEditarLugar').innerHTML = '<p class="error"><strong>El formato del correo de confirmaci&oacute;n no es correcto</strong></p>';
	}else {
		var url=""+raiz+"usuario/confirmarUsuario.php?correo="+document.editarLugar.correo.value; 
		new Ajax.Request( url , {method: 'get',onSuccess: function(transport) {
			if( transport.responseText == 'ok' ){	
				document.editarLugar.action = raiz+"usuario/lugar/crearLugar.php?mod=editar";
				document.editarLugar.submit();
				document.getElementById('negocioDeUsuario').innerHTML = '<div align="center"><br /><img src="'+raiz+'images/loader_grande.gif" /></div>';
			}else{
				document.getElementById('errorEditarLugar').innerHTML = '<p class="error"><strong>'+transport.responseText+'</strong></p>';
			}
		}});			
	}
}



//	Presupuesto en negocios, restaurantes, bares y clubes y hoteles
function editarPresupuesto(){
	document.getElementById('verPresupuesto').style.display = 'none';
	document.getElementById('editarPresupuesto').style.display = '';
}
function verPresupuesto(){
	document.getElementById('verPresupuesto').style.display = '';
	document.getElementById('editarPresupuesto').style.display = 'none';
}
function validarPresupuesto(){
	document.getElementById('editarPresupuesto').style.display = 'none';
	document.getElementById('guardandoPresupuesto').style.display = '';
	if (trim(document.presupuesto.monto.value)!="")
		valor = parseInt(document.presupuesto.monto.value);
	else
		valor=0;
	if (isNaN(valor)) {
       document.getElementById('errorPresupuesto').innerHTML = 'El presupuesto no se encuentra en un formato valido<br>&nbsp;';
	   document.getElementById('editarPresupuesto').style.display = '';
	   document.getElementById('guardandoPresupuesto').style.display = 'none';
    }else{
       document.presupuesto.action = raiz+"usuario/lugar/cambiarPresupuesto.php";
	   document.presupuesto.submit();
    } 
}




function editarInput(id, texto){
	if (trim(document.getElementById(id).value) == texto)
		document.getElementById(id).value="";	
}
function dejarInput(id, texto){
	if (trim(document.getElementById(id).value) == "")	
		document.getElementById(id).value=texto;
}

function guardarNombreEnlace(){
	patNombreEnlace = /^[a-zA-Z]{3,30}$/; 
	document.getElementById('ingresoNombreEnlace').style.display="none";
	document.getElementById('cargandoNombreEnlace').style.display="";
	if (trim(document.getElementById('nombreEnlace').value) == "" || trim(document.getElementById('nombreEnlace').value) == "Ingrese solo letras, sin caracteres ni espacios"){
		document.getElementById('errorNombreEnlace').innerHTML = 'No ingreso ningun nombre para su negocio<br>';
		document.getElementById('ingresoNombreEnlace').style.display="";
		document.getElementById('cargandoNombreEnlace').style.display="none";
	}else if (!trim(document.getElementById('nombreEnlace').value).match(patNombreEnlace)){
		document.getElementById('errorNombreEnlace').innerHTML = 'El nombre solo puede contener letras con una longitud de entre 3 y 30 caracteres, tambien evite la &ntilde; y las tildes.<br>';
		document.getElementById('ingresoNombreEnlace').style.display="";
		document.getElementById('cargandoNombreEnlace').style.display="none";
	}else{
		var url=""+raiz+"usuario/lugar/confirmarNombreEnlace.php?nombre="+trim(document.getElementById('nombreEnlace').value); 
		new Ajax.Request( url , {method: 'get',onSuccess: function(transport) {
			if( transport.responseText == 'ok' ){					
				window.location.href=raiz+"usuario/lugar/guardarNombreEnlace.php?nombre="+trim(document.getElementById('nombreEnlace').value);
			}else{
				document.getElementById('errorNombreEnlace').innerHTML = 'El nombre ingresado ya existe, ingrese otro<br>';
				document.getElementById('ingresoNombreEnlace').style.display="";
				document.getElementById('cargandoNombreEnlace').style.display="none";
			}
		}});
	}
}



function imprimirElemento(){
		alert('Debido a la configuracion de los exploradores seleccione intervalo de impresion de 1 a 1 para evitar posibles paginas en blanco');
		print();
}


function enviarContacto(){
	var patMail=/(^[\-_\.a-zA-Z0-9]+)@((([0-9]{1,3}\.){3}([0-9]{1,3})((:[0-9])*))|(([a-zA-Z0-9\-]+)(\.[a-zA-Z]{2,})+(\.[a-zA-Z]{2})?((:[0-9])*)))/;
	if (trim(document.contacto.nombre.value)==""){
		document.getElementById('errorFormularioContacto').innerHTML = 'No ha ingresado ningun nombre';
	}else if (document.contacto.correo.value.search(patMail) == -1){
		document.getElementById('errorFormularioContacto').innerHTML = 'El correo electronico ingresado no es valido';
	}else if (trim(document.contacto.asunto.value)==""){
		document.getElementById('errorFormularioContacto').innerHTML = 'No ha ingresado ningun asunto';
	}else if (trim(document.contacto.mensaje.value)==""){
		document.getElementById('errorFormularioContacto').innerHTML = 'No ha ingresado ningun mensaje';
	}else{
		document.getElementById('errorFormularioContacto').innerHTML = '<div align="center"><img src="'+raiz+'images/loader_mediano.gif" /></div>';
		document.contacto.action = raiz+"contacto.php?mod=enviar";
	   	document.contacto.submit();
	}
}

function filtrar(id){
	var cadena = sinAcentos(trim(document.getElementById('mmgBusqueda').value));
	document.getElementById('filtro_busqueda').innerHTML = '<div align="center"><img src="'+raiz+'images/loader_mediano.gif" /></div>';
	window.location.href= raiz+'directorio/busqueda.php?busqueda='+cadena+'&categoria='+id+'&orden='+aleatorio(1,12);
}

function negociosCategoria(id){
	var cadena = sinAcentos(trim(document.getElementById('mmgBusqueda').value));
	window.location.href=raiz+'directorio/busqueda.php?busqueda='+cadena+'&categoria='+id+'&orden='+aleatorio(1,12);
}

function listarNivel(nivel){
	actual = document.location.href;
	ubicacion = actual.replace(/&nivel=1/, '');
	ubicacion = ubicacion.replace(/&nivel=2/, '');
	ubicacion = ubicacion.replace(/&nivel=3/, '');
	window.location.href = ubicacion+'&nivel='+nivel;
}

function buscar(){
	if (trim(document.getElementById('mmgBusqueda').value)!=""){
		var cadena = sinAcentos(trim(document.getElementById('mmgBusqueda').value));
		window.location.href=raiz+'directorio/busqueda.php?busqueda='+cadena+'&categoria=0&orden='+aleatorio(1,12);
	}else {
		
	}
}
function buscarEnter(e) {
  tecla = document.all ? e.keyCode : e.which;
  if(tecla==13) buscar();
} 


function eliminarFavorito(id){
	if (confirm("Eliminara este elemento de la lista de favoritos, desea continuar?")){
		window.location.href=raiz+'usuario/favoritos/eliminar.php?id='+id;
	}
}

function mostrarAtravezado(){
	document.getElementById('mmgBusqueda').style.display == '';
}
