'use strict';

Ox.SelectInput = function(options, self) {

    var that;
    self = Ox.extend(self || {}, {
        options: Ox.extend({
            inputWidth: 128,
            items: [],
            label: '',
            labelWidth: 128,
            max: 1,
            min: 1,
            placeholder: '',
            title: '',
            value: options.max == 1 ? '' : [],
            width: 384
        }, options)
    });

    self.other = self.options.items[self.options.items.length - 1].id;
    self.otherWidth = self.options.width - self.options.inputWidth - 3; // fixme: 3? obscure!

    self.$select = Ox.Select({
            items: self.options.items,
            label: self.options.label,
            labelWidth: self.options.labelWidth,
            max: self.options.max,
            min: self.options.min,
            title: self.options.title,
            value: self.options.value,
            width: self.options.width
        })
        .bindEvent({
            change: function(data) {
                if (self.options.title) {
                    self.$select.options({
                        title: Ox.getObjectById(self.options.items, data.value).title
                    });
                }
                if (data.value != self.other) {
                    self.$select.options({width: self.options.width})
                        .removeClass('OxOverlapRight')
                    self.$input.hide();
                    self.options.value = data.value
                } else {
                    self.$select.options({width: self.otherWidth})
                        .addClass('OxOverlapRight');
                    self.$input.show().focusInput(true);
                    self.options.value = self.$input.value();
                }
            }
        });

    self.$input = Ox.Input({
            placeholder: self.options.placeholder,
            width: 0
        })
        .bindEvent({
            change: function(data) {
                self.options.value = data.value;
            }
        })
        .hide();

    that = Ox.FormElementGroup({
        elements: [
            self.$select,
            self.$input
        ],
        join: function(value) {
            return value[value[0] == self.other ? 1 : 0]
        },
        split: function(value) {
            return Ox.map(self.options.items, function(item, i) {
                return i < item.length - 1 ? item.id : null;
            }).indexOf(value) > -1 ? [value, ''] : [self.other, value];
        },
        width: self.options.width
    });

    self.setOption = function(key, value) {
        // ...
    };

    return that;

};