
// Declaring valid date character, minimum year and maximum year
var dtCh= "-";
var minYear=1900;
var maxYear=2100;

/**
checkBookingForm
**/
function checkBookingForm(form){
	/*alert(form);	*/
	var error_messsage= new Array();
	
	var title = form.Title;
	

	if(!checkTitle(title)) error_messsage.push({id:form.Title.id,msg:"Please select your title.\n"}) ;


	var name = form.First_Name.value;
	
	if (!hasValue(form.First_Name.value)) error_messsage.push({id:form.First_Name.id,msg:"Please enter your first name.\n"}) ;
	
	var lname = form.Last_Name.value;
	
	if (!hasValue(form.Last_Name.value)) error_messsage.push({id:form.Last_Name.id,msg:"Please enter your last name.\n"}) ;
		
	var phone = form.Phone.value;			
	
		var phoneChk=checkPhoneNumber(phone);
		if(phoneChk != true)  error_messsage.push({id:form.Phone.id,msg:phoneChk});			


   var email = checkEmailHelp(form.Email.value);
	if (email !=true) error_messsage.push({id:form.Email.id,msg:email});		
	
	var dteVal = isAlmazDate(form.Booking_Date.value);
	if( dteVal != true) error_messsage.push({id:form.booking_date.id,msg:dteVal});		
	
	if( dteVal == true && showCloseDateMessage(form.Booking_Date.value)){
			alert('Please note that we are closed at this date' );
			return false;
		}
		
	
	
	/**This the form message text area*/
   //var message = form.Message.value;	 	
	//if(!hasValue(message)) error_messsage.push({id:form.Message.id,msg:"Please enter Comments / Error messages.\n"});		
	
	
	if(hasItem(error_messsage)){		
		var instructions= 'There were errors submitting the form. Please correct the marked fields and try again.\n ';
		
		displayError(instructions,error_messsage);
		return false;
		
	}else{
		
		
		return true;
		
	}
	
	
}
/**
displayError
**/
function displayError(intructTxt,msgArray){
	
	var instructions=intructTxt;
	
	  var txt = instructions+"\n" ;
	
	
	
	for (var i=0; i<msgArray.length;i++){
		
		txt +=" - "+msgArray[i].msg;
	}
		
		alert(txt);
		
		return;
}
/**
hasValue
Checks if varialble is not empty
*/
function hasValue(str){
	var temp = trim(str);
	if(temp.length < 1) return false;
	
	return true;
}
/**
hasItem
Checks if varialble is not empty
*/
function hasItem(theArray){

	if(theArray.length >0) return true;
	
	return false;
}
function isValidPhoneNumber(phone){
	
	if ((phone ==null)||(phone =="")){
		/*alert("Please Enter your Phone Number")*/
			return false
	}
	if (checkInternationalPhone(phone)==false){
	/*	alert("Please Enter a Valid Phone Number")*/
				return false
	}
	return true
 }
 
 function checkPhoneNumber(phone){
	
	if ((phone ==null)||(phone =="")){
				return "Please Enter your Phone Number\n";
	}

		if (!isPhoneNumber(phone) && !checkInternationalPhone(phone)  ){
				return "Please Enter a Valid Phone Number\n";
		}
	
	
	return true
 }
 //Validates a local Austarlian phone number including mobile phones
function isPhoneNumber(str){
  var re =/^[0-9]{10}$|^\(0[1-9]{1}\)[0-9]{8}$|^[0-9]{8}$|^[0-9]{4}[ ][0-9]{3}[ ][0-9]{3}$|^\(0[1-9]{1}\)[ ][0-9]{4}[ ][0-9]{4}$|^[0-9]{4}[ ][0-9]{4}$/;
  return re.test(trimAllSapces(str));
}
/** 
Checks international phone number
STR must be trimed from all sapces
eg.(+123) 1234 5678 or 02 1234 5678 or 123 123 4567) or international format (eg. +61 (0) 2 1234 5678 or +1 123 123 4567). It also accepts an optional extention of up to five digits prefixed by x or ext (eg. 123 123 4567 x89). 
	 \(?\+\d{1,3}\)?(-| )? **/
function checkInternationalPhone(str){
 var re = /^((\+\d{1,3}(-| )?| \(?\d\)?(-| )?\d{1,5})|(\(\+\d{1,3}(-| )?\)| \(?\d\)?(-| )?\d{1,5})|(\(?\d{2,6}\)?))(-| )?(\d{3,4})(-| )?(\d{4})(( x| ext)\d{1,5}){0,1}$/;
 return re.test(trimAllSapces(str));
}

// Trims white space from both sides of a string and returns the trimmed string
function trim(text){

	var start=0
	var leftTrim=""
	var fullTrim=""
	var end=0
	var isAllSpaces
	
	// Check if entire string is spaces
	for(w=0;w<text.length;w++){
		if(text.charAt(w)==" "){
			isAllSpaces=true
		}
		else{
			isAllSpaces=false
			break
			}
	}
	
	// If string is all spaces return zero length string 
	if (isAllSpaces==true){
		var x=""
		return x
		}

	// If the string is not all spaces then perform trim of white space
	 
	// Perform a left trim
	// Find position first real char appears in string
	for(i=0;i<text.length;i++){
		if(text.charAt(i)!=" "){
			start=i
			break
		}
	}

	// Extract the string to the right of start
	for(i=start;i<text.length;i++){
		leftTrim+=text.charAt(i)
	}
	
	//perform right trim
	for(i=leftTrim.length-1;i>=0;i--){          // -1 is for end of string
		if(leftTrim.charAt(i)!=" "){
			end=i
			break
		}
	}

	// Extract the string to the left of start
	for(i=0;i<=end;i++){
		fullTrim+=leftTrim.charAt(i)
	}
	return fullTrim
}	

function trimAllSapces(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 checkTitle(titleSelect){
	var x =titleSelect.options[titleSelect.selectedIndex].value
	var y = trimAllSapces(x)=="select" ? false : true
	if (!y){
	/*	alert("Please select the area where the area error/problem occured occurred.")*/
		return false
	}
	else{
		return true  
	}
}
//=========================================================================================================
function checkEmailHelp(email){
	var msg=""
	var invalidChars="/:,; ";
	/*var email = trim(email);*/
	var position=email.indexOf("@");
	var periodPos=email.indexOf(".",position);
	var errorFlagB
	var errorFlag

	if (email==""){
		msg=msg+"You must enter an email address.\n";
		errorFlag=false;
	}	else if (email.length<6){
		msg=msg+"Your email address must be at least 6 characters long.\n";
		errorFlag=false;
	}	else if (position==-1){
		msg=msg+"Your email address must contain a '@' character.\n";
		errorFlag=false;
	}	else if ((email.indexOf("@",(position+1)))!=-1){
		msg=msg+"You can only have one '@' character in your email address\n";
		errorFlag=false;
	}	else if ((position==0)||(position==(email.length-1))){
		msg=msg+"You can't have the '@' character as the first or\n"+
		"last character in your email address.\n";
		errorFlag=false;
	}	else if ((periodPos==-1)||((periodPos+3)>email.length)){
		msg=msg+"The name of your mail server must have a '.com' (or similar) extension.\n";
		errorFlag=false;
	}else if ((position ==(periodPos -1))||((periodPos+3)>email.length)){
		msg=msg+"The '@' should not be folowed by '.'.\n";
		errorFlag=false;
	}
	
	

	
	for (i=0;i<invalidChars.length;i++){
		badChar=invalidChars.charAt(i);
		if (email.indexOf(badChar,0)!=-1){
			errorFlagB=true;
			}
		}
				
			
	if (errorFlagB==true){
		msg=msg+"Your email address contains invalid character(s) (ie. / : , ; space)\n";
		errorFlag=false;
		return msg
		}
		
	if (errorFlag==false){
		/*alert(msg)*/
		return msg
		}
	else
		return true
}



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 isAlmazDate(dtStr){
	var daysInMonth = DaysArray(12)
	var pos1=dtStr.indexOf(dtCh)
	var pos2=dtStr.indexOf(dtCh,pos1+1)
	var strYear=dtStr.substring(0,pos1)
	var strMonth=dtStr.substring(pos1+1,pos2)
	var strDay=dtStr.substring(pos2+1)
	strYr=strYear
	if (strDay.charAt(0)=="0" && strDay.length>1) strDay=strDay.substring(1)
	if (strMonth.charAt(0)=="0" && strMonth.length>1) strMonth=strMonth.substring(1)
	for (var i = 1; i <= 3; i++) {
		if (strYr.charAt(0)=="0" && strYr.length>1) strYr=strYr.substring(1)
	}
	month=parseInt(strMonth)
	
	day=parseInt(strDay)
	year=parseInt(strYr)
	if (pos1==-1 || pos2==-1){
			return "The date format should be : yyyy - mm - dd"
	}
	if (strMonth.length<1 || month<1 || month>12){
		
		return "Please enter a valid month"
	}
	if (strDay.length<1 || day<1 || day>31 || (month==2 && day>daysInFebruary(year)) || day > daysInMonth[month]){
		
		return "Please enter a valid day"
	}
	if (strYear.length != 4 || year==0 || year<minYear || year>maxYear){
			return "Please enter a valid 4 digit year between "+minYear+" and "+maxYear
	}
	if (dtStr.indexOf(dtCh,pos2+1)!=-1 || isInteger(stripCharsInBag(dtStr, dtCh))==false){
		
		return "Please enter a valid date"
	}
	
return true
}

function showCloseDateMessage(formDate){
		 var date1 =  new Date (2010,12, 23);
		 var date2 =  new Date (2011, 01, 03);	
		 //
		 var pos1=formDate.indexOf(dtCh);
	     var pos2=formDate.indexOf(dtCh,pos1+1);
		 var strYear=formDate.substring(0,pos1);
	     var strMonth=formDate.substring(pos1+1,pos2);
	     var strDay=formDate.substring(pos2+1);
		 
		 var date3 = new Date(parseInt(strYr),parseInt(strMonth),parseInt(strDay));
        
		if ((greaterDate(date3, date1) == 1) && (greaterDate(date2, date3) == 1)){ 
		 return true;
		}else{		
		  return false;
		}
		
	}
	
	function greaterDate(start_date, end_date)
	{
	  
	   var start =  start_date.getTime();
	   var end =  end_date.getTime();
	  
	 if (start-end > 0)
		return 1;
	  else
	   return 0;
	}




