﻿/*
 * Registration Components Validation Routines
 */

function isValidState(parm)
{
   switch (parm) {
   case 'AK':
   case 'AL':
   case 'AR':
   case 'AZ':
   case 'CA':
   case 'CO':
   case 'CT':
   case 'DC':
   case 'DE':
   case 'FL':
   case 'GA':
   case 'HI':
   case 'IA':
   case 'ID':
   case 'IL':
   case 'IN':
   case 'KS':
   case 'KY':
   case 'LA':
   case 'MA':
   case 'MD':
   case 'ME':
   case 'MI':
   case 'MN':
   case 'MO':
   case 'MS':
   case 'MT':
   case 'NC':
   case 'ND':
   case 'NE':
   case 'NH':
   case 'NJ':
   case 'NM':
   case 'NV':
   case 'NY':
   case 'OH':
   case 'OK':
   case 'OR':
   case 'PA':
   case 'RI':
   case 'SC':
   case 'SD':
   case 'TN':
   case 'TX':
   case 'UT':
   case 'VA':
   case 'VT':
   case 'WA':
   case 'WI':
   case 'WV':
   case 'WY':
      return true;
   }
   return false;
}

function isValidProvince(parm)
{
   switch (parm) {
   case 'AB':
   case 'BC':
   case 'MB':
   case 'NB':
   case 'NL':
   case 'NS':
   case 'ON':
   case 'PE':
   case 'QC':
   case 'SK':
      return true;
   }
   return false;
}

function isNum(parm)
{
   var val = '0123456789';
   for (i=0; i<parm.length; i++) {
      if (val.indexOf(parm.charAt(i),0) == -1) {
         return false;
      }
   }
   return true;
}

function isPassword(parm)
{
   // try to exclude ones outside of valid single-byte characters:
   // characters below \u0020 (space) are control characters, and
   // the upper limit \u00FF will exclude double-byte characters
   // which http cookies cannot handle well ...
   var reInvalidChars = "[^\u0020-\u00FF]";
   
   if (parm.search(reInvalidChars) != -1) {
      return false;
   }  
   
   return true;
}

function isLogin(parm)
{
   // try to exclude ones outside of valid single-byte characters:
   // characters below \u0020 (space) are control characters, and
   // the upper limit \u00FF will exclude double-byte characters
   // which http cookies cannot handle well ...

   var reInvalidChars = "[^\u0020-\u00FF]";
   
   if (parm.indexOf('&') != -1) 
   {
      return false;
   }
   if (parm.indexOf('@') != -1) 
   {
      return false;
   }
   if (parm.search(reInvalidChars) != -1) {
      return false;
   }   
   return true;
}

function isName(parm)
{
   var reInvalidChars = "[!\$%\^&=\+]";
   if (parm.search(reInvalidChars) != -1) {
      return false;
   }
   return true;
}

function isValidZipCode(value) {
   var re = /^\d{5}([\-]\d{4})?$/;
   return (re.test(value));
}

/* Validate Contact Component */
function ValidateContact()
{
   var bRetVal = false;

   /* get inputs */
   var firstname = document.forms[0].site_ContactFirstname;
   var lastname  = document.forms[0].site_ContactLastname;
   var firstnamephonetic = document.forms[0].site_ContactFirstnamePhonetic;
   var lastnamephonetic  = document.forms[0].site_ContactLastnamePhonetic;
   var companyname = document.forms[0].site_ContactCompanyname;
   var companytype = document.forms[0].site_ContactCompanytype;
   var email = document.forms[0].site_ContactEmail;
   var address1 = document.forms[0].site_ContactAddress1;
   var address2 = document.forms[0].site_ContactAddress2;
   var city = document.forms[0].site_ContactCity;
   var state = document.forms[0].site_ContactState;
   var province = document.forms[0].site_ContactProvince;
   var zip = document.forms[0].site_ContactZip;
   var country = document.forms[0].site_ContactCountry;
   var other = document.forms[0].site_ContactCountryOther;
   var phone = document.forms[0].site_ContactPhone;
   var fax = document.forms[0].site_ContactFax;

   do {

      /* validate first name */
      if (firstname != null)
      {
         if (firstname.value.length == 0)
         {
            alert(g_REG_COMP_ENTERFIRSTNAME);
            break;
         }

         if (isName(firstname.value) == false)
         {
            alert(g_REG_COMP_FIRSTNAMEINVALID);
            break;
         }
      }

      /* validate last name */
      if (lastname != null)
      {
         if (lastname.value.length == 0)
         {
            alert(g_REG_COMP_ENTERLASTNAME);
            break;
         }

         if (isName(lastname.value) == false)
         {
            alert(g_REG_COMP_LASTNAMEINVALID);
            break;
         }
      }

      /* validate company name */
      if (companyname != null)
      {
         if (companyname.value.length == 0)
         {
            alert(g_REG_COMP_ENTERCOMPANYNAME);
            break;
         }
      }

      /* validate email */
      if (email != null)
      {
         if (email.value.length == 0)
         {
            alert(g_REG_COMP_ENTEREMAIL);
            break;
         }
         if (email.value.length < 6)
         {
            alert(g_REG_COMP_EMAILMINIMUM);
            break;
         }
         if (isValidEmail(email.value) == false)
         {
            alert(g_REG_COMP_EMAILINVALID);
            break;
         }
      }

      /* validate address1 */
      if (address1 != null)
      {
         if (address1.value.length == 0)
         {
            alert(g_REG_COMP_ENTERADDRESS);
            break;
         }
      }

      /* validate city */
      if (city != null)
      {
         if (city.value.length == 0)
         {
            alert(g_REG_COMP_ENTERCITY);
            break;
         }
      }

      /* validate state or province */
      if (country != null && state != null && province != null )
      {
         if (country.value == 'USA')
         {
            // make sure valid state was selected
            if (!isValidState(state.value.toUpperCase()) || province.value != '')
            {
               alert(g_REG_COMP_SELECTSTATEONLY);
               break;
            }
         }
         else if (country.value == 'Canada')
         {
            // make sure valid canadian province was selected
            if (!isValidProvince(state.value.toUpperCase()) || province.value != '')
            {
               alert(g_REG_COMP_SELECTPROVINCEONLY);
               break;
            }
         }
         else  /* covers other country too */ 
         {       
            if (province.value == '')
            {
               alert(g_REG_COMP_ENTERPROVINCE);
               break;
            }
            if (state.value.toLowerCase() != 'other')            
            {
               alert(g_REG_COMP_DONOTSELECTSTATE);
               break;
            }
         }
      }
            
      /* validate zip */
      if (zip != null)
      {
         if (zip.value.length == 0)
         {
            alert(g_REG_COMP_ENTERZIP);
            break;
         }
         if (zip.value.length < 4)
         {
            alert(g_REG_COMP_ZIPMINIMUM);
            break;
         }

         if (country != null && country.value == 'USA')
         {
             if (!isValidZipCode(zip.value))
             {
                 alert(g_REG_COMP_INVALIDUSAZIPFORMAT);
                 break;
             }
         }
      }

      /* validate country */
      if (country != null)
      {
         if (country.value == 'other')
         {
            if (other != null && other.value.length == 0)
            {
               alert(g_REG_COMP_SELECTCOUNTRY);
               break;
            }
         }
         else
         {
            if (other != null && other.value.length > 0)
            {
               alert(g_REG_COMP_ENTERONECOUNTRY);
               break;
            }         
         }
      }

      /* validate phone */
      if (phone != null)
      {
         if (phone.value.length == 0)
         {
            alert(g_REG_COMP_ENTERPHONE);
            break;
         }
         if (phone.value.length < 7)
         {
            alert(g_REG_COMP_PHONEMINIMUM);
            break;
         }
      }

      /* validate fax */
      if (fax != null)
      {
         if (fax.value.length > 0)
         {
            if (fax.value.length < 7)
            {
               alert(g_REG_COMP_FAXMINIMUM);
               break;
            }
         }
      }

      /* successful validation */
      bRetVal = true;

   } while (false);

   return bRetVal;
}

/* Validate Login Component */
function ValidateLogin()
{
   var bRetVal = false;

   /* get inputs */
   var login = document.forms[0].site_LoginLogin;
   var password = document.forms[0].site_LoginPassword;
   var confirmpw = document.forms[0].site_LoginConfirmpw;

   do {

      /* validate login */
      if (login != null)
      {
         if (login.value.length == 0)
         {
            alert(g_REG_COMP_ENTERLOGIN);
            break;
         }
         if (isLogin(login.value) == false)
         {
            alert(g_REG_COMP_LOGININVALID);
            break;
         }
      }

      /* validate password */
      if (password != null)
      {
         if (password.value.length == 0)
         {
            alert(g_REG_COMP_ENTERPASSWORD);
            break;
         }
         if (password.value.length < 6)
         {
            alert(g_REG_COMP_PASSWORDMINIMUM);
            break;
         }
         if (isPassword(password.value) == false)
         {
            alert(g_REG_COMP_PASSWORDINVALID);
            break;
         }
      }

      /* validate confirm password */
      if (confirmpw != null)
      {
         if (confirmpw.value.length == 0)
         {
            alert(g_REG_COMP_ENTERCONFIRMPW);
            break;
         }
         if (password.value != confirmpw.value)
         {
            alert(g_REG_COMP_PASSWORDSMATCH);
            break;
         }
      }

      /* successful validation */
      bRetVal = true;

   } while (false);

   return bRetVal;
}

/* Validate WebOffice Address Component */
function ValidateWOA()
{
   var bRetVal = false;

   /* get inputs */
   var address = document.forms[0].site_WOAAddress;
   var companyname = document.forms[0].site_ContactCompanyname;
   var sitename = document.forms[0].site_WOASiteName;

   var sitehostname  = document.forms[0].site_WOAHostName;
   var domain        = document.forms[0].site_WOADomain;
   do {

      /* validate address */
      if (address != null)
      {
         if (address.value.length == 0)
         {
            alert(g_REG_COMP_ENTERWOA);
            break;
         }
      }

      /* if the action is trial, then copy company name into sitename */
      if ((document.forms[0].action.indexOf("/reg/trial/dispatch.aspx") > -1) ||
          (document.forms[0].action.indexOf("/reg/trial1/dispatch.aspx") > -1) ||
          (document.forms[0].action.indexOf("/reg/trial2/dispatch.aspx") > -1))
      {
          if(companyname != null && sitename != null)
          {
              if(sitename.value.length == 0)
              {
                  if(companyname.value.length > 0)
                  {
                      document.forms[0].site_WOASiteName.value = document.forms[0].site_ContactCompanyname.value;
                      sitename.value = document.forms[0].site_ContactCompanyname.value;
                  }
              }
          }
      }
      /* validate sitename */
      if (sitename != null)
      {
         if (sitename.value.length == 0)
         {
             if ((document.forms[0].action.indexOf("/reg/trial/dispatch.aspx") > -1)  ||
                 (document.forms[0].action.indexOf("/reg/trial1/dispatch.aspx") > -1) ||
                 (document.forms[0].action.indexOf("/reg/trial2/dispatch.aspx") > -1))
             {
                 alert(g_REG_COMP_ENTERCOMPANYNAME);
             }
             else
             {
                 alert(g_REG_COMP_ENTERSITENAME);
             }
            break;
         }
      }

      /* successful validation */
      bRetVal = true;

      // set sitehostname
      if (domain != null && sitehostname != null) {
         sitehostname.value = address.value + '.' + domain.value;
      }

   } while (false);

   return bRetVal;
}

/* Validate Describe Your Group Component */
function ValidateDescribeGroup()
{
   var bRetVal = false;

   /* get inputs */
   var type = document.forms[0].site_GroupType;
   var size = document.forms[0].site_GroupSize;
   var industry = document.forms[0].site_GroupIndustry;

   do {

      /* validate type */
      if (type != null)
      {
         if (type.value == g_REG_COMP_SELECTPROMPT)
         {
            alert(g_REG_COMP_SELECTGROUPTYPE);
            break;
         }
      }

      /* validate size */
      if (size != null)
      {
         if (size.value == g_REG_COMP_SELECTPROMPT)
         {
            alert(g_REG_COMP_SELECTGROUPSIZE);
            break;
         }
      }

      /* validate industry */
      if (industry != null)
      {
         if (industry.value == g_REG_COMP_SELECTPROMPT)
         {
            alert(g_REG_COMP_SELECTINDUSTRY);
            break;
         }
      }

      /* successful validation */
      bRetVal = true;

   } while (false);

   return bRetVal;
}

/* Validate Billing Component */
function ValidateBilling()
{
    var bRetVal = false;

   /* get inputs */
   var first = document.forms[0].bill_BillingFirst;
   var middle = document.forms[0].bill_BillingMiddle;
   var last = document.forms[0].bill_BillingLast;
   var email = document.forms[0].bill_BillingEmail;
   var companyname = document.forms[0].bill_BillingCompanyname;
   var vat = document.forms[0].bill_BillingVat;
   var address1 = document.forms[0].bill_BillingAddress1;
   var address2 = document.forms[0].bill_BillingAddress2;
   var city = document.forms[0].bill_BillingCity;
   var state = document.forms[0].bill_BillingState;
   var province = document.forms[0].bill_BillingProvince;
   var zip = document.forms[0].bill_BillingZip;
   var country = document.forms[0].bill_BillingCountry;
   var phone = document.forms[0].bill_BillingPhone;
   var fax = document.forms[0].bill_BillingFax;

   do {

      /* validate first name */
      if (first != null)
      {
         if (first.value.length == 0)
         {
            alert(g_REG_COMP_ENTERFIRSTNAME);
            break;
         }

         if (isName(first.value) == false)
         {
            alert(g_REG_COMP_FIRSTNAMEINVALID);
            break;
         }
      }

      /* validate middle name */
      if (middle != null)
      {
         if (middle.value.length > 0)
         {
            if (isName(middle.value) == false)
            {
               alert(g_REG_COMP_MIDDLENAMEINVALID);
               break;
            }
         }
      }

      /* validate last name */
      if (last != null)
      {
         if (last.value.length == 0)
         {
            alert(g_REG_COMP_ENTERLASTNAME);
            break;
         }

         if (isName(last.value) == false)
         {
            alert(g_REG_COMP_LASTNAMEINVALID);
            break;
         }
      }

      /* validate email */
      if (email != null)
      {
         if (email.value.length == 0)
         {
            alert(g_REG_COMP_ENTEREMAIL);
            break;
         }
         if (email.value.length < 6)
         {
            alert(g_REG_COMP_EMAILMINIMUM);
            break;
         }
         if (isValidEmail(email.value) == false)
         {
            alert(g_REG_COMP_EMAILINVALID);
            break;
         }
      }

      /* validate company name */
      if (companyname != null)
      {
         if (companyname.value.length == 0)
         {
            alert(g_REG_COMP_ENTERCOMPANYNAME);
            break;
         }
      }

      /* validate address1 */
      if (address1 != null)
      {
         if (address1.value.length == 0)
         {
            alert(g_REG_COMP_ENTERBILLINGADDRESS);
            break;
         }
      }

      /* validate city */
      if (city != null)
      {
         if (city.value.length == 0)
         {
            alert(g_REG_COMP_ENTERCITY);
            break;
         }
      }

      /* validate state or province */
      if (country != null && state != null && province != null )
      {
         if (country.value == 'USA')
         {
            // make sure valid state was selected
            if (!isValidState(state.value.toUpperCase()) || province.value != '')
            {
               alert(g_REG_COMP_SELECTSTATEONLY);
               break;
            }
         }
         else if (country.value == 'Canada')
         {
            // make sure valid canadian province was selected
            if (!isValidProvince(state.value.toUpperCase()) || province.value != '')
            {
               alert(g_REG_COMP_SELECTPROVINCEONLY);
               break;
            }
         }
         else 
         {       
            if (province.value == '')
            {
               alert(g_REG_COMP_ENTERPROVINCE);
               break;
            }
            if (state.value.toLowerCase() != 'other')            
            {
               alert(g_REG_COMP_DONOTSELECTSTATE);
               break;
            }
         }
      }
         
      /* validate zip */
      if (zip != null)
      {
         if (zip.value.length == 0)
         {
            alert(g_REG_COMP_ENTERZIP);
            break;
         }
         if (zip.value.length < 4)
         {
            alert(g_REG_COMP_ZIPMINIMUM);
            break;
         }

         if (country != null && country.value == 'USA')
         {
             if (!isValidZipCode(zip.value))
             {
                 alert(g_REG_COMP_INVALIDUSAZIPFORMAT);
                 break;
             }
         }
      }

      /* validate country */
      if (country != null)
      {
         if (country.value == 'other')
         {
            alert(g_REG_COMP_SELECTCOUNTRY);
            break;
         }
      }

      /* validate phone */
      if (phone != null)
      {
         if (phone.value.length == 0)
         {
            alert(g_REG_COMP_ENTERPHONE);
            break;
         }
         if (phone.value.length < 7)
         {
            alert(g_REG_COMP_PHONEMINIMUM);
            break;
         }
      }

      /* validate fax */
      if (fax != null)
      {
         if (fax.value.length > 0)
         {
            if (fax.value.length < 7)
            {
               alert(g_REG_COMP_FAXMINIMUM);
               break;
            }
         }
      }

      /* successful validation */
      bRetVal = true;

   } while (false);

   return bRetVal;
}

/* Validate Credit Card Component */
function ValidateCreditCard()
{
   var bRetVal = false;

   /* get inputs */
   var number = document.forms[0]._CreditCardNumber;
   var expmonth = document.forms[0].bill_CreditCardExpmonth;
   var expyear = document.forms[0].bill_CreditCardExpyear;
   var mode = document.forms[0].bill_CreditCardMode;
   var accountnumber = document.forms[0].bill_AccountNumber;
   var paymenttype = document.forms[0].bill_CreditCardType;
   var isUpdate = document.forms[0]._Update;

   do {

      /* if direct debit is selected, don't validate credit card inputs */
      if (paymenttype != null && paymenttype.value == 'directdebit')
      {
         bRetVal = true;
         break;
      }

      // check to see if product total is eligible for billme
      if (paymenttype != null && paymenttype.value == 'BM')
      {
         // if this is an edit then don't check the billme dollar amount
          
         if (isUpdate != null && isUpdate.value == "false")
         {
             // check to see that price is greater than $100
             if ((regSelectedProductsTotal() < 100) || (strCurrency == '¥' && strPeriod.toLowerCase() == 'false'))
             {
                alert(g_REG_COMP_NOBILLME);
                break;
             }

         }

         bRetVal = true;
         break;
      }

      /* validate credit card number */
      if (number != null)
      {
         if (number.value.length == 0)
         {
            alert(g_REG_COMP_ENTERCREDITCARD);
            break;
         }
         /***
         if (isNum(number.value) == false)
         {
            alert(g_REG_COMP_CREDITCARDNUM);
            break;
         }
         ***/
      }

      /* validate account number 
      if (accountnumber != null)
      {
         if (accountnumber.value.length == 0)
         {
            alert(g_REG_COMP_ENTERACCOUNTNUMBER);
            break;
         }
         if (isNum(accountnumber.value) == false)
         {
            alert(g_REG_COMP_ACCOUNTNUMBERNUM);
            break;
         }
      }
      */

      /* successful validation */
      bRetVal = true;

   } while (false);

   return bRetVal;
}

/* Validate Direct Debit Component */
function ValidateDirectDebit()
{
   var bRetVal = false;

   /* get inputs */
   var bankaccount = document.forms[0].bill_DdebitBankaccount;
   var routenum = document.forms[0].bill_DdebitRoutenum;
   var bankname = document.forms[0].bill_DdebitBankname;
   var paymenttype = document.forms[0].bill_CreditCardType;

   do {

      /* only validate inputs if payment type is selected */
      if (paymenttype == null || paymenttype.value != 'directdebit')
      {
         bRetVal = true;
         break;
      }

      if (bankaccount != null)
      {
         if (bankaccount.value.length == 0)
         {
            alert(g_REG_COMP_ENTERBANKNUMBER);
            break;
         }
         if (isNum(bankaccount.value) == false)
         {
            alert(g_REG_COMP_BANKNUMBERNUM);
            break;
         }
      }

      if (routenum != null)
      {
         if (routenum.value.length == 0)
         {
            alert(g_REG_COMP_ENTERROUTENUMBER);
            break;
         }
         if (isNum(routenum.value) == false)
         {
            alert(g_REG_COMP_ROUTENUMBERNUM);
            break;
         }
      }

      if (bankname != null)
      {
         if (bankname.value.length == 0)
         {
            alert(g_REG_COMP_ENTERBANKNAME);
            break;
         }
      }

      /* successful validation */
      bRetVal = true;

   } while (false);

   return bRetVal;
}

/* Validate Terms of Service (TOS) Component */
function ValidateTOS()
{
   var bRetVal = false;

   /* get inputs */
   var tos = document.forms[0]._TOS;

   do {

      if (tos != null)
      {
         if (tos.checked == false)
         {
            alert(g_REG_COMP_TOS);
            break;
         }
      }

      /* successful validation */
      bRetVal = true;

   } while (false);

   return bRetVal;
}

/* Validate Product Info component */
function ValidateProductInfo()
{
   var bRetVal = false;

   do {
      // make sure at least one COS_INTRANET has been selected
      var intranet_count = 0;
      
      // only valid if 'activate' inputs are on the form
      var bAnyActivateFound = false;
      var bAnyActivateChecked = false;

      // loop thru form inputs
      var elements = document.forms[0].elements;
      for (var i = 0; i < elements.length; i++)
      {
         // find hidden 'activate' inputs
         // in the form 'services_<product>_activate'
         var index = elements[i].id.indexOf('_activate');
         if (index > 0)
         {
            // we've found an activate input so
            // validate that somethings been checked
            bAnyActivateFound = true;

            // get product name from activate input
            var product = elements[i].id.substring(0, index)
            var hyphen = product.indexOf('_');
            product = product.substring(hyphen+1);

            // we only want to validate products that have
            // a checkbox checked
            var visibleCheckbox = document.getElementById('_'+product+'activate');
            if (visibleCheckbox != null && visibleCheckbox.checked == true)
            {
               // determine if anything has been checked
               bAnyActivateChecked = true;

               // get price model for product
               var pricemodel = document.getElementById('_'+product+'_pricemodel');
               if (pricemodel != null)
               {
                  if (pricemodel.value == 'BillingPlan')
                  {
                     // has a valid billing plan been selected
                     var plan = document.getElementById('services_'+product+'_serviceplan');
                     if (plan != null && plan.value == -1)
                     {
                        alert(g_REG_COMP_SELECTBILLINGPLAN);
                        return false;
                     }
                  }
                  if (pricemodel.value == 'PerUnit' || pricemodel.value == 'PerUnitSliding')
                  {
                     // only validate seats if annual plan is chosen
                     var paymentplan = document.getElementById('services_'+product+'_data4');
                     var seats = document.getElementById('services_'+product+'_data3');
                     if (seats != null && paymentplan != null && paymentplan.value == 'annually')
                     {
                        // get minimum and maximum values for product
                        var productMinimum = regGetProductMinimum(product, 'annually');
                        var productMaximum = regGetProductMaximum(product, 'annually');
						var productPluralName = eval('obj' + product + 'pluralname');

                        // verify the seats entered fall within the valid range
                        if (seats.value < productMinimum)
                        {
                           var msg = g_REG_COMP_SEATMINIMUM;
						   msg = msg.replace('%1', productMinimum);
                           alert(msg.replace('%2', productPluralName));
                           return false;
                        }
                        if (seats.value > productMaximum)
                        {
                           var msg = g_REG_COMP_SEATMAXIMUM;
						   msg = msg.replace('%1', productMaximum);
						   alert(msg.replace('%2', productPluralName));
                           return false;
                        }
                     }
                  }
               }

               // does this product have an intranet class of service
               var cos = document.getElementById('_'+product+'_cos');
               if (cos != null)
               {
                  if (cos.value.indexOf('COS_INTRANET,')>=0)
                  {
                     // keep track of number of intranets selected
                     // (only count if you're not already subscribed )
                     var subscribed = document.getElementById('_'+product+'_subscribed');
                     if (subscribed != null && subscribed.value == 'False')
                     {
                        intranet_count++;
                     }
                  }

                  // if this product has COS_EMAIL,
                  // validate Domain component inputs
                  if (cos.value.indexOf('COS_EMAIL,')>=0)
                  {
                     var domain = document.getElementById('services_'+product+'_data1');
                     if (domain != null)
                     {
                        if (domain.value == null || domain.value.length == 0)
                        {
                           alert(g_REG_COMP_ENTERDOMAIN);
                           return false;
                        }
                        if (domain.value.length < 5)
                        {
                           alert(g_REG_COMP_DOMAINMINIMUM);
                           return false;
                        }
                     }
                  }
               }
            }
         }
      }

      // count the number of subscribed COS_INTRANET products
      // (should only be 1 or 0)
      var subscribed_intranet_count = 0;
      for (var i = 0; i < elements.length; i++)
      {
         // find hidden 'subscribed' inputs
         // in the form 'services_<product>_subscribed'
         var index = elements[i].id.indexOf('_subscribed');
         if (index > 0)
         {
            // get product name from input
            var product = elements[i].id.substring(0, index)
            product = product.substring(1);

            var subscribed = document.getElementById('_'+product+'_subscribed');
            if (subscribed != null && subscribed.value == 'True')
            {
               // does this product have an intranet class of service
               var cos = document.getElementById('_'+product+'_cos');
               if (cos != null)
               {
                  if (cos.value.indexOf('COS_INTRANET,')>=0)
                  {
                     subscribed_intranet_count++;
                  }
               }
            }
         }
      }

      // if any activate is found on the page, perform validation
      if (bAnyActivateFound == true)
      {
         if (bAnyActivateChecked == false)
         {
            alert(g_REG_COMP_NOTHINGTOPROVISION);
            break;
         }

         // verify that one and only one COS_INTRANET product has been selected
         var iIntranetCount = parseInt(subscribed_intranet_count) + parseInt(intranet_count);
         if (iIntranetCount < 1)
         {
            alert('Must select at least one product with COS_INTRANET.');
            break;
         }

         // verify that no more than 1 COS_INTRANET product has been selected.
         if (iIntranetCount > 1)
         {
            alert('Cannot select more than one product with COS_INTRANET.');
            break;
         }
      }

      /* successful validation */
      bRetVal = true;

   } while (false);

   return bRetVal;
}

var bRunValidateComponents = false;
function ValidateComponents()
{
   // temporarily turn off validation
   //return true;

   var bRetVal = false;

   if(!bRunValidateComponents) {
      
      do {

         if (ValidateContact() == false)
         {
            break;
         }
         if (ValidateLogin() == false)
         {
            break;
         }
         if (ValidateWOA() == false)
         {
            break;
         }
         if (ValidateDescribeGroup() == false)
         {
            break;
         }
         if (ValidateBilling() == false)
         {
            break;
         }
         if (ValidateCreditCard() == false)
         {
            break;
         }
         if (ValidateDirectDebit() == false)
         {
            break;
         }
         if (ValidateTOS() == false)
         {
            break;
         }
         if (ValidateProductInfo() == false)
         {
            break;
         }

         /* successful validation */
        bRetVal = true;
        bRunValidateComponents = true;
      } while (false);
    }

   return bRetVal;
}

function ValidateComponentsForEdit()
{
   // temporarily turn off validation
   //return true;

   var bRetVal = false;

   do {

      if (ValidateContact() == false)
      {
          break;
      }
      if (ValidateLogin() == false)
      {
          break;
      }
      if (ValidateWOA() == false)
      {
          break;
      }
      if (ValidateDescribeGroup() == false)
      {
         break;
      }
      if (ValidateBilling() == false)
      {
         break;
      }
      if (ValidateCreditCardForEdit() == false)
      {
          break;
      }
      if (ValidateDirectDebit() == false)
      {
         break;
      }
      if (ValidateTOS() == false)
      {
         break;
      }
      if (ValidateProductInfo() == false)
      {
         break;
      }

      /* successful validation */
      bRetVal = true;

   } while (false);

   return bRetVal;
}

// Registration Event Handlers

var g_strBrandID = '';

// This function performs any registration page initialization
function regInit(siteflags, brandid)
{
   g_strBrandID = brandid;

   // Need to iterate over subscribed products and disable
   // any products that may be a subset of the subscribed product

   // loop thru inputs
   var elements = document.forms[0].elements;
   for (var i = 0; i < elements.length; i++)
   {
      // find 'subscribed' input
      var index = elements[i].id.indexOf('_subscribed');
      if (index > 0)
      {
         // determine if this product is subscribed
         if (elements[i].value == 'True')
         {
            // get product name from '_<product>_subscribed'
            var product = elements[i].id.substring(0, index)
            product = product.substring(1);

            // validate product
            regValidateProduct(product, true);
         }
      }
      else
      // see if any products are checked that
      // require the domain selection component
      {
         index = elements[i].id.indexOf('_activate');
         if (index > 0)
         {
            // get product name from 'services_<product>_activate'
            var product = elements[i].id.substring(0, index)
            var hyphen = product.indexOf('_');
            product = product.substring(hyphen+1);

         // display domain selection area if necessary
         var bDisplay = elements[i].value == 'True' ? true : false;
         regDisplayDomainSelection(product, bDisplay);

            var bSiteIsTrial = siteflags & 131072; //0x20000 SiteFlag_PETrial
            

            // determine if this is the product we are registering for
            // or if we are in a workgroup trial
            var productname = document.getElementById('productname');
            if ((productname != null && productname.value == product) ||
               ((product == 'workgroup' || product == 'intranetonly' || product == 'intranetjp') && bSiteIsTrial))
            {
               // if there is one COS_INTRANET product, check and disable it
               if (regGetIntranetProductCount() <= 1)
               {
               // check and disable this product
               var checkbox = document.getElementById('_'+product+'activate');
               if (checkbox != null)
               {
                  checkbox.checked = true;
                  checkbox.disabled = true;
               }

               // update services activate node
               var services_activate = document.getElementById('services_'+product+'_activate');
               if (services_activate != null)
               {
                  services_activate.value = 'True';
               }

               // update display
               var pricingmodel = document.getElementById('_'+product+'_pricemodel');
               if (pricingmodel != null)
               {
                  regOnActivate(product, true, pricingmodel.value);
               }
            }
            else
            {
               // Initialize one of many COS_INTRANET products
               regInitIntranetProduct(product);
            }
            }

          // determine if product requires email and, if email
         // is not checked, disable those products
         regHandleEmailRelatedProducts(product);

         }
      }
   }
   
   // need to initialize direct debit if brand and country permit
   var country = document.forms[0].bill_BillingCountry;
   if (country != null)
   {
      regOnBillingCountryChange(g_strBrandID, country.value);
   }
}

// This function is called when the user checks
// a product to purchase
function regOnActivate(product, checked, pricingmodel)
{
   // update hidden input
   var input = document.getElementById('services_'+product+'_activate');
   if (input != null)
   {
      input.value = checked ? 'True' : 'False';
   }

   // perform any price model specific handling
   if (pricingmodel == 'FlatFee')
   {
      // update total
      var total = document.getElementById('_'+product+'total');
      if (total != null)
      {
         total.value = '';
         var price = document.getElementById('_'+product+'price');
         if (price != null && checked)
         {
            total.value = price.value;
         }
      }
   }
   // perform any price model specific handling
   else if (pricingmodel == 'BillingPlan')
   {


      var plan = document.getElementById('services_'+product+'_serviceplan');
      if (plan != null)
      {
         // enable/disable plan list
         plan.disabled = checked ? false : true;

         // when unchecked, reset plan to 'Please Select One'
         if (checked == false)
         {
            plan.value = -1;
         }

         // determine if product supports annual discounts
         var annual = 'FALSE';
         var input = document.getElementById('_'+product+'_AllowForAnnualDiscount');
         if (input != null)
         {
            annual = input.value;
         }
         
         // enable/disable paymentplan
         var monthly = document.getElementById('_'+product+'monthly');
         var annually = document.getElementById('_'+product+'annually');
         if (monthly != null && annually != null)
         {
			monthly.disabled = checked ? false : true;
			annually.disabled = checked ? false : true;
         }

         // update total, payment plan, and overage sections
         regOnServicePlanChange(product, plan.value, annual)
      }
   }
   // perform any price model specific handling
   else if (pricingmodel == 'PerUnit' || pricingmodel == 'PerUnitSliding')
   {
      var monthly = document.getElementById('_'+product+'monthly');
      var annually = document.getElementById('_'+product+'annually');
      if (monthly != null && annually != null)
      {
         monthly.disabled = checked ? false : true;
         annually.disabled = checked ? false : true;
         monthly.checked = false;
         annually.checked = false;

         var paymentplan = document.getElementById('services_'+product+'_data4');
         if (paymentplan != null)
         {
         if (paymentplan.value == 'monthly')
         {
               monthly.checked = true;
         }
         else
         {
               annually.checked = true;
         }
         }

         var hiddenseats = document.getElementById('services_'+product+'_data3');
         var seats = document.getElementById('_'+product+'_data3');
         if (seats != null && hiddenseats != null)
         {
            // enable/disable seats
            seats.disabled = (checked && paymentplan.value == 'annually') ? false : true;
            
            if (checked == false)
            {
               seats.value = '';
               hiddenseats.value = 0;
               var total = document.getElementById('_'+product+'total');
               if (total != null)
               {
                  total.value = '';
               }
            }
            else
            {
               // update seats section
               if (hiddenseats.value == '' || hiddenseats.value <= 0)
               {
                  // initialize seats
                  seats.value = regGetProductMinimum(product, paymentplan.value);
               }
               else
               {
                  // user has already entered a value
                  seats.value = hiddenseats.value;
               }
               hiddenseats.value = seats.value;
               regNumSeatsChanged(product, seats.value, true);
            }
         }
      }
      else
      {
         // if here, plan does not warrant an annual discount
         // so just update total
         var total = document.getElementById('_'+product+'total');
         if (total != null)
         {
            total.value = '';
            var price = document.getElementById('_'+product+'price');
            if (price != null && checked)
            {
               total.value = price.value;
            }
         }
      }
   }

   // validate product
   regValidateProduct(product, checked);
}

// When a product is selected, determine if any other products
// include a subset of the same classes of service, and if so,
// uncheck and enable/disable them.
function regValidateProduct(product, checked)
{

   // get classes of service for this product
   var productCOS = document.getElementById('_'+product+'_cos');
   if (productCOS != null && productCOS.value != null)
   {
      //alert('Product = '+product+' COS = '+productCOS.value);

      // determine if this product contains COS_EMAIL
      regDisplayDomainSelection(product, checked);

      // determine if product requires email and, if email
      // is not checked, disable
      regHandleEmailRelatedProducts(product);

      // loop thru inputs
      var elements = document.forms[0].elements;
      for (var i = 0; i < elements.length; i++)
      {
         // find any activate inputs
         var index = elements[i].id.indexOf('_activate');
         if (index > 0)
         {
            // get product name from 'services_<product2>_activate'
            var product2 = elements[i].id.substring(0, index)
            var hyphen = product2.indexOf('_');
            product2 = product2.substring(hyphen+1);

            // make sure we're not looking at ourselves
            if (product2 != product)
            {
               // get the class of services for this product
               var product2COS = document.getElementById('_'+product2+'_cos');
               if (product2COS != null && product2COS.value != null)
               {
                  //alert('Product2 = '+product2+' COS2 = '+product2COS.value);

                  // if this product contains COS_INTRANET, don't disable
                  // so that people can upgrade their intranet product
                  if (product2COS.value.indexOf('COS_INTRANET') >= 0)
                  {
                      // This return is commented out because even if the type is cos_intranet we want to disable it.
                      // Uncommenting this return will cause cos_intranets in the available services section of additional services to be selectable
                      // return;
                  }

                  // make sure we have a valid list of services for this product
                  var product2ServiceNames = product2COS.value.split(",");

                  // determine if this product is a subset of the original product
                  var bSubset = false;
                  for (var j=0; j < product2ServiceNames.length; j++)
                  {
                     // get the current service
                     var serviceName = product2ServiceNames[j];
                     if (serviceName != null && serviceName != '')
                     {
                        // see if the service is included
                        if (productCOS.value.indexOf(serviceName+',') >= 0)
                        {
                           bSubset = true;
                        }
                     }
                  }

                  // if we've gone thru all of the services, then
                  // this product is a subset.
                  if (bSubset)
                  {
                     regResetProduct(product2, false);
                  }
               }
            }
         }
      }
   }
}

// This function is called whenever a service plan changes
function regOnServicePlanChange(product, value, annual)
{
   regDisplayTotal(product, value);
   regDisplayOverageText(product, value);
   regDisplayPaymentPlan(product, value, annual);
}

// This function updates the 'total' field
function regDisplayTotal(product, value) {

   var total = document.getElementById('_'+product+'total');
   if (total != null)
   {
      if (value == -1)
      {
         total.value = '';
      }
      else
      {
         var objHash = eval('obj'+product+'price');
         if (objHash != null)
         {
            total.value = objHash[value];
         }
         else
         {
            total.value = '';
         }
      }
   }
}

// This function updates the 'overage' area
function regDisplayOverageText(product, value) {

   var div = document.getElementById('_'+product+'overagetext');
   if (div != null)
   {
      var strOverageText = '';
      var objHash = eval('obj'+product+'overage');
      if (objHash != null && value != -1)
      {
         var overage = objHash[value];
         if (overage != null && overage.length > 0)
         {
            strOverageText = overage;
         }
      }

      // don't display overage text if price is 0 or negative
      var objPriceHash = eval('obj'+product+'price');
      if (objPriceHash != null)
      {
         var price = objPriceHash[value];
         var noprice = regFormatCurrency(product, '0');
         if (price != null && (price == noprice || price.indexOf('-') >= 0))
         {
            strOverageText = '';
         }
      }
      
      div.style.display = 'block';
      div.innerHTML = strOverageText;

		// adjust menus
		cb_menu_move();
   }
}

// This function updates the 'onetime' area
function regDisplayOneTimeText(product) {

   var input = document.getElementById('services_'+product+'_serviceplan');
   var div = document.getElementById('_'+product+'onetimefee');
   if (div != null && input != null)
   {
      var strOneTimeText = '';
      var objHash = eval('obj'+product+'onetime');
      if (objHash != null && input.value != -1)
      {
         var onetime = objHash[input.value];
         if (onetime != null && onetime.length > 0)
         {
            strOneTimeText = onetime;
         }
      }

      if (strOneTimeText.length > 0)
      {
         var resulttext = g_REG_COMP_SETUPFEE.replace('%1', regFormatCurrency(product, strOneTimeText));
         div.style.display = 'block';
         div.innerHTML = resulttext;
      }
      else
      {
         div.style.display = 'none';
      }
   }
}



// This function hides/shows the payment plan area
function regDisplayPaymentPlan(product, value, annualsupport) {

   var div = document.getElementById('_'+product+'paymentdiv');
   if (div != null)
   {
      // does product support an annual discount
      if (annualsupport != null && annualsupport == 'TRUE')
      {
         div.style.display = 'block';
      }
      else
      {
         div.style.display = 'none';
      }

      // calculate paymentplan based on plan selected.
      var newpaymentplan = '';
      var objAnnualHash = eval('obj'+product+'annual');
      if (objAnnualHash != null)
      {
        for (var i in objAnnualHash)
        {
            if (value == i)
            {
            newpaymentplan = 'annually';
            break;
            }
        }
      }

      var objMonthlyHash = eval('obj'+product+'monthly');
      if (objMonthlyHash != null)
      {
        for (var i in objMonthlyHash)
        {
            if (value == i)
            {
            newpaymentplan = 'monthly';
            break;
            }
        }
      }

      // update payment plan
      var paymentplan = document.getElementById('services_'+product+'_data4');
      if (paymentplan != null)
      {
         paymentplan.value = newpaymentplan;
      }

   }
}

// This function is called whenever the payment plan changes
function regOnPaymentPlanChange(product, value)
{

   if (value == 'monthly')
   {
      document.getElementById('_'+product+'monthly').checked=true;
      document.getElementById('_'+product+'annually').checked=false;
   }
   else
   {
      document.getElementById('_'+product+'monthly').checked=false;
      document.getElementById('_'+product+'annually').checked=true;
   }

   // update payment plan
   var paymentplan = document.getElementById('services_'+product+'_data4');
   if (paymentplan != null)
   {
      paymentplan.value = value;
   }

   // if number of seats input exists, disable it
   var hiddenseats = document.getElementById('services_'+product+'_data3');
   var seats = document.getElementById('_'+product+'_data3');
   if (seats != null)
   {
      seats.disabled = value == 'monthly' ? true : false;
      seats.value = regGetProductMinimum(product, value);
      hiddenseats.value = seats.value;
   }

   // update billing plans (if necessary)
   var input = document.getElementById('services_'+product+'_serviceplan');
   if (input != null)
   {
      if (input.tagName == 'SELECT')
      {
         var hash;
         if (value == 'monthly')
         {
            hash = eval('obj'+product+'monthly');
         }
         else
         {
            hash = eval('obj'+product+'annual');
         }

         // remove all options.
         input.options.length = 0;

         // add '-- Please Select One --' option
         input.options[0] = new Option(g_REG_COMP_SELECTPROMPT, -1);

         // add plans from hash
         var j = 1;
         for (var i in hash) {
            if (i == -1) {
               continue;
            }
            input.options[j++] = new Option(hash[i], i);
         }
      }
      else
      {
         // if here, we are using the seats model
         var strAnnual;
         if (value == 'monthly')
         {
            strAnnual = 'False';
         }
         else
         {
            strAnnual = 'True';
         }
            
         var plan = regGetSeatPlan(product, seats.value, strAnnual);
         if (plan != -1)
         {
            input.value = plan;
         }
      }
   }

   // hide overage text
   var div = document.getElementById('_'+product+'overagetext');
   if (div != null)
   {
      div.style.display = 'none';
   }

   // update total
   var total = document.getElementById('_'+product+'total');
   if (total != null)
   {
      var price = 0;
      var productMinimum = 1;
      var objPriceHash = eval('obj'+product+'price');

      if (value == 'monthly')
      {
         // for BillingPlan pricing, clear out total
         // for Per Unit pricing, use monthly plan in hash
         var pricemodel = document.getElementById('_'+product+'_pricemodel');
         if (pricemodel != null && pricemodel.value == 'PerUnit' && objPriceHash != null)
         {
            var annualHash = eval('obj'+product+'seatannual');
            if (annualHash != null)
            {
				for (var i in annualHash)
				{
					if (annualHash[i] == 'False')
					{
						price = objPriceHash[i];
						break;
					}
				}
            }
            productMinimum = regGetProductMinimum(product, value);
         }
         if (price > 0)
         {
            var actualcost = productMinimum * price;
            total.value = regFormatCurrency(product, actualcost.toString());
         }
         else
         {
            total.value = '';
         }
      }
      else
      {
         if (objPriceHash != null && input != null)
         {
            // get price based on plan
            var plan = parseInt(input.value);
            if (plan > 0)
            {
               price = objPriceHash[plan];
            }
         }
         var actualcost = 0;
         if (seats != null && seats.value > 0)
         {
            actualcost = price * seats.value;
         }
         if (actualcost > 0)
         {
            total.value = regFormatCurrency(product, actualcost.toString());
         }
         else
         {
            total.value = '';
         }
      }
   }
   regDisplayOneTimeText(product);
}

// This function is called whenever the number of seats changes
function regNumSeatsChanged(product, value, bTestMinMax)
{
   var paymentplan = document.getElementById('services_'+product+'_data4');
   var hiddenseats = document.getElementById('services_'+product+'_data3');
   var seats = document.getElementById('_'+product+'_data3');
   var total = document.getElementById('_'+product+'total');
   var serviceplan = document.getElementById('services_'+product+'_serviceplan');
   if (total != null && serviceplan != null && seats != null && hiddenseats != null && paymentplan != null)
   {
      var price = 0;
      var actualcost = '';

      if (paymentplan.value == 'annually')
      {
		 // get minimum and maximum values for product
		 var productMinimum = regGetProductMinimum(product, 'annually');
		 var productMaximum = regGetProductMaximum(product, 'annually');
		 var productPluralName = eval('obj' + product + 'pluralname');

		 if(bTestMinMax.toString() == 'true')
		 {
			 // only allow numbers
			 if (isNum(value) == false)
			 {
				alert(g_REG_COMP_MAILBOXESNUM);
				value =  productMinimum;
				seats.value = value;
			 }
	
			 // verify the seats entered fall within the valid range
			 if (value < productMinimum)
			 {
				var msg = g_REG_COMP_SEATMINIMUM;
				msg = msg.replace('%1', productMinimum);
				alert(msg.replace('%2', productPluralName));
				value =  productMinimum;
				seats.value = value;
			 }
	
			 if (value > productMaximum)
			 {
				var msg = g_REG_COMP_SEATMAXIMUM;
				msg = msg.replace('%1', productMaximum);
				alert(msg.replace('%2', productPluralName));
				value =  productMinimum;
				seats.value = value;
			 }
		 }

         // update hidden input
         hiddenseats.value = value;
      }

      // find the plan based on the number of seats entered
      var strAnnual = paymentplan.value == 'annually' ? 'True' : 'False';
      var plan = regGetSeatPlan(product, value, strAnnual);

      // update the service plan input with the correct plan
      // based on the number of seats entered
      if (plan != -1)
      {
         serviceplan.value = plan;

         // find the price based on the plan
         var priceHash = eval('obj'+product+'price');
         if (priceHash != null)
         {
            price = priceHash[plan];
         }
         // update the 'Price Per' section
         var priceper = document.getElementById('_'+product+'_priceper');
         if (priceper != null)
         {
            priceper.innerHTML = regFormatCurrency(product, price.toString());
         }
      }

      // determine if 'annual' is selected
      if (paymentplan.value == 'annually')
      {
         if (value > 0)
         {
            var totalannualcost = price * value;
            actualcost = totalannualcost;
         }
         else
         {
            actualcost = null;
         }
      }
      else
      {
         actualcost = hiddenseats.value * price;
      }

      if (actualcost != null && actualcost != '')
      {
         total.value = regFormatCurrency(product, actualcost.toString());
      }
      else
      {
         total.value = '';
      }
   }
   regDisplayOneTimeText(product);
}



// This function returns the plan based on seats and payment plan (annual or monthly)
function regGetSeatPlan(product, seats, strAnnual)
{
   var plan = -1;
   var minHash = eval('obj'+product+'min');
   var maxHash = eval('obj'+product+'max');
   var annualHash = eval('obj'+product+'seatannual');
   if (minHash != null && maxHash != null)
   {
      for (var i in minHash)
      {
         var minimum = parseInt(minHash[i]);
         var maximum = parseInt(maxHash[i]);
         var annual = annualHash[i];
         if (seats >= minimum && seats <= maximum && annual == strAnnual)
         {
            plan = i;
            break;
         }
      }
   }
   return plan;
}

// This function is called when the user wants to use
// a domain that's already registered
function regOnDisplayDomainInfo(product, appid)
{
   // get inputs
   var domain = document.getElementById('services_'+product+'_data1');

   do
   {
      if (domain != null && domain.value != null)
      {
         if (domain.value.length == 0)
         {
            alert(g_REG_COMP_ENTERDOMAIN);
            break;
         }

         if (domain.value.length < 5)
         {
            alert(g_REG_COMP_DOMAINMINIMUM);
            break;
         }

         // successful validation so display window
         var theURL;
         if (appid == '47')
         {
            theURL = '/commerce';
         }
         else
         {
            theURL = '/reg';
         }
         theURL += '/purchase/dispatch.aspx?_command=domaininfo&domain='+domain.value + '&domainproduct='+product;
         var winHeight=600, winWidth=550;
         var windowX=240, windowY=480;
         if (document.all) {
            windowX = screen.width; windowY = screen.height;
         } else
         if (document.layers) {
            windowX = window.outerWidth; windowY = window.outerHeight;
         }
         var leftPos = (windowX - winHeight)/2, topPos = (windowY - winWidth)/2;
         var hWnd = window.open(theURL, 'domaininfo','toolbar=no,location=no,status=yes,menubar=no,scrollbars=yes,resizable=yes,copyhistory=no,height='+winHeight+',width='+winWidth+',screenX='+leftPos+',screenY='+topPos+',top='+topPos+',left='+leftPos);
         hWnd.opener = self;
      }
   }
   while (false);
}

// This function is called when the user clicks yes on the domain info page
function regOnDomainInfoYes(product)
{
   var command = document.forms[0]._command;
   if (command != null)
   {
      command.value = 'save';
      document.forms[0].submit();
   }
}

// This function is called when the user clicks no on the domain info page
function regOnDomainInfoNo(product)
{
   // reset domain radio button section
   //regOnDomainCreateModeChanged(product, 'new');

   // set focus back on domain input
   var input = document.getElementById('services_'+product+'_data1');
   if (input != null)
   {
      input.focus();
   }
}

// This function is called when the user clicks on a domain name suggestion
function regOnDomainSuggestion(product, radio)
{
   var domain = document.getElementById('services_'+product+'_data1');
   if (domain != null)
   {
      domain.value = radio.value;
   }

   //select/deselect radio buttons
   var prefix = '_'+product+'DomNam';
   var elements = document.forms[0].elements;
   for (var i = 0; i < elements.length; i++)
   {
      var current = elements[i];
      if (current.name != null && current.name.indexOf(prefix) == 0)
      {
         if (current.name == radio.name)
         {
            current.checked = true;
         }
         else
         {
            current.checked = false;
         }
      }
   }
}

// This function is called when the user clicks on the domain radio
// buttons ("I need a new domain" or "I want to use an existing domain"
function regOnDomainCreateModeChanged(product, value)
{
   var data2 = document.getElementById('services_'+product+'_data2');
   var newDomain = document.getElementById('_'+product+'_newdomain');
   var existingDomain = document.getElementById('_'+product+'_existingdomain');
   var button = document.getElementById('_'+product+'_infobtn');
   if (data2 != null && newDomain != null && existingDomain != null && button != null)
   {
      if (value == 'new')
      {
         data2.value = 'True';
         newDomain.checked = true;
         existingDomain.checked = false;
         button.style.display = 'none';
      }
      else
      {
         data2.value = 'False';
         newDomain.checked = false;
         existingDomain.checked = true;
         button.style.display = 'block';
      }

		// adjust menus
		cb_menu_move();
   }
}

// This function is used to format currency
function regFormatCurrency(product, value)
{
   var strCurrency = '$';
   var strDecimalSep = '.';
   
   var productCurrency = document.getElementById('_'+product+'_currency');
   if (productCurrency != null && productCurrency.value != '')
   {
      strCurrency = productCurrency.value;
      if (strCurrency == '')
      {
         strDecimalSep = ',';
      }
   }   

   var i = value.indexOf(strDecimalSep);
   if (i < 0)
   {
      // no decimal exists so add it
      value += strDecimalSep + "00";
   }
   if (i > 0)
   {
      if (i+1 == (value.length-1))
      {
         // only one number after the decimal point so add a zero
         value += "0";
      }
      if (i+2 < value.length)
      {
         // more than 2 decimal places so truncate
         value = value.substring(0, i+2+1);
      }
   }
   
   var retval;
   if (isNaN(value.charAt(0)))
   {
      retval = value;
   }
   else
   {
      retval = strCurrency + value;
   }
   return retval;
}

// this function enables/disables email related products
// if email is selected/deselected
function regHandleEmailRelatedProducts(product)
{
   var productCOS = document.getElementById('_'+product+'_cos');
   if (productCOS != null && productCOS.value != null)
   {
      if (productCOS.value.indexOf('COS_EMAIL,') >= 0)
      {
         // find any products that depend on email
         // and enable/disable them

         // loop thru inputs
         var elements = document.forms[0].elements;
         for (var i = 0; i < elements.length; i++)
         {
            // find any activate inputs
            var index = elements[i].id.indexOf('_activate');
            if (index > 0)
            {
               // get product name from 'services_<product2>_activate'
               var product2 = elements[i].id.substring(0, index)
               var hyphen = product2.indexOf('_');
               product2 = product2.substring(hyphen+1);

               // make sure we're not looking at ourselves
               if (product2 != product)
               {
                  // get the class of services for this product
                  var product2COS = document.getElementById('_'+product2+'_cos');
                  if (product2COS != null && product2COS.value != null)
                  {
                     // determine if this product depends on email
                     if (product2COS.value.indexOf('COS_EMAIL_') >= 0)
                     {
                        // check to see if the email product is subscribed
                        var subscribed = document.getElementById('_'+product+'_subscribed');
                        if (subscribed != null && subscribed.value != 'True')
                        {
                           // check to see if the email product is checked
                           var activate = document.getElementById('_'+product+'activate');
                           if (activate != null)
                           {
                              regResetProduct(product2, activate.checked);
                           }
                        }
                     }
                  }
               }
            }
         }
      }
   }
}

// this function is called to disable a product
// and clear it's related inputs (total, serviceplan, ...)
function regResetProduct(product, bEnable)
{
   // reset only if disabling
   if (!bEnable)
   {
      // reset 'services_<product2>_activate'
      var activate2 = document.getElementById('services_'+product+'_activate');
      if (activate2 != null)
      {
         activate2.value = 'False';
      }

      // reset total
      var total = document.getElementById('_'+product+'total');
      if (total != null)
      {
         total.value = '';
      }
   }

   // enable/disable the visible checkbox
   var activate = document.getElementById('_'+product+'activate');
   if (activate != null)
   {
      activate.disabled = bEnable ? false : true;

      // reset checked only if disabling
      if (!bEnable)
      {
         activate.checked = false;
      }
   }

   // reset related inputs
   var pricemodel = document.getElementById('_'+product+'_pricemodel');
   if (pricemodel != null)
   {
      if (pricemodel.value == 'BillingPlan')
      {
         var plan = document.getElementById('services_'+product+'_serviceplan');
         if (plan != null)
         {
            if (activate != null)
            {
               plan.disabled = activate.checked ? false : true;
            }

            // reset plan only if disabling
            if (!bEnable)
            {
               plan.value = -1;
            }
         }
      }
   }
}

// this function hides/shows the domain selection area
function regDisplayDomainSelection(product, bDisplay)
{
   var productCOS = document.getElementById('_'+product+'_cos');
   if (productCOS != null && productCOS.value != null)
   {
      // if this product contains COS_INTRANET, we don't
      // want to display the domain selection component
      // because it should have already been displayed
      // on a previous page.
      if (product == "emailstandalone")
      {
         return;
      }


      // determine if this product contains COS_EMAIL
      if (productCOS.value.indexOf('COS_EMAIL,') >= 0)
      {
         // get domain selection component
         var domain = document.getElementById('_'+product+'_DomainSelection');
         if (domain != null)
         {
            domain.style.display = bDisplay == true ? 'block' : 'none';
         }

         // get domain creation mode (create new domain or use existing)
         var data2 = document.getElementById('services_'+product+'_data2');
         if (data2 != null)
         {
            var value = (data2.value == 'True') ? 'new' : '';
            regOnDomainCreateModeChanged(product, value);
         }
      }
      
      // adjust menus
      cb_menu_move();
   }
}

// This function gets called whenever the 'Update'
// button is clicked on the additional services page
function regOnProductUpdate(product, button)
{
   var pricingDiv = document.getElementById('_'+product+'_ProductPricing');
   var activateDiv = document.getElementById('_'+product+'_ActivateCheckboxDiv');
   var activateImageDiv = document.getElementById('_'+product+'_ActivateImageDiv');
   var activate = document.getElementById('services_'+product+'_activate');
   var checkbox = document.getElementById('_'+product+'activate');
   var serviceplan = document.getElementById('services_'+product+'_serviceplan');

   if (pricingDiv != null && activateDiv != null && activate != null && checkbox != null)
   {
      if (pricingDiv.style.display == 'block')
      {
         pricingDiv.style.display = 'none';
         activateDiv.style.display = 'none';
		 activateImageDiv.style.display = 'block';
         activate.value = 'False';
         checkbox.checked = false;
         button.value = g_REG_COMP_UPDATE;
         regDisplayDomainSelection(product, false);
      }
      else
      {
         pricingDiv.style.display = 'block';
         activateDiv.style.display = 'block';
		 activateImageDiv.style.display = 'none';
         activate.value = 'True';
         checkbox.checked = true;
         button.value = g_REG_COMP_CLOSE;
         regDisplayDomainSelection(product, true);
      }
   }
}

// This function gets called when the 'Cancel'
// button is clicked during a registration process
function regOnCancel()
{
   var strURL;
   var url = document.forms[0].returnURL;
   if (url != null && url.value.length > 0)
   {
      strURL = url.value;
   }
   else
   {
      strURL = 'http://www.webexone.com';
   }
   top.location = strURL;
}

// This function gets called when the 'Apply'
// button is clicked (from the 'Offer' component)
function regOnOffer()
{
   var next = document.forms[0]._nextStep;
   var current = document.forms[0]._thisStep;
   var command = document.forms[0]._command;
   if (next != null && current != null && command != null)
   {
      next.value = current.value;
      command.value = 'getoffer';
      document.forms[0].submit();
   }
}
// This function is called when the user clicks on the
// Invoice Billing link
function regOnInvoiceBilling()
{
   var div = document.getElementById('BillMeDiv');
   var idiv = document.getElementById('InvoiceDiv');
   if (div != null && idiv != null)
   {
      div.style.display = 'block';
      idiv.style.display = 'none';
   }
}

// This function is called when the user clicks on various
// billing type radio buttons (direct debit, credit card, bill me)
function regOnBillingTypeChange(name)
{
   var type1 = document.getElementById('_billtype_cc');
   if (type1 != null)
   {
      type1.checked = false;
   }

   var type2 = document.getElementById('_billtype_dd');
   if (type2 != null)
   {
      type2.checked = false;
   }

   var type3 = document.getElementById('_billtype_billme');
   if (type3 != null)
   {
      type3.checked = false;
   }

   var billingtype = document.getElementById('bill_CreditCardType');
   if (billingtype != null && name != null)
   {
      var value = billingtype.value;
      if (name == '_billtype_dd')
      {
         value = 'directdebit';
      }
      if (name == '_billtype_billme')
      {
         value = 'BM';
      }
      
      // if we just clicked 'credit card' and we're
      // changing from 'bill me' or 'direct debit', reset value to MC
      if (name == '_billtype_cc' && (value == 'BM' || value == 'directdebit'))
      {
         value = 'MC';
      }
      
      billingtype.value = value;

      var input = document.getElementById(name);
      if (input != null)
      {
         input.checked = true;
      }

      // enable/disable credit card fields
      var cc_type = document.getElementById('_CreditCardType');
      var cc_num = document.getElementById('_CreditCardNumber');
      var cc_num_hidden = document.getElementById('bill_CreditCardNumber');
      var cc_exp_day = document.getElementById('bill_CreditCardExp_day');
      var cc_exp_month = document.getElementById('bill_CreditCardExp_month');
      var cc_exp_year = document.getElementById('bill_CreditCardExp_year');
      if (cc_type != null && cc_num != null && cc_exp_day != null && cc_exp_month != null && cc_exp_year != null && cc_num_hidden != null)
      {
         var bDisabled = (value != 'BM' && value != 'directdebit') ? false : true;

         cc_type.disabled = bDisabled ? true : false;
         cc_num.disabled = bDisabled ? true : false;
         cc_exp_year.disabled = bDisabled ? true : false;
         cc_exp_month.disabled = bDisabled ? true : false;

         // need to reset day so INDate validation will succeed
         cc_exp_day.value = bDisabled ? '' : '01';
         
         // reset values
         //
         // JMR: Can't reset values, since it'll clear out any
         // data already stored in the transaction
         //
         //cc_num.value = '';
         //cc_num_hidden.value = '';
      }
      
      // enable/disable direct debit controls
      var dd_bankaccount = document.getElementById('bill_DdebitBankaccount');
      var dd_routingnumber = document.getElementById('bill_DdebitRoutenum');
      var dd_bankname = document.getElementById('bill_DdebitBankname');
      if (dd_bankaccount != null && dd_routingnumber != null && dd_bankname != null)
      {
         var bDisabled = (value == 'directdebit') ? false : true;
         
         dd_bankaccount.disabled = bDisabled ? true : false;
         dd_routingnumber.disabled = bDisabled ? true : false;
         dd_bankname.disabled = bDisabled ? true : false;
      }
   }
}

// This function returns the minimum quantity
// of all the plans for this product
function regGetProductMinimum(product, paymenttype)
{
   var productMinimum = 9999;
   var minHash = eval('obj'+product+'min');
   var annualHash = eval('obj'+product+'seatannual');
   if (minHash != null && annualHash != null)
   {
      for (var i in minHash)
      {
         var minimum = parseInt(minHash[i]);
         var annual = annualHash[i];
         if (annual == 'True')
         {
			annual = 'annually';
         }
         else
         {
			annual = 'monthly';
         }
         if (productMinimum > minimum && annual == paymenttype)
         {
            productMinimum = minimum;
         }
      }
   }
   return productMinimum;
}

// This function returns the maximum quantity
// of all the plans for this product
function regGetProductMaximum(product, paymenttype)
{
   var productMaximum = 0;
   var maxHash = eval('obj'+product+'max');
   var annualHash = eval('obj'+product+'seatannual');
   if (maxHash != null && annualHash != null)
   {
      for (var i in maxHash)
      {
         var maximum = parseInt(maxHash[i]);
         var annual = annualHash[i];
         if (annual == 'True')
         {
			annual = 'annually';
         }
         else
         {
			annual = 'monthly';
         }
         if (productMaximum < maximum && annual == paymenttype)
         {
            productMaximum = maximum;
         }
      }
   }
   return productMaximum;
}

// This function is called when the user changes the
// contact country select control
function regOnContactCountryChange(brandid, value)
{
      // hide/show required asterisk on state and province field based on country
      var stateRequired = document.getElementById('contactStateRequired');
      var provinceRequired = document.getElementById('contactProvinceRequired');
      if (stateRequired != null && provinceRequired != null)
      {
         if (value == 'USA' || value == 'Canada')
         {
            stateRequired.innerHTML = '*';
            provinceRequired.innerHTML = '';
         }
         else
         {
            stateRequired.innerHTML = '';
            provinceRequired.innerHTML = '*';
         }
      }
}

// This function is called when the user changes the
// billing country select control
function regOnBillingCountryChange(brandid, value)
{
   var invoicediv = document.getElementById('InvoiceDiv');
   var directdebitdiv = document.getElementById('DirectDebitDiv');
   var billmediv = document.getElementById('BillMeDiv');
   var billtype = document.forms[0].bill_CreditCardType;
   var billtype_dd = document.getElementById('BillTypeDirectDebitDiv');

   if (invoicediv != null && directdebitdiv != null && billmediv != null && billtype != null && billtype_dd != null)
   {
      if (brandid == '805' && (value == 'Germany' || value == 'Austria'))
      {
         // display direct debit inputs (bank account, routing number, bank name)
         directdebitdiv.style.display = 'block';
         
         // make 'direct debit' choice visible         
         billtype_dd.style.display = 'block';

         // display radio group with billing choices (credit card, direct debit, bill me)
         billmediv.style.display = 'block';

         // don't display invoice div since radio buttons already need to display
         invoicediv.style.display = 'none';
      }
      else
      {
         // hide direct debit inputs
         directdebitdiv.style.display = 'none';
         
         // hide direct debit radio option
         billtype_dd.style.display = 'none';

         if (billtype.value == 'directdebit')
         {
            // you've changed countries to a country other than
            // germany or austria.  Need to reset creditcard type
            billtype.value = 'MC';
            billmediv.style.display = 'none';
            invoicediv.style.display = 'block';
         }
         else if (billtype.value == 'BM')
         {
            // if they have already chosen bill me, need to keep
            // this section visible.
            billmediv.style.display = 'block';
            invoicediv.style.display = 'none';
         }
         else
         {
            billmediv.style.display = 'none';
            invoicediv.style.display = 'block';
         }
      }
       
      // hide/show required asterisk on state field based on country
      var stateRequired = document.getElementById('billingStateRequired');
      var provinceRequired = document.getElementById('billingProvinceRequired');

      if (stateRequired != null)
      {
         if (value == 'USA' || value == 'Canada')
         {
            stateRequired.innerHTML = '*';
            provinceRequired.innerHTML = '';            
         }
         else
         {
            stateRequired.innerHTML = '';
            provinceRequired.innerHTML = '*';            
         }
      }
      
      // enable disable credit card/direct debit controls
      var name = '_billtype_cc';
      if (billtype.value == 'BM')
      {
		name='_billtype_billme';
      }
      else if (billtype.value == 'directdebit')
      {
		name='_billtype_dd';
      }
      regOnBillingTypeChange(name);
   }
}

// This function is called whe the user changes the
// WebOffice Addresss field
function regOnWOAAddressChange()
{
   var name = document.forms[0].site_WOAHostName;
   var address =document.forms[0].site_WOAAddress;
   var domain = document.forms[0].site_WOADomain;

   if (name != null && address != null && domain != null)
   {
      address.value = address.value.replace('www.','');
      name.value = address.value + '.' + domain.value;
   }
}

// This function is called when the user clicks on
// a COS_INTRANET product radio button.  It handles
// verifying that only one COS_INTRANET product is selected
function regOnIntranetActivate(product, checked, pricingmodel)
{
   // loop thru inputs
   var elements = document.forms[0].elements;
   for (var i = 0; i < elements.length; i++)
   {
      // find any activate inputs
      var index = elements[i].id.indexOf('_activate');
      if (index > 0)
      {
         // get product name from 'services_<product2>_activate'
         var product2 = elements[i].id.substring(0, index)
         var hyphen = product2.indexOf('_');
         product2 = product2.substring(hyphen+1);

         // make sure we're not looking at ourselves
         if (product2 != product)
         {
            // if the activate input type is radio, then this is a
            // COS_INTRANET product and should be unchecked
            var input = document.getElementById('_'+product2+'activate');
            if (input != null && input.type == 'radio')
            {
               input.checked = false;

               // call regOnActivate to update related inputs
               var pricingmodel2 = document.getElementById('_'+product2+'_pricemodel');
               if (pricingmodel2 != null)
               {
                  regOnActivate(product2, false, pricingmodel2.value);
               }
            }
         }
      }
   }

   // check the desired COS_INTRANET product
   regOnActivate(product, checked, pricingmodel);
}

// This function is called from regInit to determine
// the number of COS_INTRANET products are on the page
function regGetIntranetProductCount()
{
   var count = 0;

   // loop thru inputs
   var elements = document.forms[0].elements;
   for (var i = 0; i < elements.length; i++)
   {
      // find any activate inputs
      var index = elements[i].id.indexOf('_activate');
      if (index > 0)
      {
         // get product name from 'services_<product>_activate'
         var product = elements[i].id.substring(0, index)
         var hyphen = product.indexOf('_');
         product = product.substring(hyphen+1);

         var cos = document.getElementById('_'+product+'_cos');
         if (cos != null && cos.value.indexOf('COS_INTRANET') >= 0)
         {
            count++;
         }
      }
   }

   return count;
}

// This function is called from regInit to initialze the
// current COS_INTRANET product
function regInitIntranetProduct(product)
{
   // determine if a product has already been selected
   var selectedProduct = product;

   // loop thru inputs
   var elements = document.forms[0].elements;
   for (var i = 0; i < elements.length; i++)
   {
      // find any activate inputs
      var index = elements[i].id.indexOf('_activate');
      if (index > 0)
      {
         // get product name from 'services_<product2>_activate'
         var product2 = elements[i].id.substring(0, index)
         var hyphen = product2.indexOf('_');
         product2 = product2.substring(hyphen+1);

         // if the activate input type is radio, then this is a
         // COS_INTRANET product
         var input = document.getElementById('_'+product2+'activate');
         if (input != null && input.type == 'radio')
         {
            if (input.checked)
            {
               selectedProduct = product2;
            }
         }
      }
   }

   // check and disable this product
   var checkbox = document.getElementById('_'+selectedProduct+'activate');
   if (checkbox != null)
   {
      checkbox.checked = true;
   }

   // update services activate node
   var services_activate = document.getElementById('services_'+selectedProduct+'_activate');
   if (services_activate != null)
   {
      services_activate.value = 'True';
   }

   // update display
   var pricingmodel = document.getElementById('_'+selectedProduct+'_pricemodel');
   if (pricingmodel != null)
   {
      regOnIntranetActivate(selectedProduct, true, pricingmodel.value)
   }
}


function changeLocale(brandid, regtype) {

   var domain = document.forms[0]['site_WOADomain'].value;
   var prefix = document.forms[0]['site_WOAAddress'].value;
   var locale = document.forms[0]['site_SiteLocaleId'].value;

   var qs = "_command=new&brandid=" + brandid + "&localeid=" + locale + "&domain=" + domain + "&prefix=" + prefix;

   window.location = "/reg/" + regtype + "/dispatch.aspx?" + qs;

}

// this function returns the total price for all the selected products
// (it is used to determine eligibility for 'bill me' payment)
function regSelectedProductsTotal()
{
	var total = 0;
	if (objSelectedProducts != null)
	{
		for (var i in objSelectedProducts)
		{
			var price = objSelectedProducts[i];
			if (price != null)
			{
				total += parseInt(price);
			}
		}
	}
	return total;
}

function WarnIfCookiesDisabled()
{
    if(!window.navigator.cookieEnabled)
    {
        alert("In order to function, this website requires that your web browser be set to allow cookies.");
    }
}
