﻿/*****************

  (c) 2006 Q42 B.V.

  The contents of this file, partially or in whole, may not be reproduced
  without prior written permission by Q42 B.V.

*****************/

function Search()
{
	Spif.DOMEvents.attach(window, "load", this.doLoad, this);
}

Search.prototype =
{
  firstLoad: true,
  isSubmitted: false,

  doLoad: function() {
    var searchFullSubmit = document.getElementById("search-full-submit");
    if (searchFullSubmit) {
      Spif.DOMEvents.attach(searchFullSubmit, "click", function() {
        if (navigator.userAgent.indexOf("MSIE 5.5") == -1) { // Only for non IE 5.5 browsers
          if (dataCollector == undefined || (dataCollector && dataCollector.productCount == 0 && dataCollector.accommodationCount == 0)) {
            return false; /* Disable button if 0 results */
          }
        }
        search.submitForm();
      });
      Spif.DOMEvents.attach(searchFullSubmit, "focus", function() { this.blur() });
    }

    var searchFullSubmitMap = document.getElementById('search-full-submit-map');
    if (searchFullSubmitMap) {
      Spif.DOMEvents.attach(searchFullSubmitMap, "click", function() {
        if (navigator.userAgent.indexOf("MSIE 5.5") == -1) {
          if (dataCollector == undefined || (dataCollector && dataCollector.productCount == 0 && dataCollector.accommodationCount == 0)) {
            return false;
          }
          search.submitForm("map");
        }
      });
    }

    // Attach all events to buttons, summary-bars etcetera
    var searchByCodeSubmitButton = document.getElementById("search-by-code-submit-button");
    if (searchByCodeSubmitButton) {
      var searchByCodeInput = document.getElementById("search-by-code-input-ctrl");
      Spif.DOMEvents.attach(searchByCodeInput, "keypress", search.handleKeyPress);
      Spif.DOMEvents.attach(searchByCodeSubmitButton, "click", search.submitCodeForm);
    }

    // Attach event to map tab
    var searchMapTab = document.getElementById("search-full-1-tabGooglemap");
    if (searchMapTab) {
      Spif.DOMEvents.attach(searchMapTab, "click", search.checkMap);
    }

    if (document.getElementById('search-full-5'))
      Spif.DOMEvents.attach(document.getElementById('search-full-5'), 'click', search.doClickBudget);
    if (document.getElementById('period-of-arrival'))
      Spif.DOMEvents.attach(document.getElementById('period-of-arrival'), 'change', search.doChangePeriodOfArrival);
    if (document.getElementById('search-full-1-title'))
      Spif.DOMEvents.attach(document.getElementById('search-full-1-title'), 'click', search.clickCountryAndAreaTitle);
    if (document.getElementById('search-full-panel'))
      Spif.DOMEvents.attach(document.getElementById('search-full-panel'), 'click', search.clickTabHoliday);
    if (document.getElementById('search-by-code'))
      Spif.DOMEvents.attach(document.getElementById('search-by-code'), 'click', search.clickTabCode);
    if (document.getElementById('search-by-sitemap'))
      Spif.DOMEvents.attach(document.getElementById('search-by-sitemap'), 'click', search.clickTabSitemap);

    //Attach tooltips
    vstooltip.attachTooltip('info_selectcamp');
    vstooltip.attachTooltip('info_camp2relax');

    setTimeout(function() { search.fillSearchedFor(false); }, 1000);
    search.firstLoad = false;
  },

  submitForm: function(type) {
    var form = document.getElementById("search-full-panel");

    if (type == "map") {
      var mapUrl = document.getElementById('submitMapUrl');
      var listUrl = document.getElementById('submitListUrl');
      var submitUrl = form.getAttribute("action");
      submitUrl = submitUrl.replace(listUrl.value, mapUrl.value);
      form.setAttribute("action", submitUrl);
    }

    //remove names from country
    var selCountry = document.getElementById("selCountry");
    if (selCountry != null) selCountry.setAttribute("name", "");

    //remove names from area's
    var inputfields = form.getElementsByTagName("input");
    for (var i = 0; i < inputfields.length; i++) {
      if (inputfields[i].name.length > 5 &&
	      (inputfields[i].name.substring(0, 5) == "area-" ||
	        inputfields[i].name.substring(0, 10) == "all-areas-")) {
        inputfields[i].name = "";
        inputfields[i].checked = false;
      }
    }

    search.isSubmitted = true;
    form.submit();
  },

  Expanded: false,

  Expand: function() {
    if (!this.Expanded) {
      Spif.Utils.setTimeoutHandler(function() {
        Spif.ClassNameAbstraction.replace(document.getElementById('search-box'), 'search-box-collapsed', 'search-box-expanded');
        //search.fillSearchedFor(true);
      }, 0);

      var alternatives = document.getElementById('search-alternatives-submit');
      if (alternatives != null) {
        Spif.ClassNameAbstraction.replace(alternatives, 'enabled', 'hidden');
      }

      this.Expanded = true;
    }
  },

  Collapse: function() {
    if (this.Expanded) {
      var expandText = document.getElementById("expanded-text");
      if (expandText.innerHTML != '') {
        Spif.Utils.setTimeoutHandler(function() {
          Spif.ClassNameAbstraction.replace(document.getElementById('search-box'), 'search-box-expanded', 'search-box-collapsed');
          if (document.getElementById('search-full-1').className == 'option-expanded') {
            Spif.ClassNameAbstraction.replace(document.getElementById('search-full-1'), 'option-expanded', 'option-collapsed');
          }
          //search.fillSearchedFor(false);
          search.Expanded = false;
        }, 250);
      }
    }
  },

  CollapseOrExpand: function() {
    var legendLink = document.getElementById("legendLink");
    if (this.Expanded) {
      Spif.Utils.setTimeoutHandler(function() {
        Spif.ClassNameAbstraction.replace(document.getElementById('search-box'), 'search-box-expanded', 'search-box-collapsed');
        if (document.getElementById('search-full-1').className == 'option-expanded') {
          Spif.ClassNameAbstraction.replace(document.getElementById('search-full-1'), 'option-expanded', 'option-collapsed');
        }
        //search.fillSearchedFor(false);
        search.Expanded = false;
      }, 0);

      if (legendLink) {
        legendLink.innerHTML = resources.messages.legendOpen;
      }
    }
    else {
      search.Expand();

      if (legendLink) {
        legendLink.innerHTML = resources.messages.legendClose;
      }
    }
  },

  resetAll: function() {
    //Indicate resetAll is called, handled in GetTotals.aspx
    var resetAll = document.getElementById("rall");
    if (resetAll) resetAll.value = '1';

    search.resetCountryAndArea();
    search.resetNumberOfPeople();
    search.resetPeriod();
    search.resetTypeOfHoliday();
    search.resetBudget();
    search.resetGeneral();
    search.resetSelectionText();

    ClickTracker.trackClick(new Click(resources.messages.clicktracker.ct_search_resetall));
  },

  resetSelectionText: function() {
    var selectionDiv = document.getElementById("search-selection-div");
    var hiddenSelection = document.getElementById("hss");

    if (selectionDiv) {
      Spif.ClassNameAbstraction.replace(selectionDiv, "shown", "hidden");
    }

    if (hiddenSelection) {
      hiddenSelection.value = "0";
    }

  },

  resetCountryAndArea: function() {
    var countryDDL = document.getElementById("selCountry");
    if (countryDDL) {
      // Reset country dropdown
      countryDDL.selectedIndex = 0;
    }
    if (document.getElementById('search-full-1').className == 'option-expanded') {
      // Reset the countryandarea object and map
      countryAndArea.changeToCountry("-1");
    } else {
      // Reset the countryandarea object, refresh the map when clicking on the countryandarea-title
      // The flashmap doesn't listen to commands when collapsed, then it crashes.
      // This is a workaround to make the resetting work.
      countryAndArea.changeToCountry("-1");
      countryAndArea.resetMap = true;

      // Rest of the reset-map functionality is handled in the clickCountryAndAreaTitle event-handler.
    }
    ClickTracker.trackClick(new Click(resources.messages.clicktracker.ct_search_ca_reset));
  },

  clickCountryAndAreaTitle: function() {
    Spif.Utils.setTimeoutHandler(function() { flashMap.setMap() }, 501);
  },

  clickTabHoliday: function() {
    if (Spif.ClassNameAbstraction.contains(document.getElementById('search-full-panel'), 'search-panel-collapsed')) {
      if (!search.firstLoad && !search.isSubmitted)
        ClickTracker.trackClick(new Click(resources.messages.clicktracker.ct_search_tab_holiday));

      Spif.Utils.setTimeoutHandler(function() { flashMap.setMap() }, 501);
    }
  },

  clickTabCode: function() {
    if (Spif.ClassNameAbstraction.contains(document.getElementById('search-by-code'), 'search-panel-collapsed')) {
      if (!search.firstLoad)
        ClickTracker.trackClick(new Click(resources.messages.clicktracker.ct_search_tab_code));
    }
  },

  clickTabSitemap: function() {
    if (Spif.ClassNameAbstraction.contains(document.getElementById('search-by-sitemap'), 'search-panel-collapsed')) {
      if (!search.firstLoad)
        ClickTracker.trackClick(new Click(resources.messages.clicktracker.ct_search_tab_sitemap));
    }
  },

  resetPeriod: function() {
    document.getElementById("duration-no-preference").checked = true;
    // document.getElementById("period-of-arrival").selectedIndex = 4;
    document.getElementById("date-of-arrival").value = "";
    // document.getElementById('duration-exact-value').selectedIndex = 0;
    // document.getElementById('duration-min').selectedIndex = 0;
    // document.getElementById('duration-max').selectedIndex = 0;
    document.getElementById("calendar").contentWindow.document.location.replace("/Search/Calendar.aspx?dummy=" + new Date().getTime());
    if (document.getElementById("bandwidth-5radio") != null)
      document.getElementById("bandwidth-5radio").checked = true;
    ClickTracker.trackClick(new Click(resources.messages.clicktracker.ct_search_period_reset));
  },

  resetTypeOfHoliday: function() {
    var el = document.getElementById("search-full-4");
    var inputs = el.getElementsByTagName("input");
    for (var i = 0; i < inputs.length; i++) {
      var input = inputs.item(i);
      if (input.type == "checkbox")
        input.checked = false;
    }
    document.getElementById('number-of-bedrooms').selectedIndex = 0;
    ClickTracker.trackClick(new Click(resources.messages.clicktracker.ct_search_acco_reset));
  },

  resetBudget: function() {
    searchBudgetSlider.minBudget.value = 0;
    searchBudgetSlider.maxBudget.value = 0;
    searchBudgetSlider.setSliderToInputValues();
    ClickTracker.trackClick(new Click(resources.messages.clicktracker.ct_search_price_reset));
  },

  resetNumberOfPeople: function() {
    var numberDDL = document.getElementById("selNumberOfPeople");
    if (numberDDL) {
      numberDDL.selectedIndex = 0;
      Spif.ClassNameAbstraction.replace(document.getElementById('numberofpeople-summary'), 'search-summary-selected', 'search-summary-noselection');
    }
    ClickTracker.trackClick(new Click(resources.messages.clicktracker.ct_search_travelparty_reset));
  },

  resetCode: function() {
    var searchByCodeInput = document.getElementById("search-by-code-input-ctrl");
    var searchByCodeMessage = document.getElementById("search-by-code-message");

    //Clear given text and also hide any possible errormessage
    searchByCodeInput.value = '';
    if (searchByCodeMessage != null) searchByCodeMessage.className = 'hidden';

    ClickTracker.trackClick(new Click(resources.messages.clicktracker.ct_search_code_reset));
  },

  resetGeneral: function() {
    var promotionsAndLastMinutesContainingDiv = document.getElementById("lastMinuteAndPromotionsOptions");
    var inputsInDiv = promotionsAndLastMinutesContainingDiv.getElementsByTagName("input");
    for (var i = 0; i < inputsInDiv.length; i++) {
      var input = inputsInDiv.item(i);
      if (input.type == "checkbox")
        input.checked = false;
    }
  },

  checkCodeFormIsEmpty: function(evt) {
    var inputField = document.getElementById('search-by-code-input').getElementsByTagName('input')[0];

    if (inputField.value != "") {
      var submitButton = document.getElementById('search-by-code-submit').getElementsByTagName('input')[0];
      submitButton.disabled = true;
      submitButton.style.cursor = 'default';
      document.getElementById('search-by-code-form').submit();
      ClickTracker.trackClick(new Click(resources.messages.clicktracker.ct_search_codebutton));
      return true;
    }
    else {
      return false;
    }
  },

  submitCodeForm: function() {
    return search.checkCodeFormIsEmpty();
  },

  handleKeyPress: function(evt) {
    var key = evt.keyCode || evt.which;
    if (key == 13) {
      search.checkCodeFormIsEmpty();
    }
  },

  // check that min < max when selecting a stay period
  //  checkMinMaxPeriod: function(evt)
  //  {
  //    var min = document.getElementById('duration-min');
  //    var max = document.getElementById('duration-max');
  //    var minmax = document.getElementById('duration-minmax');

  //    if (parseInt(min.options[min.selectedIndex].value) >= parseInt(max.options[max.selectedIndex].value))
  //    {
  //      alert(ERROR_PERIOD_MINMAX);
  //      (evt.srcElement || evt.target).selectedIndex = 0;
  //      if (evt.preventDefault)
  //        evt.preventDefault();
  //      return false;
  //    }
  //    else
  //      minmax.checked = true;
  //  },

  // if we select an exact duration, reset our min-max settings
  doClickDurationExact: function() {
    document.getElementById('duration-exact').checked = true;
    // document.getElementById('duration-min').selectedIndex = 0;
    // document.getElementById('duration-max').selectedIndex = 0;
  },

  // if we select a min-max duration, reset our exact settings
  // doClickDurationMinMax: function()
  // {
  //  document.getElementById('duration-minmax').checked = true;
  //  document.getElementById('duration-exact-value').selectedIndex = 0;
  //},

  doClickBudget: function(evt) {
    if (/\bdisabled/.test(this.className))
      alert(resources.SpecialDecode(resources.messages.error_budget_selectperiod));
  },

  checkMap: function() {
    if (GoogleMapSearch) {
      Spif.Utils.setTimeoutHandler(function() { GoogleMapSearch.checkResize() }, 50);
    }
  },

  fillSearchedFor: function(expand) {
    var searchedFor = document.getElementById('results-header-searched-for');

    if (searchedFor == null) return;
    if (expand) {
      Spif.ClassNameAbstraction.replace(searchedFor, 'enabled', 'hidden');
      return;
    }
    else {
      Spif.ClassNameAbstraction.replace(searchedFor, 'hidden', 'enabled');
    }

    var codeSearch = document.getElementById('resultContent');

    var html = [];

    if (codeSearch != null && codeSearch.innerHTML != '') {
      html.push(codeSearch.innerHTML);
    }
    else {
      var summary, hasSummary;
      var summaries = [
				document.getElementById('countryandarea-summary'),
				document.getElementById('numberofpeople-summary'),
				document.getElementById('searchperiod-summary'),
				document.getElementById('searchtype-summary'),
				document.getElementById('searchbudget-summary')
			];

      for (var i = 0; i < summaries.length; i++) {
        summary = summaries[i];
        hasSummary = !/-noselection/.test(summary.className);
        if (html.length >= 6) {
          break;
        }
        if (hasSummary) {
          html.push(summary.innerHTML);
        }
      }
    }

    if (html.length > 0) {
      var index = searchedFor.innerHTML.indexOf(':');
      var searchedString = searchedFor.innerHTML.substring(0, index + 1) + ' ' + html.join(", ");
      if (searchedString.length > 90) {
        searchedString = searchedString.substring(0, 90) + '...';
      }
      searchedFor.innerHTML = searchedString;
    }
    else {
      if (searchedFor.innerHTML.indexOf(resources.messages.mapSelection) == -1) {
        Spif.ClassNameAbstraction.replace(searchedFor, 'enabled', 'hidden');
      }
      else {
        var index = searchedFor.innerHTML.indexOf(':');
        searchedFor.innerHTML = searchedFor.innerHTML.substring(0, index + 1) + ' -';
      }
    }
  },

  doChangePeriodOfArrival: function(evt) {
    var newValue = this.options[this.selectedIndex].value;
    var iframe = document.getElementById('calendar');
    var iframeLoc = iframe.contentWindow.document.location.href;
    if (/period-of-arrival=/.test(iframeLoc))
      iframe.contentWindow.document.location = iframeLoc.replace(/period-of-arrival=([^=]*)/, 'period-of-arrival=' + newValue);
    else
      iframe.contentWindow.document.location = iframeLoc + (iframeLoc.indexOf("?") == -1 ? "?" : "&") + "period-of-arrival=" + newValue;
  },

  reloadCalendar: function(url) {
    document.getElementById("calendar").contentWindow.document.location.replace(url);
  }
}
var search = new Search();