/* global Bdf,MultiAdmin,Overlay,$,$$,Pane */

MultiAdmin.Metadata = {};

MultiAdmin.Metadata.init = function (callback) {
    MultiAdmin.Metadata.loadAjax(function (metadata) {
        MultiAdmin.Metadata.update(metadata);
        if (callback) {
            callback(metadata);
        } else {
            MultiAdmin.Metadata.load(metadata);
        }
    });
};

MultiAdmin.Metadata.update = function (metadata) {
    Bdf.langConfiguration = metadata.langConfiguration;
};

MultiAdmin.Metadata.load = function (metadata) {
    var formId = Bdf.generateId();
    $$("layout_main").html(Bdf.render("multiadmin:metadataform", {
        action: Bdf.URL + "multi-admin",
        formId: formId,
        labelArray: Bdf.toLabelArray(metadata.labelMap),
        labelsLocKey: "_ title.multi.titlelabels",
        attributes: Bdf.attrMapToString(metadata.attrMap),
        attributesLocKey: "_ title.multi.attributes",
        workingLangs: metadata.langConfiguration.workingLangArray.join(";"),
        authority: metadata.authority
    }));
    Bdf.Deploy.init($$("layout_main"));
    $$(formId).ajaxForm({
        beforeSerialize: function ($form, options) {
            attributesCodeMirror.save();
            return true;
        },
        dataType: "json",
        success: function (data, textStatus, jqXHR, $form) {
            if (Bdf.checkError(data)) {
                Pane.setChange(false);
                if (Bdf.showCommandMessage(data.commandMessage)) {
                    Bdf.updateDefaultValues($$(formId));
                    MultiAdmin.Metadata.update(data.metadata);
                }
            }
        }
    });
    var attributesCodeMirror = Pane.initAttributesDetails(formId);
    Pane.checkState();    
};

MultiAdmin.Metadata.loadAjax = function (callback) {
    $.ajax({
        url: Bdf.URL + "multi-admin",
        data: {
            json: "multimetadata"
        },
        dataType: Bdf.jsonDataType,
        success: function (data, textStatus) {
            if (MultiAdmin.testAuthentification(data)) {
                Bdf.checkData(data, "metadata", callback);
            }
        }
    });
};
