﻿// Global Variables - Used for getObject function
var ns4=document.layers
var ns6=document.getElementById&&!document.all
var ie4=document.alldd
var validationType;
var myHash = new Hash('M', 'false', 'S', 'false', 'A', 'false', 'C','false','I','false','D','false','E','false','N','false');
var pleaseWaitEnabled = 'true';

// gets the rad window you are sitting in
function GetRadWindow()
{
    var oWindow = null;
    if (window.radWindow) oWindow = window.radWindow; //Will work in Moz in all cases, including clasic dialog
    else if (window.frameElement.radWindow) oWindow = window.frameElement.radWindow;//IE (and Moz az well)
    return oWindow;
}

// toggle disabled property on controls based on checkbox status
function enableControls(chkId)
{
	var chkBox = document.getElementById(chkId);
	for (var i = 1; i < enableControls.arguments.length; i++) {
		var control = document.getElementById(enableControls.arguments[i]);
		control.disabled = !chkBox.checked;
		control.parentNode.disabled = !chkBox.checked;
	}
}

// toggle disabled property on controls based on checkbox status
function disableControls(chkId)
{
	var chkBox = document.getElementById(chkId);
	for (var i = 1; i < disableControls.arguments.length; i++) {
		var control = document.getElementById(disableControls.arguments[i]);
		control.disabled = chkBox.checked;
		control.parentNode.disabled = chkBox.checked;
	}
}

// CIBIS
function MM_openBrWindow(theURL,winName,features) { //v2.0
  window.open(theURL,winName,features);
}

// Open Templates maintenence
function OpenTemplateMaint()
{
	//window.open("../AMS/Admin/upload.aspx","templatemaintenence","toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=no,copyhistory=no,width=600,height=600");
	window.open("/AMS/Admin/upload.aspx","templatemaintenence","toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=no,copyhistory=no,width=620,height=600");
}

function OpenUserPasswordReset( userID, sessionKey)
{
	window.open( "/AMS/Admin/UserPasswordReset.aspx?UserID=" + userID + "&SessionKey=" + sessionKey, "userpasswordreset", "toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=no,resizable=no,copyhistory=no,width=370,height=200");
}

// Help and other Popup screens
var cWindow = null;
function newWindow(theURL) { //v2.0
	if(cWindow == null){
			cWindow = window.open(theURL,'','width=550,height=450,status=yes,scrollbars=yes,resizable=yes');
	}else{
			if(cWindow.closed){
				cWindow = window.open(theURL,'','width=550,height=450,status=yes,scrollbars=yes,resizable=yes');
			}else{
				cWindow.location=theURL;
			}
	}
	cWindow.focus();
}

function disableListBoxes()
{
	var listboxes = document.getElementsByTagName("SELECT");
	
	for(var i = 0; i < listboxes.length; i++)
	{
		listboxes[i].style.visibility = "hidden";
	}
}

function enableListBoxes()
{
	var listboxes = document.getElementsByTagName("SELECT");
	
	for(var i = 0; i < listboxes.length; i++)
	{
		listboxes[i].style.visibility = "visible";
	}
}

// ------------------  Button_Press : Animate a button  -------------------------

function Button_Press( ButtonName, PlaceName) {
	if ( GetObject( PlaceName)) {
		GetObject( PlaceName).src = ButtonName;
	}
}

function OpenCenteredWindow(url, height, width, name, parms) {
   var left = Math.floor( (screen.width - width) / 2);
   var top = Math.floor( (screen.height - height) / 2);
   var winParms = "top=" + top + ",left=" + left + ",height=" + height + ",width=" + width;
   if (parms) { winParms += "," + parms; }
   var win = window.open(url, name, winParms);
   if (parseInt(navigator.appVersion) >= 4) { win.window.focus(); }
   return win;
}


function OpenSubWindow(theURL,winName,features) { //v2.0

//  URL = location of the document to be shown in new window 

//  Name = window name, useful for TARGET field of <a> tag 

//  FEATURES
//  directories - show Links panel (yes, no) 
//  location - show Location panel (yes, no) 
//  menubar - show standard program menu with items like File, Edit,... (yes, no) 
//  resizable - allow user to change window size (yes, no) 
//  scrollbars - show scrollbars if they are needed (yes, no) 
//  status - show status bar in the bottom (yes, no) 
//  toolbar - show commands panel with icons like Back, Refresh,... (yes, no) 
//  width - width in pixels (integer) 
//  height - height in pixels (integer) 
//  fullscreen - opens new window in fullscreen mode (yes, no) or there is also a Netscape specific property: 
//  titlebar - show standart windows title bar, containing system window name (yes, no) 
//  top - position of window from the top of the screen
//  left - position of window from the left of the screen

	if (features == "")
			{
			// set standard features
			features = "scrollbars=yes,width=550,height=450,top=50,left=100";
	}
		
    	ObjWindow = window.open(theURL,winName,features);
    	ObjWindow.focus();
}

// ------------------ Expanding Section Code  -------------------------

function expandIt( Section, Button)
{
	if (Section.style["display"] != "none") {
		// Hide Section and make button a plus sign
		Section.style["display"] = "none";
		Button.src = "/images/icons/smallicons/icon_closed.gif";
	} else {
		// Show Section and make button a minus sign
		Section.style["display"] = "block";
		Button.src = "/images/icons/smallicons/icon_open.gif";
	}	
}

function expandItNew( Section, Button)
{
	if (Section.style["display"] != "none") {
		// Hide Section and make button a plus sign
		Section.style["display"] = "none";
		Button.src = "/Images/navigation/WhiteDown.gif"
	} else {
		// Show Section and make button a minus sign
		Section.style["display"] = "block";
		Button.src = "/Images/navigation/WhiteUp.gif"
	}	
}


function expandTab(Section,Button,Tab1,Section1,Tab2,Section2)
{
	if (Section.style["display"] != "none") {
		// Hide Section and make button a UP sign
		Section.style["display"] = "none";
		//alert("DEBUG: ["+Button.id+"]");
		Button.src = "Images/"+Button.id+"UP.gif";
	} else {
		// Show Section and make button a DOWN sign
		Section.style["display"] = "block";
		//alert("DEBUG: ["+Button.id+"]");
		Button.src = "Images/"+Button.id+"DOWN.gif";
	}
	// Close the other tabs
	Section1.style["display"] = "none";
	Tab1.src = "Images/"+Tab1.id+"UP.gif";
	Section2.style["display"] = "none";
	Tab2.src = "Images/"+Tab2.id+"UP.gif";
}
function expandTabNew(Section,Button,Tab1,Section1,Tab2,Section2)
{
	if (Section.style["display"] != "none") {
		// Hide Section and make button a UP sign
		Section.style["display"] = "none";
		//alert("DEBUG: ["+Button.id+"]");
		Button.src = "/Images/tabs/"+Button.id+"UP.gif";
	} else {
		// Show Section and make button a DOWN sign
		Section.style["display"] = "block";
		//alert("DEBUG: ["+Button.id+"]");
		Button.src = "/Images/tabs/"+Button.id+"DOWN.gif";
	}
	// Close the other tabs
	Section1.style["display"] = "none";
	Tab1.src = "/Images/tabs/"+Tab1.id+"UP.gif";	
        Section2.style["display"] = "none";
        Tab2.src = "/Images/tabs/"+Tab2.id+"UP.gif";
}

function show ( pSection)
{
	if ( pSection )
	{
		pSection.style.display = "block";
	}
}
function hide ( pSection)
{
	if ( pSection )
	{
		pSection.style.display = "none";
	}
}
function showhide( pSection)
{
	if ( pSection )
	{
		if ( pSection.style.display == "none")
		{
			show( pSection);
		}
		else
		{
			hide( pSection);
		}
	}
}

function showHideWithButton( pSection, pButton, pInputField, pClosedImgSrc, pOpenImgSrc)
{
	Section = GetObject( pSection);
	Button = GetObject( pButton);
	inputField = GetObject( pInputField);
	// show or hide section
	if ( Section ) {
		if ( Section.style["display"] == "none") {
			Section.style["display"] = "block";
			if ( Button) {
				Button.src = pOpenImgSrc;
			}
			inputField.value = "max";
		} else {
			Section.style["display"] = "none";
			if ( Button) {
				Button.src = pClosedImgSrc;
			}
			inputField.value = "min";
		}
	}
}

// ------------------ Enter button catch methods ------------------

// will try to call a javascript function or click a button
function enterCheck( event, functionToCall)
{
	if ( event && event.keyCode == 13) {
		try {
			eval( functionToCall);
		} catch ( e) {
			try {
				hrefButton.click();
			} catch ( e) {
			}
		}
	}
}

// ------------------ Popup modal window  -------------------------

function openModalPopup(theURL,winName,features) 
{ 

//dialogHeight: sHeight 
//dialogLeft: sXpos 
//dialogTop: sYpos 
//dialogWidth: sWidth 
//center: ( yes | no | 1 | 0 | on | off ) 
//dialogHide: ( yes | no | 1 | 0 | on | off ) 
//edge: ( sunken | raised ) 
//help: ( yes | no | 1 | 0 | on | off ) 
//resizable: ( yes | no | 1 | 0 | on | off ) 
//scroll: ( yes | no | 1 | 0 | on | off ) 
//status: ( yes | no | 1 | 0 | on | off ) 
//unadorned: ( yes | no | 1 | 0 | on | off ) 
//centered :( true | false) 

	//  open modal window
	if (window.navigator.appName.toLowerCase().indexOf("microsoft") > -1) {
		if (features == ""){
			// set standard features
			features = "center=yes;dialogHeight=30;dialogWidth=40;";
			features += "width=480;height=200;";
			features += "scroll=yes;status=no;resizable=yes;edge=sunken;help=yes;unadorned=yes";
		}
		window.showModalDialog(theURL,winName,features);
	}
	else {
		if (features == ""){
			// set standard features
			features = "center=yes,dialogHeight=30,dialogWidth=40,";
			features += "width=480,height=200,";
			features += "scroll=yes,status=no,resizable=yes,edge=sunken,help=yes,unadorned=yes";
		}
		features += ",modal=yes";
		window.open(theURL,winName,features);
	}
}

// ------------------ Popup modal window  -------------------------

function openModalPopupError(theURL,winName,features) 
{ 

//dialogHeight: sHeight 
//dialogLeft: sXpos 
//dialogTop: sYpos 
//dialogWidth: sWidth 
//center: ( yes | no | 1 | 0 | on | off ) 
//dialogHide: ( yes | no | 1 | 0 | on | off ) 
//edge: ( sunken | raised ) 
//help: ( yes | no | 1 | 0 | on | off ) 
//resizable: ( yes | no | 1 | 0 | on | off ) 
//scroll: ( yes | no | 1 | 0 | on | off ) 
//status: ( yes | no | 1 | 0 | on | off ) 
//unadorned: ( yes | no | 1 | 0 | on | off ) 
//centered :( true | false) 

	//  open modal window
	if (window.navigator.appName.toLowerCase().indexOf("microsoft") > -1) {
		if (features == ""){
			// set standard features
			features = "center=yes;dialogHeight=15;dialogWidth=35;";
			features += "width=480;height=200;";
			features += "scroll=yes;status=no;resizable=no;edge=sunken;help=yes;unadorned=yes";
		}
		window.showModalDialog(theURL,winName,features);
	}
	else {
		if (features == ""){
			// set standard features
			features = "center=yes,dialogHeight=15,dialogWidth=35,";
			features += "width=480,height=200,";
			features += "scroll=yes,status=no,resizable=no,edge=sunken,help=yes,unadorned=yes";
		}
		features += ",modal=yes";
		window.open(theURL,winName,features);
	}

}

// ------------------ Form Validation Routines  -------------------------


function ValidLength(sFormName, sFieldName, iMinLength) {
	var oField = eval('document.' + sFormName + '.' + sFieldName)
	if (oField.value.length < iMinLength) {
		return false;
	}
	return true;
}


function ValidNumeric(FieldDesc,TheField,TheNumber,IsMandatory) {
	var valid = 1
	var GoodChars = "0123456789."
	var i = 0

	if (FieldDesc == ""){
		FieldDesc = "The Field";
	}
	if (IsMandatory== ""){
		IsMandatory= False;
	}

//alert("DEBUG: The Field Desc is " + FieldDesc);
//alert("DEBUG: The Field is " + TheField);
//alert("DEBUG: The Number is " + TheNumber);
//alert("DEBUG: Mandatory is " + IsMandatory);

	if (TheNumber=="") {
		// Return false if number is empty
		if (IsMandatory) {
			alert(FieldDesc+" is mandatory. Please re-enter");
		}
	}
	for (i =0; i <= TheNumber.length -1; i++) {
		if (GoodChars.indexOf(TheNumber.charAt(i)) == -1) {
			alert(FieldDesc+" is NOT a valid number. Please re-enter");
			TheNumber = "";
		} // End if statement
	} // End for loop

	// focus and select field
	if (TheField != ""){
		document.all[TheField].focus();
      		document.all[TheField].select();
	}

	return valid
}

function isEmailAddr(email)
{
  var result = false;
  var theStr = new String(email);
  var index = theStr.indexOf("@");
  if (index > 0)
  {
    var pindex = theStr.indexOf(".",index);
    if ((pindex > index+1) && (theStr.length > pindex+1))
	result = true;
  }
  return result;
}

function validRequired( formField, fieldLabel) {
	var result = "";
	//alert("DEBUG validRequired: Field is  [" + formField.value + "]");
	//alert("DEBUG validRequired: Label is  [" + fieldLabel + "]");
	//alert("DEBUG validRequired length [" + formField.value.length + "]");
	if ( formField.value == "" ) {
		//formField.focus();
		result = '"' + fieldLabel +'" is required.';
	}
	//alert("DEBUG validRequired RETURNING result [" + result + "]");
	return result;
}

function allDigits(str)
{
	return inValidCharSet(str,"0123456789.");
}

function inValidCharSet( str, charset) {
	var result = true;
	// Note: doesn't use regular expressions to avoid early Mac browser bugs	
	for (var i=0; i<str.length; i++) {
		if ( charset.indexOf( str.substr( i, 1)) < 0) {
			result = false;
			break;
		}
	}
	return result;
}

function validEmail( formField, fieldLabel) {
	var result = "";
	//alert("DEBUG validEmail: validEmail length [" + formField.value.length + "]");
	if (formField.value != "") {
		if ( (formField.value.length < 3) || !isEmailAddr(formField.value) )
		{
			result = 'Please enter a complete email address for "' + fieldLabel +'" (ie name@yourdomain.com)';
		}
	}
	return result;
}

function validDate( formField, fieldLabel, required) {
	var result = true;
	if (required && !validRequired(formField,fieldLabel)) {
		result = false;
	}
 	if (result)
 	{
 		var elems = formField.value.split("/");
 		result = (elems.length == 3); // should be three components
 		if (result)
 		{
 			
  			var day = parseInt(elems[0],10);
			var month = parseInt(elems[1],10);
 			var year = parseInt(elems[2],10);
			result = allDigits(elems[0]) && (month > 0) && (month < 13) &&
					 allDigits(elems[1]) && (day > 0) && (day < 32) &&
					 allDigits(elems[2]) && ((elems[2].length == 2) || (elems[2].length == 4));
 		}
  		if (!result)
 		{
 			alert('Please enter a date in the format DD/MM/YYYY for the "' + fieldLabel +'" field.');
			formField.focus();		
		}
	} 
	return result;
}

function validDate( formField, fieldLabel) {
	var result = "";
	
 	if (formField.value != "")
 	{
 		var elems = formField.value.split("/");
 		result = (elems.length == 3); // should be three components
 		if (result)
 		{
 			var day = parseInt(elems[0],10);
			var month = parseInt(elems[1],10);
 			var year = parseInt(elems[2],10);
			result = allDigits(elems[0]) && (month > 0) && (month < 13) &&
					 allDigits(elems[1]) && (day > 0) && (day < 32) &&
					 allDigits(elems[2]) && ((elems[2].length == 2) || (elems[2].length == 4));
 		}
  		if (!result)
 		{
 			result = 'Please enter a date in the format DD/MM/YYYY for the "' + fieldLabel +'" field.';	
		} else {
			result = '';
		}
			
	} 
	return result;
}

function validNum( formField, fieldLabel) {
	var result = "";
	if (formField.value != "")
	{
 		var num = parseInt(formField.value,10);
 		if (isNaN(num))
 		{
 			result = 'Please enter a NUMBER for the "' + fieldLabel +'" field.';
		}
	}
	return result;
}

function validInt( formField, fieldLabel) {
	var result = "";
	if (formField.value != "")
	{
 		if (!allDigits(formField.value))
 		{
 			result = 'Please enter a positive, whole NUMBER for the "' + fieldLabel +'" field.';
		}
	} 
	return result;
}

function validAlpha( formField, fieldLabel) {
	var result = "";
	if (formField.value != "")
	{
		var sValidDigits = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890 -_()'";
		var sChar;
		var i;
		for (i = 0; i < formField.value.length; i++) {
			sChar = formField.value.charAt(i);
			if (sValidDigits.indexOf(sChar) == -1) {
				result = 'Please enter only CHARACTERS or NUMBERS for the "' + fieldLabel +'".';
			}
		}
	}
	return result;
}

function validChar(formField,fieldLabel) {
	var result = "";
	if (formField.value != "")
	{
		var sValidDigits = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ[] -_()'";
		var sChar;
		var i;
		for (i = 0; i < formField.value.length; i++) {
			sChar = formField.value.charAt(i);
			if (sValidDigits.indexOf(sChar) == -1) {
				result = 'Please enter only CHARACTERS for the "' + fieldLabel +'".';
			}
		}
	}
	return result;
}

function ProcessError( aMessage, form, field){
	//var errormessage = new String();
 	if (aMessage != ""){
 		// Add to error message
 		errormessage += "<br>" + aMessage;
 		// Make field yellow
 		makeyellow( form, field);
	}
    //return errormessage;
}

function ProcessMandatory(aMessage,aformname,afieldname){
 	if (aMessage != ""){
 		// Add to error message
 		mandatorymessage += "<br>" + aMessage;
 		// Make field red
 		makered(aformname,afieldname);
	}
}

function ValidateForm( form, arrayOfControlsToValidate) {
//alert("DEBUG: ValidateForm ["+document.forms[theForm].name+"]" );
	var returnmessage  = new String();
	var elementsToValidate = null;
	if ( arrayOfControlsToValidate != null ){
		elementsToValidate = Array( arrayOfControlsToValidate.length );
		for( var i=0; i< arrayOfControlsToValidate.length ; i++){
			elementsToValidate[i]=GetObject( arrayOfControlsToValidate[i]);
		}
	}else{
		elementsToValidate = form.elements;
	}

	for ( i=0; i < elementsToValidate.length; i++) {
		if ( elementsToValidate[i] != null  &&
			( typeof(elementsToValidate[i].readonly) == 'undefined' || elementsToValidate[i].readonly == false) &&
			( typeof(elementsToValidate[i].disabled) == 'undefined' || elementsToValidate[i].disabled == false ) ){
			var fieldname = elementsToValidate[i].name ;
			var fieldid = elementsToValidate[i].id ;
			var validation = "";
			var displayname = "";
			var mandatory = false;
			var field = elementsToValidate[i];
			// set Display Name
			displayname = getDisplayname( form, field) ;
			// set validation
			validation = getValidation( form, field);
			//alert("DEBUG: Validation for field ["+fieldname+"], is ["+validation+"]" );
			//alert("DEBUG: Display name for field ["+fieldname+"], is ["+displayname+"]" );
			
        		// M - Mandatory
        		// S - Strip junk characters such as %#!@*&()'_+=:;<>?/\\|~`\"^{}[]
        		// A - Validate AlphaNumeric (abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890)
        		// C - Validate as Charaters (abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ)
        		// I - Integer Validation (whole positive number, non decimal)
        		// D - Date Validation (valid date that will be reformatted as dd mmm yyyy)
        		// E - Email Validation (ie name@yourdomain.com)
        		// N - Number Validation (any number)
	 
			// Do validation checks on field by converting validation string 
			// to an array and processing each validation type.

		
			if ( trim( validation) != "") {	
					
				// Validating a field. Before we start, we'll just remove any leading/trailing spaces
				//alert("DEBUG: processing Validation for field ["+fieldname+"], with Validation ["+validation+"]" );
				field.value = trim( getFieldValue(field), "");
			
				//alert("DEBUG: processing Validation for field ["+fieldname+"], with Validation ["+validation+"]" );
				if (myHash.items['S'] == "true" && inValidCharSet("S",validation)){
					StripChars( field,"");
				}
				if (myHash.items['A'] == "true" && inValidCharSet("A",validation)){
					//alert("DEBUG: Alpha ["+validation+"]");
					returnmessage = validAlpha( field, displayname);
					ProcessError( returnmessage, form, field);
				}
				if (myHash.items['C'] == "true" && inValidCharSet("C",validation)){
					//alert("DEBUG: Character ["+validation+"]");
					returnmessage = validChar( field, displayname);
					ProcessError( returnmessage, form, field);
				}
				if (myHash.items['I'] == "true" && inValidCharSet("I",validation)){
					//alert("DEBUG: Integer ["+validation+"]");
					returnmessage = validInt( field, displayname);
					ProcessError( returnmessage, form, field);
				}
			
				if (myHash.items['D'] == "true" && inValidCharSet("D",validation)){
					//alert("DEBUG: Date ["+validation+"]");
					returnmessage = validDate( field, displayname);
					ProcessError( returnmessage, form, field);
				}
				if (myHash.items['E'] == "true" && inValidCharSet("E",validation)){
					//alert("DEBUG: Email ["+validation+"], displayname "+ displayname );
					returnmessage = validEmail( field, displayname);
					ProcessError( returnmessage, form, field);
				}
				if (myHash.items['N'] == "true" && inValidCharSet("N",validation)){
					//alert("DEBUG: Number ["+validation+"]");
					returnmessage = validNum( field, displayname);
					ProcessError( returnmessage, form, field);
				}
				// Do mandatory checks on field (if required)
				if (myHash.items['M'] == "true" && inValidCharSet("M",validation)){
					//alert("DEBUG: Mandatory ["+validation+"], field "+document.forms[theForm].elements[i].name);
					returnmessage = validRequired( field, displayname);
					ProcessError( returnmessage, form, field);
				}
			}
		}
	}
}

function ValidFields( form, arrayOfControlsToValidate) {
	ValidateForm( form, arrayOfControlsToValidate);
	// Try on page validation
	try {
		LOCALFieldValidation( form);
	}
	catch( err) {
	}
	//alert("DEBUG: Leaving ValidFields");
	if(errormessage.length > 2 || mandatorymessage.length > 2) {
		return false;
	}
	return true;
}

// arrayOfControlsToValidate may be left as null
// If its null, all the elements in the form will be processed instead. As per usual.
function ProcessForm(aformname, arrayOfControlsToValidate){
	/*for (var i in myHash.items) {
		alert('key is: ' + i + ', value is: ' + myHash.items[i]);
	}*/
	
	

	if ( document.forms[aformname] ) {
		return ProcessFormDirect( document.forms[aformname], arrayOfControlsToValidate);
	} else {
		return false;
	}
}

function ProcessFormDirect( form, arrayOfControlsToValidate){
//alert("DEBUG: Process Form ["+document.forms[aformname].name+"]");
	var displaymessage = new String();
	errormessage = "";
	mandatorymessage = "";
	// Is there a submitButton
	if ( form.SubmitButton) {
		// get it's value - in lower case (easier to do comparisons)
		// Commenting the below code ( subButValue ) becasue its no longer used 
		//var subButValue = form.SubmitButton.value.toLowerCase();
		// not a value that requires validation - just return
	}
	
/*	//alert("DEBUG: Stop submit buttons being clicked on more than once...");
	// Stop submit buttons being clicked on more than once...
	if ( form.FormSubmitted.value != "False") {
		return false;
	}*/
	
//	alert("DEBUG: ValidateFields ");
	if ( ValidFields( form, arrayOfControlsToValidate) == true) {
//		form.FormSubmitted.value = "True"
		return true;
	}
	else {
		//alert("ALL NOT OK !!!");
		// Display Error Messages
		if ( errormessage.length > 2) {
			displaymessage += "<p><img border='0' src='/Images/error/CriticalError.gif'>";
			displaymessage += errormessage;
			displaymessage += "</p>";
		}
		if ( mandatorymessage.length > 2) {
			displaymessage += "<p><img border='0' src='/Images/error/MandatoryField.gif'>";
			displaymessage += mandatorymessage;
			displaymessage += "</p>";
		}
		if ( displaymessage.length > 0) {
			// Normal Windows Message Box
			//alert(displaymessage);
			// Pretty Popup
			openModalPopupError("/AMS/Errors/DisplayError.aspx?Message="+displaymessage,"ErrorWindow","")
		}
		//alert("Please correct the indicated errors before proceeding.");
		return false;
	}
}
function ShowPopupErrorWindow( errorMessage, mandatoryMessage) {
	// Display Error Messages
	var displaymessage = new String();
	if ( errorMessage.length > 2) {
		displaymessage += "<p><img border='0' src='/Images/Critical%20Error.gif'><br>";
		displaymessage += errorMessage;
		displaymessage += "</p>";
	}
	if ( mandatoryMessage.length > 2) {
		displaymessage += "<p><img border='0' src='/Images/Mandatory%20Field.gif'><br>";
		displaymessage += mandatoryMessage;
		displaymessage += "</p>";
	}
	if ( displaymessage.length > 0) {
		// Pretty Popup
		openModalPopupError("/AMS/Errors/DisplayError.aspx?Message="+displaymessage,"ErrorWindow","")
	}
}

function SetupForm() {
	// Tag mandatory fields with 
	var numberForms = document.forms.length;
	var formIndex;
	for (formIndex = 0; formIndex < numberForms; formIndex++)
	{
		tagmandatoryfields( formIndex );
	}
}

function ReplaceQuotes(aField) {
	if (aField.indexOf("'") > 0 )
	{
		aField = aField.replace("'", "%");
	}
	return aField;
}

function ReplaceChars(formField,out,add) {
	temp = "" + formField.value; // temporary holder

	while (temp.indexOf(out)>-1) 
	{
		pos= temp.indexOf(out);
		temp = "" + (temp.substring(0, pos) + add + 
		temp.substring((pos + out.length), temp.length));
	}

	formField.value = temp;
//alert("DEBUG ReplaceChars: ["+out+"] with [" + add + "]");
}

function StripChars(formField,aStripChars){

//alert("DEBUG StripCharacters: with fieldname [" + formField.value + "]");

	s = formField.value;
	var i;
	var returnString = "";

	if (aStripChars == "") {
		// if no Strip Characters are sent, strip the following
		aStripChars = "%#!*&+=:;<>?/\\|~\"^{}[]";     // Characters stripped out
	}

	for (i = 0; i < s.length; i++) {
	        // Search through string and append to unfiltered values to returnString.
		var c = s.charAt(i);
		if (aStripChars.indexOf(c) == -1) returnString += c;
		}

//alert("DEBUG StripCharacters: replacing [" + formField.value + "] with  [" + returnString + "]");
	formField.value = returnString;
}

function getValidation( form, field) {
	var validation = "";
	// set validation
	if ( field) {
		if ( field.attributes["validation"]){
			validation = field.attributes["validation"].value;
		}
		if ( field.attributes["VALIDATION"]){
			validation = field.attributes["VALIDATION"].value;
		}
		if ( field.attributes["Validation"]){
			validation = field.attributes["Validation"].value;
		}
		validation = validation.toUpperCase();
	}
	return validation;
}

function getDisplayname( form, field) {
	var displayname = "";
	// set displayname
	if ( field) {
		//alert("getDisplayname form ["+formname+"], field ["+fieldname+"]");
		if ( field.attributes["displayname"]) {
			displayname = field.attributes["displayname"].value;
		}
		if ( field.attributes["DISPLAYNAME"]) {
			displayname = field.attributes["DISPLAYNAME"].value;
		}
		if ( field.attributes["Displayname"]) {
			displayname = field.attributes["Displayname"].value;
		}
		if ( field.attributes["DisplayName"]) {
			displayname = field.attributes["DisplayName"].value;
		}
		if ( displayname == "") {
			if(field.name != null)
			{
				displayname = ltrim(SplitCaps( field.name));
				displayname = displayname.toUpperCase();
			}
		}
		else{
			displayname = displayname.toUpperCase();
		}
	}
	return displayname;
}

function tagmandatoryfields(aformname) {
	// put a star infront of mandatory fields
	var starhtml = "<span class='redtext'><img src='/images/icons/asterisk.gif' height=9 width=9 border=0></span>";
	var validation = "";
	
	for (i=0; i < document.forms[aformname].elements.length; i++) {
		if (( typeof(document.forms[aformname].elements[i].readonly) == 'undefined' || document.forms[aformname].elements[i].readonly == false) &&
		( typeof(document.forms[aformname].elements[i].disabled) == 'undefined' || document.forms[aformname].elements[i].disabled == false ) ){

			//alert('document.forms[aformname].elements.length == ' + document.forms[aformname].elements.length + '\n' +	'i == ' + i );
			var fieldname = document.forms[aformname].elements[i].name;
			// set validation
			if ( fieldname != ""){
				//alert("DEBUG: looking at field ["+fieldname+"]" );
				validation = getValidation( aformname, document.forms[aformname].elements[i]);
				if (trim(validation) != ""){
					//alert("DEBUG: Validation for field ["+document.forms[aformname].elements[i].name+"], is ["+validation+"]" );
					//alert(" field html ["+document.forms[aformname].elements[i].outerHTML+"], is ["+validation+"]" );
					if (inValidCharSet("M",validation)){
						//document.forms[aformname].elements[i].outerHTML = document.forms[aformname].elements[i].outerHTML + starhtml ;
						document.forms[aformname].elements[i].insertAdjacentHTML('afterend', starhtml );
					}
				}
			}
		}
	}
}


function Hash()
{
	this.length = 0;
	this.items = new Array();
	for (var i = 0; i < arguments.length; i += 2) {
		if (typeof(arguments[i + 1]) != 'undefined') {
			this.items[arguments[i]] = arguments[i + 1];
			this.length++;
		}
	}
   
	this.removeItem = function(in_key)
	{
		var tmp_value;
		if (typeof(this.items[in_key]) != 'undefined') {
			this.length--;
			var tmp_value = this.items[in_key];
			delete this.items[in_key];
		}
	   
		return tmp_value;
	}

	this.getItem = function(in_key) {
		return this.items[in_key];
	}

	this.setItem = function(in_key, in_value)
	{
		if (typeof(in_value) != 'undefined') {
			if (typeof(this.items[in_key]) == 'undefined') {
				this.length++;
			}

			this.items[in_key] = in_value;
		}
	   
		return in_value;
	}

	this.hasItem = function(in_key)
	{
		return typeof(this.items[in_key]) != 'undefined';
	}
}

function validateAllFields () {
     	
   for (var key in myHash.items) {
      myHash.setItem(key, 'true');
   }

}

function validateNoFields () {
   
   for (var key in myHash.items) {
      myHash.setItem(key, 'false');
   }

}

function removeValidationField(key) {
   
   myHash.setItem(key, 'false');   

}

function addValidationField(key) {
   
   myHash.setItem(key, 'true');   

}

function validateAllExtFields(except) {
   
   for (var key in myHash.items) {
      if(key == except) {
	myHash.setItem(key, 'false');
      } else {
      	myHash.setItem(key, 'true');
      }
   }

}
// ------------------ Get Field Value -------------------------------
function getFieldValue(field)
{
	switch(field.type)
	{
		case "text" :
		case "textarea" :
		case "password" :
		case "hidden" :
			return field.value;

		case "select-one" :
			var i = field.selectedIndex;
			if (i == -1){   
				return "";
			}else {
				return (field.options[i].value == "") ? field.options[i].text : field.options[i].value;
			}
			
		case "select-multiple" :
			var allChecked = new Array();
			for(i = 0; i < field.options.length; i++){
				if(field.options[i].selected){
					allChecked[allChecked.length] = (field.options[i].value == "") ? field.options[i].text : field.options[i].value;
				}
			}
			return allChecked;

		case "button" :
		case "reset" :
		case "submit" :
			return "";

		case "radio" :
		case "checkbox" :
			if (field.checked) { 
				return field.value; 
			} else { 
				return ""; 
			}
			
		default :
		if(field[0] != null)
		{
			if(field[0].type == "radio")
			{
				for (i = 0; i < field.length; i++){
					if (field[i].checked){
						return field[i].value;
					}
				}
				return "";
			}
			else if(field[0].type == "checkbox"){
				var allChecked = new Array();
				for(i = 0; i < field.length; i++){
					if(field[i].checked){
						allChecked[allChecked.length] = field[i].value;
					}
				}
				return allChecked;
			}
			else{
				var str = "";
			}
		}
		for (x in field) { 
			str += x + "\n"; 
		}
		break;
	}
	return "";
}



// ------------------ Form Utilities  -------------------------

function MakeWhite( field)
{
	if ( field){
		field.style.backgroundColor = "white";
	}
}

function MakeGray( field) {
	if ( field) {
		field.style.backgroundColor = "#d3d3d3";
	}
}

function makered(formname, fieldname)
{
//alert("DEBUG makered: with field name [" + fieldname + "]");
	if (formname){
		// form element
		document.forms[formname].all[fieldname].style.backgroundColor = "#D5BBB8";
	} else {
		// Not a form element
		fieldname.style.backgroundColor = "#D5BBB8";
	}

}

function makesolidred(formname, fieldname)
{
//alert("DEBUG makered: with field name [" + fieldname + "]");
	if (formname){
		// form element
		document.forms[formname].all[fieldname].style.backgroundColor = "#8A2C33";
	} else {
		// Not a form element
		fieldname.style.backgroundColor = "#8A2C33";
	}

}

function makeyellow( form, field)
{
	field.style.backgroundColor = "#F8DF8A";
}

function Disableform(formname, DisableTheForm) {
	var fieldname;
	var fieldtype;
	var fieldlength = 0;
	//alert("DEBUG Disableform: with form name [" + formname + "]");
	if (DisableTheForm) {
		for (i=0; i < document.forms[formname].elements.length; i++) {
			fieldname = document.forms[formname].elements[i].name.toUpperCase();
			fieldtype = document.forms[formname].elements[i].type.toUpperCase();
			fieldlength = document.forms[formname].elements[i].name.length;
			//alert("DEBUG Disableform: field name [" + fieldname + "]");
			//alert("DEBUG Disableform: field name length [" + fieldlength + "]");
			if ((fieldname != "ENABLE") && (fieldtype != "HIDDEN")){
				document.forms[formname].elements[i].disabled = true;
			}
		}
	}
	else {
		for (i=0; i < document.forms[formname].elements.length; i++) {
			document.forms[formname].elements[i].disabled = false;
		}
	}
}

function ClearSelect( selectName) {
	var select = GetObject( selectName);
	if ( select && select.selectedIndex) {
		select.selectedIndex = -1;
	}
}

// ------------------ Banner Search Validation Routines  -------------------------


function DoSearch(aType) 
{
	var errormsg = "";

	SearchForm.SearchType.value = aType;
	// Remove any trailing or leading spaces HEAT #1763
	SearchForm.SearchText.value = trim(SearchForm.SearchText.value);

	StripChars((document.forms["SearchForm"].all["SearchText"]),"")
	//ReplaceChars((document.forms["SearchForm"].all["SearchText"]),"AA","BB")

	// Post Form to window
	if (SearchForm.SearchText.value != ""){
		if (SearchForm.SearchText.value.length > 1){
			errormsg = validAlpha((document.forms["SearchForm"].all["SearchText"]),"Search.",false);
			if (errormsg == ""){
				// perform search
				SearchForm.SubmitButton.value='PerformSearch';
				SearchForm.submit();
			}
			else {
				alert(errormsg);
			}

		}
		else {
				alert("Please enter 2 or more characters to perform a Search.");
		}
	}
}

// ------------------ String Trim Routines  -------------------------

/* function to remove spaces in front of string */
function ltrim(vInStr) {
    var vlen = vInStr.length;
    while (vInStr.charAt(0) == " ") {
        vInStr = vInStr.substring(1,vlen);
        vlen = vInStr.length;
    }
    return vInStr;
}

/* function to remove spaces at the back of string */
function rtrim(vInStr) {
    var vlen = vInStr.length;
    while (vInStr.charAt(vlen-1) == " ") {
        vInStr = vInStr.substring(0,vlen-1);
        vlen = vInStr.length;
    }
    return vInStr;
}
/* function to remove spaces in front of/ at the back of string */ 
function trim(vInStr) {
    return ltrim(rtrim(vInStr));
}

function charAt(n)
{
var str = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
var s;
s = str.charAt(n - 1);
return(s);
} 

/* function to split the string on capitals*/ 
function SplitCaps(aString)
{
var checkOK = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
var checkStr = "";
	checkStr = aString;
		for (var m = 0;  m < checkStr.length;  m++)
		{
			ch = checkStr.charAt(m);
			for (var j = 0;  j < checkOK.length;  j++)
			if (ch == checkOK.charAt(j))
			{
				var headStr = checkStr.substring(0, m);
				var endStr = checkStr.substring(m, checkStr.length);
				var newStr = headStr + " " + endStr;
				checkStr = newStr;
				m++;
			}
		}
		
	return(checkStr)
}

function InStr(strSearch, charSearchFor)
/*
InStr(strSearch, charSearchFor) : Returns the first location a substring (SearchForStr)
                           was found in the string str.  (If the character is not
                           found, -1 is returned.)
*/
{
	for (var i=0; i < Len(strSearch); i++)
	{
	    if (charSearchFor == Mid(strSearch, i, 1))
	    {
			return i;
	    }
	}
	return -1;
}


function copyField(fromName, toName) {
  var fromCntl = document.getElementById(fromName);
  var toCntl = document.getElementById(toName);
  if ((fromCntl != null) && (toCntl != null)) {
	if (toCntl.value == '') {
	toCntl.value=fromCntl.value;}  
     }
}


// This function checks for DOM strategy, then returns an object reference.
function GetObject( name) {
	if ( document.all) {
		//alert('geting by doc.all');
		return document.all[name];
	} else {
		//alert( 'getting by element');
		return document.getElementById(name);
	}
}

// =================================================================
// Array and functions to populate 2 select boxes, with the 2nd
// select being populated based on the selection from the 1st select
// =================================================================
// Original:  Jerome Caron (jerome.caron@globetrotter.net)
// This script and many more are available free online at
// The JavaScript Source!! http://javascript.internet.com

// Array formatted as follows (null is an empty array item):
// templates = new Array(
// new Array(
// new Array("Saku Koivu", 39482304),
// new Array("Jeff Hackett", 39823498),
// new Array("Karl Dykhuis", 89092834)
// ),
// new Array(
// new Array("Mario Lemieux", 23840238),
// new Array("Kevin Stevens", 29345423)
// ),
// null,
// new Array(
// new Array("Alexei Yashin", 20394802),
// new Array("Radek Bonk", 98234902)
// )
// );

//  Use on 1st select box: onchange="fillSelectFromArray(this.form.<name of 2nd selectbox>, ((this.selectedIndex == -1) ? null : <name of array>[this.selectedIndex-1]));"

function fillSelectFromArray(selectCtrl, itemArray, goodPrompt, badPrompt, defaultItem) {
  var i, j;
  var prompt;
  
  // empty existing items
  for (i = selectCtrl.options.length; i >= 0; i--) {
    selectCtrl.options[i] = null;
  }
  prompt = (itemArray != null) ? goodPrompt : badPrompt;
  if (prompt == null) {
    j = 0;
  }
  else {
    selectCtrl.options[0] = new Option(prompt);
    j = 1;
  }
  if (itemArray != null) {
    // add new items
    for (i = 0; i < itemArray.length; i++) {
      selectCtrl.options[j] = new Option(itemArray[i][0]);
      if (itemArray[i][1] != null) {
        selectCtrl.options[j].value = itemArray[i][1];
      }
      j++;
    }
    // select first item (prompt) for sub list
    selectCtrl.options[0].selected = true;
   }
}


// <!-- Original:  Donnie Brewer (brewsky@home.com) -->
// <!-- Web Site:  http://www.brewskynet.com/javatest/popup.html -->

// <!-- This script and many more are available free online at -->
// <!-- The JavaScript Source!! http://javascript.internet.com -->

function ViewProgressBar(user,ValueShow) {
//var mousex = window.event.x;        // mouse location capture event
//var mousey = window.event.y;        // mouse location capture event
  user.style.visibility = ValueShow;  // show or hide respective Example
//user.style.left = mousex + 5;       // place popup at the mouse X (left) location
//user.style.top = mousey;            // place popup at the mouse Y (top) location
}

function getSelectedRadio(buttonGroup) {
      // returns the array number of the selected radio button or -1 if no button is selected
      if (buttonGroup[0]) { // if the button group is an array (one button is not an array)
         for (var i=0; i<buttonGroup.length; i++) {
            if (buttonGroup[i].checked) {
               return i
            }
         }
      } 
	  else {
         if (buttonGroup.checked) { return 0; } // if the one button is checked, return zero
   }
   // if we get to this point, no radio button is selected
   return -1;
} // Ends the "getSelectedRadio" function


// function used for deleting collections.
function deleteObject(hidTextBox) {
	GetObject(hidTextBox).value = "true";
}

// Prototype for outerHTML for mozilla. 
// This sometimes causes irregular behaviour when setting. Becareful of use.
if ( navigator.userAgent.indexOf("MSIE") == -1){	
	var _emptyTags = {
	"IMG":   true,
	"BR":    true,
	"INPUT": true,
	"META":  true,
	"LINK":  true,
	"PARAM": true,
	"HR":    true
	};

	window.HTMLElement.prototype.__defineGetter__("outerHTML", function () {
	var attrs = this.attributes;
	var str = "<" + this.tagName;
	for (var i = 0; i < attrs.length; i++)
		str += " " + attrs[i].name + "=\"" + attrs[i].value + "\"";

	if (_emptyTags[this.tagName])
		return str + ">";

	return str + ">" + this.innerHTML + "</" + this.tagName + ">";
	});

	window.HTMLElement.prototype.__defineSetter__("outerHTML", function (sHTML) {
	var r = this.ownerDocument.createRange();
	r.setStartBefore(this);
	var df = r.createContextualFragment(sHTML);
	this.parentNode.replaceChild(df, this);
	});
}

//Prototype for adjacentHTML for mozilla.
if ( navigator.userAgent.indexOf("MSIE") == -1){	

	HTMLElement.prototype.insertAdjacentHTML = function (sWhere, sHTML) {
	var df;   // : DocumentFragment
	var r = this.ownerDocument.createRange();
	   
	switch (String(sWhere).toLowerCase()) {  // convert to string and unify case
		case "beforebegin":
			r.setStartBefore(this);
			df = r.createContextualFragment(sHTML);
			this.parentNode.insertBefore(df, this);
			break;
	         
		case "afterbegin":
			r.selectNodeContents(this);
			r.collapse(true);
			df = r.createContextualFragment(sHTML);
			this.insertBefore(df, this.firstChild);
			break;
	         
		case "beforeend":
			r.selectNodeContents(this);
			r.collapse(false);
			df = r.createContextualFragment(sHTML);
			this.appendChild(df);
			break;
	         
		case "afterend":
			r.setStartAfter(this);
			df = r.createContextualFragment(sHTML);
			this.parentNode.insertBefore(df, this.nextSibling);
			break;
	}   
	};
}
/* End Slide out panel bar scripts */
/*-------------------------------------------------------------------------------*/
/*-------------------------------------------------------------------------------*/
/* Find position methods */
function findPosX( obj)
{
	var curleft = 0;
	if (obj.offsetParent) {
		while (obj.offsetParent) {
			curleft += obj.offsetLeft
			obj = obj.offsetParent;
		}
	}
	else if (obj.x) {
		curleft += obj.x;
	}
	return curleft;
}
function findPosY( obj)
{
	var curtop = 0;
	if (obj.offsetParent) {
		while (obj.offsetParent) {
			curtop += obj.offsetTop
			obj = obj.offsetParent;
		}
	}
	else if (obj.y) {
		curtop += obj.y;
	}
	return curtop;
}
/* End Find position methods */
/*-------------------------------------------------------------------------------*/
/*-------------------------------------------------------------------------------*/
/* Slide out panel bar scripts */
/* Modified by i.deak 19/05/06- no longer setting width of div to the same as button width*/
function slideDownMenu( btnObject, slideOutDivObject, panel, panelItemsIDArray, objectName, width) {
	
	// the objects involved in this slide out menu
	this.objectName = objectName;
	this.btnObject = btnObject;
	this.slideOutDivObject = slideOutDivObject;
	this.panel = panel;
	this.panelItemsIDArray = panelItemsIDArray;
	// the size of the panel bar div

	//this.panelBarWidth = btnObject.offsetWidth;
	this.panelBarWidth = width;
	this.panelBarHeight = slideOutDivObject.offsetHeight;
	this.leftOffset = findPosX( this.btnObject);
	this.topOffset = (findPosY( this.btnObject) - this.panelBarHeight + this.btnObject.offsetHeight);
	// the slide options of the menu
	this.slideSpeed = 5;
	this.slideStep = 10;
	// the moving of the panel variables
	this.currentPosition = 0;
	this.movingSlider = false;
	// setting the intial values of the div tag
	this.slideOutDivObject.style.width = this.panelBarWidth + "px";
	this.slideOutDivObject.style.clip = "rect(" + this.panelBarHeight + "px, " + this.panelBarWidth + "px, 800px, 0px)";

	this.slideOutDivObject.style.top = (this.topOffset + "px");
	this.slideOutDivObject.style.right = "1px";
	// slide down function
	this.slideDownPanelBar = function() {
		this.slideDownPanelBar2( true);
	}
	this.slideDownPanelBar2 = function( firstTime) {
		if ( this.movingSlider && firstTime) {
			return;
		}
		this.movingSlider = true;
		// checking if the panel is fully down
		if ( this.currentPosition < this.panelBarHeight) {
			// add the slide step value to the new position
			this.currentPosition += this.slideStep;
			// if the new current position is bigger than the panel 
			// height then set it to the panel height
			if ( this.currentPosition > this.panelBarHeight) {
				this.currentPosition = this.panelBarHeight;
			}
			// adjust the top position of the panel
			this.slideOutDivObject.style.top = this.topOffset + this.currentPosition + "px";
			// adjust the clip box value
			try {
				this.slideOutDivObject.style.clip = "rect(" + (this.panelBarHeight - this.currentPosition) + "px, " + this.panelBarWidth + "px, " + (600 + this.panelBarHeight) + "px, 0px)";

			} catch(e) {
			}
			if ( this.panelBarHeight == this.currentPosition) {
				this.movingSlider = false;
			}
		}
		if ( this.currentPosition < this.panelBarHeight) {
			setTimeout( objectName + ".slideDownPanelBar2( false)", this.slideSpeed);
		}
	}
	this.slideUpPanelBar = function() {
		this.slideUpPanelBar2( true);
	}
	this.slideUpPanelBar2 = function( firstTime) {
		if ( this.movingSlider && this.firstTime) {
			return;
		}
		if ( this.firstTime) {
			try {
				this.closeTabPanels();
			} catch(e) {
			}
		}
		this.movingSlider = true;
		// check if the panel is fully up
		if ( this.currentPosition > 0) {
			// stubtract the slied step value to the new position
			this.currentPosition -= this.slideStep;
			// if the current position is less than zero then it has gone 
			// to far, so set it to zero, the fully up position.
			if ( this.currentPosition < 0) {
				this.currentPosition = 0;
			}
			// adjust the top position of the panel
			this.slideOutDivObject.style.top = this.topOffset + this.currentPosition + "px";
			try {

				this.slideOutDivObject.style.clip = "rect(" + (this.panelBarHeight - this.currentPosition) + "px, " + this.panelBarWidth + "px, " + this.panelBarHeight + "px, 0px)";
			} catch(e) {
			}
			if ( 0 == this.currentPosition) {
				this.movingSlider = false;
			}
		}
		if ( this.currentPosition > 0) {
			setTimeout( this.objectName + ".slideUpPanelBar2( false)", this.slideSpeed);
		}
	}
	this.closeTabPanels = function() {
		for ( i=0; i<this.panelItemsIDArray.length; ++i) {
			this.panel.GetPanelItemById( this.panelItemsIDArray[i]).Collapse();
		}
	}
}
/* End Slide out panel bar scripts */
/*-------------------------------------------------------------------------------*/

// Get window size
function getWindowSize() {
	var myWidth = 0, myHeight = 0;
	if( typeof( window.innerWidth ) == 'number' ) {
		//Non-IE
		myWidth = window.innerWidth;
		myHeight = window.innerHeight;
	} else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
		//IE 6+ in 'standards compliant mode'
		myWidth = document.documentElement.clientWidth;
		myHeight = document.documentElement.clientHeight;
	} else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
		//IE 4 compatible
		myWidth = document.body.clientWidth;
		myHeight = document.body.clientHeight;
	}
	return {width: myWidth, height: myHeight};
}

// Get scroll bar position
function getScrollPositions() {
	var scrollTop = 0, scrollLeft = 0;
	if (window.pageYOffset){  
		scrollTop = window.pageYOffset ;
		scrollLeft = window.pageXOffset ;
	} else if(document.documentElement && document.documentElement.scrollTop){ 
		scrollTop = document.documentElement.scrollTop; 
		scrollLeft = document.documentElement.scrollLeft; 
	} else if(document.body){ 
		scrollTop = document.body.scrollTop;
		scrollLeft = document.body.scrollLeft; 
	} 
	return {scrollLeft: scrollLeft, scrollTop: scrollTop};
}

function clearTimeAndReload(redirectToView){
	var currentTime = new Date().getTime();
	if(redirectToView != ''){
		window.parent.location = 'default.aspx?cvn='+redirectToView +'&ResetStartTime='+ currentTime;
	} else {
		window.parent.location = 'default.aspx?ResetStartTime='+ currentTime;
	}	
}

/* Refresh a given frame  */
/* Or load the given view if required */
function refreshFrame( frameID, childViewName, queryString)
{
	var frame = getFrame( frameID );
	if ( frame != null ){
		if(pleaseWaitEnabled == 'true'){
			pleasewait(frame, 'Small');
		}
		if ( childViewName != '' ){
			var currentTime =  new Date().getTime();
			frame.contentWindow.location = 'default.aspx?Child='+ childViewName +  '&ResetStartTime=' + currentTime + '&' + queryString;
		}else{
			parent.frames[frameID].location.href='default.aspx';
		}
	}else{
		// Do nothing
		//alert('Cannot find Frame ID: ' + frameID );
	}
}

/* Refresh current frame */
function refreshThisFrame( childViewName, queryString)
{
	if ( childViewName == null ){
		if( this.frameElement != null ){
			this.frameElement.src = void(0);
		}
	}else{
		var currentTime =  new Date().getTime();
		this.document.location.href = 'default.aspx?Child='+ childViewName + '&ResetStartTime=' + currentTime + '&' + queryString;
	}
}

/* Find a frame based on a given element ID  */
function getFrame( frameID )
{
	var topFrame = document.frames.top;
	for ( var i=0; i < topFrame.document.frames.length ; i ++ ){
		var foundFrame = topFrame.document.frames[i] ;
		if ( foundFrame != null && foundFrame.frameElement != null && ( foundFrame.frameElement.id == frameID || foundFrame.frameElement.name == frameID )) {
			return foundFrame.frameElement;
		}
	}
	return null;
}

/* Run a method thats ina  different frame */
/* Use null or '' as the frameID to run a method on the main window  */
/* returns true if successful, and false incase of an error */
function getFrameRunFunction( frameID, funcNameAndParams )
{
	// Run the method on the top window
	if ( frameID == '' || frameID == null ){
		try {		
			eval( 'document.frames.top.window.document.Script.' + funcNameAndParams + ';'); 
			return true;
		}catch(err){
		}
	}else{
		// Run the method in a named frame
		var frame = getFrame(frameID );
		if ( frame != null ){
			try {		
				eval( 'frame.contentWindow.document.Script.' + funcNameAndParams + ';'); 
				return true;
			}catch(err){
			}
		}
	}
	return false;
}


function pleasewait(Frame,SizeIn){
	var WaitSmallHtml ='<center><p  style="margin-top:100px "></p><p><img src="/Images/Progress/loading.gif" width="130" height="60"></p></center>';
	var WaitBigHtml ='<center><p  style="margin-top:100px "></p><p><img src="/Images/Progress/loading.gif" width="130" height="60"></p></center>';
 
 
	if(SizeIn == "Big"){
 		Frame.contentWindow.document.write(WaitBigHtml);
	}else if(SizeIn == "Small"){
		Frame.contentWindow.document.write(WaitSmallHtml);
	} else {
 		Frame.contentWindow.document.write(WaitSmallHtml);
	} 
}


function pleasewait2(DivNameIn,SizeIn){
	// preload the images before the html elements are shown. Otherwise, sometimes the images dont have time to load before each postback.
     if (document.images){
	    preloadImgObj = new Image();
		preloadImgObj.src = '/images/spacer.gif';
		preloadImgObj.src = '/Images/Progress/loading.gif';
		//preloadImgObj.src = '/Images/Progress/loadinggray.gif';
		//preloadImgObj.src = '/Images/Progress/spin.gif';
	}
	// End preload image
	var divTop = GetObject(DivNameIn); 	
	var WaitSmallHtml ='<center><table border="0" cellspacing="0" cellpadding="0" width="200" >';
		WaitSmallHtml += '<tr><td class="bTl"><img src="/images/spacer.gif" height="10" width="10"></td><td class="bT"></td><td class="bTr"></td></tr>';
		WaitSmallHtml += '<tr><td class="bL"></td><td class="bM" align="left"><p align="center"></strong><strong><img src="/Images/Progress/loading.gif" width="130" height="60" /></p></td><td class="bRR"></td></tr>';
		WaitSmallHtml += '<tr><td class="bBl"></td><td class="bB"></td><td class="bBr"><img src="/images/spacer.gif" height="10" width="10"></td></tr></table></center>';
	var WaitBigHtml ='<center><table width="250" border="0" cellpadding="0" cellspacing="0" ><tbody><tr><td class="boxTopLeft"><img src="/images/spacer.gif" height="10" width="10"></td><td class="boxTop"></td><td class="boxTopRight"></td></tr>';
      		WaitBigHtml += '<tr><td class="boxLeft"></td><td class="boxMain"><!-- Inner table --><table border="0" cellpadding="0" cellspacing="5" width="100%">';
       		WaitBigHtml += '<tbody><tr><td><p align="center"><img src="/Images/Progress/loading.gif" width="130" height="60" /></p></td>';
                WaitBigHtml += '</tr></tbody></table></td><td class="boxRight"></td></tr><tr><td class="boxBottomLeft"></td><td class="boxBottom"></td><td class="boxBottomRight"><img src="/images/spacer.gif" height="10" width="10"></td>';
     		WaitBigHtml += '</tr></tbody></table></center>';
 
	if(SizeIn == "Big"){
 		divTop.innerHTML=WaitBigHtml;
	}else if(SizeIn == "Small"){
		divTop.innerHTML=WaitSmallHtml;
	} else {
 		divTop.innerHTML=WaitSmallHtml;
	}
	repositionPleaseWait();
	// Firefox 1 doesnt support on resize and onscroll was buggy in firefox 1. Fixed in 2.0 i think.
	var ie4 = (document.all != null);
	if (ie4) {
		window.onscroll = repositionPleaseWait;
		window.onresize = repositionPleaseWait;
	  }
}

function repositionPleaseWait()
{
	var windowSize = getWindowSize();
	var scrollPosition = getScrollPositions();
	var divTop = GetObject('divTop'); 	
	divTop.style['display'] = 'block';
    divTop.style['top'] =  ( (windowSize.height / 2) + scrollPosition.scrollTop ) - 100;
	divTop.style['left'] =  ( (windowSize.width / 2) + scrollPosition.scrollLeft ) - 100;
}



