var comentando = false;
var cargando = false;
var citaspage = 0;
var lastyclick = 0;
var lastxclick = 0;
var docW = 0;
var docH = 0;
var moviendo = false;
$(function () {
   $(document).click(function(e){
      lastxclick = e.pageX;
      lastyclick = e.pageY;
   }); 
   docW = $(document).width();
   docH = $(document).height();  	
	$("#fileToUpload").filestyle({ 
	     image: "images/common/examinar_on.jpg",
	     imageHover: "images/common/examinar_off.jpg",
	     imageheight : 42,
	     imagewidth : 102,
	     width : 180
	 });
	$("#fileToUpload2").filestyle({ 
	     image: "images/common/examinar_on.jpg",
	     imageHover: "images/common/examinar_off.jpg",
	     imageheight : 42,
	     imagewidth : 102,
	     width : 180
	 });
	 $(".autofav").autocomplete("/main.php?_action=listafav");
	 $(".allUsers").autocomplete("/main.php?_action=listaAllUsers");
	//$("div").pngFix();
	$(".clean_text").focus(function(){
		if($(this).attr("title") == $(this).val())
			$(this).val("");
	});
	$(".clean_text").blur(function(){
		if($(this).val()=="")
		$(this).val($(this).attr("title"));
	});
	$("#frmReg").submit(function(){
		if($("#tyc").attr("checked")==false){
			mensaje("Debes aceptar los t&eacute;rminos y condiciones.");
			return false;	
		} 
	})
	$("#selectHoroscopo1").change(function(){
		getHoroscopo(1,$(this).val());
	})
	$("#selectHoroscopo2, #selectHoroscopo3").change(function(){
		if($("#selectHoroscopo2").val()!="" && $("#selectHoroscopo3").val()!=""){
			getHoroscopo(2,$("#selectHoroscopo2").val(),$("#selectHoroscopo3").val());
		}
	})
	$("#sendHoroscopo").click(function(){
		sendHoroscopo();
	})
	$("#uploadModal").click(function(){
		var html = '<div id="uploadDiv"><center><span class="sub_titulo1">Subir nueva foto</span><br><span class="txt3b">Vista Previa      </span></center><BR><div style="height: 180px;" id="preview"></div><br/><br/><input type="file" class="input" name="fileToUpload" id="fileToUpload" size="10" /><input type="button" onclick="ajaxFileUploadGalery();" value="Subir" id="doUpload"/><input type="hidden" name="img_path" id="img_path"/><br/><div style="display: none;" id="loading"><img src="images/loading.gif"/></div><br/><br/><table width="200" border="0" align="center" cellpadding="0" cellspacing="0"><tr><td width="50%" align="center"><a href="javascript:void(0)" class="boton2" onclick="modalFlowles.close();">Cerrar</a></td><td width="50%" align="center"><a href="javascript:void(0)" class="boton2" onclick="guardarFoto();">Guardar</a></td></tr></table></div>';
		$("#modal").css("top","30%");
		modalFlowles.show('Subir foto',html);
		
	})
	$("#fileToUpload").change(function(){
		ajaxFileUploadAvattar();
	});
	$("#fileToUpload2").change(function(){
		ajaxFileUploadGalery();
	});
	
	$("#reg_now").click(function(){
		$("#frm_reg1").attr("action","/main.php?_action=doRegister&quick=true");
		document.frm_reg1.submit();
	})
	$("#reg_continue").click(function(){
		document.frm_reg1.submit();
	});
	$("#btn_log").click(function(){
		document.frm_login.submit();	
	});
	$("#saveEdit1").click(function(){
		document.frm_edit1.submit();	
	});
	$("#cancelEdit1").click(function(){
		location.href='main.php?_action=perfil'	
	});
	$("#sig_edit2").click(function(){
	var errores = "";
	if($("input[name=caracteristicas]:checked").length>6)
		errores +="* Puedes elegir 6 caracter&iacute;sticas m&aacute;ximo.";
	if($("input[name=deportes]:checked").length>6)
		errores +="* Puedes elegir 6 deportes m&aacute;ximo.";
	if($("input[name=actividades]:checked").length>6)
		errores +="* Puedes elegir 6 actividades m&aacute;ximo.";
	if(errores){
		mensaje(errores);
	}else{
			var car = new Array();
			var act = new Array();
			var dep = new Array();
			$("input[name=caracteristicas]:checked").each(function(){
				car.push($(this).val());
			})
			$("input[name=actividades]:checked").each(function(){
				act.push($(this).val());
			})
			$("input[name=deportes]:checked").each(function(){
				dep.push($(this).val());
			})
			$("#carac").val(car.join(", "));
			$("#activi").val(act.join(", "));
			$("#depor").val(dep.join(", "));	
			document.frm_edit2.submit();
	}
		
	});
	$("#cancel_edit2").click(function(){
		location.href='main.php?_action=perfil'	
	});
	$("#sig_paso2").click(function(){
	var errores = "";
	if($("input[name=caracteristicas]:checked").length>6)
		errores +="* Puedes elegir 6 caracter&iacute;sticas m&aacute;ximo.";
	if($("input[name=deportes]:checked").length>6)
		errores +="* Puedes elegir 6 deportes m&aacute;ximo.";
	if($("input[name=actividades]:checked").length>6)
		errores +="* Puedes elegir 6 actividades m&aacute;ximo.";
	if(errores){
		mensaje(errores);
	}else{
			var car = new Array();
			var act = new Array();
			var dep = new Array();
			$("input[name=caracteristicas]:checked").each(function(){
				car.push($(this).val());
			})
			$("input[name=actividades]:checked").each(function(){
				act.push($(this).val());
			})
			$("input[name=deportes]:checked").each(function(){
				dep.push($(this).val());
			})
			$("#carac").val(car.join(", "));
			$("#activi").val(act.join(", "));
			$("#depor").val(dep.join(", "));	
			document.frm_paso2.submit();
	}

	});
	$("#endReg").click(function(){
	var errores = "";
	if($("input[name=interes]:checked").length>6)
		errores +="* Puedes elegir 6 caracter&iacute;sticas m&aacute;ximo.";
	if($("input[name=generos]:checked").length>6)
		errores +="* Puedes elegir 6 deportes m&aacute;ximo.";
	if(errores){
		mensaje(errores);
	}else{		
			var inter = new Array();
			var gener = new Array();
			var piel = new Array();
			$("input[name=interes1]:checked").each(function(){
				inter.push($(this).val());
			})
			$("input[name=interes2]:checked").each(function(){
				inter.push($(this).val());
			})
			$("input[name=interes3]:checked").each(function(){
				inter.push($(this).val());
			})
			$("input[name=interes4]:checked").each(function(){
				inter.push($(this).val());
			})			
			$("input[name=interes5]:checked").each(function(){
				inter.push($(this).val());
			})	
			$("input[name=interes6]:checked").each(function(){
				inter.push($(this).val());
			})			
			$("input[name=interes7]:checked").each(function(){
				inter.push($(this).val());
			})
			$("input[name=interes8]:checked").each(function(){
				inter.push($(this).val());
			})			
								
			$("input[name=piel]:checked").each(function(){
				piel.push($(this).val());
			})
			$("#intereses").val(inter.join(", "));
			$("#generos_musicales").val(gener.join(", "));
			$("#pieles").val(piel.join(", "));	
			document.frm_paso3.submit();		
	}
	});
});
function noregMsj(){
	alert("Tienes que estar logueado.");
}
function mensaje(msj){
	modalFlowles.show("My Love Story",msj,3000);
}
function guardarFoto(){
		if($("#img_path").val()==""){
			mensaje("Debes subir una foto primero.");
			return;
		}
		datos = "_action=guardarFotoPerfil&path="+$("#img_path").val();
		var date = new Date();
		var timestamp = date.getTime();
		$.ajax({
		   type: "POST",
		   url: "/main.php?t="+timestamp,
		   data: datos,
		   beforeSend: function(){
			},
		   success: function(data){
				if(data == "noSession"){
					noregMsj();
				}
				if(data == "noFile"){
					mensaje("El archivo especificado no existe, por favor intente nuevamente.");
				}
				if(parseInt(data)>0){
					var imagen = '<div id="foto'+parseInt(data)+'" class="item_foto"><a rel="lightbox" href="'+$("#img_path").val()+'" title="'+parseInt(data)+'"><img src="'+$("#img_path").val()+'" width="60" height="60"></a></div>';
					if($("#galeria div").length>0)
						$("#galeria div:first").before(imagen);
					else
						$("#galeria").html(imagen);
					refreshGaleria();
					mensaje("La foto h&aacute; sido agregada a tu perfil.");
				}

		  }
		});		
}
function in_array(needle, haystack, strict) {
    var found = false, key, strict = !!strict;
 
    for (key in haystack) {
        if ((strict && haystack[key] === needle) || (!strict && haystack[key] == needle)) {
            found = true;
            break;
        }
    }
 
    return found;
}
//modal
var modalFlowles = {
	position: 0,
	secondsDelay: 10,
	tipoModal: 'normal',
	isOpen: 'false',
	show: function (titulo, texto,delay,w,h) {

		if ($("#modalContent").is(":visible")) {
		
			$("#modalContainer").hide();
			$("#modalContent").hide();
		
			modalFlowles.isOpen = false;			
		}
		//if(is_numeric($("#vid").val())){
			$("#videoPlay").css("visibility","hidden");
		//}
		modalFlowles.tipoModal = 'normal';
		
		//var extraHtml = (titulo!='Contacto')? '<br><br><a href="javascript:void(0);" id="btn_cerrar">OK</a>' : '';
		
		$("#modalContent_msj").html(texto);
		
		$("#modalContent_title").text(titulo);
		//$("#modalContent").css('width', '500px');
		if (jQuery.browser.msie){
			$("#modalContainer").show();			
			$("#modalContainer").css('opacity', '0.5').css('filter', 'alpha(opacity = 50)');
			//$("#modalContent").css('width', '500px');
		}
		else
		{
			$("#modalContainer").fadeIn();
		}
		$("#modalContent").show();
		//$("#modalContent").css({'text-align':'left','height':'auto', 'width':'auto'});
		modalFlowles.isOpen=true;
		if(delay){
			setTimeout(function(){
				modalFlowles.close();
			}, delay);			
		}
		if(lastyclick>docH-300)
			lastyclick = lastyclick-300; 
		$("#modalContent").css("top",lastyclick);
		$("#modalContainer").css({"width":docW,"height":docH,"margin-left":"0px"});
	},
	close: function () {
		$("#btn_mini_cerrar").remove();
		if (!$("#modalContent").is(":visible")) return;
		
		
		if (modalFlowles.tipoModal=='loading') {
			
			$("#modalContainer").fadeOut(100);
			$("#modalContent").fadeOut(100);
		}
		else
		{
		
			$("#modalContainer").fadeOut(100);
			$("#modalContent").fadeOut(100);
		}
		modalFlowles.isOpen = false;
		$("#videoPlay").css("visibility","visible");	
	}, 
	showLoading: function(){
		modalFlowles.tipoModal = 'loading';
		$("#modalContent").html('<img src="images/ajax-loader.gif"> Cargando, espere por favor...').css({'text-align':'left','height':'33px', 'width':'220px'});
		if (jQuery.browser.msie){
			$("#modalContainer").show();
			$("#modalContainer").css('opacity', '0.5').css('filter', 'alpha(opacity = 50)');
		}
		else
		{
			$("#modalContainer").show();
		}
		$("#modalContent").show();
	
	}
}
function checkUsername(){
			if($("#usuario_reg").val()==""){
				alert("Ingresa un nombre de usuario.");
				return;
			}
			datos = "_action=checkUsername&username="+$("#usuario_reg").val();
			var date = new Date();
			var timestamp = date.getTime();
			$.ajax({
			   type: "POST",
			   url: "/main.php?t="+timestamp,
			   data: datos,
			   beforeSend: function(){
			   	$("#loading2").show();
				},
			   success: function(data){
			   	
			   	if(data=="OK"){
			   		$("#checkUn").css("color","green");
			   		$("#checkUn").val("Disponible!!!");
				}else{
			   		$("#checkUn").css("color","red");
			   		$("#checkUn").val("No disponible!!!");
				}
				$("#loading2").hide();
			  }
			});
}
function borrarFoto(id){
		var theId = id.replace('foto','');
		datos = "_action=borrarFoto&id="+theId;
		var date = new Date();
		var timestamp = date.getTime();
		$.ajax({
		   type: "POST",
		   url: "/main.php?t="+timestamp,
		   data: datos,
		   beforeSend: function(){
			},
		   success: function(data){
				if(data == "noDuenio"){
					mensaje("Solo puedes borrar fotos y avatares de tu perfil.");
				}
				if(data=="OK"){
					$("#"+id).fadeOut('slow');
					$("#"+id).remove();
				}

		  }
		});		
}
function refreshGaleria(){
		//$("#fotos").corner();
		var ocultar = true;
		$(".closes_for_pictures").remove();
		$(".item_foto").mouseover(function(){
			if ($("#close_for_"+$(this).attr('id')).attr('id')==undefined){
				$("body").append('<a href="javascript:void(0);" id="close_for_' + $(this).attr('id') + '" class="borrar_item">&nbsp;</a>');
				if($.browser.msie){
					var topo = 0;
				}else{
					var topo = 90;
				}
				$("#close_for_"+$(this).attr('id')).css({
					"position":"absolute",
					"left":$(this).offset().left+$(this).width()-15+"px",
					"top": ($(this).offset().top-topo)+"px"
				}).addClass('closes_for_pictures');
			
				$("#close_for_"+$(this).attr('id')).attr('for_id', $(this).attr('id')).mouseover(function(){
					$(this).show();
					ocultar=false;
				});
				$("#close_for_"+$(this).attr('id')).mouseout(function(){
					ocultar=true;
				});
				$("#close_for_"+$(this).attr('id')).click(function(){
					ocultar=false;
					$(this).hide();
					$(".closes_for_pictures").remove();
					borrarFoto($(this).attr('for_id'));
					
				});
			}
			$("#close_for_"+$(this).attr('id')).show();
			ocultar=true;

		}).click(function(){
			//alert('mostrar lightbox o similar para esta foto/avatar. Incluir un link para establecer como avatar predeterminado.');
		});
		
		$(".item_foto").mouseout(function(){
			if (ocultar) $("#close_for_"+$(this).attr('id')).hide();
		});
		$('.item_foto a').lightBox();
			
}

function backSection(){
	if($("#accion").val()=="out")
		var modo = 1;
	if($("#accion").val()=="in")
		var modo = 2;
	if($("#accion").val()=="wrt")
		var modo = 3;
	changeMsjMode(modo);
}
function msgAction(obj){
	//alert($(obj).val());
if($(obj).val()=="Seleccionar" || parseInt($(".checkMsj:checked").length)==0){
	return false;
}
if($(obj).val()==1){
	if(!confirm("Seguro desea borrar los mensajes seleccionados?"))
		return;
}
var ids = new Array();
$(".checkMsj:checked").each(function(){
	ids.push($(this).attr("todelete"));
});
messageActions($(obj).val(),ids.join("/"));	
}
function responderMsj(id){
	changeMsjMode(3,id);
}
function messageActions(action,ids){
		datos = "_action=messageActions&action="+action+"&ids="+ids+"&page="+$("#pg").val()+"&inout="+$("#accion").val();
		var date = new Date();
		var timestamp = date.getTime();
		$.ajax({
		   type: "POST",
		   url: "/main.php?t="+timestamp,
		   data: datos,
		   beforeSend: function(){
		   	modalFlowles.showLoading();
			},
		   success: function(data){
		   	modalFlowles.close();
				if(data == "noSession"){
					noregMsj();
					return;
				}
				if(data == "noSelect"){
					mensaje("No has seleccionado ningun mensaje.");
					return;
				}
				if(data == "noValido"){
					mensaje("No puedes modificar este mensaje.");
					return;
				}
				if(data=="OK"){
					getNextMessages($("#pg").val(),"");
				}

		  }
		});		
}
function getNextMessages(p,jq){
	$("#pg").val(p);
		datos = "_action=getMessages&accion="+$("#accion").val()+"&page="+p;
		var date = new Date();
		var timestamp = date.getTime();
		$.ajax({
		   type: "POST",
		   url: "/main.php?t="+timestamp,
		   data: datos,
		   dataType:"json",
		   beforeSend: function(){
		   	modalFlowles.showLoading();
			},
		   success: function(data){
		   	modalFlowles.close();
		   	$(".trMsj").remove();
				if(data == "noSession"){
					noregMsj();
					return;
				}
				if(data == "noValido"){
					mensaje("Asegurate que el avatar elegido existe.");
					return;
				}
				if(data.html!=""){
					$("#inflexo").before(data.html);
					if(p==0){
					$("#paginacionInbox").pagination(
							         parseInt(data.count), {
							         num_edge_entries: 2,
							         items_per_page: 10,
							         prev_text:"<",
							         next_text:">",
							        callback: getNextMessages
							        });							
					}
				}
			
		  }
		});	
}
function changeMsjMode(mode,id){
	if(mode==2){
		$("#accion").val("in");
	}
	if(mode==1){
		$("#accion").val("out");
	}
	if(mode==3){
		$("#accion").val("wrt");
	}
	$("#pg").val(0);
		datos = "_action=setModo&modo="+mode+"&accion="+$("#accion").val()+"&id="+id;
		var date = new Date();
		var timestamp = date.getTime();
		$.ajax({
		   type: "POST",
		   url: "/main.php?t="+timestamp,
		   data: datos,
		   dataType:"json",
		   beforeSend: function(){
		   	modalFlowles.showLoading();
			},
		   success: function(data){
		   	modalFlowles.close();
				if(data == "noSession"){
					noregMsj();
					return;
				}
				if(data == "noValido"){
					mensaje("H&aacute; ocurrido un error.");
					return;
				}
				if(data.html!=""){
					$("#escucha").html(data.html);
				if(mode==1 || mode==2){
					if(parseInt(data.count)>10){
					$("#paginacionInbox").pagination(
							         parseInt(data.count), {
							         num_edge_entries: 2,
							         items_per_page: 10,
							         prev_text:"<",
							         next_text:">",
							        callback: getNextMessages
							        });
					$("#paginacionInbox").show();
					}	
					}
				$(".amigos").autocomplete("/main.php?_action=getAmigos");
						
				}
			}
			
		});
}
function sendMessage(){
		datos = "_action=sendMessage&to="+$("#para").val()+"&tema="+$("#tema").val()+"&mensaje="+$("#mensaje").val();
		var date = new Date();
		var timestamp = date.getTime();
		$.ajax({
		   type: "POST",
		   url: "/main.php?t="+timestamp,
		   data: datos,
		   beforeSend: function(){
		   	modalFlowles.showLoading();
			},
		   success: function(data){
		   	modalFlowles.close();
				if(data == "noSession"){
					noregMsj();
					return;
				}
				if(data == "noUsuario"){
					mensaje("El usuario "+$("#para").val()+" no existe en Lovepark.");
					return;
				}
				if(data=="OK"){
					mensaje("Mensaje enviado correctamente!");
					$("#para, #tema, #mensaje").val("");
				}

		  }
		});	
}
function verMensaje(id){
		datos = "_action=readMessage&id="+id;
		var date = new Date();
		var timestamp = date.getTime();
		$.ajax({
		   type: "POST",
		   url: "/main.php?t="+timestamp,
		   data: datos,
		   beforeSend: function(){
		   	modalFlowles.showLoading();
			},
		   success: function(data){
		   	modalFlowles.close();
				if(data == "noSession"){
					noregMsj();
					return;
				}
				if(data == "noAccesso"){
					mensaje("Debes tienes permisos para acceder a este mensaje.");
					return;
				}
				if(data!=""){
					$("#escucha").html(data);
				}

		  }
		});	
}
function establecerAvattar(id){
		datos = "_action=establecerAvatar&id="+id;
		var date = new Date();
		var timestamp = date.getTime();
		$.ajax({
		   type: "POST",
		   url: "/main.php?t="+timestamp,
		   data: datos,
		   beforeSend: function(){
		   	//modalFlowles.showLoading();
			},
		   success: function(data){
				if(data == "noSession"){
					mensaje("Debes estar logueado.");
				}
				if(data == "noValido"){
					mensaje("Asegurate que el avatar elegido existe.");
				}
				if(data == "OK"){
					mensaje("El avatar se agreg&oacute; con &eacute;xito!");
				}

		  }
		});		
}
function ajaxFileUploadGalery(){
		$("#loading")
		.ajaxStart(function(){
			$(this).show();
		})
		.ajaxComplete(function(){
			$(this).hide();
		});

		$.ajaxFileUpload
		(
			{
				url:'/doajaxfileupload2.php',
				secureuri:false,
				fileElementId:'fileToUpload2',
				dataType: 'json',
				success: function (data, status)
				{
					//$("#uploadDiv").before(data);
					if(data.path!=""){
						$("#avattar").attr("src",data.path);
						$("#img_path").val(data.path);
						var imagen = "<img src='"+data.path+"' style='max-height:250px;max-width:250px'>";
						$("#preview").html(imagen);
						$("#preview").css({"width":"auto","height":"auto"});
					}
				},
				error: function (data, status, e)
				{
					alert(e);
				}
			}
		)
		
		return false;

	}

function ajaxFileUploadAvattar()
{
	$("#loading")
	.ajaxStart(function(){
		$("#loading").show();
	})
	.ajaxComplete(function(){
		$("#loading").hide();
	});

	$.ajaxFileUpload
	(
		{
			url:'/doajaxfileupload.php',
			secureuri:false,
			fileElementId:'fileToUpload',
			dataType: 'json',
			success: function (data, status)
			{
				if(data.path!=""){
					
					$("#avatar_prev").html("<img src='"+data.path+"' width='100px' height='100px'>");
					$("#img_path").val(data.path);
					alert("El avatar se ha cargado correctamente!");
				}
			},
			error: function (data, status, e)
			{
				mensaje(e);
			}
		}
	)
	if ($.browser.msie){
		if($("input.inputfile").val().length>20){
			$("input.inputfile").val(substr($("input.inputfile").val(),0,20));
		}
		$("input.inputfile").change(function(){
			if($("input.inputfile").val().length>20){
				$("input.inputfile").val(substr($("input.inputfile").val(),0,20));
			}			
		})
	}
	return false;

}
function addFriend(id){
    var datos="_action=serAmigo&id="+id;
    	var date = new Date();
        var timestamp = date.getTime();
        $.ajax({
           type: "POST",
           url: "/main.php?t="+timestamp,
           data: datos,
           beforeSend: function(){
            },
           success: function(msg){
           	var msg2 = msg.split('/');
				if(msg2[0]=="hecho")
					alert("Hemos enviado tu petici&oacute;n de amistad a "+msg2[1]+"!!");
				if(msg2[0]=="noLogged")
					noregMsj();
				if(msg2[0] == "noAceptado")
					alert("Ya has pedido ser su amigo de "+msg2[1]+".");
				if(msg2[0]=="yaAceptado")
					alert("Ya eres amigo de "+msg2[1]+".");
				//else
					//mensaje("No se pudo agregar.");
	       }
        });	
}
function responseFriend(opt,uid){
    var datos="_action=respFriend&opt="+opt+"&uid="+uid;
    	var date = new Date();
        var timestamp = date.getTime();
        $.ajax({
           type: "POST",
           url: "/main.php?t="+timestamp,
           data: datos,
           beforeSend: function(){
            },
           success: function(msg){
				if(parseInt(msg)>0){
					if(opt == 0)
						mensaje("&iexcl;Amistad aceptada! verif&iacute;ca tus nuevos amigos.");
					else
						mensaje("Hecho! La solicitud fu&eacute; eliminada.");
					$("#sol_"+parseInt(msg)).fadeOut('slow');
				}
					
				else
					mensaje("No se pudo realizar.");
	       }
        });		
}
function doComment(){
	if(!comentando){
		if($("#textfield").val()==""){
			mensaje("No puedes enviar un comentario vacio.");
			return;	
		}
    var datos="_action=doComment&seccion="+$("#section").val()+"&comment="+$("#textfield").val()+"&id="+$("#item").val();
    	var date = new Date();
        var timestamp = date.getTime();
        $.ajax({
           type: "POST",
           url: "/main.php?t="+timestamp,
           data: datos,
           beforeSend: function(){
     			comentando = true;
     			$("#img_loading_com").show();
	        },
           success: function(msg){
           	$("#textfield").val("");
           	if(msg=="noSession"){
				noregMsj();
				return;
			}

			if($("#comentarios").html()=="No hay comentarios" || $("#comentarios tr").length==0){
				if($("#nocom"))
					$("#nocom").remove();
				$("#comentarios").html(msg);
				$("#comentarios tr:first").fadeIn('slow');				
			}else{
				$("#comentarios tr:first").before(msg);
				$("#comentarios tr:first").fadeIn('slow');
				if($("#comentarios tr").length>10){
				$("#comentarios tr:last").fadeOut('slow');
				$("#comentarios tr:last").remove();					
				}
				
			}
				comentando = false;
				$("#img_loading_com").hide();
            }
        });	
    }
}
function getThePageComments(p,jq){
		datos = "_action=getCommentsSection&page="+p+"&section="+$("#section").val()+"&itemid="+$("#item").val();
		var date = new Date();
		var timestamp = date.getTime();
		$.ajax({
		   type: "POST",
		   url: "/main.php?t="+timestamp,
		   data: datos,
		   dataType:"json",
		   beforeSend: function(){
			},
		   success: function(data){
			if(data.html!=""){
				$("#comentarios").html(data.html);
				$("#commPagination").show();
				if(p>0)
					$("#prevCom").show();
				else
					$("#prevCom").hide();
				if(data.next)
					$("#nextCom").show();
				else
					$("#prevCom").hide();
				
			}
		  }
		});	
}
function setCommentsPagination(t,nee,ipp){
	 $("#commPagination").pagination(
         t, {
         num_edge_entries: nee,
         items_per_page: ipp,
         prev_text:"Ant.",
         next_text:"Siguiente",
        callback: getThePageComments
        });	
}
function setOption(tid,np,pg,rp){
	$("#tid").val(tid);
	$("#idp").val(np);
	$("#np").val(pg);
	$("#ido").val(rp);
	getTest();
}
function getTest(tid){
	if(!cargando){
	var teid = (parseInt(tid)>0?tid:$("#tid").val());
	np = $("#idp").val();
	pg = $("#np").val();
	rp = $("#ido").val();
	if($("#idp").val()>0 && $("#ido").val()==0){
		mensaje("Debes elegir una opci&oacute;n para continuar.");
		return;
	}
    var datos="_action=getTest&tid="+teid+"&np="+np+"&pg="+pg+"&rp="+rp;
    	var date = new Date();
        var timestamp = date.getTime();
        $.ajax({
           type: "POST",
           url: "/main.php?t="+timestamp,
           data: datos,
           beforeSend: function(){

           	cargando = true;
           	$("#img_loading").fadeIn();
            },
           success: function(msg){
           	cargando = false;
           	$("#img_loading").fadeOut();
           	//$("#opcion1, #opcion2, #opcion3").unbind();
			$("#testDiv").html(msg);
				/*$("#opcion1, #opcion2, #opcion3").click(function(){
					$("#opcion1, #opcion2, #opcion3").removeClass("optSelected");
					$("#opcion1, #opcion2, #opcion3").css('background-image', 'url(images/fondo_boton_test.jpg)');
					$(this).css('background-image', 'url(images/fondo_boton_test_on.jpg)');
					$(this).addClass("optSelected");
				});
				$("#opcion1, #opcion2, #opcion3").mouseover(function(){
					if($(this).css("background-image"))
					$("#opcion1, #opcion2, #opcion3").css('background-image', 'url(images/fondo_boton_test.jpg)');
					$(this).css('background-image', 'url(images/fondo_boton_test_over.jpg)');
				});
				$("#opcion1, #opcion2, #opcion3").mouseout(function(){
					$(".optSelected").css('background-image', 'url(images/fondo_boton_test_on.jpg)');
				});*/

        	//$(document).pngFix();
		}
		});
	}		
}
function setOption2(tid,np,pg,rp){
	$("#tid").val(tid);
	$("#idp").val(np);
	$("#np").val(pg);
	$("#ido").val(rp);
	getTest2();
}
function getTest2(tid){
	if(!cargando){
	var teid = (parseInt(tid)>0?tid:$("#tid").val());
	np = $("#idp").val();
	pg = $("#np").val();
	rp = $("#ido").val();
	if($("#idp").val()>0 && $("#ido").val()==0){
		mensaje("Debes elegir una opci&oacute;n para continuar.");
		return;
	}
    var datos="_action=getTest2&tid="+teid+"&np="+np+"&pg="+pg+"&rp="+rp;
    	var date = new Date();
        var timestamp = date.getTime();
        $.ajax({
           type: "POST",
           url: "/main.php?t="+timestamp,
           data: datos,
           beforeSend: function(){

           	cargando = true;
           	$("#img_loading").fadeIn();
            },
           success: function(msg){
           	cargando = false;
           	$("#img_loading").fadeOut();
           	//$("#opcion1, #opcion2, #opcion3").unbind();
			$("#testDiv").html(msg);

		}
		});
	}		
}

function getHoroscopo(section,val1,val2){
			if(val1=="")
				return;
			datos = "_action=getHoroscopo&section="+section+"&val1="+val1+"&val2="+val2;
			var date = new Date();
			var timestamp = date.getTime();
			$.ajax({
			   type: "POST",
			   url: "/main.php?t="+timestamp,
			   data: datos,
			   dataType:"json",
			   beforeSend: function(){
			   	modalFlowles.showLoading();
				},
			   success: function(data){
			   	modalFlowles.close();
			   	if(section==1){
					$("#horoscopo1").html(data.horoscopo1);
				}
			   	if(section==2){
					$("#horoscopo2").html(data.horoscopo2);
					$("#cid").val(data.cid);
				}	
			  }
			});	
}
function sendHoroscopo(){
			if($("#signoNombre").val()==""){
				mensaje("No has ingresado el nombre.");
				return;				
			}
			if($("#signoMail1").val()==""){
				mensaje("No has ingresado su email.");
				return;				
			}			
			if($("#signoMail2").val()==""){
				mensaje("No has ingresado tu email.");
				return;				
			}
			if($("#cid").val()==""){
				mensaje("No has elegido una combinaci&oacute;n de signos.");
				return;				
			}
			datos = "_action=sendHoroscopo&nombre="+$("#signoNombre").val()+"&mail1="+$("#signoMail1").val()+"&mail2="+$("#signoMail2").val()+"&mensaje="+$("#signoMensaje").val()+"&cid="+$("#cid").val();
			var date = new Date();
			var timestamp = date.getTime();
			$.ajax({
			   type: "POST",
			   url: "/main.php?t="+timestamp,
			   data: datos,
			   beforeSend: function(){
			   	modalFlowles.showLoading();
				},
			   success: function(data){
			   	modalFlowles.close();
					if(data == "noName"){
						mensaje("No has ingresado el nombre.");
						return;
					}
					if(data == "invalid"){
						mensaje("No has elegido una combinaci&oacute;n de signos.");
						return;
					}
					if(data == "invalidMail"){
						mensaje("Email no v&aacute;lido.");
						return;
					}
					if(data == "ok"){
						mensaje("Hecho! El resultado del horoscopo<br> fu&eacute; enviado correctamente.");
						return;
					}
			  }
			});		
}
function setRegalosPagination(t,nee,ipp){
	 $("#regalosPagination").pagination(
         t, {
         num_edge_entries: nee,
         items_per_page: ipp,
         prev_text:"<",
         next_text:">",
        callback: listaDeRegalos
        });	
}
function listaDeRegalos(p,jq){
			var categoria = $("#categoria_regalos").val();
			datos = "_action=getListaDeRegalos&categoria="+categoria+"&page="+p;
			var date = new Date();
			var timestamp = date.getTime();
			$.ajax({
			   type: "POST",
			   url: "/main.php?t="+timestamp,
			   data: datos,
			   dataType:"json",
			   beforeSend: function(){
			   	//modalFlowles.showLoading();
				},
			   success: function(data){
			   	//modalFlowles.close();
				if(!p){
					var select_categoria = "Categoria: <select id='select_categoria'>";
					$.each(data.categorias, function(i,item){
						select_categoria += "<option value='"+item+"'>"+item+"</option>";
					});
					select_categoria += "<option value=''>Todas</option>";
					select_categoria += "</select><br>";
					data.html = select_categoria+data.html;
					data.html+="<br><div id='regalosPagination' class='pagination'></div><br><input type='button' value='Enviar' onclick='enviarRegalo();'>";
					modalFlowles.show("Regalos",data.html);	
					setRegalosPagination(data.max,2,9);
					if(categoria)
						$("#select_categoria").val(categoria);0
					$("#select_categoria").change(function(){
						$("#categoria_regalos").val($(this).val());
						listaDeRegalos();
					});		
				}else{
					$("#regalos").html(data.html);
				}

			  }
			});		
}
function enviarRegalo(){
	if($("input[name=regalo]:checked").length==0) return;
	var rid = 0;
	$("input[name=regalo]:checked").each(function(){
		rid = $(this).val();
	})

			datos = "_action=doEnviarRegalo&to="+$("#itemID").val()+"&rid="+rid+"&texto="+$("#textoregalo").val();
			var date = new Date();
			var timestamp = date.getTime();
			$.ajax({
			   type: "POST",
			   url: "/main.php?t="+timestamp,
			   data: datos,
			   //dataType:"json",
			   beforeSend: function(){
			   	//modalFlowles.showLoading();
				},
			   success: function(data){
			   	//modalFlowles.close();
			   	if(data == "noSession"){
					mensaje("Debes loguearte primero.")
				}
				if(data == "OK"){
					mensaje("El regalo fu&eacute; enviado!")
				}
			  }
			});	
}
function agregarAFavoritos(uid){
			datos = "_action=addFavourites&uid="+uid;
			var date = new Date();
			var timestamp = date.getTime();
			$.ajax({
			   type: "POST",
			   url: "/main.php?t="+timestamp,
			   data: datos,
			   //dataType:"json",
			   beforeSend: function(){
			   	//modalFlowles.showLoading();
				},
			   success: function(data){
			   	//modalFlowles.close();
			   	if(data == "yaAgregado"){
					mensaje("Ya has agregado a este usuario como favorito.")
				}	
			   	if(data == "noSession"){
					mensaje("Debes loguearte primero.")
				}
			   	if(data == "OK"){
					mensaje("Ha sido agregado a tus favoritos.")
				}	
			  }
			});	
}
function addRegMue(){
			datos = "_action=doAddEmail&email="+$("#email").val()+"&opt="+$("#opt").val();
			var date = new Date();
			var timestamp = date.getTime();
			$.ajax({
			   type: "POST",
			   url: "/main.php?t="+timestamp,
			   data: datos,
			   //dataType:"json",
			   beforeSend: function(){
				},
			   success: function(data){
					if(data == "OK"){
						if($("#opt").val() == 1)
							mensaje("Pronto te contactaremos.");
						else
							mensaje("Gracias por participar, en breve ser&aacute;s contactada.");
						setTimeout(function(){
							location.href = "/teaser/";
						}, 5000);	
					}
					if(data == "invalidEmail"){
						mensaje("El email ingresado no es v&aacute;lido!");
					}
					if(data == "yaExiste"){
						if($("#opt").val() == 1){
							mensaje("Ya est&aacute;s registrado!");
						}
						else
							mensaje("Ya est&aacute;s participando!");						
					}
			  }
			});	
}

function setStatus(){
	var estado = $("#estado_animo").val();
			datos = "_action=setStatus&estado="+estado;
			var date = new Date();
			var timestamp = date.getTime();
			$.ajax({
			   type: "POST",
			   url: "/main.php?t="+timestamp,
			   data: datos,
			   //dataType:"json",
			   beforeSend: function(){
			   //	modalFlowles.showLoading();
				},
			   success: function(data){
			   	//modalFlowles.close();
			   	if(data == "OK"){
					$("#estadodeanimo2").html(estado+"&nbsp;<a href='javascript:editStatus();'>Editar</a>");
				}
				$("#estadodeanimo2").show();
				$("#estadodeanimo").hide();	
			  }
			});
}
function pedirMuestra(){
			if($("#nombre").val()=="" || $("#nombre").val()=="Nombre"){
				mensaje("Debes completar el campo 'Nombre'.");
				return;
			}
			if($("#apellido").val()=="" || $("#apellido").val()=="Apellido"){
				mensaje("Debes completar el campo 'Apellido'.");
				return;
			}
			if($("#email").val()=="" || $("#email").val()=="Correo Electr&oacute;nico"){
				mensaje("Debes completar el campo 'Correo Electr&oacute;nico'.");
				return;
			}
			if($("#calle").val()=="" || $("#calle").val()=="Calle"){
				mensaje("Debes completar el campo 'Calle'.");
				return;
			}
			if(isNaN(parseInt($("#numeroexterior").val()))){
				mensaje("Debes completar el campo 'N&uacute;mero Exterior'.");
				return;
			}
			if(isNaN(parseInt($("#numerointerior").val()))){
				mensaje("Debes completar el campo 'N&uacute;mero Interior'.");
				return;
			}
			if($("#ciudad").val()=="" || $("#ciudad").val()=="Ciudad"){
				mensaje("Debes completar el campo 'Ciudad'.");
				return;
			}
			if($("#estado").val()=="" || $("#estado").val()=="Estado"){
				mensaje("Debes completar el campo 'Estado'.");
				return;
			}
			if(isNaN(parseInt($("#codigopostal").val()))){
				mensaje("Debes completar el campo 'C&oacute;digo Postal'.");
				return;
			}
			if($("#telefono").val()=="" || $("#telefono").val()==$("#telefono").attr("title")){
				mensaje("Debes completar el campo 'Tel&eacute;fono'.");
				return;
			}
			if($("#colonia").val()=="" || $("#colonia").val()==$("#colonia").attr("title")){
				mensaje("Debes completar el campo 'Colonia'.");
				return;
			}
			datos = "_action=pedirMuestra&nombre="+$("#nombre").val()+"&apellido="+$("#apellido").val()+"&email="+$("#email").val()+"&calle="+$("#calle").val()+"&nume="+$("#numeroexterior").val()+"&numi="+$("#numerointerior").val()+"&colonia="+$("#colonia").val()+"&ciudad="+$("#ciudad").val()+"&estado="+$("#estado").val()+"&cp="+$("#codigopostal").val()+"&telefono="+$("#telefono").val();
			var date = new Date();
			var timestamp = date.getTime();
			$.ajax({
			   type: "POST",
			   url: "/main.php?t="+timestamp,
			   data: datos,
			   //dataType:"json",
			   beforeSend: function(){
			   	//modalFlowles.showLoading();
				},
			   success: function(data){
			   	//modalFlowles.close();
			   		if(data  == "yaExisteEmail"){
						mensaje("Ya te encuentras registrad@ para solicitar tu muestra");
					}
					if(data == "invalidEmail"){
						mensaje("El email ingresado no es v&aacute;lido!");
					}
					if(data == "OK"){
						mensaje("Ahora ya te encuentras registrada!");
					}
			  }
			});
			return false;
}
function getFavoritosPage(p,jq){
			datos = "_action=getFavoritos&page="+p;
			var date = new Date();
			var timestamp = date.getTime();
			$.ajax({
			   type: "POST",
			   url: "/main.php?t="+timestamp,
			   data: datos,
			   //dataType:"json",
			   beforeSend: function(){
			   //	modalFlowles.showLoading();
				},
			   success: function(data){
			   	$("#listaFavoritos").html(data);
			   	//modalFlowles.close();
	
			  }
			});	
}
function getcompatiblesPage(p,jq){
			datos = "_action=getCompatibles&page="+p;
			var date = new Date();
			var timestamp = date.getTime();
			$.ajax({
			   type: "POST",
			   url: "/main.php?t="+timestamp,
			   data: datos,
			   //dataType:"json",
			   beforeSend: function(){
			   	//modalFlowles.showLoading();
				},
			   success: function(data){
			   	$("#listaCompatibles").html(data);
			   	//modalFlowles.close();
	
			  }
			});	
}
function getComPriPage(p,jq){
			datos = "_action=getComPriPage&page="+p+"&section=comentarios_privados&item="+$("#itemID").val()+"&opd="+$("#opd").val();
			var date = new Date();
			var timestamp = date.getTime();	
			$.ajax({
			   type: "POST",
			   url: "/main.php?t="+timestamp,
			   data: datos,
			   //dataType:"json",
			   beforeSend: function(){
			   	//modalFlowles.showLoading();
				},
			   success: function(data){
			   	$("#privateComs").html(data);
				/*$(".comClass").mouseover(function(){
					$("#comid_"+$(this).attr("locid")).fadeIn(200);
				})
				$(".comClass").mouseout(function(){
					$(".deleteMsj").hide();
				})*/
	
			  }
			});		
}
function getComPubPage(p,jq){
			datos = "_action=getComPubPage&page="+p+"&section=perfil_publicos&item="+$("#itemID").val()+"&opd="+$("#opd").val();
			var date = new Date();
			var timestamp = date.getTime();
			$.ajax({
			   type: "POST",
			   url: "/main.php?t="+timestamp,
			   data: datos,
			   //dataType:"json",
			   beforeSend: function(){
			   	//modalFlowles.showLoading();
				},
			   success: function(data){
			   	$("#mimuro").html(data);
				/*$(".comClass").mouseover(function(){
					$("#comid_"+$(this).attr("locid")).fadeIn(200);
				})
				$(".comClass").mouseout(function(){
					$(".deleteMsj").hide();
				})*/
	
			  }
			});		
}
function getPerPubPage(p,jq){
			datos = "_action=getComPubPage&page="+p+"&section=perfil_publicos&item="+$("#itemID").val()+"&opd="+$("#opd").val();
			var date = new Date();
			var timestamp = date.getTime();
			$.ajax({
			   type: "POST",
			   url: "/main.php?t="+timestamp,
			   data: datos,
			   //dataType:"json",
			   beforeSend: function(){
			   	//modalFlowles.showLoading();
				},
			   success: function(data){
			   	$("#murolista").html(data);
				/*$(".comClass").mouseover(function(){
					$("#comid_"+$(this).attr("locid")).fadeIn(200);
				})
				$(".comClass").mouseout(function(){
					$(".deleteMsj").hide();
				})*/
	
			  }
			});	
}
function comentar(section){
	if($("#textoCom").val() == ""){
		mensaje("Debes escribir un comentario.");
		return;
	}
			datos = "_action=comentar&section="+section+"&texto="+$("#textoCom").val()+"&item="+$("#itemID").val();
			var date = new Date();
			var timestamp = date.getTime();
			$.ajax({
			   type: "POST",
			   url: "/main.php?t="+timestamp,
			   data: datos,
			   //dataType:"json",
			   beforeSend: function(){
			   	//modalFlowles.showLoading();
				},
			   success: function(data){
			   	if(section == "perfil_publicos"){
					getPerPubPage(0,"");
				}
			   	if(section == "comentarios_publicos"){
					getComPubPage(0,"");
				}
			   	if(section == "comentarios_privados"){
					getComPriPage(0,"");
				}
				$("#textoCom").val("");
				if(data == "noSession"){
					mensaje('Debes loguearte para comentar.');
				}
				if(data == "OK"){
					mensaje("El comentario fu&eacute; enviado!");
				}
			  }
			});		
}
function is_numeric(input){
	return typeof(input)=='number';
}

function doQuickRegister(){
	if(!$("#tyc").is(":checked")){
		mensaje('Debes aceptar los t&eacute;rminos y condiciones.');
		return;
	}

	/*if(!is_numeric($("input[name=entre]").val()) || !is_numeric($("input[name=edady]").val())){
		mensaje('Tienes que ingresar la edad de tus futur@s candidat@s.');
		return;		
	}*/
	var tlibre = new Array();
	$("input[name=checks_tlibre]").each(function(){
		if($(this).attr("checked") == true){
			tlibre.push($(this).val());
		}
	})
	var compart = new Array();
	var flag = false;
	$("input[name=checks_compartir]").each(function(){
		if($(this).attr("checked") == true){
			compart.push($(this).val());
			flag = true;
		}
	})
	if(flag == false){
		mensaje('El campo "Con una pareja deseo..." es obligatorio.');
		return;		
	}
			var usr = $("#usuario_reg").val();
			var pss = $("#password_reg").val();
			var eml = $("#email_reg").val();
			var edd = $("input[name=edad]").val();
			var etr = $("input[name=entre]").val();
			var ety = $("input[name=edady]").val();
			var sex = $("input[name=sexo]").val();
			if(sex == ""){
				mensaje('El campo "Sexo" es obligatorio.');
				return;					
			}			
			var bus = $("input[name=busco]").val();
			var est = $("input[name=estado]").val();
			var eci = $("input[name=ecivil]").val();
			var ciu = $("#ciudad").val();
			var ipt = $("#img_path").val();
			var coj = $("input[name=cojos]").val();
			var cpe = $("input[name=cpelo]").val();
			var ett = $("input[name=estatura]").val();
			var tfi = $("input[name=tfisico]").val();
			var pes = $("input[name=peso]").val();
			var rel = $("input[name=religion]").val();
			var tom = $("input[name=tomas]").val();
			var fum = $("input[name=fumas]").val();
			var etu = $("input[name=estudios]").val();
			var pro = $("input[name=profesion]").val();
			if(pro == "Profesi&oacute;n"){
				pro = "Sin respuesta";
			}
			var sig = $("input[name=signo]").val();
			var pde = $("input[name=pdeportes]").val();
			//var tli = $("input[name=tiempolibre]").val();
			var tli = tlibre.join(', ');
			//var com = $("input[name=compartir]").val();
			var com = compart.join(', ');
			var alg = $("#algomas").val();
			datos = "_action=doRegister&quick=true&usuario_reg="+usr+"&password_reg="+pss+"&email_reg="+eml+"&edad="+edd+"&entre="+etr+"&edady="+ety+"&sexo="+sex+"&busco="+bus+"&estado="+est+"&ecivil="+eci+"&ciudad="+ciu+"&img_path="+ipt+"&cojos="+coj+"&cpelo="+cpe+"&estatura="+ett+"&tfisico="+tfi+"&peso="+pes+"&religion="+rel+"&tomas="+tom+"&fumas="+fum+"&estudios="+etu+"&profesion="+pro+"&signo="+sig+"&pdeportes="+pde+"&tiempolibre="+tli+"&compartir="+com+"&algomas="+alg;
			if(usr == ""){
				mensaje("Debes introducir un nombre de usuario.");
				return;
			}
			if(pss == ""){
				mensaje("Debes introducir una contrase&ntilde;a.");
				return;
			}
			if(eml == ""){
				mensaje("Debes introducir una direcci&oacute;n de email.");
				return;
			}
			var date = new Date();
			var timestamp = date.getTime();
			$.ajax({
			   type: "POST",
			   url: "/main.php?t="+timestamp,
			   data: datos,
			   //dataType:"json",
			   beforeSend: function(){
			   	//modalFlowles.showLoading();
				},
			   success: function(data){
			   	if(data == "invalidEmail"){
					mensaje("El email introducido no es v&aacute;lido.");
				}
			   	if(data == "isUser"){
					mensaje("<b>"+usr+"</b> ya est&aacute; siendo usado.");
				}
				if(data =="noEdad"){
					mensaje('Tienes que ingresar la edad de tus futur@s candidat@s.');
				}			
			   	//modalFlowles.close();
				if(data == "OK"){
					mensaje("<b>"+usr+"</b> ya est&aacute;s registrad@!");
					setTimeout(function(){location.href="/personal/"}, 5000);
				}
			  }
			});	
}
function doQuickRegisterEdit(){
	var tlibre = new Array();
	$("input[name=checks_tlibre]").each(function(){
		if($(this).attr("checked") == true){
			tlibre.push($(this).val());
		}
	})
	var compart = new Array();
	var flag = false;
	$("input[name=checks_compartir]").each(function(){
		if($(this).attr("checked") == true){
			compart.push($(this).val());
			flag = true;
		}
	})
	if(flag == false){
		mensaje('El campo "Con una pareja deseo..." es obligatorio.');
		return;		
	}	
			var usr = $("#usuario_reg").val();
			var pss = $("#password_reg").val();
			var eml = $("#email_reg").val();
			var edd = $("input[name=edad]").val();
			var etr = $("input[name=entre]").val();
			var ety = $("input[name=edady]").val();
			var sex = $("input[name=sexo]").val();
			if(sex == ""){
				mensaje('El campo "Sexo" es obligatorio.');
				return;					
			}
			var bus = $("input[name=busco]").val();
			var est = $("input[name=estado]").val();
			var eci = $("input[name=ecivil]").val();
			var ciu = $("#ciudad").val();
			var ipt = $("#img_path").val();
			var coj = $("input[name=cojos]").val();
			var cpe = $("input[name=cpelo]").val();
			var ett = $("input[name=estatura]").val();
			var tfi = $("input[name=tfisico]").val();
			var pes = $("input[name=peso]").val();
			var rel = $("input[name=religion]").val();
			var tom = $("input[name=tomas]").val();
			var fum = $("input[name=fumas]").val();
			var etu = $("input[name=estudios]").val();
			var pro = $("input[name=profesion]").val();
			var sig = $("input[name=signo]").val();
			var pde = $("input[name=pdeportes]").val();
			//var tli = $("input[name=tiempolibre]").val();
			var tli = tlibre.join(', ');
			//var com = $("input[name=compartir]").val();
			var com = compart.join(', ');
			var alg = $("#algomas").val();
			datos = "_action=doRegisterEdit&quick=true&usuario_reg="+usr+"&password_reg="+pss+"&email_reg="+eml+"&edad="+edd+"&entre="+etr+"&edady="+ety+"&sexo="+sex+"&busco="+bus+"&estado="+est+"&ecivil="+eci+"&ciudad="+ciu+"&img_path="+ipt+"&cojos="+coj+"&cpelo="+cpe+"&estatura="+ett+"&tfisico="+tfi+"&peso="+pes+"&religion="+rel+"&tomas="+tom+"&fumas="+fum+"&estudios="+etu+"&profesion="+pro+"&signo="+sig+"&pdeportes="+pde+"&tiempolibre="+tli+"&compartir="+com+"&algomas="+alg;
			if(usr == ""){
				mensaje("Debes introducir un nombre de usuario.");
				return;
			}
			if(pss == ""){
				mensaje("Debes introducir una contrase&ntilde;a.");
				return;
			}
			if(eml == ""){
				mensaje("Debes introducir una direcci&oacute;n de email.");
				return;
			}
			var date = new Date();
			var timestamp = date.getTime();
			$.ajax({
			   type: "POST",
			   url: "/main.php?t="+timestamp,
			   data: datos,
			   //dataType:"json",
			   beforeSend: function(){
			   	//modalFlowles.showLoading();
				},
			   success: function(data){
			   	if(data == "invalidEmail"){
					mensaje("El email introducido no es v&aacute;lido.");
				}
			   	if(data == "isUser"){
					mensaje("<b>"+usr+"</b> ya est&aacute; siendo usado.");
				}				
			   	//modalFlowles.close();
				if(data == "OK"){
					mensaje("<b>"+usr+"</b>, tu perfil se actualiz&oacute; correctamente!");
					setTimeout(function(){location.href="/perfil/"}, 5000);
				}
			  }
			});	
}
function substr( f_string, f_start, f_length ) {
    // http://kevin.vanzonneveld.net
    // +     original by: Martijn Wieringa
    // +     bugfixed by: T.Wild
    // +      tweaked by: Onno Marsman
    // *       example 1: substr('abcdef', 0, -1);
    // *       returns 1: 'abcde'
    // *       example 2: substr(2, 0, -6);
    // *       returns 2: ''
 
    f_string += '';
 
    if(f_start < 0) {
        f_start += f_string.length;
    }
 
    if(f_length == undefined) {
        f_length = f_string.length;
    } else if(f_length < 0){
        f_length += f_string.length;
    } else {
        f_length += f_start;
    }
 
    if(f_length < f_start) {
        f_length = f_start;
    }
 
    return f_string.substring(f_start, f_length);
}
function getRegalosPage(p,jq){
			datos = "_action=getAjaxRegalos&page="+p+"&item="+$("#itemID").val();
			var date = new Date();
			var timestamp = date.getTime();
			$.ajax({
			   type: "POST",
			   url: "/main.php?t="+timestamp,
			   data: datos,
			   //dataType:"json",
			   beforeSend: function(){
			   	//modalFlowles.showLoading();
				},
			   success: function(data){
			   	$("#ajaxRegalos").html(data);
			   	//modalFlowles.close();
			   	$(".img_regalos").lightBox();
	
			  }
			});		
}
function getCitasPage(p,jq){
			citaspage = p;
			datos = "_action=getAjaxEventos&page="+p+"&item="+$("#itemID").val();
			var date = new Date();
			var timestamp = date.getTime();
			$.ajax({
			   type: "POST",
			   url: "/main.php?t="+timestamp,
			   data: datos,
			   //dataType:"json",
			   beforeSend: function(){
			   	//modalFlowles.showLoading();
				},
			   success: function(data){
			   	$("#ajaxEventos").html(data);
			   	//modalFlowles.close();
				$(".toolt").tooltip({showURL: false});
			  }
			});	
}
function getGalPage(p,jq){
			datos = "_action=getAjaxGal&page="+p+"&item="+$("#item").val();
			var date = new Date();
			var timestamp = date.getTime();
			$.ajax({
			   type: "POST",
			   url: "/main.php?t="+timestamp,
			   data: datos,
			   //dataType:"json",
			   beforeSend: function(){
			   	//modalFlowles.showLoading();
				},
			   success: function(data){
			   	$("#ulfotos").html(data);
			   	//modalFlowles.close();
				refreshGaleria();
			  }
			});	
}
function doInvitar(){
			datos = "_action=doInvitalo&email="+$("#email").val();
			var date = new Date();
			var timestamp = date.getTime();
			$.ajax({
			   type: "POST",
			   url: "/main.php?t="+timestamp,
			   data: datos,
			   //dataType:"json",
			   beforeSend: function(){
			   	//modalFlowles.showLoading();
				},
			   success: function(data){
			   	if(data == "OK"){
					mensaje("L@ has invitado correctamente!");
				}
			   	if(data == "invalidEmail"){
					mensaje("El email introducido no es v&aacute;lido.");
				}
	
			  }
			});	
}
function doResetPass(){
	if($("#mail").val()==""){
		mensaje("Debes ingresar tu correo.");
		return;
	}
		datos = "_action=resetPass&email="+$("#mail").val();
		var date = new Date();
		var timestamp = date.getTime();
		$.ajax({
		   type: "POST",
		   url: "/main.php?t="+timestamp,
		   data: datos,
		   beforeSend: function(){
		   	//modalFlowles.showLoading();
			},
		   success: function(data){
		   //	modalFlowles.close();
				if(data == "noValid"){
					mensaje('El correo ingresado no existe en el sitio.');
				}
				if(data == "OK"){
					mensaje('Tus datos fueron enviados a tu correo.');
				}

		  }
		});	
}
function addResponderForm(uid,section,id,obj){
 var html = '<div id="divr_'+id+'"><p class="presponse"><textarea rows="4" cols="58" id="textoCom_'+id+'" class="tresponse"></textarea></p><a href="javascript:void(0)"><img src="images/personal/responde.jpg" alt="Responde" onclick="responseComm('+id+');"/></a><input type="hidden" id="uidresp_'+id+'" value="'+uid+'"><input type="hidden" id="sectionresp_'+id+'" value="'+section+'"><p class="muroresponder"><a href=\'javascript:cancelarResp("'+id+'","'+section+'","'+id+'");\'>Cancelar</a></p></div>';
 	$(obj).parent().html(html);
	$(obj).remove(); 
	if(section == "comentarios_privados")
		$("#divr_"+id).css("margin-top","50px");
}
function cancelarResp(uid,section,id){
$("#divr_"+id).parent().html("<p class='muroresponder'><a href='javascript:void(0)' onclick=\"addResponderForm('"+uid+"','"+section+"','"+id+"',this);\">Responder</a></p>");	
}
function responseComm(id){
	$("#modalContent").css("top","50%");
	var uid = $("#uidresp_"+id).val();
	var section = $("#sectionresp_"+id).val();
	var texto = $("#textoCom_"+id).val();
	if(texto == ""){
		mensaje("Debes ingresar un comentario.");
		return;
	}
		datos = "_action=responderCom&uid="+uid+"&id="+id+"&section="+section+"&texto="+texto;
		var date = new Date();
		var timestamp = date.getTime();
		$.ajax({
		   type: "POST",
		   url: "/main.php?t="+timestamp,
		   data: datos,
		   beforeSend: function(){
		   	//modalFlowles.showLoading();
			},
		   success: function(data){
		   //	modalFlowles.close();
		   
				if(data == "OK"){
					mensaje('Tu comentario fu&eacute; enviado correctamente.');
					$("#divr_"+id).parent().html("<p class='muroresponder'><a href='javascript:void(0)' onclick=\"addResponderForm('"+uid+"','"+section+"','"+id+"',this);\">Responder</a></p>");
				}
				if(data == "noSession"){
					mensaje('Debes loguearte para comentar.');
				}


		  }
		});
}
function showPrivado(){
	$("#compriv").show();
	$("#textoCom_Privado").val("").focus();
}
function cancelPrivado(){
	$("#compriv").hide();
}
function comPrivado(uid){
	var texto = $("#textoCom_Privado").val();
	if(texto == ""){
		mensaje("Debes ingresar un comentario.");
		return;
	}
	var section = "comentarios_privados";
		datos = "_action=comPrivado&uid="+uid+"&section="+section+"&texto="+texto;
		var date = new Date();
		var timestamp = date.getTime();
		$.ajax({
		   type: "POST",
		   url: "/main.php?t="+timestamp,
		   data: datos,
		   beforeSend: function(){
		   	//modalFlowles.showLoading();
			},
		   success: function(data){
		   //	modalFlowles.close();
		   		if(data == "noSession"){
					mensaje('Debes loguearte para comentar.');
				}
				if(data == "OK"){
					mensaje('Tu comentario fu&eacute; enviado correctamente.');
					cancelPrivado();
				}

		  }
		});
}
function agregarCita(){
			datos = "_action=addCita&invitado="+$("#parausuario").val()+"&fecha="+$("#fechac").val()+"&texto="+$("#agregarunacita").val();
			var date = new Date();
			var timestamp = date.getTime();
			$.ajax({
			   type: "POST",
			   url: "/main.php?t="+timestamp,
			   data: datos,
			   //dataType:"json",
			   beforeSend: function(){
				},
			   success: function(data){
			   	$("#modalContent").css("top","140%");
				if(data == "noUser"){
					mensaje("El usuario elegido no existe!");
				}
				if(data == "noFecha"){
					mensaje("La fecha ingresada no es v&aacute;lida!");
				}
				if(data == "OK"){
					mensaje("La cita se agreg&oacute; correctamente!");
					getCitasPage(citaspage,"");
				}
			  }
			});	
}
function getUsuariosSearch(p,jq){
			datos = "_action=resultadoBusqueda&usuario="+$("#usuario").val()+"&email="+$("#email").val()+"&edad1="+$("#edadmin").val()+"&edad2="+$("#edadmax").val()+"&quesea="+$("input[name=quesea]").val()+"&interesadoen="+$("input[name=interesadoen]").val()+"&quevivaen="+$("input[name=quevivaen]").val()+"&page="+p;
			var date = new Date();
			var timestamp = date.getTime();
			$.ajax({
			   type: "POST",
			   url: "/main.php?t="+timestamp,
			   data: datos,
			   dataType:"json",
			   beforeSend: function(){
				},
			   success: function(data){
			   	$("#resultadoBusqueda").html(data.html);
			   	if(p == 0 && data.total >9){
				$("#pagBusqueda").pagination(
				         data.total, {
				         num_edge_entries: 2,
				         items_per_page: 9,
				         prev_text:"Ant.",
				         next_text:"Siguiente",
				        callback: getUsuariosSearch
				        });	
						$('.current.prev, current.next').hide();$("#pagBusqueda").show();					
				 if($.browser.mozilla)
 					$("#pagBusqueda").css("position","inherit");
				}
				if(data.total < 10){
					$("#pagBusqueda").hide();
				}
			  }
			});		
}
function watchVideo(dir,alta){
			if(alta == "1"){
				var getAlta = "&alta=1";
				var wvid = 585;
				var hvid = 309;
			}else{
				var getAlta = "";
				var wvid = 418;
				var hvid = 212;
			}
			datos = "_action=getVideo&dir="+dir+"&vid="+$("#vid").val()+getAlta;
			var date = new Date();
			var timestamp = date.getTime();
			$.ajax({
			   type: "POST",
			   url: "/main.php?t="+timestamp,
			   data: datos,
			   dataType:"json",
			   beforeSend: function(){
			   	$("#videoContent").html("<div style='color:#ffffff;text-align:center;width:418px;height:212px;background:#000000'><img src='images/ajax-loader.gif' width='32' height='32' /><br>Cargando...</div>");
				},
			   success: function(data){
					$("#videoContainer").html("<div id='videoPlay' />");
					var flashvars = {};
					flashvars.allowFullScreen = true;
					var params = {};
					params.allowFullScreen = true;
					
				   swfobject.embedSWF("reproductores/player.swf?&video=videos/"+data.archivo, "videoPlay", wvid, hvid, "9.0.0", "", flashvars, params);
				   if(data.md == 1){
					   $("#vid").val(data.vid);
					   $("#titulov").html(data.titulo+'<br /><b><span id="subtitulov">'+data.subtitulo+'</span></b>');
					   //$("#subtitulov").html(data.subtitulo);
					   $("#pievideo").html(data.descripcion);
					  // $("#protagonistas").load("/video.protagonistas.html");
					  	$("#protagonistas").css("visibility","visible");				
				   }else{
					   $("#vid").val(data.vid);
					   $("#titulov").html("");
					   //$("#subtitulov").html("");
					   $("#pievideo").html("");
					   $("#protagonistas").css("visibility","hidden");
					   //$("#protagonistas").html("");				
				   }
				   $("#fder").unbind('click');
				   $("#fizq").unbind('click');
				   if(data.next == 1){
						   $("#fder").click(function(){
								watchVideo(1,alta);
						   });
				   }else{
						   $("#fder").click(function(){
								watchVideo(1,alta);
						   });					
				   }
				   if(data.prev == 1){
						   $("#fizq").click(function(){
								watchVideo(0,alta);
						   });	
					//$("#fizq").css("visibility","visible");
						}
				   else{
						   $("#fizq").click(function(){
								watchVideo(0,alta);
						   });	
					//$("#fizq").css("visibility","hidden");
				}
				   
				   						   	

			  }
			});		
}
var modalVids = {
	position: 0,
	secondsDelay: 10,
	tipoModal: 'normal',
	isOpen: 'false',
	show: function (titulo, texto,delay,w,h) {
		if ($("#modalVideo").is(":visible")) {
		
			$("#modalContainer2").hide();
			$("#modalVideo").hide();
		
			modalVids.isOpen = false;			
		}
		
		modalVids.tipoModal = 'normal';
		$("#modalVideo_msj").html(texto);
		
		$("#modalVideo_title").text(titulo);
		if (jQuery.browser.msie){
			$("#modalContainer2").show();			
			$("#modalContainer2").css('opacity', '0.8').css('filter', 'alpha(opacity = 50)');
		}
		else
		{
			$("#modalContainer2").fadeIn();
		}
		$("#modalVideo").show();
		modalVids.isOpen=true;
		if(delay){
			setTimeout(function(){
				modalVids.close();
			}, delay);			
		}
		    var flashvars = {};
			flashvars.allowFullScreen = true;
			var params = {};
			params.allowFullScreen = true;
		   swfobject.embedSWF("reproductores/player.swf?&video=videos/7 DAYS CON MONEY-BACK.flv", "playerModal", "340", "245", "9.0.0", "", flashvars, params);
		$("#modalContent").css("top",lastyclick);
		$("#modalContainer").css({"width":docW,"height":docH,"margin-left":"0px"});
	},
	close: function () {
		$("#playerModal").html("");
		if (!$("#modalVideo").is(":visible")) return;
		$("#modalContainer2").fadeOut(100);
		$("#modalVideo").fadeOut(100);
		modalVids.isOpen = false;	
	}
}
var modalFlexible = {
	position: 0,
	secondsDelay: 10,
	tipoModal: 'normal',
	isOpen: 'false',
	show: function (titulo, texto,delay,optionModal) {
		if ($("#modal_flexible").is(":visible")) {
		
			$("#modalContainer").hide();
			$("#modal_flexible").hide();
		
			modalFlexible.isOpen = false;			
		}
		
		modalFlexible.tipoModal = 'normal';
		$("#modal_flexible_content").html(texto);
		if (jQuery.browser.msie){
			$("#modalContainer").show();			
			$("#modalContainer").css('opacity', '0.8').css('filter', 'alpha(opacity = 50)');
		}
		else
		{
			$("#modalContainer").fadeIn();
		}
		$("#modal_flexible").show();
		modalFlexible.isOpen=true;
		if(delay){
			setTimeout(function(){
				modalFlexible.close();
			}, delay);			
		}
		if(optionModal == 2){
			$("#modal_flexible").css("top",lastyclick);
			if($.browser.msie && $.browser.version < 7){
				$("#link_cerrar_horos").css("margin-top","45px");
				$("#modal_flexible, #modalContainer").click(function(){
					modalFlexible.close();
				})	
			}
		}else{
			$("#modal_flexible").css("top",(lastyclick-500));
			if($.browser.msie && $.browser.version < 7){
				$("#link_cerrar_horos").css("margin-top","45px");
				$("#modal_flexible, #modalContainer").click(function(){
					modalFlexible.close();
				})
			}
		}
		$(document).pngFix();
		
		$("#modalContainer").css({"width":docW,"height":docH,"margin-left":"0px"});
	},
	close: function () {
		if (!$("#modal_flexible").is(":visible")) return;
		$("#modalContainer").fadeOut(100);
		$("#modal_flexible").fadeOut(100);
		modalFlexible.isOpen = false;	
	}
}
function videoModal(id){
	modalVids.show("titulo","algo");
}
function cerrarVideo(){
	modalVids.close();
	$("#playerModal").remove();
	$("#modalVideo").append("<div id='playerModal' />");
}
function busquedaTodos(){
	$("input").val("");
	getUsuariosSearch(0,"");
}
function getTheCouncils(p,jq){
		datos = "_action=getConsejos&page="+p;
		var date = new Date();
		var timestamp = date.getTime();
		$.ajax({
		   type: "POST",
		   url: "/main.php?t="+timestamp,
		   data: datos,
		   beforeSend: function(){
			},
		   success: function(data){
			$("#divConsejos").html(data);
		  }
		});	
}
function makeCouncil(){
	if($("#pregunta").val() == ""){
		mensaje("Debes ingresar una pregunta!");
		return;
	}
		datos = "_action=makeCouncil&pregunta="+$("#pregunta").val();
		var date = new Date();
		var timestamp = date.getTime();
		$.ajax({
		   type: "POST",
		   url: "/main.php?t="+timestamp,
		   data: datos,
		   beforeSend: function(){
			},
		   success: function(data){
		   		if(data == "noSession"){
					mensaje('Debes loguearte para pedir consejos.');
				}
				if(data == "OK"){
					mensaje('Tu pregunta se agreg&oacute; correctamente.');
					$("#pregunta").val("");
				}
		  }
		});		
}
function getComConsejos(p,jq){
		datos = "_action=getComPubPage&page="+p+"&section=comentarios_consejos&item="+$("#itemID").val();
		var date = new Date();
		var timestamp = date.getTime();
		$.ajax({
		   type: "POST",
		   url: "/main.php?t="+timestamp,
		   data: datos,
		   beforeSend: function(){
			},
		   success: function(data){
			$("#murolista").html(data);
		  }
		});		
}
function getHoroscopoInfo(signo1,signo2){
		datos = "_action=getHoroscopoInfo&signo1="+signo1+"&signo2="+signo2;
		var date = new Date();
		var timestamp = date.getTime();
		$.ajax({
		   type: "POST",
		   url: "/main.php?t="+timestamp,
		   data: datos,
		   beforeSend: function(){
			},
		   success: function(data){
		   	if(signo2 != undefined)
				modalFlexible.show("",data,0,1);
			else
				modalFlexible.show("",data,0,2);
		  }
		});		
}
function getHoroscopoInfo2(){
	getHoroscopoInfo($("input[name=tueres]").val(),$("input[name=eles]").val());
}
function isLogged(action){
		datos = "_action=isLogged";
		var date = new Date();
		var timestamp = date.getTime();
		$.ajax({
		   type: "POST",
		   url: "/main.php?t="+timestamp,
		   data: datos,
		   beforeSend: function(){
			},
		   success: function(data){
		   	if(data > 0)
		   		eval(action);
		   	else
		   		mensaje('Debes loguearte para pedir una muestra.');
		   		$("#modalContent").css("top","800px");
		  }
		});		
}
function goIsLogged(url){
	isLogged('location.href="'+url+'";');
}
function deleteEvent(id){
	if(confirm("Seguro deseas borrar esta cita?")){
			datos = "_action=deleteEvent&id="+id;
			var date = new Date();
			var timestamp = date.getTime();
			$.ajax({
			   type: "POST",
			   url: "/main.php?t="+timestamp,
			   data: datos,
			   beforeSend: function(){
				},
			   success: function(data){
			   	if(data == "OK"){
					getCitasPage(0,"");
					mensaje('La cita ha sido borrada!');
				}
			   	if(data == "noValido")
			   		mensaje('Debes loguearte para borrar citas.');
			  }
			});	
	}	
}
function delMjs(id,section){
	if(confirm("Seguro deseas borrar el mensaje?")){
			datos = "_action=delMsj&id="+id;
			var date = new Date();
			var timestamp = date.getTime();
			$.ajax({
			   type: "POST",
			   url: "/main.php?t="+timestamp,
			   data: datos,
			   beforeSend: function(){
				},
			   success: function(data){
			   	if(data == "OK"){
			   		if(section == "comentarios_privados")
			   			getComPriPage(0,"");
			   		if(section == "perfil_publicos"){
						getPerPubPage(0,"");
						getComPubPage(0,"");
					}
			   			
			   		if(section == "getPerPubPage")
					mensaje('El mensaje ha sido borrado!');
				}
			   	if(data == "noValido")
			   		mensaje('Debes loguearte para borrar citas.');
			  }
			});	
	}	
}
function removeItems(dir){
	count = 1;
	if(dir == 1){
		for(var i = 1;i<8;i++){
			$("#slider li:first").remove();
		}
	}else{
		for(var i = 1;i<8;i++){
			$("#slider li:last").remove();
		}
	}
}
function moveScroll(direction,sumar,paso){

	paginaAct = $("#scrollPage").val();
	datos = "_action=loadSliderPage&direction="+direction+"&page="+paginaAct;
	var date = new Date();
	var timestamp = date.getTime();
	$.ajax({
	   type: "POST",
	   url: "/main.php?t="+timestamp,
	   data: datos,
	   dataType:"json",
	   beforeSend: function(){
	   	moviendo = true;
		},
	   success: function(data){
	   	if(data != ""){
	   		$("#scrollPage").val(parseInt(data.page));
	   		//$("#slider").html(data.html);
	   		if(data.noleft == 1){
				$("#f_izquierda").css("visibility","hidden");
			}else{
				$("#f_izquierda").css("visibility","visible");
			}
			if(data.noright == 1){
				$("#f_derecha").css("visibility","hidden");
			}else{
				$("#f_derecha").css("visibility","visible");
			}
			if(data.noright != 1 && data.noleft != 1){
				if(direction == 1){
					//removeItems(1);
					$("#slider").append(data.html);
				}else{
					//removeItems(2);
					$("#slider").prepend(data.html);
				}				
			}
			$("#slider").css("width",$("#slider li").length*115);
			if(direction == 1){
				$("#slider").animate({ 
		        marginLeft: (sumar*-1)
		      }, 300 , 'swing', function(){
		   
		   		setTimeout(function(){
				$(".comp_slider").hide();
				$(".comp_slider").each(function(i,val){
					if(i >= paso*7 && i <= paso*7+6){
						$(this).show();
					}
				})					
					
				},100);		      	
			  		
			  });				
			}else{
				
			}
			
		}
		moviendo = false;
	  }
	});	
}