﻿function Alerts()
{
	var THIS = this;
	var divContainer = document.getElementById("newsEntries");
	var arrEntries = new Array();
	this.Count = 0;
	this.RefreshMarker = -1;
	this.intScrollSpeed = 1;

	var divNoEntries = document.createElement("DIV");
	divNoEntries.innerHTML = "No alerts or notifications";
	divNoEntries.id = "divNoEntries";
	
	var divDisabled = document.createElement("DIV");
	divDisabled.innerHTML = "Alerts and Notifications are disabled";
	divDisabled.id = "divNoEntries";

	var intScrollingHandle = null;
	var intDelay = 50;
	var intPosition = 0;
	var intHeight = 0;
	var blnMouseOver = false;
	var blnRefreshRequired = false;
	var intMaxHeight = 0;
	var blnScrollSet = false;
	var intRefreshCounter = 0;
	var blnHideAlertsAndNotifications = false;
	var strStep = window.location.pathname.toLowerCase().replace('?back=0', '');
	var intOffset = 0;
	var blnShowControls = false;
	
	switch (strStep)
	{
		case '/operator':
		case '/operator/index.aspx':
		case '/workshop':
		case '/workshop/index.aspx':
			intOffset = 36;
			break;
	}

	THIS.Refreshing = false;
	THIS.QueueRefreshInterval = 100000;
	THIS.intRefreshHandle = null;

	THIS.lblAlerts = document.getElementById('lblAlerts');
	THIS.lblClause = document.getElementById('lblClause');
	THIS.lblNotifications = document.getElementById('lblNotifications');

	divContainer.onmouseover = Container_MouseOver;
	divContainer.onmouseout = Container_MouseOut;
	
	try
	{
		//Check if Alerts and Notifications have been disabled
		if(hasPermissions(true, false, 111) && getUserDetail().XUserRoleTypeCode != 'CMP')
		{
			blnHideAlertsAndNotifications = true;
		}
		else
		{
			blnShowControls = true;	
			document.getElementById('newsControls').className = '';		
		}
	}
	catch(e)
	{
	}

	var blnScrollingRequired = false;

	//====================================================
	// Resize this control because the page has been resized
	//====================================================
	this.OnResize = function OnResize(blnUpdateUI)
	{
		try
		{			
			intMaxHeight = 0;

			if (document.getElementById("contentHeading") != null)
				intMaxHeight = document.getElementById("contentHeading").offsetHeight;
			this.Height = 0;

			var stats = document.getElementById("stats");

			if (stats != null)
				intMaxHeight -= (stats.offsetHeight + 16 + 16 + 5);

			var divSiteAlert = document.getElementById("siteAlert");
			if (divSiteAlert != null)
				intMaxHeight += divSiteAlert.offsetHeight + 4;

			var divPanels = document.getElementById("panels");
			if (divPanels != null)
				intMaxHeight += divPanels.offsetHeight;

			var otherScroller = document.getElementById("advertEntries");
			if (otherScroller)
				intMaxHeight = (intMaxHeight - 32) / 2;

			if (intMaxHeight < 100)
				intMaxHeight = 100;

			if (BrowserDetect.browser == "Explorer" && BrowserDetect.version == 6)
				intMaxHeight -= 9;

			if (BrowserDetect.browser == "Explorer" && BrowserDetect.version == 8)
				intMaxHeight += 1;

			if (BrowserDetect.browser == "Explorer" && BrowserDetect.version > 8)
				intMaxHeight += 3;

			if (BrowserDetect.browser == "Chrome" || BrowserDetect.browser == "Safari")
				intMaxHeight += 1;
				
			if(blnShowControls)
				intMaxHeight -= 21;

			if (blnUpdateUI)
			{
				divContainer.style.height = (intMaxHeight - intOffset) + "px";
			}
		}
		catch (exc)
		{
			HtmlPopup.Error(exc);
		}
	}

	//====================================================
	// The mouse has left the control, allow the scrolling to resume
	//====================================================
	function Container_MouseOut()
	{
		blnMouseOver = false;
	}

	//====================================================
	// The mouse has entered the control, stop the scrolling
	//====================================================
	function Container_MouseOver()
	{
		blnMouseOver = true;
	}

	//====================================================
	// Enqueue a refresh of the alerts, to occurr when the events are out of view from the scrolling
	//====================================================
	this.QueueRefresh = function QueueRefresh()
	{
		window.clearTimeout(THIS.intRefreshHandle);
		
		// Check if scrolling is required.
		if (!blnScrollingRequired)
		{
			THIS.Refreshing = false;
			THIS.Refresh();
		}
		return;
	}

	//====================================================
	// Make one step on a scroll increment
	//====================================================
	this.Scroll = function Scroll()
	{
		try
		{
			if (blnScrollingRequired == false || blnMouseOver == true || arrEntries.length == 0)
				return;

			var popupBackground = document.getElementById("popupBackground");

			if (popupBackground && popupBackground.style.display == "block")
				return;

			if (intDelay > 0)
			{
				intDelay--;
				return;
			}

			if(intPosition <= 0 || THIS.intScrollSpeed > 0)
				intPosition = intPosition - THIS.intScrollSpeed;
			
			var divFirstEntry = arrEntries[0].Container;

			if (arrEntries[0].tagName == "DIV")
				divFirstEntry = arrEntries[0];

			if (Math.abs(intPosition) >= divFirstEntry.offsetHeight)
			{
				var intDifference = Math.abs(intPosition) - divFirstEntry.offsetHeight;
				intPosition = 0 - intDifference;

				divContainer.removeChild(divFirstEntry);
				arrEntries.shift();

				if (arrEntries.length > 0)
				{
					divFirstEntry = arrEntries[0].Container;

					if (arrEntries[0].tagName == "DIV")
						divFirstEntry = arrEntries[0];
				}
				else
				{
					divFirstEntry = null;
					return;
				}
			}

			divFirstEntry.style.marginTop = intPosition + "px";

			if (arrEntries.length <= THIS.RefreshMarker && THIS.RefreshMarker > 0)
			{
				//refresh the next section...
				THIS.Refreshing = false;
				THIS.Refresh();
				THIS.RefreshMarker = -1;
			}

			if (Math.abs(intPosition) >= intHeight)
			{
				intPosition = THIS.Height - 10;

				if (blnRefreshRequired)
				{
					THIS.Refreshing = false;
					THIS.Refresh();
				}
			}
		}
		catch (exc)
		{
			window.clearTimeout(THIS.intRefreshHandle);
			HtmlPopup.Error(exc);
		}
	}

	//====================================================
	// Clear the list of alerts
	//====================================================
	this.Clear = function Clear()
	{
		try
		{
			divContainer.className = "hideEntries segmentBackground";
			while (arrEntries.length > 0)
			{
				var objEntry = arrEntries.shift();

				if (objEntry.Container)
					divContainer.removeChild(objEntry.Container);
				else if (objEntry.tagName == "DIV")
					divContainer.removeChild(objEntry);
			}

			try
			{
				divContainer.removeChild(divNoEntries);
			}
			catch (exc) { }

			if (!blnRefreshRequired && THIS.Refreshing == false)
			{
				intHeight = 50;
				divContainer.style.height = (intHeight - intOffset) + "px";
				blnScrollingRequired = false;
				intDelay = 10;
				intPosition = 0;
			}
		}
		catch (exc)
		{
			window.clearTimeout(THIS.intRefreshHandle);
			HtmlPopup.Error(exc);
		}
	}

	//====================================================
	// Refresh the list of alerts (only if the alerts are not already refreshing, and the statistics are not refreshing)
	//====================================================
	this.Refresh = function Refresh()
	{
		try
		{			
			if (intMaxHeight == 0)
				this.OnResize(false);
				
			//if alerts and notifications are disabled then do not show
			if(blnHideAlertsAndNotifications)
			{				
				THIS.DisplayAlerts('DISABLED');
				return;
			}
				
			//if counter is > 0 then this function has been called multiple times
			if(intRefreshCounter > 0)
				return;

			// Check if the alerts are refreshing.
			if (THIS.Refreshing)
				return;

			THIS.Refreshing = true;
			
			intRefreshCounter++;

			var soapGetAlerts = new SoapClient();
			soapGetAlerts.AddParameter('intAlertId', '0');
			soapGetAlerts.SendRequest('/WebServices/NewDesign.asmx', 'http://www.truckfile.co.uk/', 'GetAlerts', THIS.DisplayAlerts);
		}
		catch (exc)
		{
			window.clearTimeout(THIS.intRefreshHandle);
			HtmlPopup.Error(exc);
		}
	}

	//====================================================
	// Display the list of alerts
	//====================================================
	this.DisplayAlerts = function DisplayAlerts(Response)
	{
		intRefreshCounter = 0;
		
		try
		{
			var aResponse = Response.split('|');

			// Check if an error occured.
			if (aResponse[0] == 'ERROR')
			{
				var newsEntries = document.getElementById('newsEntries');
				var contentHeading = document.getElementById('contentHeading');

				newsEntries.style.height = contentHeading.offsetHeight - 26 + 'px';
				newsEntries.innerHTML = '<div style="padding:4px;">There are currently no news items available.</div>';
				newsEntries.className = 'segmentBackground';

				// Check if the session has ended.
				if (aResponse[1] == 'SessionEnd')
				{
					if (window.location.toString().indexOf('home.aspx') < 0)
						NavigateToHome();
				}
				else
				{
					Functions.DisplayError(aResponse[1]);
				}
				return;
			}
			
			// Check if it has been disabled.
			if (aResponse[0] == 'DISABLED')
			{
				divContainer.className = "segmentBackground";
				divContainer.appendChild(divDisabled);
			}
		
			// Check the response XML.
			if (aResponse[1] == '<NewDataSet/>')
			{
				divContainer.className = "segmentBackground";
				try
				{
					divContainer.appendChild(divNoEntries);
				}
				catch (exc) { }
				return;
			}

			// View the data.
			if (window.location.hostname == DevelopmentHostName)
			{
				var soapClient = new SoapClient();
				soapClient.AddParameter('Name', 'AlertsNotifications.xml');
				soapClient.AddParameter('Data', escape(aResponse[1]));
				soapClient.SendRequest('/WebServices/Common.asmx', 'http://www.truckfile.co.uk/', 'ViewXMLData');
			}

			// Load the recordset.
			var objAlertsDS = new RecordSet();
			objAlertsDS.LoadXML(aResponse[1], 'Table');

			// Check if the alerts label is present.
			if (THIS.lblAlerts)
			{
				objAlertsDS.Filter('[Type]="ALERT"');
				THIS.lblAlerts.innerHTML = ((objAlertsDS.RecordCount == 0) ? 'NO' : objAlertsDS.RecordCount) + ' ALERT' + ((objAlertsDS.RecordCount == 1) ? '' : 'S');
				objAlertsDS.Filter('');

				THIS.lblClause.innerHTML = '&nbsp;&amp;&nbsp;';

				objAlertsDS.Filter('[Type]="NOTIFICATION"');
				THIS.lblNotifications.innerHTML = ((objAlertsDS.RecordCount == 0) ? 'NO' : objAlertsDS.RecordCount) + ' NOTIFICATION' + ((objAlertsDS.RecordCount == 1) ? '' : 'S');
				objAlertsDS.Filter('');
			}

			if ((objAlertsDS.RecordCount > 0 || arrEntries.length > 0) && blnScrollingRequired == false)
				THIS.Clear();

			THIS.Count += objAlertsDS.RecordCount;
			if (THIS.RefreshMarker < 0)
				THIS.RefreshMarker = 0;
			THIS.RefreshMarker += (objAlertsDS.RecordCount / 2);

			intHeight = 0;
			while (!objAlertsDS.EOF())
			{
				var objEntry = new AlertEntry(this, objAlertsDS);

				arrEntries.push(objEntry);
				divContainer.appendChild(objEntry.Container);

				intHeight += objEntry.Container.offsetHeight;

				objAlertsDS.MoveNext();
			}

			if (arrEntries.length == 0 && aResponse[0] != 'DISABLED')
			{
				try
				{
					divContainer.appendChild(divNoEntries);
				}
				catch (exc) { }
				intHeight = 25;
			}

			var intSetHeight = intHeight;
			if (intSetHeight > intMaxHeight)
			{
				blnScrollingRequired = true;

				//add the truckfile logo...
				var divStopper = document.createElement("DIV");
				divStopper.id = "stopper";
				divContainer.appendChild(divStopper);
				arrEntries.push(divStopper);

				if (blnRefreshRequired)
				{
					intDelay = 0;
					intPosition = intMaxHeight - 10;
					var divFirstEntry = arrEntries[0].Container;
					divFirstEntry.style.marginTop = intPosition + "px";
				}
			}
			else
				blnScrollingRequired = false;

			intSetHeight = intMaxHeight;

			blnRefreshRequired = false;
			divContainer.className = "segmentBackground";
			divContainer.style.height = (intSetHeight - intOffset) + "px";
			THIS.Height = intSetHeight;	
			
			//only set the scroll once
			if(blnScrollSet == false)
			{				
				window.setInterval("m_objAlerts.Scroll()", 50);
				blnScrollSet = true;
			}
			
			if (aResponse[0] != 'DISABLED')
			{
			// Refresh the queue.
				THIS.intRefreshHandle = window.setTimeout(m_objAlerts.QueueRefresh, THIS.QueueRefreshInterval);
			}
			
			
			THIS.Refreshing = false;
			
			// Check the current page.
			//window.status = 'Alerts updated: ' + Date() + ', ' + objAlertsDS.RecordCount;
			delete objAlertsDS;
		}
		catch (exc)
		{
			HtmlPopup.Error(exc);
		}
	}
	
	//====================================================
	// Pause Notifications
	//====================================================
	this.PauseNotifications = function PauseNotifications()
	{
		var imgAlertsPausePlay = document.getElementById('imgAlertsPausePlay');
		
		if(THIS.intScrollSpeed == 0)
		{
			THIS.intScrollSpeed = 1;
			imgAlertsPausePlay.src = '../images/management/pause.png';
		}
		else
		{
			THIS.intScrollSpeed = 0;
			imgAlertsPausePlay.src = '../images/management/play.png';
		}
		
		return;
	}
	
	//====================================================
	// Increase and decrease Notification speed
	//====================================================
	this.ChangeNotificationSpeed = function ChangeNotificationSpeed(SpeedChange)
	{
		var imgAlertsPausePlay = document.getElementById('imgAlertsPausePlay');
			imgAlertsPausePlay.src = '../images/management/pause.png';
		
		//if rewinding and the scroll is going forward set the current speed to 0
		if(SpeedChange < 0 && THIS.intScrollSpeed > 0)
			THIS.intScrollSpeed = 0;
		
		//if fast forwarding and the scroll is going backwards set the current speed to 0	
		if(SpeedChange > 0 && THIS.intScrollSpeed < 0)
			THIS.intScrollSpeed = 0;
		
		THIS.intScrollSpeed = THIS.intScrollSpeed + SpeedChange;		
		return;
	}
	
	return;
}

var m_objAlerts = null;
Alerts.Create = function Create()
{
	try
	{
		if (document.getElementById("newsEntries") == null)
			return null;

		if (m_objAlerts == null)
			m_objAlerts = new Alerts();

		// Invoke the refresh.
		switch (window.location.pathname.toLowerCase())
		{
			case '/home.aspx':
			case '/operator-signup.aspx':
			case '/demonstration.aspx':
			case '/contact-us.aspx':
				m_objAlerts.QueueRefreshInterval = 60000;
				m_objAlerts.Refresh();
				break;
				
			case '/operator':
			case '/operator/':
			case '/operator/index.aspx':
				m_objAlerts.QueueRefreshInterval = 60000;
				m_objAlerts.Refresh();
				break;
				
			case '/workshop':
			case '/workshop/':
			case '/workshop/index.aspx':
				m_objAlerts.QueueRefreshInterval = 60000;
				m_objAlerts.Refresh();
				break;
		}

		return m_objAlerts;
	}
	catch (exc)
	{
		HtmlPopup.Error(exc);
	}
}

addInitMethod(Alerts.Create);

//====================================================
// Alert entry class.
//====================================================
function AlertEntry(objAlerts, recordset)
{
	var THIS = this;
	this.Alerts = objAlerts;
	this.Container = document.createElement("DIV");
	var h2Heading = document.createElement("H2");
	var pSummary = document.createElement("P");

	this.AlertId = recordset["AlertId"];
	this.Title = recordset["Title"].replace(/&amp;/gi, '&');
	this.Summary = recordset["Summary"].replace(/&amp;/gi, '&');
	this.AlertType = recordset["AlertType"];
	this.Body = recordset["Body"];

	this.Container.id = "entry";
	if (this.Container.attachEvent)
		this.Container.attachEvent("onclick", AlertEntry_OnClick);
	else
		this.Container.onclick = AlertEntry_OnClick;

	h2Heading.innerHTML = this.Title;
	pSummary.innerHTML = this.Summary;

	this.Container.appendChild(h2Heading);
	this.Container.appendChild(pSummary);

	//====================================================
	// An alert has been clicked, get the body for the alert if not dont already, and open the popup for it
	//====================================================
	function AlertEntry_OnClick(evt)
	{
		try
		{
			// Check if the alert body is available.
			if (!THIS.Body || THIS.Body == "" || THIS.Body == null)
			{
				Functions.DisplayMessage('Unfortunately the content body of the alert is missing. Please contact your system administrator if you continue to receive this message.', 'Alert Error', 'Information');
//				var soapGetAlerts = new SoapClient();
//				soapGetAlerts.AddParameter('intAlertId', THIS.AlertId);
//				soapGetAlerts.AddParameter('strAlertType', THIS.AlertType);
//				soapGetAlerts.SendRequest('/WebServices/NewDesign.asmx', 'http://www.truckfile.co.uk/', 'GetAlerts', THIS.StoreBody);
			}
			else
			{
				//open the popup with already gathered content...
				OpenPopup();
			}
		}
		catch (exc)
		{
			HtmlPopup.Error(exc);
		}
	}

	//====================================================
	// Store the details for the body of the alert
	//====================================================
	this.StoreBody = function StoreBody(Response)
	{
		try
		{
			var aResponse = Response.split('|');
			
			// Check if an error occured.
			if (aResponse[0] == 'ERROR')
			{
				// Do nothing.
				return;
			}
			
			// Check the response XML.
			if (aResponse[1] == '<NewDataSet/>')
			{
				HtmlPopup.Error('Unable to display alert/notification as there was no data returned from the server.');
				return;
			}

			// Load the recordset.
			var objAlertsDS = new Recordset();
			objAlertsDS.LoadXML(aResponse[1], 'Table');
			
			THIS.Body = objAlertsDS["Body"];

			OpenPopup();
		}
		catch (exc)
		{
			HtmlPopup.Error(exc);
		}
	}

	//====================================================
	// Open the popup for the alert, or goto the URL in the body if it starts with GOTO:
	//====================================================
	function OpenPopup()
	{
		try
		{
			if (THIS.Body.indexOf("GOTO:") == 0)
			{
				var strURL = THIS.Body.substring(5, THIS.Body.length);
				Navigate(strURL, false, null);
			}
			else if (THIS.Body.indexOf("INVOKE:") == 0)
			{
				var strInvoke = THIS.Body.substring(7, THIS.Body.length);

				try
				{
					eval(strInvoke);
				}
				catch (exc)
				{
					HtmlPopup.Alert("An error was encountered when executing the operation for this alert.\n" + exc.message + "\n\n" + strInvoke);
				}
			}
			else
			{
				//openPopup(THIS.Container, THIS.Title, null, THIS.Body);
				if (getUserDetail() == null)
					NewPopup.OpenPopup(THIS.Container, THIS.Title, "", THIS.Body);
				else
					HtmlPopup.Alert(THIS.Body, THIS.Title, "/images/truckfile32.png");
			}
		}
		catch (exc)
		{
			HtmlPopup.Error(exc);
		}	
	}
}
