// The following functions validate data type semantics of the input value

//--------------------------------------------------
//--------------------------------------------------

// function VAL_List
// Parameters
//   strList --- the input list
//   strDelimter --- a string containing all the characters that are valid delimiter
//   intOption --- extra delimiter options
//    1 : strList is list of numbers
//    2 : strList is list of alphanumeric words
//    3 : strList is list of words with no numeric characters
// return 1 if strList is a list delimted by strDelimiter
// return 0 if strList is empty
// return -1 if strList is not a list
// return -2 if any of the parameter is invalid
function VAL_List(strList, strREDelimiter, intOption)
{
	var re_listitem;
	var strDelimit;
	var strText;
	var strTmp;
	var isList;
	var iindex;

	if (strList == null || strREDelimiter == null)
		return -2;

	if (strList.length == 0)
		return 0;

	// if no delimiter is provided, use "," as the delimiter
	if (strREDelimiter.length == 0)
		strDelimit = ",";
	else
		strDelimit = strREDelimiter;

	switch (intOption)
	{
		case '1'	:
			strText = "[0-9]+"
			break;
		case '2'	:
			strText = "\w+"
			break;
		case '3'	:
			strText = "[A-Za-z_]+"
			break;
		default		:
			strText = "\w+"
	}

	strTmp = strText + strDelimit
	re_listitem = new RegExp(strTmp, "g");

	isList = true;
	strTmp = strList;

	// Remove all spaces
	strTmp = strTmp.replace(/\s/g,"");
//	alert(strTmp + " no space: " +  re_listitem.source);
	// Remove all list item up to last item
	strTmp = strTmp.replace(/[0-9]+,/g,"");
//	alert(strTmp + " last left: " +  re_listitem.source);

	if (strTmp.length == 0)
	{
		//strList=strList.substring(0,strList.length-1);
		//alert("OK: "+strList);
		return 2;
	}

	// Remove last item
	re_listitem = new RegExp(strText)
	strTmp = strTmp.replace(/[0-9]+/,"");

//	alert(strTmp + " reg: " +  re_listitem.source);
	if (strTmp.length == 0)
		return 1;
	else
		return -1;


}


// Format_Date
// return a formatted date in a string specify by the option
// 1) return MM/DD/YYYY and do not append 0 to single digit month and day
// 2) return MM/DD/YYYY and append 0 to single digit month and day
// 3) return MM/DD/YY and do not append 0 to single digit month and day
// 4) return MM/DD/YY and append 0 to single digit month and day
// 5) return MM and do not append 0 to single digit month
// 6) return MM and append 0 to single digit month
// 7) return DD and do not append 0 to single digit day
// 8) return DD and append 0 to single digit day
// 9) return YYYY
// 10) return YY
//
var VAL_FD_MDYYYY = 1;
var VAL_FD_MMDDYYYY = 2;
var VAL_FD_MDYY = 3;
var VAL_FD_MMDDYY = 4;
var VAL_FD_M = 5;
var VAL_FD_MM = 6;
var VAL_FD_MMM =7
var VAL_FD_D = 8;
var VAL_FD_DD = 9;
var VAL_FD_YYYY = 10;
var VAL_FD_MMMDDYYYY = 11;
//var VAL_FD_YY = 11;

var VAL_RE_MMD = 1;
var VAL_RE_MMMD =2;
var VAL_RE_DMMM =3;
var REDateMatchArray = new Array(
  	/(\d?\d)[\/,-](\d?\d)[\/,-](\d?\d?\d\d)/, 1,
  	/(\d\d)(\d\d)(\d\d\d\d)/, 1,
   	/([a-zA-Z]{3})[\/,-]?(\d\d)[\/,-]?(\d\d\d\d|\d\d)/, 2,
		/(\d?\d)[\/,-]?([a-zA-Z]{3})[\/,-]?(\d\d\d\d|\d\d)/, 3,
  	/([a-zA-Z]{3})[\/,-](\d?\d)[\/,-](\d\d\d\d|\d\d)/, 2,
		/(\d\d)(\d\d)(\d\d)/, 1);

function Format_Date(strDate, Option) {
  var strMMM, strMM, strM, strDD, strD, strYY, strYYYY;
  var strRet = "";
  var intM, intD, intY;

/*  var REMatch = /(\d?\d)[\/,-](\d?\d)[\/,-](\d?\d?\d\d)/;
  var REMatch2 = /(\d\d)(\d\d)(\d\d\d\d)/;
  var REMatch3 = /(\d\d)(\d\d)(\d\d)/;
*/
  var MatchArray;
  var i = 0;
  var iFormat=0;

  // split the date up into Month, Day, and year
  i=0;
  while (MatchArray == null && i < REDateMatchArray.length)
  {
  	MatchArray = strDate.match(REDateMatchArray[i]);
  	if (MatchArray == null) i+=2;
  }
  if (MatchArray != null)
  {
  	iFormat= REDateMatchArray[i+1];
  	if (MatchArray.length  == 4)
  	{

  		if (iFormat == VAL_RE_DMMM)
  		{
	 	    strM = MatchArray[2];
  	 	  strD = MatchArray[1];
  		}
  		else
  		{
 	    	strM = MatchArray[1];
   	  	strD = MatchArray[2];
   	  }

   	 	// if month is in MMM format, change to M format
   	  if (iFormat != VAL_RE_MMD)
   	  {

   	  	strM = val_Month(strM);
   	  }

   	  strYY = MatchArray[3];
   	  if ( (intM = val_Month(strM)) < 10) strMM = "0"+ intM;
   	  else strMM = strM;
   	  strMMM = val_Month(strM,true);
   	  if ( (intD = val_Day(strD,strM,strYY)) < 10) strDD = "0"+ intD;
   	  else strDD = strD;
	    strYYYY = "" + val_Year(strYY);

	    switch (Option) {
	    case 1: strRet = strM + "/" + strD + "/" + strYYYY; break;
	    case 2: strRet = strMM + "/" + strDD + "/" + strYYYY; break;
	    case 5: strRet = strM; break;
	    case 6: strRet = strMM; break;
	    case 7: strRet = strMMM; break;
	    case 8: strRet = strD; break;
	    case 9: strRet = strDD; break;
	    case 10: strRet = strYYYY; break;
	    case 11: strRet = strMMM + "-" + strDD + "-" + strYYYY; break;
	    default: break;
	    }
    	}
  }


  return strRet;
}

//--------------------------------------------------
//--------------------------------------------------
function val_fld_date(obj) {
  var intRet;
  var strD1 = "";
  var strD2 = "";
  if ((intRet = val_Date(obj.value)) >0) {
    strD1 = Format_Date(obj.value, 1);
    strD2 = Format_Date(obj.value, 2);
  }
  if (intRet != 1 && obj.value != "")  {
    setErrText(typeErr,"Error: " + intRet + ".Date must be in the format MM/DD/YYYY" );
    obj.focus();
  } else
    setErrText(typeErr,"");
}

function val_Year(strYear) {
	var intYear;
	if (isNaN(strYear)) return -1;
	else
	{
  	intYear = parseInt(strYear,10);
		if (intYear < 30) intYear += 2000;
   	else if (intYear >= 30 && intYear < 100) intYear += 1900;
   	if (intYear < 1000 || intYear > 9999) return -1;
   	else return intYear;
	}
}

function val_Month(strMonth,useMMM) {
   var intMonth;
   var isUse = false;
   var MONTHLIST="JAN|FEB|MAR|APR|MAY|JUN|JUL|AUG|SEP|OCT|NOV|DEC|";
   if (useMMM != null)
   	if (useMMM == true)isUse = true;

   if (isNaN(strMonth))
   {
   	intMonth= MONTHLIST.indexOf(strMonth.toUpperCase()+"|");
   	if (intMonth != -1)
   	{
   		if (isUse)
   		{
 				return MONTHLIST.substr(intMonth,3);
   		}
 			return (intMonth/4+1);
   	}
   	else
   		return -1;
   }
   else {
   	intMonth = parseInt(strMonth,10);
   	if (intMonth < 1 || intMonth > 12) return -1;
   	if (isUse)
   	{
   		return MONTHLIST.substr((intMonth-1)*4,3);
   	}
   	else
   		return intMonth;
   }
}

// val_Day
// return
//		0 if Year is invalid year
//		0 if Month is invalid month
//		-1 if Day is invalid day
//		inDay if Day is valid day
function val_Day(strDay, strMonth, strYear) {
   var intDay;
   var intMonth;
   var intYear;
   var intTmp;
   var isLeap = false;
   var MthDays = 31; // Total day in the month
   var ErrStr = "";

	if (isNaN(strDay)) return -1;

  // Find out if it is a leap year
  // if year is not valid, will assume it is not leap year
	if ( (intYear = val_Year(strYear)) < 0) return 0;
  else
  {
  	if ((strYear % 4) == 0) isLeap = true;
   	else isLeap = false;
	}

	// Find out how many days is in the month
	// if month is not valid, will assume 31 days in a month
	if ( (intMonth = val_Month(strMonth)) < 0) return 0;
	else
	{
  	if (intMonth == 2 && isLeap == true)  //leap year
   	 	MthDays = 29;
   	else if (intMonth ==2)
   		MthDays = 28;
   	else if ( ((intMonth <= 7 ? intMonth : intMonth - 7) % 2) == 0 ) // even months
   	  MthDays = 30;
   	else MthDays = 31;
  }

  // if strDay starts with a zero, remove first character from strDay
	if (strDay.substr(0,1) == "0") strDay = strDay.substr(1);

  // Parse string into integer
  intDay = parseInt(strDay,10);
  
  if(isNaN(intDay))
		return -1;

	// if Day is not a valid day, return -1, otherwise return the day
  if (intDay < 1 || intDay > MthDays) return -1;
  else return intDay;

}



// return -1 for invalid month
//	  -2 for invalid day
//	  -4 for invalid year
//	  -3 for invalid month and day
// 	  -5 for invalid year and month
//	  -6 for invalid year and day
//	  -7 for invalid year, day and month
//	  0 for invalid date format
// 	   1 for valid date w/ M or MM month format
//     2 for valid date w/ MMM month format

function val_Date(strIn) {
  var strDelimit = "[\/,-]";
//  var REMatch2 = /(\d\d)(\d\d)(\d\d\d\d)/;
//  var REMatch3 = /(\d\d)(\d\d)(\d\d)/;

  var MatchArray;
  var strMonth, strDay, strYear;
  var intMonth, intDay, intYear;
  var RetCode = 1;
  var intArrayLen;
  var i, j;
  var iFormat = 0;
  strOut = "";
  var tmpstr;

  // Test for the T-# format first. It is a special case since it is
  //   an intrepreted format
  //alert("strIn: " + strIn);
  strOut = strIn.toUpperCase();
  tmpstr = strOut.match(/\s*T/);
  if (tmpstr != null) // We have a T-#
  {
	 //alert("tmpstr: " + tmpstr);
	 strOut.replace(/\s/g,"");   // Remove all whitespace
	 //alert("strOut: " + strOut);
	 i = strOut.length;
	 if (j > 1)    // If not T
	 {
		if (strOut.charAt(1) != '-') // Error!
		   return -1 ;
		strOut = strOut.substr(2,j - 2);
		if (isNaN(strOut))
		   return -1;
	    return 99;
	 }
	 return 99;
  }
  // Check for L
	tmpstr = strOut.match(/\s*L/);
	if (tmpstr != null)
	{
	   strOut.replace(/\s/g,"");   // Remove all whitespace
	   i = strOut.length;
	   if (i > 1)    // Must be only L
		  return -1;
	   return 99;
    }
  strOut = "";


  // split the date up into Month, Day, and year
  i=0;
  while (MatchArray == null && i < REDateMatchArray.length)
  {
  	MatchArray = strIn.match(REDateMatchArray[i]);
  	if (MatchArray == null) i+=2;
  }

  if (MatchArray != null) {
   	intArrayLen = MatchArray.length;
   	iFormat = REDateMatchArray[i+1];
   	if (intArrayLen == 4)
   	{
   		if (iFormat != VAL_RE_MMD)
   		{
	    	strYear = MatchArray[3];
   			if (iFormat == VAL_RE_MMMD)
   			{
 	  			strMonth = MatchArray[1];
 			  	strDay = MatchArray[2];
	    	}
	    	else // iFormat == VAL_RE_DMMM
	    	{
 	  			strMonth = MatchArray[2];
 			  	strDay = MatchArray[1];
	    	}

   		  RetCode = 0;

  	 	  if ( (intYear = val_Year(strYear)) < 0)
	   	  {
   	  		RetCode += (intYear * 4);
				}
  	  	if ( (intMonth = val_Month(strMonth)) < 0)
  	  	{
   	  		RetCode += intMonth;
				}
   	  	if ( (intDay = val_Day(strDay,strMonth,strYear)) < 0)
   		  {
  	 	  	RetCode += (intDay * 2);
				}
   	  	if (RetCode == 0)
   		  {
  	 	  	RetCode = 2;
				}

   		}
   		else
   		{
 	  		strMonth = MatchArray[1];
 	    	strDay = MatchArray[2];
 	    	strYear = MatchArray[3];
   	  	RetCode = 0;

   	  	if ( (intYear = val_Year(strYear)) < 0)
   	  	{
   	  		RetCode += (intYear * 4);
				}
  	  	if ( (intMonth = val_Month(strMonth)) < 0)
  	  	{
   	  		RetCode += intMonth;
				}
   	  	if ( (intDay = val_Day(strDay,strMonth,strYear)) < 0)
   	  	{
   	  		RetCode += (intDay * 2);
				}
   	  	if (RetCode == 0)
   	  	{
   	  		RetCode = 1;
				}
			}
   	} else {
			RetCode = 0;
   	}


  } else {
  	RetCode = 0;
  }
  //setErrText(typeErr,"Month: " + intMonth + ", Day: " + intDay + ", Year: " + intYear);
  return RetCode;
}





//tek 01.15.01
//Validates the phone number is a valid phone number in either the format with 123-1234	or 123-123-1234
function ckPhone(obj)
{

  var indexofdash = obj.value.indexOf("-",0);
  var lastindex = obj.value.lastIndexOf("-",obj.value.length-1);
  var firstthree;
  var secondthree;
  var lastfour;


  //First check to ensure a valid number is entered
 //check to see if no dashes are entered and it is a fully numeric number
  if ((isNaN(obj.value)) && (indexofdash == -1))
  	{
  		alert("The phone number must be numeric");
  		obj.value = "";
  		obj.focus();
  	 	return;
  	}
//check to see if a 10 digit number is entered without dashes
  if ((indexofdash == -1) &&  (obj.value.length == 10))
  {
  	firstthree = obj.value.substring(0,3);
  	secondthree = obj.value.substring(3,6);
  	lastfour = obj.value.substring(6,10);

  }
//check to see if a 7 digit number is entered without dashes
  else if ((indexofdash == -1) && (obj.value.length == 7))
  {
  	secondthree = obj.value.substring(0,3);
  	lastfour = obj.value.substring(3,7);

  }
//returns if a 7 digit number with one dash in the 4th position is entered
  else if ((obj.value.length == 8) && (indexofdash == 3))
  {
  	secondthree = obj.value.substring(0,3);
  	lastfour = obj.value.substring(4,8);
  	if ((isNaN(secondthree)) || (isNaN(lastfour)))
  	{
  		alert("The phone number must be numeric");
  		obj.value = "";
  		obj.focus();
  		return;
  	}
	return;
  }
  //returns if a 10 digit number with a dash in the 4th position and a dash in the 8th position are entered
  else if ((obj.value.length == 12) && (indexofdash == 3) && (lastindex == 7))
  {
  	firstthree = obj.value.substring(0,3);
  	secondthree = obj.value.substring(4,7)
  	lastfour = obj.value.substring(8,12)
  	if ((isNaN(firstthree)) || (isNaN(secondthree)) || (isNaN(lastfour)))
  	{
  		alert("The phone number must be numeric");
  		obj.value = "";
  		obj.focus();
  		return;
  	}
  	return;
  }
  else if (obj.value.length == 0)
  {
  	return;
  }
  else
  {
  	alert("This is not a valid phone number");
  	obj.value = "";
   	obj.focus();
  	return;
  }
  if (firstthree != null)
  {
     obj.value = firstthree + "-" + secondthree + "-" + lastfour;
  }
  else
  {
     obj.value = secondthree + "-" + lastfour;
  }

}

//tek 01.15.01
//Validates the zip code is a valid number in the format 12345
function ckZip(obj)
{
//check to see if 5 characters are entered
  if((obj.value.length < 5) && (obj.value.length != 0))
  {
  	alert("You must enter at least 5 digits of the zip code");
  	obj.value = "";
  	obj.focus();
  	return;
  }



  //Then check to ensure a valid number is entered
  if (isNaN(obj.value))
  	{
  		alert("The zip code must be numeric");
  		obj.value = "";
  		obj.focus();
  	 	return;
  	}
}
//jas 06.07.02
// function to validate email address
function ckEmail(obj)
{
  if(obj.value.length == 0)
  {
  	return;
  }
  for(i=0; i< obj.value.length; i++) {
  	if (obj.value.substring(i,i+1) == "@")
  	  break;
  }
  if ( i >= (obj.value.length - 1))
  {
  	alert('The email address must contain @ to be valid');
  	obj.value = "";
  	obj.focus();
  	return;
  }
   for (j = i; j< obj.value.length; j++) {
  	if (obj.value.substring(j,j+1) == ".")
  	break;
  }
  if ( j >= (obj.value.length -1) )
  {
  	alert('Missing .com or .net of address');
  	obj.value = ""
  	obj.focus();
  	return;
  }
}
  
//--------------------------------------------------
//--------------------------------------------------
//--------------------------------------------------
//--------------------------------------------------
//Validates the social is entered without -'s
function FixSocial(obj)
{

  var indexofdash = obj.value.indexOf("-",0);
  var strssn;
  var i;

if (indexofdash < 0 )
	return;
//strssn = obj.value;

//obj.value = strssn.replace("-", "");
for (i = 0; i < obj.value.length; i++)
{
	strssn = obj.value;
	indexofdash = strssn.indexOf("-",0);
	if (indexofdash < 0)
	{
		break;
	}
	obj.value = strssn.replace("-", "");
}

//alert (obj.value);
  //First check to ensure a valid number is entered
 //check to see if no dashes are entered and it is a fully numeric number
  if (isNaN(obj.value))
  	{
  		alert("The social security number must be numeric.");
  		obj.value = "";
  	 	return;
  	}
  return;
}

/*
 * Strip/replace specified characters out of fields before insert/update.
 * The account-wide values are stored in stringFilter_search and stringFilter_replace in account.js
 * If other characters need to be handled they can be passed in.
 *	If you need to truncate data, set the max="xxx" (where xxx = character limit) parameter in the html
 *	The call should look like stringFilter('S', 'X,Y,Z', 'x,y,z', true, this)  for single field validation
 *	The call should look like stringFilter('S', 'X,Y,Z', 'x,y,z')  for full form validation
 *
 * @param  string formName Form that needs to be validated. “P” for popup window,
 *                         “N” for non-framed page; otherwise sch_input will be used.
 * @param  array  checkValue
 * @param  array  replaceValue
 * @param  boolean singleFieldCheck  true for single field validation indicated by objName argument
 *                                                          otherwise full form validation
 * @param  object objName  If !singleFieldCheck, this form field will be used.
 * @author Johnny Cunningham
*/
function stringFilterX(formName,checkValue,replaceValue,singleFieldCheck,objName) {
var i, ct;
var re  = new RegExp();
var tmpCheck = new Array();
var tmpReplace= new Array();

//create the temp arrays to work with for the check/replace
if (stringFilter_search && stringFilter_replace) {
    for (i = 0; i < stringFilter_search.length; i++) {
	tmpCheck.push(stringFilter_search[i]);
	tmpReplace.push(stringFilter_replace[i]);
    }
}	

//add to the two temp arrays from the passed in values
if (checkValue && replaceValue) {
    var cArray = checkValue.split(",");
    var rArray = replaceValue.split(",");
    for (i = 0; i < cArray.length; i++) {
	tmpCheck.push(cArray[i]);
	tmpReplace.push(rArray[i]);
    }
}

if (tmpCheck.length == 0 || tmpReplace.length == 0) {
    return;
}    
	
//Check variable to determine if we are doing a single field (true) or full form validation (false)
if (singleFieldCheck == true) {
    //check that a field name was passed into the function
    if (!objName) {
	errMsg  = "There was a validation error. \n";
	errMsg += "Please contact MarketLinx Customer Support \n";
	errMsg += "with the following information... \n \n";
	errMsg += "Function: StringFilter \n";
	errMsg += "Level: ObjName for Single Field validation \n \n";
	errMsg += "This will assist us in getting this corrected as soon as possible.";
	alert(errMsg);
	return;
    }	
    //replace no value with '-' for textareas (only for single field validation)
    if (objName.type == "textarea" && objName.value.length == 0) {
	objName.value = "-";
       	return;
    }
    for (i = 0; i < tmpCheck.length; i++) {
	//build the regular expression value to use in the replace function below
	re.compile(tmpCheck[i],"g");
	objName.value = objName.value.replace(re,tmpReplace[i]);
    }
} else { // Full form validation
    //switch case to set up the form name of the one to be cleaned, based on passed in parameter 1
    switch(formName) {
        case 'P':   //pop-up window
	    if (saveWin.document.forms[0])	
   		frm = saveWin.document.forms[0];
   	    break;
  	case 'N':   //non-framed page
  	    if (window.top.frames['middle'].document.forms[0])
   		frm = window.top.frames['middle'].document.forms[0];
   	    break;
  	default:
   	    if (sch_input.document.forms[0])
   		frm = sch_input.document.forms[0];
    }
    if (!frm) {
	errMsg  = "There was a validation error. \n";
	errMsg += "Please contact MarketLinx Customer Support \n";
	errMsg += "with the following information... \n \n";
	errMsg += "Function: StringFilter \n";
	errMsg += "Level: Form Name Invalid \n \n";
	errMsg += "This will assist us in getting this corrected as soon as possible.";
	alert(errMsg);
	return;
    }	
    // inArray prototype
    Array.prototype.inArray = function (value) {
        for (i=0; i < this.length; i++) {
	    if (this[i] == value) { 
	        return true;
	    }        
        }
        return false;
    }	   			
    //Loop through the entire form
    for (ct = 0; ct < frm.length; ct++) {
        // Look for specific tag types to clean
	if (frm.elements[ct].type == "text" || frm.elements[ct].type == "textarea") {
	    //Check for any fields that should be excluded from the validation
	    var endChar = frm.elements[ct].name.length - 4;
	    if (!stringFilter_bypass.inArray(frm.elements[ct].name.substr(0, (frm.elements[ct].name.length - 4)).toUpperCase())) {  
		if (!stringFilter_bypass.inArray(frm.elements[ct].name.toUpperCase())) {
                    for (i = 0; i < tmpCheck.length; i++) {
          		//build the regular expression value to use in the replace function below
          		re.compile(tmpCheck[i],"g");
          		frm.elements[ct].value = frm.elements[ct].value.replace(re,tmpReplace[i]);
         	    }
             	    //After looping through and replacing the arrayed values, strip out any tabs and html tags
        	    removeTagX(frm[ct]);
               	    //If the max parameter is set, check it and truncate the data if necessary
               	    if (frm.elements[ct].max) {
                	maxLimit = parseInt(frm.elements[ct].max);
                	if (typeof(maxLimit) == 'number') {
                            if (frm.elements[ct].value.length > maxLimit) {
               		        frm.elements[ct].value = frm.elements[ct].value.substring(0, maxLimit);
                            }           
                        }
               	    }
                }                       	    
    	    }
   	}  //End of check for element type
    }  //End of for loop for looping through the entire form
}  //End of else for full form validation
}

/*
 * function used to clear html tags and tabs from data
 *
 * @param  ev string form field
 * @author Unknown
 */
function removeTagX(ev) {
var objvalue = ev.value;
//2008-29-02 Chauncey Wilson TRK141411
if (window.top.frames['middle'].frames['sch_input']) {
    if (window.top.frames['middle'].frames['sch_input'].document.MntInputForm) {
	var reg = new RegExp('<marquee[^>]*>', 'ig');
    } else {	
	var reg = new RegExp('<[^>]*>', 'ig');
    }	
    objvalue = objvalue.replace(reg, "");
    ev.value = objvalue;
}
}
