//Browser Support Code

function ajaxFunction(){
        var ajaxRequest;  // The variable that makes Ajax possible!

        try{
                // Opera 8.0+, Firefox, Safari
                ajaxRequest = new XMLHttpRequest();
        } catch (e){
                // Internet Explorer Browsers
                try{
                        ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
                } catch (e) {
                        try{
                                ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
                        } catch (e){
                                // Something went wrong
                                alert("Your browser broke!");
                                return false;
                        }
                }
        }
        // Create a function that will receive data sent from the server
        ajaxRequest.onreadystatechange = function(){
                if(ajaxRequest.readyState == 4){
                        //document.myForm.time.value = ajaxRequest.responseText;
                        document.getElementById('ajaxDiv').innerHTML  = ajaxRequest.responseText;

                }
        }
        var vName = escape(document.getElementById('name').value);
        var vDate = escape(document.getElementById('datefield').value);
        var vNumber = escape(document.getElementById('numberfield').value);
        var vTime = escape(document.getElementById('time').value);
        var vTel = escape(document.getElementById('phone').value);
        var vEmail = escape(document.getElementById('email').value);
	var vComments = escape(document.getElementById('comments').value);
        var query="?name=" + vName + "&date=" + vDate + "&number=" + vNumber + "&time=" + vTime + "&tel=" + vTel +"&email=" + vEmail + "&comments=" + vComments;
        ajaxRequest.open("GET", "serverTime2.php" + query, true);
        ajaxRequest.send(null); 
}

var nbsp = 160;		// non-breaking space char
var node_text = 3;	// DOM text node-type
var emptyString = /^\s*$/ ;


function trim(str)
{
  return str.replace(/^\s+|\s+$/g, '');
}

// --------------------------------------------
//                  msg
// Display warn/error message in HTML element.
// commonCheck routine must have previously been called
// --------------------------------------------

function msg(fld,     // id of element to display message in
             msgtype, // class to give element ("warn" or "error")
             message) // string to display
{
  // setting an empty string can give problems if later set to a 
  // non-empty string, so ensure a space present. (For Mozilla and Opera one could 
  // simply use a space, but IE demands something more, like a non-breaking space.)
  var dispmessage;
  if (emptyString.test(message)) 
    dispmessage = String.fromCharCode(nbsp);    
  else  
    dispmessage = message;

  var elem = document.getElementById(fld);
  elem.firstChild.nodeValue = dispmessage;  
 
  
  elem.className = msgtype;   // set the CSS class to adjust appearance of message
}

// --------------------------------------------
//            commonCheck
// Common code for all validation routines to:
// (a) check for older / less-equipped browsers
// (b) check if empty fields are required
// Returns true (validation passed), 
//         false (validation failed) or 
//         proceed (don't know yet)
// --------------------------------------------

var proceed = 2;  

function commonCheck    (valfield,   // element to be validated
                         infofield,  // id of element to receive info/error msg
                         required)   // true if required
{
 msg ('inf_submit', "warn", "");

  if (!document.getElementById) return true;  // not available on this browser - leave validation to the server
  var elem = document.getElementById(infofield);
  if (!elem.firstChild) return true;  // not available on this browser 
  if (elem.firstChild.nodeType != node_text) return true;  // infofield is wrong type of node  

  if (emptyString.test(valfield.value)) {
    if (required) {
      msg (infofield, "error", "Please enter something");  
 //     setfocus(valfield);
      return false;
    }
    else {
      msg (infofield, "warn", "");   // OK
      return true;  
    }
  }
  return proceed;
}

// --------------------------------------------
//            validatePresent
// Validate if something has been entered
// Returns true if so 
// --------------------------------------------

function validatePresent(valfield,   // element to be validated
                         infofield ) // id of element to receive info/error msg
{
  var stat = commonCheck (valfield, infofield, true);
  if (stat != proceed) return stat;

  msg (infofield, "warn", "");  
  return true;
}

// --------------------------------------------
//               validateEmail
// Validate if e-mail address
// Returns true if so (and also if could not be executed because of old browser)
// --------------------------------------------

function validateEmail  (valfield,   // element to be validated
                         infofield,  // id of element to receive info/error msg
                         required)   // true if required
{
  var stat = commonCheck (valfield, infofield, required);
  if (stat != proceed) return stat;

  var tfld = trim(valfield.value);  // value of field with whitespace trimmed off
  var email = /^[^@]+@[^@.]+\.[^@]*\w\w$/  ;
  if (!email.test(tfld)) {
    msg (infofield, "error", "That doesn't look like a proper e-mail address");
    //setfocus(valfield);
    return false;
  }

  var email2 = /^[A-Za-z][\w.-]+@\w[\w.-]+\.[\w.-]*[A-Za-z][A-Za-z]$/  ;
  if (!email2.test(tfld)) 
    msg (infofield, "warn", "That's a bit of a wierd e-mail address?");
  else
    msg (infofield, "warn", "");
  return true;
}


// --------------------------------------------
//            validatePhone
// Validate telephone number
// Returns true if so (and also if could not be executed because of old browser)
// Permits spaces, hyphens, brackets and leading +
// --------------------------------------------

function validatePhone  (valfield,   // element to be validated
                         infofield,  // id of element to receive info/error msg
                         required)   // true if required
{
  var stat = commonCheck (valfield, infofield, required);
  if (stat != proceed) return stat;

  var tfld = trim(valfield.value);  // value of field with whitespace trimmed off
  var phone = /^\+?[0-9 ()-]+[0-9]$/  ;
  if (!phone.test(tfld)) {
    msg (infofield, "error", "Only digits in your phone number, please.");
//    setfocus(valfield);
    return false;
  }

  var numdigits = 0;
  for (var j=0; j<tfld.length; j++)
    if (tfld.charAt(j)>='0' && tfld.charAt(j)<='9') numdigits++;

  if (numdigits<6) {
    msg (infofield, "error", "Number is too short");
    //setfocus(valfield);
    return false;
  }

  if (numdigits>11)
    msg (infofield, "warn", "looks on the long side");
  else { 
    if (numdigits<10 && numdigits != 6)
      msg (infofield, "warn", "Number looks a funny length?");
    else
      msg (infofield, "warn", "");
  }
  return true;
}


function validateNumber (valfield,   // element to be validated
                         infofield,  // id of element to receive info/error msg
                         required)   // true if required
{
  	var stat = commonCheck (valfield, infofield, required);
 	if (stat != proceed) return stat;
	
	var tfld = trim(valfield.value);
  	var numRE = /^[0-9]{1,3}$/
  	
	if (!numRE.test(tfld) || tfld<1 )  {
    		msg (infofield, "error", "Sorry - how many?");
    		return false;
  	}

	if (tfld>150) {
		 msg (infofield, "error", "Sorry you can't fit that many in");
		return false;
	}

	if (tfld>40) msg (infofield, "warn", "For this many people, ask about our private hire options.");
  	else {
    		if (tfld<2) {
			msg (infofield, "warn", "Drinking alone again?");
		} else {
			msg (infofield, "warn", "");
  		
		}
	}
  	return true;
}

function validateOnSubmit() {
    
	var errors= AllErrorCheck();
   
    if (errors>1)  msg('inf_submit', 'error', 'Some answers need correcting first.');
    if (errors==1)  msg('inf_submit', 'error', 'Something needs correcting first.' );

    if (errors==0) {
		ajaxFunction();
    }

    return;

  };

function AllErrorCheck() {

    var errs;
    errs=0;

    if (!validateNumber (document.forms.myForm.numberfield,   'inf_number',  true)) errs += 1;
    if (!validateEmail  (document.forms.myForm.email, 'inf_email', false)) errs += 1;
    if (!validateDate   (document.forms.myForm.datefield, 'inf_date', true)) errs += 1;
    if (!validateTime   (document.forms.myForm.time, 'inf_time', true)) errs += 1;
    if (!validatePhone  (document.forms.myForm.phone, 'inf_phone', true)) errs += 1;
    if (!validatePresent(document.forms.myForm.name,  'inf_name', true))        errs += 1;
    if (!IsInTheFuture  (document.forms.myForm.datefield.value + " " + document.forms.myForm.time.value, 'inf_date', true)) errs +=1;
    return errs;
}


function validateTime(objName, infofield, required) {

        var stat = commonCheck (objName, infofield, required);
        if (stat != proceed) return stat;

	var strTime;
	var strHour;
	var strMin;
	var intHour;
	var intMin;
        var strSeparatorArray = new Array("-", " ", "/", ".", ":");
        var intElementNr;
	var bFound = false;


	strTime=objName.value;
	if (strTime.length <1) {
		return true;
	}

        for (intElementNr = 0; intElementNr < strSeparatorArray.length; intElementNr++) {
                if (strTime.indexOf(strSeparatorArray[intElementNr]) != -1) {
                        strTimeArray = strTime.split(strSeparatorArray[intElementNr]);

                        // If the string won't split into three it isn't a proper date
                        if (strTimeArray.length != 2) {
                                msg (infofield, "error", "Sorry - I don't understand.  Try hh:mm.");
                                return false;
                        } else {
                                // Assume hh:mm
                                strHour = strTimeArray[0];
                                strMin = strTimeArray[1];
                        }
		bFound=true;
		}
	}

	
 	if (bFound == false) {
                // Check for 4 digit times
                if (strTime.length=4) {
                        strHour = strTime.substr(0, 2);
                        strMin = strTime.substr(2, 2);
		}
	}
	
	if (strMin.length == 1) {
		strMin = '0' + strMin;
	}

        intHour = parseInt(strHour, 10);
        if (isNaN(intHour)) {
                // not a number
                msg (infofield, "error", "I can't work out what hour you mean.");
                return false;
        }

        intMin = parseInt(strMin, 10);
        if (isNaN(intMin)) {
                // not a number
                msg (infofield, "error", "I can't work out how many minutes you mean.");
                return false;
        }

        if (intHour<12) {
		intHour+=12;
	}

        //Set box to what we think we have
	objName.value = intHour + ":" + strMin;
        

	if (intMin>59 || intMin<0) {
                //Minutes too big or too small
                msg (infofield, "error", "Not the right number of minutes in the hour.");
                return false;
        }
	
        if (intHour>23 || intHour<0) {
                //Minutes too big or too small
                msg (infofield, "error", "Not the right number of hours in the day.");
                return false;
        }
 
	if ( intHour!=12 && ( intHour<16 || ( intHour==16 && intMin<30 ))) {
            	//not open if the hour is less <= 16 unless it's 12:something!
             	msg (infofield, "error", "Sorry, we're only open from 4:30pm to 1:00 am");
              	return false;
       }


        msg (infofield, "warn", "");
        return true;


}


function validateDate(objName, infofield, required) {
        
	var stat = commonCheck (objName, infofield, required);
        if (stat != proceed) return stat;

	var strDate;
	var strDateArray;
	var strDay;
	var strMonth;
	var strYear;
	var intDay;
	var intMonth;
	var intYear;
	var booFound = false;
	var datefield = objName;
	var strSeparatorArray = new Array("-"," ","/",".");
	var intElementNr;
	var err = 0;

	var strMonthArray = new Array(12);
		strMonthArray[0] = "Jan";
		strMonthArray[1] = "Feb";
		strMonthArray[2] = "Mar";
		strMonthArray[3] = "Apr";
		strMonthArray[4] = "May";
		strMonthArray[5] = "Jun";
		strMonthArray[6] = "Jul";
		strMonthArray[7] = "Aug";
		strMonthArray[8] = "Sep";
		strMonthArray[9] = "Oct";
		strMonthArray[10] = "Nov";
		strMonthArray[11] = "Dec";

	strDate = datefield.value;

	// Look for different seperators
	for (intElementNr = 0; intElementNr < strSeparatorArray.length; intElementNr++) {
		if (strDate.indexOf(strSeparatorArray[intElementNr]) != -1) {
			strDateArray = strDate.split(strSeparatorArray[intElementNr]);
			
			// If the string won't split into three it isn't a proper date
			if (strDateArray.length != 3) {
				msg (infofield, "error", "Sorry - I don't understand.  Try dd/mm/yyyy.");
				return false;
			} else {
				// Assume Day-Month-Year
				strDay = strDateArray[0];
				strMonth = strDateArray[1];
				strYear = strDateArray[2];
			}

		booFound = true;
   		}
	}


	if (booFound == false) {
		// Check for 6 or 8 digit dates
		if (strDate.length=6) {
			strDay = strDate.substr(0, 2);
			strMonth = strDate.substr(2, 2);
			strYear = strDate.substr(4);
   		}
		if (strDate.length=8) {
			strDay = strDate.substr(0, 2);
			strMonth = strDate.substr(2, 2);
			strYear = strDate.substr(4);
   		}
	}
	if (strYear.length == 1) {
		strYear = '0' + strYear;
	}
	
	if (strYear.length == 2) {
		strYear = '20' + strYear;
	}

	if (strYear.length == 3) {
		 msg (infofield, "error", "Year looks a bit funny...");
                return false;
        }

	intDay = parseInt(strDay, 10);
	if (isNaN(intDay)) {
		// Day is not a number
		msg (infofield, "error", "I can't work out what day you mean.");
		return false;
	}


	intMonth = parseInt(strMonth, 10);
	if (isNaN(intMonth)) {
		// If month isn't a number, check it isn't an approved abreviation
		for (i = 0;i<12;i++) {
			if (strMonth.toUpperCase() == strMonthArray[i].toUpperCase()) {
				intMonth = i+1;
				strMonth = strMonthArray[i];
				i = 12;
   			}
		}
		if (isNaN(intMonth)) {
			// Month isn't a number
       		        msg (infofield, "error", "I can't work out what month you mean.");
			return false;
   		}
	}

	intYear = parseInt(strYear, 10);
	if (isNaN(intYear)) {
		// Year isn't a number
                msg (infofield, "error", "I can't work out what year you mean.");
		return false;
	}

	//Set date here so user can see basis for checks
	datefield.value = intDay + " " + strMonthArray[intMonth-1] + " " + strYear;

	if (intMonth>12 || intMonth<1) {
		//Month too big or too small
                msg (infofield, "error", "Month is too big (or too small).");
		return false;
	}

	if (intDay < 1) {
		//Day is too small
                msg (infofield, "error", "Day is too small.");
		return false;
	}

	if ((intMonth == 1 || intMonth == 3 || intMonth == 5 || intMonth == 7 || 
			intMonth == 8 || intMonth == 10 || intMonth == 12) && intDay > 31) {
		// day is too big for month
                msg (infofield, "error", "Month doesn't have " + intDay + " days");
		return false;
	}


	if ((intMonth == 4 || intMonth == 6 || intMonth == 9 || intMonth == 11) && intDay > 30) {
		// day is too big for 30 day month
                msg (infofield, "error", "Month doesn't have " + intDay + " days");
		return false;
	}

	if (intMonth == 2) {
		if (LeapYear(intYear) == true) {
			// Day is too big despite leap year
			if (intDay > 29) {
		                msg (infofield, "error", "Month doesn't have " + intDay + " days - even in a leap year");
				return false;
			}
		
		} else {
			if (intDay > 28) {
				// Day is to big
		                msg (infofield, "error", "Month doesn't have " + intDay + " days");
				return false;
			}	
		}
	}


	if ((intMonth == 12 && intDay == 25) || (intMonth == 1 && intDay == 1)) {
		msg (infofield, "error", "Sorry, we are closed on Christmas Day and New Year's Day");
		return false;
	}

	msg (infofield, "warn", "");
	return true;
}


function LeapYear(intYear) {
	if (intYear % 100 == 0) {
		if (intYear % 400 == 0) { 
			return true; 
		}
	}
	
	else {
		if ((intYear % 4) == 0) { 
			return true; 
		}
	}


	return false;
}
        

function IsInTheFuture(booking, infofield, required) {
	var today= new Date();
        if (Date.parse(booking) < today) {
                  // Day is in the past 
                  msg (infofield, "error", "That date is in the past");
                  return false;
        }

	return true;

}

///Display Functions

function Head() {
                page = new Array ('about', 'cocktails', 'spirits', 'list', 'private', 'a2u', 'jobs' );
                myDisplay('0');

}  

function myDisplay(option) {     
        for (j=0; j<page.length; j++) {
                document.getElementById(page[j]).style.display="none";
        }
        document.getElementById(page[option]).style.display="block";
}


