﻿// ====================================================================================================
//
//          Page: AJAX BASE FUNCTIONS
//        Author: Michael Marzilli   ( http://www.linkedin.com/in/michaelmarzilli )
//       Created: Aug 11, 2011
//
//	Minify with: http://sundgaard.dk/javascript-minify.aspx
//
// VERS 1.0.000 : Aug 11, 2011 : Original File Created, split off from JSLibrary.js.
//			1.0.001 : Oct 24, 2011 : WEB CHAT:
//															 Added a Notify icon to tell the user when a new chat line has come in.
//															 Programmer can specify his own notify object (using "UseCustomNotify")
//															 or use the default object.
//
// ====================================================================================================


function AJAX()
{
	// PUBLIC PROPERTIES (SETTINGS)
	var strID            = '';
	var intAJAXpoll      = 0;
	var intAJAXrecord    = 10000000000;
	var strFileTarget    = 'AJAX_Process.aspx';
	var strGetFunction   = '';
	var params           = '';
	var soundEmbed       = null; 

	// INTERNAL VARIABLES
	var sendReq          = getXmlHttpRequestObject();
	var receiveReq       = getXmlHttpRequestObject();
	var intDivHeight     = 0;
	var strDivContainer  = '';
	var strDivTarget     = '';
	var strDivTempTarget = '';
	var strWaitObject    = '';
	var strWaitDiv       = '';
	var strNotifyObject  = '';
	var strNotifyDiv     = '';
	var mTimer           = 0;
	var blnScrolling     = false;
	var blnPlayBeepSound = false;
	var blnBeepOverride  = false;
	var blnBeep          = 0;

	// FUNCTION MAPPING
	this.SetID                = SetID;
	this.SetAJAXpoll          = SetAJAXpoll;
	this.SetAJAXgetFunction   = SetAJAXgetFunction;
	this.SetAJAXtarget        = SetAJAXtarget;
	this.SetAJAXscrolling     = SetAJAXscrolling;
	this.SetAJAXwaitObject    = SetAJAXwaitObject;
	this.SetAJAXnotifyObject  = SetAJAXnotifyObject;
	this.SetAJAXWaitVisible   = SetAJAXWaitVisible;
	this.SetAJAXbeepPlay      = SetAJAXbeepPlay;
	this.SetAJAXbeep          = SetAJAXbeep;
	this.SetAJAXbeepOverride  = SetAJAXbeepOverride;
	this.SetTargetDiv         = SetTargetDiv;
	this.SetTargetTempDiv     = SetTargetTempDiv;
	this.SetAJAXNotifyHidden  = SetAJAXNotifyHidden;
	this.SetAJAXNotifyVisible = SetAJAXNotifyVisible;

	this.AJAXstart       = AJAXstart;
	this.ClearDiv        = ClearDiv;
	this.ScrollDiv       = ScrollDiv;
	this.GetRecordCount  = GetRecordCount;
	this.GetDiv          = GetDiv;
	this.GetTempDiv      = GetTempDiv;
	this.GetDivInnerHTML = GetDivInnerHTML;
	this.SetDivInnerHTML = SetDivInnerHTML;
	this.ClearParams     = ClearParams;
	this.AddParam        = AddParam;
	this.ResetDiv        = ResetDiv;
	this.GetAJAX         = GetAJAX;
	this.HandleGetAJAX   = HandleGetAJAX;
	this.SendAJAXtext    = SendAJAXtext;
	this.HandleSendAJAX  = HandleSendAJAX;


	// SET UP FUNCTIONS -------------------------------------------------------
	// ------------------------------------------------------------------------
	function getXmlHttpRequestObject()
	{
		if (window.XMLHttpRequest)
		{
			return new XMLHttpRequest();
		} else if (window.ActiveXObject) {
			return new ActiveXObject("Microsoft.XMLHTTP");
		} else {
			var objStatus = getObjectElementByID('', 'web_chat_status');
			if (objStatus != null)
				objStatus.innerHTML = '<font color="red">Offline</font>';
		}
	}
	function SetID(strTarget)
	{
		strID = strTarget;
	}
	function SetAJAXpoll(intPoll)
	{
		intAJAXpoll = intPoll * 1000;
	}
	function SetAJAXtarget(strTarget)
	{
		strFileTarget = strTarget;
	}
	function SetAJAXgetFunction(strTarget)
	{
		strGetFunction = strTarget;
	}
	function SetTargetDiv(strContainer, strTarget)
	{
		if (strContainer != '')
			strDivContainer = strContainer;
		if (strTarget    != '')
			strDivTarget    = strTarget;
		intDivHeight      = GetDiv().clientHeight - 10;
	}
	function SetTargetTempDiv(strTarget)
	{
		if (strTarget != '' && strDivTempTarget == '')
		{
			strDivTempTarget = strTarget;
			GetTempDiv().style.display    = 'none';
			GetTempDiv().style.visibility = 'hidden';
		}
	}
	function SetAJAXwaitObject(strContainer, strTarget)
	{
		if (strContainer != '' && strWaitDiv == '')
			strWaitDiv      = strContainer;
		if (strTarget    != '' && strWaitObject == '')
			strWaitObject   = strTarget;
	}
	function SetAJAXnotifyObject(strContainer, strTarget)
	{
		if (strContainer != '' && strNotifyDiv == '')
			strNotifyDiv    = strContainer;
		if (strTarget    != '' && strNotifyObject == '')
			strNotifyObject = strTarget;
	}
	function SetAJAXscrolling(blnTarget)
	{
		blnScrolling = blnTarget;
	}
	function SetAJAXbeepPlay(blnTarget)
	{
		blnPlayBeepSound = blnTarget;
	}
	function SetAJAXbeep(blnTarget)
	{
		blnBeep = blnTarget;
	}
	function SetAJAXbeepOverride(blnTarget)
	{
		blnBeepOverride = blnTarget;
	}


	function AJAXstart()
	{
		if (strGetFunction != '')
			setTimeout(strGetFunction + '();', 300);
		else
			SetWaitVis(false);
	}


	// PARAMETER FUNCTIONS ----------------------------------------------------
	// ------------------------------------------------------------------------
	function ClearParams()
	{
		this.params = '';
		this.AddParam('XID', 0);
	}
	function AddParam(strKey, strValue)
	{
		strKey = strKey.toUpperCase();
		if (this.params == '')
		{
			this.params = strKey + '=' + strValue;
		} else {
			this.params += '&' + strKey + '=' + strValue;
		}
	}
	function GetDiv()
	{
		var objReturn = getObjectElementByID(strDivContainer, strDivTarget);
		if (objReturn == null)
			objReturn   = document.getElementById(strDivTarget);
		return objReturn;
	}
	function GetTempDiv()
	{
		var objReturn = getObjectElementByID(strDivContainer, strDivTempTarget);
		if (objReturn == null)
			objReturn   = document.getElementById(strDivTempTarget);
		return objReturn;
	}
	function ClearDiv()
	{
		GetDiv().innerHTML     = '';
		GetTempDiv().innerHTML = '';
		GetDiv().scrollTop     = 0;
	}
	function ResetDiv()
	{
		ClearDiv();
		eval(strGetFunction + '();');
	}
	function ScrollDiv()
	{
		if (!blnScrolling)
			return;

		var obj = GetDiv();
		if (obj != null)
		{
			try { obj.style.height = intDivHeight + 'px'; } catch (err) { }
			var i = obj.scrollHeight;
			if (GetTempDiv() != null)
				i = GetTempDiv().scrollHeight;
		}
		setTimeout(strID + '.GetDiv().scrollTop = ' + i + ' + 5000000;', 10);
	}
	function GetDivInnerHTML()
	{
		var str = '';
		var obj = GetDiv();
		if (obj != null)
			str = obj.innerHTML;
		return str;
	}
	function SetDivInnerHTML(str)
	{
		var obj = GetDiv();
		if (obj != null)
			obj.innerHTML = str;
	}
	function GetRecordCount()
	{
		var n = 0;
		var obj = document.getElementById('hidWebChatRecordCount');
		if (obj != null)
			n = Number(obj.value);
		return n;
	}
	function SetRecordCount(n)
	{
		var obj = document.getElementById('hidWebChatRecordCount');
		if (obj != null)
			obj.value = n;
		else
			obj.value = '0';
	}
	function SetWaitVis(bln)
	{
		if (strWaitObject == '')
			return;

		var obj = getObjectElementByID(strWaitDiv, strWaitObject);
		if (obj == null)
			getObjectElementByID('', strWaitObject);

		if (obj != null)
		{
			if (bln)
				obj.style.visibility = 'visible';
			else
				obj.style.visibility = 'hidden';
		}
	}
	function SetAJAXWaitVisible()
	{
		SetWaitVis(true);
	}
	function SetNotifyVis(bln)
	{
		if (strNotifyObject == '')
			return;

		var obj = getObjectElementByID(strNotifyDiv, strNotifyObject);
		if (obj == null)
			getObjectElementByID('', strNotifyObject);

		if (obj != null)
		{
			if (bln)
				obj.style.visibility = 'visible';
			else
				obj.style.visibility = 'hidden';
		}
	}
	function SetAJAXNotifyVisible()
	{
		SetNotifyVis(true);
	}
	function SetAJAXNotifyHidden()
	{
		SetNotifyVis(false);
	}


	// AJAX GET FUNCTIONS -----------------------------------------------------
	// ------------------------------------------------------------------------
	function GetAJAX()
	{
		if (receiveReq.readyState == 4 || receiveReq.readyState == 0)
		{
			SetWaitVis(true);
			var strPost = strFileTarget + '?' + this.params;
			receiveReq.open("GET", strPost, true);
			receiveReq.onreadystatechange = HandleGetAJAX;
			receiveReq.send(this.params);
		}
	}
	function HandleGetAJAX()
	{
		if (receiveReq.readyState == 4)
		{
			var strInput = receiveReq.responseText;

			// STRIP RECORD COUNT (IF APPLICABLE)
			var a1 = strInput.indexOf('[[[');
			var a2 = strInput.indexOf(']]]');
			if (a1 > -1 && a2 > a1)
			{
				intAJAXrecord = Number(strInput.substr(a1 + 3, (a2 - a1) - 3));
				SetRecordCount(intAJAXrecord);
				if (a1 == 0)
					strInput = strInput.substr(a2 + 3);
			}

//			SetAJAXNotifyHidden();
			if (strInput != '')
			{
				var obj = GetTempDiv();
				if (obj != null)
				{
					obj.innerHTML = strInput;
					if (obj.innerHTML != GetDiv().innerHTML ||
							 (obj.innerHTML == '' && GetDiv().innerHTML == ''))
					{
						if (obj.innerHTML != '')
						{
//							SetAJAXNotifyVisible();
							if (blnBeepOverride)
								blnBeepOverride = false;
							else if (blnBeep == 1)
							{
								if (blnPlayBeepSound)
								{
									var blnPlaySuccessful = true;
									var sobj;

									// ATTEMPT TO PLAY VIA <AUDIO> OBJECT
									try
									{
										blnPlaySuccessful = true;
										sobj = document.getElementById('chatBeepSound1');
										sobj.play();
									} catch (Err) {
										blnPlaySuccessful = false;
									}

									// ATTEMPT TO PLAY VIA <EMBED> OBJECT
									if (!blnPlaySuccessful)
									{
										try
										{
											blnPlaySuccessful = true;
											sobj = document.getElementById('chatBeepSound2');
											PlaySound('chatBeepSound2');
										} catch (Err) {
											blnPlaySuccessful = false;
										}
									}

									// ATTEMPT TO PLAY VIA INSERT <EMBED> OBJECT INTO SPAN
									if (!blnPlaySuccessful)
									{
										try
										{
											blnPlaySuccessful = true;
											sobj = document.getElementById('chatBeepSound3');
											sobj.innerHTML = '<embed src="Scripts/notify.wav" hidden="true" autostart="true" loop="false" />';
										} catch (Err) {
											blnPlaySuccessful = false;
										}
									}

									// ATTEMPT TO PLAY VIA INSERT <EMBED> OBJECT INTO DOCUMENT
									if (!blnPlaySuccessful)
									{
										try
										{
											blnPlaySuccessful = true;
											if (!soundEmbed)
											{
												soundEmbed = document.createElement(strID + "embed");
												soundEmbed.setAttribute("src", "Scripts/notify.wav");
												soundEmbed.setAttribute("hidden", true);
												soundEmbed.setAttribute("autostart", true);
											} else {
												document.body.removeChild(soundEmbed);
												soundEmbed.removed = true;
												soundEmbed = null;
												soundEmbed = document.createElement(strID + "embed");
												soundEmbed.setAttribute("src", "Scripts/notify.wav");
												soundEmbed.setAttribute("hidden", true);
												soundEmbed.setAttribute("autostart", true);
											}
											soundEmbed.removed = false;
											document.body.appendChild(soundEmbed);
										} catch (Err) {
											blnPlaySuccessful = false;
										}
									}
								}
							} else
								blnBeep = true;
						}
						GetDiv().innerHTML = strInput;
						ScrollDiv();
					}
				}
			}
			SetWaitVis(false);
			if (intAJAXpoll > 0)
				mTimer = setTimeout(strGetFunction + '();', intAJAXpoll);
		}
	}


	// AJAX SEND FUNCTIONS ----------------------------------------------------
	// ------------------------------------------------------------------------
	function SendAJAXtext()
	{
		if (sendReq.readyState == 4 || sendReq.readyState == 0)
		{
			blnBeep = 0;
			blnBeepOverride = true;
			SetWaitVis(true);
			clearInterval(mTimer);
			var strPost = strFileTarget + '?' + this.params;
			sendReq.open("POST", strPost, true);
			sendReq.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
			sendReq.onreadystatechange = HandleSendAJAX;
			sendReq.send(this.params);
		}
	}
	function HandleSendAJAX()
	{
		clearInterval(mTimer);

		if (strGetFunction != '')
		{
			if (intAJAXpoll > 0)
				mTimer = setTimeout(strGetFunction + '()', 500);
			else
				eval(strGetFunction + '()');
		} else
			SetWaitVis(false);
	}
}

