/*
 * Bitmunk Forms Support
 *
 * @requires jQuery v1.2 or later (http://jquery.com/)
 * @requires jQuery Form Plugin (http://malsup.com/jquery/form/)
 *
 * @author David I. Lehn <dlehn@digitalbazaar.com>
 */
$(document).ready(function(){
   /**
    * Setup a form. 
    * 
    * @param i form index (for $(...).each(setupForm) usage)
    * @param form the form to setup
    */
   setupForm = function(i, form) {
      $(form).ajaxForm({
         dataType: 'xml',
         timeout: 35000,
         beforeSubmit: function(formData, jqForm, options) {
            formData.push({name: "actionType", value: "ajax"});
            formData.push({name: "form", value: jqForm.attr("id")});
            $(".inputFeedback,.formFeedback", jqForm).empty();
            return true;
         },
         success: function(responseXml, statusText) {
            $(":input", form).enable();
            replaceIds(responseXml);
            $("redirect_url", responseXml).eq(0).each(function(i, el) {
               window.location = $(el).text();
            });
         },
         error: function (XMLHttpRequest, textStatus, errorThrown) {
            $(":input", form).enable();
            $("#"+$(form).attr("id")+"-feedback").html("Request Error: " + textStatus);
         },
         beforeSend: function() {
            $(":input", form).enable(false);
            $("#"+$(form).attr("id")+"-activity").show();
         },
         complete: function() {
            // input enable() called in success() and error() in order to be
            // called before replaceIds() in the success() case.  Not called
            // here to avoid calling twice in the success() case.
            $("#"+$(form).attr("id")+"-activity").fadeOut(1250);
         }
      });
   };
   
   replaceIds = function(xml) {
      // find response_html or make an empty result set
      var text = $("response_html", xml).text() || [];
      // convert to DOM and find all DIVs with ids
      $(text).filter("div[id]").each(function(){
         // for each div replace div with same id in the main document with
         // the contents of the new div.
         $("#"+$(this).attr("id")).empty().append($(this).contents().clone(true));
      });
      // setup all the forms since new ones may have been added
      $("form.ajax").each(setupForm);
   };
   
   // setup all the forms
   $("form.ajax").each(setupForm);
});
