function centreWindow(windowWidth, windowHeight) {
  return("left=" + ((screen.width - windowWidth) / 2) + ", top=" + ((screen.height - windowHeight) / 2));
}
function getTop(windowHeight) {
  return((screen.height - windowHeight) / 2);
}

function getLeft(windowWidth) {
  return((screen.width - windowWidth) / 2);
}

function isEmpty(str) {
  return ((str == null) || (str == ""));
}

function strReplace(strVar, fromStr, toStr) {
  var newStr = "";

  if (isEmpty(strVar)) {
    return null;
  } else if (strVar.length == 0) {
    return strVar;
  } else {
    for (count = 0; count < strVar.length; count++) {
      if (strVar.charAt(count) == fromStr) {
        newStr += toStr;
      }
      else {
        newStr += strVar.charAt(count);
      }
    }
    return (newStr);
  }
}

function isNum(passedVal) {
  for (i=0; i<passedVal.length; i++) {
    if (passedVal.charAt(i) < "0") return false;
    if (passedVal.charAt(i) > "9") return false;
  }
  return true;
}

// Function which Checks to see if any of the number fields entered are not numbers
function checkEntryIsNumber (entry, description){
    var err = "";
	err += !isEmpty(strTrim(entry)) && ( isNaN(entry) || entry < 0 || entry.indexOf(".") > -1 )? description + "\n" : "";
    return (err);
}

function strTrimTail (strVar) {
  // trims trailing spaces from strings
  while (strVar.charAt(strVar.length - 1) == " " && strVar.length != 0) {
    strVar = strVar.substring(0, strVar.length - 1);
  }
  return (strVar);
}

function strTrimZero(strVar) {
  // trims leading zeroes
  while (strVar.charAt(0) == "0" && strVar.length != 0) {
    strVar = strVar.substring(1, strVar.length);
  }
  return (strVar);
}

function strTrim(strVar) {
  // trims leading and trailing spaces from strings
  while (strVar.charAt(0) == " " && strVar.length != 0) {
    strVar = strVar.substring(1, strVar.length);
  }
  while (strVar.charAt(strVar.length - 1) == " " && strVar.length != 0) {
    strVar = strVar.substring(0, strVar.length - 1);
  }
  return (strVar);
}

function getUserTime(form, timeField) {
  var timeStr = eval("form." + timeField + ".value");

  if (timeStr.length == 0 ) {
    return null;
  }

  for (i = 0; i < delim.length; i++)  {
    timeStr = strReplace(timeStr, delim[i], ':');
  }

  var d3 = timeStr.indexOf(':');
  var hhStr = timeStr.substring(0, d3);
  var minStr = timeStr.substring(d3 + 1);
  var hh = parseInt(hhStr, 10);
  var min = parseInt(minStr, 10);

  if (timeStr.length < 4  || timeStr.length > 6 || isNaN(hhStr) || isNaN(minStr) || hh < 0 || hh > 24 || min < 0 || min > 59 || (hh == 0 && min == 0)) {
    return null;
  } else {
    hours = hh;
    minutes = min;
    return timeField;
  }
}

function claimForm(type, policy, risk) {
  var currentDate = new Date();
  var currTime = currentDate.getTime();

  if (type == 'HPK') {
   url = "/servlet/HomeRiskServlet?riskRequest=claim&effectiveDate=" + effectiveDate + "&policyNumber=" + policy + "&policyType=" + type + "&policyRisk=" + risk + "&time=" + currTime;
   // url = "/servlet/EclaimsServlet?ACTION_TYPE=NEW_CLAIM&policyNumber=" + policy + "&policyRisk=" + risk + "&effectiveDate=" + effectiveDate + "&indexSelected=" + selected;
  } else if (type == 'BPK') {
    url = "/servlet/BPKOldRiskServlet?riskRequest=claim&effectiveDate=" + effectiveDate + "&policyNumber=" + policy + "&policyType=" + type + "&policyRisk=" + risk + "&time=" + currTime;
  } else {
    alert("Policy type " + type + " is not valid. Only HPK and BPK is supported now.");
    return false;
  }
  if (window.opener && window.document.forms[0].name == 'PolicySections') {
    window.opener.location.href = url;
  } else {
    top.location.href = url;
  }
}

function newClaim(type, policy, risk) {
  var currentDate = new Date();
  var currTime = currentDate.getTime();

  if (type == 'HPK') {
    url = "/servlet/EclaimsServlet?ACTION_TYPE=NEW_CLAIM&policyNumber=" + policy + "&policyRisk=" + risk + "&effectiveDate=" + effectiveDate + "&indexSelected=" + selected;
  } else if (type == 'BPK') {
    url = "/servlet/BPKOldRiskServlet?riskRequest=claim&effectiveDate=" + effectiveDate + "&policyNumber=" + policy + "&policyType=" + type + "&policyRisk=" + risk + "&time=" + currTime;
  } else {
    alert("Policy type " + type + " is not valid. Only HPK and BPK is supported now.");
    return false;
  }
  if (window.opener && window.document.forms[0].name == 'PolicySections') {
    window.opener.location.href = url;
  } else {
    top.location.href = url;
  }
}


function CofNCDForm(type, policy, risk, effDate) {
  var CofNCDWind = window.open("/servlet/MotorRiskServlet?riskRequest=CofNCD&effectiveDate=" + effDate + "&policyNumber=" + policy + "&policyRisk=" + risk + "&time=" +  (new Date().getTime()), "CofNCD", "width=760,height=560,toolbar=yes,location=no,directories=no,status=no,menubar=yes,scrollbars=yes,resizable=yes,copyhistory=no");

  if (document.images) {
    CofNCDWind.focus();
  }
}

function schedule(effDate, policyNumber, scheduleType) {
  time = new Date().getTime();
 url = "/servlet/DocumentSaveServlet?effDate=" + effDate + "&policyNumber=" + policyNumber + "&scheduleType=" + scheduleType + "&documentType=405&time=" + time + "&fromBrowser=Y";
  if (document.layers) {
    newWin = window.open(url,"schedule","toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=yes,copyhistory=no");
  }
  else {
    newWin = window.open(url,"schedule","toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=no,resizable=yes,copyhistory=no");
  }
  if (document.images) {
    newWin.focus();
  }
}

// FSRA - Help
function fsraHelp(heading) {
  time = new Date().getTime();
  url = "";

  if (heading == "Important Information") {
    url = "/fsra/FsraHelp.jsp?heading=" + heading + "&time=" + time;
  } else {
    if (document.forms[0].system.value.toUpperCase() != 'CCHANGE') {
      url = "/servlet/AuthoriseServlet?fsraWindow=Y&fsraHelp=fsraHelp&intermediaryCode=" + document.forms[0].intermediaryCode.value + "&LoginSystemUserId=" + document.forms[0].brokSysId.value + "&System=" + document.forms[0].system.value + "&heading=" + heading + "&time=" + time;
    } else {
      if (heading == "Underwriting Screen" ||
          heading == "Risk Screen") {
        url = "/servlet/FsraHelpServlet?heading=" + heading + "&time=" + time;
      } else {
        url = "/fsra/FsraHelp.jsp?heading=" + heading + "&time=" + time;
      }
    }
  }

  if (!isEmpty(url)) {
    if (document.layers) {
        newWin = window.open(url,"fsraHelp",centreWindow(651,440) + ",width=651,height=440,toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=no,resizable=no,copyhistory=no");
    } else {
        newWin = window.open(url,"fsraHelp",centreWindow(651,440) + ",width=650,height=440,toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=no,resizable=no,copyhistory=no");
    }
    if (document.images) {
      newWin.focus();
    }
  }
}

// FSRA - General Warning Advice
function gaw() {
  time = new Date().getTime();
  gawWindow = window.open('','gaw',centreWindow(760,400) + ',width=760,height=400,toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=no,resizable=no,copyhistory=no');
  if (gawWindow.document.forms[0] != null && gawWindow.document.forms[0].name == 'gaw' && gawWindow && !gawWindow.closed) {
    gawWindow.focus();
  } else {

    if (document.forms[0].system.value.toUpperCase() != 'CCHANGE') {
        url = "/servlet/AuthoriseServlet?fsraWindow=Y&gaw=gaw&intermediaryCode=" + document.forms[0].intermediaryCode.value + "&LoginSystemUserId=" + document.forms[0].brokSysId.value + "&System=" + document.forms[0].system.value + "&time=" + time;
    } else {
        url = "/servlet/SoaServlet?gaw=gaw" + "&time=" + time;
    }


    if (document.layers) {
      newWin = window.open(url,'gaw',centreWindow(760,400) + ',width=760,height=400,toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=no,resizable=no,copyhistory=no');
    }
    else {
      newWin = window.open(url,'gaw',centreWindow(760,400) + ',width=760,height=400,toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=no,resizable=no,copyhistory=no');
    }
    if (document.images) {
      newWin.focus();
    }
  }
}

// FSRA - Statement of Advice
function soa(account, refNumber, tranType, premium, commRate, commAmt) {
  time = new Date().getTime();
  if (readCookie("documentInclude") == "400") {
    soaWindow = window.open('','soa', centreWindow(760,400) + ',width=760,height=400,toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=no,resizable=no,copyhistory=no');
    soaWindow.document.forms[0].account.value = account;
    soaWindow.document.forms[0].refNumber.value = refNumber;
    soaWindow.document.forms[0].tranType.value = tranType;
    soaWindow.document.forms[0].premium.value = premium;
    soaWindow.document.forms[0].commRate.value = commRate;
    soaWindow.document.forms[0].commAmt.value = commAmt;
    soaWindow.focus();
  } else {
    if (document.forms[0].system.value.toUpperCase() != 'CCHANGE') {
        url = "/servlet/AuthoriseServlet?fsraWindow=Y&intermediaryCode=" + document.forms[0].intermediaryCode.value + "&LoginSystemUserId=" + document.forms[0].brokSysId.value + "&System=" + document.forms[0].system.value + "&account=" + account + "&refNumber=" + refNumber + "&tranType=" + tranType + "&premium=" + premium + "&commRate=" + commRate + "&commAmt=" + commAmt + "&time=" + time;
    } else {
        url = "/servlet/SoaServlet?account=" + account + "&refNumber=" + refNumber + "&tranType=" + tranType + "&premium=" + premium + "&commRate=" + commRate + "&commAmt=" + commAmt + "&time=" + time;
    }

    if (document.layers) {
      newWin = window.open(url,'soa',centreWindow(760,400) + ',width=760,height=400,toolbar=no,location=no,directories=no,status=yes,menubar=no,scrollbars=no,resizable=no,copyhistory=no');
    }
    else {
      newWin = window.open(url,'soa',centreWindow(760,400) + ',width=760,height=400,toolbar=no,location=no,directories=no,status=yes,menubar=no,scrollbars=no,resizable=no,copyhistory=no');
    }
    if (document.images) {
      newWin.focus();
    }
  }
}

// FSRA - Update Statement of Advice window with premium commission etc...
function soaUpdate(account, refNumber, tranType, premium, commRate, commAmt, brokerFee) {
  var err = "";
  time = new Date().getTime();
  if (readCookie("documentInclude") == "400") {
    soaWindow = window.open('','soa',centreWindow(1,1) + ',width=1,height=1,toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=no,resizable=no,copyhistory=no');
    if (soaWindow.document.forms[0] != null && soaWindow.document.forms[0].name == 'soa' && soaWindow && !soaWindow.closed) {
      soaWindow.document.forms[0].account.value = account;
      soaWindow.document.forms[0].refNumber.value = refNumber;
      soaWindow.document.forms[0].tranType.value = tranType;
      soaWindow.document.forms[0].brokerFee.value = brokerFee;
      // Do not redisplay soa window if premium and commission have not changed
      if (soaWindow.document.forms[0].premium.value != premium
          || soaWindow.document.forms[0].commRate.value != commRate
          || soaWindow.document.forms[0].commAmt.value != commAmt) {
        soaWindow.document.forms[0].premium.value = premium;
        soaWindow.document.forms[0].commRate.value = commRate;
        soaWindow.document.forms[0].commAmt.value = commAmt;
        soaWindow.nextPage('Paid', soaWindow.document.forms[0]);
      }
    }
  }
}

// FSRA - Statement of Advice field validation
function soaVerify() {
  var err = "";
  verified = true;
  errorSection = ""
  time = new Date().getTime();
  if (readCookie("documentInclude") == "400") {
    soaWindow = window.open('','soa',centreWindow(760,400) + ',width=760,height=400,toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=no,resizable=no,copyhistory=no');
    if (isEmpty(soaWindow.document.forms[0].advice.value) || isEmpty(soaWindow.document.forms[0].basis.value)) {
      err += "  The 'Personal Advice' section is not complete.\n";
      if (isEmpty(errorSection)) {
        errorSection = "Advice";
      }
    }
    if (isEmpty(soaWindow.document.forms[0].adviser.value)) {
      err += "  The 'Adviser Name' section is not complete.\n";
      if (isEmpty(errorSection)) {
        errorSection = "Adviser";
      }
    }
    if (!isEmpty(soaWindow.document.forms[0].referrer.value) &&
        (isEmpty(soaWindow.document.forms[0].remuneration.value) ||
         isEmpty(soaWindow.document.forms[0].howToPay.value))) {
      err += "  Referrer entered with incomplete details in Statement of Advice\n";
      if (isEmpty(errorSection)) {
        errorSection = "Referral";
      }
    }
    if (isEmpty(soaWindow.document.forms[0].referrer.value) &&
        (!isEmpty(soaWindow.document.forms[0].remuneration.value) ||
         !isEmpty(soaWindow.document.forms[0].howToPay.value))) {
      err += "  Referrer details entered without a referrer in Statement of Advice\n";
      if (isEmpty(errorSection)) {
        errorSection = "Referral";
      }
    }
    if (err != "") {
      var msg = "You have not completed the mandatory sections of the Statement of Advice.";
      msg += "\n\n" + err;
      msg += "\nPlease enter the required information or cancel the Statement of Advice.";
      alert(msg);
      verified = false;
      soaWindow.nextPage(errorSection, soaWindow.document.forms[0]);
      soaWindow.focus();
    } else if (!confirm("Warning: Do you want to check the contents of the Statement of Advice before saving? \n\(You won't be able to make changes to the Statement of Advice later.\)\n\n Click \"OK\" to continue saving or \"Cancel\" to revisit the SoA")) {
      verified = false;
      soaWindow.focus();
    }
  }

  return (verified);
}

// FSRA - Save Document to DB2 in pdf format
function documentSave(account, refNumber, tranType, dateStr, premium, commRate, commAmt, userId, dataString) {
  var msg = "";
  var url2= "";
  var time = new Date().getTime();
  var newWin;
  if (readCookie("documentInclude") == "400" && (isEmpty(account) || isEmpty(refNumber) || isEmpty(tranType) || isEmpty(dateStr)
  || isEmpty(userId) || isEmpty(premium))) {
      msg += "The following parameters must be passed to save this quote\n";
      msg += "  account=" + account + "\n";
      msg += "  refNumber=" + refNumber + "\n";
      msg += "  tranType=" + tranType + "\n";
      msg += "  dateStr=" + dateStr + "\n";
      msg += "  premium=" + premium + "\n";
      msg += "  commRate=" + commRate + "\n";
      msg += "  commAmt=" + commAmt + "\n";
      msg += "  userId=" + userId + "\n";
      alert (msg);
  }
  else {

  if (readCookie("documentInclude") == "400") {
      showDocuments();
      soaWindow = window.open('','soa',centreWindow(1,1) + ',width=1,height=1,toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=no,resizable=no,copyhistory=no');
      soaWindow.document.forms[0].account.value = account;
      soaWindow.document.forms[0].refNumber.value = refNumber;
      soaWindow.document.forms[0].tranType.value = tranType;
      soaWindow.document.forms[0].dateStr.value = dateStr;
      soaWindow.document.forms[0].userId.value = userId;
      soaWindow.document.forms[0].dataString.value = dataString;
      if ((document.forms[0].system.value.toUpperCase() != 'CCHANGE')
          || (tranType == "QUOTE")) {
        soaWindow.document.forms[0].premium.value = premium;
        soaWindow.document.forms[0].commRate.value = commRate;
        soaWindow.document.forms[0].commAmt.value = commAmt;
      }
      if (tranType == "QUOTE") {
        // Save Statement of Advice and qoute letter as one document
        url = "/servlet/DocumentSaveServlet?time=" + time + "&documentType=400"+ "&fromBrowser=Y";
      } else {
        // Save Statement of Advice on it own
        url = "/servlet/DocumentSaveServlet?time=" + time + "&documentType=406"+ "&fromBrowser=Y";
      }
      soaWindow.document.forms[0].action = url;
      soaWindow.document.forms[0].target = "";
      soaWindow.document.forms[0].submit();
      soaWindow.document.forms[0].unloadOnRequest.value = "Y";
    }
    else {
      if (document.forms[0].system.value.toUpperCase() != 'CCHANGE') {
        url = "/servlet/AuthoriseServlet?fsraWindow=Y&docBuild=docBuild&intermediaryCode=" + document.forms[0].intermediaryCode.value + "&LoginSystemUserId=" + document.forms[0].brokSysId.value + "&System=" + document.forms[0].system.value + "&fsraOn=" + document.forms[0].fsraOn.value + "&account=" +  account + "&refNumber=" + refNumber + "&tranType=" + tranType + "&dateStr=" + dateStr  + "&userId=" + userId + "&time=" + time;
      } else {
        url = "/fsra/DocBuild.jsp?time=" + time + "&account=" +  account + "&refNumber=" + refNumber + "&tranType=" + tranType + "&dateStr=" + dateStr + "&userId=" + userId + "&system=" + document.forms[0].system.value + "&fsraOn=" + document.forms[0].fsraOn.value;
      }
      if (document.layers)
    	  newWin = window.open(url,'docBuild',centreWindow(400,128) + ',width=400,height=128,toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=no,resizable=no,copyhistory=no');
      else
    	  newWin = window.open(url,'docBuild',centreWindow(400,128) + ',width=400,height=128,toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=no,resizable=no,copyhistory=no');

    }
  }
}

// FSRA - Launch the pdf of Statement of Advice from DB2

function soaPrint(tfsraDocumentId, intermediaryCode, brokSysId) {
  var  callingProg = eval("\"soaDelayPrint('" + tfsraDocumentId + "','" + intermediaryCode + "','" + brokSysId + "');\"");
  setTimeout(callingProg, 2000);
}


function soaDelayPrint(tfsraDocumentId, intermediaryCode, brokSysId) {

  time = new Date().getTime();
  if (intermediaryCode == "") {
      url = "/servlet/SoaPrintPDFServlet?tfsraDocumentId=" + tfsraDocumentId + "&time=" + time + "&fromBrowser=Y";
  }
  else {
	  url = "/servlet/AuthoriseServlet?fsraDocument=" + tfsraDocumentId + "|IntermediaryId=" + intermediaryCode + "|LoginSystemUserId=" + brokSysId + "|system=Sunrise|fromURL=N|pdf=.pdf";
  }
  if (document.layers) {
    newWin = window.open(url,"soaPDF",centreWindow(760,400) + ",width=760,height=400,toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=yes,copyhistory=no");
  }
  else {
    newWin = window.open(url,"soaPDF",centreWindow(760,400) + ",width=760,height=400,toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=yes,copyhistory=no");
  }
  if (document.images) {
    newWin.focus();
  }
}


function directClaim(type) {
  if (isEmpty(type)) {
    type = prompt("Please enter the 3-character policy type. For example, HPK, BPK", "");

    if (isEmpty(type)) {
      return;
    } else {
      while (type.length != 3) {
        type = prompt("The policy type must be 3 characters. Please re-enter", "");

        if (isEmpty(type)) {
          return;
        }
      }
    }
  }

  type = type.toUpperCase();

  if (type == 'BPK') {
    var currentDate = new Date();
    var currTime = currentDate.getTime();

    newurl = "/claim/BPKOfflineSections.jsp?riskRequest=claim&effectiveDate=" + effectiveDate + "&policyNumber=" + "&policyType=" + type + "&policyRisk=" + "&time=" + currTime;

    if (navigator.userAgent.indexOf("IE") != -1) {
      newWin = window.open(newurl,"Policy",centreWindow(500,217) + ",width=500,height=217,toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=no,resizable=no,copyhistory=no");
    } else {
      newWin = window.open(newurl,"Policy",centreWindow(500,217) + ",width=501,height=217,toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=no,copyhistory=no");
    }

    newWin.focus();
  } else {
    claimForm(type,'','');
  }
}

function riskAttachments(policy, risk, action) {
  if (action == 'IP' || action == 'EC' || action == 'GP' || action == 'SC' || action == 'SV') {
    if (navigator.appName == 'Netscape') {
      var attachWind = window.open("/servlet/RiskAttachmentsServlet?effectiveDate=" + effectiveDate + "&policyNumber=" + policy + "&policyRisk=" + risk + "&policySection=&attachment=" + action, "RiskAttachments",centreWindow(501,217) + ", width=501,height=217,toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=no,copyhistory=no");
    } else {
      var attachWind = window.open("/servlet/RiskAttachmentsServlet?effectiveDate=" + effectiveDate + "&policyNumber=" + policy + "&policyRisk=" + risk + "&policySection=&attachment=" + action, "RiskAttachments",centreWindow(501,217) + ", width=500,height=217,toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=no,resizable=no,copyhistory=no");
    }

    if (document.images) {
      attachWind.focus();
    }
  } else {
    alert("Action type " + action + " is not valid. Only IP (Interested Parties), EC (Endorsement Clauses), GP (General Pages), SC (Specified Contents) and SV (Specified Valuables) are supported.");
    return false;
  }
}

function changeTab(form, tabName, direction) {
  var errList = "";
  var err = "";
  var currentSection = parseInt(form.currentSection.value);
  form.toTab.value = tabName;

  if (direction != 'prev') {
    if ((err = verifyTabDetails(form)) != "") {
      errList += err + "\n";
    }
  } else {
    setCheckBox(form);
  }

  if (errList == "" || direction == 'prev') {
        if (direction == 'next') {
         currentSection += 1;
       } else if (direction == 'prev' && currentSection > 0) {
         currentSection -= 1;
       }
    form.currentSection.value = currentSection;



    form.submit();
     if (direction == 'next') {
        _disableLink("nextTab");
    } else {
        _disableLink("prevTab");
    }
  } else {
    var msg = "Please complete the following fields:";
    msg += "\n\n" + errList;
    alert(msg);
  }
}

function setCheckBox(form) {
  // default function, do nothing! BPK claim's BMB, BMC and BGP overloads it.
}

// Used to validate a date field
/////////////////////////////////////////
function isValidDate(dateStr) {

  if (isEmpty(dateStr)) {
    // The date can't be empty
    return false;
  } 
  else if (dateStr.indexOf('/') <= 0) {
    // The date must have forward slashes
    return false;
  } 
  else {
    var day  = dateStr.substring(0, dateStr.indexOf("/"));
    var mth  = dateStr.substring(dateStr.indexOf("/") + 1, dateStr.lastIndexOf("/"));
    var year = dateStr.substring(dateStr.lastIndexOf("/") + 1);

    // Check that the day, month and year are numbers
    if (isNaN(day) || isNaN(mth) || isNaN(year)) {
      return false;
    }
    
    // Check there are no dots within the numbers
    if ( (day.indexOf('.') >= 0) || (mth.indexOf('.') >= 0) || (year.indexOf('.') >= 0)) {
      return false;
    }    
    

    day = day.substring(0, 1) == "0" ? parseInt(day.substring(1)) : parseInt(day);
    mth = mth.substring(0, 1) == "0" ? parseInt(mth.substring(1)) : parseInt(mth);
    year = parseInt(year);

    if (mth > 12 || mth < 1 || year == 0 || (day > 30 && (mth == 4 || mth == 6 || mth == 9 || mth == 11)) || (day > 31) || (day > 29 && mth == 2) ||
     (day > 28 && mth == 2 && !((year % 4 == 0 && year % 100 != 0) || year % 400 == 0)) || (year < 1800)) {
      return false;
    }

    return true;
  }
}

// new version of data validation function, added in PI project.
// Can check data format dd/mm/yyyy or mm/yyyy
function validDateField (input, hasDateField) {
    var validformat=/^\d{1,2}\/\d{1,2}\/\d{4}$/ //Basic check for format validity
    var returnval = false;
    if (input) {
        var dateStr = input.value;
        if(!hasDateField){
            dateStr = "01/" + dateStr;
        }
        if (!validformat.test(dateStr)) {
            returnval = false;
        }
        else{
            //Detailed check for valid date ranges
            var dayfield=dateStr.split("/")[0];
            var monthfield=dateStr.split("/")[1];
            var yearfield=dateStr.split("/")[2];
            var dayobj = new Date(yearfield, monthfield-1, dayfield);

            if ((dayobj.getMonth()+1!=monthfield)||(dayobj.getDate()!=dayfield)||(dayobj.getFullYear()!=yearfield))
                returnval = false;
            else
                returnval=true;
        }

        if (returnval==false)
            input.select();
    }

    return returnval;
}

function accountSearchByPolicyType(fieldname, policyType) {
   var url = "/common/AccountSearch.jsp?fieldName=" + fieldname + "&policyType=" + policyType;

  if (navigator.appName.index == 'Netscape' || navigator.userAgent.indexOf('Gecko') != -1) {
    newWin = window.open(url,"AccountSearch",centreWindow(500,217) + ",width=500,height=217,toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=no,copyhistory=no");
  } else {
    newWin = window.open(url,"AccountSearch",centreWindow(500,217) + ",width=500,height=217,toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=no,resizable=no,copyhistory=no");
  }

  if (document.images) {
    newWin.focus();
  }
}

function accountSearch(fieldName) {
  var url = "/common/AccountSearch.jsp?fieldName=" + fieldName;

  if (navigator.appName.index == 'Netscape' || navigator.userAgent.indexOf('Gecko') != -1) {
    newWin = window.open(url,"AccountSearch",centreWindow(500,217) + ",width=500,height=217,toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=no,copyhistory=no");
  } else {
    newWin = window.open(url,"AccountSearch",centreWindow(500,217) + ",width=500,height=217,toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=no,resizable=no,copyhistory=no");
  }

  if (document.images) {
    newWin.focus();
  }
}

function selectAccount(fieldName, name, status, policyType, branch) {
  var resultUrl = "/servlet/AccountServlet?fieldName=" + fieldName + "&name=" + name + "&status=" + status + "&searchAction=S&policyType=" + policyType + "&branch=" + branch ;

  if (navigator.appName.index == 'Netscape' || navigator.userAgent.indexOf('Gecko') != -1) {
    resultWin = window.open(resultUrl,"SearchResult",centreWindow(701,500) + ",width=701,height=500,toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=no,copyhistory=no");
  } else {
    resultWin = window.open(resultUrl,"SearchResult",centreWindow(701,500) + ",width=700,height=500,toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=no,resizable=no,copyhistory=no");
  }

  if (document.images) {
    resultWin.focus();
  }

  if (newWin != null) {
    newWin.close();
  }
}

function verifyABN(abnNum) {
  var checksum = (abnNum.substring(0, 1) - 1) * 10 + abnNum.substring(1, 2) * 1 + abnNum.substring(2, 3) * 3 +
    abnNum.substring(3, 4) * 5 + abnNum.substring(4, 5) * 7 + abnNum.substring(5, 6) * 9 +
    abnNum.substring(6, 7) * 11 + abnNum.substring(7, 8) * 13 + abnNum.substring(8, 9) * 15 +
    abnNum.substring(9, 10) * 17 + abnNum.substring(10, 11) * 19;

  return (checksum % 89 != 0 ? false : true);
}

function radioButton(field) {
  for (i = 0; i < field.length; i++) {
    if (field[i].checked)
      return (i);
    }
    return (-1);
}



 // Function that gets a cookie?s value by searching
 // for the name of the cookie.

 function readCookie(name) {
  var cookies = document.cookie;
//  alert("cookies : " + cookies);
  var start;
  var end;
  var value;

  start = cookies.indexOf(name + "=");

  if (start == -1){
   return '';
  } start = cookies.indexOf("=", start) + 1;

  end = cookies.indexOf(";", start);

  if (end == -1){
   end = cookies.length;
  }


  value = unescape(cookies.substring(start, end));

  if(value == null){
   return '';
  }
  else{
   return value;
  }
 }



 // Function that sets a cookie?s value

 function setCookie(name, value) {
  document.cookie = name + "=" + value;
 }

 // disables a link that we dont want to be clicked again (useful for stopping multiple clisks on ADD or SUBMIT links)
 //   - linkId is id on the <A> tag eg <a href="blah" id="linkId">link text</a>
 //   - color is the color to set link text to give a disabled look
 //   - _document is the document where the link came from (see IPMSummaryInfo.jsp for example of use)
 ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
 function _disableLink( linkId, color, _document ) {

   // default color if none supplied
   if ( isEmpty (color) ) {
       color = "silver" ;
   }

   // Use cuurent document if _document is not specified
   if ( isEmpty (_document) ) {
       _document = document;
   }

   // Check the element exists.
   // If the element has a type field then its not a link
   // ie a button has a type property
   linkElem = _document.getElementById (linkId) ;

   // if link is on page - this will be the <a> tag
   if ( ( linkElem ) && (! linkElem.type) ) {
      linkElem.href                      = "#";                               // href link goes nowhere
      linkElem.onclick                   = "javascript:return(false);";       // return false tells browser we didnt really click a link
      linkElem.style.textDecoration      = "none";                            // remove underline
      linkElem.style.cursor              = "default";                         // remove hand cursor
      linkElem.style.color               = color;                             // change color to give the disabled look (ie grey it)
      if (linkElem.lastChild.style) {
         linkElem.lastChild.style.color  = color;                             // "grey" it out - we assume the last child of  <a> contains clickable text and might have a style color
      }
   }
 }


 // disables a link that we dont want to be clicked again (useful for stopping multiple clisks on ADD or SUBMIT links)
 //   - linkId is id on the <A> tag eg <a href="blah" id="linkId">link text</a>
 //   - color is the color to set link text to give a disabled look
 ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
 function _enableLink( linkId, color, linkAction ) {

   // default color if none supplied
   if ( isEmpty (color) ) {
       color = "silver" ;
   }

   // Check the element exists.
   // If the element has a type field then its not a link
   // ie a button has a type property
   linkElem = document.getElementById (linkId) ;

   // if link is on page - this will be the <a> tag
   if ( ( linkElem ) && (! linkElem.type) ) {

      linkElem.href                      = linkAction;                        // href link goes nowhere
      linkElem.onClick                   = linkAction;       // return false tells browser we didnt really click a link
      linkElem.style.textDecorationNone  = "underline";                       // remove underline
      linkElem.style.cursor              = "hand";                            // remove hand cursor
      linkElem.style.color               = color;                             // change color to give the disabled look (ie grey it)
      if (linkElem.lastChild.style) {
         linkElem.lastChild.style.color  = color;                             // "grey" it out - we assume the last child of  <a> contains clickable text and might have a style color
      }
   }
 }

 function _enableLinkClick( linkId, color, linkAction ) {

   // default color if none supplied
   if ( isEmpty (color) ) {
       color = "silver" ;
   }

   // Check the element exists.
   // If the element has a type field then its not a link
   // ie a button has a type property
   linkElem = document.getElementById (linkId) ;

   // if link is on page - this will be the <a> tag
   if ( ( linkElem ) && (! linkElem.type) ) {

      linkElem.onclick                   = linkAction;       // return false tells browser we didnt really click a link
      linkElem.style.textDecorationNone  = "underline";                       // remove underline
      linkElem.style.cursor              = "hand";                            // remove hand cursor
      linkElem.style.color               = color;                             // change color to give the disabled look (ie grey it)
      if (linkElem.lastChild.style) {
         linkElem.lastChild.style.color  = color;                             // "grey" it out - we assume the last child of  <a> contains clickable text and might have a style color
      }
   }
 }

// set the style display property of the element for the given id so it is visible
function _elementDisplayShow ( elementId ) {

    if ( eval("document.getElementById('" + elementId + "')") ) {              // check element exists for Id
        var element = eval("document.getElementById('" + elementId + "')") ;   // get access to element
        element.style.display = "block";  				       				   // change it
    }
}

// set the style display property of the element for the given id so it is hidden
function _elementDisplayHide  ( elementId ) {

    if ( eval("document.getElementById('" + elementId + "')") ) {              // check element exists for Id
        var element = eval("document.getElementById('" + elementId + "')") ;   // get access to element
        element.style.display = "none";  		     						   // change it
    }
}

// returns true if element for the given id is visible on page
function _isElementDisplayVisible ( elementId ) {

	var visible = false;
    if ( eval("document.getElementById('" + elementId + "')") ) {              // check element exists for Id
        var element = eval("document.getElementById('" + elementId + "')") ;   // get access to element
        visible = (element.style.display != "none") ;
    }
	return visible;
}

 // APT-REQ1354
 // Function that tabs through form fields on enter key, up/down arrow and when field size is exceeded
 function autoTab(evt, thisFld, downFld, upFld, maxChars) {

	var code;
	if (evt.keyCode) code = evt.keyCode;
	else if (evt.which) code = evt.which;

    // tab to next field on enter key and arrow down; tab to previous field on arrow up
	if ( (code == 13  && evt.type == "keypress" ) || code == 40 || code == 38) {
        evt.keyCode = 0;
        evt.which = 0;
        if (code == 38) upFld.focus();
        else downFld.focus();
        return false;
    }
    // tab to next field if current field exceeds allowed length (disabled by supplying maxChars = 0)
    if (evt.type == "keypress" && thisFld.value.length >= maxChars && maxChars > 0) {
        downFld.focus();
        return false;
    }
    return true;
 }

// Function which validates email address
function verifyEmail(email) {
  var errList = "";
  if (email.length >0 && (email.indexOf("@",0) == -1||email.indexOf(".",email.indexOf("@")) == -1) ||
     (email.indexOf("@")== 0) || (email.indexOf(".")== 0)) {
    errList +="Incorrect email address. Enter your full Email Address \n";
  }

  if(email.substring(email.length-1,email.length)== "."){
  	errList +="Invalid Email Address. Cannot end with '.' \n";
  }

  if(email.substring(email.length-1,email.length)== "@"){
    errList +="Invalid Email Address. Cannot end with '@' \n";
  }

  if ((email.indexOf("!",0) != -1)||(email.indexOf("%",0) != -1)||
      (email.indexOf("^",0) != -1)||(email.indexOf("$",0) != -1)||(email.indexOf("*",0) != -1)||
      (email.indexOf("+",0) != -1)||(email.indexOf("=",0) != -1)||(email.indexOf(",",0) != -1)||
      (email.indexOf("?",0) != -1)||(email.indexOf(":",0) != -1)||(email.indexOf(";",0) != -1)||
      (email.indexOf("~",0) != -1)||(email.indexOf("#",0) != -1)) {
	errList += "Invalid Characters !%^$*+=,?:;~# in Email Address\n";
  }

  if (email.indexOf(" ",0) != -1) {
	errList += "Space character is not allowed in Email Address\n";
  }
  return errList;
}

// Function which validates multiple email addresses that must be separated by ','.
function verifyEmails(emails) {
  var errList = "";
  beginIndex = 0;
  endIndex = 0;
  email = ""

  for ( i = 0; i < emails.length; i++) {
      if (emails.charAt(i) != ",") {
        email += emails.charAt(i);
      } else {
        // Trim leading and trailing spaces from email address before validation
        errList += verifyEmail(strTrim(email));
        email = "";
      }
  }
  // Validate the last email address if exists
  if (email != "") {
      errList += verifyEmail(strTrim(email));
      email = "";
  }
  // If error remind the user to use ',' as a separator.
  if (errList != "") {
    errList += "Use ',' to separate multiple email addresses\n";
  }
  return errList;
}

// Function which verify every character of the input string that is within the
// Basic Latin Unicode Range or new line character. In other words the character
// must exist on a typical keyboard.
// The initial purpose is to avoid FOP unconvertible character being entered.
//////////////////////////////////////////////////////////////////////////////
function validateBasicChar(inString) {
  var errList = "";
  len = inString.length;

  for ( i = 0; i < len; i++) {
    if (!((inString.charCodeAt(i) >=32 && inString.charCodeAt(i) <= 126)       // Basic Latin Unicode Range
          || inString.charCodeAt(i) == 10                                      // New line
          || inString.charCodeAt(i) == 13)                                     // Carriage return
       ) {
        errList += "Invalid character " + inString.charAt(i) + " is found\n";
    }
  }
  return errList;
}


function confirmQuestion(title,mess,icon,defbut,mods) {
   IE4 = (document.all);

   if (IE4) {
      icon = (icon==0) ? 0 : 2;
      defbut = (defbut==0) ? 0 : 1;
      retVal = makeMsgBox(title,mess,icon,4,defbut,mods);
      retVal = (retVal==6);
   }
   else {
      retVal = confirm(mess);
   }
   return retVal;
}

 // Simulate href link and disable link after clicking
 //   - url is the url to be called
 //   - linkId is id on the <A> tag eg <a href="blah" id="linkId">link text</a>
 //   - _document is the document where the link came from (see IPMSummaryInfo.jsp for example of use)
 ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
function submitHref(url, hrefLinkId, _document){

 // Use cuurent document if _document is not specified
 if ( isEmpty (_document) ) {
     _document = document;
 }

  _document.forms[0].action = url;
  _document.forms[0].submit();
  _disableLink(hrefLinkId, "", _document);
}


// convert a string value into int
// if strVal cannot be converted into int, return the defaultValue
function toInt(strVal, defaultValue) {
    var intVal = parseInt(strVal);
    if (isNaN(intVal)) {
        return defaultValue;
    }
    else {
        return intVal;
    }
}



