﻿function handleWindowError() 
{
	return true;
}

/*
- Opens and centres a non modal resizable window
-
*/
function openWindow(url, name, height, width)
{
    var x = 0, y = 0;

    // Co-ordinates to centre window
    x = (window.screen.width - width) / 2;
    y = (window.screen.height - height) / 2;

    var loginWin = window.open(url, name, 'titlebar=no,height=' + height + ',width=' + width + ',resizable=no');

    loginWin.moveTo(x, y);
}

/*
-- Uses a hit test to determine if a control will have the focus after an event has been fired.
--
*/
function eventFocusedOnControl(e, control)
{
    var left, top;
    var h, w, x, y;

    try 
    {
        // Control co-ordinates
        left = new Number(control.offsetLeft);
        top = new Number(control.offsetTop);

        // Control dimensions
        h = new Number(control.clientHeight);
        w = new Number(control.clientWidth);

        // Event co-ordinates
        x = e.x;
        y = e.y;

        // Was the control the location of the event ?
        if (x >= left && x <= (left + w) &&
            y >= top && y <= (top + h)) 
        {
            return true;
        }

        return false;
    }
    catch (Err) 
    {
        return false;
    }
}

/*
- Validates the length of a postcode. The textbox containing the postcode is assumed
- to contain only integers.
*/
function validatePostcode(textboxID) 
{
    var textbox = findTextBox(0, textboxID);

    if (textbox != null && trim(textbox.value).length > 0)
    {
        if (textbox.value.length != 4)
        {
            alert('Postcode is invalid - it must be four digits in length');
            textbox.select();
            return false;
        }
    }

    return true;
}

/*
- Cancels an Ajax callback
-
*/
function CancelAsyncPostBack() 
{
	var prm = Sys.WebForms.PageRequestManager.getInstance();

    if (prm.get_isInAsyncPostBack()) 
    {
      prm.abortPostBack();
    }
}

/*
- Forces title case in a textbox
-
*/
function titleCaseOnly(textbox)
{
	var allWords = textbox.value.split(" ");		// All words in the textbox
	var changeWord;									// Change a word - true or false
	var x;
	
	// These words are not subject to title case processing
	var ignoreWords = new Array('and', 'the', 'to', 'for', 'is', 'in', 'a', 'at', 'an', 'from', 'by', 'if', 'of');
	
	for (i = 0; i < allWords.length; i++) 
	{
		// Always capitalise the first word
		if (i == 0) 
		{
			allWords[i] = (allWords[i].substring(0, 1)).toUpperCase() + allWords[i].substring(1).toLowerCase();
		}
		else 
		{ 
			changeWord = true;
			
			for (x = 0; x < ignoreWords.length; x++)
			{
				if (ignoreWords[x].indexOf(allWords[i]) > -1) 
				{
					changeWord = false;
					break;
				}
		  	}
		  	
		  	// Capitalise the word if it is not in the list of words to ignore
		  	if (changeWord)
		  	{
		  		allWords[i] = (allWords[i].substring(0,1)).toUpperCase() + allWords[i].substring(1).toLowerCase();
		  	}
		}
	}
	
	textbox.value = allWords.join(' ');
}

/*
- Indicates if all of the cells in a table row are empty.
-
*/
function isTableRowEmpty(row)
{
	var endTagIdx;			// character index of the first enclosing tag '>'
	var valueIdx;			// character index of ' value='

	for (var c = 0; c < row.cells.length; c++)
	{
		// The ' value=' string must occur before the end of the first enclosing tag
		valueIdx = row.cells[c].innerHTML.indexOf(' value=');
		endTagIdx = row.cells[c].innerHTML.indexOf('>');
		if (valueIdx > -1 && valueIdx < endTagIdx)
		{
			return false;
		}
	}

	return true;
}

/*
- Sets alpha characters to upper case as they are entered.
-
*/
function toUpperCase(e)
{
	// lower case alpha
	if (e.keyCode >= 97 & e.keyCode <= 122) 
	{
		e.keyCode -= 32;
	}
}

/*
- Sets alpha characters to lower case as they are entered.
-
*/
function toLowerCase(e) 
{
    // Upper case alpha
    if (e.keyCode >= 65 & e.keyCode <= 92) 
    {
        e.keyCode += 32;
    }
}

/*
- Only allow allow a-z, A-Z, ' ' and <backspace> to be entered into a control as per a
- telephone number.
-
- e				The onkeypress event in the textbox control.
- textbox		The textbox control where the string is being entered.
-
*/
function alphaOnly(e, textbox)
{
	//     <backspace>		       space				 a - z								  A - Z
	if (e.keyCode != 8 & e.keyCode != 32 & (e.keyCode < 97 | e.keyCode > 122) & (e.keyCode < 65 | e.keyCode > 90))
	{
		e.keyCode = '\0';
	}
}

/*
- Only allow allow a-z, A-Z, and <backspace> to be entered into a control as per a login name
-
- e				The onkeypress event in the textbox control.
- textbox		The textbox control where the string is being entered.
-
*/
function alphaNoSpaceOnly(e, textbox) 
{
    //     <backspace>		           a - z	  						    A - Z
    if (e.keyCode != 8 & (e.keyCode < 97 | e.keyCode > 122) & (e.keyCode < 65 | e.keyCode > 90)) {
        e.keyCode = '\0';
    }
}

/*
- Only allow allow a-z, A-Z, 0-9 and <backspace> to be entered into a control.
-
- e				The onkeypress event in the textbox control.
- textbox		The textbox control where the string is being entered.
-
*/
function alphaNumericOnly(e, textbox) 
{
    //     <backspace>	     		   a - z								A - Z                               0 - 9
    if (e.keyCode != 8 & (e.keyCode < 97 | e.keyCode > 122) & (e.keyCode < 65 | e.keyCode > 90) & (e.keyCode < 48 | e.keyCode > 57)) 
    {
        e.keyCode = '\0';
    }
}

/*
- Only allow allow 0-9, ' ' and <backspace> to be entered into a control as per a
- telephone number.
-
- e				The onkeypress event in the textbox control.
- textbox		The textbox control where the number is being entered.
-
*/
function telephoneOnly(e, textbox)
{
	//     <backspace>		       space				 0 - 9
	if (e.keyCode != 8 & e.keyCode != 32 & (e.keyCode < 48 | e.keyCode > 57))
	{
		e.keyCode = '\0';
	}
}

/*
- Performs basic email address validation
-
*/
function validateEmail(emailTextbox) 
{
    var st = 0;
    var fnd = 0;
    var cntr = 0;

    if (emailTextbox.value == null || emailTextbox.value.length == 0) 
    {
        return true;
    }

    // Check for the existence of a single '@'
    while (fnd != -1) 
    {
        fnd = emailTextbox.value.indexOf('@', st);
        if (fnd > -1) 
        {
            cntr++;
        }
        else 
        {
            break;
        }
        st = fnd + 1;
    };

    if (cntr != 1) 
    {
        alert('Email address is not valid');
        emailTextbox.select();
        return false;
    }

    fnd = 0;
    cntr = 0;
    st = 0;

    // Check for the existence of two periods
    while (fnd != -1) 
    {
        fnd = emailTextbox.value.indexOf('.', st);
        if (fnd > -1) 
        {
            cntr++;
        }
        else 
        {
            break;
        }
        st = fnd + 1;
    };

    if (cntr == 0) 
    {
        alert('Email address is not valid');
        emailTextbox.select();
        return false;
    }
}

/*
- Force the use of the Ajax calendar control in populating a date
- textbox. Call when the onkeyup event occurs
- 
*/
function forceCalendarUse(e, textbox)
{

	if (e.keyCode != 9) 
	{
		alert('Please enter the date using the calendar'); 
		textbox.value = '\0';
	}
}

/*
- Only allow allow 0-9, '.' and <backspace> to be entered into a control.
-
- e				The onkeypress event in the textbox control.
- textbox		The textbox control where the number is being entered.
- precision		How many decimal places are allowed for the entered value.
-
*/
function floatOnly(e, textbox)
{
	// Only one decimal point may be entered
	if (textbox.value.indexOf('.') > -1 && e.keyCode == 46)
	{
		e.keyCode = '\0';
		return;
	}
	
	// Prevent a decimal point in the first position
	if (e.keyCode == 46 && textbox.value.length == 0)
	{
		e.keyCode = '\0';
	}

	//               '.'      <backspace>				0 - 9
	if (e.keyCode != 46 & e.keyCode != 8 & (e.keyCode < 48 | e.keyCode > 57))
	{
		e.keyCode = '\0';
	}
}

/*
- Only allow allow 0-9 and <backspace> to be entered into a control.
-
- e		The onkeypress event in the edit control.
-
*/
function intOnly(e)
{
	//     <backspace>				0 - 9
	if (e.keyCode != 8 & (e.keyCode < 48 | e.keyCode > 57))
	{
		e.keyCode = '\0';
	}
}

/*
- Clears all edit fields on a page.
-
- legendLabelID		A label that is used as a 'legend' near the bottom of the page to explain
-					the meaning of the '*' character.
-
*/
function clearAllEditFields(legendLabelID)
{
	var controls;
	var i;
	
	// TextBoxes
	controls = document.getElementsByTagName('input');
	for (i = 0; i < controls.length; i++)
	{
		// Ignore buttons
		if (controls[i].type == 'submit' || controls[i].type == 'button' || controls[i].type == 'hidden' || controls[i].className == 'TextBoxHidden')
		{
			continue;
		}
	
		controls[i].value = '';
	}

	// DropDownLists
	controls = document.getElementsByTagName('select');
	for (i = 0; i < controls.length; i++)
	{
		controls[i].selectedIndex = -1;
	}
	
	// CheckBoxes
	controls = document.getElementsByTagName('checkbox');
	for (i = 0; i < controls.length; i++)
	{
		controls[i].checked = false;
	}
	
	// Spans that are required field labels
	controls = document.getElementsByTagName('span');
	for (i = 0; i < controls.length; i++)
	{
		if (controls[i].innerText == '*')
		{
			controls[i].innerText = '';
		}
	}
	
	// Labels that are required field labels
	controls = document.getElementsByTagName('label');
	for (i = 0; i < controls.length; i++)
	{
		if (controls[i].innerText == '*')
		{
			controls[i].innerText = '';
		}
	}
	
	// Hide the legend label
	var span = findSpanOrLabel(legendLabelID)
	if (span != null)
	{
		span.innerText = '';
	}
}

/*
- Clears all edit controls on a page ignoring controls whose id's have been passed to
- the function in the 1 dimensional ignoreControlsArray argument.
-
- legendLabelID		A label that is used as a 'legend' near the bottom of the page to explain
-					the meaning of the '*' character.
-
*/
function clearAllEditFieldsExcept(legendLabelID, ignoreControlsArray)
{
	var controls;
	var i;
	
	// TextBoxes
	controls = document.getElementsByTagName('input');
	for (i = 0; i < controls.length; i++)
	{
		// Ignore buttons
		if (controls[i].type == 'submit' || controls[i].type == 'button' || controls[i].type == 'hidden' || controls[i].className == 'TextBoxHidden')
		{
			continue;
		}
		
		// In the ignore list ?
		if (findArrayValue(ignoreControlsArray, controls[i].id))
		{
			continue;
		}
	
		controls[i].value = '';
	}

	// DropDownLists
	controls = document.getElementsByTagName('select');
	for (i = 0; i < controls.length; i++)
	{
		// In the ignore list ?
		if (findArrayValue(ignoreControlsArray, controls[i].id))
		{
			continue;
		}
	
		controls[i].selectedIndex = -1;
	}
	
	// CheckBoxes
	controls = document.getElementsByTagName('checkbox');
	for (i = 0; i < controls.length; i++)
	{
		// In the ignore list ?
		if (findArrayValue(ignoreControlsArray, controls[i].id))
		{
			continue;
		}
	
		controls[i].checked = false;
	}
	
	// Spans that are required field labels
	controls = document.getElementsByTagName('span');
	for (i = 0; i < controls.length; i++)
	{
		// In the ignore list ?
		if (findArrayValue(ignoreControlsArray, controls[i].id))
		{
			continue;
		}
	
		if (controls[i].innerText == '*')
		{
			controls[i].innerText = '';
		}
	}
	
	// Labels that are required field labels
	controls = document.getElementsByTagName('label');
	for (i = 0; i < controls.length; i++)
	{
		// In the ignore list ?
		if (findArrayValue(ignoreControlsArray, controls[i].id))
		{
			continue;
		}
	
		if (controls[i].innerText == '*')
		{
			controls[i].innerText = '';
		}
	}
	
	// Hide the legend label
	var span = findSpanOrLabel(legendLabelID)
	if (span != null)
	{
		span.innerText = '';
	}
}

/*
- Examines all controls on a page and replaces the current style with a new style.
-
*/
function changeStyleInAllControls(oldStyle, newStyle) 
{
    var control;
    var i;

    for (i = 0; i < document.forms[0].length; i++)
    {
        control = document.forms[0].elements[i];
    
        if (control.className == oldStyle)
        {
            control.className = newStyle;
        }
    }    
}

/*
- Enables all mandatory fields. Mandatory fields are identified by their className property.
-
*/
function enableMandatoryFields()
{
	var labels = document.getElementsByTagName('label'); 
	var label; 
	var control;
	var i;
	
	// All labels on the form
	for (i = 0; i < labels.length; i++)
	{
		label = labels[i];
		
		// The label has an associated control
		if (label.htmlFor != null)
		{
			// Get the associated control
			control = document.getElementById(label.htmlFor);
		
			// The control's class indicates that it is mandatory
			if (control.className != 'ComboBoxEditMand' && control.className != 'TextBoxEditMand')
			{
				continue;
			}
		
			control.disabled = false;
		}
	}
}

/*
- Disables all mandatory fields. Mandatory fields are identified by their className property.
-
*/
function disableMandatoryFields()
{
	var labels = document.getElementsByTagName('label'); 
	var label; 
	var control;
	var i;
	
	// All labels on the form
	for (i = 0; i < labels.length; i++)
	{
		label = labels[i];
		
		// The label has an associated control
		if (label.htmlFor != null)
		{
			// Get the associated control
			control = document.getElementById(label.htmlFor);
		
			// The control's class indicates that it is mandatory
			if (control.className != 'ComboBoxEditMand' && control.className != 'TextBoxEditMand')
			{
				continue;
			}
		
			control.disabled = true;
		}
	}
}

/*
- Checks that all mandatory fields have been populated. For each field that
- has not been populated, this function will populate an associated label control with a '*'.
- Mandatory fields are identified by their className property.
- 
- legendLabelID		A label that is used as a 'legend' near the bottom of the page to explain
-					the meaning of the '*'
-
*/
function checkMandatoryFields(legendLabelID)
{
	var labels = document.getElementsByTagName('label'); 
	var label; 
	var control;
	var valid = true;
	var i;
	
	// All labels on the form
	for (i = 0; i < labels.length; i++)
	{
		label = labels[i];
		
		// The label has an associated control
		if (label.htmlFor != null)
		{
			// Get the associated control
			control = document.getElementById(label.htmlFor);
		
			// The control's class indicates that it is mandatory
			if (control.className != 'ComboBoxEditMand' && control.className != 'TextBoxEditMand' && control.className != 'Mandatory')
			{
				continue;
			}
		
			switch (control.type)
			{
				// TextBox
			    case 'text':	
				case 'password':
					if (trim(control.value).length == 0)
					{
						// TextBox is empty - set the label text to '*'
						label.innerText = '*';
						valid = false;
					}
					else
					{
						label.innerText = '';
					}
					break;
			
				// DropDownList or ListBox
				case 'select-one':
					label.innerText = '';
					
					// ListBox
					if (control.size > 1)
					{
						// No elements in the ListBox
						if (control.options.length == 0)
						{
							label.innerText = '*';
							valid = false;						
						}
					}
					else
					{
						// DropDownList
						if (control.selectedIndex == -1 || control.options[control.selectedIndex].text.length == 0)
						{
							// Nothing selected - set the label text to '*'
							label.innerText = '*';
							valid = false;
						}
					}
					break;
			}
		}
	}
		
	if (!valid)
	{
		// Show the legend indicating what the red star means
		label = findSpanOrLabel(legendLabelID)
		label.innerText = '* indicates value must be entered.';
	}
	
	return valid;
}

/*
- Enables a Save button if all mandatory fields on the page have been populated
- 
- saveButtonID		Identifies the 'Save' button
-
*/
function enableSaveButton(saveButtonID)
{
	var labels = document.getElementsByTagName('label'); 
	var label; 
	var control;
	var valid = true;
	var i;
	
	// All labels on the form
	for (i = 0; i < labels.length; i++)
	{
		label = labels[i];
		
		// The label has an associated control
		if (label.htmlFor != null)
		{
			// Get the associated control
			control = document.getElementById(label.htmlFor);
		
			// The control's class indicates that it is mandatory
			if (control.className != 'ComboBoxEditMand' && control.className != 'TextBoxEditMand')
			{
				continue;
			}
		
			switch (control.type)
			{
				// TextBox
				case 'text':	
					if (trim(control.value).length == 0)
					{
						valid = false;
					}
					break;
			
				// DropDownList
				case 'select-one':
					if (control.selectedIndex == -1 || control.options[control.selectedIndex].text.length == 0)
					{
						valid = false;
					}
					break;
			}
		}
		
		// At least one mandatory field hasn't been populated - look no further !!
		if (!valid)
		{
			break;
		}
	}
	
	// Enable/disable the Save button based on whether all mandatory fields have been populated.
	enableSubmitButton(saveButtonID, valid);
}

/*
- Ensures that a username and password are entered
- 
*/
function validateLogin()
{
	var userName = findTextBox(0, 'logonNameTextBox');
	var pwd = findPasswordTextBox(0, 'pwdTextBox');
	var userSpan;
	var pwdSpan;
	var span;
	var focusOn;
	var valid = true;
	
	if (trim(userName.value).length == 0)
	{
		userSpan = findSpanOrLabel('userNameRequiredSpan');
		userSpan.style.visibility="visible";
		focusOn = userName;
		valid = false;
	}
	
	if (trim(pwd.value).length == 0)
	{
		userSpan = findSpanOrLabel('pwdNameRequiredSpan');
		userSpan.style.visibility="visible";
		if (focusOn == null)
		{
			focusOn = pwd;
		}
		valid = false;
	}
	
	if (!valid)
	{
		span = findSpanOrLabel('requiredSpan');
		span.style.visibility="visible";
		focusOn.focus();
	}
	
	return valid;
}

/*
- Sets the value "1" for dirty or "0" for not dirty in
- a nominated TextBox.
- textBoxID		Is the ID of the TextBox where the value will be set
- isDirty		true or false 
-
*/
function setDirtyFlag(textBoxID, isDirty)
{
	var textbox = findTextBox(0, textBoxID);
	
	if (isDirty)
	{
		textbox.value = "1";
	}
	else
	{
		textbox.value = "0";
	}

	return true;
}

/*
- Shows the Lookup page modally
- arg1 is the lookup type. See CodeEnumerations.LookupType.
- arg2, arg3 and arg4 are optional arguments. Pass as '' if not used.
-
*/
function showModalLookupPage(title, heightPx, widthPx, arg1, arg2, arg3, arg4, arg5)
{
	var nav = navigator;
	var version = nav.appVersion;
	
	// Adjust height and width for IE6
	if (version.indexOf('MSIE 7.0;') == -1)
	{
		heightPx += 60;
		widthPx += 5;
	}

	window.showModalDialog('../LookupPage.aspx?LookupTitle=' + title +
						   '&arg1=' + arg1 +	
						   '&arg2=' + arg2 +
						   '&arg3=' + arg3 +
						   '&arg4=' + arg4 +
						   '&Active=' + arg5,
						   '', 'dialogHeight: ' + heightPx + 'px; dialogWidth: ' + widthPx + 'px; dialogHide: yes; status: no; scroll: no');
}						   

/*
- Shows the InputAndUpdate page modally.
-
- arg1	The input prompt
- arg2	The default input value
- arg3  The page title
- arg4	The type of input and update request
- arg5	The maximum length of the input.
- arg6  Miscellaneous argument 1
- arg7	Miscellaneous argument 2
- arg8	Miscellaneous argument 3
-
*/
function showModalInputAndUpdatePage(arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8)
{
	var rc = window.showModalDialog('../InputAndUpdate.aspx?arg1=' + arg1 +
									'&arg2=' + arg2 +
									'&arg3=' + arg3 +
									'&arg4=' + arg4 +
									'&arg5=' + arg5 +
									'&arg6=' + arg6 +
									'&arg7=' + arg7 +
									'&arg8=' + arg8,
									'', 'dialogHeight: 100px; dialogWidth: 441px; dialogHide: yes; status: no; scroll: no');
	return rc;
}	

/*
- Trims a string - left and right.
-
*/
function trim(str)
{
	var trimmed = str.replace(/^\s+|\s+$/g, '') ;

	return trimmed;
}


/*
- Gets the date on the client in the format dd/mm/yy
-
*/
function getShortDateFromClient()
{
	var d = new Date();
	var mth, dy;
	var year;
	
	// Day
	dy = d.getDate();
	if (dy.length == 2)
	{
		// Pad with zeroes if required
		dy = '0' + dy;
	}

	// Month 
	mth = parseInt(d.getMonth() + 1);
	if (mth.length == 2)
	{
		// Pad with zeroes if required
		mth = '0' + mth;
	}

	// Year	
	year = d.getFullYear();
	
	// ------------------------------------------
	// dd / mm / yy
	// ------------------------------------------
	return dy + '/' + mth + '/' + year.toString().substr(2, 2);
}

/*
- Gets the date on the client in the format dd-mm-yyyy
-
*/
function getDateFromClient()
{
	var d = new Date();
	var mth, dy;
	
	// Day
	dy = d.getDate();
	if (dy.toString().length == 1)
	{
		// Pad with zeroes if required
		dy = '0' + dy;
	}

	// Month 
	mth = parseInt(d.getMonth() + 1);
	
	if (mth.toString().length == 1)
	{
		// Pad with zeroes if required
		mth = '0' + mth;
	}
	
	// ------------------------------------------
	// Day - Month - Year
	// ------------------------------------------
	return dy + '-' + mth + '-' + d.getFullYear();
}

/*
- Gets the date and time on the client. Time is in 24hr format and includes milliseconds. The date
- is in the format yyyy-mm-dd
-
*/
function getClientDateAndTime()
{
	var d = new Date();
	var clientDateTime;
	var d1, d2, d3;
	
	// Month 
	d1 = parseInt(d.getMonth()+1) + '-';
	if (d1.length == 2)
	{
		// Pad with zeroes if required
		d1 = '0' + d1;
	}
	
	// Day
	d2 = d.getDate() + ' ';
	if (d2.length == 2)
	{
		// Pad with zeroes if required
		d2 = '0' + d2;
	}
	
	// ------------------------------------------
	// Year - Month - Day 
	// ------------------------------------------
	clientDateTime = d.getFullYear() + '-' + d1 + d2;
	
	// Hours
	d1 = d.getHours() + ':';
	if (d1.length == 2)
	{
		// Pad with zeroes if required
		d1 = '0' + d1;
	}
	
	// Minutes
	d2 = d.getMinutes() + ':';
	if (d2.length == 2)
	{
		// Pad with zeroes if required
		d2 = '0' + d2;
	}
	
	// Seconds
	d3 = d.getSeconds() + '.';
	if (d2.length == 2)
	{
		// Pad with zeroes if required
		d2 = '0' + d2;
	}
	
	// 24 Hour - Minute - Second - Millisecond
	clientDateTime += d1 + d2 + d3 + d.getMilliseconds();

	return clientDateTime;
}

/*
- Identify the element that was the target of a click or mousedown event etc.
-
*/
function identifyElementInEventByName(e)
{
    var targ;
    
    if (!e)
    {
      var e=window.event;
    }
    
    if (e.target)
    {
      targ=e.target;
    }
    else if (e.srcElement)
    {
      targ=e.srcElement;
    }
    
    if (targ.nodeType==3)   // defeat Safari bug
    {
      targ = targ.parentNode;
    }
    
    return targ.name;
}

/*
- Identify the element that was the target of a click or mousedown event etc.
-
*/
function identifyElementInEventByID(e)
{
    var targ;
    
    if (!e)
    {
      var e=window.event;
    }
    
    if (e.target)
    {
      targ=e.target;
    }
    else if (e.srcElement)
    {
      targ=e.srcElement;
    }
    
    if (targ.nodeType==3)   // defeat Safari bug
    {
      targ = targ.parentNode;
    }
    
    return targ.id;
}

/*
- Show a <div> that has been setup to give the illusion that it is s
- modal dialog box.
-
*/
function showModalDiv(divID)
{
	window.onscroll = function () { document.getElementById(divID).style.top = document.body.scrollTop; };
	document.getElementById(divID).style.display = "block";
	document.getElementById(divID).style.top = document.body.scrollTop;
}

/*
- Hide a <div> that has been setup to give the illusion that it is s
- modal dialog box.
-
*/
function hideModalDiv(divID)
{
	document.getElementById(divID).style.display = "none";
}

/*
- Toggle a button caption
- 
*/
function toggleButtonCaption(button, caption1, caption2)
{
	if (button.value == caption1)
	{
		button.value = caption2;
	}
	else if (button.value == caption2)
	{
		button.value = caption1;
	}
}

/*
- Enable or disable all of the mandatory controls on the page based on whether the user
- has clicked 'Cancel' or 'New'
- 
*/
function enableDisableMandatory(button)
{
	if (button.value == 'Cancel')
	{
		enableMandatoryFields();
	}
	else if (button.value == 'New')
	{
		disableMandatoryFields();
	}
}

/*
- Enable or disable all of the edit controls on the page based on whether the user
- has clicked 'Cancel' or 'New'
- 
*/
function enableDisableEdit(button)
{
	if (button.value == 'Cancel')
	{
		enableEditControls(true);
	}
	else if (button.value == 'New')
	{
		enableEditControls(false);
	}
}

/*
- Enable or disable all edit controls on a page.
-
- enable			true or false.
-
- legendLabelID		A label that is used as a 'legend' near the bottom of the page to explain
-					the meaning of the '*' character.
-
*/
function enableEditControls(enable, legendLabelID)
{
	var controls;
	var i;
	
	// TextBoxes
	controls = document.getElementsByTagName('input');
	for (i = 0; i < controls.length; i++)
	{
		// Ignore buttons
		if (controls[i].type == 'submit' || controls[i].type == 'button' || controls[i].type == 'hidden' || controls[i].className == 'TextBoxHidden')
		{
			continue;
		}
	
		controls[i].disabled = !enable;
	}

	// DropDownLists
	controls = document.getElementsByTagName('select');
	for (i = 0; i < controls.length; i++)
	{
		controls[i].disabled = !enable;
	}
	
	// CheckBoxes
	controls = document.getElementsByTagName('checkbox');
	for (i = 0; i < controls.length; i++)
	{
		controls[i].disabled = !enable;
	}
	
	// Hide the legend label
	var span = findSpanOrLabel(legendLabelID)
	if (span != null)
	{
		span.innerText = '';
	}
}

/*
- Sets a hidden textbox called PageDirtyHidden to a value of "1"
- indicating that an edit control on a page has been modified
- by the user.
- 
*/
function setPageDirty()
{
	var textbox = findTextBox(0, 'PageDirtyHidden');
	
	if (textbox != null)
	{
		textbox.value = '1';
	}
	else
	{
		return;
	}
}

/*
- Sets a hidden textbox called PageDirtyHidden to a value of "0"
- indicating that no edit controls on a page have been modified
- by the user.
- 
*/
function setPageNotDirty()
{
	var textbox = findTextBox(0, 'PageDirtyHidden');
	
	if (textbox != null)
	{
		textbox.value = '0';
	}
	else
	{
		alert('PageDirtyHidden textbox not found. js/Utility.js');
	}
}

/*
- Alerts the user if Caps Lock has been set on their keyboard. 
- Called from the onkeypress event
- 
*/
function checkCapsLock(e) 
{
	var keyCode=0;
	var shiftKey=false;
	var msg='Caps Lock is On.\n\nTo prevent entering your password incorrectly,\nyou should press Caps Lock to turn it off.';

	// Internet Explorer 4+
	if (document.all) 
	{
		keyCode = e.keyCode;
		shiftKey = e.shiftKey;
	} 
	// Netscape 4
	else if (document.layers) 
	{
		keyCode = e.which;
		shiftKey = (keyCode == 16) ? true : false;
	} 
	// Netscape 6
	else if (document.getElementById) 
	{
		keyCode = e.which;
		shiftKey =(keyCode == 16) ? true : false;
	}

	// Upper case letters are seen without depressing the Shift key, therefore Caps Lock is on
	if ((keyCode >= 65 && keyCode <= 90) && !shiftKey) 
	{
		alert(msg);
	} 
	// Lower case letters are seen while depressing the Shift key, therefore Caps Lock is on
	else if ((keyCode >= 97 && keyCode <= 122) && shiftKey) 
	{
		alert(msg);
	}
}

/*
- Searches a 1 dimensional array for the value of an element with
- a matching search value. Returns true if the value is found in
- the array.
- 
*/
function findArrayValue(arrayObject, searchFor)
{
	if (arrayObject.length == 0)
	{
		return false;
	}
	
	for (var i = 0; i < arrayObject.length; i++)
	{
		if (arrayObject[i] == searchFor)
		{
			return true;
		}
	}

	return false;
}

/*
- Searches a 1 dimensional array for the index of an element with
- a matching search value. Returns -1 if the search value was not
- found in the array.
-
*/
function findArrayIdx(arrayObject, searchFor)
{
	if (arrayObject.length == 0)
	{
		return -1;
	}
	
	for (var i = 0; i < arrayObject.length; i++)
	{
		if (arrayObject[i] == searchFor)
		{
			return i;
		}
	}

	return -1;
}

/*------------------------------------------------------------------*
|							DATE SECTION
*------------------------------------------------------------------*/

/* -----------------------------------------------------------------
| Gets the number of days between two dates. date1 is subtracted
| from date2.
|
| date1		mm-dd-yyyy or mm/dd/yyyy
| date2		mm-dd-yyyy or mm/dd/yyyy
|
\-----------------------------------------------------------------*/
function dateDiffDays(date1, date2, dateSepChar)
{
	// The number of milliseconds in one day
	var ONE_DAY = 1000 * 60 * 60 * 24

	// Convert both dates to milliseconds
	var date1_ms = Date.parse(date1);
	var date2_ms = Date.parse(date2);

	// Calculate the difference in milliseconds
	var difference_ms = date2_ms - date1_ms;
    
	// Less than one day
    if (Math.abs(difference_ms) < ONE_DAY)
    {
		return 0;
	}
	else
    {
		// Convert back to days and return
		return Math.round(difference_ms/ONE_DAY)
	}
}

/* -----------------------------------------------------------------
| Gets the number of a day within a year. eg January 7th is day 7.
|
| date1		a date object
|
\-----------------------------------------------------------------*/
function getDayOfTheYear(date1)
{
	var isLeapYr = false;
	var days = 0;
	var day;
	var mth;
	var yr;
	var mthDays = new Array(12);
	
	yr = date1.getFullYear();
	mth = date1.getMonth();		// 0 - 11
	day = date1.getDate();
	
	if (yr % 4 == 0)
	{
		isLeapYr = true;
	}

	mthDays[0] = 31;
	
	if (isLeapYr)
	{
		mthDays[1] = 29;
	}
	else
	{
		mthDays[1] = 28;
	}
	mthDays[2] = 31;
	mthDays[3] = 30;
	mthDays[4] = 31;
	mthDays[5] = 30;
	mthDays[6] = 31;
	mthDays[7] = 31;
	mthDays[8] = 30;
	mthDays[9] = 31;
	mthDays[10] = 30;
	mthDays[11] = 31;		

	// count the days in each month until reaching the month
	// that the day is in.	
	for (var i = 0; i < mth; i++)
	{
		days += mthDays[i];
	}
	
	days += day;
	
	return days;
}

/* -----------------------------------------------------------------
| Gets the number of days between today and date1.
|
| date1		mm-dd-yyyy or mm/dd/yyyy
|
\-----------------------------------------------------------------*/
function dateDiffToday(date1, dateSepChar)
{
	var date2 = new Date();			// Today
	var today1 = new Date();
	var today2;
	var days = 0;
	var sign = -1;
	
	// The number of milliseconds in one day
	var ONE_DAY = 1000 * 60 * 60 * 24

	// Convert the UTC date (today) to dd/mm/yyyy etc
	SetDateSepCharacter(dateSepChar);
	date2 = GetDateFromUTCDate(date2);

	// Convert both dates to milliseconds since 1970
	var date1_ms = Date.parse(date1);
	var date2_ms = Date.parse(date2);		// Today

	// Calculate the difference in milliseconds
	var difference_ms = Math.abs(date2_ms - date1_ms);
    
	// Less than one day
    if (Math.abs(difference_ms) < ONE_DAY)
    {
		// Same day
		if (date1 == date2)
		{
			return 0;
		}
		else
		{
			if (date2_ms - date1_ms > 0)	// Yesterday
			{
				return -1;
			}
			else
			{
				return 1;					// Tomorrow
			}
		}
	}
	else
    {
		if (difference_ms > 0)
		{
			sign = 1;
		}	
    
		difference_ms = Math.abs(difference_ms);
    
		// Convert back to days and return
		while (difference_ms > 0)
		{
			days++;
			difference_ms -= ONE_DAY;
		};

		days = days * sign;

		if (days > 0)
			days--;

		return days;
	}
}

/* -----------------------------------------------------------------
| Gets the day part of a date string. The DateString argument must
| be in the format dd/mm/yyyy, d/m/yyyy or dd-mm-yyyy etc.
\-----------------------------------------------------------------*/
function getDay(DateString, dateSepChar)
{
    var fnd;
    var day;
    
    // The first separator character indicates the end of the day string
    fnd = DateString.indexOf(dateSepChar);
    
    // The day string begins at the beginning of the string
    day = DateString.substring(0,fnd);
    
    // Pad left with a zero if the length of the day string is 1
    if (day.length == 1)
        day = '0' + day;
    
    return day;
}


/* -----------------------------------------------------------------
| Gets the month part of a date string. The DateString argument must
| be in the format dd/mm/yyyy hh:mm AM|PM or d/m/yyyy h:mm AM|PM.
\-----------------------------------------------------------------*/
function getMonth(DateString, dateSepChar)
{
    var fnd, st;
    var mth;
    
    // The first separator character indicates the beginning of the month string
    fnd = DateString.indexOf(dateSepChar);
    st = fnd + 1;
    
    // The next separator character (-1) is the end of the month string
    fnd = DateString.lastIndexOf(dateSepChar);
    
    // Month string
    mth = DateString.substring(st, fnd);
    
    // Pad left with a zero if the length of the month string is 1
    if (mth.length == 1)
        mth = '0' + mth;
    
    return mth;
}

/* -----------------------------------------------------------------
| Gets the year part of a date string. The DateString argument must
| be in the format dd/mm/yyyy or d/m/yyyy etc
\-----------------------------------------------------------------*/
function getYear(DateString, dateSepChar)
{
    var fnd, st;
    var year;
    
    // The last separator character indicates the beginning of the year string
    fnd = DateString.lastIndexOf(dateSepChar);
    
    year = DateString.substr(fnd + 1, DateString.length - fnd);
    
    // Year string
    return year;
}




