var locationArray = new Array();
var suggestionElement = parent.document.createElement("div");
suggestionElement.Id = "suggestionbox";
var isTabbed = false;

function tabCheck(ev)
{
  if(ev.keyCode == 9)
    isTabbed = true;
  if(ev.keyCode == 13) {setSubtypeId();validateSearchCriteria()}//simulating Submit when clicking on ENTER
}

function focusNextElement(event)
{
  if(event.keyCode == 9)
  {
    parent.$("departure").focus();
    suggestionElement.style.visibility = "hidden";
    suggestionElement.style.display = "none";
    $("departure").value = '';
  }
}

function retrieveURL(e)
{
  var inputBox= $("departure");
  inputBox.onblur = function(){
  isTabbed = true;
  if(isTabbed)
  {
    if(inputBox.value.length > 2)
    {
      if(parent.$("suggest") && parent.$("suggest").disabled == false)
      {
        parent.$('suggest').style.display='inline';
        parent.$('suggest').style.visibility = 'visible';
        parent.$('suggest').focus();
      }
      else
      {
        suggestionElement.style.display = "none";
        inputBox.value = '';
      }
    }
  }
  isTabbed = false;
}

  if ((e.keyCode >= 65 && e.keyCode <= 90) ||
  (e.keyCode >= 97 && e.keyCode <= 122) ||
  (e.keyCode >= 33 && e.keyCode <= 39) ||
  (e.keyCode >= 16 && e.keyCode <= 20) ||
  (e.keyCode >= 44 && e.keyCode <= 46) ||
  (e.keyCode==91 || e.keyCode==92 || e.keyCode==27 || e.keyCode == 40 || e.keyCode == 46 || e.keyCode == 8 || e.keyCode==9 || e.keyCode == 13 || e.keyCode ==109 || e.keyCode == 144 || e.keyCode == 192 || e.keyCode == 222 || e.keyCode == 55))
  {
    var nchar = getNormalCharacter();
    if (nchar!=0)
    {
      var locationName = $('departure').value;
      locationName = locationName.substr(0,locationName.length-1)+nchar;
      $('departure').value = locationName;
    }

    // This code is added to allow key press for special keys
    // like PRINTSCREEN, ESC to enter for search but not to proceed with it.
    // Without this condition 'No Results' will get displayed
    // for such keys when entered, which is wrong.
    if((e.keyCode >= 44 && e.keyCode <= 46) || (e.keyCode >= 16 && e.keyCode <= 20) || e.keyCode==9 || e.keyCode==91 || e.keyCode==92 || e.keyCode==27 || e.keyCode == 144 ||(e.keyCode >= 33 && e.keyCode <= 39) )
    {
      return;
    }

    if ($('departure').value.length < 3 )
    {
      resetSearchCodes();
      suggestionElement.style.visibility = "hidden";
      suggestionElement.style.display = "none";
      suggestionElement.innerHTML = "";
      return;
    }

    suggestionElement.style.visibility = "visible";
    suggestionElement.style.display = "inline";

    var ignorelist = new Array('hot','hote','hotel','hotel ','vil','vill','villa','villa ','the');
    for (i=0;i<ignorelist.length;i++)
    {
      if($('departure').value.toString().toLowerCase() == ignorelist[i])
      {
        suggestionElement.innerHTML = "<select style=\"min-width:170px;font-size:11px !important;font-family:arial !important;\" size='4' style=\"width:198px;\" id=\"suggest\"><option>No Results</option></select>";
        alignSuggestionBox();
        parent.$("suggest").disabled = true;
        return;
      }
    }

    var predictStr = inputBox.value;
    var ampPosition=predictStr.indexOf('&');
    if(ampPosition!=-1)
    {
      predictStr = predictStr.substr(0, ampPosition-1) + ' AMPERSAND' + predictStr.substr(ampPosition+1, predictStr.length);
    }

    //convert the url to a string
    url="/accom/page/common/search/predictivesearch.page?"+"destinationString=" + predictStr;
    //Do the AJAX call
    if (window.XMLHttpRequest)
    {
      // Non-IE browsers
      req = new XMLHttpRequest();
      req.onreadystatechange = processStateChange;
      try
      {
        req.open("GET", url, true);
      }
      catch (e)
      {
        alert("Server Communication Problem\n"+e);
      }
      req.send(null);
    } else if (window.ActiveXObject)
    {
      // IE
      req = new ActiveXObject("Microsoft.XMLHTTP");
      if (req)
      {
        req.onreadystatechange=processStateChange;
        req.open("GET", url, true);
        req.send();
      }
    }
  }
  else if($('departure').value.length > 2)
  {
    if(e.keyCode!=32)
    {
      suggestionElement.style.visibility = "visible";
      suggestionElement.style.display = "inline";
      ajaxHtmlResponse = "<select style=\"min-width:170px;font-size: 11px !important;font-family:arial !important;\" size='4' style=\"width:198px;\" id=\"suggest\"><option>No Results</option></select>";
      suggestionElement.innerHTML = ajaxHtmlResponse;
      alignSuggestionBox();
      parent.$("suggest").disabled = true;
    }
  }
}

function getNormalCharacter()
{
  var stringEntered = $('departure').value
  var lastCharEntered = stringEntered.substr(stringEntered.length-1, stringEntered.length).toUpperCase();
  for(var i=0;i<specialChar.length;i++)
  {
    if(lastCharEntered==specialChar[i].toUpperCase())
    {
      return displayChar[i];
    }
  }
  return 0;
}

function processStateChange()
{
  // Complete
  if (req.readyState == 4)
  {
  // OK response
    if (req.status == 200)
    {
      var ajaxHtmlResponse = "<select style=\"min-width:170px;font-size: 11px !important;font-family:arial !important;\" size='11' id=\"suggest\" onclick=\"var withinIframe = false;var iframeObjIdx = null;for(i=0;i<parent.document.getElementsByTagName(\'iframe\').length;i++){if (parent.document.getElementsByTagName(\'iframe\')[i].src && parent.document.getElementsByTagName(\'iframe\')[i].src.indexOf(\'searchpanel.page\') !== -1){withinIframe = true;iframeObjIdx = i;break;}}if (withinIframe){parent.frames[iframeObjIdx].setPredictiveDestinationValues(this)}else{setPredictiveDestinationValues(this);}\" onkeydown=\"var withinIframe = false;var iframeObjIdx = null;for(i=0;i<parent.document.getElementsByTagName(\'iframe\').length;i++){if (parent.document.getElementsByTagName(\'iframe\')[i].src && parent.document.getElementsByTagName(\'iframe\')[i].src.indexOf(\'searchpanel.page\')){withinIframe = true;iframeObjIdx = i;break;}}if (withinIframe){parent.frames[iframeObjIdx].focusNextElement(event);parent.frames[iframeObjIdx].setPredictiveDestinationValuesUsingKeyBoard(event, this);}else{focusNextElement(event);setPredictiveDestinationValuesUsingKeyBoard(event, this);}\">"
      if (req.responseXML != null)
      {
        $('ajaxresponse').innerHTML = req.responseText;
        $('ajaxresponse').style.display='none';
        var content=$('ajaxresponse').getElementsByTagName("table");

        if (content[0])
        {
          var subtypeArr = getSelectedSubtype().split("|");
          var arrIndex=0;
          var locations = content[0].childNodes[0].childNodes;
          for (var x=0; x<content[0].childNodes[0].childNodes.length; x++)
          {
            if(locations[x].childNodes[1].getAttribute("Id")!="")
            /* Check if 2nd <TD> in the response is null. Ensures The resort code is present always */
            {
              locationArray[arrIndex] = new Location(
              locations[x].childNodes[0].getAttribute("Id"),locations[x].childNodes[0].getAttribute("Name"),
              locations[x].childNodes[1].getAttribute("Id"),locations[x].childNodes[1].getAttribute("Name"),
              locations[x].childNodes[2].getAttribute("Id"),locations[x].childNodes[2].getAttribute("Name"),
              locations[x].childNodes[3].getAttribute("Id"),locations[x].childNodes[3].getAttribute("Name"));

              if(locations[x].childNodes[0].getAttribute("Name")!="")
              {
                ajaxHtmlResponse += "<option id=\""+x+"\">" + locations[x].childNodes[0].getAttribute("Name") + "</option>"
                arrIndex++;
              }
              else if(locations[x].childNodes[1].getAttribute("Name")!="")
              {
                ajaxHtmlResponse += "<option id=\""+x+"\">" + locations[x].childNodes[1].getAttribute("Name") + "</option>"
                arrIndex++;
              }
              else if ((locations[x].childNodes[2].getAttribute("Name") != "") && (subtypeArr[0]=='CITY'))
              {
                ajaxHtmlResponse += "<option id=\""+x+"\">" + locations[x].childNodes[2].getAttribute("Name") + "</option>"
                arrIndex++;
              }
              else
              {
                ajaxHtmlResponse += "<option id=\""+x+"\">" + locations[x].childNodes[3].getAttribute("Name") + "</option>"
                arrIndex++;
              }
            }
            else
            {
            /* Check if 4th <TD> in the response is null. Ensures atleast the Country ID is returned  */
              if (locations[x].childNodes[3].getAttribute("Id")!="")
              {
                locationArray[arrIndex] = new Location(locations[x].childNodes[0].getAttribute("Id"),locations[x].childNodes[0].getAttribute("Name"),
                locations[x].childNodes[1].getAttribute("Id"),locations[x].childNodes[1].getAttribute("Name"),
                locations[x].childNodes[3].getAttribute("Id"),locations[x].childNodes[3].getAttribute("Name"),
                locations[x].childNodes[3].getAttribute("Id"),locations[x].childNodes[3].getAttribute("Name"))

                if (locations[x].childNodes[3].getAttribute("Name").toLowerCase().indexOf($('departure').value.toLowerCase())>-1 && locations[x].childNodes[2].getAttribute("Id") == "")
                /* Check if 3rd <TD> in the response is null. Filters top level & no wrong Country ID is returned  */
                {
                  ajaxHtmlResponse += "<option id=\""+x+"\">"+ locations[x].childNodes[3].getAttribute("Name") + "</option>";
                  arrIndex++;
                }
              }
            }

          }
          ajaxHtmlResponse +="</select>"
              suggestionElement.innerHTML = ajaxHtmlResponse;
              alignSuggestionBox();
        }
        else
        {
          ajaxHtmlResponse = "<select style=\"min-width:170px;font-size: 11px !important;font-family:arial !important;\" size='4' style=\"width:198px;\" id=\"suggest\"><option>No Results</option></select>"
          suggestionElement.innerHTML = ajaxHtmlResponse;
          alignSuggestionBox();
          parent.$("suggest").disabled = true;
        }
      }
    }
  }
}

function findPos(obj) {
  if (obj)
  {
    var curleft = curtop = 0;
    if (obj.offsetParent) {
      curleft = obj.offsetLeft
      curtop = obj.offsetTop
      while (obj = obj.offsetParent) {
        curleft += obj.offsetLeft
        curtop += obj.offsetTop
      }
    }
    return [curleft,curtop];
  }else{
    return [0,0];
  }
}

function clearPredictiveInputElements()
{
  if (parent.$("suggest") != null)
  {
    if ( suggestionElement.style.display == 'inline' && parent.$("suggest").selectedIndex == '-1')
    {
      suggestionElement.style.display = 'none';
      $("departure").value = '';
    }
  }
    else if (parent.$("suggest") == null )
    {
      if($("departure").value.length > 2)
      {
        suggestionElement.style.display = 'none';
        $("departure").value = '';
      }
    }
}

function appendOnFocusToAllElements()
{
  for (i=0; i<document.forms.length; i++)
  {
    for (j=0; j<document.forms[i].elements.length; j++)
    {
      if (document.forms[i].elements[j].type != 'hidden' && document.forms[i].elements[j].name != 'departure' && document.forms[i].elements[j].name != 'suggest')
      {
        document.forms[i].elements[j].onfocus=function(){clearPredictiveInputElements();}
      }
    }
  }
}

function Location(accommodationCode, accommodationName, resortCode, resortName, destinationCode, destinationName, countryCode, countryName)
{
  this.accommodationCode = accommodationCode;
  this.accommodationName = accommodationName;
  this.resortCode = resortCode;
  this.resortName = resortName;
  this.destinationCode = destinationCode;
  this.destinationName = destinationName;
  this.countryCode = countryCode;
  this.countryName = countryName;
}

function setPredictiveDestinationValues(selectedOption)
{
  var index = selectedOption.selectedIndex;
  $("departure").value = selectedOption.options[index].text;
  $("countryCode").value = locationArray[index].countryCode;
  $("destinationCode").value = locationArray[index].destinationCode;
  $("resortCode").value = locationArray[index].resortCode;
  $('accommodationCode').value = locationArray[index].accommodationCode;
  setDropdownsToDefault();
  setRadioToDefault();
  suggestionElement.style.visibility = "hidden";
  suggestionElement.style.display = "none";
}

function setPredictiveDestinationValuesUsingKeyBoard(e, selectedOption)
{
  if (e.keyCode == 13)
  {
    var index = selectedOption.selectedIndex;
    $("departure").value = selectedOption.options[index].text;
    $("countryCode").value = locationArray[index].countryCode;
    $("destinationCode").value = locationArray[index].destinationCode;
    $("resortCode").value = locationArray[index].resortCode;
    $('accommodationCode').value = locationArray[index].accommodationCode;
    setDropdownsToDefault();
    setRadioToDefault();
    suggestionElement.style.visibility = "hidden";
    suggestionElement.style.display = "none";
  }
}

function resetSearchCodes()
{
  if($("countryDestCode").selectedIndex==0 && ($('departure').value.length < 3 || $('departure').value == "Type your destination here"))
  {
    $("countryCode").value = "";
    $("destinationCode").value = "";
    $("accommodationCode").value = "";
    $("resortCode").value = "";
    $("resortAccomCode").selectedIndex=0;
  }
  if($("resortAccomCode").selectedIndex == 0)
  {
    $("resortCode").value = "";
    $("resortAccomCode").selectedIndex=0;
  }
}

function setDropdownsToDefault()
{
  $("resortAccomCode").value="";
  $("resortAccomCode").selectedIndex =0;
  $("resortAccomCode").disabled=true;
  $("countryDestCode").value="";
  $("countryDestCode").selectedIndex =0;
}

function clearPredictivePanels()
{
  suggestionElement.style.visibility = "hidden";
  suggestionElement.style.display = "none";
  $("departure").value = "";
}

function disableFreeTextSearchOnEnter()
{
  var nav = window.Event ? true : false;
  if (nav) {
    if (typeof(Event.KEYDOWN) != 'undefined')
    {
      window.captureEvents(Event.KEYDOWN);
      window.onkeydown = NetscapeEventHandler_KeyDown;
    }
  } else {
    document.onkeydown = MicrosoftEventHandler_KeyDown;
  }
  function NetscapeEventHandler_KeyDown(e) {
    if (e.which == 13 && (parent.$("suggest")==null || parent.$("suggest").selectedIndex== -1)) { return false; }
    return true;
  }
  function MicrosoftEventHandler_KeyDown() {
    if (event.keyCode == 13 && (parent.$("suggest")==null || parent.$("suggest").selectedIndex== -1)) { return false; }
    return true;
  }
}

function setRadioToDefault()
{
  if (document.searchForm.favouriteDestination)
  {
    for (i=0;i<9 ;i++ )
    {
      document.searchForm.favouriteDestination[i].checked = false;
    }
  }
}

function setDestinationCode(countryCode, destinationCode)
{
  suggestionElement.style.visibility = "hidden";
  suggestionElement.style.display = "none";
  $("departure").value="";
  $("destinationCode").value=destinationCode;
  $("countryCode").value=countryCode;
  if ($("matchedDestinations"))
  {
    ElementAction('matchedDestinations', 'hide');
    ElementAction('matchedDestinations', 'nodisplay');
  }
}

function alignSuggestionBox()
{
  suggestionElement.style.position= "absolute";
  var withinIframe = false;
  var iframeObj = null;
  for(i=0;i<parent.document.getElementsByTagName('iframe').length;i++)
  {
    if (parent.document.getElementsByTagName('iframe')[i].src && parent.document.getElementsByTagName('iframe')[i].src.indexOf('searchpanel.page') !== -1)
    {
      withinIframe = true;
      iframeObj = parent.document.getElementsByTagName('iframe')[i];
      break;
    }
  }
  if (withinIframe)
  {
    suggestionElement.style.left = findPos($("predictbox"))[0] + findPos(iframeObj)[0] + "px";
    suggestionElement.style.top = findPos($("predictbox"))[1] + findPos(iframeObj)[1] + "px";
  }else{
    suggestionElement.style.left = findPos($("predictbox"))[0] + "px";
    suggestionElement.style.top = findPos($("predictbox"))[1] + "px";
  }
  suggestionElement.style.zIndex ="100";
  parent.document.body.appendChild(suggestionElement);
}
