/* This function validates the Name field on the contact form. Only allowable charcters are a-z, A-Z, spaces and '.' */

function validateName(name) {
  var error = "";
  var alphaExp = /^[a-z. A-Z]+$/;
	
	if (name.value == ''){
		error = "Name not provided\n";
		name.focus();
		return error;
	}			 
	
	if(!name.value.match(alphaExp)){
		error = "Name has unrecognised characters. Please enter correct Name\n";
		name.focus();
		return error;
	}	 

	return error;	 		 
}

/* This function validates the Email field on the contact form. */

function validateEmail (email) {

  /* The following variable tells the rest of the function whether or not
  to verify that the address ends in a two-letter country or well-known
  TLD.  1 means check it, 0 means don't. */
  var error = "";
  var checkTLD=1;
  
  /* The following is the list of known TLDs that an e-mail address must end with. */
  
  var knownDomsPat=/^(com|net|org|edu|int|mil|gov|arpa|biz|aero|name|coop|info|pro|museum)$/;
  
  /* The following pattern is used to check if the entered e-mail address
  fits the user@domain format.  It also is used to separate the username
  from the domain. */
  
  var emailPat=/^(.+)@(.+)$/;
  
  /* The following string represents the pattern for matching all special
  characters.  We don't want to allow special characters in the address. 
  These characters include ( ) < > @ , ; : \ " . [ ] */
  
  var specialChars="\\(\\)><@,;:\\\\\\\"\\.\\[\\]";
  
  /* The following string represents the range of characters allowed in a 
  username or domainname.  It really states which chars aren't allowed.*/
  
  var validChars="\[^\\s" + specialChars + "\]";
  
  /* The following pattern applies if the "user" is a quoted string (in
  which case, there are no rules about which characters are allowed
  and which aren't; anything goes).  E.g. "jiminy cricket"@disney.com
  is a legal e-mail address. */
  
  var quotedUser="(\"[^\"]*\")";
  
  /* The following pattern applies for domains that are IP addresses,
  rather than symbolic names.  E.g. joe@[123.124.233.4] is a legal
  e-mail address. NOTE: The square brackets are required. */
  
  var ipDomainPat=/^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/;
  
  /* The following string represents an atom (basically a series of non-special characters.) */
  
  var atom=validChars + '+';
  
  /* The following string represents one word in the typical username.
  For example, in john.doe@somewhere.com, john and doe are words.
  Basically, a word is either an atom or quoted string. */
  
  var word="(" + atom + "|" + quotedUser + ")";
  
  // The following pattern describes the structure of the user
  
  var userPat=new RegExp("^" + word + "(\\." + word + ")*$");
  
  /* The following pattern describes the structure of a normal symbolic
  domain, as opposed to ipDomainPat, shown above. */
  
  var domainPat=new RegExp("^" + atom + "(\\." + atom +")*$");
  
  /* Finally, let's start trying to figure out if the supplied address is not null. */
  
  if (email.value == ''){
  	error = "Email address not provided\n";
  	email.focus();
  	return error;
  }		
  
  /* Begin with the coarse pattern to simply break up user@domain into
  different pieces that are easy to analyze. */
  
  var matchArray=email.value.match(emailPat);
  
  if (matchArray==null) {
    /* Too many/few @'s or something; basically, this address doesn't
    even fit the general mould of a valid e-mail address. */
    
    error = "Email address seems incorrect (check @ and .'s)\n";
    email.focus();
    return error;
  }
	
  var user=matchArray[1];
  var domain=matchArray[2];
  
  // Start by checking that only basic ASCII characters are in the strings (0-127).
  
  for (i=0; i<user.length; i++) {
    if (user.charCodeAt(i)>127) {
      error = "This username contains invalid characters\n";
      email.focus();
      return error;
    }
  }
	
  for (i=0; i<domain.length; i++) {
    if (domain.charCodeAt(i)>127) {
      error = "This domain name contains invalid characters.\n";
      email.focus();
      return error;
    }
  }
  
  // See if "user" is valid 
  
  if (user.match(userPat)==null) {
    // user is not valid
    
    error = "The username doesn't seem to be valid.\n";
    email.focus();
    return error;
  }

  /* if the e-mail address is at an IP address (as opposed to a symbolic
  host name) make sure the IP address is valid. */
  
  var IPArray=domain.match(ipDomainPat);
  if (IPArray!=null) {
    // this is an IP address
    
    for (var i=1;i<=4;i++) {
      if (IPArray[i]>255) {
        error = "Destination IP address is invalid!\n";
        email.focus();
        return error;
      }
    }
    return true;
  }
    
  // Domain is symbolic name.  Check if it's valid.
   
  var atomPat=new RegExp("^" + atom + "$");
  var domArr=domain.split(".");
  var len=domArr.length;
  for (i=0;i<len;i++) {
    if (domArr[i].search(atomPat)==-1) {
      error = "The domain name does not seem to be valid.\n";
      email.focus();
      return error;
    }
  }
  
  /* domain name seems valid, but now make sure that it ends in a
  known top-level domain (like com, edu, gov) or a two-letter word,
  representing country (uk, nl), and that there's a hostname preceding 
  the domain or country. */
  
  if (checkTLD && domArr[domArr.length-1].length!=2 && 
  domArr[domArr.length-1].search(knownDomsPat)==-1) {
    error = "The address must end in a well-known domain or two letter " + "country.\n";
    email.focus();
    return error;
  }
  
  // Make sure there's a host name preceding the domain.
  
  if (len<2) {
    error = "This address is missing a hostname!#n";
    email.focus();
    return error;
  }
  
  // If we've gotten this far, everything's valid!
  return error;
}

/* This function validates whether the Retype Email and Email field on the contact form have same value */

function validateReemail(reemail){
  var error = "";
  if (document.contactform.email.value != reemail.value) {
    error = "ReType Email field does not match Email field\n";
    reemail.focus();
    return error;
  }
  return error;
}

/* This function validates the Telephone field on the contact form. Only allowable characters are +, 0-9, -, () */


// Declaring required variables
var digits = "0123456789";
// non-digit characters which are allowed in phone numbers
var phoneNumberDelimiters = "()- ";
// characters which are allowed in international phone numbers
// (a leading + is OK)
var validWorldPhoneChars = phoneNumberDelimiters + "+";
// Minimum no of digits in an international phone no.
var minDigitsInIPhoneNumber = 10;

function isInteger(s)
{   var i;
    for (i = 0; i < s.length; i++)
    {   
        // Check that current character is number.
        var c = s.charAt(i);
        if (((c < "0") || (c > "9"))) return error;
				
    }
    // All characters are numbers.
    return true;
}
function trim(s)
{   var i;
    var returnString = "";
    // Search through string's characters one by one.
    // If character is not a whitespace, append to returnString.
    for (i = 0; i < s.length; i++)
    {   
        // Check that current character isn't whitespace.
        var c = s.charAt(i);
        if (c != " ") returnString += c;
    }
    return returnString;
}

function stripCharsInBag(s, bag)
{   var i;
    var returnString = "";
    // Search through string's characters one by one.
    // If character is not in bag, append to returnString.
    for (i = 0; i < s.length; i++)
    {   
        // Check that current character is not whitespace.
        var c = s.charAt(i);
        if (bag.indexOf(c) == -1) returnString += c;
    }
    return returnString;
}

function validatePhone(phone){
  var bracket=3;
	var phoneNo;
	var error = "";
	
  if (phone.value == '') {
    error = "Telephone Number not provided\n";
    phone.focus();
    return error;
  }

  phoneNo=trim(phone.value);
  
	if(phoneNo.indexOf("+")>1){
	  error = "'+' can be put only at the beginning in telephone number\n";
		phone.focus();
    return error;
	}	
		
  if(phoneNo.indexOf("-")!=-1)
	  bracket=bracket+1;
		
  if(phoneNo.indexOf("(")!=-1 && phoneNo.indexOf("(")>bracket){
	  error = "'(' has been put at the wrong position in telephone number\n";
    phone.focus();
		return error;
	}	
		
  var brchr=phoneNo.indexOf("(");
	
  if(phoneNo.indexOf("(")!=-1 && phoneNo.charAt(brchr+2)!=")"){
	  error = "')' has been put at the wrong position in telephone number\n";
    phone.focus();
		return error;
	}	
	
  if(phoneNo.indexOf("(")==-1 && phoneNo.indexOf(")")!=-1){
		error = "')' appears without matching '(' in telephone number\n";
    phone.focus();
		return error;
	}	
  
	s = stripCharsInBag(phoneNo,validWorldPhoneChars);
	
	if (s.length < minDigitsInIPhoneNumber){
		error = "Telephone number has less than " + minDigitsInIPhoneNumber + " digits. Make sure to include area code\n";
    phone.focus();
		return error;
	}
	
	if (!isInteger(s)){
		error = "Telephone number should have only values 0-9.\n";
    phone.focus();
		return error;
	}
	
  return error;
}


function validateCheckInOutDates (indate, outdate) {
  var error = "";

  if (indate.value == '') {
    error = "Check In Date not provided\n";
    indate.focus();
    return error;
  }

  if (outdate.value == '') {
    error = "Check Out Date not provided\n";
    indate.focus();
    return error;
  }

  var str1  = indate.value;
  var str2  = outdate.value;

  var tokens;

  tokens = str1.split("/");
  var dt1   = parseInt(tokens[0]);
  var mon1  = parseInt(tokens[1]) - 1;
  var yr1   = parseInt(tokens[2]);

  tokens = str2.split("/");
  var dt2   = parseInt(tokens[0]);
  var mon2  = parseInt(tokens[1]) - 1;
  var yr2   = parseInt(tokens[2]);

  var date1 = new Date(yr1, mon1, dt1);
  var date2 = new Date(yr2, mon2, dt2);

  //error = "Check in date: " + date1 + " Check out date: " + date2 + "\n" ;
  if(date2 <= date1)
  {
    error += "Check out date should be later than check in date. \n";
    indate.focus();
  }

  /* getDay() returns value between 0-6 for days sunday-saturday */
  if ((date1.getDay() != 6) || (date2.getDay() != 6))
  {
    error += " Please note Booking is available only for whole week (Saturday to Saturday). Correct check in, check out dates. \n";
    indate.focus();
  }

  return error;
}

/* This function validates the contact form. */

function validate_form(){
  var reason = "";

	reason += validateName(document.contactform.name);
	reason += validateEmail(document.contactform.email);
	reason += validateReemail(document.contactform.reemail);
	reason += validatePhone(document.contactform.phone);
	reason += validateCheckInOutDates(document.contactform.indate, document.contactform.outdate);
	
	if (reason != ""){
		 alert("Some fields need correction\n" + reason);
		 return false;		 						 
	}
	return true;
}


