/**
 * Cleaned up and documented, but essentially copied from:
 *
 *  AJAX IFRAME METHOD (AIM)
 *  http://www.webtoolkit.info/
 *
 **/
var AIM = {
  /**
   * Create the div and the hidden iframe.  Attach the specified "onComplete" callback
   * so that when the form is submitted, we get notification in the main window
   */
  frame : function( callbacks )
  {
    var iFrameId = 'f' + Math.floor( Math.random() * 99999 );
    var newDiv = document.createElement( 'DIV' );
    newDiv.setAttribute( 'style', 'width:1px; height:1px;' );
    newDiv.innerHTML = '<iframe style="display:none" src="about:blank" id="' + iFrameId + '" name="' + iFrameId + '" onload="AIM.loaded(\'' + iFrameId + '\')" width="1" height="1"></iframe>';
    document.body.appendChild( newDiv );
    var iFrame = document.getElementById( iFrameId );
    if( callbacks && typeof( callbacks.onComplete ) == 'function' )
    {
      iFrame.onComplete = callbacks.onComplete;
    }
    return iFrameId;
  },
  /**
   * tell the form on the main page what the target frame should be
   */
  form : function( theForm, name )
  {
    theForm.setAttribute( 'target', name );
  },
  submit : function( theForm, callbacks )
  {
    AIM.form( theForm, AIM.frame( callbacks ) );
    if( callbacks && typeof( callbacks.onStart ) == 'function' )
    {
      return callbacks.onStart();
    }
    else
    {
      return true;
    }
  },
  loaded : function( iFrameId )
  {
    var iFrame = document.getElementById( iFrameId );
    var iFrameDocument;
    if( iFrame.contentDocument ) //ff
    {
      iFrameDocument = iFrame.contentDocument;
    }
    else if( iFrame.contentWindow ) //ie
    {
      iFrameDocument = iFrame.contentWindow.document;
    }
    else
    {
      iFrameDocument = window.frames[iFrameId].document;
    }
    if( iFrameDocument.location.href == "about:blank" )
    {
      return;
    }
    if( typeof( iFrame.onComplete ) == 'function' )
    {
      iFrame.onComplete( iFrameDocument.body.innerHTML, iFrameId );
    }
  }
}