/* global Bdf,$$,CentralSphere,Pane */

CentralSphere.Metadata = {};

CentralSphere.Metadata.init = function (sphereName, callback) {
    CentralSphere.Ajax.loadMetadata(sphereName, function (metadata) {
        if (callback) {
            callback(sphereName, metadata);
        } else {
            CentralSphere.Metadata.load(sphereName, metadata);
        }
    });
};

CentralSphere.Metadata.load = function (sphereName, metadata) {
    var formId = Bdf.generateId();
    $$("layout_main").html(Bdf.render("centralsphere:metadataform", {
        action: Bdf.URL + "multi-sphere",
        sphereName: sphereName,
        formId: formId,
        labelArray: Bdf.toLabelArray(metadata.labelMap),
        labelsLocKey: "_ title.multi.titlelabels_sphere",
        attributes: Bdf.attrMapToString(metadata.attrMap),
        attributesLocKey: "_ title.multi.attributes_sphere"
    }));
    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));
                }
            }
        }
    });
    var attributesCodeMirror = Pane.initAttributesDetails(formId);
    Pane.checkState();    
};
