﻿// validation

var SIGNUP_EMAIL = 'Signup email';
var reBadChar = /[\?\(\)\<\>\.\;\:\\\/\"\[\]\{\}\|\`\~\!\+\=\,\'\-]/g;
var reBadAddress = /[\?\(\)\<\>\.\;\:\\\/\"\[\]\{\}\|\`\~\!\+\=]/g;

/************* require field ***************/
function validRrequiredDropDown(ddlControl, label) {
    if (ddlControl.value.length == 0) {
        showErrorMessage(label + ' is blank');
        ddlControl.focus();
        return false;
    }
    return true;
}

function validRrequiredField(txtField, label, lblMessage) {
    var trimmed = trim(txtField.value);
    txtField.value = trimmed;
    if (trimmed.length == 0) {
        if (lblMessage)
            showErrorMessageAt(lblMessage, label + ' is blank');
        else
            showErrorMessage(label + ' is blank');

        txtField.focus();
        return false;
    }
    return true;
}

/************* valid ***************/
function validAddress(txtField, label) {
    if (txtField.value.length == 0)
        return true;

    // remove illegal characters from raw input
    var stripped = trim((txtField.value).replace(reBadAddress, ''));
    txtField.value = stripped;
    
    var error = '';
    if (stripped.length == 0)
        error = label + ' is blank';
        
    if (error) {
        showErrorMessage(error);
        txtField.focus();
        return false;
    } else
        return true;
}

function validAlphaNumericSpace(txtField, label, lblMessage) {
    if (txtField.value.length == 0)
        return true;

    // remove illegal characters from raw input
    var stripped = trim((txtField.value).replace(reBadChar, ''));
    txtField.value = stripped;
    
    var error = '';
    if (stripped.length == 0)
        error = label + ' is blank';
    else if (!isAlphaNumericSpace(stripped))
        error = label + ' is invalid';
        
    if (error) {
        if (lblMessage)
            showErrorMessageAt(lblMessage, error);
        else
            showErrorMessage(error);

        txtField.focus();
        return false;
    } else
        return true;
}

function validAlphabetSpaceUnderscore(txtField, label, lblMessage) {
    if (txtField.value.length == 0)
        return true;

    // remove illegal characters from raw input
    var stripped = trim((txtField.value).replace(reBadChar, ''));
    txtField.value = stripped;
    
    var error = '';
    if (stripped.length == 0)
        error = label + ' is blank';
    else if (!isAlphaNumericSpace(stripped))
        error = label + ' is invalid';
        
    if (error) {
        if (lblMessage)
            showErrorMessageAt(lblMessage, error);
        else
            showErrorMessage(error);

        txtField.focus();
        return false;
    } else
        return true;
}

function validEmailAddress(txtField, label, lblMessage) {
    if (txtField.value.length == 0)
        return true;

    // remove illegal characters from raw input
    var stripped = (txtField.value).replace(/[ \?\'\(\)\<\>\,\;\:\\\/\"\[\]]/g, '');
    txtField.value = stripped;
    
    var error = '';
    if (stripped.length == 0)
        error = label + ' is blank';
    else if (!isEmailAccount(stripped))
        error = label + ' is invalid';
        
    if (error) {
        if (lblMessage)
            showErrorMessageAt(lblMessage, error);
        else
            showErrorMessage(error);

        txtField.focus();
        return false;
    } else
        return true;
}

function validPhoneNumber(txtField, label, lblMessage) {
    if (txtField.value.length == 0)
        return true;

    var stripped = (txtField.value).replace(/[ -]/g, '');    // strip out spaces and hypens
    txtField.value = stripped;

    var error = '';
    
    if (stripped.length == 0)
        error = label + ' is blank';
    else {
        var isChinaPhone = stripped.substr(0, 1).toUpperCase() == 'C';
        if (isChinaPhone)
            stripped = stripped.substr(1, stripped.length - 1);

        if (stripped.length == 0)
            error = label + ' is blank';
        else if (!isNumber(stripped))
            error = label + ' contains non-digits';
        else if (isChinaPhone && stripped.length <= 10)
            error = label + ' should be 10+ digits long in China (you have ' + stripped.length + ')';
        else if (!isChinaPhone && stripped.length != 10)
            error = label + ' should be 10 digits long (you have ' + stripped.length + ')';
    }
    
    if (error) {
        if (lblMessage)
            showErrorMessageAt(lblMessage, error);
        else
            showErrorMessage(error);

        txtField.focus();
        return false;
    } else
        return true;
}

function validNumber(txtField, label, requiredLength) {
    if (txtField.value.length == 0)
        return true;

    var stripped = (txtField.value).replace(/[ -]/g, '');    // strip out spaces and hypens
    txtField.value = stripped;

    var error;

    if (stripped.length == 0)
        error = label + ' is blank';
    else if (!isNumber(stripped))
        error = label + ' contains non-digits';
    else if (stripped.length != requiredLength)
        error = label + ' should be ' + requiredLength + ' digits long (you have ' + stripped.length + ')';
    
    if (error) {
        showErrorMessage(error);
        txtField.focus();
        return false;
    } else
        return true;
}

function validScreenName(txtField, label, lblMessage) {
    if (txtField.value.length == 0)
        return true;

    // remove illegal characters from raw input
    var stripped = trim((txtField.value).replace(reBadChar, ''));
    txtField.value = stripped;
    
    var error = '';
    if (stripped.length == 0)
        error = label + ' is blank';
    else if (!isScreenName(stripped))
        error = label + ' is invalid';
        
    if (error) {
        if (lblMessage)
            showErrorMessageAt(lblMessage, error);
        else
            showErrorMessage(error);

        txtField.focus();
        return false;
    } else
        return true;
}

function validUSPhoneNumber(txtField, label, lblMessage) {
    if (txtField.value.length == 0)
        return true;

    var stripped = (txtField.value).replace(/[ -]/g, '');    // strip out spaces and hypens
    txtField.value = stripped;

    var error = '';
    if (stripped.length == 0)
        error = label + ' is blank';
    else if (!isNumber(stripped))
        error = label + ' contains non-digits';
    else if (stripped.length != 10)
        error = label + ' should be 10 digits long (you have ' + stripped.length + ')';

    if (error) {
        if (lblMessage)
            showErrorMessageAt(lblMessage, error);
        else
            showErrorMessage(error);

        txtField.focus();
        return false;
    } else
        return true;
}

function validYahooMessengerID(txtField, label, lblMessage) {
    // strip "@yahoo.com" if any
    var pos = txtField.value.toLowerCase().indexOf("@yahoo.com");
    if (pos > 0)
        txtField.value = txtField.value.substr(0, pos);
        
    return validAlphabetSpaceUnderscore(txtField, label, lblMessage);
}

function validZipcode(txtField) {
    if (txtField.value.length == 0)
        return true;

    var label = 'Zip code';
    var error;
    
    var stripped = (txtField.value).replace(/ |-/g, '');    // strip out spaces and hypens
    txtField.value = stripped;

    if (stripped.length == 0)
        error = label + ' is blank';
    else if (stripped.length != 5 && stripped.length != 10)
        error = label + ' should be 5 or 10 digits long (you have ' + stripped.length + ')';
    else if (!isZipcode(stripped))
        error = label + ' is invalid';
    
    if (error) {
        showErrorMessage(error);
        txtField.focus();
        return false;
    } else
        return true;
}

/***************** is *********************/
function isAlphaNumeric (s) {
    var re = /^\w+$/;
    return re.test(s);
}

function isAlphaNumericSpace(s) {
    var re = /^(\w| )+$/;
    return re.test(s);
}

function isEmailAccount(s) {
    var re = /^.+@.+\..{2,4}$/;
    return re.test(s);
}

function isLeapYear(year){
    return year % 4 == 0 && year % 100 != 0 || year % 100 == 0 && year % 400 == 0
}

function isNumber(s) {
    var re = /^[0-9]+$/;
    return re.test(s);
}

function isScreenName(s) {
    // not include underscore
    // can't be pure digits
    var re = /^([a-zA-Z0-9]| )+$/;
    return re.test(s) && !isNumber(s);
}

function isTime(s) {
    s = s.toLowerCase().replace(/ /g, '');
    
    // regular expression to match required time format
    var re = /^(\d{1,2})(:)?(\d{2})?([ap]m)?$/;         //no space and am/pm part is optional
    var valid = true;
    
    if (regs = s.match(re)) {   // patten match
        // check hour range
        if (regs[4]) {  // has am/pm part
            if (regs[1] < 1 || regs[1] > 12) // hour should be between 1 to 12
                valid = false;
        } else {    //without am/pm part
            if (regs[1] > 23)      // hour should be less than 24
                valid = false;
        }

        // check minute range
        if (regs[2] && regs[2] > 59)
          valid = false;
    } else {    // patten does not match
        valid = false;
    }
    return valid;
}

function isUSDate(strValue) {
/************************************************
DESCRIPTION: Validates that a string contains only
    valid dates with 2 digit month, 2 digit day,
    4 digit year. Date separator can be ., -, or /.
    Uses combination of regular expressions and
    string parsing to validate date.
    Ex. mm/dd/yyyy or mm-dd-yyyy or mm.dd.yyyy

PARAMETERS:
   strValue - String to be tested for validity

RETURNS:
   True if valid, otherwise false.

REMARKS:
   Avoids some of the limitations of the Date.parse()
   method such as the date separator character.
*************************************************/
    var objRegExp = /^\d{1,2}(\-|\/|\.)\d{1,2}\1\d{4}$/

    //check to see if in correct format
    if (!objRegExp.test(strValue))
        return false; //doesn't match pattern, bad date

    // get the first separator
    for (i = 0; i < strValue.length; i++) {
      if (strValue.charAt(i) > '9' || strValue.charAt(i) < '0')
        break;
    }
    var strSeparator = strValue.charAt(i);

    //split date into month, day, year
    var arrayDate = strValue.split(strSeparator);
    // there is a bug in parseInt, which treats "08" and "09" as 0. use parseFloat instead
    var intMonth = parseFloat(arrayDate[0]);
    var intDay = parseFloat(arrayDate[1]);

    var arrayLookup = {1:31, 3:31, 4:30, 5:31, 6:30, 7:31, 8:31, 9:30, 10:31, 11:30, 12:31}

    //check if month value and day value agree
    if (arrayLookup[intMonth] != null && intDay != 0 && intDay <= arrayLookup[intMonth])
            return true; //found in lookup table, good date

    //check for February
    // A year will be a leap year if it is divisible by 4 but not by 100. 
    // If a year is divisible by 4 and by 100, it is not a leap year unless it is also divisible by 400. 
    if (intMonth == 2) { 
        var intYear = parseInt(arrayDate[2]);
        if (isLeapYear(intYear)) 
            return intDay > 0 && intDay <= 29;        // leap year
        else
            return intDay > 0 && intDay <= 28;        // not leap year
    }

    return false; //any other values, bad date
}

function isZipcode(s){
    var re = new RegExp(/(^\d{5}$)|(^\d{5}-\d{4}$)/);
    return (re.test(s));
}
