// $Id: ajaxsubmit.js,v 1.8.2.5 2008/04/14 16:10:31 nedjo Exp $

/**
 * Attaches the ajaxsubmit behaviour to forms.
 */
Drupal.behaviors.ajaxSubmit = function (context) {
  $('form.ajaxsubmit:not(.ajaxsubmit-processed)').each(function () {
    if (this.ajaxsubmit_target) {
      var target = this.ajaxsubmit_target.value;
    }
    else {
      var target = document.createElement('div');
      $(target).addClass('ajaxsubmit-message');
      $(this).before(target);
    }
    // Set a flag to indicate that the form is using ajaxsubmit.
    if (!this.ajaxsubmit) {
      var ajaxsubmitInput = document.createElement('input');
      $(ajaxsubmitInput)
        .attr('type', 'hidden')
        .attr('name', 'ajaxsubmit')
        .attr('value', '1');
      $(this).append(ajaxsubmitInput);
    }
    $(this).addClass('ajaxsubmit-processed');
    new Drupal.ajaxsubmit(this, target);
  });
};

/**
 * JS ajaxsubmit object.
 */
Drupal.ajaxsubmit = function (form, target) {
  this.target = target;
  this.form = form;

  if(this.form.action.indexOf('?') > -1) {
    dylanFormDestination = this.form.action.substring(this.form.action.indexOf('?') + 1);
    dylanFormDestination = dylanFormDestination.replace('destination=', '');

    // Sorry - hashes must die.
    if(dylanFormDestination.indexOf('%2523') > -1) {
      dylanFormDestination = dylanFormDestination.substr(0, dylanFormDestination.indexOf('%2523'));
    }

    this.destination = dylanFormDestination;

    // Sorry - no question marks allowed, since they mean destinations.
    this.form.action = this.form.action.substr(0, this.form.action.indexOf('?'));    
  }

  Drupal.dylanRedirectFormSubmit($(form).attr('action'), form, this);
};

/**
 * Handler for the form redirection submission.
 */
Drupal.ajaxsubmit.prototype.onsubmit = function () {   
  //dylan_debug("Form submitted!");
  // Remove any error messages.
  var form = this.form;
  for (var i = 0; elt = form.elements[i]; i++) {
    $(elt).removeClass('error');
  }
  $(this.target).html('');
  // Insert progressbar.
  if (form.ajaxsubmit_progress) {

    // Success: redirect to the summary.
    var submitCallback = function (progress, status, pb) {
      if (progress == 100) {
        pb.stopMonitoring();
        window.location = '';
      }
    }

    // Failure: point out error message and provide link to the summary.
    var errorCallback = function (pb) {
      var div = document.createElement('p');
      $(div)
        .addClass('error')
        .html('An unrecoverable error has occured. You can find the error message below.');
      $('#progress').children(0).before(div);
      $('#wait').css('display', 'none');
 
    }
    this.progress = new Drupal.progressBar('updateprogress', submitCallback, HTTPPost, errorCallback);
    this.progress.startMonitoring(Drupal.url(form.ajaxsubmit_progress.value, 'form_id=' + form.form_id.value), 0);
  }
  else {
    this.progress = new Drupal.progressBar('ajaxsubmitprogress');
  }
  this.progress.setProgress(-1, 'Loading');
  //this.progress.element.style.width = '28em';
  //this.progress.element.style.height = '200px';
  //$(this.progress.element).css('width', '98%').css('position', 'absolute').css('bottom', '0');
  $(this.progress.element).addClass('progress-bar');

  $(this.target).append(this.progress.element);

};

/**
 * Handler for the form redirection completion.
 */
Drupal.ajaxsubmit.prototype.oncomplete = function (data) {
  //dylan_debug("Form oncomplete() handler.");
  //print_r(data);

  // Remove progressbar
  $(this.progress.element).remove();
  this.progress = null;
  
  var messageDelay = false;
  
  if(data['message']) {
    //dylan_debug("Message ");
    if ( $("#nyroModalFull").is(":visible").length > 0 ) {
      $(this.target).css('width', '98%').css('position', 'absolute').css('bottom', '0');
      $(this.target).html(data['message']);
    }
    else {
      scrollTo(this.target);
    }
    messageDelay = true;
    
    convertLinks(this.target);
  }
  
  if (data['errors']) {
    //dylan_debug('Oh noes - return has errors!');
    for (id in data['errors']) {
      // edit[foo][bar] -> foo-bar
      $('#edit-' + id.replace('][', '-')).addClass('error');
    }
  } else if (data['preview']) {
    //dylan_debug('Data preview: ' + data['preview']);
    $(this.target).html($(this.target).html() + data['preview']);
  } else if (data['destination']) {
    //dylan_debug('Data destination! ' + data['destination']);
    // This will never happen.
    SWFAddress.setValue('/' + data['destination']);
    //window.location = Drupal.url(data['destination']);
  } else if (data['redirect']) {
      //alert('Form submitted... the redirect is: ' + data['redirect']);
      dylan_debug('Form submitted... the redirect is: ' + data['redirect']);
      if (messageDelay) {
        setTimeout("$(this.target).fadeOut(); SWFAddress.setValue('/' + data['redirect']);", 7000);
      } else {
        SWFAddress.setValue('/' + data['redirect']);    
      }  
  } else {
    $(this.form).fadeOut();

    if (this.destination) {
      //this.destination = unescape(this.destination);
      //dylan_debug('Form submitted... destination is: ' + this.destination);      


      /*
      if (messageDelay) {
        setTimeout("$(this.target).fadeOut(); SWFAddress.setValue('/' + this.destination);", 5000);   
      } else {
      */
        if ( $("#nyroModalFull").is(":visible").length > 0 ) {
          SWFAddress.setValue('/' + this.destination);    
        }
        else {
	  if ( messageDelay ) {
	    //setTimeout("$('#nyroModalContent').remove();", 5000);
	    //setTimeout("$('#nyroModalFull').close();", 5000);
	    //setTimeout("$('#nyroModalFull').remove();", 5000);
	    setTimeout("$('#nyroModalWrapper').fadeOut(1000,function(){$('#nyroModalFull').remove()})", 5000);
	  }
          dylanMessageModal = true;
          $.nyroModalManual({
            content: data['message']
          });
          SWFAddress.setValue('/' + this.destination);
        }
      
      /*
      }
      */
    } else {
      //dylan_debug('Form submitted... no destination found, let us head here: ' + this.destination);
      if(messageDelay) {
        setTimeout("$(this.target).fadeOut(); renderPage(SWFAddress.getValue());", 5000);   
      } else {
        // No destination, so reload the current page.
        renderPage(SWFAddress.getValue());          
      }
    }
    return;
  }

  /*
  // Redirect.
  if (data['destination']) {
    window.location = Drupal.url(data['destination']);
  }
  */

  Drupal.scrollTo(this.target);
  Drupal.attachBehaviors(this.target);
};

/**
 * Handler for the form redirection error.
 */
Drupal.ajaxsubmit.prototype.onerror = function (error) {
   //dylan_debug("ERROR IN FORM SUBMISSION!");
  // Remove progressbar
  $(this.progress.element).remove();
  this.progress = null;
  // Go to a designated error page, if any.
  var form = this.form;
  $(this.target).html(form.ajaxsubmit_error_message ? form.ajaxsubmit_error_message.value : 'An error occurred:<br /><br />'+ error);
  if (form.ajaxsubmit_error_redirect) {
    //NO!
    window.location.href = form.ajaxsubmit_error_redirect.value;
  }
};

/**
 * Redirects a form submission to a hidden iframe and displays the result
 * in a given wrapper. The iframe should contain a call to
 * window.parent.iframeHandler() after submission.
 */
Drupal.dylanRedirectFormSubmit = function (uri, form, handler) {
  $(form).submit(function() {
    // Create target iframe
    Drupal.createIframe();

    // Prepare variables for use in anonymous function.
    var form = this;

    // Redirect form submission to iframe
    this.action = uri;
    this.target = 'redirect-target';

    //$(this.target).css('width', '80%').css('height', '24px');

    handler.onsubmit();

    // Set iframe handler for later
    window.iframeHandler = function () {
      var iframe = $('#redirect-target').get(0);

      // Get response from iframe body
      try {
        response = (iframe.contentWindow || iframe.contentDocument || iframe).document.body.innerHTML;
        // Firefox 1.0.x hack: Remove (corrupted) control characters
        response = response.replace(/[\f\n\r\t]/g, ' ');
        if (window.opera) {
          // Opera-hack: it returns innerHTML sanitized.
          response = response.replace(/&quot;/g, '"');
        }
      }
      catch (e) {
        //dylan_debug("OH NOES ERROR!");
        response = null;
      }

      response = Drupal.parseJson(response);
      // Check response code
 
      if (!is_object(response.data)) {
        Drupal.deleteIframe();
		//$.nyroModalRemove();
        renderPage(SWFAddress.getValue());
		
        return false;
      }
      
      if (response.status == 0) {
        handler.onerror(response.data);
        return;
      }
      handler.oncomplete(response.data);

      return true;
    };

    return true;
  });
};

function is_object( mixed_var ){
    // http://kevin.vanzonneveld.net
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Legaev Andrey
    // +   improved by: Michael White (http://crestidg.com)
    // *     example 1: is_object('23');
    // *     returns 1: false
    // *     example 2: is_object({foo: 'bar'});
    // *     returns 2: true
    // *     example 3: is_object(null);
    // *     returns 3: false
 
    if(mixed_var instanceof Array) {
        return false;
    } else {
        return (mixed_var !== null) && (typeof( mixed_var ) == 'object');
    }
}

function print_r( array, return_val ) {
    // http://kevin.vanzonneveld.net
    // +   original by: Michael White (http://crestidg.com)
    // +   improved by: Ben Bryan
    // *     example 1: print_r(1, true);
    // *     returns 1: 1
 
    var output = "", pad_char = " ", pad_val = 4;
 
    var formatArray = function (obj, cur_depth, pad_val, pad_char) {
        if (cur_depth > 0) {
            cur_depth++;
        }
 
        var base_pad = repeat_char(pad_val*cur_depth, pad_char);
        var thick_pad = repeat_char(pad_val*(cur_depth+1), pad_char);
        var str = "";
 
        if (obj instanceof Array || obj instanceof Object) {
            str += "Array\n" + base_pad + "(\n";
            for (var key in obj) {
                if (obj[key] instanceof Array) {
                    str += thick_pad + "["+key+"] => "+formatArray(obj[key], cur_depth+1, pad_val, pad_char);
                } else {
                    str += thick_pad + "["+key+"] => " + obj[key] + "\n";
                }
            }
            str += base_pad + ")\n";
        } else {
            str = obj.toString();
        }
 
        return str;
    };
 
    var repeat_char = function (len, pad_char) {
        var str = "";
        for(var i=0; i < len; i++) { 
            str += pad_char; 
        };
        return str;
    };
    output = formatArray(array, 0, pad_val, pad_char);
 
    if (return_val !== true) {
        dylan_debug(output);
        return true;
    } else {
        return output;
    }
}

