function checkField (field_data, data_format) {
            
  var num_only = /^\d+$/;
  var let_only = /^[a-zA-Z\. ]+$/;
  var city_only = /^[a-zA-Z\.\'\- ]+$/;
  var name_only = /^[0-9a-zA-Z\.\- ]+$/;
  var dollars_only = /^\d+(\.\d{2})?$/;
  var expiry_only = /^\d{2}\/\d{2}$/;
  var address_only = /^[0-9a-zA-Z\.\-\#\/ ]+$/;
  var num_let_only = /^\w+$/;
  var zip_only = /^\d{5}(-\d{4})?$/;
  var phone_only = /^\(?[0-9]{3}\)?[-. ]?[0-9]{3}[-. ]?[0-9]{4}$/;
  var email_only = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[(2([0-4]\d|5[0-5])|1?\d{1,2})(\.(2([0-4]\d|5[0-5])|1?\d{1,2})){3} \])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
  var unmatchable = /^uNmAtchABLe$/;
  var formats = {
                   name:  name_only,
                   email: email_only,
                   digits: num_only,
                   letters: let_only,
                   dollars: dollars_only,
                   expiry: expiry_only,
                   num_letters: num_let_only,
                   address: address_only,
                   zip: zip_only,
                   city: city_only,
                   unmatchable: unmatchable         
                };

  if(data_format == 'phone') {
     
    return phone_only.test(field_data) || num_only.test(field_data);

  } else if(formats[data_format]) {

    return formats[data_format].test(field_data);

  } else {
    // some unknown format
    return field_data != "";
  }
}


function fieldTrimmer (field_name) {
  
  var field_data = jQuery(field_name).val();
  
  field_data = field_data.replace(/\s{2,}/g,"");
  
  var trimmed_data = field_data.replace(/^\s+|\s+$/g,"");
  
  jQuery(field_name).val(trimmed_data);
}

    
function hasBadFields (fields) {
      
  var errors = new Array();
  // some constants to make the code clearer
  var is_popup = 0;
  
  for (var ix = 0; ix < fields.length; ix++) {
          
    var f = fields[ix];

    var selector   = f[0];
    var name       = f[1];
    var re         = f[2];
    var display_as = f[3];
    
    var bill_prefix = /^\#cu\_/;
    var ship_prefix = /^\#ship\_/;
    var credit_prefix = /^\#x\_/;
    
    var h2_id_selector = "";
    
    fieldTrimmer(selector); // Trim the fields
    
    if (ship_prefix.test(selector)) {
      
      h2_id_selector = selector.replace(ship_prefix,"");
      h2_id_selector = "#" + h2_id_selector + "_ship";
    }
    
    else if (bill_prefix.test(selector)) {
      
      h2_id_selector = selector.replace(bill_prefix,"");
      h2_id_selector = "#" + h2_id_selector + "_cu";
    }
    
    else if (credit_prefix.test(selector)) {
      
      h2_id_selector = selector.replace(credit_prefix,"");
      h2_id_selector = "#" + h2_id_selector + "_x";
    }
     
    if( display_as == "popup" ) { is_popup = 1 }
    
    var frm_elt_class = jQuery(selector).attr("class");
    
    if ( !jQuery(selector).val() ) {
          
      errors.push(name + " is a required field.");
  
      jQuery(h2_id_selector).attr("class", "error");
      
      
      if (!(/\_error$/.test(frm_elt_class))) {
        frm_elt_class += "_error";
      }

    } else if ( !checkField(jQuery(selector).val(), re) ) {

      errors.push(name + " is not valid.");
      
      jQuery(h2_id_selector).attr("class", "error");
      
      
      if (!(/\_error$/.test(frm_elt_class))) {
        frm_elt_class += "_error";
      }

    } else {             
      
      jQuery(h2_id_selector).removeAttr("class");
      
      if (/\_error$/.test(frm_elt_class)) {
        
       frm_elt_class = frm_elt_class.replace(/\_error$/,"");
      }
    }

    jQuery(selector).attr("class", frm_elt_class);	
  }

  if (is_popup) {
    return errors.join('\n');
  } else if (errors.length){
    var str = '<ul><li>';
    str += errors.join('<li>'); 
    str += '</ul>';
    return str;
  } else {
    return '';
  }
}

function submitForm() {
 
  var have_errors = "";
  var have_ship_errors = ""; 
  var have_bill_errors = "";
  var error_text = '';             
  
  // Check shipping fields.  
  var fields_shipping =  new Array(	['#ship_firstname', 'First Name', 'name', 'popup'],
                                    ['#ship_lastname', 'Last Name', 'name', 'popup'],
                                    ['#ship_address1', 'Address', 'address', 'popup'],
                                    ['#ship_city', 'City', 'city', 'popup'],
                                    ['#ship_email', 'Email', 'email', 'popup']);
  
  // Doesn't quite match actual implementation, but it'll work.  
  if ( (jQuery('#cu_country_id').val() == 'ca') || (jQuery('#cu_country_id').val() == 'us') ) {
              
    fields_shipping.push( ['#ship_st_prov', 'State', 'letters', 'popup'],
                          ['#ship_phone', 'Phone', 'phone', 'popup']);
                                             
    if (jQuery('#cu_country_id').val() == 'us') {
      fields_shipping.push( ['#ship_zip_post', 'Zip', 'zip', 'popup']);
    }
    
    else {
      fields_shipping.push( ['#ship_zip_post', 'Postal Code', 'num_letters', 'popup']);
    }  
  }
   
  else {
   
    fields_shipping.push( ['#ship_st_foreign', 'State or Province', '', 'popup'],
                          ['#ship_phone', 'Phone', 'digits', 'popup'],
                          ['#ship_zip_post', 'Postal Code', '', 'popup']);
 
  }
 
  have_ship_errors += hasBadFields(fields_shipping);
  
  if (have_ship_errors != "") {
    have_ship_errors = "Please correct the following Shipping errors: \n" + have_ship_errors;
  }
  
  if (jQuery('#diff_bill_ship').val() == 1) {
    
    var fields_billing =  new Array(	['#cu_firstname', 'First Name', 'name', 'popup'],
                                      ['#cu_lastname', 'Last Name', 'name', 'popup'],
                                      ['#cu_address1', 'Address', 'address', 'popup'],
                                      ['#cu_city', 'City', 'city', 'popup']);
    
    if ( (jQuery('#cu_country_id').val() == 'ca') || (jQuery('#cu_country_id').val() == 'us') ) {
              
      fields_billing.push( ['#cu_st_prov', 'State', 'letters', 'popup'],
                           ['#cu_phone', 'Phone', 'phone', 'popup']);
                                               
      if (jQuery('#cu_country_id').val() == 'us') {
        fields_billing.push( ['#cu_zip_post', 'Zip', 'zip', 'popup']);
      }
      
      else {
        fields_billing.push( ['#cu_zip_post', 'Postal Code', 'num_letters', 'popup']);
      }
  
    }
    
    else {
      
      fields_billing.push( ['#cu_st_foreign', 'State or Province', '', 'popup'],
                           ['#cu_phone', 'Phone', 'digits', 'popup'],
                           ['#cu_zip_post', 'Postal Code', '', 'popup']);
  
    }
  
    have_bill_errors += hasBadFields(fields_billing);
    
    if (have_bill_errors != "") {
      
      var newlines = "";
      
      if (have_ship_errors != "") {
        newlines = "\n\n";
      }
      
      have_bill_errors = newlines + "Please correct the following Billing errors: \n" + have_bill_errors;
    }
  }
  
  have_errors = have_ship_errors + have_bill_errors;
  
  if (have_errors != "") {
    
    alert (have_errors);
    
    return false;  
  }
}


function submitOrder() {

  var have_cc_errors = "";
  var have_exp_errors = "";
  
  var fields_credit = new Array ( ['#x_card_num', 'Credit Card Number', 'digits', 'popup'],
                                  ['#x_Card_Code', 'CVV2', 'digits', 'popup'],
                                  ['#x_cc_type', 'Credit Card Type', 'letters', 'popup'] );
  
  var fields_exp = new Array ( ['#x_Exp_Month', 'Expiration Month', 'digits', 'popup'],
                               ['#x_Exp_Year', 'Expiration Year', 'digits', 'popup'] );
  
  have_exp_errors += hasBadFields(fields_exp);
  
  if (have_exp_errors != "") {
     
     have_exp_errors = "\n" + have_exp_errors;
     
     jQuery('#exp_x').attr("class", "error");      
  }
  
  else {
    
    jQuery('#exp_x').removeAttr("class");     
  }
  
  have_cc_errors += hasBadFields(fields_credit);
  
  have_cc_errors += have_exp_errors;
  
  if (have_cc_errors != "") {
    
    have_cc_errors = "Please correct the following credit card errors: \n" + have_cc_errors;
    
    alert (have_cc_errors);
    
    return false;
  }
  
  else {
    
    if ( (jQuery('#x_card_num').val().length < 13) || (jQuery('#x_card_num').val().length > 16) ) {
      
      have_cc_errors += "The credit card number must be at least 16 digits long.\n";  
    }
    
    if (jQuery('#x_Card_Code').val().length < 3) {
      
      have_cc_errors += "The CVV2 number must be at least 3 numbers long.\n";      
    }
    
        
    if (have_cc_errors != "") {
      
      have_cc_errors = "Please correct the following credit card errors: \n" + have_cc_errors;
        
      alert (have_cc_errors);
      
      return false;
    }
  }
  
  if (jQuery('[name=agreement_accept]:checked').length == 0) {
    
    alert ("You must accept the Terms & Conditions to complete your free trial request.");
    
    return false;
  }
}