// (C) 2009 WhiteNoize CS

function createRequestObject()
{
 if (window.XMLHttpRequest) return new XMLHttpRequest();
 try
 {
  return new ActiveXObject('Msxml2.XMLHTTP');
 }
 catch(e)
 {
  return new ActiveXObject('Microsoft.XMLHTTP');
 }
}

function sendRequest(url, sendResponse, method, data)
{
 if (typeof(method) == 'undefined') var method = 'GET';
 var Req = createRequestObject();

 Req.onreadystatechange = function()
 {
  if (Req.readyState == 4 && Req.status == 200) sendResponse(Req.responseText);
 }

 Req.open(method, url, true);

 if (method == 'GET')
 {
  Req.send('');
 }

 if (method == 'POST')
 {
  Req.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
  Req.send(data);
 }
}

function getInputValue(inp)
{
 if (typeof(inp.nodeName) == 'undefined')
 {
  for (var i=0; i<inp.length; i++)
  if (inp[i].checked) return (inp[i].name ? (encodeURIComponent(inp[i]).name + '=') : '') + encodeURIComponent(inp[i].value);
  return '';
 }

 if (inp.type == 'select-multiple')
 {
  var ret = [];
  for (var i=0; i<inp.options.length; i++) if (inp.options[i].selected) ret[ret.length] = (inp.options[i].name ? (encodeURIComponent(inp.options[i].name) + '[]') : inp.name) + '=' + encodeURIComponent(inp.options[i].value);
  return ret.join('&');
 }
 else if (inp.type == 'select-one')
 {
  var value = inp.options[inp.selectedIndex].value;
  if (value == '') value = inp.options[inp.selectedIndex].text;
  return (inp.selectedIndex >= 0) ? ((inp.name ? (encodeURIComponent(inp.name) + '=') : '') + encodeURIComponent(value)) : '';
 }

 if (inp.type == 'image') return (inp.name ? (encodeURIComponent(inp.name) + '=') : '') + encodeURIComponent(inp.src);
 else return (inp.name ? (encodeURIComponent(inp.name) + '=') : '') + encodeURIComponent(inp.value);
}

function encodeForm(target)
{
 form = document.getElementById(target);

 if (!form || !form.elements) throw 'encodeForm: error, argument is not a FORM';
 var ret = [], el;
 for (var i=0; i<form.elements.length; i++)
 {
  el = form.elements[i];
  if ("checkboxradio".indexOf(el.type) >= 0)
  {
   if (el.checked) ret[ret.length] = getInputValue(el);
  }
  else if (el.type != 'button' && el.type != 'submit') ret[ret.length] = getInputValue(el);
 }
 return ret.join('&');
}
