String.prototype.trim = function() {
	return this.replace(/^\s+|\s+$/g,"");
}

function ocultarTwitreply() {
    if(twitreplymostrado !=null)
    {
        twitreplymostrado.hide();
        twitreplymostrado = null;
    }
}

function enviarTwitreply(idrep) {
    $("#formtwit"+idrep).submit();
    ocultarTwitreply();
}

function chopText(elem, limit, nombre) {
    if(elem.value.length>limit) {
        elem.value=elem.value.substring(0,limit);
    }

    cont = limit-elem.value.length;
    $("#"+nombre).html("&nbsp;&nbsp;"+cont);
}

function show_mini_alert(text) {
    $('<span class="mini_alert">'+text+'</span>').appendTo($('body')).fadeIn().delay(1000).fadeOut(function() { $(this).remove() });    
}

function num_notificaciones() {
    // hack para que no salga el loader ajax
    $('#ajax-loader-body').hide();
    $('#ajax-loader-body').off(".mine");
    
    send = {'referer' : 'common', 'action': 'get_numero_notificaciones', 'data' : {}}                
    $.getJSON(ajax_dispatcher, send, function(data) {
        if(data.sucess == 'ok') {
            notificaciones_switch = $("#notificaciones-switch");
            notificaciones_switch.text(data.data.numero_notificaciones);
            if(data.data.numero_notificaciones > 0) {
                notificaciones_switch.addClass("btn-success");
            }
            else {
                notificaciones_switch.removeClass("btn-success");
            }
        }
    });
    
    // hack (2da parte)
    $('#ajax-loader-body').on("ajaxStart.mine", function() { $(this).show(); });
    $('#ajax-loader-body').on("ajaxStop.mine", function() { $(this).hide(); });    
}

var twitreplymostrado = null,
    ajax_dispatcher = "/ajax/dispatcher.php",
    intervalo_notificaciones = setInterval("num_notificaciones()", 20000); 

$(document).ready(function() {
    // ajax loader
    $('#ajax-loader-body').on("ajaxStart.mine", function() { $(this).show(); });
    $('#ajax-loader-body').on("ajaxStop.mine", function() { $(this).hide(); });

    // Sidebar Tabs 
    $(function () {
        $('.module').each(function() {
          var tabContainer = $(this).find('.content > div');
          tabContainer.hide().filter(':first').show();
        });

        $('.tabs').each(function() { $(this).find('a:first').addClass('active'); });

        $('ul.tabs a').click(function () {
          var tabContainers = $(this).closest('.module').find('.content > div');
          tabContainers.hide();
          tabContainers.filter(this.hash).show();

          $(this).closest('ul.tabs').find('a').removeClass('active');
          $(this).addClass('active');

          return false;
        });
    });
  
 
    // Zebra on Sidebar Posts
    $('.posts li:nth-child(even)').addClass('even');

    // Scroll to Top
    $('.top').click(function(){
        $('html, body').animate({scrollTop:0}, 'fast');
    });

    // User Options Toggle 
    $('.userStatus .userName').click(function() {
        $('.userOptions').toggleClass('active');
        return false;
    });

    // mostrar reply en estados (cambiar esto ASAP)
    $('.twitreplink').click(function() {
        idrep = $(this).attr("id_reply");
        if(twitreplymostrado !=null)
        {
            id2 = twitreplymostrado.attr("id_reply");
            if(id2==idrep)
            {
                twitreplymostrado.hide();
                twitreplymostrado = null;
            }else{
                twitreplymostrado.hide();
                twitreplymostrado = $("#twitreply"+idrep);
                $("#twitreply"+idrep+" textarea").val("");
                twitreplymostrado.fadeIn('fast');
            }
        }else{
            twitreplymostrado = $("#twitreply"+idrep);
            $("#twitreply"+idrep+" textarea").val("");
            twitreplymostrado.fadeIn('fast');
        }
    });

    // compartir barra superior
    $('#compartir-texto').click(function(e) {
       e.stopPropagation();
    });

    // autofocus para el textarea de cambio de estado
    $('#compartir-switch').click(function() {
        setTimeout(function() { $("#compartir-texto").focus() }, 300);
    });

    $("#compartir-texto").keypress(function() { 
        if($("#compartir-counter").length > 0) {
            if($(this).val().length > 140)
                $(this).val($(this).val().substring(0, 140))
            $("#compartir-counter").text($(this).val().length+'/140');                            
        }
    });

    $("#boton_enviar_compartir").click(function(e) {
        e.preventDefault();
        datos = { 'texto' : $('#compartir-texto').val() }
        send = { 'referer' : 'common', 'action': 'enviar_compartir', 'data' : datos }                
        $.getJSON(ajax_dispatcher, send, function(data) {
            if(data.sucess == 'ok') {
                $('.enviar_mensaje_modal').val('');
                show_mini_alert('¡Estado enviado con exito!');
            }
        });
    });
    
    // actividad reciente barra superior
    $("#actividad_reciente-switch").click(function(e) {
        e.preventDefault();
        
        if($("ul#actividad_reciente").css('display') == 'none') {
            send = { 'referer' : 'common', 'action': 'get_actividad_reciente', 'data' : {} }
            $.get(ajax_dispatcher, send, function(data) {
                $("ul#actividad_reciente").html(data);            
            });
        }
    });
    
    // favoritear entradas
    $("a.bookmark").click(function(e) {
        e.preventDefault();
        $this = $(this);
        id = $this.attr('id').substr(11);
        favorito = ($this.hasClass('active')) ? 0 : 1;
        
        datos = { 'id_entrada' : id, 'favorito' : favorito }
        send = { 'referer' : 'common', 'action': 'articulo_favorito', 'data' : datos }                
        $.getJSON(ajax_dispatcher, send, function(data) {
            if(data.sucess == 'ok') {
                if(favorito == 1)
                    $this.addClass("active").attr('title',"Quitar de favoritos");
                else
                    $this.removeClass("active").attr('title',"Añadir a favoritos");
            }
        });        
    });

    // follow de usuarios
    $(document).on("click", "a.follow-user", function(e) {
        e.preventDefault();
        $this = $(this);
        user = $this.attr('href').substr(1);

        send = { 'referer' : 'common', 'action': 'follow_user', 'data' : { 'user' : user } };
        $.getJSON(ajax_dispatcher, send, function(data) {
            if(data.sucess == 'ok') {
                $this.replaceWith('<a href="'+$this.attr('href')+'" class="unfollow-user btn">No seguir</a>');
            }
        });        
    });
    
    // unfollow de usuarios
    $(document).on("click", "a.unfollow-user", function(e) {
        e.preventDefault();
        $this = $(this);
        user = $this.attr('href').substr(1);

        send = { 'referer' : 'common', 'action': 'unfollow_user', 'data' : { 'user' : user } };
        $.getJSON(ajax_dispatcher, send, function(data) {
            if(data.sucess == 'ok') {
                $this.replaceWith('<a href="'+$this.attr('href')+'" class="follow-user btn btn-success">Seguir</a>');
            }
        });        
    }); 
    
    // switch de ventana modal de mensajes privados
    $("a.mensaje_to").click(function(e) {
        e.preventDefault();
        str = $(this).attr('href').split('#');
        user_data = str[1].split('@');
        $('#modal-mensajes_privados .alert').text('').hide();
        $('#modal-mensajes_privados h3').text('Enviar mensaje privado a '+user_data[0]);
        $('#boton_enviar_mensaje').attr('href', '#'+user_data[1]);
        $('#modal-mensajes_privados').on('shown', function () {
            $('.enviar_mensaje_modal').focus();
        })        
        $('#modal-mensajes_privados').modal('show');
    });
    
    // enviar mensajes privados
    $("#boton_enviar_mensaje").click(function(e) {
        e.preventDefault();
        boton = $(this);
        boton.button('loading');
        datos = { 'to_id' : $('#boton_enviar_mensaje').attr('href').substr(1), 'texto' : $('#mensaje_modal').val() }
        send = { 'referer' : 'common', 'action': 'enviar_mensaje_privado', 'data' : datos }                
        $.getJSON(ajax_dispatcher, send, function(data) {
            if(data.sucess == 'ok') {
                boton.button('complete');
                $('#modal-mensajes_privados').modal('hide');
                $('.enviar_mensaje_modal').val('');
                boton.button('reset');
            }
            else {
                $('#modal-mensajes_privados .alert').text(data.error).fadeIn('fast');
                boton.button('reset');
            }
        });
    }); 
    
    // switch de desplegable de notificaciones privadas
    $("#notificaciones-switch").click(function(e) {
        e.preventDefault();
        
        if($("ul#notificaciones").css('display') == 'none') {
            send = {'referer' : 'common', 'action': 'get_notificaciones_dropdown', 'data' : {}}
            $.get(ajax_dispatcher, send, function(data) {
                $("ul#notificaciones").html(data);
                num_notificaciones();
            });
        }
    });
});


