var MaxYearRange = 5;

function validate_form(form_name) 
{
	//alert("validate: " + form_name)
	var message = "Data Validation Errors:";
	var SubMessage = "";
	var errorOccurred = false;
	var SubError = false;
	var tempVar;
	var ThisForm = eval("document."+form_name);
	var formVars = Array();
	
	
//	alert(form_name)
	for(var j=0; j<ThisForm.elements.length; j++  )
  {
		if ( ThisForm.elements[j].type != "select-one")			
			formVars[ThisForm.elements[j].name]	= ThisForm.elements[j].value;		
		else
			formVars[ThisForm.elements[j].name] = ThisForm.elements[j].selectedIndex;
	}	
			
  if ( form_name == "booking_form" ) 
	{			
		
		// check require fields has been filled in	=====================	  
		if ( !isNotEmpty(formVars["txt_Name"]) )
		{
			SubMessage += "\n - Name";
			SubError = true;		
		}		
		if ( !isNotEmpty(formVars["txt_HomePhone"]) )
		{
			SubMessage += "\n - Home Phone";
			SubError = true;		
		}			
		if ( !isNotEmpty(formVars["txt_Mobile"]) )
		{
			SubMessage += "\n - Mobile";
			SubError = true;		
		}			
		if ( !isNotEmpty(formVars["txt_Email"]) )
		{
			SubMessage += "\n - Email";
			SubError = true;		
		}	
		if ( !isNotEmpty(formVars["txt_Time"]) )
		{
			SubMessage += "\n - Booking Time";
			SubError = true;		
		}					
		if ( !isNotEmpty(formVars["txt_Date"]) || !isNotEmpty(formVars["txt_Year"]) )
		{
			SubMessage += "\n - Booking Date";
			SubError = true;		
		}			
		if( SubError )
		{
			message += "\n\nPlease fill in all required fields:" + SubMessage;
			errorOccurred = true;	
		}
		
	
		// check phone no in integer ==========================
		SubMessage = "";
		SubError = false;
		if ( !isPosInteger(formVars["txt_Mobile"]) )
		{
			SubMessage += "\n - Mobile";
			SubError = true;		
		}			
		if ( !isPosInteger(formVars["txt_HomePhone"]) )
		{
			SubMessage += "\n - Home Phone";
			SubError = true;		
		}			
		if ( !isPosInteger(formVars["txt_WorkPhone"]) )
		{
			SubMessage += "\n - Work Phone";
			SubError = true;		
		}		
		if( SubError )
		{
			message += "\n\nPhone no must be a Number:" + SubMessage;
			errorOccurred = true;	
		}			
	
		// verify email address format ==============================
		if ( isNotEmpty(formVars["txt_Email"]) )
		{
			if( !isEMailAddr(formVars["txt_Email"]) )
			{
				message += "\n\nInvalid Email format.";
				errorOccurred = true;
			}
			else if ( formVars["txt_Email"] != formVars["txt_RetypeEmail"] )
			{
				message += "\n\nRetyped Email does not match the Email.";
				errorOccurred = true;
			}
		}
		
		// verify post code ===========================
		if( !isPosInteger(formVars["txt_Postcode"]) )
		{
			message += "\n\nPost Code must be a Number.";
			errorOccurred = true;
		}
				
		// verify Booking Time =================================		
		if ( !isTime(formVars["txt_Time"]) )
		{
			message += "\n\nInvalid Time Format.";
			errorOccurred = true;
		}	
		
		// verify Booking Date =================================
		SubMessage = "";
		SubError = false;
		if ( !isPosInteger(formVars["txt_Date"]) )
		{
			SubMessage += "\n - Date";
			SubError = true;		
		}	
		if ( !isPosInteger(formVars["txt_Year"]) )
		{
			SubMessage += "\n - Year";
			SubError = true;		
		}				
		
		var check_date = isCorrect_Date(formVars["txt_Year"], formVars["select_Month"], formVars["txt_Date"])
		
		if( SubError )
		{
			message += "\n\nBooking Date must be a Number:" + SubMessage;
			errorOccurred = true;	
		}
		else if (check_date != 0)
		{
			switch (check_date)
			{
				case 1:	message += "\n\nBooking Date: Error date range.";
								break;
				
				case 2: message += "\n\nBooking Date over the maximum booking period: " + MaxYearRange + " years.";
								break;
				
				case 3: message += "\n\nBooking Date must not before today.";
								break;
				
				default:
			}			
			
			errorOccurred = true;
		}					
		
		// verify flight number ===========================
//		alert(ThisForm.select_From.options[ThisForm.select_From.selectedIndex].text);
		if( ThisForm.select_From.options[ThisForm.select_From.selectedIndex].text == "Airport" )		
		{			
			if( !isNotEmpty(formVars["txt_FlightNo"]) )
			{
				message += "\n\nSince you are departing from airport, \nplease fill in your fligh no.";
				errorOccurred = true;
			}
		}
				
  }  // end if ( form_name == "booking_form" ) 
	else if(form_name == "frm_NewBooking" || form_name == "frm_ModifyBooking")
	{
		// check require fields has been filled in	=====================	  
		if ( !isNotEmpty(formVars["txt_Email"]) )
		{
			SubMessage += "\n - Email";
			SubError = true;		
		}	
		if ( !isNotEmpty(formVars["txt_Time"]) )
		{
			SubMessage += "\n - Booking Time";
			SubError = true;		
		}					
		if ( !isNotEmpty(formVars["txt_Date"]) || !isNotEmpty(formVars["txt_Year"]) )
		{
			SubMessage += "\n - Booking Date";
			SubError = true;		
		}			
		if( SubError )
		{
			message += "\n\nPlease fill in all required fields:" + SubMessage;
			errorOccurred = true;	
		}
		
		// verify email address format ==============================
		if ( isNotEmpty(formVars["txt_Email"]) )
		{
			if( !isEMailAddr(formVars["txt_Email"]) )
			{
				message += "\n\nInvalid Email format.";
				errorOccurred = true;
			}			
		}
		
		// verify Booking Time =================================		
		if ( !isTime(formVars["txt_Time"]) )
		{
			message += "\n\nInvalid Time Format.";
			errorOccurred = true;
		}	
		
		// verify Booking Date =================================
		SubMessage = "";
		SubError = false;
		if ( !isPosInteger(formVars["txt_Date"]) )
		{
			SubMessage += "\n - Date";
			SubError = true;		
		}	
		if ( !isPosInteger(formVars["txt_Year"]) )
		{
			SubMessage += "\n - Year";
			SubError = true;		
		}				
		
		var check_date = isCorrect_Date(formVars["txt_Year"], formVars["select_Month"], formVars["txt_Date"])
		
		if( SubError )
		{
			message += "\n\nBooking Date must be a Number:" + SubMessage;
			errorOccurred = true;	
		}
		else if (check_date == 1)
		{
			message += "\n\nBooking Date: Error date range.";								
			errorOccurred = true;
		}					
		
		// verify flight number ===========================
//		alert(ThisForm.select_From.options[ThisForm.select_From.selectedIndex].text);
		if( ThisForm.select_From.options[ThisForm.select_From.selectedIndex].text == "Airport" )		
		{			
			if( !isNotEmpty(formVars["txt_FlightNo"]) )
			{
				message += "\n\nSince you are departing from airport, \nplease fill in your fligh no.";
				errorOccurred = true;
			}
		}
		
		//== verify Price format =========================
		if ( !isPosNumber(formVars["txt_Price"]) )
		{
			message += "\n\nInvaild Price.";
			errorOccurred = true;
		}	
		
	} // end else if(form_name == "frm_NewBooking" || form_name == "frm_ModifyBooking")
	
	else if(form_name == "frm_NewCustomer" || form_name == "frm_ModifyCustomer")
	{
		// check require fields has been filled in	=====================	  
		if ( !isNotEmpty(formVars["txt_Email"]) )
		{
			SubMessage += "\n - Email";
			SubError = true;		
		}			
		if ( !isNotEmpty(formVars["txt_Name"]) )
		{
			SubMessage += "\n - Name";
			SubError = true;		
		}		
		if ( !isNotEmpty(formVars["txt_HomePhone"]) )
		{
			SubMessage += "\n - Home Phone";
			SubError = true;		
		}			
		if ( !isNotEmpty(formVars["txt_Mobile"]) )
		{
			SubMessage += "\n - Mobile";
			SubError = true;		
		}			
		
		if( SubError )
		{
			message += "\n\nPlease fill in all required fields:" + SubMessage;
			errorOccurred = true;	
		}		
	
		// check phone no in integer ==========================
		SubMessage = "";
		SubError = false;
		if ( !isPosInteger(formVars["txt_Mobile"]) )
		{
			SubMessage += "\n - Mobile";
			SubError = true;		
		}			
		if ( !isPosInteger(formVars["txt_HomePhone"]) )
		{
			SubMessage += "\n - Home Phone";
			SubError = true;		
		}			
		if ( !isPosInteger(formVars["txt_WorkPhone"]) )
		{
			SubMessage += "\n - Work Phone";
			SubError = true;		
		}		
		if( SubError )
		{
			message += "\n\nPhone no must be a Number:" + SubMessage;
			errorOccurred = true;	
		}			
	
		// verify email address format ==============================
		if ( isNotEmpty(formVars["txt_Email"]) )
		{
			if( !isEMailAddr(formVars["txt_Email"]) )
			{
				message += "\n\nInvalid Email format.";
				errorOccurred = true;
			}			
		}
		
		// verify post code ===========================
		if( !isPosInteger(formVars["txt_Postcode"]) )
		{
			message += "\n\nPost Code must be a Number.";
			errorOccurred = true;
		}		
		
	} // end else if(form_name == "frm_NewCustomer" || form_name == "frm_ModifyCustomer") ======
	
	else if (form_name == "frm_ModifyAdmin")
	{
		//alert("pass = " + formVars["txt_Password"])
		if ( !isNotEmpty(formVars["txt_Password"]) )
		{
			message += "\n\n Password cannot be empty.";
			errorOccurred = true;		
		}		
		else if (formVars["txt_Password"] != formVars["txt_ConfirmPassword"])
		{
			message += "\n\nPasswords do not match.";
			errorOccurred = true;
			
		}
		
	}	// end else if (form_name == "frm_ModifyAdmin") ===========================
	
	else if (form_name == "frm_StandardPrice")
	{
		//alert("out");
		//alert(formVars["Single_PriceID"]);
		if (formVars["Single_PriceID"] == "-1")
		{
//			alert("");
			//-- checking all records -------------------
			//-- required field -------------------------			
			SubMessage = "";
			SubError = false;
			for(var i=0; i<ThisForm.elements["PriceID"].length; i++  )
			{				
				if ( ThisForm.elements["PriceID"][i].checked)
				{
					
					var pid = ThisForm.elements["PriceID"][i].value;
					
					if ( !isNotEmpty(formVars["suburb"+pid]) )
					{
						SubMessage += "\n - " + pid + ": Suburb ";
						SubError = true;		
					}					
					if ( !isNotEmpty(formVars["city_price"+pid]) )
					{
						SubMessage += "\n - " + pid + ": City Price ";
						SubError = true;		
					}								
					if ( !isNotEmpty(formVars["airport_price"+pid]) )
					{
						SubMessage += "\n - " + pid + ": Airport Price ";
						SubError = true;		
					}												
				}						
					
			}
			if( SubError )
			{
				message += "\n\nPlease fill in all required fields: " + SubMessage;
				errorOccurred = true;	
			}
			
			//-- checking price -------------------
			SubMessage = "";
			SubError = false;
			for(var i=0; i<ThisForm.elements["PriceID"].length; i++  )
			{				
				if ( ThisForm.elements["PriceID"][i].checked)
				{
					
					var pid = ThisForm.elements["PriceID"][i].value;
					
					if ( !isPosNumber(formVars["city_price"+pid]) )
					{
						SubMessage += "\n - " + pid + ": City Price ";
						SubError = true;		
															
					}
					if ( !isPosNumber(formVars["airport_price"+pid]) )
					{
						SubMessage += "\n - " + pid + ": Airport Price ";
						SubError = true;		
													
					}
				}						
					
			}
			if( SubError )
			{
				message += "\n\nPrice must be the positive number: " + SubMessage;
				errorOccurred = true;	
			}
		}		
		else
		{
			//-- checking single one record -------------------
			//-- validate required field -----------------
			SubMessage = "";
			SubError = false;
			var pid = formVars["Single_PriceID"];
			if ( !isNotEmpty(formVars["suburb"+pid]) )
			{
				SubMessage += "\n - " + pid + ": Suburb ";
				SubError = true;		
			}					
			if ( !isNotEmpty(formVars["city_price"+pid]) )
			{
				SubMessage += "\n - " + pid + ": City Price ";
				SubError = true;		
			}								
			if ( !isNotEmpty(formVars["airport_price"+pid]) )
			{
				SubMessage += "\n - " + pid + ": Airport Price ";
				SubError = true;		
			}							
			if( SubError )
			{
				message += "\n\nPlease fill in all required fields: " + SubMessage;
				errorOccurred = true;	
			}
			
			//-- validate price ----------------------------
			SubMessage = "";
			SubError = false;
			//if ( isNotEmpty(formVars["city_price"+pid]) )
			//{
				if ( !isPosNumber(formVars["city_price"+pid]) )
				{
					SubMessage += "\n - " + pid + ": City Price ";
					SubError = true;		
				}									
			//}
			
				if ( !isPosNumber(formVars["airport_price"+pid]) )
				{
					SubMessage += "\n - " + pid + ": Airport Price ";
					SubError = true;		
				}							
			
			if( SubError )
			{
				message += "\n\nPrice must be the positive number: " + SubMessage;
				errorOccurred = true;	
			}
			
		}
			
		
		
	} // end else if (form_name == "frm_StandardPrice")
	else if (form_name == "frm_Options")
	{
		//alert(form_name);
		//-- checking required field ---------------------
		SubMessage = "";
		SubError = false;
		for(var i=0; i<ThisForm.elements["OptionID"].length; i++  )
		{				
			
			if ( ThisForm.elements["OptionID"][i].checked)
			{				
				var oid = ThisForm.elements["OptionID"][i].value;
				formVars["txt_value"+oid] = formVars["txt_value"+oid].replace(/ /g, "");
				if ( !isNotEmpty(formVars["txt_value"+oid]) )
				{
					SubMessage += "\n - ID: " + oid;
					SubError = true;							
				}						
			}			
		}
		if( SubError )
		{
			message += "\n\nPlease fill in all required fields: " + SubMessage;
			errorOccurred = true;	
		}		
		
		//-- checking float format ---------------------
		SubMessage = "";
		SubError = false;
		for(var i=0; i<ThisForm.elements["OptionID"].length; i++  )
		{				
			if ( ThisForm.elements["OptionID"][i].checked)
			{
				var oid = ThisForm.elements["OptionID"][i].value;
				//alert(formVars["valid"+oid]);
				if (formVars["valid"+oid] == "float")
				{
					if ( !isPosNumber(formVars["txt_value"+oid]) )
					{
						SubMessage += "\n - Must be the postive number, ID: " + oid;
						SubError = true;							
					}						
				}
				else if (formVars["valid"+oid] == "integer")
				{
					if ( !isPosInteger(formVars["txt_value"+oid]) )
					{
						SubMessage += "\n - Must be the postive integer, ID: " + oid;
						SubError = true;							
					}						
				}
				else if (formVars["valid"+oid] == "time")
				{
					if ( !isTime(formVars["txt_value"+oid]) )
					{
						SubMessage += "\n - Must be the valid time, ID: " + oid;
						SubError = true;							
					}						
				}
				else if (formVars["valid"+oid] == "float, percent")
				{
					var str_tmp = formVars["txt_value"+oid].replace(/%/, "");
					if ( !isPosNumber(str_tmp) || !isNotEmpty(str_tmp) )
					{
						SubMessage += "\n - Must be a number or percentage, ID: " + oid;
						SubError = true;							
					}						
				}			
				
			}			
		}
		if( SubError )
		{
			message += "\n\nFollow fields have invalid format: " + SubMessage;
			errorOccurred = true;	
		}		
		
	} // end else if (form_name == "frm_Options")
	
  
  if( errorOccurred )
	{
		alert(message);				
//		document.getElementById("Error_Msg_Area").innerHTML = message;
	}
	
	return !errorOccurred;	
	
}


//==========================================================

// validates that the field value string has one or more characters in it
function isNotEmpty(elem) 
{
	var str = elem;
  var re = /.+/;
  if(!str.match(re)) 
		return false;
  else
    return true;   
}
   
//validates that the entry is a positive or negative number
function isNumber(elem) 
{
	var str = elem;
  var re = /^[-]?\d*\.?\d*$/;
  str = str.toString( );
  if (!str.match(re))
		return false;
  else
    return true;
}

//validates that the entry is a positive number
function isPosNumber(elem) 
{
	var str = elem;
  var re = /^[+]?\d*\.?\d*$/;
  str = str.toString( );
  if (!str.match(re))
		return false;
  else
    return true;
}

//validates that the entry is positive interger
function isPosInteger(elem) 
{
	var str = elem;
	str =	str.replace(/ /g, "");
  var re = /^\d*$/;
  str = str.toString();
  if (!str.match(re)) 
		return false;
  else
    return true;
}
   
   
// validates that the entry is formatted as an email address
function isEMailAddr(elem) 
{
	var str = elem;
  var re = /^[\w-]+(\.[\w-]+)*@([\w-]+\.)+[a-zA-Z]{2,7}$/;

  if (!str.match(re)) 
		return false;
  else 
		return true;
			    
}

function isTime(elem)
{
	var str = elem;
  
	// delete all space in a string. 'g' allow function to replace all space, 
	// without it, the function will only replace the first occurrence.
	str =	str.replace(/ /g, "").toLowerCase();	
  var re =	/^\d{1,2}:\d{2}(pm|am){0,1}$/
	
	if (!str.match(re)) 
		return false;
		
	if (str.length == 7)
	{		
		if ( str.substr(0,2) > 12 )
			return false;		
			
		if ( str.substr(3,2) > 59 )
			return false;					
	}
	else if (str.length == 6)
	{
		if ( str.substr(2,2) > 59 )
			return false;							
	}		
	else if (str.length == 5)
	{
		if ( str.substr(0,2) > 23 )
			return false;		
		if ( str.substr(3,2) > 59 )
			return false;					
	}
	else if (str.length == 4)
	{
		if ( str.substr(2,2) > 59 )
			return false;									
	}	
  
	return true;
	
}

// 0 = no error
// 1 = Error: Date is larger then the Days in a month
// 2 = Error: Year of Booking is over the maximum booking period
// 3 = Error: Booking Date is before today
function isCorrect_Date(y, m, d) 
{
	//-- Check Dates -------------------------------------------
	var DaysOfMonth = 31;
	//alert(m);
	switch (m)
	{		
		case 1:
			if ( (y%4) == 0 )
				DaysOfMonth = 29;
			else
				DaysOfMonth = 28;
			break;
		
		case 3: case 5: case 8: case 10: //month 4, 6, 9, 11
			DaysOfMonth = 30;
			break;
			
		default:												// month 1, 3, 5, 7, 8, 10, 12
			DaysOfMonth = 31;
	}
	
	if (d > DaysOfMonth)
		return 1;
	
	//-- Check Years --------------------------------------
	var current_datetime = new Date();	
	if (y > current_datetime.getFullYear()+MaxYearRange)
		return 2;
	
	//-- Check Range --------------------------------------
	var current_date = new Date(current_datetime.getFullYear(), current_datetime.getMonth(), current_datetime.getDate());
	var input_date = new Date(y, m, d);		
	if (input_date < current_date)
		return 3;

	return 0;
}

//=================================================================
function confirm_delete()
{
  var	result = window.confirm("Are you sure to delete these records");
	
	return result;
	
}


