/**
 * AJAX functions for WebUpdate
 * Copyright (C) Absent Oy, All rights reserved.
 */

var targetId = "";
var ajaxURL  = "";
var request  = null;
var isWorking = false;

function initializeAjax( _targetId, _ajaxURL ) {
  targetId = _targetId;
  ajaxURL  = _ajaxURL;

  if ( ajaxURL.indexOf("?") == -1 )
    ajaxURL = ajaxURL + "?";
}

/**
 * Function initializes a request object which has already been constructed.
 * Parameters:
 *  requestType    - HTTP request type: GET or POST.
 *  url            - The URL of the handler script.
 *  asynchronous   - Boolean: use asynchronous connection or not.
 *  responseHandle - The name of the function that will handle the response.
 */
function initRequest( requestType, url, asynchronous, responseHandle ) {
  try {
      // Set the callback function
      request.onreadystatechange = responseHandle;

      // Try to open connection
      request.open( requestType, url, asynchronous );

      if( requestType.toLowerCase() == "post" ) {
        request.setRequestHeader( "Content-Type", "application/x-www-form-urlencoded; charset=iso-8859-1" );
        request.send( arguments[4] );
      } else {
        request.send( null );
      }
  } catch (errv) {
    isWorking = false;
    alert(  "The application cannot contact the server at the moment.\n"+
            "Please try again in a few seconds.\n" );
  }
}

/**
 * Function constructs a Request object. Handles both Mozilla-based
 * browsers and Microsoft-browsers.
 * Parameters:
 *  requestType    - HTTP request type: GET or POST.
 *  url            - The URL of the handler script.
 *  asynch         - Boolean: use asynchronous connection or not.
 *  responseHandle - The name of the function that will handle the response.
 *  Note:
 *  Any fifth parameters represented as arguments[4] are the data a
 *  POST request is designed to send.
 */
function httpRequest( requestType, url, asynch, responseHandle ) {
  try
  {
    // Firefox, Opera 8.0+, Safari
    request=new XMLHttpRequest();
  }
  catch (e)
  {
    // Internet Explorer
    try
    {
      request=new ActiveXObject("Msxml2.XMLHTTP");
    }
    catch (e)
    {
      try
      {
        request=new ActiveXObject("Microsoft.XMLHTTP");
      }
      catch (e)
      {
        alert("Your browser does not support AJAX!");
        return false;
      }
    }
  }

  // Test for a null request if neither ActiveXObject was initialized
  if ( request ) {
    if( requestType.toLowerCase() != "post" ) {
      initRequest( requestType, url, asynch, responseHandle );
    } else {
      //the POSTed data
      var args = arguments[4];
      if( args != null && args.length > 0 ){
        initRequest( requestType, url, asynch, responseHandle, args );
      }
    }
  }
}
