/***********************************************************************************************************
 * Moderation-related javascript objects
 ***********************************************************************************************************/
    var moderator =
    {
        init : function ()
        {
            box = $('#momt');
            $('#momt a').click(function(){
                if ( box.hasClass('show') ){
                    box.removeClass('show');
                    box.addClass('hide');
                }else{
                    box.removeClass('hide');
                    box.addClass('show');
                }
            });
            
            
            $('#mo-board').delegate('a', 'click', function(){
                $('#mo-board').html('<img src="/apps/forum/code/views/default/images/icon/ajax-loader.gif"/>');
                $.ajax({
                    url: '/apps/forum/code/ajax/moderation/trigger.ajax.php', type: 'GET', dataType: 'text',
                    data: { 'option': 'change_board', 'post': $('#mo-id').text() },
                    success: function(response){
                        $('#mo-board').html(response);
                    }
                });
                return false;
            });

            $('#mo-board').delegate('input', 'click', function(){
                board = $('#mo-board select').val();
                if ( board > 0 ){
                    $(this).parents('td').html('Modificando tablón <img src="/apps/forum/code/views/default/images/icon/ajax-loader.gif"/>');
                    $.ajax({
                        url: '/apps/forum/code/ajax/moderation/trigger.ajax.php', type: 'GET', dataType: 'text',
                        data: { 'option': 'commit_board', 'post': $('#mo-id').text(), 'board': board },
                        success: function(response){
                            $('#mo-board').html(response);
                        }
                    });
                }
                return false;
            });
            
            $('#mo-author').delegate('a', 'click', function(){
                $('#mo-author').html('<img src="/apps/forum/code/views/default/images/icon/ajax-loader.gif"/>');
                $.ajax({
                    url: '/apps/forum/code/ajax/moderation/trigger.ajax.php', type: 'GET', dataType: 'text',
                    data: { 'option': 'change_author', 'post': $('#mo-id').text() },
                    success: function(response){
                        $('#mo-author').html(response);
                    }
                });
                return false;
            });
            
            $('#mo-author').delegate('input', 'click', function(){
                author = $('#mo-author select').val();
                if ( author > 0 ){
                    $(this).parents('td').html('Modificando autor <img src="/apps/forum/templates/default/images/icon/ajax-loader.gif"/>');
                    $.ajax({
                        url: '/apps/forum/code/ajax/moderation/trigger.ajax.php', type: 'GET', dataType: 'text',
                        data: { 'option': 'commit_author', 'post': $('#mo-id').text(), 'author': author },
                        success: function(response){
                            $('#mo-author').html(response);
                        }
                    });
                }
                return false;
            });
            
            $('#threads > ul').delegate('.show-edition', 'click', function(){
                div = $(this).parents('li').children('.edition');
                if ( div.css('display') == 'none' ){
                    div.css('display', 'block');
                    $(this).addClass('less').removeClass('more');
                }else{
                    div.css('display', 'none');
                    $(this).addClass('more').removeClass('less');
                };
            });

        }
        
    }

/***********************************************************************************************************
 * Validación de formularios
 ***********************************************************************************************************/
 
    var jForm = 
    {
        regex :
        { 
            jpassword   :   { regex : /^[a-z0-9@!#]{6,20}$/i },
            jemail      :   { regex : /^\w[-.\w]*\@+(?:\w[-\w]*)+(?:\.\w[-\w]*)*\.(?:[a-z][a-z]|biz|com|edu|info|name|net|org|pro|aero|asia|cat|coop|edu|gov|int|jobs|mil|mobi|museum|tel|travel|arpa|nato)$/i },
            jtext       :   { regex : /^(\s|.){2,}$/i },
            jname       :   { regex : /^[a-zá-úñ' ]{2,}$/i },
            jusername   :   { regex : /^[-a-z0-9]{4,20}$/i },
            jnum        :   { regex : /^[0-9]+$/ },
            jtimestamp  :   { regex : /^[0-9]{4,4}-[0-9]{2,2}-[0-9]{2,2} [0-9]{2,2}:[0-9]{2,2}:[0-9]{2,2}$/ }
        },
        
        init : function ()
        {
            $('.jForm .jvalidate').blur(function(){
                jForm.validate(this);
            });
            $('.jForm').submit(function()
            {
                jForm.formOk = true;
                $('.jvalidate', this).each(function(){
                    jForm.validate(this);
                });
                return jForm.formOk;
            });
            
            $('.jForm .jrequired').each(function(){
                $(this).parents('li').children('label').append($('<p style="color: #f00; ">Requerido</p>'));
            });
        },
        
        validate : function (obj)
        {
            if ( ( $(obj).is('.jrequired') ) || ( $(obj).val() != '' ) )
            {
                clase = $(obj).attr('class').replace( /(jrequired|jvalidate|jwrong|jcorrect|\s)/g, '' );
                if ( jForm.regex[clase].regex.test($(obj).val()) )
                {
                    $(obj).removeClass('jwrong').addClass('jcorrect');
                }
                else
                {
                    $(obj).removeClass('jcorrect').addClass('jwrong');
                    jForm.formOk = false;
                }
            }
            else
            {
                $(obj).removeClass('jcorrect').removeClass('jwrong');
            }
        }
    };

/***********************************************************************************************************
 * OBJETO Forum
 ***********************************************************************************************************/
    var Forum = 
    {
        previewPost : function ()
        {
            $('input.preview').click(function()
            {
                $.ajax({
                    url: '/apps/forum/code/ajax/previewPost.php', type: 'POST', dataType: 'text',
                    data: { title:  escape($('#post-title').val()), body: escape($('#post-body').val()) },
                    success: function(response){
                        // Function for closing the popup
                        $("#pop-preview").click(function (){ 
                            $(this).fadeOut('slow'); 
                        });
                        // Setting up distances inside the window
                        $("#pop-preview").css( "left", "50px" ); 
                        $("#pop-preview").css( "top", "50px" );     
                        $('#pop-preview').fadeIn('slow');                   
                        $('#preview').html(response);
                    }
                });
                return false;
            }); 
        },
        
        quotePost : function ()
        {
            $('.button-quote a').click(function()
            {
                var id = $(this).attr('href').substr(1).split(',');
                $.ajax({
                    url: '/apps/forum/code/ajax/getPostBody.php', type: 'GET', dataType: 'text',
                    data: { post : id[0], board : id[1] },
                    success: function(response){
                        $('#post-body').append(response).focus();
                    }
                });
                return false;
            });
        },
    
        confirmDelete : function ()
        {
            $('.button-delete a, #mo-delete a, .button-draft-delete a').click(function()
            {
                return confirm("¿Está seguro de que quiere borrar el mensaje?");
            });
        },
        
        viewUser : function ()
        {
            $('#user-list li.user').click(function()
            {
                var id = $('a', this).attr('href').split('/');
                $.ajax({
                    url: '/apps/forum/code/ajax/users/viewUser.php', type: 'GET', dataType: 'text',
                    data: { 'id': ( id[id.length-1] > 0 ) ? id[id.length-1] : 0 },
                    success: function(response){
                        $('#selected-user-info').html(response);
                    }
                });
            });
        }
        
    };

/***********************************************************************************************************
 * OBJETO RecentPosts
 ***********************************************************************************************************/
    var RecentPosts =
    {
        // Show and hide recent messages info
        showRecentList : function (container, context)
        {
            $(container).click(function()
            {
                $(this).parents('li').children('div').toggle();
            });
        }
    };
    
/***********************************************************************************************************
 * OBJETO FileUploader
 ***********************************************************************************************************/
    var NewFileUploader =
    {
        init : function ()
        {
            //$('#fileone').click;
        },
        
        request : function ( option, info )
        {
            tag = [];
            tag.begin = '<tr class="fu_nomorefiles"><td colspan="7">';
            tag.end = '</td></tr>';
            ok = function(){};
            dataopt = {};
            
            switch ( option )
            {
                case 'show':
                    dataopt = { 'option': option, 'post': info.post, 'type': info.type, 'board': info.board };
                    ok = function(response){
                        $(info.div).html(response);
                        $(".file-uploader-list").delegate(".a_file_position, .a_file_text", "change", function(a){
                            $.ajax({
                                url: '/apps/forum/code/ajax/filehandling/trigger.ajax.php', type: 'GET', dataType: 'text',
                                data: { 'option': 'change', 'input': $(this).attr('class'), 'file': $(this).parents('tr').attr('id'), 'value': escape( $(this).val() ) }
                            });
                        });
                    };
                    break;
                    
                case 'delete':
                    dataopt = { 'option': option, 'file': info.fileId };
                    $('#file-'+info.fileId).remove();
                    ok = function(response){
                        if ( response == 'File Deleted' ){
                            if ( $('#post-assigned-files tbody tr').length === 0 ) {
                                $('#post-assigned-files tbody').append( tag.begin+'No hay archivos subidos.'+tag.end );}
                            if ( $('#warehouse-files-list tbody tr').length === 0 ) {
                                $('#warehouse-files-list tbody').append( tag.begin+'No hay archivos subidos.'+tag.end );}
                        }
                    };
                    break;
                    
                case 'remove':
                    dataopt = { 'option': option, 'file': info.fileId };
                    ok = function(response){
                        if ( response == 'File deattached' ){
                            tr = '<tr id="file-'+info.fileId+'">'+$('#file-'+info.fileId).html().replace( /remove/g, 'assign' ).replace( /Desvincular/g, "Asignar" )+'</tr>';
                            $('#file-'+info.fileId).remove();
                            $('#warehouse-files-list tbody').append(tr);
                            $('#warehouse-files-list tr.fu_nomorefiles').remove();
                            if ( $('#post-assigned-files tbody tr').length === 0 ) {
                                $('#post-assigned-files tbody').append( tag.begin+'No hay archivos asignados.'+tag.end );}
                        }
                    };
                    break;
                    
                case 'assign':
                    dataopt = { 'option': option, 'file': info.fileId, 'post': info.post };
                    ok = function(response){
                        if ( response == 'File assigned' ){
                            tr = '<tr id="file-'+info.fileId+'">'+$('#file-'+info.fileId).html().replace( /assign/g, 'remove' ).replace( /Asignar/g, "Desvincular" )+'</tr>';
                            $('#file-'+info.fileId).remove();
                            $('#post-assigned-files tbody').append(tr);
                            $('#post-assigned-files tr.fu_nomorefiles').remove();
                            if ( $('#warehouse-files-list tbody tr').length === 0 ) {
                                $('#warehouse-files-list tbody').append( tag.begin+'No hay archivos subidos.'+tag.end );}
                        }
                    };
                    break;
            }
            
            $.ajax({
                url: '/apps/forum/code/ajax/filehandling/trigger.ajax.php', type: 'GET', dataType: 'text',
                data: dataopt,
                success: ok
            });
        },
        
        submitEvent : function ( input )
        {
/*          $('#'+input).change(function(){
                $('#uploading-info').html('');
                upload_field = document.getElementById(input);
                filename = upload_field.value;
                upload_field.form.submit();
                return false;
            });*/
        },
        
        imageTypeBox: function ()
        {
            $('#options input[type=checkbox]').click(function(){
                
            });
        }
        
    };
    
    $(function() {
        $('#form-upload-image').submit(function(e) {
            e.preventDefault();
            $.ajaxFileUpload({
                url            : '/apps/forum/code/ajax/filehandling/uploadFile.php?board='+$('#postBoxBoard').val()+'&is_gallery_image'+$('#is_gallery_image').attr('checked'),
                secureuri      : false,
                fileElementId  : 'fileone',
                dataType       : 'json',
                data           : {
                    'resize_width' : $('#resize_width').val(),
                    'resize_height' : $('#resize_height').val(),
                    'is_gallery_image' : $('#is_gallery_image').attr('checked')
                },
                success  : function (data, status)
                {
                },
                error : function ()
                {
                }
            });
            return false;
        });
    });
    
/***********************************************************************************************************
 * OBJETO ShowUserPosts
 ***********************************************************************************************************/
    var ShowUserPosts =
    {
        init : function ()
        {
            //alert('Se ha cargado ShowUserPosts.');
            $('#user-post-list footer a').click( function(){
                ShowUserPosts.request( 'get', { user: $('#showuser-id').val(), page: $(this).attr('class'), value: $('#curPage').val() } );
                return false;
            });
        },
        
        request : function ( option, info )
        {
            dataopt = {};
            ok = function(){};
            
            switch ( option )
            {
                case 'get':
                    dataopt = { 'option': option, 'user': info.user, 'page': info.page, 'value': info.value };
                    ok = function(response){
                        var json = eval('(' + response + ')');
                        $('#user-post-list table tbody').html( json.response );
                        $('#curPage').attr('value', json.curPage);
                        $('#jump-to').attr('value', parseInt(json.curPage) + 1);
                    };
                    break;
            }
            
            $.ajax({
                url: '/apps/forum/code/ajax/showuserposts/trigger.ajax.php', type: 'GET', dataType: 'text',
                data: dataopt,
                success: ok,
                error: function(response){
                    $('#result-message').html('Ha ocurrido un error en la comunicación con el servidor.');
                }
            });
        }       
    };
    
/***********************************************************************************************************
 * OBJETO AdminZone
 ***********************************************************************************************************/
    var AdminZone =
    {
        init : function ()
        {
            $('#admininfo > li > dl').delegate('dd.text', 'click', function(){
                $(this).parents('li').children('div').slideToggle();
            });
            
            $('#admininfo').delegate('.levup', 'click', function(){
                li      = $(this).parents('li');
                var cur     = [];
                cur.id      = li.attr('id').split('-')[1];
                cur.parent  = li.attr('id').split('-')[3];
                cur.level   = li.attr('id').split('-')[2];
                
                if ( cur.level > 0 )
                {
                    cur.level--;
                    li.attr('id', 'board-'+cur.id+'-'+cur.level+'-'+cur.parent);
                    if ( cur.level == 0 )
                        li.addClass('root').css('border-left', '-30px solid #ddd');
                    else
                        li.removeClass('root').css('border-left', (cur.level*30-30)+'px solid #ddd');
                }
                return false;
            });
            
            $('#admininfo').delegate('.levdown', 'click', function(){
                li      = $(this).parents('li');
                var cur     = [];
                cur.id      = li.attr('id').split('-')[1];
                cur.parent  = li.attr('id').split('-')[3];
                cur.level   = li.attr('id').split('-')[2];
                var prev    = [];
                prev.id     = li.prev().attr('id').split('-')[1];
                prev.parent = li.prev().attr('id').split('-')[3];
                prev.level  = li.prev().attr('id').split('-')[2];

                if ( ( prev.level == cur.level ) || ( parseInt(prev.level) == ( parseInt(cur.level) + 1 ) ) )
                {
                    cur.level++;
                    li.attr('id', 'board-'+cur.id+'-'+cur.level+'-'+cur.parent);
                    if ( cur.level == 0 )
                        li.addClass('root').css('border-left', '-30px solid #ddd');
                    else
                        li.removeClass('root').css('border-left', (cur.level*30-30)+'px solid #ddd');
                }
                return false;
            });
            
            $('#admininfo').delegate('.up', 'click', function(){
                li = $(this).parents('li');
                if ( li.prev().prev().html() !== null )
                {
                    var cur     = [];
                    cur.id      = li.attr('id').split('-')[1];
                    cur.parent  = li.attr('id').split('-')[3];
                    cur.level   = li.attr('id').split('-')[2];
                    var prev    = [];
                    prev.id     = li.prev().attr('id').split('-')[1];
                    prev.parent = li.prev().attr('id').split('-')[3];
                    prev.level  = li.prev().attr('id').split('-')[2];
                    
                    li.insertBefore(li.prev());
                    AdminZone.request( 'moveup', { 'cur':cur, 'prev':prev } );
                }
            });
            
            $('#admininfo').delegate('input.down', 'click', function(){
                li = $(this).parents('li');
                if ( li.next().html() !== null )
                {
                    var cur     = [];
                    cur.id      = li.attr('id').split('-')[1];
                    cur.parent  = li.attr('id').split('-')[3];
                    cur.level   = li.attr('id').split('-')[2];
                    var next    = [];
                    next.id     = li.next().attr('id').split('-')[1];
                    next.parent = li.next().attr('id').split('-')[3];
                    next.level  = li.next().attr('id').split('-')[2];
                    
                    if ( li.prev().html() === null && !li.next().hasClass('root') && li.hasClass('root') )
                    {
                        alert('El primer tablón tiene que ser siempre un encabezado de sección.');
                    }else{
                        li.insertAfter(li.next());
                        AdminZone.request( 'movedown', { 'cur':cur, 'prev':next } );
                    }
                }
            });
        },
        
        
        request : function ( option, info )
        {
            dataopt = {};
            ok = function(){};
            
            switch ( option )
            {
                case 'levelup':
                    break;
                    
                case 'leveldown':
                    break;
                    
                case 'moveup':
                    dataopt = { 'option':option, 'cur-id':info.cur.id, 'prev-id':info.prev.id };
                    ok = function(response){
                        var json = eval('(' + response + ')');
                        if ( json.exec == 'OK' )
                        {
                        }else{
                            alert(json.message);
                        }
                    }
                    break;
                    
                case 'movedown':
                    dataopt = { 'option':option, 'cur-id':info.cur.id, 'prev-id':info.prev.id };
                    ok = function(response){
                        var json = eval('(' + response + ')');
                        if ( json.exec == 'OK' )
                        {
                        }else{
                            alert(json.message);
                        }
                    }
                    break;
            }
            
            $.ajax({
                url: '/apps/forum/code/ajax/adminzone/trigger.ajax.php', 
                type: 'GET', 
                dataType: 'text',
                data: dataopt,
                success: ok,
                error: function(response){
                    $('#result-message').html('Ha ocurrido un error en la comunicación con el servidor.');
                }
            });
        }
    };

/***********************************************************************************************************
 * Execute after DOM load
 ***********************************************************************************************************/
    $(function(){
        $('#userzone nav h2').click(function(){
            $(this).next('ul').slideToggle();
        })
    })

