// vim: et:ts=4:sw=4:sts=4:ft=js
/*@
Ox.ColorInput <f:Ox.InputGroup> ColorInput Element
    () ->              <f> ColorInput Element
    (options) ->       <f> ColorInput Element
    (options, self) -> <f> ColorInput Element
    options <o> Options object
        id <s> element id
        value <s|0, 0, 0> rgb value
    self <o>    Shared private variable
@*/
Ox.ColorInput = function(options, self) {

    var self = $.extend(self || {}, {
            options: $.extend({
                id: '',
                value: '0, 0, 0'
            }, options)
        }),
        that;

    self.values = self.options.value.split(', ');
    self.$inputs = [];
    ['red', 'green', 'blue'].forEach(function(v, i) {
        self.$inputs[i] = new Ox.Input({
            id: v,
            max: 255,
            type: 'integer',
            value: self.values[i],
            width: 36
        })
        .bindEvent('autovalidate', change);
    });
    self.$inputs[3] = new Ox.Label({
            id: 'color',
            width: 36
        })
        .css({
            background: 'rgb(' + self.options.value + ')'
        });
    self.$inputs[4] = new Ox.ColorPicker({
            id: 'picker'
        })
        .bindEvent('change', function(event, data) {
            //Ox.print('change function called');
            self.options.value = data.value;
            self.values = data.value.split(', ');
            Ox.range(3).forEach(function(i) {
                self.$inputs[i].options({
                    value: self.values[i]
                });
            });
        })
        .options({
            width: 16 // this is just a hack to make the InputGroup layout work
        });

    that = new Ox.InputGroup({
            id: self.options.id,
            inputs: self.$inputs,
            separators: [
                {title: ',', width: 8},
                {title: ',', width: 8},
                {title: '', width: 8},
                {title: '', width: 8}
            ],
            value: self.options.value // fixme: it'd be nicer if this would be taken care of by passing self
        }, self)
        .bindEvent('change', change);

    function change() {
        self.options.value = $.map(self.$inputs, function(v, i) {
            return v.options('value');
        }).join(', ');
        self.$inputs[3].css({
            background: 'rgb(' + self.options.value + ')'
        });
    }

    return that;

};
