if (window.addEventListener)
    window.addEventListener("load", init, false);
else if (window.attachEvent)
    window.attachEvent("onload", init);
else
    window.onload = init;
var namespace; //want namespace to be global so we can get at contents using window array 
function init()
{
    // if wanting to use: UniqueName, CaptchaFieldsBeforeID, PutCaptchaInDL or NoJavascriptDivID should be set before including this file
    // UniqueName helps avoid clashes in ids (if multiple captchas)
    // CaptchaFieldsBeforeID helps place the captcha fields
    // PutCaptchaInDL is used if submitbuttonID is inside a dl, dt or dd
    // NoJavascriptDivID displays instead of the form if javascript is disabled
    namespace = ((typeof(UniqueName) != "undefined") ? UniqueName : "captcha");
    var submitID = ((typeof(CaptchaFieldsBeforeID) != "undefined") ? CaptchaFieldsBeforeID : "");
    var FatalErrorDiv = ((typeof(NoJavascriptDivID) != "undefined") ? NoJavascriptDivID : "");
    var InDL = ((typeof(PutCaptchaInDL) != "undefined") ? true : false);
    var formID = ((typeof(FormID) != "undefined") ? FormID : namespace + "Form");
    var protocol = (window.location.protocol.indexOf('https:')==0 ? "https://" : "http://");
    var test = (typeof(debug) != "undefined" && debug);
    var error = "";
    
    //try to create and insert node
    try
    {
        formNode = document.getElementById(formID); 
    }
    catch(err)
    {
        error = "Couldn't find formID=" + formID + ". Err is " + err;
        takeDownForm(error, FatalErrorDiv, formNode, test);
    }

    if (error == "")
    {   
        try
        {
            //create captcha node
            var catptchaNode, guidInput, dlNode, dtTypeNode, ddTypeNode, dtTestNode, ddTestNode, imageDivNode, audioDivNode;

            dtTypeNode = document.createElement('dt');
            dtTypeNode.innerHTML = "Verification Type";
            ddTypeNode = document.createElement('dd');
            ddTypeNode.innerHTML = "<input type='radio' id='" + namespace + "TypeImage' name='captchaType' value='image' checked='checked' onclick='" + namespace + ".useImage()' />" +                             "<label for='captchaTypeImage'>Visual Test</label>" + 
                            "<input type='radio' id='" + namespace + "TypeAudio' name='captchaType' value='audio' onclick='" + namespace + ".useAudio()' />" +
                            "<label for='" + namespace + "TypeAudio'>Audio Test</label>";
            audioDivNode = document.createElement('div');
            audioDivNode.id = namespace + "AudioDiv";
            audioDivNode.style.display = "none";
            audioDivNode.innerHTML = "<a onclick='" + namespace + ".openAudioWindow()'>" +
                            "<img src='" + protocol + "www.missouristate.edu/errors/images/xi-audio.gif' alt='Audio Test File' />" + 
                            "</a>    Enter the numbers listed in the " + 
                            "<a href='#' onclick='" + namespace + ".openAudioWindow(); return false;'>Audio Clip</a>" + 
                            " in the form fields below." +
                            "<dl><dt><label for='n1'>First number:</label></dt>" +
                            "<dd><input type='text' id='" + namespace + "n1' name='captchaNumber1' maxlength='2' size='2'/></dd>" +
                            "<dt><label for='n2'>Second number:</label></dt>" +
                            "<dd><input type='text' id='" + namespace + "n2' name='captchaNumber2' maxlength='2' size='2'/></dd>" +
                            "<dt><label for='n3'>Third number:</label></dt>" +
                            "<dd><input type='text' id='" + namespace + "n3' name='captchaNumber3' maxlength='2' size='2'/></dd></dl>";
            imageDivNode = document.createElement('div');
            imageDivNode.id = namespace + "ImageDiv";
            imageDivNode.style.display = "none";
            imageDivNode.innerHTML = "<img id='" + namespace + "Image' src='' alt='Captcha image'/><br />" +
                            "<label for='" + namespace + "Input'>Enter the code shown:</label>" +
                            "<input id='" + namespace + "Input' type='text' name='captchaUserInput' size='5' maxlength='5' />";
            dtTestNode = document.createElement('dt');
            dtTestNode.innerHTML = "Human Verification";
            ddTestNode = document.createElement('dd');
            ddTestNode.id = namespace + "Test";
            ddTestNode.appendChild(imageDivNode);
            ddTestNode.appendChild(audioDivNode);


            guidInput = document.createElement('input');
            guidInput.type = "hidden";
            guidInput.name = "captchaGuid";
            guidInput.id = namespace + "GuidInput";

            if (!InDL || submitID != "")
            {
                dlNode = document.createElement('dl');
                dlNode.appendChild(dtTypeNode);
                dlNode.appendChild(ddTypeNode);
                dlNode.appendChild(dtTestNode);
                dlNode.appendChild(ddTestNode);

                captchaNode = document.createElement('div');
                captchaNode.id = namespace + "MainDiv";
                captchaNode.appendChild(guidInput);
                captchaNode.appendChild(dlNode);
            }
        }
        catch(err)
        {
            error = error + "Couldn't create the captcha node. Err is " + err;
            takeDownForm(error, FatalErrorDiv, formNode, test);
        }
    }   
        
    if (error == "")
    {   
        try
        {
            //check for empty form also allow possible passing of submit id for the exact submit button to insertBefore
            if (submitID != "")
            {
                var sub = document.getElementById(submitID);
                if (InDL)
                {
                    //go up until we have dd or dt
                    var i;
                    for (i=sub;i.nodeName != "DD" && i.nodeName != "DT" && i.nodeName != "DL" && i.nodeName != "BODY" && i.nodeName != "HTML"; i = i.parentNode) ;
                    
                    if (i.nodeName == "DD")
                    {
                        while(!(i.nodeType == 1 && i.nodeName == "DT") && i.previousSibling){alert(i.nodeType);i = i.previousSibling;}
                        if(i.nodeName == "DT")
                        {
                            i.parentNode.insertBefore(guidInput,i);
                            i.parentNode.insertBefore(dtTypeNode,i);
                            i.parentNode.insertBefore(ddTypeNode,i);
                            i.parentNode.insertBefore(dtTestNode,i);
                            i.parentNode.insertBefore(ddTestNode,i);
                        }
                        else 
                        {
                            var tryDefaultWay = true;
                        }
            
                    }
                    else if (i.nodeName == "DT")
                    {
                        i.parentNode.insertBefore(guidInput,i);
                        i.parentNode.insertBefore(dtTypeNode,i);
                        i.parentNode.insertBefore(ddTypeNode,i);
                        i.parentNode.insertBefore(dtTestNode,i);
                        i.parentNode.insertBefore(ddTestNode,i);
                    }
                    else if (i.nodeName == "DL")
                    {
                        var mydl = document.createElement('DL');
                        mydl.appendChild(guidInput);
                        mydl.appendChild(dtTypeNode);
                        mydl.appendChild(ddTypeNode);
                        mydl.appendChild(dtTestNode);
                        mydl.appendChild(ddTestNode);
                        i.parentNode.insertBefore(mydl,i);
                    }
                    else
                    {
                        var tryDefaultWay = true;
                    }
                }
                else
                    sub.parentNode.insertBefore(captchaNode,sub);
            }
            else
            {
                var i;
                for (i = formNode.lastChild; i != formNode.firstChild && i.type != "submit"; i = i.previousSibling);
                //okay if form empty
                if(i == formNode.firstChild)
                    formNode.appendChild(captchaNode);
                else
                    formNode.insertBefore(captchaNode,i);
            }

            if (tryDefaultWay)
            {
                // try to stick a captcha that should have been in a dl (but failed) in a form as last resort
                var mydl = document.createElement('DL');
                mydl.appendChild(guidInput);
                mydl.appendChild(dtTypeNode);
                mydl.appendChild(ddTypeNode);
                mydl.appendChild(dtTestNode);
                mydl.appendChild(ddTestNode);

                var i;
                for (i = formNode.lastChild; i != formNode.firstChild && i.type != "submit"; i = i.previousSibling);
                //okay if form empty
                if(i == formNode.firstChild)
                    formNode.appendChild(mydl);
                else
                    formNode.insertBefore(mydl,i);
            }
            
        }
        catch(err)
        {
            error = error + "Couldn't insert the captcha node. Err is " + err;
            takeDownForm(error, FatalErrorDiv, formNode, test);
        }
    }   

    if (error == "")
    {   
        try
        {
            //create captcha fatal error and error nodes
            var capFatal = document.createElement('div');
            capFatal.id = namespace + "FatalError";
            capFatal.className = "Error";
            formNode.parentNode.insertBefore(capFatal,formNode);
            var capErr = document.createElement('div');
            capErr.id = namespace + "ErrorDiv";
            capErr.className = "Error";
            formNode.parentNode.insertBefore(capErr,formNode);
        }
        catch(err)
        {
            error = error + "Couldn't make captcha error node(s). Err is " + err;
            takeDownForm(error, FatalErrorDiv, formNode, test);
        }
    }   


    if (error == "")
    {   
        try
        {
                window[namespace] = new Captcha(namespace,formID,test);
                window[namespace].Captcha_Init();

               
               var tmpF = formNode.onsubmit;
               formNode.onsubmit = function()
               {
                //return tmpF() && window[namespace].validate();

                if (typeof(tmpF) != "undefined")
                    return tmpF() && window[namespace].validate();
                else
                    return window[namespace].validate();
               }

                if (FatalErrorDiv) 
                {
                    document.getElementById(FatalErrorDiv).style.display = "none";
                    formNode.style.display = "block";
                }

               
        }
        catch(err)
        {
            error = error + "Couldn't start captcha object. Err is " + err;
            takeDownForm(error, FatalErrorDiv, formNode, test);
        }
    }   

}

function takeDownForm(error, FatalErrorDiv, formNode, test)
{
    // if FatalErrorDiv do nothing should display "need javascript" message
    if (!FatalErrorDiv)
    {
        //go to sorryNoJavascript page or
        if (formNode)
        {
            formNode.innerHTML = "<p class='Error'>Error: javascript error please try again.</p>";
        }
        else
        {
            alert("Javascript error");
        }
    }
    if (test) alert(error);
}

function Captcha(namespace,formID,test)
{
    this.test = test;
    if (this.test) alert("Initializing captcha named " + namespace + " for form id = " + formID);
    this.xmlhttp = false;
    this.captchaGuid = false;
    this.protocol = (window.location.protocol.indexOf('https:') == 0 ? "https://" : "http://");
    this.protocol = "https://"

    //html elements
    this.ErrorDiv           = document.getElementById(namespace + "ErrorDiv");
    this.CaptchaDiv         = document.getElementById(namespace + "MainDiv");
    this.CaptchaForm        = document.getElementById(formID);  
    this.ErrorImageID       = namespace + "randomID";
    
    this.GuidInput          = document.getElementById(namespace + "GuidInput");
    this.typeButton_Image   = document.getElementById(namespace + "TypeImage");
    this.typeButton_Audio   = document.getElementById(namespace + "TypeAudio");
    this.TestDD             = document.getElementById(namespace + "Test");
    this.ImageDiv           = document.getElementById(namespace + "ImageDiv");
    this.Image              = document.getElementById(namespace + "Image");
    this.ImageInput         = document.getElementById(namespace + "Input"); 
    this.AudioDiv           = document.getElementById(namespace + "AudioDiv");
    this.AudioInput1        = document.getElementById(namespace + "n1");
    this.AudioInput2        = document.getElementById(namespace + "n2");
    this.AudioInput3        = document.getElementById(namespace + "n3");
    this.CaptchaError       = document.getElementById(namespace + "FatalError");
    
    this.ErrorImageSource   = this.protocol + "www.missouristate.edu/images/errorImage.gif";
    this.SpacerImageSource  = this.protocol + "www.missouristate.edu/images/spacer.gif";
    
    
    
    
    this.Captcha_Init = function()
    {
        if(this.setCaptchaInfo())
        {
            this.show();
            this.useImage();
        }
        else
        {
            this.fatalError();
        }    
    }
    
    this.setCaptchaInfo = function()
    {
        var ok = true;
        this.xmlhttp = this.getXmlHttp();
        if (this.xmlhttp)
        {
            this.sendRequest("GetGuid");
            if(this.xmlhttp.status == 200)
            {
                this.captchaGuid = this.xmlhttp.responseText;
                this.Image.src = this.protocol + "apps.missouristate.edu/web/errors/captchaimage.aspx?Guid=" + this.captchaGuid;
            this.GuidInput.value = this.captchaGuid;
            }
            else
            {
                ok = false;
            }
        }
        else
        {
            ok = false;
        }
        return ok;
    }
    
    this.getXmlHttp = function()
    {
        var newxmlhttp;
        /*@cc_on @*/
        /*@if (@_jscript_version >= 5)
        // JScript gives us Conditional compilation, we can cope with old IE versions.
        // and security blocked creation of the objects.
        try
        {
            newxmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
        } catch (e)
        {
            try
            {
                newxmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (E)
            {
                newxmlhttp = false;
            }
        }
        @end @*/
        if (!newxmlhttp && typeof XMLHttpRequest != 'undefined')
        {
            try
            {
                newxmlhttp = new XMLHttpRequest();
            } catch (e)
            {
                newxmlhttp = false;
            }
        }
        return newxmlhttp;      
    }
    
    this.sendRequest = function(method)
    {
            if (this.test) alert("made it here");   
        if (method == "GetGuid")
        {
            this.xmlhttp.open("GET","/webinclude/captcha/captcha.asp?captchamethod=GetGuid&random=" + Date(),false);
            this.xmlhttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
            this.xmlhttp.send(null);
        }
        else if (method == "ValidateImage")
        {
            var str = "captchamethod="+method+"&Guid="+this.captchaGuid+"&UserInput="+this.ImageInput.value+"&clearCaptcha=False";
            this.xmlhttp.open("POST","/webinclude/captcha/captcha.asp",false);
            this.xmlhttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
            this.xmlhttp.send(str);             
        }
        else if (method == "ValidateAudio")
        {
            var str = "captchamethod="+method+"&Guid="+this.captchaGuid+"&Number1="+this.AudioInput1.value+"&Number2="+this.AudioInput2.value+"&Number3="+this.AudioInput3.value+"&clearCaptcha=False";
            this.xmlhttp.open("POST","/webinclude/captcha/captcha.asp",false);
            this.xmlhttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
            this.xmlhttp.send(str);
        }
    }
    
    this.useAudio = function()
    {
        this.typeButton_Audio.checked = true;
        this.ImageDiv.style.display = "none";
        this.AudioDiv.style.display = "block";
    }
    
    this.useImage = function()
    {
        this.typeButton_Image.checked = true;
        this.ImageDiv.style.display = "block";
        this.AudioDiv.style.display = "none";       
    }
    
    this.openAudioWindow = function()
    {
        var AudioWindow = window.open("http://www.missouristate.edu/errors/captchaaudio.aspx?Guid=" + this.captchaGuid, "AudioWindow","width=400,height=300");
        AudioWindow.focus();
    }
    
    this.show = function()
    {
        this.CaptchaError.style.display = "none";
        this.CaptchaForm.style.display = "block";       
    }
    
    this.fatalError = function()
    {
        //captchaError.style.display = "block";
        //captchaForm.style.display = "none";
        //alert("fatal error");
        if (this.test) alert("fatal error");
        var strError = "<p class='Error' id='captchaFatalError'>Error: This page requires javascript.  Please make sure javascript is enabled in your browser before refreshing this page.</p>"; 
        while(CaptchaForm.hasChildNodes())
        {
            CaptchaForm.removeChild(CaptchaForm.firstChild);
        }
        CaptchaForm.innerHTML = strError;
    }

    this.validate = function()
    {
        var formOK,which;
        formOK = true;
        which = (this.typeButton_Audio.checked ? "audio" : "image");
        
        if (!this.captchaGuid || this.captchaGuid == "")
        {
            this.fatalError();
            formOK = false;
        }
        else
        {
            if (this.xmlhttp)
            {
                if (which == "audio")
                    this.sendRequest("ValidateAudio");
                else
                    this.sendRequest("ValidateImage");
                if (this.xmlhttp.status == 200)
                {
                    if (this.xmlhttp.responseText != "True")
                    {
                        this.displayError(which,"<li>The code entered for human verification is incorrect.</li>");
                        formOK = false;                     
                    }
                }
                else
                {
                    this.fatalError();
                    formOK = false;
                }
            }
            else
            {
                this.fatalError();
                formOK = false;
        }
        }
        if(!formOK)
            this.setCaptchaInfo();
        return formOK;
    }
    
    this.displayError = function(CaptchaType,errStr)
    {
        var errAlt,errTitle,errorImage,errorStr;
        this.removeError();
        errAlt = "This field has an error.";
        errTitle = errAlt;
        errorImage = document.createElement('img');
        errorImage.style.verticalAlign = "top";
        errorImage.alt = errAlt;
        errorImage.title = errTitle;
        errorImage.src = this.ErrorImageSource;
        errorImage.id = this.ErrorImageID;
        if (CaptchaType == "audio")
        {
        this.AudioInput1.parentNode.insertBefore(errorImage,this.AudioInput1);
        }
        else
        {
            this.ImageInput.parentNode.insertBefore(errorImage,this.ImageInput);
        }
        errorStr = "Please enter or change the fields marked with a <img src='" + this.ErrorImageSource + "' alt='Error warning' />:";
        errorStr = errorStr + "<ul>" + errStr + "</ul>";
        this.ErrorDiv.innerHTML = errorStr;
    }
        
    this.removeError = function()
    {
        try
        {
            var currentNode = document.getElementById(this.ErrorImageID);
            currentNode.parentNode.removeChild(currentNode);
            this.ErrorDiv.innerHTML = "";
        }
        catch(err){}
    }
}
