
var localHTTPRequest;

function HTTP(obj, url) {
  o 					= new Object();
  o.id 				= obj;
  eval(o.id+'=o');
  o.wait			= 0;
  o.headers 	= ['multipart/form-data', 'application/x-www-form-urlencoded'];
  if (HTTP.arguments.length <= 2)
  	o.method 		= 'GET'; else
  { // Тип запроса указан явно
  	switch(HTTP.argumants[2]) {
    	case 'GET':  o.method = 'GET'; break;
      case 'POST': o.method = 'POST'; break;
      default:     o.method = 'GET'; break;
    }	// switch
  } // if
  o.path			= url;
  o.params 		= new Array();
  o.ticker		= false;
  o.receiver	=	'';					// Содержимое возврата
  o.readyState= 0;          // Текущее состояние объекта (0 — не инициализирован, 1 — открыт, 2 — отправка данных, 3 — получение данных и 4 — данные загружены) ]
  o.status		= 0;          // Код результата обработки
  o.statustext= '';         // Текстовое представление кода
  o.onSuccess	=	null; 			// функция обратного вызова при успехе
  o.onFailure	= null; 			// Функция обратного вызова при неудаче
  o.idReceive	= ''; 				// ID объекта куда надо разместить код ответа

  // Установка адреса отправки запроса ========================================
  o.Reset						= function() 					{ this.params = new Array(); this.stopTimer(); }
  o.setMethod				= function(method) {
    switch(method) {
    	case 'GET':  this.method = 'GET'; break;
      case 'POST': this.method = 'POST'; break;
      default:     this.method = 'GET'; break;
    }	// switch
  }	// function
  o.setUrl					= function(url) 			{ this.path = url; }
  o.setReceiver			= function(oID)				{ this.idReceive = oID; }
  o.setOnSuccess		= function(func) 			{ this.onSuccess = func; }
  o.setOnFailure		= function(func) 			{ this.onFailure = func; }
  o.setQueryString 	= function(qstring) 	{
    this.params = new Array();
  	w = (qstring != '' ? qstring.split('&') : new Array());
  	for (i=0; i < w.length; i++) {
    	c = w[i].split('=',2);
      this.params.push( new Array( c[0], (c.length > 1 ? c[1]:'') ) );
  	}	// for
  } // function

  o.Init	= function() {
  	this.params = new Array();
  	if (window.XMLHttpRequest) {
        try {
            localHTTPRequest = new XMLHttpRequest();
            return true;
        } catch (e){}
    } else
    if (window.ActiveXObject) {
        try {
            localHTTPRequest = new ActiveXObject('Msxml2.XMLHTTP');
            return true;
        } catch (e){
          try {
              localHTTPRequest = new ActiveXObject('Microsoft.XMLHTTP');
              return true;
          } catch (e){}
        }
    }
    return false;
  } // function

  o.isKey 	= function (key) 	{
  		for (i=0; i < this.params.length; i++)
      	if (this.params[i][0] == key) return true;
      return false;
  }	// function

  o.remKey = function (key) {
      for (i=0; i < this.params.length; i++)
      	if (this.params[i][0] == key) this.params[i][0] = '';
  }	// function

  o.delKey 		= function(key) { this.remKey(key); }

  o.getResult	= function()		{ return this.receiver; }
  o.getMethod = function() 		{ return this.method; }
  o.getValue  = function(key) {
      for (i=0; i < this.params.length; i++)
      	if (this.params[i][0] == key) return this.params[i][1];
      return '';
  }	// function

  o.setValue = function(key,val) {
      for (i=0; i < this.params.length; i++)
      	if (this.params[i][0] == key)
        { this.params[i][1] = val; return true; }
  		this.params.push( new Array(key,val) );
  } // function

  o.getUrl = function () {
  		var str = '';
  		if (this.method == 'GET') str = this.getParams();
      return this.path + (str != '' ? '?'+str : '');
  	}	// function

  o.getParams = function () {
      var str = '';
      for (i=0; i < this.params.length; i++)
      	if (this.params[i][0] != '')
      		 str += (str != '' ? '&':'') + this.params[i][0] +'='+ this.params[i][1];
      return str;
  	} // function

  o.Erase = function () { this.params = new Array(); }
  o.Url = function () 	{ return this.getUrl(); }

  o.Response		= function() { if (typeof(this.callback) == 'function') this.callback(this.result); }
  o.stopTimer		= function() { clearTimeout(this.ticker); this.ticker = false; }
  o.startTimer	= function() {
  		if (this.ticker) this.stopTimer();
    	this.ticker = setTimeout(this.id+'.Timer()', 10);
  	}	// function

  o.Timer				= function() {
    try {
    	this.readyState = localHTTPRequest.readyState;
			if (this.readyState == 4)
      { this.stopTimer();
      	this.status 		= localHTTPRequest.status;
        this.statustext = localHTTPRequest.statusText;
      	if (this.status == 200)
      	{	this.receiver = localHTTPRequest.responseText;
        	if (this.idReceive) document.getElementById(this.idReceive).innerHTML = this.receiver;
          else
          	if (typeof(this.onSuccess) == 'function') this.onSuccess(this.receiver);
      	} else
        { this.receiver = 'ERROR: [' + this.status + '] ' + this.statustext;
          if (this.idReceive) document.getElementById(this.idReceive).innerHTML = this.receiver;
          else
        		if (typeof(this.onFailure) == 'function') this.onFailure(this.receiver);
        } // if
      } else
      	this.startTimer(); // Продолжаем обработку таймера
  	} catch(e) {}
  } // function

  o.Request = function() {
  	this.wait				= 0;
    this.readystate	= 0;
    this.status			= 0;
    this.statustext	= '';
    this.receiver 	= '';
		if (localHTTPRequest)
  	{	if (localHTTPRequest.readyState == 4 || localHTTPRequest.readyState == 0)
  		{ // Объект готов - выполняем запрос
        localHTTPRequest.open(this.getMethod(), this.Url(), true);
        // localHTTPRequest.onreadystatechange = eval(this.id+'.Timer()');
        if (this.method == 'POST')
        	localHTTPRequest.setRequestHeader('Content-Type', this.headers[0]); 
        localHTTPRequest.send( (this.method == 'POST' ? this.getParams() : null) );
        this.startTimer();
    	} // if
  	}	// if
	}	// function

  o.Init();
} // function