// JavaScript Document

function debug(s)
{
    //------------------------------------------
    // set this to true for debug alert messages.
    //------------------------------------------
    var debug=false;

    if ( debug )
    {
        alert(s);
    }//end if

}

/**
 * Determine if the supplied string contains accent characters
 */
function containsAccentCharacters( s )
{
     debug("*********************\n****[ Evaluating Accent Characters ("+s.length+"]\n*********************\n");
     for (i = 0; i < s.length; i++ )
     {
          debug("===> {"+i+"}["+s.charAt(i)+"=["+s.charCodeAt(i)+"]");
          if ( s.charCodeAt(i) > 127 )
          {
               debug("THIS CHARACTER IS INVALID =>["+s.charAt(i)+"]");
               return true;
          }//end if

     }//end for

     return false;
}//end function

/**
 * Determine if the supplied string is All Numbers
 */
function isNumeric( inputString )
{
     var numbers = "0123456789";
     var s = trim( inputString );
     var c = "";
     for (i = 0; i < s.length; i++ )
     {
          c = s.charAt( i );

          if ( numbers.indexOf(c) == -1 )
          {
               return false;
          }//end if

     }//end for

     return true;


}//end if

function trim(inputString)
{

   // Removes leading and trailing spaces from the passed string. Also removes
   // consecutive spaces and replaces it with one space. If something besides
   // a string is passed in (null, custom object, etc.) then return the input.

   debug("trim=>checking length");
   if ( inputString.length == 0 )
   {
       debug("length is already 0");
       return "";
   }//end if
   var retValue = inputString;

   var ch = retValue.substring(0, 1);
   while (ch == " ")
   { // Check for spaces at the beginning of the string
      retValue = retValue.substring(1, retValue.length);
      ch = retValue.substring(0, 1);
   }//end while

   ch = retValue.substring(retValue.length-1, retValue.length);
   while (ch == " ")
   { // Check for spaces at the end of the string
      retValue = retValue.substring(0, retValue.length-1);
      ch = retValue.substring(retValue.length-1, retValue.length);
   }//end while

   while (retValue.indexOf("  ") != -1)
   {
       retValue = retValue.replace('  ',' ');
/*
       // Note that there are two spaces in the string - look for multiple spaces within the string
      retValue = retValue.substring(0, retValue.indexOf("  ")) + retValue.substring(retValue.indexOf("  ")+1, retValue.length);
      // Again, there are two spaces in each of the strings
*/
   }//end while
   debug("Returning ["+retValue+"]");

   return retValue; // Return the trimmed string back to the user
} //end function: trim



function textCounter(field, countfield, maxlimit)
{
    if (field.value.length > maxlimit)
    {
        // if too long...trim it!
       field.value = field.value.substring(0, maxlimit);

       alert("Due to system requirements, prayer requests can be no more than "+maxlimit+" characters\n\nWe apologize for any inconvenience.");
    }

    // update 'characters left' counter
    countfield.value = maxlimit - field.value.length;

}//end function textCounter

function validatePrayerRequest(form)
{
    var maxlimit=1000
    try
    {
        form.remLen.value=maxlimit - form.PrayerRequest.value.length;
        if ( form.remLen.value < 0 )
        {
            alert("Due to system requirements, prayer requests can be no more than "+maxlimit+" characters\n\nWe apologize for any inconvenience.");
            return false;
        }//end if


       // first, validate the form contents
       var country=form.Country.value;
       var firstName=form.FirstName.value;
       var lastName=form.LastName.value;
       var address=form.Address1.value;
       var address2=form.Address2.value;
       var address3=form.Address3.value;
       var city=form.City.value;
       var state=form.State.value;

       form.Zipcode.value = trim( form.Zipcode.value );
       var zipcode=form.Zipcode.value;

       var email=form.EmailAddress.value;
       var error="";

       var emailReply=form.ReplyMethod[0].checked;
       var postalReply=form.ReplyMethod[1].checked;
       var noReply=form.ReplyMethod[2].checked;
       debug("NoReply["+noReply+"],EmailReply=["+emailReply+"],postalReply=["+postalReply+"]");
       debug("Country["+country+"] ["+country+"]");

       //###############################################################
       //####[  ACCENT CHARACTERS ]#####################################
       //###############################################################

       if (    containsAccentCharacters( firstName )
            || containsAccentCharacters( lastName )
            || containsAccentCharacters( address )
            || containsAccentCharacters( address2 )
            || containsAccentCharacters( address3 )
            || containsAccentCharacters( city )
            || containsAccentCharacters( state )
          )
       {
            error = error + "Please Do Not Enter Accent Characters.  (\'ö\', etc...).\n\n";

       }//end if


       //###############################################################
       //####[ / ACCENT CHARACTERS ]####################################
       //###############################################################


       // if the user requests a reply, make sure they have filled in the required fields
       if ( ! noReply )
       {

          debug("firstName= [" + firstName + "] ["+trim(firstName).length+"]");
          if ( trim(firstName).length == 0 )
          {
              error = error + "Please provide your First Name.\n";
          }//end if

          debug("lastName= [" + lastName + "] ["+trim(lastName).length+"]");
          if ( trim(lastName).length == 0 )
          {
             error = error + "Please provide your Last Name.\n";
          }//end if

          debug("address= [" + address + "] ["+trim(address).length+"]");
          if ( trim(address).length == 0 )
          {
             error = error + "Please provide your Address.\n";
          }//end if

          debug("address2= [" + address2 + "] ["+trim(address2).length+"]");

          // check if there is additional address for countries other than the US or Canada
          if ( trim(address2).length == 0 )
          {
              debug("checking country...");
              if (( ! isDomesticUS( country) ) && ( country != "Canada" ) )
              {
                  debug("checking city...");
                  if ( trim(city).length == 0 )
                  {
                      debug("Other city");
                      error = error + "Please provide your City (or nearest city).\n";
                  }//end if
              }//end if
          }//end if

          debug("city= [" + city + "] ["+trim(city).length+"]");
          // check if there is a city for the US or Canada
          if ( (trim(city).length == 0 ) && ( isDomesticUS( country) || (country == "Canada") ) )
          {
              // debug("US or Canadian city");
               error = error + "Please provide your City.\n";
          }//end if

          debug("state= [" + state + "] ["+trim(state).length+"]");
          if ( (trim(state).length == 0) && isDomesticUS(country) )
          {
             error = error + "Please provide your State/Province.\n";
          }//end if

          if ( (trim(state).length == 0) && (country == "Canada"))
          {
             error = error + "Please provide your Province.\n";
          }//end if

          debug("zipcode= [" + zipcode + "] ["+trim(zipcode).length+"]");

          if ( isDomesticUS(country) )
          {
              if ( ! isNumeric( zipcode ) )
              {
                   error = error + "Please provide a Numeric Zip code.\n";
              }//end if

              if ( trim(zipcode).length < 5 )
              {
                  error = error + "Please provide your ZIP Code.\n";
              }//end if
         }
         else
         if ( (country == "Canada") && (trim(zipcode).length < 6 ) )
         {
              error = error + "Please provide your Postal Code.\n";
         }//end if

           debug("email= [" + email + "] ["+trim(email).length+"]");
           if ( trim(email).length > 0 )
           {
               if ( ! validEmail(email) )
               {
                   error = error + "Incorrect email address format.\nMust be following format:\n\n  name@domain.ext\n\nFor example: fred@aol.com";
               }//end if

           }
           else
           if (emailReply)
           {
                    error = error + "Please provide your E-mail address.\n";
           }//end else/if

       }//end if (! noReply)

       debug("Finished Evaluating Fields");

       debug("country updates.");
       if ( isDomesticUS( country ) )
       {
            debug("U.S. Address");

            if ( isOutLyingDomestic( country ) )
            {
                form.NewState.value=form.Country.value;
            }//end if


            form.NewCountry.value="US";
            country=trim(form.NewCountry.value);
       }
       else
       {
           debug("Foreign");

           //###################################################################
           // Due to a 5 line limitation for addresses, foreign addresses
           // are put into Address line 3.
           //###################################################################

           if ( country == "Canada" )
           {
               debug("Canadian Address");
               if ( zipcode.indexOf(" ") == -1 )
               {
                   debug("zipcode does NOT contain Space");
                   if ( zipcode.length == 6 )
                   {
                       form.Zipcode.value=zipcode.substring(0,3)+" "+zipcode.substring(3);
                   }
                   else
                   if ( zipcode.length == 7 )
                   {
                       form.Zipcode.value=zipcode.substring(0,3)+" "+zipcode.substring(4);
                   }//end else/if

                   debug("Updated Zip Code ["+form.Zipcode.value+"]");

               }//end if
           }
           else
           {
               form.ForeignAddress3.value=form.Zipcode.value+" "+form.City.value+" "+form.State.value;
           }//end else


       }//end else

       debug("Country Value ["+form.NewCountry.value+"]");

       form.NewCountry.value=trim( country ).toUpperCase();

       debug("New Country Value ["+form.NewCountry.value+"]");

       // second, determine which Thank You/Reply page to redirect the user to
       setRedirectPage(form);

       // third, determine if there is an error, and if so alert the user
       if ( trim(error).length != 0 )
       {
           error = "To receive a reply from Silent Unity:\n\n" + error;
           alert(error);
           return false;
       }//end if

    }catch(e)
    {
      alert("Failed To Validate Form Due To UnExpected RunTime Exception-["+e+"]");
      return false;
    }
   form.Submit.disabled=true;	
   return true;

}//end function

function validEmail(email)
{
    debug("Validating Email Address");
    if ( trim(email).length==0)
    {
        return false;
    }
    debug("Preparing regular expression.");

    if (email.search(/^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/) == -1)
    {
        return false;
    }//end if

    return true;

}//end function

function setRedirectPage(form)
{
   var emailReply = form.ReplyMethod[0].checked;
   var postalReply = form.ReplyMethod[1].checked;
   var noReply = form.ReplyMethod[2].checked;

   if (emailReply)
   {
      // set the Thank You reply page for Email Response
      //form.redirect.value = "prayer_submitprayerrequest_e-reply.htm";
      form.redirect.value = "GenericRedirect.jsp?link=http://www.unityenlinea.org/pray_submitprayerrequest_e-reply.htm&target=top";
   }
   else
   if (postalReply)
   {
      // set the Thank You reply page for Postal Response
      //form.redirect.value = "prayer_submitprayerrequest_reply.htm";
      form.redirect.value = "GenericRedirect.jsp?link=http://www.unityenlinea.org/pray_submitprayerrequest_reply.htm&target=top";
   }
   else
   if (noReply)
   {
      // set the Thank You reply page for No Reply Response
      //form.redirect.value = "prayer_submitprayerrequest_anon-reply.htm";
      form.redirect.value = "GenericRedirect.jsp?link=http://www.unityenlinea.org/pray_submitprayerrequest_anon-reply.htm&target=top";
   }
}//end function: setRedirectPage

/**
 * Determine if the current Country is considered Domestic US (for postal reasons)
 */
function isDomesticUS(country)
{
     debug("Is This Domestic US? ["+country+"]" );
    if (
            (country == "United States")
         || (country == "US")
         || (country == "United States - Outlying Islands")
         || ( isOutLyingDomestic( country ) )
        )
    {
         debug("Yes");
        return true;
    }//end if

    debug("No");
    return false;
}//end function

/**
 * Determine if the country is actually a US Postal Region
 */
function isOutLyingDomestic(country)
{
         debug("Is This OutLying US? ["+country+"]" );
         if (
               (country == "Virgin Islands, US")
            || (country == "VI")
            || (country == "US")
            || (country == "AS")
            || (country == "DC")
            || (country == "FM")
            || (country == "GU")
            || (country == "MH")
            || (country == "MP")
            || (country == "PW")
            || (country == "PR")
            )
         {

            debug("Yes");
            return true;
         }

    debug("No");
    return false;

}//end function




/**
 * MAIN CountryChange "control" method/function
 */
function CountryChange(form)
{
    var redirectPageBase="Pray_submitprayerRequest";

    debug("Country Change.");

        if (  isDomesticUS(form.Country.value) )
        {
            debug("State/Province is a text field ");
            document.location.href= redirectPageBase+'-domestic.htm'
                                  +'?redirect=true&random='+getRandom()
                                  +'&Country='+escape(form.Country.selectedIndex)
                                  +'&ReplyMethod='+escape(getReplyTypeFromForm(form))
                                  //+'&Subscribe='+escape(form.Subscribe.checked)
                                  +'&Text='+escape(form.Text.value)
                                  +'&City='+escape(form.City.value)
                                  //+'&State='+escape(form.State.value)
                                  +'&ZipCode='+escape(form.Zipcode.value)
                                  +'&FirstName='+escape(form.FirstName.value)
                                  +'&LastName='+escape(form.LastName.value)
                                  +'&Address1='+escape(form.Address1.value)
                                  +'&Address2='+escape(form.Address2.value)
                                  +'&Address3='+escape(form.Address3.value)
                                  +'&EmailAddress='+escape(form.EmailAddress.value)
                                  +'&Phone1='+escape(form.Phone1.value)

        }
        else
        if (form.Country.value == "Canada")
        {
             debug("=> Canada ");

             document.location.href= redirectPageBase+'-canada.htm'
                                  +'?redirect=true&random='+getRandom()
                                  +'&Country='+escape(form.Country.selectedIndex)
                                  +'&ReplyMethod='+escape(getReplyTypeFromForm(form))
                                  //+'&Subscribe='+escape(form.Subscribe.checked)
                                  +'&Text='+escape(form.Text.value)
                                  +'&City='+escape(form.City.value)
                                  //+'&State='+escape(form.State.value)
                                  +'&ZipCode='+escape(form.Zipcode.value)
                                  +'&FirstName='+escape(form.FirstName.value)
                                  +'&LastName='+escape(form.LastName.value)
                                  +'&Address1='+escape(form.Address1.value)
                                  +'&Address2='+escape(form.Address2.value)
                                  +'&Address3='+escape(form.Address3.value)
                                  +'&EmailAddress='+escape(form.EmailAddress.value)
                                  +'&Phone1='+escape(form.Phone1.value)
        }
        else
        {
             debug("=> Foreign");

             document.location.href=redirectPageBase+'-foreign.htm'
                                  +'?redirect=true&random='+getRandom()
                                  +'&Country='+escape(form.Country.selectedIndex)
                                  +'&ReplyMethod='+escape(getReplyTypeFromForm(form))
                                  //+'&Subscribe='+escape(form.Subscribe.checked)
                                  +'&Text='+escape(form.Text.value)
                                  +'&City='+escape(form.City.value)
                                  +'&State='+escape(form.State.value)
                                  +'&ZipCode='+escape(form.Zipcode.value)
                                  +'&FirstName='+escape(form.FirstName.value)
                                  +'&LastName='+escape(form.LastName.value)
                                  +'&Address1='+escape(form.Address1.value)
                                  +'&Address2='+escape(form.Address2.value)
                                  +'&Address3='+escape(form.Address3.value)
                                  +'&EmailAddress='+escape(form.EmailAddress.value)
                                  +'&Phone1='+escape(form.Phone1.value)


        }//end else/if

        return;
}//end function

/**
 * get a string represntation of the ReplyMethod radio box array...for parameter passing.
 */
function getReplyTypeFromForm(form)
{
    if ( form.ReplyMethod[0].checked)
    {
        return "email";
    }
    else
    if (form.ReplyMethod[1].checked)
    {
        return "postal";
    }
    else
    {
        return "none";
    }//end else
}//end function

/**
 * Set the ReplyMethod radio box value depending on the string passed.
 *@see getReplyTypeFromForm()
 * Limitations:  Assumes the finite set of email, postal & none (noResponse)
 */
function setReplyType(form, stringVal)
{
    form.ReplyMethod[0].checked=( stringVal == "email" );
    form.ReplyMethod[1].checked=( stringVal == "postal" );
    form.ReplyMethod[2].checked=( stringVal == "none" );

}//end function

/**
 * Set the value of the Subscribe checkbox
 */
function setSubscribe(form, stringVal)
{
    form.Subscribe.checked=(stringVal == "true");
}//end function

/**
 * Update the list of states/provinces in the State <select>
 */
function ProcessCountryChangeUS(form)
{

    var states = new Array("Selecciona un Estado","AA","AE","AP","AL","AK","AZ","AR","CA","CO","CT","DE","DC","FL","GA","GU","HI","ID","IL","IN","IA","KS","KY","LA","ME","MD","MA","MI","MN","MO","MP","MS","MT","NE","NV","NH","NJ","NM","NY","NC","ND","OH","OK","OR","PA","PR","RI","SD","SC","TN","TX","UT","VI","VA","VT","WA","WV","WI","WY");

    updateStateSelect( form, states );

    form.Address3.disabled=false;

}//end function

/**
 *
 */
function updateStateSelect(form, arr )
{

     if ( form.State.type != "text" )
     {
         form.State.options.length=arr.length;
         for (i=0;i < arr.length; i++)
         {
               form.State.options[i].text = arr[i];
               if (i == 0)
               {
                    form.State.options[i].value = "";
               }
               else
               {
                    form.State.options[i].value = arr[i];
               }//end else
         }//end for
     }//end if
     return;
}

/**
 * Update the list of states/provinces in the State <select>
 */
function ProcessCountryChangeCanada(form)
{

    var provinces = new Array("Selecciona una Provincia","AB","BC","MB","NB","NL","NT","NS","NU","ON","PE","PQ","SK","YT");

    updateStateSelect( form, provinces );

    form.Address3.value="";
    form.Address3.disabled=true;
}


function getParameter(paramName,str)
{

    idx = str.toUpperCase().indexOf(paramName.toUpperCase()+"=");

    if ( idx == -1 )
    {
        return "";
    }//end if

    tmpStr = str.substring(idx + paramName.length + 1);

    if ( tmpStr.indexOf("&") == 0 )
    {
       return "";
    }
    else
    if ( tmpStr.indexOf("&") != -1 )
    {
        tmpStr = tmpStr.substring(0,tmpStr.indexOf("&"));

    }

    return unescape(tmpStr);

}//end function

function urlShift(str)
{
    if ( str.indexOf("?") >= 0 )
    {
        theleft = str.indexOf("?")+1;
    }
    else
    if ( str.indexOf("&") >= 0 )
    {
        theleft = str.indexOf("&")+1;

    }
    else
    {
        theleft = 0;
    }//end else

    return unescape(str.substring(theleft));


}//end function

function parseCommonParameters()
{
     debug("parsing Common Parameters");
    document.tmpForm.tmpLocation.value=window.location;

    //if the redirect parameter is not provided...do nothing more.
    document.tmpForm.tmpInput.value=getParameter("redirect",document.tmpForm.tmpLocation.value);
    if ( ! document.tmpForm.tmpInput.value )
    {
        return false;
    }//end if

    //--------------------------------------------------------------------------------
    //------------- keeping this commented out in case it is one day useful
    //--------------------------------------------------------------------------------
    //document.tmpForm.tmpLocation.value=urlShift( document.tmpForm.tmpLocation.value );

    document.form1.Text.value=getParameter("Text",document.tmpForm.tmpLocation.value);
    document.form1.remLen.value=1000-document.form1.Text.value.length;

    //Country select (drop-down)
    document.tmpForm.tmpInput.value=getParameter("Country",document.tmpForm.tmpLocation.value);
    if ( document.tmpForm.tmpInput.value != "" )
    {
        document.form1.Country.selectedIndex=document.tmpForm.tmpInput.value;
    }//end if



    document.form1.FirstName.value=getParameter("FirstName",document.tmpForm.tmpLocation.value);
    document.form1.LastName.value=getParameter("LastName",document.tmpForm.tmpLocation.value);

    document.form1.Address1.value=getParameter("Address1",document.tmpForm.tmpLocation.value);
    document.form1.Address2.value=getParameter("Address2",document.tmpForm.tmpLocation.value);
    document.form1.Address3.value=getParameter("Address3",document.tmpForm.tmpLocation.value);


    document.form1.City.value=getParameter("City",document.tmpForm.tmpLocation.value);
    document.form1.Zipcode.value=getParameter("ZipCode",document.tmpForm.tmpLocation.value);

    document.form1.EmailAddress.value=getParameter("EmailAddress",document.tmpForm.tmpLocation.value);

    document.form1.Phone1.value=getParameter("Phone1",document.tmpForm.tmpLocation.value);


    //ReplyMethod radio buttons
    setReplyType(document.form1,getParameter("ReplyMethod",document.tmpForm.tmpLocation.value));


    //Subscribe checkbox (for eNewsLetter)
    //setSubscribe(document.form1,getParameter("Subscribe",document.tmpForm.tmpLocation.value));

    return true;

}//end function

function parseDomesticParameters()
{
     debug("entering parseDomesticParameters() function");
    parseCommonParameters();

    debug("parseCommonParameters() - COMPLETE");

    document.form1.Address3.disabled=false;

    //since the domestic page is intended to display both us & canda...
    if (document.form1.Country.value == "Canada" )
    {
         ProcessCountryChangeCanada(document.form1);

    }
    else
    {
         ProcessCountryChangeUS(document.form1);
    }//end else/if

    document.form1.State.disabled=false;

    debug("Looking For Outlying domestic.");
    if ( isOutLyingDomestic( document.form1.Country.value ) )
    {
       countryVal = document.form1.Country.value;

       for (i=0;i < document.form1.State.options.length; i++)
       {
           if ( document.form1.State.options[i].value == countryVal )
           {
              document.form1.State.selectedIndex = i;
              document.form1.State.disabled=true;
              break;
           }

       }//end for


    }//end if

}//end function

function parseForeignParameters()
{
     debug("parsing Foreign Parameters");

    if ( parseCommonParameters() )
    {
        document.form1.State.value=getParameter("State",document.tmpForm.tmpLocation.value);
    }//end if

    city=trim(document.form1.City.value);

    if ( city.length > 15 )
    {
        document.form1.City.value=city.substring(0,15);
    }//end if

    document.form1.State.disabled=false;
    country=trim(document.form1.Country.value);
    if (    (country == "VI")
         || (country == "PR")
         || (country == "GU")
       )
    {
         document.form1.State.value=country;
         document.form1.State.disabled=true;

    }//end if

}//end function

function getRandom()
{
    return Math.floor(Math.random()*3001);

}//end function


function ProcessCountryChange(form)
{
  if ( form.Country.value == "Canada" )
  {
    ProcessCountryChangeCanada(form)
    form.State.disabled=false;
    return;
  }
  if ( form.Country.value == "United States" )
  {
    ProcessCountryChangeUS(form)
    form.State.disabled=false;
    return;
  }
  else
  {
    form.State.disabled=true;
    return;
  }
}