var req, response;

function loadXMLDoc(url) {
  // branch for native XMLHttpRequest object
  if (window.XMLHttpRequest) {
    req = new XMLHttpRequest();
    req.onreadystatechange = processReqChange;
    req.open("GET", url, true);
    req.send(null);
  // branch for IE/Windows ActiveX version
  }
  else if (window.ActiveXObject) {
    req = new ActiveXObject("Microsoft.XMLHTTP");
    if (req) {
      req.onreadystatechange = processReqChange;
      req.open("GET", url, true);
      req.send();
    }
  }
}

function processReqChange() 
{
  // only if req shows "complete"
  if (req.readyState == 4) {
    // only if "OK"
    if (req.status == 200) {
      // ...processing statements go here...
      showInfo('ipinfo', req.responseText);
      progress('hidden');
    }
    else {
      alert("There was a problem retrieving the XML data:\n" + req.statusText);
    }
  }
}

function getInfo (value) {
  if (value) {
    url  = 'http://geotargeting.com.ua/cgi-bin/wherefrom.cgi?ip='+value;
    progress('');
    loadXMLDoc(url);
  }
  else {
    showInfo('ipinfo', '');
  }
}

function showInfo(obj, data) {
  var div = document.getElementById(obj);
  if (div) div.innerHTML = data;
}

function progress(visibility) {
  var img = document.getElementById('progress');
  if (img) img.style.visibility = visibility;
}

function checkIP(ip) {
  ip = trim(ip);
  if (ip.match(/^((([01]?[0-9]{1,2})|(2([0-4][0-9]|5[0-5])))\.){3}(([01]?[0-9]{1,2})|(2([0-4][0-9]|5[0-5])))$/)) return true;
  alert("Проверте корректность ввода IP адреса");
  return false;
}

function trim(string) {
  return (string.replace(/^\s+/, "")).replace(/\s+$/, "");
}

function chIP(ip) {
  if (checkIP(ip)) {
    getInfo(ip);
  }
  else {
    showInfo('ipinfo', '');
  }
}
