﻿
function AllowOnlyDigits(
    ctrl_id, /*no comments)) */
    def_val, /*set the default value when clear all unnecessary chars*/
    rem_leads_zeros, /*T - remove all leads 0*/
    hit_enter_btn /*if T - then procced action for DefaultButton property*/
) {

    $("#" + ctrl_id).keypress(function(e) {
    
        if (hit_enter_btn && hit_enter_btn == "F") { }
        else {
            var ev = event ? event : window.event;
            if (e.keyCode == 13) return;
            else ev.cancelBubble = true;
        }

        if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) {
            return false;
        }

        if ((e.shiftKey && e.keyCode == 45)) {
            return false;
        }

        return true;
    });

    $("#" + ctrl_id).focusout(function() {
        var val = $(this).val();
        var res = "";
        for (var i = 0; i < val.length; i++) {
            if (!isNaN(val.charAt(i)) && val.charAt(i) != " ") {
                res = res + '' + val.charAt(i);
            }
        }


        if (res.length > 0) {
            if (res == "0") res = "1";

            if (rem_leads_zeros == 'F')
                res = res;
            else {
                res = RemLeadsZero(res);
                if (res == "0" || res == '') res = "1";
            }
            $(this).val(res.replace(" ", ""));
        }
        else {
            if (def_val != "")
                $(this).val(def_val);
            else
                $(this).val("");
        }
    });
    return true;
}

function RemLeadsZero(str_t) {
    var res = "";
    for (var i = 0; i < str_t.length; i++) {
        if (str_t.charAt(i) == '0' && res.length == 0) { } else {
            res += str_t.charAt(i);
        }
    }

    return res;
}

function CheckNumber(ctrl_id, msg) {
    var val = $("#" + ctrl_id).val();
    var re = new RegExp("^[0-9]*$");
    if (!val.match(re)) {
        alert(msg);
        return false;
    }
    return true;
}    
