/**
 * @author David Hollingworth - www.CTSWestCork.com
 *
 * Modification History
 * Version	Date		Author				Description		
 * 1.0					David Hollingworth	Original Version
 * 1.1		30/01/2009	David Hollingworth	Added functionality to differentiate days of the week
 *											Removed unused functions
 */
 
// For a more flexible event registration routine, see
// http://simon.incutio.com/archive/2004/05/26/addLoadEvent
window.onload = attachFormHandlers;

function attachFormHandlers()
{
  // Ensure we're working with a 'relatively' standards 
  // compliant browser
  if (document.getElementsByTagName)
  {
    var objForm = document.getElementsByTagName('bookingform');

    for (var iCounter=0; iCounter<objForm.length; iCounter++)
      objForm[iCounter].onsubmit = function(){return checkForm(this);}
  }
}

function checkForm(objForm)
{
  var arClass, bValid;
  var objField = objForm.getElementsByTagName('*');

  for (var iFieldCounter=0; iFieldCounter<objField.length; iFieldCounter++)
  {
    // Allow for multiple values being assigned to the class attribute
    arClass = objField[iFieldCounter].className.split(' ');
    for (var iClassCounter=0; iClassCounter<arClass.length; iClassCounter++)
    {
      switch (arClass[iClassCounter])
      {
        case 'string':
           bValid = isString(objField[iFieldCounter].value.replace(/^\s*|\s*$/g, ''));
           break;
        case 'number' :
           bValid = isNumber(objField[iFieldCounter].value);
           break;
        case 'email' :
           bValid = isEmail(objField[iFieldCounter].value);
             break;
        default:
           bValid = true;
      }

      if (bValid == false)
      {
        // If this field is invalid, leave the testing early,
        // and alert the visitor to this error
        alert('Please review the value you provided for ' + objField[iFieldCounter].name);
        objField[iFieldCounter].select();
        objField[iFieldCounter].focus();
        return false;
      }
    }
  }
  return true;
}

function isString(strValue)
{
  return (typeof strValue == 'string' && strValue != '' && isNaN(strValue));
}

function isNumber(strValue)
{
  return (!isNaN(strValue) && strValue != '');
}

function isEmail(strValue)
{
  var objRE = /^[\w-\.\']{1,}\@([\da-zA-Z-]{1,}\.){1,}[\da-zA-Z-]{2,}$/;

  return (strValue != '' && objRE.test(strValue));
}
 

//
// Special validation for the booking form to ensure everything is set-up OK
//
function aif_validate_booking(bform)
{

	var bValid = true;
	var errStr = "Please correct the following errors in your booking form before confirming your booking:\n\n";
	
	// 
	// Check that at least one person is travelling
	//
	var adults = document.getElementById("Adults").value;
	var children = document.getElementById("Children").value;
	var OAPS = document.getElementById("Oap").value;
	var students = document.getElementById("Students").value;
	
	//
	// Anything that's not a number set to 0
	//
	adults = isNaN(adults) ? 0 : adults;
	children = isNaN(children) ? 0 : children;
	OAPS = isNaN(OAPS) ? 0 : OAPS;
	students = isNaN(students) ? 0 : students;
	
	
	var travellers = adults + children + OAPS + students;
	
	if (travellers == 0)
	{
		errStr = errStr + "Please enter the number of people (adults, children, OAPs and students) who are travelling.\n";
		bValid = false;
	}
	
	//
	// Check an island has been selected
	//
	var island = document.getElementById("DepartureIsland");

	if (island.selectedIndex == -1)
	{
		errStr = errStr + "Please select the island you wish to travel to.\n";
		bValid = false;
	}
	
	//
	// Check departure and return dates and times have been selected
	//
	// alert("Checking dates");
	var d_day = document.getElementById("d_day");
	var d_month = document.getElementById("d_month");
	var d_year = document.getElementById("d_year");
	var r_day = document.getElementById("r_day");
	var r_month = document.getElementById("r_month");
	var r_year = document.getElementById("r_year");
	var d_sailtime = document.getElementById("d_sailtime");
	var r_sailtime = document.getElementById("r_sailtime");
	var tripType = document.getElementsByName("journey");	
	
	if (d_day.value == 0 || d_month.value == 0 || d_year.value == 0)
	{
		errStr = errStr + "Please select a valid departure date.\n";
		bValid = false;
	}
	if (d_sailtime.selectedIndex < 1)
	{
		errStr = errStr + "Please select a sailing time for your journey.\n";
		bValid = false;
	}
	
	//
	// If the trip type is a return then also test the return date and time
	//
	// alert("Checking return trip");
	if (tripType[1].checked == true)
	{
		if (r_day.value == 0 || r_month.value == 0 || r_year.value == 0)
		{
			errStr = errStr + "Please select a valid date for your return trip.\n";
			bValid = false;
		}
		if (r_sailtime.selectedIndex < 1)
		{
			errStr = errStr + "Please select a return sailing time.\n";
			bValid = false;
		}
	}
	
	//
	// Make sure we've chosen to include a bus journey
	//
	// alert("Checking bus transfer");
	var bus = document.getElementsByName("coachTransfer");
	var busSet = false;
	for (var i = 0; i < bus.length; i++)
	{
		if (bus[i].checked == true)
		{
			busSet = true;
		}
	}
	if (! busSet)
	{
		errStr = errStr + "Please select whether you need a bus transfer from Galway to / from the ferry terminal at Rossaveal.\n";
		bValid = false;
	}
	
	//
	// Check the contact details have been entered
	//
	// alert("Checking First Name");
	if (document.getElementById("FirstName").value == "")
	{
		errStr = errStr + "Please enter your first name.\n";
		bValid = false;
	}
	if (document.getElementById("LastName").value == "")
	{
		errStr = errStr + "Please enter your last name.\n";
		bValid = false;		
	}
	if (document.getElementById("EmailAddress").value == "")
	{
		errStr = errStr + "Please enter your email address.\n";
		bValid = false;		
	}
	
	if (!bValid)
	{
		alert(errStr);
	}
	
	//
	// Finally test the coack and sailing times
	//
	if (! check_coach_sailing())
	{
		bValid = false;
	}

	return(bValid);
}

//
// Function: check_coach_sailing()
// Description: Test to see if the user has selected the coach transfer that they haven't
// also chosen an XB sailing that doesn't have a coach ready to meet it.
//
function check_coach_sailing()
{
	var coachTransfer = document.getElementsByName("coachTransfer");
	var ret_value = true; // The return value	
	
	//
	// Has user selected a coach transfer?
	//
	if (coachTransfer[0].checked == true)
	{
		//
		// They have; so they're not allowd to book an XB sailing
		//
		var d_sailtime = document.getElementById("d_sailtime");
		var r_sailtime = document.getElementById("r_sailtime");
		var d_value = d_sailtime.options[d_sailtime.selectedIndex].text;
		var r_value = r_sailtime.options[r_sailtime.selectedIndex].text;
		
		// alert("d_value = " + d_value + " r_value = " + r_value);
		
		//
		// Test for saling times marked XB
		//
		if (d_value.search(/XB/) > 0)
		{
			alert("You have requested a coach transfer from Galway City centre; but you have selected a departure sailing " +
				  "that doesn't connect with a coach. Please reselect a departure sailing that is not marked 'XB'");
			ret_value = false;
		}

		if (r_value.search(/XB/) > 0)
		{
			alert("You have requested a coach transfer to Galway City centre; but you have selected a return sailing " +
				  "that doesn't connect with a coach. Please reselect a return sailing that is not marked 'XB'");
			ret_value = false;
		}
	}

	return(ret_value);
}
		
 
var depart_date = "";

function departure(){
    depart_date = this.date.print('d-M-y');
}

//
// Toggle the return sailing date & time information if the user
// only wants a single trip.
//
function toggleReturnTrip(evt){
    evt = (evt) ? evt : event;
    var target = (evt.target) ? evt.target : evt.srcElement;
    var block = document.getElementById("return");
    
    if (target.id == "returntrip") {
        block.style.display = "block";
    }
    else {
        block.style.display = "none";
    }
    
}

/*
 * Functions to control the sailing times. These vary according to the months of the year.
 * 
 * NB This has to be done by month AND by route for the live version
 * 
 */
 function setSail(triptype, selectedTime)
{
	var optionCount = 0; // Keep a count of the options in our select 
	
	//
	// Locate the select list that will display the sailing times	
	// depedant on whether this is an outbound or return trip
	//
	if (triptype == "departsail")
	{
		var sailChooser = document.getElementById("d_sailtime");
		var sailMonth = document.getElementById("d_month");
		var sailDay = document.getElementById("d_day");
	}
	else
	{
		var sailChooser = document.getElementById("r_sailtime");
		var sailMonth = document.getElementById("r_month");		
		var sailDay = document.getElementById("r_day");		
	}
	var selectedMonth = sailMonth.selectedIndex;	
	var selectedDay = sailDay.selectedIndex;
	
	if (selectedDay == 0 || selectedMonth == 0)
	{
		return;
	}
	
	// alert("Sailing on " + selectedDay + "/" + selectedMonth);
	
	//
	// Get the Island we're saling to / from. This helps us identify the route index
	//
	var selectedIsland = document.getElementById("DepartureIsland").selectedIndex;
	
	//
	// For the return trip add the number of routes in the  aif_sailings table / 2
	// to the selected island index to get the return sailing times.
	//
	// alert("selectedIsland = " + selectedIsland + " G_numRoutes = " + G_numRoutes);
	if (triptype != "departsail")
	{
		selectedIsland += G_numRoutes;
//		alert("Route number: " + selectedIsland);
	}
	
	//
	// Create the trip date from the month and day selected. This is used to check against start and end dates.
	//
	var today = new Date();
	var tripDate = new Date(today.getFullYear(), sailMonth.value - 1, sailDay.value);
	
	//
	// Set up the day of the week so we can check for sailings specific to this day
	//
	var tripDOW = tripDate.getDay();
	
	// Empty any previous settings
	sailChooser.options.length = 0;
	
	// Insert the first default value
	if (selectedTime == null)
	{
		sailChooser.options[optionCount] = new Option("Sailing time?", "", true, false);
	}
	else
	{
		sailChooser.options[optionCount] = new Option("Sailing time?", "", false, false);
	}
	optionCount++;
	
	//
	// Loop through the array of sailing dates selecting those that are valid
	// and setting up the select options
	//
	for (var i = 0; i < sailDb.length; i++)
	{

		if (sailDb[i].route != selectedIsland + 1)
		{
			continue;
		}

		//
		// Create date objects for the start and end dates of this sailing range
		//
		var startDate = sailDb[i].startdate.split(/-/);
		var endDate = sailDb[i].enddate.split(/-/);
		startDate = new Date(startDate[0], startDate[1] - 1, startDate[2]);
		endDate = new Date(endDate[0], endDate[1] - 1, endDate[2]);
		
		// alert("Start Date = " + startDate + " Trip date = " + tripDate + " End Date = " + endDate);
		//
		// Does our trip date fall between these start and end dates?
		//
		// alert("Sail Days for this trip = " + sailDb[i].saildays + ", Day search result = " + sailDb[i].saildays.search(tripDOW));
		if (tripDate >= startDate && tripDate <= endDate && sailDb[i].saildays.search(tripDOW) != -1)
		{
			// alert("Trip date in range " + tripDate + "DOW = " + tripDOW);
			//
			// Set the options
			//
			if (selectedTime == sailDb[i].id)
			{
				// alert("Setting selected option " + sailDb[i].sailtime);
				sailChooser.options[optionCount] = new Option(sailDb[i].sailtime, sailDb[i].id, true, true);
				optionCount++;
			}
			else
			{
				// alert("Setting unselected option " + sailDb[i].sailtime);
				sailChooser.options[optionCount] = new Option(sailDb[i].sailtime, sailDb[i].id);
				optionCount++;
			}
		}
		

	}
																																	
}

//
// Function changeMonth handles an onchange event on the month select field
//
function changeMonth(trip)
{
	var monthIndex = selMonth.selectedIndex;
	setSail(trip);
}

//
// Function changeIsland handles the refresh of sailing times if a new island is selected
//
function changeIsland()
{
	var departMonth = document.getElementById("d_month");
	var returnMonth = document.getElementById("r_month");
	
	//
	// If a month has been selected then change the sailing times
	// otherwise don't bother.
	//
	if (departMonth.selectedIndex > 0)
	{
		setSail("departsail");
	}
	if (returnMonth.selectedIndex > 0)
	{
		setSail("returnsail");
	}
}

//
// Function: clearbooking() - clears the booking form when users hits the reset button
//
function clearBooking()
{
	var myForm = document.getElementById("bookingform");
	alert("Clearing form");
	myForm.reset;
}

/*
 * Zapatec calendar routines start here
 */
 
var startDate;
var endDate;

function resetDates() {
	startDate = endDate = null;
}

function filterDates1(cal) {
	startDate = new Date(cal.date)
	startDate.setHours(0,0,0,0)	// used for compares without TIME
	/* If they haven't chosen an 
	end date before we'll set it to the same date as the start date This
	way if the user scrolls in the start date 5 months forward, they don't
	need to do it again for the end date.
	*/

	if (endDate == null) { 
		Zapatec.Calendar.setup({
			inputField     :    "r_calendar",
			button         :    "r_cal_toggler",  // What will trigger the popup of the calendar
			ifFormat       :    "%b %d, %Y",
			date           :     cal.date,
			showsTime      :     false,          //no time
			dateStatusFunc		:    disallowDateBefore, //the function to call
			onUpdate       :    filterDates2,
			weekNumbers	:	false
		});
	}
	
	var selectMonth = document.getElementById("d_month");
	selectMonth.selectedIndex = startDate.getMonth() + 1;
	var selectDay = document.getElementById("d_day");
	selectDay.selectedIndex = startDate.getDate();
	var selectYear = document.getElementById("d_year");
	selectYear.selectedIndex = (startDate.getFullYear() - 2009);

	setSail("departsail");	
}

function filterDates2(cal) {
	var date = cal.date;
	endDate = new Date(cal.date)
	endDate.setHours(0,0,0,0)	// used for compares without TIME
	
	var selectMonth = document.getElementById("r_month");
	selectMonth.selectedIndex = date.getMonth()  + 1;
	var selectDay = document.getElementById("r_day");
	selectDay.selectedIndex = date.getDate();
	var selectYear = document.getElementById("r_year");
	selectYear.selectedIndex = (date.getFullYear() - 2009);

	setSail("returnsail");
}

/*
* This functions return true to disallow a date
* and false to allow it.
*/


/* 
* Check-Out calendar allowed dates
* Check-Out date can not be BEFORE Check-In date
* Check-Out date can not be before today
*/
function disallowDateBefore(dateCheckOut) {

	dateCheckOut.setHours(0,0,0,0)
	if ((startDate != null) && startDate > dateCheckOut)
		// startDate is defined, make sure cal date is NOT before start date
		return true; 
	
	var now = new Date()
	now.setHours(0,0,0,0)
	if (dateCheckOut < now) 
		// check out date can not be befor today if startDate NOT defined
		return true;

	return false;
}

/* 
* Check-In date checking
* Check-In date can not be AFTER Check-Out date
* Check-In date can not be before today
*/
function disallowDateAfter(dateCheckIn) {

	dateCheckIn.setHours(0,0,0,0)
	if ((endDate != null) && dateCheckIn > endDate)
		// endDate defined, calendar date can NOT be after endDate
		return true;

	var now = new Date()
	now.setHours(0,0,0,0)

	if (dateCheckIn < now)
		// endDate NOT defined, calendar date can not be before today
		return true;

	return false;
}

/*
 * This is the Dreamweaver Javascript for validating individual form fields
 */

 function MM_validateForm(){ //v4.0
     if (document.getElementById) {
         var i, p, q, nm, test, num, min, max, errors = '', args = MM_validateForm.arguments;
         for (i = 0; i < (args.length - 2); i += 3) {
             test = args[i + 2];
             val = document.getElementById(args[i]);
             if (val) {
                 nm = val.name;
                 if ((val = val.value) != "") {
                     if (test.indexOf('isEmail') != -1) {
                         p = val.indexOf('@');
                         if (p < 1 || p == (val.length - 1)) 
                             errors += '- ' + nm + ' must contain an e-mail address.\n';
                     }
                     else 
                         if (test != 'R') {
                             num = parseFloat(val);
                             if (isNaN(val)) 
                                 errors += '- ' + nm + ' must contain a number.\n';
                             if (test.indexOf('inRange') != -1) {
                                 p = test.indexOf(':');
                                 min = test.substring(8, p);
                                 max = test.substring(p + 1);
                                 if (num < min || max < num) 
                                     errors += '- ' + nm + ' must contain a number between ' + min + ' and ' + max + '.\n';
                             }
                         }
                 }
                 else 
                     if (test.charAt(0) == 'R') 
                         errors += '- ' + nm + ' is required.\n';
             }
         }
         if (errors) 
             alert('The following error(s) occurred:\n' + errors);
         document.MM_returnValue = (errors == '');
     }
 }

