﻿
// 4/1/2010 *** Code for processing the Gateway webpage.

var badfield = new Array();         // array of bad-field-format field ids.
var updating = false;               // true if changing existing registration entry
var changedFields = new Array();    // array of changed-field ids.

var theFormFields = "";             // array of all the INPUT and TEXTAREA elements

function doTask(theTask, info){
    // THERE ARE 2 FORMS ON THIS PAGE.
    // Our forms have several buttons we want to use as submit buttons.
    // There is NO actual type=submit button. 
    // Set a flagfield (hidden) to identify the desired task.
    // Then submit form manually.
    // 2nd arg info is optional: a string of info about the task.
    var taskitm = "";
    var taskinfo = "";
    var mask_fields = "";
    var frm = "";
    
    if (typeof(info) != 'undefined') {
        // This is info or a msg for user.
        // Usually sent via the title attribute of the sending HTML entity.
        taskinfo = info;    
    }
    
    if (formCheck(theTask)) {
        // Store the task description for the POST work.
        if (theTask == "register" || theTask.search("updatereg") != -1) {
            mask_fields = ["pemail"];
            taskitm = document.getElementById("persontask");
        }
        else {
            mask_fields = ["email", "password", "newpw", "newpw2"];
            taskitm = document.getElementById("task");
        }
        taskitm.value = theTask;
        
        // Mask interesting fields before POST action to avoid viewability in headers.        
        for (f in mask_fields) {
            maskValue(mask_fields[f], "mask"); 
            hidePretty(mask_fields[f]);
        }
        
        if (theTask == "register" || theTask.search("updatereg") != -1) {
            // Title etc was disabled for all but SEC as LOU. Re-enable for POSTing.
            document.getElementById("title").disabled = ""; 
            document.getElementById("auxtitle").disabled = ""; 
            enableVerifyCheckboxes(true);
            frm = document.getElementById("personForm");
            var coc = document.getElementById("cocid").value;
            if (coc != "") {
                taskitm.value = "updateregcoc";  // task is COC-approval-update
                var pid = document.getElementById("personid").value;
                var tgtpage = "vault_gateway.php"; 
	            var args = "?pid=" + pid + "&coc=" + coc; 
	            frm.action = tgtpage + args;
            }
            
            // Task is register or self-update.
            if (frm) { frm.submit(); }
            return false; 
        }
        
         if (theTask == "uploadpix") {
            // Identify the person we are uploading the person for.
            // This value must be part of the current form being submitted.
            var showing = document.getElementById("personid").value;
            document.getElementById("pixpid").value = showing;
            document.getElementById("pixtask").value = theTask;
            // Note: cannot directly (easily?) upload file using ajax methods.
            // Must use full page post.
            frm = document.getElementById("imageForm");
            if (frm) { frm.submit(); }
            return true; 
         }
        
        if (theTask == "deletereg" || theTask == 'activestatus') {
            var nm = document.getElementById("firstname").value;
            nm += " "+ document.getElementById("surname").value;
            nm += " (" + document.getElementById("callsign").value + ")";
            var askmsg = taskinfo + "\n\n";
            askmsg += 'Confirm task for entry:\n\n ' + nm;
            if (confirm(askmsg)) {
                ajxDoRegJob(theTask);
                return true;
            }
            else {
                return false;
            }   
        }
           
        if (theTask == "login" || theTask == "changepw" ) {
            if (document.getElementById("rememberme").checked) {
                // Save the 'encrypted' forms of the email/password fields.
                switch (theTask) {
                    case "login":
                        setCookieItem('email', 'email');
                        setCookieItem('password', 'password');    
                        break;
                    case "changepw":
                        setCookieItem('newpw', 'password');
                        break;    
                }
            }
            if (theTask == "login") {
                // Get browser-id-info to add to log on the server.
                // testBrowserInfo(); // jkw tester 
                var browser = getBrowserInfo();
                document.getElementById("browser").value = browser;
            }
        }
        
        frm = document.getElementById("adminForm");
        if (frm) { frm.submit(); }
        return true; 
    }
    return false;
}

function formCheck(theTask) {
    // Validate that required form fields are filled.
    // NOTE: different sections of form have different fields.
    var passed = true; // default to all-ok
    var myobj;
    var reqmsg = "The highlighted fields are required.\n\n";
    var errmsg = "";
    var f; 
    var required_fields = makeFieldArray(theTask);
    
    // Verify that the minimum fields are filled in. Highlight error fields.
    for (f in required_fields) {
        myobj = document.getElementById(required_fields[f]);
        switch(myobj.nodeName) {
            case "SELECT": // a pull-down field.
                var theVal = "";
                if (myobj.selectedIndex >= 0) {
                    theVal = myobj.options[myobj.selectedIndex].text;
                }
                if ( (theVal == "") || (theVal.search("Home ") != -1) || (theVal.search("Select ") != -1) && (theVal != 'N/A')) {
                    passed = false;
                    myobj.style.backgroundColor = clrHighlight; 
                }
                break;
            case "INPUT":  // a user-entry textbox field.
                if (myobj.value.trim() == "") {
                    passed = false;
                    myobj.style.backgroundColor = clrHighlight; 
                }
                break;
        }
    }
    
    if (!passed) {
        errmsg += reqmsg;
    }
    
    // Choosing N/A for county is used only for special registrations.
    // Test validity.
    var ttext = "";
    var ctext = "";
    var tobj = document.getElementById("title");
    var cobj = document.getElementById("county");
    if (tobj) { ttext = tobj.options[tobj.selectedIndex].text; }
    if (cobj) { ctext = cobj.options[cobj.selectedIndex].text;}
    if (ctext == "N/A" && ttext != "ASEC Other" ) {
        var call = document.getElementById("callsign").value;
        var cmtobj = document.getElementById("comments");
        var cmts = cmtobj.value;
        var code = call+"/ASECOTHER";
        var fixme = new RegExp(code, "i");
        if (cmts.search(fixme) != -1) {
            // We have the special code to allow ASEC Other registration.
            // All other new registrations are forced to title 'ARES Member'
            cmtobj.value = cmts.replace(fixme, ""); // blank out the code
            
            for (var i = 0; i < tobj.options.length; i++) {
                if (tobj.options[i].text == 'ASEC Other') {
                    tobj.options[i].className = '';
                    tobj.selectedIndex = i;
                }
            }
        }
        else {
            passed = false;
            //tobj.style.backgroundColor = clrHighlight;
            cobj.style.backgroundColor = clrHighlight;
            errmsg += "The selection 'N/A' for County is not allowed in this context.\n";
            errmsg += "Select a different County.\n\n";
        }
    }
    
    // Another special case. 1/16/2011
    if (theTask == 'updatereg' && theTask == 'register') {
        var multco = document.getElementById("multyes").checked;
        if (multco == 1) {
            var co2obj = document.getElementById("auxcounty");
            if (co2obj.selectedIndex < 1) {
                 passed = false;
                 co2obj.style.backgroundColor = clrHighlight; 
                 errmsg += "When 'multiple counties' is chosen, you must enter a second county.\n";
            }
        }
    }
    
    // Content length/format has been checked for fields with onblur work (if needed).
    // Make sure User has corrected any issues.
    if (badfield.length > 0) {
        errmsg += "The following fields have uncorrected data entry errors:\n\n";
        for (f=0; f< badfield.length; f++) {
            //errmsg += badfield[f][0] + " => " + badfield[f][1] + "\n";
            errmsg += badfield[f][1] + "\n";
        }
        if (errmsg.search('password') != -1) {
            errmsg += msgpw + "\n";
        }
        passed = false;                
    }
    
    if (!passed) {
        showmsgbox(errmsg);
    }
  
    return passed;
}

function showForm(theTask) { 
    // NOTE: this can be called with task="none" to do only the other view-mgmt work.   
    // Possible args (strings):  login  changepw   forgotpw  none
    var f;
    var tt = "";
    var obj = "";
    
    hidemsgbox();
    showPersonForm('none');
    
    // ...........................................................
    // Handle the taskarea form.    
    if (theTask == "none") { 
        document.getElementById("taskarea").className = "baseform hideme";
        badfield.length = 0;  // clear the array ==> if set = "" then is it NO LONGER an array!
        viewArea('logo', 'showme');
        return true;
    }
    
    viewArea('logo', 'hideme');
    obj = document.getElementById("taskarea");
    if (obj) {
        obj.className = "baseform showme";
    
        // Show only current task fields. Hide/show the row in the form table.
        // Hide all fields....
        field_list = makeRowFieldArray("all"); 
        for (f in field_list) {
            document.getElementById(field_list[f]).className = "hideme";
        }
      
        // ... then turn ours on.
        field_list = makeRowFieldArray(theTask);
        for (f in field_list) {
            obj = document.getElementById(field_list[f]);
            if (obj) { obj.className = "showme"; }
        }
        
        // Clear any displayed message.
        var itm = document.getElementById("footer");
        var itmp = itm.getElementsByTagName("p");
        if (itmp.length > 0) {
            // The <p> does not always exist, but there is only one if it does.
            itmp[0].innerHTML = "";
        }

        // Show the right button. Focus task.
        switch (theTask) {
            case "login":
                document.getElementById("btnlogin").className = "showmeinline";
                document.getElementById("email").focus();
                tt = "Login";
                break;
            case "changepw":
                document.getElementById("btnchangepw").className = "showmeinline";
                document.getElementById("newpw").focus();
                tt = "Change Password";
                break;
            case "forgotpw":
                document.getElementById("btnforgotpw").className = "showmeinline";
                document.getElementById("email").focus();
                tt = "Forgot Password";
                break;
            default:
                break;
        }
        
        // Set our Task Title.
        document.getElementById("tasktitle").innerText = tt;   // for IE
        document.getElementById("tasktitle").textContent = tt; // for FF
        
        // 'De-crypt' any munged fields.
        field_list = makeFieldArray(theTask); 
        for (f in field_list) {
            maskValue(field_list[f], "unmask"); 
        }
    }
        
    // Pre-fill any cookies.
    getCookieItems(theTask);
    
    return true;
}

function showadminreset() {
    // SEC/master is logged on and doing admin pw reset: show the special checkbox.
    document.getElementById('adminpwreset').className='showme';
    
    // Also blank out the input field; we don't want any auto-fill here.
    document.getElementById('email').value = '';
    
    return true;
}

function makeFieldArray(theTask){
    // Create an array listing the desired fields. These are html ID values in input fields.
    // Used to determine required fields during validation.
    var fieldArray = new Array();
    
    switch (theTask) {
        case "login":   
            fieldArray = ["email", "password"];
            break;
        case "forgotpw":   
            fieldArray = ["email"];
            break;
        case "changepw":
            fieldArray = ["newpw", "newpw2"];
            break;
        case "register":
        case "updatereg":
            var fa0 = new Array();
            var fa1 = new Array();
            fa0 = ["firstname", "surname", "address", "city", "state", "zip"];
            fa1 = ["pemail", "callsign", "license", "county", "title"];
            fieldArray =  fa0.concat(fa1);
            break;  
        case "uploadpix":   
            fieldArray = ["filename"];
            break;          
        case "all":       
            // not used 11/3/2010 ... so register work not added ....    
            fieldArray = ["email", "password", "newpw", "newpw2", "firstname", "surname", "callsign", "district", "county", "title", "newemail"];
            break;
    }   
    return fieldArray;
}

function makeRowFieldArray(theTask){
    // Create an array listing the desired fields.
    // These are indicated by HTML ID values on the <tr> elements.
    // Used to determine task at hand for presentation display.
    // Don't list buttons in the non-"all" cases. 
    var fieldArray = new Array();
  
    switch (theTask) {
        case "login":   
            fieldArray = ["tremail", "trpassword", "rememberset"];
            break;
        case "forgotpw":   
            fieldArray = ["tremail", "forgotinfo"];
            break;
        case "changepw":
            fieldArray = ["trnewpw", "trnewpw2", "rememberset"]; 
            break;
        case "all":            
            // typically used to hide all 
            var fa0 = new Array();
            var fa1 = new Array();
            var fa2 = new Array();
            fa0 = ["btnlogin", "btnforgotpw", "btnchangepw"];
            fa1 = ["tremail", "trpassword", "trnewpw", "trnewpw2"];
            fa2 = ["rememberset", "forgotinfo","adminpwreset"];
            fieldArray = fa0.concat(fa1, fa2);
            break;
    }   
    return fieldArray;
}

function showPersonForm(theTask, clear) {
    // If arg clear == "clear" then clear the form also.
    // This code shows the form and adjusts buttons based on the TASK (not LOU, PID)
    // It does NOT fill data (see ajax showreg work)
    var ttl = "";
    var obj = "";
    hidemsgbox();
    
    if (clear == undefined) {
        clear = "";
    }
    
    // If 'none' hide all forms.
    if (theTask == 'none') {
        obj = document.getElementById("persontaskarea");
        if (obj) { obj.className = "person hideme"; }
        obj = document.getElementById("taskarea");
        if (obj) { obj.className = "baseform hideme"; }
        // Prevent stray error boxes when close form after partial entry. 
        badfield.length = 0; 
        viewArea('logo', 'showme');
    }
    else {
        // Hide non-register forms. Show register form.
        showForm('none');
        viewArea('logo', 'hideme');
        obj = document.getElementById("persontaskarea");
        if (obj) { obj.className = "baseform person showme"; }
        
        switch (theTask) {
            case "register":
                document.getElementById("btnregister").className = "showme";
                document.getElementById("btndelete").className = "hideme";
                document.getElementById("btnupdate").className = "hideme";
                document.getElementById("auxtitle").disabled = "";
                if (clear == "clear") { clearForm("personForm"); }
                break;
            case "updatereg":
            case "uploadpix":
                // ===> NOTE: there is no --break-- here --> code falls through.
                // Get date info from hidden field & show on form (for self-update)
                var dt = document.getElementById("lastupdateinfo").value;
                if (dt != "") {
                    document.getElementById("lblupdated").className = "showme";
                    document.getElementById("updated").innerHTML = dt;
                }
            case "deletereg":
            case "updateregcoc":
                // disable main title entry - only coc can manipulate
                document.getElementById("title").disabled = "disabled";
                document.getElementById("auxtitle").disabled = "disabled";
                document.getElementById("btnregister").className = "hideme";
                document.getElementById("btndelete").className = "showme";
                document.getElementById("btnupdate").className = "showme";
                document.getElementById("instructions").className = "hideme";
                
                // Set our Task Title.
                var tt = "Update Member Registration";
                document.getElementById("regtitle").innerHTML = tt;  // h4 element
                break;
        }
    }
    
    // Elaborate any multiple-county // second-county info.
    resolveMultCo();
    
    var querystring = window.top.location.search.substring(1);
    if (querystring.search("cocview") != -1) {
        prepCOCViewOnly();
    }
       
    window.scrollBy(0,100);  // scroll vertically 100 pixels: move lower on the screen
    return true;
}

function enableVerifyCheckboxes(forPagePost) {
    // Enable the checkboxes that indicate course verification.
    // Used in context for COC-update, for action work.
    // Used in self-update, after formcheck, so that fields will get POSTed.
    // 
    // NOTE:    The Winlink VERIFY boxes are always DISABLED on this form.
    //          These can be changed ONLY by access to the 'series' Validation page.
    var obj = document.getElementById("training");
    var i;
    var boxes = obj.getElementsByTagName("input");  
    for (i=0; i < boxes.length; i++) {
        if (boxes[i].title.search('Winlink') != -1) {
            // If we are not doing page-post work, skip the Winlink boxes.
            if (!forPagePost)  { continue; }
        }
        if (boxes[i].id.search('vfy') != -1) {
            boxes[i].disabled = "";     // enable
        }
    }
    return true;
}

function showLinks(personrecid, lastupdateinfo, callsign){
    // The User is now logged on. Reveal additional work links...
    document.getElementById("afterlogon").className = "showme";
    
    // ... and hide some.
    document.getElementById("beforelogon").className = "hideme";
    viewArea('logo', 'hideme');
    
    if (personrecid != "" && lastupdateinfo != "" && callsign != "") {
        // Store away this logged on user's Person recID in case they want to update their record.
        document.getElementById("personid").value = personrecid;
        document.getElementById("lastupdateinfo").value = lastupdateinfo;
        
        // Display facts for the user in intro area.
        var shortdate = lastupdateinfo.split(" ")[0];
        document.getElementById("callspot").innerHTML = callsign;
        document.getElementById("lastupdate").innerHTML = "Last update: " + shortdate;
        
        checkLastUpdate(lastupdateinfo);
    }
    return true;
}

function checkLastUpdate(prevUpdate) {
    // If given date is more than a year old, flag this for user to take action.
    // Date is in format: 2010-12-18    yyyy-mm-dd
    var msg = "";
    var txt = "";
    var obj = "";
    
    // Normalize string format to make ALL browsers happy for Date.parse()
    // Tested: IE7, IE8, FF, Chrome.
    var ary = prevUpdate.split("-");
    var olddate = ary[0] + "/" + ary[1] + "/" + ary[2];
    
    // Test against this admin date to issue the update-prompt when new features are added.
    var adminms = Date.parse("January 1, 2012");
    //var adminms = Date.parse("December 20, 2011");
    
    var today = new Date();
    var prevms = Date.parse(olddate);
    var todayms = Date.parse(today);
    
    // Get milliseconds in a year. (A day contains 86,400,000 milliseconds.)
    var duration = (86400000 * 365)/2;
    //txt = "a year";
    txt = "six months";
    
    if (todayms - prevms > duration) {
        msg = "Last update was more than " + txt + " ago.\n";
        msg += "Please verify your information and update it now.";
        obj = document.getElementById("overdue");
        obj.innerHTML = msg;
        obj.className = "overdue showme";
    }
    if (adminms > prevms) {
        //msg = "New features have been added to the Registration form.\n";
        msg = "The Registration form now allows you to ";
        msg += "specify a carrier for receiving text messages.";
        msg += "\nPlease verify and update your information.";
        obj = document.getElementById("overdue");
        obj.innerHTML = msg;
        obj.className = "overdue showme";
    }
    return true;
}

function prepCOCUpdate(pid, coc, isSEC){
    // Used when COC (not logged-on self) is updating member info, or viewing applicant entry.
    document.getElementById("personid").value = pid;
    document.getElementById("cocid").value = coc;
    
    // Show the in/active status button and info.
    var itm = document.getElementById("btnactivestatus");
    if (itm) { itm.className='showme'; }
    itm = document.getElementById("actstatinfo");
    if (itm) { itm.className='showme'; }
    
    return true;
}

function prepCOCViewOnly() {
    // Make the registration form read-only. COC is viewing an applicant.
    var frm = document.getElementById("personForm");
    for(i=0; i < frm.elements.length; i++) {
        var obj = frm.elements[i];
        switch (obj.type) {
            case 'text': 
            case 'textarea':
                 obj.readOnly = true;
                 break;
            case 'radio': 
            case 'checkbox': 
                // jkw IE8 radio button note: (same for IE7)
                // IE8: Clicking an unset button turns OFF any other button in that radio group.
                //      Clicking a set button has the change rejected (good).
                //      Too trivial. Ignore. User cannot implement any changes he scribbles here.
                obj.setAttribute('onclick', "return false;") ;
                break;
            case 'select-one': 
            case 'select-multiple':         // not used here
                // SELECT has no (effective) readOnly attribute.
                // Force any click to keep the same selection.
                var x = obj.selectedIndex;
                obj.setAttribute('onchange', "this.selectedIndex = " + x);
                break;
            case 'button':
                if (obj.value != 'Close') {
                    obj.className = "hideme";
                }
                break;
            case 'submit':                  // not used here
            case 'reset':                   // not used here
                obj.readOnly = true;
                break;              
            case 'hidden':                  // already untouchable
                break;                                   
            default: 
                obj.readOnly = true;
                break;
        }
    }

    document.getElementById("regtitle").innerHTML = "View Registration Application";
    document.getElementById("updated").innerHTML = "Application not yet approved. Viewing readonly.";
    return true;
}

function parsePhone(theID) {
    // put phone numbers into 'normal-form'
    // want xxx-xxx-xxx  or xxx-xxxx
    // elim () around area codes, elim dots for dividers
    // if text is present, do not disturb it.
    var obj = document.getElementById(theID);
    var val = obj.value;
    if (val != "") {
        var tmp = val.replace("(","");
        tmp = tmp.replace(")","-");
        tmp = tmp.replace(/[.]/g,"-");
        tmp = tmp.replace(/-\s/g,"-");
        tmp = tmp.replace(/\s-/g,"-");
        
        // If user put in string of 9 digits with no dividers... fix
        // Make it a nice value to show on reports.
        if ( (tmp.search("-") == -1 ) && (tmp.length == 10 ) ) {
            var a = tmp.substr(0,3);
            var b = tmp.substr(3,3);
            var c = tmp.substr(6,4);
            tmp = a + "-" + b + "-" + c;
        }
    }
    obj.value = tmp;
    
    // Test for 10 digits.
    if (theID == "cellphone") {
        tmp = val.replace(/[^0-9]/g,""); // blank out non-digits
        if (tmp.length > 0 && tmp.length != 10) {
            msg = "Cellphone entries must have 10 digits in order to use them for text messaging. ";
            msg += " Other non-digit parts are also allowed (separator marks and words). ";
            msg += " Non-digits will be blanked out when using the number.";
            showmsgbox(msg);
        }
        if (val.toLowerCase() == 'same') {
            msg = "Using 'same' for cellphone will prevent text messages to this number. ";
            msg += " Please enter the actual number. ";
            showmsgbox(msg);
        }
    }
    
    return true;
}

function checkFormat(theID){
    // Used with onblur when more than length needs checking.
    // Compare checkLength()
    var myregex;
    var msg = "";
    var itm = document.getElementById(theID);
    var ans = true; // default is good
    
    // Clear error conditions & message.
    itm.style.backgroundColor = clrClear;
    hidemsgbox();
    
    // 'Remove' this item from the bad list, if there. It has possibly just been fixed.
    var i;
    for (i = 0; i < badfield.length; i++) {
        if (badfield[i][0] == theID) {
            badfield.splice(i,1);           // removes item 
        }
    }
     
    if (itm.value.trim() == "") {
        // User blanked out the field. This is cool.
        return ans;
    } 
    
    switch (theID) {
        case "callsign":
        /*  REGEX NOTE
            Example and info from the web:
            Password matching expression. Password must be at least 4 characters, no more than 8 characters,
            and must include at least one upper case letter, one lower case letter, and one numeric digit.
                ^(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{4,8}$
            Title: this expression doesnt work in IE 7 (asp lookahead bug)
            Date: 10/1/2010 2:44:27 AM
            The above expression has to be changed to this so that it works in IE 7 and below. 
                ^(?=.{4,8}$)(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).* 
            --> also be sure to test that this disallows spaces !!!                
        */
        
            myregex =  /^(?=\S{4,9}$)(?=.*\d)(?=.*[a-zA-Z\-\\])\S{4,9}$/ ;   // new
            //myregex = /(?=.*\d)(?=.*[a-zA-Z\-\\]){4,9}/ ; // not perfect // orig
            if (itm.value && myregex.test(itm.value) != true) {
                ans = false;
                msg = "Callsign must be 4-9 characters long, no spaces, using at least 1 digit, at least 1 letter, and possibly the - and / symbols.\n\n";
            }        
            break;
        case "pemail":
        case "email":
            if (!validate_email(itm.value)){
                ans = false;
                msg = "The email is not in a valid format.\n\n";
                msg += emailmsg;
            }
            break;  
        case "password":
        case "newpw":
        case "newpw2":
            if (!validate_password(itm.value)){
                ans = false;
                msg = "The password is not in a valid format.\n\n";
				msg += msgpw;
            }
            break;  
        case "zip":
            if (itm.value.length < 5) {
                ans = false;
                msg = "The zipcode must be at least 5 characters long.\n\n";
            }
            break;                
        default:
            break;
    }
    
    if (!ans) {
        itm.style.backgroundColor = clrHighlight; 
        showmsgbox(msg);
        var errinfo = new Array(theID, msg);
        badfield.push(errinfo); // used later in formcheck for final validation
    }
    return ans;
}

function checkLength(theID, theMax) {
    // Used with onblur when only the length needs checking.
    // Compare checkFormat()
    var maxlen = 0;
    switch (theMax) {
        case "large":
            maxlen = 100;
            break;
        case "medium":
            maxlen = 35;
            break;
        case "small":
            maxlen = 10;
            break;
        default:
            maxlen = 255;
            break;
    }
     var itm = document.getElementById(theID);  
     hidemsgbox(); 
     if (itm.value.length > maxlen) {
        showmsgbox("Entry too long. Max characters allowed: " + maxlen);
        return false;
     }
     return true;
}

function resolveMultCo() {
    // Based on user choice for one/many counties, show/hide various fields.
    // 'secondcounty' is the DIV, not the SELECT
    
    var querystring = window.top.location.search.substring(1);
    if (querystring.search("cocview") != -1) {
        // This is readonly work; do nothing.
        return;
    }
    
    var obj = document.getElementById('multyes');
    if (obj) {
        if (obj.checked) {
            document.getElementById('secondcounty').className = "showme";
            
            var xt = document.getElementById('auxtitle');
            if (xt.selectedIndex <= 0 ) {
                // Nothing is already selected, so default 2nd title to ARES Member.
                // Pre-fill but disable.
                reselectPulldown('auxtitle', '', 'ARES Member'); 
                document.getElementById('auxtitle').disabled = "disabled";
            }
        }
        else {
           document.getElementById('secondcounty').className = "hideme";
        }
    }
}

function getRegFormFields() {
    // Build an array of all the input and textarea fields on the form. IN ORDER.
    // Also include SELECT boxes.
    // Do in 2 paired-groups to keep the order correct.
    // This code works if for each treated DIV: 
    //      all <input> fields are first, then all <selects> then <textareas>
    //
    
    // Do this work only once; then just reference it.
    if (theFormFields.length > 0) { 
        return theFormFields;
    }
    
    var fields = new Array();
    var i;
    var d;
    var part;
    var elist;
    
    // These are the ids of the DIV elements that have our desired fields.
    //var divlist = new Array("userinfo", "power", "capability", "training" );
    var divlist = new Array("userinfo");
   
    for (d in divlist) {
        part = document.getElementById(divlist[d]);
        if (part) {
            elist = part.getElementsByTagName("input");
            for (i=0; i < elist.length; i++) {
                // "multiple county" radios are out of tab-order -- skip them 
                if (elist[i].id == "multno" || elist[i].id == "multyes" ) {
                    continue;
                }
                fields.push(elist[i].id);
                
            }
            elist = part.getElementsByTagName("select");
            for (i=0; i < elist.length; i++) {
                // "state" is out of order -- skip it
                // it defaults correctly for 99+% of instances...
                if (elist[i].id == "state") {
                    continue;
                }
                fields.push(elist[i].id);
            }
            elist = part.getElementsByTagName("textarea");
            for (i=0; i < elist.length; i++) {
                fields.push(elist[i].id);
            }
        }
    }
    return fields;
}

function preSelectRadio(radioID) {
    // pre-select the given radio button.
    // I.e., set "checked='checked' for it.
    var obj = document.getElementById(radioID);
    if (obj) {
        obj.checked = 'checked';
    }
    return true;
}

function testCourseVer(selfid, partnerid) {
    // User is trying to click 'verify' for a course.
    // selfid = the course-verify ckbox id
    // partnerid = the course-taken ckbox id
    // Only allow verify if taken is also checked.
    var ver = document.getElementById(selfid);
    var crs = document.getElementById(partnerid);
    
    if (ver.checked && !crs.checked ) {
        var msg = "Cannot mark 'verified' for a course not taken.";
        ver.checked = "";
        showmsgbox(msg);
    }
    return true;
}

function testCourseTaken(selfid, partnerid) {
    // User is clicking box for a course taken.
    // selfid = the course-verify ckbox id
    // partnerid = the course-taken ckbox id
    // If unselect course, also unselect verify.
    var crs = document.getElementById(selfid);
    var ver = document.getElementById(partnerid);
    if (!crs.checked) {
        ver.checked = ""; 
    }
}

function showAnyCertification(cert, LOUtitle, specialLOU, LOUrank) {
    // Based on the cert fact given, display certification flags.
    // The cert fact is a coded string: n e c w -- upper vs lower case is meaningful: keep it.
    // The cert fact is in multiple parts: regular course info + course series info.
    // Only do the space-out stuff for regular portion.
    // The emblem portion is a longer string containing HTML.
    
    // Only do positive action; do not turn anything off.
    // ALSO: control who can change the course-verify boxes.

    var i;
    var pos;
    var reg = "";
    var emblem = "";
    var spaced = "";    // To build a spaced-apart string to display.
    if (!LOUtitle)      { LOUtitle = 'none'; }
    if (!specialLOU)    { specialLOU = '0'; }
    if (!LOUrank)       { LOUrank = 'none'; } // lou vs record being changed: higher/lower/self
    
    document.getElementById('certmark').className = 'hideme';
    
    if (cert != "") {
        // Break string into regular + emblem parts.
        pos = cert.indexOf("<");    // use marker at first  <span ....
        if (pos != -1) { 
            reg = cert.substr(0, pos);
            emblem = cert.substr(pos);
        }
        else {
            reg = cert;
        }
    
        if (reg != "") {
            // fancy work for regular part for display
            var clist = reg.split(""); // split each char apart
            for(i=0; i < reg.length; i++) {
	            spaced += clist[i] + ' ';
            }
        }
        
        var result = spaced + emblem;
        document.getElementById('certinfo').innerHTML = result;
        document.getElementById('certmark').className = 'showme';
    }
    
    /* No: 7/24/2011 All validation is now done on the training validation page.
    // Let certain officers change the verify boxes.
    var isOfficer = (LOUtitle=='SEC' || LOUtitle=='DEC' || LOUtitle=='EC');
    if ( specialLOU=='1' || (isOfficer && (LOUrank != 'lower')) ) {
        enableVerifyCheckboxes(false);
    }
    */
    
    return true;
}

function resolveCkBox(theID, pfxlen) {
    // Turn certain boxes on/off based on context.
    // pfxlen is the prefix-length for the element name
    // Used in registration form capability-pick area, and power area.
    
    if (pfxlen == null) { pfxlen = 4; } // default
    
    var box = document.getElementById(theID);   // homewinmor, moblhf, portpactor1, pwrcomm, pwrbatt, etc
    var pre = box.name.substr(0,pfxlen);        // pwr, home, mobl, port
    var main = box.name.substr(pfxlen);         // winmor, hf, pactor1, comm, batt, solar ...
   
    switch (main) {
        case 'pactor23':
            if (box.checked) {
                // Make sure pactor1 is also checked.
                document.getElementById(pre+'pactor1').checked = "checked";
            }
            break;
        case 'comm':
            // A disjoint choice: turn OFF any non-commercial power.
            document.getElementById('pwrbatt').checked = "";
            document.getElementById('pwrsolar').checked = "";
            document.getElementById('pwrgen').checked = "";
            break;
        case 'batt':
        case 'gen':
        case 'solar':
            // A disjoint choice: turn OFF commercial power.
            document.getElementById('pwrcomm').checked = "";
            break ;   
        default:
            break;            
    }
    return true;
}

function removeLimitedViewTitle() {
	// Display of title "ASEC Other" is limited to SEC or user with this title.
	// (Note that DBAdmin is entered as 'ASEC Other')
	// Testing of LOU title has been done; now remove this option from the select.
    // Treat 'title' and 'auxtitle' together here. 
    // Their structure & content are the same so the indexing should be identical.
    // NOTE: Sometimes we need to turn this entry back 'on'...
    //       ... so we want it to exist.
    var box = document.getElementById("title");
    var box2 = document.getElementById("auxtitle");
    var omitstr = 'ASEC Other';
    var i;
            
    for (i = 0; i < box.options.length; i++) {
        if (box.options[i].text == omitstr) {
           box.options[i].className = 'masque';
           //box.options[i].disabled = 'disabled';  // dim but visible
           //box.remove(i);                         // does not exist
        }
        if (box2.options[i].text == omitstr) {
           box2.options[i].className = 'masque';
           //box2.options[i].disabled = 'disabled';
           //box2.remove(i);
        } 
    } 
    return true;
}

function testAllowChanges(theID) {
    // Possibly make this field 'readonly' i.e., disallow changing pulldown.
    // Used for New Registrations, to force title="ARES Member"
    // Criteria: Disallow changes if we are doing a NEW REGISTRATION
    
    var context = document.getElementById("regtitle").innerHTML;
    if (context != 'Register New Member') {
        // updating or coc work ... changes are ok
        return;
    }
    
    var obj = document.getElementById(theID);
    if (obj) {
        // SELECT has no (effective) readOnly attribute.
        // Force any click to keep the same selection.
        obj.selectedIndex = 1; // ARES Member is first in list.
    }
}

function showPicture(info, pixfile){
    // Present the member picture on the registration page.
   	// Picture management ==> search for showPicture()
	// Picture display managed for tasks:
	//		login	//  pw change	// update (self & coc)
	//		showreg //  upload picture
    var obj;
    var tail = "";
        
    // Test context.
    var querystring = window.top.location.search.substring(1);
    if (querystring.search("cocview") != -1) {
        // Viewing applicant data read-only via coc access.
        // Do not show picture.
        return;
    }
    else if (querystring.search("coc=") != -1) {
        // Viewing member data via coc access.
        // Will show picture but not offer change-picture action.
        document.getElementById("pixaction").className="hideme";
    }
    else {
        // Viewing self.
        // Will show picture and offer change-picture action.
        document.getElementById("pixaction").className="showme";
    }
    
    // Show the member picture, if available.
    if (pixfile != "") {
        obj = document.getElementById("memberpix");
        if (pixfile != '../doc_repository/pix_docs/shadow.png') {
            // Build unique tail-argument for pix to avoid caching.
       	    // Find-all 'tail-argument' to see uses.
            var dt = new Date();
            var msecs = Date.parse(dt);  // gives milliseconds since 1/1/70
            tail = "?"+msecs.toString();
        }
        obj.src = pixfile+tail;
        obj.className = 'showme';
    }
    document.getElementById("photo").className="showme";
    
    // Show any status message. Do not alter any existing message here.
    if (info != "") {
        obj = document.getElementById("gatestatus");
        obj.innerHTML = info; // <p>
	    var cn = obj.className.replace("hideme", "showme");
	    obj.className = cn;
	}
}

function refreshAndMaintain(pid, info, pixfn) {
    // Show new picture after user pix update.
    // Set new control fields, and re-POST page.
    document.getElementById("pixtask").value = "statuspix";
    document.getElementById("pixpid").value = pid;
    document.getElementById("pixfile").value = pixfn;
    document.getElementById("pixinfo").value = info;
    
    var frm = document.getElementById("imageForm");
    if (frm) { frm.submit(); }
    return false; 
}

function cleanUp() {
    // Clear or hide special areas. Probably at logout time.
    viewArea('pickfile','hideme');
    viewArea('photo', 'hideme');
    return true;
}

function showLegend(itm) {
    // Shows the interpretation for this instance of the merit code.
    showmsgbox(document.getElementById(itm).title);
    return true;
}

