/*
 * Add side-offers page to any quotebox that appears on the page
 */

jQuery(document).ready(function() {
  var zip_pattern = /^\d{5}$/;
  var forms = jQuery('form');
  forms.each(function(i, e) {
    if ( /\/?quotebox_handler\.php$/.test( jQuery(e).attr('action') ) ) {
      // change the form action to the offers page and the method to GET
      jQuery(e).attr('action', 'results.php'); // the offers page
      jQuery(e).attr('method', 'get');

      // add a submit action that will open the form with the inputs as URL parameters
      jQuery(e).submit(function(e) {
        var form = jQuery(e.target);
        var zip = form.find('input[name=address1_zip]').val(); // input whose name is 'zip'
        var snr = form.find('input[name=is_over65]:checked').val();

        // handle invalid zips
        if (!zip_pattern.test(zip)) {
          alert('Please provide a valid zip.');
          e.preventDefault();
          return;
        }

        // pop the form
        var params  = "toolbar=yes,menubar=yes,location=yes,scrollbars=yes,resizable=yes,status=yes,width="+screen.width+",height="+screen.height+",fullscreen=yes";
        var pops    = "quotebox_handler.php" + "?address1_zip=" + zip;
        if (snr && /^(Y|N)$/i.test(snr) ) pops += '&is_over65=' + snr;
        window.open(pops, "", params);
      });
    }
  });
});
