// stores the reference to the XMLHttpRequest object
var xmlHttp = createXmlHttpRequestObject(); 

// retrieves the XMLHttpRequest object
function createXmlHttpRequestObject() 
{	
  // will store the reference to the XMLHttpRequest object
  var xmlHttp;
  // if running Internet Explorer
  if(window.ActiveXObject)
  {
    try
    {
      xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    catch (e) 
    {
      xmlHttp = false;
    }
  }
  // if running Mozilla or other browsers
  else
  {
    try 
    {
      xmlHttp = new XMLHttpRequest();
    }
    catch (e) 
    {
      xmlHttp = false;
    }
  }
  // return the created object or display an error message
  if (!xmlHttp)
 
    alert("Error creating the XMLHttpRequest object.");
  else 
    return xmlHttp;
}
function str_replace(search, replace, subject) {

    var s = subject;
    var ra = r instanceof Array, sa = s instanceof Array;
    var f = [].concat(search);
    var r = [].concat(replace);
    var i = (s = [].concat(s)).length;
    var j = 0;
    
    while (j = 0, i--) {
        if (s[i]) {
            while (s[i] = (s[i]+'').split(f[j]).join(ra ? r[j] || "" : r[0]), ++j in f){};
        }
    }
 
    return sa ? s : s[0];
}

function changeChars(str){
	return str_replace(['*'], ['&'], str);
}
// make asynchronous HTTP request using the XMLHttpRequest object 
function get_companis(leter, type)
{
  // proceed only if the xmlHttp object isn't busy
  if (xmlHttp.readyState == 4 || xmlHttp.readyState == 0)
  {
    // retrieve the name typed by the user on the form
    
    // execute the quickstart.php page from the server
    if(type == 1)
    	{
    		
    		if(document.getElementById('_sity').value == 0)
    		{
    			alert("Пожалуйста, заполните поле 'Город, нас. пункт'");
   			    document.addForm._sity.focus();
   			    return;

    		}
    		
			url = "index.php?mod=contacts&cmd=get_companis&type=1&letter="+leter+"&city_id="+document.getElementById('_sity').value;
		}
    	
    if(type == 2)
    	url = "index.php?mod=contacts&cmd=get_companis&type=1&city="+document.getElementById('_sity').value;
    //alert(url);
    xmlHttp.open("GET", url, true);  
    // define the method to handle server responses
    xmlHttp.onreadystatechange = handleServerResponse;
    // make the server request
    xmlHttp.send(null);
  }
  else
    // if the connection is busy, try again after one second  
    setTimeout('process()', 1000);
}
function company_info()
{
	if(document.getElementById('_sity').value == 0)
	{
		alert("Пожалуйста, заполните поле 'Город, нас. пункт'");
	    document.addForm._sity.focus();
	    return;

	}
  if(document.getElementById('_company').value>0){
  // proceed only if the xmlHttp object isn't busy
  if (xmlHttp.readyState == 4 || xmlHttp.readyState == 0)
  {
    // retrieve the name typed by the user on the form
    
    // execute the quickstart.php page from the server
    url = "index.php?mod=contacts&cmd=get_companis&type=2&company="+document.getElementById('_company').value;
    //alert(url);
    xmlHttp.open("GET", url, true);  
    // define the method to handle server responses
    xmlHttp.onreadystatechange = handleServerRespInfo;
    // make the server request
    xmlHttp.send(null);
  }
  else
    // if the connection is busy, try again after one second  
    setTimeout('process()', 1000);
  }
}

function getcitys()
{
  if(document.getElementById('_region').value>0){
  // proceed only if the xmlHttp object isn't busy
  if (xmlHttp.readyState == 4 || xmlHttp.readyState == 0)
  {
    // retrieve the name typed by the user on the form
    
    // execute the quickstart.php page from the server
    url = "index.php?mod=contacts&cmd=get_companis&type=3&region="+document.getElementById('_region').value;
    //alert(url);
    xmlHttp.open("GET", url, true);  
    // define the method to handle server responses
    xmlHttp.onreadystatechange = handleServerRespRegion;
    // make the server request
    xmlHttp.send(null);
  }
  else
    // if the connection is busy, try again after one second  
    setTimeout('process()', 1000);
  }
}

// executed automatically when a message is received from the server
function handleServerResponse() 
{

  // move forward only if the transaction has completed
  if (xmlHttp.readyState == 4) 
  {
    // status of 200 indicates the transaction completed successfully
    if (xmlHttp.status == 200) 
    {
      // extract the XML retrieved from the server
      xmlResponse = xmlHttp.responseXML;
      // obtain the document element (the root element) of the XML structure
      xmlDocumentElement = xmlResponse.documentElement;
      // get the text message, which is in the first child of
      // the the document element
      helloMessage = xmlDocumentElement.firstChild.data;
      // update the client display using the data received from the server
 	
	  document.getElementById('_company').options.length = 0;
	  document.getElementById('_company').options[0] = new Option("Выберите, пожалуйста", 0);
	  document.getElementById('_company').options[1] = new Option("Создать новую компанию", -1);
	  if(helloMessage != 'ND'){
		  var arrResponce = helloMessage.split("|||");
		  for(i=0; i<arrResponce.length-1; i++ )
		  {
		  	var arrOpt = arrResponce[i].split("|-|");
			document.getElementById('_company').options[i+2] = new Option(changeChars(arrOpt[1]), changeChars(arrOpt[0]));
		  }
	  }
	  


	  
      // restart sequence
    } 
    // a HTTP status different than 200 signals an error
    else 
    {
      alert("There was a problem accessing the server: " + xmlHttp.statusText);
    }
  }
}

function handleServerRespRegion() 
{
  // move forward only if the transaction has completed
  if (xmlHttp.readyState == 4) 
  {
    // status of 200 indicates the transaction completed successfully
    if (xmlHttp.status == 200) 
    {
      // extract the XML retrieved from the server
      xmlResponse = xmlHttp.responseXML;
      // obtain the document element (the root element) of the XML structure
      xmlDocumentElement = xmlResponse.documentElement;
      // get the text message, which is in the first child of
      // the the document element
      helloMessage = xmlDocumentElement.firstChild.data;
      // update the client display using the data received from the server
	  
	  document.getElementById('_sity').options.length = 0;
	 
	  var arrResponce = helloMessage.split(";");
	  document.getElementById('_sity').options[0] = new Option("Выберите, пожалуйста", 0);
	  for(i=0; i<arrResponce.length-1; i++ )
	  {
	  	var arrOpt = arrResponce[i].split("|");
		document.getElementById('_sity').options[i+1] = new Option(arrOpt[1], arrOpt[0]);
	  }
	  
	  disableFields(); 

	  
      // restart sequence
    } 
    // a HTTP status different than 200 signals an error
    else 
    {
      alert("There was a problem accessing the server: " + xmlHttp.statusText);
    }
  }
}

function handleServerRespInfo() 
{
  // move forward only if the transaction has completed
  if (xmlHttp.readyState == 4) 
  {
    // status of 200 indicates the transaction completed successfully
    if (xmlHttp.status == 200) 
    {
      // extract the XML retrieved from the server
      xmlResponse = xmlHttp.responseXML;
      // obtain the document element (the root element) of the XML structure
      xmlDocumentElement = xmlResponse.documentElement;
      // get the text message, which is in the first child of
      // the the document element
      helloMessage = xmlDocumentElement.firstChild.data;
      // update the client display using the data received from the server
	  
	  var arrResponce = helloMessage.split("|");
	  var branch = document.getElementById('_branch');
	  for (var i=0; i < branch.options.length; i++)
      {
        if (branch.options[i].value == arrResponce[0]) 
			branch.options[i].selected = true;
      }
	  var cemployers = document.getElementById('_cemployers');
	  for (var i=0; i < cemployers.options.length; i++)
      {
        if (cemployers.options[i].value == arrResponce[1]) 
			cemployers.options[i].selected = true;
      }
	  var full_address = document.getElementById('_full_address');
	  full_address.value = arrResponce[2];
	  
	  var company_phone = document.getElementById('_company_phone');
	  company_phone.value = arrResponce[3];
	  
	  var company_www = document.getElementById('_company_www');
	  company_www.value = arrResponce[4];
	  
	  var descr = document.getElementById('_company_description');
	  descr.value = arrResponce[5];
	  
      // restart sequence
    } 
    // a HTTP status different than 200 signals an error
    else 
    {
      alert("There was a problem accessing the server: " + xmlHttp.statusText);
    }
  }
}