//Added by mc
/**
 * DHTML date validation script. Courtesy of SmartWebby.com (http://www.smartwebby.com/dhtml/)
 */
// Declaring valid date character, minimum year and maximum year
var dtCh= "/";
var minYear=1900;
var maxYear=2100;

function chkdate(currdate,newdate1)
{
//currdate = new Date()
//userdate = new Date(document.MainFrm.Start_Date.value)

//currdate.setDate(currdate.getDate()-1)

	if (currdate <= newdate1)
	{
		return true;
	}
		else
	{
		alert("Date cannot be set in the past");
		return false;	
	}
}
function noenter() 
{
  return !(window.event && window.event.keyCode == 13); 
}

/* 
checkEmailAddress will validate the passed form field value against the regular expression below. If it doesn't pass, it alerts with the passed msg if it is defined or the default error, focuses back on the calling document with the form field selected.
onblur="javascript:checkEmailAddress(FormName.FieldName,'Please enter a valid email address')"
*/
function checkEmailAddress(field,msg) 
{
// Note: The next expression must be all on one line...
//       allow no spaces, linefeeds, or carriage returns!
var goodEmail = field.value.match(/\b(^(\S+@).+((\.com)|(\.net)|(\.edu)|(\.mil)|(\.gov)|(\.org)|(\..{2,2}))$)\b/gi);

if (!goodEmail)
	{
	if (typeof(msg) != 'undefined')
		{
   alert('' + msg);
   		}
	else
		{
   alert('The email address you entered is invalid.');
		}
	self.focus();
	field.select();
	field.focus();
   }
}

function daysInFebruary (year){
	// February has 29 days in any year evenly divisible by four,
    // EXCEPT for centurial years which are not also divisible by 400.
    return (((year % 4 == 0) && ( (!(year % 100 == 0)) || (year % 400 == 0))) ? 29 : 28 );
}

function confirmSubmit()
{
var agree = confirm("Are you sure?");
if (agree)
	return true ;
else
	return false ;
}

function DaysArray(n) {
	for (var i = 1; i <= n; i++) {
		this[i] = 31
		if (i==4 || i==6 || i==9 || i==11) {this[i] = 30}
		if (i==2) {this[i] = 29}
   } 
   return this
}
function textCounter(field, maxlimit,errmsg,fielddisp) 
{
if (typeof(fielddisp) != 'undefined')
	{
WordCount=field.value.length;
fielddisp.value=WordCount;
	}
if (field.value.length > maxlimit) {
alert(errmsg);
field.value = field.value.substring(0, maxlimit);
	if (typeof(fielddisp) != 'undefined')
		{
fielddisp.value=maxlimit;
		}
	}
}
function isDate(dtStr){
	var daysInMonth = DaysArray(12)
	var pos1=dtStr.indexOf(dtCh)
	var pos2=dtStr.indexOf(dtCh,pos1+1)
	var strMonth=dtStr.substring(0,pos1)
	var strDay=dtStr.substring(pos1+1,pos2)
	var strYear=dtStr.substring(pos2+1)
	strYr=strYear
	if (strDay.charAt(0)=="0" && strDay.length>1) strDay=strDay.substring(1)
	if (strMonth.charAt(0)=="0" && strMonth.length>1) strMonth=strMonth.substring(1)
	for (var i = 1; i <= 3; i++) {
		if (strYr.charAt(0)=="0" && strYr.length>1) strYr=strYr.substring(1)
	}
	month=parseInt(strMonth)
	day=parseInt(strDay)
	year=parseInt(strYr)
	if (pos1==-1 || pos2==-1){
		alert("The date format should be : mm/dd/yyyy")
		return false
	}
	if (strMonth.length<1 || month<1 || month>12){
		alert("Please enter a valid month")
		return false
	}
	if (strDay.length<1 || day<1 || day>31 || (month==2 && day>daysInFebruary(year)) || day > daysInMonth[month]){
		alert("Please enter a valid day")
		return false
	}
	if(strYear.length == 2)
	{
		strYear="19"+strYear;	
	}
	year=parseInt(strYear);
	if (strYear.length != 4 || year==0 || year<minYear || year>maxYear){
		alert("Please enter a valid year between "+minYear+" and "+maxYear)
		return false
	}
	if (dtStr.indexOf(dtCh,pos2+1)!=-1 || isInteger(stripCharsInBag(dtStr, dtCh))==false){
		alert("Please enter a valid date")
		return false
	}
return true
}


function trim(str)
{
  return( (""+str).replace(/^\s*([\s\S]*\S+)\s*$|^\s*$/,'$1') );
}
function ValidateDate(ctl){
	var dt=ctl//document.frmSample.txtDate
	if (trim(ctl.value)=="")
		return;
	ctl.value = trim(ctl.value);
	if (isDate(dt.value)==false){
		dt.focus()
		return false
	}
    return true
 }
 
 
function checkMandatoryFields(fieldsArr, labelsArr)
{
var ErrorStr="";
var bReturn = true;
for (var i=0; i<fieldsArr.length; i++) 
{
	for (var k=0; k<document.forms[0].length; k++) 
	{
		if (document.forms[0].elements[k].name == fieldsArr[i]) 
		{
			if (document.forms[0].elements[k].value == "") 
			{
				ErrorStr=ErrorStr+"- "+labelsArr[i] +"\n";
//				document.forms[0].elements[k].focus();
			}
		}
	}
}
return(ErrorStr);
}

function NewWindow(mypage, myname, w, h, scroll) {
	var winl = (screen.width - w) / 2;
	var wint = (screen.height - h) / 2;
	winprops = 'height='+h+',width='+w+',top='+wint+',left='+winl+',scrollbars='+'yes'+',resizable'
//	alert("winprops= " + winprops);
	win = window.open(mypage, myname, winprops)
	if (parseInt(navigator.appVersion) >= 4) { 
		win.window.focus(); 
	}
}
function PrintWindow(mypage, myname, w, h) {
	var winl = (screen.width - w) / 2;
	var wint = (screen.height - h) / 2;
	winprops =
'height='+h+',width='+w+',top='+wint+',left='+winl+',scrollbars='+'yes'+',menubar='+'yes'+',toolbar='+'yes'+',resizable' 
	win = window.open(mypage, myname, winprops)
	if (parseInt(navigator.appVersion) >= 4) { 
		win.window.focus(); 
	}
}
function ChangeAll()
{
var frmElements = document.MainFrm;
var AllChecked = true;

AllChecked = frmElements.category.checked;

	for(i=0;i < frmElements.elements.length-1;i++)
		if (frmElements.elements[i].type == "checkbox")			
			if (frmElements.elements[i].value == frmElements.category.value)		
				frmElements.elements[i].checked = AllChecked;				
}
function closeAndRefresh() {
    window.opener.location.reload();
    close();
}
/* SetFrmVal will set the value for the FormName.FrmField to FrmFieldVal
*/
function SFrmVal(FormName,FrmField,FrmFieldVal)
{
	FormName.UseList.value = 'No';
}
function SubmitFrm(FormName){
//var ThisFormName = eval("document.forms." + FormName);
	FormName.submit();
}
/* RSubmitFrm will submit the form from the reports_main page. Requires the displayval, which is the value to set for the rname var
*/
function RSubmitFrm(FormName,rnameval)
{
	FormName.rname.value = rnameval;
	FormName.submit();
}
function AddUserContact(ContactID) {
if (confirm("Are you sure you want to add this contact to your Contacts list?"))
	{
var UrlStr = '';
UrlStr = "/secure/contacts/manage_user_contacts.cfm?ContactID=" + ContactID + "&Action=Add&AutoMode=Yes";
NewWindow(UrlStr,'CRMPopup','80','80');
	}
	else 
	{
	return false;
	}
}
function RemoveUserContact(ContactID) {
if (confirm("Are you sure you want to remove this contact from your Contacts list?"))
	{
var UrlStr = '';
UrlStr = "/secure/contacts/manage_user_contacts.cfm?ContactID=" + ContactID + "&Action=Remove&AutoMode=Yes";
NewWindow(UrlStr,'CRMPopup','80','80');
	}
	else 
	{
	return false;
	}
}
/* Usage: ShowHideBlock(Blockname to show, state to enable)
ShowHideBlock(TOBlockOn,'none')
*/
function ShowHideBlock(BlockToShow,blockstate)
{
if (blockstate == "none")
	{
	BlockToShow.style.display = 'none';
	}
else
	{
	BlockToShow.style.display = 'block';
	}
}

/* ShowBlockIfOffOn is to show or hid a block named BlockToShow by setting the DISPLAY: style to OFF if the passed checkbox is not checked, and ON if the passed checkbox is checked. So it only shows the block if the checkbox is on.
Usage: ShowBlockIfOffOn(Blockname to show, state to enable)
ShowBlockIfOffOn(TOBlockOn,ACheckbox)
*/
function ShowBlockIfOffOn(BlockToShow,boxtocheck){
if (boxtocheck.checked == true)
	{
	BlockToShow.style.display = 'block';
	}
else
	{
	BlockToShow.style.display = 'none';
	}
}
// var good;
function checkall(formname,checkname,thestate){
var el_collection=eval("document.forms."+formname+"."+checkname)
for (c=0;c<el_collection.length;c++)
el_collection[c].checked=thestate
}
// -------------------------------------------------------------------
// autoComplete (text_input, select_input, ["text"|"value"], [true|false])
//   Use this function when you have a SELECT box of values and a text
//   input box with a fill-in value. Often, onChange of the SELECT box
//   will fill in the selected value into the text input (working like
//   a Windows combo box). Using this function, typing into the text
//   box will auto-select the best match in the SELECT box and do
//   auto-complete in supported browsers.
//   Arguments:
//      field = text input field object
//      select = select list object containing valid values
//      property = either "text" or "value". This chooses which of the
//                 SELECT properties gets filled into the text box -
//                 the 'value' or 'text' of the selected option
//      forcematch = true or false. Set to 'true' to not allow any text
//                 in the text box that does not match an option. Only
//                 supported in IE (possible future Netscape).
// -------------------------------------------------------------------
/*
uncheckbox will uncheck the specified form.checkbox
javascript:uncheckbox('Search_Form','CheckBoxName')
*/
function uncheckbox(formname,targ)
{
 var targ_to_uncheck = eval("document.forms."+formname+"."+targ);
 targ_to_uncheck.checked = false;
		return false ;
}

function NewUncheckAll(formname,checkname,thestate,thisval)
{
var el_collection=eval("document.forms."+formname+"."+checkname);
	for (c=0;c<el_collection.length;c++)
	{
		if (el_collection[c].value == thisval)
		{
		el_collection[c].checked = true;
		}	
		else
		{
		el_collection[c].checked = false;
		}
	}
}

function autoComplete (field, select, property, forcematch) 
{
	var found = false;
	for (var i = 0; i < select.options.length; i++) 
	{
	if (select.options[i][property].toUpperCase().indexOf(field.value.toUpperCase()) == 0) 
		{
		found=true; break;
		}
	}
	if (found) 
	{ 
	select.selectedIndex = i; 
	}
	else 
	{ 
	select.selectedIndex = -1; 
	}
	if (field.createTextRange) 
	{
		if (forcematch && !found) 
		{
			field.value=field.value.substring(0,field.value.length-1); 
			return;
		}
		var cursorKeys ="8;46;37;38;39;40;33;34;35;36;45;";
		if (cursorKeys.indexOf(event.keyCode+";") == -1) 
		{
			var r1 = field.createTextRange();
			var oldValue = r1.text;
			var newValue = found ? select.options[i][property] : oldValue;
			if (newValue != field.value) 
			{
				field.value = newValue;
				var rNew = field.createTextRange();
				rNew.moveStart('character', oldValue.length) ;
				rNew.select();
			}
		}
	}
}
function SetEntityType (Frm, NewVal)
{
if (NewVal == 2)
	{
Frm.EntityType.value = 2
	}
else
	{
Frm.EntityType.value = 1
	}
}
/* 
writeSelected will copy the text of the selected option(s) from the passed selectbox obj to the form element passed as targ. If additional 'yes' arg is passed, the script will also write the selectbox value to a form element with the same base name as targ with _val appended.
onchange="writeSelected('MainFrm','Selectbox','inputbox')
onchange="writeSelected('MainFrm','Selectbox','inputbox','yes')
*/
function writeSelected(frm,obj,targ,writeval)
//writeSelected('MainFrm','Requestor2','NewRequestor','yes')"
{
	var ChosenText = "";
	var ChosenTextVal = "";
	var selectObj = eval("document.forms."+frm+"."+obj);
	var descObj = eval("document.forms."+frm+"."+targ);
	if (writeval == 'yes')
	{
	var descObjval = eval("document.forms."+frm+"."+targ + "_val");
	}	
	if (selectObj.type == "select-multiple")
	{
	for (var i=0; i < selectObj.options.length; i++ )
		{
		if (selectObj.options[i].selected) 
			{
		ChosenText = ChosenText + selectObj.options[i].text+",";
		ChosenTextVal = ChosenTextVal + selectObj.options[i].value+",";
			}
		}
			descObj.value = ChosenText;
		if (writeval == 'yes')
		{
			descObjval.value = ChosenTextVal;
		}
	}
	else
	{
		if (selectObj.type == "select-one")
		{
	for (var i=0; i < selectObj.options.length; i++ )
			{
		if (selectObj.options[i].selected) 
				{
		ChosenText  = ChosenText + selectObj.options[i].text;
		ChosenTextVal = ChosenTextVal + selectObj.options[i].value;
				}
			}
			descObj.value = ChosenText;
		if (writeval == 'yes')
			{
			descObjval.value = ChosenTextVal;
			}
		}
	}
}
/* ResetName_UPI will set the passed fields' values to nothing. NameDisp is the element with innerhtml to be reset.
Intended for Name and UPI, but any field can be passed if it allows field.value, i.e. not for select or checkboxes. If you don't want to use Field2, pass NULL
*/
function ResetName_UPI(FormName,Field1,Field2,NameDisp)
{
	var ThisField1 = eval("document.forms."+FormName+"."+Field1);
	var ThisField2 = eval("document.forms."+FormName+"."+Field2);
	var ThisNameDisp = eval(NameDisp);
//	ThisField1 = Eval(FormName.Field1);
//	alert("ThisNameDisp = " + ThisNameDisp);
	ThisNameDisp.innerHTML = '';
	ThisField1.value='';
	ThisField2.value='';
/*
	if (eval(Field1) != null)
		{
	alert("Field1 is not null');
	FormName.Field1.value = '';
		}
	else
		{
	alert("Field1 IS null');
		}
	if (Field2 != null)
		{
	FormName.Field2.value = '';
		}
	if (NameDisp != null)
		{
	NameDisp.innerHTML = '';
		}
*/
	
}


//=========== Validation for Amount Field (added on 10/19/04)  ======================================
var reFloat = /^((\d+(\.\d*)?)|((\d*\.)?\d+))$/;

function amountOnly(s) {
  	var ret = "";
  	var amtStr = "" + s;
  	var start = 0;
  	var pos = amtStr.indexOf(',');
  	while (pos != -1)
  	{
    		ret += amtStr.substring(start, pos);
    		start = pos + 1;
    		pos = amtStr.indexOf(',', start);
 	}
  	ret += amtStr.substring(start);
  	return ret;
}

function trim(str)
{
  return( (""+str).replace(/^\s*([\s\S]*\S+)\s*$|^\s*$/,'$1') );
}

function isAmountSign(ctl)
{	
	if (trim(ctl.value)=="")
		return;
	ctl.value = trim(ctl.value);
	ctl.value = amountOnly(trim(ctl.value));	
	s=ctl.value ;
	// skip leading + or -
	startPos = 0; 
	if ( (s.charAt(0) == "-") || (s.charAt(0) == "+") )
		startPos = 1; 
	if(!reFloat.test(amountOnly(trim(s.substring(startPos, s.length)))))
	{
		alert("Please enter a valid amount");
		ctl.focus();
	}
}
//===================================================================================