﻿//*************************************************************
//* Copyright © 2009 Theuns van Rensburg (theuns@globebeat.com)
//* Ajax stack
//* Date: 2009-09-07 17:34:21 +0200 
//*************************************************************
var IE								= (navigator.userAgent.indexOf('MSIE')>0);
var	Debug							= false;
var AjaxRequestInProgress			= false;
var AjaxControlProgram				= new Array();

var AjaxRequestMethod	 			= new Array();
var AjaxRequestProgram				= new Array();
var AjaxRequestUrl					= new Array();
var AjaxRequestType					= new Array();
var AjaxRequestCallback 			= new Array();
var AjaxRequestCanvasId				= new Array();
var AjaxRequestWaitAnimation		= new Array();
var AjaxRequestSynchronous			= new Array();
var AjaxRequestFireAndForget		= new Array();
var AjaxRequestIgnoreError			= new Array();

var AjaxMethod 						= "POST"; 	// POST,GET
var AjaxProgram						= ""; 		// Example: ISQ0000.php
var AjaxUrl							= ""; 		// user=xxxxx&name=yyyyy&surname=zzzzz
var AjaxType						= "N"; 		// N=New A=Append 
var AjaxCallback 					= ""; 		// function to receive xmlDoc
var AjaxCanvasId					= ""; 		// for innerHTML
var AjaxWaitAnimation				= false; 	// Show spinning wheel or not 
var AjaxSynchronous					= false;	// Wait for response or not
var AjaxFireAndForget				= false;	// No statechanged checking
var AjaxIgnoreError					= false;	// No popup in case of error
var AjaxRequest						= null;

window.onerror=function(msg,url,linenumber)
	{
	if(Cookie.get("globebeatlogon")=="USR1"||window.location.hostname=="localhost"||Cookie.get("globebeatlogon")=="USR2"||Cookie.get("globebeatlogon")=="USR8")
		{
		alert("Mail:theuns@globebeat.com\nTheuns wil weet van hierdie fout:\nError message: "+msg+"\nURL: "+url+"\nLine Number: "+linenumber);
		}
	window.location=window.location;
	return true;
	}

function ajaxRequest()
{
// Defaults
this.method 		= "POST",
this.program 		= "",
this.url			= "",
this.type			= "N",
this.callback		= "",
this.canvasid		= "",
this.waitanimation	= false,
this.synchronous	= false,
this.fireandforget	= false,
this.ignoreerror	= false,
this.execute 		= function()
	{
	if(this.waitanimation)
		{
		var wait= new globebeatWait();
		wait.Id=this.canvasid+'waiting';
		wait.attachToId=this.canvasid;
		wait.execute();
		}
	AjaxRequestMethod.push(this.method);
	AjaxRequestProgram.push(this.program);
	top.AjaxControlProgram.push(this.program);
	AjaxRequestUrl.push(this.url);
	AjaxRequestType.push(this.type);
	AjaxRequestCallback.push(this.callback);
	AjaxRequestCanvasId.push(this.canvasid);
	AjaxRequestWaitAnimation.push(this.waitanimation);
	AjaxRequestSynchronous.push(this.synchronous);
	AjaxRequestFireAndForget.push(this.fireandforget);
	AjaxRequestIgnoreError.push(this.ignoreerror);
	};
}
function getHTTPObject() 
{
return window.ActiveXObject ? new ActiveXObject("Microsoft.XMLHTTP") : new XMLHttpRequest();
}

function ajaxRealRequest() 
{
if(top.AjaxRequestInProgress||AjaxRequestMethod.length==0) // ||top.AjaxControlProgram[0]!=AjaxRequestProgram[0]) //Not my turn
	{
	return;
	}
top.AjaxRequestInProgress		= true;
AjaxMethod 						= AjaxRequestMethod.shift();
AjaxProgram						= AjaxRequestProgram.shift();
var Dummy						= top.AjaxControlProgram.shift();
AjaxUrl							= AjaxRequestUrl.shift();
AjaxType						= AjaxRequestType.shift();
AjaxCallback 					= AjaxRequestCallback.shift();
AjaxCanvasId					= AjaxRequestCanvasId.shift();
AjaxWaitAnimation				= AjaxRequestWaitAnimation.shift();
// AjaxSynchronous					= AjaxRequestSynchronous.shift();
AjaxSynchronous					= false;
AjaxFireAndForget				= AjaxRequestFireAndForget.shift();
AjaxIgnoreError					= AjaxRequestIgnoreError.shift();
if(AjaxCallback)
	{
	var cb=true;
	}
else{
	var cb=false;
	}

if(top.Debug) 
	{
	var d= new Date();
	debug('\nRequest='+AjaxProgram+'?'+AjaxUrl+"&dummydate="+d.getTime()+
	'\nMethod='+AjaxMethod+
	'\nCallback='+cb+
	'\nCanvasid='+AjaxCanvasId+
	'\nWait animation='+AjaxWaitAnimation+
	'\nSynchronous='+AjaxSynchronous+
	'\nFire and forget='+AjaxFireAndForget+
	'\nIgnore error='+AjaxIgnoreError+
	'\nCurrent buffer length='+AjaxRequestMethod.length+
	'\n=================================================================================================================');
	}
initiateAjaxRequest();
}

function initiateAjaxRequest()
{
// add dummy date to make url unique - IE sometimes uses cache - this will force a server lookup
var d= new Date();
AjaxUrl=AjaxUrl+"&dummydate="+d.getTime();
AjaxRequest= new getHTTPObject();
if(AjaxSynchronous)
	{
	if(AjaxMethod=="POST")
		{
		AjaxRequest.open("POST",AjaxProgram, false);
		AjaxRequest.setRequestHeader("Content-Type","application/x-www-form-urlencoded; charset=UTF-8");
		AjaxRequest.setRequestHeader("Content-length", AjaxUrl.length);
//		AjaxRequest.setRequestHeader("X-Requested-With", "XMLHttpRequest");
		AjaxRequest.setRequestHeader("From", "AJAX");
		AjaxRequest.send(AjaxUrl);
		}
	else
		{
		geturl=AjaxProgram+'?'+AjaxUrl;
		AjaxRequest.open("GET", geturl, false);
		AjaxRequest.setRequestHeader("From", "AJAX");
		AjaxRequest.send(null);
		if(top.Debug)
			{
			debug('Size='+AjaxRequest.responseText.length+'\nSynchronous reply='+decodeURIComponent(AjaxRequest.responseText)+
			'\n=================================================================================================================');
			}
		}
	var xmlDoc=AjaxRequest.responseXML;
	AjaxRequest= null;
	abortAjax();
	if(top.Debug) 
		{
		debug('')
		}

	if(AjaxWaitAnimation==true)
		{
		var wait= new globebeatWait();
		wait.Id=AjaxCanvasId+'waiting';
		wait.waitAction="done";
		wait.execute();
		}
//	if (navigator.appName!="Microsoft Internet Explorer")
	if (!IE)
		{
		xmlDoc.normalize();
		}
	if(AjaxCallback)
		{
		AjaxCallback(xmlDoc);
		}
	else
		{
	 	if (xmlDoc.getElementsByTagName("innerHTML")[0].hasChildNodes()) 
			{
			if(AjaxType=="A")
				{
				document.getElementById(AjaxCanvasId).innerHTML+=decodeURIComponent(xmlDoc.getElementsByTagName("innerHTML")[0].childNodes[0].nodeValue);
				}
			else
				{
				document.getElementById(AjaxCanvasId).innerHTML=decodeURIComponent(xmlDoc.getElementsByTagName("innerHTML")[0].childNodes[0].nodeValue);
				document.getElementById(AjaxCanvasId).scrollTop=0;
				}
			
			}
		if (xmlDoc.getElementsByTagName("innerSCRIPT")[0].hasChildNodes()) 
			{
			var InlineScript=decodeURIComponent(xmlDoc.getElementsByTagName("innerSCRIPT")[0].childNodes[0].nodeValue)+";setWidth();";
			}
		else
			{
			var InlineScript="setWidth();";
			}
		setTimeout(InlineScript,0);
		}
	}
else // Asynchronous
	{
	if(AjaxFireAndForget)
		{
		AjaxRequest.onreadystatechange=abortAjax;
		if(AjaxWaitAnimation==true)
			{
			var wait= new globebeatWait();
			wait.Id=AjaxCanvasId+'waiting';
			wait.waitAction="done";
			wait.execute();
			}
		}
	else
		{
		AjaxRequest.onreadystatechange=receiveXML;
		}
	if(AjaxMethod=="POST")
		{
		AjaxRequest.open("POST",AjaxProgram, true);
		AjaxRequest.setRequestHeader("Content-Type","application/x-www-form-urlencoded; charset=UTF-8");
		AjaxRequest.setRequestHeader("Content-length", AjaxUrl.length);
		//AjaxRequest.setRequestHeader("X-Requested-With", "XMLHttpRequest");
		AjaxRequest.setRequestHeader("From", "AJAX");
		AjaxRequest.send(AjaxUrl);
		}
	else // GET
		{
		geturl=AjaxProgram+'?'+AjaxUrl;
		geturl=AjaxProgram+'?'+AjaxUrl;
		AjaxRequest.open("GET", geturl, true);
		AjaxRequest.send(null);
		}
	}
}
function receiveXML ()
{
try{
// 0: request not initialized 
// 1: server connection established
// 2: request received 
// 3: processing request 
// 4: request finished and response is ready
if (AjaxRequest.readyState==4)
	{
	// IE error sometimes returns 1223 when it should be 204 so treat it as success.
	if ((AjaxRequest.status >= 200 && AjaxRequest.status < 300 ) || AjaxRequest.status == 304 || AjaxRequest.status == 1223)
		{
		if(top.Debug)
			{
			try {			
				debug('Size='+AjaxRequest.responseText.length+'\nASynchronous reply=\n'+decodeURIComponent(AjaxRequest.responseText)+
				'\n=================================================================================================================');
				}
			catch(e)
				{
				debug('Size='+AjaxRequest.responseText.length+'\nASynchronous raw reply=\n'+AjaxRequest.responseText+
				'\n=================================================================================================================');
				}
			}

		try{ xmlDoc=AjaxRequest.responseXML;}
		catch(e){Badresponse('Bad','Invalid XML');return;};
		
		
		//if (navigator.appName!="Microsoft Internet Explorer")
		
		if (!IE)
			{
			try{xmlDoc.normalize();}
			catch(e){Badresponse('Bad','XML normalise error.');return};
			}
		//document.location.hash='#'+d.getTime();
		if(AjaxCallback)
			{
			AjaxCallback(xmlDoc);
			if(AjaxWaitAnimation==true)
				{
				var wait= new globebeatWait();
				wait.Id=AjaxCanvasId+'waiting';
				wait.waitAction="done";
				wait.execute();
				}
			setTimeout('abortAjax();if(top.Debug){debug("")}',500);
			}
		else
			{
		 	if (xmlDoc.getElementsByTagName("innerHTML")[0].hasChildNodes()) 
				{
				if(AjaxWaitAnimation==true)
					{
					fader= new globebeatFader();
					fader.attachToId=AjaxCanvasId;
					if(AjaxType=="A")
						{
						fader.cmd='document.getElementById(AjaxCanvasId).innerHTML+=decodeURIComponent(xmlDoc.getElementsByTagName("innerHTML")[0].childNodes[0].nodeValue);abortAjax();if(top.Debug){debug("")};fadeinnewhtml();';
						}
					else
						{
						fader.cmd='document.getElementById(AjaxCanvasId).innerHTML=decodeURIComponent(xmlDoc.getElementsByTagName("innerHTML")[0].childNodes[0].nodeValue);abortAjax();if(top.Debug){debug("")};document.getElementById(AjaxCanvasId).scrollTop=0;fadeinnewhtml();';
						}
					fader.wilt();
					}
				else
					{
					if(AjaxType=="A")
						{
						document.getElementById(AjaxCanvasId).innerHTML+=decodeURIComponent(xmlDoc.getElementsByTagName("innerHTML")[0].childNodes[0].nodeValue);
						}
					else
						{
						document.getElementById(AjaxCanvasId).innerHTML=decodeURIComponent(xmlDoc.getElementsByTagName("innerHTML")[0].childNodes[0].nodeValue);
						document.getElementById(AjaxCanvasId).scrollTop=0;
						}
					if (xmlDoc.getElementsByTagName("innerSCRIPT")[0].hasChildNodes()) 
						{
						var InlineScript=decodeURIComponent(xmlDoc.getElementsByTagName("innerSCRIPT")[0].childNodes[0].nodeValue)+";setWidth();";
						}
					else
						{
						var InlineScript="setWidth()";
						}
					setTimeout(InlineScript,100);
					abortAjax();
					if(top.Debug) 
						{
						debug('')
						}
					}
				}
			}
		}
	else
		{
		if(AjaxIgnoreError)
			{
			if(top.Debug)
				{
				debug('Giving up:'+AjaxProgram+
				'\n=================================================================================================================');
				}
			if(AjaxWaitAnimation==true)
				{
				var wait= new globebeatWait();
				wait.Id=AjaxCanvasId+'waiting';
				wait.waitAction="done";
				wait.execute();
				}
			abortAjax();
			}
		else
			{
			Badresponse('Bad');
			return;
			}
		}
	}
}
catch(e){};
}
function fadeinnewhtml()
{
if(AjaxWaitAnimation==true)
	{
	var wait= new globebeatWait();
	wait.Id=AjaxCanvasId+'waiting';
	wait.waitAction="done";
	wait.execute();
	}
if (xmlDoc.getElementsByTagName("innerSCRIPT")[0].hasChildNodes()) 
	{
	var InlineScript=decodeURIComponent(xmlDoc.getElementsByTagName("innerSCRIPT")[0].childNodes[0].nodeValue)+";setWidth();fader.flourish();";
	}
else
	{
	var InlineScript="setWidth();fader.flourish();";
	}
setTimeout(InlineScript,100);
}
function Badresponse(b,rsn)
{
if(AjaxWaitAnimation==true)
	{
	var wait= new globebeatWait();
	wait.Id=AjaxCanvasId+'waiting';
	wait.waitAction="done";
	wait.execute();
	}
if(rsn)
	{
	resp=rsn;
	}
else
	{
	if(b=="No")
		{
		var resp="No reply from server in 10 seconds.<br/>Check your internet connection.";
		}
	else
		{
		var resp=AjaxRequest.status;
		}
	}
var content=encodeURIComponent('<div style="width:100%;height:100%"><table ><tr><td class="Friendhead">'+b+' response from server:</td></tr>'
+'<tr><td class="smalltext">Response:'+resp+'</td></tr>'
+'<tr><td><a href=\"mailto:webmaster@globebeat.com?subject=Bad%20response%20from%20server.&body=Program:'+AjaxProgram+'%20Status: '+resp+' \">'+
'Click here to notify the webmaster of this error.</a></td></tr>'
+'</table>'
+'<div style="position:absolute;bottom:10px;right:10px"><input type="button" class="widebutton" onclick="initiateAjaxRequest();popupwindow(\'destroy\')" value="Retry" />'+
'&nbsp;<input type="button" class="widebutton" onclick="abortAjax();popupwindow(\'destroy\')" value="Close" /></div></div>');
w=350;
h=180;
a="create";
popupwindow(a,w,h,content);
};
function debug(v)
{
if(Cookie.get('globebeatlogon')=='USR1'||Cookie.get('globebeatlogon')=='USR13'||Cookie.get('globebeatlogon')=='USR2'||Cookie.get('globebeatlogon')=='USR8'||window.location.hostname=="localhost")
	{
	top.document.getElementById('ajaxstack').value="";
	for(var i =0;i<top.AjaxControlProgram.length;i++)
		{
		top.document.getElementById('ajaxstack').value+=top.AjaxControlProgram[i]+'\n';
		}
	if(AjaxProgram!='ISQ0004D2.php')
		{
		top.document.getElementById('debugtext').value+=v+'\n';
		
		top.document.getElementById('debugtext').scrollTop=99999999;
		}
	top.document.getElementById('queuelength').innerHTML=top.AjaxControlProgram.length;
	if(top.AjaxRequestInProgress)
		{
		top.document.getElementById('requestinprogress').innerHTML="true";
		}
	else
		{
		top.document.getElementById('requestinprogress').innerHTML="false";
		}
	}
else
	{
	document.getElementById('debugtext').style.display='none';
	}
}
function abortAjax()
{
try
	{
	// Clean up so IE doesn't leak memory
	delete AjaxRequest['onreadystatechange'];
	AjaxRequest= null;	
	}
catch(e){};

top.AjaxRequestInProgress=false;
}
window.onunload=abortAjax;
setInterval(function (){ajaxRealRequest();},13);
