/**
* DD_belatedPNG: Adds IE6 support: PNG images for CSS background-image and HTML <IMG/>.
* Author: Drew Diller
* Email: drew.diller@gmail.com
* URL: http://www.dillerdesign.com/experiment/DD_belatedPNG/
* Version: 0.0.8a
* Licensed under the MIT License: http://dillerdesign.com/experiment/DD_belatedPNG/#license
*
* Example usage:
* DD_belatedPNG.fix('.png_bg'); // argument is a CSS selector
* DD_belatedPNG.fixPng( someNode ); // argument is an HTMLDomElement
**/

function FlightsPage(container) {
  
  this.container = container;
  this.cookie = "flightPageCookie";
  this.browserBackCookie = "FlightsBrowserBackCookie";
  
  //reset values

  // ajax widgets
  this.travelDeals = new TravelDeals("flight", document.getElementById("dealsList"), document.getElementById("tdLoader"),     document.getElementById("tdMessage"), document.getElementById("tdError"),null);
  //this.travelDeals.getDeals();

  var o = this;
  this.travelDeals.onload = function() {
    o.resultCountLoaded();
  }
  
  var cookie = getCookie(this.cookie);

  
  //parse url parameters, preset minibooker
  var urlVars = getURLParameters();

  if(urlVars.from || urlVars.to) {
      if (urlVars.from) {
          var fromObj = eval('o' + urlVars.from);
          jQuery('#from_field').attr('value', fromObj.name);
      this.travelDeals = new TravelDeals("flight", document.getElementById("dealsList"), document.getElementById("tdLoader"), document.getElementById("tdMessage"), document.getElementById("tdError"), urlVars.from);
      this.travelDeals.getDeals();

    }
  }
  else {
      this.travelDeals.getDeals();
      //this.panel1.onItemSelect.subscribe(this.filter1, this, true);    
  }

  //this.panel1.onItemSelect.subscribe(this.filter1, this, true);
 


  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.href = "#";
      link.id = "prepopMB";

      link.title = cookieObject[0].fields[0].value + " to " +
                 cookieObject[0].fields[1].value + " on " +
                 cookieObject[0].fields[2].value + " returning " +
                 cookieObject[0].fields[3].value + " - " +
                 cookieObject[0].fields[4].value + ", " +
                 cookieObject[0].fields[5].value + ", ";

      link.appendChild(document.createTextNode(cookieObject[0].displayValue));

      jar[0].appendChild(link);
      //recent search link
      $("prepopMB").onclick = function () {
          o.prepopMB(cookieObject[0].fields[0].value, cookieObject[0].fields[1].value, cookieObject[0].fields[2].value, cookieObject[0].fields[3].value, cookieObject[0].fields[4].value, cookieObject[0].fields[5].value, cookieObject[0].fields[7].value, cookieObject[0].fields[8].value, cookieObject[0].fields[9].value, cookieObject[0].fields[6].value);
      }
  }  

}

//FlightsPage.prototype.setPromoPrice = function() {
//	//get all prices and put it into array
//	var ul = document.getElementById("dealsList");
//	var li = ul.getElementsByTagName("li");
//	var price = Array();

//	for(i=0;i<li.length;i++) {
//		var div = li[i].getElementsByTagName("div");
//		var img = div[0].getElementsByTagName("img");
//		price.push(img[0].alt);
//	}

//	
//	//sort array
//        for(var i=0;i<price.length;i++) //Hold the first element
//	{
//		for(var j=i+1;j<price.length;j++) //Hold the next element from the first element
//		{
//			if(Number(price[i]) > Number(price[j]))	//comparing first and next element
//			{
//				tempValue = price[j];	
//				price[j] = price[i];
//				price[i] = tempValue;
//			}
//		}
//	}
//}

//FlightsPage.prototype.filter1 = function(e) {
//  var panel1Value = this.panel1.getValue()
//  var panel2Value = this.panel2.getValue();
//  var newCodes = eval("r" + panel1Value);
//  
//  // sort newCode based on airport names
//  var tmpSet = new Array();
//  var tmpCode = new Array();
//  for (var i = 0; i < newCodes.length-1; i++) {
//    var cityObj = eval("o" + newCodes[i]);
//    tmpSet.push(cityObj);
//  }
//  tmpSet.sort(compareObject);
//  for (var i = 0; i < tmpSet.length; i++)
//    tmpCode.push(tmpSet[i].code);
//  tmpCode.push(0);
//  newCodes = tmpCode;
//  
//  var newSet = new Array();
//  var reselect = false; 
//  
//  for(var i=0; i<newCodes.length-1; i++) {
//    cityObj = eval("o" + newCodes[i]);
//    newSet.push(new Array(newCodes[i], cityObj.name, i));
//  }
//  newSet.push(0);
//  
//  if(panel2Value != "") {
//    for(var i=0; i<newCodes.length; i++) {
//      if(panel2Value == newCodes[i]) {
//        reselect = true;
//        break;
//      }
//    }
//  }

//  this.panel2.set = newSet;
//  this.panel2.searchSet = newSet;
//  this.panel2.render();

//  if(reselect) {
//    this.panel2.highlight(this.panel2.getAfromKey(panel2Value));
//  }
//  else { 
//    this.panel2.reset();
//  }
//  this.getDeals();
//  showToWhere(this.panel1.getValue());
//}

//FlightsPage.prototype.submitForm = function() {
//  var result = this.validator.validate();
//  var cookieObject = new Object();

//  if(result.length === undefined) {
//    if ((eval(this.adults.getValue()) + eval(this.children.getValue())) > 9){
//      alert("You are allowed a maximum of " + 9 + " passengers\nper booking online. If your party is larger\nthan this, please call our reservation center.")
//      return false 
//     }

//    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;  

//    var todayDate = new Date(); 
//    var todayDate = todayDate.getMonth() + 1 + "/" + todayDate.getDate() + "/" + todayDate.getFullYear();

//    if(todayDate == this.calPair.getValue1()) {
//      alert("Because you've selected today's date, only flights that leave at least 1 hour and 30 minutes from the current time will be shown on the next page.");
//    }

//    if(parseInt(this.adults.getValue()) == 0 && parseInt(this.children.getValue()) > 0) {
//      alert("\n\nChildren between the ages of 5 and under 14 years who will be traveling alone are considered unaccompanied minors.\n\nUnaccompanied minors may only travel on nonstop or direct flights (flight that make a stop but do not change aircraft). No connecting flights.\n\nFlights booked before May 1, 2008, are subject to a \04450 fee per person each way for unaccompanied minors. Effective May 1, 2008, the fee will be \04475.\n\nOnce booked, please call 1-800-JETBLUE (538-2583) to provide us with the name, address and phone number, as it appears on the photo ID, of the person dropping off and picking up the child. The fee will also be assessed at that time.\n");
//    } 

//    if(parseInt(this.adults.getValue()) == 0 && parseInt(this.children.getValue()) == 0) {
//      alert("You must enter at least one passenger.");
//      return false;
//    }

//   /* if($('multicity').checked == true) {
//      if(this.panelPair.panel1.getValue() != this.MultiCityPanelPair.panel2.getValue() && this.MultiCityPanelPair.panel1.getValue() != this.panelPair.panel2.getValue()) {
//        alert("\n\nThe multi-city function must include\nitineraries connected via one airport.\nThis can be either your originating or\nreturn airport. For all other multi-city\nflights please book separate one-way\nreservations.\n");
//        return false;
//      }

//      if(this.MultiCityPanelPair.panel1.getValue() == "" || this.MultiCityPanelPair.panel2.getValue() == "") {
//        alert("\nYou have selected a multi-city search, but you have\nnot entered a complete city pair for the return flight.\nPlease choose both cities.\n");
//        return false;
//      }
//    }
//   */
//    this.skylightsFormatting();

//    //TripType Multicity or Roundtrip
//    var tripType = "";
//    if($('rt').checked == true)
//      tripType = 0;
//    if($('ow').checked == true)
//      tripType = 1;
//    //if($('multicity').checked == true)
//      //tripType = 3;


//   if ( tripType == 1 ) {
//      OWAlert( $("sector1_d").value );
//   }

//    

//    //create recent search cookie
//    cookieObject.displayValue = this.panelPair.panel1.getValue() + " to " + this.panelPair.panel2.getValue();
//    cookieObject.fields = new Array();

//    cookieObject.fields.push({"value" : this.panelPair.panel1.getValue()});
//    cookieObject.fields.push({"value" : this.panelPair.panel2.getValue()});
//    cookieObject.fields.push({"value" : this.calPair.getValue1()});
//    cookieObject.fields.push({"value" : this.calPair.getValue2() });
//    cookieObject.fields.push({"value" : this.adults.getValue()});
//    cookieObject.fields.push({"value" : this.children.getValue()});
//    cookieObject.fields.push({"value" : this.fares.getValue()});
//    cookieObject.fields.push({"value" : tripType});
//    cookieObject.fields.push({"value" : ""});
//    cookieObject.fields.push({"value" : ""});

//    //save cookie
//    addTracking(this.cookie, cookieObject);

//    return true;
//    }
//  else
//    return false;
//  }


//FlightsPage.prototype.skylightsFormatting = function() {
//  var parts = this.calPair.getValue1().split("/");
// 
//  var month1 = parts[0];
//  // add leading zero
//  month1 = (month1 < 10) ? "0" + parts[0] : parts[0];
//  
//  var day1 = parts[1];
//  // add leading zero
//  day1 = (day1 < 10) ? "0" + parts[1] : parts[1];
// 
//  var year1 = parts[2];

//  parts = this.calPair.getValue2().split("/");
// 
//  var month2 = parts[0];
//  // add leading zero
//  month2 = (month2 < 10) ? "0" + parts[0] : parts[0];
//  
//  var day2 = parts[1];
//  // add leading zero
//  day2 = (day2 < 10) ? "0" + parts[1] : parts[1];
//  var year2 = parts[2];

//  document["flightsForm"].m1.value = year1 + month1 + day1 + this.panelPair.panel1.getValue() + this.panelPair.panel2.getValue();
//  document["flightsForm"].sector1_o.value = this.panelPair.panel1.getValue();
//  document["flightsForm"].sector_1_d.value = day1;
//  document["flightsForm"].sector_1_m.value = "" + month1 + year1;
//  
//  if (this.calPair.getValue2() == "xxx") {
//    document["flightsForm"].m2.value="";
//    document["flightsForm"].nom.value="1";
//  }
//  else {
//    document["flightsForm"].m2.value = year2 + month2 + day2 + this.panelPair.panel2.getValue() + this.panelPair.panel1.getValue();
//    document["flightsForm"].sector1_d.value = this.panelPair.panel2.getValue();
//    document["flightsForm"].sector_2_d.value = day2;
//    document["flightsForm"].sector_2_m.value = "" + month2 + year2;
//    document["flightsForm"].nom.value="2";
//  }
//	
//  document["flightsForm"].pT.value = document["flightsForm"].CHILD.value + "CHILD" + document["flightsForm"].ADULT.value + "ADULT";

//  document.dest1Form.dIndex.value = document["flightsForm"].sector1_d.selectedIndex;
//}

FlightsPage.prototype.getDeals = function(e) {
  if(this.panel1.getValue() != "" && this.panel2.getValue() == "") {
     this.travelDeals.getDeals(this.panel1.getValue(), "");
     showToWhere(this.panel1.getValue());     
  }
  else if(this.panel1.getValue() != "" && this.panel2.getValue() != "") {
    this.travelDeals.getDeals(this.panel1.getValue(), this.panel2.getValue());
  }
  else if(this.panel1.getValue() == "" && this.panel2.getValue() != "") {
   this.travelDeals.getDeals("", this.panel2.getValue());
  }

  this.showResultCount();
}

FlightsPage.prototype.resultCountLoaded = function(e) {
  this.showResultCount();
}

FlightsPage.prototype.showResultCount = function() {
  var el = document.getElementById("countDisplay");
  if (document.getElementById("hdnCount") != null) {
      var count = document.getElementById("hdnCount").value;
//      message = "We found " + count + " deals from " + this.panel1.getReadable();
//      el.innerHTML = message;

  }
//  if($("area2").value != "") {
//    el.innerHTML += " to " + this.panel2.getReadable(); 
//    $("seeDeals").innerHTML = "<a href='#'>See all deals from " + $("area1").value + "</a>";
//  }  

  var tdHeader = document.getElementById("cityToContainer"); 
	
  //this.setPromoPrice(); 
}

function showToWhere(place) {
  
  var container = document.getElementById("cityToContainer");
  container.className = container.className.replace("off-left ", "");
}

FlightsPage.prototype.prepopMB = function(fromCity, toCity, fromdt, todt, adults,children,tripType,Multicityfrom,Multicityto,fare) {
  this.panelPair.panel1.preset(fromCity);
  this.panelPair.panel2.preset(toCity);
  this.adults.presetAdults(adults);
  this.children.preset(children);
  this.calPair.preset0(fromdt);

  if(todt != "")
    this.calPair.preset1(todt);

  if(todt != "xxx")
    this.calPair.preset1(todt);
  
   if(tripType == '0') {
     $('rt').checked = true;
   }
   else  {
     $('ow').checked = true;  
     this.calPair.disableCal(); 
   }
   //else {
     //this.MultiCityPanelPair.panel1.preset(Multicityfrom);
     //this.MultiCityPanelPair.panel2.preset(Multicityto);
     //$("multiCityDiv").style.display = 'block';
     //this.calPair.reenableCal();
     //$('multicity').checked = true;
  //}
        
}



// Dean Edwards/Matthias Miller/John Resig

function initFlightsPage() {
  // 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 FlightsPage("tdFlBookerTop");

};

/* for Mozilla/Opera9 */
if (document.addEventListener) {
  document.addEventListener("DOMContentLoaded", initFlightsPage, false);
}

/* for Internet Explorer */
/*@cc_on @*/
/*@if (@_win32)
  document.write("<script id=__ie_onload defer><\/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)) {
      initFlightsPage(); // call the onload handler
    }
  }, 10);
}

/* for other browsers */
window.onload = initFlightsPage;

