$(document).ready(function(e) {
	
	$.ajaxSetup({ type: "POST" });
	
	$('.karaoke_download').click(function(e){
		var id_karaoke = $(this).attr("id_karaoke");
		$.ajax({
			url : '/live/karaokes/download',
			data : 'id_karaoke=' + id_karaoke,
			beforeSend : function(){
				$("#karaoke_download").addClass("karaoke_download_").addClass("karaoke_download_").html('<div class="load"></div> Cargando karaoke...');
			},
			success : function(r){
				try{
					$("#karaoke_download").addClass("karaoke_download_").html(r.response);
				}catch(e){ kAlert('Ha ocurrido un error al descargar el karaoke'); }
			}, dataType:'json'
		});
	});
	
	$('#karaoke_comment_form').submit(function(event){
		event.preventDefault();
		//alert("OK");
		var comment = $(this).serialize();
		if($("#karaoke_comment").val() == '' || $("#karaoke_comment").val() == null){
			kAlert("Debes escribir un comentario antes de continuar...");
			return false;
		}
		$.ajax({
			url:'/live/karaokes/comment_create',
			data : comment,
			beforeSend: function(){},
			success: function(r){
				try{
					if(r.error==0){ $("#comments").prepend(r.response); $("#karaoke_comment").val(""); 
						//if($("#comments .comment").length <= 0){
						//console.log($("#comments .comments_null").length);
							if($("#comments .comments_null").length>0){
								$("#comments .comments_null").remove();
							}
						//}
					}
				}catch(e){ kAlert('Ha ocurrido un error al enviar el comentario'); }
			}, dataType: 'json' 
		});
	});
		
	$("#comments .comment").live('mouseenter mouseleave', function(event){
		var id_comment = $(this).attr("id_comment");
		
		if(event.type == "mouseenter"){
			$("#comments .comment .delete[id_comment='" + id_comment + "']").show(0);
		}else{
			$("#comments .comment .delete[id_comment='" + id_comment + "']").hide(0);
		}
	});
	
	$("#comments .comment .delete").live('click', function(event){
		var id_comment = $(this).attr("id_comment");
			
		$("#comments .comment[id_comment='" + id_comment + "']").fadeTo(100, 0.5);
		
		kDialog("¿Deseas eliminar este comentario?", function(r){
			if(r == true){
				
				$.ajax('/live/karaokes/comment_delete', {
					data : 'id_comment=' + id_comment, 
					success: function(r){
						if(r.error==0){
							$("#comments .comment[id_comment='" + id_comment + "']").slideUp(0, function(){$(this).remove()});	
							if($("#comments .comment").length <= 0){
								$("#comments").html('<div class="comments_null">No hay comentarios para este karaoke</div>');
							}
						}else{
							kAlert('Ha ocurrido un error al eliminar el comentario.');
							$("#comments .comment[id_comment='" + id_comment + "']").fadeTo(100, 1);
						}
					}, dataType: 'json'
				});
			}else{ $("#comments .comment[id_comment='" + id_comment + "']").fadeTo(100, 1); return false; }
		});
	});
	
	$(".karaoke_comments_more").live('click', function(){
		var id_karaoke = $(".karaoke_comments_more").attr("id_karaoke");
		var page = parseInt($(".karaoke_comments_more").attr("page")) + 1;
		$.ajax('/live/karaokes/comments', {
			data : 'id_karaoke=' + id_karaoke + "&page=" + page,
			success : function(r){
				$("#comments").append(r.response);	
				$(".karaoke_comments_more").attr("page", page);
			}, dataType: 'json'
		});
		//console.log(id_karaoke, page);
	});
	
	$(".karaoke_edit").live("click", function(e) {
		var id_karaoke = $(this).attr("id_karaoke");
		$.ajax({
			url : '/live/karaokes/edit',
			data : 'id_karaoke=' + id_karaoke,
			beforeSend : function(){},
			success: function(r){
				try{
					kDialog(r.response, function(response){
						//alert(response);
						$("#dialog_true").attr('disabled', 'disabled').val('Guardando datos...');
						$.ajax({
							url : '/live/karaokes/edit',
							data : response,
							beforeSend:function(){},
							success: function(r){
								try{
									if(r.error==0){
										kAlert('Se han enviado los nuevos datos del karaoke, este proceso puede tardar varios minutos mientras se actualiza el sistema');
									}
								}catch(e){ kAlert('Ha ocurrido un error al editar el karaoke'); }
							}
						});					
					}, 'Editar karaoke', {form_send : true, form_enctype : 'multipart/form-data'});
				}catch(e){ kAlert('Ha ocurrido un error en la solucitud de edicion de karaoke'); }
			}, dataType: 'json' 
		});
	});
	
	$(".karaoke_report").live("click", function(event) {
		event.preventDefault();
		var id_karaoke = $(this).attr("id_karaoke");
		$.ajax({
			url : '/live/karaokes/report',
			data : 'id_karaoke=' + id_karaoke,
			success: function(r){
				try{
					if(r.error == 0){
						kDialog(r.response, function(r){
							if(r != false){
								$.ajax({
									url : '/live/karaokes/report',
									data : r,
									success : function(r){
										try{
											if(r.error == 0){
												kAlert('La denuncia se ha enviado correctamente', null);
											}else{ throw 9; }
										}catch(e){ kAlert('Ha ocurrido un error al enviar la denuncia del karaoke', null); }
									}, dataType : 'json'
								});
							}
						}, 'Denunciar karaoke');
						
					}else{ throw 9; }
				}catch(e){ kAlert('Ha ocurrido un error al denunciar el karaoke'); }
			}, dataType : 'json'
		});
	});
	
	$(".karaoke_favorite").live("click", function(event){
		var id_karaoke = $(this).attr("id_karaoke");
		event.preventDefault();
		$.ajax({
			url : '/live/karaokes/favorite',
			data: 'id_karaoke=' + id_karaoke,
			success: function(r){
				//console.log(r);
				if(r.error == 0){
					kAlert("Se ha agregado el karaoke a tus favoritos");
				}else{
					kAlert("Ha ocurrido un error al agregar el karaoke a tus favoritos");
				}
			}, dataType : 'json'
		});
	});
	
	// Menu
	
	$(".user_notifications").live('click',function(event){
		event.preventDefault();
		
		var position = $(this).position();
		
		$.ajax('/live/user/notifications_display', {
			beforeSend : function(){
				if($(".notifications_content").length <= 0){
					$('.head_outer').after('<div class="notifications_content"><div style="padding:10px; text-align:center;"><div class="load"></div> Cargando notificaciones...</div></div>');	
					
				}else{
					$(".notifications_content").html('<div style="padding:10px; text-align:center;"><div class="load"></div> Cargando notificaciones...</div>');	
				}
				$(".notifications_content").show().css({ left : (position.left - 320) });
				$(".user_notifications").html('<a href="/social/notificaciones">0</a>').addClass('inactive');
			}, success: function(r){
				$(".notifications_content").html(r.response);
			}, dataType: 'json'
		});
		
		
	});
	$(".notifications_content").live('mouseleave', function(){
		$(".notifications_content").fadeOut(100, function(){ $(this).remove(); });
	});
	// Search 
	
	$("#search #query").live('click', function(event){
		if($(this).val() == 'Buscar...'){
			$(this).val("").css({ color: '#000'}); 
			
		}
	});
	
	// Posts
	
	$(".post_delete").live('click', function(){
		var element = $(this);
		var id_post = element.attr('id_post');
		kDialog('¿Deseas eliminar esta publicacion?', function(r){
			if(r==true){
				$.ajax({
				url : '/live/posts/post_delete',
				data : 'id_post=' + id_post,
				beforeSend: function(){
					$(".post[id_post='" + id_post + "']").fadeTo(100,0.5);
				},
				success: function(r){
					try{
						if(r.error > 0){ $(".post[id_post='" + id_post + "']").fadeTo(100,1); }else{ $(".post[id_post='" + id_post + "']").fadeOut(400); }
					}catch(e){}
				}, dataType : 'json'
			});
			}
		}, 'Eliminar publicacion');
	});
	
	
	
	$(".posts_display").live('click', function(){

		var element = $(this);
		var type = element.attr("type");
		var page = parseInt(element.attr('page')) + 1;
		var id_user = element.attr('id_user');
		
		//alert(page + ':' + id_user);
		
		$.ajax({
			url: '/live/posts/posts_display',
			data: 'page=' + page + "&id_user=" + id_user + "&type=" + type,
			beforeSend:function(){
				element.before('<div class="load icon load_posts"></div>');
			},
			success: function(r){
				//console.log(r);
				$('#wall').append(r.response);
				$(".load_posts").remove();
				element.attr('page',(page));
			}, dataType : 'json'	
		});
	});
	
	
	
	
	/*
	$(".post_favorite").live('click', function(){
		var element = $(this);
		var id_post = element.attr('id_post');
		$.ajax({
			url : '/live/post_favorite',
			data : 'id_post=' + id_post,
			beforeSend: function(){
				//$(".post[id_post='" + id_post + "']").fadeTo(100,0.5);
			},
			success: function(r){
				if(r.error > 0){ 
					kAlert("No se ha podido guardar en favoritos el mensaje");
				}else{ 
					$(".post[id_post='" + id_post + "']").prepend('<div class="post_favorite_logo"></div>');
				}
			}, dataType : 'json'
		});
	});
	*/
	
	$(".post_create").live('click',function(){
		var id_user = $(this).attr('id_user');
		$.ajax({
			url : '/live/posts/post_create',
			data : 'id_user=' + id_user,
			success : function(r){
				kDialog(r.response, function(r){
					if(r != false){
						//alert(r);
						$.ajax({
							url : '/live/posts/post_create',
							data : r,
							success: function(r){
								$("#wall").prepend(r.response);
							}, dataType : 'json'
						});
						//alert(r);
					}
				});
			}, dataType : 'json'
			
		});
	});
	
	
	$(".post_share").live('click',function(e){
		var id_post = $(this).attr("id_post");
		$.ajax('/live/posts/post_share', {
			data : 'id_post=' + id_post,
			type : 'GET', 
			success : function(r){
				kDialog(r.response,function(r){
					try{
						if(r == true){
							var post = $.getJSON('/live/posts/post_share', 'id_post=' + id_post + '&share=true', function(r){ 
								try{
									$("#wall").prepend(r.response);
									//console.log(r);
								}catch(e){}
							});
							
						}	
					}catch(e){}
				}, 'Compartir publicación', {button_ok : 'Compartir publicación'});
			}, dataType : 'json'
		});
		
	});
	
	$(".post_favorite").live('click',function(e){
		var id_post = $(this).attr("id_post");
		$.ajax('/live/posts/post_favorite', {
			data : 'id_post=' + id_post,
			type : 'GET', 
			success : function(r){
				kDialog(r.response,function(r){
					try{
						if(r == true){
							var post = $.getJSON('/live/posts/post_favorite', 'id_post=' + id_post + '&favorite=true', function(r){ 
								try{
									$("#wall").prepend(r.response);
									//console.log(r);
								}catch(e){}
							});
							
						}	
					}catch(e){}
				}, 'Agregar a favoritos', {button_ok : 'Agregar a favoritos'});
			}, dataType : 'json'
		});
		
	});
	
	$(".post").live('mouseenter mouseleave', function(event){
		var id_post = $(this).attr("id_post");
		
		//console.log(event);
		//
		
		if(event.type == "mouseenter"){
			$(".post_delete[id_post='" + id_post + "']").show(0);
		}else{
			$(".post_delete[id_post='" + id_post + "']").hide(0);
		}
	});
	
	setInterval(function(){ 
		$.ajax('/live/user/social', {
			success : function(r){
				try{
					if(r.params.notifications > 0){
						$(".user_notifications").html('<a href="/social/notificaciones">' + r.params.notifications+ '</a>').removeClass("inactive");
						
					}else{
						$(".user_notifications").addClass("inactive");
					}
				}catch(e){}
			}, dataType :'json'
		});
		//kAlert('OK'); 
	}, 30000);
	
	$(".user_follow").live('click', function(event){
		var id_user = $(this).attr('id_user');
		var follow = $(this);
		
		$.ajax('/live/user/follow', {
			data : 'id_user=' + id_user,
			success : function(r){
				if(r.error==0){ 
					follow.removeClass('user_follow').addClass('user_unfollow').html('<img src="/icons/16x16/delete.png" class="icon"> Dejar de seguir'); 
				}else{ 
					kAlert('Ha ocurrido un error al seguir al usuario, intente en unos minutos'); 
				}
			}, dataType: 'json'
		});
	});
	
	
	$(".user_unfollow").live('click', function(event){
		var id_user = $(this).attr('id_user');
		var follow = $(this);
		
		$.ajax('/live/user/forget', {
			data : 'id_user=' + id_user,
			success : function(r){
				if(r.error==0){ 
					follow.addClass('user_follow').removeClass('user_unfollow').html('<img src="/icons/16x16/check.png" class="icon"> Seguir');; 
				}else{ 
					kAlert('Ha ocurrido un error al dejar de seguir al usuario, intente en unos minutos'); 
				}
			}, dataType: 'json'
		});
	});;
	
	$(".user_unfollow, .user_follow").live('mouseenter mouseleave', function(event){
		if(event.type == 'mouseenter'){
			if($(this).attr('class') == 'user_unfollow'){
				$(this).html('<img src="/icons/16x16/delete.png" class="icon"> Dejar de seguir');
			}else{
				$(this).html('<img src="/icons/16x16/check.png" class="icon"> Seguir');
			}
		}else{
			if($(this).attr('class') == 'user_unfollow'){
				$(this).html('<img src="/icons/16x16/check.png" class="icon" /> Siguiendo');
				
			}else{
				
				$(this).html('<img src="/icons/16x16/more.png" class="icon"> Seguir');
			}
		}
	});
	$(".follows_display").live('click', function(event){
		var page = parseInt($(this).attr('page')) + 1;
		var id_user = $(this).attr('id_user');
		
		$.ajax('/live/user/follows_display', {
			data : 'page=' + page + "&id_user=" + id_user,
			beforeSend : function(){$("#wall").fadeTo(100,0.5);},
			success: function(r){
				try{
					if(r.error==0){
						$("#wall").append(r.response);
						$(".follows_display").attr("page", page);
					}else{
						$(".follows_display").remove();						
					}
					$("#wall").fadeTo(100,1)
				}catch(e){}
			}, dataType : 'json'
		});
	});
	$(".followers_display").live('click', function(event){
		var page = parseInt($(this).attr('page')) + 1;
		var id_user = $(this).attr('id_user');
		
		$.ajax('/live/user/followers_display', {
			data : 'page=' + page + "&id_user=" + id_user,
			beforeSend : function(){$("#wall").fadeTo(100,0.5);},
			success: function(r){
				try{
					if(r.error==0){
						$("#wall").append(r.response);
						$(".followers_display").attr("page", page);
					}else{
						$(".followers_display").remove();						
					}
					$("#wall").fadeTo(100,1)
				}catch(e){}
			}, dataType : 'json'
		});
	});
	
	$("#karaokes_upload").live('submit', function(){ $("#karaoke_upload_send").attr('disabled', 'disabled').after('<div class="load"></div>');	});
	
	$(".karaoke_upload").live('change', function(){ var id = $(this).attr('id'); $("label[for='" + id + "']").html('<img src="/icons/16x16/file.png" class="icon" />' + $(this).val()); });
	
	$("#karaokes_upload_more").live('click', function(){

		var upload_num = $("#karaokes_upload input[type='file']").length + 1;

		$("#karaoke_upload_send").before(
			'<div class="item">' +
				'<label for="karaoke_upload_' + upload_num + '"><img src="/icons/16x16/file.png" class="icon" /> Selecciona tu karaoke o midi</label>' +
				'<input type="file" name="karaoke_upload_' + upload_num + '" id="karaoke_upload_' + upload_num + '" class="karaoke_upload">' +
			'</div>'
		);
	});
	
});
