// A utility function that returns true if a string contains only
// whitespace characters.

function isblank(s)
{
  for(var i = 0; i < s.length; i++) 
  {
   var c = s.charAt(i);
   if ((c != ' ') && (c != '\n') && (c != '\t')) return false;
  }
  return true;
}

// A utility function to determine if two fields contents match
function isMatching(a,b)
{
 	if (a.value  == b.value)
	{
		return true;
	}
	else
	{
		alert("Your email address does not match the confirmation of your email address. Please check both.");
		return false;
	}
}

// Function:        checkInt
// Description:     This verifies whether the field contains a valid integer
// Input arguments: objName (form field)
//                  fieldName (string)
// Return value:    boolean (true if problem)
// Note:            
// 
function isInt(objName) {

  if (isNaN(objName.value)){   // not a number
    return false;
  } else if(parseInt(objName.value) != objName.value) {  // not an integer
    return false;
  } 
  return true;
}

// Function:        checkEmail
// Description:     This verifies whether the field contains a valid email address
// Input arguments: str (string)
// Return value:    boolean (true if valid email address)
function checkEmail(str) {
	var at="@";
	var dot=".";
	var lat=str.indexOf(at);
	var lstr=str.length;
	var ldot=str.indexOf(dot);
	
	// don't validate a blank email address
	if (isblank(str)) return true;

	if (str.indexOf(at)==-1){
	   return false;
	}

	if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr){
	   return false;
	}

	if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr){
	    return false;
	}


	 if (str.indexOf(dot,(lat+2))==-1){
	    return false;
	 }

	//	Don't permit multiple addresses .


	 if (str.indexOf(at,(lat+1))!=-1){
	    return false;
	 }

	 if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot){
	    return false;
	 }

	 if (str.indexOf(" ")!=-1 || str.indexOf(",")!=-1) {
	    return false;
	 }

	 return true;
}


function getDescription(s)
{
	if (s.description)
		return s.description;
	else
		return s.name;
}

function getMsg(e, msg) {
	if (e.msg) {
		return e.msg;
	} else {
		return getDescription(e) + msg; 
	}
}

// This is the function that performs form verification. It will be invoked
// from the onSubmit() event handler. The handler should return whatever
// value this function returns.
function verify(f)
{

  var msg;
  var empty_fields = "";
  var errors = "";

// Make sure user has clicked a date
  
 if ((document.getElementById("resdate").innerHTML) == ("On the calendar, click the date for which you want to reserve.")) {
 	errors += ("\nOn the calendar, please click the date for which you want to reserve.\n");
 }

// Make sure if booking for today, user isn't booking in the past

// Loop through array of time selectors and find the one that's active

var TimeSelectors=['RestimeFull','RestimeShort','RestimeNoBrunch','RestimeNoBrunch','RestimeTo3'];
var restime;
for (i=0;i< TimeSelectors.length;i++) {
	TheSelector = document.getElementById(TimeSelectors[i]);
	if (TheSelector.style.display!="none") {
		restime = TheSelector.value;
		}
	}


    var nyear = document.reserve.resyear.value;
    var nmonth = document.reserve.resmonth.value - 1;
    var nday = document.reserve.resday.value;
    var nhour = parseInt(restime / 100);
    var nmin = parseInt(restime % 100);
	var rdate = new Date(nyear, nmonth, nday, nhour, nmin, 0);
	var cdate = new Date();	
    if (rdate < cdate) {
	   errors += ("\nIf booking for today, please do not book for a time that has already passed.\n");
}
	
  // Loop through the elements of the form, looking for all text,
  // validating postal codes, phone number and checking if the field is
  // blank. If the particular field has an invalid format then this
  // method will put together error messages for fields that are wrong. 
  // Rules for validation:
  // Firstname must NOT be blank
  // Middlename is optional
  // Lastname is optional
  // Phone must be a valid phone number '(nnn)nnn-nnnn' or 'nnn-nnnn'
  // Postal Code must be of the form 'lnl nln' or 'lnlnln'

  
  for(var i = 0; i < f.length; i++) 
  {
    var e = f.elements[i];
    if (e.isInteger) {
	if (!isInt(objName)) {
		errors += getMsg(e, " must be an integer");
	}
    }
	

    if (e.isEmail) {
        if (!checkEmail(e.value)) {
                errors += getMsg(e, " seems to contain an error. Please type one email address with no spaces or commas.");
        }
    }


    if ((e.isMandatory) ||
        (e.type == "text" && e.isPostal) ||
        (e.type == "text" && e.isPhone))
    {
      // first check if the field is empty
      if ((e.value == null) || (e.value == "") || isblank(e.value))
      {
        empty_fields += "\n..." + getDescription(e);
        continue;
      }
    
      // Now check for phone if it is numeric with right format
      if (e.type == "text" && e.isPhone) 
      {
        // trim out blank space in phone number before validation
        if (e.value.indexOf(' ') != -1)
        {
          var no_blank = "";
          for (var i = 0; i < e.value.length; i++)
          {
            if (e.value.substring(i, i+1) != ' ') 
            {
              no_blank += e.value.substring(i, i+1); 
            }
          }
        }
        else
        {
          no_blank = e.value;
        }
        if (no_blank.length != 8 && no_blank.length !=13) 
        {
          errors += "- The field " + getDescription(e) + " " + "must be " +
                    "with format 'nnn-nnnn or '(nnn)nnn-nnnn'\n";
        }
        else if (no_blank.length == 8)
        {
          temp_phone = "" + no_blank.substring(0,3) + 
                       no_blank.substring(4,8);
          var v2 = parseInt(temp_phone);
          if ((v2 != temp_phone) || (isNaN(v2)) || 
              (no_blank.indexOf('-') != 3))
          {       
            errors += "- The field " + getDescription(e) + " " +
                      "must be with format 'nnn-nnnn'.\n";                
          }
        }
        else if (no_blank.length == 13)
        {
          temp_phone = "" + no_blank.substring(1,4) + 
                       no_blank.substring(5,8) + 
                       no_blank.substring(9,13);
          var v2 = parseInt(temp_phone);
          if ((v2 != temp_phone) || (isNaN(v2)) || 
              (no_blank.indexOf('(') != 0) ||
              (no_blank.indexOf(')') != 4) || 
              (no_blank.indexOf('-') != 8))
          {
            errors += "- The field " + getDescription(e) + " " +
                      "must be with format '(nnn)nnn-nnnn'.\n"; 
          }
        }
      }
      // Now check if postal code is in right format 
      if (e.type == "text" && e.isPostal)
      {
        if (e.value.length != 6 && e.value.length != 7)
        {
          errors += "- The field " + getDescription(e) + " " + "must be " +
                    "with format 'lnlnln' or 'lnl nln'\n";
        }
        else if (e.value.length == 6)
        {
          var valid_alpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" + 
                            "abcdefghijklmnopqrstuvwxyz";
          var valid_num = "0123456789";
          var flag_alpha = true;
          var flag_num = true;
          for (var i = 0; i < e.value.length; i++)
          {
            temp_postal = "" + e.value.substring(i, i+1);
            if ((i == 0) || (i == 2) || (i==4))
            {
              if (valid_alpha.indexOf(temp_postal) == "-1")
                 flag_alpha = false;
            }
            else if ((i == 1) || (i == 3) || (i == 5))
            {
              if (valid_num.indexOf(temp_postal) == "-1") 
              flag_num = false;
            }
          }
          if (!flag_num || !flag_alpha)
          {
            errors += "- The field " + getDescription(e) + " " +
                       "must be in the format of 'lnlnln'.\n";
          }                         
        }
        else if (e.value.length == 7)
        {
          var valid_alpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" + 
                            "abcdefghijklmnopqrstuvwxyz";
          var valid_num = "0123456789";
          var flag_alpha = true;
          var flag_num = true;
          var flag_blank = true;
          for (var i = 0; i < e.value.length; i++)
          {
            temp_postal = "" + e.value.substring(i, i+1);
            if ((i == 0) || (i == 2) || (i==5))
            {
              if (valid_alpha.indexOf(temp_postal) == "-1") 
                 flag_alpha = false;
            }
            else if (i == 3)
            {
              if (temp_postal != " ") flag_blank = false;
            }
            else if ((i == 1) || (i == 4) || (i == 6))
            {
              if (valid_num.indexOf(temp_postal) == "-1")
                 flag_num = false;
            }
          }
          if (!flag_num || !flag_alpha || !flag_blank)
          {
            errors += "- The field " + getDescription(e) + " " +
                      "must be in the format of 'lnl nln'.\n";
          }  
        }                       
      }
    }
  }  
  // Now, if there were any errors, then display the messages, and
  // return false to prevent the form from being submitted. Otherwise
  // return true.
  if (!empty_fields && !errors) return true;
  msg = "Sorry! I can't send your message yet.\n";
  if (empty_fields) 
  {
    msg += "Please fill in..."
           + empty_fields + "\n";
    if (errors) msg += "";
  }
  msg += errors;
  alert(msg);
  return false;
}  
