var targetDetails = [];
var targetCount   = 0;
var offerDetails  = [];
var offerCount    = 0;
var suggestAll    = [];
var pageUrls      = [];
var allLabels     = [];


/**
 * Default configuration
 */
var settings = {
  datepicker: {
    buttonImage: '/typo3conf/ext/21torr_destinations/res/images/tripfinder/de_tripfinder_button_calendar.png',
    delayFirstClose: 2000,
    delayAutoClose: 2000,
    effectDuration: 750
  },
  tripfinder: {
    duration: 250,
    show: false,
    firstOpen: true
  },
  formTabs: {}
};


/**
 * Check if a variable is not undefined
 *
 * @param variable Variable
 * @return boolean TRUE if empty
 */
function isDefined(variable) {
  if (typeof(variable) != 'undefined') {
    return true;
  }
  return false;
}


/**
 * Check if a variable is empty
 *
 * @param variable Variable
 * @return boolean TRUE if empty
 */
function isEmpty(variable) {
  if (!isDefined(variable) || variable == null || variable.length == 0 || variable == '0' || variable == false) {
    return true;
  }
  if (!isNaN(variable) && variable < 1) {
    return true;
  }
  return false;
}


/**
 * Build a menu item for autocomplete list
 *
 * @param string word Search word
 * @param object item Item to render
 * @param boolean isTarget Defines that item is a target
 * @param boolean showInfo Show additional info
 * @return string
 */
function renderAutocompleteItem(word, item, isTarget, showInfo) {
  if (!isDefined(word) || !isDefined(item)) {
    return '';
  }

  // Get additonal information
  var additional = '';
  if (isTarget && showInfo) {
    additional = '(' + item.o + ')'; // Offer count
  }
  if (!isTarget && showInfo) {
    additional += (additional.length ? ' ' : '');
    additional += '(' + allLabels['offerType' + item.k] + ')';
  }
  additional = (additional.length ? '<span class="additionalInfo">' + item.o + '</span>' : '');

  // Get target path
  var path = '';
  if (isTarget) {
    path = item.t;
  } else if (item.t && isDefined(targetDetails[item.t])) {
    path = targetDetails[item.t].t;
  }

  // Save clean label
  if (!isDefined(item.value)) {
    item.value = item.label;
  }

  // Get highlighted word
  word          = '' + word;
  word          = word.toLowerCase();
  var text      = '' + (isDefined(item.value) ? item.value : item.label);
  var lowerText = text.toLowerCase();
  var position  = lowerText.indexOf(word);
  var before    = text.substring(0, position);
  var key       = text.substr(position, word.length);
  var after     = text.substr(position + word.length);

  return '<h4><b>' + before + '<span class="highlight">' + key + '</span>' + after + '</b>' + additional + '</h4>' + path;
}


/**
 * Redirects to item search page
 *
 * @param object item Autocomplete item
 * @return void
 */
function redirectAutocompleteItem(item) {
  if (!isDefined(item)) {
    return;
  }
  var url = pageUrls['default'];
  var value = (isDefined(item.value) ? item.value : item.label);
  if (isDefined(pageUrls['' + item.s])) {
    url = pageUrls[item.s]
  }
  if (url.indexOf('sword=') != -1) {
    url += value;
  }
  if (url.indexOf('show=') != -1) {
    url += item.id;
  }
  if(!isEmpty(settings.forceSearchPage)) {
    url = settings.forceSearchPage;
    url += ((url.indexOf("?") != -1)? "&" : "?") + "sword=" + escape(value);
  }
  location.href = url;
}


/**
 * Create autocomplete widget for offers and targets
 */
jQuery(document).ready(function ($) {
  $.widget("custom.fullsearch", $.ui.autocomplete, {
    targetCount:    5,
    offerCount:     5,
    targetCategory: 1,
    offerCategory:  0,
    showInfo:       false,
    _renderMenu: function(ul, items) {
      var targets   = new Array();
      var offers    = new Array();
      var self      = this;

      // Find targets and offers
      $(items).each(function(key, item) {
        if (targets.length < self.targetCount && item.c == self.targetCategory) {
          if (isDefined(targetDetails[item.u])) {
            var newItem = targetDetails[item.u];
            newItem.label = item.label;
            newItem.id = item.u;
            targets.push(newItem);
          }
        }
        if (offers.length < self.offerCount && item.c == self.offerCategory) {
          if (isDefined(offerDetails[item.u])) {
            var newItem = offerDetails[item.u];
            newItem.label = item.label;
            newItem.id = item.u;
            offers.push(newItem);
          }
        }
      });

      // Add items to menu list
      $(targets).each(function(key, item) {
        item.label = renderAutocompleteItem(self.term, item, true, self.showInfo);
        self._renderItem(ul, item);
      });
      $(offers).each(function(key, item) {
        item.label = renderAutocompleteItem(self.term, item, false, self.showInfo);
        self._renderItem(ul, item);
      });
    }
  });
});


/**
 * Add autocomplete functionallity to an input field
 *
 * @param string fieldname Fieldname
 * @param string type Type of the autocomplete
 * @param integer minLength Minimal length of input
 * @param boolean showInfo Show additional info
 * @param boolean redirect Redirect instantly while selecting an item
 * @return void
 */
function addAutocomplete(fieldname, type, minLength, showInfo, redirect) {
  if (isEmpty(fieldname)) {
    return;
  }

  $('input[name=' + fieldname + ']').each(function(key, field) {
    var $field = $(field);
    var source = suggestAll;
    var count  = 5;

    if (type == 'targets') {
      source = source.slice(0, targetCount);
      count = 10;
    }

    // Add autocomplete
    $field.focus(function() {
      $field.fullsearch('search', '');
    }).fullsearch({
      appendTo: $field.parent(),
      html: true,
      source: source,
      minLength: minLength,
      showInfo: showInfo,
      delay: 0,
      targetCount: count,
      select: function(event, ui) {
        if (redirect) {
          redirectAutocompleteItem(ui.item);
        }
        $field.val((isDefined(ui.item.value) ? ui.item.value : ui.item.label));
        $field.blur();
        return false;
      },
      focus: function(event, ui) {
        $field.val((isDefined(ui.item.value) ? ui.item.value : ui.item.label));
        return false;
      }
    });
  });
}


/**
 * Format a price
 *
 * @param string price Price to format
 * @param integer days Count of days
 * @param string type Type of the offer
 * @param float euroPrice Price in Euro
 * @param string unitType Use long / short / details format for labels
 * @param boolean showExclude Show exclude label
 * @return string
 */
function formatPrice(price, days, type, euroPrice, unitType, showExclude) {
  var newPrice = '';

  if (!isEmpty(price) && !isEmpty(days)) {
    var labelDays = (days > 1 ? allLabels['priceDays'] : allLabels['priceDay']);
    var labelExcl = (type == 2 && !isEmpty(showExclude) ? ' ' + allLabels['priceExclusive'] : '');
    var labelUnit = allLabels['priceUnitShort'];
    if (unitType == 'detail') {
      labelUnit = (type < 2 ? allLabels['priceUnitPersonDetail'] : allLabels['priceUnitRoomDetail']);
    }
    if (unitType == 'long') {
      labelUnit = (type < 2 ? allLabels['priceUnitPerson'] : allLabels['priceUnitRoom']);
    }

    if (euroPrice && euroPrice != "0") {
      newPrice = '<strong>' + days + ' ' + labelDays + ' ' + labelUnit + ' ' + euroPrice + ' </strong>' + ' (' + price + ')';
    } else {
      newPrice = '<strong>' + days + ' ' + labelDays + '</strong> ' + labelUnit + ' <strong>' +  price + '</strong>' + labelExcl;
    }
  }

  return newPrice;
}


/**
 * Builds the container for a teaser element
 *
 * @param object item Item to render
 * @param array details Item details
 * @return void
 */
function completeTeaser(item, details) {
  var $item = $(item);

  // Get location
  var location = '';
  location += (!isEmpty(details['country']) ? details['country'] : '');
  location += (!isEmpty(details['city']) ? '. ' + details['city'] : '');

  // Get price
  var price = (isDefined(details['euro_price']) ? details['euro_price'] : '');
  price = formatPrice(price, details['price_per_days'], details['destination_type'], 0, 'short', false);

  // Link
  $item.find('.destination-teaser-link').attr('href', details['detail_url']);

  // Image
  $item.find('.destination-teaser-image').attr('src', details['teaser_image']);
  if (details['teaser_image'] == 'clear.gif') {
    $item.find('.destination-teaser-image').addClass('no-background');
  }

  // Title
  $item.find('.destination-teaser-title').html(details['title']);

  // Location
  $item.find('.destination-teaser-location').html(location);

  // Price
  $item.find('.destination-teaser-price').html(price);
}


/**
 * Loads Teaser-List Offers via ajax call
 *
 * @param string id
 * @param string limit
 * @param string begin
 * @param string end
 * @param integer pid
 * @return void
 */
function buildTeaserOffers(id, limit, begin, end, pid) {
  var url = '/index.php?eID=tx_21torrdestinations_pi1&method=getTeaserOffers&pid=' + pid;
  url += '&params%5Bid%5D='    + id;
  url += '&params%5Blimit%5D=' + limit;
  url += '&params%5Bbegin%5D=' + begin;
  url += '&params%5Bend%5D='   + end;

  // Get container
  var $teaserList = $('#destination-teaser-' + id);
  if (!isDefined($teaserList)) {
    return;
  }

  // Get teasers
  var $teasers = $teaserList.find('div.destination-teaser');
  if (!isDefined($teasers)) {
    return;
  }

  jQuery.getJSON(url, function(result) {
    jQuery(result).each(function(key, data) {
      if (isDefined($teasers[key])) {
        completeTeaser($teasers[key], data);
      }
    });
  });
}


/**
 * Show tripfinder window on click
 *
 * @return void
 */
function showTripfinder() {
  var tripfinderActive = false;
  $('#tripfinder_button').click(function() {
    if (tripfinderActive) {
      tripfinderActive = false;
      $('#tripfinder_from').autocomplete('close');
      $('#tripfinder_to').autocomplete('close');
      $('#tripfinder_button_shadow').css('background-position', 'left top');
      $('#tripfinder_window').stop(true, true).slideUp({
        duration: settings['tripfinder']['duration'],
        easing: 'easeOutQuint'
      });
    } else {
      tripfinderActive = true;
      if (settings['tripfinder']['firstOpen']) {
        tripfinderFirstOpen = false;
      }
      try {
        addthis_close();
      } catch(e) {}
      $('#tripfinder_button_shadow').css('background-position', 'left bottom');
      $('#tripfinder_window').stop(false, true).slideDown({
        duration: settings['tripfinder']['duration'],
        easing: 'easeOutQuint'
      });
    }
  });
  $('#tripfinder_button').mouseover(function() {
    if (!tripfinderActive) {
      $('#tripfinder_button_shadow').css('background-position', 'left center');
    }
  });
  $('#tripfinder_button').mouseout(function() {
    if (!tripfinderActive) {
      $('#tripfinder_button_shadow').css('background-position', 'left top');
    }
  });

  if ($('#tripfinder_error').text() != '' || !isEmpty(settings['tripfinder']['show'])) {
    tripfinderActive = true;
    settings['tripfinder']['firstOpen'] = false;
    $('#tripfinder_window').show();
    $('#tripfinder_button_shadow').css('background-position', 'left bottom');
  }
};


/**
 * Add datepicker functionallity to input fields
 *
 * @param string beginField Fieldname of the begin field
 * @param string endField Fieldname of the end field
 * @return void
 */
function addDatepicker(beginField, endField) {
  $begin = $(beginField);
  $end = $(endField);

  // Build calender
  var dates = $('input[name=' + beginField + '], input[name=' + endField + ']').datepicker({
    defaultDate: "+1",
    changeMonth: false,
    numberOfMonths: 3,
    showOn: 'both',
    buttonImage: settings.datepicker.buttonImage,
    buttonImageOnly: true,
    showAnim: 'blind',
    duration: 50,
    firstDay: 1,
    showButtonPanel: false,
    onSelect: function(selectedDate) {
      var option = ($(this).attr('name') == beginField ? 'minDate' : 'maxDate');
      var instance = $(this).data('datepicker');
      var date = $.datepicker.parseDate(instance.settings.dateFormat || $.datepicker._defaults.dateFormat, selectedDate, instance.settings);
      // Set one day difference
      if ($(this).attr('name') == beginField) {
        date.setDate(date.getDate() + 1);
      } else {
        date.setDate(date.getDate() - 1);
      }
      dates.not(this).datepicker('option', option, date);
    },
    beforeShowDay: function(date) {
      // Disable dates before today
      var instance = $(this).data('datepicker');
      var today = new Date();
      if (date.getTime() < today.getTime()) {
        return [false, ''];
      }
      return [true, ''];
    }
  });
}


/**
 * Add prices dynamically
 *
 * @param string params Function parameters
 * @param string unitType Use long / short / details format for labels
 * @return void
 */
function addPrices(params, unitType) {
  var url = '/index.php?eID=tx_21torrdestinations_pi1&method=getPrices&' + params;

  jQuery.getJSON(url, function(result) {
    jQuery(result).each(function(key, data) {
      var price  = '';

      if (data.days && data.native_price) {
        price = formatPrice(data.native_price, data.days, data.type, data.euro_price, unitType, true);
      }

      if (data.native_price == '0' || data.native_price == '') {
        price = allLabels['priceNoPrice'];
      }

      jQuery('.price_' + data.uid).html(price);
    });
  });
}


/**
 * Add roomprices dynamically
 *
 * @param string params Function parameters
 * @return void
 */
function addRoomPricesAndInfos(params) {
  var url = '/index.php?eID=tx_21torrdestinations_pi1&method=getRoomPricesAndInfos&' + params;
  jQuery.getJSON(url, function(result) {
    jQuery(result).each(function(key, data) {
      var incPrice   = data.incremental_price;
      var price      = '';
      var select     = '';
      var infos      = data.infos;
      var facilities = '';
      var conditions = '';
      var cancel     = '';
      var prepay     = '';
      var meal       = '';
      var included   = '';
      var excluded   = '';
      var roomtext   = '';

      if (data.price) {
        price = data.price;
        if ($('#show-' + data.uid).hasClass("show-inactive")){
          $('#show-' + data.uid).removeClass("show-inactive");
          $('#show-' + data.uid).addClass("show-active");
        }
      }
      if (isEmpty(data.price)) {
        price = "";
      }

      if (!isDefined(incPrice) && data.uid > 0) {
        $('#price-select_' + data.uid).text('');
        $('#booking_' + data.uid).text(allLabels['priceNoPrice']);
      } else if (isDefined(incPrice)) {
        select = '<select id="' + data.uid + '" name="rooms[nr_rooms_' + data.block_id + ']">';
        for (var counter = 1; ; counter++){
          if (!isDefined(incPrice[counter])){
            break;
          }
          select += '<option value="' + counter + '">' + counter + ' (' + incPrice[counter] + ')</option>';
        }
        select += '</select>';
        $('#price-select_' + data.uid).html(select);
      }

      if (isDefined(infos) && data.uid > 0){
        facilties   = !isEmpty(infos['facilities'])       ? '<b>' + allLabels['availabilityAppointments'] + '</b>: ' + infos['facilities'] + '<br/>' : '';
        cancel      = !isEmpty(infos['cancel'])           ? allLabels['availabilityCancellation'] + ': ' + infos['cancel'] + '<br/>' : '';
        prepay      = !isEmpty(infos['prepay'])           ? allLabels['availabilityPrepay'] + ': ' + infos['prepay'] + '<br/>' : '';
        meal        = !isEmpty(infos['meal'])             ? allLabels['availabilityMealplan'] + ': ' + infos['meal'] + '<br/>' : '';
        included    = !isEmpty(infos['included'])         ? allLabels['availabilityIncluded'] + ': ' + infos['included'] + '<br/>' : '';
        excluded    = !isEmpty(infos['excluded'])         ? allLabels['availabilityExcluded'] + ': ' + infos['excluded'] + '<br/>' : '';
        roomtext    = !isEmpty(infos['roomtext'])         ? infos['roomtext'] + '<br/>' : '';
        until       = !isEmpty(infos['refundable_time'])  ? allLabels['refundableUntilTime'] : allLabels['refundableUntil'];
        refundable  = !isEmpty(infos['refundable_until']) ? ' ' +  until + ' ' + infos['refundable_until'] : '';

        $('#facilities-' + data.uid).html(facilties);
        $('#cancel-'     + data.uid).html(cancel);
        $('#prepay-'     + data.uid).html(prepay);
        $('#meal-'       + data.uid).html(meal);
        $('#included-'   + data.uid).html(included);
        $('#excluded-'   + data.uid).html(excluded);
        $('#roomtext-'   + data.uid).html(roomtext);
        $('#deposit-'    + data.uid).html(allLabels['availabilityRefundable' + infos['deposit']] + refundable + '<br/>');
        $('#breakfast-'  + data.uid).html(allLabels['availabilityBreakfast' + infos['breakfast']]);
      }

      if (data.uid > 0){
        $('#roomprice' + data.uid).html(price);
      }
    });
  });
}


/**
 * Set select value to span on change
 *
 * @return void
 */
function registerSelectChangeHandler() {
  $('div.search-select select').change(function() {
    var $selected = $(this).find('option:selected');
    var text      = $selected.text();
    var index     = $selected.val();
    var title     = $(this).parent().find('select').attr('title');
    if (!isEmpty(title) && isEmpty(index)) {
      text = title;
    }
    $(this).parent().find('span.search-select-text').text(text);
  });
  $('div.search-select select').change();
}


/**
 * Set title as input content on change
 *
 * @return void
 */
function registerInputChangeHandler() {
  $('.search-input').focus(function() {
    var value = $(this).val();
    if (!isEmpty(value) && value == $(this).attr('title')) {
      $(this).val('');
    }
  }).blur(function() {
    if (isEmpty($(this).val())) {
      $(this).val($(this).attr('title'));
    }
  });
}


/**
 * Show / hide search form field by given settings
 *
 * @param object form Instance of the form
 * @param array settings Tab configuration
 * @return void
 */
function handleTabChange(form, settings) {
  if (!isDefined(form) || !isDefined(settings)) {
    return;
  }

  // Traverse all fields
  $(form).find(':input').not(':submit').each(function(key, field) {
    if (isDefined(settings['fields'])) {
      var name = $(field).attr('name');
      name = name.replace(/(\[\])$/, '');
      name = (name == 'child1' ? 'children' : name);

      if (isDefined(name)) {
        var $field = $(form).find('.search-form-' + name);
        var fields = settings['fields'];
        fields = ',' + fields.replace(/\s+/g, '') + ',';
        index  = fields.indexOf(',' + name + ',');
        if (index == -1) {
          $field.parent().hide(); // div.search-form-field
        } else {
          var $label = $field.parent().find('label.search-form-label-default');
          var $altLabel = $field.parent().find('label.search-form-label-' + settings['kind']);
          if (!isEmpty($altLabel)) {
            $label.hide();
            $altLabel.css({display: 'block'});
          } else {
            $field.parent().find('label.search-form-label').hide();
            $label.show();
          }
          $field.parent().css({display: 'block'});
        }
      }
    }
  });
}


/**
 * Get active tab
 *
 * @param array tabConfig Tab configuration
 * @return interger Index of active tab
 */
function getActiveTab(tabConfig) {
  var kind = 'travels';
  if (isDefined(settings['kind'])) {
    kind = settings['kind'];
  }

  for (var key in tabConfig) {
    var tab = tabConfig[key];
    if (isDefined(tab['kind']) && tab['kind'] == kind) {
      return key - 1;
    }
  }

  return 0;
}


/**
 * Add tab functionallity to search forms
 *
 * @return void
 */
function addSearchFormTabs() {
  $('ul.search-tabs').each(function(key, element) {
    if (!isEmpty(element.className)) {
      var tabId = element.className;
      var position = tabId.lastIndexOf('-');
      tabId = tabId.substr(position + 1);

      // Add tabs
      $('ul.search-tabs-' + tabId).tabs('div.search-panes-' + tabId + ' > div', {
        initialIndex: getActiveTab(settings['formTabs']['search-form-' + tabId]),
        onClick: function(event, index) {
          if (isDefined(settings['formTabs']['search-form-' + tabId]) && isDefined(settings['formTabs']['search-form-' + tabId][index + 1])) {
            var tabConfig = settings['formTabs']['search-form-' + tabId][index + 1];
            var $form = $('#search-form-' + tabId);

            // Show / hide fields
            handleTabChange($form, tabConfig);

            // Set new kind
            var kind = (isDefined(tabConfig['kind']) ? tabConfig['kind'] : 'travels');
            $form.find('input[name=kind]').val(kind);

            // Add / remove css class
            $form.removeClass();
            if (isDefined(tabConfig['class'])) {
              $form.addClass(tabConfig['class']);
            }

            // Remove errors (only on real clicks)
            if (isDefined(event['button'])) {
              $form.find('div.search-form-error').removeClass('search-form-error');
              $form.parent().parent().find('div.search-form-errors').hide();
            }
          }
        }
      });
    }
  });
}


/**
 * Register click handler for multiselect checkboxes
 *
 * @return void
 */
function registerMultiselectClickHandler() {
  $('div.search-checkboxes label').click(function(event) {
    $(this).prev('input[type=checkbox]').click();
  });
}


/**
 * Register preload handler for search results
 *
 * @return void
 */
function registerPreloadResultHandler() {
  $('.search-form-preload').submit(function(event) {
    var $form = $(this);
    var $formContainer = $form.parent();
    var $to = $form.find('input[name=to]');
    var title = $to.attr('title');
    var value = $to.val();

    // Show error if field "to" is empty
    if (isEmpty(value) || (!isEmpty(title) && title == value)) {
      $formContainer.find('div.search-form-errors').text(allLabels['toNotDefined']).show();
      $to.parent().addClass('search-form-error');
      return false;
    }

    // Stop here if no UIDs were found
    if (isEmpty($form.find('input[name=uids]').val())) {
      event.preventDefault();
    }

    // Show loading overlay
    var position = $formContainer.position();
    var tabHeight = $formContainer.parent().find('ul.search-tabs').outerHeight();
    var $overlay = $formContainer.parent().find('div.search-form-loading');
    $overlay.css({
      height: ($formContainer.outerHeight() + tabHeight),
      width: $formContainer.outerWidth(),
      top: (position.top - tabHeight),
      left: position.left
    }).show();

    // Send request...
    $.ajax({
      type: 'POST',
      url: '/index.php',
      dataType: 'json',
      data: {
        eID: 'tx_21torrdestinations_pi1',
        method: 'getSearchResults',
        params: {formData: $form.serializeArray()}
      },
      success: function(result) {
        if (!isEmpty(result['uids'])) {
          // Submit form
          $form.find('input[name=uids]').val(result['uids']);
          $form.unbind('submit');
          $form.find('input.search-form-submit').trigger('click');
        } else {
          // Show error
          $formContainer.find('div.search-form-errors').text(allLabels['noResult']).show();
          $overlay.hide();
        }
      }
    });

    return true;
  });
}


/**
 * Show the div, with extended information
 *
 * @param string id Id of div
 * @return void
 */
function registerShowRoomHandler() {
  $('span.show-room-trigger').click(function(event) {
    if ($(this).hasClass('show-inactive')) {
      return false;
    }

    // Get id
    var id = $(this).attr('id');
    id = id.replace(/show\-/, '');

    // Toggle visibility
    var $room = $('#roomdiv-' + id);
    if ($room.is(':visible')) {
      $room.hide();
    } else {
      $room.show();
    }
  });
}


/**
 * Register tooltip handler for hotel rooms
 * 
 * @return void
 */
function registerRoomToolTipHandler() {
  $('.trigger').each(function(index, element) {
    $(element).tooltip({relative: true});
  });
}


/**
 * Allow manipulation of search form
 * 
 * @param string name Name of the field
 * @param string value Value to set
 * @return void
 */
function setFieldValue(name, value) {
  if (isEmpty(name) || isEmpty(value)) {
    return;
  }

    // Default text input
  $('input[name=' + name + ']').val(value);

    // Select field
  $('select[name=' + name + '] option').each(function(key, field) {
    $(this).removeAttr('selected');
    var val = $.trim($(this).val());
    var text = $.trim($(this).text());
    if (val == value || text == value) {
      $(this).attr('selected', true);
      $(this).parent().parent().find('span.search-select-text').text(text);
    }
  });
}


/**
 * Allow manipulation of the active tab
 * 
 * @param string kind Active kind
 * @return void
 */
function setTab(kind) {
  settings['kind'] = kind;
  $('ul.search-tabs').each(function(key, element) {
    if (!isEmpty(element.className)) {
      var tabId = element.className;
      var position = tabId.lastIndexOf('-');
      tabId = tabId.substr(position + 1);
      var activeTab = getActiveTab(settings['formTabs']['search-form-' + tabId]);
      var tabConfig = settings['formTabs']['search-form-' + tabId][activeTab + 1];
      var $form = $('#search-form-' + tabId);
      handleTabChange($form, tabConfig);

      $(this).find('li a').each(function(key, element) {
        $(this).removeClass('current');
        if (key == activeTab) {
          $(this).addClass('current');
        }
      });
    }
  });
}


/**
 * Bootstrap, call several methods after loading DOM
 */
jQuery(document).ready(function ($) {
  addAutocomplete('sword', 'all', 1, false, true);
  addAutocomplete('to', 'targets', 1, false, false);
  addDatepicker('begin', 'end');
  registerSelectChangeHandler();
  registerInputChangeHandler();
  registerMultiselectClickHandler();
  registerPreloadResultHandler();
  registerShowRoomHandler();
  registerRoomToolTipHandler();
});

