

var m_validMonth = new Array("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec");

var m_longMonth = new Array("JANUARY", "FEBRUARY", "MARCH", "APRIL", "MAY", "JUNE", "JULY", "AUGUST", "SEPTEMBER", "OCTOBER", "NOVEMBER", "DECEMBER");

var m_validDays = new Array(31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);

var m_elements = new Array();

var m_doCheckPageIsDirty = false;
var m_pageIsDirty = false;
var m_disableControls = false;
var m_dirtyMessage = "WARNING: Data in the form has been modified.\n\n" +
                     "Press OK - Proceed and abort changes made.\n" +
                     "Press Cancel - Retain the changes and return to the form.";
var m_smartSearchKeys = "";

var m_defaultButtonId = "";


function LTrim(p_value) {
  if (p_value == null) {
    return "";
  }
  return p_value.replace(/[ ]*/, "");
}

function RTrim(p_value) {
  if (p_value == null) {
    return "";
  }
  return p_value.replace(/[ ]*$/, "");
}

function Trim(p_value) {
  if (p_value == null) {
    return "";
  }
  return p_value.replace(/(^\s+)|(\s+$)/g,"");
}


function ValidateDate(source, args) {
  var myDateID = document.getElementById(source.controltovalidate);
  args.IsValid = true;
  if (!ConvertDate(myDateID)) {
    args.IsValid = false;
  }
  return args.IsValid;
}

function ValidateTime(source, args) {
  var myTimeID = document.getElementById(source.controltovalidate);
  args.IsValid = true;
  if (!ConvertTime(myTimeID)) {
    args.IsValid = false;
  }
  return args.IsValid;
}

function CheckSQLReservedChars(source, args) {
  var myString = document.getElementById(source.controltovalidate);
  args.IsValid = true;

  if (myString.value == "") {
    return true;
  }

  var re = new RegExp("^[\ -\~\n\r]+$", "i");
  args.IsValid = re.test(myString.value);

  if (args.IsValid) {
    var invalidArray = new Array(";", "--", "\/*", "*\/", "#", "%23", "%27");
    var invalidFound = false;

    for (var i = 0; i < invalidArray.length; i++) {
      if (myString.value.indexOf(invalidArray[i]) >= 0) {
        invalidFound = true;
        break;
      }
    }

    if (invalidFound) {
      args.IsValid = false;
    }
  }
  return args.IsValid;
}

function ConfirmDelete(p_ctl, p_associatedRecordsExist) {
  var message = ""

  if (p_associatedRecordsExist) {
    message = "WARNING: This will delete all associated records as well as this record."
  }

  var okMessage = "Delete record(s)";

  var identifier = ""

  if (p_ctl.alt) {
    identifier = p_ctl.alt;
  }

  if ((p_ctl.title) && (identifier == "")) {
    identifier = p_ctl.title;
  }

  if (identifier != "") {
    okMessage = okMessage + ":\n  " + identifier;
  } else {
    okMessage = okMessage + ".";
  }
  return ConfirmAction(message, okMessage, 'Abort the delete.');
}

function ConfirmDeleteSelectedRecords(p_ctl, p_associatedRecordsExist, p_group) {

  if (document.getElementById) {
    var message = ""
    var inputs = document.getElementById(p_group).getElementsByTagName('input');
    var recordsToDelete = false;

    for (var i = 0; i < inputs.length; i++) {
      if (inputs[i].getAttribute('type') == 'checkbox') {
        if (inputs[i].checked == true) {
          recordsToDelete = true;
        }
      }
    }

    if (!recordsToDelete) {
      alert("There are no records selected for deletion.");
      return false;
    }
    else {
      message = 'Delete records.';
      if (p_associatedRecordsExist) {
        message = "WARNING: This will delete all associated records as well as this record.\n\n"
      }
      return ConfirmAction(message, 'Delete the selected record(s).', 'Abort the delete.');
      return Confirm(message);
    }
  }
}

function Confirm(p_message) {
  if (!confirm(p_message)) {
    return false;
  }
  return true;
}

function ConfirmAction(p_informationText, p_okText, p_cancelText) {
  return confirm(p_informationText + "\r\n\nPress OK - " + p_okText + "\r\nPress Cancel - " + p_cancelText);
}

function DisablePaste(p_fieldLabel) {
  var message = p_fieldLabel + ": Paste action is not allowed.";
  alert(message);
  return false;
}


function MultipleFieldsRequireOne(source, args) {
  args.isValid = true;
  if (!MultipleRequiresOne(source.title)) {
    args.IsValid = false;
  }
  return args.IsValid;
}

function MultipleRequiresOne(p_fields) {
  var isValid = false;
  var fields = p_fields.split(",");
  var i = 0;
  while (fields[i] && !isValid) {
    if (document.getElementById(fields[i])) {
      var field = document.getElementById(fields[i]);

      if (field.tagName.toLowerCase() == 'select') {
        if (field.options[field.selectedIndex].value != "") {
          isValid = true;
        }
      }
      else {
        if (field.type == 'checkbox') {
          if (field.checked) {
            isValid = true;
          }
        }

        if (field.type == 'text') {
          if (field.value != "") {
            isValid = true;
          }
        }
      }
    }
    i++;
  }
  return isValid;
}

function MultipleFieldsSelectOne(source, args) {
  args.isValid = true;
  if (!MultipleSelectOne(source.title)) {
    args.IsValid = false;
  }
  return args.IsValid;
}

function MultipleSelectOne(p_fields) {
  var isValid = true;
  var fields = p_fields.split(",");
  var i = 0;
  var selectedCount = 0;
  while (fields[i] && isValid) {
    if (document.getElementById(fields[i])) {
      var field = document.getElementById(fields[i]);

      if (field.tagName.toLowerCase() == 'select') {
        if (field.options[field.selectedIndex].value != "") {
          selectedCount++;
        }
      }
      else {
        if (field.type == 'checkbox') {
          if (field.checked) {
            selectedCount++;
          }
        }

        if (field.type == 'text') {
          if (field.value != "") {
            selectedCount++;
          }
        }
      }
    }
    isValid = (selectedCount > 0);
    i++;
  }
  return isValid;
}

 function CheckDateRangeCustom(source, args) {
  args.isValid = true;

  if (document.getElementById) {
    var firstDate = document.getElementById(source.controltovalidate).value;
    var secondDate = document.getElementById(source.title).value;

    if (!CheckDateRange(firstDate, secondDate, 'LTE')) {
      args.IsValid = false;
    }
  }
  return args.IsValid;
}

function CheckNumberRangeCustom(source, args) {
  args.isValid = true;
  if (document.getElementById) {
    var firstNumber = document.getElementById(source.controltovalidate).value;
    var secondNumber = document.getElementById(source.title).value;

    if (!CheckNumberRange(firstNumber, secondNumber, 'LTE')) {
      args.IsValid = false;
    }
  }
  return args.IsValid;
}

function CheckCurrencyRangeCustom(source, args) {
  args.isValid = true;
  if (document.getElementById) {
    var firstNumber = document.getElementById(source.controltovalidate).value.replace(/\$|\,|\s/g,'');
    var secondNumber = document.getElementById(source.title).value.replace(/\$|\,|\s/g,'');
    if (!CheckNumberRange(firstNumber, secondNumber, 'LTE')) {
      args.IsValid = false;
    }
  }
  return args.IsValid;
}

function CheckDateRange(p_firstDate, p_secondDate, p_comparison) {
  return CheckNumberRange(GetISODate(p_firstDate), GetISODate(p_secondDate), p_comparison);
}

function CheckNumberRange(p_firstNumber, p_secondNumber, p_comparison) {
  var returnValue = true;
  if (p_firstNumber == "" || p_secondNumber == "") {
    return returnValue;
  }

  if (isNaN(p_firstNumber) || isNaN(p_secondNumber)) {
    return returnValue;
  }

  if (p_comparison == "EQ") {
    returnValue = (p_firstNumber == p_secondNumber);
  }
  if (p_comparison == "LT") {
    returnValue = (p_firstNumber < p_secondNumber);
  }
  if (p_comparison == "LTE") {
    returnValue = (p_firstNumber <= p_secondNumber);
  }
  if (p_comparison == "GT") {
    returnValue = (p_firstNumber > p_secondNumber);
  }
  if (p_comparison == "GTE") {
    returnValue = (p_firstNumber >= p_secondNumber);
  }
  return returnValue;
}

function SelectDeselectAll(p_group, p_checked) {
  var inputs = document.getElementById(p_group).getElementsByTagName('input');
  for (var i = 0; i < inputs.length; i++) {
    if (inputs[i].getAttribute('type') == 'checkbox') {
      inputs[i].checked = p_checked;
    }
  }
}

function ClearValidators() {
  if (typeof(Page_Validators) != "undefined") {
    if (document.getElementById) {
      document.getElementById("vldSummary").style.display = "none";
    }
  }
}

function ClearBusinessRules() {
  if (document.getElementById("status")) {
    document.getElementById("status").style.display = "none";
  }
  return true;
}

function AddProcessingFlag() {
  if (document.getElementById("vldSummary").style.display == "none") {
    document.getElementById("vldSummary").style.display = "block";
    document.getElementById("vldSummary").className = "processing";
    document.getElementById("vldSummary").innerHTML = "Processing...";
  }
  return true;
}

function AddToOnMouseOut(p_element, p_functionCode, p_addAfter) {
  p_element.onmouseout = new Function(AddToFunction(p_element.onmouseout, p_functionCode, p_addAfter));
  return true;
}

function AddToOnClick(p_element, p_functionCode, p_addAfter) {
  p_element.onclick = new Function(AddToFunction(p_element.onclick, p_functionCode, p_addAfter));
  return true;
}

function AddToOnSubmit(p_element, p_functionCode, p_addAfter) {
  p_element.onsubmit = new Function(AddToFunction(p_element.onsubmit, p_functionCode, p_addAfter));
  return true;
}

function AddToOnChange(p_element, p_functionCode, p_addAfter) {
  p_element.onchange = new Function(AddToFunction(p_element.onchange, p_functionCode, p_addAfter));
  return true;
}

function AddToOnReset(p_element, p_functionCode, p_addAfter) {
  p_element.onreset = new Function(AddToFunction(p_element.onreset, p_functionCode, p_addAfter));
  return true;
}

function AddToOnKeyup(p_element, p_functionCode, p_addAfter) {
  p_element.onkeyup = new Function(AddToFunction(p_element.onkeyup, p_functionCode, p_addAfter));
  return true;
}

function AddToOnKeydown(p_element, p_functionCode, p_addAfter) {
  p_element.onkeydown = new Function(AddToFunction(p_element.onkeydown, p_functionCode, p_addAfter));
  return true;
}

function AddToFunction(p_oldFunctionCode, p_newFunctionCode, p_addAfter) {
  var updatedFunction = "";
  var semiColon = "";
  if (p_oldFunctionCode) {
    var pos = p_oldFunctionCode.toString().indexOf("{");
    updatedFunction = p_oldFunctionCode.toString().substr(0, p_oldFunctionCode.toString().lastIndexOf("}") - 1);
    updatedFunction = RTrim(updatedFunction.substr(pos + 1));

    if (p_addAfter) {
      if (updatedFunction.substr(updatedFunction.length, 1) != ";") {
        semiColon = ";";
      }
      updatedFunction = updatedFunction + semiColon + " " + p_newFunctionCode;
    } else {
      if (p_newFunctionCode.substr(p_newFunctionCode.length, 1) != ";") {
        semiColon = ";";
      }
      updatedFunction = p_newFunctionCode + " " + updatedFunction;
    }
  } else {
    updatedFunction = p_newFunctionCode;
  }
  return updatedFunction;
}

function OpenWindow(p_url, p_name, p_width, p_height, p_left, p_top, p_options, p_modal, p_title) {
  var url = p_url;
  if (!url) {
    url = GetSystemPath() + "/framework/help/processing.htm"
  }
  if (p_modal && window.showModalDialog) {
    if (IsBrowserIE7()){
      p_height=p_height-25;
      if(p_width < 250)p_width=250;
    }
    OpenModalWindow(url, p_name, p_width, p_height, p_left, p_top, p_options, p_title);
  } else {
    if(IsBrowserNetscape()){
      p_height=p_height+20;
    }
    var p = window.open(url, p_name, 'width=' + p_width + ',height=' + p_height + ',' + p_options);
    if (!p.opener) p.opener = window;

    if (url.substring(0, 7).toLowerCase() != "http://") {
      p.resizeTo(p_width, p_height);
      if (p_left && p_top && screen) {
        if (p_left < 0) p_left += screen.availWidth - p_width;
        if (p_top < 0) p_top += screen.availHeight - p_height;
        p.moveTo(p_left, p_top);
      }
    }
    p.focus();
  }
}

function CloseWindow() {
  self.close();
  return true;
}

function OpenModalWindow(p_url, p_name, p_width, p_height, p_left, p_top, p_options, p_title) {
  var options = 'dialogHeight=' + p_height + 'px;dialogWidth=' + p_width + 'px;help=no;status=no;' + p_options;
  var topPos = p_top;
  var leftPos = p_left;
  if (!topPos) topPos = 0;
  if (!leftPos) leftPos = 0;

  if (topPos == 0 && leftPos == 0) {
    options = 'center=yes;' + options;
  } else {
    options = 'dialogleft=' + leftPos + 'px;dialogTop=' + topPos + 'px;' + options;
  }

  options = options.replace(/scrollbars/gi, 'scroll');

  options = options.replace(/,/g, ';');


  p_url = AppendUrlParameter(p_url, 'Title', p_title);
  p_url = AppendUrlParameter(p_url, 'Modal', 'true');

  var returnValue = window.showModalDialog(p_url, p_name, options);

  if (returnValue != null) {
    var i;
    var paramItem;
    var fieldElement;
    for (i = 0; i < returnValue.length; i++) {
      paramItem = returnValue[i].split('|');
      if (document.getElementById(paramItem[0])) {
        var fieldElement = document.getElementById(paramItem[0]);
        fieldElement.setAttribute(paramItem[2], paramItem[1]);
        if (paramItem[2] != 'innerHTML') {
          RunOnChange(fieldElement);
        }
      }
    }
  }
}

function OpenCalendar(p_formId, p_fieldId, p_startYear, p_endYear) {
  var myDateID = document.forms[p_formId].elements[p_fieldId];
  var myDateValue = myDateID.value.replace(/\s/g, '');
  var calUrl = GetSystemPath() + "/framework/_common/PopupCalendar.aspx?FormId=" + p_formId + "&FieldId=" + p_fieldId + "&DisplayDate=" + myDateValue + "&YearStart=" + p_startYear + "&YearEnd=" + p_endYear;
  var popupWidth = 190;
  var popupHeight = 210;
  var topPos = null;
  var leftPos = null;
  var options = "resizable=yes,scrollbars=no,status=no";
  var modal = true;
  var title = 'Pick a date';
  OpenWindow(calUrl, "PopupCalendar", popupWidth, popupHeight, leftPos, topPos, options, modal, title);
}

function OpenHelp(p_url) {
  var popupWidth = 480;
  var popupHeight = 600;
  var topPos = 1;
  var leftPos = 1;
  var options = "resizable=yes,scrollbars=yes";
  var modal = false;
  var title = null;
  OpenWindow(p_url, "PopupHelp", popupWidth, popupHeight, leftPos, topPos, options, modal, title);
}

function OpenAbout(p_title) {
  var aboutUrl = GetSystemPath() + "/framework/_common/PopupAbout.aspx";
  var popupWidth = 560;
  var popupHeight = 370;
  var topPos = null;
  var leftPos = null;
  var options = "resizable=yes,scrollbars=no";
  var modal = true;
  var title = p_title;
  OpenWindow(aboutUrl, "PopupAbout", popupWidth, popupHeight, leftPos, topPos, options, modal, title);
}

function OpenLookup(p_url, p_title) {
  var popupWidth = 520;
  var popupHeight = 550;
  var topPos = null;
  var leftPos = null;
  var options = "resizable=yes,scrollbars=yes";
  var modal = true;
  var title = p_title;
  OpenWindow(p_url, "PopupLookup", popupWidth, popupHeight, leftPos, topPos, options, modal, title);
}

function OpenCentre(p_url, p_title) {
  var popupWidth = 660;
  var popupHeight = 610;
  var topPos = null;
  var leftPos = null;
  var options = "resizable=yes,scrollbars=yes";
  var modal = true;
  var title = p_title;
  OpenWindow(p_url, "PopupCentre", popupWidth, popupHeight, leftPos, topPos, options, modal, title);
}

function PassBack(p_formId, p_fieldId, p_value, p_modal) {
  if (p_modal && window.showModalDialog) {
    var returnList = new Array(0);
    returnList = AddModalReturnValue(returnList, p_fieldId, p_value);
    window.returnValue = returnList;
  } else if (window.opener != null) {
    var myField = window.opener.document.forms[p_formId].elements[p_fieldId];
    myField.value = p_value;
    RunOnChange(myField);
  }

  window.close();
}

function PassBackWithDescription(p_codeFieldId, p_descFieldId, p_lookupCd, p_lookupDesc, p_modal) {
  if (p_modal && window.showModalDialog) {
    var returnList = new Array(0);
    returnList = AddModalReturnValue(returnList, p_codeFieldId, p_lookupCd);
    returnList = AddModalReturnValue(returnList, p_descFieldId, p_lookupDesc, 'innerHTML');
    window.returnValue = returnList;
  } else if (window.opener != null && document.getElementById) {
    window.opener.document.getElementById(p_codeFieldId).value = p_lookupCd;
    RunOnChange(window.opener.document.getElementById(p_codeFieldId));
    if (window.opener.document.getElementById(p_descFieldId)) {
      window.opener.document.getElementById(p_descFieldId).innerHTML = p_lookupDesc;
    }
  }
  window.close();
}

function AddModalReturnValue(p_listArray, p_field, p_value, p_property) {
  var listArray = p_listArray;
  if (p_field == null && p_value == null)
    return listArray;

  if (p_property == null)
    p_property = 'value';

  var data = p_field + '|' + p_value + '|' + p_property;
  listArray[listArray.length] = data;

  return listArray;
}

function RunOnChange(p_field) {
  if (p_field.onchange) {
    if (p_field.onchange.toString().toLowerCase().indexOf('validatoronchange') > -1) {
      if (p_field.fireEvent) {
        p_field.fireEvent("onchange");
      }
    } else {
      p_field.onchange();
    }
  }
}

function ResetLookupDescription(p_descFieldId) {
  if (document.getElementById) {
    var desc = document.getElementById(p_descFieldId);
    desc.innerHTML = "";
    if (desc.oldvalue) {
      desc.innerHTML = desc.oldvalue;
    }
  }
  return true;
}

function NoContextMenu() {
  event.cancelBubble = true, event.returnValue = false;
  return false;
}

function NoRightClick(e) {
  if (window.Event) {
    if (e.which == 2 || e.which == 3) return false;
  }
  else if (event.button == 2 || event.button == 3) {
    event.cancelBubble = true, event.returnValue = false;
    return false;
  }
}

function SuppressRightClick() {

  if (window.Event)
    document.captureEvents(Event.MOUSEUP);

  if (document.layers)
    document.captureEvents(Event.MOUSEDOWN);

  document.oncontextmenu = NoContextMenu;
  document.onmousedown = NoRightClick;
  document.onmouseup = NoRightClick;

}

function Close_OnClick() {
  close();
}

function CloseKeyPress() {
  var key = event.keyCode;
  if (key == 27) close();
}

function GetSystemPath() {
  var systemPath = top.location.pathname.substring(0, top.location.pathname.indexOf("/", 1));
  if (systemPath.indexOf("/", 0) != 0)
    systemPath = '/' + systemPath;
  return systemPath;

}

function ConvertTime(p_field) {
  if (p_field.value == "") {
    return true;
  }
  var splitChar = ":";
  var timeValue = p_field.value;
  if (isNaN(timeValue) || timeValue.indexOf(".") >= 0 || timeValue.indexOf(",") >= 0) {
    timeValue = timeValue.replace(/\s/g, splitChar);
    timeValue = timeValue.replace(/,/g, splitChar);
    timeValue = timeValue.replace(/-/g, splitChar);
    timeValue = timeValue.replace(/\./g, splitChar);

    var colonPos = timeValue.indexOf(splitChar);
    if (colonPos == -1 || timeValue.indexOf(splitChar, colonPos + 1) >= 0) {
     return false;
    }

  } else {

    if ((timeValue.length) < 3 || (timeValue.length) > 4) {
      return false;
    }

    var endPos = 2;
    if (timeValue.length == 3) {
     var endPos = 1;
    }
    timeValue = timeValue.substring(0, endPos) + splitChar + timeValue.substring(endPos);
  }
  var splitTime = timeValue.split(splitChar);
  var hh = splitTime[0];
  var mi = splitTime[1];

  if (isNaN(hh) || isNaN(mi)) {
    return false;
  } else {
    if (hh < 0 || hh > 23) {
      return false;
    }

    if (mi.length != 2) {
      return false;
    }

    if (mi < 0 || mi > 59) {
      return false;
    }

    if (hh.length == 1) {
      hh = "0" + hh;
    }

  }
  p_field.value = hh + splitChar + mi;

  return true;
}

function ConvertDate(p_field) {
  var dd;
  var mm;
  var yy;
  var yyyy;
  var mon = "";
  var currentDate = new Date();

  if (p_field.value == "") {
    return true;
  }

  if (isNaN(p_field.value)) {
    var splitChar = "-";
    var dateValue = p_field.value
    dateValue = dateValue.replace(/\s/g, splitChar);
    dateValue = dateValue.replace(/,/g, splitChar);
    dateValue = dateValue.replace(/\./g, splitChar);
    dateValue = dateValue.replace(/\\/g, splitChar);
    dateValue = dateValue.replace(/\//g, splitChar);

    if (dateValue.indexOf(splitChar) == -1) {
      return false;
    }

    var splitDate = dateValue.split(splitChar);
    dd = splitDate[0];
    mm = splitDate[1];
    yy = splitDate[2];

    if (dd == "") {
      dd = currentDate.getDate();
    }

    if (mm == "") {
      mm = currentDate.getMonth() + 1;
    }

    if (yy == "") {
      yy = currentDate.getFullYear().toString().substr(2, 2);
    }

  } else {

    if (p_field.value.indexOf('.') >= 0) {
      return false;
    }

    if (p_field.value.length != 6 && p_field.value.length != 8) {
      return false;
    } else {
      dd = p_field.value.substr(0, 2);
      mm = p_field.value.substr(2, 2);
      yy = p_field.value.substr(4, 4);
    }
  }

  if (isNaN(dd)) {
    return false;
  } else if (dd < 1 || dd > 31) {
    return false;
  }

  if (isNaN(yy)) {
    return false;
  } else if (yy.length != 4 && yy.length != 2) {
    return false;
  } else {

    if (yy.length == 4) {
      yyyy = yy;
    } else {
      var currentCentury = currentDate.getFullYear().toString().substr(0, 2);
      var currentYear = parseInt(currentDate.getFullYear().toString().substr(2, 2));

      if (yy > (20 + currentYear)) {
        yyyy = currentCentury - 1 + yy;
      } else {
        yyyy = currentCentury + yy;
      }
    }
  }

  if (isNaN(mm)) {

    var i = 0;
    var valid = false;

    while (m_validMonth[i] && !valid) {
      if (m_validMonth[i].toUpperCase() == mm.toUpperCase() ||
        m_longMonth[i] == mm.toUpperCase()) {
        valid = true;
        mon = m_validMonth[i];
        mm = i;
      }
      i++;
    }
    if (!valid) {
      return false;
    }

  } else {
    if (mm > 0 && mm < 13) {
      mm = mm - 1;
      mon = m_validMonth[mm];
    } else {
      return false;
    }
  }

  var add_days = 0;
  if (mm == 1 && (yyyy%4) == 0) {

    if (yyyy.substr(2, 2) == "00" && (yyyy%400) != 0) {
      add_days = 0;
    } else {
      add_days = 1;
    }
  }

  if (dd > (m_validDays[mm] + add_days)) {
    return false;
  }

  if (dd.length == 1) {
    dd = "0" + dd;
  }

  p_field.value = dd + "-" + mon + "-" + yyyy;

  return true;
}

function GetISODate(p_date) {
  if (p_date == "" || p_date.indexOf("-") < 0) return "";

  var splitDate = p_date.split("-");

  var found = false;
  var mm;
  var i = 0;
  while (m_validMonth[i] && !found) {
    if (splitDate[1].toLowerCase() == m_validMonth[i].toLowerCase()) {
      mm = i + 1;
      found = true;
    }
    i++;
  }
  if (mm < 10) {
    mm = "0" + mm;
  }

  return splitDate[2] + mm + splitDate[0];
}

function AppendUrlParameter(p_url, p_paramName, p_paramValue) {
  var returnValue = p_url;

  if (p_paramValue) {
    if (p_url.indexOf('?') > 0)
      returnValue += '&' + p_paramName + '=' + p_paramValue
    else
      returnValue += '?' + p_paramName + '=' + p_paramValue
  }
  return returnValue;
}

function RemoveParameter(p_url, p_parameter) {
  var returnValue = p_url;
  var pos
  pos = p_url.indexOf('?' + p_parameter + '=');
  if (pos < 0) {
   pos = p_url.indexOf('&' + p_parameter + '=');
  }
  if (pos < 0) {
    return returnValue;
  }
  var moreParams = p_url.indexOf('&', pos + 1);
  if (moreParams < 0) {
    returnValue = p_url.substring(0, pos);
  } else {
    returnValue = p_url.substring(0, pos + 1) + p_url.substring(moreParams + 1);
  }
  return returnValue;
}

function GetProtocol(p_url) {
  var protocol = "";
  if (p_url.indexOf(':') < p_url.indexOf('/')) {
    protocol = p_url.substring(0, p_url.indexOf(':'));
  }
  return protocol.toLowerCase();
}

function GetServer(p_url) {
  var url = p_url + "/";
  var server = "";
  var protocolLength = GetProtocol(url).length + 3;
  if (protocolLength > 3) {
    server = url.substring((protocolLength), url.indexOf('/', protocolLength + 1));
  }
  return server.toLowerCase();
}


function GetApplicationPath(p_url) {
  var applicationPath = p_url + "/";

  var protocolLength = GetProtocol(applicationPath).length + 3;
  if (protocolLength > 3) {
    applicationPath = applicationPath.substring(applicationPath.indexOf('/', protocolLength + 1));
  }

  if (applicationPath.substring(0, 1) == "/") {
    applicationPath = applicationPath.substring(0, applicationPath.indexOf('/', 1));
  } else {
    applicationPath = "";
  }
  return applicationPath.toLowerCase();
}

function FormatNumber(p_value, p_decimalPlaces, p_padWithZeros) {
  var returnValue = p_value;

  var numberValue = p_value.replace(/\$|\,|\s/g,'');

  if ((numberValue != "") && !(isNaN(numberValue))) {
    var absNumber = Math.abs(numberValue);
    var wholeStr = absNumber.toString();
    var decimalStr = ".";
    var pos = absNumber.toString().indexOf('.');
    if (pos > -1) {
      wholeStr = absNumber.toString().substring(0, pos);
      decimalStr = absNumber.toString().substring(pos);
    }

    if (!(isNaN(p_decimalPlaces))) {
      if (decimalStr.length > (p_decimalPlaces + 1)) {
        decimalStr = decimalStr.substring(0, p_decimalPlaces + 1);
      }
      if (p_padWithZeros) {
        while (decimalStr.length < (p_decimalPlaces + 1)) {
          decimalStr += "0";
        }
      }
    }

    for (var i = 0; i < Math.floor((wholeStr.length - (1 + i))/3); i++) {
      wholeStr = wholeStr.substring(0, wholeStr.length - (4 * i + 3)) + ',' + wholeStr.substring(wholeStr.length - ( 4 * i + 3));
    }

    returnValue = wholeStr + decimalStr;
    if (numberValue < 0) {
      returnValue = "-" + returnValue;
    }
  }
  return returnValue;
}

function FormatCurrency(p_value) {
  return FormatNumber(p_value, 2, true);
}

function FormatCurrency(p_element, p_applyStyleForNegatives) {
  p_element.value = FormatNumber(p_element.value, 2, true);
  if (p_applyStyleForNegatives) {
    ApplyStyleForNegative(p_element);
  }
}

function ApplyStyleForNegative(p_element) {
  var checkValue = p_element.value.replace(/\$|\,|\s/g,'');
  p_element.style.color = "#000";
  if (!(isNaN(checkValue)) && (checkValue < 0)) {
    p_element.style.color = "#F00";
  }
}

function FormatFields(p_doCheckPageIsDirty, p_defaultButtonId) {
  m_doCheckPageIsDirty = p_doCheckPageIsDirty
  m_defaultButtonId = p_defaultButtonId;
  if (document.getElementById) {

    var inputFields = document.getElementsByTagName('input');
    var i = 0;
    while (inputFields[i]) {
      FormatField(inputFields[i]);
      if (m_doCheckPageIsDirty) {
        AddDirtyCheckToField(inputFields[i]);
      }
      i++;
    }

    var textareas = document.getElementsByTagName('textarea');
    var j = 0;
    while (textareas[j]) {
      if (navigator.userAgent.indexOf('Opera') == -1) {
        if (textareas[j].getAttribute("case")) {
          SetCase(textareas[j], textareas[j].getAttribute("case"));
        }
      }
      if (m_doCheckPageIsDirty) {
        AddDirtyCheckToField(textareas[j]);
      }
      j++;
    }

    var selectFields = document.getElementsByTagName('select');
    var m = 0;
    while (selectFields[m]) {
      if (selectFields[m].className.indexOf('multiselect') >= 0) {
        InitialiseMultiSelect(selectFields[m]);
      }
      m++;
    }

    if (m_doCheckPageIsDirty) {
      var k = 0;
      while (selectFields[k]) {
        AddDirtyCheckToField(selectFields[k]);
        k++;
      }

      var anchorFields = document.getElementsByTagName('a');
      var l = 0;
      while (anchorFields[l]) {
        CheckPageIsDirty(anchorFields[l]);
        l++;
      }
    }

    AddCharacterRemainingMessages();
  }
  return true;
}

function FormatField(p_field) {

  if (p_field.type == "text" || p_field.type == "password") {

    var defaultButtonId = "";
    if (p_field.getAttribute('defaultbutton')) {
      defaultButtonId = p_field.getAttribute('defaultbutton');
    }
    if (defaultButtonId.length > 0) {

      AddToOnKeydown(p_field, 'DefaultButtonHandler(\'' + defaultButtonId + '\', window.event);', false);
    }
    else if (m_defaultButtonId.length > 0) {
      AddToOnKeydown(p_field, 'DefaultButtonHandler(\'' + m_defaultButtonId + '\', window.event);', false);
    }
  }

  if (p_field.type == "text") {

    if (p_field.className == "currency") {
      AddToOnChange(p_field, 'FormatCurrency(this, true);', false);
      ApplyStyleForNegative(p_field);
      AddToOnReset(p_field.form, 'setTimeout(\'FormatCurrency(document.getElementById("' + p_field.id + '"), true);\', 1);', false);
    }

    if (p_field.className == "lookupdescription") {
      AddToOnReset(p_field.form, 'ResetLookupDescription(\'' + p_field.getAttribute('descfieldid') + '\');', true);
    }

    if (p_field.className == "calendar") {
      CreateLookupIcon(p_field,
                      'Pick a date',
                      'calendar.gif',
                      'OpenCalendar',
                       p_field.getAttribute('mindate') + ', ' +
                       p_field.getAttribute('maxdate'));
    }

    if (p_field.className == "lookup") {
      CreateLookupIcon(p_field,
                       p_field.getAttribute('alttext'),
                      'lookup.gif',
                       p_field.getAttribute('jsfunction'),
                       p_field.getAttribute('extraparameters'));
    }

    if (p_field.getAttribute("case")) {
      SetCase(p_field, p_field.getAttribute("case"));
    }
  }

  if (p_field.type == "submit") {
    if (p_field.getAttribute("clearbrmessages") == "true") {
      AddClearBRToButtons(new Array(p_field.getAttribute("id")));
    }
  }

}

function AddClearBRToButtons(p_buttonIds) {
  if (typeof(Page_Validators) != "undefined") {
    var i = 0;
    while (p_buttonIds[i]) {
      if (document.getElementById(p_buttonIds[i])) {
        AddToOnClick(document.getElementById(p_buttonIds[i]), "ClearBusinessRules();");
        AddToOnClick(document.getElementById(p_buttonIds[i]), "AddProcessingFlag();", true);
      }
      i++;
    }
  }
}

function CreateLookupIcon(p_field, p_altText, p_imgFile, p_jsFunction, p_extraParameters) {
  var imgElement = document.createElement('img');
  imgElement.setAttribute('alt', p_altText);
  imgElement.setAttribute('src', '/framework/_images/' + p_imgFile);
  imgElement.className = 'lookupicon';

  var functionCode = p_jsFunction + '(\'' + p_field.form.getAttribute('id') + '\', \'' + p_field.id + '\'';

  if (p_field.getAttribute('descfieldid')) {
    AddToOnReset(p_field.form, 'ResetLookupDescription(\'' + p_field.getAttribute('descfieldid') + '\');', true);
    functionCode += ', \'' + p_field.getAttribute('descfieldid') + '\'';
  }

  if (p_extraParameters) {
    functionCode += ', ' + p_extraParameters;
  }
  imgElement.onclick = new Function(functionCode + ');');

  p_field.parentNode.insertBefore(imgElement, p_field.nextSibling);

}

function Lookup_OnChange(p_descFieldId) {
  if (document.getElementById) {
    document.getElementById(p_descFieldId).innerHTML = '';
  }
}

function SetCase(p_field, p_case) {
  if (p_case == "upper") {
    AddToOnChange(p_field, "this.value = this.value.toUpperCase();", false);
  }
  else if (p_case == "lower") {
    AddToOnChange(p_field, "this.value = this.value.toLowerCase();", false);
  }
}

function AddDirtyCheckToField(p_field) {
  var fieldType = p_field.getAttribute('type');

  if (p_field.getAttribute("excludefromdirtycheck") != "true") {

    if (fieldType == "button" || fieldType == "hidden") {
      return;
    }

    if (fieldType == "submit" || fieldType == "image") {
      CheckPageIsDirty(p_field);
      return;
    }

    if (fieldType == "reset") {
      CheckPageIsDirty(p_field);
      AddToOnReset(p_field.form, 'setTimeout(\'m_pageIsDirty = false;\', 5);', false);
      return;
    }

    if (fieldType == 'checkbox' ||
       (fieldType == 'radio' && !p_field.checked)) {
      AddToOnClick(p_field, "m_pageIsDirty = true;", true);
    } else {
      AddToOnChange(p_field, "m_pageIsDirty = true;", true);
    }
  }
}

function CheckPageIsDirty(p_field) {
  var addCheck = true;
  var addAfter = false;

  if (p_field.tagName == "A") {
    addAfter = true;
  }

  if (p_field.getAttribute("nocheckisdirty") == "true") {
    addCheck = false;
  } else if (p_field.getAttribute("ignoredirtyprompt") == "true") {
    addCheck = false;
  } else {
    if (p_field.className.indexOf("nocheckisdirty") >= 0) {
      addCheck = false;
    }
    else if (p_field.className.indexOf("ignoredirtyprompt") >= 0) {
      addCheck = false;
    }
  }

  if (addCheck) {
    AddToOnClick(p_field, "if (m_doCheckPageIsDirty && m_pageIsDirty && !confirm(m_dirtyMessage)) return false;", addAfter);
  }
}

function AddCharacterRemainingMessages() {

  var divs = document.getElementsByTagName('div');
  var j = 0;

  while (divs[j]) {
    if (divs[j].className == 'textarea') {

      var p = divs[j].getElementsByTagName('p');

      var textarea = divs[j].getElementsByTagName('textarea');

      if (textarea[0] && p[0]) {

        var maxChars = textarea[0].getAttribute('maxchars');

        var strong = document.createElement('strong');
        m_elements[textarea[0].id] = strong;

        strong.innerHTML = (maxChars - textarea[0].value.length);

        var f = 'CountCharacters(this, ' + maxChars + ');'
        AddToOnKeyup(textarea[0], f, true);
        AddToOnChange(textarea[0], f, true);

        p[0].appendChild(document.createTextNode(' - '));
        p[0].appendChild(strong);
        p[0].appendChild(document.createTextNode(' characters remaining'));

        AddToOnReset(textarea[0].form, 'setTimeout(\'RunOnChange(document.getElementById("' + textarea[0].id + '"));\', 1);', false);
      }
    }
    j++;
  }
}

function CountCharacters(p_textField, p_maxLength) {
  if (document.getElementById) {

    var remaining = (p_maxLength - p_textField.value.length);
    var counter = m_elements[p_textField.id];

    if (remaining >= 0) {
      counter.replaceChild(document.createTextNode(remaining), counter.firstChild);
      counter.className = "";
    }

    if (remaining == 0) {
      counter.className = "errormessage";
    }

    if (remaining < 0) {
      p_textField.value =  p_textField.value.substring(0, p_maxLength);
    }
  }

}

function MoveItems(p_sourceListId, p_destinationListId) {
  if (document.getElementById) {
    var sourceList = document.getElementById(p_sourceListId);
    var destinationList = document.getElementById(p_destinationListId);
    var selectedItems = new Array();
    var i = 0;
    var j = 0;
    while (sourceList.options[i]) {
      if (sourceList.options[i].selected) {
        selectedItems[j] = i;
        j++;
      }
      i++;
    }
    for (var k = 0; k < selectedItems.length; k++) {
      AddItem(destinationList, sourceList.options[selectedItems[k]].text, sourceList.options[selectedItems[k]].value);
    }
    for (var k = selectedItems.length - 1; k > -1; k--) {
      RemoveItem(sourceList, selectedItems[k]);
    }
  }
}

function AddItem(p_list, p_text, p_value) {
  p_list.options[p_list.options.length] = new Option(p_text, p_value);
}

function RemoveItem(p_list, p_index) {
  p_list.options[p_index] = null;
}

function IsItemSelected(p_listId, p_listLabel, p_entity) {
  var selected = true;
  if (document.getElementById) {
    var lst = document.getElementById(p_listId);
    if (lst) {
      if (lst.selectedIndex == -1) {
        var message = p_listLabel + ": One ";
        if (lst.multiple) {
          message += "or more '" + p_entity + "' items must be selected.";
        } else {
          message += "'" + p_entity + "' item must be selected.";
        }
        alert(message);
        selected = false;
      }
    }
  }
  return selected;
}

function SetFocus(p_fieldId) {
  if (document.getElementById) {
    if (document.getElementById(p_fieldId)) {
      var field = document.getElementById(p_fieldId);

      if (field.tagName == "SPAN" || field.tagName == "TABLE") {
        var inputPos = field.innerHTML.toLowerCase().indexOf('<input');
        var selectPos = field.innerHTML.toLowerCase().indexOf('<select');

        if (inputPos == -1 && selectPos == -1) {
          if (field.tagName == "TABLE")
            field.focus();
          return;
        } else {
          var tagName = "input";
          if (inputPos == -1) {
            tagName = "select";
          } else if (selectPos > -1) {
            if (selectPos < inputPos) {
              tagName = "select";
            }
          }
        }
        var element = field.getElementsByTagName(tagName)[0];
        field = element;
      }

      if (!field.disabled) {
        field.focus();
      }
    }
  }
}


function ApplyProfiler() {

  var forms = document.getElementsByTagName('form');
  for (var i = 0; i < forms.length; i++) {
    AddToOnSubmit(forms[i], "SetProfilerStartTime(this);", true);
  }
  var links = document.getElementsByTagName('a');
  for (var i = 0; i < links.length; i++) {
    if (ValidProfilerLink(links[i].href)) {
      AddToOnClick(links[i], "SetProfilerStartTime(this);");
    }else{
      AddToOnClick(links[i], "SetPostBackProfile();");
    }
  }
  var inputs =  document.getElementsByTagName('input');
  for (var i = 0; i < inputs.length; i++) {
    AddToOnClick(inputs[i], "SetPostBackProfile();");
  }
  var selects =  document.getElementsByTagName('select');
  for (var i = 0; i < selects.length; i++) {
    AddToOnChange(selects[i], "SetPostBackProfile();");
  }
}

function SetPostBackProfile() {
  var form = 'frmProfile';
  var currentDate = new Date();
  var startTimeField = 'PostBackStartTime';
  var forms = document.getElementsByTagName('frmProfile');
  CreateCookie(startTimeField,currentDate.getTime(),1);
  return true;
}

function ValidProfilerLink(p_url) {
  if (p_url.length == 0) {
    return false;
  }

  if (p_url.substring(0, 10).toLowerCase() == "javascript") {
    return false;
  }

  var protocol = GetProtocol(p_url);
  if (protocol.length > 0) {
    if (protocol != "http") {
      return false;
    }
  }

  var linkServer = GetServer(p_url);
  if (linkServer.length > 0) {
    if (linkServer != location.host.toLowerCase()) {
      return false;
    }
  }

  if (GetApplicationPath(p_url) != GetApplicationPath(location.href)) {
    return false;
  }

  return true;
}

function SetProfilerStartTime(p_element) {
  var currentDate = new Date();
  var action;
  if (p_element.tagName == "A") {
    action = p_element.href;
  } else {
    action = p_element.action;
  }
  if ((action.indexOf('?bt=') >= 0) || (action.indexOf('&bt=') >= 0)) {
    action = RemoveParameter(action, 'bt');
  }
  if (action.indexOf('?') >= 0) {
    action = action + '&'
  } else {
    action = action + '?'
  }
  action =  action + 'bt=' + currentDate.getTime();

  if (p_element.tagName == "A") {
    p_element.href = action;
  } else {
    p_element.action = action;
  }
  return true;
}

function SaveProfiler() {
  var form = 'frmProfile';
  var startTimeField = 'BStartTime';
  var endTimeField = 'BEndTime';
  var totalTimeServerField = 'STotalTime';
  var postBackTimeField = 'PostBackStartTime';
  if (document.forms[form]) {
    var serverTotalmsec = document.forms[form].elements[totalTimeServerField].value
    var currentDate = new Date();
    var startTimeBrowser = document.forms[form].elements[startTimeField].value;
    var endTimeBrowser = currentDate.getTime();

    var postBackTime = ReadCookie(postBackTimeField);
    if(postBackTime){
      document.forms[form].elements[postBackTimeField].value = postBackTime;
      EraseCookie(postBackTimeField);
    }
    var overAllTotalmsec;
    if(postBackTime > startTimeBrowser){
      overAllTotalmsec    = endTimeBrowser - postBackTime;
    }else{
      overAllTotalmsec    = endTimeBrowser - startTimeBrowser;
    }
    var remainderTotalmsec = overAllTotalmsec - serverTotalmsec;

    document.forms[form].elements[endTimeField].value = endTimeBrowser;
    document.forms[form].submit();

    if (document.getElementById('profiledisplay')) {
      document.getElementById('profiledisplay').innerText = 'Page generated in ' + overAllTotalmsec/1000 + ' seconds (' + serverTotalmsec/1000 + ' on server/' + remainderTotalmsec/1000 + ' others)';
    }
  }
  return true;
}

function CheckSelectAll(p_group, p_selectAllCheckboxId, p_checkboxId) {

  if (document.getElementById) {
    var inputs = document.getElementById(p_group).getElementsByTagName('input');
    var chkAll = true;
    var i = 0;

    while (i < inputs.length && chkAll) {
      if (inputs[i].getAttribute('type') == 'checkbox') {
        if (inputs[i].getAttribute('id') != p_selectAllCheckboxId) {
          if (inputs[i].getAttribute('id').indexOf(p_checkboxId) >= 0) {
            chkAll = inputs[i].checked;
          }
        }
      }
      i++;
    }
  }

  document.getElementById(p_selectAllCheckboxId).checked = chkAll;

}

function IsBrowserIE() {
  return (navigator.appName == "Microsoft Internet Explorer");
}

function IsBrowserIE7(){
  var strBVersion = new String(navigator.appVersion);
  var bVersion = strBVersion.indexOf("MSIE 7");
  return (IsBrowserIE() && bVersion != -1);
}

function IsBrowserNetscape() {
  return (navigator.appName == "Netscape");
}

function IsBrowserNetscapeOrIE() {
  var userAgentValue = navigator.userAgent.toLowerCase();

  if (IsBrowserIE() || IsBrowserNetscape()) {
    if (userAgentValue.indexOf("opera") == -1) {
      return true;
    }
  }
  return false;
}


function BuildMultiSelectOptions(p_dropDownListId) {
  var listboxInput = null;
  var dropDownListInput =  null;
  var i = 0;
  var j = 1;

  if (!(IsBrowserNetscapeOrIE())) {
    return true;
  }

  if (document.getElementById) {

    dropDownListInput = document.getElementById(p_dropDownListId);

    listboxInput = document.getElementById(dropDownListInput.id.slice(0, -12));

    if (listboxInput.options[0].value == "") {
      i = 1;
    }

    for ( ; i < listboxInput.options.length; i++) {
      dropDownListInput.options[j] = new Option(listboxInput.options[i].text, listboxInput.options[i].value);
      j++;
    }
  }
}

function ActivateMultiSelect(p_dropDownListId) {
  var listboxInput = null;
  var dropDownListInput =  null;

  if (!(IsBrowserNetscapeOrIE())) {
    return true;
  }

  if (document.getElementById) {

    dropDownListInput = document.getElementById(p_dropDownListId);

    listboxInput = document.getElementById(dropDownListInput.id.slice(0, -12));

    listboxInput.style.display = "none";

    eval(p_dropDownListId + "_Active = 'true';");

    dropDownListInput.style.display = "inline";

    AddToOnReset(dropDownListInput.form, "ResetMultiSelect('" + p_dropDownListId + "');", false);
  }
}

function ResetMultiSelect(p_dropDownListId) {
  var dropDownListInput = null;
  var i = 1;

  if (!(IsBrowserNetscapeOrIE())) {
    return true;
  }

  if (document.getElementById) {
    dropDownListInput = document.getElementById(p_dropDownListId);

    for (;i<dropDownListInput.options.length;i++) {
      dropDownListInput.options[i].style.color = eval(p_dropDownListId + "_ForeColourStyle;");
      dropDownListInput.options[i].style.backgroundColor = eval(p_dropDownListId + "_BackgroundColourStyle;");
    }

    dropDownListInput.options[0].value = "";

    dropDownListInput.options[0].text = eval(p_dropDownListId + "_Prompt;");

    MultiSelectPrepopulate(p_dropDownListId, eval(p_dropDownListId + "_Original;"));

    dropDownListInput.selectedIndex = dropDownListInput.options.length - 1;
    dropDownListInput.selectedIndex = 0;
  }
}

function MultiSelectPrepopulate(p_dropDownListId, p_selectedValues) {
  var preselectedValues = "";
  var dropDownListInput =  null;

  if (!(IsBrowserNetscapeOrIE())) {
    return true;
  }

  if (p_selectedValues == "") {
    return true;
  }

  if (document.getElementById) {

    dropDownListInput = document.getElementById(p_dropDownListId);

    if (eval(p_dropDownListId + "_Active") != "true") {
      return true;
    }

    preselectedValues = p_selectedValues.split(",");

    for(var selectedValue in preselectedValues)
    {
      for (var i=0;i<dropDownListInput.options.length;i++)
      {
        if (i != 0)
        {
          if (dropDownListInput.options[i].value == preselectedValues[selectedValue])
          {
            dropDownListInput.selectedIndex = i;

            MultiSelectAddSelection(dropDownListInput);

            break;
          }
        }
      }
    }

    dropDownListInput.selectedIndex = 0;
  }
}

function MultiSelectValueSelection(p_dropDownListInput) {

  var listboxInput = null;
  var isAlreadySelected = false;

  if (!(IsBrowserNetscapeOrIE())) {
    return true;
  }

  if (document.getElementById) {

    if (eval(p_dropDownListInput.id + "_Active") != "true") {
      return true;
    }

    if (p_dropDownListInput.selectedIndex != 0){

      listboxInput = document.getElementById(p_dropDownListInput.id.slice(0,-12));

      if (listboxInput.options.length == p_dropDownListInput.options.length){
        isAlreadySelected = listboxInput.options[p_dropDownListInput.selectedIndex].selected;
      } else
      {
        isAlreadySelected = listboxInput.options[p_dropDownListInput.selectedIndex-1].selected;
      }

      if (!(isAlreadySelected))
      {
        MultiSelectAddSelection(p_dropDownListInput);
      } else {
        MultiSelectRemoveSelection(p_dropDownListInput);
      }
    }

    p_dropDownListInput.selectedIndex = 0;
  }
}

function MultiSelectAddSelection(p_dropDownListInput) {
  var listboxInput = null;

  if (!(IsBrowserNetscapeOrIE())) {
    return true;
  }

  if (document.getElementById) {

    listboxInput = document.getElementById(p_dropDownListInput.id.slice(0,-12));

    if (eval(p_dropDownListInput.id + "_Active") != "true") {
      return true;
    }

    if (p_dropDownListInput.options[0].value == "") {

      eval(p_dropDownListInput.id + "_ForeColourStyle = '" + p_dropDownListInput.style.color + "';");
      eval(p_dropDownListInput.id + "_BackgroundColourStyle = '" + p_dropDownListInput.style.backgroundColor + "';");
      eval(p_dropDownListInput.id + "_Prompt = '" + p_dropDownListInput.options[0].text + "';");

      p_dropDownListInput.options[0].text = p_dropDownListInput.options[p_dropDownListInput.selectedIndex].text;
      p_dropDownListInput.options[0].value = p_dropDownListInput.options[p_dropDownListInput.selectedIndex].value;
    } else
    {
      p_dropDownListInput.options[0].text += ", " + p_dropDownListInput.options[p_dropDownListInput.selectedIndex].text;
      p_dropDownListInput.options[0].value += "," + p_dropDownListInput.options[p_dropDownListInput.selectedIndex].value;
    }

    if (listboxInput.options.length == p_dropDownListInput.options.length){
      listboxInput.options[p_dropDownListInput.selectedIndex].selected = true;
    } else
    {
      listboxInput.options[p_dropDownListInput.selectedIndex - 1].selected = true;
    }

    p_dropDownListInput.options[p_dropDownListInput.selectedIndex].style.color = '#fff';
    p_dropDownListInput.options[p_dropDownListInput.selectedIndex].style.backgroundColor = '#136';
  }
}

function EscapeRegularExpression(p_string) {
  var regReg = /(\*|\^|\$|\+|\?|\.|\(|\)|\||\{|\}|\,|\[|\]|\\|\/)/g
  return p_string.replace(regReg,'\\$1');
}

function MultiSelectRemoveSelection(p_dropDownListInput) {
  var listboxInput = null;
  var re = null;

  if (!(IsBrowserNetscapeOrIE())) {
    return true;
  }

  if (document.getElementById) {

    listboxInput = document.getElementById(p_dropDownListInput.id.slice(0,-12));

    if (eval(p_dropDownListInput.id + "_Active") != "true") {
      return true;
    }

    if (p_dropDownListInput.options[0].text.indexOf(",") == -1)
    {

      p_dropDownListInput.options[0].text = eval(p_dropDownListInput.id + "_Prompt;");

      p_dropDownListInput.options[0].value = "";

    } else
    {

      re = new RegExp("\\s" + EscapeRegularExpression(p_dropDownListInput.options[p_dropDownListInput.selectedIndex].text) + ",|^" + EscapeRegularExpression(p_dropDownListInput.options[p_dropDownListInput.selectedIndex].text) + ",\\s|, " + EscapeRegularExpression(p_dropDownListInput.options[p_dropDownListInput.selectedIndex].text) + "$");
      p_dropDownListInput.options[0].text = p_dropDownListInput.options[0].text.replace(re, "");

      re = new RegExp("^" + EscapeRegularExpression(p_dropDownListInput.options[p_dropDownListInput.selectedIndex].value) + ",|," + EscapeRegularExpression(p_dropDownListInput.options[p_dropDownListInput.selectedIndex].value));
      p_dropDownListInput.options[0].value = p_dropDownListInput.options[0].value.replace(re, "");
    }

    if (listboxInput.options.length == p_dropDownListInput.options.length){
      listboxInput.options[p_dropDownListInput.selectedIndex].selected = false;
    } else
    {
      listboxInput.options[p_dropDownListInput.selectedIndex - 1].selected = false;
    }

    p_dropDownListInput.options[p_dropDownListInput.selectedIndex].style.color = eval(p_dropDownListInput.id + "_ForeColourStyle;");
    p_dropDownListInput.options[p_dropDownListInput.selectedIndex].style.backgroundColor = eval(p_dropDownListInput.id + "_BackgroundColourStyle;");
  }
}

function ClearMultiSelect(p_dropDownListId) {

  var dropDownListInput = null;
  var listboxInput = null;
  var originalValue = "";

  if (!(IsBrowserNetscapeOrIE())) {
    return true;
  }

  if (document.getElementById) {

    dropDownListInput = document.getElementById(p_dropDownListId);

    listboxInput = document.getElementById(dropDownListInput.id.slice(0, -12));

    if (eval(p_dropDownListId + "_Active") != "true") {
      return true;
    }

    if (dropDownListInput.options[0].value != "") {

      for (var i = 0; i < listboxInput.options.length; i++) {
        listboxInput.options[i].selected = false;
      }

      for (var j = 0; j < dropDownListInput.options.length; j++) {
        dropDownListInput.options[j].style.color = eval(dropDownListInput.id + "_ForeColourStyle;");
        dropDownListInput.options[j].style.backgroundColor = eval(dropDownListInput.id + "_BackgroundColourStyle;");
      }

      dropDownListInput.options[0].text = eval(dropDownListInput.id + "_Prompt;");
      dropDownListInput.options[0].value = "";

      originalValue = eval(p_dropDownListId + "_Original;");

      if (originalValue != "") {
        RunOnChange(document.getElementById(p_dropDownListId));
      }
    }
  }

  dropDownListInput.selectedIndex = 0;

}

function InitialiseMultiSelect(p_field) {

  if (p_field.getAttribute("clearmultiselect")) {

    var defaultValues = "";
    if (p_field.getAttribute("defaultvalues")) {
      defaultValues = p_field.getAttribute("defaultvalues");
    }

    var imgElement = document.createElement('img');
    imgElement.setAttribute('alt', p_field.getAttribute('alttext'));
    imgElement.setAttribute('src', '/framework/_images/erase.gif');
    imgElement.className = 'lookupicon';

    var functionCode = 'ClearMultiSelect(\'' + p_field.id + '\', \'' + defaultValues + '\'';

    imgElement.onclick = new Function(functionCode + ');');

    p_field.parentNode.insertBefore(imgElement, p_field.nextSibling);
  }
}

function IsMultiSelectCentreListBoxSelected(p_lstBoxId, p_label) {
  if (document.getElementById) {
    var lstBox = document.getElementById(p_lstBoxId);
    if (!lstBox.disabled) {
      if (lstBox.selectedIndex == -1) {
        var message = p_label + ": A centre must be selected from the list box.";
        alert(message);
        return false;
      }
    }
    else
      return false;
  }
  return true;
}

function IsMultiSelectCentreAlreadyExists(p_txtBoxId, p_lstBoxId, p_label) {
  if (document.getElementById) {
    var txtBox = document.getElementById(p_txtBoxId);

    if (!txtBox.disabled) {
      if (txtBox.value.length < 1) {
        var message = p_label + ": A centre code must be entered in the text box.";
        alert(message);
        SetFocus(p_txtBoxId);
        return false;
      }

      var lstBox = document.getElementById(p_lstBoxId);
      var opt = lstBox.options;
      var message= p_label +": The centre already exists in the list box.";
      for(var i = 0; i < opt.length; i++) {
        if (opt[i].value == txtBox.value) {
          alert(message);
          return false;
        }
      }
    }
    else {
      return false;
    }
  }
  return true;
}

function ValidateMandatoryMultiSelectCentre(source, args) {
  args.IsValid = true;
  if (document.getElementById) {
    var ctrl = document.getElementById(source.controltovalidate);
    alert(ctrl.value);
    if (ctrl.value == -1) {
      args.IsValid = false;
      alert(ctrl.value)
    }
  }
  return args.IsValid;
}

function SelectKeyDown() {
  var key = window.event.keyCode;
  if (key == 27)
  ClearKeys();
  if (key == 8) {
    if (m_smartSearchKeys != "") {
      m_smartSearchKeys = m_smartSearchKeys.slice(0, -1);
    }
    window.event.keyCode = 0;
  }
}

function SelectKeyPress() {

  if (document.getElementById) {
    var sndr = window.event.srcElement;
    var pre = m_smartSearchKeys;
    var key = window.event.keyCode;
    var chars = String.fromCharCode(key);
    var re;

    var matched = false;


    if (key != 40 && key != 41 && key != 42 && key != 43 && key != 63 && key != 91 && key != 92) {
      if (key == 8 || key == 27) {
        re = new RegExp("^" + pre,"i");
        chars = "";
      }
      else {
        re = new RegExp("^" + pre + chars, "i"); // "i" -> ignoreCase
        chars = String.fromCharCode(key);
      }

      for (var i = 0; i < sndr.options.length; i++) {
        if (re.test(sndr.options[i].text))  {
          sndr.options[i].selected = true;
          if (sndr.onchange) {
            sndr.onchange();
          }
          m_smartSearchKeys += chars;
          window.event.returnValue = false;
          matched = true;
          break;
        }
      }
      if (!matched && m_smartSearchKeys != "") {
        window.event.returnValue = false;
      }
    }
  }
}

function ClearKeys() {
  m_smartSearchKeys = "";
}

function DisableAllControls() {

  var controlTypes = new Array("INPUT", "SELECT", "A", "TEXTAREA");

  if (m_disableControls) {
    document.body.style.cursor = "wait";

    var i;
    for (i = 0; i < controlTypes.length; i++) {
      var inputFields = document.getElementsByTagName(controlTypes[i]);
      var j = 0;
      while (inputFields[j]) {
        var ctrl = inputFields[j];
        if (ctrl.type != "hidden") {
          ctrl.disabled = true;
          ctrl.style.cursor = "wait";
        }
        if (controlTypes[i] == "A") {
          ctrl.href = "#";
        }
        j++;
      }
    }
    m_disableControls = false;
  }
}

function RegisterDisableControlsForButtons() {
  var inputFields = document.getElementsByTagName('input');
  var i = 0;
  while (inputFields[i]) {
    if (inputFields[i].type.toUpperCase() == "SUBMIT") {
      if (!inputFields[i].getAttribute("ignoredisablecontrols")) {
        AddToOnClick(inputFields[i], "SetDisableControls();", true);
      }
    }
    i++;
  }
}

function SetDisableControls() {
  m_disableControls = true;
}

function DisableChildControls(p_parentId) {

  if (document.getElementById) {
    var parentDiv = document.getElementById(p_parentId);
    ChangeDisableStatus(parentDiv, true);
    ChangeInputDisableStatus(parentDiv, true);
  }
}

function ChangeDisableStatus(p_node, p_disableStatus) {
  for (var i = 0; i < p_node.childNodes.length; i++) {
    if (p_node.childNodes[i].nodeType == 1) {
      ChangeDisableStatus(p_node.childNodes[i], p_disableStatus);
      p_node.childNodes[i].disabled = p_disableStatus;

      if (p_node.childNodes[i].nodeName == 'IMG') {
        if (p_node.childNodes[i].className = 'lookupicon') {
          p_node.childNodes[i].className = '';
          p_node.childNodes[i].onclick = 'return false;';
        }
        if (p_node.childNodes[i].src.indexOf('/framework/_images/lookup.gif') > 0)
          p_node.childNodes[i].src = '/framework/_images/lookupdisabled.gif';
        if (p_node.childNodes[i].src.indexOf('/framework/_images/erase.gif') > 0)
          p_node.childNodes[i].src = '/framework/_images/erasedisabled.gif';
        if (p_node.childNodes[i].src.indexOf('/framework/_images/view.gif') > 0)
          p_node.childNodes[i].src = '/framework/_images/viewdisabled.gif';
        if (p_node.childNodes[i].src.indexOf('/framework/_images/edit.gif') > 0)
          p_node.childNodes[i].src = '/framework/_images/editdisabled.gif';
        if (p_node.childNodes[i].src.indexOf('/framework/_images/delete.gif') > 0)
          p_node.childNodes[i].src = '/framework/_images/deletedisabled.gif';
        if (p_node.childNodes[i].src.indexOf('/framework/_images/calendar.gif') > 0)
          p_node.childNodes[i].src = '/framework/_images/calendardisabled.gif';
      }

      if (p_node.childNodes[i].nodeName == 'A') {
        p_node.childNodes[i].className = p_node.childNodes[i].className;
        p_node.childNodes[i].style.cursor = p_node.childNodes[i].style.cursor;
        p_node.childNodes[i].href = p_node.childNodes[i].href;
        p_node.childNodes[i].onclick = p_node.childNodes[i].onclick;
        p_node.childNodes[i].target = p_node.childNodes[i].target;
        if(p_disableStatus) {
          p_node.childNodes[i].className = '';
          p_node.childNodes[i].style.cursor = 'default';
          p_node.childNodes[i].href = '#';
          p_node.childNodes[i].onclick = 'return false;';
          p_node.childNodes[i].target = '';
        }
      }
    }
  }
}

function ChangeInputDisableStatus(p_node, p_disableStatus) {
  for (var i = 0; i < p_node.childNodes.length; i++) {
    if (p_node.childNodes[i].nodeType == 1) {
      if (p_node.childNodes[i].nodeName == 'INPUT') {
        p_node.childNodes[i].readOnly = p_disableStatus;
      }
      ChangeInputDisableStatus(p_node.childNodes[i],p_disableStatus);
    }
  }
}

function ValidateMandatoryCheckBoxList(p_validatorControl) {
  var ctrl = document.getElementById(p_validatorControl.controltovalidate);
  var chk = ctrl.all;
  for (i = 0; i < chk.length; i++) {
    if (chk[i].tagName.toUpperCase() == 'INPUT') {
      if (chk[i].checked) {
        return true;
      }
    }
  }
  return false;
}

function HideErrors() {
  return true;
}



function DefaultButtonHandler(p_btnId, p_event) {

  var btn = GetObject(p_btnId);

  if (p_event) {

    if (document.all) {
      if (p_event.keyCode == 13) {
        p_event.returnValue = false;
        p_event.cancel = true;
        btn.focus();
        btn.click();
      }
    }
    else if (document.getElementById) {
      if (p_event.keyCode == 13) {
        p_event.returnValue = false;
        p_event.cancel = true;
        btn.click();
      }
    }
    else if (document.layers) {
      if (p_event.which == 13) {
        p_event.returnValue = false;
        p_event.cancel = true;
        btn.focus();
        btn.click();
      }
    }
  }
}

function GetObject(p_objectId, p_doc) {
  var pos, i, retObj;
  if (!p_doc)
    p_doc = document;
  if ((pos = p_objectId.indexOf("?")) > 0 && parent.frames.length) {
    p_doc = parent.frames[p_objectId.substring(pos + 1)].document;
    p_objectId = p_objectId.substring(0, pos);
  }
  if (!(retObj = p_doc[p_objectId]) && p_doc.all)
    retObj = p_doc.all[p_objectId];
  for (i = 0; !retObj && i < p_doc.forms.length; i++)
    retObj = p_doc.forms[i][p_objectId];
  for (i = 0; !retObj && p_doc.layers && i < p_doc.layers.length; i++)
    retObj = GetObject(p_objectId, p_doc.layers[i].document);
  if (!retObj && p_doc.getElementById)
    retObj = p_doc.getElementById(p_objectId);
  return retObj;
}

function CreateCookie(p_name,p_value,p_days) {
	if (p_days) {
		var date = new Date();
		date.setTime(date.getTime()+(p_days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = p_name+"="+p_value+expires+"; path=/";
}

function ReadCookie(p_name) {
	var nameEQ = p_name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function EraseCookie(p_name) {
	CreateCookie(p_name,"",-1);
}
