/* script myajax.js
   My_AJAX_ver_1.0
   Version 1.0
   Copyright (c) 2009 [Maslov Rafail]. 

   method createRequest - создает объект XMLHttpRequest (кроссбраузерность поддерживается)

   method setParam(method, url, sinch) - задает параметры: $method - метод передачи данных (GET|POST)
                                                           $url - адрес возвращаемой страницы на сервере
														   $sinch - (true|false) синхронность запроса)

   method setParam_of_Send - задает параметры соединения

   method CurrentAction - задает произвольный обработчик данных, возвращенных сервером

   method importHTMLto(element) - если серверный сценарий возвращает HTML вставляет его в узел element;
   
   method getVars_of_Form(form) - возвращает строку параметров сформированную на базе формы form;

*/

// ajax function

function myajax() {

  this.createRequest = createRequest;
  this.setParam = setParam;
  this.param_of_send = null;
  this.setParam_of_Send = setParam_of_Send;
  this.getVars_of_Form = getVars_of_Form;
  this.Send = Send;
  this.importHTMLto = importHTMLto;
  this.addImportHTMLto = addImportHTMLto;
  this.Action = Action;
}

function init() {
  createRequest();
}

function createRequest() {
  try {
    this.request = new XMLHttpRequest();
  }
  catch (trymicrosoft) {
    try	{
	  this.request = new ActiveXObject("Msxml2.XMLHTTP");
	}
	catch (othermicrosoft) {
	  try {
	    this.request = new ActiveXObject("Microsoft.XMLHTTP");
	  }
	  catch (failed)  {
	    this.request = false;
	  }
	}
  }
  if (this.request == null) {
    alert("Ошибка создания ajax-соединения!");
  }
}

function setParam(method, url, sinch){
  this.method = method;
  this.url = url;
  this.sinch = sinch;
}

function setParam_of_Send() {
  this.param_of_send = null;
  var param_string = "";
  if (arguments.length > 0) {
    param_string = arguments[0];
    for (var i = 1; i < arguments.length; i++) {
      param_string += "&" + arguments[i];
    }
    this.param_of_send = param_string;
  }
}

function getVars_of_Form(form) {
  this.param_of_send = null;
  var form = $(form);
  var inputs = form.getElementsByTagName('input');
  var param_string = '';
  var amp;
  for (var i=0; i<inputs.length; i++) {
    if (i == 0) {amp = ''} else {amp = '&'}
    input = inputs[i];
    if (input.type == 'text' || input.type =='password' || input.type == 'checkbox' || input.type == 'hidden') {
	  paramName = input.name;
	  paramValue = encodeURI(input.value);
	  param_string += amp + paramName + "=" + paramValue;
	}
	else if (input.type == 'radio') {
      if (input.checked == true) {
  	    paramName = input.name;
	    paramValue = encodeURI(input.value);
	    param_string += amp + paramName + "=" + paramValue;
      }
  	}
  }
  this.param_of_send = param_string;
}

function Send() {
  if (this.request) {
    var ready = this.request.readyState;
    if (ready == 0 || ready == 4) {
      try {
        if (this.method == "POST") { 
       	  this.request.open(this.method, this.url, this.sinch);
          this.Action(this);
          this.request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
          this.request.setRequestHeader("Content-length", this.param_of_send.length);
          this.request.setRequestHeader("Connection", "close");
          this.request.send(this.param_of_send);
	  	}
		else {
		  url = this.url + "?" + this.param_of_send;
          this.request.open(this.method, url, this.sinch);
          this.Action(this);
          this.request.send(null);
		}
	  }
	  catch (e) {
  	    alert ("Ошибка соединения с сервером. Попробуйте еще раз.");
  	  }
    }
  }
}

function importHTMLto(element) {
  this.CurrentAction = function() {
    var data = this.request.responseText;
    element.innerHTML=data;
  }
  this.Send();
}

function addImportHTMLto(element) {
  this.CurrentAction = function() {
    var data = this.request.responseText;
    newNode = document.createElement('div');
    newNode.innerHTML=data;
    $(element).appendChild(newNode);
  }
  this.Send();
}

function Action(obj) {
  obj.request.onreadystatechange = function () {
    if (obj.request.readyState==4) {
      if (obj.request.status==200) {
        var data = obj.request.responseText;
        obj.CurrentAction(obj);
      } else alert ("Ошибка соединения с сервером. Попробуйте еще раз.\n Код ошибки - " + obj.request.status);
    }
  }
}

window.onload = init;

// simply DOM function

function $(element) { 
  if (typeof(element) == "string")
    element = document.getElementById(element);
  return element;
}

function $hide(element) {
  if ($(element)) {
   $(element).style.display = 'none';
  }
}

function $show(element) {
  if ($(element)) {
  $(element).style.display = '';
  $(element).style.display = 'block';
  }
}

function $remove(element) {
  element = $(element);
  element.parentNode.removeChild(element);
}

function $setStyle(element) {
  var style=null;
  if (arguments.length > 1) {
    for (var i = 1; i < arguments.length; i++) {
      style=arguments[i].split(/: /);
      new_style="this.style." + escape(style[0]) + " = " + "'" + escape(style[1]) + "'";
      eval(new_style);
    }
  }
}

function $addScript(src) {
  var ap_url = '?d=' + new Date().getTime();
  var head = document.getElementsByTagName('head')[0];
  script = document.createElement('script');
  script.type = 'text/javascript';
  script.src = src + ap_url;
  head.appendChild(script);
}

function $addStylesheet(src) {
  var ap_url = '?d=' + new Date().getTime();
  var head = document.getElementsByTagName('head')[0];
  style = document.createElement('link');
  style.type = 'text/css';
  style.rel = 'stylesheet';
  style.href = src + ap_url;
  head.appendChild(style);
}

// others

function getAttributes(element) {
  attrList=element.attributes;
  var i = 0; var result="";
  while(i < attrList.length) {
  var attrObj = attrList.item(i);
    result+=attrObj.name + " = " + attrObj.value + "\n";
    i++
  }
  alert(result);
}




