//fuggosegek: 
if (typeof BROWSERDETECT == "undefined") {
  alert("(XMLHTTP) BROWSERDETECT include missing");
}
//tobbszoros include:
if (typeof XMLHTTP != "undefined") {
  alert("XMLHTTP multiple insert!");
}
XMLHTTP=true;


/** Az XmlHttpRequest burkolo osztalya, a letrehozas sokfelesege es a timeout miatt
  */
function XmlHttp() {
}

/** A konstruktor teljes tartalma ebben a fuggvenyben van, ki kellett venni, hogy orokolt fuggvenyek tudjak hivni
  * @param cfg beallitasok objektuma
  */
XmlHttp.prototype.init = function (cfg) {
  this.status="inactive"; //inactive, active, aborted, completed

  this.setDefaults();
  this.readConfig(cfg);
  

  if (this.url == null) {
    this.onError(new Error("url undefined"),null);
    return null;
  }
  if (this.callback == null) {
    this.onError(new Error("callback undefined"),null);
    return null;
  }

  this.requestHeaders["User-Agent"]="iMind XmlHttpRequest javascript client v1.0  ("+navigator.userAgent+")";
  this.requestHeaders["Cache-Control"]="no-cache";
  
  
  try {
    if (window.XMLHttpRequest) {                                                  //mozilla
      this.req = new XMLHttpRequest();
      
      // some versions of Moz do not support the readyState property
      // and the onreadystate event so we patch it!
      if (this.req.readyState == null) {    //ez csak regebbi mozillanal kell, mostaninal eleg a readystate eventet figyelni
        this.req.readyState = 1;
        var req = this.req;
        this.req.addEventListener("load", function () {
            req.readyState = 4;
            if (typeof req.onreadystatechange == "function") {
              req.onreadystatechange();
            }
            }, false);
      }
    } else if (window.ActiveXObject) {                                            //IE
      this.req=new ActiveXObject(XmlHttp.getXmlHttpProgId());
    }

    if (this.req) {
      var xmlhttp=this;
      this.req.onreadystatechange=function () {
        xmlhttp.onReadyStateChange();
      };
    }    
  }
  catch (ex) {}
}

/** Ezt a fuggvenyt hivja XmlHttpRequest, amikor valtozik az allapota
  */
XmlHttp.prototype.onReadyStateChange = function () {
  var xmlhttp=this;
  if (xmlhttp.req.readyState == 4 && xmlhttp.status == 'active') {   //ha teljesen letoltodott, akkor callback fuggveny jon
    //opera meghivja szinkron eseten is, de kinyirja neha
    //mozilla nem hivja meg szinkron eseten
    //IE szinkron eseten is meghivja
    xmlhttp.status='completed';
    xmlhttp.cancelTimeout();
    if (this.req.status == "200" || this.req.status == "304") { //Opera 304-et ad, ha megvan a cache-ben
      if (typeof xmlhttp.callback == 'function') {
        //van callback
        xmlhttp.callback(xmlhttp.req); 
      }
    } else { 
      alert(this.req.status+" "+this.req.statusText);
      this.onError(new Error("HTTP error"),this);
      return null;
    }
  }
}


/** Alapertelmezett beallitasok beallitasa
  */
XmlHttp.prototype.setDefaults = function () {
  this.method="GET";
  this.url=null;
  this.asyncFlag=false;
  this.username=null;
  this.password=null;
  this.requestHeaders={};
  this.callback=null;
  this.onError=function (e,xmlhttp) {alert(e.message);};  //default-ban alert lesz
  this.timeoutLimit=0;
}

/** Az alapertelmezett beallitasok felulirasa ervenyes beallitasokkal
  * @param cfg a beallitasok objektuma
  */
XmlHttp.prototype.readConfig = function (cfg) {
  if (typeof cfg.method == 'string' && cfg.method != '') {
    this.method=cfg.method;
  }
  if (typeof cfg.url == 'string') {
    this.url=cfg.url;
  }
  if (typeof cfg.asyncFlag == 'boolean') {
    this.asyncFlag=cfg.asyncFlag;
  }

  if (typeof cfg.username == 'string') {
    this.username=cfg.username;
  }
  if (typeof cfg.password == 'string') {
    this.password=cfg.password;
  }
  if (typeof cfg.requestHeaders == 'object') {
    this.requestHeaders=copyObject(cfg.requestHeaders);
  }
  if (typeof cfg.callback == 'function') {
    this.callback=cfg.callback;
  }
  if (typeof cfg.onError == 'function') {
    this.onError=cfg.onError;
  }
  
  if (typeof cfg.timeoutLimit == 'number' && cfg.timeoutLimit > 0) {
    this.timeoutLimit=cfg.timeoutLimit;
  }
}

/** Visszaadja a peldanyositott XmlHttpRequest objektumot
  * @return XmlHttpRequest objektum, ha van
  */
XmlHttp.prototype.getXmlHttpRequest = function () {
  return this.req;
}

/** Osszeallitja a kerest es elkuldi, majd beallitja a timeoutot, ha aszinkron
  * @param data POST adatok, ha vannak
  */
XmlHttp.prototype.send = function (data) {
  if (this.status == 'inactive' && this.req) {
    try {
      this.status='active';
      this.req.open(this.method,this.url,this.asyncFlag,this.username,this.password);
      for (var i in this.requestHeaders) {
        if (typeof this.requestHeaders[i] != "function") { 
          //ez xml-rpc miatt van, object prototype toxmlrpc :(
          try {
            this.req.setRequestHeader(i,this.requestHeaders[i]);
          } catch (e) {
            //opera behal, ha user-agent-et allitok neki :(
          }
        }
      }
      var xmlhttp=this;
      if (this.timeoutLimit > 0 && this.asyncFlag == true) {
        //mozillanak koszonhetoen csak aszinkron keresekre lesz timeout
        this.timerId=setTimeout(function() {xmlhttp.transferTimeout();},this.timeoutLimit*1000);
      }
      if (this.asyncFlag == true) {
        //callback-et majd meghivja onreadystatechange
        return this.req.send(data);
      } else {
        this.req.send(data);
        //ennel aztan elszall mozilla
//        this.req.onreadystatechange();  //kesznek kell lennie, ha szinkron modban valamelyik nem hivta meg, hat most meg kell
        this.onReadyStateChange();
      }
    } catch (e) {
      this.onError(new Error(e),this);
      return null;
    }
  }
}

/** Timeout esemenykezeloje, leallitja a keres vegrehajtasat es meghivja a timout fuggvenyt, ha be lett allitva
  */
XmlHttp.prototype.transferTimeout = function () {
  if (this.req && this.status == 'active') {
    this.timerId=null;
    this.abort();
    this.onError(new Error("timeout"),this);
  }
}

/** Leallitja a kerest
  */
XmlHttp.prototype.abort = function () {
  this.status='aborted';
  this.req.abort();
  this.cancelTimeout();  
}

/** Leallitja a timeout idozitest
  */
XmlHttp.prototype.cancelTimeout = function () {
  if (this.timerId != null) {
    clearTimeout(this.timerId);
    this.timerId = null;
  }
}


/*
ezeket nem lehet meg megcsinalni operaval!!   
ha nem get-et szeretnenk, akkor lehet post, vagy head is, lehet szinkron is
--
XmlHttp.req.open("HEAD",url,false);  //szinkron
XmlHttp.req.send(null);
alert(XmlHttp.req.getAllResponseHeaders());   //headereket kirakja
--
XmlHttp.req.open("POST",url,false);  //szinkron
XmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=utf-8');
xmlHttp.send("param1=value1&param2=value2");
xmlHttp.responseText;

responseXml, responseText, status, getResponseHeader(), setRequestHeader()


*/

/** Visszaadja, hogy tamogatott-e a XmlHttpRequest objektum
  * @return true ha tamogatott, egyebkent false
  */
XmlHttp.isSupported = function () {
  if (window.XMLHttpRequest) {
    //mozilla es opera
    return true;
  } else if (XmlHttp.getXmlHttpPrefix()) {
    //IE
    return true;
  }
  return false;
}

/** IE miatt nem egyszeru a megfelelo ActiveX osztalyt peldanyositani, ez megkeresi, hogy melyiket kell
  * @return ActiveX osztaly nevet ad
  */
XmlHttp.getXmlHttpProgId = function() {   //statikus fuggveny
  if (XmlHttp.progId) {
    return XmlHttp.progId;
  }

  var progIds=['Msxml2.XMLHTTP.6.0','Msxml2.XMLHTTP.4.0','Msxml2.XMLHTTP.3.0','Msxml2.XMLHTTP','Microsoft.XMLHTTP','MSXML.XmlHttp','MSXML3.XmlHttp'];
  
  for (var i=0;i<progIds.length;++i) {
    try {      // try to create the objects
      new ActiveXObject(progIds[i]);
      XmlHttp.progId=progIds[i];
      return progIds[i];
    } catch (ex) {}
  }
  return "";
//  alert("no MSXML prefix found");
  /*
     var types = [
     'Microsoft.XMLHTTP',
     'MSXML2.XMLHTTP.5.0',
     'MSXML2.XMLHTTP.4.0',
     'MSXML2.XMLHTTP.3.0',
     'MSXML2.XMLHTTP'
     ];
     
     */
}

