/******************************************************************************/
/*SOURCE CODE: http://www.squarejelly.com                                     */
/*AUTHOR: Bradley A. Micallef                                                 */
/*SCRIPT: AjaxNow                                                             */
/*VERSION: 3.0                                                                */
/*DATE: 2006.12.05                                                            */
/*PURPOSE: Allow for server-side include functionality as well as remote      */
/*         scripting calls from non-server side pages, such as basic HTML     */
/*         pages, or as AJAX style event handlers in any web page including   */
/*         JAVA, .NET, PHP etc.                                               */
/*EXTERNAL SOURCES: This script was derived from the following two sources    */
/*         and constitutes a derivative work that is protected by the existing*/
/*         licences of both sources.                                          */ 
/*         http://www.boutell.com/newfaq/creating/include.html                */
/*         http://www.bigbold.com/snippets/posts/show/61                      */
/*CLASS SAMPLES:                                                              */
/*  AjaxNow SAMPLE:                                                           */
/*         var ajax = new AjaxNow();                                          */
/*         ajax.id = 'objTarget.id;                                           */
/*         ajax.statusId = objStatus.id;                                      */
/*         ajax.url = 'somePage.php?params=values';                           */
/*         ajax.async = false;   //Default: true                              */
/*         ajax.method = 'POST'; //Default: GET                               */
/*         ajax.callBack = 'TellMe( "Finished!" )';                           */
/*         ajax.Run();                                                        */
/*  CreatHtmlElement SAMPLE:                                                  */
/*         var html = new CreateHtmlElement();                                */
/*         html.elementTag = 'div'; //Default: div                            */
/*         html.elementId = 'tool_1'; //Default: null                         */
/*         html.elementClass = 'StatusBar'; //Default: null                   */
/*         html.elementContent = mesgText; //Default: null                    */
/*         html.parentId = null; //Default: null - adds new element to <body/>*/
/*         html.Run();                                                        */
/******************************************************************************/

var http = null;
var outputResult = null;
var statusResult = null;
var result = null;
var endEvent = null;

//Public CLASS
function AjaxNow()
{
  this.id;
  this.statusId;
  this.indicator = null;
  this.url;
  this.async = true;
  this.method = 'GET';
  this.send = null;
  this.callBack = null;
  
  this.Run = function()
  {

      //alert( 'id: ' + this.id + '\nStatusId: ' + this.statusId + '\nurl: ' + this.url + '\nasync: ' + this.async + '\nmethod: ' + this.method + '\nsend: ' + this.send );
  
      //Make query string unique - handles existing parameters
      var qsSym = '?';
      if ( this.url.indexOf( '?' ) != -1  )
      {
        qsSym = '&';
      }
      this.url += qsSym + 'unq=' + Math.random();
     
      //Create xmlHttpRequst obj
      http = __XmlHttp();
      
      //Status Element
      statusResult = document.getElementById( this.statusId );
      if ( !statusResult )
      {
        var html = new CreateHtmlElement();
        html.elementTag = 'div';
        html.elementId = this.statusId;
        html.elementClass = this.statusId;
        statusResult = html.Run();
      }
      
      //OutputElement
      outputResult = document.getElementById( this.id );
      if ( !outputResult )
      {
        var html = new CreateHtmlElement();
        html.elementTag = 'div';
        html.elementId = this.id;
        html.elementClass = this.id;
        outputResult = html.Run();
      }
      
      //Loading Indicator
      if ( this.indicator != null )
      {
        outputResult.innerHTML = this.indicator;
      }
      
      //Callback Event
      endEvent = this.callBack;
      if ( !this.callBack )
      {
        endEvent = null;
      }
      
      //Handle method
      if ( this.method.toUpperCase() == 'POST' || this.method.toUpperCase() == 'GET')
      {
          this.method = this.method.toUpperCase();
      }
      else
      {
          this.method = 'GET';
      }
      //Handle HTTP request
      if ( http )
      {
        try
        {
          //POST & GET, Async & Sync
          http.onreadystatechange = __PushResult;
          
          //Async & Sync
          http.open( this.method, this.url, this.async );
          
          //POST only
          if ( this.method == 'POST' )
          {
            if ( http.overrideMimeType )
            {
              http.overrideMimeType('text/html'); //text/xml
            }
            http.setRequestHeader( 'Content-type', 'application/x-www-form-urlencoded' );
            http.setRequestHeader( 'Content-length', this.send.length );
            http.setRequestHeader( 'Connection', 'close' );
          }
          
          //POST & GET, Async & Sync
          http.send( this.send );
          
          //Async notification only
          if ( this.async == false )
          {
            statusResult.innerHTML = 'Loading ...';
            outputResult.innerHTML = http.responseText;
            result = http.responseText;
            statusResult.innerHTML = '';
          }
        }
        catch( e )
        {
          statusResult.innerHTML = '';
          outputResult.innerHTML = 'Error: \'' + this.url + '\' ... failed to load properly.<br/>Details: ' + e.description;
          
          result = false;
        }
      }
      else
      {
        statusResult.innerHTML = '';
        outputResult.innerHTML = 'Error: AjaxNow failed to load properly.';
        
        result = false;
      }
      return result;
  }
}

//Display status for Async
function __PushResult()
{
  if ( http.readyState == 4 )
  {
    outputResult.innerHTML = http.responseText;
    result = http.responseText;
    statusResult.innerHTML = '';
    
    //Call end event function
    if ( endEvent != null )
    {
    	eval( endEvent );
    }
  }
  else
  {
    statusResult.innerHTML = 'Loading ...';
  }
  
  return true;
}
//Create xmlHttpRequest
function __XmlHttp()
{
  //Non PC or Non IE
  var xmlReq = false;
  if ( window.XMLHttpRequest )
  {
    try
    {
      xmlReq = new XMLHttpRequest();
    }
    catch( e )
    {
      xmlReq = false;
    }
  }
  else if ( window.ActiveXObject )
  {
    //PC - IE
    try
    {
      xmlReq = new ActiveXObject( 'Msxml2.XMLHTTP' );
    }
    catch( e )
    {
      try
      {
        xmlReq = new ActiveXObject( 'Microsoft.XMLHTTP' );
      }
      catch( e )
      {
        xmlReq = false;
      }
    }
  }
  return xmlReq;
}

//Public CLASS
//Create missing element tags


function CreateHtmlElement()
{
    this.elementTag = 'div';
    this.elementId = null;
    this.elementClass = null;
    this.elementContent = null;
    this.parentId = null;
    
    this.Run = function() {
        var elem = null;
        
        if ( this.elementTag != null )
        {
            //Create Element
            elem = document.createElement( this.elementTag ); 
            
            //Assign Element ID
            if ( this.elementId != null )
            {
                elem.id = this.elementId;
            }
            //Assign Element Class
            if ( this.elementClass != null )
            {
                elem.className = this.elementClass
            }
            //Assign Element Content
            if ( this.elementContent != null )
            {
                if ( this.elementContent.indexOf( '<' ) != -1 )
                {
                    elem.innerHTML = this.elementContent;
                }
                else
                {
                    elem.appendChild( document.createTextNode( this.elementContent ) );
                }
            }
            
            //Assign to Parent Element
            var prnt = document.getElementById( this.parentId );
            if ( prnt )
            {
                //Append to Parent
                prnt.appendChild( elem );
            }
            else
            {
                //Append to Body
                document.getElementsByTagName('body').item(0).appendChild( elem );
            }
        }
        
        return elem;    
    }
 }
