/* AJAX main class wrapper.
 * (c) 2008 by Bert
 */
function CXMLHttp() {
  // Contructor
  this.xmlHttpReq = false;
  this.onDone = null;
  this.onError = null;
  this.xmlHttpVersionUsing = "";
  this._ms_xmlHttpVersion = "";
  this.m_div_elem = $('AJAXProgressDiv');
  this.m_charset = "windows-1251";
  if (this.m_div_elem != null)
    this.m_div_elem.innerHTML = '<img src="/img/sp.gif" border="0" alt="" title="" width="16" height="16">';

  // ------------------------

  // Return used XMLHttp version (embedded or ActiveX)
  this.getVersion = function() { 
    return this.xmlHttpVersionUsing;
  };

  // Create a XMLHttpRequest
  this.createXMLHttp = function() {
    var aVersions = [ 
        "MSXML2.XMLHttp.7.0",
        "MSXML2.XMLHttp.6.0",
        "MSXML2.XMLHttp.5.0",
        "MSXML2.XMLHttp.4.0",
	"MSXML2.XMLHttp.3.0",
        "MSXML2.XMLHttp",
	"Microsoft.XMLHttp" ];


    if (this._ms_xmlHttpVersion != "")
      this.xmlHttpReq = new ActiveXObject(this._ms_xmlHttpVersion);
    else {
      for (var i = 0; i < aVersions.length; i++) {
        try {
            this.xmlHttpReq = new ActiveXObject(aVersions[i]);
            this.xmlHttpVersionUsing = aVersions[i];
            this._ms_xmlHttpVersion = aVersions[i];
	    break;
        } catch (oError) {
           //Do nothing
        };
      };

      if (!this.xmlHttpReq) {
        this._ms_xmlHttpVersion = "";
        var ieHelp = (isIE) ? " * Откройте меню Сервис->Свойства обозревателя, затем откройте вкладку 'Безопасность'.\n * Щелкните на кнопке 'Другой'.\n * Найдите в дереве ветвь 'Элементы ActiveX и модули подключения'.\n * Установите значение 'Выполнять сценарии ActiveX помеченные как безопасные' в 'Разрешить'\n * Установите значение 'Запуск элементов ActiveX и модулей подключения' в 'Разрешить'" : '';
        throw new Error("MSXML не установлен или выполнение объектов ActiveX запрещены в настройках вашего браузера.\n" + ieHelp);
      };
    };
  };
  
  this.init = function() { 
    if ( this.xmlHttpReq )
      delete this.xmlHttpReq;

    this.xmlHttpReq = false;

    if ( window.XMLHttpRequest ) {
      this.xmlHttpReq = new XMLHttpRequest();
      this.xmlHttpVersionUsing = "XMLHttpRequest (embedded)";
    } else {
      if ( window.ActiveXObject ) {
        try {
          this.createXMLHttp();
        } catch (e) {
          alert(e.message);
        };
      } else {
        alert("AJAX assumed that ActiveX support should be turned on in your browser");
      };
    };
  };

  this.onStateChanged = function() { 
    if (this.xmlHttpReq.readyState == 4) { // Completed
      if (this.xmlHttpReq.status == 200 && typeof(this.onDone) == "function")
        this.onDone(this.xmlHttpReq); // Invoke attached event
      else if (this.xmlHttpReq.status != 200 && typeof(this.onError) == "function") 
	this.onError(this.xmlHttpReq); // Invoke attached event
      if (this.m_div_elem != null)
        this.m_div_elem.innerHTML = '';
    };
  };

  // Invokes a abstract query to the server
  this._doQuery = function(reqType, reqUrl, reqData) { 
    this.init();


    if (this.xmlHttpReq) { 

      var self = this;
      this.xmlHttpReq.onreadystatechange = function() { 
        self.onStateChanged(); 
      };

      if (this.m_div_elem != null)  
        this.m_div_elem.innerHTML = '<img src="/img/progress.gif" border="0" alt="AJAX query in progress" width="16" height="16">';
      
      this.xmlHttpReq.open(reqType, reqUrl, true);
      this.xmlHttpReq.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded;charset=' + this.m_charset);
      this.xmlHttpReq.send(reqData);
    };
  };
  
  // Invoke a GET query to server.
  this.getQuery = function(reqUrl) { this._doQuery('GET', reqUrl, ''); };
  // Invoke a POST query to server.
  this.postQuery = function(reqUrl, reqData) { this._doQuery('POST', reqUrl, reqData);};

  // Set up the div element to show the progress icon  
  this.setProgressDiv = function(divId) { 
    var el = $(divId);
    if (typeof(el) != 'undefined')
      this.m_div_elem = el;
  };

  this.setCharset = function(value) { this.m_charset = value; };
  this.abort = function() { if (this.xmlHttpReq) this.xmlHttpReq.abort(); };
};

