﻿var strChangeTypeForSessionTrackerNotification = "";
var blnIsOccurredErr = false;
function ManageClients()
{
	if (bIsTrackerOn)
	{
		alert(sAlertStopTracker);
		return;
	}

	// clicked on "choose client", display/hide client list drop down
	ShowHideClientList();
}

function ShowHideClientList(bKeepChecked)
{
	var divClientList = document.getElementById(divClientListID);

	if (divClientList.style.visibility == "hidden")
	{
		if (parseInt(divClientList.clientHeight) > parseInt(maxClientListHeight))
		{
			divClientList.style.height = maxClientListHeight;
		}    
		divClientList.style.visibility = "visible";
	}
	else
	{
		divClientList.style.visibility = "hidden";

		if (bKeepChecked == null || !bKeepChecked)
		{
			// unselect any selected radio buttons, and clear text box
			var arClients = document.getElementsByName("cbClients");

			for (var i=0; i<arClients.length; i++)
			{
				arClients[i].checked = false;
			}                    
		}

		document.getElementById("tbNewClient").value = sTbNewClientValue;
	}
}

function ChangeClient()
{
	if (bIsTrackerOn)
	{
		alert(sAlertSessionTrackerOn);
		return;
	}

	var arClients = document.getElementsByName("cbClients");

	for (var i=0; i<arClients.length; i++)
	{
		if (arClients[i].checked)
		{
			if (arClients[i].value == 0)
			{
				// new client
				if (document.getElementById("tbNewClient").value == "")
				{
					alert(sAlertEnterNewClient);
					document.getElementById("tbNewClient").focus();
					return;
				}
				CreateNewClient_ST();
				return;
			}
			else
			{
				SwitchToClient(arClients[i].value);
			}
		}
	}
}

function ParentCreateNewClientFromNotice( strNewClientName )
{
	document.getElementById("cbClientsNew").checked = true;
	document.getElementById("tbNewClient").value = strNewClientName;
	ChangeClient();
	if ( ! blnIsOccurredErr )
	{
		ShowHideClientList(true);
	}
	else
	{
		blnIsOccurredErr = false;
	}
}

function ParentSelectAndStartFromNotice ( strClientID )
{
	var arClients = document.getElementsByName("cbClients");
	var intClientsLength = arClients.length;
	var spanCurrentClient = document.getElementById("spanCurrentClient");
	var iClientId = parseInt(strClientID, 10);
	for (var i=0; i < intClientsLength; i++)
	{
		arClients[i].checked = (arClients[i].value==strClientID);
	}        

	spanCurrentClient.firstChild.firstChild.nodeValue = document.getElementById("spanClientName_" + iClientId).firstChild.nodeValue;

	iSTCurrentClient =  iClientId;

	StartStopSession();
	//ShowHideClientList(true);
}

function CreateNewClient_ST()
{
	var sParams = "clientID=0&clientName=" + encodeURI(document.getElementById("tbNewClient").value);
	setTimeout("var obj = new ajax.ContentLoader(\"" + sUrlSessionTrackerEditCreateClient + sParams + "\", UpdateClientList, handleClientUpdateError, \"GET\")",0);
}

function UpdateClientList()
{
	var jsonObj = parseAjaxResponse(this.req.status, this.req.responseText);
	if (jsonObj == null) return;

	var iClientId = jsonObj.Client.ID;
	var sClientName = jsonObj.Client.Name;

	if (jsonObj.Client.ID == -1)
	{
		blnIsOccurredErr = true;
		alert(sAlertClientNameExists);
		ShowHideClientList();
	}
	else
	{                        
		// update HTML
		var divClientList = document.getElementById(divClientListID);

		var tblObj = divClientList.getElementsByTagName("table")[0];

		var newRow = tblObj.insertRow(tblObj.rows.length - 3);

		var tblCellContentInput;
		try
		{
			tblCellContentInput = document.createElement('<input type="radio" name="cbClients" checked/>');
		}
		catch(err){
			tblCellContentInput = document.createElement('input');
			tblCellContentInput.setAttribute('type','radio');
			tblCellContentInput.setAttribute('name','cbClients');
			tblCellContentInput.setAttribute("checked", "true");
		}

		tblCellContentInput.value = iClientId;

		var tblCellContentSpan = document.createElement("span");
		tblCellContentSpan.id = "spanClientName_" + iClientId;
		tblCellContentSpan.className = "normalText";
		tblCellContentSpan.appendChild(document.createTextNode(" " + sClientName));

		var tblCell = newRow.insertCell(0);
		var tblCell2 = newRow.insertCell(1);
		tblCell.appendChild(tblCellContentInput);
		tblCell2.appendChild(tblCellContentSpan);

		if (parseInt(divClientList.clientHeight) > parseInt(maxClientListHeight))
		{
			divClientList.style.height = maxClientListHeight;
		}              

		SwitchToClient(iClientId);
	}        
}

function handleClientUpdateError()
{
	// var newWin = window.open("", "_blank");
	// newWin.document.write(this.req.responseText);
}

function SwitchToClient(iClientId)
{
	// update [choose client] link in Session Tracker to the client name
	var spanCurrentClient = document.getElementById("spanCurrentClient");
	spanCurrentClient.firstChild.firstChild.nodeValue = document.getElementById("spanClientName_" + iClientId).firstChild.nodeValue;
	iSTCurrentClient = iClientId;
	ShowHideClientList(true);
	StartStopSession();
}

function StartStopSession()
{
	var imgButton = document.getElementById("SessionPlayStop");
	var d = new Date();

	if (imgButton.src.indexOf("Play") != -1)
	{
		// user wants to start the session tracker
		if (iSTCurrentClient == 0)
		{
			// used to alert, instead just open the list ... alert(sAlertSelectClientToStart);
			ShowHideClientList();
			return;
		}

		// ajax call to start session tracker
		var sParams = "stClientID=" + iSTCurrentClient + "&stAction=1" + "&nc=" + d.getTime();
		setTimeout("var obj = new ajax.ContentLoader(\"" + sUrlSessionTrackerUpdateSession + sParams + "\", EnableDisableClientList, handleClientUpdateError, \"GET\")", 0);
	}
	else
	{
	var sComment = encodeURI(document.getElementById("txtSTComment").value);
	var sParams = "stSessionID=" + iSTCurrentSessionId + "&stClientID=" + iSTCurrentClient + "&stAction=0&stComment=" + sComment + "&nc=" + d.getTime();
	setTimeout("var obj = new ajax.ContentLoader(\"" + sUrlSessionTrackerUpdateSession + sParams + "\", EnableDisableClientList, handleClientUpdateError, \"GET\")", 0);
	}
}

function EnableDisableClientList()
{
	var imgButton = document.getElementById("SessionPlayStop");
	var jsonObject = parseAjaxResponse(this.req.status, this.req.responseText);
	if (jsonObject == null) return;

	if (jsonObject.Session.ActionTaken == 1)
	{
		// session tracker was started
		imgButton.src = imgStopSrc;
		StartSessionTrackerTimer();

		iSTCurrentSessionId = jsonObject.Session.ID;
		
		// for K3 pages, set the cookie right away
		if (document.K3TreeView)
		{
			var stCookie = "";           
			var myDate = new Date();                                    
			myDate.setDate(myDate.getDate() + 30);
			stCookie = "sessiontracker=" + iSTCurrentSessionId + "&client=" + iSTCurrentClient + "&stTimer=" + document.getElementById("sessionTrackerTimer").firstChild.nodeValue + "&clientTime=" + myDate;
			stCookie += "; path=/";
			document.cookie = stCookie;
			//alert (stCookie);		
		}
	}
	else if (jsonObject.Session.ActionTaken == 0)
	{
		// session tracker was stopped
		if (document.getElementById("divSTComment").style.display == "block")
		ShowHideComment();

		imgButton.src = imgPlaySrc;
		StopSessionTrackerTimer();
	}
}

function StopSessionTrackerTimer()
{
	if (typeof (bIsTrackerOn) == 'undefined') return; // not defined if viewing in Viewer.aspx
	
	if (bIsTrackerOn)
	{
		clearTimeout(timerID)
	}

	bIsTrackerOn = false;
	document.getElementById("sessionTrackerTimer").firstChild.nodeValue = "00:00:00";

	// destroy the tracker cookie
	var myDate=new Date();
	myDate.setDate(myDate.getDate()-30);
	document.cookie = "sessiontracker=; expires=" + myDate.toGMTString() + "; path=/";
}

function StartSessionTrackerTimer()
{       
	document.getElementById("sessionTrackerTimer").firstChild.nodeValue = "00:00:00";

	timerID = setTimeout("UpdateTimer(0,0,0)",1000);
	bIsTrackerOn = true;
}

function ShowHideComment()
{
	var divSTComment = document.getElementById("divSTComment");

	if (divSTComment.style.display == "none")
	{
		if (!bIsTrackerOn)
		{
			alert(sAlertStartTrackerToComment);
			return;
		}
		divSTComment.style.display = "block";
	}
	else
	{
		divSTComment.style.display = "none";
	}
}

function GetSessionComment()
{
	var sParams = "stSessionID=" + iSTCurrentSessionId + "&stClientID=" + iSTCurrentClient;
	sParams += "&random=" + document.getElementById("sessionTrackerTimer").firstChild.nodeValue.replace(":", "");

	var obj = new ajax.ContentLoader(sUrlSessionTrackerGetComment + sParams, GetSessionComment_Cont, handleClientUpdateError, "GET");
}

function GetSessionComment_Cont()
{
	var sComment = this.req.responseText;
	document.getElementById("txtSTComment").value = decodeURI(sComment);
}

function SaveSTComment()
{
	var sComment = encodeURI(document.getElementById("txtSTComment").value);
	var sParams = "stAction=2&stSessionID=" + iSTCurrentSessionId + "&stClientID=" + iSTCurrentClient + "&stComment=" + sComment;
	var obj = new ajax.ContentLoader(sUrlSessionTrackerUpdateSession + sParams, SaveSTComment_Cont, handleClientUpdateError, "GET");
}

function SaveSTComment_Cont()
{
	ShowHideComment();
}

function UpdateTimer(hours, minutes, seconds)
{
	var newHours = hours;
	var newMins = minutes;
	var newSecs = seconds;
	var bUpdateDB = false;

	newSecs++;

	if (newSecs >= 60)
	{
		newSecs = 0;
		newMins++;
		bUpdateDB = true;
	}

	if (newMins >= 60)
	{
		newMins = 0;
		newHours++;
	}

	var timeValue = ((newHours < 10) ? "0" + newHours : newHours);
	timeValue  += ((newMins < 10) ? ":0" : ":") + newMins;
	timeValue  += ((newSecs < 10) ? ":0" : ":") + newSecs;

	document.getElementById("sessionTrackerTimer").firstChild.nodeValue = timeValue;

	timerID = window.setTimeout( function() { UpdateTimer.call(this, newHours, newMins, newSecs); }, 1000);

	if (bUpdateDB)
	{
		// 60 seconds have passed, do call back to update database time
		var sParams = "stSessionID=" + iSTCurrentSessionId + "&stClientID=" + iSTCurrentClient + "&stAction=2&random=" + newHours.toString() + newMins.toString() + newSecs.toString();

		var obj = new ajax.ContentLoader(sUrlSessionTrackerUpdateSession + sParams, EnableDisableClientList, handleClientUpdateError, "GET");
	}
}

function DoShowSessionTrackerNotification()
{
	var hdnObj = document.getElementById ("hdnSessionTrackerShowNotification");
	var hdnObjPage = document.getElementById ("hdnSessionTrackerNotificationPageURL");
	
	if ( hdnObj && hdnObjPage )
	{
		if (hdnObj.value == "PromptUser")
		{   
			PopupWindow (hdnObjPage.value, "stPromptUserPopup", strSTPopUpScreenSize, "toolbar=no,scrollbars=no,resizeable=no");
		}

		var arClients = document.getElementsByName("cbClients");
		var intClientsLength = arClients.length;

		if (hdnObj.value == "AutoStart")
		{
			for (var i=0; i < intClientsLength; i++)
			{
				arClients[i].checked = (arClients[i].value==strGeneraClientID);
			}        
			SwitchToClient(parseInt(strGeneraClientID,10));
			ShowHideClientList(true);
		}
	}
}

function ParentSessionTrackerHandleNotification (strAjaxPage, strTypeChange)
{    
	strChangeTypeForSessionTrackerNotification = strTypeChange;
	if (ajax && strAjaxPage.length != 0 && strTypeChange.length != 0)
	{
		setTimeout("var objCallForNotificationChange = new ajax.ContentLoader(\"" + strAjaxPage + "\", sessionTrackerSuccess, doNothing, \"GET\")", 10);
	}
}

function sessionTrackerSuccess()
{    
	var arClients = document.getElementsByName("cbClients");
	var intClientsLength = arClients.length;

	if (strChangeTypeForSessionTrackerNotification == "3")
	{
		for (var i=0; i < intClientsLength; i++)
		{
			arClients[i].checked = (arClients[i].value==strGeneraClientID);
		}        
		SwitchToClient(parseInt(strGeneraClientID,10));
		ShowHideClientList(true);
	}    
}
