jscape.domain = jscape.domain || {};

/** @class */
jscape.TradingPartner = Class.extend(
    /** @lends {jscape.TradingPartner.prototype} */
{
    /** @constructor */
    initialize: function(a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y, z, aa, ab, ac, ad, ae, af) {
        this.name = a || "";
        this.protocol = b || "";
        this.company = c || null;
        this.email = d || "";
        this.url = e || "";
        this.host = f || "";
        this.port = parseInt(g) || 0;
        this.timeout = parseInt(h) || 0;
        this.tcpNoDelayEnabled = !!i;
        this.connectionType = j || null;
        this.username = k !== undefined ? k : "";
        this.password = l !== undefined ? l : null;
        this.domain = m !== undefined ? m : null;
        this.keyProvider = n || null;
        this.hostKeyProvider = o || null;
        this.ftpPostLoginCommand = p || "";
        this.sftpStartSubsystemReplyRequired = !!q;
        this.as2Sender = r || "";
        this.as2Recipient = s || "";
        this.as2FromAddress = t || "";
        this.as2ReceiptType = u || "";
        this.as2ReceiptHttpsRequired = !!v;
        this.as2ReceiptSignatureRequired = !!w;
        this.as2ReceiptAwaitingTimeout = parseInt(x) || 0;
        this.encryptionKeyProvider = y || null;
        this.encryptionAlgorithm = z || null;
        this.signingKeyProvider = aa || null;
        this.signatureAlgorithm = ab || null;
        this.as2CompressionRequired = !!ac;
        this.encryptionRequired = !!ad;
        this.oftpData = ae || null;
        this.tags = af || [];
    }
});
jscape.TradingPartner.fromJSON = function(data) {
    function signatureAlgorithmOf(algorithm) {
        algorithm = jscape.SignatureAlgorithm.valueOf(algorithm);
        return algorithm ? algorithm.hashAlgorithm : null;
    }
    return $.extend(new jscape.TradingPartner(), data, {
        keyProvider: jscape.KeyProvider.fromJSON(data.keyProvider),
        hostKeyProvider: jscape.KeyProvider.fromJSON(data.hostKeyProvider),
        encryptionKeyProvider: jscape.KeyProvider.fromJSON(data.encryptionKeyProvider),
        signingKeyProvider: jscape.KeyProvider.fromJSON(data.signingKeyProvider),
        signatureAlgorithm: signatureAlgorithmOf(data.signatureAlgorithm),
        sftpStartSubsystemReplyRequired: !!data.sftpStartSubsystemReplyRequired,
        oftpData: jscape.OftpPartnerData.fromJSON(data.oftpData)
    });
};
jscape.TradingPartner.aftp = function(name, company, email, host, port, timeout, tcpNoDelay, username, password, keyProvider, hostKeyProvider, tags) {
    return $.extend(new jscape.TradingPartner(name, jscape.TradingPartner.Protocol.AFTP, company, email, undefined, host, port, timeout, tcpNoDelay, undefined, username, password),
                    {keyProvider: keyProvider, hostKeyProvider: hostKeyProvider, tags: tags});
};
jscape.TradingPartner.amazonS3 = function(name, company, email,timeout, username, password, encryptionRequired, tags) {
    return $.extend(new jscape.TradingPartner(name, jscape.TradingPartner.Protocol.AMAZON_S3, company, email, undefined, undefined, undefined, timeout, undefined, undefined, username, password),
                    {encryptionRequired: encryptionRequired, tags: tags});
};
jscape.TradingPartner.as2 = function(name, company, email, url, timeout, username, password, keyProvider, hostKeyProvider, compressionRequired, sender, recipient, fromAddress, receiptType, receiptUseSsl, receiptSignatureRequired, receiptAwaitingTimeout, encryptionKeyProvider, encryptionAlgorithm, signingKeyProvider, signatureAlgorithm, tags) {
    return $.extend(new jscape.TradingPartner(name, jscape.TradingPartner.Protocol.AS2, company, email, url, undefined, undefined, timeout, undefined, undefined, username, password),
                    {
                        keyProvider: keyProvider, hostKeyProvider: hostKeyProvider, as2CompressionRequired: compressionRequired, as2Sender: sender, as2Recipient: recipient, as2FromAddress: fromAddress || "",
                        as2ReceiptType: receiptType, as2ReceiptHttpsRequired: !!receiptUseSsl, as2ReceiptSignatureRequired: !!receiptSignatureRequired, as2ReceiptAwaitingTimeout: parseInt(receiptAwaitingTimeout),
                        encryptionKeyProvider: encryptionKeyProvider, encryptionAlgorithm: encryptionAlgorithm, signingKeyProvider: signingKeyProvider, signatureAlgorithm: signatureAlgorithm, tags: tags
                    });
};
jscape.TradingPartner.sftp = function(name, company, email, host, port, timeout, tcpNoDelay, username, password, keyProvider, hostKeyProvider, sftpStartSubsystemReplyRequired, tags) {
    return $.extend(new jscape.TradingPartner(name, jscape.TradingPartner.Protocol.SFTP, company, email, undefined, host, port, timeout, tcpNoDelay, undefined, username, password),
                    {keyProvider: keyProvider, hostKeyProvider: hostKeyProvider, sftpStartSubsystemReplyRequired: !!sftpStartSubsystemReplyRequired, tags: tags});
};
jscape.TradingPartner.ftp = function(name, company, email, host, port, timeout, tcpNoDelay, username, password, ftpPostLoginCommand, tags) {
    return $.extend(new jscape.TradingPartner(name, jscape.TradingPartner.Protocol.FTP, company, email, undefined, host, port, timeout, tcpNoDelay, undefined, username, password),
                    {ftpPostLoginCommand: ftpPostLoginCommand, tags: tags});
};
jscape.TradingPartner.ftpsImplicit = function(name, company, email, host, port, timeout, tcpNoDelay, username, password, keyProvider, hostKeyProvider, ftpPostLoginCommand, tags) {
    return $.extend(new jscape.TradingPartner(name, jscape.TradingPartner.Protocol.FTPS_IMPLICIT, company, email, undefined, host, port, timeout, tcpNoDelay, undefined, username, password),
                    {keyProvider: keyProvider, hostKeyProvider: hostKeyProvider, ftpPostLoginCommand: ftpPostLoginCommand, tags: tags});
};
jscape.TradingPartner.ftpsExplicit = function(name, company, email, host, port, timeout, tcpNoDelay, username, password, keyProvider, hostKeyProvider, ftpPostLoginCommand, tags) {
    return $.extend(new jscape.TradingPartner(name, jscape.TradingPartner.Protocol.FTPS_EXPLICIT, company, email, undefined, host, port, timeout, tcpNoDelay, undefined, username, password),
                    {keyProvider: keyProvider, hostKeyProvider: hostKeyProvider, ftpPostLoginCommand: ftpPostLoginCommand, tags: tags});
};
jscape.TradingPartner.webdav = function(name, company, email, url, timeout, username, password, domain, keyProvider, hostKeyProvider, tags) {
    return $.extend(new jscape.TradingPartner(name, jscape.TradingPartner.Protocol.WEBDAV, company, email, url, undefined, undefined, timeout, undefined, undefined, username, password, domain),
                    {keyProvider: keyProvider, hostKeyProvider: hostKeyProvider, tags: tags});
};
jscape.TradingPartner.oftp = function(name, company, email, host, port, timeout, username, password, oftpData, tags) {
    return $.extend(new jscape.TradingPartner(name, jscape.TradingPartner.Protocol.OFTP, company, email, undefined, host, port, timeout, undefined, undefined, username, password),
                    {oftpData: oftpData, tags: tags});
};
jscape.TradingPartner.rest = function(name, company, email, host, port, timeout, username, password, domain, keyProvider, hostKeyProvider, encryptionRequired, tags) {
    return $.extend(new jscape.TradingPartner(name, jscape.TradingPartner.Protocol.REST, company, email, undefined, host, port, timeout, undefined, undefined, username, password, domain),
                    {keyProvider: keyProvider, hostKeyProvider: hostKeyProvider, encryptionRequired: !!encryptionRequired, tags: tags});
};
jscape.TradingPartner.tftp = function(name, company, email, host, port, timeout, tags) {
    return $.extend(new jscape.TradingPartner(name, jscape.TradingPartner.Protocol.TFTP, company, email, undefined, host, port, timeout), {tags: tags});
};
jscape.TradingPartner.imap = function(name, company, email, host, port, timeout, connectionType, username, password, keyProvider, hostKeyProvider, tags) {
    return $.extend(new jscape.TradingPartner(name, jscape.TradingPartner.Protocol.IMAP, company, email, undefined, host, port, timeout, undefined, connectionType, username, password),
                    {keyProvider: keyProvider, hostKeyProvider: hostKeyProvider, tags: tags});
};
jscape.TradingPartner.pop3 = function(name, company, email, host, port, timeout, connectionType, username, password, keyProvider, hostKeyProvider, tags) {
    return $.extend(new jscape.TradingPartner(name, jscape.TradingPartner.Protocol.POP3, company, email, undefined, host, port, timeout, undefined, connectionType, username, password),
                    {keyProvider: keyProvider, hostKeyProvider: hostKeyProvider, tags:tags});
};
jscape.TradingPartner.smtp = function(name, company, email, host, port, timeout, connectionType, username, password, keyProvider, hostKeyProvider, tags) {
    return $.extend(new jscape.TradingPartner(name, jscape.TradingPartner.Protocol.SMTP, company, email, undefined, host, port, timeout, undefined, connectionType, username, password),
                    {keyProvider: keyProvider, hostKeyProvider: hostKeyProvider, tags: tags});
};
jscape.TradingPartner.smb = function(name, company, email, host, port, timeout, username, password, domain, tags) {
    return $.extend(new jscape.TradingPartner(name, jscape.TradingPartner.Protocol.SMB, company, email, undefined, host, port, timeout, undefined, undefined, username, password, domain),
                    {tags: tags});
};
jscape.TradingPartner.Protocol = {AFTP: "AFTP", AMAZON_S3: "AmazonS3", AS2: "AS2", FTP: "FTP", FTPS_IMPLICIT: "Implicit FTPS", FTPS_EXPLICIT: "Explicit FTPS", IMAP: "IMAP", OFTP: "OFTP", POP3: "POP3", REST: "REST", SFTP: "SFTP", SMB: "SMB", SMTP: "SMTP", TFTP: "TFTP", WEBDAV: "WebDAV", WEBDAV_SSL: "WebDAV SSL"};
jscape.TradingPartner.Protocol.values = function() { return [jscape.TradingPartner.Protocol.AFTP, jscape.TradingPartner.Protocol.AMAZON_S3, jscape.TradingPartner.Protocol.AS2, jscape.TradingPartner.Protocol.FTP, jscape.TradingPartner.Protocol.FTPS_IMPLICIT, jscape.TradingPartner.Protocol.FTPS_EXPLICIT, jscape.TradingPartner.Protocol.IMAP, jscape.TradingPartner.Protocol.OFTP, jscape.TradingPartner.Protocol.POP3, jscape.TradingPartner.Protocol.REST, jscape.TradingPartner.Protocol.SFTP, jscape.TradingPartner.Protocol.SMB, jscape.TradingPartner.Protocol.SMTP, jscape.TradingPartner.Protocol.TFTP, jscape.TradingPartner.Protocol.WEBDAV, jscape.TradingPartner.Protocol.WEBDAV_SSL]; };

/** @class */
jscape.OftpPartnerData = Class.extend(
    /** @lends {jscape.OftpPartnerData.prototype} */
{
    /** @constructor */
    initialize: function (a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u) {
        this.destinationId = a || "";
        this.sslCertificateData = b || new jscape.CertificateData();
        this.sslKeyAlias = c || "";
        this.authenticationCertificateData = d || new jscape.CertificateData();
        this.authenticationKeyAliases = e || [];
        this.requestEncryptionCertificateData = f || new jscape.CertificateData();
        this.requestDecryptionKeyAliases = g || [];
        this.requestSigningKeyAlias = h || "";
        this.requestSignatureVerificationCertificateData = i || new jscape.CertificateData();
        this.receiptSigningKeyAlias = j || "";
        this.receiptSignatureVerificationCertificateData = k || new jscape.CertificateData();
        this.cipherSuite = l;
        this.sslEnabled = m != undefined ? !!m : false;
        this.secureAuthenticationEnabled = n != undefined ? !!n : false;
        this.requestCompressionEnabled = o != undefined ? !!o : false;
        this.requestEncryptionEnabled = p != undefined ? !!p : false;
        this.requestSigningEnabled = q != undefined ? !!q : false;
        this.receiptSignatureRequired = r != undefined ? !!r : false;
        this.automaticReceiptGenerationAllowed = s != undefined ? !!s : false;
        this.certificateExchangeAllowed = t != undefined ? !!t : false;
        this.relayAllowed = u != undefined ? !!u : false;
    }
});
jscape.OftpPartnerData.fromJSON = function(data) {
    return data ? new jscape.OftpPartnerData(data.destinationId,
                                             jscape.CertificateData.fromJSON(data.sslCertificateData),
                                             data.sslKeyAlias,
                                             jscape.CertificateData.fromJSON(data.authenticationCertificateData),
                                             data.authenticationKeyAliases,
                                             jscape.CertificateData.fromJSON(data.requestEncryptionCertificateData),
                                             data.requestDecryptionKeyAliases,
                                             data.requestSigningKeyAlias,
                                             jscape.CertificateData.fromJSON(data.requestSignatureVerificationCertificateData),
                                             data.receiptSigningKeyAlias,
                                             jscape.CertificateData.fromJSON(data.receiptSignatureVerificationCertificateData),
                                             data.cipherSuite,
                                             data.sslEnabled,
                                             data.secureAuthenticationEnabled,
                                             data.requestCompressionEnabled,
                                             data.requestEncryptionEnabled,
                                             data.requestSigningEnabled,
                                             data.receiptSignatureRequired,
                                             data.automaticReceiptGenerationAllowed,
                                             data.certificateExchangeAllowed,
                                             data.relayAllowed)
            : null;
};

/** @class */
jscape.CertificateData = Class.extend(
    /** @lends {jscape.CertificateData.prototype} */
{
    /** @constructor */
    initialize: function(descriptor, aliases) {
        this.descriptor = descriptor || new jscape.CertificateDescriptor();
        this.aliases = aliases || [];
    }
});
jscape.CertificateData.fromJSON = function(data) {
    return data ? new jscape.CertificateData(jscape.CertificateDescriptor.fromJSON(data.descriptor), data.aliases) : null;
};

/** @class */
jscape.CertificateDescriptor = Class.extend(
    /** @lends {jscape.CertificateDescriptor.prototype} */
{
    /** @constructor */
    initialize: function (a, b, c, d) {
        this.issuer = a || "";
        this.subject = b || "";
        this.keyUsages = c || [];
        this.extendedKeyUsages = d || [];
    }
});
jscape.CertificateDescriptor.fromJSON = function(data) {
    return data ? new jscape.CertificateDescriptor(data.issuer, data.subject, data.keyUsages, data.extendedKeyUsages) : null;
};


/** @class */
jscape.domain.TradingPartnersModule = jscape.domain.DomainModule.extend(
    /** @lends {jscape.domain.TradingPartnersModule.prototype} */
{
    onCreate: function() {
        this._super.apply(this, arguments);

        this.controller = new jscape.domain.TradingPartnersController();
        this.controller.onCreate(this.managementService, this.domainName);
    },

    onStart: function () {
        this.controller.onStart();
    },

    onResume: function () {
        this.controller.onResume();
    }
});

/** @class */
jscape.domain.TradingPartnersController = jscape.ui.DatagridController.extend(
    /** @lends {jscape.domain.TradingPartnersController.prototype} */
{
    view: null,

    /** @constructor */
    initialize: function() {
        this._initValidators();
    },

    onCreate: function (managementService, domainName) {
        this.managementService = managementService;
        this.domainName = domainName;

        this.addController = new jscape.domain.AddTradingPartnerController();
        this.copyController = new jscape.domain.CopyTradingPartnerController();
        this.editController = new jscape.domain.EditTradingPartnerController();
        this.deleteController = new jscape.domain.DeleteTradingPartnerController();
        this.testController = new jscape.domain.TestTradingPartnerController();
    },

    onStart: function () {
        if (this.view == null) {
            this.view = new jscape.domain.TradingPartnersView();
        }
        this.view.show(this);
    },

    onResume: function() {
        this.view.refresh();
    },

    onRefresh: function(params) {
        params = jscape.Page.requestParameters(params);
        return this.managementService.listTradingPartners(this.domainName, params.startIndex, params.count, params.query)
                .then(jscape.Page.datagridFormatter());
    },

    onAddPartner: function() {
        this.addController.start(this, this.managementService, this.domainName)
                .done($.proxy(this._partnerAdded, this));
    },

    onCopyPartner: function(partner) {
        this.copyController.start(this.managementService, this.domainName, partner.name)
                .done($.proxy(this._partnerCopied, this))
                .done($.proxy(this._fireApplySuccess, this));
    },

    onEditPartner: function (partner, force) {
        var index = $.inArray(partner, this.view.getPartners());
        if (index != -1 || force === true) {
            this.editController.start(this, this.managementService, this.domainName, partner.name)
                    .done($.proxy(this._partnerEdited, this, index));
        }
    },

    onDeletePartner: function(partners) {
        this.deleteController.start(this.managementService, this.domainName, partners)
                .done($.proxy(this._partnerDeleted, this, partners));
    },

    onTestPartner: function(partner) {
        return this.testController.start(this.managementService, this.domainName, partner);
    },

    _partnerAdded: function(partner) {
        this._reloadAndSelect(partner);
    },

    _partnerEdited: function (index, partner) {
        this._recordAdded(partner);
    },

    _partnerCopied: function(partner, editAfterDone) {
        if (editAfterDone)  {
            this.view.refresh($.proxy(function() {
                this.view.selectRecord(partner);
                this.onEditPartner(partner, true);
            }, this));
        } else {
            this._partnerAdded(partner);
        }
    },

    _partnerDeleted: function (partners) {
        this._recordDeleted(partners);
    },

    _initValidators: function () {
        var v = new jscape.Validator();
        v.nonEmptyRule("partner_name_nonempty", window.R.string.TRADING_PARTNERS_ERROR_BAD_NAME);
        v.nonEmptyRule("partner_host_nonempty", window.R.string.TRADING_PARTNERS_ERROR_BAD_HOST);
        v.rule("partner_unique", $.proxy(this._partnerNotExists, this), window.R.string.TRADING_PARTNERS_ERROR_ALREADY_EXIST);
        v.rule("partner_url", $.proxy(this._validUrl, this), window.R.string.TRADING_PARTNERS_ERROR_BAD_URL);
        v.rule("partner_sender", $.proxy(this._validAs2Name, this), window.R.string.TRADING_PARTNERS_ERROR_BAD_SENDER);
        v.rule("partner_recipient", $.proxy(this._validAs2Name, this), window.R.string.TRADING_PARTNERS_ERROR_BAD_RECIPIENT);
    },

    _partnerNotExists: function(name) {
        name = (name || "").toUpperCase();
        var values = $.map(this.view.getPartners(), function(partner) { return partner.name.toUpperCase(); });
        return $.inArray(name, values) == -1;
    },

    _validUrl: function(value) {
        return /http(s)?:\/\/.+/i.test(value);
    },

    _validAs2Name: function(value) {
        return /^[\x20\x21\x23-\x5B\x5D-\x7E]{1,128}$/.test(value);
    }
});

/** @class */
jscape.domain.TradingPartnersView = jscape.ui.DatagridView.extend(
    /** @lends {jscape.domain.TradingPartnersView.prototype} */
{
    selection: null,

    /** @constructor */
    initialize: function() {
        var initializing = true;

        this.fieldset = $("fieldset[name=tradingpartnersfields]");

        this.data = $("table[role=grid][aria-label=tradingpartners]", this.fieldset);
        this.data.datagrid({
            fit: true,
            fitColumns: true,
            singleSelect: true,
            pagination: true,
            search: true,
            remoteSearch: true,
            remoteSort: true,
            sortName: "name",
            idField: "name",
            columns: [[
                {field: "name", title: $("thead th:nth-child(1)", this.data).text(), width: 200, sortable: true},
                {field: "company", title: $("thead th:nth-child(2)", this.data).text(), width: 100, sortable: true, resizable: true, sorter: function(a, b) { return a == b ? 0 : a == null || a < b ? -1 : 1; }},
                {field: "protocol", title: $("thead th:nth-child(3)", this.data).text(), width: 100, sortable: true, formatter: $.proxy(this._formatProtocol, this), finder: {type: "combobox", options: {data: $.map(jscape.TradingPartner.Protocol.values(), $.proxy(function(value) { return {text: this._formatProtocol(value), value: value}; }, this)), panelHeight: "auto", panelMaxHeight: 150}}},
                {field: "server", title: $("thead th:nth-child(4)", this.data).text(), width: 200, sortable: false, searchable: false, formatter: $.proxy(function(_, row) { return this._formatServer(row); }, this)},
                {field: "tags", title: $("thead th:nth-child(5)", this.data).text(), width: 80, formatter: function(value) { return String($.isArray(value) ? value.join(", ") : value).escapeXml(); }}
            ]],
            onSelect: $.proxy(this._adjustState, this),
            onUnselect: $.proxy(this._adjustState, this),
            onDblClickRow: $.proxy(this._onClick$EditButton, this),
            loader: $.proxy(this._onLoad$Data, this),
            onBeforeLoad: function () { return !initializing; },
            onLoadSuccess: $.proxy(this._adjustState, this)
        });

        this.addButton = $("a[role=button][name=add]", this.fieldset).linkbutton({onClick: $.proxy(this._onClick$AddButton, this)});
        this.editButton = $("a[role=button][name=edit]", this.fieldset).linkbutton({disabled: true, onClick: $.proxy(this._onClick$EditButton, this)});
        this.copyButton = $("a[role=button][name=copy]", this.fieldset).linkbutton({disabled: true, onClick: $.proxy(this._onClick$CopyButton, this)});
        this.deleteButton = $("a[role=button][name=delete]", this.fieldset).linkbutton({disabled: true, onClick: $.proxy(this._onClick$DeleteButton, this)});
        this.testButton = $("a[role=button][name=test]", this.fieldset).linkbutton({disabled: true, onClick: $.proxy(this._onClick$TestButton, this)});

        initializing = false;
    },

    show: function(listener) {
        this.listener = listener || jscape.domain.TradingPartnersView.LISTENER;
        this._adjustState();
    },

    getPartners: function() {
        return this.getRecords();
    },

    _onLoad$Data: function(params, success, error) {
        this.listener.onRefresh(params).done(success).fail(error);
    },

    _formatProtocol: function (value) {
        return window.R.string["APPLICATION_PROTOCOL_" + (value + "").toUpperCase().replace(" ", "_")] || "";
    },

    _formatServer: function (partner) {
        return String(partner.url && partner.url.trim().length ? partner.url : partner.host
                ? partner.host + (partner.port ? ":" + partner.port : "")
                : "").escapeXml();
    },

    _onClick$AddButton: function() {
        this.listener.onAddPartner(this);
    },

    _onClick$EditButton: function() {
        this.listener.onEditPartner(this.selection[0]);
    },

    _onClick$CopyButton: function() {
        this.listener.onCopyPartner(this.selection[0]);
    },

    _onClick$DeleteButton: function() {
        this.listener.onDeletePartner(this.selection);
    },

    _onClick$TestButton: function() {
        this.testButton.linkbutton("disable");
        this.listener.onTestPartner(this.selection[0])
                .always($.proxy(function() { this.testButton.linkbutton("enable"); }, this));
    },

    _adjustState: function () {
        this.selection = this.data.datagrid("getSelections");
        this.editButton.linkbutton(this.selection.length == 1 ? "enable" : "disable");
        this.copyButton.linkbutton(this.selection.length == 1 ? "enable" : "disable");
        this.testButton.linkbutton(this.selection.length == 1 ? "enable" : "disable");
        this.deleteButton.linkbutton(this.selection.length != 0 ? "enable" : "disable");
    }
});
jscape.domain.TradingPartnersView.LISTENER = {
    onRefresh: $.noop,
    onAddPartner: $.noop,
    onEditPartner: $.noop,
    onCopyPartner: $.noop,
    onDeletePartner: $.noop,
    onTestPartner: $.noop
};

/** @class */
jscape.domain.AddTradingPartnerController = Class.extend(
    /** @lends {jscape.domain.AddTradingPartnerController.prototype} */
{
    deferred: null,

    /** @constructor */
    initialize: function() {
        this.controllerMap = {};
        this.controllerMap[jscape.TradingPartner.Protocol.AFTP] = jscape.domain.AddAftpTradingPartnerController;
        this.controllerMap[jscape.TradingPartner.Protocol.AS2] = jscape.domain.AddAs2TradingPartnerController;
        this.controllerMap[jscape.TradingPartner.Protocol.AMAZON_S3] = jscape.domain.AddAmazonS3TradingPartnerController;
        this.controllerMap[jscape.TradingPartner.Protocol.FTP] = jscape.domain.AddFtpTradingPartnerController;
        this.controllerMap[jscape.TradingPartner.Protocol.FTPS_IMPLICIT] = jscape.domain.AddFtpsImplicitTradingPartnerController;
        this.controllerMap[jscape.TradingPartner.Protocol.FTPS_EXPLICIT] = jscape.domain.AddFtpsExplicitTradingPartnerController;
        this.controllerMap[jscape.TradingPartner.Protocol.IMAP] = jscape.domain.AddImapTradingPartnerController;
        this.controllerMap[jscape.TradingPartner.Protocol.OFTP] = jscape.domain.AddOftpTradingPartnerController;
        this.controllerMap[jscape.TradingPartner.Protocol.POP3] = jscape.domain.AddPop3TradingPartnerController;
        this.controllerMap[jscape.TradingPartner.Protocol.REST] = jscape.domain.AddRestTradingPartnerController;
        this.controllerMap[jscape.TradingPartner.Protocol.SFTP] = jscape.domain.AddSftpTradingPartnerController;
        this.controllerMap[jscape.TradingPartner.Protocol.SMTP] = jscape.domain.AddSmtpTradingPartnerController;
        this.controllerMap[jscape.TradingPartner.Protocol.SMB] = jscape.domain.AddSmbTradingPartnerController;
        this.controllerMap[jscape.TradingPartner.Protocol.WEBDAV] = jscape.domain.AddWebDavTradingPartnerController;
        this.controllerMap[jscape.TradingPartner.Protocol.TFTP] = jscape.domain.AddTftpTradingPartnerController;
    },

    start: function(listener, managementService, domainName) {
        this.listener = listener || jscape.domain.AddTradingPartnerController.LISTENER;
        this.managementService = managementService;
        this.domainName = domainName;
        this.deferred = $.Deferred();
        this._setupDialog().show(this);
        return this.deferred.promise();
    },

    onTestServer: function(partner) {
        return this.listener.onTestPartner(partner);
    },

    onSubmit: function(dialog) {
        var protocol = dialog.getProtocol();
        dialog.destroy();

        var theClass = this.controllerMap[protocol];
        var controller = new theClass();
        controller.start(this, this.managementService, this.domainName)
                .done($.proxy(this._storePartner, this))
                .fail($.proxy(function() { this.deferred.reject(); this.deferred = null; }, this));
    },

    onCancel: function(dialog) {
        dialog.destroy();
        this.deferred.reject();
    },

    _setupDialog: function() {
        return new jscape.domain.AddTradingPartnerProtocolDialog();
    },

    _storePartner: function (partner) {
        this.managementService.addTradingPartner(this.domainName, partner)
                .done($.proxy(function(partner) { this.deferred.resolve(partner); }, this))
                .fail($.proxy(function() { this.deferred.reject(); this.deferred = null; }, this));
    }
});
jscape.domain.AddTradingPartnerController.LISTENER = {
    onTestServer: $.noop
};

/** @class */
jscape.domain.AddTradingPartnerProtocolDialog = Class.extend(
    /** @lends {jscape.domain.AddTradingPartnerProtocolDialog.prototype} */
{
    /** @constructor */
    initialize: function() {
        this.dialog = $("#d-partner-add-protocol").clone().attr("id", new Date().getTime().toString(36));
        this.dialog.dialog({
            width: 530, height: "auto",
            modal: true, resizable: false, closable: true, closed: true,
            buttons: [
                {text: window.R.string.DIALOG_BUTTON_OK || "Ok", handler: $.proxy(this._onSubmit, this)},
                {text: window.R.string.DIALOG_BUTTON_CANCEL || "Cancel", handler: $.proxy(this._onCancel, this)}
            ],
            onClose: $.proxy(function () {if (!this.closing) { this._onCancel(); }}, this)
        }).show();

        this.fieldset = $("fieldset[name=partnerprotocolfields]", this.dialog);
        this.protocol = $("select[name=protocol]", this.fieldset);
        this.protocol.combobox({required: true, editable: false, width: 150, panelHeight: "auto", panelMaxHeight: 150});
    },

    getProtocol: function() {
        return this.protocol.combobox("getValue");
    },

    show: function (listener) {
        this.listener = listener;
        this.dialog.dialog("center").dialog("open");
        this.fieldset.form("validate");
        this.protocol.combobox("textbox").focus();
    },

    hide: function () {
        if (!this._closed()) {
            this.closing = true;
            this.dialog.dialog("close");
            this.fieldset.form("disableValidation");
            this.closing = false;
        }
    },

    destroy: function() {
        this.dialog.dialog("destroy");
    },

    _onSubmit: function () {
        if (this.fieldset.form("validate")) {
            this.hide();
            this.listener.onSubmit(this);
        }
    },

    _onCancel: function () {
        this.hide();
        this.listener.onCancel(this);
    },

    _closed: function () {
        return !!this.dialog.dialog("options").closed;
    }
});

/** @class */
jscape.domain.EditTradingPartnerController = Class.extend(
    /** @lends {jscape.domain.EditTradingPartnerController.prototype} */
{
    deferred: null,

    /** @constructor */
    initialize: function() {
        this.controllerMap = {};
        this.controllerMap[jscape.TradingPartner.Protocol.AFTP] = jscape.domain.EditAftpTradingPartnerController;
        this.controllerMap[jscape.TradingPartner.Protocol.AS2] = jscape.domain.EditAs2TradingPartnerController;
        this.controllerMap[jscape.TradingPartner.Protocol.AMAZON_S3] = jscape.domain.EditAmazonS3TradingPartnerController;
        this.controllerMap[jscape.TradingPartner.Protocol.FTP] = jscape.domain.EditFtpTradingPartnerController;
        this.controllerMap[jscape.TradingPartner.Protocol.FTPS_IMPLICIT] = jscape.domain.EditFtpsImplicitTradingPartnerController;
        this.controllerMap[jscape.TradingPartner.Protocol.FTPS_EXPLICIT] = jscape.domain.EditFtpsExplicitTradingPartnerController;
        this.controllerMap[jscape.TradingPartner.Protocol.IMAP] = jscape.domain.EditImapTradingPartnerController;
        this.controllerMap[jscape.TradingPartner.Protocol.OFTP] = jscape.domain.EditOftpTradingPartnerController;
        this.controllerMap[jscape.TradingPartner.Protocol.POP3] = jscape.domain.EditPop3TradingPartnerController;
        this.controllerMap[jscape.TradingPartner.Protocol.REST] = jscape.domain.EditRestTradingPartnerController;
        this.controllerMap[jscape.TradingPartner.Protocol.SFTP] = jscape.domain.EditSftpTradingPartnerController;
        this.controllerMap[jscape.TradingPartner.Protocol.SMTP] = jscape.domain.EditSmtpTradingPartnerController;
        this.controllerMap[jscape.TradingPartner.Protocol.SMB] = jscape.domain.EditSmbTradingPartnerController;
        this.controllerMap[jscape.TradingPartner.Protocol.WEBDAV] = jscape.domain.EditWebDavTradingPartnerController;
        this.controllerMap[jscape.TradingPartner.Protocol.TFTP] = jscape.domain.EditTftpTradingPartnerController;
    },

    start: function(listener, managementService, domainName, partnerName) {
        this.listener = listener || jscape.domain.EditTradingPartnerController.LISTENER;
        this.managementService = managementService;
        this.domainName = domainName;
        this.partnerName = partnerName;
        this.deferred = $.Deferred();
        this.managementService.getTradingPartner(this.domainName, this.partnerName)
                .done($.proxy(this._editPartner, this))
                .fail($.proxy(function () { this.deferred.reject(); this.deferred = null; }, this));
        return this.deferred.promise();
    },

    onTestServer: function(partner) {
        return this.listener.onTestPartner(partner);
    },

    _editPartner: function(partner) {
        var theClass = this.controllerMap[partner.protocol];
        var controller = new theClass();
        return controller.start(this, this.managementService, this.domainName, partner)
                .done($.proxy(this._storePartner, this))
                .fail($.proxy(function () { this.deferred.reject(); this.deferred = null; }, this));
    },

    _storePartner: function (partner) {
        this.managementService.setTradingPartner(this.domainName, partner.name, partner)
                .done($.proxy(function() { this.deferred.resolve(partner); this.deferred = null; }, this))
                .fail($.proxy(function() { this.deferred.reject(); this.deferred = null; }, this));
    }
});
jscape.domain.EditTradingPartnerController.LISTENER = {
    onTestServer: $.noop
};


/** @class */
jscape.domain.DeleteTradingPartnerController = Class.extend(
    /** @lends {jscape.domain.DeleteTradingPartnerController.prototype} */
{
    deferred: null,

    start: function (managementService, domainName, partners) {
        this.managementService = managementService;
        this.domainName = domainName;
        this.deferred = $.Deferred();
        this._confirmDelete(partners)
                .done($.proxy(this._deleteConfirmed, this, partners))
                .fail($.proxy(function() { this.deferred.reject(); this.deferred = null; }, this));
        return this.deferred.promise();
    },

    _confirmDelete: function(partners) {
        var text = $.map(partners, function(partner) { return partner.name; }).join(", ");
        return jscape.ConfirmDialog.confirm(
                window.R.string.TRADING_PARTNERS_CONFIRM_DELETE_TITLE,
                window.R.string.TRADING_PARTNERS_CONFIRM_DELETE_MESSAGE.supplant({0: text}));
    },

    _deleteConfirmed: function(partners) {
        $.when.apply(jQuery, $.map(partners, $.proxy(function(partner) { return this.managementService.deleteTradingPartner(this.domainName, partner.name); }, this)))
                .done($.proxy(this.deferred.resolve, this.deferred, partners))
                .fail($.proxy(function() { this.deferred.reject(); this.deferred = null; }, this));
    }
});

/** @class */
jscape.domain.TestTradingPartnerController = Class.extend(
    /** @lends {jscape.domain.TestTradingPartnerController.prototype} */
{
    deferred: null,

    start: function(managementService, domainName, partner) {
        this.managementService = managementService;
        this.domainName = domainName;
        this.deferred = $.Deferred();
        this.managementService.testTradingPartner(this.domainName, partner)
                        .done($.proxy(this._testPassed, this))
                        .fail($.proxy(this._testFailed, this));
        return this.deferred.promise();
    },

    _testPassed: function() {
        $.messager.alert(window.R.string.TRADING_PARTNERS_TEST_TITLE,
                         window.R.string.TRADING_PARTNERS_TEST_PASSED,
                         "info");
        this.deferred.resolve();
        this.deferred = null;
    },

    _testFailed: function() {
        this.deferred.reject();
        this.deferred = null;
    }
});

/** @class */
jscape.domain.CopyTradingPartnerController = Class.extend(
    /** @lends {jscape.domain.CopyTradingPartnerController.prototype} */
{
    deferred: null,


    start: function(managementService, domainName, partnerName) {
        this.managementService = managementService;
        this.domainName = domainName;
        this.partnerName = partnerName;
        this.deferred = $.Deferred();
        this._setupDialog().show(this);
        return this.deferred.promise();
    },

    onSubmit: function(dialog) {
        var newName = dialog.getNewPartnerName();
        var editAfterDone = dialog.isEditAfterDone();
        dialog.destroy();

        this.managementService.copyTradingPartner(this.domainName, this.partnerName, newName)
                .done($.proxy(function(partner) { this.deferred.resolve(partner, editAfterDone); this.deferred = null; }, this))
                .fail($.proxy(function() { this.deferred.reject(); this.deferred = null; }, this));
    },

    onCancel: function(dialog) {
        dialog.destroy();
        this.deferred.reject();
        this.deferred = null;
    },

    _setupDialog: function() {
        var dialog = new jscape.domain.CopyTradingPartnerDialog();
        dialog.setPartnerName(this.partnerName);
        dialog.setEditAfterDone(true);
        return dialog
    }
});

/** @class */
jscape.domain.CopyTradingPartnerDialog = Class.extend(
    /** @lends {jscape.domain.CopyTradingPartnerDialog.prototype} */
{
    /** @constructor */
    initialize: function() {
        this.dialog = $("#d-partner-copy").clone().attr("id", "");
        this.dialog.dialog({
            width: 530, height: "auto",
            modal: true, resizable: false, closable: true, closed: true,
            buttons: [
                {text: window.R.string.DIALOG_BUTTON_OK || "Ok", handler: $.proxy(this._onSubmit, this)},
                {text: window.R.string.DIALOG_BUTTON_CANCEL || "Cancel", handler: $.proxy(this._onCancel, this)}
            ],
            onClose: $.proxy(function () {if (!this.closing) { this._onCancel(); }}, this)
        }).show();

        this.title = this.dialog.dialog("header").text();
        this.fieldset = $("fieldset[name=copytradingpartnerfields]", this.dialog);

        this.name = $("input[name=name]", this.fieldset).textbox({required: true, validType: ["partner_name_nonempty", "partner_unique"], missingMessage: window.R.string.TRADING_PARTNERS_ERROR_BAD_NAME, width: "60%"});
        this.editAfterDone = $("input[name=editafterdone]:checkbox", this.fieldset);
    },

    getNewPartnerName: function() {
        return this.name.textbox("getValue");
    },

    setPartnerName: function(value) {
        this.dialog.dialog("setTitle", this.title.supplant({0: value}));
    },

    isEditAfterDone: function() {
        return this.editAfterDone.is(":checked");
    },

    setEditAfterDone: function(value) {
        this.editAfterDone.prop("checked", !!value);
    },

    show: function (listener) {
        this.listener = listener;
        this.dialog.dialog("center").dialog("open");
        this.fieldset.form("validate");
        this.name.textbox("textbox").focus();
    },

    hide: function () {
        if (!this._closed()) {
            this.closing = true;
            this.dialog.dialog("close");
            this.fieldset.form("disableValidation");
            this.closing = false;
        }
    },

    destroy: function() {
        this.dialog.dialog("destroy");
    },

    _onSubmit: function () {
        if (this.fieldset.form("validate")) {
            this.hide();
            this.listener.onSubmit(this);
        }
    },

    _onCancel: function () {
        this.hide();
        this.listener.onCancel(this);
    },

    _closed: function () {
        return !!this.dialog.dialog("options").closed;
    }
});

/** @class */
jscape.domain.BaseTradingPartnerController = Class.extend(
    /** @lends {jscape.domain.BaseTradingPartnerController.prototype} */
{
    clientKeyProvider: null,
    deferred: null,

    /** @constructor */
    initialize: function() {
        this.clientKeyController = new jscape.domain.ClientKeyController();
    },

    start: function(listener, managementService, domainName, keyProvider) {
        this.listener = listener || jscape.domain.BaseTradingPartnerController.LISTENER;
        this.managementService = managementService;
        this.domainName = domainName;
        this.clientKeyProvider = keyProvider || null;
        this.deferred = $.Deferred();
        this._setupDialog().show(this);
        return this.deferred.promise();
    },

    onSubmit: function(dialog) {
        var descriptor = this._createPartner(dialog);
        dialog.destroy();
        this.deferred.resolve(descriptor);
        this.deferred = null;
    },

    onCancel: function(dialog) {
        dialog.destroy();
        this.deferred.reject();
        this.deferred = null;
    },

    onTest: function(dialog) {
        return this.listener.onTestServer(this._createPartner(dialog));
    },

    onSelectClientKey: function() {
        this.clientKeyController.start(this.managementService, this.domainName, this.clientKeyProvider)
                .done($.proxy(function(provider) { this.clientKeyProvider = provider; }, this));
    },

    _loadHostKeys: function () {
        return this.managementService.getHostCertificates()
                .then(function(certificates) { return $.map(certificates, function (certificate) { return certificate.name; }); });
    },

    _fireSuccess: function(message) {
        if (message) {
            $(document).triggerHandler("broadcast", [message]);
        }
    },

    _setupDialog: function() {
        throw "not implemented";
    },

    _createPartner: function (dialog) {
        throw "not implemented";
    }
});
jscape.domain.BaseTradingPartnerController.LISTENER = {
    onTestServer: $.noop
};

/** @class */
jscape.domain.AddAftpTradingPartnerController = jscape.domain.BaseTradingPartnerController.extend(
    /** @lends {jscape.domain.AddAftpTradingPartnerController.prototype} */
{
    DEFAULTS: {port: 3000, timeout: 30 * 1000, tcpNoDelay: true},

    _setupDialog: function() {
        var dialog = new jscape.domain.AddAftpTradingPartnerDialog();
        dialog.setPort(this.DEFAULTS.port);
        dialog.setTimeout(this.DEFAULTS.timeout);
        dialog.setTcpNoDelay(this.DEFAULTS.tcpNoDelay);
        this.managementService.getDomainTags(this.domainName).done(function(tags) { dialog.setAvailableTags(tags); });
        this._loadHostKeys(dialog).done(function(keys) { dialog.setHostKeys(keys); });
        return dialog;
    },

    _createPartner: function(dialog) {
        return jscape.TradingPartner.aftp(dialog.getName(),
                                          dialog.getCompany(),
                                          dialog.getEmail(),
                                          dialog.getHost(),
                                          dialog.getPort(),
                                          dialog.getTimeout(),
                                          dialog.getTcpNoDelay(),
                                          dialog.getUsername(),
                                          dialog.getPassword(),
                                          this.clientKeyProvider,
                                          dialog.getHostKey() != null ? new jscape.ServerKeyProvider(dialog.getHostKey()) : null,
                                          dialog.getTags());
    }
});

/** @class */
jscape.domain.EditAftpTradingPartnerController = jscape.domain.BaseTradingPartnerController.extend(
    /** @lends {jscape.domain.EditAftpTradingPartnerController.prototype} */
{
    /** @override */
    start: function(listener, managementService, domainName, partner) {
        this.partner = partner;
        return this._super(listener, managementService, domainName, partner.keyProvider);
    },

    _setupDialog: function () {
        var dialog = new jscape.domain.EditAftpTradingPartnerDialog();
        var partner = this.partner;
        if (partner) {
            dialog.setName(partner.name);
            dialog.setCompany(partner.company);
            dialog.setEmail(partner.email);
            dialog.setHost(partner.host);
            dialog.setPort(partner.port);
            dialog.setTimeout(partner.timeout);
            dialog.setTcpNoDelay(partner.tcpNoDelayEnabled);
            dialog.setUsername(partner.username);
            dialog.setPassword(partner.password);
        }
        this.managementService.getDomainTags(this.domainName)
                .done(function (tags) {
                          dialog.setAvailableTags(tags);
                          partner && dialog.setTags(partner.tags);
                      });
        this._loadHostKeys()
                .done(function (keys) {
                          dialog.setHostKeys(keys);
                          partner && dialog.setHostKey(partner.hostKeyProvider ? partner.hostKeyProvider.keyAlias : null);
                      });
        return dialog;
    },

    _createPartner: function (dialog) {
        return jscape.TradingPartner.aftp(this.partner.name,
                                          dialog.getCompany(),
                                          dialog.getEmail(),
                                          dialog.getHost(),
                                          dialog.getPort(),
                                          dialog.getTimeout(),
                                          dialog.getTcpNoDelay(),
                                          dialog.getUsername(),
                                          dialog.getPassword(),
                                          this.clientKeyProvider,
                                          dialog.getHostKey() != null ? new jscape.ServerKeyProvider(dialog.getHostKey()) : null,
                                          dialog.getTags());
    }
});

/** @class */
jscape.domain.TradingPartnerDialog = Class.extend(
    /** @lends {jscape.domain.TradingPartnerDialog.prototype} */
{
    /** @constructor */
    initialize: function(dialog) {
        this.dialog = dialog.clone().attr("id", "");
        this.dialog.dialog({
            width: 760, height: "auto",
            modal: true, resizable: false, closable: true, closed: true,
            buttons: [
                {text: window.R.string.DIALOG_BUTTON_OK || "Ok", handler: $.proxy(this._onSubmit, this)},
                {text: window.R.string.DIALOG_BUTTON_CANCEL || "Cancel", handler: $.proxy(this._onCancel, this)}
            ],
            onClose: $.proxy(function () {if (!this.closing) { this._onCancel(); }}, this)
        }).keydown($.proxy(function(e) {
            if (e.keyCode == 13) {
                e.stopPropagation();
                this._onSubmit();
            } if (e.keyCode == 27) {
                e.stopPropagation();
                this._onCancel();
            }
        }, this)).show();

        this.fieldset = $("fieldset[name=tradingpartnerfields]", this.dialog);

        this.company = $("input[name=company]", this.fieldset).textbox({width: "60%"});
        this.email = $("input[name=email]", this.fieldset).textbox({required: false, validType: "multi_value['email',',']", invalidMessage: window.R.string.TRADING_PARTNERS_ERROR_BAD_EMAIL, width: "60%"});
        this.tags = $("select[name=tags]", this.fieldset).tagbox({limitToList: true, hasDownArrow: true, panelHeight: "auto", panelMaxHeight: 150, width: "80%", onLoadSuccess: function() { $(this).tagbox("clear"); }});

        this.testButton = $("a[role=button][name=test]", this.fieldset).linkbutton({onClick: $.proxy(this._onClick$TestButton, this)});
    },

    getCompany: function() {
        return this.company.textbox("getValue");
    },

    setCompany: function(value) {
        this.company.textbox("setValue", value);
    },

    getEmail: function() {
        return this.email.textbox("getValue");
    },

    setEmail: function(value) {
        this.email.textbox("setValue", value);
    },

    setAvailableTags: function(values) {
        this.tags.tagbox("loadData", values);
    },

    getTags: function() {
        return this.tags.tagbox("getValues");
    },

    setTags: function(values) {
        this.tags.tagbox("setValues", values);
    },

    show: function (listener) {
        this.listener = listener;
        this.dialog.dialog("center").dialog("open");
        this.fieldset.form("validate");
        this.fieldset.find("input:first").focus();
        return this;
    },

    hide: function () {
        if (!this._closed()) {
            this.closing = true;
            this.dialog.dialog("close");
            this.fieldset.form("disableValidation");
            this.closing = false;
        }
        return this;
    },

    destroy: function() {
        this.dialog.dialog("destroy");
        return this;
    },

    _onSubmit: function () {
        if (this.fieldset.form("validate")) {
            this.hide();
            this.listener.onSubmit(this);
        }
    },

    _onCancel: function () {
        this.hide();
        this.listener.onCancel(this);
    },

    _onClick$TestButton: function () {
        if (this.fieldset.form("validate")) {
            this.testButton.linkbutton("disable");
            this.listener.onTest(this)
                    .always($.proxy(function() { this.testButton.linkbutton("enable"); }, this));
        }
    },

    _closed: function () {
        return !!this.dialog.dialog("options").closed;
    }
});
jscape.domain.TradingPartnerDialog.LISTENER = {
    onSubmit: $.noop,
    onCancel: $.noop,
    onTest: $.noop
};

/** @class */
jscape.domain.AftpTradingPartnerDialog = jscape.domain.TradingPartnerDialog.extend(
    /** @lends {jscape.domain.AftpTradingPartnerDialog.prototype} */
{
    TIMEOUT_FACTOR: 1000,

    /** @constructor */
    initialize: function(dialog) {
        this._super(dialog);

        this.host = $("input[name=host]", this.fieldset).textbox({required: true, validType: "partner_host_nonempty", missingMessage: window.R.string.TRADING_PARTNERS_ERROR_BAD_HOST, width: "60%"});
        this.port = $("input[name=port]", this.fieldset).numberspinner({required: true, min: 1, max: 65535, width: 100});
        this.timeout = $("input[name=timeout]", this.fieldset).numberspinner({required: true, min: 1, max: 60, width: 60});
        this.tcpNoDelay = $("input[name=tcpnodelay]:checkbox", this.fieldset);

        this.username = $("input[name=username]", this.fieldset).textbox({width: "50%"});
        this.password = $("input[name=password]", this.fieldset).textbox({type: "password", width: "50%"});

        this.useHostKey = $("input[name=usehostkey]:checkbox", this.fieldset).prop("disabled", true);
        this.useHostKey.change($.proxy(function() { this.hostKey.combobox(this.useHostKey.is(":checked") ? "enable" : "disable"); }, this));
        this.hostKey = $("select[name=hostkey]", this.fieldset);
        this.hostKey.combobox({editable: false, disabled: true, width: 170, panelHeight: "auto", panelMaxHeight: 150, onLoadSuccess: $.proxy(function(data) {
            this.useHostKey.prop("disabled", data.length == 0);
            if (data.length != 0) {
                this.hostKey.combobox("select", data[0].value);
            }
        }, this)});

        this.clientKeyButton = $("a[role=button][name=selectclientkey]", this.fieldset).linkbutton({onClick: $.proxy(this._onClick$ClientKeyButton, this)});
    },

    getHost: function() {
        return this.host.textbox("getValue");
    },

    setHost: function(value) {
        this.host.textbox("setValue", value);
    },

    getPort: function() {
        return this.port.numberspinner("getValue");
    },

    setPort: function(value) {
        this.port.numberspinner("setValue", value);
    },

    getTimeout: function() {
        return this.timeout.numberspinner("getValue") * this.TIMEOUT_FACTOR;
    },

    setTimeout: function(value) {
        this.timeout.numberspinner("setValue", parseInt(value) / this.TIMEOUT_FACTOR);
    },

    getTcpNoDelay: function() {
        return this.tcpNoDelay.is(":checked");
    },

    setTcpNoDelay: function(value) {
        this.tcpNoDelay.prop("checked", !!value);
    },

    getUsername: function() {
        return this.username.textbox("getValue");
    },

    setUsername: function(value) {
        this.username.textbox("setValue", value);
    },

    getPassword: function() {
        return this.password.textbox("getValue");
    },

    setPassword: function(value) {
        this.password.textbox("setValue", value);
    },

    getHostKey: function() {
        return this.useHostKey.is(":checked") ? this.hostKey.combobox("getValue") : null;
    },

    setHostKey: function(value) {
        this.useHostKey.prop("checked", value != null).change();
        if (value != null) {
            this.hostKey.combobox("setValue", value);
        }
    },

    setHostKeys: function(values) {
        this.hostKey.combobox("loadData", values);
    },

    /** @override */
    show: function(listener) {
        return this._super(listener || jscape.domain.AftpTradingPartnerDialog.LISTENER);
    },

    _onClick$ClientKeyButton: function() {
        this.listener.onSelectClientKey();
    }
});
jscape.domain.AftpTradingPartnerDialog.LISTENER = $.extend({
    onSelectClientKey: $.noop
}, jscape.domain.TradingPartnerDialog.LISTENER);

/** @class */
jscape.domain.AddAftpTradingPartnerDialog = jscape.domain.AftpTradingPartnerDialog.extend(
    /** @lends {jscape.domain.AddAftpTradingPartnerDialog.prototype} */
{
    /** @constructor */
    initialize: function() {
        this._super($("#d-partner-add-aftp"));

        this.name = $("input[name=name]", this.fieldset).textbox({
            required: true,
            validType: ["partner_name_nonempty", "partner_unique"],
            missingMessage: window.R.string.TRADING_PARTNERS_ERROR_BAD_NAME,
            width: "60%"
        });
    },

    getName: function() {
        return this.name.textbox("getValue");
    }
});

/** @class */
jscape.domain.EditAftpTradingPartnerDialog = jscape.domain.AftpTradingPartnerDialog.extend(
    /** @lends {jscape.domain.EditAftpTradingPartnerDialog.prototype} */
{
    /** @constructor */
    initialize: function() {
        this._super($("#d-partner-edit-aftp"));

        this.title = this.dialog.dialog("header").text() || "";
    },

    setName: function(value) {
        this.dialog.dialog("setTitle", this.title.supplant({0: value}));
    }
});

/** @class */
jscape.domain.AddAmazonS3TradingPartnerController = jscape.domain.BaseTradingPartnerController.extend(
    /** @lends {jscape.domain.AddAmazonS3TradingPartnerController.prototype} */
{
    DEFAULT_TIMEOUT: 30 * 1000,

    _setupDialog: function() {
        var dialog = new jscape.domain.AddAmazonS3TradingPartnerDialog();
        dialog.setTimeout(this.DEFAULT_TIMEOUT);
        this.managementService.getDomainTags(this.domainName).done(function (tags) { dialog.setAvailableTags(tags); });
        return  dialog;
    },

    _createPartner: function(dialog) {
        return jscape.TradingPartner.amazonS3(dialog.getName(),
                                              dialog.getCompany(),
                                              dialog.getEmail(),
                                              dialog.getTimeout(),
                                              dialog.getUsername(),
                                              dialog.getPassword(),
                                              dialog.isEncryptionRequired(),
                                              dialog.getTags());
    }
});

/** @class */
jscape.domain.EditAmazonS3TradingPartnerController = jscape.domain.BaseTradingPartnerController.extend(
    /** @lends {jscape.domain.EditAmazonS3TradingPartnerController.prototype} */
{
    /** @override */
    start: function(listener, managementService, domainName, partner) {
        this.partner = partner;
        return this._super(listener, managementService, domainName);
    },

    _setupDialog: function () {
        var dialog = new jscape.domain.EditAmazonS3TradingPartnerDialog();
        var partner = this.partner;
        if (partner) {
            dialog.setName(partner.name);
            dialog.setCompany(partner.company);
            dialog.setEmail(partner.email);
            dialog.setTimeout(partner.timeout);
            dialog.setUsername(partner.username);
            dialog.setPassword(partner.password);
            dialog.setEncryptionRequired(partner.encryptionRequired);
        }
        this.managementService.getDomainTags(this.domainName)
                .done(function (tags) {
                          dialog.setAvailableTags(tags);
                          partner && dialog.setTags(partner.tags);
                      });
        return dialog;
    },

    _createPartner: function(dialog) {
        return jscape.TradingPartner.amazonS3(this.partner.name,
                                              dialog.getCompany(),
                                              dialog.getEmail(),
                                              dialog.getTimeout(),
                                              dialog.getUsername(),
                                              dialog.getPassword(),
                                              dialog.isEncryptionRequired(),
                                              dialog.getTags());
    }
});

/** @class */
jscape.domain.AmazonS3TradingPartnerDialog = jscape.domain.TradingPartnerDialog.extend(
    /** @lends {jscape.domain.AmazonS3TradingPartnerDialog.prototype} */
{
    TIMEOUT_FACTOR: 1000,

    /** @constructor */
    initialize: function(dialog) {
        this._super(dialog);

        this.timeout = $("input[name=timeout]", this.fieldset).numberspinner({required: true, min: 1, max: 60, width: 60});
        this.username = $("input[name=username]", this.fieldset).textbox({width: "50%"});
        this.password = $("input[name=password]", this.fieldset).textbox({type: "password", width: "50%"});
        this.encryptionRequired = $("input[name=encrypt]:checkbox", this.fieldset);
    },

    getTimeout: function() {
        return this.timeout.numberspinner("getValue") * this.TIMEOUT_FACTOR;
    },

    setTimeout: function(value) {
        this.timeout.numberspinner("setValue", parseInt(value) / this.TIMEOUT_FACTOR).numberspinner("validate");
    },

    getUsername: function() {
        return this.username.textbox("getValue");
    },

    setUsername: function(value) {
        this.username.textbox("setValue", value);
    },

    getPassword: function() {
        return this.password.textbox("getValue");
    },

    setPassword: function(value) {
        this.password.textbox("setValue", value);
    },

    isEncryptionRequired: function() {
        return this.encryptionRequired.is(":checked");
    },

    setEncryptionRequired: function(value) {
        this.encryptionRequired.prop("checked", !!value);
    }
});

/** @class */
jscape.domain.AddAmazonS3TradingPartnerDialog = jscape.domain.AmazonS3TradingPartnerDialog.extend(
    /** @lends {jscape.domain.AddAmazonS3TradingPartnerDialog.prototype} */
{
    /** @constructor */
    initialize: function() {
        this._super($("#d-partner-add-amazons3"));

        this.name = $("input[name=name]", this.fieldset).textbox({
            required: true,
            validType: ["partner_name_nonempty", "partner_unique"],
            missingMessage: window.R.string.TRADING_PARTNERS_ERROR_BAD_NAME,
            width: "60%"
        });
    },

    getName: function() {
        return this.name.textbox("getValue");
    }
});

/** @class */
jscape.domain.EditAmazonS3TradingPartnerDialog = jscape.domain.AmazonS3TradingPartnerDialog.extend(
    /** @lends {jscape.domain.EditAmazonS3TradingPartnerDialog.prototype} */
{
    /** @constructor */
    initialize: function() {
        this._super($("#d-partner-edit-amazons3"));

        this.title = this.dialog.dialog("header").text() || "";
    },

    setName: function(value) {
        this.dialog.dialog("setTitle", this.title.supplant({0: value}));
    }
});

/** @class */
jscape.domain.AddAs2TradingPartnerController = jscape.domain.BaseTradingPartnerController.extend(
    /** @lends {jscape.domain.AddAs2TradingPartnerController.prototype} */
{
    /** @const */
    DEFAULT_TIMEOUT: 30 * 1000,
    RECEIPT_TIMEOUT: 5 * 60 * 1000,

    serverKeys: null,

    onSigningKeyChanged: function (keyAlias, dialog) {
        for (var i = 0; i < this.serverKeys.length; i++) {
            var key = this.serverKeys[i];
            if (keyAlias == key.name) {
                var keyAlgorithm = key.keyAlgorithm;
                var algorithms = jscape.SignatureAlgorithm.filter(function (entry) { return entry.asymmetricalAlgorithm == keyAlgorithm; });
                dialog.setSignatureAlgorithms($.map(algorithms, function (entry) { return entry.hashAlgorithm; }));
                break;
            }
        }
    },

    _setupDialog: function() {
        var dialog = new jscape.domain.AddAs2TradingPartnerDialog();
        dialog.setTimeout(this.DEFAULT_TIMEOUT);
        dialog.setReceiptAwaitingTimeout(this.RECEIPT_TIMEOUT);
        dialog.setSignatureAlgorithms($.map(jscape.SignatureAlgorithm.values(), function(entry) { return entry.hashAlgorithm; }));
        dialog.setReceiptHttpsRequired(true);
        dialog.setReceiptSignatureRequired(true);
        this.managementService.getDomainTags(this.domainName).done(function (tags) { dialog.setAvailableTags(tags); });
        this._loadHostKeys(dialog);
        return dialog;
    },

    _createPartner: function(dialog) {
        return jscape.TradingPartner.as2(dialog.getName(),
                                         dialog.getCompany(),
                                         dialog.getEmail(),
                                         dialog.getUrl(),
                                         dialog.getTimeout(),
                                         dialog.getUsername(),
                                         dialog.getPassword(),
                                         this.clientKeyProvider,
                                         this._serverKeyProviderFor(dialog.getHostKey()),
                                         dialog.isUseCompression(),
                                         dialog.getSender(),
                                         dialog.getRecipient(),
                                         dialog.getFromAddress(),
                                         dialog.getReceiptType(),
                                         dialog.isReceiptHttpsRequired(),
                                         dialog.isReceiptSignatureRequired(),
                                         dialog.getReceiptAwaitingTimeout(),
                                         this._serverKeyProviderFor(dialog.getEncryptionKey()),
                                         dialog.getEncryptionAlgorithm(),
                                         this._serverKeyProviderFor(dialog.getSigningKey()),
                                         dialog.getSignatureAlgorithm(),
                                         dialog.getTags());
    },

    /** @override */
    _loadHostKeys: function (dialog) {
        $.when(this.managementService.getHostCertificates(),
               this.managementService.getServerKeys())
                .done($.proxy(function (hostCertificates, serverKeys) {
                          this.serverKeys = serverKeys;
                          hostCertificates = $.map(hostCertificates, function (certificate) { return certificate.name; });
                          dialog.setHostKeys(hostCertificates);
                          dialog.setEncryptionKeys(hostCertificates);
                          dialog.setSigningKeys(serverKeys);
                      }, this));
    },

    _serverKeyProviderFor: function(keyAlias) {
        return keyAlias != null ? new jscape.ServerKeyProvider(keyAlias) : null;
    }
});

/** @class */
jscape.domain.EditAs2TradingPartnerController = jscape.domain.BaseTradingPartnerController.extend(
    /** @lends {jscape.domain.EditAs2TradingPartnerController.prototype} */
{
    serverKeys: null,

    /** @override */
    start: function(listener, managementService, domainName, partner) {
        this.serverKeys = [];
        this.partner = partner;
        return this._super(listener, managementService, domainName, partner.keyProvider);
    },

    onSigningKeyChanged: function (keyAlias, dialog) {
        for (var i = 0; i < this.serverKeys.length; i++) {
            var key = this.serverKeys[i];
            if (keyAlias == key.name) {
                var keyAlgorithm = key.keyAlgorithm;
                var algorithms = jscape.SignatureAlgorithm.filter(function (entry) { return entry.asymmetricalAlgorithm == keyAlgorithm; });
                dialog.setSignatureAlgorithms($.map(algorithms, function (entry) { return entry.hashAlgorithm; }));
                break;
            }
        }
    },

    _setupDialog: function () {
        var dialog = new jscape.domain.EditAs2TradingPartnerDialog();
        dialog.setSignatureAlgorithms($.map(jscape.SignatureAlgorithm.values(), function(entry) { return entry.hashAlgorithm; }));
        var partner = this.partner;
        if (partner) {
            dialog.setName(partner.name);
            dialog.setCompany(partner.company);
            dialog.setEmail(partner.email);
            dialog.setUrl(partner.url);
            dialog.setTimeout(partner.timeout);
            dialog.setUsername(partner.username);
            dialog.setPassword(partner.password);
            dialog.setUseCompression(partner.as2CompressionRequired);
            dialog.setSender(partner.as2Sender);
            dialog.setRecipient(partner.as2Recipient);
            dialog.setFromAddress(partner.as2FromAddress);
            dialog.setReceiptType(partner.as2ReceiptType);
            dialog.setReceiptHttpsRequired(partner.as2ReceiptHttpsRequired);
            dialog.setReceiptSignatureRequired(partner.as2ReceiptSignatureRequired);
            dialog.setReceiptAwaitingTimeout(partner.as2ReceiptAwaitingTimeout);
        }
        this.managementService.getDomainTags(this.domainName)
                .done(function (tags) {
                          dialog.setAvailableTags(tags);
                          partner && dialog.setTags(partner.tags);
                      });
        this._loadHostKeys(dialog);
        return dialog;
    },

    /** @override */
    _loadHostKeys: function (dialog) {
        var partner = this.partner;
        var hostKey = this._serverKeyProviderAlias(partner.hostKeyProvider);
        var encryptionKey = this._serverKeyProviderAlias(partner.encryptionKeyProvider);
        var signingKey = this._serverKeyProviderAlias(partner.signingKeyProvider);

        return $.when(this.managementService.getHostCertificates(),
                      this.managementService.getServerKeys())
                .done($.proxy(function (hostCertificates, serverKeys) {
                          this.serverKeys = serverKeys;
                          hostCertificates = $.map(hostCertificates, function (certificate) { return certificate.name; });
                          dialog.setHostKeys(hostCertificates);
                          dialog.setHostKey(hostKey);
                          dialog.setEncryptionKeys(hostCertificates);
                          dialog.setEncryptionKey(encryptionKey);
                          dialog.setEncryptionAlgorithm(partner.encryptionAlgorithm);
                          dialog.setSigningKeys(serverKeys);
                          dialog.setSigningKey(signingKey);
                          dialog.setSignatureAlgorithm(partner.signatureAlgorithm);
                      }, this));
    },

    _createPartner: function (dialog) {
        return jscape.TradingPartner.as2(this.partner.name,
                                         dialog.getCompany(),
                                         dialog.getEmail(),
                                         dialog.getUrl(),
                                         dialog.getTimeout(),
                                         dialog.getUsername(),
                                         dialog.getPassword(),
                                         this.clientKeyProvider,
                                         this._serverKeyProviderFor(dialog.getHostKey()),
                                         dialog.isUseCompression(),
                                         dialog.getSender(),
                                         dialog.getRecipient(),
                                         dialog.getFromAddress(),
                                         dialog.getReceiptType(),
                                         dialog.isReceiptHttpsRequired(),
                                         dialog.isReceiptSignatureRequired(),
                                         dialog.getReceiptAwaitingTimeout(),
                                         this._serverKeyProviderFor(dialog.getEncryptionKey()),
                                         dialog.getEncryptionAlgorithm(),
                                         this._serverKeyProviderFor(dialog.getSigningKey()),
                                         dialog.getSignatureAlgorithm(),
                                         dialog.getTags());
    },

    _serverKeyProviderFor: function(keyAlias) {
        return keyAlias != null ? new jscape.ServerKeyProvider(keyAlias) : null;
    },

    _serverKeyProviderAlias: function(keyProvider) {
        return keyProvider && keyProvider.keyAlias ? keyProvider.keyAlias : null;
    }
});

/** @class */
jscape.domain.As2TradingPartnerDialog = jscape.domain.TradingPartnerDialog.extend(
    /** @lends {jscape.domain.As2TradingPartnerDialog.prototype} */
{
    TIMEOUT_FACTOR: 1000,
    RECEIPT_TIMEOUT_FACTOR: 60 * 1000,

    /** @constructor */
    initialize: function(dialog) {
        this._super(dialog);

        this.url = $("input[name=url]", this.fieldset).textbox({required: true, validType: "partner_url", missingMessage: window.R.string.TRADING_PARTNERS_ERROR_BAD_URL, width: "60%"});
        this.timeout = $("input[name=timeout]", this.fieldset).numberspinner({required: true, min: 1, max: 60, width: 60});

        this.username = $("input[name=username]", this.fieldset).textbox({width: "50%"});
        this.password = $("input[name=password]", this.fieldset).textbox({type: "password", width: "50%"});

        this.useHostKey = $("input[name=usehostkey]:checkbox", this.fieldset).prop("disabled", true);
        this.useHostKey.change($.proxy(function() {
            this.hostKey.combobox(this.useHostKey.is(":checked") ? "enable" : "disable");
        }, this));
        this.hostKey = $("select[name=hostkey]", this.fieldset);
        this.hostKey.combobox({editable: false, disabled: true, width: 170, panelHeight: "auto", panelMaxHeight: 150, onLoadSuccess: $.proxy(function(data) {
            this.useHostKey.prop("disabled", data.length == 0);
            if (data.length != 0) {
                this.hostKey.combobox("setValue", data[0].value);
            }
        }, this)});

        this.clientKeyButton = $("a[role=button][name=selectclientkey]", this.fieldset).linkbutton({onClick: $.proxy(this._onClick$ClientKeyButton, this)});

        this.sender = $("input[name=sender]", this.fieldset).textbox({required: true, validType: "partner_sender", missingMessage: window.R.string.TRADING_PARTNERS_ERROR_BAD_SENDER, width: "50%"});
        this.recipient = $("input[name=recipient]", this.fieldset).textbox({required: true, validType: "partner_recipient", missingMessage: window.R.string.TRADING_PARTNERS_ERROR_BAD_RECIPIENT, width: "50%"});
        this.fromAddress = $("input[name=from]", this.fieldset).textbox({required: false, validType: "email", width: "50%"});

        this.receiptType = $("select[name=receipt]", this.fieldset);
        this.receiptType.combobox({required: true, editable: false, width: 170, panelHeight: "auto", panelMaxHeight: 150, onChange: $.proxy(function() {
            var enabled = "ASYNCHRONOUS" == this.receiptType.combobox("getValue");
            this.receiptHttpsRequired.prop("disabled", !enabled);
        }, this)});

        this.receiptHttpsRequired = $("input[name=usereceiptssl]:checkbox", this.fieldset).prop("disabled", true);
        this.receiptSignatureRequired = $("input[name=usereceiptsignature]:checkbox", this.fieldset);

        this.receipTimeout = $("input[name=receiptimeout]", this.fieldset).numberspinner({required: true, min: 1, max: 1000, width: 90});

        this.useEncryptKey = $("input[name=useencryptkey]:checkbox", this.fieldset);
        this.useEncryptKey.change($.proxy(function() {
            var enabled = this.useEncryptKey.is(":checked");
            this.encryptKey.combobox(enabled ? "enable" : "disable");
            this.encryptAlgorithm.combobox(enabled ? "enable" : "disable");
        }, this));
        this.encryptKey = $("select[name=encryptkey]", this.fieldset);
        this.encryptKey.combobox({
            editable: false, disabled: true,
            width: 170, panelHeight: "auto", panelMaxHeight: 150,
            onLoadSuccess: $.proxy(function(data) {
                if (data.length != 0) {
                    this.encryptKey.combobox("select", data[0].value);
                } else {
                    this.useEncryptKey.prop("disabled", true).prop("checked", false);
                }
                this.useEncryptKey.change();
            }, this)});
        this.encryptAlgorithm = $("select[name=encryptalgorithm]", this.fieldset).combobox({editable: false, width: 170, panelHeight: "auto", panelMaxHeight: 150});

        this.useSignKey = $("input[name=usesigningkey]:checkbox", this.fieldset);
        this.useSignKey.change($.proxy(function () {
            var enabled = this.useSignKey.is(":checked");
            this.signKey.combobox(enabled ? "enable" : "disable");
            this.signatureAlgorithm.combobox(enabled ? "enable" : "disable");
        }, this));
        this.signKey = $("select[name=signingkey]", this.fieldset);
        this.signKey.combobox({editable: false, disabled: true, textField: "name", valueField: "name", onChange: $.proxy(this._onChange$SigningKey, this), width: 170, panelHeight: "auto", panelMaxHeight: 150});
        this.signatureAlgorithm = $("select[name=signalgorithm]", this.fieldset).combobox({editable: false, disabled: true, width: 170, panelHeight: "auto", panelMaxHeight: 150});

        this.useCompression = $("input[name=usecompression]:checkbox", this.fieldset);
    },

    getUrl: function() {
        return this.url.textbox("getValue");
    },

    setUrl: function(value) {
        this.url.textbox("setValue", value);
    },

    getTimeout: function() {
        return this.timeout.numberspinner("getValue") * this.TIMEOUT_FACTOR;
    },

    setTimeout: function(value) {
        this.timeout.numberspinner("setValue", parseInt(value) / this.TIMEOUT_FACTOR);
    },

    getUsername: function() {
        return this.username.textbox("getValue");
    },

    setUsername: function(value) {
        this.username.textbox("setValue", value);
    },

    getPassword: function() {
        return this.password.textbox("getValue");
    },

    setPassword: function(value) {
        this.password.textbox("setValue", value);
    },

    getHostKey: function() {
        return this.useHostKey.is(":checked") ? this.hostKey.combobox("getValue") : null;
    },

    setHostKey: function(value) {
        this.useHostKey.prop("checked", value != null).change();
        if (value != null) {
            this.hostKey.combobox("setValue", value);
        }
    },

    setHostKeys: function(values) {
        this.hostKey.combobox("loadData", values);
    },

    getSender: function() {
        return this.sender.textbox("getValue");
    },

    setSender: function(value) {
        this.sender.textbox("setValue", value);
    },

    getRecipient: function() {
        return this.recipient.textbox("getValue");
    },

    setRecipient: function(value) {
        this.recipient.textbox("setValue", value);
    },

    getFromAddress: function() {
        return this.fromAddress.textbox("getValue");
    },

    setFromAddress: function(value) {
        this.fromAddress.textbox("setValue", value);
    },

    getReceiptType: function() {
        return this.receiptType.combobox("getValue");
    },

    setReceiptType: function(value) {
        this.receiptType.combobox("setValue", value);
    },

    isReceiptHttpsRequired: function() {
        return this.receiptHttpsRequired.is(":checked:not(:disabled)");
    },

    setReceiptHttpsRequired: function(value) {
        this.receiptHttpsRequired.prop("checked", !!value);
    },

    isReceiptSignatureRequired: function() {
        return this.receiptSignatureRequired.is(":checked");
    },

    setReceiptSignatureRequired: function(value) {
        this.receiptSignatureRequired.prop("checked", !!value);
    },

    getReceiptAwaitingTimeout: function() {
        return this.receipTimeout.numberspinner("getValue") * this.RECEIPT_TIMEOUT_FACTOR;
    },

    setReceiptAwaitingTimeout: function(value) {
        this.receipTimeout.numberspinner("setValue", parseInt(value) / this.RECEIPT_TIMEOUT_FACTOR);
    },

    getEncryptionKey: function() {
        return this.useEncryptKey.is(":checked") ? this.encryptKey.combobox("getValue") : null;
    },

    setEncryptionKey: function(value) {
        this.useEncryptKey.prop("checked", value != null).change();
        if (value != null) {
            this.encryptKey.combobox("select", value);
        }
    },

    setEncryptionKeys: function(values) {
        this.encryptKey.combobox("loadData", values);
    },

    getEncryptionAlgorithm: function() {
        return this.encryptAlgorithm.combobox("getValue");
    },

    setEncryptionAlgorithm: function(value) {
        this.encryptAlgorithm.combobox("setValue", value);
    },

    getSigningKey: function() {
        return this.useSignKey.is(":checked") ? this.signKey.combobox("getValue") : null;
    },

    setSigningKey: function(value) {
        this.useSignKey.prop("checked", value != null).change();
        if (value != null) {
            this.signKey.combobox("setValue", value);
        }
    },

    setSigningKeys: function (values) {
        this.signKey.combobox("loadData", values);
        if (values.length == 0) {
            this.useSignKey.prop("disabled", true).prop("checked", false).change();
        }
    },

    getSignatureAlgorithm: function() {
        return this.signatureAlgorithm.combobox("getValue");
    },

    setSignatureAlgorithm: function(value) {
        this.signatureAlgorithm.combobox("reset").combobox("select", value);
    },

    setSignatureAlgorithms: function (values) {
        this.signatureAlgorithm.combobox("loadData", values);
    },

    isUseCompression: function() {
        return this.useCompression.is(":checked");
    },

    setUseCompression: function(value) {
        this.useCompression.prop("checked", !!value);
    },

    /** @override */
    show: function(listener) {
        return this._super(listener || jscape.domain.As2TradingPartnerDialog.LISTENER);
    },

    _onChange$SigningKey: function() {
        this.listener.onSigningKeyChanged(this.signKey.combobox("getValue"), this);
    },

    _onClick$ClientKeyButton: function() {
        this.listener.onSelectClientKey();
    }
});
jscape.domain.As2TradingPartnerDialog.LISTENER = $.extend({
    onSelectClientKey: $.noop,
    onSigningKeyChanged: $.noop
}, jscape.domain.TradingPartnerDialog.LISTENER);

/** @class */
jscape.domain.AddAs2TradingPartnerDialog = jscape.domain.As2TradingPartnerDialog.extend(
    /** @lends {jscape.domain.AddAs2TradingPartnerDialog.prototype} */
{
    /** @constructor */
    initialize: function() {
        this._super($("#d-partner-add-as2"));

        this.name = $("input[name=name]", this.fieldset).textbox({
            required: true,
            validType: ["partner_name_nonempty", "partner_unique"],
            missingMessage: window.R.string.TRADING_PARTNERS_ERROR_BAD_NAME,
            width: "60%"
        });
    },

    getName: function() {
        return this.name.textbox("getValue");
    }
});

/** @class */
jscape.domain.EditAs2TradingPartnerDialog = jscape.domain.As2TradingPartnerDialog.extend(
    /** @lends {jscape.domain.EditAs2TradingPartnerDialog.prototype} */
{
    /** @constructor */
    initialize: function() {
        this._super($("#d-partner-edit-as2"));

        this.title = this.dialog.dialog("header").text() || "";
    },

    setName: function(value) {
        this.dialog.dialog("setTitle", this.title.supplant({0: value}));
    }
});

/** @class */
jscape.domain.AddFtpTradingPartnerController = jscape.domain.BaseTradingPartnerController.extend(
    /** @lends {jscape.domain.AddFtpTradingPartnerController.prototype} */
{
    DEFAULTS: {port: 21, timeout: 30 * 1000, tcpNoDelay: true},

    _setupDialog: function() {
        var dialog = new jscape.domain.AddFtpTradingPartnerDialog();
        dialog.setPort(this.DEFAULTS.port);
        dialog.setTimeout(this.DEFAULTS.timeout);
        dialog.setTcpNoDelay(this.DEFAULTS.tcpNoDelay);
        this.managementService.getDomainTags(this.domainName).done(function (tags) { dialog.setAvailableTags(tags); });
        return dialog;
    },

    _createPartner: function(dialog) {
        return jscape.TradingPartner.ftp(dialog.getName(),
                                         dialog.getCompany(),
                                         dialog.getEmail(),
                                         dialog.getHost(),
                                         dialog.getPort(),
                                         dialog.getTimeout(),
                                         dialog.getTcpNoDelay(),
                                         dialog.getUsername(),
                                         dialog.getPassword(),
                                         dialog.getPostLoginCommand(),
                                         dialog.getTags());
    }
});

/** @class */
jscape.domain.EditFtpTradingPartnerController = jscape.domain.BaseTradingPartnerController.extend(
    /** @lends {jscape.domain.EditFtpTradingPartnerController.prototype} */
{
    /** @override */
    start: function(listener, managementService, domainName, partner) {
        this.partner = partner;
        return this._super(listener, managementService, domainName);
    },

    _setupDialog: function () {
        var dialog = new jscape.domain.EditFtpTradingPartnerDialog();
        var partner = this.partner;
        if (partner) {
            dialog.setName(partner.name);
            dialog.setCompany(partner.company);
            dialog.setEmail(partner.email);
            dialog.setHost(partner.host);
            dialog.setPort(partner.port);
            dialog.setTimeout(partner.timeout);
            dialog.setTcpNoDelay(partner.tcpNoDelayEnabled);
            dialog.setUsername(partner.username);
            dialog.setPassword(partner.password);
            dialog.setPostLoginCommand(partner.ftpPostLoginCommand);
        }
        this.managementService.getDomainTags(this.domainName)
                .done(function (tags) {
                          dialog.setAvailableTags(tags);
                          partner && dialog.setTags(partner.tags);
                      });
        return dialog;
    },

    _createPartner: function (dialog) {
        return jscape.TradingPartner.ftp(this.partner.name,
                                         dialog.getCompany(),
                                         dialog.getEmail(),
                                         dialog.getHost(),
                                         dialog.getPort(),
                                         dialog.getTimeout(),
                                         dialog.getTcpNoDelay(),
                                         dialog.getUsername(),
                                         dialog.getPassword(),
                                         dialog.getPostLoginCommand(),
                                         dialog.getTags());
    }
});

/** @class */
jscape.domain.FtpTradingPartnerDialog = jscape.domain.TradingPartnerDialog.extend(
    /** @lends {jscape.domain.FtpTradingPartnerDialog.prototype} */
{
    TIMEOUT_FACTOR: 1000,

    /** @constructor */
    initialize: function(dialog) {
        this._super(dialog);

        this.host = $("input[name=host]", this.fieldset).textbox({required: true, validType: "partner_host_nonempty", missingMessage: window.R.string.TRADING_PARTNERS_ERROR_BAD_HOST, width: "60%"});
        this.port = $("input[name=port]", this.fieldset).numberspinner({required: true, min: 1, max: 65535, width: 100});
        this.timeout = $("input[name=timeout]", this.fieldset).numberspinner({required: true, min: 1, max: 60, width: 60});
        this.tcpNoDelay = $("input[name=tcpnodelay]:checkbox", this.fieldset);
        this.username = $("input[name=username]", this.fieldset).textbox({width: "50%"});
        this.password = $("input[name=password]", this.fieldset).textbox({type: "password", width: "50%"});
        this.postLoginCommand = $("input[name=postlogincmd]", this.fieldset).textbox({width: "60%"});
    },

    getHost: function() {
        return this.host.textbox("getValue");
    },

    setHost: function(value) {
        this.host.textbox("setValue", value);
    },

    getPort: function() {
        return this.port.numberspinner("getValue");
    },

    setPort: function(value) {
        this.port.numberspinner("setValue", value);
    },

    getTimeout: function() {
        return this.timeout.numberspinner("getValue") * this.TIMEOUT_FACTOR;
    },

    setTimeout: function(value) {
        this.timeout.numberspinner("setValue", parseInt(value) / this.TIMEOUT_FACTOR);
    },

    getTcpNoDelay: function() {
        return this.tcpNoDelay.is(":checked");
    },

    setTcpNoDelay: function(value) {
        this.tcpNoDelay.prop("checked", !!value);
    },

    getUsername: function() {
        return this.username.textbox("getValue");
    },

    setUsername: function(value) {
        this.username.textbox("setValue", value);
    },

    getPassword: function() {
        return this.password.textbox("getValue");
    },

    setPassword: function(value) {
        this.password.textbox("setValue", value);
    },

    getPostLoginCommand: function() {
        return this.postLoginCommand.textbox("getValue");
    },

    setPostLoginCommand: function(value) {
        this.postLoginCommand.textbox("setValue", value);
    }
});

/** @class */
jscape.domain.AddFtpTradingPartnerDialog = jscape.domain.FtpTradingPartnerDialog.extend(
    /** @lends {jscape.domain.AddFtpTradingPartnerDialog.prototype} */
{
    /** @constructor */
    initialize: function() {
        this._super($("#d-partner-add-ftp"));

        this.name = $("input[name=name]", this.fieldset).textbox({
            required: true,
            validType: ["partner_name_nonempty", "partner_unique"],
            missingMessage: window.R.string.TRADING_PARTNERS_ERROR_BAD_NAME,
            width: "60%"
        });
    },

    getName: function() {
        return this.name.textbox("getValue");
    }
});

/** @class */
jscape.domain.EditFtpTradingPartnerDialog = jscape.domain.FtpTradingPartnerDialog.extend(
    /** @lends {jscape.domain.EditFtpTradingPartnerDialog.prototype} */
{
    /** @constructor */
    initialize: function() {
        this._super($("#d-partner-edit-ftp"));

        this.title = this.dialog.dialog("header").text() || "";
    },

    setName: function(value) {
        this.dialog.dialog("setTitle", this.title.supplant({0: value}));
    }
});

/** @class */
jscape.domain.AddFtpsImplicitTradingPartnerController = jscape.domain.BaseTradingPartnerController.extend(
    /** @lends {jscape.domain.AddFtpsImplicitTradingPartnerController.prototype} */
{
    DEFAULTS: {port: 990, timeout: 30 * 1000, tcpNoDelay: true},

    _setupDialog: function() {
        var dialog = new jscape.domain.AddFtpsTradingPartnerDialog();
        dialog.setPort(this.DEFAULTS.port);
        dialog.setTimeout(this.DEFAULTS.timeout);
        dialog.setTcpNoDelay(this.DEFAULTS.tcpNoDelay);
        this.managementService.getDomainTags(this.domainName).done(function (tags) { dialog.setAvailableTags(tags); });
        this._loadHostKeys().done(function(keys) { dialog.setHostKeys(keys); });
        return dialog;
    },

    _createPartner: function(dialog) {
        return jscape.TradingPartner.ftpsImplicit(dialog.getName(),
                                                  dialog.getCompany(),
                                                  dialog.getEmail(),
                                                  dialog.getHost(),
                                                  dialog.getPort(),
                                                  dialog.getTimeout(),
                                                  dialog.getTcpNoDelay(),
                                                  dialog.getUsername(),
                                                  dialog.getPassword(),
                                                  this.clientKeyProvider,
                                                  dialog.getHostKey() != null ? new jscape.ServerKeyProvider(dialog.getHostKey()) : null,
                                                  dialog.getPostLoginCommand(),
                                                  dialog.getTags());
    }
});

/** @class */
jscape.domain.EditFtpsImplicitTradingPartnerController = jscape.domain.BaseTradingPartnerController.extend(
    /** @lends {jscape.domain.EditFtpsImplicitTradingPartnerController.prototype} */
{
    /** @override */
    start: function(listener, managementService, domainName, partner) {
        this.partner = partner;
        return this._super(listener, managementService, domainName, partner.keyProvider);
    },

    _setupDialog: function () {
        var dialog = new jscape.domain.EditFtpsTradingPartnerDialog();
        var partner = this.partner;
        if (partner) {
            dialog.setName(partner.name);
            dialog.setCompany(partner.company);
            dialog.setEmail(partner.email);
            dialog.setHost(partner.host);
            dialog.setPort(partner.port);
            dialog.setTimeout(partner.timeout);
            dialog.setTcpNoDelay(partner.tcpNoDelayEnabled);
            dialog.setUsername(partner.username);
            dialog.setPassword(partner.password);
            dialog.setPostLoginCommand(partner.ftpPostLoginCommand);
        }
        this.managementService.getDomainTags(this.domainName)
                .done(function (tags) {
                          dialog.setAvailableTags(tags);
                          partner && dialog.setTags(partner.tags);
                      });
        this._loadHostKeys()
                .done(function (keys) {
                          dialog.setHostKeys(keys);
                          partner && dialog.setHostKey(partner.hostKeyProvider ? partner.hostKeyProvider.keyAlias : null);
                      });
        return dialog;
    },

    _createPartner: function (dialog) {
        return jscape.TradingPartner.ftpsImplicit(this.partner.name,
                                                  dialog.getCompany(),
                                                  dialog.getEmail(),
                                                  dialog.getHost(),
                                                  dialog.getPort(),
                                                  dialog.getTimeout(),
                                                  dialog.getTcpNoDelay(),
                                                  dialog.getUsername(),
                                                  dialog.getPassword(),
                                                  this.clientKeyProvider,
                                                  dialog.getHostKey() != null ? new jscape.ServerKeyProvider(dialog.getHostKey()) : null,
                                                  dialog.getPostLoginCommand(),
                                                  dialog.getTags());
    }
});

/** @class */
jscape.domain.AddFtpsExplicitTradingPartnerController = jscape.domain.BaseTradingPartnerController.extend(
    /** @lends {jscape.domain.AddFtpsExplicitTradingPartnerController.prototype} */
{
    DEFAULTS: {port: 21, timeout: 30 * 1000, tcpNoDelay: true},

    _setupDialog: function() {
        var dialog = new jscape.domain.AddFtpsTradingPartnerDialog();
        dialog.setPort(this.DEFAULTS.port);
        dialog.setTimeout(this.DEFAULTS.timeout);
        dialog.setTcpNoDelay(this.DEFAULTS.tcpNoDelay);
        this.managementService.getDomainTags(this.domainName).done(function (tags) { dialog.setAvailableTags(tags); });
        this._loadHostKeys().done(function(keys) { dialog.setHostKeys(keys); });
        return dialog;
    },

    _createPartner: function(dialog) {
        return jscape.TradingPartner.ftpsExplicit(dialog.getName(),
                                                  dialog.getCompany(),
                                                  dialog.getEmail(),
                                                  dialog.getHost(),
                                                  dialog.getPort(),
                                                  dialog.getTimeout(),
                                                  dialog.getTcpNoDelay(),
                                                  dialog.getUsername(),
                                                  dialog.getPassword(),
                                                  this.clientKeyProvider,
                                                  dialog.getHostKey() != null ? new jscape.ServerKeyProvider(dialog.getHostKey()) : null,
                                                  dialog.getPostLoginCommand(),
                                                  dialog.getTags());
    }
});

/** @class */
jscape.domain.EditFtpsExplicitTradingPartnerController = jscape.domain.BaseTradingPartnerController.extend(
    /** @lends {jscape.domain.EditFtpsExplicitTradingPartnerController.prototype} */
{
    /** @override */
    start: function(listener, managementService, domainName, partner) {
        this.partner = partner;
        return this._super(listener, managementService, domainName, partner.keyProvider);
    },

    _setupDialog: function () {
        var dialog = new jscape.domain.EditFtpsTradingPartnerDialog();
        var partner = this.partner;
        if (partner) {
            dialog.setName(partner.name);
            dialog.setCompany(partner.company);
            dialog.setEmail(partner.email);
            dialog.setHost(partner.host);
            dialog.setPort(partner.port);
            dialog.setTimeout(partner.timeout);
            dialog.setTcpNoDelay(partner.tcpNoDelayEnabled);
            dialog.setUsername(partner.username);
            dialog.setPassword(partner.password);
            dialog.setPostLoginCommand(partner.ftpPostLoginCommand);
        }
        this.managementService.getDomainTags(this.domainName)
                .done(function (tags) {
                          dialog.setAvailableTags(tags);
                          partner && dialog.setTags(partner.tags);
                      });
        this._loadHostKeys()
                .done(function (keys) {
                          dialog.setHostKeys(keys);
                          partner && dialog.setHostKey(partner.hostKeyProvider ? partner.hostKeyProvider.keyAlias : null);
                      });
        return dialog;
    },

    _createPartner: function (dialog) {
        return jscape.TradingPartner.ftpsExplicit(this.partner.name,
                                                  dialog.getCompany(),
                                                  dialog.getEmail(),
                                                  dialog.getHost(),
                                                  dialog.getPort(),
                                                  dialog.getTimeout(),
                                                  dialog.getTcpNoDelay(),
                                                  dialog.getUsername(),
                                                  dialog.getPassword(),
                                                  this.clientKeyProvider,
                                                  dialog.getHostKey() != null ? new jscape.ServerKeyProvider(dialog.getHostKey()) : null,
                                                  dialog.getPostLoginCommand(),
                                                  dialog.getTags());
    }
});

/** @class */
jscape.domain.FtpsTradingPartnerDialog = jscape.domain.TradingPartnerDialog.extend(
    /** @lends {jscape.domain.FtpsTradingPartnerDialog.prototype} */
{
    TIMEOUT_FACTOR: 1000,

    /** @constructor */
    initialize: function(dialog) {
        this._super(dialog);

        this.host = $("input[name=host]", this.fieldset).textbox({required: true, validType: "partner_host_nonempty", missingMessage: window.R.string.TRADING_PARTNERS_ERROR_BAD_HOST, width: "60%"});
        this.port = $("input[name=port]", this.fieldset).numberspinner({required: true, min: 1, max: 65535, width: 100});
        this.timeout = $("input[name=timeout]", this.fieldset).numberspinner({required: true, min: 1, max: 60, width: 60});
        this.tcpNoDelay = $("input[name=tcpnodelay]:checkbox", this.fieldset);

        this.username = $("input[name=username]", this.fieldset).textbox({width: "50%"});
        this.password = $("input[name=password]", this.fieldset).textbox({type: "password", width: "50%"});

        this.useHostKey = $("input[name=usehostkey]:checkbox", this.fieldset).prop("disabled", true);
        this.useHostKey.change($.proxy(function() {
            this.hostKey.combobox(this.useHostKey.is(":checked") ? "enable" : "disable");
        }, this));
        this.hostKey = $("select[name=hostkey]", this.fieldset);
        this.hostKey.combobox({editable: false, disabled: true, width: 170, panelHeight: "auto", panelMaxHeight: 150, onLoadSuccess: $.proxy(function(data) {
            this.useHostKey.prop("disabled", data.length == 0);
            if (data.length != 0) {
                this.hostKey.combobox("select", data[0].value);
            }
        }, this)});

        this.clientKeyButton = $("a[role=button][name=selectclientkey]", this.fieldset).linkbutton({onClick: $.proxy(this._onClick$ClientKeyButton, this)});

        this.postLoginCommand = $("input[name=postlogincmd]", this.fieldset).textbox({width: "60%"});
    },

    getHost: function() {
        return this.host.textbox("getValue");
    },

    setHost: function(value) {
        this.host.textbox("setValue", value);
    },

    getPort: function() {
        return this.port.numberspinner("getValue");
    },

    setPort: function(value) {
        this.port.numberspinner("setValue", value);
    },

    getTimeout: function() {
        return this.timeout.numberspinner("getValue") * this.TIMEOUT_FACTOR;
    },

    setTimeout: function(value) {
        this.timeout.numberspinner("setValue", parseInt(value) / this.TIMEOUT_FACTOR);
    },

    getTcpNoDelay: function() {
        return this.tcpNoDelay.is(":checked");
    },

    setTcpNoDelay: function(value) {
        this.tcpNoDelay.prop("checked", !!value);
    },

    getUsername: function() {
        return this.username.textbox("getValue");
    },

    setUsername: function(value) {
        this.username.textbox("setValue", value);
    },

    getPassword: function() {
        return this.password.textbox("getValue");
    },

    setPassword: function(value) {
        this.password.textbox("setValue", value);
    },

    getHostKey: function() {
        return this.useHostKey.is(":checked") ? this.hostKey.combobox("getValue") : null;
    },

    setHostKey: function(value) {
        this.useHostKey.prop("checked", value != null).change();
        if (value != null) {
            this.hostKey.combobox("setValue", value);
        }
    },

    setHostKeys: function(values) {
        this.hostKey.combobox("loadData", values);
    },

    getPostLoginCommand: function() {
        return this.postLoginCommand.textbox("getValue");
    },

    setPostLoginCommand: function(value) {
        this.postLoginCommand.textbox("setValue", value);
    },

    /** @override */
    show: function (listener) {
        return this._super(listener || jscape.domain.FtpsTradingPartnerDialog.LISTENER);
    },

    _onClick$ClientKeyButton: function() {
        this.listener.onSelectClientKey();
    }
});
jscape.domain.FtpsTradingPartnerDialog.LISTENER = $.extend({
    onSelectClientKey: $.noop
}, jscape.domain.TradingPartnerDialog.LISTENER);

/** @class */
jscape.domain.AddFtpsTradingPartnerDialog = jscape.domain.FtpsTradingPartnerDialog.extend(
    /** @lends {jscape.domain.AddFtpsTradingPartnerDialog.prototype} */
{
    /** @constructor */
    initialize: function() {
        this._super($("#d-partner-add-ftps"));

        this.name = $("input[name=name]", this.fieldset).textbox({
            required: true,
            validType: ["partner_name_nonempty", "partner_unique"],
            missingMessage: window.R.string.TRADING_PARTNERS_ERROR_BAD_NAME,
            width: "60%"
        });
    },

    getName: function() {
        return this.name.textbox("getValue");
    }
});

/** @class */
jscape.domain.EditFtpsTradingPartnerDialog = jscape.domain.FtpsTradingPartnerDialog.extend(
    /** @lends {jscape.domain.EditFtpsTradingPartnerDialog.prototype} */
{
    /** @constructor */
    initialize: function() {
        this._super($("#d-partner-edit-ftps"));

        this.title = this.dialog.dialog("header").text() || "";
    },

    setName: function(value) {
        this.dialog.dialog("setTitle", this.title.supplant({0: value}));
    }
});

/** @class */
jscape.domain.OftpTradingPartnerController = jscape.domain.BaseTradingPartnerController.extend(
    /** @lends {jscape.domain.OftpTradingPartnerController.prototype} */
{
    DEFAULT_PORT: 3305,
    DEFAULT_TIMEOUT: 30 * 1000,

    sslCertificateData: null,
    authenticationCertificateData: null,
    requestEncryptionCertificateData: null,
    requestSignatureVerificationCertificateData: null,
    receiptSignatureVerificationCertificateData: null,

    /** @constructor */
    initialize: function () {
        this._super();
        this.specController = new jscape.domain.OftpTradingPartnerSpecController();
    },

    start: function(listener, managementService, domainName, oftpData) {
        if (oftpData == undefined) {
            oftpData = new jscape.OftpPartnerData();
        }
        this.sslCertificateData = oftpData.sslCertificateData;
        this.authenticationCertificateData = oftpData.authenticationCertificateData;
        this.requestEncryptionCertificateData = oftpData.requestEncryptionCertificateData;
        this.requestSignatureVerificationCertificateData = oftpData.requestSignatureVerificationCertificateData;
        this.receiptSignatureVerificationCertificateData = oftpData.receiptSignatureVerificationCertificateData;

        return this._super(listener, managementService, domainName);
    },

    onSslCertificateSpec: function() {
        return this.specController.start(this.sslCertificateData.descriptor)
                        .done($.proxy(function (descriptor) { this.sslCertificateData.descriptor = descriptor; }, this));
    },

    onAuthenticationCertificateSpec: function () {
        return this.specController.start(this.authenticationCertificateData.descriptor)
                .done($.proxy(function (descriptor) { this.authenticationCertificateData.descriptor = descriptor; }, this));
    },

    onFileEncryptionCertSpec: function () {
        return this.specController.start(this.requestEncryptionCertificateData.descriptor)
                .done($.proxy(function (descriptor) { this.requestEncryptionCertificateData.descriptor = descriptor; }, this));
    },

    onFileSignatureCertSpec: function () {
        return this.specController.start(this.requestSignatureVerificationCertificateData.descriptor)
                .done($.proxy(function (descriptor) { this.requestSignatureVerificationCertificateData.descriptor = descriptor; }, this));
    },

    onReceiptSignatureCertSpec: function () {
        return this.specController.start(this.receiptSignatureVerificationCertificateData.descriptor)
                .done($.proxy(function (descriptor) { this.receiptSignatureVerificationCertificateData.descriptor = descriptor; }, this));
    },

    _createPartner: function(dialog) {
        return jscape.TradingPartner.oftp(dialog.getName(),
                                          dialog.getCompany(),
                                          dialog.getEmail(),
                                          dialog.getHost(),
                                          dialog.getPort(),
                                          dialog.getTimeout(),
                                          dialog.getUsername(),
                                          dialog.getPassword(),
                                          new jscape.OftpPartnerData(
                                                  dialog.getDestinationId(),
                                                  new jscape.CertificateData(this.sslCertificateData.descriptor, dialog.getSslCertificate()),
                                                  dialog.getSslKey(),
                                                  new jscape.CertificateData(this.authenticationCertificateData.descriptor, dialog.getSecureAuthenticationCertificate()),
                                                  dialog.getSecureAuthenticationKey(),
                                                  new jscape.CertificateData(this.requestEncryptionCertificateData.descriptor, dialog.getRequestEncryptionCertificate()),
                                                  dialog.getRequestDecryptionKey(),
                                                  dialog.getRequestSigningKey(),
                                                  new jscape.CertificateData(this.requestSignatureVerificationCertificateData.descriptor, dialog.getRequestSignatureVerificationCertificate()),
                                                  dialog.getReceiptSigningKey(),
                                                  new jscape.CertificateData(this.receiptSignatureVerificationCertificateData.descriptor, dialog.getReceiptSignatureVerificationCertificate()),
                                                  dialog.getCipher(),
                                                  dialog.isSslEnabled(),
                                                  dialog.isSecureAuthenticationEnabled(),
                                                  dialog.isUseCompression(),
                                                  dialog.isUseEncryption(),
                                                  dialog.isUseSigning(),
                                                  dialog.isReceiptSignatureRequired(),
                                                  dialog.isReceiptAutoGenerationAllowed(),
                                                  dialog.isCertificateExchangeAllowed(),
                                                  dialog.isRelayAllowed()
                                          ),
                                          dialog.getTags());
    },

    _loadKeys: function () {
        return $.when(this.managementService.getHostCertificates(),
                      this.managementService.getClientCertificates(),
                      this.managementService.getServerKeys())
                .then(function (hostCertificates, clientCertificates, serverKeys) {
                          var hostCertificateNames = $.map(hostCertificates, function (cetrificate) { return cetrificate.name; });
                          var clientCertificateNames = $.map(clientCertificates, function (certificate) { return certificate.name; });
                          var serverKeyAliases = $.map(serverKeys, function (key) { return key.name; });

                          return $.Deferred().resolve(hostCertificateNames, clientCertificateNames, serverKeyAliases);
                      });
    }
});

/** @class */
jscape.domain.AddOftpTradingPartnerController = jscape.domain.OftpTradingPartnerController.extend(
    /** @lends {jscape.domain.AddOftpTradingPartnerController.prototype} */
{

    partnerData: null,

    _setupDialog: function() {
        var dialog = new jscape.domain.AddOftpTradingPartnerDialog();
        dialog.setPort(this.DEFAULT_PORT);
        dialog.setTimeout(this.DEFAULT_TIMEOUT);
        dialog.setReceiptAutoGenerationAllowed(true);
        this.managementService.getDomainTags(this.domainName).done(function (tags) { dialog.setAvailableTags(tags); });
        this._loadKeys()
                .done(function (hostCertificates, clientCertificates, serverKeys) {
                          dialog.setSslCertificates(hostCertificates);
                          dialog.setSslKeys(serverKeys);
                          dialog.setSecureAuthenticationCertificates(clientCertificates);
                          dialog.setSecureAuthenticationKeys(serverKeys);
                          dialog.setRequestEncryptionCertificates(clientCertificates);
                          dialog.setRequestDecryptionKeys(serverKeys);
                          dialog.setRequestSigningKeys(serverKeys);
                          dialog.setRequestSignatureVerificationCertificates(clientCertificates);
                          dialog.setReceiptSigningKeys(serverKeys);
                          dialog.setReceiptSignatureVerificationCertificates(clientCertificates);
                      });
        return dialog;
    }
});

/** @class */
jscape.domain.EditOftpTradingPartnerController = jscape.domain.OftpTradingPartnerController.extend(
    /** @lends {jscape.domain.EditOftpTradingPartnerController.prototype} */
{
    /** @override */
    start: function(listener, managementService, domainName, partner) {
        this.partner = partner;
        return this._super(listener, managementService, domainName, partner.oftpData);
    },

    _setupDialog: function () {
        var dialog = new jscape.domain.EditOftpTradingPartnerDialog();
        var partner = this.partner;
        var oftpData = partner && partner.oftpData ? partner.oftpData : new jscape.OftpPartnerData();
        if (partner) {
            dialog.setName(partner.name);
            dialog.setCompany(partner.company);
            dialog.setEmail(partner.email);
            dialog.setHost(partner.host);
            dialog.setPort(partner.port);
            dialog.setTimeout(partner.timeout);
            dialog.setUsername(partner.username);
            dialog.setPassword(partner.password);
            dialog.setDestinationId(oftpData.destinationId);
            dialog.setCipher(oftpData.cipherSuite);
            dialog.setSslEnabled(oftpData.sslEnabled);
            dialog.setSecureAuthenticationEnabled(oftpData.secureAuthenticationEnabled);
            dialog.setUseCompression(oftpData.requestCompressionEnabled);
            dialog.setUseEncryption(oftpData.requestEncryptionEnabled);
            dialog.setUseSigning(oftpData.requestSigningEnabled);
            dialog.setReceiptSignatureRequired(oftpData.receiptSignatureRequired);
            dialog.setReceiptAutoGenerationAllowed(oftpData.automaticReceiptGenerationAllowed);
            dialog.setCertificateExchangeAllowed(oftpData.certificateExchangeAllowed);
            dialog.setRelayAllowed(oftpData.relayAllowed);
        }
        this.managementService.getDomainTags(this.domainName)
                .done(function (tags) {
                          dialog.setAvailableTags(tags);
                          partner && dialog.setTags(partner.tags);
                      });
        this._loadKeys()
                .done(function (hostCertificates, clientCertificates, serverKeys) {
                          dialog.setSslCertificates(hostCertificates);
                          dialog.setSslCertificate(oftpData.sslCertificateData.aliases);
                          dialog.setSslKeys(serverKeys);
                          dialog.setSslKey(oftpData.sslKeyAlias);
                          dialog.setSecureAuthenticationCertificates(clientCertificates);
                          dialog.setSecureAuthenticationCertificate(oftpData.authenticationCertificateData.aliases);
                          dialog.setSecureAuthenticationKeys(serverKeys);
                          dialog.setSecureAuthenticationKey(oftpData.authenticationKeyAliases);
                          dialog.setRequestEncryptionCertificates(clientCertificates);
                          dialog.setRequestEncryptionCertificate(oftpData.requestEncryptionCertificateData.aliases);
                          dialog.setRequestDecryptionKeys(serverKeys);
                          dialog.setRequestDecryptionKey(oftpData.requestDecryptionKeyAliases);
                          dialog.setRequestSigningKeys(serverKeys);
                          dialog.setRequestSigningKey(oftpData.requestSigningKeyAlias);
                          dialog.setRequestSignatureVerificationCertificates(clientCertificates);
                          dialog.setRequestSignatureVerificationCertificate(oftpData.requestSignatureVerificationCertificateData.aliases);
                          dialog.setReceiptSigningKeys(serverKeys);
                          dialog.setReceiptSigningKey(oftpData.receiptSigningKeyAlias);
                          dialog.setReceiptSignatureVerificationCertificates(clientCertificates);
                          dialog.setReceiptSignatureVerificationCertificate(oftpData.receiptSignatureVerificationCertificateData.aliases);
                          partner = null;
                          oftpData = null;
                      });
        return dialog;
    },

    _createPartner: function (dialog) {
        var partner = this._super(dialog);
        partner.name = this.partner.name;
        return partner;
    }
});


/** @class */
jscape.domain.OftpTradingPartnerSpecController = Class.extend(
    /** @lends {jscape.domain.OftpTradingPartnerSpecController.prototype} */
{
    deferred: null,

    start: function(data) {
        this.deferred = $.Deferred();
        this._setupDialog(data).show(this);
        return this.deferred.promise();
    },

    onSubmit: function(dialog) {
        var data = this._createData(dialog);
        dialog.destroy();
        this.deferred.resolve(data);
        this.deferred = null;
    },

    onCancel: function(dialog) {
        dialog.destroy();
        this.deferred.reject();
        this.deferred = null;
    },

    _createData: function(dialog) {
        return new jscape.CertificateDescriptor(dialog.getIssuer(),
                                                dialog.getSubject(),
                                                dialog.getKeyUsage(),
                                                dialog.getExtendedKeyUsage());
    },

    _setupDialog: function(data) {
        var dialog = new jscape.domain.OftpTradingPartnerSpecDialog();
        dialog.setIssuer(data.issuer);
        dialog.setSubject(data.subject);
        dialog.setKeyUsage(data.keyUsages);
        dialog.setExtendedKeyUsage(data.extendedKeyUsages);
        return dialog;
    }
});

/** @class */
jscape.domain.OftpTradingPartnerSpecDialog = Class.extend(
    /** @lends {jscape.domain.OftpTradingPartnerSpecDialog.prototype} */
{
    /** @constructor */
    initialize: function() {
        this.dialog = $("#d-partner-oftp-spec").clone().attr("id", "");
        this.dialog.dialog({
            width: 610, height: "auto",
            modal: true, resizable: false, closable: true, closed: true,
            buttons: [
                {text: window.R.string.DIALOG_BUTTON_OK || "Ok", handler: $.proxy(this._onSubmit, this)},
                {text: window.R.string.DIALOG_BUTTON_CANCEL || "Cancel", handler: $.proxy(this._onCancel, this)}
            ],
            onClose: $.proxy(function () {if (!this.closing) { this._onCancel(); }}, this)
        }).show();

        this.fieldset = $("fieldset[name=oftptradingpartnerspecfields]", this.dialog);

        this.issuer = $("input[name=issuer]", this.fieldset).textbox({width: "60%"});
        this.subject = $("input[name=subject]", this.fieldset).textbox({width: "60%"});
        this.keyUsage = $("select[name=keyusage]", this.fieldset).tagbox({limitToList: true, hasDownArrow: true, panelHeight: "auto", panelMaxHeight: 150, width: "60%"});
        this.extendedkeyUsage = $("select[name=extendedkeyusage]", this.fieldset).tagbox({limitToList: true, hasDownArrow: true, panelHeight: "auto", panelMaxHeight: 150, width: "60%"});
    },

    getIssuer: function() {
        return this.issuer.textbox("getValue");
    },

    setIssuer: function(value) {
        this.issuer.textbox("setValue", value);
    },

    getSubject: function() {
        return this.subject.textbox("getValue");
    },

    setSubject: function(value) {
        this.subject.textbox("setValue", value);
    },

    getKeyUsage: function() {
        return this.keyUsage.tagbox("getValues");
    },

    setKeyUsage: function(values) {
        this.keyUsage.tagbox("setValues", values);
    },

    getExtendedKeyUsage: function() {
        return this.extendedkeyUsage.tagbox("getValues");
    },

    setExtendedKeyUsage: function(values) {
        this.extendedkeyUsage.tagbox("setValues", values);
    },

    show: function (listener) {
        this.listener = listener;
        this.dialog.dialog("center").dialog("open");
        this.fieldset.form("validate");
        this.fieldset.find("input:first").focus();
    },

    hide: function () {
        if (!this._closed()) {
            this.closing = true;
            this.dialog.dialog("close");
            this.fieldset.form("disableValidation");
            this.closing = false;
        }
    },

    destroy: function() {
        this.dialog.dialog("destroy");
    },

    _onSubmit: function () {
        if (this.fieldset.form("validate")) {
            this.hide();
            this.listener.onSubmit(this);
        }
    },

    _onCancel: function () {
        this.hide();
        this.listener.onCancel(this);
    },

    _closed: function () {
        return !!this.dialog.dialog("options").closed;
    }
});

/** @class */
jscape.domain.OftpTradingPartnerDialog = jscape.domain.TradingPartnerDialog.extend(
    /** @lends {jscape.domain.OftpTradingPartnerDialog.prototype} */
{
    TIMEOUT_FACTOR: 1000,

    /** @constructor */
    initialize: function(dialog) {
        this._super(dialog);

        this.host = $("input[name=host]", this.fieldset).textbox({required: true, validType: "partner_host_nonempty", missingMessage: window.R.string.TRADING_PARTNERS_ERROR_BAD_HOST, width: "60%"});
        this.port = $("input[name=port]", this.fieldset).numberspinner({required: true, min: 1, max: 65535, width: 100});
        this.timeout = $("input[name=timeout]", this.fieldset).numberspinner({required: true, min: 1, max: 1000, increment: 10, width: 60});

        this.username = $("input[name=username]", this.fieldset).textbox({width: "60%"});
        this.password = $("input[name=password]", this.fieldset).textbox({type: "password", width: "60%"});

        this.sslCert = $("select[name=sslcert]", this.fieldset).combobox({multiple: true, panelHeight: "auto", panelMaxHeight: 150, width: "50%"});
        this.sslCertSpecButton = $("a[role=button][name=sslcertspecbutton]", this.fieldset).linkbutton({onClick: $.proxy(this._onClick$SslCertSpecButton, this)});
        this.sslKey = $("select[name=sslkey]", this.fieldset).combobox({multiple: false, panelHeight: "auto", panelMaxHeight: 150, width: "50%"});

        this.destinationId = $("input[name=destinationid]", this.fieldset).textbox({required: true, missingMessage: window.R.string.TRADING_PARTNERS_ERROR_BAD_RECIPIENT, width: "50%"});

        this.authCert = $("select[name=authcert]", this.fieldset).tagbox({limitToList: true, hasDownArrow: true, panelHeight: "auto", panelMaxHeight: 150, width: "50%"});
        this.authCertSpecButton = $("a[role=button][name=authcertspecbutton]", this.fieldset).linkbutton({onClick: $.proxy(this._onClick$AuthCertSpecButton, this)});
        this.authKey = $("select[name=authkey]", this.fieldset).tagbox({limitToList: true, hasDownArrow: true, panelHeight: "auto", panelMaxHeight: 150, width: "50%"});

        this.fileEncryptCert = $("select[name=fileencryptcert]", this.fieldset).tagbox({limitToList: true, hasDownArrow: true, panelHeight: "auto", panelMaxHeight: 150, width: "50%"});
        this.fileEncryptCertSpecButton = $("a[role=button][name=fileencryptcertspecbutton]", this.fieldset).linkbutton({onClick: $.proxy(this._onClick$FileEncryptCertSpecButton, this)});
        this.fileDecryptKey = $("select[name=filedecryptkey]", this.fieldset).tagbox({limitToList: true, hasDownArrow: true, panelHeight: "auto", panelMaxHeight: 150, width: "50%"});
        this.fileSignKey = $("select[name=filesignkey]", this.fieldset).combobox({multiple: false, panelHeight: "auto", panelMaxHeight: 150, width: "50%"});

        this.fileSignatureVerificationCert = $("select[name=filesignatureverificationcert]", this.fieldset).tagbox({limitToList: true, hasDownArrow: true, panelHeight: "auto", panelMaxHeight: 150, width: "50%"});
        this.fileSignatureVerificationCertSpecButton = $("a[role=button][name=filesignatureverificationcertspecbutton]", this.fieldset).linkbutton({onClick: $.proxy(this._onClick$FileSignatureVerificationCertSpecButton, this)});

        this.receiptSignKey = $("select[name=receiptsignkey]", this.fieldset).combobox({multiple: false, panelHeight: "auto", panelMaxHeight: 150, width: "50%"});

        this.receiptSignatureVerificationCert = $("select[name=receiptsignatureverificationcert]", this.fieldset).tagbox({limitToList: true, hasDownArrow: true, panelHeight: "auto", panelMaxHeight: 150, width: "50%"});
        this.receiptSignatureVerificationCertSpecButton = $("a[role=button][name=receiptsignatureverificationcertspecbutton]", this.fieldset).linkbutton({onClick: $.proxy(this._onClick$ReceiptSignatureVerificationCertSpecButton, this)});

        this.cipher = $("select[name=cipher]", this.fieldset).combobox({required: true, editable: false, width: "25%", panelHeight: "auto", panelMaxHeight: 150});

        this.sslEnabled = $("input[name=sslenabled]:checkbox", this.fieldset);
        this.secureAuth = $("input[name=secureauth]:checkbox", this.fieldset);
        this.useCompression = $("input[name=usecompression]:checkbox", this.fieldset);
        this.useEncryption = $("input[name=useencryption]:checkbox", this.fieldset);
        this.useSigning = $("input[name=usesigning]:checkbox", this.fieldset);
        this.receiptSignatureRequired = $("input[name=receiptsignaturerequire]:checkbox", this.fieldset);
        this.receiptAutoGenerationAllowed = $("input[name=receiptautogenerationallowed]:checkbox", this.fieldset);
        this.certificateExchangeAllowed = $("input[name=certexchangeallowed]:checkbox", this.fieldset);
        this.relayAllowed = $("input[name=relayallowed]:checkbox", this.fieldset);
    },

    getHost: function() {
        return this.host.textbox("getValue");
    },

    setHost: function(value) {
        this.host.textbox("setValue", value);
    },

    getPort: function() {
        return this.port.numberspinner("getValue");
    },

    setPort: function(value) {
        this.port.numberspinner("setValue", value);
    },

    getTimeout: function() {
        return this.timeout.numberspinner("getValue") * this.TIMEOUT_FACTOR;
    },

    setTimeout: function(value) {
        this.timeout.numberspinner("setValue", parseInt(value) / this.TIMEOUT_FACTOR);
    },

    getUsername: function() {
        return this.username.textbox("getValue");
    },

    setUsername: function(value) {
        this.username.textbox("setValue", value);
    },

    getPassword: function() {
        return this.password.textbox("getValue");
    },

    setPassword: function(value) {
        this.password.textbox("setValue", value);
    },

    getSslCertificate: function() {
        return this.sslCert.combobox("getValues");
    },

    setSslCertificate: function(value) {
        this.sslCert.combobox("setValues", value);
    },

    setSslCertificates: function(values) {
        this.sslCert.combobox("loadData", values);
    },

    getSslKey: function() {
        return this.sslKey.combobox("getValue");
    },

    setSslKey: function(value) {
        this.sslKey.combobox("setValue", value);
    },

    setSslKeys: function(values) {
        this.sslKey.combobox("loadData", values);
    },

    getDestinationId: function() {
        return this.destinationId.textbox("getValue");
    },

    setDestinationId: function(value) {
        this.destinationId.textbox("setValue", value);
    },

    getSecureAuthenticationCertificate: function() {
        return this.authCert.tagbox("getValues");
    },

    setSecureAuthenticationCertificate: function(value) {
        this.authCert.tagbox("setValues", value);
    },

    setSecureAuthenticationCertificates: function (values) {
        this.authCert.tagbox("loadData", values);
    },

    getSecureAuthenticationKey: function() {
        return this.authKey.tagbox("getValues");
    },

    setSecureAuthenticationKey: function(value) {
        this.authKey.tagbox("setValues", value);
    },

    setSecureAuthenticationKeys: function (values) {
        this.authKey.tagbox("loadData", values);
    },

    getRequestEncryptionCertificate: function() {
        return this.fileEncryptCert.tagbox("getValues");
    },

    setRequestEncryptionCertificate: function(value) {
        this.fileEncryptCert.tagbox("setValues", value);
    },

    setRequestEncryptionCertificates: function (values) {
        this.fileEncryptCert.tagbox("loadData", values);
    },

    getRequestDecryptionKey: function() {
        return this.fileDecryptKey.tagbox("getValues");
    },

    setRequestDecryptionKey: function(value) {
        this.fileDecryptKey.tagbox("setValues", value);
    },

    setRequestDecryptionKeys: function (values) {
        this.fileDecryptKey.tagbox("loadData", values);
    },

    getRequestSigningKey: function() {
        return this.fileSignKey.combobox("getValue");
    },

    setRequestSigningKey: function(value) {
        this.fileSignKey.combobox("setValue", value);
    },

    setRequestSigningKeys: function (values) {
        this.fileSignKey.combobox("loadData", values);
    },

    getRequestSignatureVerificationCertificate: function() {
        return this.fileSignatureVerificationCert.tagbox("getValues");
    },

    setRequestSignatureVerificationCertificate: function(value) {
        this.fileSignatureVerificationCert.tagbox("setValues", value);
    },

    setRequestSignatureVerificationCertificates: function (values) {
        this.fileSignatureVerificationCert.tagbox("loadData", values);
    },

    getReceiptSigningKey: function() {
        return this.receiptSignKey.combobox("getValue");
    },

    setReceiptSigningKey: function(value) {
        this.receiptSignKey.combobox("setValue", value);
    },

    setReceiptSigningKeys: function (values) {
        this.receiptSignKey.combobox("loadData", values);
    },

    getReceiptSignatureVerificationCertificate: function() {
        return this.receiptSignatureVerificationCert.tagbox("getValues");
    },

    setReceiptSignatureVerificationCertificate: function(value) {
        this.receiptSignatureVerificationCert.tagbox("setValues", value);
    },

    setReceiptSignatureVerificationCertificates: function (values) {
        this.receiptSignatureVerificationCert.tagbox("loadData", values);
    },

    getCipher: function() {
        return this.cipher.is(":disabled") ? null : this.cipher.combobox("getValue");
    },

    setCipher: function(value) {
        this.cipher.combobox("select", value);
    },

    isSslEnabled: function() {
        return this.sslEnabled.is(":checked");
    },

    setSslEnabled: function(value) {
        this.sslEnabled.prop("checked", !!value);
    },

    isSecureAuthenticationEnabled: function() {
        return this.secureAuth.is(":checked");
    },

    setSecureAuthenticationEnabled: function(value) {
        this.secureAuth.prop("checked", !!value).change();
    },

    isUseCompression: function() {
        return this.useCompression.is(":checked");
    },

    setUseCompression: function(value) {
        this.useCompression.prop("checked", !!value);
    },

    isUseEncryption: function() {
        return this.useEncryption.is(":checked");
    },

    setUseEncryption: function(value) {
        this.useEncryption.prop("checked", !!value).change();
    },

    isUseSigning: function() {
        return this.useSigning.is(":checked");
    },

    setUseSigning: function(value) {
        this.useSigning.prop("checked", !!value).change();
    },

    isReceiptSignatureRequired: function() {
        return this.receiptSignatureRequired.is(":checked");
    },

    setReceiptSignatureRequired: function(value) {
        this.receiptSignatureRequired.prop("checked", !!value).change();
    },

    isReceiptAutoGenerationAllowed: function() {
        return this.receiptAutoGenerationAllowed.is(":checked");
    },

    setReceiptAutoGenerationAllowed: function(value) {
        this.receiptAutoGenerationAllowed.prop("checked", !!value).change();
    },

    isCertificateExchangeAllowed: function() {
        return this.certificateExchangeAllowed.is(":checked");
    },

    setCertificateExchangeAllowed: function(value) {
        this.certificateExchangeAllowed.prop("checked", !!value);
    },

    isRelayAllowed: function() {
        return this.relayAllowed.is(":checked");
    },

    setRelayAllowed: function(value) {
        this.relayAllowed.prop("checked", !!value);
    },

    /** @override */
    show: function (listener) {
        this._super(listener || jscape.domain.OftpTradingPartnerDialog.LISTENER);
        return this;
    },

    _onClick$SslCertSpecButton: function() {
        this.listener.onSslCertificateSpec();
    },

    _onClick$AuthCertSpecButton: function() {
        this.listener.onAuthenticationCertificateSpec();
    },

    _onClick$FileEncryptCertSpecButton: function() {
        this.listener.onFileEncryptionCertSpec();
    },

    _onClick$FileSignatureVerificationCertSpecButton: function() {
        this.listener.onFileSignatureCertSpec();
    },

    _onClick$ReceiptSignatureVerificationCertSpecButton: function() {
        this.listener.onReceiptSignatureCertSpec();
    }
});
jscape.domain.OftpTradingPartnerDialog.LISTENER = $.extend({
    onSslCertificateSpec: $.noop,
    onAuthenticationCertificateSpec: $.noop,
    onFileEncryptionCertSpec: $.noop,
    onFileSignatureCertSpec: $.noop,
    onReceiptSignatureCertSpec: $.noop
}, jscape.domain.TradingPartnerDialog.LISTENER);

/** @class */
jscape.domain.AddOftpTradingPartnerDialog = jscape.domain.OftpTradingPartnerDialog.extend(
    /** @lends {jscape.domain.AddOftpTradingPartnerDialog.prototype} */
{
    /** @constructor */
    initialize: function() {
        this._super($("#d-partner-add-oftp"));

        this.name = $("input[name=name]", this.fieldset).textbox({
            required: true,
            validType: ["partner_name_nonempty", "partner_unique"],
            missingMessage: window.R.string.TRADING_PARTNERS_ERROR_BAD_NAME,
            width: "60%"
        });
    },

    getName: function() {
        return this.name.textbox("getValue");
    }
});

/** @class */
jscape.domain.EditOftpTradingPartnerDialog = jscape.domain.OftpTradingPartnerDialog.extend(
    /** @lends {jscape.domain.EditOftpTradingPartnerDialog.prototype} */
{
    /** @constructor */
    initialize: function() {
        this._super($("#d-partner-edit-oftp"));

        this.title = this.dialog.dialog("header").text() || "";
    },

    getName: function() {
        return this.name;
    },

    setName: function(value) {
        this.name = value;
        this.dialog.dialog("setTitle", this.title.supplant({0: value}));
    }
});

/** @class */
jscape.domain.AddSftpTradingPartnerController = jscape.domain.BaseTradingPartnerController.extend(
    /** @lends {jscape.domain.AddSftpTradingPartnerController.prototype} */
{
    DEFAULTS: {port: 22, timeout: 30 * 1000, tcpNoDelay: true},

    _setupDialog: function() {
        var dialog = new jscape.domain.AddSftpTradingPartnerDialog();
        dialog.setPort(this.DEFAULTS.port);
        dialog.setTimeout(this.DEFAULTS.timeout);
        dialog.setTcpNoDelay(this.DEFAULTS.tcpNoDelay);
        this.managementService.getDomainTags(this.domainName).done(function (tags) { dialog.setAvailableTags(tags); });
        this._loadHostKeys().done(function(keys) { dialog.setHostKeys(keys); });
        return dialog;
    },

    _createPartner: function(dialog) {
        return jscape.TradingPartner.sftp(dialog.getName(),
                                          dialog.getCompany(),
                                          dialog.getEmail(),
                                          dialog.getHost(),
                                          dialog.getPort(),
                                          dialog.getTimeout(),
                                          dialog.getTcpNoDelay(),
                                          dialog.getUsername(),
                                          dialog.getPassword(),
                                          this.clientKeyProvider,
                                          dialog.getHostKey() != null ? new jscape.ServerKeyProvider(dialog.getHostKey()) : null,
                                          dialog.isStartSubsystemReplyRequired(),
                                          dialog.getTags());
    }
});

/** @class */
jscape.domain.EditSftpTradingPartnerController = jscape.domain.BaseTradingPartnerController.extend(
    /** @lends {jscape.domain.EditSftpTradingPartnerController.prototype} */
{
    /** @override */
    start: function(listener, managementService, domainName, partner) {
        this.partner = partner;
        return this._super(listener, managementService, domainName, partner.keyProvider);
    },

    _setupDialog: function () {
        var dialog = new jscape.domain.EditSftpTradingPartnerDialog();
        var partner = this.partner;
        if (partner) {
            dialog.setName(partner.name);
            dialog.setCompany(partner.company);
            dialog.setEmail(partner.email);
            dialog.setHost(partner.host);
            dialog.setPort(partner.port);
            dialog.setTimeout(partner.timeout);
            dialog.setTcpNoDelay(partner.tcpNoDelayEnabled);
            dialog.setUsername(partner.username);
            dialog.setPassword(partner.password);
            dialog.setStartSubsystemReplyRequired(partner.sftpStartSubsystemReplyRequired);
        }
        this.managementService.getDomainTags(this.domainName)
                .done(function (tags) {
                          dialog.setAvailableTags(tags);
                          partner && dialog.setTags(partner.tags);
                      });
        this._loadHostKeys()
                .done(function (keys) {
                          dialog.setHostKeys(keys);
                          partner && dialog.setHostKey(partner.hostKeyProvider ? partner.hostKeyProvider.keyAlias : null);
                      });
        return dialog;
    },

    _createPartner: function (dialog) {
        return jscape.TradingPartner.sftp(this.partner.name,
                                          dialog.getCompany(),
                                          dialog.getEmail(),
                                          dialog.getHost(),
                                          dialog.getPort(),
                                          dialog.getTimeout(),
                                          dialog.getTcpNoDelay(),
                                          dialog.getUsername(),
                                          dialog.getPassword(),
                                          this.clientKeyProvider,
                                          dialog.getHostKey() != null ? new jscape.ServerKeyProvider(dialog.getHostKey()) : null,
                                          dialog.isStartSubsystemReplyRequired(),
                                          dialog.getTags());
    }
});

/** @class */
jscape.domain.SftpTradingPartnerDialog = jscape.domain.TradingPartnerDialog.extend(
    /** @lends {jscape.domain.SftpTradingPartnerDialog.prototype} */
{
    TIMEOUT_FACTOR: 1000,

    /** @constructor */
    initialize: function(dialog) {
        this._super(dialog);

        this.host = $("input[name=host]", this.fieldset).textbox({required: true, validType: "partner_host_nonempty", missingMessage: window.R.string.TRADING_PARTNERS_ERROR_BAD_HOST, width: "60%"});
        this.port = $("input[name=port]", this.fieldset).numberspinner({required: true, min: 1, max: 65535, width: 100});
        this.timeout = $("input[name=timeout]", this.fieldset).numberspinner({required: true, min: 1, max: 60, width: 60});
        this.tcpNoDelay = $("input[name=tcpnodelay]:checkbox", this.fieldset);

        this.username = $("input[name=username]", this.fieldset).textbox({width: "50%"});
        this.password = $("input[name=password]", this.fieldset).textbox({type: "password", width: "50%"});

        this.useHostKey = $("input[name=usehostkey]:checkbox", this.fieldset).prop("disabled", true);
        this.useHostKey.change($.proxy(function() {
            this.hostKey.combobox(this.useHostKey.is(":checked") ? "enable" : "disable");
        }, this));
        this.hostKey = $("select[name=hostkey]", this.fieldset);
        this.hostKey.combobox({editable: false, disabled: true, width: 170, panelHeight: "auto", panelMaxHeight: 150, onLoadSuccess: $.proxy(function(data) {
            this.useHostKey.prop("disabled", data.length == 0);
            if (data.length != 0) {
                this.hostKey.combobox("select", data[0].value);
            }
        }, this)});

        this.clientKeyButton = $("a[role=button][name=selectclientkey]", this.fieldset).linkbutton({onClick: $.proxy(this._onClick$ClientKeyButton, this)});

        this.startSubsystemReply = $("input[name=startsubsystemreply]:checkbox", this.fieldset);
    },

    getHost: function() {
        return this.host.textbox("getValue");
    },

    setHost: function(value) {
        this.host.textbox("setValue", value);
    },

    getPort: function() {
        return this.port.numberspinner("getValue");
    },

    setPort: function(value) {
        this.port.numberspinner("setValue", value);
    },

    getTimeout: function() {
        return this.timeout.numberspinner("getValue") * this.TIMEOUT_FACTOR;
    },

    setTimeout: function(value) {
        this.timeout.numberspinner("setValue", parseInt(value) / this.TIMEOUT_FACTOR);
    },

    getTcpNoDelay: function() {
        return this.tcpNoDelay.is(":checked");
    },

    setTcpNoDelay: function(value) {
        this.tcpNoDelay.prop("checked", !!value).change();
    },

    getUsername: function() {
        return this.username.textbox("getValue");
    },

    setUsername: function(value) {
        this.username.textbox("setValue", value);
    },

    getPassword: function() {
        return this.password.textbox("getValue");
    },

    setPassword: function(value) {
        this.password.textbox("setValue", value);
    },

    getHostKey: function() {
        return this.useHostKey.is(":checked") ? this.hostKey.combobox("getValue") : null;
    },

    setHostKey: function(value) {
        this.useHostKey.prop("checked", value != null).change();
        if (value != null) {
            this.hostKey.combobox("setValue", value);
        }
    },

    setHostKeys: function(values) {
        this.hostKey.combobox("loadData", values);
    },

    isStartSubsystemReplyRequired: function() {
        return this.startSubsystemReply.is(":checked");
    },

    setStartSubsystemReplyRequired: function(value) {
        this.startSubsystemReply.prop("checked", !!value);
    },

    /** @override */
    show: function (listener) {
        return this._super(listener || jscape.domain.SftpTradingPartnerDialog.LISTENER);
    },

    _onClick$ClientKeyButton: function() {
        this.listener.onSelectClientKey();
    }
});
jscape.domain.SftpTradingPartnerDialog.LISTENER = $.extend({
    onSelectClientKey: $.noop
}, jscape.domain.TradingPartnerDialog.LISTENER);

/** @class */
jscape.domain.AddSftpTradingPartnerDialog = jscape.domain.SftpTradingPartnerDialog.extend(
    /** @lends {jscape.domain.AddSftpTradingPartnerDialog.prototype} */
{
    /** @constructor */
    initialize: function() {
        this._super($("#d-partner-add-sftp"));

        this.name = $("input[name=name]", this.fieldset).textbox({
            required: true,
            validType: ["partner_name_nonempty", "partner_unique"],
            missingMessage: window.R.string.TRADING_PARTNERS_ERROR_BAD_NAME,
            width: "60%"
        });
    },

    getName: function() {
        return this.name.textbox("getValue");
    }
});

/** @class */
jscape.domain.EditSftpTradingPartnerDialog = jscape.domain.SftpTradingPartnerDialog.extend(
    /** @lends {jscape.domain.EditSftpTradingPartnerDialog.prototype} */
{
    /** @constructor */
    initialize: function() {
        this._super($("#d-partner-edit-sftp"));

        this.title = this.dialog.dialog("header").text() || "";
    },

    setName: function(value) {
        this.dialog.dialog("setTitle", this.title.supplant({0: value}));
    }
});

/** @class */
jscape.domain.AddWebDavTradingPartnerController = jscape.domain.BaseTradingPartnerController.extend(
    /** @lends {jscape.domain.AddWebDavTradingPartnerController.prototype} */
{
    /** @const */
    DEFAULT_TIMEOUT: 30 * 1000,

    _setupDialog: function() {
        var dialog = new jscape.domain.AddWebDavTradingPartnerDialog();
        dialog.setTimeout(this.DEFAULT_TIMEOUT);
        this.managementService.getDomainTags(this.domainName).done(function (tags) { dialog.setAvailableTags(tags); });
        this._loadHostKeys().done(function(keys) { dialog.setHostKeys(keys); });
        return dialog;
    },

    _createPartner: function(dialog) {
        return jscape.TradingPartner.webdav(dialog.getName(),
                                            dialog.getCompany(),
                                            dialog.getEmail(),
                                            dialog.getUrl(),
                                            dialog.getTimeout(),
                                            dialog.getUsername(),
                                            dialog.getPassword(),
                                            dialog.getDomain(),
                                            this.clientKeyProvider,
                                            dialog.getHostKey() != null ? new jscape.ServerKeyProvider(dialog.getHostKey()) : null,
                                            dialog.getTags());
    }
});

/** @class */
jscape.domain.EditWebDavTradingPartnerController = jscape.domain.BaseTradingPartnerController.extend(
    /** @lends {jscape.domain.EditWebDavTradingPartnerController.prototype} */
{
    /** @override */
    start: function(listener, managementService, domainName, partner) {
        this.partner = partner;
        return this._super(listener, managementService, domainName, partner.keyProvider);
    },

    _setupDialog: function () {
        var dialog = new jscape.domain.EditWebDavTradingPartnerDialog();
        var partner = this.partner;
        if (partner) {
            dialog.setName(partner.name);
            dialog.setCompany(partner.company);
            dialog.setEmail(partner.email);
            dialog.setUrl(partner.url);
            dialog.setTimeout(partner.timeout);
            dialog.setUsername(partner.username);
            dialog.setPassword(partner.password);
            dialog.setDomain(partner.domain);
        }
        this.managementService.getDomainTags(this.domainName)
                .done(function (tags) {
                          dialog.setAvailableTags(tags);
                          partner && dialog.setTags(partner.tags);
                      });
        this._loadHostKeys()
                .done(function (keys) {
                          dialog.setHostKeys(keys);
                          partner && dialog.setHostKey(partner.hostKeyProvider ? partner.hostKeyProvider.keyAlias : null);
                      });
        return dialog;
    },

    _createPartner: function (dialog) {
        return jscape.TradingPartner.webdav(this.partner.name,
                                            dialog.getCompany(),
                                            dialog.getEmail(),
                                            dialog.getUrl(),
                                            dialog.getTimeout(),
                                            dialog.getUsername(),
                                            dialog.getPassword(),
                                            dialog.getDomain(),
                                            this.clientKeyProvider,
                                            dialog.getHostKey() != null ? new jscape.ServerKeyProvider(dialog.getHostKey()) : null,
                                            dialog.getTags());
    }
});

/** @class */
jscape.domain.WebDavTradingPartnerDialog = jscape.domain.TradingPartnerDialog.extend(
    /** @lends {jscape.domain.WebDavTradingPartnerDialog.prototype} */
{
    TIMEOUT_FACTOR: 1000,

    /** @constructor */
    initialize: function(dialog) {
        this._super(dialog);

        this.url = $("input[name=url]", this.fieldset).textbox({required: true, validType: "partner_url", missingMessage: window.R.string.TRADING_PARTNERS_ERROR_BAD_URL, width: "60%"});
        this.timeout = $("input[name=timeout]", this.fieldset).numberspinner({required: true, min: 1, max: 60, width: 60});

        this.username = $("input[name=username]", this.fieldset).textbox({width: "50%"});
        this.password = $("input[name=password]", this.fieldset).textbox({type: "password", width: "50%"});
        this.domain = $("input[name=domain]", this.fieldset).textbox({width: "50%"});

        this.useHostKey = $("input[name=usehostkey]:checkbox", this.fieldset).prop("disabled", true);
        this.useHostKey.change($.proxy(function() {
            this.hostKey.combobox(this.useHostKey.is(":checked") ? "enable" : "disable");
        }, this));
        this.hostKey = $("select[name=hostkey]", this.fieldset);
        this.hostKey.combobox({editable: false, disabled: true, width: 170, panelHeight: "auto", panelMaxHeight: 150, onLoadSuccess: $.proxy(function(data) {
            this.useHostKey.prop("disabled", data.length == 0);
            if (data.length != 0) {
                this.hostKey.combobox("select", data[0].value);
            }
        }, this)});

        this.clientKeyButton = $("a[role=button][name=selectclientkey]", this.fieldset).linkbutton({onClick: $.proxy(this._onClick$ClientKeyButton, this)});
    },

    getUrl: function() {
        return this.url.textbox("getValue");
    },

    setUrl: function(value) {
        this.url.textbox("setValue", value);
    },

    getTimeout: function() {
        return this.timeout.numberspinner("getValue") * this.TIMEOUT_FACTOR;
    },

    setTimeout: function(value) {
        this.timeout.numberspinner("setValue", parseInt(value) / this.TIMEOUT_FACTOR);
    },

    getUsername: function() {
        return this.username.textbox("getValue");
    },

    setUsername: function(value) {
        this.username.textbox("setValue", value);
    },

    getPassword: function() {
        return this.password.textbox("getValue");
    },

    setPassword: function(value) {
        this.password.textbox("setValue", value);
    },

    getDomain: function() {
        return this.domain.textbox("getValue");
    },

    setDomain: function(value) {
        this.domain.textbox("setValue", value);
    },

    getHostKey: function() {
        return this.useHostKey.is(":checked") ? this.hostKey.combobox("getValue") : null;
    },

    setHostKey: function(value) {
        this.useHostKey.prop("checked", value != null).change();
        if (value != null) {
            this.hostKey.combobox("setValue", value);
        }
    },

    setHostKeys: function(values) {
        this.hostKey.combobox("loadData", values);
    },

    /** @override */
    show: function (listener) {
        return this._super(listener || jscape.domain.WebDavTradingPartnerDialog.LISTENER);
    },

    _onClick$ClientKeyButton: function() {
        this.listener.onSelectClientKey();
    }
});
jscape.domain.WebDavTradingPartnerDialog.LISTENER = $.extend({
    onSelectClientKey: $.noop
}, jscape.domain.TradingPartnerDialog.LISTENER);

/** @class */
jscape.domain.AddWebDavTradingPartnerDialog = jscape.domain.WebDavTradingPartnerDialog.extend(
    /** @lends {jscape.domain.AddWebDavTradingPartnerDialog.prototype} */
{
    /** @constructor */
    initialize: function() {
        this._super($("#d-partner-add-webdav"));

        this.name = $("input[name=name]", this.fieldset).textbox({
            required: true,
            validType: ["partner_name_nonempty", "partner_unique"],
            missingMessage: window.R.string.TRADING_PARTNERS_ERROR_BAD_NAME,
            width: "60%"
        });
    },

    getName: function() {
        return this.name.textbox("getValue");
    }
});

/** @class */
jscape.domain.EditWebDavTradingPartnerDialog = jscape.domain.WebDavTradingPartnerDialog.extend(
    /** @lends {jscape.domain.EditWebDavTradingPartnerDialog.prototype} */
{
    /** @constructor */
    initialize: function() {
        this._super($("#d-partner-edit-webdav"));

        this.title = this.dialog.dialog("header").text() || "";
    },

    setName: function(value) {
        this.dialog.dialog("setTitle", this.title.supplant({0: value}));
    }
});

/** @class */
jscape.domain.AddRestTradingPartnerController = jscape.domain.BaseTradingPartnerController.extend(
    /** @lends {jscape.domain.AddRestTradingPartnerController.prototype} */
{
    /** @const */
    DEFAULT_PORT: 80,
    DEFAULT_TIMEOUT: 30 * 1000,

    _setupDialog: function() {
        var dialog = new jscape.domain.AddRestTradingPartnerDialog();
        dialog.setPort(this.DEFAULT_PORT);
        dialog.setTimeout(this.DEFAULT_TIMEOUT);
        this.managementService.getDomainTags(this.domainName).done(function (tags) { dialog.setAvailableTags(tags); });
        this._loadHostKeys().done(function(keys) { dialog.setHostKeys(keys); });
        return dialog;
    },

    _createPartner: function(dialog) {
        return jscape.TradingPartner.rest(dialog.getName(),
                                          dialog.getCompany(),
                                          dialog.getEmail(),
                                          dialog.getHost(),
                                          dialog.getPort(),
                                          dialog.getTimeout(),
                                          dialog.getUsername(),
                                          dialog.getPassword(),
                                          dialog.getDomain(),
                                          this.clientKeyProvider,
                                          dialog.getHostKey() != null ? new jscape.ServerKeyProvider(dialog.getHostKey()) : null,
                                          dialog.isUseSsl(),
                                          dialog.getTags());
    }
});

/** @class */
jscape.domain.EditRestTradingPartnerController = jscape.domain.BaseTradingPartnerController.extend(
    /** @lends {jscape.domain.EditRestTradingPartnerController.prototype} */
{
    /** @override */
    start: function(listener, managementService, domainName, partner) {
        this.partner = partner;
        return this._super(listener, managementService, domainName, partner.keyProvider);
    },

    _setupDialog: function () {
        var dialog = new jscape.domain.EditRestTradingPartnerDialog();
        var partner = this.partner;
        if (partner) {
            dialog.setName(partner.name);
            dialog.setCompany(partner.company);
            dialog.setEmail(partner.email);
            dialog.setHost(partner.host);
            dialog.setPort(partner.port);
            dialog.setTimeout(partner.timeout);
            dialog.setUsername(partner.username);
            dialog.setPassword(partner.password);
            dialog.setDomain(partner.domain);
            dialog.setUseSsl(partner.encryptionRequired);
        }
        this.managementService.getDomainTags(this.domainName)
                .done(function (tags) {
                          dialog.setAvailableTags(tags);
                          partner && dialog.setTags(partner.tags);
                      });
        this._loadHostKeys()
                .done(function (keys) {
                          dialog.setHostKeys(keys);
                          partner && dialog.setHostKey(partner.hostKeyProvider ? partner.hostKeyProvider.keyAlias : null);
                      });
        return dialog;
    },

    _createPartner: function (dialog) {
        return jscape.TradingPartner.rest(this.partner.name,
                                          dialog.getCompany(),
                                          dialog.getEmail(),
                                          dialog.getHost(),
                                          dialog.getPort(),
                                          dialog.getTimeout(),
                                          dialog.getUsername(),
                                          dialog.getPassword(),
                                          dialog.getDomain(),
                                          this.clientKeyProvider,
                                          dialog.getHostKey() != null ? new jscape.ServerKeyProvider(dialog.getHostKey()) : null,
                                          dialog.isUseSsl(),
                                          dialog.getTags());
    }
});

/** @class */
jscape.domain.RestTradingPartnerDialog = jscape.domain.TradingPartnerDialog.extend(
    /** @lends {jscape.domain.RestTradingPartnerDialog.prototype} */
{
    TIMEOUT_FACTOR: 1000,

    /** @constructor */
    initialize: function(dialog) {
        this._super(dialog);

        this.host = $("input[name=host]", this.fieldset).textbox({required: true, validType: "partner_host_nonempty", missingMessage: window.R.string.TRADING_PARTNERS_ERROR_BAD_HOST, width: "60%"});
        this.port = $("input[name=port]", this.fieldset).numberspinner({required: true, min: 1, max: 65535, width: 100});
        this.timeout = $("input[name=timeout]", this.fieldset).numberspinner({required: true, min: 1, max: 60, width: 60});
        this.useSsl = $("input[name=ssl]:checkbox", this.fieldset);

        this.username = $("input[name=username]", this.fieldset).textbox({width: "50%"});
        this.password = $("input[name=password]", this.fieldset).textbox({type: "password", width: "50%"});
        this.domain = $("input[name=domain]", this.fieldset).textbox({required: true, width: "50%"});

        this.useHostKey = $("input[name=usehostkey]:checkbox", this.fieldset).prop("disabled", true);
        this.useHostKey.change($.proxy(function() {
            this.hostKey.combobox(this.useHostKey.is(":checked") ? "enable" : "disable");
        }, this));
        this.hostKey = $("select[name=hostkey]", this.fieldset);
        this.hostKey.combobox({editable: false, disabled: true, width: 170, panelHeight: "auto", panelMaxHeight: 150, onLoadSuccess: $.proxy(function(data) {
            this.useHostKey.prop("disabled", data.length == 0);
            if (data.length != 0) {
                this.hostKey.combobox("select", data[0].value);
            }
        }, this)});

        this.clientKeyButton = $("a[role=button][name=selectclientkey]", this.fieldset).linkbutton({onClick: $.proxy(this._onClick$ClientKeyButton, this)});
    },

    getHost: function() {
        return this.host.textbox("getValue");
    },

    setHost: function(value) {
        this.host.textbox("setValue", value);
    },

    getPort: function() {
        return parseInt(this.port.numberspinner("getValue"));
    },

    setPort: function(value) {
        this.port.numberspinner("setValue", parseInt(value)).numberspinner("validate");
    },

    getTimeout: function() {
        return this.timeout.numberspinner("getValue") * this.TIMEOUT_FACTOR;
    },

    setTimeout: function(value) {
        this.timeout.numberspinner("setValue", parseInt(value) / this.TIMEOUT_FACTOR);
    },

    isUseSsl: function() {
        return this.useSsl.is(":checked");
    },

    setUseSsl: function(value) {
        this.useSsl.prop("checked", !!value);
    },

    getUsername: function() {
        return this.username.textbox("getValue");
    },

    setUsername: function(value) {
        this.username.textbox("setValue", value);
    },

    getPassword: function() {
        return this.password.textbox("getValue");
    },

    setPassword: function(value) {
        this.password.textbox("setValue", value);
    },

    getDomain: function() {
        return this.domain.textbox("getValue");
    },

    setDomain: function(value) {
        this.domain.textbox("setValue", value);
    },

    getHostKey: function() {
        return this.useHostKey.is(":checked") ? this.hostKey.combobox("getValue") : null;
    },

    setHostKey: function(value) {
        this.useHostKey.prop("checked", value != null).change();
        if (value != null) {
            this.hostKey.combobox("setValue", value);
        }
    },

    setHostKeys: function(values) {
        this.hostKey.combobox("loadData", values);
    },

    /** @override */
    show: function (listener) {
        return this._super(listener || jscape.domain.RestTradingPartnerDialog.LISTENER);
    },

    _onClick$ClientKeyButton: function() {
        this.listener.onSelectClientKey();
    }
});
jscape.domain.RestTradingPartnerDialog.LISTENER = $.extend({
    onSelectClientKey: $.noop
}, jscape.domain.TradingPartnerDialog.LISTENER);

/** @class */
jscape.domain.AddRestTradingPartnerDialog = jscape.domain.RestTradingPartnerDialog.extend(
    /** @lends {jscape.domain.AddRestTradingPartnerDialog.prototype} */
{
    /** @constructor */
    initialize: function() {
        this._super($("#d-partner-add-rest"));

        this.name = $("input[name=name]", this.fieldset).textbox({
            required: true,
            validType: ["partner_name_nonempty", "partner_unique"],
            missingMessage: window.R.string.TRADING_PARTNERS_ERROR_BAD_NAME,
            width: "60%"
        });
    },

    getName: function() {
        return this.name.textbox("getValue");
    }
});

/** @class */
jscape.domain.EditRestTradingPartnerDialog = jscape.domain.RestTradingPartnerDialog.extend(
    /** @lends {jscape.domain.EditRestTradingPartnerDialog.prototype} */
{
    /** @constructor */
    initialize: function() {
        this._super($("#d-partner-edit-rest"));

        this.title = this.dialog.dialog("header").text() || "";
    },

    setName: function(value) {
        this.dialog.dialog("setTitle", this.title.supplant({0: value}));
    }
});

/** @class */
jscape.domain.AddTftpTradingPartnerController = jscape.domain.BaseTradingPartnerController.extend(
    /** @lends {jscape.domain.AddTftpTradingPartnerController.prototype} */
{
    /** @const */
    DEFAULT_PORT: 69,
    DEFAULT_INTERVAL: 3 * 1000,
    DEFAULT_ATTEMPTS: 6,

    _setupDialog: function() {
        var dialog = new jscape.domain.AddTftpTradingPartnerDialog();
        dialog.setPort(this.DEFAULT_PORT);
        dialog.setRetransmitInterval(this.DEFAULT_INTERVAL);
        dialog.setMaxRetransmitAttempts(this.DEFAULT_ATTEMPTS);
        this.managementService.getDomainTags(this.domainName).done(function (tags) { dialog.setAvailableTags(tags); });
        return dialog;
    },

    _createPartner: function(dialog) {
        return jscape.TradingPartner.tftp(dialog.getName(),
                                          dialog.getCompany(),
                                          dialog.getEmail(),
                                          dialog.getHost(),
                                          dialog.getPort(),
                                          dialog.getRetransmitInterval(),
                                          /* dialog.getMaxRetransmitAttempts(), */
                                          dialog.getTags());
    }
});

/** @class */
jscape.domain.EditTftpTradingPartnerController = jscape.domain.BaseTradingPartnerController.extend(
    /** @lends {jscape.domain.EditTftpTradingPartnerController.prototype} */
{
    /** @override */
    start: function(listener, managementService, domainName, partner) {
        this.partner = partner;
        return this._super(listener, managementService, domainName);
    },

    _setupDialog: function () {
        var dialog = new jscape.domain.EditTftpTradingPartnerDialog();
        var partner = this.partner;
        if (partner) {
            dialog.setName(partner.name);
            dialog.setCompany(partner.company);
            dialog.setEmail(partner.email);
            dialog.setHost(partner.host);
            dialog.setPort(partner.port);
            dialog.setRetransmitInterval(partner.timeout);
            dialog.setMaxRetransmitAttempts(6/*partner.maxRetransmitAttempts*/);
        }
        this.managementService.getDomainTags(this.domainName)
                .done(function (tags) {
                          dialog.setAvailableTags(tags);
                          partner && dialog.setTags(partner.tags);
                      });
        return dialog;
    },

    _createPartner: function (dialog) {
        return jscape.TradingPartner.tftp(this.partner.name,
                                          dialog.getCompany(),
                                          dialog.getEmail(),
                                          dialog.getHost(),
                                          dialog.getPort(),
                                          dialog.getRetransmitInterval(),
                                          /* dialog.getMaxRetransmitAttempts(),*/
                                          dialog.getTags());
    }
});

/** @class */
jscape.domain.TftpTradingPartnerDialog = jscape.domain.TradingPartnerDialog.extend(
    /** @lends {jscape.domain.TftpTradingPartnerDialog.prototype} */
{
    TIME_FACTOR: 1000,

    /** @constructor */
    initialize: function(dialog) {
        this._super(dialog);

        this.host = $("input[name=host]", this.fieldset).textbox({required: true, validType: "partner_host_nonempty", missingMessage: window.R.string.TRADING_PARTNERS_ERROR_BAD_HOST, width: "60%"});
        this.port = $("input[name=port]", this.fieldset).numberspinner({required: true, min: 1, max: 65535, width: 100});

        this.retransmitInterval = $("input[name=retransmitinterval]", this.fieldset).numberspinner({required: true, min: 1, max: 255, width: 60});
        this.retransmitAttempts = $("input[name=retransmitattempts]", this.fieldset).numberspinner({required: true, min: 1, max: 100, width: 60});
    },

    getHost: function() {
        return this.host.textbox("getValue");
    },

    setHost: function(value) {
        this.host.textbox("setValue", value);
    },

    getPort: function() {
        return parseInt(this.port.numberspinner("getValue"));
    },

    setPort: function(value) {
        this.port.numberspinner("setValue", parseInt(value)).numberspinner("validate");
    },

    getRetransmitInterval: function() {
        return parseInt(this.retransmitInterval.numberspinner("getValue")) * this.TIME_FACTOR;
    },

    setRetransmitInterval: function(value) {
        this.retransmitInterval.numberspinner("setValue", parseInt(value) / this.TIME_FACTOR).numberspinner("validate");
    },

    getMaxRetransmitAttempts: function() {
        return parseInt(this.retransmitAttempts.numberspinner("getValue"));
    },

    setMaxRetransmitAttempts: function(value) {
        this.retransmitAttempts.numberspinner("setValue", parseInt(value)).numberspinner("validate");
    }
});

/** @class */
jscape.domain.AddTftpTradingPartnerDialog = jscape.domain.TftpTradingPartnerDialog.extend(
    /** @lends {jscape.domain.AddTftpTradingPartnerDialog.prototype} */
{
    /** @constructor */
    initialize: function() {
        this._super($("#d-partner-add-tftp"));

        this.name = $("input[name=name]", this.fieldset).textbox({
            required: true,
            validType: ["partner_name_nonempty", "partner_unique"],
            missingMessage: window.R.string.TRADING_PARTNERS_ERROR_BAD_NAME,
            width: "60%"
        });
    },

    getName: function() {
        return this.name.textbox("getValue");
    }
});

/** @class */
jscape.domain.EditTftpTradingPartnerDialog = jscape.domain.TftpTradingPartnerDialog.extend(
    /** @lends {jscape.domain.EditTftpTradingPartnerDialog.prototype} */
{
    /** @constructor */
    initialize: function() {
        this._super($("#d-partner-edit-tftp"));

        this.title = this.dialog.dialog("header").text() || "";
    },

    setName: function(value) {
        this.dialog.dialog("setTitle", this.title.supplant({0: value}));
    }
});

/** @class */
jscape.domain.AddImapTradingPartnerController = jscape.domain.BaseTradingPartnerController.extend(
    /** @lends {jscape.domain.AddImapTradingPartnerController.prototype} */
{
    /** @const */
    DEFAULT_PORT: 143,
    DEFAULT_TIMEOUT: 30 * 1000,

    _setupDialog: function() {
        var dialog = new jscape.domain.AddImapTradingPartnerDialog();
        dialog.setPort(this.DEFAULT_PORT);
        dialog.setTimeout(this.DEFAULT_TIMEOUT);
        this.managementService.getDomainTags(this.domainName).done(function (tags) { dialog.setAvailableTags(tags); });
        this._loadHostKeys().done(function(keys) { dialog.setHostKeys(keys); });
        return dialog;
    },

    _createPartner: function(dialog) {
        var hostKeyProvider = dialog.getHostKey() != null ? new jscape.ServerKeyProvider(dialog.getHostKey()) : null;
        return jscape.TradingPartner.imap(dialog.getName(),
                                          dialog.getCompany(),
                                          dialog.getEmail(),
                                          dialog.getHost(),
                                          dialog.getPort(),
                                          dialog.getTimeout(),
                                          dialog.getConnectionType(),
                                          dialog.getUsername(),
                                          dialog.getPassword(),
                                          this.clientKeyProvider,
                                          hostKeyProvider,
                                          dialog.getTags());
    }
});

/** @class */
jscape.domain.EditImapTradingPartnerController = jscape.domain.BaseTradingPartnerController.extend(
    /** @lends {jscape.domain.EditImapTradingPartnerController.prototype} */
{
    /** @override */
    start: function(listener, managementService, domainName, partner) {
        this.partner = partner;
        return this._super(listener, managementService, domainName, partner.keyProvider);
    },

    _setupDialog: function () {
        var dialog = new jscape.domain.EditImapTradingPartnerDialog();
        var partner = this.partner;
        if (partner) {
            dialog.setName(partner.name);
            dialog.setCompany(partner.company);
            dialog.setEmail(partner.email);
            dialog.setHost(partner.host);
            dialog.setPort(partner.port);
            dialog.setTimeout(partner.timeout);
            dialog.setConnectionType(partner.connectionType);
            dialog.setUsername(partner.username);
            dialog.setPassword(partner.password);
        }
        this.managementService.getDomainTags(this.domainName)
                .done(function (tags) {
                          dialog.setAvailableTags(tags);
                          partner && dialog.setTags(partner.tags);
                      });
        this._loadHostKeys()
                .done(function (keys) {
                          dialog.setHostKeys(keys);
                          partner && dialog.setHostKey(partner.hostKeyProvider ? partner.hostKeyProvider.keyAlias : null);
                      });
        return dialog;
    },

    _createPartner: function (dialog) {
        var hostKeyProvider = dialog.getHostKey() != null ? new jscape.ServerKeyProvider(dialog.getHostKey()) : null;
        return jscape.TradingPartner.imap(this.partner.name,
                                          dialog.getCompany(),
                                          dialog.getEmail(),
                                          dialog.getHost(),
                                          dialog.getPort(),
                                          dialog.getTimeout(),
                                          dialog.getConnectionType(),
                                          dialog.getUsername(),
                                          dialog.getPassword(),
                                          this.clientKeyProvider,
                                          hostKeyProvider,
                                          dialog.getTags());
    }
});

/** @class */
jscape.domain.AddPop3TradingPartnerController = jscape.domain.BaseTradingPartnerController.extend(
    /** @lends {jscape.domain.AddPop3TradingPartnerController.prototype} */
{
    /** @const */
    DEFAULT_PORT: 110,
    DEFAULT_TIMEOUT: 30 * 1000,

    _setupDialog: function() {
        var dialog = new jscape.domain.AddPop3TradingPartnerDialog();
        dialog.setPort(this.DEFAULT_PORT);
        dialog.setTimeout(this.DEFAULT_TIMEOUT);
        this.managementService.getDomainTags(this.domainName).done(function (tags) { dialog.setAvailableTags(tags); });
        this._loadHostKeys().done(function(keys) { dialog.setHostKeys(keys); });
        return dialog;
    },

    _createPartner: function(dialog) {
        var hostKeyProvider = dialog.getHostKey() != null ? new jscape.ServerKeyProvider(dialog.getHostKey()) : null;
        return jscape.TradingPartner.pop3(dialog.getName(),
                                          dialog.getCompany(),
                                          dialog.getEmail(),
                                          dialog.getHost(),
                                          dialog.getPort(),
                                          dialog.getTimeout(),
                                          dialog.getConnectionType(),
                                          dialog.getUsername(),
                                          dialog.getPassword(),
                                          this.clientKeyProvider,
                                          hostKeyProvider,
                                          dialog.getTags());
    }
});

/** @class */
jscape.domain.EditPop3TradingPartnerController = jscape.domain.BaseTradingPartnerController.extend(
    /** @lends {jscape.domain.EditPop3TradingPartnerController.prototype} */
{
    /** @override */
    start: function(listener, managementService, domainName, partner) {
        this.partner = partner;
        return this._super(listener, managementService, domainName, partner.keyProvider);
    },

    _setupDialog: function () {
        var dialog = new jscape.domain.EditPop3TradingPartnerDialog();
        var partner = this.partner;
        if (partner) {
            dialog.setName(partner.name);
            dialog.setCompany(partner.company);
            dialog.setEmail(partner.email);
            dialog.setHost(partner.host);
            dialog.setPort(partner.port);
            dialog.setTimeout(partner.timeout);
            dialog.setConnectionType(partner.connectionType);
            dialog.setUsername(partner.username);
            dialog.setPassword(partner.password);
        }
        this.managementService.getDomainTags(this.domainName)
                .done(function (tags) {
                          dialog.setAvailableTags(tags);
                          partner && dialog.setTags(partner.tags);
                      });
        this._loadHostKeys()
                .done(function (keys) {
                          dialog.setHostKeys(keys);
                          partner && dialog.setHostKey(partner.hostKeyProvider ? partner.hostKeyProvider.keyAlias : null);
                      });
        return dialog;
    },

    _createPartner: function (dialog) {
        var hostKeyProvider = dialog.getHostKey() != null ? new jscape.ServerKeyProvider(dialog.getHostKey()) : null;
        return jscape.TradingPartner.pop3(this.partner.name,
                                          dialog.getCompany(),
                                          dialog.getEmail(),
                                          dialog.getHost(),
                                          dialog.getPort(),
                                          dialog.getTimeout(),
                                          dialog.getConnectionType(),
                                          dialog.getUsername(),
                                          dialog.getPassword(),
                                          this.clientKeyProvider,
                                          hostKeyProvider,
                                          dialog.getTags());
    }
});

/** @class */
jscape.domain.AddSmtpTradingPartnerController = jscape.domain.BaseTradingPartnerController.extend(
    /** @lends {jscape.domain.AddSmtpTradingPartnerController.prototype} */
{
    /** @const */
    DEFAULT_PORT: 25,
    DEFAULT_TIMEOUT: 30 * 1000,

    _setupDialog: function() {
        var dialog = new jscape.domain.AddSmtpTradingPartnerDialog();
        dialog.setPort(this.DEFAULT_PORT);
        dialog.setTimeout(this.DEFAULT_TIMEOUT);
        this.managementService.getDomainTags(this.domainName).done(function (tags) { dialog.setAvailableTags(tags); });
        this._loadHostKeys().done(function(keys) { dialog.setHostKeys(keys); });
        return dialog;
    },

    _createPartner: function(dialog) {
        var hostKeyProvider = dialog.getHostKey() != null ? new jscape.ServerKeyProvider(dialog.getHostKey()) : null;
        return jscape.TradingPartner.smtp(dialog.getName(),
                                          dialog.getCompany(),
                                          dialog.getEmail(),
                                          dialog.getHost(),
                                          dialog.getPort(),
                                          dialog.getTimeout(),
                                          dialog.getConnectionType(),
                                          dialog.getUsername(),
                                          dialog.getPassword(),
                                          this.clientKeyProvider,
                                          hostKeyProvider,
                                          dialog.getTags());
    }
});

/** @class */
jscape.domain.EditSmtpTradingPartnerController = jscape.domain.BaseTradingPartnerController.extend(
    /** @lends {jscape.domain.EditSmtpTradingPartnerController.prototype} */
{
    /** @override */
    start: function(listener, managementService, domainName, partner) {
        this.partner = partner;
        return this._super(listener, managementService, domainName, partner.keyProvider);
    },

    _setupDialog: function () {
        var dialog = new jscape.domain.EditSmtpTradingPartnerDialog();
        var partner = this.partner;
        if (partner) {
            dialog.setName(partner.name);
            dialog.setCompany(partner.company);
            dialog.setEmail(partner.email);
            dialog.setHost(partner.host);
            dialog.setPort(partner.port);
            dialog.setTimeout(partner.timeout);
            dialog.setConnectionType(partner.connectionType);
            dialog.setUsername(partner.username);
            dialog.setPassword(partner.password);
        }
        this.managementService.getDomainTags(this.domainName)
                .done(function (tags) {
                          dialog.setAvailableTags(tags);
                          partner && dialog.setTags(partner.tags);
                      });
        this._loadHostKeys()
                .done(function (keys) {
                          dialog.setHostKeys(keys);
                          partner && dialog.setHostKey(partner.hostKeyProvider ? partner.hostKeyProvider.keyAlias : null);
                      });
        return dialog;
    },

    _createPartner: function (dialog) {
        var hostKeyProvider = dialog.getHostKey() != null ? new jscape.ServerKeyProvider(dialog.getHostKey()) : null;
        return jscape.TradingPartner.smtp(this.partner.name,
                                          dialog.getCompany(),
                                          dialog.getEmail(),
                                          dialog.getHost(),
                                          dialog.getPort(),
                                          dialog.getTimeout(),
                                          dialog.getConnectionType(),
                                          dialog.getUsername(),
                                          dialog.getPassword(),
                                          this.clientKeyProvider,
                                          hostKeyProvider,
                                          dialog.getTags());
    }
});

/** @class */
jscape.domain.MailAccessTradingPartnerDialog = jscape.domain.TradingPartnerDialog.extend(
    /** @lends {jscape.domain.MailAccessTradingPartnerDialog.prototype} */
{
    TIMEOUT_FACTOR: 1000,

    /** @constructor */
    initialize: function(dialog) {
        this._super(dialog);

        this.host = $("input[name=host]", this.fieldset).textbox({required: true, validType: "partner_host_nonempty", missingMessage: window.R.string.TRADING_PARTNERS_ERROR_BAD_HOST, width: "60%"});
        this.port = $("input[name=port]", this.fieldset).numberspinner({required: true, min: 1, max: 65535, width: 100});
        this.timeout = $("input[name=timeout]", this.fieldset).numberspinner({required: true, min: 1, max: 60, width: 60});
        this.connectionType = $("select[name=connectiontype]", this.fieldset).combobox({required: true, editable: false, width: 120, panelHeight: "auto", panelMaxHeight: 150});

        this.username = $("input[name=username]", this.fieldset).textbox({width: "50%"});
        this.password = $("input[name=password]", this.fieldset).textbox({type: "password", width: "50%"});

        this.useHostKey = $("input[name=usehostkey]:checkbox", this.fieldset).prop("disabled", true);
        this.useHostKey.change($.proxy(function() {
            this.hostKey.combobox(this.useHostKey.is(":checked") ? "enable" : "disable");
        }, this));
        this.hostKey = $("select[name=hostkey]", this.fieldset);
        this.hostKey.combobox({editable: false, disabled: true, width: 170, panelHeight: "auto", panelMaxHeight: 150, onLoadSuccess: $.proxy(function(data) {
            this.useHostKey.prop("disabled", data.length == 0);
            if (data.length != 0) {
                this.hostKey.combobox("setValue", data[0].value);
            }
        }, this)});

        this.clientKeyButton = $("a[role=button][name=selectclientkey]", this.fieldset).linkbutton({onClick: $.proxy(this._onClick$ClientKeyButton, this)});
    },

    getHost: function() {
        return this.host.textbox("getValue");
    },

    setHost: function(value) {
        this.host.textbox("setValue", value);
    },

    getPort: function() {
        return parseInt(this.port.numberspinner("getValue"));
    },

    setPort: function(value) {
        this.port.numberspinner("setValue", parseInt(value)).numberspinner("validate");
    },

    getTimeout: function() {
        return this.timeout.numberspinner("getValue") * this.TIMEOUT_FACTOR;
    },

    setTimeout: function(value) {
        this.timeout.numberspinner("setValue", parseInt(value) / this.TIMEOUT_FACTOR);
    },

    getConnectionType: function() {
        return this.connectionType.combobox("getValue");
    },

    setConnectionType: function(value) {
        this.connectionType.combobox("select", value).combobox("validate");
    },

    getUsername: function() {
        return this.username.textbox("getValue");
    },

    setUsername: function(value) {
        this.username.textbox("setValue", value);
    },

    getPassword: function() {
        return this.password.textbox("getValue");
    },

    setPassword: function(value) {
        this.password.textbox("setValue", value);
    },

    getHostKey: function() {
        return this.useHostKey.is(":checked") ? this.hostKey.combobox("getValue") : null;
    },

    setHostKey: function(value) {
        this.useHostKey.prop("checked", value != null).change();
        if (value != null) {
            this.hostKey.combobox("setValue", value);
        }
    },

    setHostKeys: function(values) {
        this.hostKey.combobox("loadData", values);
    },

    /** @override */
    show: function(listener) {
        return this._super(listener || jscape.domain.MailAccessTradingPartnerDialog.LISTENER);
    },

    _onClick$ClientKeyButton: function() {
        this.listener.onSelectClientKey();
    }
});
jscape.domain.MailAccessTradingPartnerDialog.LISTENER = $.extend({
    onSelectClientKey: $.noop
}, jscape.domain.TradingPartnerDialog.LISTENER);

/** @class */
jscape.domain.AddImapTradingPartnerDialog = jscape.domain.MailAccessTradingPartnerDialog.extend(
    /** @lends {jscape.domain.AddImapTradingPartnerDialog.prototype} */
{
    /** @constructor */
    initialize: function() {
        this._super($("#d-partner-add-imap"));

        this.name = $("input[name=name]", this.fieldset).textbox({
            required: true,
            validType: ["partner_name_nonempty", "partner_unique"],
            missingMessage: window.R.string.TRADING_PARTNERS_ERROR_BAD_NAME,
            width: "60%"
        });
    },

    getName: function() {
        return this.name.textbox("getValue");
    }
});

/** @class */
jscape.domain.EditImapTradingPartnerDialog = jscape.domain.MailAccessTradingPartnerDialog.extend(
    /** @lends {jscape.domain.EditImapTradingPartnerDialog.prototype} */
{
    /** @constructor */
    initialize: function() {
        this._super($("#d-partner-edit-imap"));

        this.title = this.dialog.dialog("header").text() || "";
    },

    setName: function(value) {
        this.dialog.dialog("setTitle", this.title.supplant({0: value}));
    }
});

/** @class */
jscape.domain.AddPop3TradingPartnerDialog = jscape.domain.MailAccessTradingPartnerDialog.extend(
    /** @lends {jscape.domain.AddPop3TradingPartnerDialog.prototype} */
{
    /** @constructor */
    initialize: function() {
        this._super($("#d-partner-add-pop3"));

        this.name = $("input[name=name]", this.fieldset).textbox({
            required: true,
            validType: ["partner_name_nonempty", "partner_unique"],
            missingMessage: window.R.string.TRADING_PARTNERS_ERROR_BAD_NAME,
            width: "60%"
        });
    },

    getName: function() {
        return this.name.textbox("getValue");
    }
});

/** @class */
jscape.domain.EditPop3TradingPartnerDialog = jscape.domain.MailAccessTradingPartnerDialog.extend(
    /** @lends {jscape.domain.EditPop3TradingPartnerDialog.prototype} */
{
    /** @constructor */
    initialize: function() {
        this._super($("#d-partner-edit-pop3"));

        this.title = this.dialog.dialog("header").text() || "";
    },

    setName: function(value) {
        this.dialog.dialog("setTitle", this.title.supplant({0: value}));
    }
});

/** @class */
jscape.domain.AddSmtpTradingPartnerDialog = jscape.domain.MailAccessTradingPartnerDialog.extend(
    /** @lends {jscape.domain.AddSmtpTradingPartnerDialog.prototype} */
{
    /** @constructor */
    initialize: function() {
        this._super($("#d-partner-add-smtp"));

        this.name = $("input[name=name]", this.fieldset).textbox({
            required: true,
            validType: ["partner_name_nonempty", "partner_unique"],
            missingMessage: window.R.string.TRADING_PARTNERS_ERROR_BAD_NAME,
            width: "60%"
        });
    },

    getName: function() {
        return this.name.textbox("getValue");
    }
});

/** @class */
jscape.domain.EditSmtpTradingPartnerDialog = jscape.domain.MailAccessTradingPartnerDialog.extend(
    /** @lends {jscape.domain.EditSmtpTradingPartnerDialog.prototype} */
{
    /** @constructor */
    initialize: function() {
        this._super($("#d-partner-edit-smtp"));

        this.title = this.dialog.dialog("header").text() || "";
    },

    setName: function(value) {
        this.dialog.dialog("setTitle", this.title.supplant({0: value}));
    }
});

/** @class */
jscape.domain.AddSmbTradingPartnerController = jscape.domain.BaseTradingPartnerController.extend(
    /** @lends {jscape.domain.AddSmbTradingPartnerController.prototype} */
{
    /** @const */
    DEFAULT_PORT: 445,
    DEFAULT_TIMEOUT: 30 * 1000,

    _setupDialog: function() {
        var dialog = new jscape.domain.AddSmbTradingPartnerDialog();
        dialog.setPort(this.DEFAULT_PORT);
        dialog.setTimeout(this.DEFAULT_TIMEOUT);
        this.managementService.getDomainTags(this.domainName).done(function (tags) { dialog.setAvailableTags(tags); });
        return dialog;
    },

    _createPartner: function(dialog) {
        return jscape.TradingPartner.smb(dialog.getName(),
                                         dialog.getCompany(),
                                         dialog.getEmail(),
                                         dialog.getHost(),
                                         dialog.getPort(),
                                         dialog.getTimeout(),
                                         dialog.getUsername(),
                                         dialog.getPassword(),
                                         dialog.getDomain(),
                                         dialog.getTags());
    }
});

/** @class */
jscape.domain.EditSmbTradingPartnerController = jscape.domain.BaseTradingPartnerController.extend(
    /** @lends {jscape.domain.EditSmbTradingPartnerController.prototype} */
{
    /** @override */
    start: function(listener, managementService, domainName, partner) {
        this.partner = partner;
        return this._super(listener, managementService, domainName, partner.keyProvider);
    },

    _setupDialog: function () {
        var dialog = new jscape.domain.EditSmbTradingPartnerDialog();
        var partner = this.partner;
        if (partner) {
            dialog.setName(partner.name);
            dialog.setCompany(partner.company);
            dialog.setEmail(partner.email);
            dialog.setHost(partner.host);
            dialog.setPort(partner.port);
            dialog.setTimeout(partner.timeout);
            dialog.setUsername(partner.username);
            dialog.setPassword(partner.password);
            dialog.setDomain(partner.domain);
        }
        this.managementService.getDomainTags(this.domainName)
                .done(function (tags) {
                          dialog.setAvailableTags(tags);
                          partner && dialog.setTags(partner.tags);
                      });
        return dialog;
    },

    _createPartner: function (dialog) {
        return jscape.TradingPartner.smb(this.partner.name,
                                         dialog.getCompany(),
                                         dialog.getEmail(),
                                         dialog.getHost(),
                                         dialog.getPort(),
                                         dialog.getTimeout(),
                                         dialog.getUsername(),
                                         dialog.getPassword(),
                                         dialog.getDomain(),
                                         dialog.getTags());
    }
});

/** @class */
jscape.domain.SmbTradingPartnerDialog = jscape.domain.TradingPartnerDialog.extend(
    /** @lends {jscape.domain.SmbTradingPartnerDialog.prototype} */
{
    TIMEOUT_FACTOR: 1000,

    /** @constructor */
    initialize: function(dialog) {
        this._super(dialog);

        this.host = $("input[name=host]", this.fieldset).textbox({required: true, validType: "partner_host_nonempty", missingMessage: window.R.string.TRADING_PARTNERS_ERROR_BAD_HOST, width: "60%"});
        this.port = $("input[name=port]", this.fieldset).numberspinner({required: true, min: 1, max: 65535, width: 100});
        this.timeout = $("input[name=timeout]", this.fieldset).numberspinner({required: true, min: 1, max: 60, width: 60});

        this.username = $("input[name=username]", this.fieldset).textbox({required: true, width: "50%"});
        this.password = $("input[name=password]", this.fieldset).textbox({type: "password", width: "50%"});
        this.domain = $("input[name=domain]", this.fieldset).textbox({width: "50%"});
    },

    getHost: function() {
        return this.host.textbox("getValue");
    },

    setHost: function(value) {
        this.host.textbox("setValue", value);
    },

    getPort: function() {
        return this.port.numberspinner("getValue");
    },

    setPort: function(value) {
        this.port.numberspinner("setValue", value);
    },

    getTimeout: function() {
        return this.timeout.numberspinner("getValue") * this.TIMEOUT_FACTOR;
    },

    setTimeout: function(value) {
        this.timeout.numberspinner("setValue", parseInt(value) / this.TIMEOUT_FACTOR).numberspinner("validate");
    },

    getUsername: function() {
        return this.username.textbox("getValue");
    },

    setUsername: function(value) {
        this.username.textbox("setValue", value);
    },

    getPassword: function() {
        return this.password.textbox("getValue");
    },

    setPassword: function(value) {
        this.password.textbox("setValue", value);
    },

    getDomain: function() {
        return this.domain.textbox("getValue");
    },

    setDomain: function(value) {
        this.domain.textbox("setValue", value);
    }
});

/** @class */
jscape.domain.AddSmbTradingPartnerDialog = jscape.domain.SmbTradingPartnerDialog.extend(
    /** @lends {jscape.domain.AddSmbTradingPartnerDialog.prototype} */
{
    /** @constructor */
    initialize: function() {
        this._super($("#d-partner-add-smb"));

        this.name = $("input[name=name]", this.fieldset).textbox({
            required: true,
            validType: ["partner_name_nonempty", "partner_unique"],
            missingMessage: window.R.string.TRADING_PARTNERS_ERROR_BAD_NAME,
            width: "60%"
        });
    },

    getName: function() {
        return this.name.textbox("getValue");
    }
});

/** @class */
jscape.domain.EditSmbTradingPartnerDialog = jscape.domain.SmbTradingPartnerDialog.extend(
    /** @lends {jscape.domain.EditSmbTradingPartnerDialog.prototype} */
{
    /** @constructor */
    initialize: function() {
        this._super($("#d-partner-edit-smb"));

        this.title = this.dialog.dialog("header").text() || "";
    },

    setName: function(value) {
        this.dialog.dialog("setTitle", this.title.supplant({0: value}));
    }
});