// JavaScript Document <!--


function isNumeric (str)
{
    return 0>str.search(/[^0-9]/);
}

function isAlphaNumeric (str)
{
    return 0>str.search(/[^0-9A-Za-z]/);
}

/**
 * returns true if string has double quotes.
 * @param str
 * @return
 */
function hasDoubleQuotes(str) {
	return (str.indexOf('"') >-1);

}
function isPhone (str)
{
    if (str.length <13)  return false;
    var count = 0;
    for(var i = 0; i < str.length; i++){
        var strC = str.charAt(i);
        var nFound = false;
    	if(isDigit(strC)) {
    		nFound = true;
    		count++;
    	}
    	if (!nFound && !(strC == ')') && !(strC =='(') && !(strC == '-')) return false;
    }   
    return (count==10);
}

function isSSN (str){
    return 0>str.search(/[^0-9 -]/);
}

function isZipcode (str){
    return 0>str.search(/[^0-9 -]/);
}
function isEmail(str) {

		var at="@"
		var dot="."
		var lat=str.indexOf(at)
		var lstr=str.length
		var ldot=str.indexOf(dot)
		if (str.indexOf(at)==-1){
		   //alert("Invalid E-mail ID")
		   return false
		}
		if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr){
		   //alert("Invalid E-mail ID")
		   return false
		}
		if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr){
		    //alert("Invalid E-mail ID")
		    return false
		}

		 if (str.indexOf(at,(lat+1))!=-1){
		    //alert("Invalid E-mail ID")
		    return false
		 }

		 if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot){
		    //alert("Invalid E-mail ID")
		    return false
		 }

		 if (str.indexOf(dot,(lat+2))==-1){
		    //alert("Invalid E-mail ID")
		    return false
		 }
		
		 if (str.indexOf(" ")!=-1){
		    //alert("Invalid E-mail ID")
		    return false
		 }

 		 return true					
	}

function GetDaysInMonth(intMonth, intYear) {
	var arrDaysInMonth = new Array(31,28,31,30,31,30,31,31,30,31,30,31);
	var intCount = arrDaysInMonth[intMonth-1];
	if(intMonth == 2) {
		if((intYear%4) == 0 ) {	// post-2000 leap year - ignore 2100 etc.
			intCount++;
		}
	}
	return intCount;
}
<!-- Begin

function ValidatePhone(m){
p=m.value

sp = p.indexOf(' ');
while(sp != -1) {
        p = p.substring(0,sp) + p.substring(sp+1, p.length);
        sp = p.indexOf(' ');
}
if(p.length==3){
        pp=p;
        d4=p.indexOf('(')
        d5=p.indexOf(')')
        if(d4==-1){
                pp="("+pp;
        }
        if(d5==-1){
                pp=pp+")";
        }
        m.value="";
        m.value=pp;
}
if(p.length>3){
        d1=p.indexOf('(')
        d2=p.indexOf(')')
        if (d2==-1){
                l30=p.length;
                p30=p.substring(0,4);
                p30=p30+")"
                p31=p.substring(4,l30);
                pp=p30+p31;
                m.value="";
                m.value=pp;
        }
}
if(p.length>5){
        p11=p.substring(d1+1,d2);
        if(p11.length>3){
             p12=p11;
             l12=p12.length;
             l15=p.length
             p13=p11.substring(0,3);
             p14=p11.substring(3,l12);
             p15=p.substring(d2+1,l15);
             m.value="";
             pp="("+p13+")"+p14+p15;
             m.value=pp;
        }
        l16=p.length;
        p16=p.substring(d2+1,l16);
        l17=p16.length;
        if(l17>3&&p16.indexOf('-')==-1){
                p17=p.substring(d2+1,d2+4);
                p18=p.substring(d2+4,l16);
                p19=p.substring(0,d2+1);
        pp=p19+p17+"-"+p18;
        m.value="";
        m.value=pp;
        }
}

}

function testphone(obj1){
         p=obj1.value
         p=p.replace("(","")
         p=p.replace(")","")
         p=p.replace("-","")
         p=p.replace("-","")
         if (isNaN(p)==true){
                  alert("Check phone");
                  return false;
         }
}
//  End -->


// for Validaing a date entry
function cleanDigits(strDigits) {
	var strResult = "0";
	for(var i = 0; i < strDigits.length; i++){
		var strC = strDigits.charAt(i);
		if(isDigit(strC)) {
			strResult += "" + strC;
		}
	}
	var iResult = parseInt(strResult,10);
	return(iResult);
}
function isDigit(ch) {
	return(ch >= '0' && ch <= '9');
}
function IsValidDate(intDate, intMonth, intYear) {
	if( (intYear > 2050) || (intYear < 1900) ) {return false;}
	if( (intMonth > 12) || (intMonth < 1) ) {return false;}
	if(intDate < 1) {return false;}
	var intMaxDate = GetDaysInMonth(intMonth, intYear);
	if(intDate > intMaxDate) {return false;}
	return true;
}
function isDate(strDate){
	var lenDateString = strDate.length;
	if(lenDateString == 0) {return(false);}

	arrDate = strDate.split("/");
	if(arrDate.length < 3) {return(false);}

	var intMonth = cleanDigits(arrDate[0]);
	var intDate = cleanDigits(arrDate[1]);
	var intYear = cleanDigits(arrDate[2]);
	return IsValidDate(intDate, intMonth, intYear);	
}

function validateForm()
{
  expandAll();
  displayCollapseAllImg();
  // this object that holds the "document.form1" object
  form = document.forms[0];  
  
  //make sure that callDateTime date and time parts are already exist before validating them.
  if(form.callDateTime != null && form._date_callDateTime != null && form._time_callDateTime != null){
  	// Make sure CallDate be filled
  	if(form._date_callDateTime.value == "" ){
    	alert('Please enter the date of call');
	    form.date_callDateTime.focus();
    	return false;
  	}
  	// Make sure CallTime be filled
  	if(form._time_callDateTime.value == ""){
    	alert("the time of call has not been entered or it is incorrect.");
    	form._hour_time_callDateTime.focus();
    	return false;
   	}
  }
   
  // Make sure ContactTypeId value
  if( form.ContactId.value == "" ){
    alert('Please enter the Contact Type');
    form.ContactId.focus();
    return false;
  }
  
  // Confirm from the user if he needs to leave the priority empta.
  if(!validatePriority(form.PriorityID)){
  	return false;
  }
  
  // Make sure IncidentDate be filled
  if( form.IncidentDate.value == "" ){
    alert('Please enter the incident date');
    form.IncidentDate.focus();
    return false;
  }
  // make sure if at most one category was chosen in a single category CAS applications
  if (form._SubCategorySelected != null && !validateCategories()) {
  	return false;
  }
  // Make sure IncidentTime be filled
  if(form.IncidentTime.value == ""){
    var agree = confirm("Incident time has not been entered or it is incorrect. Do you still want to continue?");  
    if (!agree) {
        form._hourIncidentTime.focus();
        return false;
    }
  }
  
  // Make sure Customer(s) information be filled
  if(form._CustomerIdsRadio && form._CustomerIdsRadio[0].checked){
    var agree = confirm("Are you sure that you want to file this case as 'Anonymous' customer?");
    if (!agree) {
        form._CustomerIdsRadio[0].focus();
        return false;
    }
  }else {
	var ci = document.getElementById('_CustomersInfo');
  	if ((ci && ci.innerHTML == "") 
  		|| (form._CustomersInfo && (form._CustomersInfo.value == null || form._CustomersInfo.value == ""))) {
	  // select customers option was chosen here
	    alert('Please click on the select customer(s) button to assign customer(s) to this new CAF.');
	    return false;
	 }
  }
  // Reference must be provided
  if (form._isReleaseAction.value == "true" && form.Reference.value == "") {
    if (form._ForceNotReleasedCase != null && form._ForceNotReleasedCase.value=="true") {
    	if (form.Dept == null  || form.Dept.value == "") {
    		alert("You should have, at least, the 'Referred To' or 'Department' fields filled out.");
		    form.Reference.focus();
		    form.Reference.select();
		    return false;
    	}
    } else {
	    alert("Enter a reference in FollowUp section");
	    form.Reference.focus();
	    form.Reference.select();
	    return false;
    }
  }
  // Users might refer a caf case to themselves. An extra check is made to make sure that the reference 
  // name is not as same as the login username while adding a case.
   if (form._LoginUsername != null && !canReferToSelf(form._LoginUsername.value)){
      return false;
   }
  if (form.FollowupDate != null && form.FollowupDate.value !="" && !isDate(form.FollowupDate.value)){
    alert('Date field must be a date!. Format: MM/DD/YYYY');
    form.FollowupDate.focus();
    form.FollowupDate.select();
    return false;
  }else
  if (form.ERDate != null && form.ERDate.value !="" && !isDate(form.ERDate.value)){
    alert('Date field must be a date!. Format: MM/DD/YYYY');
    form.ERDate.focus();
    form.ERDate.select();
    return false;
  }else
  if (form.CRDate != null && form.CRDate.value !="" && !isDate(form.CRDate.value)){
    alert('Date field must be a date!. Format: MM/DD/YYYY');
    form.CRDate.focus();
    form.CRDate.select();
    return false;
  }else {
    doSubmit();
  }
}

function validateFormEC(){
  // this object that holds the "document.form1" object
  form = document.forms[0];
  // Make sure IncidentDate is filled
  if( form.IncidentDate.value == "" ){
    alert('Please enter the incident date');
    // form.IncidentDate.focus();
    return false;
  }else
  // Make sure IncidentDate is filled
  if(!isDate(form.IncidentDate.value)){
    alert('Incident Date is incorrect!. Format: MM/DD/YYYY.');
    // form.IcidentDate.focus();
    return false;
  }else
    // Make sure IncidentTime be filled
  if(form.IncidentTime.value == ""){
    var agree = confirm("Incident time has not been entered or it is incorrect. Do you still want to continue?");
    if (!agree) {
        form._hour.focus();
        return false;
    }
  } else
  // Make sure Customer(s) information be filled
  if(form._CustomerIdsRadio[0] && form._CustomerIdsRadio[0].checked){
    var agree = confirm("Are you sure that you want to file this case as 'Anonymous' customer?");
    if (!agree) {
        form._CustomerIdsRadio[0].focus();
        return false;
    }
  }else if (form._CustomerIdsRadio[0] && (form._CustomersInfo.value == null || form._CustomersInfo.value == "")) {
  // select customers option was chosen here
    alert('Please click on the select customer(s) button to assign customer(s) to this case.');
    form._CustomersInfo.focus();
    return false;
  }
  else{
     doSubmit();
  }
}

/*
 * This function will be called from all JSPs (Except ReadCaf.jsp) to change the submit button's
 * Caption during the submission process
 *
 */
function doSubmit(){
  // this object that holds the "document.form1" object
  form = document.forms[0];
  for (var i=0;i<form.elements.length;i++){
	   	var e = form.elements[i];
	   	if (e.type=='submit')  {
	   	    e.value = "Please Wait.......";
            e.disabled  = true;
        }
   }
   form.submit();
   return true;
}

function validateFormReadCaf(){
  // this object that holds the "document.form1" object
  form = document.forms[0];
  // Make sure ContactTypeId value
  if( form.txtSETContactId.value == "" ){
    alert('Please enter the Contact Type');
    form.txtSETContactId.focus();
    return false;
  }
  
  // Confirm from the user if he needs to leave the priority empta.
  if(!validatePriority(form.txtSETPriorityID)){
  	return false;
  }
  // make sure if at most one category was chosen in a single category CAS applications
  if (form._SubCategorySelected != null && !validateCategories()) {
  	return false;
  }
  // Reference must be provided
  if (form.Reference.value == "") {
     alert("Enter a reference in FollowUp section");
     form.Reference.focus();
     form.Reference.select();
     return false;
  }
  // This check for dual inbox users. these users might release a caf case back to themselves.
  // To stop this from happening, an extra check is considered to make sure that the reference 
  // name is not as same as the login username while updating and release the current viewed case.
  if (form._LoginUsername!=null && !canReferToSelf(form._LoginUsername.value)){
     return false;
  }
  else{
     doSubmit();
  }
}

/**
 * Function that is used to validate all the required textarea fields in the CAF form
 */
function validateRequiredFields() {
  var form = document.forms[0];
  var elements = form.elements;

  for (var i=0;i< elements.length; i++){
	var e = elements[i];
	if (e.tagName.toLowerCase() == 'textarea')  {
	    if (e.className != null) {
	   		required = e.className.indexOf('required') >= 0;
	    }
    	if (required && !e.disabled && !e.readOnly && (e.value == null || e.value == "")) {
		    index = e.className.indexOf('|') + 1;
		    alert('Please enter the ' + e.className.substring(index) + ' textarea');
		    e.focus();
		    return false;
		}
	 }
   }
   return true;
}
/**
 * validate the CAF form after clicking on the update & close button
 */
function validateFormReadCafForClosing(){

  // this object that holds the "document.form1" object
  form = document.forms[0];
  
  // Confirm from the user if he needs to leave the priority empty.
  if(!validatePriority(form.txtSETPriorityID)){
  	return false;
  }

  // make sure if at most one category was chosen in a single category CAS applications
  if (form._SubCategorySelected != null && !validateCategories()) {
  	return false;
  } else {
  	doSubmit();
  }
}

function modifyTime(time,h,m,ampm){
    // check the hour, m and ampm if they are null of zero-length string
    if (h == null || h.value == "" || m == null || m.value == "" ||
                ampm == null || ampm.value == "")
        time.value = "";
    else
        time.value = h.value +":"+m.value+":00 "+ampm.value;
}

function MM_openBrWindow(theURL,winName,features) { //v2.0
  window.open(theURL,winName,features);
}

var MAXLIMIT = 5000;
function textCounter(field, countfield, maxCount) {
	if (!maxCount) {
		maxCount = MAXLIMIT
	} 
	if (field.value.length > maxCount) // if too long...trim it!
	{
	       field.value = field.value.substring(0, maxCount);
	       alert("You can not enter more than "+maxCount+" characters");
	}
	// otherwise, update 'characters left' counter
	else
		countfield.value = maxCount - field.value.length;
}
//alerts if the length of a entered string exceeds a predefined length(maxCharacters)
function characterCounter(e, field , maxCharacters)
{
	// To make it compatible with firefox.
	evt = e || window.event;
	var keyPressed = evt.which || evt.keyCode;

	if(keyPressed != 8 && keyPressed != 46)
	{
       if (field.options[field.selectedIndex].value.length > maxCharacters )
       {
           field.options[field.selectedIndex].value = field.options[field.selectedIndex].value.substring(0 , maxCharacters);
    	   field.options[field.selectedIndex].text = field.options[field.selectedIndex].value.substring(0 , maxCharacters);
	       field.options[field.selectedIndex].selected=true;
           alert("The length should not exceed "+maxCharacters+" characters."); 
       }
	}
}

function trim(string)  {
    return string.replace(/^(\s+)?(.*\S)(\s+)?$/, '$2');
}

//Function source: http://www.pbdr.com/jscript/trimstr.htm
function trimText(sInString)
{
    sInString = sInString.replace( /^\s+/g, "" );// strip leading
    return sInString.replace( /\s+$/g, "" );// strip trailing
}

function removeValue(commaString, value) {
    var result = "";
    var startIdx = commaString.indexOf(value);
    var endIdx = startIdx + value.length;
    if (startIdx == 0) {
        endIdx++;
        result = commaString.substring(endIdx)
    } else if (endIdx == commaString.length) {
        result = commaString.substring(0, --startIdx);
    } else {
        result = commaString.substring(0, startIdx) + commaString.substring(++endIdx, commaString.length);
    }
    return result;
}

//method to set transaction
function setTransaction(val){
    document.form1._Transaction.value = val;    
}
//method to clear the date field
function cleardate(name)
{
var field = document.getElementById(name);
field.value = "";
}

//Set Transaction type and Save categories for CAF
function setTransnSaveCat(val){
	//set transaction
    setTransaction(val);
    
    //save categories
    alwaysSelectedItems(document.form1._SubCategorySelected);
}

/* Global variables used to swtich between the "Update" and "Update & Release" Actions*/
var referHtmlTD = null;
var ccHtmlTD = null;
var buttonCaption = null;

/*
 * This function swtich between the update and update & release action for users with the 
 * canConvertUpdateReleaseActionToUpdate() permission.
 */
function switchBetweenUpdateAndUpdateRelease(updateTransNo, updateReleaseTransNo){
	var form = document.forms[0];
	var cb = document.getElementById('_convertToUpdate');
	var toTD = document.getElementById('toTD');
	var ccTD = document.getElementById('ccTD');
	if (cb.checked) {

		if (buttonCaption == null) {
			buttonCaption = form._updateButton.value;
			referHtmlTD = toTD.innerHTML;
			ccHtmlTD = ccTD.innerHTML;
		}
		form._updateButton.value = "  Update  ";
		toTD.innerHTML = "Referred To";
		ccTD.innerHTML = "<image src='images/red.jpg' width='14' height='14'/>CC"
		form._updateButton.onclick = function anonymous() { setTransaction(updateTransNo); if (form._SubCategorySelected != null && validateCategories())  doSubmit(); else return false; }
	} else {
		
		form._updateButton.value = buttonCaption;
		toTD.innerHTML = referHtmlTD;
		ccTD.innerHTML = ccHtmlTD;
		form._updateButton.onclick = function anonymous() { setTransaction(updateReleaseTransNo); return validateFormReadCaf(); }
	}
	
}



/*
 * Users might refer a caf case to themselves. An extra check is made to make sure that the reference 
 * name is not as same as the login username while adding/releasing a case.
 */
function canReferToSelf(loginUsername)
{
    var form = document.forms[0];
    var agree = true;
    if (loginUsername != null && form.Reference.value.indexOf(loginUsername) >= 0) 
    {
  	   alert("Sorry, transaction is not allowed. You cannot release a case to yourself.\nPlease refer this case to another user.");
       form.Reference.focus();
       form.Reference.select();
       agree = false;
    }
    return agree;
}

/*
	I takes a dateTimeObj, date, time and change the value of the dateTimeObj depending on the values of date and time.
*/
function modifyDateTime(dateTimeObj, date ,time){
	if(date == null){
		dateTimeObj.value = "";
	} else if (time == null){
		dateTimeObj.value = date.value + " 00:00:00 am";
	} else {
		dateTimeObj.value = date.value + " " + time.value;
	}
}

/*
	It takes a dateObj (field) and checks if it is a part of DateTime field.
	if it is a part of a DateTime field it will call the 'modifyDateTime' function to change the value of the dateTime field
*/

function modifyDateTimeByDateObj(dateObj){
    if (document.form1._DATE_TIME_SUFIX != null) {
		var dateTimeSufix =document.form1._DATE_TIME_SUFIX.value;				//DateTime field sufix
		if(dateObj != null && dateObj.name.indexOf(dateTimeSufix)!=-1){			// if it is a DateTime field
			var datePrefix = document.form1._DATE_PREFIX.value;					//date field prefix
			var timePrefix = document.form1._TIME_PREFIX.value;					//time field prefix
			var dateTimeObjName = dateObj.name.substr(datePrefix.length);		
			var timeObjName = timePrefix + dateTimeObjName;
			var dateTimeObj = document.getElementsByName(dateTimeObjName)[0];
			var timeObj = document.getElementsByName(timeObjName)[0];
			modifyDateTime(dateTimeObj, dateObj, timeObj);
		}
	}
}
/*
	- It validates the Priority.
	- @param: priorityCtrl
*/
function validatePriority(priorityCtrl){
	var form = document.forms[0];	
	
	if(priorityCtrl!= null && priorityCtrl.value == ""){
		if(form._canValidatePriority != null && form._canValidatePriority.value== 'true'){
			var agree = confirm("Are you sure that you don't want to assign a priority to this case?");  
			if (!agree) {
				priorityCtrl.focus();
				return false;
			}
		}
	}
    return true;
}
//-->