/**
 * everyPage.js
 *
 * This file contains javascript functions used by mpower-suite
 * modules.
 * This file is included on every page
 *
 * $Header: /JavaScript/everypage.js 193   20/04/06 17:22 Aa $
 * $Revision: 193 $
 *
 * $Log: /JavaScript/everypage.js $
 * 
 * 193   20/04/06 17:22 Aa
 * 2033561
 * 
 * 192   17/04/06 9:40 Gc
 * 2033149
 *
 * 191   10/04/06 17:01 Aa
 * 2033456
 *
 * 190   10/04/06 11:44 Gc
 * 2033793
 *
 * 189   10/04/06 10:45 Aa
 *
 * 188   30/03/06 11:23 Gc
 * 2032848
 *
 * 187   21/03/06 13:57 Aa
 * 2032404
 *
 * 186   13/03/06 14:22 Gc
 * 2032324
 *
 * 185   10/03/06 13:49 Ts
 * 2031925
 *
 * 184   3/03/06 16:40 Gc
 * 2032314
 *
 * 183   1/03/06 15:28 Gc
 * 2031384
 *
 * 182   23/02/06 15:01 Aa
 * 2031734
 *
 * 181   22/02/06 9:17 Aa
 * 2031714
 *
 * 180   21/02/06 16:14 Aa
 * 2031714
 *
 * 179   13/02/06 10:33 Aa
 * 2031169
 *
 * 178   9/02/06 10:45 Gc
 *
 * 177   7/02/06 15:58 Ts
 *
 * 176   6/02/06 16:26 Gc
 * 2019875
 *
 * Copyright 1996-2004 Monitor Management Control Systems Ltd.
 *
 *  Amendment History
 *
 *  Who  When         Why
 *  TS   31-01-06  2030170 : Changes to och() to better handle table filtering on date fields (including those with times).
 *  GC   31-01-06  2030105 : Modified address functions so that there can be more than one address popup per row
 *  GC   01-02-06  2030433 : Added saveCopy (moved from ui_copy_obj)
 *  GC   02-02-06  2019875 : Modified export functions so that an export can be done on any table.
 *  GC   02-02-06  2019875 : Added exportRSetPrint
 *  TS   07-02-06            Fixed typo in Help text.
 *  AA   13-02-06  2031169 : Added functionality to allow login error message to be exited via the x.
 *  AA   21-02-06  2031714 : disable navigation on navigatePage
 *  AA   21-02-06  2031714 : Rework - disable navigation on navigatePage
 *  AA   22-02-06  2031714 : Rework - disable navigation on navigatePage
 *  AA   23-02-06  2031734 : Add scrollPrevMonth and scrollNextMonth for calendar.
 *  GC   01-03-06  2031384 : Modified export functions to allow a sql table to be passed in.  changed set and getCurrUser to always use the variable in the headerframe
 *  GC   03-03-06  2032314 : Call addHistory from navigatePage
 *  TS   10-03 05  2031925 : Make applets re-appear when window background is clicked (and therefore when popups/dropdowns close). Gather the list of applets into just one place.
 *  GC   13-03-06  2032324 : Added get and set UserParameters
 *  AA   21-03-06  2032404 : Various updates for calendar
 *  GC   30-03-06  2032848 : Added isInterfaceActive
 *  AA   10-04-06  2033456 : Added function setObjectDependingOnType
 *  GC   10-04-06  2033793 : Call closeMenu in bodyClicked
 *  AA   10-04-06  2033456 : REWORK function setObjectDependingOnType
 *  GC   17-04-06  2033149 : Added rebuildNextHref and isAutoSaveOn
 *  AA   20-04-06  2033561 : Added clear functionality for saved searches in doClearFilter function.
 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
var mouseX, mouseY;
var lastRow;
var bIsBusy = false;
var rowIndex = 0;
var bSaveChanges = false;
var bCheckUnload = true;
var bNavigationEnabled = true;
var sNextHref = "";
var sNextSaveHref = "";
var session = "";
var currUser = "";
var aQueryDescs = new Array();
var bAutoSave = false;
var sReportScreenID = "";
var sReportParameters = "";
var bAddressSearch = false;
var numberFormat;
var screenTitle;
var imageArray;
var bSetChanged = true;
var bDisableHotKey = false;

var exportQuery = "";
var exportParams = "";

var aUserParameters = new Array();

// Rows
var nSelectedRow = 0;

function getMenuOpenType(){
  if (typeof top.headerFrame == "object"){
    return top.headerFrame.getOpenType();
  }else{
    return 0;
  }
}

/**
 * function to set the session for use within js functions
 * @param newSession String - the session.
 */
function setSession(newSession){
  session = newSession;
}

function setCurrUser( newValue ){
  if(top.frames.length > 0){
    top.frames[0].currUser = newValue;
  }else{
    top.frames.currUser = newValue;
  }
}

function getCurrUser(){
  if(top.frames.length > 0){
    return top.frames[0].currUser;
  }else{
    return top.frames.currUser;
  }
}

function setUserParameter(p_param_id, p_value){
  if(top.frames.length > 0){
    top.frames[0].aUserParameters[p_param_id] = p_value;
  }else{
    top.frames.aUserParameters[p_param_id] = p_value;
  }
}

function getUserParameter(p_param_id){
  if(top.frames.length > 0){
    return top.frames[0].aUserParameters[p_param_id];
  }else{
    return top.frames.aUserParameters[p_param_id];
  }
}

function setNumberFormat( newValue ){
  numberFormat = newValue;
}

function getNumberFormat(){
  return numberFormat;
}

function isInterfaceActive(p_interface_id){
  if(typeof top.headerFrame == "object" && typeof top.headerFrame.getInterfaceStatus == "function"){
    return top.headerFrame.getInterfaceStatus(p_interface_id);
  }

  return false;
}


function setExportQuery(newValue){ exportQuery = newValue; }
function setExportParams(newValue){ exportParams = newValue; }
function getExportQuery(){ return exportQuery; }
function getExportParams(){ return exportParams; }

function setHeaderIcon(p_icon){
  if (typeof top.headerFrame == "object" && typeof top.headerFrame.tdScreenImg == "object"){
    var imgObj = top.headerFrame.tdScreenImg;

    if (p_icon != ""){
      imgObj.innerHTML = "<IMG SRC=\""+getImage(p_icon)+"\">";
    }else{
      imgObj.innerHTML = "";
    }
  }
}


function doNav(p_params){
  var paramArray = p_params.split("@");
  var actionParams = "";
  var loopCount = 0;
  for (var i in paramArray){
    if (loopCount > 0){
      actionParams += (actionParams.length > 0?"$":"") + paramArray[i];
    }
    loopCount++;
  }
  doAction(actionParams);
}


function getMouseXY(e) {
  mouseX = event.clientX + document.body.scrollLeft
  mouseY = event.clientY + document.body.scrollTop

  // Overlib stuff
  try{
    if ( (ns4) || (ns6) ) {o3_x=e.pageX; o3_y=e.pageY;}
    if (ie4) {o3_x=event.x; o3_y=event.y;}
    if (ie5) {o3_x=mouseX; o3_y=mouseY;}

    if (o3_allowmove == 1) {
      placeLayer();
    }

  } catch (e) {}

}

function setObjectStyleDisplay(o, s) {
  if ( typeof o == "object" ) o.style.display=s;
}

function setAppletStyleDisplay(s) {
  setObjectStyleDisplay(top.bodyFrame.objAnalysisApplet, s);
  setObjectStyleDisplay(top.bodyFrame.ActivityGantt, s);
}

function bodyClicked(e){
  if ( typeof menuDiv == "object" ) menuDiv.style.display="none";
  if ( typeof top.headerFrame == "object" && typeof top.headerFrame.closeMenu == "function" ) top.headerFrame.closeMenu();
  if ( typeof top.bodyFrame == "object" ) setAppletStyleDisplay("inline");
  moveToolbar();
}

function getObject( p_ref, p_form ){
  if ( isEmpty(p_form)){
    return document.all[p_ref];
  } else {
    var form = document.all[p_form];
    if ( typeof form == "object" ){
      return form.elements[p_ref];
    } else {
      return document.all[p_ref];
    }
  }
}

function storeQueryDesc( p_page_id, p_description ){
  top.headerFrame.aQueryDescs[p_page_id] = p_description;
}

function getQueryDesc( p_page_id ){
  return top.headerFrame.aQueryDescs[p_page_id];
}

/** get row, adjusting for Javascript */
function getSelectedRow(){
  return nSelectedRow - 1;
}

/** Set the next row. */
function setSelectedRow( p_row, p_rowref, p_div ){
  nOldSelectedRow = nSelectedRow;
  nSelectedRow = p_row;

  if ( p_rowref ){
    var rowObj = getObject(p_rowref+p_row);
    if ( rowObj ){
      if (rowObj.className!="delRow"){
        // Select the new row
        rowObj.className = "selectedRow";
      }

      if (nOldSelectedRow != nSelectedRow) {
        // unselect the old row, if any
        var oldRowObj = getObject(p_rowref+nOldSelectedRow);
        if (oldRowObj) {
          if (oldRowObj.className != "delRow") {
            oldRowObj.className = "";
          }
          for ( var j = 0 ; j < oldRowObj.all.length ; j++ ){
            if ( oldRowObj.all[j].tagName == "IMG" && oldRowObj.all[j].id == "imgRow" ){
              oldRowObj.all[j].src=getImage("IMG_EXPAND");
              break;
            }
          }
        }
      }

      if ( p_div ){
        var divSingle = getObject( p_div );
      }else{
        var divSingle = getObject("divSingleEntry");
      }

      //alert("DEBUG: Ignore any messages with DEBUG at the start....");
      //alert("DEBUG: Looping round " + rowObj.all.length + " objects");
      // Now, share the objects on the row with the single entry form
      for ( var i = 0 ; i < rowObj.all.length ; i++ ){
        if ( rowObj.all[i].tagName == "INPUT" ){
          var inputObj = rowObj.all[i];
          doChangeShare( inputObj );
        }

      //alert("DEBUG: typeof divSingle " + typeof divSingle + "\ndivSingle.style.display " + divSingle.style.display);
        if ( typeof divSingle == "object" && divSingle.style.display == "inline" ){
          if ( rowObj.all[i].tagName == "IMG" && rowObj.all[i].id == "imgRow" ){
            rowObj.all[i].src=getImage("IMG_EXPANDED");
          }
        }
      }

    }

    if (typeof postSetSelectedRow == "function"){
      postSetSelectedRow(p_rowref, p_row);
    }
  }
}

/** An object's value has changed. Change any shared objects. */
function doChangeShare( p_obj, p_is_colour ){
  var myForm, shareObj, changedObj;
  var tdRef;
  if ( typeof p_obj.form == "object" && p_obj.form != null ){
    var formID = p_obj.form.id;
    // If this is a Single Entry Form, then find the selected row
    if ( formID.indexOf("Single") != -1 ) {
      myForm = document.all["frm"+formID.substring(formID.indexOf("Single")+6, formID.length)];
      if ( myForm ) shareObj = myForm.elements[p_obj.id];

      if ( shareObj ){
        var realThing = realObj(shareObj, getSelectedRow());
        if ( p_obj.type == "checkbox" ){
          realThing.checked = p_obj.checked;
          if ( p_obj.checked ){
            realThing.value = '1';
          } else {
            realThing.value = '0';
          }
        } else {
          realThing.value = p_obj.value;
          if (p_is_colour){
            realThing.style.background = p_obj.value;
            tdRef = getObject("TD"+p_obj.id+getSelectedRow());
            tdRef.style.background = p_obj.value;
          }
        }
        setChanged(realThing, getSelectedRow());
      }

      setChanged(p_obj, -1);

    } else {
      // Table Edit, so get the TR tag, and if it is selected, then proceed
      var parentTr = p_obj.parentNode.parentElement;

      if ( parentTr.className == "selectedRow" ) {
        myForm = document.all["frmSingle"+formID.substring(formID.indexOf("frm")+3, formID.length)];
        if ( myForm ) shareObj = myForm.elements[p_obj.id];

        if ( shareObj ) {
          if ( p_obj.type == "checkbox" ){
            shareObj.checked = p_obj.checked;
            if ( p_obj.checked ){
              shareObj.value = '1';
            } else {
              shareObj.value = '0';
            }
          } else {
            shareObj.value = p_obj.value;
            if (p_is_colour){
              shareObj.parentElement.style.background = p_obj.value;
              tdRef = p_obj.parentElement; //getObject("TD"+p_obj.id);
              tdRef.style.background = p_obj.value;
            }
          }
        }
      }
    }
  }
}


/** Function to set the value of a search into a main page */
function setSearchRes( p_obj, p_desc_obj, p_type, p_value, p_desc, p_row, p_do_onchange ){

  if ( typeof p_desc_obj == "object" ){
      setColumnValue( p_desc_obj, p_row, p_desc, false );
  }

  if ( typeof setSearchResult == "function" ){
    setSearchResult( p_obj, p_type, p_value, p_row );
  } else {

    setColumnValue( p_obj, p_row, p_value, false);
  }

  moveToolbar();

  if (p_do_onchange){
    if (isEmpty(p_row)){
      doOnChange(p_obj);
    }else{
      doOnChange(p_obj[p_row], p_row);
    }
  }

}

function setCheckUnload( p_newvalue ){
  bCheckUnload = p_newvalue;
}

function reset(){
  if ( top.headerFrame.tdScreenTitle ){
    top.headerFrame.tdScreenTitle.innerHTML = "";
    screenTitle  = "";
  }
  setPageID("");
  setMainTab("");
  setSubTab("");
  setRowIndex(1);
}

function setRowIndex( p_row_index ){
  rowIndex = p_row_index;
}

function getRowIndex( ){
  return rowIndex;
}

// Sets the title at the top of the screen
function setScreenTitle( newTitle ){
  if ( top.headerFrame.tdScreenTitle ){
    top.headerFrame.tdScreenTitle.innerHTML = newTitle;
    screenTitle = newTitle;
  }
}

function setPageID( pageID ){
  try {
    top.headerFrame.sPageID = pageID;
  } catch (e) {}
}

function setMainTab( mainTab ){
  try {
    top.headerFrame.sMainTab = mainTab;
  } catch (e) {}
}

function setSubTab( subTab ){
  try {
    top.headerFrame.sSubTab = subTab;
    top.headerFrame.sNextSubTab = subTab;
  } catch (e) {}
}

function setNextSubTab( subTab ){
  try {
    top.headerFrame.sNextSubTab = subTab;
  } catch (e) {}
}

function getPageID(){
  try {
    return top.headerFrame.sPageID;
  } catch (e) { return ""; }
}

function getMainTab(){
  try {
    return top.headerFrame.sMainTab;
  } catch (e) { return ""; }
}

function getSubTab(){
  try {
    return top.headerFrame.sSubTab;
  } catch (e) { return ""; }
}

function getNextSubTab(){
  try {
    return top.headerFrame.sNextSubTab;
  } catch (e) { return ""; }
}

// Selects a row in a table
function rowSel( prefix, row, total ){
  var obj = document.all[prefix+row];
  var prevObj = document.all[prefix+lastRow];

  // Reset previous row
  if ( prevObj ){
    for ( var i = 0 ; i < total ; i++ ){
      prevObj[i].className = "tdRow";
    }
  }

  // Set new row
  if ( obj && typeof obj.length != "undefined" ){
    for ( var i = 0 ; i < total ; i++ ){
      obj[i].className = "selectedRow";
    }
  } else if ( obj ) {
    obj.className = "selectedRow";
  }

  lastRow = row;
}

function isEmpty( p_obj ){
  return (p_obj == "" || p_obj == " " || typeof p_obj == "undefined");
}


function addSearchColumn( p_name, p_column ){
  var sRval = "";
  var value = "";
  if ( typeof p_column == "object" ){

    if ( !isEmpty( p_column.value ) ){

      if (p_column.type == "checkbox") {
        value = "0";
        if (p_column.checked){
          value = "1";
        }
        sRval += p_name+"@"+value+"$";
      } else {
        sRval += p_name+"@"+p_column.value+"$";
      }
    }
  } else if ( typeof p_column == "string" ){
    sRval += p_name+"@"+p_column+"$";
  }

  return sRval;
}


/** when hovering over a menu item, change the class (called in onMouseOver)*/
function inMenu( obj ){
  obj.className = "menuItemHov";
}

/** when hovering over a menu item, change the class (called in onMouseOut) */
function outMenu( obj ){
  obj.className = "menuItem";
}

function isBusy(){
  return bIsBusy;
}

function makeBusy(){
  bIsBusy = true;
}

function resetBusy(){
  bIsBusy = false;
}

/** Centre the Div on the page */
function centreDiv( p_div ){
  //alert("scrollTop " + top.bodyFrame.document.body.scrollTop + "\ndocument height " + top.bodyFrame.document.body.offsetHeight + "\ndiv pixelHeight " + p_div.style.pixelHeight);

  var leftPos = (top.bodyFrame.document.body.offsetWidth/2) - (p_div.style.pixelWidth/2) + (top.bodyFrame.document.body.scrollLeft);
  var topPos = (top.bodyFrame.document.body.offsetHeight/2) - (top.headerFrame.document.body.offsetHeight) - (p_div.style.pixelHeight/2) + (top.bodyFrame.document.body.scrollTop) + 5;

  if (leftPos < 0) leftPos = 0;
  if (topPos < 0) topPos = 0;

  p_div.style.left = leftPos;
  p_div.style.top = topPos;
}

function displayMenuDiv(){
  showDiv(top.bodyFrame.menuDiv, false);
}

function displayDiv( p_div ){
  showDiv(p_div, true);
}

function showDiv(p_div, p_centre){
  if (p_centre){
    centreDiv(p_div);
  }
  setAppletStyleDisplay("none");
  cursorAuto(false);
  p_div.style.display = "inline";
}

function showBusyDiv(){
//   if ( typeof top.bodyFrame.menuDiv == "object" ){
//     top.bodyFrame.menuDiv.style.width = 100;
//     top.bodyFrame.menuDiv.style.height = 100;
//     var theString = "<IMG src='/img/busy.gif'>";
//     top.bodyFrame.menuDiv.innerHTML=theString;
//     displayDiv(menuDiv);
//   }
}

function hideDiv( p_div ){
  p_div.style.display="none";
  if(typeof top.bodyFrame == "object" ){
    setHdrMsg(top.bodyFrame.screenTitle);

    // Make any applets appear
    setAppletStyleDisplay("inline");
    moveToolbar();
    if (typeof top.bodyFrame.formDiv == "object" && p_div == top.bodyFrame.formDiv){
      allowSetChanged(true);
    }
  } else {
    //check to ensure that we are dealing with the login page
    if(typeof window.document.login_form == "object"){
      window.document.login_form.p_username.disabled=false;
      window.document.login_form.p_password.disabled=false;
      window.document.login_form.p_username.focus();
    }
  }
  enableNavigation();
}

function hideDivs(){
  if ( typeof top.bodyFrame.miscDiv == "object" ) top.bodyFrame.miscDiv.style.display="none";
  if ( typeof top.bodyFrame.menuDiv == "object" ) top.bodyFrame.menuDiv.style.display="none";
  if ( typeof top.bodyFrame.confirmDiv == "object" ) top.bodyFrame.confirmDiv.style.display="none";
  if ( typeof top.bodyFrame.errorDiv == "object" ) top.bodyFrame.errorDiv.style.display="none";
  if ( typeof top.bodyFrame.actionMsgDiv == "object" ) top.bodyFrame.actionMsgDiv.style.display="none";
}

/** Change the cursor for the whole screen to the busy (wait) cursor */
function cursorWait(){
  makeBusy();

  hideDivs();
  showBusyDiv();

  setHdrMsg(getTerm("{BUSY}")+" <IMG SRC='"+getImage("IMG_BUSY")+"'>");
  //changeCursor("wait");
}

/** Change the cursor over an object to a pointer */
function crPoint(p_obj){
  try {
    p_obj.style.cursor = "pointer";
  } catch (e){}
}

/** Change the cursor over an object to a pointer */
function crAuto(p_obj){
  try {
    p_obj.style.cursor = "auto";
  } catch (e){}
}

/** Change the cursor for the whole screen to be the default */
function cursorAuto( p_enable ){
  resetBusy();
  setHdrMsg("");

  if ( typeof p_enable == "undefined" || p_enable == true ) enableNavigation();
}

function allowSetChanged(p_boolean){
  bSetChanged = p_boolean;
}

/** When an object is changed, this function is called */
function setChanged( p_obj, p_rownum ){
  if (bSetChanged){
    setSaveChanges(true);
    if ( typeof p_obj.style != "undefined" ){
      p_obj.style.color = "red";
    }

    // Get the changed object
    if ( typeof p_obj.form == "object" && p_obj.form != null ){
      var changed = p_obj.form.elements["p_changed"];

      if ( typeof changed != "undefined" ){
        if ( p_rownum > -1){
          if ( typeof changed.length != "undefined" ){
            changed[p_rownum].value = "Y";
          } else {
            changed.value = "Y";
          }
        } else {
          changed.value = "Y";
        }
      }
    }
  }
}

/** Return the length of an object */
function getLength( p_obj ){
  if ( typeof p_obj != "undefined" ){
    if ( typeof p_obj.length != "undefined" ){
      return p_obj.length;
    }

    return 1;
  }
  return 0;
}

/** Return the 'real' object to use. If it is an array, then return the correct entry */
function realObj( p_obj, p_row ){
  if ( typeof p_obj != "undefined" ){
    if ( typeof p_obj.length != "undefined" ){
      return p_obj[p_row];
    }

    return p_obj;
  }
}


function hasChanged(){
  return bSaveChanges;
}

function setSaveChanges(p_changed){
  bSaveChanges = p_changed;
}

/** Set the value of a column, and change its colour. */
function setColumnValue( p_obj, p_row, p_value, p_no_equals, p_noChangeShare ){
  if ( typeof p_obj != "undefined" ){
    if ( p_row == "" && typeof p_obj.length == "undefined" ) {
      if((p_obj.form.id == "searchForm") && !p_no_equals){
        p_obj.value = "=" + p_value;
      } else {
        setObjectDependingOnType(p_obj, p_value)
      }
      if(!p_noChangeShare) doChangeShare(p_obj);
      setChanged( p_obj, (p_row==""?-1:p_row) )
    } else if ( p_row != "" ) {
      setObjectDependingOnType(realObj(p_obj, p_row), p_value);
      if(!p_noChangeShare) doChangeShare( realObj(p_obj, p_row) );
      setChanged( realObj(p_obj, p_row), (p_row==""?-1:p_row) )
    }

  }
}

function setObjectDependingOnType (p_obj, p_value){
  if (p_obj.type == "checkbox"){
    if (p_value > 0) {
      p_obj.checked = true;
    } else {
      p_obj.checked = false;
    }
  }else{
    p_obj.value = p_value;
  }
}

/** Add a row */
function addRow( p_ref, p_row, p_div, p_noRowMsg, p_do_height, p_table_id ){
  var rowObj = getObject(p_ref+p_row);
  var divObj = getObject( p_div );
  if ( typeof p_table_id == "undefined" ) p_table_id = "tblOuter";
  var tbl = getObject( p_table_id );

  if ( typeof rowObj == "object" ){
    var bAddHeight = ( typeof divObj == "object" && divObj.style.display == "none" );
    rowObj.style.display="inline";

    if ( typeof divObj != "undefined" ) divObj.style.display="inline";

    setSelectedRow(p_row, p_ref, p_div);

    if ( typeof p_do_height == "undefined" || p_do_height ) {
      var heightIncrease = rowObj.offsetHeight;

      tbl.style.height = tbl.offsetHeight + heightIncrease;
    }

    incRow( p_ref );
    if (typeof postAddRow == "function"){
      postAddRow(p_ref);
    }

  } else {
    alertDialog(p_noRowMsg);
  }
}

function tableHeightAdjust(p_ref, p_expand, p_table_id){
  var rowObj = getObject(p_ref);
  var sDefaultTable = "tblOuter";
  if ( typeof p_table_id == "undefined" ) p_table_id = sDefaultTable;
  var tbl = getObject( p_table_id );
  if (typeof tbl == "undefined" && p_table_id != sDefaultTable) tbl = getObject(sDefaultTable);

  var rHeight = rowObj.offsetHeight;

  if (p_expand == "undefined" || p_expand){
    tbl.style.height = tbl.offsetHeight + rHeight;
  }else{
    tbl.style.height = tbl.offsetHeight - rHeight;
  }

}


/* function called when done button is pressed on a detailed rows screen that
 * is in insert mode.
 * @param p_row - the current row index
 * @param p_div - the detailed div
 * @param p_height - the starting height of the table
 * @param p_no_rows - the number of rows originally in the table
 * @param p_table_id - the table id, defaults to 'tblOuter'
 */
function doneAddRow(p_row, p_div, p_height, p_no_rows, p_table_id){
 var divObj = getObject( p_div );
 if ( typeof p_table_id == "undefined" ) p_table_id = "tblOuter";
 var tbl = getObject( p_table_id );

 divObj.style.display="none";
 tbl.style.height = p_height + ((p_row - p_no_rows) * 21) + (tbl.innerHTML.indexOf("blankRow") != -1?15:0);
 moveToolbar();
}



/** Delete a Row */
function delRow( p_ref, p_row, p_form ){
  var obj = getObject( p_ref+p_row );
  var form = getObject( p_form );
  var changed = form.elements["p_changed"];
  var operation = form.elements["p_operation"];
  var nRow = p_row - 1;

  if ( typeof obj == "object" ){
    if ( obj.className == "delRow" ) {
      if ( realObj(operation, nRow).value == "DELETE" ){
        obj.className="";
        realObj(operation, nRow).value = "UPDATE";
      } else {
        obj.className="selectedRow";
      }

    } else {

      obj.className="delRow";

      realObj(changed, nRow).value = "Y";

      if ( realObj(operation, nRow).value != "INSERT" ){
        realObj(operation, nRow).value = "DELETE";
      }

    }
  }

  setSaveChanges(true);
  if (typeof postDelRow == "function"){
    postDelRow(p_ref, p_row);
  }
}

/** Generic copy row function */
function copyRowData(p_rowref, p_from_row, p_to_row){

  var fromRowObj = getObject(p_rowref+(p_from_row+1));
  var toRowObj = getObject(p_rowref+(p_to_row+1));
  var tdRef;

  if (typeof fromRowObj == "object" && typeof toRowObj == "object"){

    for ( var i = 0 ; i < fromRowObj.all.length ; i++ ){
      if (i < toRowObj.all.length){
        var fromObj = fromRowObj.all[i];
        // get the toObj using the id of the fromObj incase the items do not have the same index in the all array
        var toObj   = toRowObj.all[fromObj.id];
        if ( typeof fromObj == "object" && typeof toObj == "object" && fromObj.tagName == "INPUT" && toObj.tagName == "INPUT" ){
          if (typeof fromObj == "object" && typeof toObj == "object"){
            if (fromObj.name.toLowerCase() != "p_operation" && fromObj.name.toLowerCase() != "p_changed" &&
                fromObj.name.toLowerCase() != "p_edited_by" && fromObj.name.toLowerCase() != "p_edited_date" &&
                fromObj.name.toLowerCase() != "p_created_by" && fromObj.name.toLowerCase() != "p_created_date"){

              if (fromObj.type == "checkbox"){
                toObj.checked = fromObj.checked;
                doOnChange(toObj, p_to_row);
              }else{
                toObj.value = fromObj.value;
                if (toObj.value != ""){

                  if(fromObj.name.toLowerCase() =="p_colour"){
                    try {
                      toObj.style.background = fromObj.value;
                      tdRef = getObject("TD"+fromObj.id);
                      tdRef.style.background = fromObj.value;

                      realObj(toObj, getSelectedRow()).style.background = fromObj.value;
                      tdRef = getObject("TD"+fromObj.id+getSelectedRow());
                      tdRef.style.background = fromObj.value;
                    } catch (e){ }
                  }

                  if ( !doOnChange(toObj, p_to_row) ){
                    doChangeShare(toObj)
                  }
                }
              }
            }
          }
        }
      }
    }

    if (typeof postCopyRow == "function"){
      postCopyRow();
    }

  }
}

function doAdd(){
  if (isNav()){
    if ( typeof newItem == "function") {
      newItem();
    }
  }
}

function doDelete(itemType, itemKey){
  if (isNav()){
    confirmDialog("<SPAN style='color:red'>"+getMessage("[DEL-AREYOUSURE"+(isEmpty(itemKey)?"_TMP":"")+"$"+itemType+"@"+itemKey+"]")+"</SPAN>", "doAction(\"DELETE\");", "");
  }
}

function rowHasChanged( p_ref, p_row, p_form ){
  var form = getObject( p_form );
  var obj = getObject( p_ref+(p_row+1) );

  var changed = form.elements["p_changed"];
  var operation = form.elements["p_operation"];
  var nRow = p_row;

  if ( realObj(operation, p_row).value == "INSERT" && obj.className == "delRow" ){
    return false;
  } else if ( realObj(changed, p_row).value == "Y" ) {
    return true;
  }
}

/** Change the cursor for the whole screen the the passed in cursor */
function changeCursor( newCursor ){
  top.bodyFrame.document.body.style.cursor = newCursor;

  for ( var i = 0 ; i < top.bodyFrame.document.all.length ; i++ ){
    top.bodyFrame.document.all[i].style.cursor = newCursor;
  }
}

function onPageUnload(){
  if ( hasChanged() && bCheckUnload ){
    setSaveChanges(false);
    event.returnValue = getMessage("[JS-015]");
    cursorAuto();
  }
}

function errorHandler(){
  alert("Error");
  return true;
}

function enableNavigation(){
  if(top.frames.length > 0){
    top.frames[0].bNavigationEnabled = true;
  }else{
    top.frames.bNavigationEnabled = true;
  }
}

function disableNavigation(){
  if(top.frames.length > 0){
    top.frames[0].bNavigationEnabled = false;
  }else{
    top.frames.bNavigationEnabled = false;
  }
}

function isNav(){
  if(top.frames.length > 0){
    return top.frames[0].bNavigationEnabled;
  }else{
    return top.frames.bNavigationEnabled;
  }
  return true;
}

function setNextHref( p_href ){
  sNextHref = p_href;
}

function getNextHref() {
  return sNextHref;
}

/** If the save changes function exists, then call it. */
function doSave(){
  if (isNav()){
    hideDivs();
    var bContinue = true;
    if ( typeof saveChanges == "function" ){
      if ( typeof validatePage == "function" ){
        bContinue = validatePage();
      }
      if ( bContinue) {
        disableNavigation();
        saveChanges();
        // If the busy flag has not been set, then the routine has aborted
        // so enable navigation
        if ( !isBusy() ) enableNavigation();
      } else {
        enableNavigation();
      }
    } else {
      goURL( getNextHref() );
    }
  }
}

function rebuildNextHref(p_url, p_param, p_new_value){
  var sRval = "";
  var aUrl    = p_url.split("?");
  if (aUrl.length == 1){
    sRval = p_url + p_param + "=" + p_new_value;
  }else{
    var aParams = aUrl[1].split("&");
    sRval = aUrl[0] + "?";
    var sParams = "";
    var bFound = false;
    for (var i in aParams){
      if (aParams[i].indexOf(p_param+"=") == 0){
        sParams += (sParams.length>0?"&":"") + p_param + "=" + p_new_value;
        bFound = true;
      }else{
        sParams += (sParams.length>0?"&":"") + aParams[i];
      }
    }
    if (!bFound){
      sParams += (sParams.length>0?"&":"") + p_param + "=" + p_new_value;
    }
    sRval += sParams
  }
  return sRval;
}


function doCommonAction(action){
  if (isNav()){
    doAction(action);
  }
}

function getCommonNext(){
  if (isNav()){
    getNext();
  }
}

function getCommonPrev(){
  if (isNav()){
    getPrev();
  }
}


function doApplyFilter(p_form){

  if ( !isNav()) return;

  if ( typeof applyFilter == "function" ){
    applyFilter(p_form);
  }
}

function doClearFilter(p_page, p_form){
  if (isNav()){
    storeQueryDesc( p_page, "" );
    if ( typeof clearFilter == "function" ){
      
      if(typeof getObject("searchForm") == "object"){
        frmSaveQuery.p_set_id.value = ""; 
        frmSaveQuery.p_description.value = ""; 
        frmSaveQuery.p_global_flag.checked = false; 
        frmSaveQuery.p_default_flag.checked = false; 
      }
      clearFilter(p_form);
    }
    if ( typeof extraClearFilter == "function" ){
      extraClearFilter();
    }
  }
}

function toggleFilter(p_form, p_filter_row, p_apply_filter_td, p_clear_filter_td, p_table_id, p_tab){
  if (! isEmpty( p_form )){
    var formObj = getObject( p_form );
    if (typeof formObj=="object"){
      var rowObj = getObject(p_filter_row, formObj);
      var applyIconObj = getObject(p_apply_filter_td, formObj);
      var clearIconObj = getObject(p_clear_filter_td, formObj);
      if(typeof rowObj=="object" && typeof applyIconObj=="object"){
        if(rowObj.style.display=="none"){
          rowObj.style.display="inline";
          applyIconObj.style.display="inline";
          if(typeof clearIconObj=="object"){
            clearIconObj.style.display="inline";
          }
          if(! isEmpty( p_table_id )){
            tableHeightAdjust(p_filter_row, true, p_table_id);
            if(p_tab == "SEARCH" || p_tab == "GENERATE"){
              setFilterWidths(p_form);
            }
          }else{
            tableHeightAdjust(p_filter_row, true);
            if(p_tab == "SEARCH" || p_tab == "GENERATE"){
              setFilterWidths(p_form);
            }
          }
        } else {
          if(! isEmpty( p_table_id )){
            tableHeightAdjust(p_filter_row, false, p_table_id);
          }else{
            tableHeightAdjust(p_filter_row, false);
          }
          rowObj.style.display="none";
          applyIconObj.style.display="none";
          if(typeof clearIconObj=="object"){
            clearIconObj.style.display="none";
          }
        }
      }
    }
  }
}

function setFilterWidths(p_form){
  try{
    var formObj = getObject( p_form );
    if (typeof formObj=="object"){
      var dataObj = getObject('td1', formObj);
      var filterObj = getObject('p_filter_col', formObj);
      for (var i = 0; i < filterObj.length; i++){
        filterObj[i].size=parseInt(dataObj[i].offsetWidth/6, 0)+"";
      }
    }
  }
  catch(e){}
}

function filterKeyEvent(p_form, evt){
  evt = (evt)?evt:event;
  var charCode = (evt.which)?evt.which:evt.keyCode;
  if (charCode == 13){

    try {
      p_form.p_filter_col[0].blur();
      p_form.p_filter_col[0].focus();
    } catch (e) {}

    if (isNav()){
      doApplyFilter(p_form);
    }
    return false;
  }
  return true;
}

function goNextHref(){
  goURL( getNextHref() );
}

function setAutoSave( p_value ){
  bAutoSave = p_value;
}

function isAutoSaveOn(){
  return (bAutoSave || getUserParameter("AUTO_SAVE") == "1");
}

/** When changing tabs, this checks for changes, to allow the user to do certain things */
function navigatePage( p_href, p_autosave, p_do_not_save ){
  setNextHref("");
  if ( !isNav()) return;

  if ( typeof top.headerFrame.addHistory == "function") top.headerFrame.addHistory();

  if ( typeof validatePage == "function" || typeof saveChanges == "function" ){

    // Have there been changes to the page?
    if ( hasChanged() && bCheckUnload ) {
      // Is the page OK?
      if ( (p_autosave || isAutoSaveOn() ) || (getMainTab() == "SEARCH" && getSubTab() == "RESULTS") ) {
        setNextHref( p_href );
        doSave();

      } else if (p_do_not_save) {
        setNextHref( p_href );
        goNextHref();
      } else {
        setNextHref( p_href );
        confirmDialog(getMessage("[JS-016]"), "doSave();", "goNextHref()");
      }

    } else {
      // No changes have been made
      goURL(p_href);
    }

  // Just navigate away (no validatePage function exists)
  } else {
    goURL(p_href);
  }
}

/** Show a confirmation dialog */
function confirmDialog( p_message, p_yes_action, p_no_action, p_nobr){
  var theString;
  var message = p_nobr ? p_message : wrapText(p_message);
  var cancelString = getTerm('{NO}');
  hideDivs();

  cursorAuto(false);

  theString = "<TABLE><TR><TD><IMG src='"+getImage("IMG_CONFIRM")+"'></TD><TD NOWRAP CLASS=cTL>" + message + "</TD></TR></TABLE>";

  top.bodyFrame.confirmDivTitle.innerHTML="Confirm";
  top.bodyFrame.confirmDiv.style.height = 50 + (countBR(message) * 10);
  top.bodyFrame.confirmDiv.style.width = 400
  top.bodyFrame.confirmDivContents.innerHTML=theString;

  top.bodyFrame.confirmYesButton.innerHTML=   "<TABLE><TR><TD ALIGN=CENTER CLASS=mainButton onMouseOver=\"crPoint(this);\" onMouseOut=\"crAuto(this);\" onClick='"+p_yes_action+";disabled = true';><A>"+getTerm("{YES}")+"</A></TD></TR></TABLE>";

  if ( typeof p_no_action == "string" && !isEmpty(p_no_action) ){
    top.bodyFrame.confirmNoButton.innerHTML="<TABLE><TR><TD ALIGN=CENTER CLASS=mainButton onMouseOver=\"crPoint(this);\" onMouseOut=\"crAuto(this);\" onClick='"+p_no_action+";disabled = true';><A>"+getTerm("{NO}")+"</A></TD></TR></TABLE>";
    cancelString = getTerm('{CLOSE}');
  } else {
    top.bodyFrame.confirmNoButton.innerHTML="";
  }
  top.bodyFrame.confirmCancelButton.innerHTML="<TABLE><TR><TD ALIGN=CENTER CLASS=mainButton onMouseOver=\"crPoint(this);\" onMouseOut=\"crAuto(this);\" onClick=\"enableNavigation();hideDiv(confirmDiv);clearConfirm();\"><A id=\"close\">"+cancelString+"</A></TD></TR></TABLE>";


  displayDiv(top.bodyFrame.confirmDiv);
}

function countBR(msgString){

  var tempString = msgString;
  var lineCount = 0;
  var pos;
  while (tempString.indexOf("<BR>") != -1){
    if (tempString.indexOf("<BR>") + 4 < tempString.length){
      tempString = tempString.substring(tempString.indexOf("<BR>") + 4, tempString.length);
    }else{
      tempString = "";
    }
    lineCount ++;
  }

  return lineCount;

}

function clearConfirm(){
  top.bodyFrame.confirmDivContents.innerHTML = "";
}

function wrapText(strVal){
  var nMaxChars = 80;
  var nRemoveSpace = 1;
  var sBreakChar = "<BR>";

  var rval = strVal;

  var aStr = strVal.split("<BR>");

  for (var i = 0; i < aStr.length; i++){
    if (aStr[i].length > nMaxChars){
      var nBreakPos = aStr[i].substring(0, nMaxChars-1).lastIndexOf(" ");
      if (nBreakPos == -1){
        nBreakPos = nMaxChars-2;
        sBreakChar = "-<BR>";
        nRemoveSpace = 0;
      }
      aStr[i] = aStr[i].substring(0, nBreakPos) + sBreakChar + aStr[i].substring(nBreakPos+nRemoveSpace);
      aStr[i] = wrapText(aStr[i]);
    }
  }

  return aStr.join("<BR>");
}

/** Show an alert dialog. */
function alertDialog( p_message, p_append, p_fields, p_refresh, p_disable_hotkey ){
  disableNavigation();

  var msgString = getMessage(p_message);

  if ( p_fields != null){
    msgString = msgString + p_fields;
  }

  var replaceChars   = new Array("\n",   "\t", "\r");     // List of values to replace
  var withChars      = new Array("<BR>",  "",    "");        // List of values to replace with
  var re;

  for (var i = 0; i < replaceChars.length; i++){
    if (msgString.indexOf(replaceChars[i]) != -1){
      re = new RegExp("\\" + replaceChars[i], "g");
      msgString = msgString.replace(re, withChars[i]);
    }
  }

  msgString = wrapText(msgString);

  var lineCount = countBR(msgString);

  var theString;
  var doStd = false;

  hideDivs();

  cursorAuto(false);

  if (p_append){
    var confirmMsg = getObject("confirmMsg");
    if (typeof confirmMsg == "object"){
      confirmMsg.innerHTML += "<BR><HR>"+msgString;
      lineCount = countBR(confirmMsg.innerHTML);
    }else{
      doStd = true;
    }
  }

  if (!p_append || doStd){
    theString = "<TABLE><TR><TD><IMG src='"+getImage("IMG_INFORM")+"'></TD><TD ID=confirmMsg NOWRAP CLASS=cTL>" + msgString + "</TD></TR></TABLE>";
    top.bodyFrame.confirmDivContents.innerHTML=theString;
  }

  top.bodyFrame.confirmDiv.style.height = 50 + (lineCount * 10);
  top.bodyFrame.confirmDiv.style.width = 400;

  var sClick = "enableNavigation();hideDiv(confirmDiv);clearConfirm();";
  if(p_refresh){
    sClick = "top.bodyFrame.location.reload();";
  }
  top.bodyFrame.confirmYesButton.innerHTML = "";
  top.bodyFrame.confirmNoButton.innerHTML = "";
  top.bodyFrame.confirmCancelButton.innerHTML="<TABLE><TR><TD ALIGN=CENTER CLASS=mainButton onMouseOver=\"crPoint(this);\" onMouseOut=\"crAuto(this);\" onClick=\""+sClick+"\"><A id=\"close\">"+getTerm('{CLOSE}')+"</A></TD></TR></TABLE>";
  top.bodyFrame.confirmDivTitle.innerHTML="Alert";

  displayDiv(top.bodyFrame.confirmDiv);

  // Use the offsets to correctly center the message
  top.bodyFrame.confirmDiv.style.height = top.bodyFrame.confirmDiv.offsetHeight;
  top.bodyFrame.confirmDiv.style.width  = top.bodyFrame.confirmDiv.offsetWidth;

  displayDiv(top.bodyFrame.confirmDiv);
  if ( p_disable_hotkey ) bDisableHotKey = true;

}

/** Show an about dialog. */
function aboutDialog(){
  var theString;
  hideDivs();

  cursorAuto();

  var startTag = "<TR><TD NOWRAP ALIGN=CENTER>";
  var endTag = "</TD></TR>";

  theString = "<TABLE WIDTH=100%>";
  theString += startTag + "<IMG onDblClick='toggleDebug()' src='"+getImage("IMG_MP_SUITE")+"'>" + endTag;
  theString += startTag + "<H3>Version 4.0</H3>" + endTag;
  theString += "<TR><TD NOWRAP ALIGN=CENTER CLASS=cTD>Designed and Written By</TD></TR>";
  theString += "<TR><TD><MARQUEE height=50 scrolldelay=150 style='margin:0' direction=up><TABLE ALIGN=CENTER>";
  theString += startTag + "<H4>Anders Archibald</H4>" + endTag;
  theString += startTag + "<H4>Graham Coy</H4>"       + endTag;
  theString += startTag + "<H4>Susan Frame</H4>"      + endTag;
  theString += startTag + "<H4>Thomas Sanders</H4>"   + endTag;
  theString += startTag + "<H4>Keith Simons</H4>"     + endTag;
  theString += startTag + "<H4>Dave Skinner</H4>"     + endTag;
  theString += "</TABLE></MARQUEE></TD></TR>";
  theString += "</TABLE>";

  top.bodyFrame.confirmDiv.style.left = 300;
  top.bodyFrame.confirmDiv.style.top = 100;
  top.bodyFrame.confirmDivTitle.innerHTML="About";
  top.bodyFrame.confirmCancelButton.innerHTML="<TABLE><TR><TD ALIGN=CENTER CLASS=mainButton onMouseOver=\"crPoint(this);\" onMouseOut=\"crAuto(this);\" onClick=\"enableNavigation();hideDiv(confirmDiv);clearConfirm();\"><A id=\"close\">"+getTerm('{CLOSE}')+"</A></TD></TR></TABLE>";
  top.bodyFrame.confirmDiv.style.height = 200
  top.bodyFrame.confirmDiv.style.width = 400
  top.bodyFrame.displayDiv(top.bodyFrame.confirmDiv);

  top.bodyFrame.confirmDivContents.innerHTML=theString;

}

function toggleDebug(){
  top.saveFrame.location.href="debug.p_toggle_debug?p_session="+session;
}

/** Open the Calendar Dialog.
  * @param    p_form_id   The Form the column is in
  * @param    p_column_id The ID of the column to be changed
  * @param    p_row       The Row the column is on
  */
function calendarDialog( p_form_id, p_column_id, p_row, p_onchange ){

  if (isNav()){
    var dCurDate = new Date();
    hideDivs();

    try{
      var colObj = getObject( p_column_id, p_form_id );
      if (isDate(colObj, false, true)){
        var currValue = "";
        if ( !isEmpty(p_row) && 1*p_row >= 0 ){
          currValue = colObj[p_row].value;
        } else {
          currValue = colObj.value;
        }
        if (!isEmpty(currValue)){
          var dA = currValue.split('-');
          dCurDate = new Date(dA[2], getMonthNum(dA[1])-1, dA[0]);
        }
      }
    }catch (e){}

    allowSetChanged(false);

    var theString  = '<form name="frmCalendarSample" method="post" action="">';
    theString     += '<input type="hidden" name="calSelectedDate" value="">';

    theString     += '<table align=center cellspacing=5 cellpadding=0 border=0>';
    theString     += '<tr>';
    theString     += '<td>';
    theString     += '</td>';
    theString     += '<td>';
    theString     += '<input name=tbSelMonth size=8 onkeydown="doMonthKey();" onChange="fUpdateCal(frmCalendarSample.tbSelYear.value, frmCalendarSample.tbSelMonth.value)">';
    theString     += '<A TABINDEX=-1 Href="javascript://" onClick="doCalendarDropDown();return false;">';
    theString     += '<IMG CLASS=fieldImage BORDER=0 src='+getImage("IMG_FIELD_SEARCH")+' ALT="">';
    theString     += '</A>';
    theString     += '</td>';
    theString     += '<td>';
    theString     += '<table cellspacing=0 cellpadding=0 border=0>';
    theString     += '<tr>';
    theString     += '<td valign="bottom">';
    theString     += '<A TABINDEX=-1 Href="javascript://"><IMG ID=imgNextMonth src="'+getImage("IMG_CAL_UP")+'" style="margin-right:5" onClick="scrollNextMonth();return false;" ALT="Next"></A>';
    theString     += '</td>';
    theString     += '</tr>';
    theString     += '<tr>';
    theString     += '<td valign="top">';
    theString     += '<A TABINDEX=-1 Href="javascript://"><IMG ID=imgPrevMonth style="margin-right:5" src="'+getImage("IMG_CAL_DOWN")+'" onClick="scrollPrevMonth();return false;" ALT="Prev"></A>';
    theString     += '</td>';
    theString     += '</tr>';
    theString     += '</table>';
    theString     += '</td>';
    theString     += '<td>';
    theString     += '<table align="center" cellspacing=0 cellpadding=0 border="0">';
    theString     += '<tr>';
    theString     += '<td>';
    theString     += '<input isInteger=true type="text" maxlength="4" name="tbSelYear" size="4" onkeydown="doYearKey();" onchange="isNumber(this, 0, 9999);fUpdateCal(frmCalendarSample.tbSelYear.value, frmCalendarSample.tbSelMonth.value)">';
    theString     += '</td>';
    theString     += '<td>';
    theString     += '<table align="center" cellspacing=0 cellpadding=0 border=0>';
    theString     += '<tr>';
    theString     += '<td valign="bottom">';
    theString     += '<A TABINDEX=-1 Href="javascript://"><IMG ID=imgNextYear align="bottom" style="margin-right:5" src="'+getImage("IMG_CAL_UP")+'" onClick="scrollNextYear();return false;" ALT="Next"></A>';
    theString     += '</td>';
    theString     += '</tr>';
    theString     += '<tr>';
    theString     += '<td valign="top">';
    theString     += '<A TABINDEX=-1 Href="javascript://"><IMG ID=imgPrevYear align="top" style="margin-right:5" src="'+getImage("IMG_CAL_DOWN")+'" onClick="scrollPrevYear();return false;" ALT="Prev"></A>';
    theString     += '</td>';
    theString     += '</tr>';
    theString     += '</table>';
    theString     += '</td>';
    theString     += '</tr>';
    theString     += '</table>';
    theString     += '</td>';
    theString     += '<td>';
    theString     += '</td>';
    theString     += '</tr>';
    theString     += '<tr>';
    theString     += '<td align="middle" colspan="4" ID=calendarContents>';
    theString     += '</td>';
    theString     += '</tr>';
    theString     += '</table>';
    theString     += '</form>';
    theString     += '</BODY>';
    theString     += '</HTML>';


    top.bodyFrame.formDivTitle.innerHTML="Calendar";
    top.bodyFrame.formDiv.style.height = 200;
    top.bodyFrame.formDiv.style.width = 200;
    displayDiv(formDiv);
    top.bodyFrame.formDivContents.innerHTML=theString;

    fDrawCal(dCurDate.getFullYear(), dCurDate.getMonth()+1, 20, 20, p_form_id, p_column_id, p_row, 3, p_onchange, dCurDate.getDate());

    frmCalendarSample.tbSelMonth.value = aMonths[dCurDate.getMonth()];

    frmCalendarSample.tbSelYear.value = dCurDate.getFullYear();
    frmCalendarSample.tbSelMonth.focus();
  }
}

function doCalendarDropDown() {
  if( isNav() ){
    top.saveFrame.location.href=encode_url("ui_menu.p_drop_down?p_session="+session+"&p_column=tbSelMonth&p_id=CAL_MONTHS&p_rownum=&p_term=&p_form=frmCalendarSample&p_js_rownum=&p_all_record_query=TRUE&p_do_onchange=false&p_multiple=0");
  }
}

function getMonthNo(p_month){
  var month = 0;
  for (var i = 0; i < aMonths.length; i++){
    if(aMonths[i] == frmCalendarSample.tbSelMonth.value ){
      var month = i;
      break;
    }
  }
  return month;
}

function scrollPrevMonth(){
  //Get the year listing
  var year = frmCalendarSample.tbSelYear.value;
  //get the month number
  var month = getMonthNo(frmCalendarSample.tbSelMonth.value);

  //check to see if the month is january
  if (month != 0) {
    fUpdateCal(parseInt(frmCalendarSample.tbSelYear.value), aMonths[month - 1]);
    frmCalendarSample.tbSelMonth.value = aMonths[month - 1];
  }else{
    fUpdateCal(parseInt(frmCalendarSample.tbSelYear.value) - 1, aMonths[month + 11]);
    frmCalendarSample.tbSelMonth.value = aMonths[month + 11];
    if(typeof year != "undefined"){
      frmCalendarSample.tbSelYear.value = parseInt(year) - 1;
    }
  }
}

function scrollNextMonth(){
  //Get the year listing
  var year = frmCalendarSample.tbSelYear.value;
  //get the month number
  var month = getMonthNo(frmCalendarSample.tbSelMonth.value);

  //check to see if the month is december
  if (month != 11) {
    fUpdateCal(parseInt(frmCalendarSample.tbSelYear.value), aMonths[month + 1]);
    frmCalendarSample.tbSelMonth.value = aMonths[month + 1];
  }else{
    fUpdateCal(parseInt(frmCalendarSample.tbSelYear.value) - 1, aMonths[month - 11]);
    frmCalendarSample.tbSelMonth.value = aMonths[month - 11];
    if(typeof year != "undefined"){
      frmCalendarSample.tbSelYear.value = parseInt(year) + 1;
    }
  }
}


function scrollPrevYear(){
  var year = frmCalendarSample.tbSelYear.value;

  //get the month number
  var month = getMonthNo(frmCalendarSample.tbSelMonth.value);

  frmCalendarSample.tbSelYear.value = parseInt(year) - 1;
  fUpdateCal(frmCalendarSample.tbSelYear.value, aMonths[month])
}

function scrollNextYear(){
  var year = frmCalendarSample.tbSelYear.value;

  //get the month number
  var month = getMonthNo(frmCalendarSample.tbSelMonth.value);

  frmCalendarSample.tbSelYear.value = parseInt(year) + 1;
  fUpdateCal(frmCalendarSample.tbSelYear.value, aMonths[month])
}

function doYearKey(evt){
  evt = (evt)?evt:event;
  var charCode = (evt.which)?evt.which:evt.keyCode;
  if (charCode == 38){
    scrollNextYear();
    return false;
  }else if (charCode == 40){
    scrollPrevYear();
    return false;
  }
  return true;
}

function doMonthKey(evt){
  evt = (evt)?evt:event;
  var charCode = (evt.which)?evt.which:evt.keyCode;
  if (charCode == 38){
    scrollNextMonth();
    return false;
  }else if (charCode == 40){
    scrollPrevMonth();
    return false;
  }
  return true;
}

function openExport( p_session, p_page, p_key, p_query, p_query_params, p_table ){
  hideDivs();
  setExportQuery(isEmpty(p_query)?"":p_query);
  setExportParams(isEmpty(p_query_params)?"":p_query_params);
  var sTable = (isEmpty(p_table)?"":p_table);
  var sSession = (isEmpty(p_session)?session:p_session);

  var whatExport = '{DATA_TABLE}';

  var theString = "<TABLE align=center cellspacing=2 cellpadding=2 border=0>";
  theString +=    "<TR><TD NOWRAP><A Href=\"javascript:void(0);\" onClick=\"exportRSetExcel('"+sSession+"', '"+p_page+"', '"+p_key+"', '"+sTable+"');return false;\">"+getMessage('[GEN-EXPORT$'+whatExport+'@{MS_EXCEL}]')+"</A></TD></TR>";
  theString +=    "<TR><TD NOWRAP><A Href=\"javascript:void(0);\" onClick=\"exportRSetWord('"+sSession+"', '"+p_page+"', '"+p_key+"', '"+sTable+"');return false;\">"+getMessage('[GEN-EXPORT$'+whatExport+'@{MS_WORD}]')+"</A></TD></TR>";
  theString +=    "<TR><TD NOWRAP><A Href=\"javascript:void(0);\" onClick=\"exportRSetPrint('"+sSession+"', '"+p_page+"', '"+p_key+"', '"+sTable+"');return false;\">"+getMessage('[GEN-EXPORT$'+whatExport+'@{PRINTER}..]')+"</A></TD></TR>";
  theString +=    "</TABLE>";

  top.bodyFrame.divTitle.innerHTML="Export";
  top.bodyFrame.miscDiv.style.height = 50
  top.bodyFrame.miscDiv.style.width = 200
  displayDiv(miscDiv);

  top.bodyFrame.divContents.innerHTML=theString;

}
/** Export the Result Set */
function exportRSetExcel( p_session, p_page, p_key, p_table ){
  var dest_doc = top.saveFrame.document;
  var aStr = "<HTML><HEAD></HEAD><BODY>"
           + "<FORM ACTION=ui_export.p_export_excel NAME=frmSave METHOD=POST>"
           + f_save( "p_session", ""+p_session)
           + f_save( "p_page_id", ""+p_page)
           + f_save( "p_key",     ""+p_key)
           + f_save( "p_query",   ""+getExportQuery())
           + f_save( "p_params",  ""+getExportParams())
           + f_save( "p_table",   ""+p_table)
           + "</FORM></BODY></HTML>";
  dest_doc.open();
  dest_doc.write(aStr);
  dest_doc.frmSave.submit();
}

/** Export the Result Set */
function exportRSetWord( p_session, p_page, p_key, p_table ){
  var dest_doc = top.saveFrame.document;
  var aStr = "<HTML><HEAD></HEAD><BODY>"
           + "<FORM ACTION=ui_export.p_export_word NAME=frmSave METHOD=POST>"
           + f_save( "p_session", ""+p_session)
           + f_save( "p_page_id", ""+p_page)
           + f_save( "p_key",     ""+p_key)
           + f_save( "p_query",   ""+getExportQuery())
           + f_save( "p_params",  ""+getExportParams())
           + f_save( "p_table",   ""+p_table)
           + "</FORM></BODY></HTML>";
  dest_doc.open();
  dest_doc.write(aStr);
  dest_doc.frmSave.submit();
}

/** Export the Result Set */
function exportRSetPrint( p_session, p_page, p_key, p_table ){
  var dest_doc = top.saveFrame.document;
  var aStr = "<HTML><HEAD></HEAD><BODY>"
           + "<FORM ACTION=ui_export.p_export_print NAME=frmSave METHOD=POST>"
           + f_save( "p_session", ""+p_session)
           + f_save( "p_page_id", ""+p_page)
           + f_save( "p_key",     ""+p_key)
           + f_save( "p_query",   ""+getExportQuery())
           + f_save( "p_params",  ""+getExportParams())
           + f_save( "p_table",   ""+p_table)
           + "</FORM></BODY></HTML>";
  dest_doc.open();
  dest_doc.write(aStr);
  dest_doc.frmSave.submit();
}


function maximise( p_div ){
  var div = getObject( p_div );
  var chart = getObject( "Chart" );

  div.style.left = 50;
  div.style.top = 50;

  div.style.width = document.body.offsetWidth - 100;
  div.style.height = document.body.offsetHeight - 100;

  if ( typeof chart == "object" ){
    chart.style.left = 50;
    chart.style.top = 50;

    chart.style.width = document.body.offsetWidth - 100;
    chart.style.height = document.body.offsetHeight - 100;

  }
}

function minimise( p_div ){
  var div = getObject( p_div );
  var chart = getObject( "Chart" );

  div.style.left = 300;
  div.style.top = 100;

  div.style.width = 400;
  div.style.height = 300;

  if ( typeof chart == "object" ){
    chart.style.left = 300;
    chart.style.top = 100;

    chart.style.width = 400;
    chart.style.height = 300;

  }

}

/**
 * set the screen id used to populate the reports popup
 * @param newScreen the new screen id
 */
function setReportScreen(newScreen){
  sReportScreenID = newScreen;
}

/**
 * set the report parameter list to be used for the new screen
 * @param newParameters the new parameter list.
 */
function setReportParameters(newParameters){
  sReportParameters = newParameters;
}

// Show the Reports "div"
function openReports() {
//  var div = getObject("divReports");
  var div = getObject("miscDiv");

  if (div != "undefined"){
    var dest_doc = top.saveFrame.document;

    var aStr = "<HTML><HEAD></HEAD><BODY>\r\n";
    aStr += "<FORM ACTION=ui_portal_report.p_built_report_div NAME=write_form METHOD=POST>\r\n";
    aStr += f_save("p_session",         session);
    aStr += f_save("p_screen_id",       sReportScreenID);
    aStr += f_save("p_parameter_list",  sReportParameters);
    aStr += "</FORM></BODY></HTML>";
    dest_doc.open();
    dest_doc.write(aStr);
    dest_doc.write_form.submit();

  }
}

/**
 * Function to show the miscDiv
 * @param titleString - the title for the div
 */
function showMiscDiv(titleString, p_width, p_height){
  hideDivs();
  var div = getObject("miscDiv");
  top.bodyFrame.divTitle.innerHTML=titleString;

  if (typeof p_height == "undefined"){
    top.bodyFrame.miscDiv.style.height = 50;
  }else{
    top.bodyFrame.miscDiv.style.height = p_height;
  }

  if (typeof p_width == "undefined"){
    top.bodyFrame.miscDiv.style.width = 300;
  }else{
    top.bodyFrame.miscDiv.style.width = p_width;
  }

  displayDiv(div);
}

/**
 * Function to hide the miscdiv
 * @return false
 */
function hideMiscDiv(){
  hideDiv( top.bodyFrame.miscDiv );
  return false;
}

var popupWindow;
function openReport(type, href_string, title){
  if (type == "JAVA"){

  }else{
    if (type == "WEBI6"){
      var encoded_href = href_string;

      var chars = new Array("&",     "?");
      var codes = new Array("AMPERSAND", "QUESTION");
      var re;

      for (var i = 0; i < chars.length; i++){
        if (encoded_href.indexOf(chars[i]) != -1){
          re = new RegExp("\\" + chars[i], "g");
           encoded_href = encoded_href.replace(re, codes[i]);
        }
      }
      popupWindow = window.open("ecw_main.p_portal_login?p_session='||p_session||CHR(38)||'p_login_href=http://195.153.23.105/BOSample/login.aspQUESTIONSName=KEITHSAMPERSANDSPwd=snomis05'||CHR(38)||'p_report_href="+encoded_href, "title", "resizable=yes,width="+(screen.width-110)+",height="+(screen.height-220)+",left=50,top=50;");
    }else{
      popupWindow = window.open(href_string, "title", "resizable=yes,width="+(screen.width-110)+",height="+(screen.height-220)+",left=50,top=50;");
    }
    popupWindow.focus();
  }
}

function setHdrMsg( p_new_msg ){
  if (typeof top.headerFrame != "undefined"){
    //If a message is present display it else display
    //the screen title.
    if ( typeof p_new_msg!="undefined"){
      if(p_new_msg != top.bodyFrame.screenTitle){
        if (p_new_msg != top.headerFrame.tdMsgTitle.innerHTML){
          top.headerFrame.tdMsgTitle.innerHTML = p_new_msg;
        }
      }else{
        top.headerFrame.tdMsgTitle.innerHTML = "";
      }
    }

    if ( !isEmpty(top.bodyFrame.screenTitle)){
      top.headerFrame.tdScreenTitle.innerHTML = top.bodyFrame.screenTitle;
    }
  }
}

function setHdrMsgRecord( p_new_msg ){
  if (typeof top.headerFrame != "undefined"){
    if (typeof top.headerFrame.tdMsgTitle != "undefined"){
      top.headerFrame.tdMsgTitle.innerHTML = p_new_msg;
    }
  }
}

/** go to a URL */
function goURL( p_href ){
  if (!isEmpty(p_href)){
    cursorWait();
    disableNavigation();
    top.bodyFrame.location.href = p_href;
  }
}

/** go to a URL using the save frame, possibly saving changes first */
function goSaveURL( p_href, p_autosave ){
  cursorWait();
  if (p_autosave && hasChanged() && bCheckUnload && typeof saveChanges == "function") {
    if (typeof validatePage != "function" || validatePage()) {
      sNextSaveHref = p_href;
      saveChanges();
    }
  } else {
    top.saveFrame.location.href = p_href;
  }
}

/** Open the whats this dialog */
function whtTs( p_session, p_page, p_tab, p_field, p_value ){
  if (getUserParameter("DOUBLE_CLICK_HELP") == "1"){
    top.saveFrame.location.href="ui_menu.p_whats_this?p_session="+p_session+"&p_page="+p_page+"&p_tab="+p_tab+"&p_field="+p_field+"&p_value="+p_value;
  }
}

function openSearch( p_session, p_column, p_disabled, p_form, p_rownum, p_full_id, p_lookup_id, p_term, p_long_text_key ){
  if( isNav() ){
    top.saveFrame.location.href=encode_url( "ui_menu.p_menu?p_session="+p_session+"&p_column=p_"+p_column+"&p_disabled="+p_disabled+"&p_form="+p_form+"&p_rownum="+p_rownum+"&p_full_id="+p_full_id+"&p_lookup_id="+p_lookup_id+"&p_term="+p_term+"&p_long_text_key="+p_long_text_key );
  }
}

/** Change the users current language. */
function changeLanguage( p_session, p_new_language ){
  top.saveFrame.location.href="ui_main.p_change_language?p_session="+p_session+"&p_language="+p_new_language;
}

/** Navigate fields on a key press */
function navKey( p_obj, p_row, p_rowref ){

  var obj = getObject( p_obj.id );
  var nRow = parseInt(p_row);
  var doMove = false;
  var down = false;
  var newRowHidden = true;
  var rowObj;

  switch (event.keyCode){
    case 40: //Down Arrow
      nRow = nRow;
      doMove = true;
      down = true;
      break;
    case 38: //Up Arrow
      nRow = nRow - 2;
      doMove = true;
      break;
  }

  if ( doMove && typeof obj[nRow] == "object" ){
    try {
      rowObj = getObject(p_rowref+(nRow+1));
      if (typeof rowObj != "undefined"){
        newRowHidden = (rowObj.style.display=="none");
      }
      obj[nRow].focus();
      if (typeof rowObj != "undefined"){
        setSelectedRow(nRow+1, p_rowref);
      }
    } catch (e){
      if ( typeof newRow == "function" && down ){
        if (newRowHidden){
          newRow(p_rowref);
        }
        try {
          obj[nRow].focus();
          setSelectedRow(nRow+1, p_rowref);
        } catch (e){
        }
      }
    }
    if (typeof rowObj != "undefined"){
      if (rowObj.onclick != null){
        var functionCall = "" + rowObj.onclick;
        eval(functionCall.substring(functionCall.indexOf("{")+1, functionCall.lastIndexOf("}")-1 ));
      }
    }
  }


  return true;

}

/**
 * function to control keyup events
 * @param   the current field
 * @return  true
 */
function hotKey(p_obj, p_row, p_rowref, p_search){
  if ( bDisableHotKey ){
    bDisableHotKey = false;
    return true;
  }

  if (event.ctrlKey && event.altKey){
    switch (event.keyCode){
      case 37: // Left Arrow
        if (typeof p_obj == "object"){
          p_obj.blur();
        }else if ( typeof getCommonPrev == "function" ){
          getCommonPrev();
        }
        break;
      case 39: // Right Arrow
        if (typeof p_obj == "object"){
          p_obj.blur();
        }else if ( typeof getCommonNext == "function" ){
          getCommonNext();
        }
        break;
      case 67: // C (copy)
        if (typeof p_obj == "object" && !isEmpty(p_row)){
          setRowRef(p_rowref);
          p_obj.blur();
        }else if (typeof copyRow == "function"){
          copyRow(getRowRef());
        }
        break;
      case 70: // F (find)
        if (typeof openSearch == "function" && typeof p_search != "undefined"){
          if (p_search[0] == "1"){
            openSearch(parseInt(p_search[1], 10), p_search[2], p_search[3], p_search[4], p_search[5], p_search[6], p_search[7], p_search[8], p_search[9]);
          }else if (p_search[0] == "2"){
            if (isNav()) top.saveFrame.location.href=encode_url("ui_menu.p_drop_down?p_session="+p_search[1]+"&p_column=p_"+p_search[2]+"&p_id="+p_search[7]+"&p_rownum="+p_search[5]+"&p_term="+p_search[8]+"&p_form="+p_search[4]+"&p_js_rownum="+p_search[10]+"&p_do_onchange="+p_search[11]);
          }else if (p_search[0] == "3"){
            if (isNav()) openLongText(p_search[9], p_search[3], p_search[4], p_search[5]);
          }else if (p_search[0] == "4"){
            if (isNav()) top.saveFrame.location.href=encode_url("ui_menu.p_drop_down?p_session="+p_search[1]+"&p_column=p_"+p_search[2]+"&p_id="+p_search[7]+"&p_js_rownum="+p_search[10]+"&p_rownum="+p_search[5]+"&p_term="+p_search[8]+"&p_do_onchange="+p_search[11]);
          }else if (p_search[0] == "5"){
            calendarDialog(p_search[4], "p_"+p_search[2], p_search[5], p_search[11]);
          }else{
            alertDialog("Unknown search type");
          }
        }
        break;
      case 78: // N (new row)
        if (typeof p_obj == "object"){
          setRowRef(p_rowref);
        }else if (typeof newRow == "function"){
          newRow(getRowRef());
        }
        break;
      case 81: // Q (quit)
        if (typeof p_obj == "object"){
          p_obj.blur();
          setRowRef(p_rowref);
        }else if ( typeof doneExpanded == "function" ){
          doneExpanded(getRowRef());
        }
        break;
      case 83: // S (save)
        if (typeof p_obj == "object"){
          p_obj.blur();
        }else if ( typeof doSave == "function" ){
          doSave();
        }
        break;
      default:
        break;
    }
  }else if (event.keyCode == 13){ // Enter
    if (typeof top.bodyFrame == "object"){
      if (typeof top.bodyFrame.confirmDiv == "object" && top.bodyFrame.confirmDiv.style.display == "inline" &&
          typeof top.bodyFrame.confirmCancelButton == "object" && typeof top.bodyFrame.confirmCancelButton.innerHTML != ""){

        enableNavigation();
        hideDiv(top.bodyFrame.confirmDiv);
        clearConfirm();
      }else if (typeof top.bodyFrame.errorDiv == "object" && top.bodyFrame.errorDiv.style.display == "inline" &&
                typeof top.bodyFrame.errOkButton == "object" && typeof top.bodyFrame.errOkButton.innerHTML != ""){

        enableNavigation();
        hideDiv(top.bodyFrame.errorDiv);
      }
    }
  }
  return true;
}

var rowRef;
function setRowRef(p_rowref){
  rowRef = p_rowref;
}

function getRowRef(){
  return rowRef;
}


/** Set the calendar value */
function setCalValue( p_form, p_column, p_row, p_value, p_do_onchange){
  var colObj = getObject( p_column, p_form );
  setColumnValue( colObj, p_row, p_value, true );
  if (p_do_onchange){
    if (isEmpty(p_row)){
      doOnChange(colObj, p_row, p_form);
    }else{
      doOnChange(colObj[p_row], p_row, p_form);
    }
  }
}

/** Enable a column, using the passed in class as the new class for rendering */
function enableColumn( p_column, p_class ){
  p_column.disabled = false;
  p_column.readOnly = false;
  p_column.className = p_class;
}

/** Disable a column */
function disableColumn( p_column, p_clear, p_set_class, p_class ){
  var bClear = true;
  var bSetClass = true;
  var sClass = "disabled";
  if ( typeof p_clear != "undefined" ) bClear = p_clear;
  if ( typeof p_set_class != "undefined" ) bSetClass = p_set_class;
  if ( typeof p_class != "undefined" ) sClass = p_class;
  p_column.disabled = true;
  p_column.readOnly = true;

  if ( bSetClass ) p_column.className = sClass;
  if ( bClear ) p_column.value = "";
}

/********************************/
/** The onBlur Event */
function ob(obj, options){
  var white = ((options & 1)==1);

  if ( white ){
    obj.style.background="white";
  }
}

/** The onFocus event */
function of(obj, options ){
  var highlight   = ((options & 1)==1);
  var notNav      = ((options & 2)==2);
  var doBlur      = ((options & 4)==4);

  if ( highlight ){
    if ( isNav() ) {obj.style.background="#F5F0D5";} else { obj.blur(); }
  }

  if ( notNav ){
    if ( !isNav() ) { obj.blur(); }
  }

  if ( doBlur ){
    obj.blur();
  }
}

/** Unchecks all other checkboxes in this
    column. */
function uncheckBoxes(p_obj, p_row){
  var boxes = getObject(p_obj.name);

  if (!isEmpty(boxes)) {
    for (i=0; i<boxes.length; i++){
      if (i != p_row){
        if (boxes[i].checked){
          setChanged(p_obj, p_row);
        }
        boxes[i].checked = false;
      }
    }
  }
}

function splitSearchField(p_old_value){
  var re;
  var searchPrefix = "";
  var rval = new Array();

  if (p_old_value.indexOf("<") == 0){
    if (p_old_value.indexOf(">") == 1){
      searchPrefix = "<>";
      re = new RegExp("\\" + searchPrefix, "g");
    }else if(p_old_value.indexOf("=") == 1){
      searchPrefix = "<=";
      re = new RegExp("\\" + searchPrefix, "g");
    }else{
      searchPrefix = "<";
      re = new RegExp("\\" + searchPrefix, "g");
    }
  }else if(p_old_value.indexOf(">") == 0){
    if(p_old_value.indexOf("=") == 1){
      searchPrefix = ">=";
      re = new RegExp("\\" + searchPrefix, "g");
    }else{
      searchPrefix = ">";
      re = new RegExp("\\" + searchPrefix, "g");
    }
  }else if(p_old_value.indexOf("=") == 0){
    searchPrefix = "=";
    re = new RegExp("\\" + searchPrefix, "g");
  }

  rval[0] = p_old_value.replace(re, "");
  if (p_old_value == ""){
    searchPrefix = "";
  }
  rval[1] = searchPrefix

  return rval;
}

/** The onClick event */
function oc( obj, options, p_row, p_ref ){
  doChanged   = ((options & 1)==1);
  doSetRow    = ((options & 2)==2);
  doCheckBoxUnique = ((options & 64)==64);

  if ( doChanged ){
    setChanged(obj, p_row);
    doChangeShare(obj);
  }

  if ( doSetRow ){
    setSelectedRow(p_row+1, p_ref);
  }

  if (doCheckBoxUnique && (p_row >= 0) && obj.checked){
    uncheckBoxes(obj, p_row);
  }
}


/** The onChangeEvent */
function och( obj, options, p_row, p_upper, p_lower){
  doChanged        = ((options & 1)==1);
  doUCase          = ((options & 2)==2);
  doDate           = ((options & 4)==4);
  doNumber         = ((options & 8)==8);
  doDuration       = ((options & 16)==16);
  doDurationReport = ((options & 32)==32);
  isMandatory      = ((options & 128)==128);
  doKeyField       = ((options & 256)==256);
  isColour         = ((options & 512)==512);
  doSearchFlag     = ((options & 1024)==1024);
  doTime           = ((options & 2048)==2048);
  doSearchMode     = ((options & 4096)==4096);
  incTime          = ((options & 8192)==8192);

  if (doKeyField){ // Used for fields that the invalid characters are to be stripped from
                   // but the changed flag is not to be set. ie. the quick find field.
    remove_invalid_characters(obj, true, p_row)
  } else {
    if ( doChanged ){
      remove_invalid_characters(obj, isMandatory, p_row)
      setChanged(obj, p_row);
    }

    var searchPrefix = "";
    var isValid=true;
    if (doSearchMode && !doSearchFlag){
      var splitSearch = splitSearchField(obj.value);
      obj.value = splitSearch[0];
      searchPrefix = splitSearch[1];
    }

    if ( doUCase ){
      obj.value=uCase(obj.value);
    }

    if ( doDate ){
      var suppressDateErrors = doSearchMode && !doSearchFlag && isEmpty(searchPrefix)
      // i.e. For table-filter input, suppressDateErrors true for LIKE (no prefix).
      var useTime = incTime && !(doSearchMode && !doSearchFlag) // do not use time in filter input.
      isValid = isDate(obj, useTime, suppressDateErrors)
    }

    if (doNumber){
      if (typeof p_lower != "undefined"){
        isValid = isNumber(obj, p_lower, p_upper);
      }else if (typeof p_upper != "undefined"){
        isValid = isNumber(obj, 0, p_upper);
      }else{
        isValid = isNumber(obj);
      }
    }

    if (doDuration){
      isValid = isDuration(obj, false);
    }

    if (doDurationReport){
      isValid = isDuration(obj, true);
    }

    if (doSearchFlag){
      isValid = isValidSearchFlag(obj);
    }

    if (doTime){
      isValid = isTime(obj);
    }

    if (doSearchMode && !doSearchFlag){
      if(isValid) {
        if((doDate || doTime || doNumber) && isEmpty(searchPrefix) && !isEmpty(obj.value)) searchPrefix = "=";
        if(doTime){
          var aTime = obj.value.split(":");
          obj.value = aTime[0]*60 + (aTime[1]*1);

        }
        obj.value = searchPrefix+obj.value;
      }
    }

    if ( doChanged ){
      if (isColour){
        doChangeShare(obj, true);
      } else {
        doChangeShare(obj, false);
      }
    }

  }

  if (typeof postOch == "function"){
    postOch(obj, p_row);
  }
}

/****************************************************/

// Show the Address "div"
function openAddress(values, disabledFlag, page, tab, noOnRow, posOnRow, textareaIncluded, p_form, p_row) {
  if (isNav()){
    var div = getObject("miscDiv");

    if (div != "undefined"){
      var dest_doc = top.saveFrame.document;

      var aStr = "<HTML><HEAD></HEAD><BODY>\r\n";
      aStr += "<FORM ACTION=ui_common.p_build_address_div NAME=write_form METHOD=POST>\r\n";
      aStr += f_save("p_session",         session);

      aStr += f_save("p_value_list",      values);
      aStr += f_save("p_disabled",        disabledFlag);
      aStr += f_save("p_page",            page);
      aStr += f_save("p_tab",             tab);
      aStr += f_save("p_items_per_row",   ""+noOnRow);
      aStr += f_save("p_position_on_row", ""+posOnRow);

      if (p_form != "undefined"){
        aStr += f_save("p_form",            p_form);
      }

      if (p_row != "undefined"){
        aStr += f_save("p_row",             "" + p_row);
      }

      if (textareaIncluded){
        aStr += f_save("p_inc_textarea",    "1");
      }

      aStr += "</FORM></BODY></HTML>";
      dest_doc.open();
      dest_doc.write(aStr);
      dest_doc.write_form.submit();
    }
  }
}

function addressOK(values, setTextArea, noOnRow, posOnRow, p_form, p_row){

  var formRef = window.document;
  var objRef;
  var fullAddress = "";
  var nRow;
  var nImageIdx;

  try{
    nRow = parseInt(p_row, 10);
    if (isNaN(nRow)){
      nRow = -1;
    }
  } catch (e) {nRow = -1;}

  nImageIdx = nRow;
  // if there is more than 1 address popup on the row
  // calculate the correct reference to the image
  if (noOnRow > 1){
    nImageIdx = ((nRow>=0?nRow:0) * noOnRow) + (posOnRow - 1);
  }

  if (p_form != "undefined"){
    formRef = getObject(p_form);
  }

  if (formRef == "undefined"){
    return;
  }

  var splitValues = values.split("$");
  var tmpParam;


  for (var i = 0; i <= 6; i++){
    tmpParam = splitValues[i].split("@");
    if (tmpParam[1] != "undefined"){
      if (!isEmpty(tmpParam[1])){
        fullAddress += tmpParam[1] + "\n";
      }
      if (p_form != "undefined"){
        objRef = getObject(tmpParam[0], p_form);
      }else{
        objRef = getObject(tmpParam[0]);
      }
      if (objRef != "undefined"){
        if (nRow >= 0){
          if ( objRef[nRow].value != tmpParam[1]){
            objRef[nRow].value = tmpParam[1];
            och(objRef[nRow], 1, -1);
          }
        }else{
          if ( objRef.value != tmpParam[1]){
            objRef.value = tmpParam[1];
            och(objRef, 1, -1);
          }
        }
      }
    }
  }

  if (setTextArea){
    if (nRow >= 0){
      if ( formRef.p_fulladdress[nRow].value != fullAddress ){
        var sTemp = formRef.p_fulladdress[nRow].value;
        formRef.p_fulladdress[nRow].value = fullAddress;

        if ( sTemp != formRef.p_fulladdress.value ){
          och(formRef.p_fulladdress[nRow], 1, -1);
        }
      }
    }else{
      if ( formRef.p_fulladdress.value != fullAddress ){
        var sTemp = formRef.p_fulladdress.value;
        formRef.p_fulladdress.value = fullAddress;

        if ( sTemp != formRef.p_fulladdress.value ){
          och(formRef.p_fulladdress, 1, -1);
        }
      }
    }
  }

  if (nImageIdx >= 0){
    if (isEmpty(fullAddress)){
      formRef.p_desc_image[nImageIdx].src = getImage("IMG_LONG_TEXT");
    }else{
      formRef.p_desc_image[nImageIdx].src = getImage("IMG_LONG_TEXT_ON");
    }
  }else{
    if (isEmpty(fullAddress)){
      formRef.p_desc_image.src = getImage("IMG_LONG_TEXT");
    }else{
      formRef.p_desc_image.src = getImage("IMG_LONG_TEXT_ON");
    }
  }

  hideMiscDiv();
  setCheckUnload(true);

}


/** Set the address icon on p_form to be on. */
function setAddressIcon(p_form){

  if (bAddressSearch){
    if (typeof p_form.p_desc_image == "object"){
      p_form.p_desc_image.src = getImage("IMG_LONG_TEXT_ON");
    }
  }
}

/** Sets a boolean value bAddressSearch.
  *  bAddressSearch is true if an address pop up on a
  *  search screen holds data.
  */
function setAddressSearch(bValue){
  bAddressSearch = bValue;
}

/**
 * function to clear an address text area.  Called from clearFilter in each js file
 * @param theForm a string representing the formname
 * @param theField - optional. the field name of the text area.
 * @param theRow - optional. the row identifier.
 */
function clearAddress(theForm, theField, theRow){
  if (isEmpty(theForm)){
    alertDialog("theForm must be supplied to clearAddress");
  }
  var fieldToCheck;
  if (isEmpty(theField)){
    fieldToCheck = "p_fulladdress";
  }else{
    fieldToCheck = theField;
  }
  var textField = getObject(fieldToCheck, theForm);
  var iconField = getObject("p_desc_image", theForm);

  if (isEmpty(theRow)) {
    textField.value = "";
    iconField.src = getImage("IMG_LONG_TEXT");
  }else{
    textField[theRow].value = "";
    iconField[theRow].src = getImage("IMG_LONG_TEXT");
  }

}

/** Function to call the middle layer routine to change the status
  * @param  p_session       The current Session ID
  * @param  p_page_id       The ID of the Page that needs the hard status changed
  * @param  p_hard_status   The Hard Sttaus to to change to
  * @param  p_soft_status   The Soft Status to change to
  * @param  p_id            The ID of the object to change the hard status of
  */
function setHardStatus( p_session, p_page_id, p_hard_status, p_soft_status, p_id ){
  cursorWait();
  disableNavigation();
  top.saveFrame.location.href="sv_hard_status.p_iu_hard_status?p_session="+p_session+
                                                             "&p_page_id="+p_page_id+
                                                             "&p_hard_status="+p_hard_status+
                                                             "&p_soft_status="+p_soft_status+
                                                             "&p_id="+p_id;
}


function openLongText(values, disabledFlag, p_form, p_row) {

  var div = getObject("miscDiv");
  var formRef = window.document;
  var objRef;
  var nRow;
  var sCurrentValue = "";

  if (div != "undefined"){
    var dest_doc = top.saveFrame.document;
    var params = values.split("@");

    var aStr = "<HTML><HEAD></HEAD><BODY>\r\n";
    aStr += "<FORM ACTION=ui_common.p_build_longdesc_div NAME=write_form METHOD=POST>\r\n";
    aStr += f_save("p_session",         session);

    aStr += f_save("p_field",           params[3]);
    aStr += f_save("p_objid",           params[4]);
    aStr += f_save("p_disabled",        params[5]);

    try{
      nRow = parseInt(p_row, 10);
      if (isNaN(nRow)){
        nRow = -1;
      }
    } catch (e) {nRow = -1;}


    if (p_form != "undefined"){
      formRef = getObject(p_form);
      objRef = getObject(params[3], p_form);
    }else{
      objRef = getObject(params[3]);
    }

    if (formRef == "undefined"){
      return;
    }

    if (objRef != "undefined"){
      if (nRow >= 0){
        aStr += "<TEXTAREA NAME=p_long_text>"+realObj(objRef, nRow).value+"</TEXTAREA>";
      }else{
        aStr += "<TEXTAREA NAME=p_long_text>"+objRef.value+"</TEXTAREA>";
      }
    }

    if (p_form != "undefined"){
      aStr += f_save("p_form",            p_form);
    }

    if (p_row != "undefined"){
      aStr += f_save("p_row",             "" + p_row);
    }

    aStr += "</FORM></BODY></HTML>";
    dest_doc.open();
    dest_doc.write(aStr);
    dest_doc.write_form.submit();

  }


}

function longTextOK(fieldID, formID, row, objId, longText){

 //alert(fieldID + "\r\n" + formID + "\r\n" + row + "\r\n" + objId + "\r\n" + longText);

  var formRef = window.document;
  var objRef;
  var iconRef;
  var nRow;
  var newIcon = getImage("IMG_LONG_TEXT_ON");

  try{
    nRow = parseInt(row, 10);
    if (isNaN(nRow)){
      nRow = -1;
    }
  } catch (e) {nRow = -1;}


  if (formID != "undefined"){
    formRef = getObject(formID);
    objRef = getObject(fieldID, formID);
    iconRef = getObject(fieldID+"_img", formID);
  }else{
    objRef = getObject(fieldID);
    iconRef = getObject(fieldID+"_img");
  }

  if (formRef == "undefined"){
    return;
  }

  if (typeof objRef == "object"){
    if (nRow >= 0){
      var sTemp = realObj(objRef, nRow).value;
      realObj(objRef, nRow).value = longText;

      if ( sTemp != realObj(objRef, nRow).value ){
        setChanged(realObj(objRef, nRow), nRow);
        doChangeShare(realObj(objRef, nRow), false);
      }
    }else{
      var sTemp = objRef.value;
      objRef.value = longText;
      if ( sTemp != objRef.value ){
        setChanged(objRef, nRow);
        doChangeShare(objRef, false);
      }
    }
  }

  if (isEmpty(longText)){
    newIcon = getImage("IMG_LONG_TEXT");
  }

  if (typeof iconRef == "object"){
    if (nRow >= 0){
      realObj(iconRef, nRow).src = newIcon;
    }else{
      iconRef.src = newIcon;
    }
  }

  hideMiscDiv();
  setCheckUnload(true);

}


function openColour(p_field, p_form, p_row) {

  var div = getObject("miscDiv");
  var formRef = window.document;
  var objRef;
  var nRow;
  var sCurrentValue = "";

  if (div != "undefined"){
    var dest_doc = top.saveFrame.document;

    var aStr = "<HTML><HEAD></HEAD><BODY>\r\n";
    aStr += "<FORM ACTION=ui_common.p_build_colour_div NAME=write_form METHOD=POST>\r\n";
    aStr += f_save("p_session",         session);

    aStr += f_save("p_field",           p_field);
    try{
      nRow = parseInt(p_row, 10);
      if (isNaN(nRow)){
        nRow = -1;
      }
    } catch (e) {nRow = -1;}


    if (p_form != "undefined"){
      formRef = getObject(p_form);
      objRef = getObject(p_field, p_form);
    }else{
      objRef = getObject(p_field);
    }

    if (formRef == "undefined"){
      return;
    }

    if (p_form != "undefined"){
      aStr += f_save("p_form",            p_form);
    }

    if (p_row != "undefined"){
      aStr += f_save("p_row",             "" + p_row);
    }

    aStr += "</FORM></BODY></HTML>";
    dest_doc.open();
    dest_doc.write(aStr);
    dest_doc.write_form.submit();

  }
}

function colourOK(fieldID, formID, row, newColour){

  var formRef = window.document;
  var objRef;
  var tdRef;
  var nRow;

  try{
    nRow = parseInt(row, 10);
    if (isNaN(nRow)){
      nRow = -1;
    }
  } catch (e) {nRow = -1;}


  if (formID != "undefined"){
    formRef = getObject(formID);
    objRef = getObject(fieldID, formID);
  }else{
    objRef = getObject(fieldID);
  }

  if (nRow >= 0){
    tdRef = getObject("TD"+fieldID+row);
  }else{
    tdRef = getObject("TD"+fieldID);
  }


  if (formRef == "undefined"){
    return;
  }

  if (typeof objRef == "object"){
    if (nRow >= 0){
      objRef[nRow].value = newColour;
      objRef[nRow].style.background = newColour;
      tdRef.style.background = newColour;
      och(objRef[nRow], 513, -1);
      setChanged(objRef[nRow], nRow);
    }else{
      objRef.value = newColour;
      objRef.style.background = newColour;
      tdRef.style.background = newColour;
      och(objRef, 513, -1);
      setChanged(objRef, nRow);
    }
  }

  hideMiscDiv();
  setCheckUnload(true);

}

function doOnChange(p_field, p_row, p_form){

  var theForm;

  if (typeof p_form != "undefined"){
    theForm = p_form;
  }else{
    theForm = getForm(p_field);
  }

  if (p_field.onchange != null){
    p_field.onchange();
    return true;
  }

  return false;
}






/***********/

var currentX = currentY = 0;  // initialize global position-tracking variables
var whichDiv = null;           // initialize global element-being-dragged variable
var draggable = new Array("miscDiv",
                          "formDiv",
                          "errorDiv",
                          "confirmDiv",
                          "actionMsgDiv",
                          "divUserReport"); // list of items that are draggable

function isDraggable(objectID){
  var rval = false;
  for (var i in draggable){
    if (draggable[i] == objectID){
      rval = true;
      break;
    }
  }
  return rval;
}

function grabDiv() {       // function for onmousedown
  whichDiv = event.srcElement;
  while (!isDraggable(whichDiv.id)) {
    whichDiv = whichDiv.parentElement;
    if (whichDiv == null) { return }
  }

  whichDiv.style.pixelLeft = whichDiv.offsetLeft;
  whichDiv.style.pixelTop = whichDiv.offsetTop;

  currentX = (event.clientX + document.body.scrollLeft);
  currentY = (event.clientY + document.body.scrollTop);
}

function moveDiv() {       // function for onmousemove
  getMouseXY(event);

  if (whichDiv == null) { return };

  newX = (event.clientX + document.body.scrollLeft);
  newY = (event.clientY + document.body.scrollTop);

  distanceX = (newX - currentX);
  distanceY = (newY - currentY);
  currentX = newX;
  currentY = newY;

  whichDiv.style.pixelLeft += distanceX;
  whichDiv.style.pixelTop += distanceY;
  event.returnValue = false;
}

function dropDiv() {       // function for onmouseup
  whichDiv = null;
}

function updateEmail(p_field_id, p_email){
  obj = getObject("mailLink"+p_field_id);
  obj.href="mailto:"+p_email.value
}


function remove_invalid_characters(theField, keyField, theRow, searchField){
  var invalidItems      = new Array("\\", "£", "^");              // List of values to remove for all fields
  var keyInvalidItems   = new Array("&", "$", "@", "\"", "'");    // List of values to remove for key fields only
  var keyInvalidItemsDisplay   = new Array("&", "&#36", "&#64", "\"", "'");    // Display values for list of values to remove for key fields only

  var previousFind      = false;
  var newValue;
  var re;
  var errorMessage;
  var originalField;

  if ( (theRow > -1) && (theField.length>1) ){
    originalField = theField[theRow].value;
  }else{
    originalField = theField.value;
  }

  //Remove $ and @ because these are key characters in the error message string
  re = new RegExp("\\" + "$", "g");
  originalField = originalField.replace(re, "&#36");
  re = new RegExp("\\" + "@", "g");
  originalField = originalField.replace(re, "&#64");

  errorMessage = "[VAL-JS01$"+originalField+"@";

  if ( (theRow > -1) && (theField.length>1) ){
    if (keyField) theField[theRow].value = trim(theField[theRow].value);
    newValue = theField[theRow].value;
  } else {
    if (keyField) theField.value = trim(theField.value);
    newValue = theField.value;
  }

  for (var i = 0; i < invalidItems.length; i++){
    if (newValue.indexOf(invalidItems[i]) != -1){
      re = new RegExp("\\" + invalidItems[i], "g");
      newValue = newValue.replace(re, "");
      if (previousFind){
        errorMessage = errorMessage + ", ";
      }
      errorMessage = errorMessage + invalidItems[i];
      previousFind = true;
    }
  }

  if (keyField){
    for (var i = 0; i < keyInvalidItems.length; i++){
      if (newValue.indexOf(keyInvalidItems[i]) != -1){
        re = new RegExp("\\" + keyInvalidItems[i], "g");
        newValue = newValue.replace(re, "");
        if (previousFind){
          errorMessage = errorMessage + ", ";
        }
        errorMessage = errorMessage + keyInvalidItemsDisplay[i];
        previousFind = true;
      }
    }
  }

  errorMessage = errorMessage + "]";
  if (previousFind){
    alertDialog(errorMessage);
    if ( (theRow > -1) && (theField.length>1) ){
      theField[theRow].value = newValue;
    } else {
      theField.value = newValue;
    }
  }
}




/**
 * A function used on the search forms
 * for activating
 */
function searchFormKeyEvent(evt){
  evt = (evt)?evt:event;
  var charCode = (evt.which)?evt.which:evt.keyCode;
  if (charCode == 13 && typeof getQuery == "function"){
    if (typeof p_quick_find == "object"){
      p_quick_find.focus();
    }
    getQuery('RESULTS', false);
    return false;
  }
  return true;
}

/**
 * Function to get terminology for javascript
 */
function getTerm(termString){
  if (typeof top.headerFrame == "object"){
    if (typeof top.headerFrame.getJSTerm == "function"){
      return top.headerFrame.getJSTerm(termString);
    }
  }
  return termString;
}

function getImage(imageId){
  if (typeof top.headerFrame == "object"){
    if (typeof top.headerFrame.getJSImage == "function"){
      return top.headerFrame.getJSImage(imageId);
    }
  }
  return imageId;
}

/**
 * Function to get javascript for javascript
 */
function getMessage(messageString){
  if (typeof top.headerFrame == "object"){
    if (typeof top.headerFrame.getJSMessage == "function"){
      return top.headerFrame.getJSMessage(messageString);
    }
  }
  return messageString;
}

function hasSecurity(securityID, accessRight){
  if (typeof top.headerFrame == "object"){
    if (typeof top.headerFrame.hasJSSecurity == "function"){
      return top.headerFrame.hasJSSecurity(securityID, accessRight);
    }
  }
  return false;
}

function hasModule(moduleID){
  if (typeof top.headerFrame == "object"){
    if (typeof top.headerFrame.hasJSModule == "function"){
      return top.headerFrame.hasJSModule(moduleID);
    }
  }
  return false;
}

function getModuleTerm(moduleID){
  if (typeof top.headerFrame == "object"){
    if (typeof top.headerFrame.getJSModuleTerm == "function"){
      return top.headerFrame.getJSModuleTerm(moduleID);
    }
  }
  return false;
}

function getModules(){
  if (typeof top.headerFrame == "object"){
    if (typeof top.headerFrame.getJSModules == "function"){
      return top.headerFrame.getJSModules();
    }
  }
  return false;
}

function getForm(childObj){
  if (childObj.tagName == "FORM"){
    return childObj;
  }else if (typeof childObj.parentElement == "object"){
    return getForm(childObj.parentElement);
  }else{
    return null;
  }
}

function setCaretToEnd(obj) {
  if (obj.createTextRange) {
    var val = obj.value;
    var range = obj.createTextRange();
    range.moveStart('character', val.length);
    range.select();
  }
}

function moveToolbar(){
  if (typeof top.bodyFrame == "object" && typeof top.bodyFrame.getObject == "function"){
    var toolbarDiv = top.bodyFrame.getObject("mainToolbar");
    if (typeof toolbarDiv != "undefined"){
      if (document.body.clientWidth > 820){
        toolbarDiv.style.left = top.bodyFrame.document.body.scrollLeft + "px";
      }
      toolbarDiv.style.top = top.bodyFrame.document.body.scrollTop + "px";
    }
  }
}

function doFilter(evt){
  evt = (evt)?evt:event;
  var charCode = (evt.which)?evt.which:evt.keyCode;
  if (charCode == 13){
    top.saveFrame.goHref("FIND");
    return false;
  }
  return true;
}

function hasAnalysisCompleted(){
  if (typeof top.bodyFrame.objAnalysisApplet == "object"){
    if (top.bodyFrame.objAnalysisApplet.done()){
      if (top.bodyFrame.objAnalysisApplet.hasErrors()){
        alertDialog(getMessage(top.bodyFrame.objAnalysisApplet.getErrors()));
      }else{
        alertDialog(getMessage("[GEN-COMPLETE$"+getTerm("{ANALYSIS}")+"]"));
      }
      hideDiv(top.bodyFrame.formDiv);
    }else{
      setTimeout("hasAnalysisCompleted();", 2000);
    }
  }
}

var winPopup;
function openPopup(p_url){
  if(!winPopup || winPopup.closed) {
    var regexp = /\&/g;
    winPopup = window.open("ui_main.p_top_frameset?p_session="+session+"&p_header=0&p_url="+p_url.replace(regexp, "^"), "Popup", "toolbar=no,location=no,directories=no,menubar=no,status=no,resizable=yes,scrollbars=yes,width=1012,height=669,left="+Math.round((screen.width/2)-(1024/2))+",top="+Math.round((screen.height/2)-(700/2)));
    if(!winPopup.opener) {
      winPopup.opener = window;
    }
  } else {
    var regexp = /\^/g;
    winPopup.top.bodyFrame.location.href=p_url.replace(regexp, "&");
    winPopup.focus();
  }
}



// function called when f_add_column is set up with p_display_as_hyperlink true.
function fieldSelected(p_params){
  if (typeof returnWithValue == "function"){
    returnWithValue(p_params);
  }
  if (typeof top.opener == "object" && typeof top.opener.top.bodyFrame == "object" && typeof top.opener.top.bodyFrame.winPopup == "object"){
    top.opener.top.bodyFrame.winPopup.close();
  }
}

// function called by add to favourite popup to allow a folder to be created
function favFolderSelected(p_new_value){
  var folderDetailsDiv = getObject("folderDetailsDiv");
  if (typeof folderDetailsDiv == "object"){
    frmAttachDoc.p_new_fav_category.value = "";
    frmAttachDoc.p_new_fav_description.value = "";
    frmAttachDoc.p_new_fav_disp_order.value = "";
    if (p_new_value == "[NEW]"){
      folderDetailsDiv.style.display = "inline";
      frmAttachDoc.p_new_fav_category.focus();
    }else{
      folderDetailsDiv.style.display = "none";
    }
  }
}

function createFavourite(p_session, p_username, p_category, p_menu_id, p_disp_order, p_new_category, p_new_description, p_new_disp_order){
  var folderDetailsDiv = getObject("folderDetailsDiv");
  if (typeof folderDetailsDiv == "object"){
    enableNavigation();
    formDiv.style.display="none";
    goSaveURL("sv_hub.p_add_to_favourite?p_session="+p_session+"&p_user_name="+p_username+"&p_category="+p_category+
              "&p_menu_id="+p_menu_id+"&p_disp_order="+p_disp_order+"&p_new_category="+p_new_category+
              "&p_new_description="+p_new_description+"&p_new_disp_order="+p_new_disp_order);
  }
}

function createTask(p_session, p_username, p_category, p_task_id, p_description, p_href, p_disp_order, p_due_date, p_title,
                    p_new_category, p_new_description, p_new_disp_order){
  var folderDetailsDiv = getObject("folderDetailsDiv");
  if (typeof folderDetailsDiv == "object"){
    enableNavigation();
    formDiv.style.display="none";
    goSaveURL("sv_hub.p_add_to_task?p_session="+p_session+"&p_user_name="+p_username+"&p_category="+p_category+
              "&p_task_id="+p_task_id+"&p_description="+p_description+"&p_href="+p_href+"&p_disp_order="+p_disp_order+
              "&p_due_date="+p_due_date+"&p_title="+p_title+"&p_new_category="+p_new_category+
              "&p_new_description="+p_new_description+"&p_new_disp_order="+p_new_disp_order);
  }
}

function setCBAll(p_cball, p_selected){
  if (typeof p_selected == "object")  {
    if (getLength(p_selected) > 0)  {
      for ( var i = 0 ; i < getLength(p_selected) ; i++ ){
        var obj = realObj(p_selected, i);
        obj.checked = p_cball.checked;
      }
    }
  }
}

function setMandatory(rowObj, term, on){
  for (var i in rowObj.children){
    if (rowObj.children[i].tagName == "TD" && rowObj.children[i].innerHTML.indexOf(term) == 0){
      if (on){
        rowObj.children[i].className = "cT";
        rowObj.children[i].innerHTML = term+":<SPAN CLASS=asterisk><IMG SRC=\"/img/mand.gif\" ALT=\"\"></SPAN>";
      }else{
        rowObj.children[i].className = "cTNM";
        rowObj.children[i].innerHTML = term+":";
      }
    }
  }
}

function saveCopy(p_session, p_page, p_obj_id, p_load_new_item, p_to_label, p_desc_label, p_contract_label, p_inc_contract){
  resetRequiredFields();
  requiredFields[requiredFields.length] = "p_copy_id";
  requiredFields[requiredFields.length] = "p_copy_desc";
  fieldNames[fieldNames.length] = p_to_label;
  fieldNames[fieldNames.length] = p_desc_label;
  if (p_inc_contract){
    requiredFields[requiredFields.length] = "p_copy_contract";
    fieldNames[fieldNames.length] = p_contract_label;
  }
  if (checkRequiredFields(top.bodyFrame.frmCopyObj)){
    goSaveURL(encode_url("sv_copy_obj.p_copy?p_session="        +p_session                                                +
                                    "&p_page="                  +p_page                                                   +
                                    "&p_obj_id="                +p_obj_id                                                 +
                                    "&p_new_id="                +top.bodyFrame.frmCopyObj.p_copy_id.value                 +
                                    "&p_new_desc="              +top.bodyFrame.frmCopyObj.p_copy_desc.value               +
                                    "&p_copy_project="          +top.bodyFrame.frmCopyObj.p_copy_contract.value           +
                                    "&p_copy_sub_jobs="         +getCbx(top.bodyFrame.frmCopyObj.p_copy_sub_jobs)         +
                                    "&p_copy_book_contents="    +getCbx(top.bodyFrame.frmCopyObj.p_copy_book_contents)    +
                                    "&p_copy_chapter_contents=" +getCbx(top.bodyFrame.frmCopyObj.p_copy_chapter_contents) +
                                    "&p_apply_factor_qty="      +top.bodyFrame.frmCopyObj.p_apply_factor_qty.value        +
                                    "&p_apply_factor_cost="     +top.bodyFrame.frmCopyObj.p_apply_factor_cost.value       +
                                    "&p_apply_factor_price="    +top.bodyFrame.frmCopyObj.p_apply_factor_price.value      +
                                    "&p_do_const="              +getCbx(top.bodyFrame.frmCopyObj.p_copy_const)            +
                                    "&p_renumber_jobs="         +getCbx(top.bodyFrame.frmCopyObj.p_renumber_jobs)         +
                                    "&p_load_new_item="         +p_load_new_item));
    hideDiv(top.bodyFrame.formDiv);
    top.bodyFrame.cursorWait();
  }
}


/***********/

// Register events
//window.onError = errorHandler();

document.onmousemove = moveDiv;
document.onclick = bodyClicked;
document.onkeyup = hotKey;

window.onscroll = moveToolbar;
window.onresize = moveToolbar;
