/**
 * This object will incapsulate operations for escorts
 * on public part
 */
var Friends = {
    friendsPageRegEx: /^\/contacts.*?(-\d+)?$/,
    friendsRequestPath: /^\/requests.*$/,
    /**
     * Initiates event handlers for the links
     */
    init: function() {
        /**
         * Bind add as friend handler
         */
        $('.add_as_friend').live('click', function(event){ 
             if ($(event.target).attr('rel')) {
                 Friends.addAsFriend($(event.target).attr('rel'));
             }
             return false;
        });

        
        $('.accept_as_friend').live('click', function(event){
            if ($(event.target).attr('rel')) {
                Friends.addAsAccept($(event.target).attr('rel'));
            }
            return false;
        });

        
        $('.rejected_friend').live('click', function(event){
            if ($(event.target).attr('rel')) {
                Friends.rejectedFriend($(event.target).attr('rel'));
            }
            return false;
        });
        
        
        /**
         * Bind remove as friend handler
         */
        $('.remove_as_friend').live('click', function(event){
            if ($(event.target).attr('rel')) {
                Friends.removeAsFriend($(event.target).attr('rel'));
            }
            return false;
        });

        /**
         * Initiate sort bar select elements
         * If browser is on friends page
         */
        if (location.pathname.match(this.friendsPageRegEx)) {
            /**
             * OnChange event handler
             */
            $('.filter_search_select').change(function() {
                /**
                 * Get current location and sort bar values
                 * aMathes[1] will contain '-'+pageNumber
                 */
                var aMatches = location.pathname.match(Friends.friendsPageRegEx);
                var sSortBy = $('.filter_search_select.sortby:firts').val();
                var sOrder = $('.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('order'):
                    sOrder = $(this).val();
                    break;
                }

                /**
                 * Redirect browser to the new location
                 */
                location.assign('/contacts-' + sSortBy + '-' + sOrder + (aMatches[1] ? aMatches[1] : ''));
            });
        }
    },
   
    
    /**
     * Sends AJAX request in order to add user as friend
     */
    addAsFriend: function(id) {
        var oClickedLink = $('.add_as_friend[rel="'+id+'"]');

        $.ajax({
            url: '/contacts',
            type: 'POST',
            dataType: 'json',
            data: {
                'do': 'process_request',
                'action': 'add',
                'id': id
            },

            /**
             * Before send request disable link and show loading picture
             */
            beforeSend: function(xhr) {
                oClickedLink.attr('rel', '')
                    .addClass('gray')
                    .parent().prev().addClass('loading');
            },

            /**
             * Change text of the link
             */
            success: function(data, status) {
                if ('ok' == data.type) {
                    oClickedLink.text('Pending Approval').css('cursor', 'default');
                    if ($('#js_requets_span').length) {
                        $('#js_requets_span').replaceWith('<a id="js_requests_link" href="/requests">Requests</a>');
                    }
                } else {
                    this.error();
                }
            },

            /**
             * Enable link for one more try
             */
            error: function(xhr, status) {
                oClickedLink.removeClass('gray')
                    .attr('rel', id);
            },

            /**
             * Hide loading picture
             */
            complete: function(xhr, status) {
                oClickedLink.parent().prev().removeClass('loading');
            }
        });

        return false;
    },

    /**
     * Sends AJAX request in order to remove user as friend
     */
    removeAsFriend: function(id) {
        var oClickedLink = $('.remove_as_friend[rel="'+id+'"]');

        $.ajax({
            url: '/contacts',
            type: 'POST',
            dataType: 'json',
            data: {
                'do': 'process_request',
                'action': 'remove',
                'id': id
            },

            /**
             * Before send request disable link and show loading picture
             */
            beforeSend: function(xhr) {
                oClickedLink.attr('rel', '')
                    .addClass('gray')
                    .parent().prev().addClass('loading');
            },
            
            /**
             * Change text of the link and class to rebind handler
             */
            success: function(data, status) {
                if ('ok' == data.type) {
                    if (location.pathname.match(Friends.friendsRequestPath)) {
                        var oUserToRemove = $('#user_' + id)
                            .add($('#user_' + id).prev())
                            .add($('#user_' + id).next());

                        $('#user_' + id).slideUp(function() {
                            oUserToRemove.remove();
                        });

                        $('#smallUser_' + id).slideUp();

                        $('#requestUser_' + id).slideUp(function() {
                            $(this).remove();

                            if (!$('.contact_request div.space').length) {
                                $('.contact_request').parent().replaceWith(
                                    '<div class="sh_p_block_height align_center" style="padding: 125px 0">'+
                                        'No Current Requests'+
                                    '</div>'
                                );

                                if (!$('#js_request_count').length) {
                                    $('#js_requests_link').replaceWith('<span id="js_requests_span">Requests</span>');
                                }
                            }
                        });
                        
                    } else {
                        oClickedLink.removeClass('remove_as_friend')
                            .addClass('add_as_friend')
                            .text('Add as Contact');
                    }
                }
            },

            /**
             * Hide loading picture
             */
            complete: function(xhr, status) {
                oClickedLink.attr('rel', id)
                    .removeClass('gray')
                    .parent().prev().removeClass('loading');
            }
        });

        return false;
    },
    
    
    		
    addAsAccept: function(id) {
        var oClickedLink = $('.accept_as_friend[rel="'+id+'"]');

        $.ajax({
            url: '/requests',
            type: 'POST',
            dataType: 'json',
            data: {
                'do': 'process_request',
                'id': id
            },

            /**
             * Before send request disable link and show loading picture
             */
            beforeSend: function(xhr) {
                oClickedLink
                    .removeClass('accept_as_friend')
                    .addClass('remove_as_friend')
                    .parent().prev().addClass('loading');

                if (!location.pathname.match(/^\/requests/i)) {
                    oClickedLink.text('Remove as Contact');
                }
            },

            /**
             * Change text of the link
             */
            success: function(data, status) {
                if ('ok' == data.type) {
                    if (location.pathname.match(Friends.friendsRequestPath)) {
                        var oUserToRemove = $('#user_' + id)
                            .add($('#user_' + id).prev())
                            .add($('#user_' + id).next());

                        $('#user_' + id).slideUp(function() {
                            oUserToRemove.remove();
                        });

                        $('#requestUser_' + id).slideUp(function() {
                            $(this).remove();
                            
                            if (!$('.contact_request div.space').length) {
                                $('.contact_request').parent().replaceWith(
                                    '<div class="sh_p_block_height align_center" style="padding: 125px 0">'+
                                        'No Current Requests'+
                                    '</div>'
                                );
                            }
                        });

                        if (data.count > 0) {
                            $('#js_request_count').text(data.count);
                        } else if(data.hasRequests) {
                            $('#js_requests_link').replaceWith('<a id="js_requests_link" href="/requests">Requests</a>');
                        } else {
                            $('#js_requests_link').replaceWith('<span id="js_requests_span">Requests</span>');
                        }


                        if (location.pathname.match(/^\/requests/i)) {
                            var oFriendsBox = $('.firends_left_box');

                            if (!oFriendsBox.find('.js_small_friend').length) {
                                oFriendsBox.find('.navigation').replaceWith(
                                    '<div class="float_left"></div>' +
                                    '<div class="float_right"></div>' +
                                    '<div class="clear">&nbsp;</div>'
                                );

                                oFriendsBox.prev().find('.other').html('<a href="'+$('.js_account_link').attr('href')+'/contacts">See All</a>');
                                $('.js_contacts_link').replaceWith('<a href="/contacts">Contacts</a>');
                            }

                            var oFriendsContainer = null;
                            if (oFriendsBox.find('.float_left .js_small_friend').length > oFriendsBox.find('.float_right .js_small_friend').length) {
                                oFriendsContainer = oFriendsBox.find('.float_right');
                                if (!oFriendsContainer.find('.js_small_friend').length) {
                                    oFriendsContainer.empty();
                                }
                            } else if ($('.firends_left_box .float_left .js_small_friend').length < 3) {
                                oFriendsContainer = oFriendsBox.find('.float_left');
                            }

                            if (oFriendsContainer) {
                                oFriendsContainer.prepend(
                                    '<a style="display:none;" class="js_small_friend" href="/'+(data.username)+'"  id="smallUser_'+id+'">'+
                                        '<img align="left" style="background: transparent url('+(data.url)+') center center no-repeat;" src="images/dot_1x1.gif" alt="'+(data.username)+'" title="'+(data.username)+'" width="70" height="70" border="0"/>'+
                                        '<br/>'+
                                        (data.name)+
                                    '</a>'
                                );

                                $('#smallUser_' + id).slideDown();
                            }
                        }

                    } 
                }
            }
        });

        return false;
    },

    
    rejectedFriend: function(id) {
        var oClickedLink = $('.rejected_friend[rel="'+id+'"]');

        $.ajax({
            url: '/requests',
            type: 'POST',
            dataType: 'json',
            data: {
                'do': 'process_request',
                'action': 'reject',
                'id': id
            },

            /**
             * Before send request disable link and show loading picture
             */
            beforeSend: function(xhr) {
                oClickedLink.parent().prev().addClass('loading');
            },

            /**
             * Change text of the link
             */
            success: function(data, status) {
                if ('ok' == data.type) {
                    if (location.pathname.match(Friends.friendsRequestPath)) {
                        var oUserToRemove = $('#user_' + id)
                            .add($('#user_' + id).prev())
                            .add($('#user_' + id).next());

                        $('#user_' + id).slideUp(function() {
                            oUserToRemove.remove();
                        });

                        $('#requestUser_' + id).slideUp(function() {
                            $(this).remove();

                            if (!$('.contact_request div.space').length) {
                                $('.contact_request').parent().replaceWith(
                                    '<div class="sh_p_block_height align_center" style="padding: 125px 0">'+
                                        'No Current Requests'+
                                    '</div>'
                                );
                            }
                        });
                                                
                    }

                    if (data.count > 0) {
                        $('#js_request_count').text(data.count);
                    } else if(data.hasRequests) {
                        $('#js_requests_link').replaceWith('<a id="js_requests_link" href="/requests">Requests</a>');
                    } else {
                        $('#js_requests_link').replaceWith('<span id="js_requests_span">Requests</span>');
                    }

                }
            }
        });

        return false;
    }
    
    
};

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