VALIDATION_REGEX_PHONE = "^\+?(([0-9 ]+([\-.]{1}[0-9 ]+)*)*(\([0-9 ]+([\-.]{1}[0-9 ]+)*\))*)+$";
VALIDATION_REGEX_EMAIL = "^[\w_\-]+(\.[\w_\-]+)*@([\w_\-]+\.)+\w{2,4}$";
VALIDATION_REGEX_DIGIT = "^[0-9 ]*$";

function Validate(def)
{
    var IsValid = true;
    var objVal;
    $('.validator[type=required]', def).each(function(i){
        objVal = $($(this).attr("ControlToValidate")).val();
        if (objVal == ""){
            $(this).show();
            IsValid = false;
        }else
            $(this).hide();
    });
    $('.validator[type=regexpr]', def).each(function(i){
        objVal = $($(this).attr("ControlToValidate")).val();
        if (objVal != ""){
            IsValid = IsValidByRegEx(objVal, $(this).attr("ValidationExpression"));
            if (IsValid) $(this).hide();
            else $(this).show();
        }else
            $(this).hide();
    });
    $('.validator[type=phonenumber]', def).each(function(i){
        objVal = $($(this).attr("ControlToValidate")).val();
        if (objVal != ""){
            IsValid = IsValidByRegEx(objVal, VALIDATION_REGEX_PHONE);
            if (IsValid) $(this).hide();
            else $(this).show();
        }else
            $(this).hide();
    });
    $('.validator[type=emailadderss]', def).each(function(i){
        objVal = $($(this).attr("ControlToValidate")).val();
        if (objVal != ""){
            IsValid = IsValidByRegEx(objVal, VALIDATION_REGEX_EMAIL);
            if (IsValid) $(this).hide();
            else $(this).show();
        }else
            $(this).hide();
    });
    $('.validator[type=creditcardnumber]', def).each(function(i){
        objVal = $($(this).attr("ControlToValidate")).val();
        if (objVal != ""){
            IsValid = IsValidByLuhnAlg(objVal);
            if (IsValid) $(this).hide();
            else $(this).show();
        }else
            $(this).hide();
    });
    return IsValid;
}
function IsValidByRegEx(val, regex)
{
    re = new RegExp(regex, 'i');
    result = val.match(re);
    return (result != null);
}
function IsValidByLuhnAlg(val)
{
    var r = new RegExp(" ", 'g');
	val = val.replace(r, "");
    if (!IsValidByRegEx(val, VALIDATION_REGEX_DIGIT)) return false;
    sum = 0;
    imax = val.length - 1;
    for (i=imax; i>=0; i--){
        digit = val[i] * 1;
        if (i%2 == imax%2)
            sum += digit;
        else if (digit <= 4)
            sum += digit * 2;
        else
            sum += digit * 2 - 9;
    }
    return (sum%10 == 0);
}
