/*
 * Variable used for the Public Access Name Search Case Formatting.
 * I = Initial Capitalization
 * U = Uppercase
 * L = Lowercase
 */
var nameSearchCase = "U";

/*
 * Variables used for the Public Access Search XML configuration file.
 */
var searchXMLDoc = null;
var searchXMLDocIsLoaded = false;

/*
 * Load the Public Access Search XML configuration file into a variable.
 */
if (document.implementation && document.implementation.createDocument) {
    searchXMLDoc = document.implementation.createDocument("", "", null);
	searchXMLDoc.onload = searchXMLDocLoaded;
}	else if (window.ActiveXObject) {
	searchXMLDoc = new ActiveXObject("Microsoft.XMLDOM");
	searchXMLDoc.onreadystatechange = function () {
		if (searchXMLDoc.readyState == 4) {
		  searchXMLDocLoaded();
		}
	};
}

/*
 * Initialize Load of Page
 */
function initializeSearch() {

  displayProgressStatusText(null);

  // Load Config XML
  var formName = document.forms[0].name;
  if (searchXMLDoc != null) {
      searchXMLDoc.load("/pa/includes/" + formName + ".xml");
  }

  // Load Select options.
  loadPtyCdDropDown();
  loadCaseCdDropDown();
  loadStatCdDropDown();

}

// Validate and Display search process
function performSearch() {
 if (!validateSearch()) return false;
 displaySearchInProcess();
 return true;
}

/*
 * Submit Search page
 */
function validateSearch() {
  // Document was loaded
  if (searchXMLDoc.documentElement == null) return true;

  var elm = document.forms[0].elements;
  var rsltMsg = "";
  var minMsg = "";
  var minfound = false;
  var minreq = false;
  var returnStatus = true;
  for (var i = 0; i < elm.length; i++) {
      if (elm[i].type == 'text' || elm[i].type == 'select-one' || elm[i].type == 'radio') {
         var elmValue = elm[i].value;
         // Check Required
         if (getElementAttribute(elm[i].id, "required") == "true") {
             if ((elmValue == null) || (elmValue.length == 0)) {
                 rsltMsg = getSearchXMLElementValue(elm[i].id) + " is required to search.";
                 returnStatus = false;
                 break
             }
         }
         // Check for minimum search field
         if (getElementAttribute(elm[i].id, "minrequired") == "true") {
             minreq = true;
             if ((elmValue == null) || (elmValue.length == 0)) {
       	        if (minMsg.length > 0) {minMsg += " or ";}
                minMsg += getSearchXMLElementValue(elm[i].id);
             } else {
                minfound = true;
             }
         }

         // Check Length
         if ((elmValue != null) && (elmValue.length > 0)) {
            var minLength = getElementAttribute(elm[i].id, "minlength")
            if ((minLength == null) || (minLength == "")) {minLength = 0};
            if (elmValue.length < (minLength *1)) {
               rsltMsg = "At least " + minLength + " characters for " + getSearchXMLElementValue(elm[i].id) + " are required to search.";
               returnStatus = false;
               break;
            }
         }

      } // End element types
  } // end For

  if (returnStatus && minreq && !minfound) {
      rsltMsg = "The following are required to perform a search: " + minMsg;
      returnStatus = false;
  }

  resultMsg(rsltMsg);
  return returnStatus;

}


/*
 * The Public Access Search XML configuration file has been loaded
 * into the variable.
 */
function searchXMLDocLoaded() {
  searchXMLDocIsLoaded = true;
}

/*
 * Gets the XML element with the supplied name from the Search
 * XML configuration file.
 */
function getSearchXMLElementValue(xmlEleName) {
  var result = "";

  if ((xmlEleName != null) && (searchXMLDoc != null) && searchXMLDocIsLoaded) {
    var xmlEleList = searchXMLDoc.documentElement.getElementsByTagName(xmlEleName);

    if ((xmlEleList != null) && (xmlEleList.length > 0) && xmlEleList.item(0).hasChildNodes()
        && (xmlEleList.item(0).firstChild.nodeType == 3)) {
      result = xmlEleList.item(0).firstChild.nodeValue;
    }
  }

  return result;
}
/*
 * Gets the XML element's attribute value with the supplied element name and
 * attribute name from the Search XML configuration file.
 */
function getElementAttribute(xmlEleName, attribName) {
  var result = "";

  if ((xmlEleName != null) && (attribName != null) && (searchXMLDoc != null) && searchXMLDocIsLoaded) {
    var xmlEleList = searchXMLDoc.documentElement.getElementsByTagName(xmlEleName);

    if ((xmlEleList != null) && (xmlEleList.length > 0) && (xmlEleList.item(0).attributes != null) &&
        (xmlEleList.item(0).attributes.length > 0)) {
        result = xmlEleList.item(0).attributes.getNamedItem(attribName);

      if (result == null) {
        result = "";
      } else {
        result = result.nodeValue;
      }
    }
  }

  return result;
}

/*
 * Fetch Party Code Data
 */
function loadPtyCdDropDown() {

    if (document.getElementById("ptyCd") == null) return;

    var retRequest = getXMLHttpRequest();
    var retCallbackHand =  getCallBackHandler(retRequest, buildPtyCdDropDown);
    retRequest.onreadystatechange= retCallbackHand;
    retRequest.open("POST", "/pa/app", true);
    retRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    retRequest.send("service=xmlRecords/PtyCd");

}

/*
 * process XML and update party code options with results.
 */
function buildPtyCdDropDown(retXML) {

 var ptyCdFld = document.getElementById("ptyCd");
 var ptyCdLoading = document.getElementById("ptyCdLoading");
 var xmlEleList = retXML.documentElement.getElementsByTagName("ptycd");

    if ((xmlEleList != null) && (xmlEleList.length > 0) && (ptyCdFld != null) && (ptyCdLoading != null)) {

       for (var i = 0; i < xmlEleList.length; i++) {
           if ((xmlEleList.item(i).attributes != null) && (xmlEleList.item(i).attributes.length > 0)) {
               var codeOpt = new Option();
               result = xmlEleList.item(i).attributes.getNamedItem("pty_cd");
               if (result != null) {codeOpt.value = result.nodeValue;}

               result = xmlEleList.item(i).attributes.getNamedItem("dscr");
               if (result != null) {codeOpt.text = result.nodeValue;}

               // Build Options
               ptyCdFld.options[ptyCdFld.options.length] = codeOpt;

            } // end Attributes

       }  // End For

       ptyCdLoading.style.display = "none";
       ptyCdFld.style.display = "";

     } // End Xml Ele

}

/*
 * Fetch Case Code Data
 */
function loadCaseCdDropDown() {

    if (document.getElementById("caseCd") == null) return;

    var retRequest = getXMLHttpRequest();
    var retCallbackHand =  getCallBackHandler(retRequest, buildCaseCdDropDown);
    retRequest.onreadystatechange= retCallbackHand;
    retRequest.open("POST", "/pa/app", true);
    retRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    retRequest.send("service=xmlRecords/CaseCd");

}

/*
 * process XML and update case code options with results.
 */
function buildCaseCdDropDown(retXML) {

 var caseCdFld   = document.getElementById("caseCd");
 var caseCdLoading = document.getElementById("caseCdLoading");
 var xmlEleList = retXML.documentElement.getElementsByTagName("realCasecd");

    if ((xmlEleList != null) && (xmlEleList.length > 0) && (caseCdFld != null)) {

       for (var i = 0; i < xmlEleList.length; i++) {
           if ((xmlEleList.item(i).attributes != null) && (xmlEleList.item(i).attributes.length > 0)) {
               var codeOpt = new Option();
               result = xmlEleList.item(i).attributes.getNamedItem("case_cd");
               if (result != null) {codeOpt.value = result.nodeValue;}

               result = xmlEleList.item(i).attributes.getNamedItem("dscr");
               if (result != null) {codeOpt.text = result.nodeValue;}

               // Build Options
               caseCdFld.options[caseCdFld.options.length] = codeOpt;
            } // end Attributes

       }  // End For

       caseCdLoading.style.display = "none";
       caseCdFld.style.display = "";

     } // End Xml Ele

}

/*
 * Fetch Status Code Data
 */
function loadStatCdDropDown() {

    if (document.getElementById("statCd") == null) return;

    var retRequest = getXMLHttpRequest();
    var retCallbackHand =  getCallBackHandler(retRequest, buildStatCdDropDown);
    retRequest.onreadystatechange= retCallbackHand;
    retRequest.open("POST", "/pa/app", true);
    retRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    retRequest.send("service=xmlRecords/StatCd");

}

/*
 * process XML and update status code options with results.
 */
function buildStatCdDropDown(retXML) {

 var statCdFld   = document.getElementById("statCd");
 var statCdLoading = document.getElementById("statCdLoading");
 var xmlEleList = retXML.documentElement.getElementsByTagName("statcd");

    if ((xmlEleList != null) && (xmlEleList.length > 0) && (statCdFld != null)) {

       for (var i = 0; i < xmlEleList.length; i++) {
           if ((xmlEleList.item(i).attributes != null) && (xmlEleList.item(i).attributes.length > 0)) {
               var codeOpt = new Option();
               result = xmlEleList.item(i).attributes.getNamedItem("stat_cd");
               if (result != null) {codeOpt.value = result.nodeValue;}

               result = xmlEleList.item(i).attributes.getNamedItem("dscr");
               if (result != null) {codeOpt.text = result.nodeValue;}

               // Build Options
               statCdFld.options[statCdFld.options.length] = codeOpt;

            } // end Attributes

       }  // End For

       statCdLoading.style.display = "none";
       statCdFld.style.display = "";

     } // End Xml Ele

}

// Format SSN
//
// This function checks the format of the SSN number entered. This to
// verify that a valid ssn is entered for searching and case init.
//
//  Parameters
//    Object Pointer for ssn.
//
//  History
//    12/14/2000 RJB Initial coding.

function CheckSSN(src) {

	ssn = src.value;  // Value of SSN

	if (ssn.length < 1) {
	    return true;
	}

	var matchArr = ssn.match(/^(\d{3})-?\d{2}-?\d{4}$/);
	var numDashes = ssn.split('-').length - 1;

  if (matchArr == null || numDashes == 1) {
     msg = ' SSN is Invalid. Must be 9 digits format: NNN-NN-NNNN.';
     CRTVmsg(msg);
     src.focus();
     return false;
  }


  if (parseInt(matchArr[1],10)==0) {
     msg = ' SSN is Invalid. Can not start with 000.                  \n';
     CRTVmsg(msg);
     src.focus();
     return false;
  }

 // Format SSN Number Entered.
 if (ssn.substring(3, 4) != '-') {
    ssn = ssn.substring(0, 3) + '-' + ssn.substring(3, 12);
 }

 if (ssn.substring(6,7) != '-') {
   ssn = ssn.substring(0, 6) + '-' + ssn.substring(6, 12);
 }

 // Format Number
 src.value = ssn;

 return true;

}
// check SSN
function CheckSSN(src) {

	ssn = src.value;  // Value of SSN

	if (ssn.length < 1) {
	    return true;
	}

	var matchArr = ssn.match(/^(\d{3})-?\d{2}-?\d{4}$/);
	var numDashes = ssn.split('-').length - 1;

  if (matchArr == null || numDashes == 1) {
     alert(' SSN is Invalid. Must be 9 digits format: NNN-NN-NNNN.');
     return false;
  }

  if (parseInt(matchArr[1],10)==0) {
     alert(' SSN is Invalid. Can not start with 000.');
     return false;
  }

 // Format SSN Number Entered.
 if (ssn.substring(3, 4) != '-') {
    ssn = ssn.substring(0, 3) + '-' + ssn.substring(3, 12);
 }

 if (ssn.substring(6,7) != '-') {
   ssn = ssn.substring(0, 6) + '-' + ssn.substring(6, 12);
 }

 // Format Number
 src.value = ssn;

 return true;

}

/*
 * This function converts the initial character of the text value to uppercase.
 * Parameters:	src	(required)
 * onchange="initUpcase(this)"
 *
 */
function initUpcase(src) {
  if ((src != null) && (src.value != null) && (src.value.length > 0)) {
    var firstChar = src.value.substring(0, 1);

    if (/[^0-9A-Z]/.test(firstChar)){
      firstChar = firstChar.toUpperCase();
    }

    var restChars = "";

	  if (src.value.length > 1) {
    	restChars = src.value.substr(1);
      }
	  src.value = firstChar + restChars;
  }

}

/**
 * This function converts the supplied element's value to the defined name search case format.
 * Parameters:  ele (required)
 * onblur="convertNameSearchCase(this)"
 */
function convertNameSearchCase(ele) {
  if ((typeof ele != "undefined") && (ele != null)
      && (typeof ele.value != "undefined") && (ele.value != null)
      && (ele.value.length > 0) && (typeof nameSearchCase != "undefined")) {
    if ((nameSearchCase == null) || (nameSearchCase.length != 1)) {
      nameSearchCase = "I";
    } else {
      nameSearchCase = nameSearchCase.toUpperCase();
    }

    var eleName = ele.value;

    if (nameSearchCase == "U") {
      eleName = eleName.toUpperCase();
    } else if (nameSearchCase == "L") {
      eleName = eleName.toLowerCase();
    } else {
      eleName = eleName.toLowerCase();
      var curChar = eleName.substring(0, 1).toUpperCase();

      if (eleName.length > 1) {
        var before = "";
        var after = eleName.substr(1);
        eleName = curChar + after;

        var spacePos = eleName.indexOf(" ", 1);
        var quotePos = eleName.indexOf("'", 1);

        while ((spacePos > -1) || (quotePos > -1)) {
          var thePos = spacePos;

          if ((quotePos > -1)
              && ((spacePos == -1) || (spacePos > quotePos))) {
            thePos = quotePos;
          }

          if (thePos + 1 < eleName.length) {
            curChar = eleName.substring(thePos + 1, thePos + 2).toUpperCase();
            before = eleName.substring(0, thePos + 1);

            if (thePos + 2 < eleName.length) {
              after = eleName.substr(thePos + 2);
            } else {
              after = "";
            }

            eleName = before + curChar + after;
          }

          if (thePos + 1 >= eleName.length) {
            break;
          }

          spacePos = eleName.indexOf(" ", thePos + 1);
          quotePos = eleName.indexOf("'", thePos + 1);
        }
      } else {
        eleName = curChar;
      }
    }

    ele.value = eleName;
  }
}

// Check format
function datefmt(src) {

 dt = src.value;
 if ((dt == "") || (dt.length == 0)) return true;

 curdate    = new Date();
 var err    = 0;
 var valchr = "0123456789/";
 var tmp    = "";
 var i;
 var msg = "Date";

 // Check for valid characters Numeric or forward slash
 for (i=0; i < dt.length; i++) {
     tmp = "" + dt.substring(i, i+1);
     if (valchr.indexOf(tmp) == "-1") err = 1;
 }

 // 08/10/2004 MBA Modified to return a blank value instead of 'true'.
 //if (dt.length < 1) return true;  // No Date entered
 if (dt.length < 1) {
 	  rtDate = "";
 	  return rtDate;
 }

// Added Zeros Month and Day
 if (dt.substring(1, 2) == '/') dt = '0' + dt;  // Add zero to month
 if ((dt.length == 5) || (dt.length == 3)) dt = '0' + dt;  // Add zero to month

 if (dt.substring(4, 5) == '/') {
    dt = dt.substring(0,3) + '0' + dt.substring(3,10);  // Add zero to day
 }

 if (dt.length < 4) err=1;

 if (dt.substring(2, 3) != '/') {
   dt = dt.substring(0, 2) + '/' + dt.substring(2, 10);
 }

 if (dt.substring(5,6) != '/') {
   dt = dt.substring(0, 5) + '/' + dt.substring(5, 10);
 }

 // Default year and or Century
 fyy = curdate.getFullYear();
 // Year and Century
 if (dt.length == 6) {
    dt = dt + fyy.toString();
 }
 // Century
 if (dt.length == 8) {
    cen = fyy.toString();
    cen = cen.substring(0, 2);
    if ((dt.substring(6, 8) *1) > 19) cen = "19";  // RJB added 04/23/04
    dt  = dt.substring(0, 6) + cen + dt.substring(6, 8);
 }

 // must be 10 now..
 if (dt.length != 10) err=1;

 mm  = dt.substring(0, 2); // month
 dd  = dt.substring(3, 5); // day
 cc  = dt.substring(6, 8); // Century
 yy  = dt.substring(8, 10); // year

 if (mm.length == 1) mm = '0' + mm;
 if (dd.length == 1) dd = '0' + dd;

 if (mm < 1 || mm > 12) err = 1;

 if (dd < 1 || dd > 31) err = 1;

 if (yy < 0 || yy > 99) err = 1;

 if (mm == 4 || mm == 6 || mm == 9 || mm == 11){
   if (dd == 31) err=1;
 }

 if (mm == 2){
   var g=parseInt(yy / 4);
   if (isNaN(g)) {
     err=1;
   }
   if (dd > 29) err=1;
   if (dd == 29 && ((yy / 4)!=parseInt(yy / 4))) err=1;
 }

 if (err==1) {
   // Error message, set field focus
   msg += " is invalid. Format: MM/DD/YYYY";

   resultMsg(msg);

   src.value = "";
   return false;
 }
   // Set field with format
  resultMsg("");
  src.value = dt;

  return true;
}

// Display Result Msg
function resultMsg(msg) {
   xInnerHtml("rsltMsg", msg);
}

/*
 * Display the search in process status text.
 */
function displaySearchInProcess() {
  var searchButton = xGetElementById("searchButton");

  if (searchButton != null) {
    searchButton.disabled = true;
  }

  displayProgressStatusText("Your Search request is being processed.");
}

