function SmartEncode(value)
{
	var retVal = "";
	try
	{
		retVal = encodeURIComponent(value);
	}
	catch(e)
	{
		retVal = escape(value);
	}
	return retVal;
}

function IsValidObject(value) 
{ 
	var ret = false;
	if("undefined" != typeof(value) && null != value)
		ret = true; 
	return ret; 
} 

// Use if we need to debug the JS
var _debugWindow = null;
function WriteDebugMessage(msg)
{
	if((null == _debugWindow) || (_debugWindow.closed))
	{
		_debugWindow = window.open("", "console", "width=600, height=300, resizable=yes, scrollbars=yes");
		_debugWindow.document.open("text/plain");
	}
	// _debugWindow.focus();
	_debugWindow.document.writeln(msg);
}

var ableToOpen;

function SightMaxMonitor(propertyName)
{
	this.PropertyName			= propertyName;

	this.SiteID					= "13";
	this.QueueID				= "18";
	this.BrowserID				= "7be29710-0c83-44ad-8e4d-5750b959467f";
	this.SessionID				= "11adb797-baae-4f42-a39d-729223e09058";
	this.Path					= "http://worthingtonboosters.com/SightMaxAgentInterface/";
	this.AccountID				= "2";
	
	this.ChatWindowOptions		= "width=490,height=404,resizable=no,scrollbars=no,menubar=no,status=no";
	this.InviteDivTopOffset		= 25;
	this.InviteDivLeftOffset	= 200;
	
	this.InviteLocation         = "<div ID=\"SightMaxChatRequest\" style=\"border-top-style: none; border-right-style: none; border-left-style: none; border-bottom-style: none; position: absolute; z-index:9999; top: 0px; left: 0px; visibility: hidden\"><img src=\""+ this.Path + "Images/acceptInvite.gif\"  onclick=\"SightMaxAccept()\"/><br /><img src=\""+ this.Path + "Images/CancelInvite.gif\" onclick=\"SightMaxCancel()\"/></div>";
	ableToOpen             = "no";
	
	document.writeln("<DIV STYLE=\"position: absolute; top: 0px; left: 0px; visibility: hidden\"><IMG SRC=\"" + this.Path + "Images/Spacer.gif\" ID=CommandImage NAME=CommandImage></DIV>");
	
	// Coords are: L, T, R, B
	document.writeln(this.InviteLocation);
	
	this.PendingImageDownload	= false;
	this.SightMaxCommandImage	= document.CommandImage;
	
	this.CommandTimerID			= null;
	
	this.InviteDiv				= document.getElementById("SightMaxChatRequest");
	
	this.Attempts				= 0;
	this.ImageCheckFrequency	= 1000;
	this.ImageCheckTimeSpan		= 5000;	// 15000
	this.LastHeight				= -1;
	this.UniqueID				= 0;
	this.bConnected				= true;
	
	this.lastTop				= -1;
	this.bTopChanged			= true;
	this.scrollTimeout			= -1;
	this.inviteResponse			= null;
	
	
	var pd				= parent.document;
	
	var screenRes		= "";
	if(IsValidObject(screen) && IsValidObject(screen.width) && IsValidObject(screen.height) && IsValidObject(screen.colorDepth))
		screenRes = "&screenRes=" + SmartEncode(screen.width + 'x' + screen.height + 'x' + screen.colorDepth);
	var currentPage		= "";
	if(IsValidObject(pd.location.protocol) && IsValidObject(pd.location.hostname) && IsValidObject(pd.location.pathname))
		currentPage = "&currentPage=" + SmartEncode(pd.location.protocol + '//' + pd.location.hostname + pd.location.pathname);

	var referrer		= pd.referrer;
	if(!IsValidObject(referrer) || referrer == "")
		referrer = "";
	else
		referrer = "&referrer=" + SmartEncode(referrer);
	var pageTitle		= pd.title;
	if(!IsValidObject(pageTitle) || pageTitle == "")
		pageTitle = "";
	else
		pageTitle = "&pageTitle=" + SmartEncode(pageTitle);
	var queryString		= pd.location.search;
	if(!IsValidObject(queryString) || queryString == "")
		queryString = "";
	else
		queryString = "&queryString=" + SmartEncode(queryString);
	var cookies			= pd.cookie;
	if(!IsValidObject(cookies) || cookies == "")
		cookies = "";
	else
		cookies = "&cookies=" + SmartEncode(cookies);
		
	var maxLength			= 2000;
	
	var requestString = "commandInit.smgif?siteID=" + this.SiteID + "&sessionID=" + this.SessionID + "&accountID=" + this.AccountID + "&browserID=" + this.BrowserID;
	
	if(requestString.length + screenRes.length < maxLength)
		requestString += screenRes;
	
	if(requestString.length + currentPage.length < maxLength)
		requestString += currentPage;
		
	if(requestString.length + referrer.length < maxLength)
		requestString += referrer;
		
	if(requestString.length + pageTitle.length < maxLength)
		requestString += pageTitle;
		
	if(requestString.length + queryString.length + cookies.length < maxLength)
	{
		requestString += queryString + cookies;	
	}
	
	this.SendRequest(requestString);
		
	this.SetCommandTimer(this.ImageCheckFrequency);
}

SightMaxMonitor.prototype.GetUniqueID = function()
{
	return this.UniqueID++;
}

SightMaxMonitor.prototype.SetCommandTimer = function(milliseconds)
{
	if(null == milliseconds)
		milliseconds = this.ImageCheckTimeSpan;
		
	this.CommandTimerID = window.setTimeout(this.PropertyName + ".Process();", milliseconds);
}

SightMaxMonitor.prototype.ClearCommandTimer = function()
{
	window.clearTimeout(this.CommandTimerID);
}

SightMaxMonitor.prototype.Process = function()
{
	var gotImage = false;
	if(!this.PendingImageDownload)
	{
		this.SendPollRequest();
	}
	else
	{
		this.Attempts++;
		if(this.Attempts > 6)
		{
			this.PendingImageDownload = false;
			this.SendPollRequest();
		}
		else
		{
			gotImage = true;
			this.GetCommand();
		}
	}
	
	if(this.bConnected)
	{
		if(gotImage)
			this.SetCommandTimer(this.ImageCheckFrequency);
		else
			this.SetCommandTimer(this.ImageCheckTimeSpan);
	}			
}

SightMaxMonitor.prototype.SendPollRequest = function()
{
	var request = "commandmonitor.smgif?u=" + this.GetUniqueID() + "&sessionID=" + this.SessionID + "&siteID=" + this.SiteID + "&BrowserID=" + this.BrowserID + "&accountID=" + this.AccountID;
	this.SendRequest(request);
}

SightMaxMonitor.prototype.SendRequest = function(newSrc)
{
	this.Attempts				= 0;
	this.PendingImageDownload	= true;
	this.SightMaxCommandImage.src		= this.Path + newSrc;
}

SightMaxMonitor.prototype.SendCoBrowseData = function()
{
	var allCookies	= escape(document.cookie);
	var queryString = escape(window.location.search);
	var src = "commandcobrowse.smgif?=" + this.GetUniqueID() + "&sessionID=" + this.SessionID + "&siteID=" + this.SiteID + "&cookies=" + allCookies + "&query=" + queryString;
	this.SendRequest(src);
}

SightMaxMonitor.prototype.GetCommand = function()
{
	if(this.PendingImageDownload)
	{
	   
        var w = this.SightMaxCommandImage.width;
	    var h = this.SightMaxCommandImage.height;
	    if(0 != h)
	    {
		    this.PendingImageDownload = false;
		    this.HandleCommand(h, w);
	    }
	   
		
	} 
}

SightMaxMonitor.prototype.HandleCommand = function(height, width)
{
	// If the height is not 1, the image is not our command image (maybe a default image from IIS?)
	// and if the image is the same as last time, we have already taken that action
	if(width != 1 || height == this.LastHeight)
		return;
		
	this.LastHeight = height;
	switch(height)
	{
		case 10:
			break;
		case 20:
			this.InviteChat();
			break;
		case 35:
			this.InvokeChat();
			break;
		case 40:
			this.bConnected = false;
			break;
		case 50:
			this.SendCoBrowseData();
			break;
		default:
			break;
	}
}






///Operator invoked/invited chat section.

SightMaxMonitor.prototype.OpenChat = function(startType)
{
	if("undefined" == typeof(startType))
		startType = "";
	var WinStr = this.Path + "PreChatSurvey.aspx?accountID=" + this.AccountID + "&siteID=" + this.SiteID + "&queueID=" + this.QueueID + "&startType=" + startType;
	window.open(WinStr, 'sightMaxChatWindow', this.ChatWindowOptions);
}

SightMaxMonitor.prototype.InvokeChat = function()
{
	this.OpenChat("OperatorForcedChat");
}


SightMaxMonitor.prototype.InviteChat = function()
{
	if(null == this.InviteDiv) 
		return;	
		
	try
	{
		//this.CheckScroll();//place <div> before making visible.
		if(ableToOpen == "yes")
		{
		    var WinStr = this.Path + "PreChatSurvey.aspx?accountID=" + this.AccountID + "&siteID=" + this.SiteID + "&queueID=" + this.QueueID + "&skipSurvey=yes";
		    var win = window.open(WinStr, 'sightMaxChatWindow', this.ChatWindowOptions);
		    if(null == win)
		    {
		        ableToOpen = "no";
		        //this is called if the window fails to open
                this.InviteDiv.style.visibility = "visible";
                this.SetScrollTimer();
            }
            else
            {
                //if the window does open, we need to report that the invite was successful
                var instance = document.sightMaxMonitor;
                instance.inviteResponse = new Image();
	            instance.inviteResponse.src = instance.Path + "commandmonitor.smgif?u=" + instance.GetUniqueID() 
		        + "&sessionID=" + instance.SessionID + "&siteID=" + instance.SiteID 
		        + "&BrowserID=" + instance.BrowserID + "&inviteResponse=accepted";
            }
        }
        else
        {
            this.InviteDiv.style.visibility = "visible";
            this.SetScrollTimer();
        }
		
	}
	catch(e)
	{
	}
}

function SightMaxAccept()
{
	var instance = document.sightMaxMonitor;
	instance.ClientAcceptInvite();
	instance.inviteResponse = new Image();
	instance.inviteResponse.src = instance.Path + "commandmonitor.smgif?u=" + instance.GetUniqueID() 
		+ "&sessionID=" + instance.SessionID + "&siteID=" + instance.SiteID 
		+ "&BrowserID=" + instance.BrowserID + "&inviteResponse=accepted";
}

function SightMaxCancel()
{
	var instance = document.sightMaxMonitor;
	instance.ClientCancelInvite();
	instance.inviteResponse = new Image();
	instance.inviteResponse.src = instance.Path + "commandmonitor.smgif?u=" + instance.GetUniqueID() 
		+ "&sessionID=" + instance.SessionID + "&siteID=" + instance.SiteID 
		+ "&BrowserID=" + instance.BrowserID + "&inviteResponse=declined";
}


SightMaxMonitor.prototype.ClientAcceptInvite = function()
{
	this.HideInvite();
	this.OpenChat("OperatorInvitedChat");
}

SightMaxMonitor.prototype.OpCancelInvite = function()
{
	var img = new Image();
	img.src = 
	this.HideInvite();
}

SightMaxMonitor.prototype.ClientCancelInvite = function()
{
	this.HideInvite();
}

SightMaxMonitor.prototype.HideInvite = function()
{
	if(null == this.InviteDiv)
		return;
	try
	{
		this.InviteDiv.style.visibility = "hidden";
		this.ClearScrollTimer();
	}
	catch(e)
	{
	}	
}

SightMaxMonitor.prototype.PlaceInvite = function(thLeft, theTop)
{
	try
	{
		this.InviteDiv.style.top	= (theTop + this.InviteDivTopOffset)		+ "px";
		this.InviteDiv.style.left	= (theLeft + this.InviteDivLeftOffset)		+ "px";
	}
	catch(e)
	{
	}
}

SightMaxMonitor.prototype.SetScrollTimer = function()
{
	this.scrollTimeout = window.setTimeout(this.PropertyName +  ".CheckScroll();", 250);
}

SightMaxMonitor.prototype.ClearScrollTimer = function()
{
	window.clearTimeout(this.scrollTimeout);
}

SightMaxMonitor.prototype.CheckScroll = function()
{
	var thisTop = -1;
	var thisLeft = -1;
	if("undefined" == typeof(document.body.scrollTop))
	{
		thisTop = window.pageYOffset;
		thisLeft = window.pageXOffset;
	}
	else
	{
		thisTop = document.body.scrollTop;
		thisLeft = document.body.scrollLeft;
	}
	if(thisTop != this.lastTop)
	{
		this.bTopChanged = true;
	}
	else if(this.bTopChanged)
	{
		this.PlaceInvite(thisLeft, thisTop);
		this.bTopChanged = false;
	}
	this.lastTop = thisTop;
	this.SetScrollTimer();
}

document.sightMaxMonitor	=	new SightMaxMonitor("document.sightMaxMonitor");