﻿
/// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
/// Make sure to update MyCtrl.GetJsEH with any new handlers for field types
/// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

// normally there is a control with the [id] + 'Ttl' but sometimes there is no title, in this case the control will have the 'ttl' attribute
function GetFldTtl(id)
{
	var control = $(id + 'Ttl');
	//alert('id = ' + id + ' - control = ' + control);
	if(IsDefinedNNotNull(control) && IsDefinedNNotNull(control.innerHTML))	 //if(control != null)	
		return control.innerHTML;
	else	
	{
	    control = $(id);
	    if(IsDefinedNNotNull(control))
	    {
	        var ttl = control.getAttribute('ttl');
	        //alert('ttl = ' + ttl);
	        if(!IsDefinedNNotNull(ttl) || ttl == '')
	        //if(ttl == null || ttl == '' || ttl == 'undefined')
	        {
	            if(control != null)
	            {
	                /// The MyID is necessary to user for UsrCtrls which are not rptrs
	                var myid = control.getAttribute('myid');	
	                //alert('myid = ' + myid);
	                if(IsDefinedNNotNull(myid) && myid != '' && myid != id)
	                { 
	                    control = $(myid + 'Ttl');       
	                    //alert(' using myid + Ttl to get control - control = ' + control + ' - IsDefinedNNotNull(control)  = ' + IsDefinedNNotNull(control))    	            	            	            
                        if(IsDefinedNNotNull(control) && IsDefinedNNotNull(control.innerHTML))
                            return control.innerHTML;	            
                        else
                            return '';
	                }
	            }
	        }
	        if(IsDefinedNNotNull(ttl))
		        return ttl;
		    else
		        return '';
		}
	}
	return '';
}

function SetFldInvalidCss(id)
{	
	var control = $(id);
	var controlType = control.getAttribute('tp');
	if(controlType == '7') // phone	
		SetPhnInvalidCss(id);
	else if(controlType == '21') // ssn
		SetSSNInvalidCss(id);
	else if(controlType == '3' || controlType == '4') // time or date+time // do nothing because the field the inline validation should have already done the css work
		return;
	else if(controlType == '10') // region	
		SetRgnInvalidCss(id);
	else
		SetControlInvalidCss(control); 
		// if(control.className.indexOf(' err') == -1) control.className += ' err';
}
 
function SetFldValidCss(id)
{	
	// just in case of freak occurences
	if(id == null || id == '') return;
	
	var control = $(id);
	// there are time when the control wont exist but this is called anyway to reset it if it does exist
	if(control == null) return;
	
	var controlType = control.getAttribute('tp');		
	var idx = control.className.indexOf('err');
	
	if(controlType == '7') // phone	
		SetPhnValidCss(id);
	else if(controlType == '21') // ssn
		SetSSNValidCss(id);
	else if(controlType == '3' || controlType == '4') // time or date+time // do nothing because the field the inline validation should have already done the css work
		return;		
	else if(controlType == '10') // region	
		SetRgnValidCss(id);
	// have to check if it is the only css class on the control
	else
	{
		SetControlValidCss(control);
	}
//	 if(idx == 0) control.className = control.className.replace('err', '');		
//	else if(idx != -1) control.className = control.className.replace(' err', '');			
}

// created this because some fields need to pass in a different control depending on the condition
function SetControlValidCss(control)
{
	if(control == null) return;
	var idx = control.className.indexOf('err');
	
	if(idx == 0) control.className = control.className.replace('err', '');		
	else if(idx != -1) control.className = control.className.replace(' err', '');		
}
function SetControlInvalidCss(control)
{		
	if(control.className.indexOf(' err') == -1) control.className += ' err';
}

function ShowCustomErrMsg(msgHdr, msgDtl, controlID, isMulti)
{
	// isMulti is when there are mulitple custom error messages and each one is contained in an <li> element
	if(!IsDefined(isMulti)) isMulti = false;
	
	if(msgHdr == null || msgHdr == '') msgHdr = 'Some required fields are not filled out or have incorrect input!';
	var str = '<div class="center"><img src="/SAM/Img/Warning.png" /><span class="errHdr">' + msgHdr + '</span></div>';
	str += '<ul>';
	if(!isMulti) str += '<li>';			
	str += msgDtl;										
	if(!isMulti) str += '</li>';
	str += '</ul>';				
	
	var dvErr = $('dvErr');
	dvErr.className = 'dvErr';
	dvErr.innerHTML = str;
	
	// make sure to show the tblErrArea if the page uses the SaveBtn instead of the Save Area
	var tblErrArea = $('tblErrArea');
	if(tblErrArea) tblErrArea.style.display = ''; // make save
	
	if(controlID != null) SetFldInvalidCss(controlID);
}

function ShowErrMsg(arrReqs, arrDt, arrTm, arrNum, arrCur, arrEml, arrUrl, arrPhn, arrImg, arrDoc, arrSSN, arrCustom, customErrMsg, arrPas, arrPasConfirm)
{	
	var str = '<div class="center"><img src="/SAM/Img/Warning.png" /><span class="errHdr">Some required fields are not filled out or have incorrect input!</span></div>';
	str += '<ul>';
												
	str += GetErrMsgLstItem(arrCustom, customErrMsg, customErrMsg); 
	str += GetErrMsgLstItem(arrReqs, 'is a required field.', 'Plese enter the following required fields:', 'Please enter all the required fields.'); 
	str += GetErrMsgLstItem(arrDt, 'is an invalid date or not in the format of mm/dd/yyyy.', 'The following dates are invalid or not in the format of mm/dd/yyyy:', 'You have entered an invalid date or a date not in the format of mm/dd/yyyy.');
	str += GetErrMsgLstItem(arrTm, 'is an invalid time.', 'The following fields are not valid times:', 'You have entered an invalid time.');
	str += GetErrMsgLstItem(arrNum, 'is an invalid number.', 'The following fields are not valid numbers:', 'You have entered an invalid number.');
	str += GetErrMsgLstItem(arrCur, 'is an invalid currency amount.', 'The following fields are not valid currency amounts:', 'You have entered an invalid currency amount.');									
	str += GetErrMsgLstItem(arrEml, 'is an invalid email address.', 'The following fields are not valid email addresses:', 'You have entered an invalid email addresses.');
	str += GetErrMsgLstItem(arrUrl, 'is an invalid hyperlink.', 'The following fields are not valid hyperlinks:', 'You have entered an invalid hyperlink.');									
	str += GetErrMsgLstItem(arrPhn, 'is an invalid phone number.', 'The following fields are not valid phone numbers:', 'You have entered an invalid phone number.');
	str += GetErrMsgLstItem(arrImg, 'is not an allowed photo type.', 'The following file uploads are not allowed photo types:');
	str += GetErrMsgLstItem(arrDoc, 'is not an allowed document type.', 'The following file uploads are not allowed document types:');
	str += GetErrMsgLstItem(arrSSN, 'is an invalid Social Security Number.', 'The following fields are not valid Social Security Numbers:');
	str += GetErrMsgLstItem(arrPas, 'is an invalid password because it does not meet the requirements of having at least 8 characters, having 1 upper case and 1 lower case letter and 1 number.', 'The following fields are not valid passwords because they do not meet the requirements of having at least 8 characters, having 1 upper case and 1 lower case letter and 1 number:');
	str += GetErrMsgLstItem(arrPasConfirm, 'does not match the confirmation password. Please re-enter the password and the confirmation password.', '');
									
									
	str += '</ul>';				
	
	var dvErr = $('dvErr');
	dvErr.className = 'dvErr';
	dvErr.innerHTML = str;
	
	// make sure to show the tblErrArea if the page uses the SaveBtn instead of the Save Area
	var tblErrArea = $('tblErrArea');
	if(tblErrArea) tblErrArea.style.display = ''; // make save
		
	var arrErr = new Array();
	arrErr.concat(arrReqs).concat(arrDt).concat(arrNum).concat(arrCur).concat(arrEml).concat(arrUrl).concat(arrPhn).concat(arrImg).concat(arrDoc).concat(arrSSN).concat(arrCustom).concat(arrPas).concat(arrPasConfirm);
	
	var hidErr = $('hidErr');
	
	if(hidErr.value != '')
	{
		var arrErrOld = hidErr.value.split(';');
		
		// reset the controls css if they are not in the new error array
		for(var i = 0; i < arrErrOld.length; i++)
		{
			if(!IsArrayContains(arrErr, arrErrOld[i]))
			{
				SetFldValidCss(arrErrOld[i]);
			}
		}			
	}
	
	hidErr.value = arrErr.join(";");					
}

function GetErrMsgLstItem(arr, singleFldErr, multiFldErr, noTtlFldErr)
{
	var str = '';		
	
	if(arr != null && arr.length > 0)
	{
		str += '<li>';
		
		if(arr.length == 1)
		{			
			var fldTtl = GetFldTtl(arr[0]);
			if(fldTtl != null && fldTtl != '')		
				str += '<b>' + fldTtl + '</b> ' + singleFldErr;
			else if(IsDefinedNNotNull(noTtlFldErr))
				str += noTtlFldErr;
			else if(IsDefinedNNotNull(singleFldErr))
			    str += singleFldErr;
			SetFldInvalidCss(arr[0]);
		}
		else
		{
			// have to make sure the there are no duplicate names listed
			var arrFldTtl = new Array();
	
			// see if can get the first fld ttl, if can't then it is a sign that probably wont be able to get other also so cant use the multiFldErr
			var firstFldTtl = GetFldTtl(arr[0]);
			if(firstFldTtl != null && firstFldTtl != '')			
			{
			    if(IsDefinedNNotNull(multiFldErr))
				    str += multiFldErr + '<ul>';			
				else
				    str += '<ul>';			
			}
			
			
			for(var i = 0; i < arr.length; i++)	
			{			
				var fldTtl = GetFldTtl(arr[i]);
				//alert('arr[i] = ' + arr[i] + ' - fldTtl = "' + fldTtl + '"');
				if(!IsArrayContains(arrFldTtl,  fldTtl))
				{														
					if(fldTtl != null && fldTtl != '')				
						str += '<li><b>' + fldTtl + '</b></li>';						
					else if(IsDefinedNNotNull(noTtlFldErr) && str.indexOf(noTtlFldErr) == -1) // add the generic error type message only if it is not already shown
						str += '<b>' + noTtlFldErr + '</b>';
					
					arrFldTtl[arrFldTtl.length] = fldTtl;
				}
				SetFldInvalidCss(arr[i]);
			}
			
			if(firstFldTtl != null && firstFldTtl != '')			
				str += '</ul>';					
		}
		str += '</li>';				
	}
	return str;
}

function HideErrMsg()
{
	var dvErr = $('dvErr');
	dvErr.className = '';
	dvErr.innerHTML = '&nbsp;';
}

function IsInputEmpty(id)
{
    if(id == '') return false;
    
	
	var control = $(id);
	//alert('id = ' + id + '\n\ncontrol = ' + control);
	
	/// crypt controls will not be shown on the form sometimes but they may be set as required
	if(control == null) return false;
	
	var fldTpID = control.getAttribute('tp');
	
	//alert('id = ' + id + '\n\nfldTpID = ' + fldTpID + '\n\ncontrol.offsetWidth = ' + control.offsetWidth);
	//if(fldTpID == '24') alert('Pas Ctrl - offsetWidth = ' + control.offsetWidth);
	
	/// The State/Region (and Big Search List) control might have one part hidden so we have to exclude it here, but we have to check if the actual cell is really hidden because if it is then we have to return like the other normal controls that are hidden
	if(fldTpID == '10' || fldTpID == '26')
	{
	    var ctrlTtl = $(id + 'Ttl');    
	    //alert('id = ' + id + '\n\nspecial control that uses a hid input\n\nctrlTtl = ' + ctrlTtl + '\n\nctrlTtl.offsetWidth=' + ctrlTtl.offsetWidth);
	    if(ctrlTtl != null && ctrlTtl.offsetWidth == 0) return false;
	}
	else if(control.offsetWidth == 0) return false; // means that it is hidden
	//else if(control.offsetWidth == 0 && fldTpID != '10' && fldTpID != '26') return false; // means that it is hidden
	
	//alert('control = ' + control + '\nid = ' + id);
	
	
	if(fldTpID == '7') // phone	
		return IsPhnEmpty(id);	
	else if(fldTpID == '21') // ssn
		return IsSSNEmpty(id);
	else if(fldTpID == '2') // date
		return IsDtEmpty(id);				
	else if(fldTpID == '3') // time
	    return IsTmEmpty(id);
	else if(fldTpID == '4') // date+time	 
		return IsDtTmEmpty(id);
	else if(fldTpID == '10') // region	
		return IsRgnEmpty(id);		
	else if(fldTpID == '25') // yes/no radio buttons
	{		
		var rdo_0 = $(id + '_0')
		if(control.checked == true || rdo_0.checked == true) 
			return false;
		else
			return true;
	}
	else if(fldTpID == '22') // doc, cntr will not be displayed when editing
	{
		var cntr = $(id + '_cntr');
		if(cntr.style.display == 'none')
			return false;
		else if(GetControlValue(id + "_isentr") == '1')
			return false;
		else
		{
			if(Trim(control.value) == "") 
				return true;
			else
				return false;
		}
	}
	/// No need to have anything special because it is just a regular hidden input
//	else if(fldTpID == '26')
//	    return IsBigSearchLstEmpty(id);
	else if(fldTpID == '28')
	    return IsChkLstEmpty(id);
	else if(fldTpID == '29')
	    return IsAnlDtEmpty(id);
	else if(Trim(control.value) == "") 
		return true;
	else
		return false;
}

//function IsBigSearchLstEmpty(id)
//{
//    
//}

function IsAnlDtEmpty(id)
{
    /// We only check the month because if no day is selected then it default to "1"
    var mon = $(id + '_Mon');
    if(mon.value == '') return true;
    else return false;
}

function IsChkLstEmpty(id)
{
    /// The id that is passed in is just of the first chk, so we have to get the "fld" atr and check if any of the chk are checked
    var fld = $(id).getAttribute('fld');
    var chks = GetElementsByTagNAttr('input', 'fld', fld);    
    for(var i = 0; i < chks.length; i++)    
        if(chks[i].checked) return false;
            
    return true; /// the default
}

// inline validation for a required fld, should be fired for onblur event
function VldtReq(control)
{
	if(control && Trim(control.value) == "")
	{
		SetFldInvalidCss(control.id);
	}
	else
	{
		SetFldValidCss(control.id);
	}
}

function IsRgnEmpty(id)
{
	var st = $(id + '_st');
	var rgn = $(id + '_st');
	
	// We have to check that this control is visible
	if(rgn.offsetWidth == 0 && st.offsetWidth == 0) return false;
	
	if(GetControlValue(id + '_hidIsSt') == '1') // when state
	{
		if(st.value == '') return true; //arrReqs[arrReqs.length] = 'stFltrVal_' + i;
	}
	else
	{
		if(GetControlValue(id) == '') return true; //arrReqs[arrReqs.length] = 'FldVal_' + i;
	}
	return false;
}
function SetRgnValidCss(id)
{
	
	if(GetControlValue(id + '_hidIsSt') == '1') // when state	
	{		
		SetControlValidCss($(id + '_st'));			
	}
	else	
		SetControlValidCss($(id));			
	
}
function SetRgnInvalidCss(id)
{
	if(GetControlValue(id + '_hidIsSt') == '1') // when state	
		SetControlInvalidCss($(id + '_st'));	
	else	
		SetControlInvalidCss($(id));	
}

function IsEmlValid(id)
{
	var control = $(id);	
	var value = control.value;
	value = Trim(value);
	//alert(value.indexOf(','));
	if(value.indexOf(',') != -1)
	{
		var emls = value.split(',');
		//alert('emls.length = ' + emls.length);
		for(var i = 0; i < emls.length; i++)
			if(IsEmlValidStr(emls[i]) == false) return false;
		return true;
	}
	else
		return IsEmlValidStr(value);	
	

// was not working properly
//	email = email.replace(' ', '');
//	if(email == '') return true;	
//	var emailReg = "^[\\w-_\.]*[\\w-_\.]\@[\\w]\.+[\\w]+[\\w]$";
//    var regex = new RegExp(emailReg);
//    return regex.test(email);
}
function IsEmlValidStr(s)
{
	s = Trim(s);
	if(s == '') return true;	
	var apos = s.indexOf("@");
	var dotpos = s.lastIndexOf(".");
	if (apos<1||dotpos-apos<2) 	
		return false;
	else 
		return true;
}

//var uploadImgTypes; // this has to be set from the server on page load
//var uploadDocTypes; // this has to be set from the server on page load
//function IsImgValid(id)
//{
//	return IsUploadValid(id, uploadImgTypes);
//}
//function IsDocValid(id)
//{
//	return IsUploadValid(id, uploadDocTypes);
//}
//function IsUploadValid(id, types)
//{
//	var fileName = GetControlValue(id);	
//	if(fileName != '') fileName = Trim(fileName);
//	if(fileName == '') return true; // its okay if empty, will have separate check for req
//	
//	var fileExt = GetFileExtension(fileName);
//	var arr = types.split(',');
//	
//	for(var i = 0; i < arr.length; i++)	
//		if(arr[i] == fileExt) return true;		
//	
//	return false;		
//}

function IsUrlValid(id)
{
	var control = $(id);
	var url = control.value;
	url = Trim(url);
	if(url == '') return true;
	
	// checks that there are no special characters or spaces in the url
	//if(url.replace(/\w|\:|\.|\-|\//g, '') != '') return false;
	
	url = url.replace('http://', ''); // the http is not really necessary so remove it to check the actual domain name
	url = url.replace('https://', ''); 
	var dotIndex = url.indexOf('.');	
	var lastDotIndex = url.lastIndexOf('.');
	
	// checks that there is a dot and there is no dot at the beginning of the url and the one at the end has at least two chars after it 
	// pretty lienet because users have to be able to put in hyperlinks which have page names after them
	if(dotIndex <= 0 || dotIndex >= (url.length - 2) || url.length < 6)// || lastDotIndex < (url.length - 7)) return false;			
		return false;
	
	
	return true;
}

function IsPhnEmpty(fldID)
{
	var hidPhn = $(fldID + '_HidPhn');	
	if(hidPhn.value == '1')
	{
		var phnInt = $(fldID + '_PhnInt');
		var val = Trim(phnInt.value);
		if(val == '') 
			return true;
		else 
			return false;
	}
	else
	{
		var phn0 = Trim($(fldID + '_Phn0').value);
		var phn1 = Trim($(fldID + '_Phn1').value);
		var phn2 = Trim($(fldID + '_Phn2').value);
	
		if(phn0 == '' && phn1 == '' && phn2 == '')
			return true;	
		else
			return false;	
	}
}
function IsPhnValid(fldID)
{
	var hidPhn = $(fldID + '_HidPhn');	
	if(hidPhn.value == '1')
	{
		var phnInt = $(fldID + '_PhnInt');
		var val = Trim(phnInt.value);
		return (val == '' || val.length > 9);
	}
	else
	{
		var phn0 = Trim($(fldID + '_Phn0').value);
		var phn1 = Trim($(fldID + '_Phn1').value);
		var phn2 = Trim($(fldID + '_Phn2').value);
		var phn3 = Trim($(fldID + '_Phn3').value);
		
		if(phn0 == '' && phn1 == '' && phn2 == '' && phn3 == '')
			return true;
		else
		{
			if(phn0.length == 3 && phn1.length == 3 && phn2.length == 4)
				return true;
			else
				return false;
		}
	}	
}

// only for the US phone numbers inputs and not on the extension and the International phone number
// needs to return true or false because the FldDupChk will follow if true
function VldtPhn(control, containerID, isReq)
{
	var container = $(containerID);
	var phn0 = $(containerID + '_Phn0');
	var phn1 = $(containerID + '_Phn1');
	var phn2 = $(containerID + '_Phn2');
	var phn3 = $(containerID + '_Phn3');						
	var phnInt = $(containerID + '_PhnInt');
	var hidPhn = $(containerID + '_HidPhn');	
		
	if(isReq != null && isReq == true)
	{
		// will only fire for the international input or for the last control so as to now show in red too early
		if((hidPhn.value == '1' || (hidPhn.vaue != '1' && control.id == (containerID + '_Phn2'))) && IsPhnEmpty(containerID))
		{
			SetPhnInvalidCss(containerID);		
			return false; // needs to get out because the check for isValid will reverse this			
		}
		else
		{			
			// only set the phone to valid if it really is
			if(IsPhnValid(containerID))
			{ 
				SetPhnValidCss(containerID);							
				return true; 
			}
		}
	
//		if(control.value.replace(' ', '') == '')
//		{						
//			SetPhnInvalidCss(containerID);		
//			return false;
//		}		
//		else if(container.className.indexOf(' err') != -1)
//		{																		
//			if(phn0.value.length == 3 && phn1.value.length == 3 && phn2.value.length == 4)// || (phn0.value.length == 0 && phn1.value.length == 0 && phn2.value.length == 0))
//			{			
//				SetPhnValidCss(containerID);				
//				return true;
//			}
//		}		
	}
	
	// will validate the phn number is correct if there is one entered (but not required)
	// will only fire on the last input or if there is something entered for each of the controls so as to not turn red before it should
	//if((control.id == (containerID + '_Phn2')  IsPhnValid
	if(
		hidPhn.value != '1' 
		&& 
		(
			((control.id == (containerID + '_Phn2') || (control.id == (containerID + '_Phn3'))) && (phn0.value.length != 0 || phn1.value.length != 0 || phn2.value.length != 0))
			|| (phn0.value.length != 0 && phn1.value.length != 0 && phn2.value.length != 0)
		)
		&& !IsPhnValid(containerID))
	{		
		SetPhnInvalidCss(containerID);		
		return false; 
	}
	else
	{ 
		SetPhnValidCss(containerID);			
		return true; 
	}		
	
}

// gets the phone number (needed because phone box is a special control)
function GetPhnVal(containerID)
{	
	//alert('GetPhnVal');
	if(GetControlValue(containerID + '_HidPhn') == '1') // when international so just get the txt value
	{
		return Trim(GetControlValue(fldID + '_PhnInt'));		
	}
	else
	{
		var phn0 = Trim(GetControlValue(containerID + '_Phn0'));
		var phn1 = Trim(GetControlValue(containerID + '_Phn1'));
		var phn2 = Trim(GetControlValue(containerID + '_Phn2'));
		var phn3 = Trim(GetControlValue(containerID + '_Phn3'));		
		
		if(phn0 != '' && phn1 != '' && phn2 != '')
		{
			return '(' + phn0 + ')' + phn1 + '-' + phn2 + (phn3 != '' ? ' ext' + phn3 : '');
		}
		else
			return '';
	}		
}

function SetPhnInvalidCss(containerID)
{
	var container = $(containerID);
	if(container.className.indexOf(' err') == -1)
	{ 			
		container.className += ' err';	
		$(containerID + '_Phn0').className += ' phnErr';
		$(containerID + '_Phn1').className += ' phnErr';
		$(containerID + '_Phn2').className += ' phnErr';
		$(containerID + '_Phn3').className += ' phnErr';
		$(containerID + '_PhnInt').className += ' err';						
	}
}

function SetPhnValidCss(containerID)
{
	var container = $(containerID);	
	if(container.className.indexOf(' err') != -1)
	{																		
		var phn0 = $(containerID + '_Phn0');
		var phn1 = $(containerID + '_Phn1');
		var phn2 = $(containerID + '_Phn2');
		var phn3 = $(containerID + '_Phn3');		
		var phnInt = $(containerID + '_PhnInt');
	
		phn0.className = phn0.className.replace(' phnErr', '');
		phn1.className = phn1.className.replace(' phnErr', '');
		phn2.className = phn2.className.replace(' phnErr', '');
		phn3.className = phn3.className.replace(' phnErr', '');
		phnInt.className = phnInt.className.replace(' err', '');
		container.className = container.className.replace(' err', '');					
	}
}

function IsSSNValid(fldID)
{		
	// first have to check if the control is shown because it could be not there
	if($(fldID + '_0'))
	{
		var val0 = Trim($(fldID + '_0').value);
		var val1 = Trim($(fldID + '_1').value);
		var val2 = Trim($(fldID + '_2').value);
		
		if(val0 != '' && (isNaN(val0) || val0.length != 3)) return false;
		if(val1 != '' && (isNaN(val1) || val1.length != 2)) return false;
		if(val2 != '' && (isNaN(val2) || val2.length != 4)) return false;		
	}
						
	return true;			
}
function IsSSNEmpty(fldID)
{
	// first have to check if the control is shown because it could be not there
	if($(fldID + '_0') != null)
	{
		var val0 = Trim($(fldID + '_0').value);
		var val1 = Trim($(fldID + '_1').value);
		var val2 = Trim($(fldID + '_2').value);				
				
		if(val0 == '' || val1 == '' || val2 == '') return true;
		
	}
	return false;
}
function VldtSSN(control, fldID, isReq)
{
	// don't need to validate untill the user has left the last input because validating on first two inputs is too early
	if(control.id == fldID + '_2' || $(fldID + '_0').className == 'err')
	{
		if(IsSSNValid(fldID) && (isReq == false || (isReq == true && !IsSSNEmpty(fldID))))
		{			
			SetSSNValidCss(fldID);
		}
		else
		{		
			SetSSNInvalidCss(fldID);
		}
	}			
}
function SetSSNInvalidCss(fldID)
{	
	if($(fldID + '_0').className.indexOf('err') == -1)		
	{ 				
		$(fldID + '_0').className = 'err';
		$(fldID + '_1').className = 'err';						
		$(fldID + '_2').className = 'err';						
	}
}
function SetSSNValidCss(fldID)
{
	if($(fldID + '_0').className.indexOf('err') != -1)		
	{ 										
		$(fldID + '_0').className = '';
		$(fldID + '_1').className = '';						
		$(fldID + '_2').className = '';								
	}	
}


// inline validation for an email fld
function VldtEml(control)
{
	if(!IsEmlValid(control.id))	
	{
		SetFldInvalidCss(control.id);			
		return false;
	}
	else
	{
		SetFldValidCss(control.id);
		return true;
	}
}

function VldtUrl(control)
{
	if(!IsUrlValid(control.id))
		SetFldInvalidCss(control.id);
	else
		SetFldValidCss(control.id);
}
// inline validation for a required fld, should be fired for onblur event
function VldtDt(control, isReturn)
{
	if(!IsDtValid(control.id))
	{
		SetFldInvalidCss(control.id);
		if(isReturn && isReturn == true) return false;
	}
	else
	{
		SetFldValidCss(control.id);
		if(isReturn && isReturn == true) return true;
	}
}
function IsDtValid(id, isSetCss)
{
	var control = $(id);
	
	if(control == null)  return true; // the control can be hidden at the time so exclude it if so 
	
	var dt = control.value;
	dt = dt.replace(" ", "");
	if(dt == "" || dt == dateFormat) return true; // if blank then its okay
	
	var validformat=/^\d{1,2}\/\d{1,2}\/\d{4}$/;
			
	if (!validformat.test(dt))
	{
		if(isSetCss && isSetCss == true) SetFldInvalidCss(id);
		return false;
	}
	else
	{ 
		var month = dt.split("/")[0];
		var day = dt.split("/")[1];
		var year = dt.split("/")[2];		
		
		var dayobj = new Date(year, month-1, day);
		
		if ((dayobj.getMonth() + 1 != month) || (dayobj.getDate() != day) || (dayobj.getFullYear() != year))
		{
			if(isSetCss && isSetCss == true) SetFldInvalidCss(id);
			return false;
		}
		else
		{
			var currentDate = new Date();
			//var currentYear = currentDate.getFullYear();
			//if(year < (currentYear - 150) || year > (currentYear + 100) || year < 1900 || year > 2079) // !!! if change this then need to update it in MyErrHdlr.cs
			/// smalldatetime limits
			if(year < 1900 || year > 2079) // !!! if change this then need to update it in MyErrHdlr.cs
			{
				if(isSetCss && isSetCss == true) SetFldInvalidCss(id);
				return false;
			}
			else
			{
				if(isSetCss && isSetCss == true) SetFldValidCss(id);
				return true;
			}
		}
	}	
}
function IsDtEmpty(id, isSetCss)
{
	var control = $(id);
	var dt = control.value;
	dt = dt.replace(' ', '');
	if(dt == '' || dt == dateFormat)
	{ 
		SetFldInvalidCss(id);
		return true; 
	}
	else 
	{
		SetFldValidCss(id);
		return false;
	}
}

function VldtTmHr(control)
{
	var val = Trim(control.value);
	if(IsNumRangeValid(val, 1, 12) == false)
	{	
		SetFldInvalidCss(control.id);			
		return false;
	}
	else
	{
		SetFldValidCss(control.id);	
		return true;
	}
}
function VldtTmMin(control)
{			
	var val = Trim(control.value);
	if(IsNumRangeValid(val, 0, 59) == false)
	{
		SetFldInvalidCss(control.id);			
		return false;
	}
	else
	{
		SetFldValidCss(control.id);	
		return true;
	}
}
function IsTmValid(id)
{
	var hrControl = $(id + '_hr');
	var minControl = $(id + '_min');
	
	if(VldtTmHr(hrControl) == true && VldtTmMin(minControl) == true)
		return true;
	else
		return false;
}
function IsDtTmValid(id)
{
	var hrControl = $(id + '_hr');
	var minControl = $(id + '_min');
	var dtControl = $(id + '_dt');
	
	// sets the controls css and returns true if they are valid
	if(VldtTmHr(hrControl) == true && VldtTmMin(minControl) == true && VldtDt(dtControl, true) == true)
		return true;
	else
		return false;
}

function IsTmEmpty(id)
{
	var hr = GetControlValue(id + '_hr');
	var min = GetControlValue(id + '_min');
	var returnVal = false;
		
	if(hr == '')
	{ 
		SetFldInvalidCss(id + '_hr');
		returnVal = true;
	}
	
	return returnVal;
}
	
function IsDtTmEmpty(id)
{
	var hr = GetControlValue(id + '_hr');
	var min = GetControlValue(id + '_min');
	var returnVal = false;

	if(IsDtEmpty(id + '_dt', true) == true) returnVal = true;
	
	if(hr == '')
	{ 
		SetFldInvalidCss(id + '_hr');
		returnVal = true;
	}
	// the minutes can be left empty 
//	if(min == '')
//	{ 
//		SetFldInvalidCss(id + '_min');
//		returnVal = true;
//	}
	
	return returnVal;
}

function VldtCur(control)
{
	if(IsCurValid(control.id) == false)
		SetFldInvalidCss(control.id);
	else
		SetFldValidCss(control.id);
}

function IsCurValid(id)
{
	var val = GetControlValue(id);
	if(val != '')
	{
		var valStripped = val.replace(',', '').replace('.', '');
		if(isNaN(valStripped)) return false;
		var dotIndex = val.indexOf('.');
		
		// if there is a dot present, it should be at the '1.00'
//		if(dotIndex != -1)	
//			if(dotIndex != (val.length - 3)) return false;					
	}
	
	return true;
}
function VldtCC(id, cardTypeCtrlID)
{	
	if(IsCCValid(id, cardTypeCtrlID) == false)
		SetFldInvalidCss(id);
	else
		SetFldValidCss(id);	
}

function IsCCValid(id, cardTypeCtrlID)
{
	var ctrl = $(id);
	if(ctrl == null || ctrl.offsetWidth == 0) return true;

	var cardNumber = GetControlValue(id);
	var cardType = GetDDLSelectedText(cardTypeCtrlID);
	if(cardNumber == '') return true;
	
	cardType = cardType.toLowerCase();	
	
  var isValid = false;
  var ccCheckRegExp = /[^\d -]/;
  isValid = !ccCheckRegExp.test(cardNumber);

  if (isValid)
  {
    var cardNumbersOnly = cardNumber.replace(/ /g,"").replace(/-/g, '');    
    var cardNumberLength = cardNumbersOnly.length;
    var lengthIsValid = false;
    var prefixIsValid = false;
    var prefixRegExp;

    switch(cardType)
    {
      case "mastercard":
        lengthIsValid = (cardNumberLength == 16);
        prefixRegExp = /^5[1-5]/;
        break;

      case "visa":
        lengthIsValid = (cardNumberLength == 16 || cardNumberLength == 13);
        prefixRegExp = /^4/;
        break;

      case "amex":
        lengthIsValid = (cardNumberLength == 15);
        prefixRegExp = /^3(4|7)/;
        break;

      default:
		return lengthIsValid = (cardNumberLength > 12 && cardNumberLength < 17);
        //prefixRegExp = /^$/;
        break;        
    }

    prefixIsValid = prefixRegExp.test(cardNumbersOnly);
    isValid = prefixIsValid && lengthIsValid;
  }

  if (isValid)
  {
    var numberProduct;
    var numberProductDigitIndex;
    var checkSumTotal = 0;

    for (digitCounter = cardNumberLength - 1; 
      digitCounter >= 0; 
      digitCounter--)
    {
      checkSumTotal += parseInt (cardNumbersOnly.charAt(digitCounter));
      digitCounter--;
      numberProduct = String((cardNumbersOnly.charAt(digitCounter) * 2));
      for (var productDigitCounter = 0;
        productDigitCounter < numberProduct.length; 
        productDigitCounter++)
      {
        checkSumTotal += 
          parseInt(numberProduct.charAt(productDigitCounter));
      }
    }

    isValid = (checkSumTotal % 10 == 0);
  }

  return isValid;
}

function VldtCCCode(control)
{
	if(IsCCCodeValid(control.id) == false)
		SetFldInvalidCss(control.id);
	else
		SetFldValidCss(control.id);	
}
function IsCCCodeValid(id)
{
	var val = GetControlValue(id);
	if(val != '')
	{
		var valLen = val.length;
		val = Number(val);
		if(isNaN(val)) return false;
		else if(valLen < 3 || valLen > 4) return false;
	}
	return true;
}

function VldtMonth(control)
{
	if(IsVldMonth(control.id) == false)
		SetFldInvalidCss(control.id);
	else
		SetFldValidCss(control.id);	
}
// for the CC Exp Month
function IsVldMonth(id)
{
	var val = GetControlValue(id);
	if(val != '')
	{
		val = Number(val);
		if(isNaN(val)) return false;
		else if(val < 1 || val > 12) return false;
	}
	return true;
}

function VldtYear(control)
{
	if(IsVldYear(control.id) == false)
		SetFldInvalidCss(control.id);
	else
		SetFldValidCss(control.id);	
}
// for the CC Exp Year
function IsVldYear(id)
{
	var val = GetControlValue(id);
	if(val != '')
	{
		var sVal = val;
		val = Number(val);
		
		var currentDate = new Date();
		var currentYear = currentDate.getFullYear();
				
		
		if(isNaN(val)) return false;
		else if(sVal.length == 2)
		{
			currentYear = Number(String(currentYear).substr(2,2));			
			if(val < currentYear || val > (currentYear + 20)) return false;			
		}
		else if(sVal.length == 4)
		{
			if(val < currentYear || val > (currentYear + 20)) return false;
		}		
		else // means that it was not 2 or 4 digits so its not valid
			return false;
	}
	return true;
}


function VldtNum(control)
{
	if(IsNumValid(control.id) == false)
		SetFldInvalidCss(control.id);
	else
		SetFldValidCss(control.id);	
}
function IsNumValid(id)
{
	
	var val = GetControlValue(id);
	if(val != '')
	{		
		if(isNaN(val)) return false;		
		
		// check if the number is allowed to be negative
		var isNeg = $(id).getAttribute('isneg');
		if(isNeg == '0') 
		{
			if(Number(val) < 0) return false;
		}
	}
	
	return true;
}

function IsNumRangeValid(val, minNum, maxNum)
{	
	if(val != '')
	{
		if(isNaN(val))				
			return false;
		else
		{
			var num = Number(val);		
			if(num < minNum || num > maxNum)							
				return false;			
		}
	}			

	return true;
}

function IsImgValid(id)
{
	var val = GetControlValue(id);
	if(val != '')
	{				
		var extension = GetFileExtension(val);
		return IsArrayContains(arrAllowedImgTypes, extension);		
	}	
	return true;
}
function VldtImg(control)
{
	if(IsImgValid(control.id) == false)
		SetFldInvalidCss(control.id);
	else
		SetFldValidCss(control.id);	
}

function IsDocValid(id)
{
	var val = GetControlValue(id);
	if(val != '')
	{				
		var extension = GetFileExtension(val);
		return IsArrayContains(arrAllowedDocTypes, extension);		
	}
	
	return true;
}
function VldtDoc(control)
{
	if(IsDocValid(control.id) == false)
		SetFldInvalidCss(control.id);
	else
		SetFldValidCss(control.id);	
}

/// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
/// Make sure to update MyCtrl.GetJsEH with any new handlers for field types
/// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!


var arrDupNm = new Array(); 
var arrDupLnk = new Array();

// called when a duplicate is found, dup control id is first added to the arrDup
function ShowDupMsg()
{
	var dvDup = $('dvDup');
	
	if(arrDupNm.length > 0)
	{
		var str = '<div class="center"><img src="/SAM/Img/Warning.png" /><span class="errHdr">Duplicate Record Alert!<a name="dupDiv">&nbsp;</a></span></div>';
		str += '<ul>';
		for(var i = 0; i < arrDupNm.length; i++)
		{
			str += '<li>The <b>' + arrDupNm[i] + '</b> is entered for another Record.<span class="PL10">&nbsp;</span>';
			if(arrDupLnk[i] != null && arrDupLnk[i] != '') str += '<a href="' + arrDupLnk[i] + '" target="_blank">View Duplicate Record</a>';
			str += '</li>';
		}
		str += '</ul>';
		dvDup.className = "dvErr";
		dvDup.innerHTML = str;		
		dvDup.style.display = '';
		
	}	
	else if(dvDup.style.display != 'none')
	{ 
		dvDup.style.display = 'none';
	}
}

function IsPasswordValid(id)
{
    /// If the container is hidden then it means that the password has already been set
    var cntr = $(id + '_cntr');    
    if(cntr && cntr.style && cntr.style.display == 'none') return true;
    
	var val = GetControlValue(id);
	// the password cannot be valid
	if(val != '')
	{	
		var regEx = /^.*(?=.{8,})(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).*$/;
		return regEx.test(val);
	}
	else
	{
		return true; // it can be blank because the Req fld is checked elsewhere
	}
}

function VldtPassword(control)
{
	if(IsPasswordValid(control.id) == false)
		SetFldInvalidCss(control.id);
	else
		SetFldValidCss(control.id);	
}

function IsPasswordConfirm(id)
{
    /// If the container is hidden then it means that the password has already been set
    var cntr = $(id + '_cntr');    
    if(cntr && cntr.style && cntr.style.display == 'none') return true;
    
	var pas = GetControlValue(id);
	var pasConfirm = GetControlValue(id + '_Confirm');
	if(pas != '')
	{
		return pas == pasConfirm;
	}
	else
		return true; // true because it means that it is not being entered right now
}

function VldtPasswordConfirm(control)
{
	var id = control.id.replace('_Confirm', '');
	if(!IsPasswordConfirm(id)) 
	{
		SetFldInvalidCss(control.id);
		SetFldInvalidCss(id);
	}
	else
	{
		if(IsPasswordValid(control.id)) SetFldValidCss(control.id);	
		if(IsPasswordValid(id)) SetFldValidCss(id);	
	}
	 
	
}

function IsUsernameValid(id)
{
	var val = GetControlValue(id);
	if(val.length < 6)
	{			
		return false;
	}
	else
	{
		return true;
	}
}

function VldtUsername(control)
{
	if(IsUsernameValid(control.id) == false)
		SetFldInvalidCss(control.id);
	else
		SetFldValidCss(control.id);	
}


/// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
/// Make sure to update MyCtrl.GetJsEH with any new handlers for field types
/// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

// for the SearchCtrl and other places that use the MyFld stuff
function MyFldValidateInput()
{				
	var arrReqs = new Array();		
	var arrDt = new Array();
	var arrTm = new Array();
	var arrNum = new Array();
	var arrCur = new Array();
	var arrEml = new Array();
	var arrUrl = new Array();
	var arrPhn = new Array();
	
	var hidNum = GetControlByMyID('input', 'hidNum');
	var searchNum = Number(hidNum.value);
	
	for(var i = 0; i < searchNum; i++)
	{
		
		if(GetControlValue('hidIsDel_' + i) != '1')
		{
			var ddlFld = $('FldID_' + i);
			var oprtr = GetControlValue('Oprtr_' + i);
			//alert(' oprtr = ' + oprtr);
			if($('FldID_' + i) == null && $('Tbl_' + i) != null)
			{
				arrReqs[arrReqs.length] = 'Tbl_' + i;
			}
			else
			{
				//alert(ddlFld.options[ddlFld.selectedIndex].value); return;
				if(ddlFld.options[ddlFld.selectedIndex].value == '') 
					arrReqs[arrReqs.length] = ddlFld.id;
				else
				{
					var fldTpID = ddlFld.options[ddlFld.selectedIndex].getAttribute('fldtpid');
					
					
					// Checking if inputs are empty
					
					// region has special checking because it has two inputs
					//alert('fldTpID = ' + fldTpID)
					if(fldTpID == '10') 
					{
						if(oprtr != '' && oprtr != 'is null' && oprtr != 'is not null' && oprtr != 'AllEntr' && oprtr != 'AllEmpty') // have to check for blank because this is for the Fld_Val_Edt too
						{
							if(GetControlValue('hidIsStFltrVal_' + i) == '1') // when state
							{
								if(IsInputEmpty('stFltrVal_' + i)) arrReqs[arrReqs.length] = 'stFltrVal_' + i;
							}
							else
							{
								if(IsInputEmpty('FldVal_' + i)) arrReqs[arrReqs.length] = 'FldVal_' + i;
							}
						}
					}
					// check if the input is empty, dates are NOT checked here because they have special checks setup 
					else if(fldTpID != '2' && fldTpID != '4')
					{
						
						if(oprtr != '' && oprtr != 'is null' && oprtr != 'is not null' && oprtr != 'AllEntr' && oprtr != 'AllEmpty' && IsInputEmpty('FldVal_' + i)) arrReqs[arrReqs.length] = 'FldVal_' + i;
					}
					
					
					if(fldTpID == '2' || fldTpID == '4') // Date or DateTime
					{
												
						if(oprtr.indexOf('DateDiff') == 0)
						{														
							if(IsInputEmpty('FltrDtNum_' + i)) arrReqs[arrReqs.length] = 'FltrDtNum_' + i;
							else if(!IsNumValid('FltrDtNum_' + i)) arrNum[arrNum.length] == 'FltrDtNum_' + i							
						}
						else
						{
							if(oprtr.indexOf('DatePart') == -1 && oprtr != '' &&  oprtr != 'is null' && oprtr != 'is not null' && oprtr != 'AllEntr' && oprtr != 'AllEmpty' && IsInputEmpty('FldVal_' + i)) arrReqs[arrReqs.length] = 'FldVal_' + i;
							
							if(fldTpID == '4')
							{							
								if(!IsDtValid('FldVal_' + i + '_dt')) arrDt[arrDt.length] = 'FldVal_' + i + '_dt';												
								if(!IsTmValid('FldVal_' + i)) arrTm[arrTm.length] = 'FldVal_' + i;
							}
							else
							{							
								if(!IsDtValid('FldVal_' + i)) arrDt[arrDt.length] = 'FldVal_' + i;												
							}
						}
					}
					else if(fldTpID == '3') // Time
					{
						if(!IsTmValid('FldVal_' + i)) arrTm[arrTm.length] = 'FldVal_' + i;
					}
					else if(fldTpID == '13' || fldTpID == '16') // number/decimal
					{
						if(!IsNumValid('FldVal_' + i)) arrNum[arrNum.length] = 'FldVal_' + i;
					}
					else if(fldTpID == '6') // currency
					{
						if(!IsCurValid('FldVal_' + i)) arrCur[arrCur.length] = 'FldVal_' + i;
					}
				
				}
			}			
		}
	}
	
	if(arrReqs.length > 0 || arrDt.length > 0 || arrTm.length > 0 || arrNum.length > 0 || arrCur.length > 0 || arrEml.length > 0 || arrUrl.length > 0 || arrPhn.length > 0)
	{
		ShowErrMsg(arrReqs, arrDt, arrTm, arrNum, arrCur, arrEml, arrUrl, arrPhn);	
		return false;
	}	
	else
		return true;
}
