// vim: et:ts=4:sw=4:sts=4:ft=javascript
'use strict';
/*@
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) {

    self = Ox.extend(self || {}, {
            options: Ox.extend({
                id: '',
                mode: 'RGB',
                value: options.mode == 'HSL' ? [0, 1, 0.5] : [0, 0, 0]
            }, options)
    });
    var that;

    self.$inputs = [];
    Ox.loop(3, function(i) {
        self.$inputs[i] = Ox.Input({
            id: self.options.id + i,
            max: self.options.mode == 'RGB' ? 255 : i == 0 ? 360 : 1,
            type: self.options.mode == 'RGB' || i == 0 ? 'int' : 'float',
            value: self.options.value[i],
            width: 40
        })
        .bindEvent('autovalidate', change);
    });
    self.$inputs[3] = Ox.Label({
            id: 'color',
            width: 40
        })
        .css({
            background: 'rgb(' + getRGB().join(', ') + ')'
        });
    self.$inputs[4] = Ox.ColorPicker({
            id: 'picker',
            mode: self.options.mode
        })
        .bindEvent({
            change: function(data) {
                //Ox.Log('Form', 'change function called');
                self.options.value = data.value;
                Ox.loop(3, function(i) {
                    self.$inputs[i].value(self.options.value[i]);
                });
                self.$inputs[3].css({
                    background: 'rgb(' + getRGB().join(', ') + ')'
                });
            }
        })
        .options({
            width: 16 // this is just a hack to make the InputGroup layout work
        });

    that = 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
        })
        .bindEvent('change', change);

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

    function getRGB() {
        return self.options.mode == 'RGB'
            ? self.options.value
            : Ox.rgb(self.options.value).map(function(value) {
                return Math.round(value);
            });
    }

    return that;

};
