// This function is called on the onload event being fired for every page
function initialisePage()
{
   try
   {
      if(START_FIELD!="")
         setFocus(START_FIELD);
   }
   catch(e)
   {
      // Ignore error
   }
}

// This function places the focus on the supplied object
function setFocus(fieldid)
{
   document.getElementById(fieldid).focus();
}

// This function is called by buttons on the forms
// any validation is applied and the form is submitted.
function submitForm(formid, actionurl, validate)
{
   //_form = document.all(formid);
   if(validate)
   {
      if(validateForm(formid))
      {
         if(actionurl != "")
         {
            document.forms[formid].action = actionurl;
            //_form.action = actionurl;
         }
         document.forms[formid].submit()
         //_form.submit();
      }
   }
   else
   {
      //_form.submit();
      document.forms[formid].submit();
   }
}

// This function returns true/false depending on whether the data entry
// items have been populated correctly.
function validateForm(formid)
{
   //_form = document.all(formid);
   _message = "";
   _length = document.forms[formid].elements.length;
   _valid = true;
   _object = null;
   if(clearFailedValidation())
   {
      for(i=0;i<_length & _valid;i++)
      {
         //_object = _form.all(i);
         _object = document.forms[formid].elements[i];
         try
         {

            _value = _object.name.substr(0,4);
            //remove prefix from the name
            _name = _object.name.substr(4);
            //structure the name tag
            _name = _name.replace('_', ' ');
            //retreive prefix of name property from an HTML input tag and check for
            //the appropriate validation function
            // validation prefix's

            // first three characters define the field type,
            // the fourth character states if the field is mandatory or optional
            // _  - optional
            // m  - mandatory

            //prefix's

            // txtm  - mandatory text field
            // numm  - mandatory number box field
            // dat_  - date optional field
            // datm  - date mandatory field
            // com_  - combo box optional
            // pas_  - optional password, checks that 2 entered password are the same
            // pasm  - mandatory password
            // fil_  - optional file upload field
            // filg  - mandatory gedcom file upload field
            // rad_  - radio prefix
            // eml_  - email optional field
            // emlm  - email mandatory field
            // emlc  - email confirmation
            // emlo  - email confirmation optional

            switch(_value.toLowerCase())
            {
               case "txtm":
               {
                  _valid = validateTextbox(_object);
                  _message = "You must enter a " + _name;
                  break;
               }
               case "numm":
               {
                  _valid = validateNumberbox(_object);
                  _message = "You must enter a " + _name;
                  break;
               }
               case "datm":
               {
                  _valid = validateDatebox(_object, true);
                  _message = "You must enter a valid date (dd/mm/yyyy) ";
                  break;
               }
               case "dat_":
               {
                  _valid = validateDatebox(_object, false);
                  _message = "You must enter a valid date (dd/mm/yyyy) ";
                  break;
               }
               case "com_":
               {
                  _valid = validateCombobox(_object, false);
                  _message = "You must select a " + _name;
                  break;
               }
               case "comm":
               {
                  _valid = validateCombobox(_object, true);
                  _message = "You must select a " + _name;
                  break;
               }
               case "pasm":
               {
                  _valid = validatePassword(_object, true);
                  _message = "The password is not valid or do not match.";
                  break;
               }
               case "pas_":
               {
                  _valid = validatePassword(_object, false);
                  _message = "The password is not valid or do not match.";
                  break;
               }
               case "rad_":
               {
                  _valid = validateRadio(_object, _form);
                  _message = "The radio button is not correct";
                  break;
               }
               case "filg":
               {
                  filetype = new Array(1);
                  filetype = new Array("ged");
                  _valid =  validatefile(_object, true, filetype);
                  _message = "You must upload a gedcom file to upload a family tree.";
                  break;
               }
               case "fil_":
               {
                  filetype = new array("");
                  _valid =  validatefile(_object, false, filetype);
                  break;
               }
               case "emlm":
               {
                  _valid = validateEmail(_object, true);
                  _message = "You must enter a valid email address";
                  break;
               }
               case "eml_":
               {
                  _valid = validateEmail(_object, false);
                  _message = "You must enter a valid email address";
                  break;
               }
               case "emlc":
               {
                  _valid = validateConfirmEmail(_object, true);
                  _message = "Your email address is not valid or does not match the confirmation.";
                  break;
               }
               case "emlo":
               {
                  _valid = validateConfirmEmail(_object, false);
                  _message = "Your email address is not valid or does not match the confirmation.";
                  break;
               }
               case "imge":
               {
                  _valid = validateTextbox(_object);

                  _message = "You must upload an image for you epitaph.";
                  break;
               }
               default:
               {
                  break;
               }
            }
         }
         catch(e)
         {
            // Ignore error
         }
      }
   }

   // The form validation failed so display message label
   // associated with the data entry field.
   if(!_valid)
   {
      document.getElementById("lblFailedValidationMessage").value="Form Error" + ": " + _message;
      document.getElementById("tblFailedValidation").style.display = "block";
      _object.focus();
   }

   return _valid;
}

// This function simply resets the failed validation
// message box, returns true if the object exists and false if not
function clearFailedValidation()
{
   _result = true;
   try
   {
      _object = document.getElementById("lblFailedValidationMessage");
      _object.value = "";

      _object = document.getElementById("tblFailedValidation");
      _object.style.display = "none";
   }
   catch(e)
   {
      _result = false;
   }
   return _result;
}

function ShowErrorIfExists()
{

if(document.getElementById("lblFailedValidationMessage").value !="")
    {
      
document.getElementById("tblFailedValidation").style.display = "block";
    }
}

// This function validates a text to ensure that it has
// been populated with some data, not just SPACES!
function validateTextbox(textbox)
{
   textbox.value = trim(textbox.value);

   if(textbox.value!="")
      return true;
   else
      return false;

}


function  validatefile(file, mandatory, filetypes)
{
   result = false;
   //   Value   entered   in   File   Input
   var   theFile   =   file.value;
   //   Split   that   value   at   every   period.
   var   isText   =   theFile.split(".");
   //   number   of   splits   (1   period   ==   two   splits,   2   periods   =   3   splits,   etc.).
   var   isTextLen   =   isText.length   -   1;
   //   If   there   is   at   least   one   split,   then   there   is   a   file.
   if(filetypes.length >= 1)
   {
      if   (isTextLen   >=   1)
      {
         //   Look   for   the   last   split   to   be   only   "txt"
         for(row=0; row < filetypes.length; row++)
         {
            if   (isText[isTextLen]   ==   filetypes[row])
               result=true;
         }
      }
   }
   return result;
}

//validate that two passwords are the same
function validatePassword(password, mandatory)
{
   if(document.getElementById("Password").value==document.getElementById("ConfirmPassword").value)
   {
      if(mandatory)
      {
         if(document.getElementById("Password").value=="")
            return false;
         else
            return true;
      }
      else
         return true;
   }
   else
      return false;
}

// This function takes the supplied value and returns true if it is a valid number
// and false if it is not.
function validateNumberbox(numberbox)
{
   return!(isNaN(parseFloat(numberbox.value)));
}

//This function takes the supplied value and return true is the value contains at
//least one @ symbol and one .
function validateEmail(email, mandatory)
{
   result = true;

   if(mandatory & email.value=="")
      result = false;
   if(email.value!="")
   {
      if(email.value.indexOf("@") == -1  || email.value.indexOf(".") == -1 || email.value.length < 8)
      {
         result = false;
      }
   }

   return result;
}


function validateConfirmEmail(_email, mandatory)
{
   if(document.getElementById("email").value==document.getElementById("cemail").value)
   {
      if(validateEmail(_email, mandatory))
         return true;
      else
         return false;
   }
   else
      return false;
}


//checks too see if a radio button has been ticked
function validateRadio(radio, form)
{
   result = false;
   var _object;

   i=2;
   for(i=0; i< form.all.length & _valid; i++)
   {
      _object = form.all(i);
      if(_object.name==radio.name)
      {
         if(_object.checked)
         {
            result = true;
            break;
         }
      }
   }
   return result;
}

// Validates a date entry
function validateDatebox(dateinput, mandatory)
{
   _result = true;
   _date = dateinput.value;

   if(_date!="")
   {
      try
      {
         _date = dateinput.value;
         _result = (Date.parse(_date) > -5364662400000);
      }
      catch(err)
      {
         _result = false;
      }
      return _result;
   }
   else if(mandatory)
   {
      return false;
   }
   return _result;
}

function validateCombobox(comboinput, mandatory)
{
   try
   {
      _result = (comboinput.selectedIndex > -1);
      if(comboinput.value=="")
         _result = false;
      else if(comboinput.value==0)
         _result = false;
   }
   catch(err)
   {
      _result = false;
   }
   return _result;
}

// Validates a time entry
function validateTimebox(timeinput)
{
  return /^([01]?[0-9]|[2][0-3])(:[0-5][0-9])?$/.test(timeinput)
}


// This funtion removes the leading and trailing spaces from a String object.
function trim(str)
{
   var newitem = "" + str;

   //Remove spaces from start
   while((newitem.substr(0,1)==" ") && (newitem.length>0))
   newitem=newitem.substr(1);

   //Remove spaces from end
   while((newitem.substr(newitem.length-1,1)==" ") && (newitem.length>0))
   newitem=newitem.substr(0,newitem.length-1);

   return newitem;
}

// This function takes the supplied number and rounds it to the specified number of decimal places
function roundNumber(num, places)
{
   if (places > 0)
   {
        if ((num.toString().length - num.toString().lastIndexOf('.')) > (places + 1))
        {
            var Rounder = Math.pow(10, places);
            return Math.round(num * Rounder) / Rounder;
        }
        else return num;
   }
   else return Math.round(num);
}