/*****************************************************************************************
 * This function finds a form object in the document
 *     Taken from Dreamweaver Ultradev Code Snippets
 *****************************************************************************************/
function findObj(theObj, theDoc)
{
  var p, i, foundObj;

  if(!theDoc) theDoc = document;
  if( (p = theObj.indexOf("?")) > 0 && parent.frames.length)
  {
    theDoc = parent.frames[theObj.substring(p+1)].document;
    theObj = theObj.substring(0,p);
  }
  if(!(foundObj = theDoc[theObj]) && theDoc.all) foundObj = theDoc.all[theObj];
  for (i=0; !foundObj && i < theDoc.forms.length; i++)
    foundObj = theDoc.forms[i][theObj];
  for(i=0; !foundObj && theDoc.layers && i < theDoc.layers.length; i++)
    foundObj = findObj(theObj,theDoc.layers[i].document);
  if(!foundObj && document.getElementById) foundObj = document.getElementById(theObj);

  return foundObj;
}

    /*************************************************************************************
     *  First, leading and trailing spaces are removed from the string in a couple of statements.
     *  Build a regular expression statement that will find one or more starting white space characters
     * (space, tab, form feed, or line feed), then any character (\W\w ends up being anything),
     * then one or more ending white spaces after a word boundary. If that pattern is found in the
     * input string, maintain only the middle characters (the \W\w part).
     *
     * To trim interior consecutive spaces, set up the regular expression object to hold two spaces
     * (var obj = /  /g; has 2 spaces). While 2 spaces is somewhere in the string, replace all consecutive
     * spaces with a single space. This only does one pass through, so if there were 3 consecutive spaces,
     * it would replace the first 2 with a single space and end up with 2 spaces still.
     * So the while loop is necessary.
     *        var obj = /  /g;      //To remove interior spaces
     *        while (temp.match(obj)) { temp = temp.replace(obj, " "); }
     *
     *************************************************************************************/
    function trim(value)
    {
       var temp = value;
       var obj = /^(\s*)([\W\w]*)(\b\s*$)/;
       if (obj.test(temp)) { temp = temp.replace(obj, '$2'); }
       return temp;
    }

    /*************************************************************************************
     *  Another way to accomplish the replacing of interior multiple spaces is to replace all
     * instances of one or more spaces with a single space. So if there already is one space,
     * it will be replaced with one space. But if there are 2 or more consecutive spaces,
     * all will be replaced with 1 space.

     * However, if the string is just a line of spaces, then this results in a single space,
     * so an additional check needs to be made.
     *************************************************************************************/
    function trimAllExtraSpaces(value)
    {
       var temp = value;
       var obj = /^(\s*)([\W\w]*)(\b\s*$)/;
       if (obj.test(temp)) { temp = temp.replace(obj, '$2'); }
       var obj = / +/g;
       temp = temp.replace(obj, " ");
       if (temp == " ") { temp = ""; }
       return temp;
    }

    /*************************************************************************************
     *  Select the current item in the Drop Down List Box - based on value
     *      returns -1 if not found
     *************************************************************************************/
    function selectDropDownValue(inValue, inObject)
    {
        var optionCounter;
        var currObj;

        /* Try to find first based on value */
        currObj = findObj(inObject);
        if (currObj)
        {
            for (optionCounter = 0; optionCounter < currObj.length; optionCounter++)
            {
                if (inValue == currObj.options[optionCounter].value)
                {
                    currObj.selectedIndex = optionCounter;
                    return optionCounter;
                }
            }
        }

        return -1;
    }

    /*************************************************************************************
     *  Select the current item in the Drop Down List Box - based on value
     *      returns -1 if not found
     *************************************************************************************/
    function selectDropDownValueExplicit(inValue, inObject)
    {
        var optionCounter;
        var currObj;

        /* Try to find first based on value */
        currObj = inObject;
        if (currObj)
        {
            for (optionCounter = 0; optionCounter < currObj.length; optionCounter++)
            {
                if (inValue == currObj.options[optionCounter].value)
                {
                    currObj.selectedIndex = optionCounter;
                    return optionCounter;
                }
            }
        }

        return -1;
    }


    /*************************************************************************************
     *  Select the current item in the Drop Down List Box - based on text
     *************************************************************************************/
    function selectDropDownText(inValue, inObject)
    {
        var optionCounter;
        var currObj;

        /* Try to find next based on text */
        currObj = findObj(inObject);
        if (currObj)
        {
            for (optionCounter = 0; optionCounter < currObj.length; optionCounter++)
            {
                if (inValue == currObj.options[optionCounter].text)
                {
                    currObj.selectedIndex = optionCounter;
                    return optionCounter;
                }
            }
        }

        return -1;
    }

    /*************************************************************************************
     *  Select the current item in the Drop Down List Box - based on text
     *************************************************************************************/
    function selectDropDownTextPartial(inValue, inObject)
    {
        var optionCounter;
        var currObj;

        /* Try to find next based on text */
        currObj = findObj(inObject);
        if (currObj)
        {
            for (optionCounter = 0; optionCounter < currObj.length; optionCounter++)
            {
                textval = currObj.options[optionCounter].text
                if (textval.indexOf(inValue)!=-1)
                {
                    currObj.selectedIndex = optionCounter;
                    return optionCounter;
                }
            }
        }

        return -1;
    }

/*****************************************************************************************
 * This function validates alphanumeric fields
 *****************************************************************************************/
function validateAlphaField(inField, inFieldName)
{
    if (inField.value == ""  ||                     //Check for no value
        inField.value.match(/\S/) == null)          //Check for only spaces
    {
        alert("Please Provide a Valid " + inFieldName + "\n" +
              "A blank field or all spaces not allowed.");
        inField.select();
        inField.focus();
        return false;
    }

    return true;
}

/*****************************************************************************************
 * This function validates integer fields >= 0
 *****************************************************************************************/
function validateIntegerPos(inField, inFieldName)
{
    if (inField.value == ""  ||                     //Check for no value
        inField.value.match(/\D/) != null  ||       //Check for non-digit
        inField.value < 0)                          //number must be > =0
    {
        alert("Please Provide a Valid " + inFieldName + "\n" +
              "This number must be zero or greater.");
        inField.select();
        inField.focus();
        return false;
    }

    return true;
}

/*****************************************************************************************
 * This function validates integer fields >= 0
 *****************************************************************************************/
function validateIntegerPosAmount(inField, inFieldName, inAmount)
{
    if (inField.value == ""  ||                     //Check for no value
        inField.value.match(/\D/) != null  ||       //Check for non-digit
        inField.value < inAmount)                   //number must be > amount
    {
        alert("Please Provide a Valid " + inFieldName + "\n" +
              "This number must be " + inAmount + " or greater and must be a whole dollar amount.");
        inField.select();
        inField.focus();
        return false;
    }

    return true;
}

/*****************************************************************************************
 * This function validates integer fields >= 0 (or blank)
 *****************************************************************************************/
function validateIntegerPosBlank(inField, inFieldName)
{
    if (inField.value.match(/\D/) != null  ||       //Check for non-digit
        inField.value < 0)                          //number must be > =0
    {
        alert("Please Provide a Valid " + inFieldName + "\n" +
              "This number must be blank, zero, or greater.");
        inField.select();
        inField.focus();
        return false;
    }

    return true;
}

/*****************************************************************************************
 * This function validates integer fields >= 0
 *****************************************************************************************/
function validateIntegerPosNeg(inField, inFieldName)
{
    if (inField.value.match(/^-?\d\d*$/) == null)
    {
        alert("Please Provide a Valid " + inFieldName + "\n" +
              "This number must be a valid integer.\nEnter a negative, zero, or positive number.");
        inField.select();
        inField.focus();
        return false;
    }

    return true;
}

/*************************************************************************************
 *  Respond to Form Selection
 *************************************************************************************/
function checkTextBoxLength(inLength, inField)
{
    var newField;   //Used for editing quotes

    if (inField.value.length > inLength)
    {
        alert("There is a limit of " + inLength + " characters allowed for this text field.\n" +
              "Please limit your description or contact the webmaster to have this limit increased.\n\n" +
              "The first " + inLength + " characters of your description is:\n" +
              inField.value.substr(0,inLength) );
        inField.select();
        inField.focus();

        return false;
    }

    //newField = inField.value.replace(/[\"]/g, "&quot;");    //replace all quotes
    //inField.value = newField;

    return true;
}

/*****************************************************************************************
 * This function validates phone number fields
 *****************************************************************************************/
function validatePhoneField(inField, inFieldName)
{
    var newPhone;   //Used for temporary phone that is just digits

    newPhone = inField.value.replace(/[\-\(\)\ \\\/]/g, "");    //remove: '-() \/' these chars
    if (newPhone.match(/^\d{10}(X\d{4})?$/) == null &&  //if not exactly 10 digits (anchor to line start and end)
        inField.value != "")                            //if not empty
    {
        alert("Please Provide a Valid " + inFieldName + ", including area code, or leave blank.\n" +
              "Phone extensions can be used by adding X1234 after first 10 digits.");
        inField.select();
        inField.focus();
        return false;
    }

    return true;
}

/*****************************************************************************************
 * This function validates Email fields
 *****************************************************************************************/
function validateEmailField(inField, inFieldName)
{
    if (inField.value == ""  ||                     //Check for no value
        inField.value.match(/\s/) != null  ||       //spaces not allowed
        inField.value.match(/([\w\-\_]+@[\w\-\_]+\.[\w\-\_]+)/) == null)  //Email check
                //Old match statement: /(\w+@\w+\.\w+)/
               //must have word (1+), @ (exactly 1), word (1+), . (exactly 1), word (1+)
               //New match - /(^[\\w-_\.]*[\\w-_\.]\@[\\w]\.+[\\w]+[\\w]$)/
               //   ^ and $ are left and right boundaries, add in dash underscore and dot
               //   \\w instead of the normal \w was added by http://www.4guysfromrolla.com/webtech/052899-1.shtml
    {
        alert("Please Provide a Valid " + inFieldName + ".");
        inField.select();
        inField.focus();
        return false;
    }

    return true;
}

/*****************************************************************************************
 * This function validates database query fields
 *****************************************************************************************/
function validateDBField(inField, inFieldName)
{
    if (inField.value.length > 0 && inField.value.match(/[^a-zA-Z0-9\ \-\+\%\?\_\*\.\(\)\!\,]/) != null)
    {
        alert("Please Enter a Valid Search String For " + inFieldName + ".\n\n" +
              "This character is not allowed -->" + inField.value.match(/[^a-zA-Z\ \-\+\%\?\_\*\.\(\)\!\,]/) + "<--\n\n" +
              "Upper and lower case letters, numbers, spaces, and\n" +
              "the following characters are only allowed:\n\n" +
              "    %\t(Wildcard for 0 to unlimited characters)\n" +
              "    _\t(Wildcard for 1 character placeholder)\n" +
              "    \t+ - ? * . ( ) ! ," );
        inField.select();
        inField.focus();
        return false;
    }

    return true;

}

/*****************************************************************************************
 * This function validates text box fields (no double quotes allowed)
 *****************************************************************************************/
function validateTextBoxField(inField, inFieldName)
{
    if (inField.value.length > 0 && inField.value.match(/[^a-zA-Z0-9\ \-\+\%\?\_\*\.\(\)\!\,\'\#\$]/) != null)
    {
        alert("Please Enter a Description For " + inFieldName + ".\n\n" +
              "This character is not allowed -->" + inField.value.match(/[^a-zA-Z\ \-\+\%\?\_\*\.\(\)\!\,\'\#\$]/) + "<--");
        inField.select();
        inField.focus();
        return false;
    }

    return true;

}

/*****************************************************************************************
 * This function validates text box fields (no double quotes allowed)
 *****************************************************************************************/
function validateTextBoxFieldNoQuotes(inField, inFieldName)
{
    if (inField.value.length > 0 && inField.value.match(/[\"]/) != null)
    {
        alert("Please Enter a Description For " + inFieldName + ".\n\n" +
              "This character is not allowed -->" + inField.value.match(/[\"]/) + "<--");
        inField.select();
        inField.focus();
        return false;
    }

    return true;

}

/*****************************************************************************************
 * This function validates Userid and Password fields
 *****************************************************************************************/
function validateUserPwdField(inField, inFieldName)
{
    if (inField.value == ""  ||                     //Check for no value
        inField.value.match(/^\S{5,20}$/) == null)  //5-20 characters only
    {
        alert("Please Provide a Valid " + inFieldName + ".\n" +
              "Enter 5 - 20 numbers or letters of your choice. (No spaces)");
        inField.select();
        inField.focus();
        return false;
    }

    return true;
}


/*****************************************************************************************
 * This function validates drop-down listbox fields
 *****************************************************************************************/
function validateDropDownField(inField, inFieldName)
{

    if (inField.selectedIndex == 0)
    {
        if ( inFieldName.substring(0,1) == "A" || inFieldName.substring(0,1) == "a" ||
             inFieldName.substring(0,1) == "E" || inFieldName.substring(0,1) == "e" ||
             inFieldName.substring(0,1) == "I" || inFieldName.substring(0,1) == "i" ||
             inFieldName.substring(0,1) == "O" || inFieldName.substring(0,1) == "o" ||
             inFieldName.substring(0,1) == "U" || inFieldName.substring(0,1) == "u"
           )
          alert("Please Select an " + inFieldName + ".");
        else
          alert("Please Select a " + inFieldName + ".");
        inField.options.focus();
        return false;
    }

    return true;
}

/*****************************************************************************************
 * This function validates drop-down listbox fields
 *****************************************************************************************/
function validateNoneSelected(inField, inFieldName)
{

    if (inField.selectedIndex == -1)
    {
        alert("Please Select a " + inFieldName + ".");
        inField.options.focus();
        return false;
    }

    return true;
}

/*****************************************************************************************
 * This function validates State Codes
 *****************************************************************************************/
function checkState(check) {
    var states  = "ALAKAZARCACOCTDEDCFLGAHIIDILINIAKS";
        states += "KYLAMEMDMAMIMSMNMOMTNENMNVNHNJNMNY";
        states += "NCNDOHOKORPARISCSDTNTXUTVTVAWAWVWIWY";

    // If the string is found in an even position, the state is valid.
    return (0 == (states.indexOf(check) % 2));

}


/*****************************************************************************************
 * This function validates money fields
 *****************************************************************************************/
function validateCreditCardField(inField, inFieldName)
{
    var newField;   //Used for temporary phone that is just digits

    newField = inField.value.replace(/[\-\ ]/g, "");    //remove: '-' these chars and spaces

    if (inField.value == ""  ||                     //Check for no value
        newField.match(/\D/) != null)               //Check for any char other than digit
    {
        alert("Please Provide a Valid " + inFieldName + ".\n" +
              "You must enter a numeric value (spaces and dashes are ignored).");
        inField.select();
        inField.focus();
        return false;
    }

    return true;
}

/*****************************************************************************************
 * This function validates money fields
 *****************************************************************************************/
function validateMoneyField(inField, inFieldName)
{
    var newField;   //Used for temporary phone that is just digits

    newField = inField.value.replace(/[\,\$\ ]/g, "");    //remove: ',$' these chars and spaces

    if (inField.value == ""  ||                     //Check for no value
        newField.match(/\D/) != null)               //Check for any char other than digit
    {
        alert("Please Provide a Valid " + inFieldName + ".\n" +
              "You must enter a numeric value in whole dollar amounts.");
        inField.select();
        inField.focus();
        return false;
    }

    return true;
}

/*****************************************************************************************
 * This function validates numbers that can be blank or contain decimals
 *****************************************************************************************/
function validateDecNumBlank(inField, inFieldName)
{
    var newField;   //Used for temporary phone that is just digits

    newField = inField.value.replace(/[\.]/, "");    //remove: 1 decimal

    if (newField.match(/\D/) != null)                 //Check for any char other than digit
    {
        alert("Please Provide a Valid " + inFieldName + ".\n" +
              "You must enter a valid number.");
        inField.select();
        inField.focus();
        return false;
    }

    //check for just a period (not caught in code above)
    newField = inField.value.replace(/[ ]/g, "");    //remove: ',$' these chars and spaces
    if (newField == ".")
    {
        alert("Please Provide a Valid " + inFieldName + ".\n" +
              "You must enter a valid number.");
        inField.select();
        inField.focus();
        return false;
    }


    return true;
}

/*****************************************************************************************
 * This function validates money fields
 *****************************************************************************************/
function validateCardExpiration(inField, inFieldName)
{
    if (inField.value == ""  ||                     //Check for no value
        inField.value.match(/\s/) != null  ||       //spaces not allowed
        inField.value.match(/^\d{2}\/{1}\d{2}$/) == null)  //Check for valid expiration date
               //must have word (1+), @ (exactly 1), word (1+), . (exactly 1), word (1+)
    {
        alert("Please Provide a Valid " + inFieldName + ".");
        inField.select();
        inField.focus();
        return false;
    }

    return true;
}

/*****************************************************************************************
 * This function was written and provided by Ultimate Survey ASP creator John Fischer
 * http://www.ultimateapps.com/products/ultimatesurvey.asp
 *     Creates a pop-up window for messages
 *****************************************************************************************/
function popup(URL,name,toolbar,scrollbars,location,statusbar,menubar,resizable,width,height,left,top)
{
    var popwin;
    var params = 'toolbar=' + toolbar +
                 ',scrollbars=' + scrollbars +
                 ',location=' + location +
                 ',statusbar=' + statusbar +
                 ',menubar=' + menubar +
                 ',resizable=' + resizable +
                 ',width=' + width +
                 ',height=' + height +
                 ',left=' + left +
                 ',top=' + top;
    popwin = window.open(URL, name, params);
    popwin.focus();
}

/*****************************************************************************************
 * This function was written and provided by Ultimate Survey ASP creator John Fischer
 * http://www.ultimateapps.com/products/ultimatesurvey.asp
 *     Provides true or false answer from questions prompted to user
 *****************************************************************************************/
function confirmAction(message)
{
    if (confirm(message) == true)
    {
        return true;
    }
    else
    {
        return false;
    }
}

/*****************************************************************************************
 * Return value of selected DropDown
 *****************************************************************************************/
function getSelectedDropDownValue(inOption)
{
     return inOption.options[inOption.selectedIndex].value;
}

/*****************************************************************************************
 * Return value of selected DropDown
 *****************************************************************************************/
function getSelectedDropDownText(inOption)
{
     return inOption.options[inOption.selectedIndex].text;
}

/*****************************************************************************************
 * Return array number of selected radion button (or -1 if not found)
 *****************************************************************************************/
function getSelectedRadioButton(inRadio)
{
   if (inRadio[0])
   {
      // if the button group is an array (one button is not an array)
      for (var i=0; i < inRadio.length; i++)
      {
         if (inRadio[i].checked)
            return i
      }
   }
   else
   {
      if (inRadio.checked) { return 0; } // if the one button is checked, return zero
   }

   // if we get to this point, no radio button is selected
   return -1;
}

/*****************************************************************************************
 * Return value of selected radion button (or "" if not found)
 *****************************************************************************************/
function getSelectedRadioButtonValue(inRadio)
{
   var i = getSelectedRadioButton(inRadio);

   if (i == -1)
   {
      return "";
   }
   else
   {
      if (inRadio[i]) // Make sure the button group is an array (not just one button)
      {
         return inRadio[i].value;
      }
      else
      {
         return inRadio.value;    // The button group is just the one button, and it is checked
      }
   }
}

/*****************************************************************************************
 * find index of radio button matching value
 *****************************************************************************************/
function findSelectedRadioButtonValue(inRadio, inValue)
{
   if (inRadio[0]) // Make sure the button group is an array (not just one button)
   {
      // if the button group is an array (one button is not an array)
      for (var i=0; i < inRadio.length; i++)
      {
         if (inRadio[i].value == inValue)
            return i
      }
   }
   else
   {
         if (inRadio.value == inValue)
            return 0
   }

   // if we get to this point, no radio button value matched
   return -1;
}

/*****************************************************************************************
 * This function validates that a radio button was selected
 *****************************************************************************************/
function checkRadio(inField, inFieldName)
{
    if (getSelectedRadioButton(inField) == -1)          //Check if radio button was selected
    {
        alert("Please " + inFieldName);
           if (inField[0]) { inField[0].focus(); }
           else inField.focus();
        return false;
    }

    return true;
}

function validateCBX(inCBX, inFormField)
{

    if (inCBX && inFormField)
    {
        //alert(inCBX.name + ": " + inCBX.checked);
        if (inCBX.checked)
        {
            inFormField.value = 1;
        }
        else
        {
            inFormField.value = 0;
        }
    
        return true;
    }
    else
    {
        return false;
    }


}

function validateCBXtf(inCBX, inFormField)
{

    if (inCBX && inFormField)
    {
        //alert(inCBX.name + ": " + inCBX.checked);
        if (inCBX.checked)
        {
            inFormField.value = "T";
        }
        else
        {
            inFormField.value = "F";
        }
    
        return true;
    }
    else
    {
        return false;
    }


}

/*****************************************************************************************
 * This function loops through all form objects in the current form (parm2)
 * to find elements containing a keyword (parm2) and unchecks the checkboxes
 *****************************************************************************************/
function uncheckBoxesInGroup(inForm, inkeyword, inSelected)
{
  var aLen      = inForm.length;
  var aElements = inForm.elements;

  //Loop through all form elements
  for (var i = 0; i < aElements.length ; i++)
  {
      //Look for element with keyword to found -- if not was to be selected, then blank all not just the ones with the matching value
      if (inForm.elements[i].name.indexOf(inkeyword) > -1 && (inSelected == '' || inForm.elements[i].value == inSelected.value) )
      {
          //alert(inForm.elements[i].name + " " + inForm.elements[i].value + " " + inForm.elements[i].checked);
          inForm.elements[i].checked = false;
      }

  }

  //Check the radio button that was passed to this function to be selected
  if (inSelected != '')
     inSelected.checked = true;

}
