
var showErrors = false;
var cache = new Array();

var xmlHttp = createXmlHttpRequestObject();

function createXmlHttpRequestObject() {

  var xmlHttp;
 
  try {
    xmlHttp = new XMLHttpRequest();
  }
  catch(e) {
    
    var XmlHttpVersions = new Array("MSXML2.XMLHTTP.6.0",
                                    "MSXML2.XMLHTTP.5.0",
                                    "MSXML2.XMLHTTP.4.0",
                                    "MSXML2.XMLHTTP.3.0",
                                    "MSXML2.XMLHTTP",
                                    "Microsoft.XMLHTTP");
   
    for (var i=0; i < XmlHttpVersions.length && !xmlHttp; i++) {
      try { 
        xmlHttp = new ActiveXObject(XmlHttpVersions[i]);
      } 
      catch (e) {} 
    }
  }
 
  if (!xmlHttp)
    displayError("Błąd podczas tworzenia obiektu XMLHttpRequest.");
  else 
    return xmlHttp;
}

function saveMail(tresc, telefon, mail) {
	
   if(xmlHttp) { 

   	if(tresc) {
      	tresc 	= encodeURIComponent(tresc);
		telefon	= encodeURIComponent(telefon);
		mail 	= encodeURIComponent(mail);
      		cache.push("tresc="+tresc+'&telefon='+telefon+'&mail='+mail);
    }
    try {
      if((xmlHttp.readyState == 4 || xmlHttp.readyState == 0) && cache.length > 0) {
      	
      	var cacheEntry = cache.shift();
        xmlHttp.open("POST", 'form.php', true);
        xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
        //xmlHttp.setRequestHeader("Content-Type", "text/html; charset=iso-8859-2");
        xmlHttp.onreadystatechange = saveMailHandleRequest;
        xmlHttp.send(cacheEntry);
      }
    }
    catch (e) {
      displayError(e.toString());
    }
  }
}

function saveMailHandleRequest() {

  if(xmlHttp.readyState == 4) {
    if(xmlHttp.status == 200) {
      try {
        saveMailReadResponse();
      }
      catch(e) {
        displayError(e.toString());
      }
    }
    else {
      displayError(xmlHttp.statusText);
    }
  }
}

function saveMailReadResponse() {

  var response = xmlHttp.responseText;

  if (response.indexOf("ERRNO") >= 0 || response.indexOf("error:") >= 0 || response.length == 0) {
  	throw(response.length == 0 ? "Server error." : response);
  }

  if(response==1){
	ending = true;
  }
}


function displayError($message) {
 
  if (showErrors) {
   
    showErrors = false;
    alert("Wystąpił błąd: \n" + $message);
  }
}

						
 