var MONTH_LIST= ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sept", "Oct", "Nov", "Dec"];

function DateSelectControl(initialDate, maxDate, minDate, dayElement, monthElement, yearElement, onChangeFunction) {
  return {
     "dayElement": dayElement,
     "monthElement": monthElement,
     "yearElement": yearElement,
     "maxDate": maxDate,
     "minDate": minDate,
     "ocf": onChangeFunction,
     "years": [minDate.getFullYear()], 
     date: initialDate,

     "getUpdateFunction": function(){
        var hubba = this;
        return function(){
           hubba.update();
        } 

     },

     "redrawDays": function(){
       //* Make sure the correct amount of days show for that month on load
       //* when a user selects a departure date in a month that has 30 days, make sure the return day list has 31 days
       //* when a user selects a month with 31 days, make sure the return days list has the right amount of days for the next month
       var daysInMonth = 32 - new Date(this.date.getFullYear(), this.date.getMonth(), 32).getDate();
       var startDay = 0;
       // this probably needs a rethink but will do for now; maybe we can use a pre-built calendar
       if(this.maxDate.getFullYear() == this.date.getFullYear() && this.maxDate.getMonth() == this.date.getMonth())
       {
          daysInMonth = this.maxDate.getDate();
		  
       }
       this.dayElement.options.length = 0;
       for(var i = startDay; i < daysInMonth; i++)
       {
         this.dayElement.options[this.dayElement.options.length]=new Option(i+1, i+1);
         if(i == (this.date.getDate()-1))
         {
              this.dayElement.options[this.dayElement.options.length-1].selected = true;
         }
       }
       
     },
     "redrawMonths": function(){
        var monthCount = 12;
        var startMonth = 0;    
        this.monthElement.options.length = 0;
		for(var i = startMonth; i < monthCount; i++)
        {
          this.monthElement.options[this.monthElement.options.length]=new Option(MONTH_LIST[i], i+1);
          if(this.date.getMonth() == i)
          {
            this.monthElement.options[this.monthElement.options.length-1].selected = true;
          }
        }

     },
     "redrawYears": function(){

        this.yearElement.options.length = 0;
	for(var i = 0; i < this.years.length; i++)
        {
          this.yearElement.options[i]=new Option(this.years[i], this.years[i]);
          if(this.years[i] == this.date.getFullYear())
          {
             this.yearElement.options[i].selected = true;
          }
        }
        
     },

     "redraw": function(){
        this.redrawDays();
        this.redrawMonths();
		this.redrawYears();
      },

     "showDate": function(theNewDate){
		this.date = theNewDate;
        this.redraw();
        if(this.ocf)
          this.ocf();
     },   

     "getAsDate": function(){

        return this.date;
     },
	
	"update": function(){
		 this.date.setDate(1);
         //use the values instead of the indicies
         this.date.setMonth(this.monthElement.options[this.monthElement.selectedIndex].value-1);
         this.date.setFullYear(this.yearElement.options[this.yearElement.selectedIndex].value);
         var daysInMonth = 32 - new Date(this.date.getFullYear(), this.date.getMonth(), 32).getDate();
         var day = this.dayElement.options[this.dayElement.selectedIndex].value;
         //build a test date
         var tmpDate = new Date();
         tmpDate.setDate(1);
         tmpDate.setFullYear(this.date.getFullYear());
         tmpDate.setMonth(this.date.getMonth());
         if(day <= daysInMonth)
         {
         	tmpDate.setDate(day);
         }
         else
         {
            tmpDate.setDate(daysInMonth);
         }
         
         // if the tmpdate is later than the max date, set the date to the max date
		 if(tmpDate > this.maxDate)
         {
            this.date.setTime(this.maxDate.getTime());
			friendlyMaxDate = flightMaxD.getDate() + " " + MONTH_LIST[(flightMaxD.getMonth())] + " " + flightMaxD.getFullYear();
			document.getElementById('error_flights').innerHTML = "This date is not yet available for sale. You may book up to 330 days in advance, ie. no later than "+friendlyMaxDate;			
			document.getElementById('error_cars').innerHTML = "This date is not yet available for sale. You may book up to 330 days in advance, ie. no later than "+friendlyMaxDate;
         }else{
            //if the tmpdate is earlier than today, set the date to today
            if(tmpDate < this.minDate)
            {
			  this.date.setTime(this.minDate.getTime());
			  friendlyMinDate =  minDate.getDate() + " " + MONTH_LIST[(minDate.getMonth())] + " " + minDate.getFullYear();
              document.getElementById('error_flights').innerHTML = "You cannot choose a date earlier than "+friendlyMinDate;
              document.getElementById('error_cars').innerHTML = "You cannot choose a date earlier than "+friendlyMinDate;
            }
            else
            {
               this.date.setTime(tmpDate.getTime());
			   document.getElementById('error_flights').innerHTML = '';
			   document.getElementById('error_cars').innerHTML = '';
			   //perform a full redraw
				this.redraw();
					if(this.ocf)
						this.ocf();
					}
			}	
     },
     "init": function(){

        this.dayElement.onchange = this.getUpdateFunction();
        this.monthElement.onchange = this.getUpdateFunction();
        this.yearElement.onchange = this.getUpdateFunction();
        if(this.maxDate.getFullYear() > this.minDate.getFullYear())
        {
           for(var i = this.minDate.getFullYear() + 1; i <= this.maxDate.getFullYear(); i++)
           {
              this.years[this.years.length] = i;
           }
        }
		this.redraw();
     return this;
	     }
 
  }.init();
}

function addEvent(obj, evType, fn){ 
	 if (obj.addEventListener){ 
	   obj.addEventListener(evType, fn, false); 
	   return true; 
	 } else if (obj.attachEvent){ 
	   var r = obj.attachEvent("on"+evType, fn); 
	   return r; 
	 } else { 
	   return false; 
	 } 
}

Date.prototype.addDays = function(num) {
   var ONE_DAY_IN_MS = 1000*60*60*24;
   this.setTime(this.getTime() + (ONE_DAY_IN_MS*num));
}

//flights
var flightDaysInAdvance = 4;//change this value to be in accordance with the customer's choice for the first possible day to make a booking.
var daysInTrip = 31;
var flightMinD = new Date();
flightMinD.addDays(flightDaysInAdvance);
var flightMaxD = new Date(flightMinD.getTime());
flightMaxD.addDays(330);


//cars
var carDaysInAdvance = 4;//change this value to be in accordance with the customer's choice for the first possible day to make a reservation.
var carDaysInTrip = 31;
var carMinD = new Date();
carMinD.addDays(carDaysInAdvance);
var carMaxD = new Date(carMinD.getTime());
carMaxD.addDays(330);

function setupDates()
{
	//* When page loads, show current date 
	//* Make return date a month later

	//flights
	var departDate = new Date();
	  departDate.addDays(flightDaysInAdvance);
	var returnDate = new Date(departDate);
	  returnDate.addDays(daysInTrip);

	
 	//cars
	var carDepartDate = new Date();
	  carDepartDate.addDays(carDaysInAdvance);
	var carReturnDate = new Date(carDepartDate);
	  carReturnDate.addDays(carDaysInTrip);

	//flights
	flightDepartDateControl = new DateSelectControl(departDate, flightMaxD, flightMinD, document.getElementById('searchAir.segments[0].departDate.day'),document.getElementById('searchAir.segments[0].departDate.month'),document.getElementById('searchAir.segments[0].departDate.year'), updateReturnFlight);
	flightReturnDateControl = new DateSelectControl(returnDate, flightMaxD, flightMinD, document.getElementById('searchAir.segments[1].departDate.day'),document.getElementById('searchAir.segments[1].departDate.month'),document.getElementById('searchAir.segments[1].departDate.year'));
	
	//cars
	carDepartDateControl = new DateSelectControl(carDepartDate, carMaxD, carMinD, document.getElementById('searchCar.segments[0].pickupDate.day'),document.getElementById('searchCar.segments[0].pickupDate.month'),document.getElementById('searchCar.segments[0].pickupDate.year'), updateReturnCar);
	carReturnDateControl = new DateSelectControl(carReturnDate, carMaxD, carMinD, document.getElementById('searchCar.segments[0].dropoffDate.day'),document.getElementById('searchCar.segments[0].dropoffDate.month'),document.getElementById('searchCar.segments[0].dropoffDate.year'));
}

function updateReturnFlight()
{
  //* When user changes departure date, make return date month later
  //* If the user chooses the 12th month as departure date, change the return month to the 1st and the return year to the next year
   var newDate = new Date(flightDepartDateControl.getAsDate());
        newDate.addDays(daysInTrip);
        newDate.setTime(Math.min(newDate.getTime(), flightMaxD.getTime()));
     	flightReturnDateControl.showDate(newDate);
}


function updateReturnCar()
{
  //* When user changes departure date, make return date month later
  //* If the user chooses the 12th month as departure date, change the return month to the 1st and the return year to the next year
   var newDate = new Date(carDepartDateControl.getAsDate());
        newDate.addDays(daysInTrip);
        newDate.setTime(Math.min(newDate.getTime(), carMaxD.getTime()));
     	carReturnDateControl.showDate(newDate);
}

function checkBlankFlights()
{
	if (document.getElementById('searchAir.segments[0].departCity').value == "") {
		document.getElementById('searchAir.segments[0].departCity').focus();
		document.getElementById('error_depart').innerHTML = "Please type in the first 4 letters of city, then select from the list that appears";
		return false ;
	}else if(document.getElementById('searchAir.segments[0].arrivalCity').value == "") {
		document.getElementById('searchAir.segments[0].arrivalCity').focus();
		document.getElementById('error_arrive').innerHTML = "Please type in the first 4 letters of city, then select from the list that appears";
		return false ;
	}else if (document.getElementById('error_flights').innerHTML !=""){
		return false;
	}else{	
		//send the value of the cabin class chosen through to the full search page
		var cabClass = document.getElementById("cabClassSelect").value
		document.getElementById("searchAir.segments[0].cabinIndicator").value= cabClass;
		document.getElementById("searchAir.segments[1].cabinIndicator").value= cabClass;
		return true ;
  }
}


function checkBlankCars()
{
	if (document.getElementById('searchCar.segments[0].pickupCity').value == "") {
		document.getElementById('searchCar.segments[0].pickupCity').focus();
		document.getElementById('error_cars_city').innerHTML = "Please type in the first 4 letters of city, then select from the list that appears";
		return false ;
	}else if (document.getElementById('error_cars').innerHTML !=""){
		return false;	
	}else{
		//send the value of the drop off city to be the same as the pick up city
		var dropOff = document.getElementById("searchCar.segments[0].pickupCity").value
		document.getElementById("segments[0].dropoffCity").value= dropOff;
		return true ;
  }
}


function clearError()
{
	document.getElementById('error_depart').innerHTML = "";
	document.getElementById('error_arrive').innerHTML = "";
	document.getElementById('error_cars').innerHTML = "";
	document.getElementById('error_cars_city').innerHTML = "";
	document.getElementById('error_flights').innerHTML = "";
	}



function disableReturn()
{
	var found_it
	var returnEl = document.flights.elements["return"];
	for (var i=0; i<returnEl.length; i++)  {
		if (returnEl[i].checked)  {
			selected = returnEl[i].value
			if (selected=="O")
			{
				document.getElementById("searchAir.segments[1].departDate.day").disabled = true;
				document.getElementById("searchAir.segments[1].departDate.month").disabled = true;
				document.getElementById("searchAir.segments[1].departDate.year").disabled = true;

			}else{
				document.getElementById("searchAir.segments[1].departDate.day").disabled = false;
				document.getElementById("searchAir.segments[1].departDate.month").disabled = false;
				document.getElementById("searchAir.segments[1].departDate.year").disabled = false;
			}
		}
	} 
}


addEvent(window, 'load', setupDates);
