﻿var ProfileCommentsHelper = function(config) {
    //PRIVATE VARIABLES ---------------------------------------------------------------------------------------------------------------------------------------------- 
    var _config = config;

    var _contentType = 'application/json; charset=utf-8';
    var _type = 'Post';
    var _dataType = 'json';
    var _page = '';

    var _comments;
    var _parentId = '00000000-0000-0000-0000-000000000000';
    var _callType = 'create';
    var _currentIndex = -1;
    var _lastDeletedCommentIndex = -1;


    var popup = new ModalPopup('popupComment', 'comment-mask', 'ReplyText', false); //body, mask, textCapture, container page

    //EO: PRIVATE VARIABLES ----------------------------------------------------------------------------------------------------------------------------------------------

    var _loadComments = function() {
        _showSpinner();

        $.getJSON(_config.GetCommentsUrl, { userId: _config.FriendUserId }, _renderComments);
        _hideSpinner();
    }

    var _createComment = function() {
        _showSpinner();

        text = $('#users_Profile_comment').val();
        if (jQuery.trim(text).length > 0) {
            $.getJSON(_config.CreateCommentUrl, { commentText: text, parentId: '00000000-0000-0000-0000-000000000000', siblingId: '00000000-0000-0000-0000-000000000000' }, _createComment_Callback);
        } else {
            _hideSpinner();
        }

    }

    var _createComment_Callback = function(response) {
        _currentIndex = 0;
        _renderComments({ comments: response.comments });
        $('#users_Profile_comment').val('');
        _hideSpinner();
    }

    var _createReply_Callback = function(response) {
        _updateComment_Callback(response);
    }

    var _updateComment_Callback = function(response) {
        _siblingId = '00000000-0000-0000-0000-000000000000';
        if (!response.success) {
            alert(response.message);
        } else {
            _loadComments();
        }
    }

    var _renderComments = function(response) {
        _hideSpinner();
        _comments = response;
        $('#CommentsContainerProfile').empty();
        $('#CommentsContainerProfile').setTemplate($("#commentResultsTableProfile").html(), null, { filter_data: false });
        $('#CommentsContainerProfile').processTemplate(_comments);

        $('#comment' + _currentIndex).pulse({
            backgroundColors: ['yellow'],
            textColors: ['black'],
            speed: 500,
            duration: 2000
        });
        //$('#commentCountPost').text(response.commentsCount);

        _setupIcons(_comments.comments);
    }

    var _deleteComment = function(id, inx) {
        _lastDeletedCommentIndex = inx;
        $.post(_config.DelCommentUrl, { commentId: id }, _deleteComment_Callback, "json");
    }

    var _deleteComment_Callback = function(data) {
        if (data.success) {
            var cr = new Array();
            if (_lastDeletedCommentIndex > -1) {
                for (i = 0; i < _comments.comments.length; i++) {
                    if (_lastDeletedCommentIndex != i && _comments.comments[i].Comment.ParentId != data.parentId)
                        cr.push(_comments.comments[i]);
                }
                _comments.comments = cr;
            }
            _renderComments(_comments);
        } else {
            alert(data.message);
        }
        _lastDeletedCommentIndex = -1;
    }

    //  FRIENDING
    var _addFriend = function() {
        //url = _config.AddToFriendsUrl;
        //alert(url);
        $.getJSON(_config.AddFriendUrl, { initiatingUserId: _config.UserId, friendId: _config.FriendUserId }, _addFriend_Callback);
    }

    var _addFriend_Callback = function() {
        //$("#addToFriendsText").toggle();		
        $('.addFriends .addFriendText').hide();
        $('.addFriends .pendingFriendText').show();
    }

    var _removeFriend = function() {
        $.getJSON(_config.RemoveFriendUrl, { initiatingUserId: _config.UserId, friendId: _config.FriendUserId }, _removeFriend_Callback);
    }

    var _removeFriend_Callback = function() {
        $('.addFriends .removeFriendText').hide();
        $('.addFriends .sendMessageText').show();
        $('.addFriends .addFriendText').show();
        $('.addFriends .blockUserText').show();
    }

    var _acceptFriend = function() {
        _config.UserId = $('a[id^="lnkAcceptFriend_"]')[0].id.replace('lnkAcceptFriend_', '');
        $.getJSON(_config.AcceptFriendUrl, { initiatingUserId: _config.UserId, friendId: _config.FriendUserId }, _acceptFriend_ResponseCallback);
    }

    var _acceptFriend_ResponseCallback = function(response) {
        if (response.success)
            $.getJSON(_config.GetFriendRequestsUrl, { loggedInUser: response.loggedInUser }, _acceptFriendUI_Callback);
    }

    var _acceptFriendUI_Callback = function(response) {
        if (response.reqCount > 0)
            $('div[id^="div_"]').remove(); //remove selected friend request link
        else {
            $('#div_AllActions').remove(); //remove the accept all & reject all links
            $('div[id^="div_"]').remove(); //remove selected friend request link
            $('#msg').show(); //no more friend request left, show msg
        }
    }

    var _acceptFriend_Callback = function() {
        $('.addFriends .acceptFriendText').hide();
        $('.addFriends .removeFriendText').show();
        $('.addFriends .sendMessageText').show();
        $('.addFriends .blockUserText').show();
    }

    var _rejectFriend = function() {
        _config.UserId = $('a[id^="lnkRejectFriend_"]')[0].id.replace('lnkRejectFriend_', '');
        $.getJSON(_config.RejectFriendUrl, { initiatingUserId: _config.UserId, friendId: _config.FriendUserId }, _rejectFriend_Callback);
    }

    var _rejectFriend_Callback = function(response) {
        if (response.success) {
            $.getJSON(_config.GetFriendRequestsUrl, { loggedInUser: response.loggedInUser }, _rejectFriendUI_Callback);
        }
    }

    var _rejectFriendUI_Callback = function(response) {
        if (response.reqCount > 0)
            $('div[id^="div_"]').remove(); //remove selected friend request link
        else {
            $('div[id^="div_"]').remove(); //remove selected friend request link
            $('#msg').show(); //no more friend request left, show msg
        }
    }


    var _blockUser = function() {
        $.getJSON(_config.BlockUserUrl, { initiatingUserId: _config.UserId, friendId: _config.FriendUserId }, _blockUser_Callback);
    }

    var _blockUser_Callback = function() {
        $('.addFriends .blockUserText').hide();
        $('.addFriends .addFriendText').hide();
        $('.addFriends .sendMessageText').hide();
        $('.addFriends .pendingFriendText').hide();
        $('.addFriends .unblockUserText').show();
    }

    var _unblockUser = function() {
        $.getJSON(_config.UnblockUserUrl, { initiatingUserId: _config.UserId, friendId: _config.FriendUserId }, _unblockUser_Callback);
    }

    var _unblockUser_Callback = function() {
        $('.addFriends .unblockUserText').hide();
        $('.addFriends .sendMessageText').show();
        $('.addFriends .addFriendText').show();
        $('.addFriends .blockUserText').show();
    }

    //  CREATE NEW REPLY
    var _createNewReply = function() {
        commentText = popup.CommitChanges();
        if (jQuery.trim(commentText).length > 0)
            $.getJSON(_config.CreateCommentUrl, { commentText: commentText, parentId: _parentId, siblingId: _siblingId }, _createReply_Callback);
    }

    var _updatedComment = function() {
        updatedText = popup.CommitChanges();

        if (jQuery.trim(updatedText).length > 0) {
            $.post(_config.UpdateCommentUrl, { commentId: _comments.comments[_currentIndex].Comment.CommentId, commentText: updatedText }, _updateComment_Callback, "json");
        }
    }

    var _showSpinner = function() {
        $('#spinnerSubmitProfile').show();
    }

    var _hideSpinner = function() {
        $('#spinnerSubmitProfile').hide();
    }

    var _setup = function() {
        $.ajaxSetup({ cache: false });
        _loadComments();
    }

    // APPLY TEMPLATES FUNCTION //  ---------------------------------------------------------------------------------
    var _currentTemplate = '';
    function ApplyTemplate(data, template) {
        if (_currentTemplate != template) {
            _currentTemplate = template;
            $('#CommentsContainerProfile').setTemplate(_currentTemplate, null, { filter_data: false }); //filter data false causes html to be allowed, otherwise the <br>'s show
        }
        $('#CommentsContainerProfile').processTemplate(data);
    }

    // AJAX CALLER
    var _executeServiceCall = function(methodName, methodParams, successCallback, failCallback, successCallbackParams) {
        if (methodParams == null || methodParams == '')
            methodParams = '{}';
        else {
            methodParams = JSON.stringify(methodParams);
        }
        $.ajax({
            type: _type,
            url: _page + methodName,
            data: methodParams,
            contentType: _contentType,
            dataType: _dataType,
            success: function(response) {
                if (successCallback != null)
                    successCallback(response, successCallbackParams);
            },
            error: function(message) {
                if (failCallback != null)
                    failCallback(message);
                else
                    alert(message.responseText);
            }
        });
    }

    //EXPLICIT BINDINGS ---------------------------------------------------------------------------------------------------------------------------------------------- EXPLICIT BINDINGS

    //ADD TO FRIENDS
    $('#addFriendLink').click(function() {
        _addFriend();
    });

    $('#addFriendLinkBlog').click(function() {
        debugger;
        alert('test'); //_addFriend();
    });

    $('#testytest').click(function() {
        debugger;
        alert('freaking hell'); //_addFriend();
    });


    $('#removeFriendLink').click(function() {
        _removeFriend();
    });

    $('#acceptFriendLink').click(function() {
        _acceptFriend();
    });

    $('a[id^="lnkAcceptFriend_"]').click(function() {
        _acceptFriend();
    });

    $('a[id^="lnkRejectFriend_"]').click(function() {
        _rejectFriend();
    });

    $('#blockUserLink').click(function() {
        _blockUser();
    });

    $('#unblockUserLink').click(function() {
        _unblockUser();
    });

    //CREATE A NEW COMMENT - COMMENT DIRECTLY ON POST
    $('#enterCommentProfile').click(function() {
        _createComment();
    });


    //REPLIED TO A SPECIFIC COMMENT
    $('#btnCommitChangesProfile').click(function() {
        if (_callType == 'create') {
            _createNewReply();
        }
        else if (_callType == 'update') {
            _updatedComment();
        }
    });

    //CANCELLED THE REPLY
    $('#popupCloseProfile').click(function() {
        popup.CancelComment();
        _parentId = '00000000-0000-0000-0000-000000000000';
    });

    var _setupIcons = function(comments) {
        // BIND THE CALLBACK TO THEIR RESPECTIVE ELEMENTS //  ---------------------------------------------------------------------------------
        for (var i = 0; i < comments.length; i++) {
            if (_config.IsLoggedIn) {
                $('#ri_' + i).click(function() {
                    var inx = _getIndexFromId(this);
                    _sci(parseInt(inx) + 1);
                    _parentId = comments[inx].Comment.ParentId != '00000000-0000-0000-0000-000000000000' ? comments[inx].Comment.ParentId : comments[inx].Comment.CommentId;
                    _siblingId = comments[inx].Comment.ParentId != '00000000-0000-0000-0000-000000000000' ? comments[inx].CommentId : '00000000-0000-0000-0000-000000000000';

                    _callType = 'create';

                    popup.SetText('');
                    popup.PostComment();
                });
            }


            if (_isMyComment(comments[i].UserId) || _config.IsOwner) {
                $('#ei_' + i).click(function() {
                    _sci(_getIndexFromId(this));

                    _callType = 'update';
                    var r = /<br \/>/g;

                    popup.SetText(comments[_currentIndex].Comment.Message.replace(r, '\n'));
                    popup.PostComment();
                });


                $('#di_' + i).click(function() {
                    if (confirm(_config.DeleteConfirm)) {
                        //SHOW SPINNER
                        _showSpinner();
                        inx = _getIndexFromId(this);
                        _sci(-1);
                        _deleteComment(comments[inx].Comment.CommentId, inx);
                    }
                });
            }
        }
    }

    var _sci = function(inx) { _currentIndex = inx; };

    var _getIndexFromId = function(o) {
        var inx = o.id.indexOf('_');
        if (inx > 0)
            inx++;
        return o.id.slice(inx);
    }

    var _isMyComment = function(userId) {
        return ((userId != null) && (userId == _config.UserId));
    }

    //end of: EXPLICIT BINDINGS ----------------------------------------------------------------------------------------------------------------------------------- end of: EXPLICIT BINDINGS 


    //  PUBLICS
    return {
        Setup: function() {
            _setup();
        }
    }
};
