/**********************************
* Other scripts
**********************************/


(function($) {
      $.fn.ajaxifyForm = function(settings) {
      //This crashes IE6 :-(
         var $self = $(this);
          var self = this;
          
          settings = settings || {};
          
          $self.ajaxForm({
              dataType:  'json',
    
              beforeSubmit: function(){
                  if (settings.beforeSubmit && settings.beforeSubmit() == false) {
                      return false; // Don't submit the form
                  }
                  $('.form-error-container').fadeOut('fast');
                  if (settings.submit_button != undefined) {
                      self.submit_button_text = settings.submit_button.attr('value');
                      settings.submit_button.attr('value', 'Processing...');
                      settings.submit_button.attr("disabled", "true");
                  }
                  return true; // All fine, you can submit the form
              },
              
              success: function(json){
                  if (settings.submit_button != undefined) {
                      settings.submit_button.attr('value', self.submit_button_text);
                      settings.submit_button.removeAttr('disabled');
                  }
                  if (!json['form_valid']) {
                      for(var field_name in json['errors']){
                          $('#errors_' + field_name).html(json['errors'][field_name]).fadeIn('slow');
                      }
                  }
                  else {
                      if (settings.success && jQuery.isFunction(settings.success)) {
                          settings.success(json['result']);
                      }
                      else {
                          window.location = json['redirect_url'];
                      }
                  }
              },
              
              error: function() {
                  //todo: give a popup saying that an error occurred on the server
                  if (settings.submit_button != undefined) {
                      settings.submit_button.attr('value', self.submit_button_text);
                      settings.submit_button.removeAttr('disabled');
                  }
                  if (settings.error && jQuery.isFunction(settings.error)) {
                      settings.error();
                  }
              }
          });
      };
      
    })(jQuery);
    