/**
 * Created by vlade on 12/15/14.
 */
/**
 * Validating numerics inputs
 */
function NumericValidate(elemet, example){
    var reg = new RegExp("^([0-9])*$");

    if(elemet.value != "" && !reg.test(elemet.value))
    {
        alert("You must put a numeric value here.\nExample: " + example);
        elemet.value = elemet.value.substr(0,elemet.value.length-1);
    }
}

function validate_N(elemet){
    var regex = /^\d+$/;
    if(!regex.test($(elemet).val())){
        $(elemet).parent().addClass("has-error");
        $(elemet).bind('blur', function(event){
            var sanitized = $(event.target).val();
            sanitized = sanitized.replace(/[^\d+]/gi, "");
            $(event.target).parent().removeClass("has-error");
            $(event.target).val(sanitized).trigger('change');
        });
    }
    else{
        $(elemet).parent().removeClass("has-error");
    }
}

function validate_R1(elemet){
    var regex = /^\d+(?:\.\d{0,1}){0,1}$/;
    validate_float(elemet,regex,1);
}
function validate_R2(elemet){
    var regex = /^\d+(?:\.\d{0,2}){0,1}$/;
    validate_float(elemet,regex,2);
}
function validate_R3(elemet){
    var regex = /^\d+(?:\.\d{0,3}){0,1}$/;
    validate_float(elemet,regex,3);
}
function validate_R4(elemet){
    var regex = /^\d+(?:\.\d{0,4}){0,1}$/;
    validate_float(elemet,regex,4);
}

function validate_float(elemet,regex,decimals){
    //var reg = new RegExp("^[0-9]+\[.]{0,1}\[0-9]{0,2}$");
    if(!regex.test($(elemet).val())){
        $(elemet).parent().addClass("has-error");
        $(elemet).bind('blur', function(event){
            var sanitized = $(event.target).val();
            sanitized = sanitized.replace(/[^\d+\.+]/gi, "").replace(/\.\.+/gi, ".");
            var array = sanitized.split('.');
            if(array.length > 0)
                if(array.length > 1)
                    sanitized = array[0] + "." + array[1].substr(0,decimals);
                else
                    sanitized = array[0];
            else
                sanitized = "";
            $(event.target).parent().removeClass("has-error");
            $(event.target).val(sanitized).trigger('change');
            /*setTimeout(function(){
                $(event.target).focus();
                $(elemet).bind('blur');
            },50);*/
            });
    }
    else{
        $(elemet).parent().removeClass("has-error");
    }
}
