//in_array function as used by "checkWithinDeliveryZone"
Array.prototype.inArray = function (value){ // Returns true if the passed value is found in the array. Returns false if it is not.

var i;

for (i=0; i < this.length; i++){
	if (this[i] == value){
		return true;
	}
}
return false;
};



function longEnough(elem){

	var errorName = 'error_'+elem.name;
	if (elem.value.length < 6){

		document.getElementById(errorName).style.display='block';	//Make the red asterisk show up next to the error field
		elem.focus();

		return false;
	}

	document.getElementById(errorName).style.display='none';
	return true;
}


function notEmpty(elem){

	var errorName = 'error_'+elem.name;
	if(elem.value.length == 0){
		document.getElementById(errorName).style.display='block';	//Make the red asterisk show up next to the error field
		elem.focus();
		return false;
	}

	document.getElementById(errorName).style.display='none';
	return true;
}

function notEmptyTwo(elem1, elem2){
	if((elem1.value.length == 0) && (elem2.value.length == 0)){

		var errorName = 'error_'+elem2.name;

		document.getElementById(errorName).style.display='block';	//Make the red asterisk show up next to the error field
		elem2.focus();

		return false;
	}
	return true;
}

function isAnInteger(elem, helperMsg){ //Like isInteger used above but handles error messages
	var i;

	//alert("here");

    for (i = 0; i < elem.value.length; i++){
        // Check that current character is number.
        var c = elem.value.charAt(i);

		//alert(c);

        if (((c < "0") || (c > "9"))) {
			var errorName = 'error_'+elem.name;
			document.getElementById('errorText').value=helperMsg;
			document.getElementById('errorText').style.visibility='visible'; //Show the error message
			document.getElementById(errorName).style.visibility='visible';	//Make the red asterisk show up next to the error field
			elem.focus();

			return false;
		}
    }
    // All characters are numbers.
    return true;
}

function isChecked(elem, helperMsg){
	if (!(elem.checked)){

		var errorName = 'error_'+elem.name;

		document.getElementById('errorText').value=helperMsg;
		document.getElementById('errorText').style.visibility='visible'; //Show the error message
		document.getElementById(errorName).style.visibility='visible';	//Make the red asterisk show up next to the error field

		if (elem.name == "terms_and_conditions"){
			alert(helperMsg); //Webkit Safari on iPhone doesn't focus on checkboxes
		}

		elem.focus();

		return false;
	}
	return true;
}

function convertUKDatetoISO(inputDate) {	//Convert to YYYY,MM,DD format
	var dateArray = inputDate.split(/[\\\/]/);
	var convertedDate = new Date(dateArray[2]+'/'+dateArray[1]+'/'+dateArray[0]);
	return convertedDate;
}

function convertUKDatetoFitAddMonths(inputDate) {    //Convert to mm/dd/yyyy format
	var dateArray = inputDate.split(/[\\\/]/);
	var convertedDate = new Date(dateArray[1]+'/'+dateArray[0]+'/'+dateArray[2]);
	return convertedDate;
}

function notBeforeToday(elem, today){
	var inputDate = elem.value;

	//Convert to YYYY,MM,DD format for comparison with "today"
	var convertedDate = convertUKDatetoISO(inputDate);

	if(convertedDate < today){

		var errorName = 'error_'+elem.name;
		document.getElementById(errorName).style.display='block';	//Make the red asterisk show up next to the error field
		elem.focus();
		return false;

		return false;
	}
	return true;
}

Date.prototype.addMonths = function (n) {
var day = this.getDate();
this.setMonth(this.getMonth() + n);
if (this.getDate() < day) {
	this.setDate(1);
	this.setDate(this.getDate() - 1);
	}
return this;
}
// Functions for and including isADate
var todayX = new Date();
var todayX = new Date(todayX.getFullYear(), todayX.getMonth(), todayX.getDate());
var numberOfYearsBookableInTheFuture = 1;

var ddX = todayX.getDate();
var mmX = todayX.getMonth()+1;//January is 0!
var yyyyX = todayX.getFullYear();
var dtCh= "/";
var minYear=yyyyX;
var maxYear=(yyyyX + numberOfYearsBookableInTheFuture);

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 false;
    }
    // All characters are numbers.
    return true;
}

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++){
        var c = s.charAt(i);
        if (bag.indexOf(c) == -1) returnString += c;
    }
    return returnString;
}

function daysInFebruary (year){
	// February has 29 days in any year evenly divisible by four,
    // EXCEPT for centurial years which are not also divisible by 400.
    return (((year % 4 == 0) && ( (!(year % 100 == 0)) || (year % 400 == 0))) ? 29 : 28 );
}

function DaysArray(n) {
	for (var i = 1; i <= n; i++) {
		this[i] = 31;
		if (i==4 || i==6 || i==9 || i==11) {this[i] = 30;}
		if (i==2) {this[i] = 29;}
   }
   return this;
}


function checkBottlesOrdered(elem,threshold){

	var errorName = 'error_'+elem.name;
	if((elem.value > 0) && (elem.value < threshold)){
		document.getElementById(errorName).style.display='block';	//Make the red asterisk show up next to the error field
		//elem.focus(); //element is hidden!!
		return false;
	}

	document.getElementById(errorName).style.display='none';
	return true;
}

function checkWithinDeliveryZone(elem,allowed_delivery_zones){

	var errorName = 'error_'+elem.name;
	var delivery_zones_array=allowed_delivery_zones.split("**");

	if ((delivery_zones_array.inArray(elem.value)) == false){

		document.getElementById(errorName).style.display='block';	//Make the red asterisk show up next to the error field
		//elem.focus(); //element is hidden!!
		return false;
	}

	document.getElementById(errorName).style.display='none';
	return true;
}


function isInteger(elem, sText)
{

   var ValidChars = "0123456789-";
   var IsNumber=true;
   var Char;


   for (i = 0; i < sText.length && IsNumber == true; i++)
      {
      Char = sText.charAt(i);
      if (ValidChars.indexOf(Char) == -1)
         {

			var errorName = 'error_'+elem.name;
			document.getElementById(errorName).style.display='block';	//Make the red asterisk show up next to the error field
			elem.focus();
	        IsNumber = false;

         }
      }
   return IsNumber;
}

function moneyValidator(elem){
	var moneyExp = /^[0-9\.\-]+\.[0-9]{2,4}$/;
	if(elem.value.match(moneyExp)){
		return true;
	}else{
		var errorName = 'error_'+elem.name;

		document.getElementById(errorName).style.visibility='visible';	//Make the red asterisk show up next to the error field
		elem.focus();
	}
}

function roundNumber(num, dec) {
	var result = Math.round(num*Math.pow(10,dec))/Math.pow(10,dec);
	return result;
}

function validate_contact_us(){

	// Make quick references to our fields
	var val_name = document.getElementById('Name');
	var val_email = document.getElementById('Email');

	//Hide the asterisks prior to any of them showing up (otherwise they persist)
	//document.getElementById('error_name').style.display='block';

	// Check each input in the booking that it appears in the form!

	if(notEmpty(val_name)){
		if(notEmpty(val_email)){
			if (jcap()){
		   		return true;
			}
		}
	}
	return false;
}

function validate_email() {
var where = document.getElementById("news_email").value.indexOf("@");

if (document.getElementById("news_email").value.length < 1) {
  window.alert("You must include your e-mail address.");
  return false;
}
if (where < 0) {
  window.alert("You must enter a valid email address");
  return false;
}
return true;
}

function sameValue(elem1,elem2){

	var errorName = 'error_'+elem2.name;
	if(elem1.value != elem2.value){
		document.getElementById(errorName).style.display='block';	//Make the red asterisk show up next to the error field
		elem2.focus();
		return false;
	}

	document.getElementById(errorName).style.display='none';
	return true;
}

function validate_email_address(elem) {

	var errorName = 'error_'+elem.name;

	if(elem.value.length == 0){
		document.getElementById(errorName).style.display='block';	//Make the red asterisk show up next to the error field
		elem.focus();
		return false;
	}

	var at="@"
	var dot="."
	var lat=elem.value.indexOf(at)
	var lelem=elem.value.length
	var ldot=elem.value.indexOf(dot)

	if (elem.value.indexOf(at)==-1){

		document.getElementById(errorName).style.display='block';	//Make the red asterisk show up next to the error field
		elem.focus();

		return false;
	}

	if (elem.value.indexOf(at)==-1 || elem.value.indexOf(at)==0 || elem.value.indexOf(at)==lelem){

		document.getElementById(errorName).style.display='block';	//Make the red asterisk show up next to the error field
		elem.focus();

		return false;
	}

	if (elem.value.indexOf(dot)==-1 || elem.value.indexOf(dot)==0 || elem.value.indexOf(dot)==lelem){
		document.getElementById(errorName).style.display='block';	//Make the red asterisk show up next to the error field
		elem.focus();

		return false;
	}

	 if (elem.value.indexOf(at,(lat+1))!=-1){
		document.getElementById(errorName).style.display='block';	//Make the red asterisk show up next to the error field
		elem.focus();

		return false;
	 }

	 if (elem.value.substring(lat-1,lat)==dot || elem.value.substring(lat+1,lat+2)==dot){
		document.getElementById(errorName).style.display='block';	//Make the red asterisk show up next to the error field
		elem.focus();

		return false;
	 }

	 if (elem.value.indexOf(dot,(lat+2))==-1){
		document.getElementById(errorName).style.display='block';	//Make the red asterisk show up next to the error field
		elem.focus();

		return false;
	 }

	 if (elem.value.indexOf(" ")!=-1){
		document.getElementById(errorName).style.display='block';	//Make the red asterisk show up next to the error field
		elem.focus();

		return false;
	 }

	document.getElementById(errorName).style.display='none';
	return true;

}

function notChecked(elem){

	var errorName = 'error_'+elem.name;

	if(elem.checked == false){

		document.getElementById(errorName).style.display='block';	//Make the red asterisk show up next to the error field
		elem.focus();

		return false;
	}

	document.getElementById(errorName).style.display='none';
	return true;
}

function isInteger(elem, sText)
{

   var ValidChars = "0123456789-";
   var IsNumber=true;
   var Char;


   for (i = 0; i < sText.length && IsNumber == true; i++)
      {
      Char = sText.charAt(i);
      if (ValidChars.indexOf(Char) == -1)
         {

			var errorName = 'error_'+elem.name;
			document.getElementById(errorName).style.display='block';	//Make the red asterisk show up next to the error field
			elem.focus();
	        IsNumber = false;

         }
      }
   return IsNumber;
}

function moneyValidator(elem){
	var moneyExp = /^[0-9\.\-]+\.[0-9]{2,4}$/;
	if(elem.value.match(moneyExp)){
		return true;
	}else{
		var errorName = 'error_'+elem.name;

		document.getElementById(errorName).style.visibility='visible';	//Make the red asterisk show up next to the error field
		elem.focus();
	}
}

function roundNumber(num, dec) {
	var result = Math.round(num*Math.pow(10,dec))/Math.pow(10,dec);
	return result;
}




function validate_demographics(){

	// Make quick references to our fields

	var val_delivery_firstname = document.getElementById('delivery_firstname');
	var val_delivery_surname = document.getElementById('delivery_surname');
	var val_delivery_address_address = document.getElementById('delivery_address_address');
	var val_delivery_address_province = document.getElementById('delivery_address_province');
	var val_delivery_address_country_code = document.getElementById('delivery_address_country_code');
	var val_delivery_address_postalCode = document.getElementById('delivery_address_postalCode');
	var val_delivery_address_city = document.getElementById('delivery_address_city');
	var val_contact_phoneNumber = document.getElementById('contact_phoneNumber');
	var val_email = document.getElementById('email');
	var val_password = document.getElementById('password');
	var val_password_again = document.getElementById('password_again');
	var val_secret_question = document.getElementById('secret_question');
	var val_secret_answer = document.getElementById('secret_answer');
	var val_contact_firstname = document.getElementById('contact_firstname');
	var val_contact_surname = document.getElementById('contact_surname');


	//Not checked:

	//Hide the asterisks prior to any of them showing up (otherwise they persist)

	// Check each input in the booking that it appears in the form!

//	if(notChecked(val_terms_and_conditions)){

	if(notEmpty(val_contact_firstname)){
		if(notEmpty(val_contact_surname)){
			if(notEmpty(val_contact_phoneNumber)){
				if((validate_email_address(val_email)) && (notEmpty(val_email))){
					if((notEmpty(val_password)) && (sameValue(val_password,val_password_again))){
						if((longEnough(val_password))){
							if(notEmpty(val_secret_question)){
								if(notEmpty(val_secret_answer)){
									if(notEmpty(val_delivery_firstname)){
										if(notEmpty(val_delivery_surname)){
											if(notEmpty(val_delivery_address_address)){
												if(notEmpty(val_delivery_address_city)){
													if(notEmpty(val_delivery_address_province)){
														if(notEmpty(val_delivery_address_postalCode)){
															if(notEmpty(val_delivery_address_country_code)){
														   		return true;
															}
														}
													}
												}
											}
										}
									}
								}
							}
						}
					}
				}
			}
		}
	}

//	}
	return false;
}

function validate_order_form(threshold,allowed_delivery_zones){

	//NB threshold is How many bottles must be ordered to qualify.  Note that zero is also allowed since restriction only applies to wine.

	// Make quick references to our fields
	var val_bottles_ordered = document.getElementById('bottles_ordered');
	var val_over_18 = document.getElementById('over_18');
	var val_delivery_address_country_code = document.getElementById('delivery_address_country_code');

	//Hide the asterisks prior to any of them showing up (otherwise they persist)
	//document.getElementById('error_name').style.display='block';

	// Check each input in the booking that it appears in the form!

	if(checkBottlesOrdered(val_bottles_ordered,threshold)){
		if(notChecked(val_over_18)){
			if(checkWithinDeliveryZone(val_delivery_address_country_code,allowed_delivery_zones)){
	   			return true;
			}
		}
	}
	return false;
}

function validate_online_booking(){

	//NB threshold is How many bottles must be ordered to qualify.  Note that zero is also allowed since restriction only applies to wine.

	// Make quick references to our fields
	var date_from = document.getElementById('date_from');
	var contact_name = document.getElementById('contact_name');
	var number_of_people = document.getElementById('number_of_people');
	var contact_phone = document.getElementById('contact_phone');
	var contact_email = document.getElementById('contact_email');

	var today = new Date();
	var today = new Date(today.getFullYear(), today.getMonth(), today.getDate());

	// Check each input in the booking that it appears in the form!
	if(notEmpty(date_from)){
		if(notBeforeToday(date_from, today)){
			if(notEmpty(number_of_people)){
				if(notEmpty(contact_name)){
					if(notEmpty(contact_phone)){
						if(validate_email_address(contact_email)){
							if (jcap()){
						   		return true;
							}
						}
					}
				}
			}
		}
	}
	return false;
}


