$.foxyutils = {
    /**
     * Adds a file to an fstable, the foxyfile is a dictionary.
     */
    add_to_fstable: function(foxyfile, service_name) {
        var size_mb = foxyfile['size'] / 1024 / 1024;
        var name = foxyfile['name'];
        var anchor_id = "file_" + foxyfile['file_id'];
        $("#foxyfiles > table > tbody").append("<tr id=" + anchor_id + " value=" + foxyfile["file_id"] + "><td width=\"70%\" class=\"tableCells\"><a href=\"#\" style=\"border:none;\"><img src=\"/static/img/generic/close_icon.png\" alt=close width=11 height=10 /></a> " + name + "</td><td width=\"30%\" class=tableCells value=" + size_mb.toFixed(2) + ">" + size_mb.toFixed(2) + "&nbsp;<a href=\"#\" style=\"border:none;\"><img src=\"/static/img/generic/up_icon.png\" alt=\"up\" width=\"13\" height=\"12\" /></a><a href=\"#\" style=\"border:none;\"><img src=\"/static/img/generic/down_icon.png\" alt=\"down\" width=\"13\" height=\"12\" /></a></td></tr>");

        // Activates the delete button.
        var sel_delete_btn = $("#" + anchor_id + ' > td > a:eq(0)');
        sel_delete_btn.button().click(function() {
            var row = sel_delete_btn.parent().parent();

            // Find the size of the file we're about to delete.
            del_size = parseFloat(row.find("td:eq(1)").attr("value"))

            var full_url = $.sprintf("/fsitems/%s/%s/delete/", service_name, row.attr('value'));
            $.ajax({
                type: 'delete',
                url: full_url,
                success: function(response) {
                    row.remove();
                    var files = $.foxyutils.get_files_from_fstable();
                    if (files.length < 1)
                    {
                        $.foxyutils.hide_fstable();
                    }

                    // subtract from total
                    $.foxyutils.subtract_from_total_fstable(del_size);
                }
            });

            return false;
        });

        // Move up button.
        $("#" + anchor_id + ' > td > a:eq(1)').button().click(function() {
            var row = $(this).parent().parent();
            var prevRow = row.prev();
            if (prevRow.length == 0)
            {
                return false;
            }

            // We need to make sure the prev row is a file.
            if ($.string(prevRow.attr("id")).startsWith("file_"))
            {
                row.insertBefore(prevRow);
            }

            return false;
        });

        // Move down button.
        $("#" + anchor_id + ' > td > a:eq(2)').button().click(function() {
            var row = $(this).parent().parent();
            var nextRow = row.next();
            if (nextRow.length != 0)
            {
                row.insertAfter(nextRow);
            }
            return false;
        });

        // Add to total
        $.foxyutils.add_to_total_fstable(size_mb);
    },

    add_to_total_fstable: function(num) {
        $selector = $("#foxyfiles > table > tfoot td:eq(1)");
        old_val = parseFloat($selector.html());

        new_val = old_val + num;
        if (!isNaN(new_val))
        {
            $selector.html(new_val.toFixed(2));
        }
    },

    subtract_from_total_fstable: function(num) {
        $selector = $("#foxyfiles > table > tfoot td:eq(1)");
        old_val = parseFloat($selector.html());

        new_val = old_val - num;
        if (!isNaN(new_val))
        {
            $selector.html(new_val.toFixed(2));
        }
    },

    /**
     * Returns all files from the fstable
     */
    get_files_from_fstable: function() {
        var ret = new Array();
        $("#foxyfiles > table > tbody").children().each(function() {
            var tr = $(this);
            if ($.string(tr.attr("id")).startsWith("file_"))
            {
                ret.push({
                    id: tr.attr("value"),
                    size: parseFloat(tr.find("td:eq(1)").attr("value"))
                });
            }
        });

        return ret;
    },

    /**
     * Returns all file ids from the fstable
     */
    get_file_ids_from_fstable: function() {
        var ret = new Array();
        $("#foxyfiles > table > tbody").children().each(function() {
            var tr = $(this);
            if ($.string(tr.attr("id")).startsWith("file_"))
            {
                ret.push(tr.attr("value"));
            }
        });

        return ret;
    },

    hide_fstable: function() {
        $("#foxyfiles").css("display", "none");
    },

    show_fstable: function() {
        $("#foxyfiles").css("display", "");
    },

    clear_fstable: function(service_name) {
        var files = $.foxyutils.get_files_from_fstable();
        $.each(files, function(index, file) {
            var delete_url = "/fsitems/" + service_name + "/" + file.id + "/delete/";

            $.ajax({
                url: delete_url,
                type: 'DELETE',
                success: function(resp) {
                    // Subtract from total
                    $.foxyutils.subtract_from_total_fstable(file.size);
                }
            });
        });

        $('#foxyfiles > table > tbody').children().remove();
        $.foxyutils.hide_fstable();
    },

    /**
     * Fills the fstable using the backend.
     */
    fill_fstable: function(url, service_name) {
        $.get(url, function(data) {
            var added = false;
            $.each(data, function(index, foxyfile_obj) {
                if (foxyfile_obj.is_outgoing == false) {
                    $.foxyutils.add_to_fstable(foxyfile_obj, service_name);
                    added = true;
                }
            });

            if (added)
            {
                $.foxyutils.show_fstable();
            }
        });
    }
}

