//************************************************************
//FUNCION PARA AGREGAR UN COMENTARIO
//************************************************************
function addComentario(texto, tipo){
	$.post("/includes/sql_handler.php",{accion: 'addComentario', 
										id_nota: texto.attr("rel"), 
										comentario: texto.val(), 
										rand: Math.random() } ,function(data){
		if(data=="ok"){
			getComentarios(texto.attr("rel"), tipo);
			texto.val("Opinar");
		}else{
			alert("Error al guardar el comentario");	
		}
	});
}


//************************************************************
//FUNCION PARA LIMPIAR UN FORMULARIO
//************************************************************
function clear_form(){
	$(".clear_form").val('');
}



//************************************************************
//FUNCION PARA BORRAR UN COMENTARIO
//************************************************************
function delComentario(nota, comentario, link_comentario){
	if(confirm("Se procederá a borrar el comentario seleccionado")){
		link_comentario.html("Borrando...");
		$.post("/includes/sql_handler.php",{accion: 'delComentario', 
											id_comentario: comentario, 
											rand: Math.random() } ,function(data){
			if(data=="ok"){
				getComentarios(nota, "noticia");
			}else{
				alert("Error al borrar el comentario");	
			}
		});
	}
}


//************************************************************
//FUNCION PARA BORRAR UN COMENTARIO
//************************************************************
function delMensaje(mensaje, tipo){
	if(confirm("Se procederá a borrar el mensaje seleccionado")){
		$.post("/includes/sql_handler.php",{accion: 'delMensaje', 
											id_mensaje: mensaje, 
											tipo: tipo, 
											rand: Math.random() } ,function(data){
			if(data=="ok"){
				window.location.reload();
			}else{
				alert("Error al borrar el comentario");	
			}
		});
	}
}


//************************************************************
//FUNCION PARA IGUALAR EL ALTO DE LAS COLUMNAS
//************************************************************
function equalHeight(){
	
	if($("#publicidad-gral").length){ //si existe la columna de publicidad...
		
		if( $("#publicidad-gral").height() > $("#botonera-contenido").height()+$("#contenedor-gral").height() ){
			contenido_height = $("#publicidad-gral").height()-$("#botonera-contenido").height();
			$("#contenedor-gral").height(contenido_height+14);	
		}else{
			publicidad_height = $("#botonera-contenido").height()+$("#contenedor-gral").height();
			$("#publicidad-gral").height(publicidad_height-14);	
		}
	}
	
	if($("#contenedor-buscador").length){ //si existe la columna del contenedor buscador...
		
		if( $("#menu-gral").height() > $("#botonera-contenido").height()+$("#contenedor-buscador").height() ){
			contenido_height = $("#menu-gral").height()-$("#botonera-contenido").height();
			$("#contenedor-buscador").height(contenido_height+14);	
		}else{
			menu_height = $("#botonera-contenido").height()+$("#contenedor-buscador").height();
			$("#menu-gral").height(menu_height-14);	
		}	
	}
	
	if($("#contenedor-noticia").length){ //si existe la columna del contenedor noticia...
	
		if( $("#menu-gral").height() > $("#botonera-contenido").height()+$("#contenedor-noticia").height() ){
			contenido_height = $("#menu-gral").height()-$("#botonera-contenido").height();
			$("#contenedor-noticia").height(contenido_height+14);	
		}else{
			menu_height = $("#botonera-contenido").height()+$("#contenedor-noticia").height();
			$("#menu-gral").height(menu_height-14);	
		}
	}
	
	if($("#contenedor-noticia2").length){ //si existe la columna del contenedor noticia 2...	
		if( $("#menu-gral").height() > $("#botonera-contenido").height()+$("#contenedor-noticia2").height() ){
			contenido_height = $("#menu-gral").height()-$("#botonera-contenido").height();
			$("#contenedor-noticia2").height(contenido_height+14);
		}else{
			menu_height = $("#botonera-contenido").height()+$("#contenedor-noticia2").height();
			$("#menu-gral").height(menu_height-14);	
		}
	}
}


//************************************************************
//FUNCION PARA TRAER LOS COMENTARIOS DE UNA NOTA
//************************************************************
function getComentarios(id_nota, tipo){
	$.post("/includes/sql_handler.php",{accion: 'getComentarios', 
										id_nota: id_nota, 
										tipo: tipo,
										rand:Math.random() } ,function(data){
		$("#comentarios_"+id_nota).html(data.html).fadeOut('slow').fadeIn("slow");
		$("#cant_opiniones_"+id_nota).html(data.cantidad);
		equalHeight();
	},"json");
}


//************************************************************
//FUNCION PARA TRAER MAS NOTICIAS
//************************************************************
function getMasNoticias(div){
	$(".mas_noticias").html("Cargando...");
	$.post("/includes/sql_handler.php",{accion:'getNoticias', 
										filtro:$("#pag_filtro").val(), 
										cantidad:$("#pag_cantidad").val(),
										desde:$("#pag_desde").val(),
										seccion:$("#pag_seccion").val(),
										rand:Math.random() } ,function(data){

		div.html(data);
		equalHeight();
	});
}


//************************************************************
//FUNCION PARA TRAER LA IMAGEN DE UN PERFIL
//************************************************************
function getPerfilImagen(){
	$.post("/includes/sql_handler.php",{accion:'getPerfilImagen', 
										rand:Math.random() } ,function(data){

		$('#imgPerfil').attr("src",data);
	});
}


//************************************************************
//FUNCION PARA REDIRECCIONAR A UNA URL
//************************************************************
function goto(url){
	document.location = url;	
}

	
//************************************************************
//FUNCION PARA INICILIZAR EL CAMPO DE BUSQUEDA
//************************************************************
function init_buscador(){
	$("#t_buscador").autocomplete({
		source: function( request, response ) {
			$.getJSON("/includes/sql_handler.php", {accion: 'getBusqueda', 
												    busqueda: $("#t_buscador").val(), 
												    rand: Math.random()}, response );
			},
		minLength: 2,
		select: function( event, ui ) {
			goto(ui.item.link);
			return false;
		}
	})
	.data( "autocomplete" )._renderItem = function( ul, item ) {
		return $( "<li></li>" )
			.data( "item.autocomplete", item )
			.append( "<a>" + "<img class='img' src='" + item.imagen + "' width='50' height='50' />" +
					 "<div class='tit'>" + item.titulo + "</div></a>" )
			.appendTo( ul );
	};
}

	
//************************************************************
//FUNCION PARA INICILIZAR LOS CAMPOS DE COMENTARIOS
//************************************************************
function init_comentarios(){	
	$('.t_comentario').unbind('keypress');
	$('.t_comentario').unbind('blur');
	$('.t_comentario').unbind('focus');
	$('.t_comentario').keypress(function(e){
		if($(this).val()!="" && e.keyCode==13){ 
			addComentario($(this), "home");
		}
	})
	.blur(function() {
		if($(this).val()==""){
			$(this).val("Opinar");
		}
		return false;
	})
	.focus(function() {
		if($(this).val()=="Opinar"){
			$(this).val("");
		}
		return false;
	});
}


//************************************************************
//FUNCION PARA INICILIZAR EL CAMPO DE COMENTARIO DE UNA NOTA
//************************************************************
function init_comentarios_nota(){	
	$('.t_comentario_nota').keypress(function(e){
		if($(this).val()!="" && e.keyCode==13){ 
			addComentario($(this), "noticia");
		}
	})
	.blur(function() {
		if($(this).val()==""){
			$(this).val("Opinar");
		}
		return false;
	})
	.focus(function() {
		if($(this).val()=="Opinar"){
			$(this).val("");
		}
		return false;
	});
}



//************************************************************
//FUNCION PARA INICILIZAR LOS CAMPOS DE REDACTAR
//************************************************************
function init_redaccion(){	
	$('.redactar').focus(function() {
		if($(this).val()=="Para" || $(this).val()=="Mensaje"){
			$(this).val("");
		}
		return false;
	});
	
	
	$(".destinatario").autocomplete({
		source: function( request, response ) {
			$.getJSON("/includes/sql_handler.php", {accion: 'getDestinatarios', 
												    usuario: $("#t_para").val(), 
												    rand: Math.random()}, response );
			},
		minLength: 2,
		focus: function( event, ui ) {
			$("#t_para").val(ui.item.nombre);
			return false;
		},
		select: function( event, ui ) {
			$("#t_destinatario").val(ui.item.id);
			$("#t_para").val(ui.item.nombre);
			return false;
		}
	})
	.data( "autocomplete" )._renderItem = function( ul, item ) {
		return $( "<li></li>" )
			.data( "item.autocomplete", item )
			.append( "<a>" + "<img class='img' src='" + item.imagen + "' width='50' height='50' />" +
					 "<div class='tit'>" + item.nombre + "</div></a>" )
			.appendTo( ul );
	};
}




//************************************************************
//FUNCION PARA INICILIZAR EL ACORDION DEL MENU
//************************************************************
function init_menu_secciones(){	
	$("#accordion").accordion({autoHeight: false,
							   navigation: true,
							   collapsible: true,
							   active: -1,
							   header: "> p",
							   icons: false
							  });
	
	$('.accordion p').click(function() {
		$(this).next().toggle('slow');
		return false;
	}).next().hide();
}


//************************************************************
//FUNCION PARA LOGUEAR A LOS USUARIOS
//************************************************************
function login_user(){
	$("#note").html('Validando...').fadeIn(1000);
	$.post("/includes/dir_login.php",{ t_usuario:$('#t_usuario').val(),t_password:$('#t_password').val(),rand:Math.random() } ,function(data){
		switch(data){
			case "activo":
				document.location = $('#t_url').val();
				break;
			
			case "inactivo":
				alert("El usuario ingresado está inactivo");
				break;
				
			case "error":
				alert("El usuario o contraseña es incorrecto");
				break;
				
			default:
				alert(data);
				break;
		}
	});	
	return false;
}


//************************************************************
//FUNCION PARA ENVIAR EL FORM DE CONTACTO
//************************************************************
function sendContacto(){
	$("#msg-rta").addClass("msg-guardando").html("Enviando...").show("slow");
	$.post("/includes/sql_handler.php",{accion:'sendContacto', 
										tipo: $("#t_tipo").val(), 
										nombre: $("#t_nombre").val(), 
										apellido: $("#t_apellido").val(), 
										propiedad: $("#t_propiedad").val(), 
										email: $("#t_email").val(), 
										telefono: $("#t_telefono").val(), 
										movil: $("#t_movil").val(), 
										asunto: $("#t_asunto").val(), 
										mensaje: $("#t_mensaje").val(), 
										rand:Math.random() } ,function(data){

		$('#msg-rta').removeClass("msg-guardando");
		$('#msg-rta').removeClass("msg-error");
		if(data=="ok"){
			$("#msg-rta").addClass("msg-ok").html("Su mensaje se ha enviado correctamente").fadeIn("slow").fadeOut('slow').fadeIn("slow");
			$("#t_asunto").val("");
			$("#t_mensaje").val("");
		}else{
			$("#msg-rta").addClass("msg-error").html("Ha ocurrido un problema al enviar el mensaje. Vuelva a intentarlo m&aacute;s tarde.").fadeIn("slow").fadeOut('slow').fadeIn("slow");
		}
	});	
}



//************************************************************
//FUNCION PARA ENVIAR EL FORM DE CONTACTO PUBLICO
//************************************************************
function sendContactoPub(){
	$("#lbl_enviando").html("Enviando...");
	$.post("/includes/sql_handler.php",{accion:'sendContactoPub', 
										nombre: $("#t_nombre").val(), 
										apellido: $("#t_apellido").val(), 
										email: $("#t_email").val(), 
										telefono: $("#t_telefono").val(), 
										celular: $("#t_celular").val(), 
										pais: $("#t_pais").val(), 
										mensaje: $("#t_mensaje").val(), 
										rand:Math.random() } ,function(data){

		if(data=="ok"){
			$("#lbl_enviando").html("Su mensaje se ha enviado correctamente").fadeIn("slow").fadeOut('slow').fadeIn("slow");
			clear_form();
		}else{
			$("#lbl_enviando").html("Ha ocurrido un problema al enviar el mensaje. <br>Vuelva a intentarlo m&aacute;s tarde.");
		}
	});	
}



//************************************************************
//FUNCION PARA GUARDAR LA IMAGEN DEL PERFIL
//************************************************************
function savePerfilImagen(id, nombre){
	$.post("/mi-perfil/inc_images.php",{accion: 'save', 
									 	id_usuario: id, 
									 	nombre_img: nombre, 
									 	rand: Math.random() } ,function(data){
		if(data=="ok"){
			getPerfilImagen();
		}else{
			alert("Error al guardar la imagen");	
		}
	});
}
	
	
	
//************************************************************
//FUNCION PARA ENVIAR EL FORM DE INGRESO DE PERSONAL
//************************************************************
function sendIngresoPersonal(){
	var isChk = $("#t_check").is(":checked");
	if(isChk){
		$("#msg-rta").addClass("msg-guardando").html("Enviando...").show("slow");
		$.post("/includes/sql_handler.php",{accion:'sendIngresoPersonal', 
											formulario: $("#frmIngreso").serialize(),											
											rand:Math.random() } ,function(data){
	
			$('#msg-rta').removeClass("msg-guardando");
			$('#msg-rta').removeClass("msg-error");
			if(data=="ok"){
				$("#msg-rta").addClass("msg-ok").html("La autorizaci&oacute;n se ha enviado correctamente").fadeIn("slow").fadeOut('slow').fadeIn("slow");
				$("#t_propiedad").val("");
				$("#t_comentario").val("");
				
				/*for(i=1; i<=10; i++){
					$("#t_nombre_"+i).val("");
					$("#t_apellido_"+i).val("");
					$("#t_dni_"+i).val("");
					$("#t_motivo_"+i).val("");
					$("#t_dias_"+i).val("");
				}*/
				
				$("#t_check").attr('checked', false);
			}else{
				$("#msg-rta").addClass("msg-error").html("Ha ocurrido un problema al enviar la autorizaci&oacute;n. Vuelva a intentarlo m&aacute;s tarde.").fadeIn("slow").fadeOut('slow').fadeIn("slow");
			}
		});	
	}else{
		$("#msg-rta").addClass("msg-error").html("Para enviar la autorizaci&oacute;n debe tildar la opci&oacute;n de acuerdo").fadeIn("slow").fadeOut('slow').fadeIn("slow");
	}
}


//************************************************************
//FUNCION PARA ENVIAR LA INVITACION
//************************************************************
function sendInvitacion(){
	$("#msg-rta").addClass("msg-guardando").html("Enviando...").show("slow");
	$.post("/includes/sql_handler.php",{accion:'sendInvitacion', 
										nombre: $("#t_nombre").val(), 
										apellido: $("#t_apellido").val(), 
										email: $("#t_email").val(), 
										telefono: $("#t_telefono").val(), 
										user: $("#t_user").val(), 
										password: $("#t_password").val(), 
										rand:Math.random() } ,function(data){

		$('#msg-rta').removeClass("msg-guardando");
		$('#msg-rta').removeClass("msg-error");
		if(data=="ok"){
			$("#msg-rta").addClass("msg-ok").html("Su invitaci&oacute;n se ha enviado correctamente").fadeIn("slow").fadeOut('slow').fadeIn("slow");
		}else{
			$("#msg-rta").addClass("msg-error").html("Ha ocurrido un problema al enviar la invitaci&oacute;n. Vuelva a intentarlo m&aacute;s tarde.").fadeIn("slow").fadeOut('slow').fadeIn("slow");
		}
	});	
}


//************************************************************
//FUNCION PARA ENVIAR LOS MENSAJES
//************************************************************
function sendMensaje(){
	$("#msg-rta").addClass("msg-guardando").html("Enviando...").show("slow");
	$.post("/includes/sql_handler.php",{accion:'sendMensaje', 
										destinatario: $("#t_destinatario").val(), 
										mensaje: $("#t_mensaje").val(), 
										rand:Math.random() } ,function(data){

		$('#msg-rta').removeClass("msg-guardando");
		$('#msg-rta').removeClass("msg-error");
		if(data=="ok"){
			$("#msg-rta").addClass("msg-ok").html("Su mensaje se ha enviado correctamente").fadeIn("slow").fadeOut('slow').fadeIn("slow");
		}else{
			$("#msg-rta").addClass("msg-error").html("Ha ocurrido un problema al enviar el mensaje. Vuelva a intentarlo m&aacute;s tarde.").fadeIn("slow").fadeOut('slow').fadeIn("slow");
		}
	});	
}


//************************************************************
//FUNCION PARA ENVIAR EL FORM DE PUBLICIDAD
//************************************************************
function sendPubliciteAqui(){
	$("#msg-rta").addClass("msg-guardando").html("Enviando...").show("slow");
	$.post("/includes/sql_handler.php",{accion:'sendPubliciteAqui', 
										nombre: $("#t_nombre").val(), 
										apellido: $("#t_apellido").val(), 
										email: $("#t_email").val(), 
										telefono: $("#t_telefono").val(), 
										mensaje: $("#t_mensaje").val(), 
										rand:Math.random() } ,function(data){

		$('#msg-rta').removeClass("msg-guardando");
		$('#msg-rta').removeClass("msg-error");
		if(data=="ok"){
			$("#msg-rta").addClass("msg-ok").html("Su solicitud se ha enviado correctamente").fadeIn("slow").fadeOut('slow').fadeIn("slow");
			$("#t_mensaje").val("");
		}else{
			$("#msg-rta").addClass("msg-error").html("Ha ocurrido un problema al enviar su solicitud. Vuelva a intentarlo m&aacute;s tarde.").fadeIn("slow").fadeOut('slow').fadeIn("slow");
		}
	});	
}



//************************************************************
//FUNCION PARA ENVIAR EL FORM DE RECUPERO DE PASSWORD
//************************************************************
function sendRecuperoPsw(){
	$("#lbl_enviando").html("Enviando...");
	$.post("/includes/sql_handler.php",{accion:'sendRecuperoPsw', 
										email: $("#t_mail").val(), 
										rand:Math.random() } ,function(data){

		if(data=="ok"){
			$("#lbl_enviando").html("Su mensaje se ha enviado correctamente").fadeIn("slow").fadeOut('slow').fadeIn("slow");
			$("#t_mail").val("ejemplo@email.com");
		}else{
			//$("#lbl_enviando").html("Ha ocurrido un problema al enviar el mensaje. <br>Vuelva a intentarlo m&aacute;s tarde.");
			$("#lbl_enviando").html(data);
		}
	});	
}


//************************************************************
//FUNCION PARA ENVIAR EL FORM DE CONTACTO
//************************************************************
function sendRetiroElementos(){
	var isChk = $("#t_check").is(":checked");
	if(isChk){
		$("#msg-rta").addClass("msg-guardando").html("Enviando...").show("slow");
		$.post("/includes/sql_handler.php",{accion:'sendRetiroElementos', 
											propiedad: $("#t_propiedad").val(), 
											autorizado: $("#t_autorizado").val(), 
											dni: $("#t_dni").val(), 
											elementos: $("#t_elementos").val(), 
											rand:Math.random() } ,function(data){
	
			$('#msg-rta').removeClass("msg-guardando");
			$('#msg-rta').removeClass("msg-error");
			if(data=="ok"){
				$("#msg-rta").addClass("msg-ok").html("La autorizaci&oacute;n se ha enviado correctamente").fadeIn("slow").fadeOut('slow').fadeIn("slow");
				$("#t_propiedad").val("");
				$("#t_autorizado").val("");
				$("#t_dni").val("");
				$("#t_elementos").val("");
				$("#t_check").attr('checked', false);
			}else{
				$("#msg-rta").addClass("msg-error").html("Ha ocurrido un problema al enviar el mensaje. Vuelva a intentarlo m&aacute;s tarde.").fadeIn("slow").fadeOut('slow').fadeIn("slow");
			}
		});	
	}else{
		$("#msg-rta").addClass("msg-error").html("Para enviar la autorizaci&oacute;n debe tildar la opci&oacute;n de acuerdo").fadeIn("slow").fadeOut('slow').fadeIn("slow");
	}
}


//************************************************************
//FUNCION PARA PARA GUARDAR LOS DATOS DEL PERFIL
//************************************************************
function setPerfil(){
	$('html, body').animate( { scrollTop: 0 }, 'slow');
	$("#msg-rta").addClass("msg-guardando").html("Guardando...").show("slow");
	$.post("/includes/sql_handler.php",{accion:'setPerfil', 
										nombre: $("#t_nombre").val(), 
										apellido: $("#t_apellido").val(), 
										nro_asociado: $("#t_nro_asociado").val(), 
										email: $("#t_email").val(), 
										telefono: $("#t_telefono").val(), 
										movil: $("#t_movil").val(), 
										propiedad: $("#t_propiedad").val(), 
										fecha_nac: $("#t_fecha_nac").val(), 
										estado_civil: $("#c_estado_civil").val(), 
										sexo: $("#c_sexo").val(), 
										user: $("#t_user").val(), 
										password: $("#t_password").val(), 
										sobre_mi: $("#t_sobre_mi").val(), 
										pub_email: $("#c_pub_email").is(":checked"), 
										pub_sexo: $("#c_pub_sexo").is(":checked"), 
										pub_telefono: $("#c_pub_telefono").is(":checked"), 
										pub_fecha_nac: $("#c_pub_fecha_nac").is(":checked"), 
										pub_estado_civil: $("#c_pub_estado_civil").is(":checked"), 
										pub_sobre_mi: $("#c_pub_sobre_mi").is(":checked"), 		
										permitir_contacto: $("#c_permitir_contacto").val(), 
										rand:Math.random() } ,function(data){

		$('#msg-rta').removeClass("msg-guardando");
		$('#msg-rta').removeClass("msg-error");
		if(data=="ok"){
			$("#msg-rta").addClass("msg-ok").html("Su perfil se actualiz&oacute; correctamente").fadeIn("slow").fadeOut('slow').fadeIn("slow");
		}else{
			$("#msg-rta").addClass("msg-error").html("Ha ocurrido un problema al actualizar su perfil. Vuelva a intentarlo m&aacute;s tarde.").fadeIn("slow").fadeOut('slow').fadeIn("slow");
		}
	});	
}


//************************************************************
//FUNCION PARA PARA GUARDAR LA SECCION QUE DESEA EL USUARIO
//QUE LE ENVIEN POR MAIL
//************************************************************
function setSubSeccionByUsuario(combo){
	id_subseccion = combo.val();
	(combo.is(":checked"))? tipo="alta" : tipo="baja";
	$.post("/includes/sql_handler.php",{accion:'setSubSeccionByUsuario', 
										tipo: tipo,
										subseccion: id_subseccion, 
										rand:Math.random() } ,function(data){

		if(data!="ok"){
			alert(data);
		}
	});	
}


//************************************************************
//FUNCION PARA BORRAR LOS CAMPOS DE CONTACTO
//************************************************************
function doClear(text){
	if (text.value == text.defaultValue) { 
		text.value = "" 
	} 
};


//************************************************************
//FUNCION PARA PONER LOS DATOS DEFATULS EN LOS CAMPOS DE CONTACTO
//************************************************************
function doDefault(text){ 
	if (text.value == ""){ 
		text.value = text.defaultValue
	}
};
