
var originalDurations = new Array();
var dbform ;
var startdate = new Date();
var daysinmonth = new Array(31,28,31,30,31,30,31,31,30,31,30,31);
var weekdays = new Array('Sun','Mon','Tue','Wed','Thu','Fri','Sat','Sun');


function changeboxes()
{
  var curform = document.getElementById('bookingForm');
  var currDate = new Date();
  var currDate1 = new Date();
  curform.dateRangeStart.value = formatDate(currDate1,"yyMMdd");
  currDate1.setYear(currDate1.getFullYear() + 2);
  curform.dateRangeEnd.value = formatDate(currDate1,"yyMMdd");

  var monthyear = curform.myMonths;
  while (monthyear.length > 0) {
    monthyear[monthyear.length-1] = null; 
  }

    //set limit future months to 12
  var latestDate = new Date();
  latestDate.setYear(latestDate.getFullYear() + 1);
  //latestDate.setMonth(05);
  	// block all popup cal dates before tommorrow
  	// format addDisabledDates(start, end)   as YYYY-MM-DD
  cal.addDisabledDates("1970-01-01", (currDate.getFullYear()+"-"+(currDate.getMonth()+1) +"-"+currDate.getDate() ));
  	// block all popup cal dates 1 year after today
  cal.addDisabledDates((latestDate.getFullYear()+"-"+(latestDate.getMonth()+1)+"-"+latestDate.getDate()), "2099-12-31");

  var newDate = new Date();
  newDate.setDate(1);
  var counter = 1;

  while (newDate.getFullYear() <= latestDate.getFullYear()) {
    if (newDate.getFullYear() == latestDate.getFullYear() && newDate.getMonth() == latestDate.getMonth()) {
       break;
    }
    newDate.setMonth(newDate.getMonth() + 1);
    counter++;
  }

  monthyear.length = counter + 1;
  for(var i = 0; i < counter + 1; i++) {

	var optionValue = formatDate(currDate,"NNN yyyy");
	var optionName = formatDate(currDate,"MM/yyyy");
    var month = currDate.getMonth();

	monthyear[i] = new Option(optionValue,optionName);

    normalMonths[i] = "('" + optionValue + "', '" + optionName + "')";

        
    if ((month == 11) && (newyearMonths.length == 0)) {
       newyearMonths[0] = "('" + optionValue + "', '" + optionName + "')";
    }
    if ((month == 0) && (newyearMonths.length > 0)) {
       newyearMonths[1] = "('" + optionValue + "', '" + optionName + "')";
    }

    currDate.setMonth(currDate.getMonth() + 1);
  }


  var durationSelect = curform.myDur;
  while (durationSelect.length > 0) {
    durationSelect[durationSelect.length-1] = null; 
  }

  var currDateNY1 = new Date();
  var currDateNY2 = new Date();
  currDateNY2.setYear(currDateNY2.getFullYear() + 1);

  // pre-load the duration Select
  durationSelect.length = 5;
  durationSelect[0] = new Option("Weekend (3 nights)*", "Weekend (3 nights)*");
  durationSelect[1] = new Option("Midweek (4 nights)*", "Midweek (4 nights)*");
  durationSelect[2] = new Option("1 Week (7 nights)", "1 Week (7 nights)");
  durationSelect[3] = new Option("2 Weeks (14 nights)", "2 Weeks (14 nights)");
  durationSelect[4] = new Option("3 Weeks (21 nights)", "3 Weeks (21 nights)");

}


function getDropDownValue(DDB){
	if (DDB == null)
		return null;
	if ("text|hidden" .indexOf(DDB.type)>=0)
		return DDB.value;
	var theValue = "";
	if (DDB.selectedIndex !=  - 1){
		theValue = DDB.options[DDB.selectedIndex].value;
	}
	return theValue;
}

function setDropDown (DDB, value) {
	if (DDB == null) return;

	if ((DDB.type != "select-one") && (DDB.type != "select-multiple")) return;

	for (var i = 0; i < DDB.options.length; i++) {
		if (DDB.options[i].value == value) {
			DDB.options[i].selected = true;
		} else {
			DDB.options[i].selected = false;
		}
	}
}

function populateDDBAry (DDB, selectedArray, validationFunction) {
	if (DDB == null) return;
	if (selectedArray == null) return;

	var curSel = getDropDownValue(DDB);

	while (0 < DDB.options.length) {
		DDB.options[(DDB.options.length - 1)] = null;
	}

	for (var i = 0, j = 0; i < selectedArray.length; i++) {
		var curItem = eval("new Array "+ selectedArray[i]);
		if ((typeof validationFunction != "function") || (validationFunction(curItem[1]))) {
			eval("DDB.options[j]=" + "new Option" + selectedArray[i]);
			j++;
		}
	}

	setDropDown(DDB, curSel);
}


	// removes the unwanted days from the duration drop down
function removeDuration(y,m,d)
{
  var curform = document.getElementById('bookingForm');
  var startDate = curform.startdate;
  setOriginalDurations();
  var selectElement = curform.myDur;
  var theDate = new Date(y,m-1,d,0,0,0);
  var theDoW = theDate.getDay();
  var days;
  
  // set the start date textbox
  startDate.value = formatDate(theDate,window.CP_dateFormat);

  if (theDoW == 1) { days = 3; }
  if (theDoW == 5) { days = 4; }
  
  for(i=0; i< selectElement.length; i++)
  {
    if (parseInt(selectElement[i].value) == days) { selectElement[i] = null; }
  }

}

function getOriginalDurations()
{
  var curform = document.getElementById('bookingForm');
  var selectElement = curform.myDur;
  for(i=0; i< selectElement.length; i++)
  {
    originalDurations[i] = new Array();
    originalDurations[i][0] = selectElement.options[i].text;
    originalDurations[i][1] = selectElement.options[i].value;
  }

}


function setOriginalDurations()
{
  var curform = document.getElementById('bookingForm');
  for(i=0; i< curform.myDur.length; i++)
  {
    curform.myDur[i] = null;
  }

  var selectElement = curform.myDur;
  for(i=0; i< originalDurations.length; i++)
  {
    selectElement[i] = new Option(originalDurations[i][0], originalDurations[i][1]);
  }
  
}
	// To toggle Mondays availability
function changeOptions(sel){
  if(sel.value.indexOf("Midweek") ==-1 ){			// This should be identical to the setting on the calendar page for Friday
    cal.setDisabledWeekDays(0,1,2,3,5,6);			// Allow Friday only (mon=0)
    durStay = sel.value.indexOf("Weekend") !=-1 && hide_season_Weekends ? "Weekend" : "";
  }else{
	cal.setDisabledWeekDays(1,2,3,4,5,6);			// Allow Monday only (mon=0)
	durStay = sel.value.indexOf("Midweek") !=-1 && hide_season_Midweeks ? "Midweek" : "";
  }
  changedates();
}

function changedates(initFlag) {
  var curform = document.getElementById('bookingForm');
  var myDurIdx = curform.myDur.selectedIndex;
  if (initFlag == null) initFlag = false;
  var monyr = curform.myMonths.options[curform.myMonths.selectedIndex].value;
  var dur = curform.myDur.options[curform.myDur.selectedIndex].value;
  var thedate = curform.myDays;
  var amdate = monyr.substring(0,2)+"/01/"+monyr.substring(3,9); // need american date format!
  var tdate = new Date(amdate);
  var yy = tdate.getFullYear();
  var mm = tdate.getMonth();
  var count = 0;
  var minDate = createDate(curform.dateRangeStart.value);
  var maxDate = createDate(curform.dateRangeEnd.value);

	// this is a leap year ?
  if (((yy % 4 == 0) && (yy % 100 != 0)) || (yy % 400 == 0)) daysinmonth[1] = 29;

  var selectedDay = getDropDownValue(thedate);

  while (thedate.length > 0) {
    thedate[thedate.length-1] = null; 
  }
  
  for (i=1; i<= daysinmonth[mm]; i++) {
    tdate.setYear(yy);
    tdate.setMonth(mm);
    tdate.setDate(i); 
 			// restrict date to the date object max
	if (tdate.getMonth() == 05 && tdate.getDate() > 26 && tdate.getFullYear() == 2099)
	{
			//Ignore these out of range dates
	}
	else
	{ 
		if ((tdate.getTime() >= minDate.getTime()) && (tdate.getTime() <= maxDate.getTime())) {
				// if Midweek and monday AND not during season
			if (myDurIdx == 1 && tdate.getDay() == 1 && !( durStay == "Midweek" &&  seasonMonths.indexOf(tdate.getMonth())!=-1) ){
					thedate[count++] = new Option(i+" "+weekdays[tdate.getDay()]+"",i);
			}
		  		// if Friday and not Midweek  AND not Weekend during season
			if (myDurIdx != 1 &&  tdate.getDay() == 5 && !( durStay == "Weekend" &&  seasonMonths.indexOf(tdate.getMonth())!=-1) ) {
					thedate[count++] = new Option(i+" "+weekdays[tdate.getDay()]+"",i);
			}
		      
			if (dur != 7 && dur != 3 && dur != 4) {
				initFlag = true;
			}      
		}
	}
  }

  if (thedate.options.length == 1) {
    if (!initFlag)
      alert("The month you selected ("+curform.myMonths.options[curform.myMonths.selectedIndex].text+") has no available dates for the selected duration.");
    var mon = curform.myMonths.selectedIndex;
    if (mon+1 < curform.myMonths.options.length) {
      curform.myMonths.options[mon].selected = false;  
      curform.myMonths.options[mon+1].selected = true;  
    } else {
      curform.myMonths.options[mon].selected = false;  
      curform.myMonths.options[0].selected = true;         
    }
    changedates(initFlag);  
  }

  if (selectedDay = "") selectedDay = "0"; 
  setDropDown(thedate, selectedDay);
  if(typeof thedate.onchange == "function")  thedate.onchange();
  grabArrDate();
}

function grabArrDate() {
	var dbform = document.getElementById('bookingForm');
	var monyr = getDropDownValue(dbform.myMonths);
	var day = getDropDownValue(dbform.myDays);
	if (day == "0")
	{
		dbform.arrDate.value = monyr.substring(5,8)+monyr.substring(0,2)+"00";
	}
	else
	{
		var d = new Date ( monyr.substring(0,2)+"/"+day+"/"+monyr.substring(3));
		dbform.arrDate.value = formatbookingFormDate(d);
	}
}

	// set dropdowns from cal popup
function setMultipleValues(y,m,d) 
{
  var curform = document.getElementById('bookingForm');
  var tempdate;
  if (m<10)
  {
    tempdate = "0" + m+ "/" + y;
  }
  else
  {
    tempdate = m+ "/" + y;
  }

  for (var i=0; i<curform.myMonths.options.length; i++) 
  {
    if (curform.myMonths.options[i].value==tempdate) 
    {
      curform.myMonths.selectedIndex=i;
    }
  }

  changedates();
  
  for (var i=0; i<curform.myDays.options.length; i++) 
  {
    if (curform.myDays.options[i].value==d) 
    {
      curform.myDays.selectedIndex=i;
    }
  }

}


function modifyCalendar(which)
{
  resetCalendar();
  var val;
  val = which.options[which.selectedIndex].value;
  
  if (val == -1) {
    populateDDBAry(which.form.myMonths, newyearMonths);  
  } else {
    populateDDBAry(which.form.myMonths, normalMonths);      
  }
  which.form.myMonths.options[which.form.myMonths.options.length-1] = null;
}

//create onDomReady Event
window.onDomReady = DomReady;

//Setup the event
function DomReady(fn)
{
	//W3C
	if(document.addEventListener)
	{
		document.addEventListener("DOMContentLoaded", fn, false);
	}
	//IE
	else
	{
		document.onreadystatechange = function(){readyState(fn)}
	}
}

//IE execute function
function readyState(fn)
{
	//dom is ready for interaction

//	if(document.readyState == "interactive")
	if(document.readyState == "complete")
	{
		fn();
	}
}

	// Set up calendar and populate date dropdowns
function pageInit() {
  durStay = hide_season_Weekends ? "Weekend" : "";
  changeboxes();

  dbform = document.getElementById('bookingForm');
  
  var code = dbform.myDur.value; 
  var dateCookie = new Cookie(document,"dateCookie");
  if (dateCookie.load()) {
    setDropDown(dbform.myMonths, dateCookie.monyr);
    dbform.myMonths.onchange();
    setDropDown(dbform.myDays, dateCookie.day);
  }

  changedates(true);

  modifyCalendar(dbform.myDur);
//  toggleCodeInput();

  if (dbform.arrDate.value) {
      //    setDropDown(dbform.myDays, dbform.arrDate.value.substr(4));
      var arrDate = dbform.arrDate.value.substr(4);
      if(arrDate.charAt(0) == '0')
      {
            arrDate = arrDate.substr(1);
      }
      setDropDown(dbform.myDays, arrDate);
  }

}
var durStay;
var hide_season_Weekends = false;  //default var:: Set this var on the calenar page not here


// -------------------------- date_stringHowManyDays --------------------------
// NAME       : date_stringHowManyDays
// PARAMETERS : string thisMonth   ("01" to "12")
//            : int thisYear = current year 
// RETURNS    : int monthDays
// BEHAVIOUR  : Returns the number of days in the month
// ----------------------------------------------------------------------------
function date_stringHowManyDays (thisMonth, thisYear)
{
	return date_howManyDays (thisMonth - 1, thisYear);
}

// -------------------------- date_howManyDays --------------------------------
// NAME       : date_howManyDays
// PARAMETERS : int thisMonth    (0 to 11)
//            : int thisYear = current year 
// RETURNS    : int monthDays
// BEHAVIOUR  : Returns the number of days in the month
// ----------------------------------------------------------------------------
function date_howManyDays (thisMonth, thisYear)
{
	// default the year if it hasn't been entered
	if (!thisYear)
	{
		thisYear = date_getCurrentYear ();
		if (date_isItNextYear (thisMonth))
		{
			thisYear++;
		}
	}

	var monthDays = new Array(31,28,31,30,31,30,31,31,30,31,30,31);
	if (thisMonth != 1)
	{
		return monthDays[thisMonth];
	}
	else
	{
		// month is february
		if (   (   (thisYear%400)  == 0 ) 
				|| (   ((thisYear%100) != 0 ) 
						&& ((thisYear%4)   == 0 )
					 ) 
			 )
		{
			return 29;
		}
		else
		{
			return 28;
		}
	}
}

// -------------------------- date_isItNextYear -------------------------------
// NAME       : date_isItNextYear
// PARAMETERS : int  themonth
// RETURNS    : bool returnvalue
// BEHAVIOUR  : Check to see if a month is this year or next...
// ----------------------------------------------------------------------------
function date_isItNextYear (themonth)
{
	var returnvalue  = false;
	var currentDate  = new Date();
	var currentMonth = currentDate.getMonth();
	if (themonth <= currentMonth)
	{
		returnvalue = true;
	}

	return returnvalue;
}

// ------------------------- date_getCurrentYear ------------------------------
// NAME       : date_getCurrentYear
// PARAMETERS : none
// RETURNS    : int y
// BEHAVIOUR  : Returns the current year in four digit format
// ----------------------------------------------------------------------------
function date_getCurrentYear () {
	var currentDate = new Date();
	var y = currentDate.getFullYear();
	if (y < 1000) {
		y += 1900;
	}
	return y;
}

//-------------------------- duration_validate --------------------------------
// NAME       : duration_validate
// PARAMETERS : form, string ci (prefix), string co (prefix)
// RETURNS    : bool
// BEHAVIOUR  : function ensures out date is same or greater than in date
//              activated on form submit, submition continues if returns 'true'
//-----------------------------------------------------------------------------
function duration_validate(f, ci, co) {
	var msg;    //The error message
	var err=0;  //Default error flag to 0 (no error)

	//Now if any errors, display them and return false to prevent form
	//submition, otherwise return true
	msg  = "______________________________________________________\n\n";
	msg += "The form was not submitted because of the following error(s).\n";
	msg += "Please correct these error(s) and re-submit.\n";
	msg += "______________________________________________________\n\n";

	if (parseFloat(getDropDownValue(eval("f."+ci+"Mon"))) > 
			parseFloat(getDropDownValue(eval("f."+co+"Mon")))) {
		msg += "The check-out date must be after the check-in date";
		err = 1; //set the error flag, error has occured
	}

	if (parseFloat(getDropDownValue(eval("f."+ci+"Mon"))) == 
			parseFloat(getDropDownValue(eval("f."+co+"Mon")))) {
		if (parseFloat(getDropDownValue(eval("f."+ci+"Day"))) > 
				parseFloat(getDropDownValue(eval("f."+co+"Day")))) {
			msg += "The check-out date must be after the check-in date";
			err = 1;
		}
	}

	if (err == 0) return true;
	alert(msg);
	return false;  
}

function setDays(direction) {
	var currentYear = date_getCurrentYear();
	var yearField = eval("document.getElementById('bookingForm')."+direction+"Year");
	if (typeof yearField == 'object') {
		if (yearField.type == "text") {
			currentYear = yearField.value;
		} else { // Must be a drop down
			currentYear = yearField.options[yearField.selectedIndex].value;
		}
	}

	
	var month = eval("document.getElementById('bookingForm')." + direction + "Mon.selectedIndex");
	var selIn = 0;
	var currentDate = new Date();

	if (month != currentDate.getMonth()) {
		if ((date_isItNextYear(1, month+1)) && (typeof yearField == 'undefined')) {
			currentYear++;
		}
	}

	var monlen = date_howManyDays(month, currentYear);
	var datesel = eval("document.getElementById('bookingForm')." + direction + "Day");
	selIn = datesel.selectedIndex;
	datesel.length = 28;

	for (var i=datesel.length;i<monlen;i++) {
		var optext = i+1;
		if (optext == 29 || optext == 30) {
			optext += "th";
		}
		else {
			optext += "st";
		}
		datesel.options[i] = new Option(optext,i+1,false,false);
	}

	if (datesel.length-1 < selIn) {
		selIn = datesel.length-1;
	}

	datesel.selectedIndex = selIn;
}

//--------------------------- expiry_validate ---------------------------------
// NAME       : expiry_validate
// PARAMETERS : object expiryDate
// RETURNS    : string status (3 chars long '123')
//              '1' indicates date structure error
//              '2' indicates 01-12 month range error
//              '3' indicates expiry date before today error
//              '4' indicates 01-31 day range error
//              '5' indicates invalid date (eg 31 Sep)
// BEHAVIOUR  : returns empty string if expiry date is correct structure & 
//              > today
//-----------------------------------------------------------------------------
function expiry_validate(expiryDate, datelen) {

	if (datelen == null) datelen = 4;

	var evstr = "";            //Date validation variable
	var today = new Date;      //Todays date
	var newmonth;        //Used to check expiry is after today
	var theyear;         //Holds expiry year
	var expdate;         //Proposed date of expiry
	var errstr = "";           //The error string returned initialised to
	//no errors

	//Now validate the expiry date format MM/YY is length correct?
	if (expiryDate.value.length != datelen) {
		errstr = "1"; //Set error string to '1' representing MM/YY type error
	}

	// Grab day from date
	var theDay = "01";
	if (datelen>5)
		theDay = expiryDate.value.substr(0,2);

	if (parseFloat(theDay) < 1 || parseFloat(theDay) > 31)
		errstr += "4";

	//Grab month from expiry date
	evstr = expiryDate.value.substr((datelen-4),2);

	//Is month in correct range?
	if (parseFloat(evstr) < 1 || (parseFloat(evstr) > 12)) {
		errstr += "2"; //Set str to str + 2 indicating month range type error
	}

	//Grab the year
	theyear = expiryDate.value.substr((datelen-2),2);

	if (datelen < 5) {
		//newmonth is the expiry month + 1
		if (parseFloat(evstr) == 12) {
			newmonth = 1;
			theyear = parseFloat(theyear) + 1;
		}

		if (parseFloat(evstr) != 12) {
			newmonth = parseFloat(evstr) + 1;
		}
	} else {
		newmonth = evstr;
	}

	//Format year correctly
	if (parseFloat(theyear) < 10) {
		theyear = "0" + parseFloat(theyear);
	}

	if (parseFloat(theyear) > 89) {
		theyear = "19" + theyear;
	}
	else theyear = "20" + theyear;

	if (theDay > date_howManyDays((parseFloat(evstr)-1), theyear))
		errstr += "5";

	//Create date for comparison with date object (today)
	if (parseFloat(theDay) <10) theDay = "0" + parseFloat(theDay);
	if (parseFloat(newmonth) <10) newmonth = "0" + parseFloat(newmonth);
	expdate = theDay + (newmonth + "") + theyear;

	//if (theDay < 10) expdate = "0" + expdate;

	//Now check expiry is after today
	//Check the year
	if (parseFloat(expdate.substr(4,4)) < parseFloat(today.getFullYear())) {
		errstr += "3";  //Set str to hold 3 indicating expires before or on today
	}

	//Check the month if year is same
	if (parseFloat(expdate.substr(4,4)) == parseFloat(today.getFullYear())) {
		if (parseFloat(expdate.substr(2,2)) < parseFloat(today.getMonth() + 1)) {
			if (errstr.indexOf("3") == -1)
				errstr += "3"; //If this error type is not already assigned do it
		}
	}

	//Check the day against today if same year and month
	if ((parseFloat(expdate.substr(4,4)) == parseFloat(today.getFullYear())) &&
			(parseFloat(expdate.substr(2,2)) == parseFloat(today.getMonth() + 1))) {
		if (parseFloat(expdate.substr(0,2)) <= parseFloat(today.getDate())) {
			if (errstr.indexOf("3") == -1)
				errstr += "3";
		}
	}

	return(errstr);
}


//--------------------------- dropdate_validate -------------------------------
// NAME       : dropdate_validate
// PARAMETERS : object OutDay, object OutMon, object OutYear
// RETURNS    : year drop down object 
//            
// BEHAVIOUR  : returns same year as passed in if whole date is after today
//              otherwise returns next year 
// DEPENDENCY : compare_date
//-----------------------------------------------------------------------------
function dropdate_validate(OutDay, OutMon, OutYear) {
	var today = new Date;      //Todays date
	var compareYear = "";
	var compareMonth = "";
	var compareDay = "";
	var compareDate = "";
	var inputDate = "";
	var inputYear = "";

	compareYear = today.getFullYear();
	compareMonth = today.getMonth() + 1;
	compareDay = today.getDate() + 1;
	compareDate += compareYear;
	compareDate += compareMonth;
	compareDate += compareDay;

	inputDate += getDropDownValue(OutYear);
	inputYear = inputDate;
	inputDate += getDropDownValue(OutMon);
	inputDate += getDropDownValue(OutDay); 

	if (parseFloat(inputDate) < parseFloat(compareDate)) {
		inputYear = (inputYear - 0) + 1;
	}

	return(inputYear);
}


//--------------------------- dropDate_AfterToday -----------------------------
// NAME       : dropDate_AfterToday
// PARAMETERS : object OutDay, object OutMon, object OutYear
// RETURNS    : bool, true if date set is after today 
//            
// BEHAVIOUR  : else false if date set is not after today 
// DEPENDENCY : compare_date            
//-----------------------------------------------------------------------------
function dropDate_AfterToday(OutDay, OutMon, OutYear) {
	var errString = ""; //The returned error string

	errString = compare_date(OutDay, OutMon, OutYear);

	if (errString == 1) return true;
	else return false;
}

//--------------------------- is_DOB ------------------------------------------
// NAME       : is_DOB
// PARAMETERS : object ddob, object mdob, object ydob
// RETURNS    : bool, true if date is a valid birthday 
//            
// BEHAVIOUR  : checks structure of birth date and if is before today
// DEPENDENCY : compare_date
//-----------------------------------------------------------------------------
function is_DOB(ddob, mdob, ydob) {
	var errString = ""; //The returned error string
 
	errString = compare_date(ddob, mdob, ydob);

	if (errString == "-1") return true;
	else return false;
}

//--------------------------- compare_date ------------------------------------
// NAME       : compare_date
// PARAMETERS : object dayval, object monthval, object yearval
// RETURNS    : string (-1 or 1 or 0 or 9)  -1= < today
//               1= > today
//               0= is today
//               9= input is not a date
// BEHAVIOUR  : checks structure of birth date and if is before today
//              function works with drop downs and text boxes
// CALLED FROM: can be called from; dropDate_validate,
//                                  dropDate_AfterToday
//            is_DOB 
//-----------------------------------------------------------------------------
function compare_date(ddob, mdob, ydob) {
	var today = new Date(); //Todays date

	var compareYear = "";
	var compareMonth = "";
	var compareDay = "";
	var compareDate = "";
	var inputDate = "";     //Users inputted date
	var maxDays = "";       //Maximum no. days for given month and year
	var inDay = "";   //Users Day
	var inMonth = "";   //Users month
	var inYear = "";    //Users year

	compareYear = today.getFullYear();   //Todays date
	compareMonth = today.getMonth() + 1;
	if (parseInt(compareMonth) < 10)
		compareMonth = "0" + compareMonth;
	compareDay = today.getDate();
	if (parseInt(compareDay) < 10)
		compareDay = "0" + compareDay;
	compareDate += compareYear;
	compareDate += compareMonth;
	compareDate += compareDay;

	//Deal with both text boxes and dropdowns
	if (ydob.type == "text") {
		inputDate = ydob.value;
		inYear = ydob.value;
	}
	else {
		inputDate = getDropDownValue(ydob);
		inYear = getDropDownValue(ydob);
	}
	if (mdob.type == "text") {
		inputDate += mdob.value;
		inMonth = mdob.value;
	}
	else {
		inputDate += getDropDownValue(mdob);
		inMonth = getDropDownValue(mdob);
	}
	if (ddob.type == "text") {
		inputDate += ddob.value;
		inDay = ddob.value;
	}
	else {
		inputDate += getDropDownValue(ddob);
		inDay = getDropDownValue(ddob);
	}
	

	//Check if users value is valid date day range/month range for given year
	//Is month in correct range?
	if (parseFloat(inMonth) < 1 || (parseFloat(inMonth) > 12)) {
		return "9"; //Is not valid date
	}

	//Is day value valid for the month and the year?
	//Grab max days for month value
	maxDays = date_stringHowManyDays (inMonth, inYear);
	if ((inDay < 1) || (inDay > maxDays)) return "9"; //Not a valid date

	if (inputDate < compareDate) return "-1"; //Date B4 today
	if (inputDate > compareDate) return "1";  //Date after today
	if (inputDate == compareDate) return "0"; //Date is today
}

//--------------------------- comp_dropdates ----------------------------------
// NAME       : comp_dropdates
// PARAMETERS : object OutDay, object OutMon, object OutYear,
//              object RetDay, object RetMon, object RetYear
// RETURNS    : bool, true if RetDate is >= OutDate
//            
// BEHAVIOUR  : checks if RetDate is >= OutDate
// DEPENDENCY : 
//-----------------------------------------------------------------------------
function comp_dropdates(OutDay, OutMon, OutYear, RetDay, RetMon, RetYear) {
// parseInt -- taken out of Month -- Ret and Out Mon

	if (parseInt(getDropDownValue(RetYear)) < parseInt(getDropDownValue(OutYear))) {
		return false;
	}

	if (parseInt(getDropDownValue(RetYear)) == parseInt(getDropDownValue(OutYear))) {
		if ((getDropDownValue(RetMon)) < (getDropDownValue(OutMon))) {
			return false;
		}
	}

	if (parseInt(getDropDownValue(RetYear)) == parseInt(getDropDownValue(OutYear))) {
		if ((getDropDownValue(RetMon)) == (getDropDownValue(OutMon))) {
			if (parseFloat(getDropDownValue(RetDay)) < parseFloat(getDropDownValue(OutDay))) {
				return false;
			}
		}
	}

	return true;
}

//--------------------------- comp_daterange ----------------------------------
// NAME       : comp_daterange
// PARAMETERS : object form, string OutDay ,string OutMon string OutYear
//    string default start date, string default end date  
// RETURNS    : bool 
//            
// BEHAVIOUR  : if true -= the date is correct, false= alert msg to user
// DEPENDENCY : NONE
//-----------------------------------------------------------------------------

function comp_daterange(OutDay, OutMon, OutYear, start_rng, end_rng) {
	// check that year is with in range
	// if it is 
	//check that month within the required year range
	// if the month is right check that the day is with in the range
	var test_day = getDropDownValue(OutDay);
	var test_month = getDropDownValue(OutMon);
	var test_yr = getDropDownValue(OutYear);

	test_yr = (parseInt(test_yr)) % 100;
	
	var test_date = ""+test_yr+test_month+test_day;

	if (test_yr < 10) test_date = "0" + test_date;

  return comp_daterange(test_date, start_rng, end_rng);
}

function comp_daterange(test_date, start_rng, end_rng) {
	if ((test_date <start_rng) || (test_date > end_rng)) {
		return false;
	} else {
		return true;
	}
}

//----------------------------- compMMYYDate ----------------------------------
// NAME       : compMMYYDate
// PARAMETERS : string date 1, string date 2
// 
// RETURNS    : bool
// BEHAVIOUR  : returns true if date2 is after date1
//
//-----------------------------------------------------------------------------
function compMMYYDate(date1, date2) {
	if (parseFloat(date1.substr(2,2)) > parseFloat(date2.substr(2,2))) 
		return false;

	if (parseFloat(date1.substr(2,2)) == parseFloat(date2.substr(2,2)))
		if (parseFloat(date1.substr(0,2)) > parseFloat(date2.substr(0,2)))
			return false; 

	return true;
}

// ---------------------------- prepare_date ----------------------------------
// NAME       : prepare_date
// PARAMATERS : object datedropdown, object datedropdown, object datedropdown
//     
// RETURNS    : string 6 char date ie 010101
// BEHAVIOUR  : builds a standard 6 char date from three drop downs 
// ----------------------------------------------------------------------------
function prepare_date(dateDay, dateMonth, dateYear) {
	var theYear; //Must grab a two character year
	var theMonth = getDropDownValue(dateMonth);
	var theDate;

	if (dateYear == null) {
		theYear = date_getCurrentYear();
		if (date_isItNextYear(parseFloat(theMonth)-1)) theYear++;
		theYear += '';
	} else {
		theYear = getDropDownValue(dateYear);
	}
	theYear = parseFloat(theYear);
	if (theYear < 100) theYear += 2000;	
	
	theDate = new Date();
	theDate.setFullYear(theYear);
	theDate.setMonth(parseFloat(theMonth) -1);
	theDate.setDate(parseFloat(getDropDownValue(dateDay)));


	return formatbookingFormDate(theDate);
	
}

// --------------------------------- addToDate --------------------------------
// NAME       : addToDate
// PARAMETERS : date date1, int displacement (number of days displacement)
//
// RETURNS    : date new date
// BEHAVIOUR  : Adds displacement to date, and returns new date
// ----------------------------------------------------------------------------
function addToDate(oldDate, numDays) {
	var odMilli = oldDate.getTime();
	var inMilli = numDays * (24 * 60 * 60 * 1000);
	var newDate = new Date(odMilli + inMilli);
	
	return newDate;
}

// ------------------------------- longDate -----------------------------------
// NAME       : longDate
// PARAMETERS : date date1
//
// RETURNS    : string
// BEHAVIOUR  : Takes date object and returns as string ie (3 March 2001)
// ----------------------------------------------------------------------------
function longDate(theDate) {
	var months = new Array("January","February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December");

	var grabMonth = theDate.getMonth();
	grabMonth = months[grabMonth];

	var dString = theDate.getDate() + " " + grabMonth + " " + 
								theDate.getFullYear();

	return dString;
}

// ----------------------------- strLongDate ----------------------------------
// NAME       : strLongDate
// PARAMETERS : string date1
//
// RETURNS    : string
// BEHAVIOUR  : Takes date string YYMMDD format and returns 3 March 2001 etc
// ----------------------------------------------------------------------------
function strLongDate(theDate) {
	var yearOK = "20" + theDate.substr(0,2); //Always Y2K it
	var passDate = new Date(parseInt(yearOK),(parseFloat(theDate.substr(2,2)) - 1),parseFloat(theDate.substr(4,2)));
	var dString = longDate(passDate);  

	return dString;
}

// ------------------------------ format bookingForm Date -------------------------------
// NAME       : formatbookingFormDate
// PARAMETERS : date date1
// 
// RETURNS    : string 
// BEHAVIOUR  : Takes date object and returns as string YYMMDD format
// ----------------------------------------------------------------------------
function formatbookingFormDate(theDate) {
	var grabYear = theDate.getFullYear();
	grabYear = (grabYear % 100)+"";
	if (grabYear < 10) grabYear = "0" + grabYear;
	var grabMonth = theDate.getMonth();
	grabMonth++;
	if (grabMonth < 10) grabMonth = "0" + grabMonth;
	var grabDate = theDate.getDate();
	if (grabDate < 10) grabDate = "0" + grabDate;
	var newDate = grabYear + grabMonth + grabDate;
	
	return newDate;
}

function formatDob(theDate) {  
	var grabYear = theDate.getFullYear()+"";
	var grabMonth = theDate.getMonth();
	grabMonth++;
	if (grabMonth < 10) grabMonth = "0" + grabMonth;
	var grabDate = theDate.getDate();
	if (grabDate < 10) grabDate = "0" + grabDate;
	var newDate = grabYear + grabMonth + grabDate;
	
	return newDate;  
}

// --------------------------------- createDate -------------------------------
// NAME       : createDate
// PARAMETERS : string date
// 
// RETURNS    : date object
// BEHAVIOUR  : converts string YYMMDD date into new date object
// ----------------------------------------------------------------------------
function createDate(theDate) {
  var theYear = parseFloat(theDate.substr(0,2));
  if (theYear < 46) theYear += 2000;
  else theYear += 1900;
	var theMonth = parseFloat(theDate.substr(2,2) - 1);
	var theDay = parseFloat(theDate.substr(4,2));
	var newDate = new Date(theYear, theMonth, theDay);

	return newDate;
}

function setDateDDB(strDate, dateName) {
	var theDate = createDate(strDate);
	var yrDDB  = eval("document.getElementById('bookingForm')."+dateName+"Year");
	var monDDB = eval("document.getElementById('bookingForm')."+dateName+"Mon");
	var dayDDB = eval("document.getElementById('bookingForm')."+dateName+"Day");

	setDropDown(yrDDB,  theDate.getFullYear);
	setDropDown(monDDB, theDate.getMonth+1);
	setDays(dateName);
	setDropDown(dayDDB, theDate.getDay);
}

function calcDuration(startDate, endDate) {
	return Math.round((endDate.getTime() - startDate.getTime()) /(1000*24*60*60))
}


// The constructor function: creates a cookie object for the specified
// document, with a specified name and optional attributes.
// Arguments:
//   document: The Document object that the cookie is stored for. Required.
//   name:     A string that specifies a name for the cookie. Required.
//   hours:    An optional number that specifies the number of hours from now
//             that the cookie should expire.
//   path:     An optional string that specifies the cookie path attribute.
//   domain:   An optional string that specifies the cookie domain attribute.
//   secure:   An optional Boolean value that, if true, requests a secure cookie.
//
function Cookie(document, name, hours, path, domain, secure)
{
    // All the predefined properties of this object begin with '$'
    // to distinguish them from other properties which are the values to
    // be stored in the cookie.
    this.$document = document;
    this.$name = name;
    if ((hours) && (hours != 0))
        this.$expiration = new Date((new Date()).getTime() + hours*3600000);
    else this.$expiration = null;
    if (path) this.$path = path; else this.$path = null;
    if (domain) {
      if (domain == "_DOMAIN_") this.$domain = getDomain();
      else if (domain == "_HOST_") this.$domain = document.location.host;
      else this.$domain = domain; 
    } else {
      this.$domain = null;
    }
    if (secure) this.$secure = true; else this.$secure = false;
}

function getDomain() {
    var server = document.location.host.split(".");
    if (server.length > 1) {
      return server.slice(1).join(".");
    }
    else return null;
}

// This function is the store() method of the Cookie object.
function _Cookie_store()
{
    // First, loop through the properties of the Cookie object and
    // put together the value of the cookie. Since cookies use the
    // equals sign and semicolons as separators, we'll use colons
    // and ampersands for the individual state variables we store 
    // within a single cookie value. Note that we escape the value
    // of each state variable, in case it contains punctuation or other
    // illegal characters.
    var cookieval = "";
    for(var prop in this) {
        // Ignore properties with names that begin with '$' and also methods.
        if ((prop.charAt(0) == '$') || ((typeof this[prop]) == 'function')) 
            continue;
        if (cookieval != "") cookieval += '&';
        cookieval += prop + ':' + escape(this[prop]);
    }

    // Now that we have the value of the cookie, put together the 
    // complete cookie string, which includes the name and the various
    // attributes specified when the Cookie object was created.
    var cookie = this.$name + '=' + cookieval;
    if (this.$expiration)
        cookie += '; expires=' + this.$expiration.toGMTString();
    if (this.$path) cookie += '; path=' + this.$path;
    if (this.$domain) cookie += '; domain=' + this.$domain;
    if (this.$secure) cookie += '; secure';

    // Now store the cookie by setting the magic Document.cookie property.
    this.$document.cookie = cookie;
}
// This function is the load() method of the Cookie object.
function _Cookie_load()
{
    // First, get a list of all cookies that pertain to this document.
    // We do this by reading the magic Document.cookie property.
    var allcookies = this.$document.cookie;
    if (allcookies == "") return false;

    // Now extract just the named cookie from that list.
    var start = allcookies.indexOf(this.$name + '=');
    if (start == -1) return false;   // Cookie not defined for this page.
    start += this.$name.length + 1;  // Skip name and equals sign.
    var end = allcookies.indexOf(';', start);
    if (end == -1) end = allcookies.length;
    var cookieval = allcookies.substring(start, end);

    // Now that we've extracted the value of the named cookie, we've
    // got to break that value down into individual state variable 
    // names and values. The name/value pairs are separated from each
    // other by ampersands, and the individual names and values are
    // separated from each other by colons. We use the split method
    // to parse everything.
    var a = cookieval.split('&');    // Break it into array of name/value pairs.
    for(var i=0; i < a.length; i++)  // Break each pair into an array.
        a[i] = a[i].split(':');

    // Now that we've parsed the cookie value, set all the names and values
    // of the state variables in this Cookie object. Note that we unescape()
    // the property value, because we called escape() when we stored it.
    for(var i = 0; i < a.length; i++) {
        this[a[i][0]] = unescape(a[i][1]);
    }

    // We're done, so return the success code.
    return true;
}

// This function is the remove() method of the Cookie object.
function _Cookie_remove()
{
    var cookie;
    cookie = this.$name + '=';
    if (this.$path) cookie += '; path=' + this.$path;
    if (this.$domain) cookie += '; domain=' + this.$domain;
    cookie += '; expires=Fri, 02-Jan-1970 00:00:00 GMT';

    this.$document.cookie = cookie;
}

// Create a dummy Cookie object, so we can use the prototype object to make
// the functions above into methods.
new Cookie();
Cookie.prototype.store = _Cookie_store;
Cookie.prototype.load = _Cookie_load;
Cookie.prototype.remove = _Cookie_remove;

function durationChange() { 
    showCalendar();
    changedates();
    modifyCalendar(dbform.myDur);
}

function dayChange() { 
  var bp = overrideDates.findBookPattern(getDropDownValue(dbform.myDur), getDropDownText(dbform.myDays));
  if (bp != null) { 
    dbform.duration.value = bp.duration;
    bp.onSelect(dbform);        
  }   
}

function hideCalendar() {
}

function showCalendar() {
}




