
    window.AjaxSimpleGL_TimeMark = null;

    // обработчик событий отправки объекта AjaxSimpleGL
	/*
    	in_OBJ - (obj) объект AjaxSimpleGL
	*/
	function AjaxSimpleGL_HandlerFunc(in_OBJ)
    {
        	//if (in_OBJ._debug == true) in_OBJ.ShowAlert("in_OBJ.HendlerFunc is active ");


        	try
        	{
        		if (in_OBJ)
        		{
		        	if (in_OBJ.XMLHttp)
					{
		            	//if (in_OBJ._debug == true) in_OBJ.ShowAlert("in_OBJ.XMLHttp.readyState = " + in_OBJ.XMLHttp.readyState);
                        //alert("in_OBJ.XMLHttp.readyState = " + in_OBJ.XMLHttp.readyState);

		            	switch (in_OBJ.XMLHttp.readyState)
		            	{
						   // не инициализировано
						   case 0:

	                            in_OBJ.dataResponce = null;
	                            in_OBJ.dataReceived_completed = false;

	                      		if (in_OBJ._debug == false && in_OBJ._show_error_user == true) in_OBJ.ShowAlert("js error, execute request in current moment not possible, please request later");
	            				else in_OBJ.ShowAlert("XMLHTTP not init");

						   break;

						   // загрузка
						   case 1:

	                            in_OBJ.dataResponce = null;
	                            in_OBJ.dataReceived_completed = false;
						   		if (in_OBJ.function_loading != null) eval(in_OBJ.function_loading);

						   break;

						   // загружено
						   case 2:

						   		in_OBJ.dataResponce = null;
						   		in_OBJ.dataReceived_completed = false;
						   		if (in_OBJ.function_loaded != null) eval(in_OBJ.function_loaded);

						   break;

						   // ожидание
						   case 3:

						   		in_OBJ.dataResponce = null;
						   		in_OBJ.dataReceived_completed = false;
						   		if (in_OBJ.function_wait != null) eval(in_OBJ.function_wait);

						   break;

						   // завершено
						   case 4:

	                            if (in_OBJ.XMLHttp.status == 200)
	                            {
	                            	// обрабатываем данные
	                            	in_OBJ.dataResponce = in_OBJ.XMLHttp.responseText; // записываем пришедшие данные

	                            	if (in_OBJ._debug == true) in_OBJ.ShowAlert("in_OBJ.GetDataResponce() = " + in_OBJ.GetDataResponce());
	                            	if (in_OBJ._debug == true) in_OBJ.ShowAlert("in_OBJ.function_completed = " + in_OBJ.function_completed);

	                            	if (in_OBJ.function_completed != null) eval(in_OBJ.function_completed);
	                            	if (in_OBJ.dataResponce.length > 0) in_OBJ.dataReceived_completed = true;  // флаг, что данные получены
	                            }
	                            else
	                            {
	                            	in_OBJ.ShowAlert("There was a problem with the request\n" + in_OBJ.XMLHttp.statusText);
	                            	in_OBJ.dataReceived_completed = false;  // флаг, что данные не получены
	                            	if (in_OBJ.function_not_completed != null) eval(in_OBJ.function_not_completed); // не удачное завершение
	                            }


                                in_OBJ.SendRepeatReq(in_OBJ); // повторная отправка запроса

						   break;
						}
					}
				}
			}
			catch(e)
			{
            	if (in_OBJ._debug == false && in_OBJ._show_error_user == true) in_OBJ.ShowAlert("js error, execute request in current moment not possible, please request later");
            	else if(in_OBJ._debug == true) in_OBJ.ShowAlert(" :: HandlerFunc :: " + e.message);
			}
	}


    // стетчик времени выполнения запроса, объект AjaxSimpleGL
    /*
    	in_OBJ - (obj) объект AjaxSimpleGL
	*/
	function AjaxSimpleGL_TimeOut(in_OBJ)
	{
        	try
        	{
	        	if (in_OBJ)
	        	{
		        	if (in_OBJ.XMLHttp)
					{
	                	if (in_OBJ.XMLHttp.readyState != 4 && in_OBJ.XMLHttp.readyState != 0)
	                	{
	                		in_OBJ.XMLHttp.onreadystatechange = function () { };
	                		in_OBJ.XMLHttp.abort(); // перываем запрос
	                		if (in_OBJ.function_not_completed != null) eval(in_OBJ.function_not_completed); // не удачное завершение
	                		in_OBJ.SendRepeatReq(in_OBJ); // повторная отправка запроса
	                		if (in_OBJ._show_error_user == true) in_OBJ.ShowAlert("server temporarily is not available, please request later");
	                	}
					}
				}
			}
			catch(e)
			{
            	if (in_OBJ._debug == false && in_OBJ._show_error_user == true) in_OBJ.ShowAlert("js error, execute request in current moment not possible, please request later");
            	else if (in_OBJ._debug == true) in_OBJ.ShowAlert(" :: AjaxSimpleGL_TimeOut :: " + e.message);
			}
	}



	// объект AjaxSimpleGL
	function AjaxSimpleGL()
	{
	    //Переменные  -------------------------------------------------------------------------------
	    this.XMLHttp = null;  // объект XMLHttp

	    this.dataResponce = null;  // контейнер с пришедшими данными
	    this.synchronous_request_off = true;  // включение синхронного режима передачи, при false синхронный режим включается
	    this.dataReceived_completed = false;  // флаг окончания работы запроса и получения данных

	    this.url = "";  // URL c параметрами для отправки на сервер
	    this.typeSend = ""; // тип запроса
	    this.valuesList = ""; // входные данные
	    this.thisOBJ = null; // ссылка на копию внешнего объекта

	    this.function_loading = null; // функция загрузка
	    this.function_loaded = null; // функция загружено
	    this.function_wait = null; // функция ожидания получения данных
	    this.function_completed = null; // функция для которая будет выполнена после завершения получения данных
	    this.function_not_completed = null; // функция для которая будет выполнена после не удачного завершения получения данных,



	    //Значение по умолчанию  --------------------------------------------------------------------
        this._obj_version = "1.0"; // версия скрипта
        this._charset = "windows-1251"; // кодировка по умолчанию
        this._timeMs = 25000; // время в милисекундах ожидания получения данных от сервера (20000)
        this._debug = false; // вкл./откл. режима отладки для разработчика
        this._show_error_user = false; // вкл./откл. режима показа сообщений для пользователя

        this._hash_last_request = ""; // хеш последнего запроса
        this._current_count_Sended = 0; // текущее количетсво отправок одного и тогоже запроса
        this._max_count_Sended = 3; // максимальное количетсво отправок одного и тогоже запроса


		//Функции  ----------------------------------------------------------------------------------


        // вывод ошибок
	    this.ShowAlert = function(s)
	    {
	    	alert("AjaxSimpleGL error: " + s);
	    }


        // показать объект
        /*
			In_id - (string) ID объекта
		*/
        this.ShowAjaxSpLoading = function (In_id)
		{
			try
			{
		  		if (typeof(In_id) == "string")
		  		{
		  			if (In_id.length > 0)
		  			{
		  				var oOBJ = this.byId(In_id);

		                if (typeof(oOBJ) == "object")
		                {
		                	oOBJ.style.display = 'inline';
		                }
		  			}
		  		}
			}
			catch(e)
			{
		     	if (this._debug == false && this._show_error_user == true) this.ShowAlert("js error, execute request in current moment not possible, please request later");
	            else if (this._debug == true) this.ShowAlert(" :: ShowAjaxSpLoading :: " + e.message);
			}
		}



		// спрятать объект
		/*
			In_id - (string) ID объекта
		*/
		this.HideAjaxSpLoading = function (In_id)
		{
			try
			{
		  		if (typeof(In_id) == "string")
		  		{
		  			if (In_id.length > 0)
		  			{
		  				var oOBJ = this.byId(In_id);

		                if (typeof(oOBJ) == "object")
		                {
		                	oOBJ.style.display = 'none';
		                }
		  			}
		  		}
			}
			catch(e)
			{
		    	if (this._debug == false && this._show_error_user == true) this.ShowAlert("js error, execute request in current moment not possible, please request later");
	            else if (this._debug == true) this.ShowAlert(" :: HideAjaxSpLoading :: " + e.message);
			}
		}



	    // попытка отправить еще один запрос в случае не удачи
	    /*
    		in_OBJ - (obj) объект AjaxSimpleGL
		*/
	    this.SendRepeatReq = function(in_OBJ)
	    {
	    	try
        	{
	    		if (in_OBJ)
	    		{
	    					if (in_OBJ.dataReceived_completed == false)
	                        {
                                	// если данные не получены, повторная отправка не удочного запроса
                                	var hash_current = in_OBJ.url + in_OBJ.typeSend + in_OBJ.PrepareDataToURL(in_OBJ.valuesList);

	                            	if (in_OBJ._hash_last_request == hash_current && in_OBJ._current_count_Sended < in_OBJ._max_count_Sended)
	                            	{
	                            		in_OBJ.SendRequest (in_OBJ.url, in_OBJ.typeSend, in_OBJ.valuesList, in_OBJ.thisOBJ);
	                           		}
	                        }
	       		}
	        }
	    	catch(e)
			{
	            	if (this._debug == false && this._show_error_user == true) this.ShowAlert("js error, execute request in current moment not possible, please request later");
	            	else if (this._debug == true) this.ShowAlert(" :: GetDataIntoContainer :: " + e.message);
			}

	    }



	    // вывод данных в контейнер
	    /*
	      	in_obj_IDstr - (string) - ID контейнера
	    */
	    this.GetDataIntoContainer = function(in_obj_IDstr)
	    {
	    	//alert("this.GetDataResponce() = "+  this.GetDataResponce());

	    	try
        	{
	    			if (typeof(in_obj_IDstr) != 'undefined')
	    			{
		    			var targetOBJ = this.byId(in_obj_IDstr);

		    			if (targetOBJ)
		    			{
		    				//alert("this.GetDataResponce() = " + this.GetDataResponce());
		    				//alert("targetOBJ.id" + targetOBJ.id);
		    				//alert("typeof(targetOBJ.innerHTML) = " + typeof(targetOBJ.innerHTML));
		    				//alert("targetOBJ.innerHTML = " + targetOBJ.innerHTML);

		    				if (typeof(targetOBJ.innerHTML) != "undefined")
		    				{
		    					targetOBJ.innerHTML = this.GetDataResponce();  // поместить в специальный контейнер что-либо
		   					}
		   					else if (typeof(targetOBJ.value) != "undefined")
		   					{
                                targetOBJ.value = this.GetDataResponce();  // поместить в специальный контейнер что-либо
		   					}
		    			}
	    			}
	    			else
	    			{
	    				eval(this.GetDataResponce()); // выполнить JS
	    			}
	    	}
	    	catch(e)
			{
	            	if (this._debug == false && this._show_error_user == true) this.ShowAlert("js error, execute request in current moment not possible, please request later");
	            	else if (this._debug == true) this.ShowAlert(" :: GetDataIntoContainer :: " + e.message);
			}

	    }


		// инциализация объекта XMLHTTP
		// return (object)
		this.Init = function()
	    {
        	try
        	{
        		this.XMLHttp = new XMLHttpRequest();
        	}
			catch(e)
			{
				this.XMLHttp = null;
			}

			try
			{
				if(!this.XMLHttp) this.XMLHttp = new ActiveXObject("Msxml2.XMLHTTP");
			}
			catch(e)
			{
				this.XMLHttp = null;
			}

			try
			{
				if(!this.XMLHttp) this.XMLHttp = new ActiveXObject("Microsoft.XMLHTTP");
			}
			catch(e)
			{
				this.XMLHttp = null;
			}

			if (!this.XMLHttp)
			{
				if (this._debug == false && this._show_error_user == true) this.ShowAlert("error, execute XMLHttpRequest request in current moment not possible, AJAX not support on this browser");
            	else if (this._debug == true) this.ShowAlert(" :: Init :: " + "XMLHTTP not support on you browser");
			}

			return this.XMLHttp;
	    }


	    //получение объекта по ID
	    /*
	    	s - (String|Node)
	    */
	    this.byId = function(s)
	    {
        	return !s ? s : s.nodeType ? s : document.getElementById(s);
	    }



        /*
        Возвращает полный список HTTP-заголовков в виде строки. Заголовки разделяются знаками переноса (CR+LF).
			Если флаг ошибки равен true, возвращает пустую строку.
			Если статус 0 или 1, вызывает ошибку INVALID_STATE_ERR.
        */
	    this.getAllResponseHeaders = function()
	    {
        	try
        	{
	        	if (this.XMLHttp)
				{
                	return this.XMLHttp.getAllResponseHeaders();
				}
			}
			catch(e)
			{
            	if (this._debug == false && this._show_error_user == true) this.ShowAlert("js error, execute request in current moment not possible, please request later");
            	else if (this._debug == true) this.ShowAlert(" :: getAllResponseHeaders :: " + e.message);
			}

			return "";
	    }






	    /*
        Возвращает значение указанного заголовка.
			Если флаг ошибки равен true, возвращает null.
			Если заголовок не найден, возвращает null.
			Если статус 0 или 1, вызывает ошибку INVALID_STATE_ERR.
        */
	    this.getResponseHeader = function(headerName)
	    {
        	try
        	{
	        	if (this.XMLHttp && typeof(headerName) != 'undefined')
				{
                	if (headerName.length > 0) return this.XMLHttp.getResponseHeader(headerName);
				}
			}
			catch(e)
			{
            	if (this._debug == false && this._show_error_user == true) this.ShowAlert("js error, execute request in current moment not possible, please request later");
            	else if (this._debug == true) this.ShowAlert(" :: getAllResponseHeaders :: " + e.message);
			}

			return "";
	    }



	    // получить dataResponce
	    this.GetDataResponce = function()
	    {
        	try
        	{
	        	if (this.XMLHttp)
				{
                	if (this.dataResponce != null) return this.dataResponce;
				}
			}
			catch(e)
			{
            	if (this._debug == false && this._show_error_user == true) this.ShowAlert("js error, execute request in current moment not possible, please request later");
            	else if (this._debug == true) this.ShowAlert(" :: GetDataResponce :: " + e.message);
			}

			return "";
	    }









	    // подготовим данный для отправки
	    /*
	    	data - (object) входные данные    (var rSendArr = new Object(); rSendArr['id_country'] = this.value;)
	    */
	    this.PrepareDataToURL = function(in_dataArr)
	    {
			if (this._debug == true) this.ShowAlert("typeof(in_dataArr) = " + typeof(in_dataArr));

			try
			{
		    	//convert hash object to URL string
		        if(typeof(in_dataArr) == "object")
		        {
		            var sArr = new Array("");  // array
		            var t = 0;

		            for(var i in in_dataArr)
		            {
		            	if (typeof(in_dataArr[i]) != "function")
		            	{
		            		sArr[t] = escape(i) + "=" +  escape(in_dataArr[i]);
		            		t++;
		        		}
		            }

		            var s = sArr.join("&");
		        }

		        //if (this._debug == true) this.ShowAlert("s = " + s);
		        //alert("s = " + s);
		        return s;
	        }
	        catch(e)
	        {
	        	if (this._debug == false && this._show_error_user == true) this.ShowAlert("js error, execute request in current moment not possible, please request later");
            	else if (this._debug == true) this.ShowAlert(" :: PrepareDataToURL :: " + e.message);

            	return "";
	        }
	    }



        // отправляем запрос
        /*
        	in_url - (string) путь до серверного скрипта
        	in_typeSend - (string) тип отправки GET or POST
        	in_valuesList - (array) параметры в виде массива
        	in_thisOBJ - (obj) ссылка на сам объект извне
        */
	    this.SendRequest = function(in_url, in_typeSend, in_valuesList, in_thisOBJ)
	    {
			try
        	{
				//if (this._debug == true) this.ShowAlert("this.SendRequest is active");

				if (typeof(in_typeSend) == "undefined" || !in_typeSend)
				{
					in_typeSend = "POST";
				}

				in_typeSend = in_typeSend.toUpperCase();

				if(typeof(in_url) != "undefined" && typeof(in_typeSend) != "undefined" && typeof(in_valuesList) != "undefined" && in_thisOBJ)
				{
					if (in_url.length > 0 && in_typeSend.length > 0)
					{
						if (this.XMLHttp)
						{
							// кешируем вход. параметры
							this.url = in_url = in_url.replace(/\?/i, "");
						    this.typeSend = in_typeSend;
						    this.valuesList = in_valuesList;
						    this.thisOBJ = in_thisOBJ;

						    var hash_current = this.url + this.typeSend + this.PrepareDataToURL(this.valuesList);

						    //alert("hash_current = "+  hash_current);

	                        if (this._hash_last_request == hash_current)
	                        {
                            	this._current_count_Sended++;
	                        }
	                        else
	                        {
                            	// если запрос новый
                            	this._current_count_Sended = 0;
	                        }

						    this._hash_last_request = hash_current; // хеш последнего запроса

							if (this._debug == true) this.ShowAlert("in_typeSend = " + in_typeSend + " :: in_url = "+ in_url);

                            window.setTimeout( function() { AjaxSimpleGL_TimeOut(in_thisOBJ); }, this._timeMs); // ограничение времени выолнения запроса методом стетчика

							// если синхронный режим передачи
							if (this.synchronous_request_off == false)
							{
								this.dataResponce = null;
	                            this.dataReceived_completed = false;

						   		if (this.function_loading != null) eval(this.function_loading);
						   		if (this.function_loaded != null) eval(this.function_loaded);
						   		if (this.function_wait != null) eval(this.function_wait);
							}

							if (in_typeSend == "POST")
							{
								this.XMLHttp.open("POST", in_url, this.synchronous_request_off);

								// обработчик событий
								if (this.synchronous_request_off == true)
								{
									// если асинхронный режим
									this.XMLHttp.onreadystatechange = function() { AjaxSimpleGL_HandlerFunc(in_thisOBJ) };
								}

								this.XMLHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=" + this._charset);
								this.XMLHttp.setRequestHeader("X-Requested-With", "XMLHttpRequest"); // запрашивает ли клиент скрипт через аякс
								this.XMLHttp.send( this.PrepareDataToURL(in_valuesList) +"&uniq=" + Math.random());
							}
							else if (in_typeSend == "GET")
							{
								this.XMLHttp.open("GET", in_url  + "?" + this.PrepareDataToURL(in_valuesList) + "&uniq=" + Math.random(), this.synchronous_request_off);

								// обработчик событий
								if (this.synchronous_request_off == true)
								{
									// если асинхронный режим
									this.XMLHttp.onreadystatechange = function() { AjaxSimpleGL_HandlerFunc(in_thisOBJ) };
								}

								this.XMLHttp.send("uniq=" + Math.random());
							}

                            // если синхронный режим передачи
							if (this.synchronous_request_off == false)
							{
								//alert("если синхронный режим передачи");
								AjaxSimpleGL_HandlerFunc(in_thisOBJ);
							}
						}
					}
				}
            }
            catch(e)
            {
            	if (this._debug == false && this._show_error_user == true) this.ShowAlert("js error, execute request in current moment not possible, please request later");
            	else if (this._debug == true) this.ShowAlert(" :: SendRequest :: " + e.message);
            }
		}



	}
	// end of объект AjaxSimpleGL




