var counter = 0;
var pairIndex = 0;
var defaultMinibookColSize = 18; // default column size of minibooker city panel

//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.length == 3 && typeof(eval("s" + title)) == "string") ? eval("s" + title) + " (" + 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); 

  // 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(pWrapper, "click", this.panelOnClick, this); 

  var pbody = document.createElement("div");
  pbody.className = "panelBody";

  var pfoot = document.createElement("div");
  pfoot.className = "panelFoot";

  var pfootInnerDiv = document.createElement("div");

  var closeAnchor = document.createElement("a");
  closeAnchor.href = "javascript:void(0)";
  YAHOO.util.Event.addListener(closeAnchor, "click", this.closeAnchorOnClick, this); 

  var closeBtn = document.createElement("img");
  closeBtn.src = "http://hola.jetblue.com/img/jetblue/ES_1502.gif";

  closeAnchor.appendChild(closeBtn);
  pfootInnerDiv.appendChild(closeAnchor);
  pfoot.appendChild(pfootInnerDiv);
  p.appendChild(pbody);
  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.inputOnFocus = function(e, obj) {
  var input = YAHOO.util.Event.getTarget(e);    

  if(input.setSelectionRange)
    input.setSelectionRange(0, input.value.length);
  else
    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();
    if(target == "li" || target == "div" || target == "ul" || target == "h5")
      document.getElementById(obj.inputName).focus();
  }

GenericPanel.prototype.closeAnchorOnClick = function(e, obj) {
  var elTarget = YAHOO.util.Event.getTarget(e);    
    obj.hidePanel();
  }

  GenericPanel.prototype.render = function() {
      this.kbIndex = -1;

      var area = document.getElementById(this.panelId).firstChild;
      area.innerHTML = "";

      var total = this.searchSet.length - 1;
      if (total <= defaultMinibookColSize * 2) 
      	colSize = Math.ceil(total/3) > 0 ? Math.ceil(total/3) : 1;
      else
        colSize = defaultMinibookColSize;
      var numCols = (this.numCols) ? this.numCols : Math.ceil(total / colSize);
      var totalCols = numCols;
      var start = 0;
      var width = 0;
      var startTemp, end, 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;
      while (start < total) {
          ul = document.createElement("ul");

          startTemp = start;
          end = Math.ceil((total - start) / numCols);
          for (var i = start; i < startTemp + end; i++) {
              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" : "";
              // click handlers for the a tags happen on the parent so we only use 1 click handler

              if (window.IsMacCity && IsMacCity(this.searchSet[i][0])) {
                  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];

              if (!ExcludeFromOrigin(this.panelId, this.searchSet[i][0])) {
                  textNode = document.createTextNode(text);
                  a.appendChild(textNode);
                  li = document.createElement("li");
                  li.appendChild(a);
                  ul.appendChild(li);
              }

              start++;
          }
          numCols--;
          container.appendChild(ul);

      }
      if (totalCols < 3) 
          ul.style.width = "360px";
      cell.appendChild(container);
      cell.className = "CityPanelTopCell";
      cell.setAttribute('noWrap','true');
      row.appendChild(cell);
      tbody.appendChild(row)
      
      var row = document.createElement("tr");
      var cell = document.createElement("td");
      
      var jetText = document.createTextNode("Viaja desde Europa y otros lugares");
      if (this.panelId.indexOf("a") > -1)
      	jetText = document.createTextNode("Viaja a Europa y otros lugares");
      var separator1 = document.createElement("span");
      var separator2 = document.createElement("span");
      separator1.className = "CityPanelSeparator";
      separator2.className = "CityPanelSeparator";
      
      var aLH = document.createElement("a");
      aLH.href = "http://hola.jetblue.com/enes/about/ourcompany/lufthansa/";
      var imgLH = document.createElement('img');
      imgLH.setAttribute('src', 'http://www.jetblue.com/UnifiedMinibooker/images/L_logo_normal.gif');
      imgLH.onmouseover = function(){this.setAttribute('src', 'http://www.jetblue.com/UnifiedMinibooker/images/L_logo_rollover.gif')};
      imgLH.onmouseout = function(){this.setAttribute('src', 'http://www.jetblue.com/UnifiedMinibooker/images/L_logo_normal.gif')};
      imgLH.className = "CityPanelImage";
      aLH.appendChild(imgLH);
      
      var aAL = document.createElement("a");
      aAL.href = "http://hola.jetblue.com/enes/about/ourcompany/aerlingus/";
      var imgAL = document.createElement('img');
      imgAL.setAttribute('src', 'http://www.jetblue.com/UnifiedMinibooker/images/A_logo_normal.gif');
      imgAL.onmouseover = function(){this.setAttribute('src', 'http://www.jetblue.com/UnifiedMinibooker/images/A_logo_rollover.gif')};
      imgAL.onmouseout = function(){this.setAttribute('src', 'http://www.jetblue.com/UnifiedMinibooker/images/A_logo_normal.gif')};
      imgAL.className = "CityPanelImage";
      aAL.appendChild(imgAL);

      cell.appendChild(jetText);
      cell.appendChild(separator1);
      cell.appendChild(aLH);
      cell.appendChild(separator2);
      cell.appendChild(aAL);
      
      cell.className = "CityPanelBottomCell";
      row.appendChild(cell);
      tbody.appendChild(row)
      
      tbl.appendChild(tbody);
      
      area.appendChild(tbl);
      YAHOO.util.Event.addListener(container.id, "mousedown", 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 results = new Array();
  var list = this.set;
  var value = input.value.toLowerCase();
  var text;
  var code;
  var parts = new Array();
 
  for(var i=0; i<list.length-1; i++) {
    text = list[i][1];
    text = text.toLowerCase();
    
    if(text.indexOf(value) == 0) {
      results[results.length] = list[i];
      continue;
    }
   
    text = list[i][0];
    text = text.toLowerCase(); 
    if(text.indexOf(value) == 0) {
      results[results.length] = list[i];
      break;
    }
  }

  results[results.length] = 0;

  var pbody = document.getElementById(this.panelId).getElementsByTagName("div")[0];
  if(results.length > 1) {
    this.searchSet = results;
    this.render();
    if(results.length == 2)
      pbody.getElementsByTagName("a")[0].className = "selected";
    }
  else {
    pbody.innerHTML = "<ul><li><h5>\241Uy! Intenta nuevamente o borra tu<br />acceso para ver los lugares adonde volamos.</h5></li></ul>";
    this.setWidth();
    }

  }

GenericPanel.prototype.kbListener = function(e) {
    var list = document.getElementById(this.panelId).getElementsByTagName("div")[0].getElementsByTagName("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 == 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) {
    this.highlight(a);
    this.setField(a.innerHTML);
    this.hidePanel();
    this.onItemSelect.fire(); 
  }

GenericPanel.prototype.highlight = function(a) {
  if(this.selectedItem)
    this.selectedItem.className = "";
  this.selectedItem = a;
  document.getElementById(this.selectedItem.id).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);
  }
  p.style.width = width + "px";
  }

GenericPanel.prototype.showPanel = function() {
  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);
  input.value = this.selectedItem ? this.set[this.selectedItem.id.split("_")[1]][1] : this.title;
  }

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) {
  var id = this.getIDfromKey(key);
  if (id == null)
    {
    var a = new Object();  
    a.innerHTML = this.blankTitle;
    }
  var a = $(this.pos + "-" + this.targetId + "_" + id);
  this.onclickWrap(a);
  }

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);
}


/* These functions enact the restriction against one-way flights originating in a foreign country
 * where we do not yet have permission 
 */

// Define your popup messages here:
MBJ_popup = "***Disclaimer***\n\nPurchasing a one way flight to Montego Bay, Jamaica does not guarantee return to originating city. Return service on JetBlue Airways from Sangster International Airport is subject to receipt of Jamaican operating authority and is NOT currently available for purchase except as part of a roundtrip itinerary.\n\nTravel currently must be purchased and originate in the United States only; itineraries that begin in Montego Bay will be available for sale at a later date, pending final government approval."

// Detect and alert certain cities:
function ExcludeFromOrigin (panelID, liText)
{
  if ( panelID.match('Desde') && liText )
  {
    // EXAMPLE: MBJ:
    //if (liText.match('(MBJ)'))
    //  return true;

    // ???: Add more here as necessary.
  }

  return false;
}

function OWAlert(cityCode)
{
  // EXAMPLE: MBJ:
  //if (cityCode == 'MBJ')
  //{
  //  alert(MBJ_popup);
  //  return true;
  //}

  // ???: Add more here as necessary.

  return false;
}