// ***************************************************************************
//
// File Name   :  js_util.js
// Description :  Common functions used with forms
//
// Function Name       Description
// ==================  =======================================================
// getFieldByName      Get the field object/element by its name
//    (myField, 
//     exactMatch)
//
// setFocusToField     Set focus to the field
//    (myField)
// 
// clearField          Reset the field value to empty
//    (myField)
// 
// getValueFromCombo   Get the value of the selected item of a combo box
//    (element)
//
// getValueFromCheck   Get the value of the a check box
//    (element)
//
// getValueFromRadio   Get the value of the checked item of a radio button
//    (element)
//
// requireValues       Validate input field
//    (form, 
//     requiredText, 
//     len)
// 
// requireSelects      Takes a form and an array of element names; verifies 
//    (form,           that each has an option selected (other than the 
//     requiredSelect) first; assumes that the first option in each select 
//                     menu contains instructions)
// 
// requireRadios       Takes a form and an array of element names; verifies 
//    (form,           that each has a value checked
//     requiredRadio)
// 
// isInteger           Takes a value, checks if it's an integer, and returns 
//    (value)          true or false
//
// isFloat             Takes a value, checks if it's a float number, and returns 
//    (value)          true or false
//
// checkRange          Takes a value, checks if it's between a range, and returns 
//    (value,          true or false
//     minValue,
//     maxValue)
//
// dateBetween         Takes two date values, calculate how many days between the two dates
//    (fromDate,       inclusively, and turns number of days
//     toDate)
//
// getTodayString      Take a date seperator, return a string of today in yyyy-mm-dd  
//    (seperator)      where - is the seperator
//
// checkDateText       Takes a form and an array of element names; verifies
//    (form,           that each has a date format in yyyy/mm/dd
//     dateText)
// 
// checkDateFormat     Verifies that the value of date has yyyy/mm/dd format
//    (element, 
//     idate)
// 
// ***************************************************************************

function getFieldByName(myField, exactMatch) 
{
   if(!myField) 
      return null;

   found = false;
   formElement = null;
   for(var j=0; (j<document.forms.length) && !found; j++) 
   {
      var myForm = document.forms[j];
      for (var i=0; (i < myForm.elements.length) && !found; i++) 
      {
         formElement = myForm.elements[i];
         if ((myField.indexOf(formElement.name, 0) > -1) ||
                  (formElement.name.indexOf(myField, 0) > -1)) 
         {
            found = true;
         }
      }
   }
   return formElement;
}

function setFocusToField(myField) 
{
   theElement = getFieldByName(myField);
   theElement.focus();
}

function clearField(myField) 
{
   theElement = getFieldByName(myField);
   theElement.value='';
}

// Get the value of the selected item of a combo box
function getValueFromCombo(element)
{
   var val = "";
   for(var i=0; i<element.options.length; i++)
      if(element.options[i].selected)
         val = element.options[i].value;

   return val;
}
 
// Get the value of the selected item of a combo box
function getIndexFromCombo(element)
{
   for(var i=0; i<element.options.length; i++)
      if(element.options[i].selected)
         return i;

   return -1;
}
 
// Get the value of the a check box
function getValueFromCheck(element)
{
   var val = "N";
   if(element.checked)
      val = element.value;

   return val;
}

// Get the value of the checked item of a radio button
function getValueFromRadio(element)
{
   var val = "";
   for(var i=0; i<element.length; i++)
      if(element[i].checked)
         val = element[i].value;

   return val;
}

// Takes a form and an array of element names; verifies that each has a value
function requireValues(form, requiredText, len)
{
   // alert("Call requireValues()");

   for(var i = 0; i < requiredText.length; i++)
   {
      element = requiredText[i];

      if(form[element].value == "" || (form[element].value).length < len)
      {
         if(len == 0)
           alert("Please enter value for " + element + ".");
         else
           alert("Please enter at least " + len + 
                 " characters value for " + element + ".");

         return false;
      }
   }
   return true;
}

// Takes a form and an array of element names; verifies that each has a value
function requireValuesMsg(form, requiredText, msgText, len)
{
   // alert("Call requireValuesMsg()");

   for(var i = 0; i < requiredText.length; i++)
   {
      element = requiredText[i];
      msg = msgText[i];

      if(form[element].value == "" || (form[element].value).length < len)
      {
         alert(msg);
         return false;
      }
   }
   return true;
}

// Takes a form and an array of element names; verifies that each has an
// option selected (other than the first; assumes that the first option in
// each select menu contains instructions)
function requireSelects(form, requiredSelect) 
{
   for(var i = 0; i < requiredSelect.length; i++) 
   {
      element = requiredSelect[i];
      if(form[element].selectedIndex <= 0) 
      {
         alert( "Please select a value for " + element + ".");
         return false;
      }
   }
   return true;
}


// Takes a form and an array of element names; verifies that each has a
// value checked
function requireRadios(form, requiredRadio) 
{
   for(var i = 0; i < requiredRadio.length; i++) 
   {
      element = requiredRadio[i];
      isChecked = false;
      for(j = 0; j < form[element].length; j++) 
      {
         if(form[element][j].checked) 
         {
            isChecked = true;
         }
      }
      if(! isChecked) 
      {
         alert( "Please choose a/an " + form[element][0].name + ".");
         return false;
      }
   }
   return true;
}

// Takes a value, checks if it's within a range
function checkRange(value, minVal, maxVal) 
{
   if(!isFloat(value))
      return false;
   if(value < minVal || value > maxVal)
      return false 
   return true;
}

// Take two dates (yyyy-mm-dd), calculate the no. of days between the two dates inclusively
function dateBetween(fromDate, toDate)
{
  var newDateFrom = fromDate.substr(0,4) + "/" + fromDate.substr(5,2) + "/" + 
                    fromDate.substr(8,2);
  var newDateTo = toDate.substr(0,4) + "/" + toDate.substr(5,2) + "/" + 
                  toDate.substr(8,2);
  var fromDay = new Date(newDateFrom);
  var toDay = new Date(newDateTo);

  // Date.valueOf() returns value in milliseconds
  var noOfDays = 0;
  noOfDays = (toDay.valueOf() - fromDay.valueOf()) / (1000 * 60 * 60 * 24);  
  noOfDays = noOfDays + 1;
  return noOfDays;
}

// Take a date seperator, return a string of today in yyyy-mm-dd where - is the seperator
function getTodayString(seperator)
{
  var toDay = new Date();
  var yyyy = toDay.getYear();
  var mm = toDay.getMonth() + 1;
  var dd = toDay.getDate();

  if(mm < 10)
    mm = "0" + mm;
  if(dd < 10)
    dd = "0" + dd;

  var sToDay = yyyy + seperator + mm + seperator + dd;
  return sToDay;  
}

// Takes a value, checks if it's an integer, and returns true or false
function isInteger(value) 
{
   return (value == parseInt(value));
}

// Takes a value, checks if it's a float number, and returns true or false
function isFloat(value) 
{
   return (value == parseFloat(value));
}

function checkDateText(form, dateText) 
{ 
   for(var i = 0; i < dateText.length; i++)
   {
      element = dateText[i];
      dt = form[element].value;
      // alert("Call function checkDateText: " + dt);

      if(! checkDateFormat(element, dt))
      {
         return false;
      }
   }
   return true;
}

// Verifies that the value of date has yyyy/mm/dd format
function checkDateFormat(element, idate) 
{
   var funct = "(checkDateFormat) ";
   // Date Format in yyyy/mm/dd
   // alert(funct + "element: " + element);
   // alert(funct + "idate: " + idate);

   if(idate.length != 10) 
   {
      alert("Invalid length for " + element + 
            "! Please input date in yyyy/mm/dd format.");
      return false;
   }
   
   if(idate.substr(4, 1) != "/" || idate.substr(7, 1) != "/") 
   {
      alert("Invalid separator for " + element + 
            "! Please input date in yyyy/mm/dd format.");
      return false;
   }
   
   var syyyy = idate.substr(0, 4);
   var smm = idate.substr(5, 2);
   var sdd = idate.substr(8, 2);

   if(smm.substr(0,1) == "0")
   {
      smm = smm.substr(1,1);
   }

   if(sdd.substr(0,1) == "0")
   {
      sdd = sdd.substr(1,1);
   }

   if(! isInteger(syyyy)) 
   {
      alert("Invalid year for " + element + "! Year must be number.");
      return false;
   }
   
   if(! isInteger(smm)) 
   {
      alert("Invalid month for " + element + "! Month must be number.");
      return false;
   }
   
   if(! isInteger(sdd)) 
   {
      alert("Invalid day for " + element + "! Day must be number.");
      return false;
   }
   
   var yyyy = parseInt(syyyy);
   var mm = parseInt(smm);
   var dd = parseInt(sdd);
   
   // Check month
   if(mm < 1 || mm > 12) 
   {
      alert("Invalid month for " + element + 
            "! Month muse be between 1 and 12.");
      return false;
   }
      
   // Check day
   if(mm == 4 || mm == 6 || mm == 9 || mm == 11)
   { 
      if(dd < 1 || dd > 30)
      {
         alert("Invalid day for " + element + 
               "! Day muse be between 1 and 30.");
         return false;
      }
   }
   else if(mm == 2)
   { 
      if((yyyy % 4) == 0)
      {
         if(dd < 1 || dd > 29) 
         {
            alert("Invalid day for " + element + 
                  "! Day muse be between 1 and 29.");
            return false;
         }
      }
      else
      {
         if(dd < 1 || dd > 28) 
         {
            alert("Invalid day for " + element + 
                  "! Day muse be between 1 and 28.");
            return false;
         }
      }
   }
   else 
   { 
      if(dd < 1 || dd > 31) 
      {
         alert("Invalid day for " + element + 
               "! Day muse be between 1 and 31.");
         return false;
      }
   }
   return true;
}

//Check Phone digit to be 8 

 function checkPhoneDigit(form,pDigit){
for (var i=0; i < pDigit.length; i++){
     element = pDigit[i];
	 
	if (isNaN(form[element].value) || (form[element].value).length != 8){
	  alert("Your "+ element + " is invalid!");
	  return false;
	 }
	}
  return true;
}
