/////////////////////////////////////////////////////////////////
//  
//  dateField should be a string with the qualified form field
//            calendar should populate - 'document.form1.date'
//  		  FOR SOUTHWEST.COM, this has been changed to a field 
// 			  for the month, and a field for the day
//  
//  title is the title of the field
//  selectAfter and selectBefore determine the range of 
//            available (active) days.  They are NOT inclusive.
//            Specify either a specific date in MM/DD/YYYY format 
//            or a number of days from today (can be negative) 
/////////////////////////////////////////////////////////////////

var sbookThruDate = '5/7/2010';
var jsToday = new Date();
var htlBkThruDate = new Date(jsToday.setMonth(jsToday.getMonth() + 11));  // 11 months from Current Date
var sHtlBkThruDate = (htlBkThruDate.getMonth()+1) + "/" + htlBkThruDate.getDate() + "/" + htlBkThruDate.getFullYear();

var months = new Array('January','February','March','April','May','June','July','August','September','October','November','December');
var validDays = new Array(31,28,31,30,31,30,31,31,30,31,30,31);

function openCalendar(title,viewPath,datefield,datefield_mo,datefield_day,selectAfter,selectBefore,today) {
	var field = eval(datefield);
	if (field.name != null) {
		//////////////////////////
		//  FOR SOUTHWEST.COM
		//  This code grabs the current selected date from the dropdown lists
		//  and pushes it to the hidden date field.
		
		var moField = eval(datefield_mo);
		var month = 0;
		if (moField && moField.selectedIndex != -1) {
			for (i=0; i<months.length; i++) {
				if (months[i] == moField.options[moField.selectedIndex].value) 
					month = i+1;
			}
		}	
		var dayField = eval(datefield_day);
	   var day = 0;
		if (dayField &&  dayField.selectedIndex != -1) {
			var date = new Date();
			var year = date.getFullYear();
			if (date.getMonth()+1 > month) year++;  // selected month in next year
			if (year % 4 == 0) validDays[1] = 29;  // account for leap year
			day = parseInt(dayField.options[dayField.selectedIndex].value);
			if (day > validDays[month-1]) day = validDays[month-1];
		}
		if (month != 0 && day != 0) {
			field.value = month+'/'+day+'/'+year;
		}
		
		var todayStr = "";
		if (today) {
			todayStr = "&today="+today;
		}
		
		var height = 200;
		var width = 210;
		var x = screen.width/4 - width/2;
		var y = screen.height/4 - height/2;
	
		switch (viewPath) {
			case 'ES':
				openCalendarWindow('/calendar/calendar_ES.html?field='+datefield+'&field_mo='+datefield_mo+'&field_day='+datefield_day+'&date='+field.value+'&title='+title+'&selectAfter='+selectAfter+'&selectBefore='+selectBefore+todayStr,'popupCalendar',width,height,x,y,'resizable');
				break;
			default:
				openCalendarWindow('/calendar/calendar.html?field='+datefield+'&field_mo='+datefield_mo+'&field_day='+datefield_day+'&date='+field.value+'&title='+title+'&selectAfter='+selectAfter+'&selectBefore='+selectBefore+todayStr,'popupCalendar',width,height,x,y,'resizable');
				break;
		}
		// Set the cookie that triggers that the calendar has been opened
		setCookie('windowOpen','TRUE',0);
	}
}

function openCalendarTxtField(title,viewPath,datefield,selectAfter,selectBefore,today) {
   
	var field = eval(datefield); 
   
   if (field.name != null) {		   
      var todayStr = "";
		if (today) {
			todayStr = "&today="+today;
		}
		
		var height = 200;
		var width = 210;
		var x = screen.width/4 - width/2;
		var y = screen.height/4 - height/2;
	
		switch (viewPath) {
			case 'ES':
				          openCalendarWindow('/calendar/calendar_ES.html?field='+datefield+'&date='+field.value+'&title='+title+'&selectAfter='+selectAfter+'&selectBefore='+selectBefore+todayStr,'popupCalendar',width,height,x,y,'resizable');
				break;
			default:
				openCalendarWindow('/calendar/calendar.html?field='+datefield+'&date='+field.value+'&title='+title+'&selectAfter='+selectAfter+'&selectBefore='+selectBefore+todayStr,'popupCalendar',width,height,x,y,'resizable');
				break;
		}
		// Set the cookie that triggers that the calendar has been opened
		setCookie('windowOpen','TRUE',0);
	}
}



// Following script is similar to openCalendar EXCEPT it allows to preselect a calendar date based on another date field.
// Ex: When there is a departure date, the return date will show the departure date preselected.
// BUT, when a return date is selected, return date is default.
function openCalendarPreselect(title,viewPath,datefield,datefield_mo,datefield_day,selectAfter,selectBefore,today,preSelectMo,preSelectDay) {
   var field = eval(datefield);
	if (field.name != null) {
      var currentMonth = eval(datefield_mo + ".value");
      if (currentMonth != "") {
         // Use the preselected return date
   		var moField = eval(datefield_mo);
         var dayField = eval(datefield_day);
      } else {
         // Use the preselected depart date
   		var moField = eval(preSelectMo);
   		var dayField = eval(preSelectDay);         
      }
      // Here is where the preselect month is based on a different field than the current calendar date being selected
		var month = 0;
		if (moField && moField.selectedIndex != -1) {
			for (i=0; i<months.length; i++) {
				if (months[i] == moField.options[moField.selectedIndex].value) 
					month = i+1;
			}
		}	
      // Here is where the preselect day is based on a different field than the current calendar date being selected
	   var day = 0;
		if (dayField &&  dayField.selectedIndex != -1) {
			var date = new Date();
			var year = date.getFullYear();
			if (date.getMonth()+1 > month) year++;  // selected month in next year
			if (year % 4 == 0) validDays[1] = 29;  // account for leap year
			day = parseInt(dayField.options[dayField.selectedIndex].value);
			if (day > validDays[month-1]) day = validDays[month-1];
		}
		if (month != 0 && day != 0) {
			field.value = month+'/'+day+'/'+year;
		}
		var todayStr = "";
		if (today) {
			todayStr = "&today="+today;
		}
		var height = 200;
		var width = 210;
		var x = screen.width/4 - width/2;
		var y = screen.height/4 - height/2;
      switch (viewPath) {
			case 'ES':
				openCalendarWindow('/calendar/calendar.html?field='+datefield+'&field_mo='+datefield_mo+'&field_day='+datefield_day+'&date='+field.value+'&title='+title+'&selectAfter='+selectAfter+'&selectBefore='+selectBefore+todayStr,'popupCalendar',width,height,x,y,'resizable');
				break;
			default:
            openCalendarWindow('/calendar/calendar.html?field='+datefield+'&field_mo='+datefield_mo+'&field_day='+datefield_day+'&date='+field.value+'&title='+title+'&selectAfter='+selectAfter+'&selectBefore='+selectBefore+todayStr,'popupCalendar',width,height,x,y,'resizable');
				break;
		}
		// Set the cookie that triggers that the calendar has been opened
		setCookie('windowOpen','TRUE',0);
	}
}

function validateDate(candidate,bYear,eYear) {// expect dateStr in MM/DD/YYYY format
  if (candidate == null) return false;
  var beginYear = bYear || 1970;
  var endYear = eYear || 2069;  
  
  var re = new RegExp("^[0-9]{1,2}/[0-9]{1,2}/([0-9]{2}|[0-9]{4})$","gi");
  if (candidate.match(re) != null) {
	var month = parseInt(candidate.substring(0,candidate.indexOf('/')),10);
	if (month >= 1 && month <= 12) {
	  var year = parseInt(candidate.substring(candidate.lastIndexOf('/')+1,candidate.length),10);
	  //  format 2 digit dates, dates 70+ go to 1900, under 70 to 2000.
	  //  i.e. 76 would become 1976, 03 would become 2003.
	  if (year < 100 && year >= 70) year += 1900;
	  else if (year < 100 && year < 70) year += 2000;
	  if (year >= beginYear-1 && year <= endYear) {
		if (year % 4 == 0) validDays[1] = 29;  // account for leap year
	    var date = parseInt(candidate.substring(candidate.indexOf('/')+1,candidate.lastIndexOf('/')),10);
	    if (date >= 1 && date <= validDays[month-1]) {
			var thisDate = new Date(year,month-1,date);
			return true;
		}
	  }
	}
  }  
  return false;
}
function dateToString(date) {  // takes a Date object, returns a string in MM/DD/YYYY format
	var month = date.getMonth()+1;
	var monStr = (month < 10) ? '0'+month : ''+month;
	var day = date.getDate();
	var dayStr = (day < 10) ? '0'+day : ''+day;
	return monStr+'/'+dayStr+'/'+(date.getFullYear());
}

function stringToDate(dateStr) {  // takes a string in MM/DD/YYYY format and returns a Date object
	var dateArray = dateStr.split('/');
	var year = parseInt(dateArray[2],10);
	if (year < 100 && year >= 70) year += 1900;
	else if (year < 100 && year < 70) year += 2000;
	return new Date(year,parseInt(dateArray[0]-1,10),parseInt(dateArray[1],10));
}

function gotoDay (dateStr,multiplier) {
	if (isNaN(parseInt(multiplier,10))) multiplier = 1;
	if (validateDate(dateStr)) {	
		var nextDate = new Date(stringToDate(dateStr).valueOf() + (multiplier*24*60*60*1000));
		return dateToString(nextDate);	
	}
	else return null;
}

function incDay(field) {
	var dateStr = gotoDay(field.value,1);
	if (dateStr != null) field.value = dateStr;
	field.dirty = true;
}

function decDay(field) {
	var dateStr = gotoDay(field.value,-1);
	if (dateStr != null) field.value = dateStr;
	field.dirty = true;
}


function openCalendarWindow(url,name,width,height,x,y,opts) {
//uses function getVar
	var url = (url != null) ? url : ''; 
	var width = (width != null) ? 'width='+width+',' : '';
	var height = (height != null) ? 'height='+height+',' : '';
	var x = (x != null) ? (document.all) ? 'left='+x+',' : 'screenX='+x+',' : '';
	var y = (y != null) ? (document.all) ? 'top='+y+',' : 'screenY='+y+',' : '';
	var opts = (opts != null) ? opts : 'directories,location,menubar,resizable,scrollbars,status,toolbar';
	var win = null;
	if (name == null) {
		win = window.open(url,"",width+height+x+y+opts);
	}
	else {
		win = getVar(name);
		if (win == null || win.closed) {
			win = window.open(url,name,width+height+x+y+opts);
		}
		else {
			win.location.href = url;
		}
		win.focus();
		eval (name +' = win;');
		return win;
	}
}



function getVar(name) {
	try {
		if (eval(name)) return eval(name);
	}
	catch (er) {
		return null;
	}
}

/////////////////////////////////////////////////////////////////
// The following script is used primarily on the buildItinerary 
// file to check simple date information:
//    - Is the date selected before today's date?
//       * CalendarCurrentDate must be on page
//    - Is the date selected a valid date for that month? 
//    - Is the date selected after the last bookable date?
//       * CalendarLastBookableDate must be on page
// When calling the script, you must include two params:
//    - field (REQUIRED)
//       * Field names MUST use the following format:
//         document.formName.partialFieldName
//         (both a month and day field must end with _month
//         and _day endings BUT ending is not included here)
//         Ex:
//         document.planATripForm.outbound_depart_month
//         would be this param for field:
//         document.planATripForm.outbound_depart
//    - fieldName (REQUIRED)
//       * This is used on the alert messages to help the user
//         know specifically which date is causing the alert.
/////////////////////////////////////////////////////////////////
function checkDates(field,fieldName) {
   // Set the field param for the onLoad in the body tag
   var strSelectMonth = eval(field+"_month");
   var strSelectDay = eval(field+"_day");
   
   // Determine month selected and valid dates (including leap year logic)
   var defaultMonth = strSelectMonth.value;
   var month = 0;
   for (i=0; i<months.length; i++) {
      if (months[i] == defaultMonth) {
         month = i+1;
      }
   }
   var date = new Date();
   var year = date.getFullYear();
   if (date.getMonth()+1 > month) year++;  // selected month in next year
   if (year % 4 == 0) validDays[1] = 29;  // account for leap year

   // Extract formName in order to get the CalendarCurrentDate and CalendarLastBookableDate values
   myFormRegExp = /\w+\.(\w+)\.\w+/ ;
   strMatch = myFormRegExp.exec(field+"_month");
   strFormName = "document." + strMatch[1] + ".";
   strCalCurrentDate = eval(strFormName + "CalendarCurrentDate.value");
   strCalLastBookable = eval(strFormName + "CalendarLastBookableDate.value");
   
   // Use Regular Expressions to compute valid date ranges
   myRegExp = /(\d{2})\/(\d{2})\/\d{4}/ ;
   myCurrentMatch = myRegExp.exec(strCalCurrentDate);
   myDay = parseInt(myCurrentMatch[2]);
   myLastDayMatch = myRegExp.exec(strCalLastBookable);
   myLastMonth = parseInt(myLastDayMatch[1]);
   myLastDay = myLastDayMatch[2];

   // Begin checking selected dates (only if there is both a month and day provided)
   if (strSelectMonth.value != "" && strSelectDay.value != "") {
      // ***** Checking invalid dates at the beginning of the first month... *****
      if (strSelectMonth.selectedIndex == "0") {
         if (strSelectDay.value < myDay) {
            strCheckDateMsg += "- The " + fieldName + " date selected is prior to today.\n";
            strSelectDay.focus();
         }
      }
      // ***** Checking invalid dates at the end of the months... *****
      if (strSelectDay.value > validDays[month-1]) {
         strCheckDateMsg += "- The " + fieldName + " date does not exist in the month selected.\n";
         strSelectDay.focus();
      }
         
      // ***** Checking invalid dates at the end of the last month... *****
      if (strSelectMonth.value == months[myLastMonth-1]) {
         if (parseInt(strSelectDay.value) > myLastDay) {
            strCheckDateMsg += "- The " + fieldName + " date selected is beyond our booking schedule which is currently through " + months[myLastMonth-1] + " " + myLastDay + ", " + year + "\n";
            strSelectDay.focus();
         }
      }
   }
   return true;
}

function getMonthNbr(monthName) {  // takes the month Name ('March') and returns equivalent month number (3)

var monthNbr = 0;
for (i=0; i<months.length; i++) {
   if (months[i] == monthName) {
	   var monthNbr = i+1;      
      break;     
	}   
}  
return monthNbr;
}

function determineYear(startDate, moField, yrField) {  // calculates depart Year using start Date (MM/DD/YYYY)
                                                       //  and selected month. Assumes date range < one year

var date = new Date();
var monthStr = startDate.substring(0,2);
var startMonth = parseInt(monthStr);                                  
var yearStr = startDate.substring(6,10);
var startYear = parseInt(yearStr);
var thisYear = date.getFullYear(startYear);
var nextYear = (date.getFullYear(startYear) + 1); 

for (i=0; i <= moField.length; i++)  {
   if (moField[i].selected) {   
      var selectedMonth = moField[i].value;                                                                             
      break;
    }   
}

if (getMonthNbr(selectedMonth)  <  startMonth) {
   var departYear = nextYear;     
   yrField.value = nextYear;
} else { 
   var departYear = thisYear;  
   yrField.value = thisYear;
} 
return departYear;
}

function getLengthofStay(beginDate, stopDate) {

   var lengthOfStay = "";
   var startDate = stringToDate(beginDate);
   var endDate = stringToDate(stopDate);   
   var startMonth = startDate.getMonth(); 
   var endMonth = endDate.getMonth(); 
   var startDay = startDate.getDate(); 
   var endDay = endDate.getDate(); 
   
   if (endMonth != startMonth) {   
      var departMonthLength = validDays[startMonth];
      // account for leap year
      if ((startDate.getYear() % 4 == 0) && (startMonth == 1)) { 
      
         departMonthLength = 29;  
      }           
      var departDaysRemaining = departMonthLength - startDay; 
      lengthOfStay = departDaysRemaining + endDay;
   } else {   
      lengthOfStay = endDay - startDay; 
   }
   return lengthOfStay;
}


function getMonthList(howMany) {
// Creates an array of Month names starting with current month and ending with specified number of Months
//  howMany = number of months OR 'eos' End of Schedule
   var today = new Date();   
   var startMonth = today.getMonth()+1; 
   var bookThruDate = new Date(sbookThruDate);
   var endMonth = bookThruDate.getMonth() + 1;
   var xMonths;

   if (howMany == "eos") {  
      // Calculate number of months in schedule
       xMonths = (12-startMonth)+endMonth+(bookThruDate.getYear()-today.getYear()-1)*12;
   } else { 
      xMonths = howMany;   
   }    
   
   var bookingMonths = new Array();
   j = 1;
   for (i=0; i <= xMonths; i++) {
      addMonth = startMonth + i;  
      if(addMonth > 12) {
         addMonth = j;         
         j++
      }   
      bookingMonths[i] = months[addMonth-1];       
   }   
   return bookingMonths;
}   





