var vacationsForm = Array(
    {"field":"area1","method":"validateTextField"},
    {"field":"date1","method":"validateTextField"},
    {"field":"date2","method":"validateTextField"},
    {"field":"child_age1","method":"validateChildAge","params":[2]},
    {"field":"child_age2","method":"validateChildAge","params":[2]},
    {"field":"child_age3","method":"validateChildAge","params":[2]},
    {"field":"num_rooms","method":"validateMinNumber","params":[1]}
);

function openPopUp(url) {
  window.open(url,'pop2','toolbar=0,location=0,directories=0,status=0,menubar=0,scrollbars=1,resizable=1,height=500,width=800');
}



function GetawaysPage(container){
	mb("area1").value = "";
	mb("area2").value = "";
	mb("date1").value = "";
	mb("date2").value = "";
	mb("dynamic_children").value = "0";
	mb("child_age1").value = "";
	mb("child_age2").value = "";
	mb("child_age3").value = "";
	mb("adults").value = "2";
	mb("infants_in_lap").value = "0";
	mb("num_rooms").value = "";
	this.container = container;
	this.cookie = "cookie_" + threeLetterCode;
	this.maxDate = minibookerExtensionDate;
	var o = this;
	// Set up destination variables based on the value included in the HTML file's <head>.
	this.destinationCode = threeLetterCode;
	this.destinationString = this.getDestinationString();
	this.destinationFriendly = this.getFriendlyDestination();
	this.destinationEzRez = this.getEzRezDestination();
	// MiniBooker whereFrom
	this.panel = new GenericPanel("whereFrom","Where from?","area1",0,this.getOriginAirports(),"vacationsForm","","");
	// Initialize MiniBooker DropDowns
	this.adults = new DropDown("selectObj_0");
	this.children = new DropDown("selectObj_1");
	this.infants = new DropDown("selectObj_2");
	this.hotelRooms = new DropDown("selectObj_3");
	this.hotelRooms.presetHotelRooms(1);
	this.childrenAge1 = new DropDown("selectObj_7");
	this.childrenAge2 = new DropDown("selectObj_8");
	this.childrenAge3 = new DropDown("selectObj_9");
	// Hotel Packages not available on Getaways.
	// this.hotelPackage = new DropDown("hotelPackage");
	// Set MiniBooker date, actual date plus 3 days.
	var today = new Date();
	var todayDay = today.getDate() + 1;
	this.calPair = new CalendarPair("cal0","cal1","date1","date2",(today.getMonth() + 1) + "/" + todayDay + "/" + today.getFullYear(),this.maxDate);
	this.validator = new Validator("vacationsForm","errorMessage",false);
	this.panel1 = new VacationsPanel("whereTo1","Where to?","area3",3,GetawaysDestinations,"goTovacationsForm","","");
	this.panel1.onItemSelect.subscribe(this.goToDest,this,true);
	var cookie = getCookie(this.cookie);
	// Form Submit
	mb("VacationSubmit").onclick = function(){return o.submitForm('vacationsForm');}
	// Initialize tabs.
	this.tabs();
	// Initialize stay popup window.
	this.openWindow("hotelWindow",'height=500,width=720,scrollbars=yes');
	// Initialize minibooker terms and condition popup.
	this.openWindow("termsandconditionWindow",'toolbar=0,location=0,directories=0,status=0,menubar=0,scrollbars=1,resizable=1,height=500,width=800');
	// Set destinations in Minibooker
	mb("area2_destination").value = this.destinationFriendly;
	mb("area2").value = this.destinationEzRez;
	/*if(cookie){
		var jar = document.getElementsByClassName("cookieJar", this.container);
		var cookieObject = eval(cookie);
		jar[0].appendChild(document.createTextNode("Recent search: "));
		var link = document.createElement("a");
		link.id = "prepopMB";
		link.href="#";
		link.title = cookieObject[0].fields[0].readable + " to " +
			cookieObject[0].fields[1].readable + " on " +
			cookieObject[0].fields[2].readable + " returning " +
			cookieObject[0].fields[3].readable + " - " +
			cookieObject[0].fields[4].readable + ", " +
			cookieObject[0].fields[5].readable + ", ";
		var from = cookieObject[0].fields[0].value;
		var to =cookieObject[0].fields[1].value;
		// Citycode string replacement
		if(to.split(" ").length > 2){
			cityTo = this.stringReplaceAll(to," ","_");
			to = to.split(" ")[to.split(" ").length-2];
		}
		else {
			cityTo = to.replace(" ","_");
			to = to.split(" ")[0];
		}
		if(to == "NYC"){to = "JFK";}
		if(from == "NYC"){from = "JFK";}
		link.appendChild(document.createTextNode(from + " to " + to));
		jar[0].appendChild(link);
		mb("prepopMB").onclick = function(){o.prepopMB(cookieObject[0].fields[0].value,cityTo,cookieObject[0].fields[2].value,cookieObject[0].fields[3].value,cookieObject[0].fields[4].value,cookieObject[0].fields[5].value,cookieObject[0].fields[6].value,cookieObject[0].fields[7].value,cookieObject[0].fields[8].value,cookieObject[0].fields[9].value,cookieObject[0].fields[10].value);};
	}*/
	// Show MiniBooker
	mb("tdFlBooker").style.display = 'block';

  	//set package and tabs city destination
  	var destination = document.getElementsByClassName("destination");	
 

	if(this.destinationCode == "WDW") {
  		destination[0].innerHTML = "<i>Walt Disney World</i>? Resort";
  		//destination[1].innerHTML = "<i>Walt Disney World</i>? Resort";
	}
	if(this.destinationCode == "LGB") {
  		destination[0].innerHTML = "Anaheim <i>Disneyland</i>? Resort";
  		//destination[1].innerHTML = "Anaheim <i>Disneyland</i>? Resort"
	}
}


GenericPanel.prototype.setWidth = function() {
  var p = document.getElementById(this.panelId);
  if (p.style.display != "block")
    return;

  p.style.width = "700px";
  var width = 20;
  var additionalPixel = 10;

  if (/MSIE (\d+\.\d+);/.test(navigator.userAgent)){ 
     var ieversion=new Number(RegExp.$1) 
     
     if (ieversion>=7)
        additionalPixel = 20;  
  }


  var uls = p.getElementsByTagName("ul");
  for (var i = 0; i < uls.length; i++) {
    width += (uls[i].offsetWidth + additionalPixel);
  }


  // set a minimum width
  width = (width < 252) ? 252 : width;
  
  p.style.width = width + "px";
}

VacationsPanel.prototype.setWidth = function() {
  var p = document.getElementById(this.panelId);
  if (p.style.display != "block")
    return;

  p.style.width = "700px";
  var width = 20;
  var additionalPixel = 10;

  if (/MSIE (\d+\.\d+);/.test(navigator.userAgent)){ 
     var ieversion=new Number(RegExp.$1) 
     
     if (ieversion>=7)
        additionalPixel = 20;  
  }

	
 // var uls = p.getElementsByTagName("ul");
  var uls = document.getElementById("listItems3").childNodes;
  
  for (var i = 0; i < uls.length; i++) {
    width += (uls[i].offsetWidth + additionalPixel);
	
  }


  // set a minimum width
  width = (width < 252) ? 252 : width;
  
  p.style.width = width + "px";
}

// This function determines the output string of a destination based
// on the threeLetterCode.  Abstracted out because the code was being
// repeated.
GetawaysPage.prototype.getDestinationString = function(){
	tempDest = this.destinationCode;
	
	// First exceptions are those entries which appear only once in 
	// both arrays, but do not appear in the same format.
	if (tempDest == "NYC"){
		tempDest = "JFK";
	}
	// Excluding exceptions for those locations that have multiple
	// Getaways available that use the same 3 letter code multiple
	// times in VacationDests
	if (tempDest != "LGB" && tempDest != "CUZ" &&
	    tempDest != "CUN" && tempDest != "FLL" &&
	    tempDest != "LAX" && tempDest != "MIA" &&
	    tempDest != "MCO" && tempDest != "WDW"){
		for (var i=0;i<VacationDests.length;i++) {
			if (VacationDests[i][0].indexOf(tempDest) != -1) {
				returnDest = VacationDests[i][0];
				break;
			}
		}
	}
	// We need to hard code exceptions here because the VacationDests and 
	// GetawaysDestinations arrays use different abbreviations.
	else {
		switch(tempDest) {
			case "LGB":
				returnDest = "Anaheim_LGB";
				break;
			case "CUZ":
				returnDest = "Cancun_Hotel_Zone_CUN";
				break;
			case "CUN":
				returnDest = "Cancun_Riviera_Maya_CUN";
				break;
			case "FLL":
				returnDest = "Fort_Lauderdale_FLL";
				break;
			case "LAX":
				returnDest = "LA_Hollywood_LGB";
				break;
			case "MIA":
				returnDest = "Miami_FLL";
				break;
			case "MCO":
				returnDest = "Orlando_MCO";
				break;
			case "WDW":
				returnDest = "Walt_Disney_World_MCO";
				break;
		}
	}
       
	return returnDest;
}

// Set hidden whereTo input field with a value friendly to the EzRez system.
GetawaysPage.prototype.getEzRezDestination = function(){
	var tempDest = this.destinationString;
	var cityValues = '';
	var cityTo = '';
	if (tempDest.indexOf('_') != -1) {
		if (tempDest.split("_").length > 2) {
			for (i=0; i<tempDest.split("_").length; i++) {
				cityValues += tempDest.split("_")[i] + " ";
			}
			cityTo = cityValues;
		}
		else {
			cityTo = tempDest.split("_")[0] + " " + tempDest.split("_")[1];
		}
	}	
	else {
          
	  return tempDest;
	}
	
	return cityTo;
}

// Generate a friendly value based on destinationCode. 
GetawaysPage.prototype.getFriendlyDestination = function(){
	// Unlike the setDestination function, we want to use the
	// associated values in the GetawaysDestinations array
	// instead of the VacationDests array.  So no exceptions!
	
	for (var i=0;i<GetawaysDestinations.length;i++) {
		if (GetawaysDestinations[i][0] == this.destinationCode) {
			tempDest = GetawaysDestinations[i][2];
			
			break;
		}
	}
	return tempDest;
}

GetawaysPage.prototype.stringReplaceAll = function(strReplaceAll,searchfor,replacewith){
	var stringReplace = strReplaceAll.replace(/\s*$/, '');
	var intIndexOfMatch = stringReplace.indexOf(" ");
	while (intIndexOfMatch != -1) {
		// Relace out the current instance.
		strReplaceAll = strReplaceAll.replace(searchfor, replacewith);
		intIndexOfMatch = strReplaceAll.indexOf(searchfor);
	}
	strReplaceAll = strReplaceAll.slice(0, -1);
	return strReplaceAll;
}

/* Special function for Vacations: is only allowed to pick the return date as one day after departure date or beyond */ 
CalendarPair.prototype.dateSelect0 = function(type, args, obj){
	var currDate = obj.cal0.getSelectedDates()[0];
	var parsed = Date.parse(currDate.toString());
	var jbDate = obj.cal0.Locale.WEEKDAYS_MEDIUM[currDate.getDay()] + ", " +
	obj.cal0.Locale.MONTHS_SHORT[currDate.getMonth()] + " " + currDate.getDate() + ", " + currDate.getFullYear();
	mb(obj.cal0Base + "Input").innerHTML = jbDate;
	obj.cal0Hidden.value = (currDate.getMonth() + 1) + "/" + (currDate.getDate()) + "/" + currDate.getFullYear();
	if(obj.cal1Hidden.value == ""){
		obj.cal1.setMonth(currDate.getMonth());
		obj.cal1.setYear(currDate.getFullYear());
		obj.cal1.render();
	}
	else if(Date.parse(obj.cal1Hidden.value) < parsed){
		mb(obj.cal1Base + "Input").innerHTML = obj.cal1DefaultText;
		obj.cal1Hidden.value = "";
		obj.cal1.clear();
	}
	currDate = new Date((currDate.getMonth() + 1) + "/" + (currDate.getDate() + 1) + "/" + currDate.getFullYear());
	obj.cal1.cfg.setProperty("mindate", currDate);
	obj.hide(obj.cal0.oDomContainer.id);
}
  
CalendarPair.prototype.changePage1 = function(type, args, obj){
	var currDate = obj.today;
	var nextDate = obj.cal1.cfg.getProperty("pageDate");
	var maxDate = new Date(minibookerExtensionDate);
	var diff = Date.parse(nextDate.toString()) > Date.parse(currDate.toString());
	if(Date.parse(nextDate.toString()) > Date.parse(maxDate.toString())){
		obj.cal1.Style.CSS_NAV_LEFT = "calnavleft";
		obj.cal1.Style.CSS_NAV_RIGHT = "calnavH";
	}
	else if(Date.parse(nextDate.toString()) < Date.parse(maxDate.toString())){
		obj.cal1.Style.CSS_NAV_LEFT = "calnavleft";
		obj.cal1.Style.CSS_NAV_RIGHT = "calnavright";
	}
	else{
		obj.cal1.Style.CSS_NAV_LEFT = "calnavleft";
		obj.cal1.Style.CSS_NAV_RIGHT = "calnavright";
	}
	obj.cal1.render();
}


// Overwrite filter function.  There is nothing to filter as we have only one destination.
PanelPair.prototype.filter1 = function(e){}

//as there is only one destination we need to shift around the VacationsDestination array aJFK,...
GetawaysPage.prototype.getOriginAirports = function(){
	var destination = this.destinationString;

	var output = "new Array(";
	for (var i=0;i<FlightOrigins.length-1;i++){
		var newCodes = eval("a" + FlightOrigins[i][0]);
                
		for (var j=0; j<newCodes.length; j++){
                          
			if (destination == newCodes[j]){

				output += "[\"" + FlightOrigins[i][0] + "\",\"" + FlightOrigins[i][1] + "\"],";
			}
		}
	}
	output += "0);";
	var dataSrc = eval(output);
       
	return dataSrc;
}

GetawaysPage.prototype.tabs = function(){
	//var tabControls = document.getElementsByClassName("packagesTab");	
	var tabControls = $mb(".packagesTab");
	tabControls.each(function(tab){
		tab.onclick = function(){
			//hide active tab
			//var activeTab = document.getElementsByClassName("packagesTabSelected");
			var activeTab = $mb(".packagesTabSelected");
			activeTab[0].removeClassName('packagesTabSelected');
			//var activeContent = document.getElementsByClassName("packagesTabsContentActive");
			var activeContent = $mb(".packagesTabsContentActive");
			activeContent[0].removeClassName('packagesTabsContentActive');
			//show tab
			this.addClassName('packagesTabSelected');
			mb(this.id + 'Content').addClassName('packagesTabsContentActive');
		}
	});
}

GetawaysPage.prototype.openWindow = function(className, parameters){
	//var popup = document.getElementsByClassName(className);
	var popup = $mb("." + className);
	popup.each(function(link){
		link.onclick = function(){
			bookWindow = window.open(link.href, 'new_win', parameters);
			bookWindow.focus();
			return false;
		}
	});
	return false;
}

GetawaysPage.prototype.submitForm = function(){
	var result = this.validator.validate();
	var cookieObject = new Object();
	if(result.length == undefined){
		if(this.calPair.getReadable1() == this.calPair.getReadable2())
			if(!confirm("Your return date is the same as your departure date. Is such a short trip intentional?"))
				return false;
		cookieObject.displayValue = mb("area2_destination").value;
		cookieObject.fields = new Array();
		cookieObject.fields.push({"name":"area1","value":mb("area1").value,"readable":mb("panInput_0").value});
		cookieObject.fields.push({"name":"area2","value":mb("area2").value,"readable":mb("area2_destination").value});
		cookieObject.fields.push({"name":this.calPair.getName1(), "value":this.calPair.getValue1(),"readable":this.calPair.getReadable1()});
		cookieObject.fields.push({"name":this.calPair.getName2(),"value":this.calPair.getValue2(),"readable":this.calPair.getReadable2()});
		cookieObject.fields.push({"name":this.adults.getName(),"value":this.adults.getValue(),"readable":this.adults.getReadable()});
		cookieObject.fields.push({"name":this.children.getName(),"value":this.children.getValue(),"readable":this.children.getReadable()});
		cookieObject.fields.push({"name":this.infants.getName(), "value":this.infants.getValue(),"readable":this.infants.getReadable()});
		cookieObject.fields.push({"name":this.childrenAge1.getName(), "value":this.childrenAge1.getValue(),"readable":this.childrenAge1.getReadable()});						
		cookieObject.fields.push({"name":this.childrenAge2.getName(), "value":this.childrenAge2.getValue(),"readable":this.childrenAge2.getReadable()});						
		cookieObject.fields.push({"name":this.childrenAge3.getName(),"value":this.childrenAge3.getValue(),"readable":this.childrenAge3.getReadable()});						
		cookieObject.fields.push({"name":this.hotelRooms.getName(),"value":this.hotelRooms.getValue(),"readable":this.hotelRooms.getReadable()});
		//addTracking(this.cookie, cookieObject);
		document.vacationsForm.submit();
	}
	else{
		return false;
	}
}

GetawaysPage.prototype.goToDest = function(e){
	location.href= "http://www.jetblue.com/" + mb("area3").value.toLowerCase();
}

GetawaysPage.prototype.prepopMB = function(fromCity, toCity, fromdt, todt, adults,children,infants,childrenAge1,childrenAge2,childrenAge3,hotelRooms) {
	this.panel.preset(fromCity);
	//this.panelPair.panel2.preset(toCity);
	this.adults.presetAdults(adults);
	this.children.preset(children);
	this.infants.preset(infants);
	this.calPair.preset0(fromdt);
	this.calPair.preset1(todt);
	this.childrenAge1.presetChildrenAge(childrenAge1);
	this.childrenAge2.presetChildrenAge(childrenAge2);
	this.childrenAge3.presetChildrenAge(childrenAge3);
	this.hotelRooms.presetHotelRooms(hotelRooms); 
}

function showKids(on){
	if(document.getElementById){
		var kA = document.getElementById("kidsAges");
		var k1 = document.getElementById("selectObj_7");
		var k2 = document.getElementById("selectObj_8");
		var k3 = document.getElementById("selectObj_9");
		if(k1.getElementsByTagName("input")[0].value == ""){
			k1.getElementsByTagName("input")[0].value = '0';
		}
		if(k2.getElementsByTagName("input")[0].value == ""){
			k2.getElementsByTagName("input")[0].value = '0';
		}
		if(k3.getElementsByTagName("input")[0].value == ""){
			k3.getElementsByTagName("input")[0].value = '0';
		}
		switch(on){
			case 0:
				kA.style.visibility = 'hidden';  kA.style.display = 'none';
				k1.style.visibility = 'hidden';  k1.style.display = 'none';
				k2.style.visibility = 'hidden';  k2.style.display = 'none';
				k3.style.visibility = 'hidden';  k3.style.display = 'none';
				k1.getElementsByTagName("input")[0].value = "";
				k2.getElementsByTagName("input")[0].value = "";
				k3.getElementsByTagName("input")[0].value = "";
			break;
			case 1:
				kA.style.visibility = 'visible'; kA.style.display = 'block';
				k1.style.visibility = 'visible'; k1.style.display = 'block';
				k2.style.visibility = 'hidden';  k2.style.display = 'none';
				k3.style.visibility = 'hidden';  k3.style.display = 'none';
				k2.getElementsByTagName("input")[0].value = "";
				k3.getElementsByTagName("input")[0].value = "";
			break;
			case 2:
				kA.style.visibility = 'visible'; kA.style.display = 'block';
				k1.style.visibility = 'visible'; k1.style.display = 'block';
				k2.style.visibility = 'visible'; k2.style.display = 'block';
				k3.style.visibility = 'hidden';  k3.style.display = 'none';
				k3.getElementsByTagName("input")[0].value = "";
			break;
			case 3:
				kA.style.visibility = 'visible'; kA.style.display = 'block';
				k1.style.visibility = 'visible'; k1.style.display = 'block';
				k2.style.visibility = 'visible'; k2.style.display = 'block';
				k3.style.visibility = 'visible'; k3.style.display = 'block';
				break;
		}
	}
}

// Dean Edwards/Matthias Miller/John Resig
function init(){
	// quit if this function has already been called
	if (arguments.callee.done) return;
	// flag this function so we don't do the same thing twice
	arguments.callee.done = true;
	// kill the timer
	if (_timer) clearInterval(_timer);
	var page = new GetawaysPage("tdFlBookerTop");
	initLightbox();
};

/* for Mozilla/Opera9 */
if (document.addEventListener) {
	document.addEventListener("DOMContentLoaded", init, false);
}

/* for Internet Explorer */
/*@cc_on @*/
/*@if (@_win32)
	document.write("<script id=__ie_onload defer src=javascript:void(0)><\/script>");
	var script = document.getElementById("__ie_onload");
	script.onreadystatechange = function(){
		if (this.readyState == "complete"){
			init(); // call the onload handler
		}
	};
/*@end @*/

/* for Safari */
if (/WebKit/i.test(navigator.userAgent)) { // sniff
	var _timer = setInterval(function() {
		if (/loaded|complete/.test(document.readyState)) {
			init(); // call the onload handler
		}
	}, 10);
}

/* for other browsers */
window.onload = init;
