
/*******************************************************************************************
 * Component:  lpas.js - Scripts used for LPAS application specific functions.
 *
 * Modification History:
 *
 * Date       Task# Who    Description
 * ---------- ----- ------ -----------------------------------------------------------------
 * 04-02-2004	      myan0  Created.
 * 18-02-2004       phoo0  Incorporated client review comments
 * 15-03-2004       phoo0  Added functions for Popups
 * 29-03-2004       phoo0  Change the delimiter from comma (,) to hat (^) character
 * 05-04-2004       myan0  Code review & cleanup
 * 27-08-2004       dafra0 Added p_allowOtherOwners parameter to PopupCourseSearch.
 * 08-09-2004    89 dafra0 Added p_allowAllUsers parameter to PopupUserSearch.
 * 13-09-2004    94 awon0  Added PopupOrganisationSearch function.
 * 29-09-2004   108 dafra0 Added functions to Select and Deselect all checkboxes.
 *                         Also added p_mode and p_isPopupControl parameters to PopupUserSearchSubmit().
 * 08/10/2004   112 dafra0 Added ReturnToApplication function.
 * 08/10/2004   114 dafra0 Added GetParameterValue and CreateButtonElement functions.
 * 08/10/2004   115 dafra0 Added DisableField function.
 * 08/10/2004   128 dafra0 Added AddDummyField function.
 * 03/12/2004   129 dafra0 Added AddProcessingFlagToObject function.
 * 22/12/2004   151 dafra0 Handle radio buttons in AtLeastOneSeachCriterionRequired.
 * 23/08/2005       rwil0  Added PopupGroupSearch
 * 29/08/2005       rwil0  Added PopupGroupSearchForListBox
 * 31/08/2005       rwil0  Added PopupGroupMembership
 * 07/09/2005       rwil0  Added SetMaintainResourceCentreButtons, 
 *                         SelectListAutoPostBackRestore,SelectListAutoPostBack
 * 18/01/2006   239 awon0  Add SendBackListBoxItem function to be called by CX functionality
 * 29/05/2006   LP3 cpen0  DCR_017 AddTimeStamp added.
 * 16/06/2006   LP3 cpen0  DCR_012a updated UnverifyUser
 * 30/08/2006   WP3 cpen0  Affiliates - PopupOrganisation. PopupCentre change. ToolsetOnChange.
 * 18/10/2006       awon0  Add new function OpenLPHelp - to open appropriate help from
 *                         LP banner
 * 24/11/2006       cpen0  Added Generic users functions
 * 31/01/2007       cpen0  Added PasswordValidCharacters.
 * 05/03/2007       awon0  Client review: modifications to PasswordValidCharacters.
 * 01/08/2007       cpen0  Modified the split Char in PasswordValidCharacters.
 * 09/08/2007       cpen0  Modified PopupCentre and added UpdateChkbox.
 * 27/08/2007       cpen0  Modified PopupCentre.
 * 02/05/2008       cpen0  Added ToggleRole.
 *******************************************************************************************/

var m_delimiter = "^";
var m_txtText = "_txtText";
var m_txtValue = "_txtValue";
var m_txtSelectedValue = "_txtSelectedValue";
var m_divPopupContainer = "_divPopupContainer";
var m_recordNotSelectedMessage = "Please make a selection.";



/*******************************************************************************************
 * Name:         CopyItems
 * Description:  Function that copies items between two list boxes based on whether they
 *               are selected or not. Duplicate Items (text and value) are not copied.
 * Parameters:   p_sourceListId - the source list box.
 *               p_destinationListId - the destination list box.
 *******************************************************************************************/
function CopyItems(p_sourceListId, p_destinationListId) {
  // DOM check.
  if (document.getElementById) {
  
    // Reference the elements based on the id passed.
    var sourceList = document.getElementById(p_sourceListId);
    var destinationList = document.getElementById(p_destinationListId);
    var selectedItems = new Array();
    var i = 0;
    var j = 0;
    var k = 0;
    var itemAlreadyCopied = false;
    
    // Loop through all options of the source list.
    while (sourceList.options[i]) {
    
      // Re-initialise the index & result for searching through the detaination list
      k = 0;
      itemAlreadyCopied = false;
      
      // If option is selected then add index number to array.  
      if (sourceList.options[i].selected) {
      
        // Check if the current selected option is already in the destination list
        while (destinationList.options[k]) { 
        
          if (destinationList.options[k].value == sourceList.options[i].value) {
            itemAlreadyCopied = true;
            break;
          }
          k++;
        }
        if (!(itemAlreadyCopied)) {
        
          // Item is not already in the destination list so add it.
          selectedItems[j] = i;
          j++;
        }
      }
      i++;
    }
    
    // Add all the items from source list to destination.
    for (var k=0;k<selectedItems.length;k++) {
      AddItem(destinationList, sourceList.options[selectedItems[k]].text, sourceList.options[selectedItems[k]].value);
    }
  }
}

/*******************************************************************************************
 * Name:         CopyItemsGenericUsers
 * Description:  Function that copies items between two list boxes based on whether they
 *               are selected or not. Duplicate Items (text and value) are not copied.
 *               Generic users veriation.
 * Parameters:   p_sourceListId - the source list box.
 *               p_destinationListId - the destination list box.
 *******************************************************************************************/
function CopyItemsGenericUsers(p_sourceListId, p_destinationListId) {
  // DOM check.
  if (document.getElementById) {
  
    // Reference the elements based on the id passed.
    var sourceList = document.getElementById(p_sourceListId);
    var destinationList = document.getElementById(p_destinationListId);
    var selectedItems = new Array();
    var i = 0;
    var j = 0;
    var k = 0;
    var itemAlreadyCopied = false;
    
    // Loop through all options of the source list.
    while (sourceList.options[i]) {
    
      // Re-initialise the index & result for searching through the detaination list
      k = 0;
      itemAlreadyCopied = false;
      
      // If option is selected then add index number to array.  
      if (sourceList.options[i].selected) {
      
        // Check if the current selected option is already in the destination list
        while (destinationList.options[k]) { 
        
          if (destinationList.options[k].value.substring(0,destinationList.options[k].value.indexOf('-')) == sourceList.options[i].value) {
            itemAlreadyCopied = true;
            break;
          }
          k++;
        }
        if (!(itemAlreadyCopied)) {
        
          // Item is not already in the destination list so add it.
          selectedItems[j] = i;
          j++;
        }
      }
      i++;
    }
    
    // Add all the items from source list to destination.
    for (var k=0;k<selectedItems.length;k++) {
      AddItem(destinationList, sourceList.options[selectedItems[k]].text + ' - ROLE: Student', sourceList.options[selectedItems[k]].value + '-S');
    }
  }
}

/*******************************************************************************************
 * Name:         RemoveItems
 * Description:  Function that removes items from a list box based on whether they
 *               are selected or not.
 * Parameters:   p_listId - the list box.
 *******************************************************************************************/
function RemoveItems(p_list) { 

  // DOM check.
  if (document.getElementById) {
  
    // Reference the elements based on the id passed.
    var list = document.getElementById(p_list);
    var selectedItems = new Array();
    var i = 0;
    var j = 0;
    
    // Loop through all options of the source list.
    while (list.options[i]) {
    
      // If option is selected then add index number to array.
      if (list.options[i].selected) {
        selectedItems[j] = i;
        j++;
      }
      i++;
    }

    // Remove all selected items from list.
    for (var k=selectedItems.length-1;k>-1;k--) {
      RemoveItem(list, selectedItems[k]);
    }
  }
}

/*******************************************************************************************
 * Name:         PopupGenericUser
 * Description:  Function to popup window to allow selection of Generic Users.
 * Parameters:   p_mode - mode for popup (single or multiple).
 *               p_parentTarget - target element id in calling page.
 *******************************************************************************************/
function PopupGenericUser(p_mode, p_parentTarget) {
  var popupWidth = 786;
  var popupHeight = 540;
    
  // DOM check.
  if (document.getElementById) {
    var url = "/lpas/genericuser/PopupGenericUser.aspx?Mode=" + p_mode + "&Target=" + p_parentTarget;
    OpenSimulatedModalDialog(url, popupWidth, popupHeight);
  }
}

/*******************************************************************************************
 * Name:         PopupGenericUserSearch
 * Description:  Function to popup window to allow selection of a generic user and resubmit the 
 *               calling page URL with the code of the user selected as a param.
 * Parameters:   p_mode - mode for popup (single or multiple).
 *               p_targetURL - target URL to redirect to on return of result.
 *               p_idTargetItem - id of Target Item to use to pass result to redirect page.
 *******************************************************************************************/
function PopupGenericUserSearch(p_targetURL, p_idParamName) {
  var popupWidth = 786;
  var popupHeight = 540;
    
  // DOM check.
  if (document.getElementById) {
    var url = "/lpas/genericuser/PopupGenericUser.aspx?Mode=single" + "&URL=" + encodeURIComponent(p_targetURL) +  "&ParamName=" + p_idParamName;
    OpenSimulatedModalDialog(url, popupWidth, popupHeight);
  }
  return false;
}

/*******************************************************************************************
 * Name:         PopupOrganisation
 * Description:  Function to popup window to allow selection of Organisations.
 * Parameters:   p_mode - mode for popup (single or multiple).
 *               p_parentTarget - target element id in calling page.
 *               p_editable - Where the popup should return to a readonly control. 
 *              'Y' for yes, else for No.
 *******************************************************************************************/
function PopupOrganisation(p_mode, p_parentTarget) {
  var popupWidth = 786;
  var popupHeight = 540;

  // DOM check.
  if (document.getElementById) {
    var url = "/lpas/public/organisation/PopupOrganisation.aspx?Mode=" + p_mode + "&Target=" + p_parentTarget;
       
    OpenSimulatedModalDialog(url, popupWidth, popupHeight);
  }

}

/*******************************************************************************************
 * Name:         PopupOrganisationSearch
 * Description:  Function to popup window to allow selection of an organisation and resubmit the 
 *               calling page URL with the code of the organisation selected as a param.
 * Parameters:   p_targetURL - target URL to redirect to on return of result.
 *               p_idParamName - id of parameter to use to pass result to redirect page.
 *******************************************************************************************/
function PopupOrganisationSearch(p_targetURL, p_idParamName) {
  var popupWidth = 786;
  var popupHeight = 540;
  
  try { 
   
    // DOM check.
    if (document.getElementById) {

      var url = "/lpas/public/organisation/PopupOrganisation.aspx?Mode=single" + "&URL=" + encodeURIComponent(p_targetURL) + "&ParamName=" + p_idParamName; 

      OpenSimulatedModalDialog(url, popupWidth, popupHeight);

    }
    return false;
  }
    catch(e)
  {
		
  }
  
}

/*******************************************************************************************
 * Name:         PopupCourseGenericUser
 * Description:  Function to popup window to allow selection of Courses for Generic users.
 * Parameters:   p_mode - mode for popup (single or multiple).
 *               p_parentTarget - target element id in calling page.
 *               p_courseLevel - course level to present in popup.
 *******************************************************************************************/
function PopupCourseGenericUser(p_mode, p_parentTarget, p_courseLevel) {
  var popupWidth = 786;
  var popupHeight = 600;
    
  // DOM check.
  if (document.getElementById) {
    var url = "/lpas/GenericUser/PopupCourseGenericUser.aspx?Mode=" + p_mode + "&Target=" + p_parentTarget + "&CourseLevel=" + p_courseLevel;
    OpenSimulatedModalDialog(url, popupWidth, popupHeight);
  }
}

/*******************************************************************************************
 * Name:         PopupCommunityGenericUser
 * Description:  Function to popup window to allow selection of Communities for generic users.
 * Parameters:   p_mode - mode for popup (single or multiple).
 *               p_parentTarget - target URL to redirect to on return of result.
 *******************************************************************************************/
function PopupCommunityGenericUser(p_mode, p_parentTarget) {
  var popupWidth = 786;
  var popupHeight = 600;
    
  // DOM check.
  if (document.getElementById) {
    var url = "/lpas/GenericUser/PopupCommunityGenericUsers.aspx?Mode=" + p_mode + "&Target=" + p_parentTarget;
    OpenSimulatedModalDialog(url, popupWidth, popupHeight);
  }
}

/*******************************************************************************************
 * Name:         PopupCourse
 * Description:  Function to popup window to allow selection of Courses.
 * Parameters:   p_mode - mode for popup (single or multiple).
 *               p_parentTarget - target element id in calling page.
 *               p_courseLevel - course level to present in popup.
 *******************************************************************************************/
function PopupCourse(p_mode, p_parentTarget, p_courseLevel) {
  var popupWidth = 786;
  var popupHeight = 540;
    
  // DOM check.
  if (document.getElementById) {
    var url = "/lpas/course/PopupCourse.aspx?Mode=" + p_mode + "&Target=" + p_parentTarget + "&CourseLevel=" + p_courseLevel;
    OpenSimulatedModalDialog(url, popupWidth, popupHeight);
  }
}

/*******************************************************************************************
 * Name:         PopupCourseSearch
 * Description:  Function to popup window to allow selection of a course and resubmit the 
 *               calling page URL with the code of the course selected as a param.
 * Parameters:   p_courseLevel - course level to present in popup.
 *               p_targetURL - target URL to redirect to on return of result.
 *               p_idParamName - id of parameter to use to pass result to redirect page.
 *               p_displaySingleOccurrences - 
 *               p_allowOtherOwners - 
 *               p_allowVssAdmin - 
 *******************************************************************************************/
function PopupCourseSearch(p_courseLevel, p_targetURL, p_idParamName, p_displaySingleOccurrences, p_allowOtherOwners, p_allowVssAdmin) {
  var popupWidth = 786;
  var popupHeight = 540;

  try { 
   
    // DOM check.
    if (document.getElementById) {

      var url = "/lpas/course/PopupCourse.aspx?Mode=single" + "&URL=" + encodeURIComponent(p_targetURL) + "&CourseLevel=" + p_courseLevel + "&ParamName=" + p_idParamName + "&DisplaySingleOccurrences=" + p_displaySingleOccurrences + "&AllowOtherOwners=" + p_allowOtherOwners + "&AllowVSSAdmin=" + p_allowVssAdmin; 

      OpenSimulatedModalDialog(url, popupWidth, popupHeight);

    }
    return false;
  }
    catch(e)
  {
		
  }
  
}

/*******************************************************************************************
 * Name:         PopupCourseSearchTargetSubmit
 * Description:  Function to popup window to allow selection of a course and resubmit the 
 *               calling page URL with the code of the course selected as a param, injecting 
 *               into a hidden field.
 * Parameters:   p_courseLevel - course level to present in popup.
 *               p_targetURL - target URL to redirect to on return of result.
 *               p_idParamName - id of parameter to use to pass result to redirect page.
 *               p_displaySingleOccurrences - Display single occurances
 *               p_allowOtherOwners - allow other owners
 *               p_allowVssAdmin - Allow vss admin access
 *               p_parentTarget - The hidden field Id to put selected ID into
 *******************************************************************************************/
function PopupCourseSearchTargetSubmit(p_courseLevel, p_targetURL, p_idParamName, p_displaySingleOccurrences, p_allowOtherOwners, p_allowVssAdmin, p_parentTarget) {
  var popupWidth = 786;
  var popupHeight = 540;

  try { 
   
    // DOM check.
    if (document.getElementById) {

      var url = "/lpas/course/PopupCourse.aspx?Mode=single" + "&CourseLevel=" + p_courseLevel + "&ParamName=" + p_idParamName + "&DisplaySingleOccurrences=" + p_displaySingleOccurrences + "&AllowOtherOwners=" + p_allowOtherOwners + "&AllowVSSAdmin=" + p_allowVssAdmin + "&Target=" + p_parentTarget + "&Action=submit"; 

      OpenSimulatedModalDialog(url, popupWidth, popupHeight);

    }
    return false;
  }
    catch(e)
  {
		
  }
  
}

/*******************************************************************************************
 * Name:         PopupCourseSearchSubmit
 * Description:  Function to popup window to allow selection of a course and resubmit the 
 *               calling page form.
 * Parameters:   p_courseLevel - course level to present in popup.
 *               p_parentTarget - id of the element on the parent page to populate.
 *******************************************************************************************/
function PopupCourseSearchSubmit(p_courseLevel, p_parentTarget) {
  var popupWidth = 786;
  var popupHeight = 540;
    
  // DOM check.
  if (document.getElementById) {
    var url = "/lpas/course/PopupCourse.aspx?Mode=single" + "&CourseLevel=" + p_courseLevel + "&Target=" + p_parentTarget + "&Action=submit";
    OpenSimulatedModalDialog(url, popupWidth, popupHeight);
        
  }
  return false;
}

/*******************************************************************************************
 * Name:         PopupGenericUserSearchMultiSubmit
 * Description:  Function to popup window to allow selection of a generic user and resubmit the 
 *               calling page form.
 * Parameters:   p_mode - mode of the popup.
 *               p_parentTarget - id of the element on the parent page to populate.
 *******************************************************************************************/
function PopupGenericUserSearchMultiSubmit(p_mode, p_parentTarget) {
  var popupWidth = 786;
  var popupHeight = 540;
    
  // DOM check.
  if (document.getElementById) {
		var url = "/lpas/genericuser/PopupGenericUser.aspx?Mode=" + p_mode + "&Target=" + p_parentTarget + "&Action=submit";
    OpenSimulatedModalDialog(url, popupWidth, popupHeight);
  }
  return false;
}

/*******************************************************************************************
 * Name:         PopupCommunitySearch
 * Description:  Function to popup window to allow selection of a user and resubmit the 
 *               calling page URL with the code of the community selected as a param.
 * Parameters:   p_targetURL - target URL to redirect to on return of result.
 *               p_idParamName - id of parameter to use to pass result to redirect page.
 *******************************************************************************************/
function PopupCommunitySearch(p_targetURL, p_idParamName) {
  var popupWidth = 786;
  var popupHeight = 540;
    
  // DOM check.
  if (document.getElementById) {
    var url = "/lpas/community/PopupCommunity.aspx?Mode=single" + "&URL=" + encodeURIComponent(p_targetURL) + "&ParamName=" + p_idParamName;
    OpenSimulatedModalDialog(url, popupWidth, popupHeight);
  }
  return false;
}

/*******************************************************************************************
 * Name:         PopupCommunitySearchSubmit
 * Description:  Function to popup window to allow selection of a community and resubmit the 
 *               calling page form.
 * Parameters:   p_parentTarget - id of the element on the parent page to populate.
 *******************************************************************************************/
function PopupCommunitySearchSubmit(p_parentTarget) {
  var popupWidth = 786;
  var popupHeight = 540;
    
  // DOM check.
  if (document.getElementById) {
    var url = "/lpas/community/PopupCommunity.aspx?Mode=single" + "&Target=" + p_parentTarget + "&Action=submit";
    OpenSimulatedModalDialog(url, popupWidth, popupHeight);
  }
  return false;
}

/*******************************************************************************************
 * Name:         PopupUserSearch
 * Description:  Function to popup window to allow selection of a user and resubmit the 
 *               calling page URL with the code of the user selected as a param.
 * Parameters:   p_userRoles - user roles to present in popup.
 *               p_targetURL - target URL to redirect to on return of result.
 *               p_idParamName - id of parameter to use to pass result to redirect page.
 *               p_occurrenceId - course occurrence id to return participants of a course.
 *               p_allowAllUsers - whether to check for the All Users role.
 *******************************************************************************************/
function PopupUserSearch(p_userRoles, p_targetURL, p_idParamName, p_occurrenceId, p_allowAllUsers) {
  var popupWidth = 786;
  var popupHeight = 540;
    
  // DOM check.
  if (document.getElementById) {
    if (p_occurrenceId == undefined) {
			p_occurrenceId = "";
		}
		    
    var url = "/lpas/user/PopupUser.aspx?Mode=single" + "&URL=" + encodeURIComponent(p_targetURL) + "&UserRole=" + p_userRoles + "&ParamName=" + p_idParamName + "&OccurrenceID=" + p_occurrenceId + "&AllUsers=" + p_allowAllUsers;
    OpenSimulatedModalDialog(url, popupWidth, popupHeight);
  }
  return false;
}

/*******************************************************************************************
 * Name:         PopupUserSearchSubmit
 * Description:  Function to popup window to allow selection of a user and resubmit the 
 *               calling page URL with the code of the user selected as a param.
 * Parameters:   p_userRoles - user roles to present in popup.
 *               p_parentTarget - id of the element on the parent page to populate.
 *******************************************************************************************/
function PopupUserGroupsSearch(p_userRoles, p_parentTarget, p_occurrenceId, p_mode, p_isPopupControl, p_allowAllUsers, p_lstNonPopupcontrol, p_groupLst, p_exN) {
  var popupWidth = 786;
  var popupHeight = 540;
  
  // DOM check.
  if (document.getElementById) {
		if (p_occurrenceId == undefined) {
			p_occurrenceId = "";
    }
    
    if (p_mode == undefined) {
			p_mode = "single";
    }
    
    if (p_isPopupControl == undefined) {
			p_isPopupControl = "Y";
    }
    
    if (p_allowAllUsers == undefined) {
			p_allowAllUsers = "N";
    }
    
    if (p_lstNonPopupcontrol == undefined){
      p_lstNonPopupcontrol = "N";
    }
    
    if (p_exN == undefined){
      p_exN = "N";
    }
    
    var listBox = document.getElementById(p_groupLst); 
    
    if (listBox.selectedIndex != -1){
    
      var groupId = listBox.options[listBox.selectedIndex].value

      groupId = groupId.substring(0, groupId.indexOf("|"));   
      
      if (groupId == undefined) {
			  groupId = "";
      }
      
      var url = "/lpas/cx/PopupTLEGroupUser.aspx?Mode=" + p_mode + "&UserRole=" + p_userRoles + "&Target=" + p_parentTarget + "&Action=submit&OccurrenceID=" + p_occurrenceId + "&IsPopupControl=" + p_isPopupControl + "&AllUsers=" + p_allowAllUsers + "&lnp=" + p_lstNonPopupcontrol + "&gID=" + groupId + "&exN=" + p_exN;
      OpenSimulatedModalDialog(url, popupWidth, popupHeight);
      
    }else{
      alert('Please select a group.'); 
    }
  }
  return false;
}

/*******************************************************************************************
 * Name:         PopupUserSearchSubmit
 * Description:  Function to popup window to allow selection of a user and resubmit the 
 *               calling page URL with the code of the user selected as a param.
 * Parameters:   p_userRoles - user roles to present in popup.
 *               p_parentTarget - id of the element on the parent page to populate.
 *******************************************************************************************/
function PopupUserSearchSubmit(p_userRoles, p_parentTarget, p_occurrenceId, p_mode, p_isPopupControl, p_allowAllUsers, p_lstNonPopupcontrol) {
  var popupWidth = 786;
  var popupHeight = 540;

  // DOM check.
  if (document.getElementById) {
		if (p_occurrenceId == undefined) {
			p_occurrenceId = "";
    }
    
    if (p_mode == undefined) {
			p_mode = "single";
    }
    
    if (p_isPopupControl == undefined) {
			p_isPopupControl = "Y";
    }
    
    if (p_allowAllUsers == undefined) {
			p_allowAllUsers = "N";
    }
    
    if (p_lstNonPopupcontrol == undefined){
      p_lstNonPopupcontrol = "N";
    }
    
    var url = "/lpas/user/PopupUser.aspx?Mode=" + p_mode + "&UserRole=" + p_userRoles + "&Target=" + p_parentTarget + "&Action=submit&OccurrenceID=" + p_occurrenceId + "&IsPopupControl=" + p_isPopupControl + "&AllUsers=" + p_allowAllUsers + "&lnp=" + p_lstNonPopupcontrol;
    OpenSimulatedModalDialog(url, popupWidth, popupHeight);
  }
  return false;
}

/*******************************************************************************************
 * Name:         PopupCommunity
 * Description:  Function to popup window to allow selection of Communities.
 * Parameters:   p_mode - mode for popup (single or multiple).
 *               p_parentTarget - target URL to redirect to on return of result.
 *******************************************************************************************/
function PopupCommunity(p_mode, p_parentTarget) {
  var popupWidth = 786;
  var popupHeight = 540;
    
  // DOM check.
  if (document.getElementById) {
    var url = "/lpas/community/PopupCommunity.aspx?Mode=" + p_mode + "&Target=" + p_parentTarget;
    OpenSimulatedModalDialog(url, popupWidth, popupHeight);
  }
}

/*******************************************************************************************
 * Name:         PopupUser
 * Description:  Function to popup window to allow selection of Users.
 * Parameters:   p_mode - mode for popup (single or multiple).
 *               p_parentTarget - target element id in calling page.
 *               p_userRole - user role criteria to pass into popup.
 *******************************************************************************************/
function PopupUser(p_mode, p_parentTarget, p_userRole, p_occurrenceId) {
  var popupWidth = 786;
  var popupHeight = 540;
   
  // DOM check.
  if (document.getElementById) {
    
    // Handle optional parameter
    if (!(p_userRole)) {
      p_userRole = "";
    }
  
		if ( p_occurrenceId == undefined) {
			p_occurrenceId = "";
    }
      
    var url = "/lpas/user/PopupUser.aspx?Mode=" + p_mode + "&Target=" + p_parentTarget + "&UserRole=" + p_userRole + "&OccurrenceID=" + p_occurrenceId;

    OpenSimulatedModalDialog(url, popupWidth, popupHeight);
  }
}

/*******************************************************************************************
 * Name:         PopupVSSUser
 * Description:  Function to popup window to allow selection of Users.
 * Parameters:   p_mode - mode for popup (single or multiple).
 *               p_parentTarget - target element id in calling page.
 *               p_userRole - user role criteria to pass into popup.
 *******************************************************************************************/
function PopupVSSUser(p_mode, p_parentTarget, p_userRole, p_fromReceivingCentresOnly,p_descFieldId, p_userTypes, p_centreCode,p_showVSSClasses) {
  var popupWidth = 786;
  var popupHeight = 540;
   
  // DOM check.
  if (document.getElementById) {
    
    // Handle optional parameter
    if (!(p_userRole)) {
      p_userRole = "";
    }
    
    if (p_fromReceivingCentresOnly == undefined) {     
			p_fromReceivingCentresOnly = "";
    }
    
    if (p_userTypes == undefined) {
		  p_userTypes = "";
    }

    
    if (p_centreCode == undefined){
      p_centreCode = "";
    }
          
    var url = "/lpas/VSS/VSSUser/PopupVSSUser.aspx?Mode=" + p_mode + "&Target=" + p_parentTarget + "&UserRole=" + p_userRole + "&FromRecCtr=" + p_fromReceivingCentresOnly + "&UserType=" + p_userTypes + "&CentreCode=" + p_centreCode + "&ShowClasses=" + p_showVSSClasses;
    
    if (p_descFieldId != undefined) {
      url += "&DescFieldId=" + p_descFieldId
    }
    
    OpenSimulatedModalDialog(url, popupWidth, popupHeight);
  }
}

/*******************************************************************************************
 * Name:         PopupAffiliateUser
 * Description:  Function to popup window to allow selection of Users.
 * Parameters:   p_mode - mode for popup (single or multiple).
 *               p_parentTarget - target element id in calling page.
 *               p_descFieldId - description field id.
 *               p_userTypeCategory - user type category criteria to pass into popup.
 *               p_centreOrOrgKey - Centre code or organisation id in the form "Y|<cCtr_Cd>" "N|<orgid>" criteria to pass into popup.
 *******************************************************************************************/
function PopupAffiliateUser(p_mode, p_parentTarget, p_descFieldId, p_userTypeCategory, p_centreOrOrgKey) {
  var popupWidth = 786;
  var popupHeight = 540;
   
  // DOM check.
  if (document.getElementById) {
    
    // Handle optional parameter
    if (p_userTypeCategory == undefined) {
		  p_userTypeCategory = "";
    }
    
    if (p_centreOrOrgKey == undefined){
      p_centreOrOrgKey = "";
    }
          
    var url = "/lpas/Affiliate/PopupAffiliateUser.aspx?Mode=" + p_mode + "&Target=" + p_parentTarget + "&UserTypeCat=" + p_userTypeCategory + "&CentreOrOrgKey=" + p_centreOrOrgKey;
    
    if (p_descFieldId != undefined) {
      url += "&DescFieldId=" + p_descFieldId
    }
    
    OpenSimulatedModalDialog(url, popupWidth, popupHeight);
  }
}


function SendBackItem(p_mode, p_listboxID, p_listValue, p_listText){

  if (document.getElementById) {
  
    //grab the listbox
    var listbox = opener.document.getElementById(p_listboxID);
    
      //determine mode
    if (p_mode == "EDIT"){
            
      //find the correct element
      listbox.options[listbox.selectedIndex].text = p_listText;
      listbox.options[listbox.selectedIndex].value = p_listValue;
      
      //change the Text and the Value
          
    }else{
    
      //ADD
      //Inject a new list Item into the Listbox
      var oOption = opener.document.createElement("OPTION");
		  listbox.options.add(oOption);
		  oOption.innerText = p_listText;
		  oOption.value = p_listValue;

    }
    
    CloseWindow();
    
  }

}

/*******************************************************************************************
 * Name:         SendBackListBoxItem
 * Description:  Function to send back CX group details to a listbox control which is called
 *               to maintain (CX) resource centres
 * Parameters:   p_mode - mode for popup (Add or Edit).
 *               p_listboxID - Id of the listbox entry in calling control.
 *               p_listValue - Value/identifier of the entry in the listbox.
 *               p_listText  - Text/description of the listbox entry.
 *               p_Success   - Indicator if add/update of listbox entry on popup succeeded.
 *                             If not successful, do not close popup window.
 *******************************************************************************************/

function SendBackListBoxItem(p_mode, p_listboxID, p_listValue, p_listText, p_Success){

  if (document.getElementById) {
  
    //grab the listbox
    var listbox = opener.document.getElementById(p_listboxID);
    
      //determine mode
    if (p_mode == "EDIT"){
            
      //find the correct element
      listbox.options[listbox.selectedIndex].text = p_listText;
      listbox.options[listbox.selectedIndex].value = p_listValue;
         
    }else{
    
      //ADD
      //Inject a new list Item into the Listbox
      var oOption = opener.document.createElement("OPTION");
		  listbox.options.add(oOption);
		  oOption.innerText = p_listText;
		  oOption.value = p_listValue;

    }
   
   // If the add/update failed, show message prior to closing popup
   if (p_Success == "N")
   {
     if (p_mode == "EDIT"){
			 alert( "Update of this group failed in the TLE integration database.");
     }else{
   		 alert("Creation of this group failed in the TLE integration database.");
     }
   } 
   
	 CloseWindow();
  }
 
}

/*******************************************************************************************
 * Name:         PopupUserTypeGroups
 * Description:  Function to popup user type groups. 
 * Parameters:   nil
 *******************************************************************************************/
function PopupUserTypeGroups(){
  
  if (document.getElementById) {
  
    var popupWidth = 500;
    var popupHeight = 700;
    
    var url = "/lpas/cx/usertypegroupspopup.aspx";
    
    OpenSimulatedModalDialog(url, popupWidth, popupHeight); 
  
  }
  
}

/*******************************************************************************************
 * Name:          PopupGroupName
 * Description:   Function to popup group names. 
 * Parameters:    p_mode - String mode
 *                p_parentTarget - parent target to pass back
 *                p_listboxID - Id of the list box to be passed back into.
 *******************************************************************************************/
function PopupGroupName(p_mode, p_parentTarget, p_listboxID){

  if (document.getElementById) {
    var popupWidth = 500;
    var popupHeight = 225;
    var listbox;
    var group;
    var id;

    if (p_mode == "EDIT"){

      listbox = document.getElementById(p_listboxID);

      if (listbox.selectedIndex != -1){ 

        group = listbox.options[listbox.selectedIndex].text;
        id = listbox.options[listbox.selectedIndex].value;

      }else{
        //exit
        alert("A group must be selected to use this function.");
        return false;
      }
   
    }

    var url = "/lpas/cx/GroupNamePopup.aspx?Mode=" + p_mode + "&Target=" + p_parentTarget + "&name=" + group + "&Id=" + id + "&LBID=" + p_listboxID;
    //http://localhost/lpas/user/PopupUser.aspx?Mode=single&URL=%2Flpas%2Fadministration%2FViewUser.aspx%3Fm%3Dcx&UserRole=&ParamName=%26UserId=&OccurrenceID=&AllUsers=Y

    OpenSimulatedModalDialog(url, popupWidth, popupHeight); 
    // Manually unblock the parent form elements
        //window.opener.UnBlockEvents()
        BlockEvents()
    return false;
  }
  
}

/*******************************************************************************************
 * Name:         PopupVSSUserSearchSubmit
 * Description:  Function to popup window to allow selection of Users.
 * Parameters:   p_mode - mode for popup (single or multiple).
 *               p_parentTarget - target element id in calling page.
 *               p_userRole - user role criteria to pass into popup.
 *******************************************************************************************/
function PopupVSSUserSearchSubmit(p_mode, p_parentTarget, p_userRole, p_fromReceivingCentresOnly,p_descFieldId, p_userTypes, p_centreCode,p_showVSSClasses,p_occurrenceId, p_isPopupControl, p_allowAllUsers) {
  var popupWidth = 786;
  var popupHeight = 540;
   
  // DOM check.
  if (document.getElementById) {
    
    // Handle optional parameter
    if (!(p_userRole)) {
      p_userRole = "";
    }
    
    if (p_fromReceivingCentresOnly == undefined) {     
			p_fromReceivingCentresOnly = "";
    }
    
    if (p_userTypes == undefined) {
		  p_userTypes = "";
    }

    
    if (p_centreCode == undefined){
      p_centreCode = "";
    }
    

    if (p_mode == undefined) {
			p_mode = "single";
    }
    
    if (p_occurrenceId == undefined) {
			p_occurrenceId = "";
    }
    
    if (p_isPopupControl == undefined) {
			p_isPopupControl = "Y";
    }
    
    if (p_allowAllUsers == undefined) {
			p_allowAllUsers = "N";
    }
          
    var url = "/lpas/VSS/VSSUser/PopupVSSUser.aspx?Mode=" + p_mode + "&Target=" + p_parentTarget + "&UserRole=" + p_userRole + "&FromRecCtr=" + p_fromReceivingCentresOnly + "&UserType=" + p_userTypes + "&CentreCode=" + p_centreCode + "&ShowClasses=" + p_showVSSClasses + "&Action=submit&OccurrenceID=" + p_occurrenceId + "&IsPopupControl=" + p_isPopupControl + "&AllUsers=" + p_allowAllUsers;
    
    if (p_descFieldId != undefined) {
      url += "&DescFieldId=" + p_descFieldId
    }
    
    OpenSimulatedModalDialog(url, popupWidth, popupHeight);
  }
}

/*******************************************************************************************
 * Name:         PopupCentre
 * Description:  Function to popup window to allow selection of Centre.
 * Parameters:   p_mode - mode for popup (single or multiple).
 *               p_parentTarget - target URL to redirect to on return of result.
 *               p_descFieldId - (optional) description label.
 *               p_userType - (optional) UserType to restrict centre type.
 *               p_chkboxControllerId - Id of hidden field to hold values to set in a chkbox control.
 *               p_chkboxId - Id of chkbox been controlled.
 *							 p_showOnlyUsersLocs - Y or N, where to return only centre the user belongs to. 
 *******************************************************************************************/
function PopupCentre(p_mode, p_parentTarget, p_descFieldId, p_userType, p_chkboxControllerId, p_chkboxId, p_showOnlyUsersLocs) {
  var popupWidth = 786;
  var popupHeight = 540;
  
  // DOM check.
  if (document.getElementById) {
    var url = "/lpas/public/centre/PopupCentre.aspx?Mode=" + p_mode + "&Target=" + p_parentTarget;
    
    if ((p_descFieldId != undefined)&&(p_descFieldId != '')) {
      url += "&DescFieldId=" + p_descFieldId;
    }
    
    if (p_userType != undefined) {
      url += "&UserType=" + p_userType;
    }
    
    if ((p_chkboxControllerId != undefined)&&(p_chkboxId != undefined)){
      url += "&chkboxControllerId=" + p_chkboxControllerId + "&chkboxId=" + p_chkboxId;
    }
    
    if (p_showOnlyUsersLocs != undefined){
			url += "&ShowOnlyUserLocs=" + p_showOnlyUsersLocs
    } 
    
    OpenSimulatedModalDialog(url, popupWidth, popupHeight);

  }
}

/*******************************************************************************************
 * Name:         PopupCentreSearchSubmit
 * Description:  Function to popup window to allow selection of a centre and resubmit the 
 *               calling page URL with the code of the centre selected as a param.
 * Parameters:   p_targetURL - target URL to redirect to on return of result.
 *               p_idParamName - id of parameter to use to pass result to redirect page.
 *******************************************************************************************/
function PopupCentreSearchSubmit(p_targetURL, p_idParamName) {
  var popupWidth = 786;
  var popupHeight = 540;
    
  // DOM check.
  if (document.getElementById) {
    var url = "/lpas/public/centre/PopupCentre.aspx?Mode=single" + "&URL=" + encodeURIComponent(p_targetURL) + "&ParamName=" + p_idParamName;
    OpenSimulatedModalDialog(url, popupWidth, popupHeight);
  }
  return false;
}

/*******************************************************************************************
 * Name:         PopupVSSCentre
 * Description:  Function to popup window to allow selection of Centre.
 * Parameters:   p_mode - mode for popup (single or multiple).
 *               p_parentTarget - target URL to redirect to on return of result.
 *******************************************************************************************/
function PopupVSSCentre(p_mode, p_parentTarget,p_centreFrom, p_centreType, p_descFieldId) {
  var popupWidth = 786;
  var popupHeight = 540;
  
  // DOM check.
  if (document.getElementById) {
    var url = "/lpas/VSS/VSSCentre/PopupVSSCentre.aspx?Mode=" + p_mode + "&Target=" + p_parentTarget + "&CentreType=" + p_centreType + "&CentreFrom=" + p_centreFrom;
    
    if (p_descFieldId != undefined) {
      url += "&DescFieldId=" + p_descFieldId
    }
    
    OpenSimulatedModalDialog(url, popupWidth, popupHeight);

  }
}

/*******************************************************************************************
 * Name:         PopupVSSCentreSearch
 * Description:  Function to popup window to allow selection of a centre and resubmit the 
 *               calling page URL with the code of the centre selected as a param.
 * Parameters:   p_targetURL - target URL to redirect to on return of result.
 *               p_idParamName - id of parameter to use to pass result to redirect page.
 *******************************************************************************************/
function PopupVSSCentreSearch(p_targetURL, p_idParamName, p_centreFrom, p_centreType) {
  var popupWidth = 786;
  var popupHeight = 540;
    
  // DOM check.
  if (document.getElementById) {
    var url = "/lpas/VSS/VSSCentre/PopupVSSCentre.aspx?Mode=single" + "&URL=" + encodeURIComponent(p_targetURL) + "&ParamName=" + p_idParamName + "&CentreType=" + p_centreType + "&CentreFrom=" + p_centreFrom;
    OpenSimulatedModalDialog(url, popupWidth, popupHeight);
  }
  return false;
  
 
}
/*******************************************************************************************
 * Name:         PopupPrerequisite
 * Description:  Function to popup window to allow selection of Prerequisites.
 * Parameters:   p_mode - mode for popup (single or multiple).
 *               p_parentTarget - target URL to redirect to on return of result.
 *******************************************************************************************/
function PopupPrerequisite(p_mode, p_parentTarget) {
  var popupWidth = 786;
  var popupHeight = 540;
    
  // DOM check.
  if (document.getElementById) {
    var url = "/lpas/prerequisite/PopupPrerequisite.aspx?Mode=" + p_mode + "&Target=" + p_parentTarget;
    OpenSimulatedModalDialog(url, popupWidth, popupHeight);
  }
}

/*******************************************************************************************
 * Name:         PopupSubjectClassGroupSearch
 * Description:  Function to popup window to allow selection of a course and resubmit the 
 *               calling page URL with the code of the course selected as a param.
 * Parameters:   .
 *               p_targetURL - target URL to redirect to on return of result.
 *               p_idParamName - id of parameter to use to pass result to redirect page.
 *               p_showOnlyRolloverGroups - flag to display only subject class groups that can be rollover.
 *******************************************************************************************/
function PopupSubjectClassGroupSearch(p_targetURL, p_idParamName,p_showOnlyRolloverGroups ) {
  var popupWidth = 786;
  var popupHeight = 540;
  
  try { 
  
    // DOM check.
    if (document.getElementById) {

      var url = "/lpas/VSS/VSSTimetable/PopupSubjectClassGroup.aspx?Mode=single" + "&URL=" + encodeURIComponent(p_targetURL) + "&ParamName=" + p_idParamName + "&Rollover=" + p_showOnlyRolloverGroups ; 

      OpenSimulatedModalDialog(url, popupWidth, popupHeight);
    }
    return false;
  }
  catch(e)
  {
  }
  
}

/*******************************************************************************************
 * Name:         PopupClassSearch
 * Description:  Function to popup window to allow selection of a course and resubmit the 
 *               calling page URL with the code of the course selected as a param.
 * Parameters:   .
 *               p_targetURL - target URL to redirect to on return of result.
 *               p_idParamName - id of parameter to use to pass result to redirect page.
 *               p_showOnlyRolloverGroups - flag to display only subject class groups that can be rollover.
 *******************************************************************************************/
function PopupClassSearch(p_targetURL, p_idParamName,p_showOnlyInPrimaryLocation) {
  var popupWidth = 786;
  var popupHeight = 540;
  
  try { 
  
    // DOM check.
    if (document.getElementById) {

      var url = "/lpas/VSS/VSSTimetable/PopupClass.aspx?Mode=single" + "&URL=" + encodeURIComponent(p_targetURL) + "&ParamName=" + p_idParamName + "&OnlyInPL=" + p_showOnlyInPrimaryLocation ; 

      OpenSimulatedModalDialog(url, popupWidth, popupHeight);
    }
    return false;
  }
  catch(e)
  {
  }
  
}

/*******************************************************************************************
 * Name:         PopupGroupSearch
 * Description:  Function to popup window to allow selection of a course and resubmit the 
 *               calling page URL with the code of the course selected as a param.
 * Parameters:   .
 *               p_parentTarget - id of popup control on the parent.
 *               p_isPopup - Y/N - is the parent target a popup user control
 *******************************************************************************************/
function PopupGroupSearch(p_parentTarget, p_isPopup) {
  var popupWidth = 786;
  var popupHeight = 540;
  
  try { 
  
    // DOM check.
    if (document.getElementById) {

      var url = "/lpas/VSS/VSSTimetable/PopupResourceCentreGroups.aspx?Target=" + p_parentTarget + "&IsPopup=" + p_isPopup; 

      OpenSimulatedModalDialog(url, popupWidth, popupHeight);
    }
    return false;
  }
  catch(e)
  {
  }
}

/*******************************************************************************************
 * Name:         PopupLessonGroup
 * Description:  Function to popup window to allow selection of Centre.
 * Parameters:   p_mode - mode for popup (single or multiple).
 *               p_parentTarget - target URL to redirect to on return of result.
 *******************************************************************************************/
function PopupLessonGroup(p_mode, p_parentTarget,p_classId, p_descFieldId) {
  var popupWidth = 786;
  var popupHeight = 540;
  
  // DOM check.
  if (document.getElementById) {
    var url = "/lpas/vss/vsstimetable/PopupLessonGroups.aspx?Mode=" + p_mode + "&Target=" + p_parentTarget + "&ClassId=" + p_classId;
    
    if (p_descFieldId != undefined) {
      url += "&DescFieldId=" + p_descFieldId
    }
    
    OpenSimulatedModalDialog(url, popupWidth, popupHeight);

  }
}

/*******************************************************************************************
 * Name:         PopupGroupMembership
 * Description:  Function to popup window to allow selection of Centre.
 * Parameters:   p_membersListBoxId - List control to return the values into
 *               p_editMode - Add or remove enumeration
 *               p_sizeMode - Large or small enumeration
 *               p_groupId - selected group
 *******************************************************************************************/
function PopupGroupMembership(p_membersListBoxId, p_editMode, p_sizeMode, p_groupId) {
  var popupWidth = 786;
  var popupHeight = 560;
  
  // DOM check.
  if (document.getElementById) {
    var url = "/lpas/cx/PopupGroupMembership.aspx?Target=" + p_membersListBoxId + "&EditMode=" + p_editMode + "&SizeMode=" + p_sizeMode + "&GroupId=" + p_groupId;
    
    OpenSimulatedModalDialog(url, popupWidth, popupHeight);

  }
}

/*******************************************************************************************
 * Name:         PopupMessage
 * Description:  Function to popup a window with a message from appcommon.
 * Parameters:   p_messageEnum - Message enum.
 *               p_messageType - Type of message, 0 for message, 1 for error, 2 for intergration template
 *               p_popupWidth - popup width
 *               p_popupHeight - popup height
 *******************************************************************************************/
function PopupMessage(p_messageEnum, p_messageType, p_popupWidth, p_popupHeight, p_header) {
    
  // DOM check.
  if (document.getElementById) {
    var url = "/lpas/_common/MessagePopup.aspx?enum=" + p_messageEnum + "&type=" + p_messageType;
    
    if(p_header){
      url += "&h=" + p_header;
    }
    
    OpenSimulatedModalDialog(url, p_popupWidth, p_popupHeight);
  }
}

/*******************************************************************************************
 * Name:         PopupNonEqSearch
 * Description:  Function to popup window to allow selection of an organisation or non EQ centre and resubmit the 
 *               calling page URL with the code of the non EQ selected as a param.
 *
 * Parameters:   p_targetURL - target URL to redirect to on return of result.
 *               p_idParamName - id of parameter to use to pass result to redirect page.
 *               p_affiliateOnly - return affiliates only.
 *******************************************************************************************/
function PopupNonEqSearch(p_targetURL, p_idParamName, p_affiliateOnly) {

  var popupWidth = 786;
  var popupHeight = 580;
  
  try { 
   
    // DOM check.
    if (document.getElementById) {

      var url = "/lpas/affiliate/PopupNonEQ.aspx?Mode=single" + "&URL=" + encodeURIComponent(p_targetURL) + "&ParamName=" + p_idParamName + "&Aff=" + p_affiliateOnly; 

      OpenSimulatedModalDialog(url, popupWidth, popupHeight);

    }
    return false;
  }
    catch(e)
  {
		
  }
  
}

/*******************************************************************************************
 * Name:         BuildDelimitedString
 * Description:  Function to build a delimited string from a list box's values.
 * Parameters:   p_list - id of listbox element to build delimited string from.
 *               p_delimiter - Delimiter to use.
 *******************************************************************************************/
function BuildDelimitedString(p_list, p_delimiter) {
  var delimitedString = "";
  var sourceList = null;
    
  // DOM check.
  if (document.getElementById) {
  
    // Get a handle to the source list
    sourceList = document.getElementById(p_list);
  
    for (var i=0;i<=sourceList.length-1;i++) {
      if (delimitedString == "") {
        delimitedString = sourceList.options[i].value;
      } 
      else {
        delimitedString += p_delimiter + sourceList.options[i].value;
      }
    }
  }
  return delimitedString;
}

/*******************************************************************************************
 * Name:         CloseWindow
 * Description:  Function to close popup window.
 *******************************************************************************************/
function CloseWindow() {

try {

	// Manually unblock the parent form elements
	window.opener.UnBlockEvents();
	
 }
 catch(e)
 {
	
 }

  window.close();
}


/*******************************************************************************************
 * Name:         SelectDropDownItemByValue
 * Description:  Function used to select an item in a dropdown list by the value.
 * Parameters:   p_dropdownId - id of drop down element to select option in.
 *               p_value - Value of option to be selected.
 *               p_isParentPage - specify if the drop down element is in the parent page.
 *******************************************************************************************/
function SelectDropDownItemByValue(p_dropdownId, p_value, p_isParentPage)
{
  
  if (!(p_isParentPage))
  {
    // Drop Down is in the current page
    
    // DOM Check
    if (document.getElementById) {
   
      var dropdownList = document.getElementById(p_dropdownId);
    
      // Find the index of the option holding the current value
      for (var i=0;i<dropdownList.options.length;i++) {
    
        if (Trim(dropdownList.options[i].value) == Trim(p_value)) {
          dropdownList.selectedIndex = i;
          return true;
        }
      }
    }
    
  } 
  else {
    // Drop Down is in the Parent Page
    
    // DOM Check
    if (window.opener.document.getElementById) {
   
      var dropdownList = window.opener.document.getElementById(p_dropdownId);
    
      // Find the index of the option holding the current value
      for (var i=0;i<dropdownList.options.length;i++) {
    
        if (Trim(dropdownList.options[i].value) == Trim(p_value)) {
          dropdownList.selectedIndex = i;
          return true;
        }
      }
    }  
  
  }
  
  return false;
}

/*******************************************************************************************
 * Name:         SelectDropDownItemByText
 * Description:  Function used to select an item in a dropdown list by the text.
 * Parameters:   p_dropdownId - id of drop down element to select option in.
 *               p_text - Text of option to be selected.
 *               p_isParentPage - specify if the drop down element is in the parent page.
 *******************************************************************************************/
function SelectDropDownItemByText(p_dropdownId, p_text, p_isParentPage)
{

  if (!(p_isParentPage)) {
  
    // Drop Down is in the current page

    // DOM Check
    if (document.getElementById) {
      var dropdownList = document.getElementById(p_dropdownId);
      
      // Find the index of the option holding the current value
      for (var i=0;i<dropdownList.options.length;i++) {
      
        if (Trim(dropdownList.options[i].text) == Trim(p_text)) {
          dropdownList.selectedIndex = i;
          return true;
        }
      }
    }
  } 
  else  {
    // Drop Down is in the Parent Page
      
    // DOM Check
    if (window.opener.document.getElementById) {
      var dropdownList = window.opener.document.getElementById(p_dropdownId);
      
      // Find the index of the option holding the current value
      for (var i=0;i<dropdownList.options.length;i++) {
      
        if (Trim(dropdownList.options[i].text) == Trim(p_text)) {
          dropdownList.selectedIndex = i;
          return true;
        }
      }
    }
  
  }
  return false;
}

/*******************************************************************************************
 * Name:         HTMLEncode
 * Description:  Encodes the string for HTML reserved characters.
 * Parameters:   p_text - The text to be encoded.
 *******************************************************************************************/
function HTMLEncode(p_text) {
  var rExp = / /gi;
  return p_text.replace(rExp, "&nbsp;")
}

/*******************************************************************************************
 * Name:         ApplyCssClass
 * Description:  Function to apply a CSS Class to a document element.
 * Parameters:   p_element - id of element to apply CSS Class to.
 *               p_cssClass - css class to apply to p_element.
 *******************************************************************************************/
function ApplyCssClass(p_element, p_cssClass)
{
  // DOM Check
  if (document.getElementById) {
    var element = document.getElementById(p_element);
    element.className = p_cssClass;
  }
}

/*******************************************************************************************
 * Name:         EscapeRegularExpression
 * Description:  Function to escape a string into a regular expression.
 * Parameters:   p_string - string to escape.
 *******************************************************************************************/
function EscapeRegularExpression(p_string)
{
  var regReg = /(\*|\^|\$|\+|\?|\.|\(|\)|\||\{|\}|\,|\[|\]|\\|\/)/g
  return p_string.replace(regReg,'\\$1');
}

//**********************************************************************
//  BEGIN MODAL DIALOG CODE
//***********************************************************************/

// Global for browser version branching.
var Nav4 = ((navigator.appName == "Netscape"));
// One object tracks the current modal dialog opened from this window.
var dialogWin = new Object();

/*******************************************************************************************
 * Name:         OpenSimulatedModalDialog
 * Description:  Generate a simluated modal dialog.
 * Parameters:
 *   p_url -- URL of the page/frameset to be loaded into dialog
 *   p_width -- pixel width of the dialog window
 *   p_height -- pixel height of the dialog window
 *******************************************************************************************/
function OpenSimulatedModalDialog(p_url, p_width, p_height) {
	
	if (!dialogWin.win || (dialogWin.win && dialogWin.win.closed)) {
		
		// Initialize properties of the modal dialog object.
		dialogWin.url = p_url;
		dialogWin.width = p_width;
		dialogWin.height = p_height;
		
		// Keep name unique so Navigator doesn't overwrite an existing dialog.
		dialogWin.name = (new Date()).getSeconds().toString();
		
		// Assemble window attributes and try to center the dialog.
		if (Nav4) {
			
			// Center on the main window.
			dialogWin.left = (window.screenX + ((window.outerWidth - dialogWin.width) / 2)) - 4;
			dialogWin.top = window.screenY + ((window.outerHeight - dialogWin.height) / 2) - 14;
			var attr = "screenX=" + dialogWin.left + ",screenY=" + dialogWin.top + ",resizable=no,width=" + dialogWin.width + ",height=" + dialogWin.height;
		} 
		else {
			
			// The best we can do is center in screen.
			dialogWin.left = ((screen.width - dialogWin.width) / 2) - 5;
			dialogWin.top = ((screen.height - dialogWin.height) / 2) - 28;
			var attr = "left=" + dialogWin.left + ",top=" + dialogWin.top + ",resizable=no,width=" + dialogWin.width + ",height=" + dialogWin.height;
		}
		
		// Generate the dialog and make sure it has focus.
		dialogWin.win=window.open(dialogWin.url, dialogWin.name, attr);
		dialogWin.win.focus();
	} 
	else {
		dialogWin.win.focus();
	}
}

/*******************************************************************************************
 * Name:         Deadend
 * Description:  Event handler to inhibit form element
 *               and link activity when dialog window is active.
 *******************************************************************************************/
function Deadend() {

  // Focus the dialog window if it exists
	if (dialogWin.win && !dialogWin.win.closed) {
		dialogWin.win.focus();
	}
	
	// Cancel the click event
	if (!(Nav4)) {
	  window.event.returnValue = false;
	}
	return false;
}

// Since links in IE4 cannot be disabled, preserve 
// IE link onclick event handlers while they're "disabled."
// Restore when re-enabling the main window.
var IELinkClicks

/*******************************************************************************************
 * Name:         DisableForms
 * Description:  Disable form elements and links for IE.
 *******************************************************************************************/
function DisableForms() {
  
	IELinkClicks = new Array();
	
	// Disable the elements
	for (var i = 0; i < document.forms.length; i++) {
		for (var j = 0; j < document.forms[i].elements.length; j++) {
			document.forms[i].elements[j].disabled = true;
		}
	}
	
	/* HOT FIX FOR SIDE BAR LINKS
	// Disable the links
	for (i = 0; i < document.links.length; i++) {
		IELinkClicks[i] = document.links[i].onclick;
		document.links[i].onclick = Deadend;
	}*/
	
	// Set the focus & click events
	window.onfocus = CheckModal;
  document.onclick = CheckModal;
  
}

/*******************************************************************************************
 * Name:         EnableForms
 * Description:  Restore IE form elements and links to normal behavior.
 *******************************************************************************************/
function EnableForms() {
  
  // Enable the elements
	for (var i = 0; i < document.forms.length; i++) {
		for (var j = 0; j < document.forms[i].elements.length; j++) {
			document.forms[i].elements[j].disabled = false;
		}
	}
	
	/* HOT FIX FOR SIDE BAR LINKS
	// Enable the links
	//alert(IELinkClicks);
	//if (!IELinkClicks == undefined)
	{
	  for (i = 0; i < document.links.length; i++) {
	    if (IELinkClicks[i] != undefined) {
		    document.links[i].onclick = IELinkClicks[i];
		  }
		}
	}*/
	
	//clear the focus & click events
	window.onfocus = null;
  document.onclick = null;
}

/*******************************************************************************************
 * Name:         BlockEvents
 * Description:  Grab all Navigator events that might get through to form
 *               elements while dialog is open. For IE, disable form elements.
 *******************************************************************************************/
function BlockEvents() {
	
	if (Nav4) {
		window.captureEvents(Event.CLICK | Event.MOUSEDOWN | Event.MOUSEUP | Event.FOCUS);
		window.onclick = Deadend;
	} 
	else {
		DisableForms();
	}
	window.onfocus = CheckModal;
}

/*******************************************************************************************
 * Name:         UnBlockEvents
 * Description:  As dialog closes, restore the main window's original event mechanisms.
 *******************************************************************************************/
function UnBlockEvents() {
	
	if (Nav4) {
		window.releaseEvents(Event.CLICK | Event.MOUSEDOWN | Event.MOUSEUP | Event.FOCUS);
		window.onclick = null;
		window.onfocus = null;
	} 
	else {
		EnableForms();
	}
}

/*******************************************************************************************
 * Name:         CheckModal
 * Description:  Invoked by onFocus event handler of EVERY frame,
 *               return focus to dialog window if it's open, after a short wait.
 *******************************************************************************************/
function CheckModal() {
	setTimeout("FocusDialog()", 50);
	return true;
}

/*******************************************************************************************
 * Name:         FocusDialog
 * Description:  Return the focus to the dialog if it is open.
 *******************************************************************************************/
function FocusDialog() {
	if (dialogWin.win && !dialogWin.win.closed) {
		dialogWin.win.focus();
	}
}

//**************************
//  END MODAL DIALOG CODE
//**************************/

/*******************************************************************************************
 * Name:         IsRecordSelected
 * Description:  Checks whether any check box is checked or not within the passed in container (i.e. dive)
 *******************************************************************************************/
function IsRecordSelected(p_group) {
  var recordsSelected = false;

  if (document.getElementById(p_group) != null) 
  {
    var inputs = document.getElementById(p_group).getElementsByTagName('input');
    
    // See if there are any records selected for deletion.
    for (var i = 0; i < inputs.length; i++) {
      if (inputs[i].getAttribute('type') == 'checkbox') {
        if (inputs[i].checked == true) {
          recordsSelected = true;
        }
      }
    }  
    
  }
  
  return recordsSelected;
}


/*******************************************************************************************
 * Name:         IsMoreThanOneRecordSelected
 * Description:  Checks whether more than one check box are checked or not within the passed in container (i.e. dive)
 *******************************************************************************************/
function IsMoreThanOneRecordSelected(p_group) {

  var multipleRecordsSelected = false;
  var recordCount = 0;
  
  if (document.getElementById) {
    var inputs = document.getElementById(p_group).getElementsByTagName('input');
  
    // See if there are any records selected for deletion.
    for (var i = 0; i < inputs.length; i++) {
      if (inputs[i].getAttribute('type') == 'checkbox') {
        if (inputs[i].checked == true) {
          recordCount = recordCount + 1;
        }
      }
    }  
  }

  if (recordCount > 1 ) {
    multipleRecordsSelected = true
  }
   
  return multipleRecordsSelected;
}


/*******************************************************************************************
 * Name:         ConfirmVSSParticipant
 * Description:  Confrims the operation by displaying message to the user.
 * Parameters:   p_group - The id of the div or container.
 *               p_message - Confirmation message.
 *               p_makeSelectionMessage - Select at least one record prompt message id of the hidden field.
 *               p_classLimitMessage - Exceeds class limit prompt message 
 *               p_classLimit - class limit id of the hidden field.
 *               p_confirmedNumner - confirmed number id of the hidden field.
 *               p_incorrectStatusMessage - An inccorect status message string.
 *******************************************************************************************/
function ConfirmVSSParticipant(p_group,p_message,p_makeSelectionMessage, p_incorrectStatusMessage, p_statusStr, p_waitingListMessage) {
  
  if (document.getElementById) {
    
    var p_status = p_statusStr.split(",");

    if (!IsRecordSelected(p_group)) {
			if ( p_makeSelectionMessage == undefined) {
				alert(m_recordNotSelectedMessage);
      }
      else {
				alert(p_makeSelectionMessage);
      }
      return false;
    } 
    else if (HasWaitingListStatus(p_group))
    {      
      
      p_waitingListMessage = p_waitingListMessage + "\n\nPress OK to proceed.";
      p_waitingListMessage = p_waitingListMessage + "\nPress Cancel to abort the operation.";
  
      var returnValue = Confirm(p_waitingListMessage);
      if (returnValue)
      {
        if (HasIncorrectStatus(p_group, p_status))
        {             
          alert (p_incorrectStatusMessage)  ;   
          return false;      
        }        
        return true;
      }
      
    }    
    else if (HasIncorrectStatus(p_group, p_status)){      
      
      alert (p_incorrectStatusMessage)  ;   
      return false;      
    }    
    
   else {
       
      p_message = p_message + "\n\nPress OK to proceed.";
      p_message = p_message + "\nPress Cancel to abort the operation.";
  
      return Confirm(p_message);
    }  
  }
  
  return false;	
}

/*******************************************************************************************
 * Name:         DeleteOrDeclineVSSParticipant
 * Description:  Deletes or Declines the operation by displaying message to the user.
 * Parameters:   p_group - The id of the div or container.
 *               p_message - Confirmation message.
 *               p_makeSelectionMessage - Select at least one record prompt message id of the hidden field.
 *               p_classLimitMessage - Exceeds class limit prompt message 
 *               p_classLimit - class limit id of the hidden field.
 *               p_confirmedNumner - confirmed number id of the hidden field.
 *               p_incorrectStatusMessage - An inccorect status message string.
 *******************************************************************************************/
function DeleteOrDeclineVSSParticipant(p_group,p_message,p_makeSelectionMessage, p_incorrectStatusMessage, p_statusStr) {
  
  if (document.getElementById) {
    
    var p_status = p_statusStr.split(",")
    
    if (!IsRecordSelected(p_group)) {
			if ( p_makeSelectionMessage == undefined) {
				alert(m_recordNotSelectedMessage);
      }
      else {
				alert(p_makeSelectionMessage);
      }
      return false;
    }
    else if (HasIncorrectStatus(p_group, p_status)){      
    
      alert (p_incorrectStatusMessage)     
      return false;      
    }    
    else {
       
      p_message = p_message + "\n\nPress OK to proceed.";
      p_message = p_message + "\nPress Cancel to abort the operation.";
  
      return Confirm(p_message);
    }  
  }
  
  return false;	
}

/*******************************************************************************************
 * Name:         MoveVSSParticipant
 * Description:  Move the operation by displaying message to the user.
 * Parameters:   p_group - The id of the div or container.
 *               p_message - Confirmation message.
 *               p_makeSelectionMessage - Select at least one record prompt message id of the hidden field.
 *               p_classLimitMessage - Exceeds class limit prompt message 
 *               p_classLimit - class limit id of the hidden field.
 *               p_confirmedNumner - confirmed number id of the hidden field.
 *               p_incorrectStatusMessage - An inccorect status message string.
 *******************************************************************************************/
function MoveVSSParticipant(p_group,p_message,p_makeSelectionMessage, p_incorrectStatusMessage, p_statusStr) {
  
  if (document.getElementById) {
    
    var p_status = p_statusStr.split(",")
    
    if (!IsRecordSelected(p_group)) {
			if ( p_makeSelectionMessage == undefined) {
				alert(m_recordNotSelectedMessage);
      }
      else {
				alert(p_makeSelectionMessage);
      }
      return false;
    }
    else if (HasIncorrectStatus(p_group, p_status)){      
    
      alert (p_incorrectStatusMessage)     
      return false;      
    }    
    else {
       
      p_message = p_message + "\n\nPress OK to proceed.";
      p_message = p_message + "\nPress Cancel to abort the operation.";
  
      return Confirm(p_message);
    }  
  }
  
  return false;	
}

/*******************************************************************************************
 * Name:         CompleteVSSParticipant
 * Description:  Deletes or Declines the operation by displaying message to the user.
 * Parameters:   p_group - The id of the div or container.
 *               p_message - Confirmation message.
 *               p_makeSelectionMessage - Select at least one record prompt message id of the hidden field.
 *               p_classLimitMessage - Exceeds class limit prompt message 
 *               p_classLimit - class limit id of the hidden field.
 *               p_confirmedNumner - confirmed number id of the hidden field.
 *               p_incorrectStatusMessage - An inccorect status message string.
 *******************************************************************************************/
function CompleteVSSParticipant(p_group,p_message,p_makeSelectionMessage, p_incorrectStatusMessage, p_statusStr) {
  
  if (document.getElementById) {
    
    var p_status = p_statusStr.split(",")
    
    if (!IsRecordSelected(p_group)) {
			if ( p_makeSelectionMessage == undefined) {
				alert(m_recordNotSelectedMessage);
      }
      else {
				alert(p_makeSelectionMessage);
      }
      return false;
    }
    else if (HasIncorrectStatus(p_group, p_status)){      
    
      alert (p_incorrectStatusMessage)     
      return false;      
    }    
    else {
       
      p_message = p_message + "\n\nPress OK to proceed.";
      p_message = p_message + "\nPress Cancel to abort the operation.";
  
      return Confirm(p_message);
    }  
  }
  
  return false;	
}

/*******************************************************************************************
 * Name:         CancelVSSParticipant
 * Description:  Cancels the operation by displaying message to the user.
 * Parameters:   p_group - The id of the div or container.
 *               p_message - Confirmation message.
 *               p_makeSelectionMessage - Select at least one record prompt message id of the hidden field.
 *               p_classLimitMessage - Exceeds class limit prompt message 
 *               p_classLimit - class limit id of the hidden field.
 *               p_confirmedNumner - confirmed number id of the hidden field.
 *               p_incorrectStatusMessage - An inccorect status message string.
 *******************************************************************************************/
function CancelVSSParticipant(p_group,p_message,p_singleSelectionMessage, p_incorrectStatusMessage, p_statusStr) {
  
  if (document.getElementById) {
    
    var p_status = p_statusStr.split(",")
    
    
    if (!CheckSingleSelection(p_group,p_singleSelectionMessage,m_recordNotSelectedMessage)) 
    {
    
      return false;
    }			    
    else if (HasIncorrectStatus(p_group, p_status))
    {      
    
      alert (p_incorrectStatusMessage)     
      return false;      
    }    
    else 
    {
        
      p_message = p_message + "\n\nPress OK to proceed.";
      p_message = p_message + "\nPress Cancel to abort the operation.";
  
      return Confirm(p_message);
    }  
    
  }
  
  return false;	
}
/*******************************************************************************************
 * Name:         RemoveVSSParticipant
 * Description:  Deletes or Declines the operation by displaying message to the user.
 * Parameters:   p_group - The id of the div or container.
 *               p_message - Confirmation message.
 *               p_makeSelectionMessage - Select at least one record prompt message id of the hidden field.
 *               p_classLimitMessage - Exceeds class limit prompt message 
 *               p_classLimit - class limit id of the hidden field.
 *               p_confirmedNumner - confirmed number id of the hidden field.
 *               p_incorrectStatusMessage - An inccorect status message string.
 *******************************************************************************************/
function RemoveVSSParticipant(p_group,p_message,p_makeSelectionMessage, p_incorrectStatusMessage, p_statusStr) {
  
  if (document.getElementById) {
    
    var p_status = p_statusStr.split(",")
    
    if (!IsRecordSelected(p_group)) {
			if ( p_makeSelectionMessage == undefined) {
				alert(m_recordNotSelectedMessage);
      }
      else {
				alert(p_makeSelectionMessage);
      }
      return false;
    }
    else if (HasIncorrectStatus(p_group, p_status)){      
    
      alert (p_incorrectStatusMessage)     
      return false;      
    }    
    else {
       
      p_message = p_message + "\n\nPress OK to proceed.";
      p_message = p_message + "\nPress Cancel to abort the operation.";
  
      return Confirm(p_message);
    }  
  }
  
  return false;	
}
/*******************************************************************************************
 * Name:         DeleteVSSParticipant
 * Description:  Confrims the operation by displaying message to the user.
 * Parameters:   p_group - The id of the div or container.
 *               p_message - Confirmation message.
 *               p_makeSelectionMessage - Select at least one record prompt message id of the hidden field.
 *               p_classLimitMessage - Exceeds class limit prompt message 
 *               p_classLimit - class limit id of the hidden field.
 *               p_confirmedNumner - confirmed number id of the hidden field.
 *               p_incorrectStatusMessage - An inccorect status message string.
 *******************************************************************************************/
function DeleteVSSParticipant(p_group,p_message,p_makeSelectionMessage, p_incorrectStatusMessage, p_statusStr) {
  
  if (document.getElementById) {
    
    var p_status = p_statusStr.split(",");
    
    if (!IsRecordSelected(p_group)) {
			if ( p_makeSelectionMessage == undefined) {
				alert(m_recordNotSelectedMessage);
      }
      else {
				alert(p_makeSelectionMessage);
      }
      return false;
    }
    else if (HasIncorrectStatus(p_group, p_status)){      
    
      alert (p_incorrectStatusMessage);    
      return false;      
    }    
    else {
       
      p_message = p_message + "\n\nPress OK to proceed.";
      p_message = p_message + "\nPress Cancel to abort the operation.";
  
      return Confirm(p_message);
    }  
  }
  
  return false;	
}

/*******************************************************************************************
 * Name:         CanNotDelete
 * Description:  Confrims the operation by displaying message to the user.
 * Parameters:   p_message - can not delete message. 
 *******************************************************************************************/
function CanNotDelete(p_message)
{
  alert(p_message);
  return false;
}
/*******************************************************************************************
 * Name:         GetSelectedRecordCount
 * Description:  Gets the count of selected records.
 * Parameters:   p_group - The id of the div or container.
 *******************************************************************************************/
function GetSelectedRecordCount(p_group) {
  var recordsSelected = false;

  if (document.getElementById(p_group) != null) 
  {
    var inputs = document.getElementById(p_group).getElementsByTagName('input');
    var selectedCount = 0
    // See if there are any records selected for deletion.
    for (var i = 0; i < inputs.length; i++) {
      if (inputs[i].getAttribute('type') == 'checkbox') {
        if (inputs[i].checked == true) {
          selectedCount++;
        }
      }
    }  
    
  }
  
  return selectedCount;
}

/*******************************************************************************************
 * Name:         ExceedsClassLimit
 * Description:  Returns the selected recods exceeds the class limit or not.
 * Parameters:   p_classLimit - class limit id of the hidden field.
 *               p_confirmedNumner - confirmed number id of the hidden field.
 *               p_newlyConfirmed - count of newly selected records.
 *******************************************************************************************/
function ExceedsClassLimit(p_classLimit,p_confirmedNumber,p_newlyConfirmed)
{
  var classLimit = document.getElementById(p_classLimit).value;
  var confirmedNumber = document.getElementById(p_confirmedNumber).value;
  var newCount = (parseInt(confirmedNumber) + parseInt(p_newlyConfirmed));
  
  if (classLimit < newCount)
  {
    return true;
  }
  return false;
}

/*******************************************************************************************
 * Name:         HasIncorrectStatus
 * Description:  Returns if any selected student has waiting list status.
 * Parameters:   p_classLimit - class limit id of the hidden field.
 *               p_confirmedNumner - confirmed number id of the hidden field.
 *               p_newlyConfirmed - count of newly selected records.
 *******************************************************************************************/
function HasIncorrectStatus(p_group, p_status)
{

  if (document.getElementById(p_group) != null) 
  {
    var inputs = document.getElementById(p_group).getElementsByTagName('input');
    
    // See if there are any records selected for deletion.
    for (var i = 0; i < inputs.length; i++) 
    {
    
      if (inputs[i].getAttribute('type') == 'checkbox') 
      {
        if (inputs[i].checked == true) 
        {
          var links = document.getElementById(p_group).getElementsByTagName('a');
          var status = links[i].getAttribute('StatusCode')
          var found = false;
          
          for (var j = 0; j < p_status.length; j++)
          {       
            
            if (p_status[j] == status) 
            {              
              found = true;
              break;
            }        
          }
          if (!found)          
            return true;
            
        }
      }
    }  
   }
    return false;  
}


/*******************************************************************************************
 * Name:         HasWaitingListStatus
 * Description:  Returns if any selected student has waiting list status.
 * Parameters:   p_classLimit - class limit id of the hidden field.
 *               p_confirmedNumner - confirmed number id of the hidden field.
 *               p_newlyConfirmed - count of newly selected records.
 *******************************************************************************************/
function HasWaitingListStatus(p_group)
{
  if (document.getElementById(p_group) != null) 
  {
    var inputs = document.getElementById(p_group).getElementsByTagName('input');
    
    // See if there are any records selected for deletion.
    for (var i = 0; i < inputs.length; i++) 
    {
      if (inputs[i].getAttribute('type') == 'checkbox') 
      {
        if (inputs[i].checked == true) 
        {
          var links = document.getElementById(p_group).getElementsByTagName('a');
          var status = links[i].getAttribute('StatusCode');
         
          if ("W" == status) 
          {              
            return true;            
          } 
        }       
        
      }
    }  
  }
  return false;
}

/*******************************************************************************************
 * Name:         ConfirmOperation
 * Description:  Confrims the operation by displaying message to the user.
 * Parameters:   p_group - The id of the div or container.
 *               p_message - Confirmation message.
 *               p_makeSelectionMessage - Select at least one record prompt message id of the hidden field.
 *******************************************************************************************/
function ConfirmOperation(p_group,p_message,p_makeSelectionMessage) {
  
  if (document.getElementById) {
    
    if (!IsRecordSelected(p_group)) {
			if ( p_makeSelectionMessage == undefined) {
				alert(m_recordNotSelectedMessage);
      }
      else {
				alert(p_makeSelectionMessage);
      }
      return false;
    }
    else {
       
      p_message = p_message + "\n\nPress OK to proceed.";
      p_message = p_message + "\nPress Cancel to abort the operation.";
  
      return Confirm(p_message);
    }  
  }
  
  return false;	
}

/*******************************************************************************************
 * Name:         ConfirmMessage
 * Description:  Confrims the operation by displaying message to the user.
 * Parameters:   p_message - Confirmation message.
 *******************************************************************************************/
function ConfirmMessage(p_message) {
  
  if (document.getElementById) {
    
    p_message = p_message + "\n\nPress OK to proceed.";
    p_message = p_message + "\nPress Cancel to abort the operation.";

    return Confirm(p_message);
  }
  return false;	
}

/*******************************************************************************************
 * Name:         ConfirmOperationWithSingleSelection
 * Description:  Confrims the operation by displaying message to the user.
 * Parameters:   p_group - The id of the div or container.
 *               p_message - Confirmation message.
 *               p_singleSelectionMessage - message when more than one checkboxes checked.
 *               p_makeSelectionMessage - selection prompt to check at least one check box.
 *******************************************************************************************/
function ConfirmOperationWithSingleSelection(p_group,p_message,p_singleSelectionMessage,p_makeSelectionMessage) {
  
  if (document.getElementById) {
  	
    if (!CheckSingleSelection(p_group,p_singleSelectionMessage,p_makeSelectionMessage)) {
    
      return false;
    }
    else {

      p_message = p_message + "\n\nPress OK to proceed.";
      p_message = p_message + "\nPress Cancel to abort the operation.";

      return Confirm(p_message);
    }
  }
  
  return false;	
}

/*******************************************************************************************
 * Name:         CheckSingleSelection
 * Description:  Check whether only one checkbox is checked or not.
 * Parameters:   p_group - The id of the div or container.
 *               p_message - Confirmation message.
 *               p_makeSelectionMessage - selection prompt to check at least one check box.
 *******************************************************************************************/
function CheckSingleSelection(p_group,p_message,p_makeSelectionMessage) {

  if (document.getElementById) {
    
    if (!IsRecordSelected(p_group)) {
      if ( p_makeSelectionMessage == undefined) {
				alert(m_recordNotSelectedMessage);
      }
      else {
				alert(p_makeSelectionMessage);
      }
      return false;
    }
    else if (IsMoreThanOneRecordSelected(p_group)) {
      alert(p_message);
      return false;
    }
    return true;  
  }
  return false;	
}

/*******************************************************************************************
 * Name:         CheckSelection
 * Description:  Checks whether at least one checkbox is checked or not.
 * Parameters:   p_group - The id of the div or container.
 *               p_message - Confirmation message.
 *               p_makeSelectionMessage - selection prompt to check at least one check box.
 *******************************************************************************************/
function CheckSelection(p_group,p_makeSelectionMessage) {

  if (document.getElementById) {
    
    if (!IsRecordSelected(p_group)) {
      if ( p_makeSelectionMessage == undefined) {
				alert(m_recordNotSelectedMessage);
      }
      else {
				alert(p_makeSelectionMessage);
      }
      return false;
    }
    
    return true;  
  }
  return false;	
}

/*******************************************************************************************
 * Name:         CheckSelection
 * Description:  Check whether checkbox is checked or not..
 * Parameters:   p_group - The id of the div or container.
 *               p_message - Confirmation message.
 *               p_makeSelectionMessage - selection prompt to check at least one check box.
 *******************************************************************************************/
function CheckSelection(p_group,p_message, p_makeSelectionMessage) {
  if (document.getElementById) {
    
    if (!IsRecordSelected(p_group)) {
      if ( p_makeSelectionMessage == undefined) {
				alert(m_recordNotSelectedMessage);
      }
      else {
				alert(p_makeSelectionMessage);
      }
      return false;
 
    }else{
			return true;
    }
  }
}

/*******************************************************************************************
 * Name:         AttachNavigationClick
 * Description:  Function that attaches the event to trap navigation clicks.
 * Parameters:   p_navigationLabelId - The navigation label (<SPAN>) element id.
 *               p_formName - The name of the form on the parent page.
 *               p_searchIdField - The ID of the page based search.
 *               p_pageNumberField - The page number to navigate to.
 *******************************************************************************************/
function AttachNavigationClick(p_navigationLabelId, p_formName, p_searchIdField, p_pageNumberField)
{
  // DOM Check
  if (document.getElementById) {
    var navigationLabel = document.getElementById(p_navigationLabelId);
    
    if (navigationLabel != null) {
    
      var anchorElements = navigationLabel.getElementsByTagName('A');

      if (anchorElements != null) {
        for(var x=0;x<anchorElements.length;x++){

          // Add the event to the anchor element
          AddToOnClick(anchorElements.item(x), "NavigationUsingPostBack('" + p_formName + "','" + p_searchIdField + "','" + p_pageNumberField + "','" + anchorElements.item(x).href + "'); return false;", false)
       
        }
      }
    }
  }
}

/*******************************************************************************************
 * Name:         NavigationUsingPostBack
 * Description:  Function that traps the navigation to another page of results and adds values to the form before submitting.
 * Parameters:   p_formName - The name of the form on the parent page.
 *               p_searchIdField - The ID of the page based search.
 *               p_pageNumberField - The page number to navigate to.
 *               p_targetURL - URL to navigate to.
 *******************************************************************************************/
function NavigationUsingPostBack(p_formName, p_searchIdField, p_pageNumberField, p_targetURL)
{
  
  var requestQuerystring = "";
  var paramArray = new Array();
  var pageNumberInput = null;
  var searchIdInput = null;
     
  // DOM Check
  if (document.getElementById) {
      
    // Get the Page Request, Search Id, Mode & Selected hidden form inputs
    pageNumberInput = document.getElementById(p_pageNumberField);
    searchIdInput = document.getElementById(p_searchIdField);
      
    // split the query string into param=val pieces
    requestQuerystring = p_targetURL.substr(p_targetURL.indexOf("?")+1);
    requestQuerystring = requestQuerystring.split("&");

    // split param and value into individual pieces
    for (var i=0; i<requestQuerystring.length; i++)
    {
      var tmp = new Array();
      tmp = requestQuerystring[i].split("=");
      tmp[1] = unescape(tmp[1]);
      paramArray[tmp[0]] = tmp[1]; 
    }
      
    // Set the PageRequest, Search Id & Selected List hidden form input values
    pageNumberInput.value = paramArray["PageNumber"];
    searchIdInput.value = paramArray["SearchId"];
    
    //
    if(document.getElementById("hidDisplayAll")) {
      if (paramArray["DisplayAll"]) {
        document.getElementById("hidDisplayAll").value =  paramArray["DisplayAll"];
      }
      else {
        document.getElementById("hidDisplayAll").value =  'N';
      }
    }
      
    // Submit the form
    document.forms[p_formName].submit();
    
  }  
}

/*******************************************************************************************
 * Name:         ClearOrganisationId
 * Description:  Clears the Organisation Id when an Organisation's details is edited.
 * Parameters:   p_organisationIdInput - The id of the organisation id hidden input.
 *******************************************************************************************/
function ClearOrganisationId(p_organisationIdInput)
{

  // DOM Check
  if (document.getElementById) {
  
    // Get the hidden organisation id element
    var organisationIdElement = document.getElementById(p_organisationIdInput);
   
    // Clear the value of the hidden organisation id element
    organisationIdElement.value = "";
  }
}

/*******************************************************************************************
 * Name:         DropDownListAutoPostBack
 * Description:  Onchange event for drop down list that will auto post back a page.
 * Parameters:   p_listFieldId - The id of the drop down list field.
 *               p_hiddenFieldId - The id of the hidden field.
 *******************************************************************************************/
function DropDownListAutoPostBack(p_listFieldId, p_hiddenFieldId) {

  if (document.getElementById) {

    var ddl = document.getElementById(p_listFieldId);
    var hdn = document.getElementById(p_hiddenFieldId);
    var frm = ddl.form;
    hdn.value = "Y";


    if(navigator.userAgent.indexOf("Firefox") != -1)
    {
      
    }else{
      AddProcessingFlag();
    }

   frm.submit();
  }
}


/*******************************************************************************************
 * Name:         SetHidFieldValue
 * Description:  Sets passed in field to passed in value
 * Parameters:   p_fieldName - id of field to be changed
 *               p_value - value to be set
 *******************************************************************************************/
function SetFieldValue(p_fieldName, p_value)
{

  // DOM Check
  if (document.getElementById) {
  
    // Get the hidden organisation id element
    var fieldIdElement = document.getElementById(p_fieldName);
   
    // Clear the value of the hidden organisation id element
    fieldIdElement.value = p_value;
  }
}

/*******************************************************************************************
 * Name:         MultipleFieldsRequireOne
 * Description:  Function used to validate that at least one field has been entered
 *               in IE using a custom validator.
 *******************************************************************************************/
function MultipleFieldsRequireOne(source, args) {
  args.isValid = true;
  if (!AtLeastOneSeachCriterionRequired(source.title)) {
    args.IsValid = false;
  }
  
  return args.IsValid;
}

/*******************************************************************************************
 * Name:         AtLeastOneSeachCriterionRequired
 * Description:  Function used to validate that at least one field has been entered
 *               in IE using a custom validator.
 *******************************************************************************************/
function AtLeastOneSeachCriterionRequired(p_divId) {

 var isValid = false;
 var divElement;
 var inputElements;
 var selectElements;
 var textareaElements;
 var checkboxElements;
 var elementCount;


  // DOM Check
  if (document.getElementById) {

    divElement = document.getElementById(p_divId);
    
    //Loop through all the input elements
    inputElements = divElement.getElementsByTagName('input');
    
    for (elementCount = 0;elementCount < inputElements.length; elementCount++ && isValid == false) {
    
			if (inputElements[elementCount].getAttribute('type') == 'text') {
			
				if (inputElements[elementCount].value != "") {
					isValid = true		
				}
			} else if (inputElements[elementCount].getAttribute('type') == 'checkbox') {
			
				if (inputElements[elementCount].checked == true) {
					isValid = true		
				}
			} else if (inputElements[elementCount].getAttribute('type') == 'radio') {
			
				if (inputElements[elementCount].checked == true) {
					isValid = true		
				}
			}
			
    }
    
    //Loop through all the select elements
    selectElements = divElement.getElementsByTagName('select');
    
    for (elementCount = 0;elementCount < selectElements.length; elementCount++ && isValid == false) {
    	
			if (selectElements[elementCount].value != "") {
				isValid = true		
			}
    }
    
    //Loop through all the textarea elements
    textareaElements = divElement.getElementsByTagName('textarea');
    
    for (elementCount = 0;elementCount < textareaElements.length; elementCount++ && isValid == false) {
    	
			if (textareaElements[elementCount].value != "") {
				isValid = true		
			}
    }
    
    //Loop through all the checkbox elements
    checkboxElements = divElement.getElementsByTagName('checkbox');
    for (elementCount = 0;elementCount < checkboxElements.length; elementCount++ && isValid == false) {
    	
			if (checkboxElements[elementCount].checked != "") {

				isValid = true		
			}
    }
  }
    
  return isValid;

}

/*******************************************************************************************
 * Name:         OpenHelp
 * Description:  Function used to popup the given help url.
 *******************************************************************************************/
function OpenHelp(p_url) {
  OpenWindow(p_url, "Help", 700, 500, 1, 1, "resizable=yes,scrollbars=yes");
}

/*******************************************************************************************
 * Name:         OpenLPHelp
 * Description:  Function used to popup the given help url to display the Learning Place help.
 *******************************************************************************************/
function OpenLPHelp(p_url) {
  OpenWindow(p_url, "Help", 650, 500, 0, 0, "toolbar=yes,menubar=yes,resizable=yes,scrollbars=yes,status=yes,location=yes");
}

/*******************************************************************************************
 * Name:         AddProcessing
 * Description:  Function to add Processing message to popup pages.
 *******************************************************************************************/
function AddProcessing() {
  if (document.getElementById) {
    var div = document.getElementById("divPopupNavigation");
    if (div) {
      AddProcessingFlagToObject(div);
    }
  }
}

/*******************************************************************************************
 * Name:         SelectAllCheckboxes
 * Description:  Function to check all checkboxes contained within a specified group (eg table).
 *******************************************************************************************/
function SelectAllCheckboxes(p_groupId) {
  CheckUncheck(p_groupId, true);
}

/*******************************************************************************************
 * Name:         DeselectAllCheckboxes
 * Description:  Function to uncheck all checkboxes contained within a specified group (eg table).
 *******************************************************************************************/
function DeselectAllCheckboxes(p_groupId) {
  CheckUncheck(p_groupId, false);
}

/*******************************************************************************************
 * Name:         CheckUncheck
 * Description:  Function to check or uncheck all checkboxes contained within a specified group (eg table).
 *******************************************************************************************/
function CheckUncheck(p_groupId, p_check) {
  if (document.getElementById) {
    var table = document.getElementById(p_groupId);
    
    // Get all the input elements within the group.
    var i = 0;
    var inputs = table.getElementsByTagName('input');
    
    for (i=0;i<inputs.length;i++) {
      if (inputs[i].type == "checkbox") {
        inputs[i].checked = p_check;
      }
    }
  }
}

/*******************************************************************************************
 * Name:         ReturnToApplication
 * Description:  Function to change the navigation of the 'Return to the application'
 *               link on the generic error page.  Simulate the back button.
 *******************************************************************************************/
function ReturnToApplication() {
  // If displaying error page and history exists.
  if (location.pathname.toLowerCase() == "/lpas/framework/_common/displayerror.aspx" && (history.length > 0)) {
    // Get the first link in the content section.
    if (document.getElementById) {
      var c = document.getElementById("c");
      var a = c.getElementsByTagName("a");

      // If return to application link then add onclick function.
      if (a[0] && (a[0].innerText.toLowerCase() == "return to the application")) {
        a[0].onclick = new Function('history.back(); return false;');
      }
    }
  }
}

/*******************************************************************************************
 * Name:         CreateButtonElement
 * Description:  Creates an <input type="button"> at runtime.
 * Params:       p_markerFieldId - The field where the button should be added before/after.
 *               p_text - Button text
 *               p_onclickFunction - 
 *               p_addBefore - True then add before marker field, otherwise add after the marker field.
 *******************************************************************************************/
function CreateButtonElement(p_markerFieldId, p_text, p_onclickFunction, p_addBefore) {
  if (document.getElementById) {
    if (document.getElementById(p_markerFieldId)) {
      // Get the marker field.
      var e = document.getElementById(p_markerFieldId);

      // Create the button element.
      var b = document.createElement('input');
      
      // Set attributes for the button element.
      b.setAttribute('type', 'button');
      b.setAttribute('value', p_text);
      b.onclick = new Function(p_onclickFunction);
      
      // If adding before the marker field.
      if (p_addBefore) {
        e.parentNode.insertBefore(b, e);
        e.parentNode.insertBefore(document.createTextNode(' '), e);
      } else {
        // Adding after the marker field.
        e.parentNode.insertBefore(b, e.nextSibling);
        e.parentNode.insertBefore(document.createTextNode(' '), e);
      }
    }
  }
}

/*******************************************************************************************
 * Name:         GetParameterValue
 * Description:  Gets a parameter value from a given url string.
 * Params:       p_url - url including querystring.
 *               p_parameter - Parameter name.
 *******************************************************************************************/
function GetParameterValue(p_url, p_parameter) {
  var startPos = -1;
  var endPos = -1;
  
  startPos = p_url.indexOf('?' + p_parameter + '=');
  if (startPos < 0) {
   startPos = p_url.indexOf('&' + p_parameter + '=');
  }
  // Parameter does not exist in the string.
  if (startPos < 0) {
    return "";
  }
  
  // Get start pos of parameter value.
  startPos += (p_parameter.length + 2);
  
  // Get the end pos of the parameter value.
  endPos = p_url.indexOf('&', startPos + 1);
  
  if (endPos < 0) {
    endPos = p_url.length;
  }
  
  return p_url.substring(startPos, endPos);
}

/*******************************************************************************************
 * Name:         DisableField
 * Description:  Disables a field.
 * Params:       p_fieldId - The field where the button should be added before/after.
 *******************************************************************************************/
function DisableField(p_fieldId) {
  if (document.getElementById) {
    if (document.getElementById(p_fieldId)) {
      document.getElementById(p_fieldId).disabled = "true";
    }
  }
}

/*******************************************************************************************
 * Name:         ValidateField
 * Description:  Validates a field and adds error message to validation summary if invalid.
 * Params:       p_fieldId - The field where the button should be added before/after.
 *               p_regEx   - regular expression.
 *               p_message - error message.
 *******************************************************************************************/
function ValidateField(p_fieldId, p_fieldLabel, p_regEx, p_message, p_isMandatory) {
  var returnVal = false;
  
  if (document.getElementById) {
    if (document.getElementById(p_fieldId)) {
      var regEx = new RegExp(p_regEx);
      var str = document.getElementById(p_fieldId).value;
      
      if (str.length > 0) {
        // Validate the field value with the regular expression.
        if (regEx.test(str)) {
          returnVal = true;
        } else {
          // Add error message to validation summary.
          AddErrorMessage(p_message);
        }
      } else {
        // String is null.
        if (!p_isMandatory) {
          returnVal = true;
        } else {
          // Add error message to validation summary.
          AddErrorMessage(p_fieldLabel + ': This field is mandatory.');
        }
      }
    }
  }
  return returnVal;
}

/*******************************************************************************************
 * Name:         AddErrorMessage
 * Description:  Clear the validation summary and add new error message.
 * Params:       p_message - error message or validator id.
 *******************************************************************************************/
function AddErrorMessage(p_message) {
  // Get the validation summary.
  var vld = document.getElementById("vldSummary");
  var errorMsg = "<div>Error<br />{0}</div>";
  
  // Set the error message.
  errorMsg = errorMsg.replace("{0}", p_message);
  
  // Clear the validation summary.
  vld.innerHTML = "";
  
  // Set the properties for the validation summary.
  vld.className = "errormessage";
  vld.innerHTML = errorMsg;
  vld.style.display = "block";
}

/*******************************************************************************************
 * Name:         SetupForm
 * Description:  Add a dummy textbox to the form if only one textbox exists.
 *               Add a class to buttons and checkboxes.
 *               Wrap the help icon in a div tag and add "Help" text.
 *******************************************************************************************/
function SetupForm() {
  // Get the forms on the page.
  var frm = document.getElementsByTagName("form");
  
  // Forms were found on the page.
  if (frm.length > 1) {
    var inputs = frm[1].getElementsByTagName("input");
    var i = 0;
    var j = 0;
    
    // Loop through each input field on the form.
    while (inputs[i]) {
      if (inputs[i].type == "text") {
        j++;
      } else if (inputs[i].type == "submit" || inputs[i].type == "button" || inputs[i].type == "reset") {
        // Add css class to button control.
        AddClass(inputs[i], "button");
        
      } else if (inputs[i].type == "checkbox") {
        // Add css class to checkbox control.
        AddClass(inputs[i], "checkbox");

      }
      i++;
    }
    
    // If only one textbox on the form.
    if (j == 1) {
      // Create a dummy textbox.
      var txt = document.createElement("input");
      txt.setAttribute("type", "text");
      txt.style.display = "none";
      
      // Add the dummy textbox to the form.
      frm[1].appendChild(txt);
    }
    
    // Get any links on the form.
    var links = frm[1].getElementsByTagName("a");
    
    i = 0;
    
    //Loop through each link.
    while (links[i]) {
      // If link is help icon.
      if (links[i].className == "helplink") {
        // Wrap help icon in a DIV tag and add "Help" text.
        var div = document.createElement("div");
        var spn = document.createElement("span");
        div.id = "divHelp";
        spn.innerText = "Help";
        links[i].appendChild(spn);
        div.appendChild(links[i]);
        frm[1].appendChild(div);
        
        // Exit the loop.
        i = 99999;
      }
      i++;
    }
  }
}

/*******************************************************************************************
 * Name:         AddProcessingFlagToObject
 * Description:  Adds the processing flag message to the given object.
 *******************************************************************************************/
function AddProcessingFlagToObject(p_object) {
  // Turn on the object and add "Processing..." statement.
  p_object.style.display = "block";
  p_object.className = "processing";
  p_object.innerHTML = "Processing...";
}

/*******************************************************************************************
 * Name:         AddClass
 * Description:  Adds a class name to a given element.
 * Parameters:   p_element   - Element.
 *               p_className - Class name.
 *******************************************************************************************/
function AddClass(p_element, p_className) {
  var cssClass = p_element.className;

  if (cssClass.length != 0) {
    cssClass += " ";
  }
        
  // Add a class of "button" to each button.
  cssClass += p_className;
  p_element.className = cssClass;
}

/*******************************************************************************************
 * Name:         ConfirmRollOverSubjectClassGroup
 * Description:  Confirms that the user wants to rollover the subject class group
 * Parameters:   No parameter
 *******************************************************************************************/
function ConfirmRollOverSubjectClassGroup(p_message, p_URL) {

  if (document.getElementById) {
      alert(p_URL);
     // var isConfirmed = 
      return confirm(p_message);
      /*if (isConfirmed)
      {
       
      }*/
    }
  }

/*******************************************************************************************
 * Name:         SaveReceivingCentreDetailsOnClick
 * Description:  Confirms that the user wants to add new receving centre. 
 * Parameters:   No p_message
 *******************************************************************************************/
function SaveReceivingCentreDetailsOnClick(p_message) {
  
 if (document.getElementById) {
 
    if (Page_IsValid) {

      if (ConfirmMessage(p_message)) {
        AddProcessingFlag();
        return true;
      }
      else {
        return false;
      } 
    }
    else {
      return  false;
    }
  }
 
}

/*******************************************************************************************
 * Name:         SaveDeliveryCentreDetailsOnClick
 * Description:  Confirms that the user wants to add new delivery centre.
 * Parameters:   No p_message
 *******************************************************************************************/
function SaveDeliveryCentreDetailsOnClick(p_message) {

if (document.getElementById) {
 
    if (Page_IsValid) {

      if (ConfirmMessage(p_message)) {
        AddProcessingFlag();
        return true;
      }
      else {
        return false;
      } 
    }
    else {
      return  false;
    }
  }
}

/*******************************************************************************************
 * Name:         SetSelectedUser
 * Description:  Function used to enable the edit controls on the Prerequisite popup.
 * Parameters:   p_userId - boolean to indicate whether to enable or disable the controls.
 * Parameters:   p_fieldId - boolean to indicate whether to enable or disable the controls.
 *******************************************************************************************/
function SetSelectedUser(p_userId,p_fieldId)
{

var selecetedValue = document.getElementById(p_fieldId);
selecetedValue.value = p_userId;
}

/*******************************************************************************************
 * Name:         SelectDropDownOnClickOfCheckBox
 * Description:  Function used to enable the edit controls on the Prerequisite popup.
 * Parameters:   p_checkBoxId - CheckBox Id on which click this function called.
 * Parameters:   p_comboBoxId - Id of dropdown box in which value to be set.
 * Parameters:   p_valueSelectedOnChecked - value of selected item in dropdown box.
 *******************************************************************************************/
function SelectDropDownOnClickOfCheckBox(p_checkBoxId,p_comboBoxId,p_valueSelectedOnChecked)
{
    //Get element by Id for check box
    var checkBox = document.getElementById(p_checkBoxId );

    //If check box select then set activitiy status to 
    if (checkBox.checked) {
        SelectDropDownItemByValue(p_comboBoxId,p_valueSelectedOnChecked,false)

    }
}

/*******************************************************************************************
 * Name:         SelectDropDownOnClickOfCheckBox
 * Description:  Function used to enable the edit controls on the Prerequisite popup.
 * Parameters:   p_checkBoxId - CheckBox Id in which checked on the change of dropdown value.
 * Parameters:   p_comboBoxId - Dropdown Id on which change this function will be called.
 * Parameters:   p_valueSelectedOnChecked - value of selected item in dropdown box by which checked.
 * Parameters:   p_valueSelectedOnUnChecked - value of selected item in dropdown box by which Unchecked.
 *******************************************************************************************/
function SelectCheckBoxOnChangeOfDropDown(p_checkBoxId,p_comboBoxId,p_valueSelectedByWhichChecked,p_valueSelectedByWhichUnChecked)
{

//Get element by Id for check box
var checkBox = document.getElementById(p_checkBoxId );

//Get element by Id for check box
var dropdownList = document.getElementById(p_comboBoxId);
//if passing value for checked match with drop down selected value then set checkbox checked true  
if (Trim(dropdownList.options[dropdownList.selectedIndex].value) == Trim(p_valueSelectedByWhichChecked)) {
    checkBox.checked=true;
    }
//if passing value for UnChecked match with drop down selected value then set checkbox checked false      
else if  (Trim(dropdownList.options[dropdownList.selectedIndex].value) == Trim(p_valueSelectedByWhichUnChecked) ) { 
  checkBox.checked=false;
    }  
}

/*******************************************************************************************
 * Name:         SaveDeliveryCentreDetailsOnClick
 * Description:  Confirms that the user wants to add new delivery centre.
 * Parameters:   No p_message
 *******************************************************************************************/


function ValidateAdminPopupControl(source, args) {
  args.isValid = true;
  
  var selectedOptionField = document.getElementById(source.title + m_txtSelectedValue);
  var valueField = document.getElementById(source.title + m_txtValue);
  
  if ( Trim(valueField.value) != "" && Trim(selectedOptionField.value) == "") {
    args.IsValid = false;
  }
  return args.IsValid;
}

/*******************************************************************************************
 * Name:         ValidateLessonNumber
 * Description:  Confirms that the user wants to add new delivery centre.
 * Parameters:   No p_message
 *******************************************************************************************/
function ValidateLessonNumber(source, args) {
  args.isValid = true;
  var idArray =source.title.split("|");
  var idLessonSequence=idArray[0];
  var idLessoNumberLimit=idArray[1];
  
  var selectedValue = document.getElementById(idLessonSequence);
  var maxLessonLimit = document.getElementById(idLessoNumberLimit);
  
  
  if ( parseInt(selectedValue.options[selectedValue.selectedIndex].value) > parseInt(maxLessonLimit.value)) {
 // alert("You selected more than lesson limit");
    args.IsValid = false;
  }
  return args.IsValid;
}

/*******************************************************************************************
 * Name:         ValidateExitResult
 * Description:  Check whether exit result and the rank both are selected when one them is selected.
 * Parameters:   No p_message
 *******************************************************************************************/
function ValidateExitResult(source, args) {
  args.isValid = true;
  var idArray =source.title.split("|");
  var cboStudentResultId =idArray[0];
  var cboAchievementIndicatorId=idArray[1];
  
  var cboStudentResultField = document.getElementById(cboStudentResultId);
  var cboAchievementIndicatorField = document.getElementById(cboAchievementIndicatorId);
  
  source.errormessage = "";
  
  if ( cboStudentResultField.options[cboStudentResultField.selectedIndex].value != "" && cboAchievementIndicatorField.options[cboAchievementIndicatorField.selectedIndex].value == "") {
    source.errormessage = "Exit rank must be selected for the selected Exit achievement."
    args.IsValid = false;
  }
  if ( cboStudentResultField.options[cboStudentResultField.selectedIndex].value == "" && cboAchievementIndicatorField.options[cboAchievementIndicatorField.selectedIndex].value != "") {
    source.errormessage = "Exit achievement must be selected for the selected Exit rank."
    args.IsValid = false;
  }
  
  return args.IsValid;
}


/*******************************************************************************************
 * Name:         ValidateTimeText
 * Description:  Make Standared format for Time if user input correct
 * Parameters:   No p_message
 *******************************************************************************************/
function ValidateTimeText(p_txtId) {
  //Vaiable declariton
    var timeAMPM='AM';
    var textValue=document.getElementById(p_txtId);
    var inputTime=textValue.value;
  
    //Make upper case string  
    inputTime=inputTime.toUpperCase();
  
    //Get splited string after AM/A
    var timeArray =inputTime.split('A');
    varTime=inputTime;
   
    if(timeArray.length > 1) {
          varTime=timeArray[0];
          timeAMPM="AM";
    }   
    else{ 
          var timeArrayP =inputTime.split('P');
          if(timeArrayP.length > 1){
              varTime=timeArrayP[0];
              timeAMPM="PM";
        }
    } 
  //IF length 3 then add a prefix 0
  if(varTime.length >= 3 && varTime.length <= 5) {
   
      var arrTimehhmm= varTime.split(':');
      //If : find
      if(arrTimehhmm.length >1){ 
          if (varTime.length==4){
          varhh=arrTimehhmm[0];
          varmm=arrTimehhmm[1];
        
          //if Hour part shorter append prefix 
            if(varhh.length==1){ 
                varhh='0'+ varhh;
              }
              //if miniute part shorter append prefix
             if(varmm.length==1){ 
                 varmm='0'+ varmm;
                }  
             varTime=varhh + ':' + varmm;  
          }
      //add : in between 
     if(varTime.length==5){
         varTime=varTime.substring(0,2) + ':' + varTime.substring(3,5);
          }
      }
   else{   
        if (varTime.length==3){
            varTime='0'+ varTime;
          }
      //add : in between 
     if(varTime.length==4){
          varTime=varTime.substring(0,2) + ':' + varTime.substring(2,4);
        }
     }
  }
   
    // alert(varTime+timeAMPM);
    var formatedTime=varTime + timeAMPM;
    //IF time in right format
    if(formatedTime.length==7){
    textValue.value=varTime+timeAMPM;
    }
return false;
}


/*******************************************************************************************
 * Name: ClearValue     
 * Description: This clears the popup control of values
 *******************************************************************************************/
function ClearValue(p_popupControl,p_descFieldId)
{
  var valueField;
  
  if (document.getElementById) {

    valueField = document.getElementById(p_popupControl + m_txtValue);
  	  
		// If description field is passed, then add description.
    if (p_descFieldId != undefined) {
      document.getElementById(p_descFieldId).innerText = ""; 
    }
		valueField.value = "";
  }
}

/*******************************************************************************************
 * Name:         ClientValidateLessonTime
 * Description:  Validates row
 * Parameters:   p_vreLessonTime 
 *******************************************************************************************/
function ClientValidateLessonTime(p_vreLessonTime) {
  var i;
  var validLessonTimes;
 
  validLessonTimes = true;
  
  for (i = 0; i < Page_Validators.length; i++) {
		if (Page_Validators[i].id.indexOf(p_vreLessonTime) >= 0) {
			//Page_Validators[i].enabled = true;
			ValidatorValidate(Page_Validators[i]);
			ValidatorUpdateDisplay(Page_Validators[i]);
      if (Page_Validators[i].isvalid  == false) {
        if (validLessonTimes == true) {
          validLessonTimes = false;
        }         
      }
		}
		else {
		  Page_Validators[i].isvalid = true;
		}
  }
  if (validLessonTimes == false) {
    ValidationSummaryOnSubmit(); 
  }
  return validLessonTimes;
}

/*******************************************************************************************
 * Name:         RemoveLessonOnClick
 * Description:  Confirms that the user wants to add new delivery centre.
 * Parameters:   No p_message
 *******************************************************************************************/
function RemoveLessonOnClick(p_gridId,p_messageConfirm,p_messageSelect,p_validatorId) {

    if ( ConfirmOperation(p_gridId,p_messageConfirm,p_messageSelect))
    {
       if(ClientValidateLessonTime(p_validatorId)) {
          return true;
       }
       else
      { 
        return false;
      }
    }   
    return false;
}

/*******************************************************************************************
 * Name:         EnableControls
 * Description:  Enable all control under the passed group for retaning view state
 *******************************************************************************************/
function EnableControls(p_group) {
 if (document.getElementById(p_group) != null) 
  {
  var returnValue = true;
  if (document.getElementById(p_group) != null) 
  {
    var inputs = document.getElementById(p_group).getElementsByTagName('select');
    // See if there are any records selected for deletion.
    for (var i = 0; i < inputs.length; i++) {
    inputs[i].disabled=false;
    }  
  }
 }
 return returnValue;  
}

  
 /*******************************************************************************************
 * Name:         SetSelectedGroupLesson
 * Description:  Function used to enable the edit controls on the Prerequisite popup.
 * Parameters:   p_GroupId - boolean to indicate whether to enable or disable the controls.
 * Parameters:   p_lessonId - boolean to indicate whether to enable or disable the controls.
 * Parameters:   p_fieldId - boolean to indicate whether to enable or disable the controls.
 *******************************************************************************************/
function SetSelectedGroupLesson(p_lessonGroupId,p_lessonId,p_lessonSequence,p_group,p_textBoxId)
{
 	// DOM check.
  if (document.getElementById) {
    
    var input = document.getElementById(p_textBoxId); 
    var divElement;	
    var elementCount;
    
    //Blank the hidden field.	
    input.value = "";
    
    //Get the table row item
	  divElement = document.getElementById(p_group);
    
    //Loop through all the input elements in table row
    inputElements = divElement.getElementsByTagName('input');
    
    for (elementCount = 0;elementCount < inputElements.length; elementCount++ ) {
    
			 if (inputElements[elementCount].getAttribute('type') == 'radio') {
			
				if (inputElements[elementCount].checked == true) {
					input.value += inputElements[elementCount].value	+ "^"
				}
			}
    }
  
  }
}

/*******************************************************************************************
 * Name:         buttonPress
 * Description:  Puts the name of a button in the specified hidden field
 * Parameters:   p_buttonId
 *               p_hiddenId
 *******************************************************************************************/
 function buttonPress(p_buttonId, p_hiddenId){
  
  // DOM check.
  if (document.getElementById) {
    
    var hiddenField = document.getElementById(p_hiddenId); 
    hiddenField.value = p_buttonId
    
  }
  
 }


/*******************************************************************************************
 * Name:         ValidateLessonNumber
 * Description:  Confirms that the user wants to add new delivery centre.
 * Parameters:   No p_message
 *******************************************************************************************/


function ValidateLessonSelection(source, args) {

// DOM check.
 if (document.getElementById) {
  
    args.isValid = true;
    var idArray =source.title.split("|");
    var groupId=idArray[0];
    var totalLesson=idArray[1];
    var totalCheckedFound=0;
    var divElement;	
    var elementCount;
    var selectedForDeletion;
   
    selectedForDeletion = false;
    
      //Get the table row item
	    divElement = document.getElementById(groupId);
  	  
	    //Loop through all the input elements in table row
      inputElements = divElement.getElementsByTagName('input');
      
    for (elementCount = 0;elementCount < inputElements.length; elementCount++ ) {
      
			  if (inputElements[elementCount].getAttribute('type') == 'radio') {
  			
				  if (inputElements[elementCount].checked == true) {
				  totalCheckedFound=totalCheckedFound + 1;
					  //input.value += inputElements[elementCount].value	+ "^"
				  }
			  }
			  
			  //Check if check box is ticked for deletion
			  if (inputElements[elementCount].getAttribute('type') == 'checkbox') {
  			
				  if (inputElements[elementCount].checked == true) {
				    if (selectedForDeletion == false) {
				      selectedForDeletion = true
				    }
				    
				  }
			  }
      }
    
    if ( totalCheckedFound != totalLesson ) {
    
      //if selected for deletion then don't validate
      if (selectedForDeletion == false) {
        args.IsValid = false;
      }
    }
 }  
    return args.IsValid;
}
/*******************************************************************************************
 * Name:         SelectListAutoPostBack
 * Description:  Onchange event for select list that will auto post back a page.
 * Parameters:   p_listFieldId - The id of the drop down list field.
 *******************************************************************************************/
function SelectListAutoPostBack(p_listFieldId) {

  if (document.getElementById) {
  
    if(navigator.userAgent.indexOf("Firefox") != -1)
    {
      
    }else{
      AddProcessingFlag();
    }
  
    var list = document.getElementById(p_listFieldId);
    var itemId = document.getElementById("hidSelectedIndexId");
    var groupId = document.getElementById("hidSelectedGroupId");
    var groupText = document.getElementById("hidSelectedGroupValue");
    
    var listValues = "";
    var listText = "";
 
    //store the selected group and its index
    itemId.value = list.selectedIndex;
    groupId.value = list.options[list.selectedIndex].value;
    groupText.value = list.options[list.selectedIndex].text;
   
    // store the group list values
    for (var j=0;j<list.options.length;j++) {
        if (list.options[j].text != "")
        {
          if (listValues != "") 
          { 
            listValues += m_delimiter;
            listText += m_delimiter;
          }
          listValues += list.options[j].value;
          listText +=   list.options[j].text;
        }
    }

    var valueInput = document.getElementById("hidSelectedValue");
    var textInput = document.getElementById("hidSelectedText");
    
    // Set the Selected hidden form input values
    valueInput.value = listValues;
    
    // Set the Selected hidden form input text
    textInput.value = listText;
    
    // clear the other hiddn fields used for members
    var ctrl = document.getElementById("hidNewMembers");
    ctrl.value = ""
    ctrl = document.getElementById("hidRemovedMembersText");
    ctrl.value = ""
    ctrl = document.getElementById("hidRemovedMembersId");
    ctrl.value = ""

    list.form.submit();
  }
}
/*******************************************************************************************
 * Name:         SelectListAutoPostBackRestore
 * Description:  This will restore the selected item after the SelectListAutoPostBack.
 * Parameters:   p_listFieldId - The id of the group list
 *******************************************************************************************/
function SelectListAutoPostBackRestore(p_listFieldId) {
  
  if (document.getElementById) {
    var list = document.getElementById(p_listFieldId);
    var itemId = document.getElementById("hidSelectedIndexId");
    
    var valueInput = document.getElementById("hidSelectedValue");
    var textInput = document.getElementById("hidSelectedText");
     
    var listValues = valueInput.value.split(m_delimiter);
    var listTexts = textInput.value.split(m_delimiter);

    var listOption
    for (var i=0; i<listValues.length; i++) {
        listOption = document.createElement("OPTION");
        list.options.add(listOption);
        listOption.innerText  = listTexts[i];
        listOption.value      = listValues[i];
        
    }

    list.selectedIndex = itemId.value;
  }
}

/*******************************************************************************************
 * Name:         SetMaintainResourceCentreButtons
 * Description:  Sets the availability of the 
 *******************************************************************************************/
function SetMaintainResourceCentreButtons() {
  if (window.opener == null)
  {
    var doc = window.document
  }
  else
  {
    var doc = window.opener.document
  }

  if (doc.getElementById) {
  
    var groupInput = doc.getElementById("lstGroups");
    if (groupInput == null) return;
    
    var disableGroups = (groupInput.selectedIndex == -1);
    
    var btn = doc.getElementById("divGroupsButtonsOpt")
    if (btn == null) return;
    btn.disabled = disableGroups;
   
    //btn = doc.getElementById("btnRemoveGroups");
    //if (btn == null) return;
    //btn.disabled = disableGroups;
    
    //btn = doc.getElementById("btnAddMembers");
    btn = doc.getElementById("divMembersButtons");
    if (btn == null) return;
    btn.disabled = disableGroups;
    
    btn = doc.getElementById("divGroupsOfGroupsButtons");
    if (btn == null) return;
    btn.disabled = disableGroups;
    
    
    var membersInput = doc.getElementById("lstMembers");
    if (membersInput == null) return;
    
    var disableMembers = (membersInput.options.length == 0);
    btn = doc.getElementById("divRemoveButton")
    if (btn == null) return;
    btn.disabled = disableMembers;
  }
}
/*******************************************************************************************
 * Name:         SetListContentsHiddenCache
 * Description:  This stores the contents of a listbox in a hidden field. These values can
 *               be restored by calling GetListContentsHiddenCache
 * Parameters:   p_listInputId - The id of the list
 *               p_hiddenCacheId - The hidden field to populate
 *******************************************************************************************/
function SetListContentsHiddenCache(p_listInputId, p_hiddenCacheId) {
  if (document.getElementById)
  {
    var list  = document.getElementById(p_listInputId);
    var cache = document.getElementById(p_hiddenCacheId);
    
    var listData = "";
    
    for (var i=0;i<list.options.length;i++)
    {
      if (list.options[i].value != "" && list.options[i].text)
      {
        if (listData != "") listData += m_delimiter;
        
        listData += list.options[i].value + m_delimiter + list.options[i].text;
      }
    }

    cache.value = listData;
  }
}
/*******************************************************************************************
 * Name:         GetListContentsHiddenCache
 * Description:  This stores the contents of a listbox in a hidden field. These values can
 *               be restored by calling GetListContentsHiddenCache
 * Parameters:   p_listInputId - The id of the list
 *               p_hiddenCacheId - The hidden field to populate
 *******************************************************************************************/
function GetListContentsHiddenCache(p_listInputId, p_hiddenCacheId) {
  if (document.getElementById)
  {
    var list  = document.getElementById(p_listInputId);
    var cache = document.getElementById(p_hiddenCacheId);
    
    var listData = cache.value.split(m_delimiter);
    var opt = 0;
    
    if (listData.length == 0) return;
    
    // clear any existing list contents
    list.options.length = 0;
    
    // unpack the value/text pairs
    for (var i=0;i<listData.length;i=i+2)
    {
      if (listData[i] != "")
      {
        list.options.length ++;
        opt = list.options.length - 1;
        
        list.options[opt].value = listData[i];
        list.options[opt].text  = listData[i + 1];
      }
    }
    
    // clear the cache
    cache.value = "";
  }
}

/*******************************************************************************************
 * Name:         ToggleInputControls
 * Description:  Function used to enable and disable input controls in the specified divs.
 * Parameters:   p_divIdToEnable - The id of the div of which input controls needs to be enabled
 *               p_divIdToDisable - The id of the div of which input controls needs to be disabled
 *******************************************************************************************/
function ToggleInputControls(p_divIdToEnable,p_divIdToDisable) {
  
  var divElementToEnable;
  var divElementToDisable;
  
  divElementToEnable = document.getElementById(p_divIdToDisable);
  divElementToDisable = document.getElementById(p_divIdToDisable);

  if (divElementToEnable != null) {
    EnableInputControls(p_divIdToEnable);
    EnableValidators(p_divIdToEnable);
  }
  
  if (divElementToDisable != null) {
    DisableInputControls(p_divIdToDisable);
    DisableValidators(p_divIdToDisable);
  }
  
}

/*******************************************************************************************
 * Name:         EnableInputControls
 * Description:  Function used to enable all the input controls in the div.
 * Parameters:   p_divId - The id of the div of which input controls needs to be enabled
 *******************************************************************************************/
function EnableInputControls(p_divId) {

 var divElement;
 var inputElements;
 var selectElements;
 var textareaElements;
 var checkboxElements;
 var elementCount;

  // DOM Check
  if (document.getElementById) {

    //get a handle on the element
    divElement = document.getElementById(p_divId);
    
    //Loop through all the input elements
    inputElements = divElement.getElementsByTagName('input');

    for (elementCount = 0;elementCount < inputElements.length; elementCount++ ) {
    
			if (inputElements[elementCount].getAttribute('type') == 'text') {
				inputElements[elementCount].disabled = false;
			} else if (inputElements[elementCount].getAttribute('type') == 'password') {
				inputElements[elementCount].disabled = false;
			} else if (inputElements[elementCount].getAttribute('type') == 'checkbox') {
				inputElements[elementCount].disabled = false;
			} else if (inputElements[elementCount].getAttribute('type') == 'submit') {
			  inputElements[elementCount].disabled = false;
			} else if (inputElements[elementCount].getAttribute('type') == 'button') {
			  inputElements[elementCount].disabled = false;
			} else if (inputElements[elementCount].getAttribute('type') == 'reset') {
			  inputElements[elementCount].disabled = false;
			} else if (inputElements[elementCount].getAttribute('type') == 'file') {
			  inputElements[elementCount].disabled = false;
			}
			
    }
    
    //Loop through all the select elements
    selectElements = divElement.getElementsByTagName('select');
    
    for (elementCount = 0;elementCount < selectElements.length; elementCount++ ) {
			selectElements[elementCount].disabled = false;
    }
    
    //Loop through all the textarea elements
    textareaElements = divElement.getElementsByTagName('textarea');
    
    for (elementCount = 0;elementCount < textareaElements.length; elementCount++ ) {
			textareaElements[elementCount].disabled = false;
    }
    
    //Loop through all the checkbox elements
    checkboxElements = divElement.getElementsByTagName('checkbox');
    for (elementCount = 0;elementCount < checkboxElements.length; elementCount++ ) {
			checkboxElements[elementCount].disabled = false;
    }
  }
  
}

/*******************************************************************************************
 * Name:         DisableInputControls
 * Description:  Function used to disable all the input controls in the div.
 * Parameters:   p_divId - The id of the div of which input controls needs to be disabled
 *******************************************************************************************/
function DisableInputControls(p_divId) {

 var divElement;
 var inputElements;
 var selectElements;
 var textareaElements;
 var checkboxElements;
 var elementCount;

  // DOM Check
  if (document.getElementById) {

    //Get a handle on the div
    divElement = document.getElementById(p_divId);
    
    //Loop through all the input elements
    inputElements = divElement.getElementsByTagName('input');
    
    for (elementCount = 0;elementCount < inputElements.length; elementCount++ ) {
    
			if (inputElements[elementCount].getAttribute('type') == 'text') {
				inputElements[elementCount].disabled = true;
			} else if (inputElements[elementCount].getAttribute('type') == 'password') {
				inputElements[elementCount].disabled = true;
			} else if (inputElements[elementCount].getAttribute('type') == 'checkbox') {
				inputElements[elementCount].disabled = true;
			} else if (inputElements[elementCount].getAttribute('type') == 'submit') {
			  inputElements[elementCount].disabled = true;
			} else if (inputElements[elementCount].getAttribute('type') == 'button') {
			  inputElements[elementCount].disabled = true;
			} else if (inputElements[elementCount].getAttribute('type') == 'reset') {
			  inputElements[elementCount].disabled = true;
			} else if (inputElements[elementCount].getAttribute('type') == 'file') {
			  inputElements[elementCount].disabled = true;
			}
			
    }
    
    //Loop through all the select elements
    selectElements = divElement.getElementsByTagName('select');
    
    for (elementCount = 0;elementCount < selectElements.length; elementCount++ ) {
			selectElements[elementCount].disabled = true;
    }
    
    //Loop through all the textarea elements
    textareaElements = divElement.getElementsByTagName('textarea');
    
    for (elementCount = 0;elementCount < textareaElements.length; elementCount++ ) {
			textareaElements[elementCount].disabled = true;
    }
    
    //Loop through all the checkbox elements
    checkboxElements = divElement.getElementsByTagName('checkbox');
    for (elementCount = 0;elementCount < checkboxElements.length; elementCount++ ) {
			checkboxElements[elementCount].disabled = true;
    }
  }
}

/*******************************************************************************************
 * Name:         EnableValidators
 * Description:  Function used to enable all the validators in the div.
 * Parameters:   p_divId - The id of the div of which validators needs to be enabled
 *******************************************************************************************/
function EnableValidators(p_divId) {

 var divElement;
 var spanElements;
 var selectElements;
 var textareaElements;
 var checkboxElements;
 var elementCount;

  // DOM Check
  if (document.getElementById) {

    //get a handle on the div
    divElement = document.getElementById(p_divId);
    
    //Loop through all the input elements
    spanElements = divElement.getElementsByTagName('span');
    
    for (elementCount = 0;elementCount < spanElements.length; elementCount++ ) {
    
			if (spanElements[elementCount].getAttribute('controltovalidate') != '') {
				spanElements[elementCount].enabled = true;
			} else if (spanElements[elementCount].getAttribute('clientvalidationfunction') != '') {
				spanElements[elementCount].enabled = true;
			} 
    }
  }
}

/*******************************************************************************************
 * Name:         DisableValidators
 * Description:  Function used to disable all the validators in the div.
 * Parameters:   p_divId - The id of the div of which validators needs to be disabled
 *******************************************************************************************/
function DisableValidators(p_divId) {

 var divElement;
 var spanElements;
 var selectElements;
 var textareaElements;
 var checkboxElements;
 var elementCount;

  // DOM Check
  if (document.getElementById) {

    //get a handle on the div
    divElement = document.getElementById(p_divId);
    
    //Loop through all the input elements
    spanElements = divElement.getElementsByTagName('span');
    
    for (elementCount = 0;elementCount < spanElements.length; elementCount++ ) {
    
			if (spanElements[elementCount].getAttribute('controltovalidate') != '') {
				spanElements[elementCount].enabled = false;
			} else if (spanElements[elementCount].getAttribute('clientvalidationfunction') != '') {
				spanElements[elementCount].enabled = false;
			} 
    }
  }
}

/*******************************************************************************************
 * Name:         SetSelectedValue
 * Description:  Function to put a value in a field
 * Parameters:   p_value - value to put in the control.
 *               p_fieldId - control id to put the value in.
 *******************************************************************************************/
function SetSelectedValue(p_value,p_fieldId)
{
  // DOM Check
  if (document.getElementById) {  
    var selecetedValue = document.getElementById(p_fieldId);
    selecetedValue.value = p_value;
  }
}

/*******************************************************************************************
 * Name:         UnverifyUser
 * Description:  Function to put to Change the Verification Status dropdown to Unverified.
 * Parameters:   p_unverifiedLookupCd - value to put in the control.
 *               p_unverifiedLookupCd - value to take out of the control.
 *               p_statusDropDownID - control id to put the value in.
 *******************************************************************************************/
 function UnverifyUser(p_unverifiedLookupCd, p_verifiedLookupCd, p_statusDropDownID){

   // DOM Check
   if (document.getElementById) {

     //Get a refence to the dropdown list.
     var dropdown = document.getElementById(p_statusDropDownID);

     if (dropdown.firstChild.options[dropdown.firstChild.selectedIndex].value == Trim(p_verifiedLookupCd)){

       // Find the index of the option holding the current value
       for (var i=0;i<dropdown.firstChild.options.length;i++) {

         if (Trim(dropdown.firstChild.options[i].value) == Trim(p_unverifiedLookupCd)) {

           dropdown.firstChild.selectedIndex = i;
           
         }else{ 

           if((Trim(dropdown.firstChild.options[i].value) == Trim(p_verifiedLookupCd))){   

             dropdown.firstChild.remove(i);    
           }
          
         }
        
       }
    
    }
   
  }   
 
 }
 
 /*******************************************************************************************
 * Name:         AddTimeStamp
 * Description:  Function to put Date time in a field.
 * Parameters:   p_fieldId - control id to put the value in.
 *******************************************************************************************/
function AddTimeStamp(p_fieldId)
{
  // DOM Check
  if (document.getElementById) { 
  
    //Get reference on the field 
    var inputField = document.getElementById(p_fieldId);
    
    //Get the current date
    var dt = new Date();
    
    //Format the Date
    var dateString = dt.getDate()  + '/' + (dt.getMonth() + 1) + '/' + dt.getFullYear().toString().substr(2, 2);
    
    //Format the time
    var hours = dt.getHours();
    var minutes = dt.getMinutes().toString();
    var AMPM = 'AM';

    //Turn to 12 hr time
    if(hours > 12){
      hours = hours - 12;
      AMPM = 'PM';
    }
    
    //Pad the minutes
    while(minutes.length < 2){
      minutes = '0' + minutes;
    }
    
    //Add the time to the date string
    dateString += ' ' + hours + ':' + minutes + ' ' + AMPM;
    
    //place the datetime stamp into the field.
    inputField.value += dateString + '\n';
    
    //Fire onchange event.
    RunOnChange(inputField);
    
  }
}

 /*******************************************************************************************
 * Name:         CssPrint
 * Description:  Function to hide non printing area and print it before putting it back for view batches.
 *******************************************************************************************/
function CssPrint(){

// DOM Check
  if (document.getElementById) { 
  
    //Change the class to no print
    if (document.getElementById("divNoPrintOne")){
			document.getElementById("divNoPrintOne").className = 'noprint';
		}
		if (document.getElementById("divNoPrintTwo")){
			document.getElementById("divNoPrintTwo").className = 'noprint';
    }
		if (document.getElementById("pageheader")){
			document.getElementById("pageheader").className = 'noprint';
    }
		
    if(document.getElementById("imgPrint")){
			document.getElementById("imgPrint").className = 'noprint';
    }
    if(document.getElementById("divHelp")){
			document.getElementById("divHelp").className = 'noprint';
    }
    
    //print the document
    window.print();
    
    //Chane the class back to print
    if(document.getElementById("divNoPrintOne")){
			document.getElementById("divNoPrintOne").className = 'print';
    }
    if(document.getElementById("divNoPrintTwo")){
			document.getElementById("divNoPrintTwo").className = 'print';
    }
    if (document.getElementById("pageheader")){
			document.getElementById("pageheader").className = 'print';
    }
      
    if(document.getElementById("imgPrint")){
			document.getElementById("imgPrint").className = 'print';
    }
    if(document.getElementById("divHelp")){
			document.getElementById("divHelp").className = 'print';
    }
    
  }
  return false;
}


 /*******************************************************************************************
 * Name:         VerifyWarning
 * Description:  Function to put Date time in a field.
 * Parameters:   p_cboStatusId - control id to put the value in.
 *               p_manVerifiedLookupCd - Manually Verify lookup code
 *               p_verifiedLookupCd - Verified lookup code
 *******************************************************************************************/
function VerifyWarning(p_cboStatusId, p_manVerifiedLookupCd, p_verifiedLookupCd){

  // DOM Check
 if (document.getElementById) { 
    
    var cboStatus = document.getElementById(p_cboStatusId)
    
    //check if the record is not manually verified, or verifeid
    if((cboStatus.firstChild.options[cboStatus.firstChild.selectedIndex].value != Trim(p_manVerifiedLookupCd))
     && (cboStatus.firstChild.options[cboStatus.firstChild.selectedIndex].value != Trim(p_verifiedLookupCd)))
    {
      
      var message;
      message = "The user record cannot be verified. Do you want to manually verify this user.";
      message = message + "\n\nPress OK to manually verify and save.";
      message = message + "\nPress Cancel to just save.";
  
      if(Confirm(message)){
        
        //select manually verified
        // Find the index of the option holding the current value
       for (var i=0;i<cboStatus.firstChild.options.length;i++) {

         if (Trim(cboStatus.firstChild.options[i].value) == Trim(p_manVerifiedLookupCd)) {

           cboStatus.firstChild.selectedIndex = i;
           
         }
        
       }
            
     }
     
   }
    
  }
  
}


/*******************************************************************************************
 * Name:         CausesValidationSkipManadatory
 * Description:  Performs client side validation same as CausesValidation=True but skips mandatory validations.
 *******************************************************************************************/
function CausesValidationSkipManadatory() {

  Page_IsValid = true;
  
  if (typeof(Page_ClientValidate) == 'function') {
    var i;
    for (i = 0; i < Page_Validators.length; i++) {
    
      if (Page_Validators[i].id.indexOf('vrf') >= 0) {
        //do nothing
        Page_Validators[i].isvalid = true;
      }
      else {
        ValidatorValidate(Page_Validators[i]);
      }
    }
    
    ValidatorUpdateIsValid();    
    ValidationSummaryOnSubmit();
    Page_BlockSubmit = !Page_IsValid;
    return Page_IsValid;
  }
}


/*******************************************************************************************
 * Name:         CausesValidationSkipValidators
 * Description:  Performs client side validation same as CausesValidation=True but skips some validatiors specified in list of validators.
*               p_validatorIds - Array of validators
 *******************************************************************************************/
function CausesValidationSkipValidators(p_validatorIds) {

  Page_IsValid = true;
  
  if (typeof(Page_ClientValidate) == 'function') {
    var i;
    var j;
    var inSkipList;
    
    for (i = 0; i < Page_Validators.length; i++) {
    
      inSkipList = false;
      
      //check whether validator is in skip list
      for (j = 0; j < p_validatorIds.length; j++) {
      
        //if in skip list do nothing
        if (Page_Validators[i].id.indexOf(p_validatorIds[j]) >= 0) {
          inSkipList = true;
          break;
        }
      }
      
      if (inSkipList) {
        //do nothing
        Page_Validators[i].isvalid = true;
      }
      else {
        ValidatorValidate(Page_Validators[i]);
      }
      
    }
    
    ValidatorUpdateIsValid();    
    ValidationSummaryOnSubmit();
    Page_BlockSubmit = !Page_IsValid;
    return Page_IsValid;
  }
}

function BulkUserCausesValidation() {

  var validatorList = new Array();
  
  validatorList[0] = 'vrf'; //for all required field validators
  validatorList[1] = 'vcu'; //for all custom field validators
  validatorList[2] = 'rfv'; //for all required field validators in popup controls
  
  return CausesValidationSkipValidators(validatorList);

}

/*******************************************************************************************
 * Name:         OneRecordMustBeSelected
 * Description:  Function used to validate that at least one record must be selected
 *               in IE using a custom validator.
 *******************************************************************************************/
function OneRecordMustBeSelected(source, args) {
  args.isValid = true;
  
  if (document.getElementById) {
    if (!IsRecordSelected(source.title)) {
      args.IsValid = false;
    }
  }   
  return args.IsValid;
}


/*******************************************************************************************
 * Name:         OnlyOneRecordMustBeSelected
 * Description:  Function used to validate that more than one records are selected
 *               in IE using a custom validator.
 *******************************************************************************************/
function OnlyOneRecordMustBeSelected(source, args) {
  args.isValid = true;
  
  if (document.getElementById) {
    if (IsRecordSelected(source.title) && IsMoreThanOneRecordSelected(source.title)) {
      args.IsValid = false;
    }
  }   
  return args.IsValid;
}

/*******************************************************************************************
 * Name:         ApplyBodyStyle
 * Description:  Applys the style to the body of page.
 * Parameters:   p_styleName - name of the css style.
  *******************************************************************************************/
function ApplyBodyStyle(p_styleName){
   // DOM check.
  if (document.getElementById) {
    document.body.className = p_styleName;
  }
}

/*******************************************************************************************
 * Name:         ApplyStyle
 * Description:  Applys the style to the element passed in.
 * Parameters:   p_styleName - name of the css style.
 *               p_elementId - target element id in calling page.
 *******************************************************************************************/
function ApplyStyle(p_styleName, p_elementId){
   // DOM check.
  if (document.getElementById) {
    if(document.getElementById(p_elementId)){
      document.getElementById(p_elementId).className = p_styleName;
    }
  }
}

/*******************************************************************************************
 * Name:         DoPostBack
 * Description:  Post back function with dirty check and processing falg...
 * Parameters:   p_fieldId - name of the control.
 *******************************************************************************************/
function DoPostBack(p_fieldId) {
  
  // DOM check.
  if (document.getElementById) {
  
    if (m_pageIsDirty){
      if(confirm(m_dirtyMessage)){
        AddProcessingFlag();
        __doPostBack(p_fieldId,''); 
      }
      else {
        return false;
      }
    }
    else {
    
      AddProcessingFlag();
      __doPostBack(p_fieldId,''); 
    }   
  }
}

/*******************************************************************************************
 * Name:         ToolsetOnChange
 * Description:  disable or enables the access permission field based on the toolset selected.
 * Parameters:   toolsetId - name of the toolset control.
 *               accessPermissionId - name of the access permissions control.
 *******************************************************************************************/
function ToolsetOnChange(toolsetId, accessPermissionId){

  // DOM check.
  if (document.getElementById) {
  
      if ((document.getElementById(toolsetId))&&(document.getElementById(accessPermissionId))){
      
        var toolsetControl = document.getElementById(toolsetId);
        var toolset = toolsetControl.options[toolsetControl.selectedIndex].value
        var accessPermissions = document.getElementById(accessPermissionId)
        
        if (toolset == 'INDV'){
          accessPermissions.disabled = false;
        }else{
          accessPermissions.disabled = true;
          ClearMultiSelect(accessPermissionId);
        }
      
      }
  
  }

}


/*******************************************************************************************
 * Name:         PasswordValidCharacters
 * Description:  Function used to validate that the field passed in doesnot contain one of the 
 *               banned characters.
 * Parameters:   source - details of the field to validate.
 *               args   - returns FALSE if value contains invalid characters 
 *                        otherwise returns TRUE. 
 * Note: the value of the parameter 'source' contains 2 values:
 *            1. Name of password field to validate
 *            2. List of invalid characters for the field.
 *            3. No longer spilt on the standard | char now split on !
 *******************************************************************************************/
function PasswordValidCharacters(source, args) {
  
  args.IsValid = true;
  
  // DOM Check
  if (document.getElementById) {
  
    // Get the details of the field to validate.
    // Split the field to get the 2 parts 
    var sourceTitle = source.title;
    var sourceTitleArray = sourceTitle.split("!");
    
    // Get the name of the field to validate
    var txtPassword = document.getElementById(sourceTitleArray[0]);
    var password = txtPassword.value;
    
    // Get the list of invalid characters for the field.    
    var invalidChars =  sourceTitleArray[1];
    var invalidCharArray = invalidChars.split(",");

    //Loop through the array of invalid characters.
    for (var i=0;i<invalidCharArray.length;i++){
      //Check to see if the invalid character is in the string.
      if(password.indexOf(invalidCharArray[i])!= -1){         
        args.IsValid = false;
      }
        
    }
        
  }

  return args.IsValid;
  
}

/*******************************************************************************************
 * Name:         UsernameValidCharacters
 * Description:  Function used to validate that the field passed in doesnot contain one of the 
 *               banned characters.
 *******************************************************************************************/
function UsernameValidCharacters(source, args) {
  
  args.IsValid = true;
  
  // DOM Check
  if (document.getElementById) {
    
    //Get the field to validate.
    var txtUsername = document.getElementById(source.title);
    var username = txtUsername.value;
    var invalidChars = new Array(' ');
        
    //Loop through the array of invalid characters.
    for (var i=0;i<invalidChars.length;i++){
    
        //Check to see if the invalid character is in the string.
        if(username.indexOf(invalidChars[i])!= -1){         
          args.IsValid = false;
        }
        
    }
        
  }

  return args.IsValid;
  
}

/*******************************************************************************************
 * Name:         UpdateChkbox
 * Description:  Uses values in a hidden field(Id passed in) to update a checkbox(Id passed in).
 * Paramters:    p_hidId - Id of the hidden field.
 *               p_chkboxId - Id of the checkbox.
 *******************************************************************************************/
function UpdateChkbox(p_hidId, p_chkboxId){
  
  //Get a reference to the hidden field
  var hidField = document.getElementById(p_hidId);
  
  if(hidField.value.length > 0){
  
    //Get the values from the hidden field.
    var values = hidField.value.split('|');
    
    //Get a reference to the checkbox.
    var chkbox = document.getElementById(p_chkboxId);
    
    //Check for both values.
    if (values.length == 2){
      
      //If the first Value is Y, tick the checkbox.
      if (values[0] == 'Y'){
        chkbox.checked = true;
      }else{
        chkbox.checked = false;
      }
      
      //If the second value is D, disable the checkbox.
      if (values[1] == 'D'){
        chkbox.disabled = true;
      }else{
        chkbox.disabled = false;
      }
    }
    
  }
 
  return false;
}

/*******************************************************************************************
 * Name:         SuperLPLACheckboxToggleHiddenField
 * Description:  Uses values in a checkbox(Id passed in) to update a hidden field(Id passed in).
 * Paramters:    p_hidId - Id of the hidden field.
 *               p_chkboxId - Id of the checkbox.
 *******************************************************************************************/
function SuperLPLACheckboxToggleHiddenField(p_hidId, p_chkboxId){

  //Get a reference to the hidden field
  var hidField = document.getElementById(p_hidId);

  //Get a reference to the checkbox.
  var chkbox = document.getElementById(p_chkboxId);
  
  //Get the values from the hidden field.
  var values = hidField.value.split('|');
  
  //Check for existing values.
  if (values.length = 2){
  
    if(chkbox.checked){
      values[0] = 'Y';
    }else{
      values[0] = 'N';
    }
    
    //Put new value in the hidden field.
    hidField.value = values[0] + '|' + values[1];
    
  }else{
  
    //there are no values, restore it to default.
    if(chkbox.checked){
      hidField.value = 'Y|E';
    }else{
      hidField.value = 'Y|D';
    }
    
  }
  return false;
}

/*******************************************************************************************
 * Name:         ToggleRole
 * Description:  Uses values in a checkbox(Id passed in) to update a hidden field(Id passed in).
 * Paramters:    p_cboTolePermissionStatusId - Id of the Tool Status dropdown.
 *               p_cboRoleId - Id of the Role dropdown
 *******************************************************************************************/
function ToggleRole(p_cboTolePermissionStatusId, p_cboRoleId, p_btnSubmitId){
 
   // DOM Check
  if (document.getElementById) {
    
    //Grab handles to the dropdown lists
    var cboStatus = document.getElementById(p_cboTolePermissionStatusId);
    var cboRole = document.getElementById(p_cboRoleId);
    var btnSubmit = document.getElementById(p_btnSubmitId);
    
    //If the tool status is A
    if(cboStatus.options[cboStatus.selectedIndex].value == 'A'){
      //And there is more than one role
      if(cboRole.options.length > 1){
        //unlock the role dropdown.
        cboRole.disabled = false; 
        btnSubmit.disabled = false;
      }
    }else{
      //Lock the role dropdown
      cboRole.disabled = true; 
    }
    
  } 
}