/******************************************************************************/
/*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 using GET:                                                 */
/*         var ajax = new AjaxNow();                                          */
/*         ajax.id = 'objTarget.id;                                           */
/*         ajax.statusId = objStatus.id;                                      */
/*         ajax.url = 'somePage.php?params=values';                           */
/*		   //ajax.unique = false; //Default: true							  */
/*         ajax.async = false;   //Default: true                              */
/*         ajax.method = 'POST'; //Default: GET                               */
/*         ajax.callBack = 'TellMe( "Finished!" )';                           */
/*         ajax.Run();                                                        */
/*  AjaxNow SAMPLE using POST:                                                */
/*         var ajax = new AjaxNow();                                          */
/*         ajax.id = 'objTarget.id;                                           */
/*         ajax.statusId = objStatus.id;                                      */
/*         ajax.url = 'somePage.php';				                          */
/*		   ajax.unique = false; //Default: true			    				  */
/*		   ajax.send = 'name1=value1&name2=value2'							  */
/*         ajax.method = 'POST'; //Default: GET                               */
/*         ajax.callBack = 'TellMe( "Finished!" )';                           */
/*         ajax.Run();  													  */
/*  AjaxNow SAMPLE for Cross Domain scripting:                                */
/*         var ajax = new AjaxNow();                                          */
/*         ajax.id = 'objTarget.id;                                           */
/*         ajax.statusId = objStatus.id;                                      */
/*         ajax.url = 'somePage.php'; //params may be appended here for GET   */
/*									  //or pased through ajax.send for POST	  */
/*		   ajax.remote = true; //default: false  							  */
/*							   //requires the proxy.php to be installed in	  */
/*							   //in the same directory						  */
/*         ajax.method = 'POST'; //This is required for Remote                */
/*         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 outputId = null;
var statusResult = null;
var result = null;
var endEvent = null;
var proxy_url = '/sjc/ajaxnow/proxy.php';
var qsSym = '?';

//Public CLASS
function AjaxNow()
{
  this.id = null;
  this.statusId = null;
  this.indicator = null;
  this.url;
  this.remote = false;
  this.unique = true;
  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 );
  	  
  	  //Remote URL bypass
  	  var remote_url = null;
  	  if ( this.remote )
  	  {
  	  	//split data
  	  	var arr = null;
  	  	
  	  	if ( this.send != null )
  	  	{
  	  		arr = this.send.split( '&' );

			this.send = 'sjcmethod=' + this.method + '&sjcurl=' + this.url
  	  		
  	  		qsSym = '&sjcdata=';
			for ( i = 0; i < arr.length; i++ )
			{
				this.send += qsSym + arr[ i ];
				qsSym = '!sjc!';
			}
  	  	}
  	  	else
  	  	{
			this.send = 'sjcmethod=' + this.method + '&sjcurl=' + this.url + '&sjcdata=';
  	  	}
  	  	
  	  	this.url = proxy_url;
  	  }
  	  
      //Make query string unique - handles existing parameters
      if ( this.unique )
      {
		  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 )
      {
        statusResult.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';
      }
      
      //Force POST if Remote
      //	This is required to pass 
      //	the expected POST params 
      //	to the proxy
      if ( this.remote )
      {
      	this.method = 'POST';
      }
      
      //If target id
      if ( this.id != null )
      {
      	outputId = this.id;
      }
      
      //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 ...';
            
            if ( outputResult == null )
            {
            	outputResult.innerHTML = '';
	            result = http.responseText;
            }
            else
            {
            	outputResult.innerHTML = 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 )
  {
	if ( outputId == null )
	{
		outputResult.innerHTML = '';
		result = http.responseText;
	}
	else
	{
		outputResult.innerHTML = http.responseText;
	} 
 /*
   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;    
    }
 }
