﻿function CvdEmail_Validate(sender, args) {
    emailAddr = args.Value;
    
    if (emailAddr == null || emailAddr == "") {
        args.IsValid = false;
        SetErrorMsg(sender, "Required");
    }
    else if (/\b[a-zA-Z0-9._%-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}\b/.test(emailAddr) == false) {
        args.IsValid = false;
        SetErrorMsg(sender, "E-mail Address Invalid");
    }
    else if (EmailAlreadyRegistered()) {
        args.IsValid = false;
        SetErrorMsg(sender, "This E-mail Address Is Already Registered");
    }
    else {
        args.IsValid = true;
    }
}

function userCodeExists() {
    try { if (userCode() != null) return true; }
    catch (e) { return false; }
}

function userCodeIfExists() {
    if (userCodeExists()) return userCode();
    else return null; 
}

function getXmlHttpRequestArgs() { 
    xmlHttpReqArgs = "emailAddressToCheck=" + emailAddr;
    if (userCodeIfExists() != null) xmlHttpReqArgs += "&userCode=" + userCodeIfExists();
    return xmlHttpReqArgs;
}

function EmailAlreadyRegistered() {
    if (window.XMLHttpRequest) { // Mozilla, Safari, IE7+ etc 
        xmlHttpReq = new XMLHttpRequest();
    } else if (window.ActiveXObject) { // IE 5 & 6
        xmlHttpReq = new ActiveXObject("MSXML2.XMLHTTP");
    }

    if (typeof (xmlHttpReq) == 'object') {
        with (xmlHttpReq) {
            open("POST", gAppRootPath + "WebServices/ValidationService.asmx/EmailAddressHasBeenUsedBefore", false);
                        
            setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
            xmlHttpReq.send(getXmlHttpRequestArgs()); 
            var response = xmlHttpReq.responseText;
            with (xmlHttpReq) {
                if (readyState == 4) {
                    if (status == 200) {
                        switch (responseXML.lastChild.childNodes[0].nodeValue) {
                            case "true": return true;
                            case "false": return false;
                        }
                    }
                }
            }
        }
    }
}
