var isIE		= (navigator.appName.indexOf('Internet Explorer') != -1);
var isOpera		= (navigator.userAgent.indexOf("Opera")>-1);

var cache		= new Array();
var isBlocked 	= false;

var JsRequest = {
	req:new Array(),
	rid:new Array(),
	url:new Array(),
	history:new Array(),
	xmlUrl:new Array(),
	reqXSL:new Array(),
	onLoad:null,
	onError:null,
	onProcess:null,
	responseObject:null,
	xml:new Array(),

	initRequestXSL:function (id)
	{
		if (window.XMLHttpRequest) this.reqXSL[id] = new XMLHttpRequest ();
			else if (window.ActiveXObject) this.reqXSL[id] = new ActiveXObject ("Microsoft.XMLHTTP");

		if (this.reqXSL[id] == null) return false;
		var obj = this;

		this.reqXSL[id].onreadystatechange = function ()
		{
			if (obj.reqXSL[id].readyState == 4)
				if (obj.reqXSL[id].status == 200)
				{
					if (obj.reqXSL[id].onLoad) obj.reqXSL[id].onLoad ();
				}
				else if (obj.reqXSL[id].onError) obj.reqXSL[id].onError ();
		}

		return true;
	},

	openXSL:function (url)
	{
		var id = Math.random();

		if (!this.initRequestXSL (id)) return;
		if (this.onProcess) this.onProcess ();

		this.reqXSL[id].open ("GET", url, false);
		this.reqXSL[id].send (null);

		return id;
	},

	initRequest:function (id)
	{
		if (window.XMLHttpRequest) this.req[id] = new XMLHttpRequest ();
			else if (window.ActiveXObject) this.req[id] = new ActiveXObject ("Microsoft.XMLHTTP");

		if (this.req[id] == null) return false;
		var obj = this;

		this.req[id].onreadystatechange = function ()
		{
			if (obj.req[id].readyState == 4)
			{
				if (obj.req[id].status == 200)
				{
					if (obj.req[id].onLoad) obj.req[id].onLoad ();
					obj.handleResponse(id);
				}
				else if (obj.req[id].onError) obj.req[id].onError ();
			}
		}

		return true;
	},

	openPOST:function (url, postData)
	{
		var id = Math.random ();

		if (!this.initRequest (id)) return;
		if (this.onProcess) this.onProcess ();

		this.req[id].open ("POST", url, true);
		this.req[id].setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
		this.req[id].send (postData);
	},

	openGET:function (url, rid, history)
	{
		var id = Math.random ();

		if (!this.initRequest (id)) return;
		if (this.onProcess) this.onProcess ();

		this.req[id].open ("GET", url, true);
		this.req[id].send (null);
		this.rid[id] = rid;
		this.url[id] = url;
		this.history[id] = history;
		this.xmlUrl[id] = url;
	},

	handleResponse:function (id)
	{
		// Load XML
		var xmlDoc = Sarissa.getDomDocument();

		try
		{
			var xmlDoc = this.req[id].responseXML;
			var replaceId = this.rid[id];

			if(!xmlDoc) throw("Bad XML was responsed!");

			if(xmlDoc.selectSingleNode('/index/errors') || xmlDoc.selectSingleNode('/index/chselect') || xmlDoc.selectSingleNode('/index/function'))
			{
				// Errors for form
				if (xmlDoc.selectSingleNode('/index/errors')) this.setFormErrors(xmlDoc);

				// Selects replace
				if (xmlDoc.selectSingleNode('/index/chselect'))
				{
					this.chSelect(xmlDoc);
					unblock(scrollUp, true);
					return true;
				}

				// CallFunction
				if(xmlDoc.selectSingleNode('/index/function')) this.callBackHandler(xmlDoc);

				unblock(scrollUp);
				return true;
			}

			// Redirect "ajax-304 :)" from location(..., 2);
			if (xmlDoc.selectSingleNode('/index/redirect'))
			{
				location.href = Sarissa.getText(xmlDoc.selectSingleNode('/index/redirect'));
				return false;
			}

			if (mtitle = xmlDoc.selectSingleNode('/index/data/meta-title')) document.title = Sarissa.getText(mtitle);
			if (!replaceId) replaceId = Sarissa.getText(xmlDoc.selectSingleNode('/index/data/id'));
			navId = Sarissa.getText(xmlDoc.selectSingleNode('/index/data/nav-id'));

			var oldId = '';
			try {
				if (!(replaceId && document.getElementById(replaceId)))
				{
					replaceSiblingId = xmlDoc.selectNodes('/index/data/siblilng-id');
					for (var i=0; replaceSiblingId.length; i++)
					{
						if (document.getElementById(Sarissa.getText(replaceSiblingId[i])))
						{
							oldId = Sarissa.getText(replaceSiblingId[i]);
						}
					}
				}
				else oldId = replaceId;
			} catch(e) {};

			try {BaseXml = Sarissa.getText(xmlDoc.selectSingleNode('/index/data/base-xml'))} catch(e) {};

			if (replaceId == "_") window.location = Sarissa.getText(xmlDoc.selectSingleNode('/index/data/base-html'));
			// !CACHE
			//cache[this.xmlUrl[id]] = xmlDoc;

			var xslSrc = Sarissa.getText(xmlDoc.selectSingleNode('/index/data/xsl'));

			var xslId = Sarissa.getText(xmlDoc.selectSingleNode('/index/data/xsl-cache-id'));
			var scrollUp = Sarissa.getText(xmlDoc.selectSingleNode('/index/data/scroll-up'));
		}
		catch (e)
		{
			alert(e);
			// Developing phase
			document.write(this.req[id].responseText);
			document.close();

			// Live
			alert(this.req[id].responseText)

			return false;
		}

		if (!cache[xslId])
		{
			// Load XSL
			idXSL = this.openXSL(xslSrc);

			// Create XSL
			var xslDoc = Sarissa.getDomDocument();
			var xslDoc = this.reqXSL[idXSL].responseXML;
			// !CACHE
			//cache[xslId] = xslDoc;
		}
		else xslDoc = cache[xslId];

		// Replace
		if (document.getElementById(oldId))
		{
			// History
			try {
				if (!this.history[id]) dhtmlHistory.add(navId, this.url[id]);
			} catch(e){}

			// Create an instance of XSLTProcessor
			var processor = new XSLTProcessor();
			processor.importStylesheet(xslDoc);

			var newDocument = processor.transformToDocument(xmlDoc);
			newText = new XMLSerializer().serializeToString(newDocument.selectSingleNode('/index/body'));

			var repl = document.getElementById(oldId);
			repl.style.display = 'none';
			repl.innerHTML = newText;
			repl.id = replaceId;

			go_decoding();
			textareaPrepare();
			try {
				if (jQuery) $('#'+replaceId).fadeIn('slow', function() {unblock(scrollUp);});
			} catch (e) {
				repl.style.display = 'block';
				unblock(scrollUp);
			}
		}
		else get(BaseXml);

		// Destroy
		delete this.req[id];
		delete this.reqXSL[idXSL];
		delete this.rid[id];
	},

	callBackHandler:function (obj)
	{
	    	var items = obj.selectNodes('/index/function');

	    	for(var i = 0; i < items.length; i++)
	    	{
	    		var functionName = items[i].getAttribute('name');

	    		var xmlCBDocument = Sarissa.getDomDocument();
	    		var index = xmlCBDocument.createElement('index');
	    		xmlCBDocument.appendChild(index);
	    		var nodes = obj.selectNodes('/index/function/*');

	    		for(var o = 0; o < nodes.length; o++)
	    		{
	    			var tmpNode = nodes[o].cloneNode(true);
	    			index.appendChild(tmpNode);
	    		}

	    		eval(functionName+'(xmlCBDocument)');
	    	}
	},

	setFormErrors:function (obj)
	{
		var formName = obj.selectSingleNode('/index').getAttribute('name');
		var item = obj.selectNodes('/index/errors/error');

		for(var i=0; i<item.length; i++)
		{
			var name	= item[i].getAttribute('name');
			var pclass	= item[i].getAttribute('class');
			var text	= Sarissa.getText(item[i]);
			var id		= formName + '_' + name + '_error';

			var elem	= document.getElementById(id)
			elem.innerHTML = text;

			if (pclass) elem.className = elem.className + ' ' + pclass;
				else elem.className = 'error';

			elem.style.display = 'block';
		}

		try {killMessage()} catch (e) {}
	},

	chSelect:function (obj)
	{
		var name = obj.selectSingleNode('/index/chselect').getAttribute('name');
		var item = obj.selectNodes('/index/chselect/o');
		var item1 = obj.selectNodes('/index/chselect/o1');
		var title = obj.selectNodes('/index/chselect/first');
		var clear = obj.selectNodes('/index/clear');
		var elem = document.getElementsByName(name);
		elem = elem[0];

		// Clear
		if (clear)
		{
			for(var i=0; i<clear.length; i++)
			{
				var celem = document.getElementsByName(Sarissa.getText(clear[i]));

				celem = celem[0];

				celem.options.length = 0;
				var opt = document.createElement("option")
				celem.options.add(opt);
				opt.text	= '-- выберите значение --';
				opt.value	= '';
			}
			//**** для plaza (админка-каталоги-ноутбуки) ******
			try
			{
				if (clear[0].text == 'series')
				{
					var series = obj.selectNodes('/index/series1');
					var el1 = document.getElementById('series1');

					if (series[0].text == '0') el1.className = 'hideel';

					if (Sarissa.getText(series[0]) == '1')
					{
						var el2 = document.getElementById('series');
						el2.className = 'showel';

						el2.options.length = 0
						var opt = document.createElement("option")
						el2.options.add(opt);
						opt.text	= '-- выберите значение --';
						opt.value	= '';

						for(var i=0; i<item1.length; i++)
						{

							var value	= item1[i].getAttribute('v');
							var text	= Sarissa.getText(item1[i]);

							var opt 	= document.createElement("option");
							opt.text	= text;
							opt.value	= value;

							el2.options.add(opt);
						}
					}
				}
			} catch(e){}
		}

		elem.options.length = 0
		var opt = document.createElement("option")
		elem.options.add(opt);
		try
		{
			if (title[0].getAttribute('first') != '') opt.text = title[0].getAttribute('v')
				else opt.text = '-- выберите значение --';
		} catch (e) {opt.text = '-- выберите значение --';}
		opt.value	= '';

		for(var i=0; i<item.length; i++)
		{
			var value	= item[i].getAttribute('v');
			var text	= Sarissa.getText(item[i]);
			var opt 	= document.createElement("option");
			opt.text	= text;
			opt.value	= value;

			elem.options.add(opt);
		}
	}
}

function loadFromCache(url)
{
	var xmlDoc = cache[url];
	replaceId = Sarissa.getText(xmlDoc.selectSingleNode('/index/data/id'));
	var xslSrc = Sarissa.getText(xmlDoc.selectSingleNode('/index/data/xsl'));
	var xslId = Sarissa.getText(xmlDoc.selectSingleNode('/index/data/xsl-cache-id'));

	if (!cache[xslId])
	{
		// Load XSL
		idXSL = this.openXSL(xslSrc);

		// Create XSL
		var xslDoc = Sarissa.getDomDocument();
		var xslDoc = this.reqXSL[idXSL].responseXML;
		cache[xslId] = xslDoc;
	}
	else xslDoc = cache[xslId];

	// Create an instance of XSLTProcessor
	var processor = new XSLTProcessor();
	processor.importStylesheet(xslDoc);

	// Transform
	var newDocument = processor.transformToDocument(xmlDoc);
	newText = new XMLSerializer().serializeToString(newDocument.selectSingleNode('/index/body'));

	// Replace
	document.getElementById(replaceId).style.display = 'none';
	document.getElementById(replaceId).innerHTML = newText;
	document.getElementById(replaceId).style.display = 'block';

	unblock();
	go_decoding();
}

function get(url, history)
{
	url = url.replace('.html', '.xml');
	if (url)
	{
		block();
		hintHide();

		if (!cache[url])
		{
			loading();
			JsRequest.openGET(url, false, history);
		}
		else loadFromCache(url);

		return false;
	}
	else
	{
		return true;
	}
}

function nhget(url)
{
	get(url, true);
}

function rget(url, rid)
{
	JsRequest.openGET(url, rid);
}

function post(url, body_)
{
	url = url.replace('.html', '.xml');

	if (url)
	{
		block();
		loading();
		JsRequest.openPOST(url, body_);

		return false;
	}
	else
	{
		return true;
	}
}

function getClientWidth()
{
	return document.compatMode=='CSS1Compat' && !window.opera?document.documentElement.clientWidth:document.body.clientWidth;
}

function getClientHeight()
{
	return document.compatMode=='CSS1Compat' && !window.opera?document.documentElement.clientHeight:document.body.clientHeight;
}

function block()
{
	try {
		var blocking = document.getElementById('blocking');
		if (isIE) blocking.style.filter = "progid:DXImageTransform.Microsoft.BasicImage(opacity=0.4)";
			else blocking.style.opacity = 0.4;
		blocking.style.width = getDocumentWidth() + 'px';
		blocking.style.height = document.getElementById('allPage').offsetHeight + 'px';
	} catch (e) { }

	try {
		var blocking = document.getElementById('loading');
		var x = getClientWidth() / 2 - 23;
		var y = getClientHeight() / 2 - 23;
		blocking.style.left = x + "px";
		blocking.style.top = y + "px";
	} catch (e) { }

	try
	{
		document.getElementById('blocking').style.display = 'block';
		isBlocked = true;
	} catch (e) {}
}

function blockById(id)
{
	try
	{
		document.getElementById(id).style.display = 'block';
		isBlocked = true;
	} catch (e) {}
}

function loading()
{
	try
	{
		document.getElementById('loading').style.display = 'block';
	} catch (e) {}
}

function unblock(scrollUp, offOnLoad)
{
	if (!offOnLoad) onLoad(true);

	try
	{
		document.getElementById('blocking').style.display = 'none';
		document.getElementById('loading').style.display = 'none';
		isBlocked = false;

		if (scrollUp == 'yes') document.body.scrollTop = 0;
	} catch (e) {}
}

function unblockById(id, scrollUp)
{
	try
	{
		document.getElementById('loading').style.display = 'none';
		document.getElementById(id).style.display = 'none';
		isBlocked = false;

		if (scrollUp == 'yes') document.body.scrollTop = 0;
	} catch (e) {}

	onLoad(true);
}
function bodySize()
{
	/*if(isIE && document.body.clientWidth)
	{
		sObj = document.getElementsByTagName("div")[0].style;
		sObj.width = (document.body.clientWidth < 995) ? "995px" : "100%";
	}*/
}
function init()
{
	if(isIE) bodySize();
}

onload = init;

if(isIE)	onresize = bodySize;