﻿function _formatNumber(v, noDecimals) {
    if (noDecimals === true) {
        v = Math.round(v);
    }
    v = (Math.round((v - 0) * 100)) / 100;
    v = (v === Math.floor(v)) ? v + (noDecimals ? "" : ".00") : ((v * 10 === Math.floor(v * 10)) ? v + "0" : v);
    v = String(v);
    var ps = v.split('.');
    var whole = ps[0];
    var sub = ps[1] ? ',' + ps[1] : (noDecimals ? '' : ',00');
    var r = /(\d+)(\d{3})/;
    while (r.test(whole)) {
        whole = whole.replace(r, '$1' + ' ' + '$2');
    }
    v = whole + sub;
    if (v.charAt(0) === '-') {
        return '-' + v.substr(1);
    }
    return v;
}

function _onMuchLessClick(e, mStepAmount) {
    var input = $(e.parent()).children(":input");
    var value = _parseInt(input.val());
    value = value - mStepAmount;
    if (value < 0) {
        value = 0;
    }
    input.val(_formatNumber(value, true));
}

function _onLessClick(e, stepAmount) {
    var input = $(e.parent()).children(":input");
    var value = _parseInt(input.val());
    value = value - stepAmount;
    if (value < 0) {
        value = 0;
    }
    input.val(_formatNumber(value, true));
}

function _onMuchMoreClick(e, mStepAmount) {
    var input = $(e.parent()).children(":input");
    var value = _parseInt(input.val());
    value = value + mStepAmount;
    if (value < 0) {
        value = 0;
    }
    input.val(_formatNumber(value, true));
}

function _onMoreClick(e, stepAmount) {
    var input = $(e.parent()).children(":input");
    var value = _parseInt(input.val());
    value = value + stepAmount;
    if (value < 0) {
        value = 0;
    }
    input.val(_formatNumber(value, true));
}
        
function _parseInt(value) {
    return parseInt(value.replace(/[a-zA-Z]*\s*/g, ''));
}

function _onInputKeyUp(input) {
    var value = _parseInt(input.val());

    if (value.toString() == 'NaN') {
        input.value = '';
    } else if (e.keyCode >= 48 || e.keyCode == 8 || e.keyCode == 46) {
        input.val(_formatNumber(value, true));
    }
}

