var counter = 0;
var pairIndex = 0;
var defaultMinibookColSize = 18; // default column size of minibooker city panel

function VacationsPanel(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);
  }


VacationsPanel.prototype.targetOnMouseover = function(e, obj) {
  obj.cFlag = true; 
  }

VacationsPanel.prototype.targetOnMouseout = function(e, obj) {
  obj.cFlag = false; 
  }

VacationsPanel.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();
  }

VacationsPanel.prototype.inputOnKeyPress = function(e) {
  if(!e) 
    e = window.event;
  if(e.keyCode==13)
    return false;
  }

VacationsPanel.prototype.inputOnKeyUp = function(e, obj) {
    obj.autoComplete(e);
  }

VacationsPanel.prototype.inputOnKeyDown = function(e, obj) {
  obj.titleTemp = document.getElementById(obj.inputName).value;
  obj.kbListener(e);
  }

VacationsPanel.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();
  }

VacationsPanel.prototype.closeAnchorOnClick = function(e, obj) {
  var elTarget = YAHOO.util.Event.getTarget(e);    
    obj.hidePanel();
  }

  VacationsPanel.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;
      
      var row = document.createElement("tr");
      var cell = document.createElement("td");
      
      var jetText = document.createTextNode("Destinos de las Escapadas");
      cell.appendChild(jetText);
      cell.className = "CityPanelTopCell";
      row.appendChild(cell);
      tbody.appendChild(row);
      tbl.appendChild(tbody);
      
      
      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);

      }
      
      var row = document.createElement("tr");
      var cell = document.createElement("td");
      
      cell.appendChild(container);

      cell.setAttribute('noWrap','true');
      row.appendChild(cell);
      tbody.appendChild(row)
      
      var row = document.createElement("tr");
      var cell = document.createElement("td");
      
      var jetText = document.createTextNode("Destinos de Estilos de Vida");
      cell.appendChild(jetText);
      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();
      
      //render lifestyle destinations
      this.renderLifeStyleDestinations(tbody);
  }


VacationsPanel.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; 
    }   
  }

VacationsPanel.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();
    }

  }

VacationsPanel.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();
    }
  }

VacationsPanel.prototype.onclickWrap = function(a) {
    this.highlight(a);
    this.setField(a.innerHTML);
    this.hidePanel();
    this.onItemSelect.fire(); 
  }

VacationsPanel.prototype.highlight = function(a) {
  if(this.selectedItem)
    this.selectedItem.className = "";
  this.selectedItem = a;
  document.getElementById(this.selectedItem.id).className = "selected";
  }

VacationsPanel.prototype.hideAll = function() {
  for(var i=0; i<allPanels.length; i++) {
    if(document.getElementById(allPanels[i].panelId).style.display == "block")
      hidePanel(allPanels[i]);
    }
  }

VacationsPanel.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";
  p.style.width = "600px";
  }

VacationsPanel.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();
  }

VacationsPanel.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;
  }

VacationsPanel.prototype.setField = function(text) {
  document.getElementById(this.inputName).value = text;
  this.form[this.hiddenId].value = this.set[this.selectedItem.id.split("_")[1]][0];
  }

VacationsPanel.prototype.panOffClick = function(e, obj) {
  if(!obj.cFlag)
    obj.hidePanel();
  }

VacationsPanel.prototype.getReadable = function() {
  return document.getElementById(this.inputName).value;
  }

VacationsPanel.prototype.getValue = function() {
  return this.form[this.hiddenId].value;
  }

VacationsPanel.prototype.getName = function() {
  return this.hiddenId;
  }

VacationsPanel.prototype.initPanEvents = function(e, obj) {
 
  YAHOO.util.Event.addListener(document.body, "click", obj.panOffClick, obj);
  }

VacationsPanel.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);
  }

VacationsPanel.prototype.reset = function() {
  document.getElementById(this.inputName).value = this.blankTitle;
  this.form[this.hiddenId].value = "";
  this.selectedItem = null;
  }

VacationsPanel.prototype.getIDfromKey = function(key) {
  var i;

  for (i=0; i<this.searchSet.length; i++)
    if (this.set[i][0] == key)
      return i;
  return null;
  }

VacationsPanel.prototype.getAfromKey = function(key) {
  var id = this.getIDfromKey(key);
  return $(this.pos + "-" + this.targetId + "_" + id);
  }

VacationsPanel.prototype.setDropDownPosition = function() {
 if(this.form.id == "perfectDealForm") {
   var p = document.getElementById(this.panelId);
  p.style.left = (p.style.width > "343px") ? "-180px" : "0px";
 }

}

VacationsPanel.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;
}

/* LifeStyle Destinations Panel */

VacationsPanel.prototype.gotoLifestyleDest = function(event) {
	// IE doesn't pass event into the parameter

	if ( !event ) {
          event = window.event;
	}

	var target = event.target ? event.target : event.srcElement;
	var airportcode = target.rel;
	
	location.href="http://hola.jetblue.com/enes/traveldeals/getaways/lifestyle/" + airportcode.toLowerCase();
}

VacationsPanel.prototype.renderLifeStyleDestinations = function(tableTbodyContainer) {
	var counter = 0;
	var pairIndex = 0;
	var defaultMinibookColSize = 180; // default column size of minibooker city panel
    this.kbIndex = -1;
	  this.searchSet = LifeStyleDestinations;

      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 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_lifestyle = document.createElement("div");
      container_lifestyle.id = "LifeStylelistItems" + this.pIndex;
      while (start < total) {
          ul = document.createElement("ul");
	ul.style.width = "180px";

          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;
	      a.rel = this.searchSet[i][0];
              a.href = "http://hola.jetblue.com/enes/traveldeals/getaways/lifestyle/" + this.searchSet[i][0];
              a.onclick = this.gotoLifestyleDest;
              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_lifestyle.appendChild(ul);

      }
      
      if (totalCols < 3) 
          ul.style.width = "360px";
      
      cell.appendChild(container_lifestyle);
      row.appendChild(cell);
      tableTbodyContainer.appendChild(row);
}