//constants for season dates need updating yearly!

var cdtOpenDate = "March 1, 2005";
var cdtCloseDate = "Nov 30, 2005";
var cHighSeasonDates = [["March 25, 2005","April 3, 2005"],["April 29, 2005","May 2, 2005"],["May 27, 2005","June 5, 2005"],["July 22, 2005","September 4, 2005"]]

function checkAvailabilityForm(theForm){
	var msg="";
	var caravandates = document.getElementById('caravandates');
	
	if(caravandates.className=='hide'){	
		//validation for pitches
		var dtStartDate = theForm.availabilityarrivalmonth.options[theForm.availabilityarrivalmonth.selectedIndex].value + "/" + theForm.availabilityarrivalday.value + "/" + theForm.availabilityarrivalyear.value;
		var dtEndDate = theForm.availabilitydeparturemonth.options[theForm.availabilitydeparturemonth.selectedIndex].value + "/" + theForm.availabilitydepartureday.value + "/" + theForm.availabilitydepartureyear.value;

		if (!isValidDate(dtStartDate)) msg+="Your arrival date is not a valid date.\n";
		if (!isValidDate(dtEndDate)) msg+="Your departure date is not a valid date.\n";
		if (theForm.availabilitypitchtype.options[theForm.availabilitypitchtype.selectedIndex].value=="") msg+="Please select the type of pitch you would like.\n";
	}
	else{
		//validation for hire caravans
		if (theForm.hcavailabilitynumberofnights.options[theForm.hcavailabilitynumberofnights.options.selectedIndex].value=='') {msg+="Your must choose a number of nights .\n";theForm.hcavailabilitynumberofnights.focus();}
		if (theForm.hcavailabilitydeparturedate.options[theForm.hcavailabilitydeparturedate.options.selectedIndex].value=='') {msg+="Your must choose a departure date .\n";theForm.hcavailabilitydeparturedate.focus();}
		
	}
	
	
	if (msg!=""){
		alert(msg);
		return false;
	}
	return true;
}

//adds iDays to the current start date of search
function moveDate(iDays){
	//get querystring and replace any existing value for dateoffset which will be last item in querystring
	var qstring = document.location.search;
	var i;
	var bDateOffsetFound = false;
	
	//loop qstring items and replace dateoffset if present
	var qstringArray = qstring.split("&");
	qstring = "";
	
	for(i=0;i<qstringArray.length;i++){
		
		var keyValueArray = qstringArray[i].split("=");

		//if one already exists then add new one
		if (keyValueArray[0] == "dateoffset"){
			keyValueArray[1] = parseInt(keyValueArray[1]) + parseInt(iDays);
			bDateOffsetFound = true;
		}
		if (i!=0){
			qstring += "&";
		}
		qstring += keyValueArray[0] + "=" + keyValueArray[1]
	}
	
	//if not dateoffset value then add one
	if (!bDateOffsetFound){
		qstring += "&dateoffset=" + iDays;
	}
	
	//build new url
	var sNewUrl = document.location.protocol + "//" + document.location.hostname + document.location.pathname + qstring;
	
	//redirect
	document.location.href=sNewUrl;
	
}

function showhideDates(strSelectedValue,theForm){
	//shows and hides dates depending on which type of accommodation is selected
	var pitchdates = document.getElementById('pitchdates');
	var caravandates = document.getElementById('caravandates');

	switch(strSelectedValue){
		case 'CP18ft':
		case 'CP19ft':
		case 'CP20ft':		
		case 'CP23ft':
		case 'CP24ft':		
		case 'CP26ft':
		case 'TP2-4':
		case 'TP5-8':
			pitchdates.className='show';
			caravandates.className='hide';		
			break;
		case 'HC2':
		case 'HC3':
			caravandates.className='show';
			pitchdates.className='hide';
			break;
		default:
			caravandates.className='hide';
			pitchdates.className='hide';
			break;
	}
	
	if(caravandates.className=='hide'){
		//reset drop downs
		theForm.hcavailabilitynumberofnights.options.selectedIndex=0;
		theForm.hcavailabilitydeparturemonth.options.selectedIndex=0;
		theForm.hcavailabilitydeparturedate.options.length=1;
		theForm.hcavailabilitydeparturedate.options[0].text = "--";	
	}

}

function populateDateControls(theForm){
	//populates the date dropdowns
	
	//do pitch dates
	var dtCurrentDate = new Date();
	var iNumNights = 7;
	var dtNextWeekDate = dateAdd(dtCurrentDate, "D", iNumNights);
	populateDaysControl(theForm.availabilityarrivalday,dtCurrentDate);
	populateDaysControl(theForm.availabilitydepartureday,dtNextWeekDate);
	
	populateMonthsControl(theForm.availabilityarrivalmonth,dtCurrentDate);
	populateMonthsControl(theForm.availabilitydeparturemonth,dtNextWeekDate);
	
	populateYearsControl(theForm.availabilityarrivalyear,dtCurrentDate);
	populateYearsControl(theForm.availabilitydepartureyear,dtNextWeekDate);
	
	populateNightsControl(theForm.availabilitynumberofnights,iNumNights);
	
	//do hire caravan dates
	populateHCNightsControl(theForm.hcavailabilitynumberofnights);
	
	populateHCMonthControl(theForm.hcavailabilitydeparturemonth,dtCurrentDate);
	
	//loop querystring looking for availabilitypitchtype value
	var i;
	var sAvailabilityPitchType = '';
	var qstringArray = document.location.search.split("&");
	
	for(i=0;i<qstringArray.length;i++){
		var keyValueArray = qstringArray[i].split("=");
		
		//if one already exists then add new one
		if (keyValueArray[0] == "availabilitypitchtype"){
			sAvailabilityPitchType = keyValueArray[1];
		}
	}

	
	//select pitch type if one selected on previous page
	for(i=0;i<theForm.availabilitypitchtype.options.length;i++){
		if (theForm.availabilitypitchtype.options[i].value==sAvailabilityPitchType&&sAvailabilityPitchType!=''){
			theForm.availabilitypitchtype.options.selectedIndex = i;
			showhideDates(sAvailabilityPitchType,theForm);
		}
	}
	
}

function populateNightsControl(theControl,iSelectedNumNights){
	var iNumDays = 30;
	var i;
	theControl.options.length = iNumDays;
	for(i=0;i<iNumDays;i++){
		theControl.options[i].text = i+1;
		theControl.options[i].value = i+1;
		if (i % 2==1) theControl.options[i].className ='alt';
	}
	theControl.options.selectedIndex = iSelectedNumNights-1;	
}

function populateDaysControl(theControl,selectedDate){
	var iNumDays = 31;
	var i;
	theControl.options.length = iNumDays;
	for(i=0;i<iNumDays;i++){
		theControl.options[i].text = i+1;
		theControl.options[i].value = i+1;
		if (i % 2==1) theControl.options[i].className ='alt';
	}
	theControl.options.selectedIndex = selectedDate.getDate(selectedDate)-1;
}

function populateMonthsControl(theControl,selectedDate){
	var iNumMonths = 12;
	var i;
	theControl.options.length = iNumMonths;
	for(i=0;i<iNumMonths;i++){
		theControl.options[i].text = getShortMonthFromNumber(i);
		theControl.options[i].value = i+1;
		if (i % 2==1) theControl.options[i].className ='alt';
	}
	theControl.options.selectedIndex = selectedDate.getMonth();
}

function populateYearsControl(theControl,selectedDate){
	var iNumYears = 2;
	var i;
	theControl.options.length = iNumYears;
	for(i=0;i<iNumYears;i++){
		theControl.options[i].text = selectedDate.getFullYear()+i;
		theControl.options[i].value = selectedDate.getFullYear()+i;
		if (i % 2==1) theControl.options[i].className ='alt';
	}
	theControl.options.selectedIndex = 0;
}

function populateHCNightsControl(theControl){
	theControl.options.length = 7;
	theControl.options[0].text = "Please choose";
	theControl.options[0].value = "";
	theControl.options[1].text = "3";
	theControl.options[1].value = "3";
	theControl.options[2].text = "4";
	theControl.options[2].value = "4";
	theControl.options[3].text = "7";
	theControl.options[3].value = "7";	
	theControl.options[4].text = "10";
	theControl.options[4].value = "10";
	theControl.options[5].text = "11";
	theControl.options[5].value = "11";
	theControl.options[6].text = "14";
	theControl.options[6].value = "14";						
}

// functions for hire caravan date picker
function populateHCMonthControl(theControl,selectedDate){
	var iNumMonths = 12;
	var i;
	var ii = 1;
	selectedDate.setDate(1);
	
	theControl.options.length = 1;
	theControl.options[0].text = "Please choose";
	theControl.options[0].value = "";
	
	for(i=0;i<iNumMonths;i++){

		if (!isClosedSeason(selectedDate)){
			var objOption = new Option();
			objOption.text = getShortMonthFromNumber(selectedDate.getMonth()) + " " + selectedDate.getFullYear();				
			objOption.value = (selectedDate.getMonth() + 1) + " " + selectedDate.getFullYear();
			if (ii % 2==1) objOption.className ='alt';			
			theControl.options[ii] = objOption;
			ii++;
		}
		
		if (selectedDate.getMonth() < 11){
			selectedDate.setMonth(selectedDate.getMonth()+1);
		}
		else{
			selectedDate.setMonth(0);
			selectedDate.setYear(selectedDate.getFullYear()+1);
		}
		
	}
	//theControl.options.length = ii;
}

function chageHCDates(theForm){
	//do nothing if "please choose" is selected for either control
	var theControl = theForm.hcavailabilitydeparturedate;
	
	if (theForm.hcavailabilitynumberofnights.value!=''&&theForm.hcavailabilitydeparturemonth.value!=''){
		var intnights = parseInt(theForm.hcavailabilitynumberofnights.value);
		var intmonth = parseInt(theForm.hcavailabilitydeparturemonth.value.split(" ")[0])-1;

		var intyear = parseInt(theForm.hcavailabilitydeparturemonth.value.split(" ")[1]);
		var weekdaysarray;
		
		//fill with dates depedant on number of nights and month/year selected
		
		//get possible weekdays for the choosen number of nights
		switch(intnights){
			case 3:
				weekdaysarray = new Array('5')
				break;
			case 4:
				weekdaysarray = new Array('1')
				break;
			case 7:
				weekdaysarray = new Array('1','5','6')
				break;
			case 10:
				weekdaysarray = new Array('5')
				break;
			case 11:
				weekdaysarray = new Array('1')
				break;
			case 14:
				weekdaysarray = new Array('1','5','6')
				break;
		}
		theControl.options.length = 31;
		
		//loop this month and create dates
		var dtCurrentDate = new Date(intyear,intmonth,1);
		var i = 0;
		var dtCurrentEndDate;

		
		while(dtCurrentDate.getMonth() == intmonth){
			dtCurrentEndDate = dateAdd(dtCurrentDate, "D", intnights)
			//check if dtCurrentDate is a weekday contained in weekdaysarray
			if (arrayContains(weekdaysarray,dtCurrentDate.getDay())){
				
				//check if off season date
				if (!isClosedSeason(dtCurrentEndDate)){
					//check if peak season
					if ((isPeakSeason(dtCurrentDate)&&dtCurrentDate.getDay()==6)||!isPeakSeason(dtCurrentDate)){
						theControl.options[i].text = getShortWeekDayFromNumber(dtCurrentDate.getDay()) + " " + dtCurrentDate.getDate() + " " + getShortMonthFromNumber(dtCurrentDate.getMonth()) + " " + dtCurrentDate.getFullYear();
						theControl.options[i].value = dtCurrentDate.getFullYear().toString() + "-" + dtCurrentDate.getMonth().toString() + "-" + dtCurrentDate.getDate().toString();
						if (i % 2==1) theControl.options[i].className ='alt';	
						i++;
					}
				}
				
			}
			dtCurrentDate = dateAdd(dtCurrentDate, "D", 1);
			
		}
		//no dates created so show error
		
		if (i==0){
			theControl.options[i].text = "7 night only during peak season";
			theControl.options[i].value = "";
			i++;
		}
		theControl.options.length = i;
		
	}
}

function arrayContains(varray,vobject){
	var i;
	var blnReturn = false;

	for(i=0;i<varray.length;i++){
		if (varray[i]==vobject){
			blnReturn = true;
			break;
		}
	}
	
	return 	blnReturn;
}

//functions for peak season and closed season

function isClosedSeason(theDate){
	var blnIsClose = true;
	var dtOpenDate =  new Date(cdtOpenDate);
	var dtCloseDate =  new Date(cdtCloseDate);

	//assuming open close dates are the same for any year
	//so update year of dtOpenDate & dtCloseDate to be year of theDate
	dtOpenDate.setFullYear(theDate.getFullYear());
	dtCloseDate.setFullYear(theDate.getFullYear());

	if (theDate >= dtOpenDate && theDate <= dtCloseDate){
		blnIsClose = false;
	}
	return blnIsClose;
}

function isPeakSeason(theDate){
	var i;
	var blnIsPeak = false;
	var dtStart;
	var dtEnd;

	for(i=0;i<cHighSeasonDates.length;i++){
		//get dates
		dtStart = new Date(cHighSeasonDates[i][0]);
		dtEnd = new Date(cHighSeasonDates[i][1]);
		//assuming peak dates are the same for any year
		//so update year of dtOpenDate & dtCloseDate to be year of theDate
		dtStart.setFullYear(theDate.getFullYear());
		dtEnd.setFullYear(theDate.getFullYear());	

		if(theDate >= dtStart && theDate <= dtEnd){
			blnIsPeak=true;
			break;
		}
	}
	return blnIsPeak;	
}

function getShortWeekDayFromNumber(iWeekDayNumber){
	switch(iWeekDayNumber){
		case 0:
			return "Sun";
		case 1:
			return "Mon";
		case 2:
			return "Tue";
		case 3:
			return "Wed";
		case 4: 
			return "Thu";
		case 5:
			return "Fri";
		case 6:
			return "Sat";
	}
	return "Day out of range 1-6";
}

function getShortMonthFromNumber(iMonthNumber){
	switch(iMonthNumber){
		case 0:
			return "Jan";
			break;
		case 1:
			return "Feb";
			break;
		case 2:
			return "Mar";
			break;
		case 3:
			return "Apr";
			break;
		case 4:
			return "May";
			break;
		case 5:
			return "Jun";
			break;
		case 6:
			return "Jul";
			break;
		case 7:
			return "Aug";
			break;
		case 8:
			return "Sep";
			break;
		case 9:
			return "Oct";
			break;
		case 10:
			return "Nov";
			break;
		case 11:
			return "Dec";
			break;
	}
	return "Month out of range 0-11";
}

function changeStartDate(theForm){
	//changes the end date
	updateEndDate(theForm);
}

function changeEndDate(theForm){
	//changes the nights
	updateStartDate(theForm);
}

function changeNights(theForm){
	//change the end date
	updateEndDate(theForm);	
}

function updateNights(theForm){
	var intnumnights = DateDiff(theForm.availabilityarrivalday.value + " " + theForm.availabilityarrivalmonth.options[theForm.availabilityarrivalmonth.selectedIndex].text + " " + theForm.availabilityarrivalyear.value,theForm.availabilitydepartureday.value + " " + theForm.availabilitydeparturemonth.options[theForm.availabilitydeparturemonth.selectedIndex].text + " " + theForm.availabilitydepartureyear.value,"d",1);
	theForm.availabilitynumberofnights.selectedIndex = intnumnights-1;
}

function updateEndDate(theForm){
	//change start date from new end date / nights
	var startDate = theForm.availabilityarrivalday.value + " " + theForm.availabilityarrivalmonth.options[theForm.availabilityarrivalmonth.selectedIndex].text + " " + theForm.availabilityarrivalyear.value;
	var intnights = theForm.availabilitynumberofnights.value;
	var newendDate = dateAdd( startDate, "D", intnights );
	theForm.availabilitydepartureday.selectedIndex = newendDate.getDate()-1;
	theForm.availabilitydeparturemonth.selectedIndex = newendDate.getMonth();
	var today = new Date();
	theForm.availabilitydepartureyear.selectedIndex = newendDate.getFullYear()-today.getFullYear();
}

function updateStartDate(theForm){
	//change start date from new end date / nights
	var endDate = theForm.availabilitydepartureday.value + " " + theForm.availabilitydeparturemonth.options[theForm.availabilitydeparturemonth.selectedIndex].text + " " + theForm.availabilitydepartureyear.value;
	var intnights = theForm.availabilitynumberofnights.value;
	var newstartDate = dateAdd( endDate, "D", -intnights );
	theForm.availabilityarrivalday.selectedIndex = newstartDate.getDate()-1;
	theForm.availabilityarrivalmonth.selectedIndex = newstartDate.getMonth();
	var today = new Date();
	theForm.availabilityarrivalyear.selectedIndex = newstartDate.getFullYear()-today.getFullYear();
}


function dateAdd( start, interval, number ) {
    // Create 3 error messages, 1 for each argument. 
    var startMsg = "Sorry the start parameter of the dateAdd function\n"
		startMsg += start+"\n\n"
        startMsg += "must be a valid date format.\n\n"
        startMsg += "Please try again." ;
		
    var intervalMsg = "Sorry the dateAdd function only accepts\n"
        intervalMsg += "d, h, m OR s intervals.\n\n"
        intervalMsg += "Please try again." ;

    var numberMsg = "Sorry the number parameter of the dateAdd function\n"
        numberMsg += "must be numeric.\n\n"
        numberMsg += "Please try again." ;
		
    // get the milliseconds for this Date object. 
    var buffer = Date.parse( start ) ;
	
    // check that the start parameter is a valid Date. 
    if ( isNaN (buffer) ) {
        alert( startMsg ) ;
        return null ;
    }
	
    // check that an interval parameter was not numeric. 
    if ( interval.charAt == 'undefined' ) {
        // the user specified an incorrect interval, handle the error. 
        alert( intervalMsg ) ;
        return null ;
    }

    // check that the number parameter is numeric. 
    if ( isNaN ( number ) )	{
        alert( numberMsg ) ;
        return null ;
    }

    // so far, so good...
    //
    // what kind of add to do? 
    switch (interval.charAt(0))
    {
        case 'd': case 'D': 
            number *= 24 ; // days to hours
            // fall through! 
        case 'h': case 'H':
            number *= 60 ; // hours to minutes
            // fall through! 
        case 'm': case 'M':
            number *= 60 ; // minutes to seconds
            // fall through! 
        case 's': case 'S':
            number *= 1000 ; // seconds to milliseconds
            break ;
        default:
        // If we get to here then the interval parameter
        // didn't meet the d,h,m,s criteria.  Handle
        // the error. 		
        alert(intervalMsg) ;
        return null ;
    }
    return new Date( buffer + number ) ;
}



function DateDiff( start, end, interval, rounding ) {

    var iOut = 0;
    
    // Create 2 error messages, 1 for each argument. 
    var startMsg = "Check the Start Date and End Date\n"
        startMsg += "must be a valid date format.\n\n"
        startMsg += "Please try again." ;
		
    var intervalMsg = "Sorry the dateAdd function only accepts\n"
        intervalMsg += "d, h, m OR s intervals.\n\n"
        intervalMsg += "Please try again." ;

    var bufferA = Date.parse( start ) ;
    var bufferB = Date.parse( end ) ;
    	
    // check that the start parameter is a valid Date. 
    if ( isNaN (bufferA) || isNaN (bufferB) ) {
        alert( startMsg ) ;
        return null ;
    }
	
    // check that an interval parameter was not numeric. 
    if ( interval.charAt == 'undefined' ) {
        // the user specified an incorrect interval, handle the error. 
        alert( intervalMsg ) ;
        return null ;
    }
    
    var number = bufferB-bufferA ;
    
    // what kind of add to do? 
    switch (interval.charAt(0))
    {
        case 'd': case 'D': 
            iOut = parseInt(number / 86400000) ;
            if(rounding) iOut += parseInt((number % 86400000)/43200001) ;
            break ;
        case 'h': case 'H':
            iOut = parseInt(number / 3600000 ) ;
            if(rounding) iOut += parseInt((number % 3600000)/1800001) ;
            break ;
        case 'm': case 'M':
            iOut = parseInt(number / 60000 ) ;
            if(rounding) iOut += parseInt((number % 60000)/30001) ;
            break ;
        case 's': case 'S':
            iOut = parseInt(number / 1000 ) ;
            if(rounding) iOut += parseInt((number % 1000)/501) ;
            break ;
        default:
        // If we get to here then the interval parameter
        // didn't meet the d,h,m,s criteria.  Handle
        // the error. 		
        alert(intervalMsg) ;
        return null ;
    }
    
    return iOut ;
}

//popup functions
function popup(url, title, width, height, scroll) {
	var s = 'menubar=no,toolbar=no,location=yes,resizable=yes,status=yes,dependent=yes'
	s += ',scrollbars=' + scroll
	s += ',width=' + width + ',height=' + height;
	s += ',top=' + (screen.availHeight - height) / 2 + ',left=' + (screen.availWidth - width) / 2;

	//close existing window
	try {
		if (navigator.newwindow && navigator.newwindow.close) navigator.newwindow.close();
	}
	catch(e) {}
	
	//save new window object in navigator object and activate
	navigator.newwindow = self.open(url, title, s);
	navigator.newwindow.focus();
	
	return false;
}

//popup functions
function popupMap(url, title, width, height, scroll) {
	var s = 'menubar=no,toolbar=no,location=yes,resizable=yes,status=yes,dependent=yes'
	s += ',scrollbars=' + scroll
	s += ',width=' + width + ',height=' + height;
	s += ',top=' + (screen.availHeight - height) / 2 + ',left=' + (screen.availWidth - width) / 2;

	//close existing window
	try {
		if (navigator.newwindow && navigator.newwindow.close) navigator.newwindow.close();
	}
	catch(e) {}
	
	//save new window object in navigator object and activate
	navigator.newwindow = self.open(url, title, s);
	navigator.newwindow.focus();
}

function popupPitchSizeGuide(strTarget) {
	return popup('', strTarget, 600, 400, 'yes')
}

function CloseWindow() {
	window.close();
	navigator.newwindow = null;
	if (window.opener)
		if (!window.opener.closed)
			window.opener.focus();
}

function isValidDate(dateStr) {


// Checks for the following valid date formats:
// MM/DD/YY   MM/DD/YYYY   MM-DD-YY   MM-DD-YYYY
// Also separates date into month, day, and year variables

var datePat = /^(\d{1,2})(\/|-)(\d{1,2})\2(\d{2}|\d{4})$/;

// To require a 4 digit year entry, use this line instead:
// var datePat = /^(\d{1,2})(\/|-)(\d{1,2})\2(\d{4})$/;

var matchArray = dateStr.match(datePat); // is the format ok?
if (matchArray == null) {
alert("Date is not in a valid format.")
return false;
}
month = matchArray[1]; // parse date into variables
day = matchArray[3];
year = matchArray[4];
if (month < 1 || month > 12) { // check month range
alert("Month must be between 1 and 12.");
return false;
}
if (day < 1 || day > 31) {
alert("Day must be between 1 and 31.");
return false;
}
if ((month==4 || month==6 || month==9 || month==11) && day==31) {
alert("Month "+month+" doesn't have 31 days!")
return false
}
if (month == 2) { // check for february 29th
var isleap = (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0));
if (day>29 || (day==29 && !isleap)) {
alert("February " + year + " doesn't have " + day + " days!");
return false;
   }
}

return true;  // date is valid
}