﻿function DynamicPopup(blnAutoDispose, objWindow)
{
	if (!objWindow)
		objWindow = window;

	var THIS = this;
	this.InnerPopup = null;
	this.Container = null;
	this.Title = "";
	this.Shadow = null;
	this.AutoDispose = blnAutoDispose;
	var intButtonId = 0;

	if (arguments.length == 0)
		this.AutoDispose = true;

	this.Buttons = objWindow.document.createElement("DIV");
	this.Buttons.id = "buttons";
	var arrButtons = new Array();
	var arrCallbacks = new Object();

	this.Content = objWindow.document.createElement("DIV");

	this.Heading = objWindow.document.createElement("H2");

	var divPopup = null;
	var divPopupBackground = null;

	//====================================================
	// Create the popup
	//====================================================
	function CreatePopup()
	{
		THIS.Heading.innerHTML = THIS.Title;
		if (THIS.Container == null)
		{
			THIS.Container = objWindow.document.createElement("DIV");
			THIS.Container.className = "popup";
		}

		THIS.Container.appendChild(THIS.Heading);
		THIS.Container.appendChild(THIS.Content);
		THIS.Container.appendChild(THIS.Buttons);

		divPopupBackground = objWindow.document.createElement("DIV");
		divPopupBackground.className = "popupBackground";

		//append to DOM

		var frmForm = objWindow.document.getElementById("aspnetForm");

		if (frmForm == null)
			frmForm = document.body;

		if (frmForm == null)
			throw new Error("Cannot show popup, aspnetForm and body cannot be accessed.");
		
		frmForm.appendChild(THIS.Container);
		frmForm.appendChild(divPopupBackground);

		THIS.InnerPopup = new NewPopup(THIS.Container, divPopupBackground);
		THIS.InnerPopup.OnPopupClosed = InnerPopup_PopupClosed;
		THIS.Shadow = THIS.InnerPopup.Shadow;

		if (BrowserDetect.browser == "Explorer")
		{
			THIS.InnerPopup.FadeInPopup = false;
			THIS.InnerPopup.FadeInBackground = false;
		}
	}

	//====================================================
	// Destroy the popup and remove from the DOM
	//====================================================
	this.Dispose = function Dispose()
	{
		try
		{
			var frmForm = objWindow.document.getElementById("aspnetForm");
			try
			{
				frmForm.removeChild(THIS.InnerPopup.Shadow);
			}
			catch (exc) { }

			try
			{
				frmForm.removeChild(divPopupBackground);
			}
			catch (exc) { }
		}
		catch (exc)
		{
			alert("Could not dispose DynamicPopup;\n" + exc.message);
		}
	}

	//====================================================
	// Add a button to the popup
	//====================================================
	this.AddButton = function AddButton(strText, fncClickCallback)
	{
		var btnButton = objWindow.document.createElement("INPUT");
		btnButton.type = "button";
		btnButton.className = "button wide";
		btnButton.value = strText;
		intButtonId++;
		btnButton.setAttribute("buttonId", intButtonId);

		arrCallbacks[intButtonId] = fncClickCallback;

		btnButton.onclick = btnButton_Click;

		arrButtons.push(btnButton);
		this.Buttons.appendChild(btnButton);
		return btnButton;
	}

	//====================================================
	// A button has been clicked, find and invoke the event handler
	//====================================================
	function btnButton_Click(evt)
	{
		try
		{
			evt = objWindow.event ? objWindow.event : evt;
			var target = evt.srcElement ? evt.srcElement : evt.target;
			var intButtonId = Number(target.getAttribute("buttonId"));
			var fncCallback = arrCallbacks[intButtonId];

			var fncOnClick = null;
			if (typeof (fncCallback) == "function")
				fncOnClick = fncCallback;
			else if (typeof (fncCallback) == "string")
			{
				if (fncCallback == "CLOSE" || fncCallback == "")
					fncCallback = "fncClose";

				fncOnClick = eval(fncCallback);
			}

			if (arrButtons.length == 1)
				fncClose();

			fncOnClick(evt, THIS, target);
		}
		catch (exc)
		{
			HtmlPopup.Error(exc);
		}
	}

	//====================================================
	// Event handler to close the popup
	//====================================================
	function fncClose()
	{
		THIS.Close();
		
		//force the popup to dispose
		if (THIS.AutoDispose == true)
			THIS.Dispose();
	}

	//====================================================
	// Open the popup
	//====================================================
	this.Open = function Open(blnActuallyOpen)
	{
		if (THIS.InnerPopup == null)
			CreatePopup();

		divPopupBackground.style.zIndex = ++HtmlPopup.Count;
		THIS.InnerPopup.Shadow.style.zIndex = ++HtmlPopup.Count;

		if (arguments.length == 0 || blnActuallyOpen == true)
		{
			THIS.InnerPopup.Open();

			if (arrButtons.length > 0)
				arrButtons[0].focus();
		}
		return THIS.InnerPopup;
	}

	//====================================================
	// The popup has finished closing
	//====================================================
	function InnerPopup_PopupClosed()
	{
		if (THIS.AutoDispose)
			THIS.Dispose();
	}

	//====================================================
	// Close the popup
	//====================================================
	this.Close = function Close()
	{
		if (THIS.InnerPopup == null)
			return;

		THIS.InnerPopup.Close();
	}

	//====================================================
	// Update the sizes of the controls making up the container popup
	//====================================================
	this.UpdateSize = function UpdateSize()
	{
		if (THIS.InnerPopup == null)
			return;

		THIS.InnerPopup.UpdateSize();
	}
}

function HtmlPopup() { }
HtmlPopup.Count = 1000;

//====================================================
// Show a HTML popup alert
// Usage:
// strText - the text to show in the content of the popup
// [strTitle] - the text to show in the title of the popup (optional)
// [strIcon] - the image url to use for the popup (optional)
//
// e.g.
// HtmlPopup.Alert("this is an alert");
// or
// HtmlPopup.Alert("this is an alert", "the title", "/images/anImage.png");
//====================================================
HtmlPopup.Alert = function Alert(strText, strTitle, strIcon, fncCallback, blnAutoOpen)
{
	var objButtons = new Object();
	objButtons["OK"] = fncCallback;
	
	try
	{
		strTitle = (strTitle.length == 0) ? 'Truckfile' : strTitle;
	}
	catch(e)
	{
	}
	
	var objPopup = Functions.DisplayPrompt(strText, strTitle, 'Information', objButtons);
	return objPopup;
}

HtmlPopup.LastError = null;
//====================================================
// Show the information about an error
//====================================================
HtmlPopup.Error = function HtmlPopup_Error(exc, strLocation, fncCallback)
{
	// Check if the current page is unloading.
	if (blnPageUnLoading)
		return;

	var strError = '';
	var strHeading = "";

	if (exc.message == 'GOOGLEMAPS')
	{
		Functions.DisplayError('Google Maps are not currently available.\nPlease try again later.', fncCallback);
		return;
	}

	if (typeof (exc) == 'string')
		strError = exc;
	else
	{
		strError = GetErrorDetail(exc);
		strHeading += 'The operation you are trying to perform may not have completed successfully.\n\n';
		if (!strLocation || strLocation == null || strLocation == '')
		{
			var strFunctionDefinition = (arguments.callee && arguments.callee.caller) ? arguments.callee.caller.toString() : '';
			var strFunctionKeyWord = 'function ';

			var intFunctionIndex = strFunctionDefinition.indexOf(strFunctionKeyWord);
			var strTemp = strFunctionDefinition.substring(intFunctionIndex);
			var intOpenBracketIndex = strTemp.indexOf('{');
			var strFunctionName = strTemp.substring(0, intOpenBracketIndex);

			strFunctionName = strFunctionName.substring(strFunctionKeyWord.length, strFunctionName.length);
			strFunctionName = strFunctionName.trim();

			if (strFunctionName.indexOf('(') == 0)
				strFunctionName = '[function] ' + strFunctionName;

			strLocation = strFunctionName;
		}
	}

	if (strError == HtmlPopup.LastError)
		return;

	if (strError.indexOf('ERR002:') != -1)
	{
		DynamicPopup.ShowLoggedOutMessage();
		return;
	}

	if (strHeading != null && strHeading != '')
		strHeading += 'Location = ' + strLocation + '\n';
	else
	{
		if (strHeading != '')
			strHeading += '\n';
	}

	strHeading += 'Page: ' + document.location + '\n';
	
	// Check the host name of the browser, only send an email reporting the error for live server.
	if ((window.location.hostname == 'www.truckfile.co.uk') || (window.location.hostname == 'vms.truckfile.co.uk'))
	{
		var soapClient = new SoapClient();
		soapClient.AddParameter('From', 'pageerror@truckfile.co.uk');
		soapClient.AddParameter('To', 'exception.truckfile@magicinternet.co.uk');
		soapClient.AddParameter('Subject', 'Client Error');
		soapClient.AddParameter('Message', strHeading + '\n' + strError + '\n\n' + GetBrowserInformation());
		soapClient.SendRequest('/WebServices/v1/General.asmx', 'http://www.truckfile.co.uk/', 'SendEmail');
	}

	// Display the error.
	Functions.DisplayError(strHeading + strError, fncCallback);
	return;
}

//====================================================
// Show a HTML popup confirmation
// Usage:
// strText - the text to show in the content of the popup
// objButtons - the buttons to add to the popup (see comments below)
// [strTitle] - the text to show in the title of the popup (optional)
// [strIcon] - the image url to use for the popup (optional)
//
// objButtons should be an object where the properties are the text to show on the buttons
// and the values of those properties are the methods to invoke on the clicking of the buttons
// e.g.
// var objButtons = new Object();
// objButtons["Yes"] = fncYesCallback;
// objButtons["No"] = fncNoCallback;
//
// where fncYesCallback and fncNoCallback are functions that are accessible from the method CREATING the popup
//
// e.g.
// HtmlPopup.Confirm = function("confirm this message", objButtons);
// or
// HtmlPopup.Confirm = function("confirm this message", objButtons, "the title", "/images/confirm.png");
//====================================================
HtmlPopup.Confirm = function Confirm(strText, objButtons, strTitle, strIcon)
{
	var objPopup = Functions.DisplayPrompt(strText, strTitle, 'Question', objButtons, undefined);
	return objPopup;
}

//====================================================
// An unhandled exception has occurred, show on screen and email to support
//====================================================
function Window_OnError(strMessage, strURL, intLineNumber)
{
	if (blnPageUnLoading)
		return;

	try
	{
		WaitWindow.Hide();
	}
	catch(e)
	{
	}
	
	Functions.DisplayError('Message: ' + strMessage + '<br/>URL: ' + strURL + '<br/>Line Number: ' + intLineNumber);
	return true;
}

var m_objLoggedOutMessage = null;
//====================================================
// Show a message stating that the user must be logged in to use the website
//====================================================
DynamicPopup.ShowLoggedOutMessage = function ShowLoggedOutMessage()
{
	try
	{
		if (m_objLoggedOutMessage != null)
			return;

		var objButtons = new Object();
		objButtons["Login"] = fncLoginAgain;
		var strMessage = "";
		strMessage += "<b>You have been logged out of Truckfile and will need to login again.</b>\n\n";
		strMessage += "This could be because you have left Truckfile logged in for longer than the allowed time,\n";
		strMessage += "or Truckfile has received an update which requires you to re-authenticate.";

		m_objLoggedOutMessage = HtmlPopup.Confirm(strMessage, objButtons, "Truckfile", "/images/truckfile32.png");
	}
	catch (exc)
	{
		HtmlPopup.Error(exc);
	}
}

//====================================================
// Return to the login page
//====================================================
function fncLoginAgain(evt, objPopup, btnButton)
{
	try
	{
		document.location.reload();
		//Navigate("/home.aspx", false, null);
	}
	catch (exc)
	{
		HtmlPopup.Error(exc);
		WaitWindow.Hide();
	}
}

window.onerror = Window_OnError;
