if (typeof(trinary) == 'undefined') { var trinary = {}; };
if (typeof(trinary.coder) == 'undefined') { trinary.coder = {}; };

trinary.RadixCoder = {
    binary : {
        encode : function(value) { return value.toString(2); },
        decode : function(value) { return parseInt(value,2)||0; }
    },
    trinary : {
        encode : function(value) { return trinary.core.decimalToTrinary(value); },
        decode : function (value) { return trinary.core.trinaryToDecimal(value)||0; }
    },
    octonary : {
        encode  : function(value) { return value.toString(8); },
        decode : function (value) { return parseInt(value,8)||0; }
    },
    nonary : {
        encode : function(value) { return trinary.core.trinaryToNonary(trinary.core.decimalToTrinary(value), 'lat'); },
        decode : function (value) { return trinary.core.trinaryToDecimal(trinary.core.nonaryToTrinary(value))||0; }
    },
    decimal : {
        encode : function(value) { return value; },
        decode : function (value) { return parseInt(value)||0; }
    },
    hexadecimal : {
        encode : function(value) { return value.toString(16); },
        decode : function (value) { return parseInt(value,16)||0; }
    }
};

trinary.coder.Translator = function(fields, reset) {
    this.bindFields(fields);
    if (reset) { this.bindReset(reset); };
};
trinary.coder.Translator.prototype = {
    bindFields : function(fields) {
        this.fields = fields;
        for (var i in fields) {
            var field = fields[i];
            this.bindField(field);
        };
    },
    bindField : function(field) {
        var self = this;
        field.input.keyup(function() {
            self.setValue($(this).val(), field.radix);
        });
    },
    bindReset : function(reset) {
        var self = this;
        reset.click(function() { for (var i in self.fields) { self.fields[i].input.val(''); }});
    },
    setValue : function(value, fromRadix) {
        var decimal = trinary.RadixCoder[fromRadix].decode(value);
        for (var i in this.fields) {
            var field = this.fields[i];
            if (fromRadix != field.radix) {
                field.input.val(trinary.RadixCoder[field.radix].encode(decimal));
            };
        }
    }
};