// preset.js  Copyright 2009 by Richard L. Trethewey - All Rights Reserved
// Permission is granted to use this code as long as this copyright notice
// is left intact.  For more information, see http://www.rainbodesign.com/pub/

// First, get the query string contents from the URL used by lopping off the "?"

   var query = location.search.substr(1, location.search.length-1);

function findForm(theForm) {
var formCount = document.forms.length;
  if (document.getElementById) { formElement = document.getElementById(theForm); 
    } else {
for (i=0; i<formCount; i++) {
  if (document.forms[i].name == theForm) { formElement = document.forms[i]; }
     } // endFor
  } // endif document.getElementById
  return formElement;
 } // end findForm

function setOption(theOption,choice) {
max = theOption.length;
for (i = 0; i < max; i++) {
   if (theOption.options[i].value == choice) { theOption.options.selectedIndex = i; }
    }  // end for i
} // end setOption

function setRadio(theOption,optionName) {
  max = theOption.length;
   for (i = 0; i < max; i++) {
//    alert(theOption[i].name + ' ' + theOption[i].checked);
    if (theOption[i].value == optionName) { theOption[i].checked = true; }
   }  // end for i
} // end setRadio


function fixQString(theStr) {
  pattern = '\\+';
  flags = 'g';
  reg_exp = new RegExp(pattern, flags);
  theStr = theStr.replace(reg_exp, ' ');
  theStr = unescape(theStr);
  return theStr
} // end fixQStr

function populate(formName) {
  if (query) {                       // Was there a query string?
var params =  query.split("&");      // Yes!  Split them up
var theForm = findForm(formName);    // Locate the form with the correct name/ID
    if (theForm != null) {           // Did we find the form?
     for (q=0; q<params.length; q++) {
      xy = params[q].split("="); // Split the command into name/value pair
      paramName = xy[0];
      newValue = fixQString(xy[1]);
       if (theForm.elements[paramName]) {  // does named element exist?
//   alert(theForm.elements[paramName].type + ' ' + paramName);

       switch(theForm.elements[paramName].type) {
        case 'text':
          theForm.elements[paramName].value = newValue;
        break;

        case 'hidden':
          theForm.elements[paramName].value = newValue;
        break;

        case 'select-one':
          setOption(theForm.elements[paramName], newValue);
        break;

        case undefined:  // a kludge to handle radio buttons
          setRadio(theForm.elements[paramName], newValue);
        break;

        case 'checkbox':
          theForm.elements[paramName].checked = true;
        break;

       } // end switch
      } // endif theForm.elements[paramName]
    } // end for q
   } // endif {theForm)
 } // endif (query)
} // end populate()


