/* Functions */

function userCollectionListPaginate(e) {
    if (e.loading) {
        $("#ReviewsBlock .content_abstract_tertiarynav_content").html('<div id="ratings_loading" class="loading" style="display:block;"></div>');
    }

    $.ajax({
        type: "POST",
        url: "/user/object/" + e.section + "/" + e.section + "_list_rpc.php",
        data: e.data,
        success: function(text) {
            $("#" + e.section + "_list").html(text);
        }
    });

    return false;
}

function friendRequest(id, userid, action, loc) {
    el = $("#" + id);

    if (action == 'add') {
        el.rt_overlay({
            target: "widgetize",
            target_call: el.attr("id"),
            coordinates_xoffset: ( loc.match(/^friends_list/) ) ? 140:10,
            auto_open: true
        });
    } else if (action == 'delete') {
        var link = el.attr("rel");

        el.cluetip({
            width: 140,
            activation : 'click',
            sticky : true,
            mouseOutClose : true,
            ajaxCache : false,
            ajaxSettings : {
                type : "POST",
                data : { id : userid, action : action }
            },
            onShow : function () {
                $("#tooltip_confirmation_cancel").click(function() {
                    $("#cluetip-close").click();
                    return false;
                });

                $("#tooltip_confirmation_submit").click(function() {
                    if (action == 'delete') {
                        if (loc == 'friends_list') {
                            var dom_id = "22-" + userid;
                            $("#main_row_" + dom_id).before('<tr><td class="onlyCol" colspan="' + ( ($("#main_row_" + dom_id + " td").length > 1) ? $("#main_row_" + dom_id + " td").length : 2 ) + '"><div class="loading_squares"></td></td></tr>');
                            $("." + dom_id).remove();
                        }
                    }

                    $.ajax({
                        type: "POST",
                        url: link,
                        data: { rpc : true, id : userid, action : action, loc : loc },
                        dataType : "json",
                        success: function(response) {
                            if (response.success) {
                                $("#cluetip-close").click();

                                if (response.html) {
                                    $.each(response.html, function(k, v) {
                        				$(k).html(v);
                        			});
                                }

                                if (action == 'delete') {
                                    if (loc == 'friends_list') {
                                        if (response.items > 0) {
                                            var data = { section: "friends", data: collection_list_page_data };
                                            userCollectionListPaginate(data);
                                        } else {
                                            location.reload(true);
                                        }
                                    }
                                }
                            }
                        }
                    });

                    return false;
                });
            }
        });

        if (document.createEventObject) {
            document.getElementById(id).fireEvent("onclick");
        } else if (document.createEvent) {
            el.click();
        }
    }
}

function favoriteRequest(id, userid, action, loc) {
    var el = $("#" + id);
    var link = el.attr("rel");

    el.cluetip({
        width: 140,
        activation : 'click',
        sticky : true,
        mouseOutClose : true,
        ajaxCache : false,
        ajaxSettings : {
            type : "POST",
            data : { id : userid, action : action }
        },
        onShow : function () {
            $("#tooltip_confirmation_cancel").click(function() {
                $("#cluetip-close").click();
                return false;
            });

            $("#tooltip_confirmation_submit").click(function() {
                if (action == 'delete') {
                    if (loc == 'favorites_list') {
                        var dom_id = "22-" + userid;
                        $("#main_row_" + dom_id).before('<tr><td class="onlyCol" colspan="' + ( ($("#main_row_" + dom_id + " td").length > 1) ? $("#main_row_" + dom_id + " td").length : 2 ) + '"><div class="loading_squares"></td></td></tr>');
                        $("." + dom_id).remove();
                    }
                }

                $.ajax({
                    type: "POST",
                    url: link,
                    data: { rpc : true, id : userid, action : action, loc : loc },
                    dataType : "json",
                    success: function(response) {
                        if (response.success) {
                            $("#cluetip-close").click();

                            if (response.html) {
                                $.each(response.html, function(k, v) {
                    				$(k).html(v);
                    			});
                            }

                            if (action == 'delete') {
                                if (loc == 'favorites_list') {
                                    if (response.items > 0) {
                                        var data = { section: "favorites", data: collection_list_page_data };
                                        userCollectionListPaginate(data);
                                    } else {
                                        location.reload(true);
                                    }
                                }
                            }
                        }
                    }
                });

                return false;
            });
        }
    });

    if (document.createEventObject) {
        document.getElementById(id).fireEvent("onclick");
    } else if (document.createEvent) {
        el.click();
    }
}

function messageRequest(id, mail_topic_id, action, loc) {
    var el = $("#" + id);
    var link = el.attr("rel");

    el.cluetip({
        width: 140,
        activation : 'click',
        sticky : true,
        mouseOutClose : true,
        ajaxCache : false,
        ajaxSettings : {
            type : "POST",
            data : { id : mail_topic_id, action : action }
        },
        onShow : function () {
            $("#tooltip_confirmation_cancel").click(function() {
                $("#cluetip-close").click();
                return false;
            });

            $("#tooltip_confirmation_submit").click(function() {
                if (action == 'delete') {
                    if (loc == 'messages_list') {
                        var dom_id = "main_row_" + mail_topic_id;
                        $("#" + dom_id).before('<tr><td class="onlyCol" colspan="' + $("#" + dom_id + " td").length + '"><div class="loading_squares"></td></td></tr>').remove();
                    }
                }

                $.ajax({
                    type: "POST",
                    url: link,
                    data: { rpc : true, id : mail_topic_id, action : action, loc : loc },
                    dataType : "json",
                    success: function(response) {
                        if (response.success) {
                            $("#cluetip-close").click();

                            if (action == 'delete') {
                                if (loc == 'messages_view') {
                                    window.location = "/user/messages/";
                                } else if (loc == 'messages_list') {
                                    $.ajax({
                                        type: "POST",
                                        url: "/user/messages/messages_list_rpc.php",
                                        data: collection_list_page_data,
                                        success: function(text) {
                                            $("#messages_list").html(text);
                                        }
                                    });
                                }
                            } else if (action == 'remove_thread') {
                                window.location = "/user/messages/";
                            }
                        }
                    }
                });

                return false;
            });
        }
    });

    if (document.createEventObject) {
        document.getElementById(id).fireEvent("onclick");
    } else if (document.createEvent) {
        el.click();
    }
}

function messageSendUser(id, userid, loc, viewport) {
    el = $("#" + id);
    var xoffset = (viewport == 'right') ? '180' : '10';

    el.rt_overlay({
        target: "widgetize",
        target_call: el.attr("id"),
        coordinates_xoffset: xoffset,
        auto_open: true
    });
}

function blockRequest(id, userid, action, loc) {
    var el = $("#" + id);
    var link = el.attr("rel");

    el.cluetip({
        width: 140,
        activation : 'click',
        sticky : true,
        mouseOutClose : true,
        ajaxCache : false,
        ajaxSettings : {
            type : "POST",
            data : { id : userid, action : action }
        },
        onShow : function () {
            $("#tooltip_confirmation_cancel").click(function() {
                $("#cluetip-close").click();
                return false;
            });

            $("#tooltip_confirmation_submit").click(function() {
                $.ajax({
                    type: "POST",
                    url: link,
                    data: { rpc : true, id : userid, action : action, loc : loc },
                    dataType : "json",
                    success: function(response) {
                        if (response.success) {
                            $("#cluetip-close").click();

                            if (response.html) {
                                $.each(response.html, function(k, v) {
                    				$(k).html(v);
                    			});
                            }
                        }
                    }
                });

                return false;
            });
        }
    });

    if (document.createEventObject) {
        document.getElementById(id).fireEvent("onclick");
    } else if (document.createEvent) {
        el.click();
    }
}

function sendFriendRequest(id, dom_id, loc) {
    el = $("#" + id);

    el.rt_overlay({
        target: "widgetize",
        target_call: el.attr("id"),
        coordinates_xoffset: 10,
        auto_open: true
    });
}

function groupModRequest(id, groupid, userid, loc) {
    el = $("#" + id);

    el.rt_overlay({
        target: "widgetize",
        target_call: el.attr("id"),
        coordinates_xoffset: 10,
        auto_open: true
    });
}

function groupMemberRequest(id, groupid, userid, action, loc) {
    var el = $("#" + id);
    var link = el.attr("rel");

    el.cluetip({
        width: 140,
        activation : 'click',
        sticky : true,
        mouseOutClose : true,
        ajaxCache : false,
        ajaxSettings : {
            type : "POST",
            data : { gid : groupid, uid : userid, action : action, loc : loc }
        },
        onShow : function () {
            $("#tooltip_confirmation_cancel").click(function() {
                $("#cluetip-close").click();
                return false;
            });

            $("#tooltip_confirmation_submit").click(function() {
                $.ajax({
                    type: "POST",
                    url: link,
                    data: { rpc : true, gid : groupid, uid : userid, action : action, loc : loc },
                    dataType : "json",
                    success: function(response) {
                        if (response.success) {
                            $("#cluetip-close").click();

                            if (response.html) {
                                $.each(response.html, function(k, v) {
                    				$(k).html(v);
                    			});
                            }

                            if (action == 'delete') {
                                if (loc == 'groups_members_list') {
                                    var dom_id = "main_row_25-22-" + groupid + "-" + userid;
                                    $("#" + dom_id).remove();
                                }
                            }
                        }
                    }
                });

                return false;
            });
        }
    });

    if (document.createEventObject) {
        document.getElementById(id).fireEvent("onclick");
    } else if (document.createEvent) {
        el.click();
    }
}

function pictureRequest(id, pic_id, action) {
    var el = $("#" + id);
    var link = el.attr("rel");

    if (action == 'make_profile') {
        $.ajax({
            type: "POST",
            url: link,
            data: { rpc : true, id : pic_id, action : action },
            dataType : "json",
            success: function(response) {
                if (response.success) {
                    $("#make_profile_pic_link").before(response.message).remove();
                }
            }
        });
    } else {
        el.cluetip({
            width: 140,
            activation : 'click',
            sticky : true,
            mouseOutClose : true,
            ajaxCache : false,
            ajaxSettings : {
                type : "POST",
                data : { id : pic_id, action : action }
            },
            onShow : function () {
                $("#tooltip_confirmation_cancel").click(function() {
                    $("#cluetip-close").click();
                    return false;
                });

                $("#tooltip_confirmation_submit").click(function() {
                    $.ajax({
                        type: "POST",
                        url: link,
                        data: { rpc : true, id : pic_id, action : action },
                        dataType : "json",
                        success: function(response) {
                            if (response.success) {
                                if (action == 'delete') {
                                    window.location = "/user/" + response.userid + "/pictures/";
                                }

                                $("#cluetip-close").click();
                            }
                        }
                    });

                    return false;
                });
            }
        });

        if (document.createEventObject) {
            document.getElementById(id).fireEvent("onclick");
        } else if (document.createEvent) {
            el.click();
        }
    }
}

function groupPictureRequest(id, pic_id, action) {
    var el = $("#" + id);
    var link = el.attr("rel");

    el.cluetip({
        width: 140,
        activation : 'click',
        sticky : true,
        mouseOutClose : true,
        ajaxCache : false,
        ajaxSettings : {
            type : "POST",
            data : { id : pic_id, action : action }
        },
        onShow : function () {
            $("#tooltip_confirmation_cancel").click(function() {
                $("#cluetip-close").click();
                return false;
            });

            $("#tooltip_confirmation_submit").click(function() {
                $.ajax({
                    type: "POST",
                    url: link,
                    data: { rpc : true, id : pic_id, action : action },
                    dataType : "json",
                    success: function(response) {
                        if (response.success) {
                            if (action == 'delete') {
                                window.location = "/groups/" + response.groupid + "/pictures/";
                            }

                            $("#cluetip-close").click();
                        }
                    }
                });

                return false;
            });
        }
    });

    if (document.createEventObject) {
        document.getElementById(id).fireEvent("onclick");
    } else if (document.createEvent) {
        el.click();
    }
}

function requestInviteHandler(request_id, type, action, data) {
    $.ajax({type: "POST",
            url: '/ajax/user/request_invite.php',
            data: { type: type, action: action, data: data },
            dataType : "json",
            success: function(response) {
                if (response.success) {
                    $("#request_row_" + request_id).remove();

                    if ($("#requestsTbl tbody tr").length == 0) {
                        $("#requestsTbl").before('<p class="messages"><span class="empty">You have no pending requests or invitations.</span></p>').remove();
                    }
                }
            }
    });

    return false;
}

function bindUpdateCluetip() {
    $("a.update_cluetip_link")
        .removeAttr('title').find('img').removeAttr('alt').end()
        .unbind("bindUpdateCluetip")
        .bind("bindUpdateCluetip", function() {
            $(this).cluetip({ width: 175, leftOffset: 3, topOffset: 5, positionBy: 'fixed', hoverIntent: { sensitivity: 1, interval: 50, timeout: 0 } });
        })
        .trigger("bindUpdateCluetip");
}

function showMoreUpdates(cur_date, timestamp, alt) {
    $("#updates_showmore_row td").html('<div class="loading_squares"></div>');
    
    $.ajax({type: "POST",
            url: '/ajax/user/showmore_updates.php',
            data: { 'cur_date': cur_date, 'timestamp': timestamp, 'alt': alt },
            dataType : "html",
            success: function(html) {
                $("#updates_showmore_row").remove();
                $("#updates_notifications_main tbody").append(html);
            }
    });

    return false;
}

// Initialize the id of the comment that has been replied to 0
var prev_comment_reply_id = 0;

function snCommentReply(dom_id, object_id, parent_id) {
    var el = $("#" + dom_id);
    var id = el.attr("id").split("_").pop();
    var reply_box = $("div#comment_reply_box_container_" + id);
    var arrowTrgt = el.children('img.icon:first');
    
    if (id != prev_comment_reply_id) {
        // Reset initial values
        if (prev_comment_reply_id != 0) {
            $('a#post_link_' + prev_comment_reply_id).children('img.icon:first').attr('src', arrow_right);
        }

        $('form#comments_input_form input[name=object_id]').val(object_id);
        $('form#comments_input_form input[name=parent_id]').val(parent_id);
        $('form#comments_input_form textarea[name=comment]').val('');
        $('form#comments_input_form div.counter span.count').html($('form#comments_input_form input[name=maxlength]').attr('value'));
        submitBtnToggle($('form#comments_input_form button[name=post]'), 'disabled');
        
        // Display comment box
        $("div#comment_reply_box").hide();
        reply_box.append($("#comment_reply_box"));
        $("div#comment_reply_box").slideDown(animSpeed);
        arrowTrgt.attr('src', arrow_down);

        prev_comment_reply_id = id;
    } else {
        if (reply_box.html() != '') {
            $("div#comment_reply_box").slideToggle(animSpeed);
            arrowExpandToggle(el);
        } else {
            $("div#comment_reply_box").hide();
            reply_box.append($("#comment_reply_box"));
            $("div#comment_reply_box").slideDown(animSpeed);
            arrowTrgt.attr('src', arrow_down);
        }
        
        // Weird IE bug where the form values don't stick
        $('form#comments_input_form input[name=object_id]').val(object_id);
        $('form#comments_input_form input[name=parent_id]').val(parent_id);
    }
}

function snCommentDelete(id, item_dom_id) {
    var el = $("#delete_comment_link_" + id);
    
    el.cluetip({
      width: 140,
      activation : 'click',
      sticky : true,
      mouseOutClose : true,
      ajaxCache : false,
      ajaxSettings : {
          type : "POST",
          data : { type : "delete" }
      },
      onShow : function () {
          $("#tooltip_confirmation_cancel").click(function() {
              $("#cluetip-close").click();
              return false;
          });
    
          $("#tooltip_confirmation_submit").click(function() {
              $.ajax({
                  type: "POST",
                  url: "/user/object/_common/del_comment_rpc.php",
                  data: { id : id, type : $("#comments_input_form input[name=type]").val() },
                  dataType : "json",
                  success: function(response) {
                      if (response.success) {
                          $("#cluetip-close").click();
    
                          $("#comment_container_" + id).remove();
    
                          // Update the comment count
                          var new_comment_count = $("#comment_count_" + item_dom_id).html().split(" ")[0] - response.affected;
    
                          $("#comment_count_" + item_dom_id).html( new_comment_count + " " + ((new_comment_count != 1) ? "Comments" : "Comment") );
    
                          if (new_comment_count == 0) {
                              temp = $("#comment_count_" + item_dom_id);
                              $("#count_toggle_label_" + item_dom_id).html("");
                              $("#count_toggle_label_" + item_dom_id).prepend(temp);
    
                              if ($("#comments_container_" + item_dom_id).length > 0) {
                                  $("#comments_container_" + item_dom_id).removeClass("selected");
                              }
                          }
                          
                          if (new_comment_count < 2) {
                            $("#comments_sort_" + item_dom_id).parent("label").hide();
                          } else if ($("#comments_list_" + item_dom_id).children(".comment_container").length < 2) {
                              $("#comments_sort_" + item_dom_id).parent("label").hide();
                          }
    
                          if ($("#comments_input_form input[name=parent_id]").attr("value") != 0) {
                              // Update the reply count
                              var new_reply_count = parseInt($("#comments_item_reply_count_" + $("#comments_input_form input[name=parent_id]").attr("value")).html().split(" ")[0], 10) - 1;
    
                              $("#comments_item_reply_count_" + $("#comments_input_form input[name=parent_id]").attr("value")).html( new_reply_count + " " + ((new_reply_count != 1) ? "Replies" : "Reply") );
                          }
                      }
                  }
              });
    
              return false;
          });
      }
    });
    
    if (document.createEventObject) {
        document.getElementById(el.attr("id")).fireEvent("onclick");
    } else if (document.createEvent) {
        el.click();
    }
}

/* Global */

$(document).ready(function(){
    
    // Destroys cluetips if user clicks anything else
    $('body').not('#cluetip').click(function(){
        $("#cluetip-close").trigger('click');
    });
    
    $('.ui-tabs-nav a').click(function(){
        $('#cluetip-close').trigger('click');
    });
    
});

if ($.browser.version.substr(0,1) == 6) {

    $(document).ready(function(){

        // Data DL's need :/.first-child
        $('.data dt:first-child').addClass('first-child');

        // Sidebar table's need :/.first-child
        $('.sidebar table tr:first-child').addClass('first-child');

    });

}