var DevelopmentHostName = 'truckfile2.magicinternet.local';

// Set up interval timeouts.
var intOutstandingInvoices = 10000; // 10 seconds.
var intLowStock = 10000 // 10 seconds.
var intOutstandingOrders = 10000 // 10 seconds.
var intStep_ConfigureInvoice = 10000; // 10 seconds.
var intVehicleDocumentList = 10000; // 10 seconds.
var intOrders = 10000; // 10 seconds.
var blnPageUnLoading = false;
var blnIndexStopPageUnload = false;
var elmLeavingElement = null;
var fncLeavingRetry = null;
var strLeavingUrl = null;
var blnFullscreen = false;
var strSwitchAccountEmail = '';
var strSwitchAccountName = '';

var TruckfileWebservice = "/webservices/newDesign.asmx";
var KEYCODE_LEFT = 37;
var KEYCODE_UP = 38;
var KEYCODE_RIGHT = 39;
var KEYCODE_DOWN = 40;
var KEYCODE_ENTER = 13;
var KEYCODE_SPACE = 32;
var KEYCODE_DECIMAL_1 = 46;
var KEYCODE_DECIMAL_2 = 190;
var KEYCODE_DECIMAL_3 = 110;
var KEYCODE_0 = 48;
var KEYCODE_9 = 57;
var KEYCODE_a = 97;
var KEYCODE_z = 122;
var KEYCODE_A = 65;
var KEYCODE_Q = 81;
var KEYCODE_Z = 90;
var KEYCODE_F1 = 112;
var KEYCODE_F9 = 120;
var KEYCODE_DELETE = 46;
var KEYCODE_BACKSPACE = 8;
var KEYCODE_TAB = 9;
var KEYCODE_MINUS = 45;
var SECOND = 1000;
var MINUTE = 60 * SECOND;
var HOUR = 60 * MINUTE;
var DAY = 24 * HOUR;
var DEBUG = true;
var BannerHeight = 180;
var m_objSilverlightPopup = null;
var m_intExtendSessionHandle = 0;
var m_objImpersonatePopup = null;
var WeekByWeekScroll;

//a series of methods to execute once the page has finished loading
var InitMethods = new Array();

function addInitMethod(fncExecute)
{
	InitMethods.push(fncExecute);
}

//page has finished loading, initialise any structures
function init()
{
	blnPageUnLoading = false;
	
	document.onhelp = function() {return(false);}
	window.onhelp = function() {return(false);}

	try
	{
		var strBrowserName = BrowserDetect.browser;
		
		switch (window.location.pathname.toLowerCase())
		{
			case '/workshopview/':
			case '/workshopview/index.aspx':
				if (strBrowserName == 'Explorer')
					strBrowserName += BrowserDetect.version;
				
				if (strBrowserName == 'Firefox')
				{
					var intVersion = Math.floor(Number(BrowserDetect.version));

					if (intVersion > 3)
						strBrowserName += BrowserDetect.version;
				}
				break;
				
			default:
				if (strBrowserName == 'Explorer')
					strBrowserName += BrowserDetect.version;
				break;
		}

		// Send the browser name to the server.
		var soapClient = new SoapClient();
		soapClient.AddParameter('Name', strBrowserName);
		soapClient.SendRequest('/WebServices/Common.asmx', 'http://www.truckfile.co.uk/', 'BrowserName');
		
		IsMobileBrowser();
		createUserDetail();

		document.onkeyup = document_KeyUp;
		document.onmouseup = document_MouseUp;

		var divhomeLink = document.getElementById("homeLink");
		if (divhomeLink != null)
		{
			if (divhomeLink.attachEvent)
				divhomeLink.attachEvent("onclick", headingClicked);
			else
				divhomeLink.onclick = headingClicked;
		}
		
		try
		{
			if (UserManagement)
				UserManagement.PreLoad();
		}
		catch (exc) { }

		try
		{
			if (initLogin != undefined)
				initLogin();
		}
		catch (exc) { }
		
		if (document.body.getAttribute("popup") != "1")
		{
			window.onresize = Window_OnResize;
			Window_OnResize();
		}
		
		while (InitMethods.length > 0)
		{
			var fncExec = InitMethods.shift(); //get the first element from the array, and remove it

			try
			{
				fncExec();
			}
			catch (exc)
			{
				HtmlPopup.Error(exc);
			}
		}
		
		// Check if a password change is required.
		if ((GetCookie('PasswordChangedRequired') == 'true') && (getUserDetail() != null))
		{
			// Check the current page, if it's not the homepage, redirect.
			if (window.location.pathname.toLowerCase() != '/home.aspx')
			{
				window.location = '/home.aspx';
				return;
			}

			m_objNewLogin.ChangePassword();
			Functions.DisplayMessage('You must change your password from \'Password\' before you can use Truckfile.', 'Password Change Required', 'Information');
			return;
		}

		//check if silverlight is installed, display a message
		/*var txtRequiresSilverlight = document.getElementById("txtRequiresSilverlight");
		
		if (txtRequiresSilverlight == null || txtRequiresSilverlight.value == "true")
			requiresSilverlight();*/

		var loginInfo = document.getElementById("loginInfo");
		if (loginInfo != null && getUserDetail() != null)
		{
			if (loginInfo.attachEvent)
				loginInfo.attachEvent("onclick", loginInfo_Click);
			else
				loginInfo.addEventListener("click", loginInfo_Click, false);
		}
	}
	catch (exc)
	{
		//HtmlPopup.Error(exc);
	}
}

//==============================================
// Handle the email
//==============================================
function handleEmail(evt)
{
	try
	{
		evt = window.event ? window.event : evt;
	
		if (getUserDetail() == null)
		{
			if (Navigate("/contact-us.aspx", false, null))
			{
				evt.returnValue = false;

				if (evt.preventDefault)
					evt.preventDefault();

				return false;
			}
		}
	}
	catch (exc)
	{
		HtmlPopup.Error(exc);
		WaitWindow.Hide();
	}
}

//==============================================
// Undo the impersonation of the current user
//==============================================
function loginInfo_Click(evt)
{
	try
	{
		evt = window.event ? window.event : evt;
		var target = evt.srcElement ? evt.srcElement : evt.target;

		if (target.tagName == "ABBR")
			return;

		// Logout.
		NewLogin.Logout();
	}
	catch (exc)
	{
		HtmlPopup.Error(exc);
		WaitWindow.Hide();
	}
}

//==============================================
// Undo the impersonation of the current user
//==============================================
function DoUnimpersonate(evt, objPopup, btnButton)
{
	try
	{
		objPopup.Close();
		WaitWindow.Show("Switching back to original account, please wait...");

		var params = new SOAPClientParameters();
		SOAPClient.invoke("/webservices/newdesign.asmx", "Unimpersonate", params, true, Unimpersonated, null);
	}
	catch (exc)
	{
		HtmlPopup.Error(exc);
		WaitWindow.Hide();
	}
}

//==============================================
// Successfully unimpersonated
//==============================================
function Unimpersonated(strXML, docXML, sender)
{
	try
	{
		if (typeof (strXML) == "object" && strXML != null)
			throw new Error(docXML);

		Navigate("/common/loginRedirect.aspx", true, "Unimpersonation successful, please wait...");
	}
	catch (exc)
	{
		HtmlPopup.Error(exc);
		WaitWindow.Hide();
	}
}

function headingClicked(evt)
{		
	evt = window.event ? window.event : evt;
	var target = evt.srcElement ? evt.srcElement : evt.target;
	
	if(!LeavingPage(target,1,NavigateToHome))
		return;

	if (target && target.tagName == "DIV" && target.id == "homeLink")
	{
		Navigate("/", false, null);
	}
}

//==============================================
// Navigate to home page
//==============================================
function NavigateToHome()
{
	Navigate("/", false, null);
	return;
}

//create a cookie
function createCookie(name, value, days)
{
	var expires = null;
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		expires = "; expires="+date.toGMTString();
	}
	else
		expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

//read a cookie
function readCookie(name) 
{
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

//delete a cookie (invalidate it)
function eraseCookie(name) 
{
	createCookie(name,"",-1);
}

function htmlDecode(strEncoded)
{
	var strDecoded = unescape(strEncoded);
	strDecoded = strDecoded.replace(/&amp;/g, "&");
	return strDecoded;
}

function roundNumber(number, decimals)
{
	var result = Math.round( Math.round( number * Math.pow( 10, decimals + 1 ) ) / Math.pow( 10, 1 ) ) / Math.pow(10,decimals);
	return result;
}

function toCurrency(dblValue)
{
	if (isNaN(dblValue))
		return NaN;

	var strValue = String(roundNumber(dblValue, 2));
	var intDecimalPlaces = 0;
	if (strValue.indexOf(".") != -1)
	{
		intDecimalPlaces = strValue.length - strValue.lastIndexOf(".");
		intDecimalPlaces--;
	}
	else
		strValue += ".";

	intDecimalPlaces = 2 - intDecimalPlaces;

	for (intIndex = 0; intIndex < intDecimalPlaces; intIndex++)
		strValue += "0";

	return strValue;
}

//==================================================
// Allow numeric values only.
//==================================================
function AllowNumericOnly(evt)
{
    evt = window.event ? window.event : evt;

	if (evt == null || evt == undefined)
		return false;
		
	var objSourceElement = evt.srcElement ? evt.srcElement : evt.target;
	var intKeyCode = window.event ? window.event.keyCode : evt.which;

	// Check if the keycode is a minus.
	if (intKeyCode == 45)
	{
		// Check if the source element already contains a minus.
		if (objSourceElement.value.indexOf('-') == -1)
			objSourceElement.value = '-' + objSourceElement.value;
			
		if (window.event)
		{
			window.event.returnValue = false;
		}
		else
		{
			evt.preventDefault();
		}
	}
	
	// Check if the keycode is a point.
	if (intKeyCode == 46)
	{
		// Check if the source element already contains a point.
		if (objSourceElement.value.indexOf('.') == -1)
		{
			if (objSourceElement.value == '')
				objSourceElement.value = '0';
		}
		else
		{
			if (window.event)
			{
				window.event.returnValue = false;
			}
			else
			{
				evt.preventDefault();
			}
		}
	}
	
	if ((intKeyCode == 47))
	{
		if (window.event)
		{
			window.event.returnValue = false;
		}
		else
		{
			evt.preventDefault();
		}
		return;
	}
	
	// Check the key code.
	if (!(intKeyCode > 44 && intKeyCode < 58))
	{
		if (!(intKeyCode == 0 || intKeyCode == 8))
		{
			if (window.event)
			{
				window.event.returnValue = false;
			}
			else
			{
				evt.preventDefault();
			}
		}
	}
	return;
}

//==================================================
// Allow numeric values only.
//==================================================
function AllowNumericOnlyPhone(evt)
{
    evt = window.event ? window.event : evt;

	if (evt == null || evt == undefined)
		return false;
		
	var objSourceElement = evt.srcElement ? evt.srcElement : evt.target;
	var intKeyCode = window.event ? window.event.keyCode : evt.which;

	if ((intKeyCode == 45) || (intKeyCode == 46))
	{
		if (window.event)
		{
			window.event.returnValue = false;
		}
		else
		{
			evt.preventDefault();
		}
		return;
	}

	// Check if the keycode is a plus.
	if (intKeyCode == 43)
	{
		// Check if the source element already contains a minus.
		if (objSourceElement.value.indexOf('+') == -1)
			objSourceElement.value = '+' + objSourceElement.value;
			
		if (window.event)
		{
			window.event.returnValue = false;
		}
		else
		{
			evt.preventDefault();
		}
	}
	
	if ((intKeyCode == 47))
	{
		if (window.event)
		{
			window.event.returnValue = false;
		}
		else
		{
			evt.preventDefault();
		}
		return;
	}
	
	// Check the key code.
	if (!(intKeyCode > 44 && intKeyCode < 58))
	{
		if (!(intKeyCode == 0 || intKeyCode == 8))
		{
			if (window.event)
			{
				window.event.returnValue = false;
			}
			else
			{
				evt.preventDefault();
			}
		}
	}
	return;
}

//==================================================
// Allow number values only.
//==================================================
function AllowNumbersOnly(evt)
{
    evt = window.event ? window.event : evt;

	if (evt == null || evt == undefined)
		return false;
		
	var objSourceElement = evt.srcElement ? evt.srcElement : evt.target;
	var intKeyCode = window.event ? window.event.keyCode : evt.which;

	// Check if the keycode is a minus.
	if ((intKeyCode == 45) || (intKeyCode == 46) || (intKeyCode == 47))
	{
		if (window.event)
		{
			window.event.returnValue = false;
		}
		else
		{
			evt.preventDefault();
		}
	}
	
	// Check the key code.
	if (!(intKeyCode > 44 && intKeyCode < 58))
	{
		if (!(intKeyCode == 0 || intKeyCode == 8))
		{
			if (window.event)
			{
				window.event.returnValue = false;
			}
			else
			{
				evt.preventDefault();
			}
		}
	}
	return;
}

function NumericOnly(evt)
{
	evt = window.event ? window.event : evt;

	if (evt == null || evt == undefined)
		return false;
		
	var intKeyCode = evt.keyCode ? evt.keyCode : evt.which;
	var txtElement = evt.srcElement ? evt.srcElement : evt.target;
	var blnValid = false;

	if ((intKeyCode >= KEYCODE_0 && intKeyCode <= KEYCODE_9))
		blnValid = true;

	var blnDecimals = true;
	if (txtElement.getAttribute("decimals") != null)
	{
		var strDecimals = txtElement.getAttribute("decimals");
		blnDecimals = strDecimals == "1" || strDecimals.toLowerCase() == "yes" || strDecimals.toLowerCase() == "true"
	}

	if (txtElement.value.indexOf(".") == -1 && (intKeyCode == KEYCODE_DECIMAL_1 || intKeyCode == KEYCODE_DECIMAL_2 || intKeyCode == KEYCODE_DECIMAL_3))
	{
		if (blnDecimals == true)
			blnValid = true; 
	}

	if (intKeyCode == KEYCODE_TAB || intKeyCode == KEYCODE_BACKSPACE || intKeyCode == KEYCODE_DOWN || intKeyCode == KEYCODE_LEFT || intKeyCode == KEYCODE_RIGHT || intKeyCode == KEYCODE_UP)
		blnValid = true;

	if (intKeyCode == KEYCODE_DELETE && blnDecimals)
		blnValid = true;

	if (!blnValid)
	{
		evt.cancel = true;
		if (evt.preventDefault)
			evt.preventDefault();
		return false;
	}

	return true;
}

function NumericOnlyNegative(evt)
{
	if (evt == null && window.event)
		evt = window.event;

	if (evt == null || evt == undefined)
		return false;

	var intKeyCode = evt.keyCode ? evt.keyCode : evt.which;
	var txtElement = evt.srcElement ? evt.srcElement : evt.target;
	var blnValid = false;

	if ((intKeyCode >= KEYCODE_0 && intKeyCode <= KEYCODE_9))
		blnValid = true;

	if (txtElement.value.indexOf(".") == -1 && (intKeyCode == KEYCODE_DECIMAL_1 || intKeyCode == KEYCODE_DECIMAL_2 || intKeyCode == KEYCODE_DECIMAL_3))
		blnValid = true;

	if (intKeyCode == KEYCODE_TAB || intKeyCode == KEYCODE_BACKSPACE || intKeyCode == KEYCODE_DELETE || intKeyCode == KEYCODE_DOWN || intKeyCode == KEYCODE_LEFT || intKeyCode == KEYCODE_RIGHT || intKeyCode == KEYCODE_UP)
		blnValid = true;

	if (intKeyCode == KEYCODE_MINUS && txtElement.value.indexOf("-") == -1)
		blnValid = true;

	if (!blnValid)
	{
		evt.cancel = true;
		if (evt.preventDefault)
			evt.preventDefault();
		return false;
	}

	return true;
}

function noPermissionMessage(arrArguments, blnAll)
{
	//remove the first 2 entries (blnAll, blnShowMessage)
	var arrRequiredPermissions = new Array();
	var strRequired = "";
	var intCount = 0;

	for (var intIndex = 2; intIndex < arrArguments.length; intIndex++)
	{
		var intPermissionId = arrArguments[intIndex];
	
		if (hasPermissions(false, false, intPermissionId))
			continue;
	
		if (strRequired != "")
		{
			if (blnAll)
				strRequired += " and ";
			else
				strRequired += " or ";
		}

		intCount++;
		strRequired += intPermissionId;
	}

	var strDetail = "\n\nPlease contact your system administrator if you require access to this area.";

	if (document.location.toString().indexOf("local.") != -1)
	{
		strDetail += "\n\nTo be able to access this area you require permission";

		if (intCount != 1)
			strDetail += "s";
		
		strDetail += ": " + strRequired;
	}

	HtmlPopup.Alert("You do not have sufficient permission to access this resource." + strDetail, "Truckfile", "/images/pinNumber.png");
}

//blnAll = true, return true if user has all the supplied permission ids
//blnAll = false, return true if user has any of the supplied permission ids
//usage: hasPermissions([true|false], [true|false], 1, 2, 3, ...)
function hasPermissions(blnAll, blnShowMessage)
{
	var objUserDetail = getUserDetail();

	if (objUserDetail == null)
		throw new Error("Could not access user details");

	var strPermissions = objUserDetail.Permissions;

	if (!strPermissions)
		throw new Error("Could not access permissions collection on user details");
	
	var arrPermisions = strPermissions.split(',');
	var blnFoundAll = true;

	var intCompanyId = getUserDetail().CompanyId;
	var strUserRoleTypeCode = getUserDetail().XUserRoleTypeCode;

	if (intCompanyId == 1 && strUserRoleTypeCode == "CMP")
		return true;

	var arrArguments = arguments;
	var intOffset = 2;

	if (arguments.length > 2)
	{
		try
		{
			if (arguments[2].length)
			{
				arrArguments = arguments[2];
				intOffset = 0;
			}
		}
		catch (exc) { }
	}

	for (var intCheck = intOffset; intCheck < arrArguments.length; intCheck++)
	{
		var intCheckPermissionId = Number(arrArguments[intCheck]);
		var blnFound = false;
	
		for (var intIndex = 0; intIndex < arrPermisions.length; intIndex++)
		{
			var intPermissionId = Number(arrPermisions[intIndex]);

			if (intPermissionId == intCheckPermissionId)
			{
				blnFound = true;
				break;
			}
		}

		if (blnAll == true)
		{
			if (!blnFound) //could not find this requested permission id in the list of permissions for this user (all are required)
			{
				if (blnShowMessage)
					noPermissionMessage(arguments, blnAll);
			
				return false;
			}
		}
		else
		{
			if (blnFound)
				return true; //found a permission id, and any are required, passes
		}
	}

	//finished scanning, if here has failed for ANY, and passed for ALL
	var blnSuccess = (blnAll == true);

	if (!blnSuccess && blnShowMessage)
		noPermissionMessage(arguments, blnAll);

	return blnSuccess;
}

Date.GetToday = function GetToday()
{
	var dtmNow = new Date();
	var strToday = dtmNow.print("%Y-%m-%dT00:00:00");
	var dtmToday = Date.ToDate(strToday);

	return dtmToday;
}

Date.prototype.ToShortDate = function ToShortDate()
{
	var strDate = this.print("%d/%m/%Y");
	return strDate;
}

Date.prototype.FormatDate = function FormatDate()
{
	var intDay = this.getDate();
	var intMonth = this.getMonth();
	var intYear = this.getFullYear();

	var strMonth = this.GetMonthName();
	var strDate = intDay + " " + strMonth + " " + intYear;

	return strDate;
}

Date.prototype.FormatTime = function FormatTime()
{
	var intHour = this.getHours();
	var intMinute = this.getMinutes().toString();
	var intSecond = this.getSeconds().toString();
	var strAM = "AM";

	if (intHour >= 12)
	{
		intHour -= 12;
		strAM = "PM";
	}
	
	if (intHour == 0)
	{
		intHour = 12;
	}

	if (intMinute.length == 1)
		intMinute = "0" + intMinute;

	if (intSecond.length == 1)
		intSecond = "0" + intSecond;

	var strTime = "";

	strTime = intHour + ":" + intMinute + " " + strAM;

	return strTime;
}

Date.prototype.ToSQL = function ToSQL()
{
	//format into 2005-09-01T00:00:00+01:00
	//			  yyyy-mm-ddTHH:mm:ss

	var intDay = this.getDate();
	var intMonth = this.getMonth() + 1;
	var intYear = this.getFullYear();

	if ((intDay + "").length == 1)
		intDay = "0" + intDay;

	if ((intMonth + "").length == 1)
		intMonth = "0" + intMonth;

	if ((intYear + "").length == 1)
		intYear = "0" + intYear;

	var intHour = this.getHours();
	var intMinute = this.getMinutes();
	var intSecond = this.getSeconds();

	if ((intHour + "").length == 1)
		intHour = "0" + intHour;

	if ((intMinute + "").length == 1)
		intMinute = "0" + intMinute;

	if ((intSecond + "").length == 1)
		intSecond = "0" + intSecond;

	var intOffset = this.getTimezoneOffset();
	intOffset = 0 - intOffset;
	intOffset = intOffset / 60;

	if ((intOffset + "").length == 1)
		intOffset = "0" + intOffset + "00";

	var strSQL = intYear + "-" + intMonth + "-" + intDay;
	strSQL += "T";
	strSQL += intHour + ":" + intMinute + ":" + intSecond;
	strSQL += "+";
	strSQL += intOffset;

	return strSQL;
}

Date.ToDate = function ToDate(strDate)
{
	if (strDate == undefined || strDate == null)
		return null;

	var arrParts = strDate.split('T');
	var strDatePart = arrParts[0];
	var strTimePart = arrParts[1];
	arrParts = strDatePart.split('-');
	var intYear = arrParts[0];
	var intMonth = arrParts[1];
	var intDay = arrParts[2];

	if (!intYear || !intMonth || !intDay)
		return null;

	var intHour = 0;
	var intMinute = 0;
	var intSecond = 0;
	var intOffset = 0;

	if (strTimePart)
	{
		arrParts = strTimePart.split(':');

		intHour = arrParts[0];
		intMinute = arrParts[1];
		intSecond = arrParts[2];

		intOffset = intSecond.split('+')[1];

		intSecond = intSecond.split('+')[0];
	}

	var objDate = null;
	if (intOffset)
		objDate = new Date(intYear, intMonth - 1, intDay, intHour, intMinute, intSecond, intOffset);
	else
		objDate = new Date(intYear, intMonth - 1, intDay, intHour, intMinute, intSecond);
	return objDate;
}

Date.prototype.GetMonthName = function GetMonthName()
{
	switch (this.getMonth())
	{
		case 0: return "January";
		case 1: return "February";
		case 2: return "March";
		case 3: return "April";
		case 4: return "May";
		case 5: return "June";
		case 6: return "July";
		case 7: return "August";
		case 8: return "September";
		case 9: return "October";
		case 10: return "November";
		case 11: return "December";
		default: return "Unknown Month: " + this.getMonth();
	}
}

//Add a trim prototype to the string object because Internet Explorer does not support it natively.
//http://www.whadiz.com/what-is.aspx/programming/javascript/javascript-trim
String.prototype.trim = function trim()
{
	return this.replace(/^\s+|\s+$/g, "");
}

///http://webdevel.blogspot.com/2003/07/javascript-remove-items-from-array.html
Array.prototype.removeItems = function removeItems(itemsToRemove)
{
	if (!/Array/.test(itemsToRemove.constructor))
		itemsToRemove = [itemsToRemove];

	var j;
	for (var i = 0; i < itemsToRemove.length; i++)
	{
		j = 0;
		while (j < this.length)
		{
			if (this[j] == itemsToRemove[i])
				this.splice(j, 1);
			else
				j++;
		}
	}
}

//insert the given item at the given index in the array
Array.prototype.insert = function insert(intIndex, item)
{
	this.splice(intIndex, 0, item);
}

//remove the item at the given index
Array.prototype.removeAt = function removeAt(intIndex)
{
	this.splice(intIndex, 1);
}

function WebserviceError(objError, strMethod, fncCallback)
{
	fncCallback(objError, null, SOAPClient.object);
}

if ("Calendar" in window)
{ } else
{
	window.Calendar = new Object();
}

Calendar.Show = function Show(dtmCurrentDate, elmContent, fncCallback)
{
	if (dtmCurrentDate == null)
		dtmCurrentDate = new Date();

	var cal = new Calendar(1, dtmCurrentDate, fncCallback, function(cal) { cal.hide(); });

	var params = new Array();

	function param_default(pname, def)
	{
		if (typeof params[pname] == "undefined")
			params[pname] = def;
	};

	param_default("inputField", null);
	param_default("displayArea", null);
	param_default("button", null);
	param_default("eventName", "click");
	param_default("ifFormat", "%d %B %Y");
	param_default("daFormat", "%d %B %Y");
	param_default("singleClick", true);
	param_default("disableFunc", null);
	param_default("dateStatusFunc", params["disableFunc"]); // takes precedence if both are defined
	param_default("dateText", null);
	param_default("firstDay", "1");
	param_default("align", "Br");
	param_default("range", [1900, 2999]);
	param_default("weekNumbers", true);
	param_default("flat", null);
	param_default("flatCallback", null);
	param_default("onSelect", fncCallback);
	param_default("onClose", function(cal) { cal.hide(); });
	param_default("onUpdate", fncCallback);
	param_default("date", dtmCurrentDate);
	param_default("showsTime", false);
	param_default("timeFormat", "24");
	param_default("electric", false);
	param_default("step", 2);
	param_default("position", null);
	param_default("cache", false);
	param_default("showOthers", false);
	param_default("multiple", null);

	cal.params = params;
	cal.create(params.flat);

	cal.showsOtherMonths = params.showOthers;
	cal.showsTime = params.showsTime;
	cal.time24 = (params.timeFormat == "24");
	cal.params = params;
	cal.weekNumbers = params.weekNumbers;
	cal.setRange(params.range[0], params.range[1]);
	cal.setDateStatusHandler(params.dateStatusFunc);
	cal.getDateText = params.dateText;
	cal.showAtElement(elmContent, params.align);

	return cal;
}

function Window_OnResize(evt)
{	
	try
	{
		var isInIFrame = (window.location != window.parent.location) ? true : false;
		
		if (isInIFrame)
			return;

		var intMinHeight = 100;

		//if news and stats on page then minHeight = 232;
		var divStats = document.getElementById("stats");
		var divNews = document.getElementById("latestNews");
		var divAdverts = document.getElementById("adverts");

		evt = window.event ? window.event : evt;

		var divScrollingContent = document.getElementById("scrollingContent");
		var divContentHeading = document.getElementById("contentHeading");
		var divNonScrollingFooter = document.getElementById("nonScrollingFooter");
		var divPanels = document.getElementById("panels");

		if (divStats != null && divNews != null)
		{
			if (divPanels == null || divPanels.offsetHeight <= 10)
				intMinHeight = 232;
		}

		var blnGetHeightFromBody = BrowserDetect.browser == "Explorer" || BrowserDetect.browser == "Chrome" || BrowserDetect.browser == "Safari";

		var intWindowHeight = blnGetHeightFromBody ? document.documentElement.clientHeight : window.innerHeight;

		var frmForm = document.getElementById("aspnetForm");
		if (frmForm != null)
			intWindowHeight -= (Number(frmForm.style.marginBottom.replace("px", "")) + 10)

		if (BrowserDetect.browser == "Explorer" && BrowserDetect.version == 6)
			document.getElementById("popupBackground").style.height = intWindowHeight + "px";

		if (BrowserDetect.browser == "Chrome" || BrowserDetect.browser == "Safari")
		{
			if (getUserDetail() == null)
				intWindowHeight += 120;
		}
		
		if (divContentHeading != null || divScrollingContent != null)
		{
			var intContentOffset = divContentHeading != null ? divContentHeading.offsetTop : 0;
			var intBottomPadding = 50;

			if (document.getElementById("copyright") == null)
				intBottomPadding = 15;

			var intScrollingOffset = divScrollingContent != null ? divScrollingContent.offsetTop : 0;

			if (document.getElementById("lr_wrapper") != null)
			{
				intBottomPadding = 80;
				intScrollingOffset = 15;
			}

			var intNonScrollingFooterHeight = divNonScrollingFooter != null ? divNonScrollingFooter.offsetHeight : 0;
			
			if (BrowserDetect.browser != "Explorer" || (BrowserDetect.browser == "Explorer" && BrowserDetect.version >= 8))
				intScrollingOffset = intScrollingOffset - intContentOffset; //scrolling offset is set from the window rather than the parent

			var intContentHeight = intWindowHeight - (intContentOffset + intBottomPadding);

			if (BrowserDetect.browser == "Chrome" || BrowserDetect.browser == "Safari")
			{
				if (getUserDetail() == null)
					intContentHeight -= 120;
			}
			else if (BrowserDetect.browser == "Explorer" && BrowserDetect.version < 8)
			{
				if (getUserDetail() == null)
				{
					if (document.getElementById("rightColumn") != null)
						intContentHeight += 62;
					else
						intContentHeight += 10;
				}
			}

			if (divPanels != null)
			{
				intContentHeight -= divPanels.offsetHeight;

				if (BrowserDetect.browser == "Explorer" && BrowserDetect.version < 8)
				{
					intContentHeight -= 135;

					if (getUserDetail() == null)
						intContentHeight -= 60;
				}
			}

			if (intContentHeight < 50)
				intContentHeight = 50;

			var intScrollingHeight = intContentHeight - intScrollingOffset - intNonScrollingFooterHeight + 6;

			if (intScrollingHeight < intMinHeight)
			{
				var intDifference = intMinHeight - intScrollingHeight;

				intContentHeight += intDifference;
				intScrollingHeight = intMinHeight;				
			}

			if (divContentHeading != null)
				divContentHeading.style.height = (intContentHeight + 3) + "px";
				
			//vehicle documents page	
			if (BrowserDetect.browser == "Explorer" && BrowserDetect.version == 7 && document.getElementById('AddDocument_Schedules') != null && document.getElementById('vehicleDocuments') != null)
				intScrollingHeight = intScrollingHeight - 15;
				
			intScrollingHeight = (blnFullscreen) ? intScrollingHeight + 6 : intScrollingHeight;
			
			// Check the scrolling content object.
			if (divScrollingContent != null)
			{
				var strStep = window.location.pathname.toLowerCase().replace('?back=0', '');
				switch (strStep)
				{
					case '/common/reporting/reports.aspx':
						divScrollingContent.style.height = (intScrollingHeight + 6) + "px";
						break;

					case '/workshop/wizards/newjobsheet.aspx':
					case '/workshop/wizards/convertestimate.aspx':
					case '/workshop/viewjobs.aspx':
					case '/workshop/viewjob.aspx':
					case '/common/adverts.aspx':
					case '/operator/contract.aspx':
					case '/common/notify.aspx':
					case '/templates/':
					case '/common/newvehicledetails.aspx':
					case '/common/scheduling.aspx':
					case '/common/axleconfiguration.aspx':
					case '/common/vehiclefaults.aspx':
					case '/workshop/standardcorrection.aspx':
					case '/support/systemusage/':
					case '/costcenters/index.aspx':
					case '/workshop/assigntasks.aspx':
					case '/audit/templates.aspx':
					case '/audit/scheduleevents.aspx':
					case '/orders/':
					case '/audit/directory.aspx':
					case '/workshopview/':
					case '/workshopview/index.aspx':
					case '/workshopapplication/printjob.aspx':
					case '/vehiclefaults/index.aspx':
					case '/common/safetycheck.aspx':
					case '/reports/index.aspx':
						divScrollingContent.style.height = (intScrollingHeight + 5) + "px";
						break;
						
					case '/workshoploading/':
					case '/workshoploading/index.aspx':
					case '/templates/mytemplates.aspx':
					case '/workshopapplication/printjob.aspx':
					case '/templates/completelist.aspx':
					case '/templates/mastertemplates.aspx':
					case '/searchresults/':
					case '/administration/tyresizes.aspx':
						divScrollingContent.style.height = (intScrollingHeight + 4) + "px";
						break;
						
					case '/operator/tyrewear.aspx':
					case '/common/vehicledocumentslist.aspx':
					case '/templates/vehicleSearchResults.aspx':
						divScrollingContent.style.height = (intScrollingHeight + 3) + "px";
						break;

					default:
						divScrollingContent.style.height = (intScrollingHeight + 8) + "px";
						break;
				}
			}
			
			try
			{
				if (m_objWizard && m_objWizard != null)
					m_objWizard.OnResize();
			}
			
			catch (exc) { }

			try
			{
				if (m_objViewJob)
					m_objViewJob.OnResize();
			}
			catch (exc) { }

			try
			{
				if (m_objCreateInvoices)
					m_objCreateInvoices.OnResize();
			}
			catch (exc) { }

			var scrollingDetails = document.getElementById("scrollingDetails");
			var ScrollDiv = document.getElementById("ScrollDiv");

			try
			{
				if (scrollingDetails != null)
					scrollingDetails.style.height = (intScrollingHeight - 10) + "px";

				if (ScrollDiv != null)
					ScrollDiv.style.height = (intScrollingHeight - 10) + "px";
			}
			catch (exc) { }

			var scrollingContentEscalation = document.getElementById("scrollingContentEscalation");
			
			try
			{
				if (scrollingContentEscalation != null)
					scrollingContentEscalation.style.height = (intContentHeight - 50) + "px";
			}
			catch (exc) { }

			var UserContainer = document.getElementById("UserContainer");

			try
			{
				var intUserHeight = intContentHeight - 70;

				if (intUserHeight < 100)
					intUserHeight = 100;

				if (document.getElementById("divUserList") != null)
					document.getElementById("divUserList").style.height = intUserHeight + "px";

				if (document.getElementById("divUserDetails") != null)
					document.getElementById("divUserDetails").style.height = intUserHeight + "px";

				if (UserContainer != null)
					UserContainer.style.height = intUserHeight + "px";
			}
			catch (exc) { }

			var scrollingContentSchedule = document.getElementById("scrollingContentSchedule");
			
			try
			{
				if (scrollingContentSchedule != null)
				{
					var intOffset = 306;
					if (BrowserDetect.browser == "Chrome" || BrowserDetect.browser == "Safari")
						intOffset += 28;
						
					//IE 7 fix	
					if (BrowserDetect.browser == "Explorer" && BrowserDetect.version == 7)
					{
						intContentHeight = intContentHeight - 13;
					}
				
					scrollingContentSchedule.style.height = (intContentHeight - intOffset) + "px";
				}
			}
			catch (exc) { }

			var scrollingContentWeightList = document.getElementById("scrollingContentWeightList");

			try
			{
				if (scrollingContentWeightList != null)
					scrollingContentWeightList.style.height = (intContentHeight - 70) + "px";
					
				if(document.getElementById("scrollingWeightDetails") != null)
					document.getElementById("scrollingWeightDetails").style.height = (intContentHeight - 70) + "px";
								
			}
			catch (exc) { }

			var scrollingContentCompanyAdmin = document.getElementById("scrollingContentSearchResultsArea");

			try
			{
				if (scrollingContentCompanyAdmin != null)
					scrollingContentCompanyAdmin.style.height = (intContentHeight - 90) + "px";
			}
			catch (exc) { }			

			var scrollingContentVehicle = document.getElementById("scrollingContentVehicle");
			
			try
			{
				if (scrollingContentVehicle != null)
				{
					var vehicleTabs = document.getElementById("vehicleTabs");
					if (vehicleTabs != null)
						scrollingContentVehicle.style.height = (intContentHeight - 70) + "px";
					else
						scrollingContentVehicle.style.height = (intContentHeight + 20) + "px";
				}
			}
			catch (exc) { }

			var scrollingContentDocuments = document.getElementById("scrollingContentDocuments");

			try
			{
				if (scrollingContentDocuments != null)
					scrollingContentDocuments.style.height = (intContentHeight - 98) + "px";
			}
			catch (exc) { }

			var scrollingContentAxle = document.getElementById("scrollingContentAxle");

			try
			{
				if (scrollingContentAxle != null)
					scrollingContentAxle.style.height = (intContentHeight - 120) + "px";
			}
			catch (exc) { }

			var scrollingContentContactMerge = document.getElementById("scrollingContentContactMerge");

			try
			{
				if (scrollingContentContactMerge != null)
					scrollingContentContactMerge.style.height = (intContentHeight - 115) + "px";
			}
			catch (exc) { }
			
			// link to new schedule resize
			try
			{
				if (m_objSchedule != null)
				{
					m_objSchedule.ScheduleScreenResize(intContentHeight);					
				}
			}
			catch (exc) { }

			try
			{
				if (m_objJobPacks != null)
					m_objJobPacks.OnResize();
			}
			catch (exc) { }

			try
			{
				if (Escalation_Resize != null)
					Escalation_Resize();
			}
			catch (exc) { }

			try
			{
				if (m_objStock != null)
					m_objStock.OnResize();
			}
			catch (exc) { }
			
		}

		var divWeekByWeek = document.getElementById("divWeekByWeek");

		if (divWeekByWeek != null)
		{
			// resize this gadget
			var divOutstandingInvoices = document.getElementById("divOutstandingInvoicesWrapper");
			var divLowStock = document.getElementById("divLowStock");
			var divOutstandingOrders = document.getElementById("divOutstandingOrders");
			var lstWeekByWeekWrapper = document.getElementById("lstWeekByWeekWrapper");
			var lstWeekByWeek = document.getElementById("lstWeekByWeek");
			var divSiteAlert = document.getElementById("siteAlert");
			var blnNHI = hasPermissions(false, false, 72);

			if (divOutstandingInvoices != null || divOutstandingOrders != null || divLowStock != null || blnNHI)
			{
				var intGadgetsLine2Height = 0;

				if (divOutstandingInvoices != null)
					intGadgetsLine2Height = divOutstandingInvoices.offsetHeight;
				else if (divLowStock != null)
					intGadgetsLine2Height = divLowStock.offsetHeight;
				else if (divOutstandingOrders != null)
					intGadgetsLine2Height = divOutstandingOrders.offsetHeight;
				else if (blnNHI)
				{
					//operator logged in with NHI gadgets enabled...
					intGadgetsLine2Height = 250; //height of NHI gadgets
				}

				var intWeekByWeekHeight = intWindowHeight - 405; //the height for the gadget
				//intWeekByWeekHeight -= 122;
				intWeekByWeekHeight -= 36;

				if ((BrowserDetect.browser == "Explorer" && BrowserDetect.version < 8))
					intWeekByWeekHeight -= 18;

				if (divSiteAlert != null)
					intWeekByWeekHeight -= divSiteAlert.offsetHeight + 1;

				var intMinWeekByWeekHeight = 150;

				if (intWeekByWeekHeight <= intMinWeekByWeekHeight)
					intWeekByWeekHeight = intMinWeekByWeekHeight;

				if ((BrowserDetect.browser == "Chrome") || (BrowserDetect.browser == "Safari"))
				{
					lstWeekByWeekWrapper.style.height = (intWeekByWeekHeight + 33) + "px";
				} else if (BrowserDetect.browser == "Firefox")
				{
					lstWeekByWeekWrapper.style.height = (intWeekByWeekHeight + 32) + "px";
				}
				else
				{
					if (BrowserDetect.browser == "Explorer" && BrowserDetect.version == 8)
					{
						lstWeekByWeekWrapper.style.height = (intWeekByWeekHeight + 33) + "px";
					}
					else
					{
						if (BrowserDetect.browser == "Explorer" && BrowserDetect.version == 7)
						{
							lstWeekByWeekWrapper.style.height = (intWeekByWeekHeight + 51) + "px";
						}
						else
						{
							lstWeekByWeekWrapper.style.height = (intWeekByWeekHeight + 32) + "px";
						}
					}
				}
			}
			else
			{
				var intWeekByWeekHeight = intWindowHeight - 38; //the height for the gadget
				intWeekByWeekHeight -= 130;

				if (divSiteAlert != null)
					intWeekByWeekHeight -= divSiteAlert.offsetHeight + 4;

				var intMinWeekByWeekHeight = 150;

				if (divAdverts != null)
					intMinWeekByWeekHeight += 125;

				if (intWeekByWeekHeight <= intMinWeekByWeekHeight)
					intWeekByWeekHeight = intMinWeekByWeekHeight;

				lstWeekByWeekWrapper.style.height = (intWeekByWeekHeight + 10) + "px";
			}
		}

		//call resize news
		try
		{
			if (m_objAlerts)
				m_objAlerts.OnResize(true);
		}
		catch (exc) { }

		//call resize adverts
		try
		{
			if (m_objAdverts)
				m_objAdverts.OnResize(true);
		}
		catch (exc) { }

		//contacts appear in two areas crashes on popup version
		try
		{
			var lstContact = document.getElementById("lstContact");

			if (lstContact != null)
				lstContact.style.height = (intScrollingHeight - 23) + "px";

		}
		catch (exec) { }

		var axleConfiguration = document.getElementById("axleConfiguration");

		if (axleConfiguration != null)
		{
			var intSetHeight = intScrollingHeight - 8;
			var intPaddingTop = 2;

			if (intSetHeight < 323)
				intSetHeight = 323;
			else
			{
				intPaddingTop = intScrollingHeight - 8;
				intPaddingTop -= 323;

				if (intPaddingTop > 0)
				{
					intPaddingTop = intPaddingTop / 2;
					intSetHeight -= intPaddingTop;
				}

				if (intPaddingTop < 2)
					intPaddingTop = 2;
			}

			axleConfiguration.style.paddingTop = intPaddingTop + "px";
			axleConfiguration.style.height = intSetHeight + "px";
		}

		try
		{
			if (m_objUploadsGraph != null)
				m_objUploadsGraph.OnResize();
		}
		catch (exc) { }

		try
		{
			if (objTemplate != null)
				objTemplate.Resize();
		}
		catch (exc) { }

		try
		{
			if (objCompleteList != null)
				objCompleteList.Resize();
		}
		catch (exc) { }

		try
		{
			if (CostCenter != null)
				CostCenter.Resize();
		}
		catch (exc) { }

		try
		{
			if (m_objPlantOptions != null)
				m_objPlantOptions.OnResize();
		}
		catch (exc) { }

		try
		{
			if (GoogleMap && GoogleMap.OnResize)	
				GoogleMap.OnResize();
		}
		catch (exc) { }

		try
		{
			if (m_objFleet)
				m_objFleet.OnResize();
		}
		catch (exc) { }
		
		/* Fixed pages */
		try
		{
			if (WorkshopLoading)
				WorkshopLoading.OnResize();
		}
		catch (exc) { }
		
		try
		{
			if (UserManagement)
				UserManagement.OnResize();
		}
		catch (exc) { }
		
		try
		{
			if (ConfigureInvoice)
				ConfigureInvoice.OnResize();
		}
		catch (exc) { }
		
		try
		{
			if (WorkshopView)
				WorkshopView.OnResize();
		}
		catch (exc) { }

		try
		{
			if (Reports)
				Reports.OnResize();
		}
		catch (exc) { }
		
		//IE6 Fixes
		if(BrowserDetect.browser == "Explorer" && BrowserDetect.version == 6)
		{
			//IE6 Popup Fixes
			if(document.getElementById('PopupIE6Fix') != null)
			{
				document.getElementById('aspnetForm').style.overflow = 'scroll';
				document.getElementById('aspnetForm').style.height = (intWindowHeight - 10) + 'px';
				document.getElementById('aspnetForm').style.width = '99%';
				document.getElementById('buttons').style.marginTop = (intWindowHeight) + 'px';
			}
		}
		
		if (window.navigator.userAgent.indexOf('iPad') > -1)
		{
			document.addEventListener('touchmove', function(e){ e.preventDefault(); });

			if (document.getElementById('lstWeekByWeek') != null)
				WeekByWeekScroll = new iScroll(document.getElementById('lstWeekByWeek'), {checkDOMChanges:false});
		}
	}
	catch (exc)
	{
		HtmlPopup.Error(exc);
	}
}

//==================================================
// Page unload event handler.
//==================================================
function Page_UnLoad()
{
	blnPageUnLoading = true;

	try
	{
		if (WorkshopLoading)
			WorkshopLoading.Page_UnLoad();
	}
	catch (exc) { }
	
	try
	{
		if (ConfigureInvoice)
			ConfigureInvoice.Page_UnLoad();
	}
	catch (exc) { }
	
	try
	{
		if (OutstandingInvoices)
			OutstandingInvoices.Page_UnLoad();
	}
	catch (exc) { }
	
	try
	{
		if (LowStock)
			LowStock.Page_UnLoad();
	}
	catch (exc) { }
	
	try
	{
		if (OutstandingOrders)
			OutstandingOrders.Page_UnLoad();
	}
	catch (exc) { }
	
	try
	{
		if (VehicleDocumentsList)
			VehicleDocumentsList.Page_UnLoad();
	}
	catch (exc) { }
	
	try
	{
		if (Orders)
			Orders.Page_UnLoad();
	}
	catch (exc) { }
	
	try
	{
		if (MyDetails)
			MyDetails.Page_UnLoad();
	}
	catch (exc) { }

	try
	{
		if (Reports)
			Reports.Page_UnLoad();
	}
	catch (exc) { }

	return;
}

function doInvokeWeekByWeekItemSelected(intVehicleDocumentsId, intScheduleEntryId, intVehicleId, scheduleOptions, intJobSheetId, intStatusId, strScheduleDate)
{
	try
	{
		if (typeof(ScheduleEntryOptions) == "undefined")
		{
			if (confirm("You must be on the dashboard to be able to perform this action.\n\nDo you want to go to your dashboard now?"))
			{
				Navigate("/common/loginRedirect.aspx", false, null);
			}
		}
		else
			InvokeWeekByWeekItemSelected(intVehicleDocumentsId, intScheduleEntryId, intVehicleId, scheduleOptions, intJobSheetId, intStatusId, strScheduleDate);
	}
	catch (exc)
	{
		HtmlPopup.Error(exc);
	}
}

//===================================================================
// Display the report.
//===================================================================
function DisplayReport(HTML)
{
	var objWindow = OpenWindow('/Workshop/Report.htm', '', 'location=no,menubar=no,resizable=yes,scrollbars=yes,status=no,titlebar=yes,toolbar=no');

	if (objWindow != null)
	{
		objWindow.document.open();
		objWindow.document.write(HTML);
		objWindow.document.close();
	}
}

//===================================================================
// Exit the application, invoked from the workshop application.
//===================================================================
function ExitApplication()
{
	window.close();
}

//===================================================================
// Return the detail of the error
//===================================================================
function GetErrorDetail(exc)
{
	if (exc && exc == null)
		return "unknown";

	var strMessage = "";
	if (exc.message)
	{
		strMessage = exc.message;
	}
	else
	{
		if (exc != null)
		{
			for (var strPrp in exc)
			{
				if (strMessage != "")
					strMessage += "; ";

				strMessage += strPrp + " = '" + exc[strPrp] + "'";
			}

			strMessage = strMessage;
		}
		else
			strMessage = 'Exception object is null';
	}

	var strHost = document.location.protocol + '//' + document.location.host;

	if (exc.fileName)
		strMessage += ' in ' + exc.fileName.substring(strHost.length);
	else if (exc.sourceURL)
		strMessage += ' in ' + exc.sourceURL.substring(strHost.length);

	if (exc.lineNumber)
		strMessage += ' line: ' + exc.lineNumber;
	else if (exc.line)
		strMessage += ' line: ' + exc.line;

	var strStack = '';
	try
	{
		strStack = exc.stack ? exc.stack : '';

		var arrLines = strStack.split('\n');
		strStack = '';

		for (var intIndex = 1; intIndex < arrLines.length; intIndex++)
		{
			if (strStack != '')
				strStack += '\n';
		
			strStack += arrLines[intIndex].replace('@' + strHost, ' at ').replace(':', ' line: ');
		}
	}
	catch (exc1) { }

	if (strStack == '')
	{
		try
		{
			if (exc.fileName)
				strStack = exc.filename.replace(strHost, '');
			else if (exc.sourceURL)
				strStack = exc.sourceURL.replace(strHost, '');
			else
				strStack = '';

			if (exc.lineNumber)
				strStack += ' line: ' + exc.lineNumber;
			else if (exc.line)
				strStack += ' line: ' + exc.line;
		}
		catch (exc1) { }
	}

	var strDetail = strMessage;
	//strStack = strStack.replace(/</g, '&lt;');
	//strStack = strStack.replace(/>/g, '&gt;');

	if (strStack != '')
		strDetail += '\n\n' + strStack;
	return strDetail;
}

function IsMobileBrowser()
{
	if (BrowserDetect.browser == "Safari")
	{
		if (BrowserDetect.version == "an unknown version")
		{
			document.getElementById("popupBackground").style.visibility = "hidden"; //browser does not support opacity
			return true;
		}
		else if (BrowserDetect.version == "4")
			return true;
	}

	return false;
}

//=====================================================================
// validEmailAddress checks that the email is address is valid
//=====================================================================
function validEmailAddress(strEmailAddress)
{
	//rules:
	//1. Must contain an @ character
	//2. Must contain a . character
	//3. The @ character must not be the first or last character in the string
	//4. The . character must not be the first or last character in the string
	//5. only 1 @ character can exist
	//6. Only uses letters, numbers, . and @ (spaces not allowed)
	//7. . cannot be immediately before or after the @
	//8. Must not be blank
	//9. Must be at least 2 letters after the last .
	//10. character '.' cannot appear 2 or more times consecutively
	//11. Must contain at least 1 . after the @

	//rule 8;
	if (strEmailAddress == "")
		return false;

	var arrAllowedChars = new Array("a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "0", ".", "@", "-", "_");

	//rule 1;
	if (strEmailAddress.indexOf("@") == -1)
		return false;

	//rule 2;
	if (strEmailAddress.indexOf(".") == -1)
		return false;

	//rule 3;
	if (strEmailAddress.indexOf("@") == 0 || strEmailAddress.charAt(strEmailAddress.length - 1) == "@")
		return false;

	//rule 4;
	if (strEmailAddress.indexOf(".") == 0 || strEmailAddress.charAt(strEmailAddress.length - 1) == ".")
		return false;

	//rule 9;
	if (strEmailAddress[strEmailAddress.length - 1] == "." || strEmailAddress.charAt(strEmailAddress.length - 2) == ".")
		return false;

	//rule 7;
	if (strEmailAddress.indexOf("@.") != -1 || strEmailAddress.indexOf(".@") != -1)
		return false;

	//rule 10;
	if (strEmailAddress.indexOf("..") != -1)
		return false;

	var blnIllegalChars = false;
	var intAtCount = 0; //number of @ characters
	strEmailAddress = strEmailAddress.toLowerCase();
	
	//rule 6 and 5
	for (var intIndex = 0; intIndex < strEmailAddress.length; intIndex++)
	{
		var chrLetter = strEmailAddress.substring(intIndex, intIndex + 1);
		var blnFound = false;
		
		for (var intLetter = 0; intLetter < arrAllowedChars.length; intLetter++)
		{
			var chrValid = arrAllowedChars[intLetter];

			if (chrValid == chrLetter)
			{
				blnFound = true;
				break;
			}
		}

		if (blnFound == false)
		{
			//chrLetter is not a valid letter
			return false; //rule 6
		}

		if (chrLetter == "@")
			intAtCount++;

		if (intAtCount > 1)
			return false; //rule 5
	}

	var strDomain = strEmailAddress.substring(strEmailAddress.indexOf("@") + 1);

	if (strDomain.indexOf(".") == -1)
		return false; //rule 11

	return true;
}

//=====================================================================
// validEmailAddress checks that the telephone number is valid
//=====================================================================
function validTelephoneNumber(strTelephoneNumber)
{
	//rules:
	//1: must only contain valid characters
	//2: must be at least 10 letters
	//3: cannot contain + more than once
	//4: must start with 0 or +

	if (strTelephoneNumber == "")
		return true;

	var arrAllowedChars = new Array("0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "+", " ");

	var blnIllegalChars = false;
	var intPlusCount = 0;
	strTelephoneNumber = strTelephoneNumber.toLowerCase();

	//rule 1
	for (var intIndex = 0; intIndex < strTelephoneNumber.length; intIndex++)
	{
		var chrLetter = strTelephoneNumber.substring(intIndex, intIndex + 1);

		if (intIndex == 0)
		{
			if (chrLetter != '0' && chrLetter != '+')
				return false; //rule 4
		}

		var blnFound = false;

		for (var intLetter = 0; intLetter < arrAllowedChars.length; intLetter++)
		{
			var chrValid = arrAllowedChars[intLetter];

			if (chrValid == chrLetter)
			{
				blnFound = true;
				break;
			}
		}

		if (blnFound == false)
		{
			//chrLetter is not a valid letter
			return false; //rule 1
		}

		if (chrLetter == '+')
			intPlusCount++;

		if (intPlusCount > 1)
			return false; // rule 3
	}

	if (strTelephoneNumber.length < 11)
		return false; //rule 2

	return true;
}

//====================================================
// Check the validity of the email address as it changes
//====================================================
function txtEmailChanged(evt)
{
	try
	{
		evt = window.event ? window.event : evt;
		var target = evt.srcElement ? evt.srcElement : evt.target;
		validateEmailAddress(target, false);
	}
	catch (exc)
	{
		HtmlPopup.Error(exc);
	}
}

//====================================================
// Check the validity of the telephone number as it changes
//====================================================
function txtTelephoneNumberChanged(evt)
{
	try
	{
		evt = window.event ? window.event : evt;
		var target = evt.srcElement ? evt.srcElement : evt.target;
		validateTelephoneNumber(target);
	}
	catch (exc)
	{
		HtmlPopup.Error(exc);
	}
}

//====================================================
// Update the view to show valid/invalid email in the input
//====================================================
function validateEmailAddress(txtInput, blnModify)
{
	try
	{
		var strEmail = txtInput.value;
		var blnOptional = false;

		if (txtInput.getAttribute("optional") != null)
		{
			var strOptional = txtInput.getAttribute("optional").toLowerCase();
			blnOptional = (strOptional == "true" || strOptional == "yes" || strOptional == "on");
		}

		var blnValid = false;
		if (blnOptional && strEmail == "")
			blnValid = true;
		else
		{
			if (blnModify)
			{
				strEmail = strEmail.trim();
				txtInput.value = strEmail;
			}
			
			blnValid = validEmailAddress(strEmail);
		}
		
		txtInput.className = blnValid ? "email" : "email invalid";
		return blnValid;
	}
	catch (exc)
	{
		HtmlPopup.Error(exc);
	}
}

//====================================================
// Update the view to show valid/invalid telephone in the input
//====================================================
function validateTelephoneNumber(txtInput, UpdateClass)
{
	try
	{
		var strTelephoneNumber = txtInput.value;
		var blnOptional = true;

		if (txtInput.getAttribute("optional") != null)
		{
			var strOptional = txtInput.getAttribute("optional").toLowerCase();
			blnOptional = !(strOptional == "false" || strOptional == "no" || strOptional == "off");
		}

		var blnValid = validTelephoneNumber(strTelephoneNumber);
		if (!blnOptional && txtInput.value == "")
			blnValid = false;

		var blnUpdateClass = (UpdateClass == undefined) ? true : UpdateClass;
		
		if (blnUpdateClass)
			txtInput.className = blnValid ? "email" : "email invalid";
		return blnValid;
	}
	catch (exc)
	{
		HtmlPopup.Error(exc);
	}
}

//====================================================
// Encode a url
//====================================================
function urlEncode(strURL)
{
	strURL = strURL.replace(/%/g, "%25");
	strURL = strURL.replace(/&/g, "%26");
	
	return strURL;
}

//====================================================
// Decode a url
//====================================================
function urlDecode(strURL)
{
	strURL = strURL.replace(/%26/g, "&");
	strURL = strURL.replace(/%20/g, " ");
	strURL = strURL.replace(/%3F/g, "?");
	strURL = strURL.replace(/%3D/g, "=");
	strURL = strURL.replace(/%25/g, "%");
	
	return strURL;
}

//====================================================
// Try to open a popup window with the popup wrapper, show a message if unsuccessful
//====================================================
function OpenPopup(strURL, strName, strOptions, strPopupOptions)
{
	if (!strOptions || strOptions == null)
		strOptions = "resizable=1,scrollbars=1";

	strURL = "/common/popup/?url=" + urlEncode(strURL);
	
	if (arguments.length >= 4)
	{
	    // Check if there are any popup options.
	    if (strPopupOptions != '')
		    strURL += "&" + strPopupOptions;
	}

	return OpenWindow(strURL, strName, strOptions);	
}

//====================================================
// Try to open a popup window, show a message if unsuccessful
//====================================================
function OpenWindow(strURL, strName, strOptions)
{
	if (!strOptions || strOptions == null)
		strOptions = "resizable=1,scrollbars=1";
		
	strName = "";
	
	var strForwardUserID = '0';
	
	try
	{
		strForwardUserID = objUserDetail['UserId'];
	}
	catch(e)
	{
	}

    // Add the user's ID to the URL.	
	strURL = strURL + ((strURL.indexOf('?') == -1) ? '?' : '&') + 'userid=' + strForwardUserID;

	var objWindow = window.open(strURL, strName, strOptions);

	if (objWindow == null)
		HtmlPopup.Alert("The requested popup could not be openned.\nA popup blocker might be stopping it from openning.\nDisable your popup blocker and try again.");

	return objWindow;
}

function CrossBrowser() { }
CrossBrowser.URL = "/webservices/common.asmx";
CrossBrowser.Method = "CrossDomainRequest";

//====================================================
// Perform a AJAX call to a different website (this runs on the server)
//====================================================
CrossBrowser.invoke = function invoke(strURL, strMethod, objParams, blnAsync, fncCallback, objSender, strNamespace)
{
	var strRequest = objParams.toXml();

	var params = new SOAPClientParameters();
	params.add("strURL", strURL);
	params.add("strMethod", strMethod);
	params.add("strNamespace", strNamespace);
	params.add("strRequest", strRequest);

	return SOAPClient.invoke(CrossBrowser.URL, CrossBrowser.Method, params, blnAsync, fncCallback, objSender);
}

//====================================================
// Get and display the browser information on screen
//====================================================
function DisplayBrowserInformation()
{
	try
	{
		var strInformation = GetBrowserInformation();
		var strHeading = "Please provide the below information as requested:\n\n";

		var objButtons = new Object();
		objButtons["Close"] = "CLOSE";
		//objButtons["Send to Support"] = fncEmailDetail;
		
		HtmlPopup.Confirm(strHeading + strInformation, objButtons, "Support Information", "/images/truckfile32.png");
	}
	catch (exc)
	{
		HtmlPopup.Error(exc);
	}
	return false;
}

//====================================================
// Get and return the browser information on screen
//====================================================
function GetBrowserInformation()
{
	try
	{
		var strInformation = '';

		var strOperatingSystem = BrowserDetect.OS;
		var strDotNet = getDotNet(navigator.userAgent, ', ');
		var blnOnline = navigator.onLine;
		var strPage = document.location.pathname;
		var strQuery = document.location.search;
		//var blnSilverlightInstalled = isSilverlightInstalled(true);
		var strUserName = 'Not Logged In';
		var strBrowser = (BrowserDetect.browser == 'Explorer' ? 'Internet Explorer' : BrowserDetect.browser) + ' ' + BrowserDetect.version;
		var strEmail = "";

		if (getUserDetail() != null)
		{
			strUserName = getUserDetail()['UserName'];
			strEmail = ' (' + getUserDetail()['EmailAddress'] + ')';
		}

		strInformation += 'Browser: ' + strBrowser + '\n';
		strInformation += 'Operating System: ' + strOperatingSystem + '\n';
		//strInformation += '.NET Versions: ' + strDotNet + '\n';
		strInformation += 'Screen Size: ' + screen.width + ' x ' + screen.height + '\n';
		strInformation += 'User: ' + strUserName + strEmail + '\n';
		strInformation += 'Page: ' + strPage + '\n';
		strInformation += 'Query: ' + (strQuery == '' ? 'None' : strQuery) + '\n';
		//strInformation += 'Silverlight: ' + (blnSilverlightInstalled ? 'Yes' : 'No') + '\n';
		strInformation += 'Online: ' + (blnOnline ? 'Yes' : 'No') + '\n';
		if (getUserDetail() != null)
		{
			strInformation += 'UserId: ' + getUserDetail()['UserId'] + '\n';
			strInformation += 'CompanyId: ' + getUserDetail()['CompanyId'] + '\n';
			strInformation += 'Role: ' + getUserDetail()['XUserRoleTypeCode'] + '\n';
		}

		return strInformation;
	}
	catch (exc)
	{
		return "Unable to get information: " + exc.message;
	}
}

//====================================================
// Email the information to support
//====================================================
function fncEmailDetail(evt, objPopup, btnEmail)
{
	try
	{
		var strInformation = GetBrowserInformation();
		var strTo = "SUPPORT";
		var strSubject = "Support Information";

		strInformation = "<body style=\"font-family: 'Tahoma';font-size: 8pt;\"><h2>Support Information</h2>" + strInformation + "</body>";

		var params = new SOAPClientParameters();
		params.add("strTo", strTo);
		params.add("strSubject", strSubject);
		params.add("strHTML", strInformation);

		btnEmail.disabled = true;
		btnEmail.className = "button wide disabled";

		WaitWindow.Show("Sending, please wait...");

		SOAPClient.invoke("/webservices/newDesign.asmx", "SendEmail", params, true, EmailSent, [objPopup, btnEmail]);
	}
	catch (exc)
	{
		btnEmail.disabled = false;
		btnEmail.className = "button wide";
		WaitWindow.Hide();
		HtmlPopup.Error(exc);
	}
}

function EmailSent(strXML, docXML, arrSender)
{
	var objPopup = arrSender[0];
	var btnEmail = arrSender[1];

	try
	{
		if (typeof (strXML) == "object" && strXML != null)
			throw new Error(docXML);

		HtmlPopup.Alert("Information successfully sent.");
		objPopup.Close();
	}
	catch (exc)
	{
		HtmlPopup.Error(exc);
	}
	finally
	{
		btnEmail.disabled = false;
		btnEmail.className = "button wide";
		WaitWindow.Hide();
	}
}

function getOS(strUserAgent)
{
	var arrParts = strUserAgent.split('(');
	var strDetail = arrParts[1];

	arrParts = strDetail.split(';');
	var strOS = arrParts[2];

	alert(arrParts);

	strOS = strOS.replace("NT 5.2", "2003 Server");
	strOS = strOS.replace("NT 5.1", "XP");
	strOS = strOS.replace("NT 5", "2000");

	strOS = strOS.replace("NT 6.1", "7");
	strOS = strOS.replace("NT 6", "Vista");

	if (strOS.indexOf("Mac OS X") != -1)
		strOS = "Mac OS X";

	return strOS;
}

function getDotNet(strUserAgent, strDelimiter)
{
	var arrParts = strUserAgent.split('(');
	var strDetail = arrParts[1];

	arrParts = strDetail.split(';');

	var strDotNet = "";

	for (var intIndex = 3; intIndex < arrParts.length; intIndex++)
	{
		var strPart = arrParts[intIndex];

		if (strPart.indexOf(" .NET CLR ") == 0)
		{
			strPart = strPart.substring(10);

			strPart = strPart.substring(0, 3);

			if (strDotNet != "")
				strDotNet += strDelimiter;
			
			strDotNet += strPart;
		}
	}

	if (strDotNet == "")
		strDotNet = "Unknown";

	return strDotNet;
}

function document_KeyUp(evt)
{
	try
	{
		evt = window.event ? window.event : evt;
		var intKeyCode = evt.keyCode ? evt.keyCode : evt.which;

		if (intKeyCode == KEYCODE_F1)
		{
			// Display the help documents.
			DisplayHelpDocument();

			// Cancel any event bubble.
			Functions.CancelBubble();
		}

		if ((intKeyCode == KEYCODE_F9) || (intKeyCode == KEYCODE_Q && evt.ctrlKey == true))
			DisplayBrowserInformation();

		Session.ExtendSession();
	}
	catch (exc)
	{
		//HtmlPopup.Error(exc);
	}
}

function document_MouseUp(evt)
{
	try
	{
		Session.ExtendSession();
	}
	catch (exc)
	{
		//HtmlPopup.Error(exc);
	}
}

function ExtendSession()
{
	try
	{
		Session.ExtendSession();
	}
	catch (exc)
	{
		HtmlPopup.Error(exc);
	}
}

function DoExtendSession()
{
	try
	{
		if (document.getElementById("Session") == null)
			return;	

		Session.ExtendSession();
	}
	catch (exc)
	{
		HtmlPopup.Error(exc);
	}
}

var m_blnForceNavigation = false;
var m_strNavigationWaitWindow = null;
var m_blnUnloadAttached = false;

function Navigate(strURL, blnForce, strWaitWindowMessage)
{
	try
	{
		if (m_blnUnloadAttached == false)
		{
			m_blnUnloadAttached = true;
			if (window.attachEvent)
				window.attachEvent("onunload", window_Unload);
			else
				window.addEventListener("unload", window_Unload, false);
		}
	
		m_blnForceNavigation = blnForce;

		if (!strWaitWindowMessage || strWaitWindowMessage == "" || strWaitWindowMessage == null)
			strWaitWindowMessage = "Please Wait";

		m_strNavigationWaitWindow = strWaitWindowMessage;

		document.location = strURL;

		return true;
	}
	catch (exc)
	{
		WaitWindow.Hide();
		return false;
	}
}

function window_Unload(evt)
{
	try
	{
		if (m_strNavigationWaitWindow != null && m_strNavigationWaitWindow != "")
			WaitWindow.Show(m_strNavigationWaitWindow);
	}
	catch (exc)
	{
		WaitWindow.Hide();
	}
}

//==========================================
// Prepare the auto complete request
//==========================================
function VehicleAutoComplete_PrepareRequest(objSource, objAutoComplete, params)
{
	try
	{
		if (objAutoComplete == null)
			return false;

		var strSearch = objAutoComplete.Input.value;
		var intSearchType = objSource["SearchType"];

		if (intSearchType == 1)
		{
			if (strSearch.length < 3)
				return false;

			objSource.ColumnName = "RegistrationNumber";
		}
		else if (intSearchType == 2)
		{
			if (strSearch.length < 14)
				return false;

			objSource.ColumnName = "ChassisNumber";
		}

		params.add("strSearchTerm", strSearch);
		params.add("intSearchType", intSearchType);
		params.add("strAutoComplete", "true");

		return true;
	}
	catch (exc)
	{
		HtmlPopup.Error(exc);
		return false;
	}
}

//==========================================
// Modify an entry
//==========================================
function VehicleAutoComplete_ModifyEntry(aData, strData)
{
	try
	{
		aData.setAttribute("vehVisible", "false");
		var blnShowUnlinkedVehicles = false;

		//is this vehicle visible to the company?
		if (strData.indexOf("*") != -1)
		{
			//visible to the customer
			strData = strData.substring(0, strData.length - 1);
			aData.innerHTML = strData;

			aData.setAttribute("vehVisible", "true");
		}
		else if (blnShowUnlinkedVehicles == false)
		{
			return false;
		}
	}
	catch (exc)
	{
		HtmlPopup.Error(exc);
	}
	return strData;
}

//==========================================
// SetCookie.
//==========================================
function SetWSCookie(Name, Value, ExpireDays)
{
	try
	{
		localStorage.setItem(Name, Value);
//		if ((ExpireDays == undefined) || (ExpireDays == null))
//			ExpireDays = 1;
//	
//		var _Date = new Date();

//		_Date.dateAdd('d', ExpireDays);
//		document.cookie = "WS_" + Name + "=" + escape(Value) + ((ExpireDays==null) ? "" : ";expires=" + _Date.toGMTString()) + ";path=/;domain=truckfile.co.uk";
	}
	catch(e)
	{
		alert('ERROR: SetWSCookie(): Unable to set local storage item.');
	}
	return;
}

//==========================================
// GetCookie.
//==========================================
function GetWSCookie(Name)
{
	try
	{
		return localStorage.getItem(Name);
//		c_name = "WS_" + Name;
//		
//		// Check if there are any cookies.
//		if (document.cookie.length>0)
//		{
//			c_start=document.cookie.indexOf(c_name + "=");
//			if (c_start!=-1)
//			{
//				c_start=c_start + c_name.length+1;
//				c_end=document.cookie.indexOf(";",c_start);
//				if (c_end==-1) c_end=document.cookie.length;
//					return unescape(document.cookie.substring(c_start,c_end));
//			}
//		}
	}
	catch(e)
	{
		alert('ERROR: GetWSCookie(): Unable to find local storage item.');
	}
	return undefined;
}

//==========================================
// Document viewer.
//==========================================
function DocumentViewer(URL, FileName, VehicleDocumentsID)
{
	// Check if the user is viewing a job.
	if (URL.toString().indexOf('ViewJob.aspx') > 0)
	{
		window.location = URL;
		return;
	}

	// Replace any commas.
	FileName = FileName.replace(/,/gi, '&#44;');
	FileName = FileName.replace(/=/gi, '&#61;');
	
	WaitWindow.Show('Loading document, please wait...');
	
	var soapClient = new SoapClient();
	soapClient.AddParameter('Value', escape('DocumentType=File,DocumentSource=' + FileName + ',VehicleDocumentsID=' + ((VehicleDocumentsID == undefined) ? 0 : VehicleDocumentsID)));
	soapClient.SendRequest('/WebServices/Common.asmx', 'http://www.truckfile.co.uk/', 'SetSessionVariable', DocumentViewerLauncher);
	return;
}

//==========================================
// Document viewer by vehicle document.
//==========================================
function DocumentViewerByVehicleDocument(VehicleDocumentsID, StoragePath)
{
	WaitWindow.Show('Loading document, please wait...');

	var soapClient = new SoapClient();
	soapClient.AddParameter('Value', escape('DocumentType=File,DocumentSource=' + StoragePath + ',VehicleDocumentsID=' + VehicleDocumentsID));
	soapClient.SendRequest('/WebServices/Common.asmx', 'http://www.truckfile.co.uk/', 'SetSessionVariable', DocumentViewerLauncher);
	return;
}

//==========================================
// Document viewer by schedule ID.
//==========================================
function DocumentViewerBySchedule(ScheduleEntryID, VehicleDocumentsID)
{
	WaitWindow.Show('Loading document, please wait...');
	
	var soapClient = new SoapClient();
	soapClient.AddParameter('ScheduleEntryID', ScheduleEntryID);
	soapClient.AddParameter('VehicleDocumentsID', VehicleDocumentsID);
	soapClient.SendRequest('/WebServices/Common.asmx', 'http://www.truckfile.co.uk/', 'DocumentViewerBySchedule', DocumentViewerBySchedule_Completed);
	return;
}

//==========================================
// Document viewer by schedule soap completed.
//==========================================
function DocumentViewerBySchedule_Completed(Response)
{
	var aResponse = Response.split('|');
	
	// Check if an error occured.
	if (aResponse[0] == 'ERROR')
	{
		WaitWindow.Hide();
		HtmlPopup.Error(aResponse[1]);
		return;
	}
	
	var soapClient = new SoapClient();
	soapClient.AddParameter('Value', escape('DocumentType=File,DocumentSource=' + aResponse[2] + ',VehicleDocumentsID=' + aResponse[1]));
	soapClient.SendRequest('/WebServices/Common.asmx', 'http://www.truckfile.co.uk/', 'SetSessionVariable', DocumentViewerLauncher);
	return;
}

//==========================================
// Document viewer by job sheet.
//==========================================
function DocumentViewerByJobSheet(JobSheetId, VehicleDocumentsID)
{
	WaitWindow.Show('Loading document, please wait...');
	
	var soapClient = new SoapClient();
	soapClient.AddParameter('Value', escape('DocumentType=JobSheetId,DocumentSource=' + JobSheetId + ',VehicleDocumentsID=' + ((VehicleDocumentsID == undefined) ? 0 : VehicleDocumentsID)));
	soapClient.SendRequest('/WebServices/Common.asmx', 'http://www.truckfile.co.uk/', 'SetSessionVariable', DocumentViewerLauncher);
	return;
}

//==========================================
// Document viewer by job sheet labour.
//==========================================
function DocumentViewerByJobSheetLabourXr(JobSheetId, JobSheetLabourId)
{
	WaitWindow.Show('Loading document, please wait...');
	
	var soapClient = new SoapClient();
	soapClient.AddParameter('Value', escape('DocumentType=JobSheetLabourId,DocumentSource=' + JobSheetId + ',JobSheetLabourId=' + JobSheetLabourId));
	soapClient.SendRequest('/WebServices/Common.asmx', 'http://www.truckfile.co.uk/', 'SetSessionVariable', DocumentViewerLauncher);
	return;
}

//==========================================
// Document viewer by invoice.
//==========================================
function DocumentViewerByInvoice(InvoiceId, VehicleDocumentsID)
{
	WaitWindow.Show('Loading document, please wait...');
	
	var soapClient = new SoapClient();
	soapClient.AddParameter('Value', escape('DocumentType=Invoice,DocumentSource=' + InvoiceId + ',VehicleDocumentsID=' + ((VehicleDocumentsID == undefined) ? 0 : VehicleDocumentsID)));
	soapClient.SendRequest('/WebServices/Common.asmx', 'http://www.truckfile.co.uk/', 'SetSessionVariable', DocumentViewerLauncher);
	return;
}

//==========================================
// Document viewer launcher.
//==========================================
function DocumentViewerLauncher(Response)
{
	var aResponse = Response.split('|');
	
	// Check if an error occured.
	if (aResponse[0] == 'ERROR')
	{
		WaitWindow.Hide();
		HtmlPopup.Error(aResponse[1]);
		return;
	}
	
	var intWidth = 900;
	var intHeight = 600
	var intTop = (window.screen.availHeight / 2) - (intHeight / 2);
	var intLeft = (window.screen.availWidth / 2) - (intWidth / 2);
	
	// Check the browser.
	switch (BrowserDetect.browser)
	{
		case 'Explorer':
			intTop = intTop - 35;
			break;
			
		case 'FireFox':
			intTop = intTop - 35;
			break;
			
		case 'Safari':
		case 'Chrome':
			intTop = intTop - 38;
			intHeight = intHeight + 5;
			break;
	}
	
	// Open the document viewer.
	var winDocument = window.open('/Common/DocumentViewer.aspx?uid=' + aResponse[1], null, 'location=no,menubar=no,resizable=no,scrollbars=no,status=no,toolbar=no,width=' + intWidth + ',height=' + intHeight);
	
	// Check if the window has been opened.
	if (winDocument == null)
	{
		WaitWindow.Hide();
		Functions.DisplayMessage('Unfortunately the document was unable to load because you need to allow this website in your popup blocker settings. Please contact your system administrator, NOT Truckfile support, for more information.', 'Window Blocked', 'Information');
	}
	else
	{
		winDocument.focus();
	}
	return;
}

//==========================================
// Document loaded.
//==========================================
function DocumentLoaded()
{
	WaitWindow.Hide();
	return;
}

//==========================================
// Count the number of words entered into a HTML element.
//==========================================
function WordCount(Element)
{
	var strValue = Element.value;
	var intCount = 0;
	
	// Get the words
	var aWords = strValue.replace(/\s/g,' ');
	aWords = strValue.replace(/\W/g,' ');
	aWords = aWords.split(' ');
	
	// Check the length of the matching words.
	for (var intCounter = 0; intCounter < aWords.length; intCounter++)
	{
		if (aWords[intCounter].length > 1)
			intCount++;
	}
	
	return intCount;
}

//====================================================
// NavigateToMyDetails
//====================================================
function NavigateToMyDetails()
{
	if(!LeavingPage(this,1, NavigateToMyDetails))
		return;
			
	Navigate('/MyDetails.aspx', true, 'Loading \'My Details\', please wait...');
	return;
}

//==================================================
// check if leaving page
//==================================================
function LeavingPage(element, redirectPage, retryFunction, navigateURL)
{		
	elmLeavingElement = element;
	fncLeavingRetry = null;
	strLeavingUrl = null;
	
	if(blnIndexStopPageUnload == true)
	{
		var objButtons = new Object();			
		objButtons['Yes - Return to page'] = 'CLOSE';
		
		//check if the element wants to redirect
		if(redirectPage)
		{
			//if there is a retry function fire that
			if(retryFunction != null)
			{
				fncLeavingRetry = retryFunction;
				objButtons['No - I want to leave this page'] = LeavePageRetry;
			}
			
			if(navigateURL != null)
			{
				strLeavingUrl = navigateURL;
				objButtons['No - I want to leave this page'] = LeavePageRetry;
			}
			
			if(navigateURL == null && retryFunction== null)
				objButtons['No - I want to leave this page'] = LeavePageRedirect;
		}
		else
			objButtons['No - I want to leave this page'] = LeavePageRetry;
		
		Functions.DisplayPrompt("There are unsaved items on this page, do you want to go back to save these details?", 'Details Unsaved', 'Question', objButtons, undefined);
		return false;
	}
	
	return true;
}

//==================================================
// leaving the page and forwarding by element type
//==================================================
function LeavePageRedirect()
{
	blnIndexStopPageUnload = false;
	
	switch(elmLeavingElement.tagName)
	{
		case 'A':
			window.location = elmLeavingElement;
		break;
	}
	
	elmLeavingElement = null;
	return;
}

//==================================================
// try the function after clicking that the user wants to leave
//==================================================
function LeavePageRetry()
{
	blnIndexStopPageUnload = false;
	elmLeavingElement = null;
	
	if(fncLeavingRetry != null)
		fncLeavingRetry();
	
	if(strLeavingUrl != null)
		window.location = strLeavingUrl;
	
	return;
}

//==================================================
// Display the help document for the current page.
//==================================================
function DisplayHelpDocument()
{
	try
	{
		// Check if the user object exists.
		if (objUserDetail == null)
			return;
	
		// Set the page for the help document.
		var soapClient = new SoapClient();
		soapClient.AddParameter('Page', escape(window.location.pathname));
		soapClient.SendRequest('/WebServices/HelpSystem.asmx', 'http://www.truckfile.co.uk/', 'SetPageForHelpDocument', SetPageForHelpDocument);
	}
	catch (exc)
	{
		// Check if a popup blocker has stopped the window from opening.
		if (exc.message.indexOf('focus') > 0)
		{
			WaitWindow.Hide();
			Functions.DisplayMessage('Unfortunately the help document was unable to load because you need to allow this website in your popup blocker settings. Please contact your system administrator, NOT Truckfile support, for more information.', 'Window Blocked', 'Information');
			return;
		}

		WaitWindow.Hide();
		HtmlPopup.Error(exc);
	}
	return;
}

//==================================================
// Set page soap handler.
//==================================================
function SetPageForHelpDocument(Response)
{
	try
	{
		var aResponse = Response.split('|');

		// Check if an error occured.
		if (aResponse[0] == 'ERROR')
		{
			Functions.ResponseError(aResponse[1]);
			return;
		}

		// Display the help document.
		var winHelpDocument = window.open('/HelpDocument.aspx', 'winHelpDocument', 'location=no,menubar=no,resizable=yes,scrollbars=yes,status=no,toolbar=no,width=950,height=600');
			
		// Check if the window has been opened.
		if (winHelpDocument == null)
		{
			Functions.DisplayMessage('Unfortunately the help document was unable to load because you need to allow this website in your popup blocker settings. Please contact your system administrator, NOT Truckfile support, for more information.', 'Window Blocked', 'Information');
		}
		else
		{
			winHelpDocument.focus();
		}
	}
	catch (exc)
	{
		// Check if a popup blocker has stopped the window from opening.
		if (exc.message.indexOf('focus') > 0)
		{
			WaitWindow.Hide();
			Functions.DisplayMessage('Unfortunately the help document was unable to load because you need to allow this website in your popup blocker settings. Please contact your system administrator, NOT Truckfile support, for more information.', 'Window Blocked', 'Information');
			return;
		}

		WaitWindow.Hide();
		HtmlPopup.Error(exc);
	}
	return;
}

//==================================================
// Linked account link handler.
//==================================================
function LinkedAccountImpersonate(Name, Email)
{
	try
	{
		// Check the email address.
		if (Email == '')
		{
			Functions.DisplayMessage('Unable to switch accounts.', 'Switch Accounts', 'Error');
			return;
		}

		strSwitchAccountName = Name;
		strSwitchAccountEmail = Email;
			
		var objButtons = new Object();
		objButtons['Yes'] = btnSwitchAccountsYes_Click;
		objButtons['No'] = 'CLOSE';
			
		Functions.DisplayPrompt('Are you sure that you want to switch to the \'' + Name + '\' account?', 'Switch Accounts', 'Question', objButtons, undefined);
	}
	catch (exc)
	{
		WaitWindow.Hide();
		HtmlPopup.Error(exc);
	}
	return;
}

//==================================================
// Switching account Yes button handler.
//==================================================
function btnSwitchAccountsYes_Click()
{
	try
	{
		WaitWindow.Show("Switching account, please wait...");
			
		var soapClient = new SoapClient();
		soapClient.AddParameter('Email', strSwitchAccountEmail);
		soapClient.SendRequest('/WebServices/NewDesign.asmx', 'http://www.truckfile.co.uk/', 'SwitchAccount', SwitchAccount_Completed);
	}
	catch (exc)
	{
		WaitWindow.Hide();
		HtmlPopup.Error(exc);
	}
	return;
}

//==================================================
// Impersonate soap completed handler.
//==================================================
function SwitchAccount_Completed(Response)
{
	try
	{
		var aResponse = Response.split('|');
		var strErrorCode = '';

		// Check if an error occured.
		if (aResponse[0] == 'ERROR')
		{
			strErrorCode = '0x0';

			if (aResponse[1].indexOf('incorrect email address and/or password') > -1)
				strErrorCode = '0x1';

			if (aResponse[1].indexOf('subscription') > -1)
				strErrorCode = '0x2';

			WaitWindow.Hide();
			Functions.DisplayMessage('There was an error whilst trying to switch accounts (Error code: ' + strErrorCode + '). Please contact your system administrator if you continue to receive this message.', 'Switch Account Error', 'Information');
			return;
		}

		Navigate("/common/loginRedirect.aspx", true, "Account switch successful, please wait...");
	}
	catch (exc)
	{
		WaitWindow.Hide();
		HtmlPopup.Error(exc);
	}
	return;
}
