var MessageCenter = {

    msgDefaultText: 'Write something',
    isCtrl: false,

    init: function() {
        if ($('.send_message').length) {
            /**
             * Create Send Message dialog HTML
             */
            $('body').append(
                '<div id="messageDialog" title="Send Message">' +
                    '<p class="error">'+
                        '<span class="ui-icon ui-icon-alert">&nbsp;</span>'+
                        '<span class="message">&nbsp;</span>'+
                    '</p>'+
                    '<div>'+
                        /**
                         * If users clicks "New message" link we should provide him/her
                         * an apporunity to select a recipient
                         */
                        (!$('.send_message').attr('rel') ?
                            '<label>To:</label>&nbsp;'+
                            '<select name="username">'+
                                '<option value="">Select recipient</option>'+
                            '</select>'+
                            '<div class="block_brake">&nbsp;</div>'
                        : '') +

                        '<label>Message Text:</label>'+
                        '<div class="block_brake">&nbsp;</div>'+
                        '<textarea id="messageText" name="messageText" rows="10" cols="35"></textarea>'+
                    '</div>'+
                '</div>'+
                '<div id="successMsg" title="Message sent" style="display:none;">'+
                    '<p>Your message was sent successfully</p>'+
                '</div>'
            );

            /**
             * In case if send message has no rel attribute
             * we request to the server for the friends list
             */
            if (!$('.send_message').attr('rel')) {
                $.ajax({
                    url: '/message-center',
                    type: 'POST',
                    dataType: 'json',
                    data: {
                        'do': 'get_friends'
                    },
                    /**
                     * Disable select
                     */
                    beforeSend: function() {
                        $('#messageDialog [name="username"]').attr('disabled', 'disabled');
                    },
                    /**
                     * Append options
                     */
                    success: function(data) {
                        if ('ok' == data.type) {
                            var sOptions = '';
                            for (i = 0; i < data.friends.length; ++i) {
                                var sUsername = data.friends[i];
                                sOptions += '<option value="'+sUsername+'">'+sUsername+'</option>';
                            }
                            $('#messageDialog [name="username"]').append(sOptions);
                        } else {
                            MessageCenter.displayErrors(data.message);
                        }
                    },
                    /**
                     * Redirect browser to login page if 403 status code received
                     */
                    error: function(xhr) {
                        if (403 == xhr.status) {
                            location.replace('/login');
                        }
                    },
                    /**
                     * Enable select
                     */
                    complete: function() {
                        $('#messageDialog [name="username"]').removeAttr('disabled');
                    }
                });

                /**
                 * And handle changes of the select with usernames
                 */
                $('#messageDialog [name="username"]').change(function(){
                    $('#messageDialog').dialog('option', 'username', $(this).val());
                });
            }

            /**
             * Send message Dialog initialization
             */
            $('#messageDialog').dialog({
                autoOpen: false,
                modal: true,
                width: 345,

                open: function() {
                    /**
                     * Hide error box and clear message text
                     */
                    $(this).find('.error').hide();
                    $(this).find(':input[name="messageText"]').val('');
                },

                buttons: {
                    'Ok': function() {
                        MessageCenter.sendMessage($(this));
                    },
                    'Cancel': function() {
                        $(this).dialog('close');
                    }
                }
            });

            $('#successMsg').dialog({
                autoOpen: false,
                modal: true,
                buttons: {
                    'Ok': function() {
                        $(this).dialog('close');
                    }
                }
            });

            /**
             * Send message link click handler
             */
            $('.send_message').click(function(){
                $('#messageDialog').dialog('option', 'username', $(this).attr('rel'));
                
                /**
                 * Open the dialog
                 */
                $('#messageDialog').dialog('open');

                return false;
            });
        }

        if (location.pathname.match(/^\/message-thread/)) {
            $('#submit').click(function(){
                MessageCenter.sendMessage();
                return false;
            });

            $('.post_form :input[name="text"]')
                .val(this.msgDefaultText)
                /* clear field on focus */
                .focus(function(){
                    if ($(this).val() == MessageCenter.msgDefaultText) {
                        $(this)
                            .val('')
                            .css({
                                'line-height': '15px',
                                'height' : '32px'
                            });
                    }
                })
                /* set default value of field if needed */
                .blur(function(){
                    if ($(this).val() == '') {
                        $(this)
                            .val(MessageCenter.msgDefaultText)
                            .css({
                                'line-height': '19px',
                                'height' : '20px'
                            });
                    }
                })
                .keyup(function(event){
                    if (event.which == 17) {
                        MessageCenter.isCtrl = false;
                    }

                    var aMatches = $(this).val().match(/\n/g);
                    if (aMatches && aMatches.length) {
                        $(this).css('height', 16 * (aMatches.length + 2));
                    } else {
                        $(this).css('height', 32);
                    }
                })
                .keydown(function(event){
                    if(event.which == 17) {
                        MessageCenter.isCtrl = true;
                    }

                    if(event.which == 13 && MessageCenter.isCtrl == true) {
                        MessageCenter.sendMessage();
                        MessageCenter.isCtrl = false;
                        return false;
                    }
                });
        }

        /**
         * Initiate sort bar select elements
         * If browser is on message-center or message-thread page
         */
        var aMatches = location.pathname.match(/^\/(message-center|message-thread-[^-]+).*?(-\d+)?$/);
        if (aMatches) {
            /**
             * OnChange event handler
             */
            $('.filter_search_select').change(function() {
                /**
                 * Get current location and sort bar values
                 * aMathes[1] will contain '-'+pageNumber
                 */
                var sSortBy = $(this).hasClass('sortby') ? $(this).val() : $('.filter_search_select.sortby:firts').val();
                var sOrder = $(this).hasClass('order') ? $(this).val() : $('.filter_search_select.order:firts').val();

                /**
                 * Depending on which element was changed
                 * we reset value of specific variable to proper value
                 */
                switch (true) {
                case $(this).hasClass('sortby'):
                    sSortBy = $(this).val();
                    break;

                case $(this).hasClass('sorter'):
                    sOrder = $(this).val();
                    break;
                }

                /**
                 * Redirect browser to the new location
                 */
                location.assign(aMatches[1] + '-' + sSortBy + '-' + sOrder + (aMatches[2] ? aMatches[2] : ''));
            });

            /**
             * if we on the message-thread page
             * we bind handler on mosueenter and mouseleave
             * This handler sends an AJAX request in order
             * to mark received message as read
             */
            if (aMatches[1].indexOf('thread')) {
                this.bindMessageHover($('.message'));
            }
        }
    },

    /**
     * Helps to display errors in dialog box
     */
    displayErrors: function(errors, dialog) {
        var sMessage = '';

        if (errors instanceof Array) {
            for(i = 0; i < errors.length-1; ++i) {
                sMessage += errors[i] + '<br/>';
            }
            sMessage += errors.pop();
        } else {
            sMessage = errors;
        }

        if (dialog) {
            $('#messageDialog .error .message').html(sMessage);
            $('#messageDialog .error').show('highlight', 1000);
        } else {
            $('.post_form .error')
                .html(sMessage)
                .show('highlight', 1000);
        }
    },

    /**
     * Binds mouseenter and mouseleave event handlers
     */
    bindMessageHover: function(target) {
        target.mouseenter(function(){
            var oTarget = $(this);
            oTarget.addClass('focused_message');

            /**
             * Send AJAX reques only if message is not read
             */
            if (oTarget.hasClass('unread_message')) {
                $.ajax({
                    url: '/message-center',
                    type: 'POST',
                    dataType: 'json',
                    data: {
                        'do': 'mark_as_read',
                        'id': oTarget.find('input:checkbox').val()
                    },
                    /**
                     * Remove class "unread_message"
                     */
                    success: function(data) {
                        if ('ok' == data.type) {
                            oTarget.removeClass('unread_message');
                        }
                    }
                });
            }
        }).mouseleave(function(){
           $(this).removeClass('focused_message');
        });
    },

    sendMessage: function(dialog) {
        if ($('#submit').hasClass('busy')) {
            return false;
        }

        var aErrors = [];
        var aValues = {};

        if (dialog) {
            /**
             * Hide error
             */
            dialog.find('.error').hide();

            aValues['username'] = dialog.dialog('option', 'username');
            aValues['messageText'] = dialog.find(':input[name="messageText"]').val();
        } else {
            $('.post_form .error').hide();

            aValues['username'] = $('.post_form input[name="username"]').val();
            aValues['messageText'] = $('.post_form :input[name="text"]').val();
        }


        /**
         * Validate username
         */
        if ('' == aValues.username) {
            aErrors.push('Please select one of users.');
        }

        /**
         * Validate entered message
         */
        if ('' == aValues.messageText || MessageCenter.msgDefaultText == aValues.messageText) {
            aErrors.push('Please enter a message text.');
        } else if(aValues.messageText.length > 300) {
            aErrors.push('Message should be no longer than 300 characters.');
        }

        /**
         * If errors present show them
         */
        if (aErrors.length) {
            MessageCenter.displayErrors(aErrors, dialog);
        } else {
            /**
             * Else we send an AJAX request in order to send a message
             */

            aValues['do'] = 'send_message';
            aValues['threadPage'] = location.href.match(/\/message-thread/) ? true : false;

            $.ajax({
                url: '/message-center',
                type: 'POST',
                dataType: 'json',
                data: aValues,
                /**
                 * Hide dialog buttons
                 */
                beforeSend: function() {
                    if (dialog) {
                        this.buttons = dialog.dialog('option','buttons');
                        dialog.dialog('option','buttons', {});
                    } else {
                        $('.post_form :input[name="text"]').attr('disabled', 'disabled');
                        $('#submit').addClass('busy');
                    }
                },
                /**
                 * Close dialog
                 */
                success: function(data) {
                    if ('ok' == data.type) {
                        if (dialog) {
                            dialog.dialog('close');
                            $('#successMsg').dialog('open');
                        }

                        if (aValues['threadPage']) {
                            var sNewMessage = 
                                '<div class="message" style="display: none;">'+
                                    '<table cellpadding="6" cellspacing="0" border="0" align="left" summary="">'+
                                        '<tr>'+
                                            '<td><input type="checkbox" name="messageId[]" value="'+(data.post.id)+'"/></td>'+
                                            '<td><img src="'+(data.post.image)+'" alt="" align="middle"/></td>'+
                                            '<td class="thread">'+
                                                '<div class="message_center_date align_left">'+
                                                    (data.post.sentAt)+
                                                '</div>'+
                                                '<div class="message_center_bgr">'+
                                                    '<div class="message_center_bgr_top align_left">'+
                                                        '<div class="message_center_bottom link_style bold_style">'+
                                                            (data.post.text)+
                                                        '</div>'+
                                                    '</div>'+
                                                '</div>'+
                                            '</td>'+
                                        '</tr>'+
                                    '</table>'+
                                    '<div class="clear">&nbsp;</div>'+
                                '</div>';
                                

                            var oNewMessage = {};
                            if ($('.filter_search_select.order').val() == 'ascending') {
                                oNewMessage = $('#threadForm').append(
                                    '<div class="block_brake gray_border_bottom_box2">&nbsp;</div>'+
                                        '<div class="block_brake">&nbsp;</div>'+
                                            sNewMessage +
                                        '<div class="clear">&nbsp;</div>'
                                    )
                                    .find('.message:last').slideDown();
                            } else {
                                oNewMessage = $('#threadForm').prepend(sNewMessage + '<div class="block_brake gray_border_bottom_box2">&nbsp;</div>')
                                    .find('.message:first').slideDown();

                            }

                            $('.post_form :input[name="text"]')
                                .val('')
                                .trigger('blur');
                                
                            MessageCenter.bindMessageHover(oNewMessage);
                        }
                    } else {
                        MessageCenter.displayErrors(data.message, dialog);
                    }
                },
                /**
                 * Redirect browser to login page if 403 status code received
                 */
                error: function(xhr) {
                    if (403 == xhr.status) {
                        location.replace('/login');
                    }
                },
                /**
                 * Show dialog buttons
                 */
                complete: function() {
                    if (dialog) {
                        $('#messageDialog').dialog('option','buttons', this.buttons);
                    } else {
                        $('.post_form :input[name="text"]').removeAttr('disabled');
                        $('#submit').removeClass('busy');
                    }
                }
            });
        }
    }

};

$(document).ready(function(){
    MessageCenter.init();
});
