﻿function validateEmail(email) {
	// var re = /^([a-zA-Z0-9_\.\-\+])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
	var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/ 
	return email.match(re) 
}

function emailValidator(source, arguments) { arguments.IsValid = validateEmail(arguments.Value); }

function validateMobile(phoneNumber) {
	var re = /^07[0-9]{0,1}[0-9]{2,7}$/
	if (!phoneNumber.match(re)) { return (false); }
	return (true);
}

function mobileValidator(source, arguments) { arguments.IsValid = validateMobile(arguments.Value); }

function validateUserName(userName) {
	if (validateEmail(userName)) {
		return true;
	} else {
		var re = /^[\w]+$/;
		if (!userName.match(re)) { return false; }
		return true;
	}
}

function userNameValidator(source, arguments) {
	if (validateUserName(arguments.Value)) {
		arguments.IsValid = true;
	} else {
		arguments.IsValid  = validateEmail(arguments.Value)
	}
}

function validatePNum(sPNum) {
    var numbers = sPNum.match(/^(\d)(\d)(\d)(\d)(\d)(\d)(\d)(\d)(\d)(\d)(\d)(\d)$/);
    var checkSum = 0;
    var d = new Date();
    if (!isDate(sPNum.substring(0, 4), sPNum.substring(4, 6), sPNum.substring(6, 8))) { return false; }
    if (numbers == null) { return false; }
    var n;
    for (var i = 3; i <= 12; i++) {
        n = parseInt(numbers[i]);
        if (i % 2 == 0) { checkSum += n; }
        else { checkSum += (n * 2) % 9 + Math.floor(n / 9) * 9 }
    }
    if (checkSum % 10 == 0) { return true; }
    return false;
}

function getYear(y) { return (y < 1000) ? y + 1900 : y; }

function isDate(year, month, day) {
    month = month - 1; // 0-11 in JavaScript
    var tmpDate = new Date(year, month, day);
    if ((getYear(tmpDate.getYear()) == year) && (month == tmpDate.getMonth()) && (day == tmpDate.getDate())) { return true; }
    else { return false; }
}

function stripNonAlphanumeric(element) {
	element.value = element.value.replace(/[^A-Za-z0-9]/g, '');
}

function stripNonNumeric(element) {
	element.value = element.value.replace(/[^0-9]/g, '');
}
