﻿$CS.ctrls.stepper = function (c) {
    c.cType = "stepper";
    c.btns = $G.Append(c.obj, $G.Tag("div", "arrows fr"));

    c.inp = $G.Append(c.obj, $G.Tag("input", "input", { type: "text" }));

    c.limitUp = Number(c.obj.limitUp || $G.GetAttribute(c.obj, "limitUp"));
    c.limitDown = Number(c.obj.limitDown || $G.GetAttribute(c.obj, "limitDown"));
    c.step = Number(c.obj.step || $G.GetAttribute(c.obj, "step"));

    c.comment = (c.obj.comment || $G.GetAttribute(c.obj, "comment")); // текст рядом с инпутом

    c.up = $G.Append(c.btns, $G.Tag("a", "up db", { href: "javascript://;", title: "Увеличить количество" }));
    c.down = $G.Append(c.btns, $G.Tag("a", "down db", { href: "javascript://;", title: "Уменьшить количество" }));
    c.change = function () {
        if (this.onChange)
            this.onChange();
    } .bind(c);
    c.doUp = function () {
        var val = this.getValue();
        if (val + this.step > this.limitUp)
            return;
        this.setValue(val + this.step);
    } .bind(c);
    c.doDown = function () {
        var val = this.getValue();
        if (val - this.step < this.limitDown)
            return;
        this.setValue(val - this.step);
    } .bind(c);
    $G.Event.Add(c.up, "click", c.doUp);
    $G.Event.Add(c.down, "click", c.doDown);

    $G.Event.Add(c.inp, "keypress", function (e) {
        var key = $G.Event.KeyCode(e);
        if (key == 38) {
            c.doUp();
            $G.Event.Stop(e);
        }
        if (key == 40) {
            c.doDown();
            $G.Event.Stop(e);
        }
        if ((key < 48 || key > 57) & (![8, 35, 36, 37, 38, 39, 40].contains(key))) { $G.Event.Stop(e); }
    })

    $G.Event.Add(c.inp, "keyup", function (e) {
        var key = $G.Event.KeyCode(e);
        if (key == 38) {
            c.doUp();
            $G.Event.Stop(e);
        }
        if (key == 40) {
            c.doDown();
            $G.Event.Stop(e);
        }
        if ((key < 48 || key > 57) & (key != 8)) { $G.Event.Stop(e); }
    } .bind(c))

    $G.Event.Add(c.inp, "change", function (e) {
        var val = this.getValue();
        if (/^[0-9]+$/gi.test(val)) {
            if (val > c.limitUp) { this.set(c.limitUp, true); }
            if (this.value < c.limitDown) { this.set(c.limitDown, true); }
            if (this.value == "") { this.set("0", true); }
            this.change();
        } else {
            this.value = c.limitDown;
        }
    } .bind(c))

    c.getValue = function () {
        return Number(this.inp.value);
    } .bind(c);
    c.setValue = function (val, nochange) {
        this.inp.value = val.toString();
        if (!nochange)
            this.change();
    } .bind(c);
    c.set = c.setValue;

    c.setValue(c.obj.value || $G.GetAttribute(c.obj, "value"));
}
