var BaseURL = 'http://' + window.location.hostname;
var ver = 0;
var DialogBoxHeightFix = 0;
var Window = null;
var Platform = '2000_XP';
var PlatformDistro = 'Generic';
var AppName = 'Mozilla';
var blnShowTimeoutAlert = true;

//==========================================
// PlatformBrowserInfo.
//==========================================
function PlatformBrowserInfo()
{
	// Get the operating system.
	if (window.navigator.userAgent.indexOf('Linux') > 0)
	{
		Platform = 'Linux';

		// Get the linux distro.
		if (window.navigator.userAgent.indexOf('rv:1.8.1.9') > 0)
			PlatformDistro = 'Xandros';
	}
	
	// Check the version of windows.
	if (window.navigator.userAgent.indexOf('NT6') > 0)
	{
		Platform = 'Vista';
	}
		
	// Get the browser.
	if (window.navigator.userAgent.indexOf('MSIE') > 0)
		AppName = 'IE';

	return;
}

//==========================================
// Check browser version.
//==========================================
function CheckVersion()
{
	try
	{
	    ver = InternetExplorerVersion();

	    // Check the version.
	    if ( ver > -1 )
	    {
		    // Check if the version is less than seven.
		    if ( Math.abs(ver) < 7 )
			    DialogBoxHeightFix = 28;
	    }
	}
	catch (e)
	{
		ErrorMessage.HandleError(e);
	}
	
	return;
}

//==========================================
// Top level menu item selected.
//==========================================
function InternetExplorerVersion()
{
  var rv = -1; // Return value assumes failure.

  if (navigator.appName == 'Microsoft Internet Explorer')
  {
    var ua = navigator.userAgent;
    var re  = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");
    
    if (re.exec(ua) != null)
      rv = parseFloat( RegExp.$1 );
  }
  return rv;
}

//==========================================
// WaitWindow.
//==========================================
function WaitWindow(Message, State)
{
	try
	{
		// Check if Smartflow is running inside an external application.
		if (Window && Window() && Window().External)
		{
			if (Message == undefined)
				State = true;

			document.getElementById('WaitWindowMessage').innerHTML = '';
			document.getElementById('WaitWindow').className = 'WaitWindowHide';
		
			WindowState(State);
			window.external.WaitWindowMessageText = Message;
			return;
		}
	
		// Check the message text.
		if (Message == undefined)
			Message = '';
	
		// Check if there is a message.
		if (Message == '')
		{
			// No message.
			document.getElementById('WaitWindow').className = 'WaitWindowHide';
			
			try
			{
				if (State == null)
					State = true;

				WindowState(State);
			}
			catch(e)
			{
				// Do nothing.
			}
			return;
		}

		try
		{
			WindowState(false);
		}
		catch(e)
		{
			// Do nothing.
		}

		// There is a message.
		document.getElementById('WaitWindowMessage').innerHTML = Message;
		document.getElementById('WaitWindow').className = 'WaitWindowShow';
	}
	catch(e)
	{
		if (e.stack)
			alert("ERROR: WaitWindow(): \n" + e.message + "\n\n" + e.stack);
		else
			alert("ERROR: WaitWindow(): \n" + e.message);
	}
	return;
}

//==========================================
// WindowFocus.
//==========================================
function WindowFocus()
{
	try
	{
		if (Window != null)
			Window.focus();
	}
	catch(e)
	{
		// Do nothing.
	}
	return;
}

//=====================================================================
// Remove items from a listbox.
//=====================================================================
function ListBox_ClearAll(ListBox)
{
	// Remove all items from the listbox.
	while (ListBox.length > 0)
	{
		ListBox.options.remove((ListBox.length - 1));
	}
	return;
}

//=====================================================================
// Add options to a listbox.
//=====================================================================
function ListBox_AddItem(ListBox, Value, Text)
{
	var optn = document.createElement("OPTION");
	optn.text = Text;
	optn.value = Value;
	ListBox.options.add(optn);
	return;
}

//=====================================================================
// BindListBoxData.
//=====================================================================
function BindListBoxData(ListBox, IncludeBlankRecord, recordset, Name, Value, Tag, FilterColumn, FilterValue, FilterEvaluator)
{
	var Counter = 0;
	var AddOption = true;

	if(recordset != null)
	recordset.MoveFirst();
	
	// Remove the existing options.
    if (ListBox.options.remove)
    {
        while (ListBox.length > 0)
        {
	            ListBox.options.remove((ListBox.length - 1));
	    }
	}
	else
	{
	    ListBox.options.length = 0;
    }
	
	// Check if the recordset is null.
	if (recordset == null)
	{
		// There are no options.
		if (ListBox.length == 0)
		{
			var optn = document.createElement("OPTION");
			optn.text = 'No values to select';
			optn.value = -1;
			ListBox.options.add(optn);
			ListBox.disabled = true;
		}
		return;
	}

	// Add a blank option to the list.
	if (IncludeBlankRecord != false)
	{
		var optn = document.createElement("OPTION");
		
		if (IncludeBlankRecord.toLowerCase() == 'true')
		{
			optn.text = '';
		}
		else
		{
			optn.text = IncludeBlankRecord;
		}
		
		optn.value = 0;
		ListBox.options.add(optn);
	}

	// Add the new options.
	try
	{
		var Values = Value.split('+');
		var Names = Name.split('+');

		while (!recordset.EOF())
		{
			var AddOption = true;
			
			Counter++;
			
			// Check if there is a filter column.
			try
			{
				if (FilterColumn != undefined)
				{
					// Check the value of the filter column.
					if (FilterColumn != '')
					{
						// Check if the current row matches the filter option.
						switch (FilterEvaluator)
						{
							case '<':
								AddOption = eval(recordset[FilterColumn] < FilterValue);
								break;
								
							case '>':
								AddOption = eval(recordset[FilterColumn] > FilterValue);
								break;
								
							case '<=':
								AddOption = eval(recordset[FilterColumn] <= FilterValue);
								break;
								
							case '>=':
								AddOption = eval(recordset[FilterColumn] >= FilterValue);
								break;
																
							case '=':
								AddOption = eval(recordset[FilterColumn] == FilterValue);
								break;
							
							case '!=':	
							default:
								AddOption = !eval(recordset[FilterColumn] != FilterValue);
								break;
						}
					}
				}
			}
			catch(e)
			{
				ErrorMessage.HandleError(e.description + '\n\nFilter column: ' + FilterColumn);
				break;
			}
			
			// Check if the option can be added.
			if (AddOption)
			{
				var optn = document.createElement("OPTION");

				if (Names.length == 1)
				{
					optn.text = recordset[Name];
				}
				else
				{
					for(var FieldCounter = 0; FieldCounter < Names.length; FieldCounter++)
					{
						if (optn.text != '')
							optn.text = optn.text + ', ';
							
						var optName = Names[FieldCounter].split(':');
						optn.text = optn.text + optName[0] + ': ' + recordset[optName[1]];
					}
				}
				
				// Check if an ID column is being used or a simple record position counter.
				if (Value == '_RecordPosition')
				{
					optn.value = Counter;
				}
				else
				{
					if (Values.length == 1)
					{
						optn.value = recordset[Value];
					}
					else
					{
						optn.value = "";
					
						for(var FieldCounter = 0; FieldCounter < Values.length; FieldCounter++)
						{
							if (optn.value != '')
								optn.value = optn.value + '/';

							var optValue = Values[FieldCounter].split(':');
							optn.value = optn.value + recordset[optValue[1]];
						}
					}
				}
				
				// Check if the tag item is defined.
				if (Tag != undefined)
				{
					if (Tag != '')
						optn.tag = recordset[Tag];
				}

				ListBox.options.add(optn);
			}
			
			recordset.MoveNext();
		}
		
		ListBox.disabled = false;
	}
	catch(e)
	{
		// Remove the existing options.
		while (ListBox.length > 0)
		{
			ListBox.options.remove((ListBox.length - 1));
		}
		
		var optn = document.createElement("OPTION");
		optn.text = 'No values to select';
		optn.value = -1;
		ListBox.options.add(optn);
		ListBox.disabled = true;
		return;
	}
	
	// Check if there are any options.
	if (ListBox.length == 0)
	{
		var optn = document.createElement("OPTION");
		optn.text = 'No values to select';
		optn.value = -1;
		ListBox.options.add(optn);
		ListBox.disabled = true;
	}
	return;
}

//=====================================================================
// AllowNumericOnly.
//=====================================================================
function AllowNumericOnly(TextBox)
{
	// Check the keycode.
	if (!(window.event.keyCode > 45 && window.event.keyCode < 58))
		window.event.returnValue = false;
	return;
}

//=====================================================================
// DisableField.
//=====================================================================
function DisableField(event)
{
	// Check the version.
	if (window.event)
	{
		event.returnValue = false;
	}
	else
	{
		event.preventDefault();
	}
	return;
}

//=====================================================================
// NumericField.
//=====================================================================
function NumericField(event)
{
	// Check if the window is running in locked mode.
	if (window.top.Locked)
	{
		if (window.event)
		{
			event.returnValue = false;
		}
		else
		{
			event.preventDefault();
		}
		return;
	}
	
	// Check the version.
	if (window.event)
	{
		if (!(window.event.keyCode > 45 && window.event.keyCode < 58))
			event.returnValue = false;
	}
	else
	{
		if (!(event.which > 45 && event.which < 58))
			event.preventDefault();
	}
	return;
}

//=====================================================================
// MoveListBoxItems.
//=====================================================================
function MoveListBoxItems(FromListBox, ToListBox, ItemArray)
{
	// Check if the ItemArray has been passed.
	if (ItemArray == undefined)
		var ItemArray = new Array();
		
	// Find which items are selected.
	for(var Counter = 0; Counter < FromListBox.length; Counter++)
	{
		// Check if the item is selected.
		if (FromListBox[Counter].selected)
		{
			try
			{
				FromListBox[Counter].index = Counter;
			}
			catch (exc) { }
			FromListBox[Counter].deleted = false;
			ItemArray[ItemArray.length] = FromListBox[Counter];
			
			// The item is selected, add it to the 'To' list box.
			var optn = document.createElement("OPTION");
			optn.text = FromListBox[Counter].text;
			optn.value = FromListBox[Counter].value;
			ToListBox.options.add(optn);
		}
	}
	
	// Remove the items.
	for(var Counter = (ItemArray.length - 1); Counter >= 0; Counter--)
	{
		if (!FromListBox[Counter].deleted)
		{
			FromListBox[Counter].deleted = true;
			FromListBox.remove(ItemArray[Counter].index);
		}
	}
	
	return;
}

//==========================================
// GetQueryStringValue.
//==========================================
function GetQueryStringValue(Name, strURL)
{
	var strURL = arguments.length == 1 ? window.location.search : strURL;
	var QueryString = strURL.replace(/%26/g, "&").substring(1).split('&');

	try
	{
		for (var Counter = 0; Counter <= QueryString.length; Counter++)
		{
			var QueryStringKey = QueryString[Counter].split('=');

			if (QueryStringKey[0].toUpperCase() == Name.toUpperCase())
				return QueryStringKey[1];
		}
	}
	catch(e)
	{
		// Do nothing.
	}

	for (var intIndex = 0; intIndex < QueryString.length; intIndex++)
	{
		var strValue = QueryString[intIndex];
		if (strValue.indexOf("?") != -1)
		{
			var strNewURL = strValue.substring(strValue.indexOf("?"), strValue.length);
			return GetQueryStringValue(Name, strNewURL);
		}
	}
	
	return "";
}

//==========================================
// RoundNumber.
//==========================================
function RoundNumber(Value, Points)
{
	if (Value > 8191 && Value < 10485)
	{
		Value = Value - 5000;
		var ReturnValue = Math.round(Value * Math.pow(10, Points)) / Math.pow(10, Points);
		ReturnValue = ReturnValue + 5000;
	}
	else
	{
		var ReturnValue = Math.round(Value * Math.pow(10, Points)) / Math.pow(10, Points);
	}
	
	return ReturnValue;
}

//==========================================
// Session_OnLoad.
//==========================================
function Session_OnLoad()
{
	// Check if the session has timed out.
	if (!TimeOutMessage())
	{
		//window.top.status = new Date().getHours() + ':' + new Date().getMinutes() + ', session timeout in ' + getElement('SessionTimeOut').value + ', ' + window.top.ApplicationName;
		window.setTimeout('window.location.reload();', document.getElementById('SessionTimeOut').value);
	}
	return;
}

//==========================================
// TimeOutMessage.
//==========================================
function TimeOutMessage()
{
	// Check if the users session has timed out.
	if ((document.getElementById('TimeOut').value == 'true'))
	{
		window.top.status = 'Your session has timed out and you have to log back in';
		window.top.WaitWindow('Your session has timed out and you have to log back in, please wait...');
		window.top.location = '/?timedout=1';
		
		if (blnShowTimeoutAlert == true)
			alert('Your session has timed out and you have to log back in.');
	}
	return false;
}

//==========================================
// SessionTimeOut.
//==========================================
function SessionTimeOut()
{
	try
	{
		document.getElementById("Session").contentWindow.location.reload(true);
	}
	catch(e)
	{
		alert("ERROR: SessionTimeOut(): Unable to reload session window.\n" + e.message);
	}
	return;
}

//==========================================
// SetCookie.
//==========================================
function SetCookie(Name, Value, ExpireDays)
{
	try
	{
		var _Date = new Date();

		_Date.dateAdd('d', ExpireDays);
		document.cookie = Name + "=" + escape(Value) + ((ExpireDays==null) ? "" : ";expires=" + _Date.toGMTString()) + ";path=/";
	}
	catch(e)
	{
		alert('ERROR: SetCookie(): Unable to set cookie value.');
	}
	return;
}

//==========================================
// GetCookie.
//==========================================
function GetCookie(Name)
{
	try
	{
		// Check if there are any cookies.
		if (document.cookie.length > 0)
		{
			var aCookies = unescape(document.cookie).split('; ');
			
			// Loop through the cookies and try and match the passed name.
			Name = '|' + Name;
			for (var Cookie in aCookies)
			{
				aCookies[Cookie] = '|' + aCookies[Cookie];
				if (aCookies[Cookie].indexOf(Name) == 0)
				{
					return aCookies[Cookie].substring((aCookies[Cookie].indexOf('=') + 1));
				}
			}
		}
	}
	catch(e)
	{
		alert('ERROR: GetCookie(): Unable to find cookie.');
	}
	return "";
}

//==========================================
// StoreData.
//==========================================
function StoreData(Name, Value)
{
	try
	{
		document.getElementById(Name).value = escape(Value);
	}
	catch(e)
	{
		alert('ERROR: StoreData(): Unable to find \'' + Name + '\' storage field.');
	}
	return;
}

//===============================================================
// Resize event handler.
//===============================================================
function OnResize(Container, OffSet)
{
	// Check if the container was found.
	if (Container != null)
	{
		var winWidth, winHeight, d=document;
		
		if (typeof window.innerWidth!='undefined')
		{
			winWidth = window.innerWidth;
			winHeight = window.innerHeight;
		}
		else if ( d.documentElement && typeof d.documentElement.clientWidth!='undefined' && d.documentElement.clientWidth!=0 )
		{
			winWidth = d.documentElement.clientWidth;
			winHeight = d.documentElement.clientHeight;
		}
		else if ( d.body && typeof d.body.clientWidth!='undefined')
		{
			winWidth = d.body.clientWidth;
			winHeight = d.body.clientHeight;
		}
		
		Container.style.height = winHeight - OffSet + 'px';
	}
	return;
}

//===============================================================
// Cancel event bubbling.
//===============================================================
function CancelBubble(Event)
{
	if (document.body.addEventListener)
	{
		Event.preventDefault();
		Event.stopPropagation();
	}
	else
	{
		if (window.event)
		{
			window.event.returnValue = false;
			window.event.cancelBubble = true;
		}
		else
		{
			Event.returnValue = false;
			Event.cancelBubble = true;
		}
	}
	return false;
}
