var hotelXML;
var locationsXML;
var oldPattern = '';
var hotelCount;
var locationCount;
var offerHint = 'Offer Code';
var searchHint = "Enter a Destination or Hotel";

function hotelNameSearch(searchText, restrictCountry, restrictState, restrictCity){
  $.ajax({
    type: "POST",
    data: {"name" : searchText, "restrictCountry" : restrictCountry, "restrictState" : restrictState, "restrictCity": restrictCity},
    url: "/core/search.asmx/HotelName",
    datatype: "xml",
    success: loadHotelNameDataXML
  });
}
function loadHotelNameDataXML(xml){
  hotelXML = xml;
  var currentSearchString = $('#search').val();
  $(hotelXML).find("hotels:containsi('" + currentSearchString + "')").each(function(){
    fillSelectHotel($(this).find('code').text(), $(this).find('hotelName').text());
  });
  handleStyles();
}

function fillSelectHotel(val, main){
  if (hotelCount < 5){
    var tempMain = new RegExp('(' + $('#search').val() + ')', 'gi');
    tempMain = main.replace(tempMain, '<span class="hl">$1</span>');
    $('#autoCompleteHotels').append('<dd><a href="#" onclick="return selectHotel(\'' + val + '\')">' + tempMain + '</a><dd>');
  }
  hotelCount ++;
}

function locationsSearch(searchText, restrictCountry, restrictState){
  $.ajax({
    type: "POST",
    data: {"name" : searchText, "restrictCountry" : restrictCountry, "restrictState" : restrictState},
    url: "/core/search.asmx/Locations",
    datatype: "xml",
    success: loadLocationsDataXML
  });
}

function loadLocationsDataXML(xml){
  locationsXML = xml;
  var currentSearchString = $('#search').val();
  $(locationsXML).find("locations:containsi('" + currentSearchString + "')").each(function(){
    fillSelectLocations($(this).find('type').text(), $(this).find('location').text());
  });
  handleStyles();
}

function fillSelectLocations(val, main){
  if (locationCount < 5){
    var tempMain = new RegExp('(' + $('#search').val() + ')', 'gi');
    tempMain = main.replace(tempMain, '<span class="hl">$1</span>');
    $('#autoCompleteLocations').append('<dd><a href="#" onclick="return selectLocation(\'' + val + '\',\'' + main + '\')">' + tempMain + '</a></dd>');
  }
  locationCount ++;
}

function doSearch(){
  $('#autoCompleteHotels').find('dd').remove();
  $('#autoCompleteLocations').find('dd').remove();
  var searchString = $(this).val();
  hotelCount = 0;
  locationCount = 0;
  if(searchString.length > 1){
    var newSearch = true;
    moreHotelsTrip = true;
    moreLocsTrip = true;
    if(oldPattern != ''){
      if(searchString.indexOf(oldPattern) > -1){
        $(hotelXML).find("hotelName:containsi('" + searchString + "')").parent().each(function(){
          fillSelectHotel($(this).find('code').text(), $(this).find('hotelName').text());
        });
          $(locationsXML).find("location:containsi('" + searchString + "')").parent().each(function(){
            fillSelectLocations($(this).find('type').text(), $(this).find('location').text());
          });
        newSearch = false;
      }
    }
    if(newSearch){
      hotelNameSearch(searchString, '', '', '');
        locationsSearch(searchString, '', '');
      oldPattern = searchString;
    }
  }
  handleStyles();
}

var moreHotelsTrip = true;
var moreLocsTrip = true;
function handleStyles(){
  if(hotelCount > 0 || locationCount > 0){
    if(hotelCount > 0){
      if(hotelCount > 5 && moreHotelsTrip){
        $('#autoCompleteHotels').append('<dd><a href="/search.aspx?hotelname=' + $('#search').val() + '" class="looklink">View More...</a><dd>');
        moreHotelsTrip = false;
      }
      $('#autoCompleteHotels').css('display', 'block');
    }else{
      $('#autoCompleteHotels').css('display', 'none');
    }
    if(locationCount > 0){
      if(locationCount > 5 && moreLocsTrip){
        $('#autoCompleteLocations').append('<dd><a href="/search.aspx?locationname=' + $('#search').val() + '" class="looklink">View More...</a><dd>');
        moreLocsTrip = false;
      }
      $('#autoCompleteLocations').css('display', 'block');
    }else{
      $('#autoCompleteLocations').css('display', 'none');
    }
    $('#searchFlyOut').css('display', 'block');
  }else{
    $('#searchFlyOut').css('display', 'none');
  }
}
function fillDrillDown(id, selectedName, code){
  $('#drilldown').html('<input type="hidden" id="'+ id + '" name="'+ id + '" value="' + code + '" />');
}

function selectHotel(code){
  var selectedName = $(hotelXML).find("code:contains('" + code + "')").parent().find('hotelName').first().text();
  fillDrillDown("selectedHotel", selectedName, code);
  $('#autoCompleteHotels').find('dd').remove();
  $('#autoCompleteLocations').find('dd').remove();
  $('#searchFlyOut').css('display', 'none');
  $('#search').val(selectedName);
  oldPattern = '';
  return false;
}

function selectLocation(code, name){
  fillDrillDown('selected' + code, name, name);
  $('#searchFlyOut').css('display', 'none');
  $('#search').val(name);
  oldPattern = '';
  return false;
}

function setupDDL(originalselectID)
{
  var select =  $('#' + originalselectID);
  var additionalClass = '';

  if(select.is('.active')){
    additionalClass = ' active';
  }
  var selectBoxContainer = $('<div>',{
    className	: 'tzSelect',
    html	: '<div id="' + originalselectID + 'Design" class="selectBox' + additionalClass + '"></div>'
  });
  var dropDown = $('<ul>',{className:'dropDown'});
  var selectBox = selectBoxContainer.find('#' + originalselectID + 'Design');
  select.find('option').each(function(i){
    var option = $(this);
    if(i==select.attr('selectedIndex')){
      selectBox.html(option.text());
    }
    var li = $('<li>',{
      html:  '<span>'+ $(this).attr('value') +  '</span>'
    });

    li.click(function(){
      selectBox.html(option.text());
      dropDown.trigger('hide');
      select.val(option.val());
      return false;
    });
    dropDown.append(li);
  });
  selectBoxContainer.append(dropDown.hide());
  select.hide().after(selectBoxContainer);
  dropDown.bind('show',function(){
    if(dropDown.is(':animated')){
      return false;
    }
    selectBox.addClass('expanded');
    dropDown.slideDown();
  }).bind('hide',function(){
    if(dropDown.is(':animated')){
      return false;
    }
    selectBox.removeClass('expanded');
    dropDown.slideUp();
  }).bind('toggle',function(){
    if(selectBox.hasClass('expanded')){
      dropDown.trigger('hide');
    }else dropDown.trigger('show');
  });

  selectBox.click(function(){
    dropDown.trigger('toggle');
    return false;
  });
  $(document).click(function(){
    dropDown.trigger('hide');
  });
}

function redirectToAdvancedSearch(){
  if (inputExists('selectedHotel')){
    return true;
  }else{
    var searchlink = '/advanced-search.aspx?f=w';
    var searchtext = $('#search').val();
    if (inputExists('selectedcountry')){
      searchlink += '&country=' + $('#selectedcountry').val();
      if (searchtext == $('#selectedcountry').val()){
        searchtext = '';
      }
    }
    if (inputExists('selectedstate')){
      searchlink += '&state=' + $('#selectedstate').val();
      if (searchtext == $('#selectedstate').val()){
        searchtext = '';
      }
    }
    if (inputExists('selectedcity')){
      searchlink += '&city=' + $('#selectedcity').val();
      if (searchtext == $('#selectedcity').val()){
        searchtext = '';
      }
    }
    if (searchtext != '' && searchtext != 'Enter a Destination or Hotel'){
      searchlink += '&hotelName=' +  searchtext;
    }
    if ($('#txbxArive').val() != '' && $('#txbxArive').val() != 'Arrival'){
      searchlink += '&arrivalDate=' + $('#txbxArive').val();
    }
    if ($('#txbxDepart').val() != '' && $('#txbxDepart').val() != 'Departure'){
      searchlink += '&departureDate=' + $('#txbxDepart').val();
    }
    if ($('#ddlAdults').val() != ''){
      searchlink += '&numberOfAdults=' + $('#ddlAdults').val();
    }
    if ($('#ddlChildren').val() != ''){
      searchlink += '&numberOfChildren=' + $('#ddlChildren').val();
    }
    if ($('#txbxOffer').val() != '' && $('#txbxOffer').val() != 'Offer Code'){
      searchlink += '&rateCode=' + $('#txbxOffer').val();
    }
    window.location = searchlink;
  }
  return false;
}

function inputExists(id){
  if($('#' + id).length > 0 && $('#' + id).val() != ''){
    return true;
  }
  return false;
}

$(document).ready(function(){
  $('#search')
    .keypress(function(e){
      if(((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13)) &&
          ($(this).val() != '') && ($(this).val() != searchHint)){
         $('.searchbox .searchbutton').click();
        return false;
      }
      return true;
    })
    .keyup(doSearch)
    .focusin(function(){
      if($(this).val() == searchHint){
        $(this).val('');
      }else{
        this.select();
      }
    })
    .focusout(function(){
      if($(this).val() == ''){
        $(this).val(searchHint);
      }
    });
  
  if($('#search.active').length > 0 && $('#search.active').val().length > 25){
    $('#search').hide().after('<p id="searchformatcover" class="active">' + $('#search').val().substring(0,20) + '...</p>');
  }
  $('#searchformatcover').click(function(){
    $(this).hide();
    $('#search').show();
    $('#search').focusin();
  });
  $('.active').focusin(function(){
    $(this).val('');
    $(this).removeClass('active');
  });
  $('.searchbox #search.active').focusin(function(){
    $('#drilldown').html('');
  });
  $("#txbxOffer")
    .focusin(function(){
      if($(this).val() == offerHint){
        $(this).val('');
      }
    })
    .focusout(function(){
      if($(this).val() == ''){
        $(this).val(offerHint);
      }
    });
    $("#txbxArive").datepicker({
        buttonImageOnly: true,
        showButtonPanel: true,
        numberOfMonths: 2,
        onSelect : function(dateText, inst){
          var thisDate = new Date(dateText);
          if ($("#txbxDepart").val() == 'Departure' || thisDate >=  $("#txbxDepart").datepicker('getDate')){
            $("#txbxDepart").datepicker('setDate', dateText);
            $("#txbxDepart").datepicker('setDate', 'c+1d');
          }
        }
    })
    .focusin(function(){
      if($(this).val() == 'Arrival'){
        $(this).val('');
      }
    })
    .focusout(function(){
      if($(this).val() == ''){
        $(this).val('Arrival');
      }
    });
    $('#cal_for_txbxArive').click(function(){
      $("#txbxArive").focus();
    });
    $("#txbxDepart").datepicker({
        buttonImageOnly: true,
        showButtonPanel: true,
        numberOfMonths: 2,
        onSelect : function(dateText, inst){
          var thisDate = new Date(dateText);
          if ($("#txbxArive").val() != '' && $("#txbxArive").val() != 'Departure' && thisDate <=  $("#txbxArive").datepicker('getDate')){
            $("#txbxDepart").datepicker('setDate', $("#txbxArive").datepicker('getDate'));
            $("#txbxDepart").datepicker('setDate', 'c+1d');
          }
        }
    })
    .focusin(function(){
      if($(this).val() == 'Departure'){
        $(this).val('');
      }
    })
    .focusout(function(){
      if($(this).val() == ''){
        $(this).val('Departure');
      }
    });
    $('#cal_for_txbxDepart').click(function(){
      $("#txbxDepart").focus();
    });
    $('body').click(function(){
      $('#searchFlyOut').css('display', 'none');
      $('.searchboxattributes').css('display', 'none');
      $('.searchbox .animateattrs').html('More<br />Options');
    });
    $('#searchFlyOut').click(function(event){
      event.stopPropagation();
    });
    $('.searchboxattributes').click(function(event){
      event.stopPropagation();
    });
    $('#closeflyout').click(function(){
      $('#searchFlyOut').css('display', 'none');
    });
    $('.searchbox .searchbutton').click(function(){
      if (($('#search').val() == '') || ($('#search').val() == searchHint)){
        alert('Please enter a destination or hotel');
        return false;
      }
    });
    $('#searchAttributes .searchbutton').click(function(){
      if (($('#search').val() == '') || ($('#search').val() == searchHint)){
        alert('Please enter a destination or hotel');
        return false;
      }
    });
    $('.animateattrs').click(function(){
      $('.searchboxattributes').toggle('blind');
      if ($(this).html() != '[X]'){
        if ($(this).html() == 'More<br>Options'){
          $(this).html('Close<br />Options');
        }else{
          $(this).html('More<br />Options');
        }
      }else{
        $('.searchbox .animateattrs').html('More<br />Options');
      }
      return false;
    });
    setupDDL('ddlAdults');
    setupDDL('ddlChildren');
});

// this is a modification to jQuery to make the contians() selector work regardless of case
$.extend($.expr[':'], {
  'containsi': function(elem, i, match, array)
  {
    return ($(elem).text().toLowerCase().indexOf((match[3] || "").toLowerCase()) >= 0) ||
    (scwtf($(elem).text()).toLowerCase().indexOf((match[3] || "").toLowerCase()) >= 0);
  }
});
function scwtf(source){
  return source.replace(/\xE0/g, 'a').replace(/\xC7/g, 'c').replace(/\xE7/g, 'c').replace(/\xE8/g, 'e').replace(/\xE9/g, 'e').replace(/\xEB/g, 'e').replace(/\xED/g, 'i').replace(/\xF3/g, 'o').replace(/\xF4/g, 'o').replace(/\xF6/g, 'o').replace(/\xFA/g, 'u').replace(/\xFC/g, 'u').replace(/\xAE/g, '').replace(/\x2122/g, '').replace(/\343/g,'a').replace(/\u0101/g, 'a').replace(/\361/g,'n').replace(/\316/g,'I');
}

