// initialize variables
var Ns4 = false; var Ns5 = false; var Ns6 = false; var Ns4up = false; 
var Ie4 = false; var Ie5 = false; var Ie6 = false; var Ie4up = false; 
var Ie5up = false;

if (document.images) {
	ctnBtnPressed = new Image();
	ctnBtnPressed.src = "/stf/images/buttons/continue_f2.gif";
}

if (navigator.appName.indexOf("Netscape") != -1) 
{ 
  if (navigator.userAgent.indexOf("Netscape6") != -1) Ns6 = true; 
  else if (parseInt(navigator.appVersion) >= 5) Ns5 = true; 
  else if (parseInt(navigator.appVersion) >= 4) Ns4 = true; 
  if (Ns4 || Ns5 || Ns6) Ns4up = true; 
} 
else if (navigator.appName.indexOf("Explorer") != -1) 
{ 
  if (navigator.userAgent.indexOf("MSIE 6") != -1) Ie6 = true; 
  if (navigator.userAgent.indexOf("MSIE 5") != -1) Ie5 = true; 
  else if (parseInt(navigator.appVersion) >= 4) Ie4 = true; 
  if (Ie4 || Ie5 || Ie6) Ie4up = true; 
  if (Ie5 || Ie6) Ie5up = true;
} 

DEBUG = false;
var activeElement = null;
if(DEBUG) window.status = activeElement;

/**
 * Function:	keyPress(event)
 * Purpose:	Capture enter key press events
 * Params:	evt 
 * Returns:	Traps and handles enter key events:
 **/
 
if (Ns4up)                                
  document.captureEvents(Event.KEYPRESS); 

document.onkeypress = keyPress;          
function keyPress(evt) 
{
   var key;
   if(Ns4up) 
      key = evt.which;
   if(Ie4up) 
      key = event.keyCode;
   if (key == 13) 
   {
      if(isFocusTracked())
        return;
      else
        return false;
   }
}

/**
 * Function:	trackFocus(object)
 * Purpose:	Track which form element, if any, has cursor focus
 *		Sets value of global variable activeElement
 * Params:	obj tracked
 * Returns:	nothing
 **/
 
function trackFocus(obj)
{
   if(activeElement == null) 
   {
      activeElement = obj;
      if(DEBUG) window.status = activeElement.name;
   }
   else
   {
      activeElement = null;
      if(DEBUG) window.status = activeElement;
   }
}

/**
 * Function:	isFocusTracked()
 * Purpose:	Check if focus is on a text, password, textarea or
 *		submit form element when enter key pressed
 * Params:	none
 * Returns:	boolean 
 **/

function isFocusTracked()
{
   if(activeElement)
   {
        if (activeElement.type == "textarea"||
            activeElement.type == "button"  ||
            activeElement.type == "submit")
        return true;
      else if(activeElement.type == "text"  ||
              activeElement.type == "password")
        tabNext();
      else
        return false;
    }
    else
      return false;  
}

/**
 * Function:	tabNext()
 * Purpose:	Simulate tab key when enter key pressed
 *		Moves focus to next element in form's element array
 * Params:	none
 * Returns:	nothing
 **/
 
function tabNext()
{
   var elements = document.forms[0].elements;
   for (var i = 0; i < elements.length; i++)
   {
      if(elements[i].name == activeElement.name)
      {
         elements[++i].focus();
         break;
      }
   }
}

/**
 * Function:	placeFocus()
 * Purpose:	Place focus on first form field; called by 
 *		writeScript("placeFocus()") in pageRequestBegin()
 * Params:	none
 * Returns:	nothing
 **/
 
function placeFocus() 
{
   if (document.forms.length > 0) 
   {
      var frm = document.forms[0];
      for (i = 0; i < frm.length; i++) 
      {
         if ((frm.elements[i].type == "text") || 
             (frm.elements[i].type == "password") || 
             (frm.elements[i].type == "textarea")) 
         {
            frm.elements[i].focus();
            break;
         }
      }
   }
}

//submit form
function submitBtn_onClick(){
  if (isFormValid()) {
     document.forms[0].submit();
     disableControls();
  }
  return !buttonReturn();
}


/**
 * Function: openPopupWindow(object)
 * Purpose:	Open a popup window assigning window reference to the
 * popupWindow variable.
 * Params:	link - URI to the window
 *          name - name to give this window for raising and modality
 *          width - popup window width
 *          height - popup window height
 * Returns:	nothing
 **/
var popupWindow;

function openPopupWindow(link, name, width, height)
{
	popupWindow = window.open(link, name,
		"resizable=no,scrollbars=no,toolbar=no,menubar=no,status=no,"
		+ "width=" + width + ",height=" + height);
 
	if (popupWindow != null)
	{
		popupWindow.focus();
	}
}

function openResizeablePopupWindow(link, name, width, height)
{
	popupWindow = window.open(link, name,
		"resizable=no,scrollbars=yes,toolbar=no,menubar=no,status=no,"
		+ "width=" + width + ",height=" + height);
 
	if (popupWindow != null)
	{
		popupWindow.focus();
	}
}

/**
 * Function: closePopupWindow(object)
 * Purpose:	Closes the popup window referenced by the win variable
 * after first initiating a window reloads on the parent window.
 * Params:	win - the window reference to close
 * Returns:	nothing
 **/
function closePopupWindow(win){
	closePopupWithDelay(win)
}

function reloadPage(){
	var s = location.href;
	location.href = s;
	//location.reload();
}

function closePopupWithDelay(win){	
	win.close();
	setTimeout('reloadPage();',10); 
}


/**
 * Function:	addPlotData(object)
 * Purpose:	Add plot data to the plot data controls.
 * Params:	object - the input object from which the plot data
 *   is collected and validated before being added to the plot list
 * Returns:	nothing
 **/

function addPlotData(object, plotNumberTextArea, plotNumberListbox)
{
	if (object.value.length == 0)
	{
		return;
	}
	else if (trim(object.value).length == 0)
	{
		object.value = "";
		return;
	}
	else
	{
		sInvCharsExp = /['"`&]/;

		if (object.value.search(sInvCharsExp) != -1)
		{
			alert("the plot number data contains invalid characters\n"
				+ "invalid characters are: \" ' ` & \n"
				+ "make the necessary corrections and try again");

			plotNumberTextArea.focus;
		
			return;
		}
	}
	var sPlotList = new Array();
	var iCount = 0;

	sDelimExp = /s*[|:;,\011\012\014\015]\s*/;   

	sPlotList = filterPlotData(object.value, sDelimExp);
	
	if (sPlotList == null)
	{
		return;
	}

	if (parseInt(plotNumberListbox.length) - 1 + parseInt(sPlotList.length) > 99)
	{
		alert("the number of plot numbers entered ("
			+ (parseInt(plotNumberListbox.length) - 1 + parseInt(sPlotList.length)) + ")\n"
			+ "exeeds the allowable maximum of 99, reduce\n"
			+ "the number of plot numbers and try again");

		plotNumberTextArea.focus;

		return;
	}
	
	if (sPlotList != null)
	{
		iCount = 0;

		while (iCount < sPlotList.length)
		{
			if (isDuplicateInArray(sPlotList, iCount) ||
			    isDuplicateInList(sPlotList[iCount], plotNumberListbox))
			{
				alert("duplicate or invalid plot number '" + sPlotList[iCount] + "'\n"
					+ "correct this plot number and try again");

				plotNumberTextArea.focus;

				return;
			}
			iCount++;
		}
		iCount = 0;

		while (iCount < sPlotList.length)
		{
			addPlotNumber(sPlotList[iCount],plotNumberTextArea, plotNumberListbox);
			iCount++;
		}

		object.value = "";
	}
}

/**
 * Function:	addPlotNumber(string)
 * Purpose:	Add an individual plot number element to the display list
 * Params:	sPlotNum 
 * Returns:	nothing
 **/

function addPlotNumber(sPlotNum, plotNumberTextArea, plotNumberListBox)
{
	plotNumberListBox.options[plotNumberListBox.length]
		= new Option(sPlotNum, sPlotNum);
	plotNumberTextArea.value = "";
}

/**
 * Function:	filterPlotData(string, string)
 * Purpose:	
 * Params:	sPlotData , sDelimExp 
 * Returns:	Array of "clean" plot numbers
 **/

function filterPlotData(sPlotData, sDelimExp)
{
	var iCount = 0;
	var sPlotArray = new Array();

	if (sPlotData.length == 0)
	{
		return null;
	}
	sTokens = sPlotData.split(sDelimExp);


	while (iCount < sTokens.length)
	{
		sPlot = trim(sTokens[iCount]);

		if (sPlot.length > 16) 
		{
			alert("the specified plot number '" + sPlot + "'\n"
				+ "exceeds the maximum allowable length of 16 chars\n"
				+ "correct this plot number and try again");
			return null;
		}
		else if (sPlot.length > 0)
		{
			sPlotArray[iCount] = sPlot;
		}

		iCount++;
	}
	return sPlotArray;
}

/**
 * Function:	isDuplicateInArray(Array, integer)
 * Purpose:	Determine if a plot number is a duplicate in the
 *		internal storage array
 * Params:	sPlotList - the plot number data to check
 *		iIndex - the array index of the plot number entry
 * Returns:	boolean 
 **/

function isDuplicateInArray(sPlotList, iIndex)
{
	for (var i = sPlotList.length - 1;  (i > -1) && (i != iIndex); i--)
	{
		if (sPlotList[i] == sPlotList[iIndex])
		{
			return true;
		}
	}
	
	return false;
}

/**
 * Function:	isDuplicateInList(string)
 * Purpose:	Determine if a plot number is a duplicate in display list
 * Params:	sPlotNumberData
 * Returns:	boolean 
 **/
 
function isDuplicateInList(sPlotNumberData, plotNumberList)
{
	for (var i = plotNumberList.length - 1;  i > -1 ; i--)
	{
		if (plotNumberList.options[i].value == sPlotNumberData)
		{
			return true;
		}
	}
	
	return false;
}

/**
 * Function:	storePlotData(object)
 * Purpose:	
 * Params:	object - the control where the plot data will be stored
 * Returns:	nothing
 **/

function storePlotData(object, inPlotNumberList)
{
	var plotString = "";
	sSeparator = " | ";

	for (var i = inPlotNumberList.length - 1;  i > 0 ; i--)
	{
		plotString = plotString + inPlotNumberList.options[i].value;
		if (i > 1) plotString = plotString + sSeparator;
	}
	object.value = plotString;
}

/**
 * Function:	delSelectedPlotData()
 * Purpose:	multiple selections are permitted
 * Params:	none
 * Returns:	nothing
 **/

function delSelectedPlotData(plotNumberListbox)
{
	for (var i = plotNumberListbox.length - 1;  i > -1 ; i--)
	{
		if (plotNumberListbox.options[i].selected)
		{
			if (i > 0)
			{
				plotNumberListbox.options[i] = null;
			}
			else
			{
				plotNumberListbox.options[i].selected = false;
			}
		}
	}
}

/**
 * Function:	validateObjectLength(object, integer)
 * Purpose:	Validate the length of the specified control object
 *		typically a text field, against the gievn max length
 * Params:	object,len 
 * Returns:	boolean 
 **/

function validateObjectLength(object, len)
{
	return (object.length <= len);
}

/**
 * <<<<< DEPRECATED >>>>> use validateObjectLength()
 **/
function validatePropertyDescription()
{
	var propdesc = Page.spPropertyDetails.taPropertyDescription.value;

	if (propdesc.length > 1024)
	{
		alert("Property description is limited to 1,024 characters.");
		Page.spPropertyDetails.taPropertyDescription.focus();

		return false;
	}

	return true;
}

/**
 * Function:	isListElementSelected()
 * Purpose:	Determines if an element in a list box is selected
 *		Only supports lists which provide, as their first
 *		element (at index 0), a default element representing
 *		no selection, such as: <select data provider>
 * Params:	object - the control object to check
 * Returns:	boolean
 **/

function isAdminAreaSelected(object)
{
	return (object.selectedIndex > 0);
}

/**
 * Function:	trim(string)
 * Purpose:	Remove leading and trailing whitespace from a string
 * Params:	strText 
 * Returns:	string 
 **/
 
function trim(strText)
{
	while (strText.substring(0,1) == ' ') 
		strText = strText.substring(1, strText.length);
	while (strText.substring(strText.length-1,strText.length) == ' ')
		strText = strText.substring(0, strText.length - 1);

	return strText;
}

/**
 * Function:	isBlank(string)
 * Purpose:	Check whether the input value is all blank
 * Params:	strText 
 * Returns:	boolean
 **/

function isBlank(strText)
{
	for (var i = 0; i < strText.length; i++)
	{
		var c = strText.charAt(i);
		if (c != ' ' && c != '\n' && c != '\t') return false;
	}

	return true;
}

/**
 * Function:	isAlphaNumeric(unknown)
 * Purpose:	Check whether the input value is alphanumeric
 * Params:	inputVal 
 * Returns:	boolean
 **/

function isAlphaNumeric (inputVal)
{
	inputStr = inputVal.toString();
	for (var i = 0; i < inputStr.length; i++)
	{
		var oneChar = inputStr.charAt(i);

		if ((oneChar < "0" || oneChar > "9") &&
		    (oneChar < "a" || oneChar > "z") &&
		    (oneChar < "A" || oneChar > "Z"))
		{
			return false;
		}
	}

	return true;
}

/**
 * Function:	isValidDate(string)
 * Purpose:	Check whether the input value is a valid date
 * Params:	inputStr 
 * Returns:	boolean 
 **/

function isValidDate(inputStr)
{
	var delim1 = inputStr.indexOf("/");
	var delim2 = inputStr.lastIndexOf("/");

	if ((delim1 == -1) || (delim1 != -1 && delim1 == delim2))
	{
		return false;		
	}
	else
	{
		if (	!isNumeric(inputStr.substring(0, delim1))
			||	!isNumeric(inputStr.substring(delim1 + 1, delim2))
			||	!isNumeric(inputStr.substring(delim2 + 1, inputStr.length))
		   )
		{
			return false;
		}
	
		var dd = parseInt(inputStr.substring(0, delim1), 10);
		var mm = parseInt(inputStr.substring(delim1 + 1, delim2), 10);
		var yyyy = parseInt(inputStr.substring(delim2 + 1, inputStr.length), 10);

		if (isNaN(dd) || isNaN(mm) || isNaN(yyyy)) { return false; }

		if ((yyyy < 1000) || (yyyy > 9999)) { return false; }

		if ((mm < 1) || (mm > 12)) { return false; }

		if (!isValidDay(dd,mm,yyyy)) { return false; }

		return true;
	}
}





/**
 * Function:	isValidDay(string, string, string)
 * Purpose:	Check whether the input value is a valid day
 * Params:	dd, mm, yy 
 * Returns:	boolean
 **/

function isValidDay(dd, mm, yyyy)
{
	var yeardays = new Array(0, 31,28,31, 30,31,30, 31,31,30, 31,30,31); 
	var leapdays = new Array(0, 31,29,31, 30,31,30, 31,31,30, 31,30,31); 

	if (dd <= 0) { return false; }
	if ((yyyy % 100) == 0) 
	{
		if ((yyyy % 400) > 0) 
		{
	
			return (dd <= yeardays[mm]);
		} 
		else
		{
	
			return (dd <= leapdays[mm]);
		}
	}
	if ((yyyy % 4) > 0)
	{ 
		return (dd <= yeardays[mm]);
	}
	else
	{
		return (dd <= leapdays[mm]);
	}
}

/**
 * Function:	isNotFutureDate(string)
 * Purpose:	Check whether the input value is a not a Future date
 * Params:	inputStr 
 * Returns:	boolean 
 **/

function isNotFutureDate(inputStr)
{
    var delim1 = inputStr.indexOf("/");
	var delim2 = inputStr.lastIndexOf("/");

	var dd = parseInt(inputStr.substring(0, delim1), 10);
	var mm = parseInt(inputStr.substring(delim1 + 1, delim2), 10);
	var yyyy = parseInt(inputStr.substring(delim2 + 1, inputStr.length), 10);
  
        var d = new Date();
        var currdd = d.getDate();
        var currmm = 1 + d.getMonth();
        var curryyyy = d.getFullYear();
   	if (yyyy > curryyyy) 
	{ 
	return false; 
	}
    if (((mm == currmm) && (yyyy == curryyyy)) && (dd > currdd))
	{ 
		return false; 
	}
    if (yyyy == curryyyy && mm > currmm) 
	{
		return false; 
	}
    return true;
}

/**
 * Function:	isValidDateRange(string, string)
 * Purpose:	Check whether the from and to dates give a valid date range
 * Params:	inputStr 
 * Returns:	boolean 
 **/

function isValidDateRange(fromDate, toDate)
{
    var fromDelim1 = fromDate.indexOf("/");
	var fromDelim2 = fromDate.lastIndexOf("/");

    var toDelim1 = toDate.indexOf("/");
	var toDelim2 = toDate.lastIndexOf("/");


	var fromdd = parseInt(fromDate.substring(0, fromDelim1), 10);
	var frommm = parseInt(fromDate.substring(fromDelim1 + 1, fromDelim2), 10);
	var fromyyyy = parseInt(fromDate.substring(fromDelim2 + 1, fromDate.length), 10);
  
    var todd = parseInt(toDate.substring(0, toDelim1), 10);
	var tomm = parseInt(toDate.substring(toDelim1 + 1, toDelim2), 10);
	var toyyyy = parseInt(toDate.substring(toDelim2 + 1, toDate.length), 10);
          
        
   	if (fromyyyy > toyyyy) 
	{ 
	return false; 
	}
    if (((frommm == tomm) && (fromyyyy == toyyyy)) && (fromdd > todd))
	{ 
		return false; 
	}
    if (fromyyyy == toyyyy && frommm > tomm) 
	{
		return false; 
	}
    return true;
}


/**
 * Function:	AlertAndRedirect(msg, url)
 * Purpose:	Display an alert with the specified message and then
 *		redirect to the specified URL after user acknowledges
 * Params:	msg , url 
 * Returns:	nothing
 **/

function AlertAndRedirect(msg, url)
{
	alert(msg);
	document.location = url;
}

/**
 * Function:	AlertAndReplace(msg, url)
 * Purpose :    Display an alert with the specified message,
 *              then replace the URL in the browser with the
 *              specified URL.
 */

function AlertAndReplace(msg, url)
{
	alert(msg);
	document.location.replace(url);
}


/*******************************************************************
 * 
 * Date: 0ct-11-2002  
 * Author: akarim
 * Confirm javascript method
 * 
 *******************************************************************/
function confirmAndRedirect(mssg, url,alturl)
{
	if (confirm (mssg))
	{
		window.location.replace(url);
//		document.location = url;
	}
	else
		window.location.replace(alturl);
//		document.location = alturl;
}

/**
 * Function:	disableControls()
 **/

function disableControls()
{
	disableAllControls();
	disableAllLinks();
	disableAllInputImages();
}

/**
 * Function:	disableAllControls()
 **/

function disableAllControls()
{
	var elements = document.forms[0].elements;

//    var elementslist;

	for (var i in elements)
	{
		if (elements[i])
		{
//            elementslist = elementslist + elements[i].name + " " + elements[i].type + " " + elements[i].id + "\n";
			if (elements[i].type == "text"     ||
				elements[i].type == "textarea" ||
				elements[i].type == "hidden"   ||
				elements[i].type == "password" ||
				elements[i].type == "fileUpload")
			{
				elements[i].onfocus = onTextDisabled;
			}

			if (elements[i].type == "button"   ||
				elements[i].type == "reset"    ||
				elements[i].type == "image"    ||				
				elements[i].type == "submit")
			{
				elements[i].onclick = onButtonDisabled;
			}
		}
	}
//	alert(elementslist);
}

/**
 * Function: disableAllInputImages()
 * Purpose:  disable images since they are not available
 *           through disableAllControls method
 * Params:	 none
 * Returns:	 nothing
 **/
function disableAllInputImages()
{
	var elements = document.all;
	for (var i in elements)	{
		if (elements[i])		{
			if (   (elements[i].type) 
			    && (elements[i].type == "image")){
              elements[i].disabled = true;
			}
		}
	}
}

/**
 * Function:	onTextDisabled()
 * Purpose:	Forces focus to this field to be discarded immediately
 *		by calling the blur() function on the current field.
 * Params:	none
 * Returns:	nothing
 **/

function onTextDisabled()
{
	this.blur();
}

/**
 * Function:	onButtonEnabled()
 * Function:	onButtonDisabled()
 * Function:	buttonReturn()
 * Purpose:	Enable/Disable an HTML button control 
 **/

function onButtonEnabled()
{
	return buttonReturn();
}

function onButtonDisabled()
{
	return !buttonReturn();
}

function buttonReturn()
{
	var bAppName = window.navigator.appName;
	var bAgent = window.navigator.userAgent;

	if (bAppName.indexOf("Explorer") >= 0 &&
		bAgent.indexOf("Mozilla/3") >= 0)
	{
		return false; 
	}
	else
	{
		return true; 
	}
}

/**
 * Function:	disableAllLinks()
 * Purpose:	Disables all links in the DOM.
 * Params:	none
 * Returns:	nothing
 **/

function disableAllLinks()
{
	for (var i in document.links)
	{
		if (document.links[i])
		{
			if (i != "length")
			{

				document.links[i].onclick = onLinkDisabled;
			}
		}
	}
}

/**
 * Function:	onLinkEnabled()
 * Function:	onLinkDisabled()
 * Function:	linkReturn()
 * Purpose:	Enable/Disable an HTML hyper-link control 
 * Params:	none
 * Returns:	nothing
 **/

function onLinkEnabled()
{
	return !linkReturn();
}

function onLinkDisabled()
{
	return linkReturn();
}

function linkReturn()
{
	var bAppName = window.navigator.appName;
	var bAgent = window.navigator.userAgent;

	if (bAppName.indexOf("Explorer") >= 0 &&
		bAgent.indexOf("Mozilla/3") >= 0)
	{
		return true; 
	}
	else
	{
		return false; 
	}
}




// Page Navigation Trail                                           */
function TSPageNav( textClass, anchorClass, url, curRec, recsPerPage, totalRecs, imagePath ) {


    wrapLength = 30;
    wrapIndex = 0;
  
    prevStart = curRec - recsPerPage;
    ttlPages = (totalRecs / recsPerPage);
    lastRec = curRec + recsPerPage;
    nextStart= curRec + recsPerPage;
    if ( totalRecs < recsPerPage ) {
        return;
    }
    if ( nextStart > totalRecs ) {
        nextStart = totalRecs-1;
    }
    document.write("<TABLE BORDER=\"0\"><TR><TD VALIGN=\"TOP\">");
    
    document.write("<TABLE>");
    document.write("<TD>");
    if ( curRec == 0 ) {
        document.write("<span class=\""+textClass+"\">Previous</span>");
    } else {
        document.write("<a class=\"bodyLink\" href=\""+url+"&startIndex="+prevStart+"&count="+recsPerPage+"\" title=\"Previous Page\">Previous</a>");
    }
    document.write("</TD>");
    document.write("</TABLE>");
    
    document.write("</TD><TD VALIGN=\"TOP\">");
    
    document.write("<TABLE>");
    document.write("<TD>");
    document.write("<IMG SRC=\""+imagePath+"/left_arrow.gif\" BORDER=\"0\" VALIGN=\"TOP\">");
    document.write("</TD>");
    document.write("</TABLE>");
    
    document.write("</TD>");
    document.write("<TD VALIGN=\"MIDDLE\">");
    
    document.write("<TABLE BORDER=\"0\">");

    startNewRow = true;
    
    if ( ttlPages > 0 ) {
        for ( pg = 0; pg < ttlPages; pg++ ) {
        
            wrapIndex++;
        
            if (startNewRow == true){
              document.write("<TR>");            
              startNewRow = false;
            }
        
            si = pg * recsPerPage;
            document.write("<TD VALIGN=\"TOP\">&nbsp;");
            if ( si == curRec ) {
                document.write("<span class=\""+textClass+"\"><b>"+(pg+1)+"</b></span>");
            } else {
                document.write("<a class=\"bodyLink\" href=\""+url+"&startIndex="+si+"&count="+recsPerPage+"\">"+(pg+1)+"</a>");
            }
            document.write("</TD>");
            
            // close and start a new row if necessary
            if (wrapIndex >= wrapLength){
              document.write("</TR>");
              startNewRow = true;
              wrapIndex = 0;
            }
            
            
        }           
    }
    document.write("</TABLE>")
    
    document.write("&nbsp;</TD><TD VALIGN=\"TOP\">");
    
    document.write("<TABLE>");
    document.write("<TD>");
    document.write("<IMG SRC=\""+imagePath+"/right_arrow.gif\" BORDER=\"0\" VALIGN=\"TOP\">");
    document.write("</TD>");
    document.write("</TABLE>");
    
    
    document.write("</TD><TD VALIGN=\"TOP\">");
    
    document.write("<TABLE>");
    document.write("<TD>");
    if ( lastRec >= totalRecs ) {
        document.write("<span class=\""+textClass+"\">Next</span>");
    } else {
        document.write("<a class=\"bodyLink\" href=\""+url+"&startIndex="+nextStart+"&count="+recsPerPage+"\" title=\"Next Page\">Next</a>");
    }
    document.write("</TD>");
    document.write("</TABLE>");   
     
    document.write("</TD></TR></TABLE>");
}


/**
 * Function:maxlength(obj,len)
 * Purpose:	textarea maxlength validation
 * Params:	object and man length
 * Returns:	nothing
 **/
function maxlength(obj,len) {
	//first we need to convert the newline characters into 2 dummy characters to 
	//take into account Mozilla representing newline with \n and IE \r\n 
	var tempStr = escape(obj.value);
	var dummyChars = "##";
	for(i=0; i < tempStr.length; i++)
	{ 
		if(tempStr.indexOf("%0D%0A") > -1)
		{ 
			//IE encodes returns as \r\n hex
			tempStr=tempStr.replace("%0D%0A",dummyChars)
		}
		else if(tempStr.indexOf("%0A") > -1)
		{ 
			//Mozilla encodes returns as \n hex
			tempStr=tempStr.replace("%0A",dummyChars)
		}
		else if(tempStr.indexOf("%0D") > -1)
		{ 
			//Macintosh encodes returns as \r hex
			tempStr=tempStr.replace("%0D",dummyChars)
		}
	}
	tempStr =  unescape(tempStr);
    if(tempStr.length > len)
    {
		alert('The maximum number of characters this field will accept is '+ len + ' characters.\nIt currently contains ' + tempStr.length + '. Please remove at least ' + (tempStr.length - len) + ' characters.');
		obj.focus();
	}
}

function validTextField(obj,fieldLabel,maxLen)
{
	var length = textFieldLength(obj);
	if (length > maxLen)
	{
		alert("The maximum amount of characters the " + fieldLabel + "  field can accept \nis " + maxLen + "; it currently holds "+ length);
		obj.focus();
		return false;
	}
	return true;
}

function textFieldLength(obj) {
	//first we need to convert the newline characters into 2 dummy characters to 
	//take into account Mozilla representing newline with \n and IE \r\n 
	var tempStr = escape(obj.value);
	var dummyChars = "##";
	for(i=0; i < tempStr.length; i++)
	{ 
		if(tempStr.indexOf("%0D%0A") > -1)
		{ 
			//IE encodes returns as \r\n hex
			tempStr=tempStr.replace("%0D%0A",dummyChars)
		}
		else if(tempStr.indexOf("%0A") > -1)
		{ 
			//Mozilla encodes returns as \n hex
			tempStr=tempStr.replace("%0A",dummyChars)
		}
		else if(tempStr.indexOf("%0D") > -1)
		{ 
			//Macintosh encodes returns as \r hex
			tempStr=tempStr.replace("%0D",dummyChars)
		}
	}
	tempStr =  unescape(tempStr);
    return tempStr.length;
}

/**
 * Function: validateTitleNumber
 * Purpose:	 perform all validation needed for title numbers.
 * Params:	titleNumber, titleNumberCodesFieldname 
 * Returns:	boolean 
 **/
function validateTitleNumber(titleNumber, titleNumberCodesFieldname){
	
    var titleNumberCodes = eval(eval("\"" + document.forms[0].elements[titleNumberCodesFieldname].value + "\""));
    
    if (!isUnknownTitleNumber(titleNumber)) {
		if (  (isBlank(titleNumber)) 
		   || (isAlphaNumeric(titleNumber) == false)) {	
		   	alert("Please enter an Alphanumeric Title Number.");
			return false;
		}
		if (titleNumber.length > 9){
			alert("The title number must be less than 9 characters in length.");
		  	return false;
		}
		
		return validateTitleNumberCode(titleNumber, titleNumberCodes);
	}
	
	return true;
}

function validateTitleNumberCode(titleNumber, titleNumberCodes){

   var prefix = tnGetPrefix(titleNumber);         
   var number = tnGetNumber(titleNumber, prefix); 
   var suffix = tnGetSuffix(prefix, number, titleNumber); 
   
   if (!tnIsValidPrefix(prefix,titleNumberCodes)){
     if (prefix == null || trim(prefix) == '')
     {
   		alert('A title number prefix is required.');
   		return false;
     }
     else
     {	
   		alert('The title number prefix '+ prefix+ ' is not valid.');
   		return false;
     }
     
   }
         
   if (!tnCheckZSuffix(prefix, suffix)){
 	 alert('If the title number prefix is Z, the suffix must also be Z.');
 	 return false;     
   }
   if (!tnIsValidPrefix("Z",titleNumberCodes) && suffix !=null && suffix != "")
   {
   	 alert("Title number suffixes are not allowed");
   	 return false;
     	
   }
   
   if (!tnCheckNoSuffix(prefix, suffix)){
	 alert('The title number suffix ' + suffix + ' is not valid.');  
     return false;
   }
  
   if (!tnCheckNumberExists(number)){
     alert('The title number requires a numeric component.');
     return false;
   }
   
   if (!tnCheckNumberLeadingZeros(number)){
     alert('The title number numeric component can not have a leading zero.');
     return false;
   }
   
   if (!tnCheckNumberUnderMax(prefix, number,titleNumberCodes)){
   
     return false;
   }
   
   return true;
}

function isUnknownTitleNumber(titleNumber)
{	
	if (titleNumber != null && titleNumber == 'UNKNOWN')
	{
		return true
	}
	else
	{
		return false;
	}
}

/**
 * Function: tnCheckNumberUnderMax
 * Purpose:	check that the number parameter is less than or equal
 * to the value specified in titleNumberCodes for the passed in prefix. 
 * Params:	prefix, number, titlenumbercodes
 * Returns:	boolean 
 **/
function tnCheckNumberUnderMax(prefix, number, titleNumberCodes){
   
   var tnFound = false;
   var currentCodeIndex = 0;
   var maxValue = 999999999;
    
   while (   (currentCodeIndex < titleNumberCodes.length) 
          && (!tnFound)
          ){
          
     if (prefix == titleNumberCodes[currentCodeIndex][0]){
       tnFound = true;
     }else{
       if (    (titleNumberCodes[currentCodeIndex][0] == null)
            && (prefix == null || prefix.length == 0) ){
         tnFound = true;
         
         if ((number >= 200000) && (number <= 210000)){
           alert("The title number numeric component must be between 1 and 199999 or 210001 and 470000 when no prefix is specified.");
           return false;
         }
       } 
     }
     
     if (tnFound){
       if (titleNumberCodes[currentCodeIndex][1] != null){
          maxValue = titleNumberCodes[currentCodeIndex][1];
       }
     }
     
     currentCodeIndex++;     
   }
   
   if (number <= maxValue){
     return true;
   }else{
     if ((trim(prefix).length == 0) || (null == prefix)){
       alert("The title number numeric component must be between 1 and 199999 or 210001 and 470000 when no prefix is specified.");
     } else {
       alert("The title number numeric component for the prefix "+prefix+" must be less than or equal to " + maxValue );
     }
     return false;
   }
}

/**
 * Function: tnCheckNumberLeadingZeros
 * Purpose:	check does not have a leading zero
 * Params:	number
 * Returns:	boolean 
 **/
function tnCheckNumberLeadingZeros(number){
  var firstNumber = number.charAt(0);
  if (firstNumber == '0'){
    return false;
  }
  return true;
}

/**
 * Function: tnCheckNumberExists
 * Purpose:	return true if the passed in number is a number
 * zero
 * Returns:	boolean 
 **/
function tnCheckNumberExists(number){
  if (   (null == number) 
       ||(number.length == 0) 
       ||(isNaN(number))
      ){
    return false;
  }
  return true;
}

/**
 * Function: tnCheckNoSuffix
 * Purpose:	check that the suffix is null unless the prefix is Z.
 * Params:	prefix, suffix
 * Returns:	boolean 
 **/
function tnCheckNoSuffix(prefix, suffix){
  if (prefix != 'Z' && suffix.length > 0){
    return false;
  }
  return true;
}

/**
 * Function: tnCheckZSuffix
 * Purpose:	check that the suffix Z if the prefix is Z
 * Params:	prefix, suffix
 * Returns:	boolean 
 **/
function tnCheckZSuffix(prefix, suffix){
  if (trim(prefix) == 'Z'){
    if (trim(suffix) != 'Z'){
      return false;
    }
  }
  return true;
}

/**
 * Function: tnIsValidPrefix
 * Purpose:	check that the prefix exists in the list of valid prefixes
 * Params:	prefix, titleNumberCodes
 * Returns:	boolean 
 **/
function tnIsValidPrefix(prefix, titleNumberCodes)
{
   var tnFound = false;
   var currentCodeIndex = 0;
    
   while (   (currentCodeIndex < titleNumberCodes.length) 
          && (!tnFound)
          )
   {         
     if (prefix == titleNumberCodes[currentCodeIndex][0]){
         tnFound = true;
     }else if    ((titleNumberCodes[currentCodeIndex][0] == null) 
              && (prefix == null || prefix.length ==0)){
         tnFound = true;
     }
     currentCodeIndex++;     
   }
   return tnFound;
}

/**
 * Function: tnGetSuffix
 * Purpose:	get the suffix of the passed in titlenumber.  
 * Params:	prefix, number, titleNumber
 * Returns:	the suffix of the title number
 **/
function tnGetSuffix(prefix, number, titleNumber){
  var startIndex = prefix.length + number.length;
  var suffix = titleNumber.substring(startIndex, titleNumber.length);
  return suffix;
}

/**
 * Function: tnGetPrefix
 * Purpose:	get the prefix of the passed in titlenumber.
 * Params:	titleNumber
 * Returns:	the prefix of the title number
 **/
function tnGetPrefix(titleNumber){
  
  var prefix;
  var prefixExists = false;  
  var validPrefix = true;
  
  if ( isAlpha(titleNumber.charAt(0)) ){
    prefixExists = true;
  } else {
    return '';
  }

  var prefixEndIndex = 0;
  if (prefixExists){
    var prefixFound = false;
    while (!prefixFound){
      var c = titleNumber.charAt(prefixEndIndex);
      if (!isAlpha(trim(c)) || trim(c) == null || trim(c) == ''){
        prefixFound = true;
      }else{
        prefixEndIndex++;
      }
    }

    prefix = titleNumber.substring(0,prefixEndIndex);
    return prefix;
  }
}

/**
 * Function: tnGetNumber
 * Purpose:	get the numeric component of the passed in titlenumber.  
 * Params:	titleNumber, prefix
 **/
function tnGetNumber(titleNumber, prefix){

    var numberBeginIndex = 0;
    if (prefix != null && prefix.length > 0){
      numberBeginIndex = prefix.length;
    }
    
    var numberEndIndex = numberBeginIndex + 1;
    var foundSuffix = false;

    while (!foundSuffix && (numberEndIndex < titleNumber.length)){
      var c = titleNumber.charAt(numberEndIndex);
      if (isNaN(trim(c))){
        foundSuffix = true;
      }else{
        numberEndIndex++;
      }
    }
    
    var numberComponent = titleNumber.substring(numberBeginIndex, numberEndIndex);
    return numberComponent;
}

 
/**
 * Function:	isAlpha(unknown)
 * Params:	inputVal
 * Returns:	boolean 
 **/

function isAlpha (inputVal)
{
	inputStr = inputVal.toString();
	for (var i = 0; i < inputStr.length; i++)
	{
		var oneChar = inputStr.charAt(i);

		if ((oneChar < "a" || oneChar > "z") &&
		    (oneChar < "A" || oneChar > "Z"))
		{
			return false;
		}
	}

	return true;
} 

/**
 * Function: onHelpLinkClick(helpAnchorLink)
 * Purpose:	Popup help window
 **/

function onHelpLinkClick(helpAnchorLink)
{
   CmaHelpWin = window.open(helpAnchorLink, "HELP_WINDOW",
      "resizable=yes,scrollbars=yes,toolbar=false,menubar=true,status=off,width=650,height=300")
   CmaHelpWin.focus()
}


/**
 * Function: isValidYearNumber(inputVal) 
 **/
function isValidYearNumber (inputVal) 
{
	if (inputVal<1) return false;

	inputStr = inputVal.toString();
	for (var i = 0; i < inputStr.length; i++) 
	{
		var oneChar = inputStr.charAt(i);
		if ((oneChar < "0") || (oneChar > "9"))
		{	return false; }
	}
	return true;
}

/**
 * Function: isEmptyString(inputVal) 
 **/
function isEmptyString (inputVal) 
{
	if (inputVal =="") return true;

	inputStr = inputVal.toString();

	for (var i = 0; i < inputStr.length; i++) 
	{
		var oneChar = inputStr.charAt(i);
		if (oneChar !=" " )	return false; 
	} 
	return true;
}

function focusOnFirstElement() {
  // If there is a form in the doc...
  if (document.forms) {

    theElems = document.forms[0].elements

    // loop over the elements until finding a non-hidden one
    for (i = 0; i < theElems.length; i++) {
      theElem = theElems[i];
      if (theElem.type && theElem.type == "hidden" ) {
        continue;
      }
      // focus on the first non-hidden element
      theElem.focus();
      break;
    }
  }
}

function isNumeric(val) {
	//if (val < 0) return false;
	inputStr = val.toString();
	for (var i = 0; i < inputStr.length; i++) 
	{
		var oneChar = inputStr.charAt(i);
		if (oneChar < "0" || oneChar > "9") return false;
	}
	return true;
}

// Same as isNumeric except also allows the period
// character.
function isPrice(val){
    //if (val < 0) return false;
    inputStr = val.toString();
    var hasDecimal = false;
	
    for (var i = 0; i < inputStr.length; i++) 
    {
        var oneChar = inputStr.charAt(i);
        if ((oneChar < "0" || oneChar > "9") && oneChar != ".") 
            return false;
        if (oneChar == ".") {
            if (hasDecimal == true)
                return false;
            hasDecimal = true;
        }
    }
    return true;
}

function getTrimmedValue(fieldName){
  document.forms[0].elements[fieldName].value = trim(document.forms[0].elements[fieldName].value);
  return document.forms[0].elements[fieldName];
}


   