var usingXMLHttpRequest=false;
var requestStack=new Array(0);

function createXmlHttpRequestObject() {
	var xmlHttp;
	try {
		xmlHttp=new XMLHttpRequest();
		usingXMLHttpRequest=true;
	}
	catch(e) {
		var XmlHttpVersions=new Array('MSXML2.XMLHTTP.6.0','MSXML2.XMLHTTP.5.0','MSXML2.XMLHTTP.4.0','MSXML2.XMLHTTP.3.0','MSXML2.XMLHTTP','MICROSOFT.XMLHTTP');
		for(var i=0;i<XmlHttpVersions.length && !xmlHttp;i++) {
			try {
				xmlHttp=new ActiveXObject(XmlHttpVersions[i]);
			}
			catch(e) {}
		}
	}
	
	if(xmlHttp)
		return xmlHttp;
	else
		alert('Error creating the XMLHttpRequest object.');
}

function sendRequest(request,data) {
	var xmlHttp;
//alert('0');
	if(usingXMLHttpRequest==false || xmlHttp==null)
		xmlHttp=createXmlHttpRequestObject();

	if(request["url"] && (request["class"] || request["container"] || request["ajax"])) {
		if(xmlHttp.readyState == 4 || xmlHttp.readyState == 0) {
			try {
				if(request['indicator'])
					ShowDiv(request['indicator']);

				for(i=0 ; request['indicator'+i] ; i++)
					ShowDiv(request['indicator'+i]);
					
				if(request['grndDiv'] && request['grndImg'])
					if(elem=myGetElementById(request['grndDiv']))
						with(elem) {
							if(request['grndClearContent']==true)
								innerHTML='';
							style.backgroundImage='url('+request['grndImg']+')';
							style.backgroundRepeat='no-repeat';
							if(request['grndLoc'])
								style.backgroundPosition=request['grndLoc'];
							else
								style.backgroundPosition='center';
						}
				
				if(request['grndClearContent'] && request['grndClearContent']!=true)
					if(elem=myGetElementById(request['grndClearContent']))
						with(elem)
							if(request['grndClearContent']==true)
								innerHTML='';
				
	/*					
				for(i=0 ; request['grndDiv'+i] ; i++)
					if(elem=myGetElementById(request['grndDiv'+i]))
						with(elem) {
							if(request['grndClearContent'+i])
								innerHTML='';
							if(request['grndImg'+i])
								grndImg=request['grndImg'+i];
							else
								grndImg=request['grndImg'];
							style.backgroundImage='url('+grndImg+')';
							style.backgroundRepeat='no-repeat';
							style.backgroundPosition='center';
						}
	*/
	
				if(request["ajax"])
					url=request["url"]+'?ajax='+request["ajax"];
				else
					url=request["url"]+'?ajax=true';
				if(document.location.search.search(/phpinfo/)>0)
					url+='&phpinfo=true';

				if(request["class"])
					url+='&class='+request["class"];
				if(request["container"])
					url+='&container='+request["container"];
				if(request["method"])
					url+='&method='+request["method"];
				var param='';
				if(data)
					for(var key in data)
						if(key!='') {
							if(param)
								param+='&';
							param+=key+'='+data[key];
						}
				xmlHttp.onreadystatechange=function() { 
					if(xmlHttp && xmlHttp.readyState==4 && xmlHttp.status==200)
						handleServerResponse(xmlHttp,request);
				}
					
				if(request["POST"]) {
					if(document.location.search.search(/ajaxdebug/)>0)
						window.open(url,'dump');

					xmlHttp.open("POST",url,true);
					xmlHttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded; charset=UTF-8");
 					xmlHttp.send(param);
 				//	alert('POST:'+param);
 					outputDump('Ajax request (POST)',url,true);
 					outputDebug('Ajax request (POST)',url);
 				}
				else {
					if(document.location.search.search(/ajaxdebug/)>0) {
						alert(url+'&'+param);
						window.open(url+'&'+param,'dump');
					}
			//		alert(url+'&'+param);
					outputDump('Ajax request (GET)','<a href="'+url+'&'+param+'" target="ajax">'+url+'&'+param+'</a>',true);
 			//		outputDebug('Ajax request (GET)','<a href="'+url+'&'+param+'" target="ajax">'+url+'&'+param+'</a>');
					xmlHttp.open("GET",url+'&'+param,true);
					xmlHttp.send(null);
				}
				
				requestStack=requestStack.concat(xmlHttp);
				callStr="cancelRequest("+(requestStack.length-1)+")";
		//		setTimeout(callStr,20000);
			}
			catch(e) {
				alert("Can't connect to server:\n"+e.toString()+" "+e.message+" "+request["url"]);
			}
		}
		else {
	/*
			var callStr="";
			requestLength=dataLength=0;
			for(var key in request) {
				callStr+=",'"+key+"','"+request[key]+"'";
				requestLength++;
				
			}
			for(var key in data) {
				callStr+=",'"+key+"','"+data[key]+"'";
				dataLength++;
			}
			callStr="sendRequest2("+requestLength+","+dataLength+callStr+")";
	*/
			params=getRequestParams(request,data);
			callStr="sendRequest2("+params+")";
			setTimeout(callStr,300);
		}
	}
}

function getRequestParams(request,data) {
	requestLength=dataLength=0;
	var params="";
	for(var key in request) {
		params+=",'"+key+"','"+request[key]+"'";
		requestLength++;
	}
	for(var key in data) {
		params+=",'"+key+"','"+data[key]+"'";
		dataLength++;
	}
	return requestLength+","+dataLength+params;
}

function sendRequest2(requestLength, dataLength) {
	var a=sendRequest2.arguments;
	request = new Array(requestLength);
	data = new Array(dataLength);
	var j=2;
	for(var i=0; i<requestLength; i++) {
		var key = a[j++];
		var val = a[j++];
		request[key] = val;
	}
	for(var i=0; i<dataLength; i++) {
		var key = a[j++];
		var val = a[j++];
		data[key] = val;
	}
	sendRequest(request, data);
}
var debugWind='';
var phpinfoWin=logWin='';
function handleServerResponse(xmlHttp,request) {
	var responseXML,xmlDocumentElement,containers,i,div,htmlCode;
	try {
		var responseText=xmlHttp.responseText;
		responseText=responseText.replace(/></g,'>##!!##<');
		responseText=responseText.replace(/</g,'&lt;');
		responseText=responseText.replace(/>/g,'&gt;');
		responseText=responseText.replace(/##!!##/g,'<br>');
 		outputDump('Ajax response',responseText,false);
		responseXML=xmlHttp.responseXML;
		if(responseXML) {
			xmlDocumentElement=responseXML.documentElement;
			if(xmlDocumentElement)
				containers=xmlDocumentElement;
				if(containers && containers.tagName=="containers") {
					if(containers.childNodes) {
						for(i=0 ; i<containers.childNodes.length ; i++) {
							div=containers.childNodes[i];
							switch(div.tagName) {
								case 'body':
									var theChildNodes=null;
									try {
										theChildNodes=div.childNodes;
									}
									catch(e) {
										theChildNodes=null;
									}
									if(theChildNodes)
										for(j=0 ; j<theChildNodes.length ; j++) {
											node=theChildNodes[j];
											if(node) {
												text=node.firstChild;
												if(text) {
	//												alert(node.tagName+' '+text.nodeValue);
													document.body.setAttribute(node.tagName,text.nodeValue);
													if(node.tagName=='class')
														document.body.setAttribute("className",text.nodeValue);
												}
											}
										}
									break;
								case 'div':
								case 'span':
									divName=myGetAttribute(div,"id");
									var theChildNodes=null;
									try {
										theChildNodes=div.childNodes;
									}
									catch(e) {
										theChildNodes=null;
									}
									if(theChildNodes) {
										htmlCode='';
										var images=Array();
										for(j=0 ; j<theChildNodes.length ; j++) {
											node=theChildNodes[j];
											switch(node.tagName) {
												case "html":
													text=node.firstChild;
													if(divName && text && text.nodeType==4) { // Node.CDATA_SECTION_NODE
														htmlCode=text.nodeValue;
													}
													break;
												case "images":
													if(node.childNodes) {
														var l=0;
														for(k=0 ; k<node.childNodes.length ; k++) {
															image=node.childNodes[k];
															if(image.tagName=="img") {
																img=new Image();
																img.src=myGetAttribute(image,"src");
																images[l++]=img;
															}
														}
													}
													break;
												default:
													text=node.firstChild;
													break;
	/*
												case "indicator":
													if(node.firstChild && node.firstChild.nodeValue) {
														indicator=node.firstChild.nodeValue;
													}
													break;
	*/
											}
										}
										if(divName)
											SetContainer(divName,htmlCode,images,request);
									}
									break;
								case 'cmd':
									var id=myGetAttribute(div,"id");
									var cmd=myGetAttribute(div,"cmd");
									var html=div.firstChild;
									if(html) {
										var htmlCode=html.nodeValue;
										var div0=myGetElementById(id);
										if(div0)
											switch(cmd) {
												case 'replace':
													div0.innerHTML=htmlCode;
													break;
												case 'append':
													div0.innerHTML+=htmlCode;
													break;
											}
									}
									break;
							
								case 'custom':
							//	var javascript=myGetAttribute(div,"javascript");
									var xml=div.firstChild;
									if(xml) {
										var xmlCode=xml.nodeValue;
										alert(xml);
									}
									var xml=div.lastChild;
									if(xml) {
										var xmlCode=xml.nodeValue;
										alert(xml);
									}
									break;
								case 'javascript':
									text=div.firstChild;
									if(text && text.nodeValue)
										eval(text.nodeValue);
									break;
								case 'phpinfo':
									text=div.firstChild;
									if(text && text.nodeValue) {
										if(phpinfoWin)
											phpinfoWin.close();
										phpinfoWin=window.open("","phpinfo","menubar=yes,location=no,resizable=yes,scrollbars=yes,status=yes");
										phpinfoWin.document.write(text.nodeValue);
									}
									break;
								case 'log':
									text=div.firstChild;
									if(text && text.nodeValue) {
										if(logWin)
											logWin.close();
										logWin=window.open("","log","menubar=yes,location=no,resizable=yes,scrollbars=yes,status=yes");
										logWin.document.write(text.nodeValue);
									}
									break;
								case 'messageLog':
								case 'warningLog':
								case 'errorLog':
									text=div.firstChild;
									if(text && text.nodeValue)
										SetContainer(div.tagName,text.nodeValue,'',request);
									break;
							}
						}
				}
			}
			if(request['grndDiv'] && request['grndImg'])
				if(elem=myGetElementById(request['grndDiv']))
					with(elem)
						style.backgroundImage=style.backgroundRepeat=style.backgroundPosition='';
		//	for(i=0 ; request['grndDiv'+i] && request['grndImg'+i] ; i++)
		//		if(elem=myGetElementById(request['grndDiv'+i]))
		//			with(elem)
		//				style.backgroundImage=style.backgroundRepeat=style.backgroundPosition='';
			if(request["indicator"])
				HideDiv(request["indicator"]);
			for(i=0 ; request['indicator'+i] ; i++)
				ShowDiv(request['indicator'+i]);
			if(request["javascript"]) {
			//	alert('javascript2');
				eval(request["javascript"]);
			}
		}
/*		
		else
			alert('Ajax error: no XML content returned');
*/
	}
	catch(e) {
//		alert("Error reading the response: "+e.toString()+" "+e.message);
	}
}
var javascript_datas=new Array(0);
function SetContainer(divName,htmlCode,images,request) {
//	var div=document.getElementById(divName);
	if(divName.length>11 && divName.substr(0,11)=='javascript_') {
//		alert(divName);
		javascript_datas[divName]=htmlCode;
//		alert(javascript_datas[divName]);
		return;
	}
	var concat=false;
	if(divName[0]=='+') {
		divName=divName.substr(1);
		concat=true;
	}
	var div=myGetElementById(divName);
//	if(document.location.search.search(/ajaxdebug/)>0) {
//		alert('SetContainer: divName='+divName+' div='+div);
//	}
	if(div) {
	/*
		if(images && images.length)
			for(i=0 ; i<images.length ; i++)
				if(images[i].complete==false) {
					div.myImages=images;
					div.myRequest=request;
					div.myHtml=htmlCode;
					setTimeout("UpdateContainer('"+divName+"')",200);
					return;
				}
	*/
		div.myImages=div.myHtml=div.myRequest=null;
		if(htmlCode=='') {
			if(request['hideEmpty'])
				HideDiv(divName);
		}
		else
			ShowDiv(divName);
		if(concat)
			div.innerHTML+=htmlCode;
		else
			div.innerHTML=htmlCode;
	}
}

function UpdateContainer(divName) {
//	var div=document.getElementById(divName);
	var concat=false;
	if(divName[0]=='+') {
		divName=divName.substr(1);
		concat=true;
	}
	var div=myGetElementById(divName);
//				alert('update '+div.myHtml);
//	alert('SetContainer: divName='+divName+' div='+div);
	if(div) {
		var images=div.myImages;
		if(images && images.length)
			for(i=0 ; i<images.length ; i++)
				if(images[i].complete==false) {
					setTimeout("UpdateContainer('"+divName+"')",200);
					return;
				}
		var htmlCode=div.myHtml;
		var request=div.myRequest;
		div.myImages=div.myHtml=div.myRequest=null;
		if(htmlCode=='') {
			if(request['hideEmpty'])
				HideDiv(divName);
		}
		else
			ShowDiv(divName);
		if(concat)
			div.innerHTML=div.innerHTML+htmlCode;
		else
			div.innerHTML=htmlCode;
	}
}

function cancelRequest(id) {
	var xmlHttp=requestStack[id];
	if(xmlHttp) {
		if(xmlHttp.readyState!=4) {
			xmlHttp.abort();
			alert('Connection timeout in ajax request. Please reload the page.');
		}
	}
}

function outputDump(title,dump,request) {
	try {
		var html=$('#dumpAjax').html();
		var date=new Date();
		var h=date.getHours();
		var m=date.getMinutes();
		var s=date.getSeconds();
		if(h<10)
			h='0'+h;
		if(m<10)
			m='0'+m;
		if(s<10)
			s='0'+s;
		if(request)
			html+=h+'h'+m+':'+s+' '+title+' '+dump+'<br>';
		else {
			id=h+'_'+m+'_'+s;
			html+=h+'h'+m+':'+s+' <a href="#" onclick="javascript:$(\'.dumpDataBlocks\').slideUp(\'fast\');if($(\'#dumpDataBlock_'+id+'\').is(\':hidden\'))$(\'#dumpDataBlock_'+id+'\').slideDown(\'slow\');return false;">'+title+'</a> <div id="dumpDataBlock_'+id+'" class="dumpDataBlocks">'+dump+'</div><br>';
			html+='<SCRIPT type="text/javascript" language="JavaScript">'+"\n";
			html+='<!--'+"\n";
			html+="$(\'#dumpDataBlock_'+id+'\').hide();";
			html+='//-->'+"\n";
			html+='</SCRIPT>'+"\n";
		}
		$('#dumpAjax').html(html);
	}
	catch(e) {
	}
}

function outputDebug(title,debug) {
	if(debugWind && debugWind.document) {
		var d=new Date();
		var html;
		
		html='<font size="-1">';
		html+='&#149; <a href="javascript:ToggleDisplay(\'dump'+d.getTime()+'\');"> '+title+'</a><br>';
		html+='<div id="dump'+d.getTime()+'" style="display:none;left:10px;border:1px solid #aaaaaa;padding:3px;margin-left:8px;">';
		html+=debug;
		html+='</div>';
		html+='</font>';

		if(debugWind.document.body)
			debugWind.document.body.innerHTML+=html;
	}
}