/* global Bdf,$$,Balayage,CodeMirror,Pane */

Balayage.ContentForm = {};

Balayage.ContentForm.load = function (balayageContent, isInStock) {
    if (!isInStock) {
        isInStock = false;
    }
    var balayageName = balayageContent.balayageName;
    var contentPath = balayageContent.path;
    var content = balayageContent.content;
    var formId = Bdf.generateId();
    var saveId = formId + "_button_save";
    var textareaId = formId + "_content";
    var htmlContent = Bdf.render("balayage:contentform", {
        action: Bdf.URL + "exportation",
        formId: formId,
        balayageName: balayageName,
        path: contentPath,
        content: content
    });
    if (isInStock) {
        Pane.addStockUnit(htmlContent);
    } else {
        $$("layout_main").html(htmlContent);
    }
    $$(formId, "button_delete").click(function () {
        Balayage.Overlay.showContentRemoveConfirm(balayageName, contentPath);
    });
    $$(formId, "button_stock").click(function () {
        Pane.moveMainToStock();
    });
    $$(formId).ajaxForm({
        beforeSerialize: function ($form, options) {
            if (isInStock) {
                return false;
            } else {
                codeMirror.save();
                return true;
            }
        },
        dataType: "json",
        success: function (data, textStatus, jqXHR, $form) {
            if (Bdf.checkError(data)) {
                Pane.setChange(false);
                Bdf.showCommandMessage(data.commandMessage);
                Balayage.updateBalayage(data.balayage);
            }
        }
    });
    var codeMirror = Bdf.toCodeMirror(textareaId, {
        lineWrapping: false,
        lineNumbers: true,
        indentUnit: 4,
        theme: 'bdf',
        readOnly: isInStock
    });
    var mode = Bdf.getMatchingCodeMirrorMode(contentPath);
    if (mode.length > 0) {
        codeMirror.setOption("mode", mode);
    }
    codeMirror.on("change", function () {
        Pane.setChange(true);
    });
    $$(formId).data("stockHandler", _stockHandler);
    Pane.checkState();
    Pane.checkTooltip($$(formId));

    
    function _stockHandler(stock) {
        isInStock = stock;
        codeMirror.setOption("readOnly", stock);
    }

};