/**
 * @overview Life of German Reallife - Faction Manager Rank (script.js)
 * @author hydrant
 * @copyright (c) 2008 - 2018 Life of German
 */

var dndConfig = {
    onDragClass: "rankDnD"
};

$(document).ready(function () {
    mp.trigger("onManageFactionRanksLoaded");

    $("table#rank-table").on("click", "tr td span", function () {
        $(this).parent().parent().remove();
        $("table#rank-table").tableDnD(dndConfig);
    });

    $("#btn-add-new-rank").click(function () {
        var toAdd = $("input#input-new-rank").val();
        if (toAdd.length === 0) return;
        $("input#input-new-rank").val("");
        $("table#rank-table").append("<tr><td style='display:none;'><input disabled class='input-id' value='0' /></td><td><input class='input-rankname' value='" + toAdd + "' /><td><span class='delete-rank'>X</span></td></tr>");
        $("table#rank-table").tableDnD(dndConfig);
    });
    
    $(".save-btn").click(function () {
        var rows = $("table#rank-table tr");
        rows = rows.slice(1);

        if (rows.length === 0) {
            alert("Es muss mindestens ein Rang angegeben werden!");
            return;
        }

        var rankArray = new Array();
        rows.each(function () {
            var id = $(this).find("input.input-id")[0].value;
            var name = $(this).find("input.input-rankname")[0].value;

            var rank = new Object();
            rank.Id = parseInt(id);
            rank.Name = name;

            rankArray.push(rank);
        });

        var json = JSON.stringify(rankArray);

        mp.trigger('saveFactionRankData', json);
    });
});

function loadData(rankData) {
    $("table#rank-table tr").remove();
    $("table#rank-table").append("<tr class='nodrop nodrag'><th style='display:none;'>ID</th><th>Fraktions-Ränge</th></tr>");
    
    rankData.forEach(function (rank) {
        $("table#rank-table").append("<tr><td style='display:none;'><input disabled class='input-id' value='" + rank.Id + "' /></td><td><input class='input-rankname' value='" + rank.Name + "' /><td><span class='delete-rank'>X</span></td></tr>");
    });

    $("table#rank-table").tableDnD(dndConfig);
}