/**********************************************************************
 Function:    trimSpaces
 Purpose:     trims all non-alphanumeric characters from left and right
 Receive:     string to trim
 Return:      trimmed string
**********************************************************************/

function trimSpaces( trimStr ) {
    var index = 0;

    for( i = 0; i < trimStr.length; i++ ) {
        if( trimStr.substr( i, 1 ) != " " ) {
            index = i;
            break;
        } else {
            index = i + 1;
        }
    }

    trimStr = trimStr.substr( index );

    for( i = trimStr.length - 1; i >= 0; i-- ) {
        if( trimStr.substr( i, 1 ) != " " ) {
            index = i;
            break;
        } else {
            index = i - 1;
        }
    }
    
    trimStr = trimStr.substring( 0, index + 1 );
    
    return( trimStr );
}

/**********************************************************************
 Function:    isFloat
 Purpose:     validates for proper float number
 Receive:     number to validate
 Return:      true if proper format, false otherwise
**********************************************************************/

function isFloat( floatNum ) {
        if( !floatNum ) {
                return( false );
        }
        
    if( isNaN( parseFloat( floatNum ))) {
                return( false );
        }

    /*
        // special case
        if( parseFloat( floatNum ) > 0 && parseFloat( floatNum ) < 1 ) {
                // parseFloat( .5 ).toString( ) is "0.5" thus != ".5" when doing comparison
        // in this case, allow the value to be accepted
                return( true );
        } else {
        // "555" = "555", but "555" != "555abc"
                if( parseFloat( floatNum ).toString( ) != floatNum ) {
                        return( false );
                }
        }
        */

        return( true );
}

/**********************************************************************
 Function:    GetFloat
 Purpose:     returns the number
 Receive:     number to validate
 Return:      returns number
**********************************************************************/

function GetFloat( floatNum ) {
        if( !floatNum ) {
                return( 0 );
        }
        
    if( isNaN( parseFloat( floatNum ))) {
                return( 0 );
        }
        
    /*
        // special case
        if( parseFloat( floatNum ) > 0 && parseFloat( floatNum ) < 1 ) {
                // parseFloat( .5 ).toString( ) is "0.5" thus != ".5" when doing comparison
                return( parseFloat( floatNum ));
        } else {
        // "555" = "555", but "555" != "555abc"
                if( parseFloat( floatNum ).toString( ) != floatNum ) {
                        return( 0 );
                }
        }
        */

        
    return( parseFloat(floatNum) );
}

/**********************************************************************
 Function:    isInteger
 Purpose:     validates for proper integer number
 Receive:     number to validate
 Return:      true if proper format, false otherwise
**********************************************************************/

function isInteger( intNum ) {
        if( !intNum ) {
                return( false );
        }
        
    if( isNaN( parseInt( intNum ))) {
                return( false );
        }
        
        if( parseInt( intNum ).toString( ) != intNum ) {
                return( false );
        }
        
        return( true );
}

// FUNCTION: validates a form for all required fields
// RECEIVES: the form object, whether or not to display an error dialog box
// RETURNS: true if all required fields are filled out, false otherwise
function CheckRequiredFields( poForm, bDisplayError )
{
    var arrRequiredFields = new Array( );
    var arrEmailFields = new Array( );
    var arrNumberFields = new Array( );
    var psElementName;
    var firstField;
    var piArrayLength;
    var piChecked;
    
    // loop through all the fields on this form
    for (var i = 0; i < poForm.length; i++) {

        // set the element name
        psElementName = poForm[ i ].name;

        // check if this is a required field prefixed with underscore
        if( poForm[ i ].name.substring( 0, 1 ) == "_" || poForm[ i ].requiredField == true || poForm[ i ].requiredField == "true" ) {

            // check for empty textbox or textarea field
            if( poForm[ i ].type == 'text' || poForm[ i ].type == 'textarea' || poForm[ i ].type == 'password' ) {
                poForm[ i ].value = trimSpaces( poForm[ i ].value );
                if( poForm[ i ].value == "" ) {
                    arrRequiredFields[ arrRequiredFields.length ] = psElementName;

                    if( !firstField ) {
                        firstField = poForm[ i ];
                    }
                }
            }

            // check for non-selected drop down menu
            if( poForm[ i ].type == 'select-one' ) {
                if( poForm[ i ].selectedIndex == 0 ) {
                    arrRequiredFields[ arrRequiredFields.length ] = psElementName;

                    if( !firstField ) {
                        firstField = poForm[ i ];
                    }
                }
            }
        
            // check for non-selected multiple selection box
            if( poForm[ i ].type == 'select-multiple' ) {
                if( poForm[ i ].options[ poForm[ i ].selectedIndex ].value == null ) {
                    arrRequiredFields[ arrRequiredFields.length ] = psElementName;

                    if( !firstField ) {
                        firstField = poForm[ i ];
                    }
                }
            }

            // check for unchecked checkbox
            if( poForm[ i ].type == 'checkbox' ) {
                if( poForm[ i ].checked == false ) {
                    arrRequiredFields[ arrRequiredFields.length ] = psElementName;

                    if( !firstField ) {
                        firstField = poForm[ i ];
                    }
                }
            }
            
            // check for unselected radiobox
            if( poForm[ i ].type == 'radio' ) {
                piArrayLength = poForm[ psElementName ].length;
                piChecked = false;

                if( piArrayLength != 'undefined' ) {
                    for( var k = 0; k < piArrayLength; k++ ) {
                        if( poForm[ i ].checked ) {
                            piChecked = true;
                        }
                        i++;
                    }
                    i--;
                }

                if( !piChecked ) {
                    arrRequiredFields[ arrRequiredFields.length ] = psElementName;

                    if( !firstField ) {
                        firstField = poForm[ i ];
                    }
                }
            }
        }

        if( poForm[ i ].type == 'text' || poForm[ i ].type == 'textarea' ) {
            poForm[ i ].value = trimSpaces( poForm[ i ].value );
            if( poForm[ i ].value != "" ) {
                
                // check for valid e-mail address if e-mail field
                if( poForm[ i ].emailCheck ) {
                    if( !validateEmail( poForm[ i ].value )) {
                        arrEmailFields[ arrEmailFields.length ] = psElementName;
                        if( !firstField ) {
                            firstField = poForm[ i ];
                        }
                    }
                }

                // check for valid number if number field
                if( poForm[ i ].numberCheck ) {
                    if( !isFloat( poForm[ i ].value )) {
                        arrNumberFields[ arrNumberFields.length ] = psElementName;
                        if( !firstField ) {
                            firstField = poForm[ i ];
                        }
                    } else {
                        poForm[ i ].value = GetFloat( poForm[ i ].value );
                    }
                }
            }
        }
    }

    // return error message, if any, back to user
    if( bDisplayError ) {
        var errorMsg = "The form was not submitted because of the error(s) below.\n";
        var fieldName;
        
        if( arrRequiredFields.length > 0 ) {
            errorMsg += "\nThe following required field(s) are empty or have not been selected:\n";

            for( var k = 0; k < arrRequiredFields.length; k++ ) {
                fieldName = GetFieldName( arrRequiredFields[ k ] );
                errorMsg += " - " + fieldName + "\n";
            }
        }

        if( arrEmailFields.length > 0 ) {
            errorMsg += "\nThe following field(s) contain invalid e-mail address formats:\n";
            
            for( var k = 0; k < arrEmailFields.length; k++ ) {
                fieldName = GetFieldName( arrEmailFields[ k ] );
                errorMsg += " - " + fieldName + "\n";
            }
        }

        if( arrNumberFields.length > 0 ) {
            errorMsg += "\nThe following field(s) contain invalid numbers (please do not use comma):\n";
            
            for( var k = 0; k < arrNumberFields.length; k++ ) {
                fieldName = GetFieldName( arrNumberFields[ k ] );
                errorMsg += " - " + fieldName + "\n";
            }
        }

        if( arrRequiredFields.length > 0
         || arrEmailFields.length > 0
         || arrNumberFields.length > 0 ) {
            errorMsg += "\nClick OK to return to the form.";
            alert( errorMsg );
            firstField.focus( );
            return( false );
        }
    }
 
    return( true );
}

// FUNCTION: check that at least and just one field has value
// RECEIVES: whether or not to display an error message
//           field objects
// RETURNS: true at least and just one field has value, false otherwise
function SpecifyOnlyOneField( bDisplayError ) {

    var multipleFieldsEntered = false;
    var fieldEntered = false;
    var fieldsEmpty = true;
    var arrFields = new Array( );
    var firstField = null;

    for( var count = 1; count < SpecifyOnlyOneField.arguments.length; count++ ) {
        if( SpecifyOnlyOneField.arguments[ count ].type == 'text'
         || SpecifyOnlyOneField.arguments[ count ].type == 'textarea' ) {
            SpecifyOnlyOneField.arguments[ count ].value = trimSpaces( SpecifyOnlyOneField.arguments[ count ].value );
            
            if( !firstField ) {
                firstField = SpecifyOnlyOneField.arguments[ count ];
            }
            
            arrFields[ arrFields.length ] = SpecifyOnlyOneField.arguments[ count ].name;
            
            if( SpecifyOnlyOneField.arguments[ count ].value != "" ) {
                
                fieldsEmpty = false;
                if( fieldEntered ) {
                    multipleFieldsEntered = true;
                    break;
                }
                
                fieldEntered = true;
            }
        }
    }

    // return error message, if any, back to user
    if( bDisplayError && ( multipleFieldsEntered || fieldsEmpty )) {

        var errorMsg;
        var fieldName;

        if( fieldsEmpty ) {
            errorMsg = "Please supply a value for ONE of the following fields:\n";
        } else {
            errorMsg = "Please supply a value for ONLY ONE of the following fields:\n";
        }
        
        for( var count = 1; count < SpecifyOnlyOneField.arguments.length; count++ ) {
            fieldName = GetFieldName( SpecifyOnlyOneField.arguments[ count ].name );
            errorMsg += " - " + fieldName + "\n";
        }
        errorMsg += "\nClick OK to return to the form.";
        alert( errorMsg );
        firstField.focus( );
        return( false );
    }
    
    return( true );
}

// FUNCTION: returns the name of the field, without the _ if any
// RECEIVES: the field object
// RETURNS: the field name
function GetFieldName( fieldName ) {
    
    if( fieldName.substring( 0, 1 ) == "_" ) {
        fieldName = fieldName.substring( 1 );
    }
    fieldName = fieldName.replace( /_/g, " " );
    return( fieldName );
}

// FUNCTION: adds the subtotals to the total target field
// RECEIVES: the target field containing the total, all subtotal fields
// RETURNS:
function CalculateTotal( ) {
    
    var total = 0;
    
    // all subtotal fields has to be HTML text fields
    for( var count = 0; count < CalculateTotal.arguments.length; count++ ) {
        if( CalculateTotal.arguments[ count ].type == 'text'
         || CalculateTotal.arguments[ count ].type == 'textarea' ) {
            CalculateTotal.arguments[ count ].value = trimSpaces( CalculateTotal.arguments[ count ].value );
            
    
                if(!(CalculateTotal.arguments[ count ].value == "" || CalculateTotal.arguments[ count ].value == "0")) {
                
                    total += ConvertToNumber( CalculateTotal.arguments[ count ].value );
                    
                }
                // Function call to convert all text field values to dollar amounts
                ConvertToCurrency(CalculateTotal.arguments[ count ]);
        }
    }

    return( total );
}

// FUNCTION: updates a percentage field based on the amount
// RECEIVES: target percentage field
//           amount field
//           total field
// RETURNS:
function UpdatePercentField( percentField, amountField, totalField ) {

    amountField.value = trimSpaces( amountField.value );
    totalField.value = trimSpaces( totalField.value );
    
    if( totalField.value == "" || amountField.value == "" ) {
        percentField.value = "";
        return;
    }

    percentField.value = (( ConvertToNumber( amountField.value ) / ConvertToNumber( totalField.value )) * 100).toFixed(3);
    
    // Function call to convert all text field values to dollar amounts
    ConvertToCurrency( totalField );
    ConvertToCurrency( amountField );
}

// FUNCTION: updates an amount field based on the percent
// RECEIVES: target anount field
//           percent field
//           total field
// RETURNS:
function UpdateAmountField( amountField, percentField, totalField ) {

    ConvertToCurrency(totalField);

    percentField.value = trimSpaces( percentField.value );
    totalField.value = trimSpaces( totalField.value );
    
    if( totalField.value == "" || percentField.value == "" ) {
        amountField.value = "";
        return;
    }

       
    amountField.value = ConvertToNumber( totalField.value ) * ( ConvertToNumber( percentField.value ) / 100 );
    
    
    ConvertToCurrency(amountField);

}

// FUNCTION: add a select option to a select object
// RECEIVES: select object, option text, option value
// RETURNS:
function AddToSelect( selectObject, optionText, optionValue ) {
    var newOption = new Option( optionText, optionValue );
    selectObject.options[ selectObject.length ] = newOption;
}

// FUNCTION: remove all options from a select object
// RECEIVES: select object
//           remove all but the first option if true, otherwise remove all
// RETURNS:
function RemoveAllFromSelect( selectObject, leaveFirst ) {
    if( leaveFirst ) {
        selectObject.length = 1;
    } else {
        selectObject.length = 0;
    }
}

// FUNCTION: concatenate all fields/values together and submit form
// RECEIVES: form object
// RETURNS:
function SubmitForm( formObject ) {
    var tempArray = new Array( );
    var lastFieldName = "";
    for( i = 0; i < formObject.elements.length; i++ ) {
        if( formObject.elements[ i ].type == "text"
         || formObject.elements[ i ].type == "textarea"
         || formObject.elements[ i ].type == "password"
         || formObject.elements[ i ].type == "select-one"
         || formObject.elements[ i ].type == "select-multiple"
         || formObject.elements[ i ].type == "radio"
         || formObject.elements[ i ].type == "checkbox"
         || formObject.elements[ i ].type == "hidden" ) {
            // since all instances of radio buttons are listed, we only want the first one
            if( formObject.elements[ i ].name != lastFieldName ) {
                tempArray.push( formObject.elements[ i ].name );
                lastFieldName = formObject.elements[ i ].name;
            }
        }
    }

    if( typeof( formObject.hidAllFields ) == "undefined" ) {
        alert( "Unable to submit your form at this time. Please contact the System Admin for this web site." )
        return( false );
    }

    formObject.hidAllFields.value = tempArray.join( ";" );

    SaveForm( formObject );

    return( true );
}

// FUNCTION: saves web form using cookies
// RECEIVES: form object
// RETURNS:
function SaveForm( formObject ) {
    var expireDate = new Date( );
    var expireYear = expireDate.getYear( ) + 10;
    expireDate.setYear( expireYear );

    for( i = 0; i < formObject.elements.length; i++ ) {
        if( formObject.elements[ i ].saveValue ) {
            if( formObject.elements[ i ].type == "text" ) {
                setCookie( GetFieldName( formObject.elements[ i ].name ), formObject.elements[ i ].value, expireDate );
            }
            if( formObject.elements[ i ].type == "select-one" ) {
                setCookie( GetFieldName( formObject.elements[ i ].name ), formObject.elements[ i ].selectedIndex, expireDate );
            }
            if( formObject.elements[ i ].type == "radio" ) {
                if( formObject.elements[ i ].checked ) {
                    setCookie( GetFieldName( formObject.elements[ i ].name ), formObject.elements[ i ].value, expireDate );
                }
            }
            if( formObject.elements[ i ].type == "checkbox" ) {
                 setCookie( GetFieldName( formObject.elements[ i ].name ), formObject.elements[ i ].checked, expireDate );
            }
        }
    }

    return( true );
}

// FUNCTION: loads web form saved using cookies
// RECEIVES: form object
// RETURNS:
function LoadForm( formObject ) {
    for( i = 0; i < formObject.elements.length; i++ ) {
        if( formObject.elements[ i ].saveValue ) {
            if( formObject.elements[ i ].type == "text" ) {
                if( getCookie( GetFieldName( formObject.elements[ i ].name )) != null ) {
                    formObject.elements[ i ].value = getCookie( GetFieldName( formObject.elements[ i ].name ));
                }
            }
            if( formObject.elements[ i ].type == "select-one" ) {
                formObject.elements[ i ].selectedIndex = parseInt( getCookie( GetFieldName( formObject.elements[ i ].name )));
            }
            if( formObject.elements[ i ].type == "radio" ) {
                if( formObject.elements[ i ].value == getCookie( GetFieldName( formObject.elements[ i ].name ))) {
                    formObject.elements[ i ].checked = true;
                }
            }
            if( formObject.elements[ i ].type == "checkbox" ) {
                if( getCookie( GetFieldName( formObject.elements[ i ].name )) == "true" ) {
                    formObject.elements[ i ].checked = true;
                }
            }
        }
    }
}

// FUNCTION: concatenates all e-mails into target field
// RECEIVES: fields containing e-mails
// RETURNS:
function AssembleRecipients( ) {
    var tempArray = new Array( );

    for( var count = 0; count < AssembleRecipients.arguments.length; count++ ) {
        if( validateEmail( AssembleRecipients.arguments[ count ] )) {
            tempArray[ tempArray.length ] = AssembleRecipients.arguments[ count ];
        }
    }

    return( tempArray.join( ";" ));
}

/**********************************************************************
 Function:    validateEmail
 Purpose:     validates for proper e-mail address format
 Receive:     email to validate
 Return:      true for proper e-mail address format, false otherwise
**********************************************************************/

function validateEmail( emailStr ) {
    /* The following pattern is used to check if the entered e-mail address
       fits the user@domain format.  It also is used to separate the username
       from the domain. */
    var emailPat=/^(.+)@(.+)$/;
    /* The following string represents the pattern for matching all special
       characters.  We don't want to allow special characters in the address. 
       These characters include ( ) < > @ , ; : \ " . [ ]    */
    var specialChars="\\(\\)<>@,;:\\\\\\\"\\.\\[\\]";
    /* The following string represents the range of characters allowed in a 
       username or domainname.  It really states which chars aren't allowed. */
    var validChars="\[^\\s" + specialChars + "\]";
    /* The following pattern applies if the "user" is a quoted string (in
       which case, there are no rules about which characters are allowed
       and which aren't; anything goes).  E.g. "jiminy cricket"@disney.com
       is a legal e-mail address. */
    var quotedUser="(\"[^\"]*\")";
    /* The following pattern applies for domains that are IP addresses,
       rather than symbolic names.  E.g. joe@[123.124.233.4] is a legal
       e-mail address. NOTE: The square brackets are required. */
    var ipDomainPat=/^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/;
    /* The following string represents an atom (basically a series of
       non-special characters.) */
    var atom=validChars + '+';
    /* The following string represents one word in the typical username.
       For example, in john.doe@somewhere.com, john and doe are words.
       Basically, a word is either an atom or quoted string. */
    var word="(" + atom + "|" + quotedUser + ")";
    // The following pattern describes the structure of the user
    var userPat=new RegExp("^" + word + "(\\." + word + ")*$");
    /* The following pattern describes the structure of a normal symbolic
       domain, as opposed to ipDomainPat, shown above. */
    var domainPat=new RegExp("^" + atom + "(\\." + atom +")*$");


    /* Finally, let's start trying to figure out if the supplied address is
       valid. */
    
    /* Begin with the coarse pattern to simply break up user@domain into
       different pieces that are easy to analyze. */
    var matchArray=emailStr.match(emailPat);
    if (matchArray==null) {
      /* Too many/few @'s or something; basically, this address doesn't
         even fit the general mould of a valid e-mail address. */
        //alert("Email address seems incorrect (check @ and .'s)")
        return false
    }
    var user=matchArray[1];
    var domain=matchArray[2];
    
    // See if "user" is valid 
    if (user.match(userPat)==null) {
        // user is not valid
        //alert("The username doesn't seem to be valid.")
        return false;
    }
    
    /* if the e-mail address is at an IP address (as opposed to a symbolic
       host name) make sure the IP address is valid. */
    var IPArray=domain.match(ipDomainPat)
    if (IPArray!=null) {
        // this is an IP address
          for (var i=1;i<=4;i++) {
            if (IPArray[i]>255) {
                //alert("Destination IP address is invalid!")
                    return false;
            }
        }
        return true;
    }
    
    // Domain is symbolic name
    var domainArray=domain.match(domainPat)
    if (domainArray==null) {
        //alert("The domain name doesn't seem to be valid.")
        return false;
    }
    
    /* domain name seems valid, but now make sure that it ends in a
       three-letter word (like com, edu, gov) or a two-letter word,
       representing country (uk, nl), and that there's a hostname preceding 
       the domain or country. */
    
    /* Now we need to break up the domain to get a count of how many atoms
       it consists of. */
    var atomPat=new RegExp(atom,"g");
    var domArr=domain.match(atomPat);
    var len=domArr.length;
    if (domArr[domArr.length-1].length<2 || 
        domArr[domArr.length-1].length>3) {
       // the address must end in a two letter or three letter word.
       //alert("The address must end in a three-letter domain, or two letter country.")
       return false;
    }
    
    // Make sure there's a host name preceding the domain.
    if (len<2) {
       //alert( "This address is missing a hostname!" )
       return false;
    }
    
    // If we've gotten this far, everything's valid!
    return true;
}

// name - name of the cookie
// value - value of the cookie
// [expires] - expiration date of the cookie (defaults to end of current session)
// [path] - path for which the cookie is valid (defaults to path of calling document)
// [domain] - domain for which the cookie is valid (defaults to domain of calling document)
// [secure] - Boolean value indicating if the cookie transmission requires a secure transmission
// * an argument defaults when it is assigned null as a placeholder
// * a null placeholder is not required for trailing omitted arguments
function setCookie(name, value, expires, path, domain, secure) {
  var curCookie = name + "=" + escape(value) +
      ((expires) ? "; expires=" + expires.toGMTString() : "") +
      ((path) ? "; path=" + path : "") +
      ((domain) ? "; domain=" + domain : "") +
      ((secure) ? "; secure" : "");
  document.cookie = curCookie;
}

// name - name of the desired cookie
// * return string containing value of specified cookie or null if cookie does not exist
function getCookie(name) {
  var dc = document.cookie;
  var prefix = name + "=";
  var begin = dc.indexOf("; " + prefix);
  if (begin == -1) {
    begin = dc.indexOf(prefix);
    if (begin != 0) return null;
  } else
    begin += 2;
  var end = document.cookie.indexOf(";", begin);
  if (end == -1)
    end = dc.length;
  return unescape(dc.substring(begin + prefix.length, end));
}

// name - name of the cookie
// [path] - path of the cookie (must be same as path used to create cookie)
// [domain] - domain of the cookie (must be same as domain used to create cookie)
// * path and domain default if assigned null or omitted if no explicit argument proceeds
function deleteCookie(name, path, domain) {
  if (getCookie(name)) {
    document.cookie = name + "=" + 
    ((path) ? "; path=" + path : "") +
    ((domain) ? "; domain=" + domain : "") +
    "; expires=Thu, 01-Jan-70 00:00:01 GMT";
  }
}

// date - any instance of the Date object
// * hand all instances of the Date object to this function for "repairs"
function fixDate(date) {
  var base = new Date(0);
  var skew = base.getTime();
  if (skew > 0)
    date.setTime(date.getTime() - skew);
}

//Function : Converts numeric data to currency
//Receives: Name of the field, numeric data
//Returns: Currency equivalent of the numeric data
function ConvertToCurrency(fieldName){
 
     var fieldValue ;
     var decimalIndex ;
    
     fieldValue = ConvertToNumber(fieldName.value);
     
    
     if(fieldValue == "") {
         fieldName.value = "";
         return;
     }
                
     if(!(fieldValue == "0" ))
         fieldValue = parseFloat(fieldValue).toFixed(2);
     
     decimalIndex = fieldValue.lastIndexOf(".");
     
     while((!(decimalIndex < 4))) {
         if(!(decimalIndex == 4 && fieldValue.lastIndexOf("-") > -1))
             fieldValue = fieldValue.substring (0, decimalIndex - 3) + "," + fieldValue.substring (decimalIndex - 3, fieldValue.length);
      decimalIndex = decimalIndex - 3;
     }
     
     fieldName.value = fieldValue;
 }

//Function : Converts valid currency to numeric data
//Receives: Currency value
//Returns: Numeric equivalent

function ConvertToNumber(fieldValue) {
    
   
    while(fieldValue.indexOf(",") > 0) {
        fieldValue = fieldValue.substring(0, fieldValue.indexOf(",")) + fieldValue.substring(fieldValue.indexOf(",")+1, fieldValue.length);
    }

    if(isNaN(parseFloat(fieldValue)) || fieldValue == "") {
        return 0;
    }

    if(fieldValue == "0") {
       return "0";
    }
    
    return (parseFloat(fieldValue));

}

//Function : Forms a name value of all the fields
//Receives: form object
//Returns: Name value pairs of all the fields that have values

function FormValues( poForm, paramDelimiter ) {

    var builtQuery = "";
    
    var fieldName = "";
    var fieldValue = "";

    var radioLength = "";

    if( paramDelimiter == "" ) {
        paramDelimiter = "|||";
    }

      
    for(i=0; i < poForm.length; i++) {
        fieldName = poForm[i].name;
        
        if(poForm[i].type == "radio") {
            radioLength = poForm[fieldName].length;
            fieldValue = SetRadio(poForm[fieldName], radioLength);
            i = i + radioLength - 1;
        } else if(poForm[i].type == "checkbox") {
            fieldValue = SetCheckbox(poForm[fieldName]);
        } else {
            fieldValue= poForm[i].value;
        }
        
        if(poForm[i].type == "button") {
           continue;
        } 
        
        if(!(fieldName == "" || fieldValue == "" || fieldName.indexOf( "hid" ) != -1 )) {
            builtQuery = builtQuery + paramDelimiter + fieldName + "=" + fieldValue; 
        }
        
    }
    
    return builtQuery;
}


//Function : Replaces all occurrences of the ols character with the new character
//Receives: The form object
//Returns: Name value pairs of all the fields with values
function FormatOutput(output, oldChar, newChar) {
        
        for(var i=0; i < output.length; i++) {
                output = output.replace(oldChar, newChar);
        }

        return output;
}


/* Function to populate the page values from the temporary hidden variable 
   while navigating back and forth 
*/

function PopulateValues(poForm, pageValues, paramDelimiter ) {

    var fieldTokens = new Array();
    var indivTokens = new Array();

    var fieldName = "";
    var fieldValue = "";

    var fieldType = "";
    var fieldLength = 0;
    var splitIndex = -1;

    if( paramDelimiter == null || paramDelimiter == "" ) {
        paramDelimiter = "|||";
    }

    with(poForm) {
        if (!(pageValues == "")) {
            pageValues = FormatOutput( pageValues, "+", "%20" );
            fieldTokens = unescape( pageValues ).split( paramDelimiter );
            for (var i=0; i<fieldTokens.length; i++) {
    
                splitIndex = fieldTokens[ i ].indexOf( "=" );
                if( splitIndex < 0 ) {
                    continue;   
                }
                fieldName = fieldTokens[ i ].substring( 0, splitIndex );
                fieldValue = fieldTokens[ i ].substring( splitIndex + 1 );
                if (!( fieldName.indexOf("hid") > -1 || fieldName == "" || fieldValue == "")) {
                                        
                    if( poForm[ fieldName ].type == 'text' ) {
                        poForm[ fieldName ].value = fieldValue;
                        continue;
                    }

                    if(poForm[fieldName].type == 'checkbox') {
                        DisplayCheckbox(poForm, fieldName, fieldValue);
                        continue;
                    }

                    fieldLength = poForm[ fieldName ].length;

                    // First check for the element length and then check for the type of the first element
                    if(fieldLength > 1) {
                        if(eval(""+fieldName+"[0].type") == 'radio'){
                            DisplayRadioValue(poForm, fieldName, fieldValue);
                        }
                    }
                }
            }
        }
    
    }
    return true;

 }

/*
  Function to set the hidden radio field when the corresponding radio 
  field is clicked
*/

function SetRadio(fieldObject, fieldLength) {
    
    var fieldChecked;
    var fieldValue = "";

    for(var i=0; i < fieldLength; i++) {
        
        fieldChecked = eval("fieldObject["+i+"].checked");
        
        //alert(i+':'+fieldChecked);
        
        if(fieldChecked == true) {
            fieldValue = fieldObject[i].value;
            //alert(fieldValue);
            break;
        }
    }
    return (fieldValue);

}

/*
  Function to set the hidden Checkbox field to identify the  corresponding Checkbox 
  field is clicked
*/

function SetCheckbox(fieldObject, fieldValue) {
    
    if(fieldObject.checked == true)
        return fieldObject.value;
    else
        return "";
 
}

/*  Function to display the checkbox field as checked if the corresponding hidden 
field is not empty*/

function DisplayCheckbox(poform, fieldName) {
       
    with(poform) {
        
        eval(""+fieldName+".checked =true");
        
    }

}

/*
  Function to set the respective radio field based on the incoming hidden 
field value */


function DisplayRadioValue(poForm, fieldName, fieldValue) {
    
    var originalFieldName = fieldName;
    var originalFieldValue;
    var radioFieldLength;
    
    with(poForm) {
      
        radioFieldLength = eval(""+originalFieldName+".length");
        
        var i = 0;
                        
        while(i < radioFieldLength) {
          
          originalFieldValue =   eval(""+originalFieldName+"["+i+"].value");

          if(originalFieldValue == fieldValue) {
              eval(""+originalFieldName+"["+i+"].checked=true");
              break;

          }
          i++;
        }
              
     }
    
}

/* Function to capture the confirmation from the user to do a load or save operation and then 
   prompt for the e-mail address if it is not already captured
*/

function DisplayConfirmBox(opType, tempMailId) {
    
    var alertMsg = "";
    var mailId = "";
    var errorMsg = "The form was not submitted because of the following error below:\n";
    errorMsg += "The value you have entered contains invalid e-mail address formats\n";

    var promptMsg = "Please enter e-mail address to "+opType.toLowerCase()+" the data and make sure that it matches with the Owner e-mail address in the Contact List - Page 1";

    
    alertMsg = "Are you sure you want to "+opType.toLowerCase()+" the data ?";
    
    if( confirm( alertMsg )) {
        
        // if to check if the mail-id is already entered
        if( tempMailId.value == '' ) {
            mailId = prompt(promptMsg, ' '); 
            
            if( mailId == "" || mailId == null)
                return false;
            else { 
                
                if(!validateEmail( mailId )) {
                    alert(errorMsg);
                    return false;

                } else {

                    tempMailId.value = mailId;

                }
            }
                
        }
        return true;

    } else {

        return false;

    }
} 