//  validate1.js

/* String::trim()
 * Removes whitespace chars from left & right.
 * 'prototype' = it's a way of adding your own custom methods to both object types, and to primitives (strings, numbers)
 * Below we are creating a trim function for the String object
 */
String.prototype.trim = function(){ return this.replace(/(^\s+)|\s+$/g,"")};

function validate(form)
{
    /* parameters --------------------------------------------- */
    var mess_noSubjectChosen = "Please choose a subject for the letter.";
    var mess_unFilledInputs  = "If you have left any of the fillable form fields blank,\nyour letter will not be complete.\nPlease review the missing parts in the document \nwhich you may now save to your computer.";
    var unFilledHilite       = "#f0f8ff"; // light blue ("" for no hilite)    
    // what input types to test for filled (regexp.)
		// below syntax is a shortcut for new RegExp("text","i")
    var types = /text/i;
    /*-----------------------------------------------------------*/
    
    /* shortcuts */
    var elements = form.elements;
    var subject  = elements.subjectLetter;
    
    /*  __Required input__
     *  Make sure they enter a letter subject.
     *  If not:
     *  - scroll element into view
     *  - stop function; do not submit form
     */
    if (subject && !subject.value.trim())
    {
        alert(mess_noSubjectChosen);
        if(subject.scrollIntoView)// IE-only
            subject.scrollIntoView();
        return false;
    }
    
    /*  __Test for unfilled inputs__
     *  Loop elements to find unfilled.
     *  Filter with 'types' regexp.
     *  If unfilled found:
     *  - set allFilled = false
     *  - set BG color to hilite
     *  Else
     *  - remove BG color (maybe set previously)
     *
     *  Set input's value to trimmed value.
     */
    var elm, k=0, value, allFilled=true;
    while(elm=elements[k++])
    {
        if( types.test(elm.type)) 
        {
            value = elm.value.trim();
            if(!value)
            {
                allFilled = false;
                elm.style.backgroundColor = unFilledHilite; 
            }
            else
                elm.style.backgroundColor = "";
                
            elm.value = value;
        }
    }
    
    /*  If !allFilled, launch confirm box.. 
     *  'OK'     --> true:  submit form.
     *  'Cancel' --> false: don't submit 
     */
    if(!allFilled)
        return alert(mess_unFilledInputs) ;
    // Otherwise submit.
    return true;
    

}