/*
 *****
 * Form and Email Validation
 *
 * @author Sean Unwin stunwin {AT} yahoo {DOT} com
 * @orig_copywrite July 24, 2009
 * @copywrite July 29, 2009
 * @version 1.3
 *****
 */

// Check the form was filled out correctly
// @frm html form name
//@emID html div id for error message display
function validateForm(frm,emID) {
    // create form variables
    var fn=document.forms[frm].txtFName.value;
    var ln=document.forms[frm].txtLName.value;
    var em1=document.forms[frm].txtEmail1.value;
    var em2=document.forms[frm].txtEmail2.value;
    // array to hold error types
    var errArr = new Array();
    
    // first name field is empty
    if (fn=="") {errArr.push(0);}
    // last name field is empty
    if (ln=="") {errArr.push(1);}
    // email field is empty
    if (em1=="") {errArr.push(2);}
    // email confirmation field is empty
    if (em2=="") {errArr.push(3);}
    // email fields don't match
    if (em1!="" && em2!="") {
        if (em1!=em2) {errArr.push(4);}
    }
    // fields are filled correctly so check for legitimate syntax
    if (errArr.length==0) {
        var v = mailCheck(em2);
        if(v==true){errArr.push(5);}
    }
    // call to display error message
    reportBack(errArr,emID,frm);
    
    // do not send the form
    return false;
    
}

// Check for correct syntax of email address
// @str email address
function mailCheck(str) {
    // remove leading and trailing white spaces from email string
    str=str.replace(/^\s*/, '').replace(/\s*$/, '');
    // 'at' symbol
    var at="@";
    
    // location of '@' within email string
    var at_loc=str.indexOf(at);
    // string of local part of email
    var lp = str.substring(0,(at_loc))
    // boolean for local part character verification
    var lp_vct;
    // string of domain (hostname) of email
    var dp = str.substring((at_loc+1),str.length);
    // boolean for local part character verification
    var dp_vct;
    var dotRetVal1;
    var dotRetVal2;
    // error boolean (only require 1 error type for this function)
    var e=false;
    
    // set boolean by calling character verification for local part
    lp_vct=verifyEmailChars(lp,"lp");
    // check if invalid character is used
    if(lp_vct==false){
        e=true;
        return e;
    }
    // perform dot check on local part
    dotRetVal1 = dotCheck(lp,0);
    if(dotRetVal1==true){
        e=true;
        return e;
    }
    // set boolean by calling character verification for domain part
    dp_vct=verifyEmailChars(dp,"dp");
    // check if invalid character is used
    if(dp_vct==false){
        e=true;
        return e;
    }
    // perform dot check on domain part
    dotRetVal2 = dotCheck(dp,1);
    if(dotRetVal2==true){
        e= true;
        return e;
    }
    // check if there is text before the '@'
    if(lp.length==undefined){
        e=true;
        return e;
    }
    
    
    // no errors - returns false
    return e;
}

// Create and display error message if form was filled incorrectly
// @ea error message array containing error codes
// @eid html div id for error message display
// @f html form name
function reportBack(ea,eid,f) {
    // redirect url if no errors were found
    // append the value of requested contact checkbox
    var npg="emailconfirm.php" + "?c=" + document.frmEmailReq.chkContactReq.checked;
    // string to hold error message
    var msg="";
    // string for html line break to be included in returned error message
    var b="<br>";
    
    
    // array for error types is not empty
    if (ea.length!=undefined && ea.length>0) {
        var item;
        // cycle through each error type in array
        for (var n in ea) {
            item = ea[n];
            
            switch (item) {
                // first name field is empty
                case 0:
                    msg+="** Please enter your first name. **";
                    msg+=b;
                    break;
                // last name field is empty
                case 1:
                    msg+="** Please enter your last name. **";
                    msg+=b;
                    break;
                // email field is empty
                case 2:
                    msg+="** Please enter your email address. **";
                    msg+=b;
                    break;
                // email confirmation field is empty
                case 3:
                    msg+="** Please confirm your email address. **";
                    msg+=b;
                    break;
                // email fields don't match
                case 4:
                    msg+="** Your email address does NOT match. **";
                    msg+=b;
                    break;
                // email is not in legitimate format
                case 5:
                    msg+="** Invalid syntax for email address. **"
                    msg+=b;
                    break;
            }
        }
        // display error message
        document.getElementById(eid).innerHTML = msg;
    } else {
        /*
        // no errors so go to next page
        window.location.href=npg;
        */
        
        // process the form
        document.forms[f].submit();
        
    }
    
}
// Validate characters in an email string
// @s string to validate
// @pt string identifying local part (value = lp) or domain part (value = dp) of email address
function verifyEmailChars(s,pt){
    // RegExp string to check for invalid characters (LOCAL PART ONLY)
    // valid characters for local part are -- a-z A-Z 0-9 ! # $ % & ' * + - / = ? ^ _ ` { | } ~
    var lp_isc = /[\w\.!#$%&'*+\-\/=?^_`\{\|\}~]/;
    // RegExp string to check for invalid characters (DOMAIN PART ONLY)
    // valid characters for domain part are -- a-z A-Z 0-9 ! # $ % & ' * + - / = ? ^ _ ` { | } ~
    var dp_isc = /[\w\.\-]/;
    // test valid character depending which part is being called
    var test = (pt=="pt")?lp_isc.test(s):dp_isc.test(s);
    // return the result
    return test;
    
}

// Check that dot is within legitimate bounds
// @stc string to check
// @t type of string (local part = 0, domain part = 1)
function dotCheck(stc,t){
    // dot symbol
    var dot=".";
    // array to hold each instance of a dot
    var dotArr = new Array();
    // error boolean value
    var err;
    
    // place all local part locations of instances of '.' in an array
    for(var c in stc) {
        if(stc.charAt(c)==dot){dotArr.push(c);}
    }
    // check to see if there is a '.' at the begining, end or 2 consecutively
    if(dotArr.length==0 && t==1){
        err=true;
        return err;
    }
    if(dotArr.length!=undefined){
        var y;
        var py;
        // loop through the array
        for(var x in dotArr){
            y=dotArr[x];
            // check if dot is at beginning or end of string
            if(y==0 || y==(stc.length-1)){
                // error found
                err=true;
                return err;
            }
            // string is for domain part
            if(t==1){
                // domain suffix has to be within 2-4 characters in length
                if((y==1) || (y==(stc.length-2)) || (y<(stc.length-5))){
                    err=true;
                    return err;
                }
            }
            // check for consecutive dots in the string
            if(y==(py+1)){
                // error found
                err=true;
                return err;
            }
            // make py a number
            py=parseInt(y);
        }
    }
    
}
