if(document.implementation && document.implementation.createDocument) var isMozilla=true;
	else var isMozilla=false;

var reQuote = /\"/gi;
var savedErrorObject = false;


if(isMozilla){
		//Emulate IE xml property
		XMLDocument.prototype.__defineGetter__("xml", function (){ return (new XMLSerializer()).serializeToString(this); });
		Node.prototype.__defineGetter__("xml", function (){	return (new XMLSerializer()).serializeToString(this); });

		//Emulate IE text property
		XMLDocument.prototype.__defineGetter__("text", function (){ return this.textContent; });
		XMLDocument.prototype.__defineSetter__("text", function (text){ this.textContent=text; });
		Node.prototype.__defineSetter__("text", function (text){ this.textContent=text; });
		Node.prototype.__defineGetter__("text", function (){	return this.textContent });

		//Emulate IE loadXML method
		XMLDocument.prototype._clearDOM = function()
		{
			while(this.hasChildNodes())
			this.removeChild(this.firstChild);
		}

		XMLDocument.prototype._copyDOM = function(oDoc)
		{
			this._clearDOM();
			// importNode is not yet needed in Moz due to a bug but it will be
			// fixed so...
			var oNodes = oDoc.childNodes;
			for(i=0;i<oNodes.length;i++)
			this.appendChild(this.importNode(oNodes[i], true));
		};

		XMLDocument.prototype.loadXML = function(strXML)
		{
			var sOldXML = this.xml;
			var oDoc = (new DOMParser()).parseFromString(strXML, "text/xml");
			this._copyDOM(oDoc);
			return sOldXML;
		};

		//Emulate IE NodeFromID() method
		XMLDocument.prototype.nodeFromID = function(id)
		{
			return this.getElementById(id);
		}
}


//Создание XML объекта из XMLHttpRequest объекта
function createXMLDOM(data){
	if (isMozilla) {
		var xmlObj = document.implementation.createDocument("","doc", null);
		xmlObj = data.responseXML;
	}
	else {
		var xmlObj = new ActiveXObject("Msxml2.DOMDocument");
		xmlObj.loadXML(data.responseText);
	}
	return xmlObj;
}



/*
Создание XMLHttpRequest-объекта
Возвращает созданный объект или null, если XMLHttpRequest не поддерживается
*/
function createRequestObject() {
    var request = null;
    if(!request) try {
        request=new ActiveXObject('Msxml2.XMLHTTP');
    } catch (e){}
    if(!request) try {
        request=new ActiveXObject('Microsoft.XMLHTTP');
    } catch (e){}
    if(!request) try {
        request=new XMLHttpRequest();
    } catch (e){}
    return request;
}

/*
Кодирование данных (простого ассоциативного массива вида { name : value, ...} в
URL-escaped строку (кодировка UTF-8)
*/
function urlEncodeData(data) {
    var query = [];
    if (data instanceof Object) {
        for (var k in data) {
            query.push(encodeURIComponent(k) + "=" + encodeURIComponent(data[k]));
        }
        return query.join('&');
    } else {
        return encodeURIComponent(data);
    }
}

/*
Выполнение POST-запроса
url  - адрес запроса
data - параметры в виде простого ассоциативного массива { name : value, ...}
callback - (не обяз.) callback-функция, которая будет вызвана после выполнения запроса и получения ответа от сервера
*/
function serverRequest(url, data, callback, callbackObj) {
    var request = createRequestObject();
    if(!request) return false;
    request.onreadystatechange  = function() {
            if(request.readyState == 4 && callback) callback(callbackObj,request);
        };
    if (data && data.length){
		request.open('POST', noCache(url), true);
    	request.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
		request.setRequestHeader("Content-Length",data.length);
	} else {
		request.open('GET', noCache(url), true);
		data='';
	}
	try {
		request.send(data);
	} catch (e){
		if (callbackObj) callbackObj.showError(ssLang['FileIsNotFound']);
		else showGlobalError(ssLang['ServerDoesNotRespond']);
	}

    return true;
}


function showGlobalError(string,action, param){
	if (document.getElementById("globalError")) document.body.removeChild(document.getElementById("globalError"));
	var newMessage = document.createElement("DIV");
	newMessage.setAttribute('id','globalError');

	var newLink = document.createElement("A");
	newLink.href='#';
	savedErrorObject=action;
	eval ('newLink.onclick=function(){hideGlobalError(); return false;}');
	newLink.appendChild(document.createTextNode("OK"));
	var newButton = document.createElement("DIV");
	newButton.className='fbutton';
	newButton.appendChild(newLink);

	var newInMessage = document.createElement("DIV");
	newInMessage.className='in';
	newInMessage.appendChild(document.createTextNode(string));
	newMessage.appendChild(newButton);
	newMessage.appendChild(newInMessage);
	document.body.appendChild(newMessage);
	var showObject=document.getElementById("globalError");
	showObject.className="global_error";
	if (window.innerHeight) windowHeight2=window.innerHeight/2;
		else windowHeight2=window.document.body.offsetHeight/2;
	if (window.innerWidth) windowWidth2=window.innerWidth/2;
		else windowWidth2=window.document.body.offsetWidth/2;
	showObject.style.top = document.body.scrollTop+windowHeight2-showObject.clientHeight/2;
	showObject.style.left = document.body.scrollLeft+windowWidth2-showObject.clientWidth/2;
}

function hideGlobalError(){
	showObject=document.getElementById("globalError").style.display="none";
	if (savedErrorObject){
		 doActions(savedErrorObject);
	}
}


function showGlobalMessage(string, actions){
	if (showGlobalMessageTimeout) clearTimeout(showGlobalMessageTimeout);
	if (document.getElementById("globalMessage")) document.body.removeChild(document.getElementById("globalMessage"));
	var newMessage = document.createElement("DIV");
	newMessage.setAttribute('id','globalMessage');
	var newInMessage = document.createElement("DIV");
	newInMessage.appendChild(document.createTextNode(string));
	newMessage.appendChild(newInMessage);
	document.body.appendChild(newMessage);
	var showObject=document.getElementById("globalMessage");
	showObject.className="global_message";
	if (window.innerHeight) windowHeight2=window.innerHeight/2;
		else windowHeight2=window.document.body.offsetHeight/2;
	if (window.innerWidth) windowWidth2=window.innerWidth/2;
		else windowWidth2=window.document.body.offsetWidth/2;
	showObject.style.top = document.body.scrollTop+windowHeight2-showObject.clientHeight/2;
	showObject.style.left = document.body.scrollLeft+windowWidth2-showObject.clientWidth/2;
	showGlobalMessageAlpha=100;
	showGlobalMessageTimeout=setTimeout("hideGlobalMessage()",5000);

	if (actions){
		 doActions(actions);
	}
}


function hideConfirmMessage(){
	if (document.getElementById("globalConfirm")) document.body.removeChild(document.getElementById("globalConfirm"));
	if (document.getElementById("globalConfirmBg")) document.body.removeChild(document.getElementById("globalConfirmBg"));
	window.onresize=null;
}

function showConfirmMessage(string, okTarget, cancelTarget){
	if (document.getElementById("globalConfirm")) document.body.removeChild(document.getElementById("globalConfirm"));
	if (document.getElementById("globalConfirmBg")) document.body.removeChild(document.getElementById("globalConfirmBg"));
	var newMessageBg = document.createElement("DIV");
	newMessageBg.setAttribute('id','globalConfirmBg');
	newMessageBg.appendChild(document.createTextNode(" "));
	document.body.appendChild(newMessageBg);
	var showObject=document.getElementById("globalConfirmBg");
	showObject.className="global_confirm_bg";

	document.getElementById("globalConfirmBg").style.width=document.body.clientWidth+"px";
	document.getElementById("globalConfirmBg").style.height=document.body.clientHeight+"px";

	window.onresize=function(){
		document.getElementById("globalConfirmBg").style.width=document.body.clientWidth+"px";
		document.getElementById("globalConfirmBg").style.height=document.body.clientHeight+"px";
	};

	var newLink = document.createElement("A");
	newLink.href='#';
	eval ('newLink.onclick=function(){hideConfirmMessage(); '+okTarget+'; return false;}');
	newLink.appendChild(document.createTextNode(ssLang['Yes']));
	var newButton = document.createElement("DIV");
	newButton.className='fbutton';
	newButton.appendChild(newLink);

	var newLink2 = document.createElement("A");
	newLink2.href='#';
	eval ('newLink2.onclick=function(){hideConfirmMessage(); '+cancelTarget+';  return false;}');
	newLink2.appendChild(document.createTextNode(ssLang['No']));
	var newButton2 = document.createElement("DIV");
	newButton2.className='fbutton';
	newButton2.appendChild(newLink2);

	var newlinksCont = document.createElement("DIV");
	newlinksCont.className='buttons';
	newlinksCont.appendChild(newButton2);
	newlinksCont.appendChild(newButton);

	var newMessage = document.createElement("DIV");
	newMessage.setAttribute('id','globalConfirm');
	var newInMessage = document.createElement("DIV");
	newInMessage.className='in';
	newInMessage.appendChild(document.createTextNode(string));
	newMessage.appendChild(newInMessage);
	newMessage.appendChild(newlinksCont);
	document.body.appendChild(newMessage);
	var showObject=document.getElementById("globalConfirm");
	showObject.className="global_confirm";
	if (window.innerHeight) windowHeight2=window.innerHeight/2;
		else windowHeight2=window.document.body.offsetHeight/2;
	if (window.innerWidth) windowWidth2=window.innerWidth/2;
		else windowWidth2=window.document.body.offsetWidth/2;
	showObject.style.top = document.body.scrollTop+windowHeight2-showObject.clientHeight/2;
	showObject.style.left = document.body.scrollLeft+windowWidth2-showObject.clientWidth/2;
}

function doActions(actions){
	for (var i=0; i<actions.length; i++){
		if (actions[i].attributes){
			if (actions[i].attributes.getNamedItem('type')){
				var action=actions[i].attributes.getNamedItem('type').value;
				if (actions[i].attributes.getNamedItem('param'))
					var param=actions[i].attributes.getNamedItem('param').value;
				else var param=false;
				doAction(action, param);
			}
		}
	}
}

function doAction(action, param){
	switch (action){
		case "golink":
			document.location=param;
			break;
		case "close":
			window.close();
			break;
		case "callopener":
			callOpener(param);
			break;
		case "callmethod":
			callExtMethod(param);
			break;
	}
}

var showGlobalMessageAlpha=false;
var showGlobalMessageTimeout=false;

function hideGlobalMessage(){
	var showObject=document.getElementById("globalMessage");
	if (showGlobalMessageAlpha>0){
		showGlobalMessageAlpha=showGlobalMessageAlpha-10;
		showObject.style.filter='alpha(opacity='+showGlobalMessageAlpha+')';
		showGlobalMessageTimeout=setTimeout("hideGlobalMessage()",20);
	} else showObject.style.display="none";
}


//Имя окна, путь, "метод передачи данных", данные
function openPopup(name,path, method, data){
	var W=820;
	var H=570;
	var X=(window.screen.availWidth/2)-(W/2);
	var Y=(window.screen.availHeight/2)-(H/2);
	var param = "scrollbars=no, status=no, resizable=0,width=" + W + ",height=" + H + ",left=" + X + ",top=" + Y;
	if (!method){
		var popup=window.open(path, name, param);
		popup.focus();
	} else if (method.toUpperCase()=="GET") {
		var popup=window.open(path+"?"+data, name, param);
		popup.focus();
	} else {
		var popup=window.open("", name, param);
		popup.focus();
		popup.document.write('<form id="postform" action="'+path+'" method="POST" style="visibility: hidden">');
		var dataArray = new Array();
		var dataVal = new Array();
		dataArray=data.split("&");
		for(var i=0; i<dataArray.length; i++){
			//dataVal=dataArray[i].split("=");
			dataVal[0] = dataArray[i].substr(0, dataArray[i].indexOf("=")) ;
			dataVal[1] = dataArray[i].substr(dataArray[i].indexOf("=")+1) ;
			popup.document.write('<textarea name="'+dataVal[0]+'">'+decodeURIComponent(dataVal[1])+'</textarea>');
		}
		popup.document.write('</form>');
		popup.document.close();
		popup.document.getElementById("postform").submit();
	}
	return false;
}


//Имя окна, путь, "метод передачи данных", данные
function openPopupSlice(name,path, method, data, width, height){
	var W=width;
	var H=height;
	var X=(window.screen.availWidth/2)-(W/2);
	var Y=(window.screen.availHeight/2)-(H/2);
	var param = "scrollbars=no, status=no, resizable=0,width=" + W + ",height=" + H + ",left=" + X + ",top=" + Y;
	if (!method){
		var popup=window.open(path, name, param);
		popup.focus();
	} else if (method.toUpperCase()=="GET") {
		var popup=window.open(path+"?"+data, name, param);
		popup.focus();
	} else {
		var popup=window.open("", name, param);
		popup.focus();
		popup.document.write('<form id="postform" action="'+path+'" method="POST" style="visibility: hidden">');
		var dataArray = new Array();
		var dataVal = new Array();
		dataArray=data.split("&");
		for(var i=0; i<dataArray.length; i++){
			//dataVal=dataArray[i].split("=");
			dataVal[0] = dataArray[i].substr(0, dataArray[i].indexOf("=")) ;
			dataVal[1] = dataArray[i].substr(dataArray[i].indexOf("=")+1) ;
			popup.document.write('<textarea name="'+dataVal[0]+'">'+decodeURIComponent(dataVal[1])+'</textarea>');
		}
		popup.document.write('</form>');
		popup.document.close();
		popup.document.getElementById("postform").submit();
	}
	return false;
}

function openModal(name,path, method, data){
	if (isMozilla) openPopup(name,path, method, data);
	else {
		var W=825;
		var H=595;
		var param = "scroll=no; help=no; resizable=no; status=no; center=yes; dialogWidth=" + W + "px; dialogHeight=" + H+"px";
		if (!method){
			var popup=window.showModalDialog(path, null, param);
		} else if (method.toUpperCase()=="GET") {
			var popup=window.showModalDialog(path+"?"+data, null, param);
		}
	}
	return false;
}

function reloadWindow(name,path, method, data){
	if (!method){
		document.location=path;
	} else if (method.toUpperCase()=="GET") {
		document.location=path+"?"+data;
	} else {
		var tempStr='<form id="postform" action="'+path+'" method="POST" style="visibility: hidden">';
		var dataArray = new Array();
		dataArray=data.split("&");
		for(var i=0; i<dataArray.length; i++){
			dataVal=dataArray[i].split("=");
			tempStr+='<textarea name="'+dataVal[0]+'">'+decodeURIComponent(dataVal[1])+'</textarea>';
		}
		tempStr+='</form>';
		document.body.innerHTML=tempStr;
		document.getElementById("postform").submit();
	}
	return false;
}


//Проверка на ввод только целых чисел
function checkNumeric(ev){
	if (isMozilla) {
		event=ev;
		if ((event.charCode>47 && event.charCode<58) || event.charCode==0) return event;
			else return false;
	} else {
		if (event.keyCode>47 && event.keyCode<58) return event;
			else return false;
	}
}

//Возвращает текушее время в милисекундах
function getCurrentTime(){
	var now = new Date()
	return now.getTime();
}

//Удаляет Id у объекта
function removeId(obj){
	obj.removeAttribute('id');
	return obj;
}

//Вычисление смещения y координаты объета
function calcTop(x_ele){
//	if (!document.all) return (x_ele.offsetTop);
	var x_ret=0;
	var oParent = x_ele.offsetParent;
	if (oParent == null) return 0
		else x_ret=x_ele.offsetTop + calcTop(oParent);
	return x_ret;
}

//Вычисление смещения x координаты объета
function calcLeft(x_ele){
//	if (!document.all) return (x_ele.offsetLeft);
	var x_ret=0;
	var oParent = x_ele.offsetParent;
	if (oParent == null) return 0
		else x_ret=x_ele.offsetLeft + calcLeft(oParent);
	return x_ret;
}

//Обработчик глобальных ошибок и сообщений (для всех xml)
function checkGlobalMessage(xmlObj){
	var node = false;
	var error=xmlObj.getElementsByTagName("globalerror");
	if (error.length>0){
		node=error[0];
		if (node.text) var str=node.text;
		else var str=ssLang['Error::DataLoadingError'];
	} else {
		if (xmlObj.getElementsByTagName("globalmessage").length>0)	{
			node = xmlObj.getElementsByTagName("globalmessage")[0];
			if (node.text) var str=xmlObj.getElementsByTagName("globalmessage")[0].text;
			else var str="";
		} else var str="";
	}
	var actions=xmlObj.getElementsByTagName('action');
	if (actions.length<1) actions=false;
	if (node){
		if (error.length>0) showGlobalError(str,actions);
			else showGlobalMessage(str,actions);
		return true;
	} else return false;
}


//Отменить действие по-умолчанию
function noEvent(ev){
	if (isMozilla) ev.preventDefault();
}


function showObj(id){
	document.getElementById(id).style.display="block";
}

function hideObj(id){
	document.getElementById(id).style.display="none";
}

function showElementObject(id){
	showObj("element_"+id);
}

function hideElementObject(id){
	hideObj("element_"+id);
}

//Обработчик данных проверки прав доступа при авторизации
var checkingAuthUser = function (obj, data){
	if (data.status==0 || data.status==200){
		if (isMozilla) {
			var obj = document.implementation.createDocument("","doc", null);
			obj = data.responseXML;
		}
		else {
			var obj = new ActiveXObject("Msxml2.DOMDocument");
			obj.loadXML(data.responseText);
		}
		if (obj.getElementsByTagName("accessgranted").length>0){
			document.getElementById("auth_text").innerHTML=obj.getElementsByTagName("accessgranted")[0].text;
			document.location=obj.getElementsByTagName("accessgranted")[0].attributes.getNamedItem('path').value;
		} else {
			if (obj.getElementsByTagName("accessdenied")) document.getElementById("auth_text").innerHTML=obj.getElementsByTagName("accessdenied")[0].text;
		}
	} else showGlobalError(ssLang['ServerDoesNotRespond']);
}

//Проверка прав доступа при авторизации
function checkAuthUser(){
	//var request="login="+encodeURIComponent(document.getElementById("auth_login").value)+"&"+"password="+encodeURIComponent(document.getElementById("auth_password").value) +"&"+"remember_data="+encodeURIComponent(document.getElementById("remember_data").checked);
	var request="login="+encodeURIComponent(document.getElementById("auth_login").value)+"&"+"password="+encodeURIComponent(document.getElementById("auth_password").value);
	if (request) {
		serverRequest(checkUserPath, request, checkingAuthUser, null);
	}
	return false;
}

//добавление в имя файла случайной переменной
function noCache(name){
	var rand=Math.round(Math.random()*1000000);
	if (name.indexOf("?")>-1) return name+="&nocachexml="+rand;
	else  return name+="?nocachexml="+rand;
}


//Выполнить метод в родителе
function callOpener(method){
	if (opener && opener.location){
		try {
			eval("opener."+method);
		} catch (error){
			;
		}
	}
}

//Выполнить метод целевого объекта
function callMethod(target,method){
	if (target){
		try {
			eval(target+"."+method);
		} catch (error){
			;
		}
	}
}

//Выполнить метод целевого объекта
function callExtMethod(method){
	try {
		eval(method);
	} catch (error){
		;
	}
}

function viewObject(name)
{
	var obj = eval(name), i;
	if(!obj) {
		alert("\""+name+"\" ia not an object");
		return;
	}
	var w_Test = open("","Test","width=600,height=500,scrollbars=1");
	if(!w_Test)	{
		alert("Cannot open window for "+name);
		return;
	}

	w_Test.document.open();

	for(i in obj) w_Test.document.write(name+"."+i+"="+obj[i]+"<br>");

	w_Test.document.close();
}


