﻿rangex = new RegExp("^[ ]*\\(?[ ]*(-?\\d+(\\.\\d+)?)[ ]*\\)?[ ]*(-|to)[ ]*\\(?[ ]*(-?\\d+(\\.\\d+)?)[ ]*\\)?[ ]*$");

$(document).ready(function(){
    $(":input").bind("blur", function(){
        setupValidation(this);
    });
});

function validateall(containerId) {
    if (!containerId)
        containerId = 'lxform';

    var valid = true;
    $("#errors_on_page").hide();
    $('#' + containerId + ' :input').each(function(){
        if(!validate($(this))) {
            valid = false;
            $("#errors_on_page").show();
        }
    });
    if(valid){
        return true;
    } else {
        return false;
    }
};

function validate(obj) {
    var validation = obj.attr("validation");
    var validateHidden = (obj.attr("validate") && obj.attr("validate") == "always");
    var errdiv = '_'+obj.attr("id")+'_error';
    if (obj.get(0).disabled || (!validateHidden && (obj.get(0).offsetHeight == obj.get(0).offsetWidth && obj.get(0).offsetWidth == 0))) {
        $("#"+errdiv).remove();
        return true;
    }
    if(validation) {
        var valid = validation.split(" OR ");
        var value = obj.val() || '';
        if(obj.attr('type') == 'checkbox') {
            value = (obj.attr('checked') ? value : '');
        }
        for(var i = 0; i < valid.length; i++) {
            var v = valid[i];
            // if v matches the rangex regular expression, treat it as a range
            // otherwise treat it as a regular expression
            if(v.match(rangex)) {
                var m = rangex.exec(v);
                var s = m[1]*1;
                var e = m[4]*1;
                value = value*1;
                if(s <= value && value <= e) {
                    $("#"+errdiv).remove();
                    return true;
                }
            } else {
                re = new RegExp(v, "i");
                re.multiline = false;
                if(value.match(re)) {
                    $("#"+errdiv).remove();
                    return true;
                }
            }
        }
        // If we haven't returned "true" at this point, we haven't found a match and should
        // set the error message.
        if($("#"+errdiv).length < 1) {
            var errmessage = ''+obj.attr('error');
            if(errmessage == 'undefined' || errmessage == '') {
                errmessage = 'Invalid Entry';
            }
            obj.parent().append('<div class="field_error rer" id="'+errdiv+'">'+errmessage+'</div>');
        }
        return false;
    }
    // No validation, return true
    $("#" + errdiv).remove();
    return true;
};

function setupValidation(element) {
    validate($(element));
    if($("div.rer:visible").size() > 0) {
        $("#errors_on_page").show();
    } else {
        $("#errors_on_page").hide();
    }
};
