/* +------------------------------------------------------------------------+
   | [1102] catharsis.ru                                          Parchment |
   +------------------------------------------------------------------------+
   | Copyright © 2011 Catharsis.  All rights reserved.                      |
   +------------------------------------------------------------------------+ */

/* Theme functions.  */
var Parchment =
{
    /* Call Elodia Colon API.  */
    call: function(method, data, successCallback, errorCallback)
    {
        /* Call.  */
        $.ajax
        ({
            data                        : data,
            dataType                    : 'json',
            type                        : 'POST',
            url                         : ':/' + method + '.json'
        })

        /* Provide success callback.  */
        .success(function(data)
        {
            /* Test if there was real success.  */
            if ('undefined' != typeof data['success'])
            {
                /* Test value.  */
                if (data.success)
                {
                    /* Success callback.  */
                    if (successCallback) successCallback(data.content);
                }
                else
                {
                    /* Error callback.  */
                    if (errorCallback) errorCallback(data.errorCodes);
                }
            }
            else
            {
                /* Bad response.  */
                Parchment.Overlay.show($('<p>Elodia: неверный формат ответа с сервера.</p>'));
            }
        })

        /* Provide HTTP error callback.  */
        .error(function(_, _, errorThrown)
        {
            /* Alert.  This is abnormal so don't hesitate.  */
            alert('Elodia Colon API Error: ' + errorThrown + '.');
        });
    },

    /* Editor methods.  */
    Editor:
    {
        /* Replace elt with the editor.  */
        replace: function(elt)
        {
            return elt.tinymce(Parchment.Options.editorOptions);
        }
    },

    /* Form methods.  */
    Form:
    {
        /* Create a buttonset with one or two buttons.  */
        buttonset: function(submitText, cancelEnabled)
        {
            /* Define buttons.  */
            var submitButton            = $('<input type="submit" />').attr('value', submitText).button();
            var cancelButton            = cancelEnabled ? $('<button>Отмена</button>').button().click(Parchment.Overlay.hide) : null;

            /* Define HTML.  */
            var html                    = $('<div class="modal-buttonset" />');

            /* Append buttons.  */
            if (submitButton) html.append(submitButton);
            if (cancelButton) html.append(cancelButton);

            /* Done.  */
            return html;
        },

        /* Create a check box.  */
        checkBox: function(text, name, checked)
        {
            return $('<label class="checkbox" />').text(text).prepend($('<input type="checkbox" value="on" />').attr('name', name).addClass('v-' + name));
        },

        /* Create a fieldset.  */
        fieldset: function(name)
        {
            return $('<fieldset />').append($('<legend />').text(name));
        },

        /* Create a fieldset with centered text.  */
        fieldsetC: function(name)
        {
            return $('<fieldset />').append($('<legend style="text-align: center" />').text(name));
        },

        /* Create a form.  */
        form: function(action)
        {
            return $('<form class="modal" enctype="multipart/form-data" method="post"><div class="modal-message ui-state-error ui-corner-all">yH</div>').attr('action', action);
        },

        /* Create a hidden input.  */
        hidden: function(name, value)
        {
            return $('<input type="hidden" />').attr('name', name).addClass('v-' + name).attr('value', value);
        },

        /* Create a line edit.  */
        lineEdit: function(text, name, value, maxlength)
        {
            return $('<label />').text(text).append($('<input class="line" type="text" />').attr('name', name).addClass('v-' + name).attr('value', value).attr('maxlength', maxlength));
        },

        /* Create a password edit.  */
        passwordEdit: function(text, name, value, maxlength)
        {
            return $('<label />').text(text).append($('<input class="line" type="password" />').attr('name', name).addClass('v-' + name).attr('value', value).attr('maxlength', maxlength));
        },

        /* Create a text edit.  */
        textEdit: function(name, value)
        {
            return $('<textarea />').attr('name', name).addClass('v-' + name).html(value);
        },

        /* Create an upload field.  */
        upload: function(text, name)
        {
            return $('<label />').text(text).append($('<input class="line" type="file" />').attr('name', name).addClass('v-' + name));
        },
        
        /* Create a mass upload field.  */
        uploadMultiple: function(text, name)
        {
            return $('<label />').text(text).append($('<input class="line" type="file" multiple />').attr('name', name + '[]').addClass('v-' + name));
        }
    },

    /* Options hash.  */
    Options:
    {
        /* Colorbox options.  */
        colorboxOptions:
        {
            maxWidth                    : '680px',
            photo                       : true,
            returnFocus                 : false,

            current                     : '{current}/{total}',

            href                        : function()
            {
                /* Use the colorbox image variant.  */
                return $(this).attr('href') + 'colorbox/';
            },

            title                       : function()
            {
                /* Link to the full-size image.  */
                return $(this).attr('title') + ' [<a href="' + $(this).attr('href') + '" target="_blank">Полный размер</a>]';
            },

            onOpen                      : function()
            {
                /* Close MP3.  */
                $('#mp3-player').hide();
            },

            onClosed                    : function()
            {
                /* Open MP3.  */
                $('#mp3-player').show();
            }
        },

        /* Editor options.  */
        editorOptions:
        {
            height                      : 250,
            language                    : 'ru',
            mode                        : 'none',
            skin                        : 'o2k7',
            plugins                     : 'advimage,advlink,autolink,contextmenu,fullscreen,inlinepopups,lists,paste,preview,searchreplace,tabfocus,table',
            theme                       : 'advanced',
            theme_advanced_buttons1     : 'bold,italic,underline,strikethrough,|,sub,sup,|,hr,|,justifyleft,justifycenter,justifyright,|,bullist,numlist,|,outdent,indent,|,anchor,link,unlink,|,image,|,cut,copy,paste,pastetext,pasteword,|,undo,redo,|,formatselect,removeformat,|,code,cleanup,|,fullscreen',
            theme_advanced_buttons2     : '',
            theme_advanced_buttons3     : ''
        }
    },

    /* Overlay methods.  */
    Overlay:
    {
        /* Initialize overlay.  */
        init: function()
        {
            var body                    = $('body');
            var overlay                 = $('<div id="overlay"><div id="overlay-0"><div id="overlay-1"><div id="overlay-2"><div id="overlay-3"></div><div id="overlay-c" href="#"></div></div></div></div><div id="overlay-s"></div></div>');

            /* Append to body.  */
            overlay.appendTo(body);

            /* Initialize clicks.  */
            $('#overlay-c').click(function() { Parchment.Overlay.hide(); return false; });
        },

        /* Hide overlay.  */
        hide: function()
        {
            /* Clean up.  */
            $('#overlay textarea:tinymce').remove();

            /* Do hide.  */
            $('#overlay').hide(); $('#overlay-3').empty();

            /* Show MP3 player.  */
            $('#mp3-player').show();
        },

        /* Show overlay with elt as its child element.  */
        show: function(elt)
        {
            /* Hide MP3 player.  */
            $('#mp3-player').hide();

            /* Show overlay.  */
            $('#overlay-3').empty().append(elt); $('#overlay').show();
        }
    },
};

/* Theme initialization.  */
$(function()
{
    /* Add base to editor options.  */
    Parchment.Options.editorOptions.script_url = $('base').attr('href') + 'js/tinymce/tiny_mce.js';
    Parchment.Options.editorOptions.document_base_url = $('base').attr('href');

    /* Initialize resize behavior for wide screens.  */
    $(window).resize(function()
    {
        /* Get HTML element.  */
        var html                        = $('html');

        /* Test if we need to enable the background-size trick.  This requires
           IE9, Chrome, Opera 10.53, Safari 5.0, or Firefox 4.0.  */
        if ((html.width() > 1600) || (html.height() > 1100))
        {
            /* Enable.  */
            html.addClass('widescreen');
        }
        else
        {
            /* Disable.  */
            html.removeClass('widescreen');
        }
    });

    /* Resize for the first time.  */
    $(window).resize();

    /* Attach menu hover handlers.  */
    $('#menu li').hover
    (
        /* On mouse enter.  */
        function()
        {
            /* Show link.  */
            $('a', $(this)).fadeIn(250);
        },

        /* On mouse leave.  */
        function()
        {
            /* Hide link.  */
            $('a', $(this)).fadeOut(250);
        }
    );

    /* Hide all menu items.  */
    $('#menu li a').hide();

    /* Attach endoresement hover handlers.  */
    $('#endorsement a').hover
    (
        /* On mouse enter.  */
        function()
        {
            /* Fade in.  */
            $('img', $(this)).fadeTo(100, 1.0);
        },

        /* On mouse leave.  */
        function()
        {
            /* Fade out.  */
            $('img', $(this)).fadeTo(100, 0.2);
        }
    );

    /* Fade endorsement links out.  */
    $('#endorsement a img').fadeTo(0, 0.2);

    /* Initialize overlay.  */
    Parchment.Overlay.init();

    /* Initialize buttons.  */
    $('.button').button();

    /* Initialize colorboxes.  */
    $('.post-image-list a, #mp3-cover a').colorbox(Parchment.Options.colorboxOptions);

    /* Initialize videoboxes.  */
    $('.post-video-list a, #main-sidebar-video a').click(function()
    {
        /* Get YouTube video ID and prepare player.  */
        var id                          = $(this).attr('href').replace(/^http:\/\/www\.youtube\.com\/watch\?v=/, '');
        var widescreen                  = $(this).hasClass('widescreen');
        var height                      = 480;
        var width                       = widescreen ? (height * 16 / 9) : (height * 4 / 3);
        var options                     = '?color=white&fs=1&hd=1';
        var html                        = '<iframe width="' + width + '" height="' + height + '" src="http://www.youtube.com/embed/' + id + options + '" frameborder="0" allowfullscreen></iframe>';

        /* Show in overlay.  */
        Parchment.Overlay.show($(html));

        /* Do not follow link.  */
        return false;
    });

    /* Handle Enter link.  */
    $('#auth-operations .b-enter').click(function()
    {
        /* Create form.  */
        var form                        = Parchment.Form.form(':/Auth:enter/');

        /* Create fieldset and buttonset.  */
        var fieldset                    = Parchment.Form.fieldset('Имя пользователя и пароль');
        var buttonset                   = Parchment.Form.buttonset('Войти', true);

        /* Define fieldset.  */
        fieldset.append(Parchment.Form.lineEdit('Имя пользователя:', 'username', '', 64));
        fieldset.append(Parchment.Form.passwordEdit('Пароль:', 'password', '', 64));

        /* Define form.  */
        form.append(fieldset).append(buttonset);

        /* Show form.  */
        Parchment.Overlay.show(form);

        /* Focus input.  */
        form.find('.v-username').focus();

        /* Handle form submission.  */
        form.submit(function(event)
        {
            /* Prevent form submission.  */
            event.preventDefault();

            /* Hide message.  */
            form.find('.modal-message').hide();

            /* Call Colon API.  */
            Parchment.call('Auth:enter', form.serialize(),
            
            /* Success.  */
            function()
            {
                /* Success => reload current location.  */
                location.href = location.href;
            },

            /* Failure.  */
            function(errors)
            {
                /* Show message.  */
                form.find('.modal-message').text(errors.join(' ')).show('drop', { direction: 'down' }, 500);
            });
        });

        /* Cancel link.  */
        return false;
    });

    /* Handle Leave link.  */
    $('#auth-operations .b-leave').click(function()
    {
        /* Call Colon API.  */
        Parchment.call('Auth:leave', {}, function() { location.href = location.href; });

        /* Cancel link.  */
        return false;
    });
    
    /* Define comment-to-html function.  */
    var commentHtml = function(comment, n)
    {
        /* Create html.  */
        var html                        = $('<li />').attr('id', comment.uuid);
        
        /* Attach children.  */
        html.append($('<a href="#" />').text(comment.username).click(function()
        {
            /* Insert text.  */
            var textarea                = $(this).closest('ul').parent().find('textarea');
            var text                    = $(this).text();
                        
            /* Update.  */
            textarea.val(text + ', ' + textarea.val()); textarea.focus();
            
            /* Don't follow.  */
            return false;
        }));
        
        /* Attach delete button.  */
        if ($('.b-admin').length > 0)
        {
            /* Do it.  */
            html.append($('<a class="b-delete" href="#">Удалить комментарий</a>').click(function()
            {
                /* Confirm.  */
                if (!confirm('Точно удалить комментарий?')) return false;
                
                /* Get uuid.  */
                var uuid                = $(this).closest('li').attr('id');
                var me                  = $(this);
                
                /* Do delete.  */
                Parchment.call('Comment:delete', { uuid: uuid }, function()
                {
                    /* Remove it.  */
                    me.closest('li').remove();
                });
                
                /* Cancel.  */
                return false;
            }));
        }
        
        /* Attach more children.  */
        html.append($('<span />').text((n ? ('#' + n + ', ') : '') + comment.date));
        html.append($('<p />').text(comment.text));

        /* Done.  */
        return html;
    };
    
    /* Comment helper.  */
    var loadComments = function(uuid, page, elt)
    {
        /* Show loading.  */
        elt.find('.comment-container-more').text('Загружаем комментарии…');
        
        /* Get them.  */
        Parchment.call('Comment:get', { uuid: uuid, page : page }, function(data)
        {
            /* Test if we have more.  */
            if (parseInt(data.more) > 0)
            {
                /* Update button.  */
                elt.find('.comment-container-more').text('Ещё ' + data.more + '…').attr('rel', page + 1);
            }
            else
            {
                /* Hide button.  */
                elt.find('.comment-container-more').remove();
            }
            
            /* Iterate.  */
            for (i in data) if ('more' != i) elt.find('ul').append(commentHtml(data[i], parseInt(i) + page * 20 + 1));
        });
    };
    
    /* Handle comment click.  */
    $('.post-social-comments').click(function()
    {
        /* Store self.  */
        var self                        = $(this);
        
        /* Replace text.  */
        self.text('Загружаем комментарии…');
        
        /* Get comments.  */
        Parchment.call('Comment:get', { uuid: self.attr('rel'), page: 0 }, function(data)
        {
            /* Get container.  */
            var container               = $('<div class="comment-container"></div>').attr('rel', self.attr('rel'));
            var containerUl             = $('<ul />').appendTo(container);
            var containerDiv            = $('<div />').appendTo(container);
            var containerMore           = $('<button class="comment-container-more" />').button().appendTo(containerDiv);
            var containerForm           = $('<form method="POST" />').addClass('inline-form').appendTo(container);
            
            /* Define form.  */
            if ($('.b-enter').length > 0)
            {
                /* No form.  */
                containerForm.append($('<p>Вы должны войти на сайт, чтобы оставлять комментарии.</p>'));
            }
            else
            {
                /* Yes form.  */
                containerForm.append($('<textarea name="text"></textarea>'));
                containerForm.append($('<input type="submit" value="Отправить" />').button());
            }
            
            /* Prepend comments.  */
            for (i in data) if ('more' != i) containerUl.append(commentHtml(data[i], parseInt(i) + 1));
            
            /* Insert.  */
            self.closest('.post').append(container);
            self.closest('.news').append(container);
            
            /* Remove this link.  */
            self.remove();
            
            /* Handle button.  */
            if (parseInt(data.more) > 0)
            {
                /* Update button.  */
                container.find('.comment-container-more').text('Ещё ' + data.more + '…').attr('rel', 1);
            }
            else
            {
                /* Hide button.  */
                container.find('.comment-container-more').remove();
            }
            
            /* Button clicks.  */
            containerMore.click(function()
            {
                /* Get uuid and page.  */
                var uuid                = $(this).closest('.comment-container').attr('rel');
                var page                = parseInt($(this).attr('rel'));
                var elt                 = $(this).closest('.comment-container');
                
                /* Call.  */
                loadComments(uuid, page, elt);
            });

            /* Handle form submission.  */
            containerForm.submit(function(event)
            {
                /* Cancel.  */
                event.preventDefault();
                
                /* Get uuid and text.  */
                var uuid            = $(this).parent().attr('rel');
                var text            = $(this).find('textarea').val();
                
                /* Store self.  */
                var self            = $(this);
                                
                /* Send.  */
                Parchment.call('Comment:create', { uuid: uuid, text: text }, function(data)
                {
                    /* Success.  Add comment.  */
                    self.parent().find('ul').append(commentHtml(data, null).addClass('user'));
                    
                    /* Clear form.  */
                    self.find('textarea').val('').blur();
                });
            });
        });
        
        /* Don't follow link.  */
        return false;
    });
});

