var FuncionOnChangeIATA=null;//Para llamar a una función de callback cuando cambie el iata
var MaxItemsDesplegable=22;
var AltoFilaOpcion=15;

var BannerText = "#921700";
var BannerBackgroundColour = "#F8AE44";
var IATATextColour = "#FF0000"; // Rojo
var NonSelectedBackground = "white";
var SelectedBackground="#6297D2";
var SelectedText = "white";
var FontSize = "11px";

var ExtraWidth = 1.9; // Factor to increase knockout window above textbox
var w=""; // action - set to query
var pa=false; // always false
var ta=""; // value of the textbox?
var da=false; // da is set true when the form is about to submit
var g=""; // value of the textbox?
var G=""; // value of the textbox?
var m=""; // the key pressed
var j=-1; // selected option index
var h=null; // reference to the currently selected index
var Z=-1; // set to 0 when pa is called (unsure of meaning)
var za=null; // an array of div elements
var Ca=5; // something related to the height of the dropdown
var q=""; // holds the currently selected option
var Lb="div"; // used to enumerate Z
var Bb="span";  // used in Qa
var la=null; // form name
var a=null; // text box
var b=null; // a reference to an option in the list
var Xa=null; // Iata
var mb=null; // used for some frame thing when w is set to url.
var X=null; // something to do with multiple locales
var ha=null; // locale
var ra=false; // something to do with textbox focus
var kc=null; // not used
var hc=null; // not used
var Ua=new Object(); // cache array
var ca=1; // border width
var Aa=1; // border width
var Y=false; // Chinese locale
var na=-1; // last key pressed
var Va=(new Date()).getTime(); // now
var Q=false; // if we have a reference to the xml HTTP object
var k=null; // xmlhttp object
var sa=null; // url, including locale
var E=null; // url, exluding locale
var B=null; // reference to an IFrame
var aa=null; // the value of the textbox
var Ba=false; // something to do with multiple locales
var Ka=false; // seems to be always false
var p=60; // width in percent
var ia=null; // call back url
var ya=null; // always false for this implementation
var W=0; // number of successful calls to server
var ifKnockout=null; // IFrame.
var iata=null;

function UnInstall()
{
//Si estaba buscando tenía el icono del rayo parpadeando, le dejo el de por defecto
//Solo para Tracerdog
if (a)
  {
  newImage = "url(ImagenesBuscador/FondoEditAeropuerto.gif)";
  a.style.backgroundImage = newImage;
  }
//---------------------------------------------------------------------------------
	
	if(document.getElementById('completeDiv')!= null)
	{
		var elem = document.getElementById('completeDiv');
		elem.parentNode.removeChild(elem);
		}
	if(document.getElementById('completionFrame')!= null)
	{
		var elem = document.getElementById('completionFrame');
		elem.parentNode.removeChild(elem);
	}
	if(document.all && document.getElementById('ifKnockout')!= null)
	{
		var elem = document.getElementById('ifKnockout');
		elem.parentNode.removeChild(elem);
	}	
	
		
	w=""; // action, set to query
	pa=false;
	ta=""; // value of the text box
	da=false;
	g="";
	G="";
	m="";
	j=-1;
	h=null;
	Z=-1;
	za=null;
	Ca=5;
	q="";
	Lb="div";
	Bb="span";
	la=null; // form name
	a=null;
	b=null;
	Xa=null;
	mb=null;
	X=null;
	ha=null; // locale
	ra=false;
	kc=null;
	hc=null;
	Ua=new Object(); // cache array
	ca=1;
	Aa=1;
	Y=false;
	na=-1;
	Va=(new Date()).getTime();
	Q=false; // if we have a reference to the xmlHTTP object	
	k=null;
	sa=null;
	E=null;
	B=null;
	aa=null;
	Ba=false;
	Ka=false;
	p=60;
	ia=null; // call back url
	ya=null;
	W=0; // number of successful calls to the server
	ifKnockout=null;
	iata=null;
	//ac();
	
	//b= document.getElementById('completeDiv');
	//ba();
	//db();
}
// Called from the page (entry function?)
// InstallAC(document.CFLiveSearch,item,null,"SuggestResult.aspx","en");

//LO Llaman así --> InstallAC(document.CFLiveSearch,item,document.getElementById(iata),"SuggestResult.aspx","en");	
function InstallAC(frm,fld,sb,pn,rl,hd,sm,ufn){
  la=frm; // form name
  a=fld; // text box
  Xa=sb; // Iata textbox
  if(!pn) {
    pn="search"; // call back url
  }
  ia=pn; // call back url
  var Kb="en|";
  var Jb="zh-CN|zh-TW|ja|ko|vi|";
  if(!rl||Kb.indexOf(rl+"|")==-1) {
    rl="EN"; // locale
  }
  ha=EncodeLocale(rl); // locale
  if(Jb.indexOf(ha+"|")==-1){
    X=true;
    Y=false;
    Ba=false
  }else{
    X=false;
    if(ha.indexOf("zh")==0) {
      Y=false;
    } else {
      Y=true;
    }
    Ba=true
  }
  if(!hd) {
    hd=false; // default
  }
  ya=hd;
  if(!sm) {
    sm="query"; // default
  }
  w=sm; 
  mb=ufn; // null
  ac()
}
;

// remove the focus from the textbox, then focus it again
// this happens when the user presses up or down
function Yb(){
  ra=true;
  a.blur(); // Text box
  setTimeout("sfi();",10);
  return
}
function Fb(){
  if(document.createEventObject){
    var y=document.createEventObject();
    y.ctrlKey=true;
    y.keyCode=70;
    document.fireEvent("onkeydown",y)
  }
}
function nc(vb){
  var y=document.createEventObject();
  y.ctrlKey=true;
  y.keyCode=vb;
  document.fireEvent("onkeydown",y)
}
function gc(event){}
function ic(event){}
// handles document keypresses
function Pb(event){
  if(!event&&window.event) {
    event=window.event;
  }
  if(event) {
//PULSA LA TECLA ESCAPE ANTES borraba ambos campos
    if (event.keyCode==27)
      {
       event.keyCode=0;
       OcultarDropDown();
       return false;
      }
//FIN PULSA LA TECLA ESCAPE
    na=event.keyCode;
  }
  if(event&&event.keyCode==8){ // delete    
    if(X&&(a.createTextRange&&(event.srcElement==a&&(bb(a)==0&&lb(a)==0)))){
      cc(a); 
      event.cancelBubble=true;
      event.returnValue=false;
      return false
    }
  }
}
function mc(){}
// called on resize
function Db(){
  if(w=="url"){
    Ha() // not called. Since W is always query in our application
  }
  ba()
  SetKnockoutFrameDimensions()
}
function ba(){
  try
  {
	if(b){
		b.style.left=ob(a)+"px";
		b.style.top=Qb(a)+a.offsetHeight-1+"px";
		b.style.width=Ja()+"px";
	}
  }
  catch(ex){}
}

function SetKnockoutFrameDimensions(){  
  try
  {
	if(ifKnockout){
		ifKnockout.style.left=ob(a)+"px";
		ifKnockout.style.top=Qb(a)+(a.offsetHeight)-1+"px";
		ifKnockout.style.width=(Ja()-2)+"px" 
		//ifKnockout.style.width="200px"; 
	}
  }
  catch(ex){}
}
function Ja(){
  if(navigator&&navigator.userAgent.toLowerCase().indexOf("msie")==-1){
    return (a.offsetWidth-ca*2) * ExtraWidth; // Textbox width
  }else{
    return (a.offsetWidth) * ExtraWidth;
  }
}
function ac(){
  // jb is the xmlhttp object
  if(jb()){
    Q=true 
  }else{
    Q=false
  }
  if(pa) {
    E="es";
  } else {
    E=""+ia; // call back url
  }
  sa= "" + E+"?hl="+ha;
 
  if(!Q){
    // set a cookie - if we can't use xmlhttp
    qa("qu","",0,E,null,null)
  }
  la.onsubmit=Fa; // Call FA when the form submits
  a.autocomplete="off"; // stop the default "last typed keywords" popup on the textbox
//  a.onblur=Ob; // textbox onblur LO HE QUITADO PORQUE NO FUNCIONABA CON EL SCROLL
  if(a.createTextRange) { // CreateTextRange must be a type of browser detect.
    a.onkeyup=new Function("return okuh(event);"); // call okuh when key is pressed on textbox
  } else {
    a.onkeyup=okuh; 
  }
  a.onsubmit=Fa; // call Fa when you the textbox submits
  g=a.value; // set g to the value of the textbox
  ta=g; // set ta to the value of the textbox
  b=document.createElement("DIV");
  b.id="completeDiv";
  ca=1;
  Aa=1;
  b.style.borderRight="#53B953 "+ca+"px solid";
  b.style.borderLeft="#53B953 "+ca+"px solid";
  b.style.borderTop="#53B953 "+Aa+"px solid";
  b.style.borderBottom="#53B953 "+Aa+"px solid";
  b.style.zIndex="100";
  b.style.paddingRight="0";
  b.style.paddingLeft="0";
  b.style.paddingTop="0";
  b.style.paddingBottom="0";
  ba();
  b.style.visibility="hidden";
  b.style.position="absolute";
  b.style.backgroundColor="white";
  document.body.appendChild(b);
  Ma("",new Array(),new Array(),new Array());
  Gb(b);
  b.style.overflow="auto";//Para evitar que se reescale a su antojo
  b.style.height="0px";
  
  //Knockout IFrame
  ifKnockout =document.createElement("IFRAME")
  ifKnockout.id="ifKnockout";
  ifKnockout.style.position="absolute";
  ifKnockout.style.borderRight="black "+ca+"px solid";
  ifKnockout.style.borderLeft="black "+ca+"px solid";
  ifKnockout.style.borderTop="black "+Aa+"px solid";
  ifKnockout.style.borderBottom="black "+Aa+"px solid";
  ifKnockout.style.zIndex="80";
  ifKnockout.style.paddingRight="0";
  ifKnockout.style.paddingLeft="0";
  ifKnockout.style.paddingTop="0";
  ifKnockout.style.paddingBottom="0";
  SetKnockoutFrameDimensions();
  ifKnockout.style.visibility="hidden";
  ifKnockout.style.position="absolute";
  ifKnockout.style.backgroundColor="white";
  document.body.appendChild(ifKnockout);
  Gb(ifKnockout);
  
  var s=document.createElement("DIV");
  s.style.visibility="hidden";
 
  s.style.position="absolute";
  s.style.left="-10000";
  s.style.top="-10000";
  s.style.width="0";
  s.style.height="0";
  var M=document.createElement("IFRAME");
  M.completeDiv=b;
  M.name="completionFrame";
  M.id="completionFrame";
  //M.src=sa;
  s.appendChild(M);
  document.body.appendChild(s);
  if(frames&&(frames["completionFrame"]&&frames["completionFrame"].frameElement)) {
    B=frames["completionFrame"].frameElement;
  } else {
    B=document.getElementById("completionFrame");
  }
  if(w=="url"){
    Ha(); // not called, since w is "query"
    ba()
    SetKnockoutFrameDimensions()
  }
  window.onresize=Db;
  document.onkeydown=Pb;
  Fb() // CTRL + F?
}
// textbox onblur (PROBLEMA, me cierra aunque pinche en el scrollbar, paso directamente de el
function Ob(event){
  if(!event&&window.event)event=window.event;
  if(!ra){
    // hide the drop down div
    OcultarDropDown();
    if(na==9){ // TAB
      Xb(); // does nothing.
      na=-1
    }
  }
  ra=false
}

// this is called onKeyup of the textbox
okuh=function(e){
  m=e.keyCode; // set m to the value of the key pressed
  aa=a.value; // set aa value of the textbox
  Oa();
}
;
function Xb(){
  //Xa.focus()
}

sfi=function(){
	
  a.focus()
}
;
function Wb(va){
  for(var f=0,oa="",zb="\n\r"; f<va.length; f++) {
    if (zb.indexOf(va.charAt(f))==-1) {
      oa+=va.charAt(f);
    } else {
      oa+=" ";
    }
  }
return oa
}

// return the inner HTML of an element, where the classname 
// is equal to the passed-in value.
function Qa(i,dc){

  var ga=i.getElementsByTagName(Bb); // Bb is "Span"
  if(ga){    
	for(var f=0; f<ga.length; ++f){
      if(ga[f].className==dc){
		var value=ga[f].innerHTML;
        if(value=="&nbsp;") {
			return"";
        } else{
			iata=ga[ga.length-1].innerHTML;
			var z=Wb(value);
			return z;
	}
   }
}
  }else{
    return""
  }

}

// gets the currently selected option
function U(i){
  if(!i) {
    return null;
  }
  // Get the value of the cell with the class name cAutoComplete
  return Qa(i,"cAutoComplete")
}

// Seems identical to U() - gets the currently selected option
function wa(i){
  if(!i) {
    return null;
  }
  // Get the value of the cell with the class name dAutoComplete
  return Qa(i,"dAutoComplete")
}
// Hide the drop down box
function OcultarDropDown(){
  RemoveEvent(document,'mousedown',OcultaPopUp);//Para ocultar el pop up si el edit pierde el foco
  //----------------.----------------------------------------------------------
  document.getElementById("completeDiv").style.visibility="hidden"
  document.getElementById("ifKnockout").style.visibility="hidden";
}
// Show the drop down box
function cb(){
  //Añado un evento por si pincha en cualquier otro sitio poder cerrar el popup
  AttachEvent(document,'mousedown',OcultaPopUp);
  //----------------.----------------------------------------------------------
  document.getElementById("completeDiv").style.visibility="visible";
  document.getElementById("ifKnockout").style.visibility="visible";
  ba();
  SetKnockoutFrameDimensions();
}

function showKnockout()
{
	document.getElementById("completeDiv").style.visibility="visible";
	document.getElementById("ifKnockout").style.visibility="visible";
	ba();
    SetKnockoutFrameDimensions();  
}


//Transfer from RPC call to cache array
function Ma(is,cs,ds,pr){
	/*
	is = search word
	cs = aeropuerto
	ds = IATA
	pr = Comienza o Contiene flag
	*/	
  Ua[is]=new Array(cs,ds,pr)
}

function sendRPCDone(fr,is,cs,ds,pr){
  if(W>0) {
    W--;
  }
  var lc=(new Date()).getTime();
  if(!fr) {
    fr=B;
  }
  Ma(is,cs,ds,pr); // cache the result
  var b=fr.completeDiv;
  var ifKnockout = document.getElementById('ifKnockout');
  b.completeStrings=cs; // TextoMostrar
  b.displayStrings=ds; // IATA
  b.prefixStrings=pr; // Flag comienza(0) o Contiene(1)
  // render drop down
  rb(b,b.completeStrings,b.displayStrings,b.prefixStrings);
  Pa(b,U);
  //Ca es el nº de elementos incluidos los banner
  if(Ca>0) { //HAY ALGUNA OPCIÖN PARA MOSTRAR
    if(Ca<=MaxItemsDesplegable) //2 banner y x de cada hasta MaxItemsDesplegable
      {
      b.style.overflow="hidden"; 
      b.style.height=(AltoFilaOpcion*Ca);
      }
    else
      {
      b.style.overflow="auto";
      b.style.height=(AltoFilaOpcion*MaxItemsDesplegable);
      }

    //b.height=15*Ca+4; QUITADO 
    //ifKnockout.height=b.height-4; SUSTITUIDO POR LA DE ABAJO   
    ifKnockout.height=parseInt(b.style.height)-2;
 
  } else {
	// hide the drop down div
    OcultarDropDown();
  }
}

// Called when a key is pressed
function Oa(){
  if(m==9)
    return;//Si es TAB no hago nada ha venido de otro control y acaba de soltar el TAB
  //Pulsado FLECHA ARRIBA O FLECHA ABAJO
  if(m==40||m==38) { // m is the value of the key being pressed
    Yb(); // call Yb on up or down
  }
  if (Xa != null)
  {
	Xa.value = "";
    if(FuncionOnChangeIATA)
      FuncionOnChangeIATA();
  }
  var N=lb(a);
  var v=bb(a);
  var V=a.value;
  if(X&&m!=0){
    if(N>0&&v!=-1) {
      V=V.substring(0,v);
    } 
    if(m==13||m==3||m==9){  // enter
      var d=a; 
      if(d.createTextRange){
        var t=d.createTextRange();
        t.moveStart("character",d.value.length);
        t.select()
      } else if (d.setSelectionRange){
        d.setSelectionRange(d.value.length,d.value.length)
      }
    } else { 
      if(a.value!=V) {
		// set "a" to the value of the currently selected option
        S(V);
      }
    }
  }
  g=V;

  if(Eb(m)&&m!=0) {
    if(a.value.length>2)//SOLO MUESTRO ALGO SI EL USUARIO HA ESCRITO 3 CARACTERES O MÁS
      Pa(b,U);
    else {
      OcultarDropDown();//Oculto y Limpio el desplegable porque si no lo muestra con lo último
      while(b.childNodes.length>0) b.removeChild(b.childNodes[0]);
    }
  }
}

// used to handle form submit
function Fa(){
  return xb(w) // w="query"
}

// handles form submit
function xb(eb) {
  da=true;
  if(!Q){
	// clears a cookie called qu (only applicable where xmlhttp is unavailable)
    qa("qu","",0,E,null,null)
  }
  // hide the drop down div
  OcultarDropDown();
  if(eb=="url"){
    var R=""; // not called since eb=w and w is query
    if(j!=-1&&h) {
      R=U(h);
    }
    if(R=="") {
      R=a.value;
    }
    if(q=="") { 
      document.title=R;
    } else {
      document.title=q;
    }
    var Tb="window.frames['"+mb+"'].location = \""+R+'";';
    setTimeout(Tb,10);
    return false
  } else if(eb=="query"){
    //la.submit();
    return true // allow form to submit
  }
}

newwin=function(){
  window.open(a.value);
  // hide the drop down div
  OcultarDropDown();
  return false
}
;

// simutes a keypress if multiple locales?? heh?
idkc=function(e){
  if(Ba){
    var Ta=a.value;
    if(Ta!=aa){
      m=0;
      Oa();
    }
    aa=Ta;
    setTimeout("idkc()",10)
  }
}
;
setTimeout("idkc()",10);

//Si estoy en UTF8 lo paso a utf8 p.e.
function EncodeLocale(La){
  if(encodeURIComponent) {
    return encodeURIComponent(La);
  }
  if(escape) {
    return escape(La)
  }
}
// something to do with the time to requery server
function yb(Mb){
  var H=100;
  for(var o=1; o<=(Mb-2)/2; o++){
    H=H*2
  }
  H=H+50;
  return H
}

// this function is polled every 10 milliseconds
// once the text changes and the length exceeds 3
// then make a call to the server.
idfn=function(){
  if(ta!=g && g.length>2){
    if(!da){
      var Za=EncodeLocale(g); // set Za to the current locale
      var ma=Ua[g]; // set ma to the cache array
      if(ma){
        Va=-1; // if we got a match, then use the cache
        sendRPCDone(B,g,ma[0],ma[1],ma[2]);
      }else{
        W++; // cache miss, then contact the server
        Va=(new Date()).getTime();
        if(Q){
		  // make a request to the server		
          fc(Za)
        }else{
		  // set the qu cookie - if we have no reference to xml http
          qa("qu",Za,null,E,null,null);
          frames["completionFrame"].document.location.reload(true)
        }
      }
      
      a.focus()
    }
    da=false // da is set true when the form is about to submit
  }
  ta=g;
  setTimeout("idfn()",yb(W));
  return true
}
;
setTimeout("idfn()",10);

// Called on mousedown of the div
var Cb=function(){  
  // set "a" to the value of the currently selected option
  S(U(this));
  // get the currently selected option
  q=wa(this);
  da=true; 
  Fa() // submit form (returns true)
}
;
// called on mouse over of the div
var pb=function(){
  if(h) {
    SetClassName(h,"aAutoComplete"); // non selected text
  }
  SetClassName(this,"bAutoComplete") // selected text
}
;
// called on mouseout of the div
var ec=function(){
  SetClassName(this,"aAutoComplete") // non selected text
}
;
//GESTIONA LA PULSACION DE FLECHAS PARA ARRIBA O PARA ABAJO
function Na(C){
  g=G;
  // set the textbox to the value of the currently selected option
  S(G);
  q=G;
  if(!za||Z<=0) {
    return;
  }
  // simulate div mousedown
  cb();
  if(C>=Z){
    C=Z-1
  }
  if(j!=-1&&C!=j){
    SetClassName(h,"aAutoComplete"); // non selected text
    j=-1
  }
  if(C<0){
    j=-1;    
    a.focus();
    return
  }
  j=C;
  h=za.item(C);
  //incase it meets a header
  if(U(h)==null)
  {
	if(m==40)//down key
	{
		Na(j+1);
		return;
	}else
	{
		Na(j-1);
		return;
	}
  }
  SetClassName(h,"bAutoComplete"); // selected text
  g=G;
  // get the currently selected option
  q=wa(h);
  // set "a" to the value of the currently selected option
  S(U(h));
  //CONTROLO EL SCROLL PARA VER LA OPCIÓN SELECCIONADA SI ME MUEVO CON LAS FLECHAS
  //Si no se muestra por el scroll debo desplazar la barrita
  if(b.style.overflow=="auto")// Si es auto es que tengo scroll
    {
    //j es el indice de la opcion activa 
    var objDiv = document.getElementById("completeDiv");
    //Se sale por debajo
    if ((parseInt(objDiv.scrollTop)+parseInt(b.style.height))<((j+1)*AltoFilaOpcion))
      objDiv.scrollTop =((j+1)*AltoFilaOpcion)-parseInt(b.style.height);
    if (parseInt(objDiv.scrollTop)>(j*AltoFilaOpcion))
      {
      if (j<=1) //Si es el primero subo hasta el primer banner que no es selecionable, sino no se le ve
        objDiv.scrollTop =0;
      else objDiv.scrollTop =(j*AltoFilaOpcion); 
      } 
    }
}

//GESTION FLECHAS ARRIBA Y ABAJO
function Eb(ja){
  if(ja==40){ // down key
    Na(j+1);
    return false
  }else if(ja==38){ // up key
    Na(j-1);
    return false
  }else if(ja==13||ja==3||ja==27){ // enter(13) o escape(27)
    {//Lo añado para que devuelva la opción seleccionada cuando pulse intro joder
    S(a.value);
    Fa();
    OcultaPopUp();
    return false
    }
  }
  return true
}


function Pa(K,ib){
  var d=a;
  var T=false;
  j=-1;
  var J=K.getElementsByTagName(Lb); // lb is "Div"
  //var J= K.getElementById("resultsDiv");
  var O=J.length;
  Z=O;
  za=J;
  Ca=O;
  G=g;
  if(g==""||O==0){
    // drop the drop down div
    OcultarDropDown()
  }else{
	// simulate div mousedown   
    cb();
  }
  var Ab="";
  /*
  if(g.length>0){
    var f;
    var o;
    for(var f=1; f<O; f++){ 
		if(J.item(f).id != "header2")  
		{ 
			for(o=0; o<K.prefixStrings.length; o++){
				var Ib=K.prefixStrings[o]+g;
				if((Y||ib(J.item(f)).toUpperCase().indexOf(Ib.toUpperCase())==0)) {
					//Ab=K.prefixStrings[o]; 
					//T=true; 
					break
				}
			}
		
			if(T){
				break
			}
		}
    }
    
  }
  */
  if(T) {
    j=f;
  }
  for(var f=0; f<O; f++) {
    SetClassName(J.item(f),"aAutoComplete"); //non selected text
  }
  if(T){
    h=J.item(j);
    // get the currently selected option
    q=wa(h)
  }else{
    q=g;
    j=-1;
    h=null
  }
  var ab=false; // determines if the keypressed is alphanumeric or not
  switch(m){
    case 8:
    case 33:
    case 34:
    case 35:
    case 35:
    case 36:
    case 37:
    case 39:
    case 45:
    case 46:
      ab=true;
      break;
    default:
      break
  }
  if(!ab&&h){
    var Da=g; // if the key was alphanumeric
    SetClassName(h,"bAutoComplete"); // selected text
    var z;
    if(T) {
      z=ib(h).substr(K.prefixStrings[o].length);
    } else {
      z=Da;
    }
    if(z!=d.value){
      if(d.value!=g) {
        return;
      }
      if(X){
        if(d.createTextRange||d.setSelectionRange) {
		  // set "a" to the value of the currently selected option
          S(z);
        }
        if(d.createTextRange){
          var t=d.createTextRange();
          t.moveStart("character",Da.length);
          t.select()
        }else if(d.setSelectionRange){
          d.setSelectionRange(Da.length,d.value.length)
        }
      }
    }
  }else{
    j=-1;
    q=g
  }
}
function ob(r){
  return Ya(r,"offsetLeft")
}
function Qb(r){
  return Ya(r,"offsetTop")
}

function Ya(r,ia){   
  var kb=0;
  while(r){
    kb+=r[ia]; 
    r=r.offsetParent
  }
  return kb
}
// sets a cookie
function qa(name,value,Ra,hb,fb,Sb){
  var Nb=name+"="+value+(Ra?";expires="+Ra.toGMTString():"")+(hb?";path="+hb:"")+(fb?";domain="+fb:"")+(Sb?";secure":"");
  document.cookie=Nb
}
function Ha(){
  var xa=document.body.scrollWidth-220;
  xa=0.73*xa;
  a.size=Math.floor(xa/6.18)
}
function lb(n){
  var N=-1;
  if(n.createTextRange){
    var fa=document.selection.createRange().duplicate();
    N=fa.text.length
  }else if(n.setSelectionRange){
    N=n.selectionEnd-n.selectionStart
  }
  return N
}

function bb(n){
  var v=0;
  if(n.createTextRange){
    var fa=document.selection.createRange().duplicate();
    fa.moveEnd("textedit");
    v=n.value.length-fa.text.length;
  }else if(n.setSelectionRange){
    v=n.selectionStart
  }else{
    v=-1
  }
  return v
}
// called on a keypress, looks as if this function should hightlight
// a range of text.
function cc(d){
  if(d.createTextRange){
    var t=d.createTextRange();
    t.moveStart("character",d.value.length);
    t.select() 
  } else if(d.setSelectionRange) {
    d.setSelectionRange(d.value.length,d.value.length)
  }
}

function jc(Zb,Ea){
  if(!Ea)Ea=1;
  if(pa&&pa<=Ea){
    var Ia=document.createElement("DIV");
    Ia.innerHTML=Zb;
    document.getElementById("console").appendChild(Ia)
  }
}

// set the classname of the currently selected option.
function SetClassName(c,name){
  db();
  c.className=name;
  if(Ka){
    return // unreachable. Ka is always false
  }
  switch(name.charAt(0)){
    case "m":
      c.style.fontSize=FontSize;
      c.style.fontFamily="Arial, Tahoma, sans-serif";
      c.style.wordWrap="break-word";
      break;
    case "l":
      c.style.display="block";
      c.style.paddingLeft="3";
      c.style.paddingRight="3";
      c.style.height=AltoFilaOpcion+"px";
      if(!document.all)
		c.style.overflow="hidden";
      break;
    case "a":	
      c.style.backgroundColor=NonSelectedBackground; // non selected
      c.style.color="black";
      c.style.zindex ="200";
      if(c.displaySpan){
		//IATA colour
        c.displaySpan.style.color=IATATextColour;
        c.displaySpan.style.fontFamily='Courier New';
      }
      break;
    case "b":
      c.style.backgroundColor=SelectedBackground; // selected
      c.style.color=SelectedText;
      if(c.displaySpan){
        c.displaySpan.style.color="white";
      }
      break;
    case "c":
      c.style.width=p+"%";
      c.style.cssFloat="left";
      break;
    case "d":
      c.style.cssFloat="left";
      c.style.width=100-p+"%";
      if(w=="query"){
        c.style.fontSize=FontSize; 
        //IATA Alignment
        c.style.textAlign="right";
        c.style.color="green";
        c.style.paddingTop="0px"
      }else{
        c.style.color="#696969"
      }
      break
  }
}

function db(){
  p=65;
  if(w=="query"){
	//div split ratio
    var wb=35;
    var Sa=Ja();
    var tb=(Sa-wb)/Sa*100;
    p=tb
  }else{
    p=65 // never called since w is always query
  }
  if(ya){
    p=99.99
  }
}
function Gb(i){
  db();
  var Ub="font-size: 11px; font-family: Arial, Tahoma, sans-serif; word-wrap:break-word; ";
  var Vb="display: block; padding-left: 3; padding-right: 3; height: 14px; overflow: hidden; ";
  var bc="background-color: white; ";
  var qb="background-color: #3366cc; color: white ! important; ";
  var ub="display: block; margin-left: 0%; width: "+p+"%; float: left; ";
  var Ga="display: block; margin-left: "+p+"%; ";
  if(w=="query"){
    Ga+="font-size: 10px; text-align: left; color: red; padding-top: 3px; "
  }else{
    Ga+="color: #696969; " // never called
  }
  D(".mAutoComplete",Ub);
  D(".lAutoComplete",Vb);
  D(".aAutoComplete *",bc); // non-selected text
  D(".bAutoComplete *",qb); // selected text
  D(".cAutoComplete",ub);
  D(".dAutoComplete",Ga);
  SetClassName(i,"mAutoComplete")
}

// populates the div with headers and options
function rb(i,cs,Hb,resultType){
  while(i.childNodes.length>0) {
    i.removeChild(i.childNodes[0]);
  }
  //Header
  
  var header1Shown = false;
  var header2Shown = false;
  for(var f=0; f<cs.length; ++f){
  
	if(resultType[f]=="1" && header1Shown==false)
	{
		header1Shown =true;
		var header=document.createElement("DIV");
		header.id ="header1";
		SetClassName(header,"mAutoComplete");
		var headerSpan=document.createElement("SPAN");
        headerSpan.id='Cabecera';//Para distinguirlo y no cerrar si pincho en el
		// TODO: Translate into spanish
		headerSpan.innerHTML="Comienzan por ... ";//a.value OJO No puedo meter tags ahí
		headerSpan.style.backgroundColor = BannerBackgroundColour;
		headerSpan.style.color = BannerText;
        headerSpan.style.fontWeight='bold';
		headerSpan.style.width ="100%";
        headerSpan.style.cursor='default';
		header.appendChild(headerSpan);
		i.appendChild(header);
	}
	 //Header 2	 
	if(resultType[f]=="0" && header2Shown==false)
	{
		header2Shown =true;
		var header=document.createElement("DIV");
		header.id ="header2";
		SetClassName(header,"mAutoComplete");
		var headerSpan=document.createElement("SPAN");
        headerSpan.id='Cabecera';//Para distinguirlo y no cerrar si pincho en el
		headerSpan.innerHTML="... Contienen ...";//a.value OJO No puedo meter tags ahí
		headerSpan.style.backgroundColor = BannerBackgroundColour;
		headerSpan.style.color = BannerText;
        headerSpan.style.fontWeight='bold';
		headerSpan.style.width ="100%";
        headerSpan.style.cursor='default';
		header.appendChild(headerSpan);
		i.appendChild(header);
	}
    var u=document.createElement("DIV");
    u.id ="resultsDiv";
    SetClassName(u,"aAutoComplete"); // non selected text
    u.onmousedown=Cb;
    u.onmouseover=pb;
    u.onmouseout=ec;
    u.style.cursor='pointer';
    var ka=document.createElement("SPAN");
    SetClassName(ka,"lAutoComplete");
    var ua=document.createElement("SPAN");
    ua.innerHTML=cs[f];//Este es el texto que pone en el desplegable, TextoMostrar en la BD

    var ea=document.createElement("SPAN");
    SetClassName(ea,"dAutoComplete");
    SetClassName(ua,"cAutoComplete");
    u.displaySpan=ea;
    
    ea.innerHTML=Hb[f];	//Código IATA
    
    ka.appendChild(ua);
    ka.appendChild(ea);
    u.appendChild(ka);
    i.appendChild(u)
  }
}

function D(name,gb){
  if(Ka){
    var I=document.styleSheets[0]; // seems unreachable. Ka is always false
    if(I.addRule){
      I.addRule(name,gb)
    }else if(I.insertRule){
      I.insertRule(name+" { "+gb+" }",I.cssRules.length)
    }
  }
}

// gets a reference to the xml http object
function jb(){
  var A=null;
  try{
    A=new ActiveXObject("Msxml2.XMLHTTP")
  }catch(e){
    try{
      A=new ActiveXObject("Microsoft.XMLHTTP")
    } catch(oc){
      A=null
    }
  }
  if(!A&&typeof XMLHttpRequest!="undefined"){
    A=new XMLHttpRequest()
  }
  return A
}

// make a request to the server, if the xmlhttp object is not busy.
function fc(Rb)
{
	if(k&&k.readyState!=0)
	{
		k.abort();
	}
	// k is the xml http object
	k=jb();
	if(k)
	{	
        //Pongo un iconito para que sepa que está buscando
        newImage = "url(ImagenesBuscador/FondoEditAeropuertoBuscando.gif)";
        a.style.backgroundPosition = 'right center';
        a.style.backgroundRepeat = 'no-repeat';
        a.style.backgroundImage = newImage;
        //-----------------
		k.open("GET",sa+"&js=true&str="+Rb,true);
		k.onreadystatechange=function() 
		{
			try
			{	
                //QUITO LA IMAGEN INDICADORA
                newImage = "url(ImagenesBuscador/FondoEditAeropuerto.gif)";
                if(k.readyState==4) a.style.backgroundImage = newImage;
                //--------------------------      
				if(k.readyState==4&&k.responseText)
				{
					var frameElement=B;
					// an error may have occured if it starts with <
					if(k.responseText.charAt(0)=="<")
					{
						W-- 
					}
					else
					{
						showKnockout();
						eval(k.responseText);
					}// end if
				}//end if
			}// end try
			catch(ex){}
		};//end function
		k.send(null)
	}// end if	
} // end function


// sets "a" to the value of the currently selected option
function S(Wa){
  //Quito las marcas <B> y </B> que utilizo para marcar el substring
  Wa = Wa.replace(/<b>|<\/b>/gi, "");
  if(Wa!=null)
    {
    a.value=Wa
    if ((Xa!=null)&&(iata!=null))
      {
	  Xa.value = iata;
      if(FuncionOnChangeIATA)
        FuncionOnChangeIATA();
      }
    aa=Wa
    }
}
//----------------.----------------------------------------------------------
//----------------.----------------------------------------------------------
//----------------.----------------------------------------------------------
//Mios nuevos para controlar si pierde el foco

function AttachEvent(elemento, eventname, funcion) {
	if (elemento.attachEvent) { // IE
		elemento.attachEvent("on" +eventname, funcion);
	} else if (elemento.addEventListener) { // Gecko / W3C
		elemento.addEventListener(eventname, funcion, true);
	} else {
		elemento["on" +eventname] = funcion;
	}
}

function RemoveEvent(elemento, eventname, funcion) {
	if (elemento.detachEvent) { // IE
		elemento.detachEvent("on" + eventname, funcion);
	} else if (elemento.removeEventListener) { // Gecko / W3C
		elemento.removeEventListener(eventname, funcion, true);
	} else {
		elemento["on" + eventname] = null;
	}
}

function OcultaPopUp(e)
{
IDObjeto=whichElement(e);
//No cierro solo si ha pulsado sobre el edit o sobre el div (popup)
if((IDObjeto!=a.name) && (IDObjeto!='completeDiv') && (IDObjeto!='Cabecera'))
  OcultarDropDown();
}

//------------------------------
function whichElement(e)
{
var targ
if (!e) var e = window.event
if (e.target) targ = e.target
else if (e.srcElement) targ = e.srcElement
if (targ.nodeType == 3) // defeat Safari bug
targ = targ.parentNode
var tname
tname=targ.id;//targ.tagName
//alert("You clicked on " + tname + " element. TAG="+targ.tagName)
return tname;
}
//------------------------------
var oldVal =null;
function SetFocus(val,item,iata,CallbackChangeIATA)
{
    FuncionOnChangeIATA=CallbackChangeIATA;
	if(oldVal != item && item !=null)
		item.onKeyUp =LoadSuggest(item,iata);
	oldVal =item;	
}
//------------------------------
function LoadSuggest(item,iata)
{
	UnInstall();
	InstallAC(document.FormBuscadorVuelos,item,document.getElementById(iata),"CGIsBuscadores/SuggestAeropuertos.cgi/SuggestAeropuertos","es");	
}
//-------------------------------------------
function BuscaAeropuertosPorDefecto(CampoAeropuerto,CampoIATA)
{
    var Respuesta='';
    var URL='CGIsBuscadores/SuggestAeropuertos.cgi/BuscaAeropuertoPorDefecto?str='+EncodeLocale(FINDLayer(CampoAeropuerto).value);
    //Que deje to que está haciendo, si no cascará
	if(k&&k.readyState!=0) k.abort();
	// k is the xml http object
	k=jb();
	if(k)
	{	       
        //-----------------
		k.open("GET",URL,false);//Llamada Síncrona	
		k.send(null);
        Respuesta=k.responseText;
	}// end if	
//Proceso la respuesta
var SubCadenas=new Array();
if (Respuesta.length>0)
  SubCadenas=Respuesta.split('|');
//Si todo va bien me debería devolver 2
if (SubCadenas.length==2)
  {
  FINDLayer(CampoAeropuerto).value=SubCadenas[0];
  FINDLayer(CampoIATA).value=SubCadenas[1];
  return true;
  }
else return false;
} // end function
