// Get some scripts imported dynamically if they're not already here:
if (typeof (dynamic_imported_scripts) == 'undefined') var dynamic_imported_scripts = new Object();
dynamic_script_import('/j/OriginRestrictions.js');

function dynamic_script_import(jsFile) {
  if (dynamic_imported_scripts[jsFile] != null) return;
  var scriptElt = document.createElement('script');
  scriptElt.type = 'text/javascript';
  scriptElt.src = jsFile;
  document.getElementsByTagName('head')[0].appendChild(scriptElt);
  dynamic_imported_scripts[jsFile] = jsFile; // or whatever value your prefer
}

var counter = 0;
var pairIndex = 0;

function getOops1(panelId) {
  return "<div class=\"book_tt12 book_tt12a\">Enter a city, region or airport and we will<br />look it up for you.<br /><br /><a href=\"javascript:showDialog('cityListDlg','" + panelId + "')\">Check out all the destinations we serve</a>.</div>";
}
//var panel = new GenericPanel( "cityFrom0", "Where to pickup car?", "MARKET1_ORIG_STATION", 0, 1, Dests,posX,posY);
//dropDownPosX,dropDownPosY defines x/y position of the open dropdown (see flights page)

function GenericPanel(targetId, title, hiddenId, pIndex, dataSrc, form, dropDownPosX, dropDownPosY) {
  this.target = document.getElementById(targetId);
  this.title = title;
  this.blankTitle = this.titleTemp = this.title;

  this.targetId = targetId;
  this.anchorId = targetId + "_anchor";
  this.hiddenId = hiddenId;
  this.inputName = "panInput_" + pIndex;
  this.panelId = targetId + "_panel";
  this.cFlag = false;
  this.pIndex = pIndex;
  this.kbIndex = -1;
  this.dropDownPosX = dropDownPosX + "px";
  this.dropDownPosY = dropDownPosY + "px";
  this.pos = pIndex;
  this.numCols = null;
  YAHOO.util.Event.addListener(targetId, "mouseover", this.targetOnMouseover, this);
  YAHOO.util.Event.addListener(targetId, "mouseout", this.targetOnMouseout, this);

  // assign an "id" to each data item
  for (var i = 0; i < dataSrc.length; i++)
    dataSrc[i][2] = i;

  this.set = dataSrc;
  this.searchSet = dataSrc;
  this.selectedItem = null;

  this.form = document.forms[form];

  var pWrapper = document.createElement("div");

  pWrapper.style.position = "relative";
  pWrapper.style.zIndex = 100 - pIndex;

  var anchor = document.createElement("a");
  anchor.id = this.anchorId;

  var jsInput = document.createElement("div");
  jsInput.className = "jsInput";

  var input = document.createElement("input");
  input.type = "text";
  input.id = this.inputName;
  input.name = this.inputName;
  input.value = this.title;
  input.setAttribute("autocomplete", "off");

  YAHOO.util.Event.addListener(input, "focus", this.inputOnFocus, this);
  YAHOO.util.Event.addListener(input, "blur", this.inputOffFocus, this);

  // might not need this one
  YAHOO.util.Event.addListener(input, "keypress", this.inputOnKeyPress, this);
  YAHOO.util.Event.addListener(input, "keyup", this.inputOnKeyUp, this);
  YAHOO.util.Event.addListener(input, "keydown", this.inputOnKeyDown, this);


  jsInput.appendChild(input);
  anchor.appendChild(jsInput);
  pWrapper.appendChild(anchor);

  var p = document.createElement("div");
  p.id = this.panelId;
  p.className = "panel";
  YAHOO.util.Event.addListener(jsInput, "click", this.panelOnClick, this);

  var pbody = document.createElement("div");
  pbody.className = "panelBody";

  var pfoot = document.createElement("div");
  pfoot.className = "panelFoot";

  var panelCloser = document.createElement("div");
  panelCloser.id = "panelCloser";

  YAHOO.util.Event.addListener(panelCloser, "click", this.closeAnchorOnClick, this);

  panelCloser.appendChild(document.createTextNode("Close"));
  pfoot.appendChild(panelCloser);
  p.appendChild(pbody);
  if (targetId != 'cityFrom0' && targetId != 'cityTo0')
    p.appendChild(pfoot);
  pWrapper.appendChild(p);

  this.target.appendChild(pWrapper);

  this.onItemSelect = new YAHOO.util.CustomEvent("onItemSelect", this);
  this.render();

  YAHOO.util.Event.addListener(window, "load", this.initPanEvents, this);
  //YAHOO.util.Event.addListener(window,'click',this.initPanEvents,this);
}


GenericPanel.prototype.targetOnMouseover = function(e, obj) {
  obj.cFlag = true;
}

GenericPanel.prototype.targetOnMouseout = function(e, obj) {
  obj.cFlag = false;
}

GenericPanel.prototype.inputOffFocus = function(e, obj) {
  if (document.getElementById('module1') != null) 
    jQuery('.jsInput').css("background-image", "url('/UnifiedMinibooker/images/inputFieldBg.gif')");
}
GenericPanel.prototype.inputOnFocus = function(e, obj) {
  var input = YAHOO.util.Event.getTarget(e);
  var inputIndex = input.name.substr(9, 1);
  
  if (document.getElementById('module1') != null) {
	  var newBg = "url('/UnifiedMinibooker/images/inputFieldActiveBg.gif')";
	  var inputElem;
	  
	  switch (inputIndex) {
		case '0':
		  inputElem = jQuery('.jsInput:eq(4)');
		  break;
		case '1':
		  inputElem = jQuery('.jsInput:eq(0)');
		  break;
		case '2':
		  inputElem = jQuery('.jsInput:eq(1)');
		  break;
		case '3':
		  inputElem = jQuery('.jsInput:eq(5)');
		  break;
		case '4':
		  inputElem = jQuery('.jsInput:eq(6)');
		  break;
		case '5':
		  inputElem = jQuery('.jsInput:eq(2)');
		  break;
		case '6':
		  inputElem = jQuery('.jsInput:eq(3)');
		  break;
	  }
	  inputElem.css("background-image", newBg);
  }
  if (input.setSelectionRange)
    input.setSelectionRange(0, input.value.length);
  if (input.value.search("Where") == -1 || (inputIndex != 1 && inputIndex != 2)) 
    input.select();

  obj.showPanel();
}

GenericPanel.prototype.inputOnKeyPress = function(e) {
  if (!e)
    e = window.event;
  if (e.keyCode == 13)
    return false;
}

GenericPanel.prototype.inputOnKeyUp = function(e, obj) {
  obj.autoComplete(e);
}

GenericPanel.prototype.inputOnKeyDown = function(e, obj) {
  obj.titleTemp = document.getElementById(obj.inputName).value;
  obj.kbListener(e);
}

GenericPanel.prototype.panelOnClick = function(e, obj) {
  if (!e)
    e = window.event;
  
  var target = e.target ? e.target.nodeName.toLowerCase() : e.srcElement.nodeName.toLowerCase();
  var targetId = e.target ? e.target.id.toLowerCase() : e.srcElement.id.toLowerCase();
  
  var xBound = document.getElementById('wideBooker') ? 257 : 183; 
  var openDialog = e.clientX - jQuery('#panInput_1').offset().left > xBound ? true : false;
  // click on icons of from/to field opens popup window (Book Flight tab only)
  if (obj.inputName == "panInput_1" && targetId == "" && openDialog) {
    showDialog("cityListDlg", "cityFrom0_panel");
    return;
  }
  if (obj.inputName == "panInput_2" && targetId == "" && openDialog) {
    showDialog("cityListDlg", "cityTo0_panel");
    return;
  }
  
  document.getElementById(obj.inputName).focus();
}

GenericPanel.prototype.closeAnchorOnClick = function(e, obj) {
  var elTarget = YAHOO.util.Event.getTarget(e);
  obj.hidePanel();
}

GenericPanel.prototype.render = function(showCities) {
  this.kbIndex = -1;

  var isBookFlightsTab = (this.targetId == 'cityFrom0' || this.targetId == 'cityTo0');
  var isVacationTab = this.targetId == 'cityFrom3' || this.targetId == 'cityTo3';
  if (isBookFlightsTab && typeof (showCities) == 'undefined')
    showCities = false;
  else
    showCities = true;

  var area = document.getElementById(this.panelId).firstChild;
  area.innerHTML = "";
  if (!showCities)
    area.innerHTML = getOops1(this.panelId);
  var total = this.searchSet.length - 1; // The last element is NULL, so don't count it.

  var realCount = 0;
  if (!isVacationTab && !isBookFlightsTab) {
    for (var i = 0; i < total; i++) {
      airport = eval('o' + this.searchSet[i][0]);
      if (airport.jb) realCount++;
    }
  } else {
    realCount = total;
  }

  var defaultMinibookerMaxRows = 18;
  if (realCount > 90) defaultMinibookerMaxRows = 32;
  var maxRows = realCount < 3 * defaultMinibookerMaxRows ? Math.ceil(realCount / 3) : defaultMinibookerMaxRows;
  if (realCount < 13) maxRows = 4; // new requirement

  var numCols = Math.ceil(realCount / maxRows);
  var numRows = Math.ceil(realCount / numCols);

  var ul, li, a, text, textNode;
  var tbl = document.createElement("table");
  var tbody = document.createElement("tbody");
  var row = document.createElement("tr");
  var cell = document.createElement("td");

  // a wrapper div used to shroud the generic click handler from all other clicks around the panel
  var container = document.createElement("div");
  container.id = "listItems" + this.pIndex;

  var liCount = 0;
  ul = document.createElement("ul");
  for (var i = 0; i < total; i++) {
    if (!isVacationTab && !this.searchSet[i][0]) continue;
    if (liCount >= numRows) {
      // The last UL was full, add it to the container and add a new one
      container.appendChild(ul);
      ul = document.createElement("ul");
      liCount = 0;
    }

    var isMacCity = window.IsMacCity && IsMacCity(this.searchSet[i][0]) ? true : false;
    var hideMacCity = isMacCity && ((new RegExp('\\b' + 'noMAC' + '\\b').test(this.target.className)) == true);
    var hideThisCity = ExcludeFromOrigin(this.panelId, this.searchSet[i][0]) || hideMacCity;

    img = document.createElement('img');
    img.src = "/UnifiedMinibooker/images/bullet.gif";
    img.className = "book_tt16_dot";

    a = document.createElement("a");
    a.id = this.pos + "-" + this.targetId + "_" + this.searchSet[i][2];
    a.href = "javascript:void(0)";
    a.className = (this.selectedItem && (this.selectedItem.id == a.id)) ? "selected" : "";

    if (isMacCity) {
      a.setAttribute('title', eval('t' + this.searchSet[i][0]));
      a.setAttribute('style', 'bold');
      a.className = a.className == "" ? "mac_city" : a.className;
    }

    text = this.searchSet[i][1];
    var airport = null;
    if (!isVacationTab) //airport obj is not available for Vacation tab
      airport = eval('o' + this.searchSet[i][0]);

    if (!hideThisCity && (isBookFlightsTab || (airport == null || airport.jb))) {
      textNode = document.createTextNode(text);
      a.appendChild(textNode);
      li = document.createElement("li");
      if (isBookFlightsTab) // show orange dot for jb cities on book flight tab only
          li.className = airport.jb ? "blueCity" : "interlineCity";
      li.appendChild(a);
      ul.appendChild(li);
      liCount++;
    }
  }

  // Append last UL (or first if there's only one) to the container.
  container.appendChild(ul);

  cell.appendChild(container);
  cell.className = "CityPanelTopCell";
  cell.setAttribute('noWrap', 'true');
  row.appendChild(cell);
  tbody.appendChild(row)

  if (this.targetId == "cityFrom2" || this.targetId == "cityTo2") {
    var row = document.createElement("tr");
    var cell = document.createElement("td");

    cell.innerHTML = "Flying on one of our partner airlines out of a city not shown here? <a target=\"_blank\" href=\"flying-on-jetblue/airline-partners/ \">Click here.</a>";
    cell.className = "CityPanelBottomCell"

    row.appendChild(cell);
    tbody.appendChild(row)
  }

  tbl.appendChild(tbody);
  if (!showCities) tbl.style.display = 'none';
  area.appendChild(tbl);
  if (navigator.appName.indexOf('Internet Explorer') == -1)
    YAHOO.util.Event.addListener(container.id, "mousedown", this.cityClick, this);
  else
    YAHOO.util.Event.addListener(container.id, "mouseup", this.cityClick, this);
  this.setWidth();
}


GenericPanel.prototype.cityClick = function(e, obj) {
  var elTarget = YAHOO.util.Event.getTarget(e);

  while (elTarget.id != obj.targetId) {
    if (elTarget.nodeName.toUpperCase() == "A") {
      obj.onclickWrap(elTarget);
      break;
    }
    else
      elTarget = elTarget.parentNode;
  }
}

GenericPanel.prototype.autoComplete = function(e) {
  var input = YAHOO.util.Event.getTarget(e);

  if (this.titleTemp == input.value)
    return;

  if (!e)
    e = window.event;

  var pbody = document.getElementById(this.panelId).getElementsByTagName("div")[0];
  var results = new Array();
  var list = this.set;
  var value = input.value.toLowerCase();
  if ((this.panelId == 'cityFrom0_panel' || this.panelId == 'cityTo0_panel') && value.length < 3) {
    pbody.innerHTML = getOops1(this.panelId);
	document.getElementById(this.panelId).style.width = "252px";
    return;
  }
  var text;
  var code;
  var parts = new Array();
  var countryCode;
  var country;

  for (var i = 0; i < list.length - 1; i++) {
    var a = eval("o" + list[i][0]);
    if (JBOnly && !a.jb) continue;
    text = list[i][1];
    text = text.toLowerCase();

    if (text.indexOf(value) > -1) {
      results[results.length] = list[i];
      continue;
    }
    // matches country name (for first tab only)
    if (this.panelId == 'cityFrom0_panel' || this.panelId == 'cityTo0_panel') {
		countryCode = eval('o' + list[i][0]).cc;
		country = eval('c' + countryCode).name.toLowerCase();
		if (country.indexOf(value) > -1) {
		  results[results.length] = list[i];
		  continue;
		}
	}
  }

  var oops = false;

  if (results.length > 0) {
    results.sort(sortResults);
    results[results.length] = 0;

    this.searchSet = results;
    this.render(true);
    var pAnchors = pbody.getElementsByTagName("a");

    if (pAnchors.length > 0) {
      if (results.length == 2) {
        pAnchors[0].className = "selected";
        //document.getElementById(this.inputName).value = pAnchors[0].innerHTML; // auto populate text field
      }
      if (this.panelId == 'cityFrom0_panel' || this.panelId == 'cityTo0_panel') {
        bDiv = document.createElement("div");
        bDiv.className = "book_tt16";
        bDiv_l = document.createElement("div");
        bDiv_l.className = "book_tt16_l";
        bA = document.createElement("a");
        bA.href = "javascript:showDialog('cityListDlg','" + this.panelId + "')";
        bText1 = document.createTextNode("See All City List");
        bA.appendChild(bText1);
        bDiv_l.appendChild(bA);

        bDiv_r = document.createElement("div");
        bDiv_r.className = "book_tt16_r";
        bImg = document.createElement("img");
        bImg.src = "/UnifiedMinibooker/images/bullet.gif";
        bImg.className = "book_tt16_dot";
        bText2 = document.createTextNode("JetBlue cities");

        bDiv_r.appendChild(bImg);
        bDiv_r.appendChild(bText2);
        bDiv.appendChild(bDiv_l);
        bDiv.appendChild(bDiv_r);
        pbody.appendChild(bDiv);
      }
    }
    else
      oops = true;
  }
  else
    oops = true;

  if (oops) {
    if (this.panelId == 'cityFrom0_panel' || this.panelId == 'cityTo0_panel')
      pbody.innerHTML = getOops1(this.panelId);
	else 
		pbody.innerHTML = "<div class=\"book_tt12 book_tt12a\">Oops! Please try again or delete your<br />entry to see everywhere we fly.</div>";		
	this.setWidth();
  }
}

GenericPanel.prototype.kbListener = function(e) {
  var list = jQuery('.CityPanelTopCell', $(document.getElementById(this.panelId))).find('a');
  var input = document.getElementById(this.inputName);
  if (!e)
    e = window.event;

  var prev;
  if (e.keyCode == 13) {
    e.target ? e.preventDefault() : e.returnValue = false;
    if (list.length == 1)
      this.kbIndex = 0;
    if (this.kbIndex == -1 || list.length == 0)
      this.hidePanel();
    else
      this.onclickWrap(list[this.kbIndex]);
    input.blur();
  }
  else if ((e.shiftKey && e.keyCode == 9) || e.keyCode == 38) {
    if (list.length == 0)
      return;
    e.target ? e.preventDefault() : e.returnValue = false;
    this.kbIndex = (this.kbIndex == 0 || this.kbIndex == -1) ? list.length - 1 : this.kbIndex - 1;
    list[this.kbIndex].className = "selected";
    prev = (this.kbIndex == list.length - 1) ? 0 : this.kbIndex + 1;
    list[prev].className = ((this.selectedItem && (this.selectedItem.id == list[prev].id)) || this.kbIndex == prev) ? "selected" : "";
  }
  else if (e.keyCode == 9 || e.keyCode == 40) {
    if (list.length == 1) { // only 1 city in selection
      this.onclickWrap(list[0]);
    }  
    if (list.length == 0) return;
    e.target ? e.preventDefault() : e.returnValue = false;
    this.kbIndex = (this.kbIndex == list.length - 1) ? 0 : this.kbIndex + 1;
    list[this.kbIndex].className = "selected";
    prev = (this.kbIndex == 0) ? list.length - 1 : this.kbIndex - 1;
    list[prev].className = ((this.selectedItem && (this.selectedItem.id == list[prev].id)) || this.kbIndex == prev) ? "selected" : "";
  }
  else if (e.keyCode == 27) {
    e.target ? e.preventDefault() : e.returnValue = false;
    this.hidePanel();
    input.blur();
  }
}

GenericPanel.prototype.onclickWrap = function(a, fromPrep) {
  this.highlight(a);
  this.setField(a.innerHTML);
  this.hidePanel();
  this.onItemSelect.fire();
  if (this.targetId == "cityFrom0" && fromPrep == undefined) {
    focusWhereTo(); //focus Where To
  }
  if (this.targetId == "cityTo0" && fromPrep == undefined) {
    setTimeout("focusCalendar0()", 100); //focus calendar 0
  }
}

GenericPanel.prototype.highlight = function(a) {
  if (this.selectedItem)
    this.selectedItem.className = "";
  this.selectedItem = a;
  document.getElementById(this.selectedItem.id).className = "selected";
  //document.getElementById("2-cityTo0_1").className = "selected";
}

GenericPanel.prototype.hideAll = function() {
  for (var i = 0; i < allPanels.length; i++) {
    if (document.getElementById(allPanels[i].panelId).style.display == "block")
      hidePanel(allPanels[i]);
  }
}

GenericPanel.prototype.setWidth = function() {
  var p = document.getElementById(this.panelId);
  if (p.style.display != "block")
    return;

  p.style.width = "700px";
  var width = 20;
  var uls = p.getElementsByTagName("ul");
  for (var i = 0; i < uls.length; i++) {
    width += (uls[i].offsetWidth + 10);
  }
  // set a minimum width
  width = (width < 252) ? 252 : width;
  p.style.width = width + "px";
}

GenericPanel.prototype.showPanel = function() {
  // clear where from/to field unless a city is selected
  if (this.panelId == "cityFrom0_panel" && document.getElementById("panInput_1").value == "Where from?")
    document.getElementById("panInput_1").value = "";
  if (this.panelId == "cityTo0_panel" && document.getElementById("panInput_2").value == "Where to?")
    document.getElementById("panInput_2").value = "";
    
  var obj = document.getElementById(this.panelId);
  if (obj.style.display == "block")
    return;

  this.searchSet = this.set;
  this.render();
  obj.style.display = "block";
  this.setWidth();
  this.setDropDownPosition();
}

GenericPanel.prototype.hidePanel = function() {
  var obj = document.getElementById(this.panelId);
  if (obj.style.display != "block")
    return;

  obj.style.display = "none";
  this.cFlag = false;
  var input = document.getElementById(this.inputName);
  inputValue = this.selectedItem ? this.set[this.selectedItem.id.split("_")[1]][1] : this.title;
  input.value = inputValue;
}

GenericPanel.prototype.setField = function(text) {
  document.getElementById(this.inputName).value = text;
  this.form[this.hiddenId].value = this.set[this.selectedItem.id.split("_")[1]][0];
}

GenericPanel.prototype.panOffClick = function(e, obj) {
  if (!obj.cFlag)
    obj.hidePanel();
}

GenericPanel.prototype.getReadable = function() {
  return document.getElementById(this.inputName).value;
}

GenericPanel.prototype.getValue = function() {
  return this.form[this.hiddenId].value;
}

GenericPanel.prototype.getName = function() {
  return this.hiddenId;
}

GenericPanel.prototype.initPanEvents = function(e, obj) {
  YAHOO.util.Event.addListener(document.body, "click", obj.panOffClick, obj);
}

GenericPanel.prototype.preset = function(key, showFocus) {
  var id = this.getIDfromKey(key);
  if (id == null) {
    var a = new Object();
    a.innerHTML = this.blankTitle;
  }
  var a = $(this.pos + "-" + this.targetId + "_" + id);
  var fromPrep = showFocus == undefined || showFocus == false ? true : undefined;
  this.onclickWrap(a, fromPrep);
}

GenericPanel.prototype.resetSearchSet = function() {
  this.searchSet = this.set;
  this.render();
}

GenericPanel.prototype.reset = function() {
  document.getElementById(this.inputName).value = this.blankTitle;
  this.form[this.hiddenId].value = "";
  this.selectedItem = null;
}

GenericPanel.prototype.getIDfromKey = function(key) {
  var i;

  for (i = 0; i < this.searchSet.length; i++)
    if (this.set[i][0] == key)
    return i;
  return null;
}

GenericPanel.prototype.getAfromKey = function(key) {
  var id = this.getIDfromKey(key);
  return $(this.pos + "-" + this.targetId + "_" + id);
}

GenericPanel.prototype.setDropDownPosition = function() {
  if (this.form.id == "perfectDealForm") {
    var p = document.getElementById(this.panelId);
    p.style.left = (p.style.width > "343px") ? "-180px" : "0px";
  }

}

GenericPanel.prototype.prepopPanel = function() {
  if ($(this.hiddenId).value != "")
    this.preset($(this.hiddenId).value);
}



