/**
 * Fce nastavuje naseptavac
 *
 * @param string ID formularove polozky
 * @param string ID naseptavace
 * @param string ID selectu v naseptavaci
 * @param string ID tlacitka pro odeslani
 */
function setWhisperer(idInput, idWhisperer, idSelect, idSubmit, iciWhisperer) {

    var elSubmit = jQ('#' + idSubmit);

    jQ('#' + idWhisperer).blur(function() {
        hideAvailableDestinations(this, true);                    
    });
    
    jQ('#' + idWhisperer).keypress(function(event) {
        var result = setLocationValue(idInput, idWhisperer, this, event);
    });
    
    jQ('#' + idWhisperer).click(function(event) {
       var result = setLocationValue(idInput, idWhisperer, this, event);
    });

    // Aby neslo odeslat pomoci enter, jsou zde funkcionality na dve udalosti
    // keydown = nastavuje disabled na input submit
    // keypup = odnastavuje disabled z inputu submit
    // Neplati pro tabulator
    
    jQ('#' + idInput).bind('keydown', function(event) {
        var keyCode = getKeyCode(event);
        if (keyCode == 13) {
            jQ(elSubmit).attr('disabled', true);
            jQ(elSubmit).addClass('disabled');            
        }
    });       
    
    jQ('#' + idInput).bind('keyup', function(event) {
        var keyCode = getKeyCode(event);
        if (keyCode == 13) {    
            jQ(elSubmit).attr('disabled', false);
            jQ(elSubmit).removeClass('disabled');
        }        
        showAvailableDestinationsFast(idWhisperer, this, event, iciWhisperer);
    });
    
    jQ('#' + idInput).blur(function() {
        // Udalost je volana pri vyberu destinace a neprobihal onclick na vyber polozky, zarucuje zpozdeni
        var t = setTimeout(function(){hideAvailableDestinationsById(idWhisperer, false)}, 1000);
    });
    
    
/*
onKeyPress="setLocationValue('from1_{$identName}', 'from1target_{$identName}', this, event);

onClick="setLocationValue('from1_{$identName}', 'from1target_{$identName}', this, event);

onblur="hideAvailableDestinations(this, true);
*/
}



/**
 * Vraci kod stisknute klavesy
 *
 * @param object event
 * @return integer
 */
function getKeyCode(event) {

    var nKeyCode = null;

    try {
        nKeyCode = event.keyCode;
    } catch(eException) {
        try {
          nKeyCode = event.which;
        } catch(eException2) {}
    }
    
    return nKeyCode;
}

var gDestinationListIATA = new Array();

// Najde vnoreny element - vrati ID elementu.
function searchChildNodeByTagName(p_parentObjectID, p_tagName) {

  var oTargetObject = null;
  var oTargetSelect = null;
  var sNodeName = "";
  var sNodeID = null;

  
  try {
    oTargetObject = document.getElementById(p_parentObjectID);
  } catch(eException) {
    
  }

  for(nCounter = 0; nCounter < oTargetObject.childNodes.length; nCounter++) {
    sNodeName = oTargetObject.childNodes[nCounter].nodeName;
    sNodeName = sNodeName.toUpperCase();
    if(sNodeName = p_tagName.toUpperCase()) {
      try {
        sNodeID = oTargetObject.childNodes[nCounter].id;
      } catch(eException) {
      }
    }
  }
  return sNodeID;
}

// Zobrazi nalezene shody (zadava se pouze id DIVu s napovedou a reference na INPUT).
function showAvailableDestinationsFast(p_targetObjectID, p_referenceObject, p_eEvent, iciWhisperer) {

  var sNodeID = null;
  
  //nastaveni stringu s IATA kody pro vzhledavani pomoc search
  if(sIciDestCodes == '' && (typeof gIciDestinationCodeList != 'undefined')) {
    sIciDestCodes = gIciDestinationCodeList.toString();
  }
  
  sNodeID = searchChildNodeByTagName(p_targetObjectID, "SELECT");

  // Zavola metodu s doplnenym selectem.
  var result = showAvailableDestinations(p_targetObjectID, sNodeID, p_referenceObject, p_eEvent, iciWhisperer);

  //return result;
}

// Zobrazi nalezene shody.
function showAvailableDestinations(p_targetObjectID, p_targetSelectID, p_referenceObject, p_eEvent, iciWhisperer) {

  var sWrittenString = null;
  var oTargetObject = null;
  var aResultList = null;
  var bIataCodeFound = false;
  var nKeyCode = null;
  //var result = true;
  
  try {
    sWrittenString = p_referenceObject.value;
    oTargetObject = document.getElementById(p_targetObjectID);
    oTargetSelect = document.getElementById(p_targetSelectID);
  } catch(eException) {

  }

  try {
    nKeyCode = p_eEvent.keyCode;
  } catch(eException) {
    try {
      nKeyCode = p_eEvent.which;
    } catch(eException2) {
    }
  }
  
  // Po stisku sipky dolu presune vyber na moznosti.
  if(nKeyCode == 40) {
    setSelectBoxActive(p_targetSelectID);
  }

// Po stisku klavesy Enter nastavi hodnotu z nabidky.
  if(nKeyCode == 13) {
    try {
      if(document.getElementById(p_targetSelectID).options.length > 0) {
        p_referenceObject.value = document.getElementById(p_targetSelectID).options[document.getElementById(p_targetSelectID).selectedIndex].innerHTML;
      }
    } catch(eException) {
    }
    hideAvailableDestinationsById(p_targetObjectID, true);

    //result = false;
  }

  resetDestinationFields(oTargetSelect);
  
  // Pokud je znaku mene jak 3, skryje napovedu.
  if(sWrittenString.length < 3) {
    hideAvailableDestinations(oTargetObject);
  }

  // Pokud je znaku 3 a vice, zobrazi napovedu.
  if(sWrittenString.length >= 3) {
    // Pro 3 znaky hleda podle IATA kodu.
    aResultList = searchInIataCodes(sWrittenString);

    // Hleda podle nazvu letiste.
    if(aResultList.length == 0) {
      aResultList = searchInAirportNames(sWrittenString);
    } else {
      aResultList = mergeArrays(aResultList, searchInAirportNames(sWrittenString));
    }

    // Hleda podle nazvu mesta.
    if(aResultList.length == 0) {
      aResultList = searchInCityNames(sWrittenString);
    } else {
      aResultList = mergeArrays(aResultList, searchInCityNames(sWrittenString));
    }

    // Hleda podle nazvu zeme.
    if(aResultList.length == 0) {
      aResultList = searchInCountryNames(sWrittenString);
    } else {
      aResultList = mergeArrays(aResultList, searchInCountryNames(sWrittenString));
    }

    // Zobrazi vysledky - pokud je nalezena alespon 1 moznost. 
    if(aResultList.length > 0) {
      for(nCounter = 0; nCounter < aResultList.length; nCounter++) {
        if( (typeof iciWhisperer == 'undefined') || (sIciDestCodes.search(gDestinationListIATA[aResultList[nCounter]].toUpperCase()) > -1) ){
        	addDestinationElementRecord(oTargetObject, oTargetSelect, gDestinationListCities[aResultList[nCounter]], gDestinationListIATA[aResultList[nCounter]], gDestinationListAirports[aResultList[nCounter]], gDestinationListCountries[aResultList[nCounter]]);
      	}
      }
            
      if(aResultList.length <= nMinOptionLinesCount) {
        oTargetSelect.size = nMinOptionLinesCount;
      }
    }
  }
    
   
    
    
  //return result;
}

// Prida radek do vysledku.
function addDestinationElementRecord(p_targetObject, p_targetSelect, p_City, p_IataCode, p_Airport, p_Country) {
 

    //p_targetSelect = jQ(p_targetObject)[0];
//alert(p_targetSelect);
    //alert(jQ(p_targetSelect).children('option').length);
  var nLastOptionIndex = p_targetSelect.options.length;
//  alert(nLastOptionIndex);
  if(nLastOptionIndex < 0) {
    nLastOptionIndex = 1;
  }

  if(nLastOptionIndex >= 0) {
    //p_targetObject.style.visibility = "visible";
//    p_targetObject.style.display = "block";
    jQ(p_targetObject).addClass("show");
    
  }
  if((p_IataCode != "undefined") && (p_IataCode != null)){
    p_targetSelect.size = nLastOptionIndex + 1;
    p_targetSelect.options[nLastOptionIndex] = new Option(p_City + ', ' + p_Airport + ', ' + p_Country + ' (' + p_IataCode + ')', p_IataCode);
  }
  
  // Pokud je pocet radku vetsi, nez povoleny limit, vytvori scrollbar.
  if(p_targetSelect.size > nMaxOptionLinesCount) {
    p_targetSelect.size = nMaxOptionLinesCount;
  }
}

// Odstrani zaznamy z nabidky.
function resetDestinationFields(p_targetSelect) {

  p_targetSelect.options.length = 0;
}

// Prohleda IATA kody.
function searchInIataCodes(p_searchString) {

  var aIataCodesList = new Array();
  var nIndex = 0;
  
  for(nCounter = 0; nCounter < gDestinationListIATA.length; nCounter++) {
    if(gDestinationListIATA[nCounter] == p_searchString.toUpperCase()) {
      aIataCodesList[nIndex] = nCounter;
      nIndex += 1;
    }
  }

  return aIataCodesList;
}

// Prohleda nazvy letist.
function searchInAirportNames(p_searchString) {

  var aAirportNamesList = new Array();
  var nIndex = 0;
  var nWordLength = p_searchString.length;
  var sMatchWord = null;
  var sMatchWord2 = null;

  for(nCounter = 0; nCounter < gDestinationListAirports.length; nCounter++) {
    sMatchWord = gDestinationListAirports[nCounter].substring(0, nWordLength);
    sMatchWord = sMatchWord.toUpperCase();
    sMatchWord2 = gDestinationListAirportsIndex[nCounter].substring(0, nWordLength);
    sMatchWord2 = sMatchWord2.toUpperCase()
    if((sMatchWord == p_searchString.toUpperCase()) || (sMatchWord2 == p_searchString.toUpperCase())) {
      aAirportNamesList[nIndex] = nCounter;
      nIndex += 1;
    }
  }

  return aAirportNamesList;
}

// Prohleda nazvy mest, vcetne diakritiky.
function searchInCityNames(p_searchString) {

  var aCityNamesList = new Array();
  var nIndex = 0;
  var nWordLength = p_searchString.length;
  var sMatchWord = null;
  var sMatchWord2 = null;
  
  for(nCounter = 0; nCounter < gDestinationListCitiesIndex.length; nCounter++) {
    sMatchWord = gDestinationListCities[nCounter].substring(0, nWordLength);
    sMatchWord = sMatchWord.toUpperCase();
    sMatchWord2 = gDestinationListCitiesIndex[nCounter].substring(0, nWordLength);
    sMatchWord2 = sMatchWord2.toUpperCase()
    if((sMatchWord == p_searchString.toUpperCase()) || (sMatchWord2 == p_searchString.toUpperCase())) {
      aCityNamesList[nIndex] = nCounter;
      nIndex += 1;
    }
  }

  return aCityNamesList;
}

// Prohleda nazvy zemi, vcetne diakritiky.
function searchInCountryNames(p_searchString) {

  var aCountryNamesList = new Array();
  var nIndex = 0;
  var nWordLength = p_searchString.length;
  var sMatchWord = "";
  
  for(nCounter = 0; nCounter < gDestinationListCountries.length; nCounter++) {
    sMatchWord = gDestinationListCountries[nCounter].substring(0, nWordLength);
    sMatchWord = sMatchWord.toUpperCase();
    sMatchWord2 = gDestinationListCountriesIndex[nCounter].substring(0, nWordLength);
    sMatchWord2 = sMatchWord2.toUpperCase()
    if((sMatchWord == p_searchString.toUpperCase()) || (sMatchWord2 == p_searchString.toUpperCase())) {
      aCountryNamesList[nIndex] = nCounter;
      nIndex += 1;
    }
  }

  return aCountryNamesList;
}

// Skryje napovedu (dle ID objektu).
function hideAvailableDestinationsById(p_targetObjectID, p_forceHide) {
  // ID selectboxu vnoreneho do vrstvy, ktera se skryva. 
  var sChildSelectBoxID = null;
  var bHidingEnabled = true;
  
  // Vrstva, ktera se skryva.
  p_targetObject = document.getElementById(p_targetObjectID);
  
  // Ziska ID selectu vnoreneho do vrstvy.
  sChildSelectBoxID = searchChildNodeByTagName(p_targetObjectID, "SELECT");
  try {
    // Pokud ma select nastaven priznak "focused", nastavi priznak "aktivni". 
    if(aActiveFields[sChildSelectBoxID] == true) {
      bHidingEnabled = false;
    }
  } catch(eException) {
  }
  // Pokud neni selectbox oznacen jako aktivni, skryje vrstvu s danou prediktivni napovedou.
  if(bHidingEnabled || p_forceHide) {
    try {
    	setTimeout("hideAvailableDestinations(p_targetObject);", 100);
      //hideAvailableDestinations(p_targetObject);
      aActiveFields[sChildSelectBoxID] = null;
    } catch(eException) {
    }
  }
  
  return false;
}

// Skryje napovedu.
function hideAvailableDestinations(p_targetObject) {

  //p_targetObject.style.display = "none";
  jQ(p_targetObject).removeClass("show");
}

// Slouci do pole neduplicitni polozky.
function mergeArrays(p_array1, p_array2) {

  var aResultArray = new Array();
  var bItemAlreadyPresent = false;
  
  aResultArray = p_array1;
  // Pokud druhe pole nic neobsahuje, vraci rovnou pouze prvni pole. 
  if(p_array2 == null) {
    return aResultArray;
  }
  
  for(nCounter = 0; nCounter < p_array2.length; nCounter++) {
    bItemAlreadyPresent = false;
    for(nCounter2 = 0; nCounter2 < aResultArray.length; nCounter2++) {
      if(p_array2[nCounter] == aResultArray[nCounter2]) {
        bItemAlreadyPresent = true;
      }
    }
    if(bItemAlreadyPresent == false) {
      aResultArray[aResultArray.length] = p_array2[nCounter];
    }
  }
  return aResultArray;
}

// Nastavi hodnotu do pole.
function setLocationValue(p_targetObjectID, p_targetListID, p_sourceObject, eEvent) {

  var oTargetObject = null;
  var sEventType = null;
  var nKeyCode = null;
  
  // Zjisti typ udalosti.
  try {
    sEventType = eEvent.type;
  } catch(eException) {
  }
  
  // Zjisti stisknutou klavesu (detekce Enter).
  if(sEventType == "keypress") {
    try {
      nKeyCode = eEvent.keyCode;
      
    } catch(eException) {
      try {
        nKeyCode = eEvent.which;
      } catch(eException2) {
      }
    }
  }

  // Pokud je vybrana nabidka kliknutim, nebo klavesou Enter, nastavi se vybrana hodnota.
  if((sEventType == "click") || (nKeyCode == 13)) {
    try {
      oTargetObject = document.getElementById(p_targetObjectID);
      oTargetObject.value = jQ(p_sourceObject).find('option:selected').html();
      hideAvailableDestinations(document.getElementById(p_targetListID));
      oTargetObject.focus();
    } catch(eException) {
    }
  }
  
  return false;
}

// Nastavi pole s vyberem jako aktivni.
function setSelectBoxActive(p_targetListID) {

  document.getElementById(p_targetListID).focus();

  // Nastavi do globalni promenne ID pole, ktere je aktivni. 
  aActiveFields[p_targetListID] = true;
}
