var response;

var mooblik = {
	
	buscarusuario: function(){
		
		var nombre = $('#nombre').val();
		
		if( nombre == '' ){
			
			alert("El campo nombre no puede estar vacio.");
			return;

		}

		$.post('/ajax/buscarusuario/',{patron:nombre},function( response ){

			if( response.msg ){
				
				$('#resultadoBusqueda').html( response.msg );
				
			} else {
			
				var content = '';
				jQuery.each(response.datos, function(key, value) {
					
						if( value['nombre'] != '' ){
							
							check = '<input type="checkbox" name="usuarios[]" value="' + value['id'] + '">&nbsp;';
							content = content + check + value['usuario'] + "  -  " + value['email'] + "<br>";

							$('#resultadoBusqueda').html( content );
	
						} else {
							
							content = "No se encontraron resultados.";
							$('#resultadoBusqueda').html( content );
							
						}
						
		 		});

			}
						
		},'json');
		
	},
	
	 reloadVideo: function(){

                document.getElementById('msg').style.display = 'block';
                $.post('/videos/reload/id/'+video_id, '', function(response){
			console.log(response);
			if(response.error == 2) {
				alert('Video not avaible at this moment');
				document.location.href = '/videos';
				return;	
			}
                        if(response.error == 1){
                                document.location.href = document.location;
                                return;
                        }
                        var so = new SWFObject('/resources/swf/player.swf','mpl','440','310','10');
                            so.addParam('allowscriptaccess','always');
                            so.addParam('allowfullscreen','true');
                            so.addParam('wmode','transparent');
                            so.addParam('flashvars',response.params);
                            so.write('mooblik_player');
                },'json');
        },

	listarmiembros:function(){
		
		grupo = $('#group').val();
		
		$.post('/ajax/listarmiembros/',{grupo:grupo},function( response ){

			if( response.msg ){
				
				$('#listadoMiembros').html( response.msg );
				
			} else {
				
				var content = '';

				jQuery.each(response.datos, function(key, value) {

					content = content + "<div id='usuario_" + value.idusuario + "' ><div style='width:175px; float:left;'>" + value.usuario + "</div><div style='width:20px; float:left;'>";
					content = content + "<input  onclick='javascript:mooblik.quitarmiembro(\"" + value.idusuario + "\",\"" + grupo + "\");' type='button' class='input_trash'/></div></div>";
						
		 		});

		 			$('#listadoMiembros').html( content );
			}
						
		},'json');
		
	},
	
	quitarmiembro: function ( userId, groupId ) {
		
		if( !userId || !groupId ){
			
			alert( "Debe seleccionar un usuario y un grupo." );
			return;

		}
		
		ok = confirm( "Desea quitar al usuario del grupo ?." );
		
		if( ok ){
			
			$.post('/ajax/quitarmiembro/',{idgrupo:groupId,idusuario:userId},function( response ){

				$( '#usuario_' + userId ).remove();
						
			},'json');
			
		}
		
	},
	
	changeBotonera:function( tipo ){

		var tipo;
		var controller;
		var clase;
		if( tipo == 'videos' ){
			tab = 'tab1';
			clase = 'botonera1';
			controller = 'videos';
		}

		if( tipo == 'photos' ){
			tab = 'tab2';
			clase = 'botonera2';
			controller = 'photos';
		}

		if( tipo == 'groups' ){
			tab = 'tab3';
			clase = 'botonera3';
			controller = 'groups';
		}

		$( '#botonera' ).attr( 'class', clase );
		$( '#tabs' ).attr( 'class', tab );
		$( '#tipo' ).val( controller );
		
	},

    search: function(form_){

        var pattern = form_.pattern.value;
            pattern = jQuery.trim(pattern);            

        if(pattern == '') {
            alert('Please enter a text to search');
            return;
        }
        form_.submit();
    },

	searchCategory:function( category ){

		var tipo = $( '#tipo').val() ;

		if( tipo == 'videos' ) {

			window.location.href = "/videos/all/category/" + category;

		} else

                if( tipo == 'groups' ) {

			window.location.href = "/groups/all/category/" + category;

		} else {
			
			window.location.href = "/" + tipo + "/index/category/" + category;
		}

	},

	hidemenu:function( div ){
		
		if( div == 'videos' )	$( '#menu_videos' ).show();
		else $( '#menu_videos' ).hide();

		if( div == 'photos' )	$( '#menu_photos' ).show();
		else $( '#menu_photos' ).hide();
		
		if( div == 'people' )	$( '#menu_people' ).show();
		else $( '#menu_people' ).hide();
		
		if( div == 'groups' )	$( '#menu_groups' ).show();
		else $( '#menu_groups' ).hide();
		
	},
	
	buscarparaenvio:function( idGroup ){
		
		nombre = $('#nombre').val();
		
		if( nombre == '' ){
			
			alert("El campo nombre no puede estar vacio.");
			return;

		}
		
		$('#saving').css({'visibility' : 'visible'});
		
		$.post('/ajax/buscarusuario/',{patron:nombre},function( response ){

			if( response.msg ){
				
				$('#resultadoBusqueda').html( response.msg );
				
			} else {
			
				content = '';
				jQuery.each(response.datos, function(key, value) {
					
						$('#saving').css({'visibility' : 'hidden'});
					
						if( value['nombre'] != '' ){
							
//							email = '&nbsp;<a href="#" onclick="javascript:mooblik.enviarInvitacion(' + value['id'] + ',' + idGroup + ',\'enviomail_' + value['id'] + '\');">';
//							email = email + '<div id="enviomail_' + value['id']  + '">Enviar invitacion</div></a>&nbsp;';
							
							email = '<div onclick="javascript:mooblik.enviarInvitacion(' + value['id'] + ',' + idGroup + ',\'enviomail_' + value['id'] + '\');" id="enviomail_' + value['id']  + '" > Enviar invitacion</div></div>&nbsp;';

							content = content + value['usuario'] + "  -  " + value['email'] + email + "<br>";
								
							$('#resultadoBusqueda').html( content );
	
						} else {
							
							content = "No se encontraron resultados.";
							$('#resultadoBusqueda').html( content );
							
						}
						
		 		});

			}
						
		},'json');
		
	},
	
	enviarInvitacion:function( id, grupo, div ){
		
		$('#saving').css({'visibility' : 'visible'});
		$.post('/ajax/enviarinvitacion/',{id:id,grupo:grupo},function( response ){

			$('#saving').css({'visibility' : 'hidden'});
			
			if( response == 1 ){
				
				$('#' + div).html( "Enviado correctamente" );
				
			} else {

				$('#' + div).html( "No se pudo enviar la invitacion. Pruebe de nuevo mas tarde." );
				
			}
						
		});
		
	},
	
	quitarusuarios:function(){
		
		ok = confirm( "Desea quitar los usuarios seleccionados del grupo ? ");
		
		if( ok ){
			
			$('#saving').css({'visibility' : 'visible'});
			return true;			
		}
		
		return false;
		
		
	},
	
	confirmareliminar:function( id ){
		
		ok = confirm( "Desea eliminar el grupo ?" );
		
		if( ok ){
			
			window.location.href = "/groups/mygroups/accion/eliminar/id/" + id;
		}
		
	},
	
	eliminaralbum:function( id, usuario ){
		
		ok = confirm( "Want to delete the selected album?" );
		
		if( ok ){
			
			window.location = "/photos/eliminaralbum/id/" + id + "/usuario/" + usuario;

		}
		
	},
	
	addgrouptodiv: function(){
		
		id = $('#group').val();
		nombre =  $('#group option:selected').text();
		
		if( $('#grupo_' + id).length == 0 ){
			
			html = "<div id='grupo_" + id + "' ><div style='width:175px; float:left;'>" + nombre + "</div><div style='width:20px; float:left;'>";
			html = html + "<input type='hidden' name='grupos[]' value='" + id +  "'>"; 
			html = html + "<input  onclick='javascript:mooblik.quitardiv(\"grupo_" + id + "\");' type='button' class='input_trash'/></div></div>";
		
			result = $('#groupResult').html();
			result = result + html;
			$('#groupResult').html( result );
			
		}
		
	},
	
	quitardiv: function( id ){

		$( '#' + id ).remove();
		
	},
	
	showtoggle: function( id ){

		$( '#' + id ).toggle('slow');
		
	},
	
	showslidetoggle: function( id ){

		$( '#' + id ).slideToggle('slow');
		
	},
	
	nextpicture: function( album, last ){
		
		$( '#prevLink' ).show();
		$( '#comments' ).slideUp();
	
		$( '#titulophoto' ).html(  '' );
		$( '#visitsphoto' ).html(  '' );
		
		mooblik.showtoggle( 'form_photo' );
		
		actual = $( '#actual' );
		next = actual.next();
		actualImg = actual.find('img').attr( 'id' );
		
		$('.comments_view').html('');
		
		if( next.is('li')){

			if( next.attr('id') == last ){
				$( '#nextLink' ).hide();
			}

			actual.attr( 'id', actualImg );
			next.attr( 'id', 'actual' );
			
			$( '#id' ).val( next.find('img').attr( 'id' ) );
			
			$.post('/ajax/getimage/',{album:album,id:actualImg,next:1},function( response ){

				jQuery.each(response.datos, function(key, value) {
					
					$( '#edit' ).attr( 'href', '/photos/editphoto/id/' + value.id );
                                        $( '#download_photo' ).attr( 'href', '/photos/download/id/' + value.id );
					$( '#titulophoto' ).html(  value.titulo );
					$( '#visitsphoto' ).html(  value.views );
					
				});
						
			},'json');

			actual.hide();
			next.show();

		} else {

			$.post('/ajax/getimage/',{album:album,id:actualImg,next:1},function( response ){

				if( response.error == 'EOF' ){
					
					$( '#nextLink' ).hide();
					
				} else {
					//Si no hubo errores
					
					jQuery.each(response.datos, function(key, value) {

						if( value.id == last ){
							$( '#nextLink' ).hide();
						}

						$( '#edit' ).attr( 'href', '/photos/editphoto/id/' + value.id );
						$( '#download_photo' ).attr( 'href', '/photos/download/id/' + value.id );
						var li = $('<li />');
                            li.attr( 'id' , 'actual' );
						var img = $('<img />');
						img.attr( {'src':'/resources/albums/' + album + '/' + value.archivo, 'width':'396', 'height':'306','id':value.id} );
						li.append( img );
						
						actual.attr( 'id', actualImg );
						$( '#id' ).val( value.id );
						actual.hide();
						$( '#titulophoto' ).html(  value.titulo );
						$( '#visitsphoto' ).html(  value.views );
						$('#slide').append(li);
						
					});

				}

			},'json');
			
		}
		
		mooblik.showtoggle( 'form_photo' );

	},
	
	prevpicture: function( album, first ){
                mooblik.showtoggle( 'form_photo' );
		$( '#nextLink' ).show();
		$( '#comments' ).slideUp();
		
		$( '#titulophoto' ).html( '' );
		$( '#visitsphoto' ).html( '' );
		
		actual = $( '#actual' );
		actualId = actual.attr( 'id' );
		next = actual.prev();
		actualImg = actual.find('img').attr( 'id' );

		if( next.is('li')){

			if( next.attr('id') == first ){
				$( '#prevLink' ).hide();
			}
			
			next.attr( 'id', 'actual' );
			actual.attr( 'id', actualImg );
			
			$( '#id' ).val( next.find('img').attr( 'id' ) );

			$.post('/ajax/getimage/',{album:album,id:actualImg,next:0},function( response ){

				jQuery.each(response.datos, function(key, value) {

					$( '#edit' ).attr( 'href', '/photos/editphoto/id/' + value.id );
                                        $( '#download_photo' ).attr( 'href', '/photos/download/id/' + value.id );
					$( '#titulophoto' ).html(  value.titulo );
					$( '#visitsphoto' ).html(  value.views );
					
				});
				
			},'json');
			
			actual.hide();
			next.show();

		} else {

			$.post('/ajax/getimage/',{album:album,id:actualImg,next:0},function( response ){

				if( response.error == 'EOF' ){
					
					$( '#prevLink' ).hide();
					
				} else {
					//Si no hubo errores
					
					jQuery.each(response.datos, function(key, value) {
						
						if( value.id == first ){
							$( '#prevLink' ).hide();
						}

						var li = $('<li />');
						li.attr( 'id' , 'actual' );
						var img = $('<img />');
						img.attr( {'src':'/resources/albums/' + album + '/' + value.archivo, 'width':'396', 'height':'306','id':value.id} );
						li.append( img );
						
						$( '#titulophoto' ).html(  value.titulo );
						$( '#visitsphoto' ).html(  value.views );
						
						$( '#edit' ).attr( 'href', '/photos/editphoto/id/' + value.id );
						$( '#download_photo' ).attr( 'href', '/photos/download/id/' + value.id );
						actual.attr( 'id', actualImg );
						actual.hide();
						
						$( '#id' ).val( value.id );
						$('#slide').prepend(li);
						
					});

				}

			},'json');
			
		}
                mooblik.showtoggle( 'form_photo' );
	},
	
	addcomment:function( tipo, id ){

		comentario = $( '#comentario' ).val();
		
//		actual = $( '#actual' ).attr( 'id' );
		if( tipo == 'photo' ) {
//			actualId = $( '#actual' ).find('img').attr( 'id' );
			id = $( '#actual' ).find('img').attr( 'id' );
		}
		
//		$.post('/ajax/addcomment/',{comentario:comentario,tipo:tipo,id:actualId},function( response ){
		$.post('/ajax/addcomment/',{comentario:comentario,tipo:tipo,id:id},function( response ){

			if( response.error ){
				
				$( '#resultComment' ).html( response.error );
				
			} else {
				//Si no hubo errores
				
				$( '#resultComment' ).html( 'Comment added succesfully.' );
				comentario = $( '#comentario' ).val('');

				jQuery.each(response.datos, function(key, value) {
					html = "<p>" + value['comentario'] + "<br />User: <a href='/" + value['userName'] + "'>" + value['userName'] + "</a> | " + value['fecha'] + "</p>";
				});
				
				$('.comments_view').prepend( html );
					
			}

		},'json');
		
	},
	
	getComentarios:function(){

		actual = $( '#actual' ).attr( 'id' );
		actualId = $( '#actual' ).find('img').attr( 'id' );
		
		$( '#resultComment' ).html( '' );
		$('.comments_view').html( '' );
		
		$.post('/ajax/getcommentarios/',{tipo:'F',id:actualId},function( response ){
			
			//Si no hubo errores
			
			$( '#comentario' ).val('');

			jQuery.each(response.datos, function(key, value) {
				html = "<p>" + value['comentario'] + "<br />User: <a href='/" + value['userName'] + "'>" + value['userName'] + "</a> | " + value['fecha'] + "</p>";
                                $('.comments_view').append( html );
				
			});
                        html = $('.comments_view').html();
                        
                        if(html == '')
                        {
                            html = "<p>No comments yet.</p>";
                            $('.comments_view').append( html );
                        }
			

		},'json');
		
		$( '#comments' ).slideToggle('slow');
		
	},

	getMessages:function( id ){

//		actual = $( '#actual' ).attr( 'id' );
//		actualId = $( '#actual' ).find('img').attr( 'id' );
//		
//		$( '#resultComment' ).html( '' );
//		$('.comments_view').html( '' );
//		
//		$.post('/ajax/getcommentarios/',{tipo:'F',id:actualId},function( response ){
//			
//			//Si no hubo errores
//			
//			$( '#comentario' ).val('');
//
//			jQuery.each(response.datos, function(key, value) {
//				html = "<p>" + value['comentario'] + "<br />User: <a href='/" + value['userName'] + "'>" + value['userName'] + "</a> | " + value['fecha'] + "</p>";
//				
//				$('.comments_view').append( html );
//			});
//			
//
//		},'json');
		
		$( '#' + id ).slideToggle('slow');
		
	},
	
	addmessage:function( idContenedor ){
		
		message 	= 	$( '#message_' + idContenedor ).val();
		userId 		= 	$( '#userId' ).val();
		topicsId 	= 	$( '#topicsId_' + idContenedor ).val();

		if( message == '' ){
//			Si no completo el campo de mensaje

			$( '#msg_' + idContenedor ).html( 'Must complete all fields.' );
			$( '#msg_' + idContenedor ).show( 'slow' );
			return;
		}
		if( userId == '' || topicsId == '' ){

			$( '#msg_' + idContenedor ).html( 'You must login in order to enter a message.' );
			$( '#msg_' + idContenedor ).show( 'slow' );
			return;
		}
		
		$.post('/ajax/addmessage/',{userid:userId,topicsid:topicsId,message:message},function( response ){
	
			if( response.success ){

				$( '#message_' + idContenedor ).val('');
				$( '#msg_' + idContenedor ).html( "The message was successfully saved." );
				
				jQuery.each(response.success, function(key, value) {
					
					html = 'Mensaje: ' + message + '<br>by:&nbsp;' + value['usuario'] + '&nbsp;|&nbsp;' + value['fecha'] + '<div style="border-bottom:1px dashed #333; height:5px; margin-bottom:20px"></div>';
					$('#comments_' + idContenedor ).prepend( html );
				});
				
			}
		},'json');
		
	},
	
	jointogroup:function(){

		userId = $( '#userId' ).val();
		groupId = $( '#groupId' ).val();

		if( userId == '' ){
			//Si el usuario esta vacio lo invita a loguearse

			html = 'Debe estar logueado para ser parte del grupo.<br>';
			html = html + 'Haga click <a href="/home/login" >aqui</a>';
			$( '#msg' ).html( html );
			return;
		}
		
		$.post('/ajax/addusertogroup/',{userid:userId,groupid:groupId},function( response ){

			if( response.msg ){
				
				$( '#msg' ).html( response.msg );
				
			} 

		},'json');

	},
	
	mostrargrupos:function( permiso ){
		
		if( permiso == 'groups' ){
			
			$('#groupdiv').css({'display' : 'block'});
			
		} else {
			
			$('#groupdiv').css({'display' : 'none'});
			
		}
	},
	
	actualizarfoto:function( id ){
		
		titulo 		= $( '#titulo' ).val();
		descripcion = $( '#descripcion' ).val();
		
		$.post('/ajax/savephoto/',{id:id,titulo:titulo,descripcion:descripcion},function( response ){

			if( response.msg ){
				mooblik.showtoggle( 'msg' );
				$('#msg').html( response.msg );
			}

		},'json');
		
		
	},
	
	guardarreporte: function(){
		
		castigado 	= 	$('#usuario_castigado').val();
		id			= 	$('#id').val();
		tipoReporte	= 	$('#tipo_reporte').val();

		$.post('/ajax/addnewreport/',{id:id,castigado:castigado,tiporeporte:tipoReporte},function( response ){

			alert(response.msg);

		},'json');
		
	},
        guardarreportevideo: function(){

		castigado 	= 	$('#usuario_castigado').val();
		id		= $('#id').val();
		tipoReporte	= 	$('#tipo_reporte').val();

		$.post('/ajax/addnewreportvideo/',{id:id,castigado:castigado,tiporeporte:tipoReporte},function( response ){

			alert(response.msg);

		},'json');

	},
        
	deleteVideo: function(){

  	 var id = document.getElementById('video_id').value; 
        var user = document.getElementById('user_name').value; 
         
        answer = confirm("Are you sure you want to delete this video ?"); 
 
                if ( answer ){ 
                        //Si desea eliminar 
                        $.post('/videos/delete/',{id:id},function( response ){ 
 
                if( response.error ){ 
 
                                        alert( response.error ); 
 
                                } else { 
                                        //Si no hubo errores 
                    alert(response.message); 
                                        window.location.href = "/" + response.username + "/videos"; 
                                } 

                        },'json');

                }
       


    },
	deletePhoto: function(){
		//Si se desea eliminar la cuenta
		var id = document.getElementById('id').value;
		answer = confirm("Are you sure you want to delete this photo ?");
		
		if ( answer ){
			//Si desea eliminar
			$.post('/ajax/deletephoto/',{id:id},function( response ){
				
				if( response.error ){
				
					alert( response.error );
				
				} else {
					//Si no hubo errores
					
					window.location.href = "/" + response.datos['username'] + "/album/id/" + response.datos['album'];
					
				}

			},'json');
			
		}
		
	},
	
	validatealbum: function(){

		titulo	=	$('#titulo').val();

		if( titulo.length == 0 ){

			$( '#tituloerror' ).html('El campo "title" no puede estar vacio. Verifique.' );
			return false;

		} else {
			
			return true;
			
		}
		
	},
	
	validatelogin: function(){

		user	=	$('#user').val();
		pass	=	$('#pass').val();

		$.post('/ajax/validarusuario/',{user:user,pass:pass},function( responses ){
                
			if( responses.result == 'si' ){

                            document.forms[0].submit();
                            return true;
				
			} else {
				
				if( $('.errors').length > 0 ){
					
					$('.errors').remove();
					
				}
					
				var ul = $('<ul />');
				ul.attr( 'class', 'errors' );

				var li = $('<li />');
				li.html( 'User does not exist.' );

				ul.append( li );

				$('#pass-element').append( ul );

				return false;

			} 

		},'json');
		return false;
	},
	
	checktopico: function(){
		
		userId	=	$('#userId').val();
		if( userId == '' ) {
//			Si no esta logueado
			$( '#topicMsg' ).html( 'You must login in order to enter a topic.' );
			$( '#topicMsg' ).show( 'slow' );
			return false;

		}
		
		topico	=	$( '#topico' ).val();
		if( topico == '' ){
//			Si no ingreso el topico tira un cartel
			$( '#topicMsg' ).html( 'Must complete all fields.' );
			$( '#topicMsg' ).show( 'slow' );
			return false;
			
		}
		
	},

	deleteaccount: function( areyousure ){
		
		answer = confirm("Are you sure you want to delete your account in mooblik ?");
		
		if ( answer ){
			//Si desea eliminar
			location.href = "/people/delete/code/" + areyousure;
		}
		
	}
	
}

$(document).ready(function(){

	$("#effect").easySlider();
        var tipo = $( '#tipo' ).val();

        if(tipo)
        {
            mooblik.changeBotonera(tipo);
        }
});

