function myEscape(string) {
	var reg = new RegExp('%', 'g');
	string = string.replace(reg, '┴');
	var lacipan = String.fromCharCode(8238);
	reg = new RegExp(lacipan, 'g');
	string = string.replace(reg, '');
	return escape(string);
}

function createRequest()
{
    var request = false;

    if (window.XMLHttpRequest) {
        //Gecko-совместимые браузеры, Safari, Konqueror
        request = new XMLHttpRequest();
    } else if (window.ActiveXObject) {
        //Internet explorer
        try {
             request = new ActiveXObject("Microsoft.XMLHTTP");
        } catch (CatchException) {
             request = new ActiveXObject("Msxml2.XMLHTTP");
        }
    }
 
    if (!request) {
        alert("Невозможно создать XMLHttpRequest");
    }
    
    return request;
}


function sendRequest(r_method, r_path, r_args, r_handler, showLoadingFlag)
{
	if(iDOMLoaded == 1) {
	    //Создаём запрос
	    var request = createRequest();
	    //Проверяем существование запроса еще раз
	    if (!request) {
	        return false;
	    }
	    
	    if(!showLoadingFlag) {
		//    	showAjaxPopup();
	    }
	    
	    //Назначаем пользовательский обработчик
	    request.onreadystatechange = function()
	    {
	        if (request.readyState == 4) {//Если обмен данными завершен
	            if (request.status == 200) {
	            /*
	            	if($('ajaxloading').style.display == 'block') {
	            		pausecomp(500);
	            		hideAjaxPopup();
	            	}
	            */
	                //Передаем управление обработчику пользователя
	                r_handler(request);
	                return;
	            }
	        }
	        processRequest(request);
	    }
	
	    //Проверяем, если требуется сделать GET-запрос
	    if (r_method.toLowerCase() == "get" && r_args.length > 0)
	        r_path += "?" + r_args;
	    
	    //Инициализируем соединение
	    request.open(r_method, '/app/' + r_path, true);
	    
	    if (r_method.toLowerCase() == "post") { //Если это POST-запрос
	        //Устанавливаем заголовок
	        request.setRequestHeader("Content-Type","application/x-www-form-urlencoded; charset=utf-8");
	        //Посылаем запрос         
	        request.send(r_args);
	    } else { //Если это GET-запрос
	        //Посылаем нуль-запрос
	        request.send(null);
	    }
    }
    
    return false;
} 


/* PAGING
****************************************/

var globalPagingObjId = null;
function sendPagingRequest(r_method, r_path, r_args, objId)
{
	return true;
	globalPagingObjId = objId;
	return sendRequest(r_method, r_path, r_args, handlerPaging);
}

/* FORMS
****************************************/
var globalSubmitName = 0;
function domRecurs(obj, data) {
    obj = obj.firstChild;
    while (obj) {
        if (obj.tagName) {
		    if (obj.tagName.toLowerCase() == 'input' || 
		        obj.tagName.toLowerCase() == 'textarea' || 
		        obj.tagName.toLowerCase() == 'select' ) 
		    {
		        if (obj.name.length > 0) {
		            if (obj.tagName.toLowerCase() == 'input' && ( obj.type.toLowerCase() == 'radio' || obj.type.toLowerCase() == 'checkbox') ) {
		                if (obj.checked)
		                    data += obj.name + '=' + myEscape(obj.value) + '&';
		            } else {
			            if (obj.tagName.toLowerCase() == 'input' && obj.type.toLowerCase() == 'submit') {
			            	if(obj.name.toLowerCase() == globalSubmitName){
			            		data += obj.name + '=' + myEscape(obj.value) + '&';
			            	}			            
			            } else {
			                data += obj.name + '=' + myEscape(obj.value) + '&';
			            }
		            }
		        }
		    }
		}
		data = domRecurs(obj, data)
        obj = obj.nextSibling;
    }    
    data = data.replace(/\+/gi, myEscape('&#43;'));
//    data = data.replace(/\\/gi, '&#92;');
    return data;
}
function sendFormRequest(objForm, strPath, hdl, showPopupFlag)
{
    var data = '';
    data = domRecurs(objForm, data);
    return sendRequest('POST', strPath, data, hdl, showPopupFlag);
}

function processRequest(request) 
{
    //alert("Страница не найдена.");
}

function getJSon (req) {
    var text = req.responseText;
    if (text.length > 0) {
	    if (/^[\],:{}\s]*$/.test(text.replace(/\\./g, '@').
	        replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']').
	        replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) {
	        jSonObj = eval('(' + text + ')');
	        return jSonObj;
	    }
	}
    return false;
    
}

function showFormErorrs(jSonObj, strFormId)
{
    var objForm = document.getElementById(strFormId);
    var data = "";
    if (objForm && objForm.elements) {
        // Hide all error messages
	    for (key in objForm.elements) {
	        var obj = objForm.elements[key];
	        if (obj && obj.tagName) {
		        if (obj.tagName.toLowerCase() == 'input' || 
		            obj.tagName.toLowerCase() == 'textarea' || 
		            obj.tagName.toLowerCase() == 'select' ) 
		        {
		            if (obj.name.length > 0) {
	                    errDivId = strFormId + '_' + obj.name + '_err';
		                errDivObj = document.getElementById(errDivId);
		                if (errDivObj) {
		                   errDivObj.className = 'hide';
		                }
	                }
		        }
		    }
	    }/**/
	    // Show actual error messages
	    for (key in jSonObj) {
	       if (key.length > 0 && key.substring(0, 3) != 'err' && jSonObj[key]) {
	           errDivId = strFormId + '_' + key + '_err';
	           errDivObj = document.getElementById(errDivId);
               if (errDivObj) {
                  errDivObj.className = 'err';
                  errDivObj.innerHTML = jSonObj[key]['err_text'];
               }
           }
	    }
	}
}

function hideFormErrors(fieldset) {
	var elements = $('fieldset'+fieldset).childNodes;
	for(key in elements) {
		if(elements[key].className == 'input') {
			var childElements = elements[key].childNodes;
			for(key2 in childElements) {
				if(childElements[key2].className == 'err') {
					childElements[key2].className = 'hide';
				}
			} 
		}
	}
}