﻿
//    Array.prototype.toString = 
//    Object.prototype.toString = function() {
//        var cont = [];
//        var addslashes = function(s) {
//            // Использовать replace НЕЛЬЗЯ - в Опере
//            // происходит зацикливание, т.к. из replace
//            // зачем-то вызывается Object.toString().
//            return s.split('\\').join('\\\\').split('"').join('\\"');
//        }
//    
//        for (var k in this) {
//            if (cont.length) cont[cont.length-1] += ",";
//            var v = this[k];
//            var vs = '';
//            if (v.constructor == String) 
//                vs = '"' + addslashes(v) + '"';
//            else 
//                vs = v.toString();
//            if (this.constructor == Array)
//                cont[cont.length]
//            else 
//                cont[cont.length] = k + ": " + vs;
//        }
//      // Здесь тоже нельзя делать replace()! 
//      cont = "  " + cont.join("\n").split("\n").join("\n  ");
//      var s = cont;
//      if (this.constructor == Object) {
//        s = "{\n"+cont+"\n}";
//      } else if (this.constructor == Array) {
//        s = "[\n"+cont+"\n]";
//      }
//      return s;
//}

function urlEncodeData(data) {
    var query = [];
    if (data instanceof Object) {
        for (var k in data) {
            query.push(encodeURIComponent(k) + "=" + encodeURIComponent(data[k]));
        }
        return query.join('&');
    } else {
        return encodeURIComponent(data);
    }
}



// Параметры функции будут доступны для внутренней анонимной функции
function registreCallbackFunction(xmlHttpRequest,callback,onerror,callbackArgsArray){
// Функция-"обвертка" возвращает ссылку на анонимную функцию
    return function(){
// Если состояние запроса COMPLETE (то есть 4)
        if(xmlHttpRequest.readyState == 4){
// Если запрос успешный
            if(! xmlHttpRequest.status || xmlHttpRequest.status >= 200 && xmlHttpRequest.status < 300 
                                                || xmlHttpRequest.status == 304)
// callback-функция вызывается в контексте объекта-запроса с массивом аргументов
               callback(xmlHttpRequest,callbackArgsArray);
// Если запрос прошел с ошибкой
            else
// Если назначена функция-обработчик ошибки - вызываем ее
                if (typeof onerror == "function")
                    onerror(xmlHttpRequest,callbackArgsArray);
                else
                    throw new Error("Ошибка запроса XMLHttpRequest")
        }            
    };
}

function getXmlHttp(){
  var xmlhttp;
  try {
    xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
  } catch (e) {
    try {
      xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    } catch (E) {
      xmlhttp = false;
    }
  }
  if (!xmlhttp && typeof XMLHttpRequest!='undefined') {
    xmlhttp = new XMLHttpRequest();
  }
  return xmlhttp;
}

function sendRequest(httpMethod,url,httpParams,async,callback,onerror,callbackArgsArray){
var xmlHttpRequest=getXmlHttp();
if (! xmlHttpRequest)
    throw new Error("Ошибка создания объекта XMLHttpRequest")
if (async)
    xmlHttpRequest.onreadystatechange=
            registreCallbackFunction(xmlHttpRequest,callback,onerror,callbackArgsArray)
try{
    if (httpMethod=="get"){
        xmlHttpRequest.open("get",encodeURI(url+"?"+httpParams),async);
        xmlHttpRequest.send(null);
    }
    else{
        xmlHttpRequest.open("post",encodeURI(url+""),async);
        xmlHttpRequest.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
        xmlHttpRequest.send(urlEncodeData(httpParams));
    }
}catch(e){
    xmlHttpRequest.onreadystatechange=null;
    if (typeof onerror=="function")
        onerror(xmlHttpRequest,callbackArgsArray);
    else
        throw new Error("Ошибка запроса XMLHttpRequest")
}
}


