// **************************************************************************************
// YTCommon.js - Holds commonly used client-side functions for the YearTrack system.
//
// Author : Carl Abbott (TekSystems)
// **************************************************************************************

// **************************************************************************************
//  ytDateComp - Compares the two dates passed with the criterion passed.
//
//  Returns: true-matches criteron, false = doesn't
// **************************************************************************************
function ytDateComp(sDesc, fldField, sDate2, sComp)
{
  var blnReturn;
  var sVerbiage;

  // Compare the dates based on sComp 
  switch (sComp.toUpperCase())
  {
    case ">":
      blnReturn = Date.parse(fldField.value) > Date.parse(sDate2);
      sVerbiage = "after";
    break;
    case ">=":
      blnReturn = Date.parse(fldField.value) >= Date.parse(sDate2);
      sVerbiage = "on or after";
    break;
    case "<":
      blnReturn = Date.parse(fldField.value) < Date.parse(sDate2);
      sVerbiage = "before";
    break;
    case "<=":
      blnReturn = Date.parse(fldField.value) <= Date.parse(sDate2);
      sVerbiage = "on or before";
    break;
    case "=":
      blnReturn = Date.parse(fldField.value) == Date.parse(sDate2);
      sVerbiage = "on";
    break;
  }

  // Check for displaying an error message.
  if (!blnReturn)
  {
    window.alert("Field '" + sDesc + "' must be " + sVerbiage + " " + sDate2);
    if (!fldField.disabled) {fldField.focus();}
  }
   
  return blnReturn;
}

// **************************************************************************************
//  ytDateField - Checks for a field being a valid date.
//
//  Returns: true-valid date, false-invalid date
// **************************************************************************************
function ytDateField(sDesc, fldField)
{
  var bReturn = false;
  var dtCheck = new Date;
  var sValue = fldField.value;

  // Check for a valid date entered.
  if (ytParseDate(dtCheck, fldField.value))
    bReturn = true;
  else
  {
    window.alert("Field '" + sDesc + "' is not a valid date!");
    if (!fldField.disabled) {fldField.focus();}
  } 

  return bReturn;
}

// **************************************************************************************
//  ytDateFormat - Formats the field value to the "standard" format of M/D/YYYY
// **************************************************************************************
function ytDateFormat(fldField)
{
  var dtNew = new Date();

  if (ytParseDate(dtNew, fldField.value))
    fldField.value = (dtNew.getMonth() + 1) + "/" + dtNew.getDate() + "/" + 
                     (dtNew.getYear() < 1000 ? dtNew.getYear() + 1900 : dtNew.getYear());
  else
    fldField.value = "{invalid date}";
}

// **************************************************************************************
//  ytParseDate - Converts a string to a date.
//    Valid Formats: MM.DD.YY(YY), MM-DD-YY(YY), MM/DD/YY(YY)
//  returns: true=valid date, false=invalid date
// **************************************************************************************
function ytParseDate(dtNew, sValue)
{
  var bValid = true;
  
  var iField = 0;
  var iTemp;

  var sTemp = "";
  var sNewValue = sValue + "";
  dtNew.setDate(1); //Bug Fix: current day of 29,30,and 31 caused
					// problems when setting month field first

  // Parse out the year.
  for (var iLoop = 0; iLoop < sNewValue.length; iLoop ++)
  {
    if (sNewValue.charAt(iLoop) == '.' ||     
        sNewValue.charAt(iLoop) == '-' ||
        sNewValue.charAt(iLoop) == '/' )
    {
      switch (iField)
      {
        case 0: // Month
          iTemp = parseInt(sTemp, 10);
          if (isNaN(iTemp))
            bValid = false;
          else
          {
            if (iTemp < 1 || iTemp > 12)
              bValid = false;
            else
              dtNew.setMonth(iTemp - 1);
          }
        break;

        case 1: // Date
          iTemp = parseInt(sTemp, 10);
          if (isNaN(iTemp))
            bValid = false;
          else
          {
            if (iTemp < 1 || iTemp > 31)
              bValid = false;
            else
              dtNew.setDate(iTemp);
          }
        break;

        case 2: // Year
          // This scenario means an improper date.
          bValid = false;
        break;
      }

      // Blank out the check string.
      sTemp = "";

      // Bump the field counter.
      iField ++;
    }
    else
    { 
      // Add the character on to the string.
      sTemp += sNewValue.charAt(iLoop);
    }

    // Check for an invalid date.
    if (!bValid)
      break;
  }

  // Check for converting the year.
  if (iField == 2)
  {
    iTemp = parseInt(sTemp, 10);
    if (isNaN(iTemp))
      bValid = false;
    else
    {
      if (iTemp < 1)
        bValid = false;
      else
      {
        if (iTemp < 1000)
          iTemp += 2000;
        dtNew.setYear(iTemp);
      }
    }
  }
  else
    bValid = false;

  return bValid;
}

// **************************************************************************************
//  ytEmailField - Basic validation that field is in an email format.
//
//  Returns: true-field is valid format, false-invalid format
// **************************************************************************************
function ytEmailField(sDesc, fldField)
{
  var Check = /.+\@.+\..+/;
  //var Check = /^[\w_-]+(\.[\w_-]+)*@[\w_-]+(\.[\w_-]+)*\.[a-z]{2,3}$/;
  var sValue = fldField.value;

  //var bReturn = Check.exec(sValue);
  var bReturn = validateEmail(sValue);
  if (bReturn && sValue.indexOf(";") > 0) bReturn = false; //prevent multiple email addresses

  // Check for needing to display a warning message.
  if (!bReturn)
  {
    window.alert("Field '" + sDesc + "' is not a valid e-mail address!");
    if (!fldField.disabled) {fldField.focus();}
  } 

  return bReturn;
}

function validateEmail(srcstr)
{  
  if (srcstr.indexOf("@@") >= 0) //check for && (test@@test.com = invalid)
    return false;
  else{
    var filter = "^[\\w-_\.]*[\\w-_\.]\@[\\w]\.+[\\w]+[\\w]$";
    var regex = new RegExp(filter);
    return regex.test(srcstr);  
  }
}

// **************************************************************************************
//  ytEmptyField - Checks for a field not having any value.
//
//  Returns: true-empty, false-not empty
// **************************************************************************************
function ytEmptyField(fldField)
{
  var bReturn = false;
  var sValue = fldField.value;

  // Check for a null value.
  if (sValue == null)
    bReturn = true;
  else
  {
    for (var nLoop = 0; nLoop < sValue.length; nLoop ++)
      if (sValue.charAt(nLoop) != ' ')
        break;
    if (nLoop == sValue.length)
      bReturn = true;
  }

  return bReturn;
}

// **************************************************************************************
//  ytFormatPercent - Formats a percentage field
//
//  Returns: formatted string
// **************************************************************************************
function ytFormatPercentage(dblValue)
{
  var sReturn = dblValue + "";

  // Check for whole number.
  if (sReturn.search(/\./) == -1)
    sReturn += ".00";
  else
  {
    sReturn += "00";
    sReturn = sReturn.substr(0, sReturn.length - 1);
  }

  return sReturn;
}

// **************************************************************************************
//  ytIntegerField - Validates that the field is an integer.
//
//  Returns: true-valid, false-invalid
// **************************************************************************************
function ytIntegerField(sDesc, fldField)
{
  var bReturn = false;
  var sValue = fldField.value;

  if (ytIntegerField.arguments.length == 3) { //override message text
  	 // Check for the field being numeric.
    if (ytNumericField(sDesc, fldField, ytIntegerField.arguments[2])) {
  	   // Make sure there are no decimal places.
      if (sValue.search(/\./) == -1)
        bReturn = true;

      // Check for needing to display a warning message.
      if (!bReturn) {
    	  window.alert(ytIntegerField.arguments[2] + sDesc); 
    	  if (!fldField.disabled) {fldField.focus();}
    	}
    } 
  } else {
     // Check for the field being numeric.
	  if (ytNumericField(sDesc, fldField))	{
       // Make sure there are no decimal places.
       if (sValue.search(/\./) == -1)
         bReturn = true;

       // Check for needing to display a warning message.
       if (!bReturn) {
    	   window.alert("Field '" + sDesc + "' is not a valid integer!");
         if (!fldField.disabled) {fldField.focus();}
       }
    } 
  }

  return bReturn;
}
 
// **************************************************************************************
//  ytNumericField - Validates that the field is numeric.
//
//  Returns: true-valid, false-invalid
// **************************************************************************************
function ytNumericField(sDesc, fldField)
{
  var bReturn;
  var nCheck = fldField.value - 0;

  // Check for the field being numeric.
  bReturn = !ytEmptyField(fldField);
  if (bReturn)
    bReturn = !isNaN(nCheck);

  // Check for needing to display a warning message.
  if (!bReturn)
  {
    if (ytNumericField.arguments.length == 3) {
    	window.alert(ytNumericField.arguments[2] + " " + sDesc)
    } else {
    	window.alert("Field '" + sDesc + "' is not a valid number!");
    }
    if (!fldField.disabled) {fldField.focus();}
  } 

  return bReturn;
}

// **************************************************************************************
//  ytPercentField - Validates field as a percentage.
//
//  Returns: true-valid, false-invalid
// **************************************************************************************
function ytPercentField(sDesc, fldField)
{
  var bReturn;
  var nCheck;
  var sValue;

  // Strip out any % in the field.
  sValue = fldField.value.replace(/\%/g, "");
  fldField.value = sValue;
  nCheck = sValue - 0;

  // Check for the field being numeric.
  bReturn = ytNumericField(sDesc, fldField);
  if (bReturn)
  {
    // Check for a number with an integer portion.
    if (nCheck >= 1)
    {
      // Check for > 99.
      if (nCheck > 99)
        bReturn = false;

      // Check for 2 decimal places max.
      if ((sValue.length - sValue.search(/\./) - 1 ) > 2)
        bReturn = false;
    }
    else
    {
      // Check for 2 decimal places max.
      if ((sValue.length - sValue.search(/\./) - 1 ) > 2)
        bReturn = false;
    }
  
    // Check for needing to display a warning message.
    if (!bReturn)
    {
      window.alert("Field '" + sDesc + "' is not a valid percentage! (example: 6.25 = 6.25%)");
      if (!fldField.disabled) {fldField.focus();}
    } 
  }

  return bReturn;
}

// **************************************************************************************
//  ytRadioField - Validates that a radio button has been selected.
//
//  Returns: true-button selected, false-no button selected
// **************************************************************************************
function ytRadioField(radCheck)
{
  var bReturn = false;

  // Loop through all radio buttons to see if any are checked.
  for (var nLoop = 0; nLoop < radCheck.length; nLoop ++)
  {
    if (radCheck[nLoop].checked) 
    {
      bReturn = true;
      break;
    }
  }

  return bReturn;
}

// **************************************************************************************
//  ytRequiredField - Ensures that the specified field has a value.
//
//  Returns: true-field has non-blank value, false-null or blank value
// **************************************************************************************
function ytRequiredField(sDesc, fldField)
{/* optional param 3 = override message
 	  optional param 4 = override mode 
 	  					1: default if param 3 exists; replace standard message with override message and append sDesc
 							2: replace standard message, do not append sDesc
 							3: append override message to standard message
 	*/
  var bReturn = true;
  var sValue = fldField.value;

  // Check for field not being empty.
  bReturn = !ytEmptyField(fldField);

  // Check for needing to display a warning message.
  if (!bReturn)
  {
  	var sMode = 0 * 1;
  	var sMsg = "Field '" + sDesc + "' is a required field!";
  	switch (arguments.length) {
  		case 3: sMode=1; break;
  		case 4: sMode=arguments[3]; break;
  	}
  	switch (sMode) {
  		case 1: sMsg = arguments[2] + sDesc; break;
  		case 2:	sMsg = arguments[2]; break;
  		case 3:	sMsg += " " + arguments[2];	break;
		}  			
  	window.alert(sMsg);
	if (!fldField.disabled) {fldField.focus();}
  } 

  return bReturn;
}

// **************************************************************************************
//  ytSelectField - Ensures that the specified field has a value.
//
//  Returns: true-field has non-blank value, false-null or blank value
// **************************************************************************************
function ytSelectField(sDesc, fldField)
{
  var bReturn = true;
  var sValue = fldField[fldField.selectedIndex].value;

  // Check for field not being empty.
  if (sValue.replace(' ','') == '') bReturn = false;

  // Check for needing to display a warning message.
  if (!bReturn)
  {
    window.alert("Field '" + sDesc + "' is a required field!");
    if (!fldField.disabled) {fldField.focus();}
  } 

  return bReturn;
}

// **************************************************************************************
//  ytOIDPassword - Validates password for OID.  Passwords must be at least 6 characters
//     long and contain at least 1 number.
//
//  Returns: true-password, false-null or blank value
// **************************************************************************************
function ytOIDPassword(sDesc, fldField) 
{
  var bReturn = false;
  var sValue = fldField.value;
  
  if (sValue.length >= 6) {
    for (var i=0; i<sValue.length; i++) {
      if (!isNaN(parseInt(sValue.substr(i,1)))) {
        bReturn = true;
        break;
      }
    }
  }
    
  // check for needing to display a warning message.
  if (!bReturn) 
  {
    alert('All passwords must be 6 characters long and contain a number. Please enter a new password.');
    if (!fldField.disabled) {fldField.focus();}
  }
  
  return bReturn;
}

// **************************************************************************************
//  ytLoginField - Validates login id per YBA login requirements. 
//  Returns: true-field is valid, false-field is invalid
// **************************************************************************************
function ytLoginField(sDesc, fldField)
{
  var bReturn = false;
  var sValue = fldField.value;

  var reTest = /^[A-Z0-9\.\@\#\-\_]+$/i;
  bReturn = reTest.test(sValue);
  
  if (!bReturn)
  {
	alert('The login id you entered is invalid.  Please limit the login id to letters, numbers, period, @, #, -, and _.');
	if (!fldField.disabled) {fldField.focus();}
  }
  
  return bReturn;
}

// **************************************************************************************
//  ytPhoneField - Validates and re-formats phone number fields
//  Returns: true-phone number is valid, false-phone number is invalid
// **************************************************************************************
function ytPhoneField(sDesc, fldField)
{
  var bReturn = false;
  var sValue = fldField.value;
  
  // strip non-numeric characters
  sValue = sValue.replace(/[^\d]/g, "");
  if (sValue.length != 10) 
  {
    bReturn = false;
  }
  else
  {
    //re-format valid phone number
    fldField.value = sValue.replace(/(\d{3})(\d{3})(\d{4})/g, "($1) $2-$3");
    bReturn = true;
  }
  
  if (!bReturn)
  {
    alert("Field " + sDesc + " is not a valid phone number!");
    if (!fldField.disabled) {fldField.focus();}
  }
    
  return bReturn;
}

// ********************************************************************************
//  ytTimeFIeld - Validatse a field as time of day
//  Returns: true-the time is valid, false the time is invalid
// ********************************************************************************
function ytTimeField(sDesc, fldField)
{
  var bReturn = false;
  var sValue = fldField.value;
  
  // strip white space characters
  sValue = sValue.replace(/\s/g,"");
  
  //validate time
  if ((/([0-9]{1,2})\:([0-9]{1,2})/).test(sValue)) 
    bReturn = true;
  
  if (!bReturn)
  {
    alert("Field " + sDesc + " is not a valid time of day.");
    if (!fldField.disabled) {fldField.focus();}
  }
  
  return bReturn;
}