var oDomainRequest;
var oDomains;

window.onload += function() {
    if (window.addEventListener)
        document.getElementById("lstDomains").addEventListener("keyup", removeDomain, false);
    else
        document.getElementById("lstDomains").onkeyup = removeDomain;
    getDomains();
}

function addDomain() {
    var oTextBox = document.getElementById("txtDomain");
    var sDomain = oTextBox.value;
    if (sDomain.length > 0) {
        if (isPrivateDomain(sDomain)) {
            if (isValidDomain(sDomain)) {
                var oListBox = document.getElementById("lstDomains");
                var aOptions = oListBox.options;
                var oOption;
                for (var iOption = 0; iOption < aOptions.length; iOption++) {
                    oOption = aOptions[iOption];
                    if (oOption.value == sDomain) {
                        alert("The supplied domain has already been approved.");
                        return false;    
                    }
                }
                
                //Add the value to the list box
                var oNewOption = document.createElement("OPTION");
                oNewOption.value = sDomain;
                if (document.all)
                    oNewOption.innerText = sDomain;
                else
                    oNewOption.textContent = sDomain;
                oListBox.appendChild(oNewOption);
                oTextBox.value = "";
                setListBoxValue(oListBox);
                return true;
            }
            else {
                alert("The supplied domain's syntax is invalid.");
                return false;
            }
        }
        else {
            alert("Public email domains including, but not limited to, gmail.com, hotmail.com, and yahoo.com, live, msn, aol, earthlink, comcast domains are not allowed.");
            return false;
        }
    }
}

function changeCheckStatus(oCheckBox) {
    getInputByClientName("txtMainContactFirstName").disabled = getInputByClientName("txtMainContactLastName").disabled = getInputByClientName("txtMainContactEmail").disabled = oCheckBox.checked;
}

function getDomains() {
    if (window.XMLHttpRequest)
        oDomainRequest = new XMLHttpRequest();        
    else
        oDomainRequest = new ActiveXObject("MSXML2.XMLHTTP.3.0");
    oDomainRequest.onreadystatechange = loadDomains;
    oDomainRequest.open("GET", "http://1.11.0.22/partnerportal/xml/domains.aspx");
    oDomainRequest.send(null);
}

function getDuplicateDomains() {
    var sDuplicateDomains = "";
    
    var sDomain = getInputByClientName("txtPrimaryDomain").value;
    if (!isDomainUnique(sDomain))
        sDuplicateDomains += sDomain + "\n";
    
    var aOptions = document.getElementById("lstDomains").options;
    var oOption;
    for (var iOption = 0; iOption < aOptions.length; iOption++) {
        oOption = aOptions[iOption];
        sDomain = oOption.text;
        if (!isDomainUnique(sDomain))
            sDuplicateDomains += sDomain + "\n";
    }
    
    return sDuplicateDomains;

    function isDomainUnique(sDomain) {
        if (oDomains != null) {
            return (oDomains.selectSingleNode("domains/domain[@id='" + sDomain + "']") == undefined);
        }
        else {
            return true;
        }
    }
}

function getInputByClientName(sName) {
    var aInputs = document.getElementsByTagName("INPUT");
    var oInput;
    for (var iInput = 0; iInput < aInputs.length; iInput++) {
        oInput = aInputs[iInput];
        if (oInput.id.indexOf(sName) != -1)
            return oInput;
    }
    return null;
}

function isEmpty(sValue) {
    for (var iCharacter = 0; iCharacter < sValue.length; iCharacter++)
       if (" " != sValue.charAt(iCharacter))
          return false;
    return true;
}

function isMainContactField(oInput) {
    var sId = oInput.id;
    return !(sId.indexOf("txtMainContactFirstName") == -1 && sId.indexOf("txtMainContactLastName") == -1 && sId.indexOf("txtMainContactEmail") == -1);
}

function isPrivateDomain(sDomain) {
    //Ensure that the domain is not a "free" mail domain
    var sLowerDomain = sDomain.toLowerCase();
    if (sLowerDomain == "gmail.com" || sLowerDomain == "hotmail.com" || sLowerDomain == "yahoo.com"
        || sLowerDomain == "live.com" || sLowerDomain == "msn.com" || sLowerDomain == "aol.com"
        || sLowerDomain == "earthlink.com" || sLowerDomain == "comcast.com")
        return false;
    return true;
}

function isValidDomain(sDomain) {
    var oRegularExpression = /^[a-zA-Z0-9.-]+\.(com|edu|info|gov|int|mil|net|org|biz|name|museum|coop|aero|pro|[a-zA-Z]{2})$/;
    return oRegularExpression.test(sDomain);
}

function isValidEmailDomain(sEmail) {
    var sDomain = sEmail.substr(sEmail.indexOf("@") + 1);
    if (sDomain == getInputByClientName("txtPrimaryDomain").value)
        return true;
    else {
        var aOptions = document.getElementById("lstDomains").options;
        var oOption;
        for (var iOption = 0; iOption < aOptions.length; iOption++) {
            oOption = aOptions[iOption];
            if (sDomain == oOption.text)
                return true;
        }
    }
    return false;
}

function isEmailDomainExcluded(sDomain) {
    
    var sLowerDomain = sDomain.toLowerCase();
    if (sLowerDomain.indexOf("@gmail.") != -1 
    || sLowerDomain.indexOf("@hotmail.") != -1 
    || sLowerDomain.indexOf("@yahoo.") != -1 
    || sLowerDomain.indexOf("@live.") != -1 
    || sLowerDomain.indexOf("@msn.") != -1 
    || sLowerDomain.indexOf("@aol.") != -1 
    || sLowerDomain.indexOf("@earthlink.") != -1
    || sLowerDomain.indexOf("@comcast.") != -1
    || sLowerDomain.indexOf("@sbcglobal.net") != -1
    || sLowerDomain.indexOf("@psp.net") != -1
    || sLowerDomain.indexOf("@pillardata.com") != -1)
        return true; 
        
    return false;
}

function isValidForm() {
    var sError = "";
    var oSameContact = getInputByClientName("chkSameContact");
    var aElements = document.getElementsByTagName("INPUT");
    var oElement;
    for (var iElement = 0; iElement < aElements.length; iElement++) {
        oElement = aElements[iElement];
        if (oElement.getAttribute("required") != null) {
            if (!isMainContactField(oElement) || !oSameContact.checked)
                if (isEmpty(oElement.value))
                    sError += "  " + oElement.getAttribute("errorname") + "\n";
        }
    }

    var aSelectElements = document.getElementsByTagName("SELECT");
    var oSelectElement;
    for (var iElement = 0; iElement < aSelectElements.length; iElement++) {
        oSelectElement = aSelectElements[iElement];
        if (oSelectElement.getAttribute("required") != null) {
            if (isEmpty(oSelectElement.value)) {
                sError += "  " + oSelectElement.getAttribute("errorname") + "\n";
            }
        }
    }
    
    if (sError == "") {
        var emailPattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;  
        if (!emailPattern.test(getInputByClientName("txtEmail").value)) {
                alert("Please enter a valid email address.");
                return false;
        }
          
        if (!oSameContact.checked && !emailPattern.test(getInputByClientName("txtMainContactEmail").value)) {
                alert("Please enter a valid email address.");
                return false;
        }      
        
        if (!isValidEmailDomain(getInputByClientName("txtEmail").value)) {
            alertInvalidDomain(false);
            return false;
        }
        else if (!oSameContact.checked && !isValidEmailDomain(getInputByClientName("txtMainContactEmail").value)) {
            alertInvalidDomain(true);
            return false;
        }
        else {
            if (isEmailDomainExcluded(getInputByClientName("txtEmail").value)
                || (!oSameContact.checked && isEmailDomainExcluded(getInputByClientName("txtMainContactEmail").value)) 
                ) 
                {
                    alert("Public email domains including, but not limited to, gmail.com, hotmail.com, and yahoo.com, live, msn, aol, earthlink, comcast domains are not allowed.");
                    return false;
                }               
    
            var sError = getDuplicateDomains();
            if (sError.length > 0) {
                alert("The following domains are not unique:\n" + sError);
                return false;
            }
            
        }
        return true;
    }
    else {
        alert("Required data is missing:\n" + sError);
        return false;
    }
    
    function alertInvalidDomain(bMain) {
        alert((bMain ? "The main contact" : "Your ") + "email address is not from one of the domains you have entered.  For example, an email address of john.smith@abc-reseller.com must have abc-reseller.com listed as one of the domains.  Please DO NOT include www.  Only use the information after the @ sign.");
    }
}

function loadDomains() {
    if (oDomainRequest.readyState == 4)
       oDomains = oDomainRequest.responseXML;
}

function removeDomain(e) {
    var oListBox;
    var iKeyCode;
    if (e) {
        oListBox = e.target;
        iKeyCode = e.which;
    }
    else {
        oListBox = event.srcElement;
        iKeyCode = event.keyCode;
    }
    //Determine if the delete key has been pressed
    if (iKeyCode == 46)
        if (oListBox.selectedIndex != -1) {
            oListBox.removeChild(oListBox.options[oListBox.selectedIndex]);
            setListBoxValue(oListBox);
        }
}

function removeDomainClick()
{
    var oListBox = $('lstDomains');
    if (oListBox && oListBox.selectedIndex != -1) {
        oListBox.removeChild(oListBox.options[oListBox.selectedIndex]);
        setListBoxValue(oListBox);
    }
}

function selectSameAddress() {
    //Determine if the check box is currently checked
    var bChecked = event.srcElement.checked;
    
    //Retrieve the main contact email text box
    var aInputs = document.getElementsByTagName("INPUT");
    var oInput, oTextBox;
    for (var iInput = 0; iInput < aInputs.length; iInput++) {
        oInput = aInputs[iInput];
        if (oInput.id.indexOf("txtMainContactEmail") != -1) {
            oTextBox = oInput;
            break;
        }
    }
    
    //Modify settings and enable/disable controls
    if (bChecked) {
        oTextBox.disabled = true;
    }
    else {
        oTextBox.disabled = false;
    }
}

function setListBoxValue(oListBox) {
    var sValue = "";
    var sDelimiter = ", ";
    var aOptions = oListBox.options;
    var oOption;
    for (var iOption = 0; iOption < aOptions.length; iOption++) {
        oOption = aOptions[iOption];
        sValue += oOption.value + ", ";
    }
    sValue = sValue.substring(0, sValue.length - sDelimiter.length);
    document.getElementById("sDomains").value = sValue;
}

