var HomeBase = {
    postDefaultText: 'What\'s on your mind?',
    isCtrl: false,

    init: function() {
        $('#js_status_text')
            .val(this.postDefaultText)
            .focus(function(){
                if ($(this).val() == HomeBase.postDefaultText) {
                    $(this).val('');
                }
            })
            .blur(function(){
                if ($(this).val() == '') {
                    $(this).val(HomeBase.postDefaultText);
                }
            })
            .keyup(function(event){
                if (event.which == 17) {
                    HomeBase.isCtrl = false;
                }
            })
            .keydown(function(event){
                if(event.which == 17) {
                    HomeBase.isCtrl = true;
                }

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

        $('#js_share_button').click(function(){
            HomeBase.sendPost();
        });
    },

    sendPost: function() {
        var oClicked = $('#js_share_button');

        if (oClicked.hasClass('busy')) {
            return false;
        }

        var oTextField = $('#js_status_text');
        var aErrors = [];
        var aValues = {};

        aValues['text'] = oTextField.val();
        if (aValues['text'] == '' || aValues['text'] == HomeBase.postDefaultText) {
            aErrors.push('Please enter text of the wall post.');
        } else if (aValues['text'].length > 300) {
            aErrors.push('Text should be no longer than 300 characters.');
        }

        if (aErrors.length) {
            HomeBase.displayErrors(aErrors);
        } else {
            aValues['username'] = oClicked.attr('rel');
            aValues['do'] = 'share';

            $.ajax({
                url: '/wall.html',
                type: 'POST',
                dataType: 'json',
                data: aValues,
                /**
                 * Disable input field and link
                 */
                beforeSend: function() {
                    oTextField.attr('disabled', 'disabled');
                    oClicked.addClass('busy');
                },
                /**
                 * Show sent post
                 */
                success: function(data) {
                    if ('ok' == data.type) {
                        if ($('#wallPosts').length && Wall.isOwner) {
                            $('#wallPosts').prepend(
                                '<div class="wall_post" style="display:none;">' +
                                    '<img class="float_left" src="'+(data.post.image)+'" alt=""/>'+
                                    '<div class="post_details">'+
                                        '<a href="/'+(data.post.author)+'/wall"><b>'+(data.post.author)+'</b></a>&nbsp;&nbsp;'+
                                        (data.post.text)+
                                        '<p>'+
                                            (data.post.sentAt)+

                                            (Wall.isWallPage ? '&nbsp;&bull;&nbsp;'+
                                            '<a href="#" class="comment_post">Comment</a>&nbsp;&bull;&nbsp;'+
                                            '<a href="#" class="delete_post" rel="'+(data.post.id)+'">Delete</a>'+
                                        '</p>'+
                                        '<div class="new_comment" style="display: none;">'+
                                            '<img class="float_left" src="'+($('.new_comment:first img').attr('src'))+'" alt="" />'+
                                            '<div class="comment_details">'+
                                                '<input type="hidden" name="parentId" value="'+(data.post.id)+'"/>'+
                                                '<textarea name="text" cols="1" rows="50">'+(Wall.commentDefaulttext)+'</textarea>'+
                                                '<div class="align_right send_comment">'+
                                                    '<br/>'+
                                                    '<input onmouseout="this.src=\''+(Wall.domainDir)+'buttons/btn_comment.gif\'" onmouseover="this.src=\''+(Wall.domainDir)+'buttons/btn_comment_grey.gif\'" type="image" src="'+(Wall.domainDir)+'buttons/btn_comment.gif" alt="" />'+
                                                '</div>'+
                                            '</div>'+
                                            '<div class="clear">&nbsp;</div>'+
                                        '</div>': '</p>')+

                                    '</div>'+
                                    '<div class="clear">&nbsp;</div>'+
                                '</div>'+
                                '<div class="block_brake gray_border_bottom_box2">&nbsp;</div>'+
                                '<div class="block_brake">&nbsp;</div>'
                            ).children('.wall_post:first').slideDown();
                                
                            Wall.bindFocusHandler($('.new_comment:first :input[name="text"]'));
                        }

                        oTextField.val('').trigger('blur');

                    } else {
                        HomeBase.displayErrors(data.message);
                    }
                },
                /**
                 * Redirect browser to login page if 403 status code received
                 */
                error: function(xhr) {
                    if (403 == xhr.status) {
                        location.replace('/login');
                    }
                },
                /**
                 * Enable fields and link
                 */
                complete: function() {
                    oTextField.removeAttr('disabled');
                    oClicked.removeClass('busy');
                }
            });
        }
    },

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

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

        alert(sMessage);
    }

};

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

