function displayError(ele, errorString, errorTitle)
{
    var okFunction = function(element)
    {
        return function()
        {
            element.focus();
            element.select();
        };
    }(ele);
    if (!errorTitle)
    {
        errorTitle = "Error";
    }
    MessageBox.error(errorTitle, errorString, null, okFunction);
}

/**
 * the pages will add ids to validate this global var. The expected format of
 * each item is a mapof the form {'label':'string','elementId':'theElementId'}
 */
var g_validationFields = [];

/**
 * simply checks for blanks. A very basic, first pass interpretation of "required"
 */
function requiredValidator()
{
    var i;
    for (i = 0; i < g_validationFields.length; ++i)
    {
        var each = g_validationFields[i];
        var ele = document.getElementById(each.elementId);
        if (ele.value === "")
        {
            displayError(ele, each.label + " cannot be blank, it is required.");
            return false;
        }
    }
    return true;
}

/**
 * Returns true if the string contains 0-9 and nothing else
 * @param input
 */
function isNumericOnly(input)
{
    return input.match(/[^0-9]+/) === null;
}

/**
 * Returns true if the string is truly blank (eg it trims off whitespace)
 * @param input the value to check.
 */
function isBlank(input)
{
    // regexp for empty field expression test.
    var emptyString = /^\s*$/;

    if (typeof input == "undefined")
    {
        return true;
    }
    else if (input === null)
    {
        return true;
    }
    else
    {
        return emptyString.test(input);
    }
}


/**
 * phone number - strip out delimiters and check for 10 digits. Returns blank if good.
 * @param strng the phone number to check
 */
function checkPhone(strng)
{
    var error = "";
    if (typeof strng == "undefined" || strng === "" || strng === null)
    {
        error = "You didn't enter a phone number.\n";
    }
    else
    {
        var stripped = strng.replace(/[\(\)\.\-\ ]/g, ''); //strip out acceptable non-numeric characters
        if (isNaN(parseInt(stripped, 10)))
        {
            error = "The phone number contains illegal characters.";
        }

        if (!(stripped.length == 10))
        {
            error = "The phone number is the wrong length. Make sure you included an area code.\n";
        }
    }

    return error;
}

/**
 * validate a text input to ensure it has a proper phone number. Designed to work in onSubmit
 * @param eleId the id of the input element to validate
 * @return true if the element has a valid phone number, false otherwise
 */
function validatePhoneByEleId(eleId)
{
    var ele = document.getElementById(eleId);
    var retVal = checkPhone(ele.value);

    if (retVal === "")
    {
        return true;
    }
    else
    {
        displayError(ele, retVal);
        return false;
    }
}

/**
 * validate the text input to ensure it has a value
 * @param eleId the id of the input element to validate
 * @parma elementName a human-readable descripition of the value tested
 * @return true if the element has a valid phone number, false otherwise
 */
function validateRequiredElement(eleId, elementName)
{
    var ele = document.getElementById(eleId);
    if (isBlank(ele.value))
    {
        displayError(ele, "The " + elementName + " must not be blank");
        return false;
    }
    else
    {
        return true;
    }
}

/**
 * Parses an email address to make sure that it has the proper format
 * @param emailStr the email address to parse
 */
function validateEmailAddress(emailStr)
{
    if (emailStr === "")
    {
        return "The email address must not be blank";
    }

    var checkTLD = 0;
    var knownDomsPat = /^(com|net|org|edu|int|mil|gov|arpa|biz|aero|name|coop|info|pro|museum)$/;
    var emailPat = /^(.+)@(.+)$/;
    var specialChars = "\\(\\)><@,;:\\\\\\\"\\.\\[\\]";
    var validChars = "\[^\\s" + specialChars + "\]";
    var quotedUser = "(\"[^\"]*\")";
    var ipDomainPat = /^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/;
    var atom = validChars + '+';
    var word = "(" + atom + "|" + quotedUser + ")";
    var userPat = new RegExp("^" + word + "(\\." + word + ")*$");
    //    var domainPat = new RegExp("^" + atom + "(\\." + atom +")*$");
    var matchArray = emailStr.match(emailPat);
    var i;

    if (matchArray === null)
    {
        return "The email address is Invalid";
    }

    var user = matchArray[1];
    var domain = matchArray[2];
    for (i = 0; i < user.length; i++)
    {
        if (user.charCodeAt(i) > 127)
        {
            return "The email address's user name contains invalid characters.";
        }
    }

    for (i = 0; i < domain.length; i++)
    {
        if (domain.charCodeAt(i) > 127)
        {
            return "The email address's domain name contains invalid characters.";
        }
    }

    if (user.match(userPat) === null)
    {
        return "The email address's user name is invalid.";
    }

    var IPArray = domain.match(ipDomainPat);
    if (IPArray !== null)
    {
        for (i = 1; i <= 4; i++)
        {
            if (IPArray[i] > 255)
            {
                return "The Destination IP Address is invalid.";
            }
        }
        return true;
    }

    var atomPat = new RegExp("^" + atom + "$");
    var domArr = domain.split(".");
    var len = domArr.length;
    for (i = 0; i < len; i++)
    {
        if (domArr[i].search(atomPat) == -1)
        {
            return "The email address's domain name is invalid.";
        }
    }

    if (checkTLD && domArr[domArr.length - 1].length != 2 && domArr[domArr.length - 1].search(knownDomsPat) == -1)
    {
        return "The email address's domain name extension is invalid";
    }

    if (len < 2)
    {
        return "The email address is missing a hostname.";
    }

    return "";
}

/**
 * validate a text input to ensure it has a proper email address. Designed to work in onSubmit
 * @param eleId the id of the input element to validate
 * @return true if the element has a valid phone number, false otherwise
 */
function validateEmailByEleId(eleId)
{
    var ele = document.getElementById(eleId);
    var retVal = validateEmailAddress(ele.value);

    if (retVal === "")
    {
        return true;
    }
    else
    {
        displayError(ele, retVal);
        return false;
    }
}

/**
 * Validates the single field in a simple search box
 * @param requiredElementId the id of the single field that would contain the term to search for.
 */
function validateSimpleSearch(requiredElementId)
{
    var simpleSearchInput = document.getElementById(requiredElementId);

    if (isBlank(simpleSearchInput.value))
    {
        displayError(simpleSearchInput, "The search field must contain text", "Invalid Search Parameters");
        return false;
    }
    else
    {
        return true;
    }
}
