(function($) {
  $.fn.survey = function(options) {
    var settings = {
      // reg: 49128, // default
      // key: 'DwczcaAL',
      // 'try': 'true'
      url: 'http://' + window.location.hostname + '/tinc',
      type: 'POST', 
      ok: '<p>Thank you, our records have been updated.</p>'
    };
    
    $.extend(settings, options);
    
    // collect form inputs and merge to create submitted data
    return this.each(function() {
      if (this.nodeName.toLowerCase() != 'form') {
        if (typeof console != 'undefined') console.log('not a form');
        return false; 
      } // sanity check
      
      var inputs = $(':input', this);
      var $$ = $(this);
      $$.submit(function() {
        var t = this;
        var postData = {};
        inputs.each(function() {
          if (this.name) postData[this.name] = this.value;
        });
        
        var ok = $('div.surveySuccess', this);
        var fail = $('div.surveyError', this);
        ok.hide();
        fail.hide();
        
        if (settings.test) {
          if (typeof console != 'undefined') console.log(postData);
        }
        
        try { // to ensure we don't follow through on the form.
          $.ajax({
            url: settings.url,
            data: postData,
            type: settings.type,
            dataType: 'html',
            success: function(xml) {
              if (!xml.length) {
                if (typeof console != 'undefined') console.log('empty response');
                return false;
              }

              xml = xml.substring(xml.indexOf('<body>') + '<body>'.length);
              xml = xml.substring(0, xml.indexOf('</body>'));

              if (settings.test) {
                if (typeof console != 'undefined') console.log($('div.error', xml));
              }

              var error;

              $$.before('<div id="_ret"></div>');
              var ret = $('#_ret').hide().append(xml);
              error = $('div.error', ret);
              
              if (error.length == 0) { // success
                fail.html('').hide();
                var h = settings.ok;
                if ($.browser.msie) h = '<p>&nbsp;</p>' + h; // silly IE
                ok.html(h).fadeIn();
              } else {
                var errors = $('ul', error);
                ok.html('').hide();
                fail.html('<p>The following error occurred:</p><ul>' + errors.html() + '</ul>').fadeIn();
              }
            }
          });
        } catch (e) {
          if (typeof console != 'undefined') console.log('ajax failed: ',  e);
        } finally {
          $('#_ret').remove();
        }
         
        return false;
      });
      $('div.out', this).append('<div class="surveyError no"></div><div class="surveySuccess no"></div>');
    });
  };
})(jQuery);