//--------------------------------------------------
//
// javascript functions for frontpage and 
// categories step by step search dialogue
// and search results page; search revision,
// filtering and sorting
//
// Last updated: 2008-06-23 by tomesto
//--------------------------------------------------
//
// DO NOT EDIT THIS FILE UNLESS YOU ARE ABSOLUTELY
// SURE ABOUT WHAT YOU ARE DOING.
//
//--------------------------------------------------

//--------------------------------------------------
// The following will setup and execute waiting 
// message and graphics for infoPageSearch
//--------------------------------------------------

require("/o2www/js/util/urlMod.js");

window.onunload = function() { // let's make sure the page goes back to normal when waiting is over
  hideWaitingMessage();
}
//--------------------------------------------------
function setupWaitingMessage(message) { // create the message
  var newDiv = document.createElement('div');
  newDiv.setAttribute('id','waitingForInfoPageSearchResults');
  newDiv.className = 'waitingForInfoPageSearchResults';
  newDiv.style.display = 'none';
  newDiv.innerHTML = message;
  document.body.appendChild(newDiv);
}
//--------------------------------------------------
function showWaitingMessage() { // show the message
  var wrapperEl = document.getElementById('wrapper');
  wrapperEl.style.opacity = '0.1';
  wrapperEl.style.position = 'relative';
  wrapperEl.style.filter = 'alpha(opacity=10)';
  var waitingMessageDiv = document.getElementById('waitingForInfoPageSearchResults');
  if (waitingMessageDiv) {
    waitingMessageDiv.style.display = 'block';
  }
}
//--------------------------------------------------
function hideWaitingMessage() {
  var wrapperEl = document.getElementById('wrapper');
  wrapperEl.style.opacity = '1';
  wrapperEl.style.position = '';
  wrapperEl.style.filter = 'alpha(opacity=100)';
  var waitingForInfoPageSearchResults = document.getElementById('waitingForInfoPageSearchResults');
  if (waitingForInfoPageSearchResults) {
    waitingForInfoPageSearchResults.style.display = 'none';
  }
}
//--------------------------------------------------
function onRuleCheckSuccess() { // this function is invoked in rules.js (onsite/o2)
  showWaitingMessage();
}
//--------------------------------------------------
//--------------------------------------------------
function chooseInfoPageType(infoPageClassName) {
  var speciesContent = document.getElementById('specifySpeciesContent');
  if (speciesContent) {
    var speciesCheckboxes = speciesContent.getElementsByTagName('input');
    for (var i = 0; i < speciesCheckboxes.length; i++) {
      if (speciesCheckboxes[i].name == 'serviceTypeId') {
        speciesCheckboxes[i].checked = false;
      }
    }
  }

  if (!infoPageClassName || infoPageClassName === 'Inatur::Obj::Shop::InfoPage::Accommodation') {
    toggleChooseSpecies(false);
  }
  else {
    toggleChooseSpecies(true);
  }
  document.getElementById( 'listSpecifiedSpecies' ).style.display = 'none';
  document.getElementById( 'radioAllSpecies'      ).checked       = true;
  document.getElementById( 'radioSelectedSpecies' ).checked       = false;

  // Use proper terminology by infopagetype for "species" or "activities"
  var radioSelectedSpeciesLbl = document.getElementById('radioSelectedSpecies').nextSibling;
  if (infoPageClassName === 'Inatur::Obj::Shop::InfoPage::NatureTourism' || infoPageClassName === 'Inatur::Obj::Shop::InfoPage::OutdoorsLife') { // XXX 7789 (inatur.se)?
    radioSelectedSpeciesLbl.innerHTML = CHOOSEACTIVITIES; // XXX Language variable
  }
  else {
    radioSelectedSpeciesLbl.innerHTML = CHOOSESPECIES; // XXX Language variable
  }
}
//--------------------------------------------------
function toggleChooseSpecies( status ) {
  _toggleClassName('searchStep1', ' stripeThrough', status);
  _showOrHide('chooseSpecies', status);
}
//--------------------------------------------------
function openChooseSpecies(e) {
  var mouseCoordinates = _getMouseCoordinates(e);
  try {
    swapDivs('chooseSpecies', 'listSpecifiedSpecies');
  }
  catch (e) {}
  var infoPageClassName;
  var infoPageTypeSelect = document.getElementById('infoPageClassNameSelect');
  if (infoPageTypeSelect) {
    infoPageClassName = infoPageTypeSelect.options[ infoPageTypeSelect.selectedIndex ].value;
  }
  if (!infoPageClassName && document.getElementById('infoPageClassNameInput')) {
    infoPageClassName = document.getElementById('infoPageClassNameInput').value;
  }
  if (!infoPageClassName) {
    infoPageClassName = o2UrlMod.getParam("infoPageClassName");
  }
  specifySpecies( infoPageClassName, mouseCoordinates.x, mouseCoordinates.y + 10 );
}
//--------------------------------------------------
var currentSpeciesPopupInfoPageClassName = null;
function specifySpecies(infoPageClassName, x, y) {
  showPopup('specifySpecies', y, x);  // Somehow showPopup uses y as first of the two coordinates...
  if ( currentSpeciesPopupInfoPageClassName != infoPageClassName ) { // We're currently just updating the species, so don't reload
    var params = 'infoPageClassName=' + infoPageClassName + '&infoPageClassNameInputAlreadyIncluded=1';
    params    += SERVICETYPEIDS ? '&serviceTypeIds=' + escape(SERVICETYPEIDS) : '';
    ajaxCall({
      'serverScript' : '/o2/Search/listPossibleSpecies', // uses template 'includes/listPossibleSpecies.html'
      'params'       : params,
      'target'       : 'specifySpeciesContent',
      'where'        : 'replace'
    });
    currentSpeciesPopupInfoPageClassName = infoPageClassName;
  }
}
//--------------------------------------------------
var SERVICETYPEIDS = null;
function fillSpeciesTeaserOnInfoPageSearchResultPostLoad( infoPageClassName, serviceTypeIds  ) { // this function populates the speciesTeaser when infoPageSearchResults has loaded
  SERVICETYPEIDS = serviceTypeIds;
  var specifySpeciesPopup = document.getElementById('specifySpecies');
  specifySpeciesPopup.style.visible = 'none'; // make sure the popup isn't visible when it is populated
  specifySpecies(infoPageClassName, 0, 0); // we do need to populate the popup with available services, which in turn populates the teaser
  hidePopup('specifySpecies');  // hide the popup afterwards
  specifySpeciesPopup.style.visible = 'visible'; // set the popup back to visible
}
//--------------------------------------------------
function toggleSpecies( status, subTypeName ) {
  var name = subTypeName ? 'serviceTypeId_' + subTypeName : 'serviceTypeId';
  var allSpeciesCheckBoxes = document.getElementsByName( name );
  for (var i=0; i < allSpeciesCheckBoxes.length; i++) {
    if (allSpeciesCheckBoxes[ i ].value) {
      allSpeciesCheckBoxes[ i ].disabled = status;
      allSpeciesCheckBoxes[ i ].checked  = status;
    }
  }
  updateSpeciesTeaser();
}
//--------------------------------------------------
function updateSpeciesTeaser() {
  var teaser = document.getElementById( 'speciesTeaser' );
  if (!teaser) { 
    return; 
  }
  var inputs = document.getElementById('specifySpeciesContent').getElementsByTagName('input');
  var teaserText = '';  
  for (var i=0; i < inputs.length;i++) {
    var input = inputs[i];
    if (input.value && input.name.match(/^serviceTypeId/) && input.checked && teaserText.length + input.value.length < 22) {
      teaserText += ', ' + input.value;
    }
  }
  teaserText = teaserText.substr(1) + '...&nbsp;';
  teaser.innerHTML = teaserText;
}
//--------------------------------------------------
function toggleChoosePeriod( status ) {
  _showOrHide('choosePeriod', status);
  activateStep(2);
  _toggleClassName( 'searchStep2', 'stripeThrough', status );
}
//--------------------------------------------------
function activateStep(stepN) {
  if (stepN == 2) {
    document.getElementById('secondDividerImg').src  = document.getElementById('secondDividerImg').src.replace(/inactive/i, 'active'); 
  }
  var elm = document.getElementById( 'searchStep' + stepN );
  removeClassName( elm, 'inactive' );
  addClassName(    elm, 'active'   );
  // _replaceClassName( 'searchStep'+stepN, 'inactive', 'active' );
}
//--------------------------------------------------
function toggleChooseCounty(status) {
  activateStep( 2 );
  activateStep( 3 );
  _showOrHide( 'selectLocationsWrapper', status );
  // _showOrHide( 'selectLocations',        status );
  _toggleClassName( 'searchStep3', 'stripeThrough', status );
}
//--------------------------------------------------
var hasPoppedMunicipalities = false;
function selectMunicipalities(e) {
  document.getElementById('countyIdSelector').style.visibility = 'hidden';
  var placeImportantnessEl = document.getElementById('placeImportantness');
  if (placeImportantnessEl) {   // this one exists only on search results page
    placeImportantnessEl.value = 'important';
  }
  var mouseCoordinates = [];
  if (e) {
    mouseCoordinates = _getMouseCoordinates(e);
  }
  else {
    mouseCoordinates.x = 0;
    mouseCoordinates.y = 0;
  }
  var countyId;
  if (document.getElementById( 'countyIdSelector' ).value) {
    countyId = document.getElementById( 'countyIdSelector' ).options[ document.getElementById( 'countyIdSelector' ).selectedIndex ].value
  }
  showPopup( 'specifyMunicipalities', mouseCoordinates['y'], mouseCoordinates['x'] );  // Somehow showPopup uses y as first of the two coordinates...
  if ( !hasPoppedMunicipalities ) {
    var params = countyId     ? 'countyId='     + countyId     : 
                 COUNTYID     ? 'countyId='     + COUNTYID     : '';
    params    += MUNICIPALIDS ? '&municipalIds=' + MUNICIPALIDS : '';
    params    += COUNTYIDS    ? '&countyIds='    + COUNTYIDS    : '';
    ajaxCall({'serverScript' : '/o2/Search/listPossibleMunicipalities?', // uses template 'includes/listPossibleMunicipalities.html'
              'params'       : params,
              'target'       : 'specifyMunicipalitiesContent',
              'where'        : 'replace'
             });
     hasPoppedMunicipalities = true;
   }
}
//--------------------------------------------------
var COUNTYID = null;
var MUNICIPALIDS = null;
var COUNTYIDS = null;
function fillMunicipalitiesTeaserOnInfoPageSearchResultPostLoad( countyId, municipalIds, countyIds ) { 
  // this function populates the municipalitiesTeaser 
  // when infoPageSearchResults has loaded
  COUNTYID = countyId;
  MUNICIPALIDS = municipalIds;
  COUNTYIDS = countyIds;
  var specifyMunicipalitiesPopup = document.getElementById('specifyMunicipalities');
  specifyMunicipalitiesPopup.style.visible = 'none';
  selectMunicipalities();
  hidePopup('specifyMunicipalities');
  specifyMunicipalitiesPopup.style.visible = 'visible';
}
//--------------------------------------------------
function updateMunicipalitiesTeaser() {
  var teaser = document.getElementById( 'municipalitiesTeaser' );
  if (!teaser) {
    return;
  }
  var teaserText = '';
  var countySelectors = document.getElementById('specifyMunicipalitiesContent').childNodes;
  for (var i=0; i < countySelectors.length;i++) {
    if ( countySelectors[i].className && countySelectors[i].className.match(/countyNumberPopupDiv/)) {
      var teaserTextTmp = _getTeaserTextForCountySelector( countySelectors[i] );
      if (teaserTextTmp) {
        teaserText = teaserText + teaserTextTmp;
      }
    }
  }
  teaserText = teaserText.substr(1) + '...&nbsp;';
  teaser.innerHTML = teaserText;
}
//--------------------------------------------------
function toggleCounty( countyId, status ) {
  _showOrHide( 'countySelectorForCountyId_'+countyId, status );
  var allMunicipalityNumbersEl = document.getElementById( 'allMunicipalityNumbers_'+countyId );
  if (status) {
    allMunicipalityNumbersEl.disabled = '';
    allMunicipalityNumbersEl.checked = 'checked';
    allMunicipalityNumbersEl.value = countyId;
  } else {
    allMunicipalityNumbersEl.disabled = 'true';
  }
  updateMunicipalitiesTeaser();
}
//--------------------------------------------------
function toggleAllMunicipalities( countyId, status ) {
  var checkboxes = document.getElementById( 'countySelectorForCountyId_'+countyId ).getElementsByTagName( 'input' );
  for (var i=0; i <  checkboxes.length; i++) {
    if ( checkboxes[ i ].name == 'municipalities' ) {
      checkboxes[ i ].checked  = status;
      checkboxes[ i ].disabled = status;
    }
  }
  updateMunicipalitiesTeaser();
} 
//--------------------------------------------------
// "Private" helper functions
//--------------------------------------------------
function _getTeaserTextForCountySelector( countySelector ) {
  var teaserText;
  var teaserTextTmp = '';
  var inputs = countySelector.getElementsByTagName('input');
  for (var i=0; i < inputs.length;i++) {
    var input = inputs[i];
    if (inputs[i].name.match(/wholeCounty/) && inputs[i].disabled) {
      break;
    }
    if (input.value && input.name.match(/^municipalities/) && input.checked && teaserTextTmp.length + input.title.length < 22) {
      teaserTextTmp += ', ' + input.title;
    }
  }
  teaserText = teaserTextTmp;
  return teaserText;
}
//--------------------------------------------------
function _toggleClassName (elmId, className, status)          { 
  if (status) {
    addClassName(elmId, className);
  }
  else {
    removeClassName(elmId, className);
  }
}
//--------------------------------------------------
function _showOrHide(elmId, status) { 
  document.getElementById(elmId).style.display = status ? 'block' : 'none';
}
//--------------------------------------------------
function _getMouseCoordinates( e ) {
  var coordinates = new Array();
  e = e ? e : window.event;
  coordinates[ 'x' ] = 0; // Set x to default 0
  coordinates[ 'y' ] = 0; // Set y to default 0
  if ( e.clientX  ) {
    coordinates[ 'x' ] = e.clientX + document.body.scrollLeft;
    coordinates[ 'y' ] = e.clientY + document.body.scrollTop;
  }
  else if ( e.pageX ) {
    coordinates[ 'x' ] = e.pageX;
    coordinates[ 'y' ] = e.pageY;
  }
  if (typeof(window['isIE6']) != 'undefined' && isIE6) {
    var pp = elementGeometry(document.getElementById('wrapper'));
    coordinates[ 'x' ]=(coordinates[ 'x' ]-pp.left);
  }
  return coordinates;
}
//--------------------------------------------------

//--------------------------------------------------
//------ FILTERING FUNCTIONS -----------
//--------------------------------------------------
var searchResults = new Array();
var permanentlyRemovedSearchResults = new Array();
//--------------------------------------------------
function filter(parentElementId, subTagName) {
  var searchResultsElm = document.getElementById(parentElementId);
  if (!searchResultsElm) {
    return;
  }
  var ids = new Array("genericFilter_generic", "filterOnOfferType_week", "filterOnOfferType_hour", "filterOnOfferType_season", "filterOnOfferType_day", "filterOnOfferType_other",
    "filterOnOfferVariation_withDog", "filterOnOfferVariation_withoutDog", "filterOnOfferVariation_externalCustomerOnly", "filterOnOfferVariation_localCustomerOnly");
  for (var i = 0; i < searchResultsElm.childNodes.length; i++) {
    var elm = searchResultsElm.childNodes[i];
    if (elm.nodeName == subTagName.toUpperCase()) {
      var mustBeVisible = false;
      for (var j = 0; j < ids.length; j++) {
        var id = ids[j];
        var className = id.substring( id.indexOf("_")+1 );
        if (elm.className.indexOf(className) != -1) {
          // console.log('filterdebug: ' + id);
          if (document.getElementById(id).checked) {
            elm.style.display = '';
            mustBeVisible = true;
          }
        }
      }
      if (!mustBeVisible) {
        elm.style.display = 'none';
      }
    }
  }
}
//--------------------------------------------------
function toggleFilterByCanBuyOnline(checked) {
  if (!checked) {
    filter('searchResults', 'DIV');
    return;
  }
  var searchResultsElm = document.getElementById('searchResults');
  for (var i = 0; i < searchResultsElm.childNodes.length; i++) {
    var elm = searchResultsElm.childNodes[i];
    if (elm.nodeName == "DIV") {
      if (elm.className.indexOf("canBuyOnline") == -1) {
        elm.style.display = "none";
      }
    }
  }
}
//--------------------------------------------------
function toggleCheckOfferTypes(checked) {
  var ids = new Array("genericFilter_generic", "filterOnOfferType_week", "filterOnOfferType_hour", "filterOnOfferType_season", "filterOnOfferType_day", "filterOnOfferType_other");
  for (var i = 0; i < ids.length; i++) {
    var elm = document.getElementById(ids[i]);
    if (checked != elm.checked) {
      elm.click();
    }
  }
}
//--------------------------------------------------
function hidePermanentlyRemovedSearchResults() {
  for (var i = 0; i < permanentlyRemovedSearchResults.length; i++) {
    document.getElementById( permanentlyRemovedSearchResults[i] ).style.display = "none";
  }
}
//--------------------------------------------------
function updateSavedFilters(element) {
  var serverScript = '/o2/Search/' + (element.checked ? 'addFilterToSavedSearch' : 'removeFilterFromSavedSearch');
  ajaxCall({
    'serverScript' : serverScript,
    'params'       : 'filter=' + element.value
  });
}
//--------------------------------------------------
function removeInfoPageFromResults(element, infoPageId) {
  element.parentNode.style.display = 'none';
  permanentlyRemovedSearchResults.push(element.parentNode.id);
  ajaxCall({
    'serverScript' : '/o2/Search/removeInfoPageFromSavedSearch',
    'params'       : 'infoPageId=' + infoPageId
  });
}
//--------------------------------------------------

//--------------------------------------------------
//------ SORTING -----------
//--------------------------------------------------
// Complete rewrite 2008-06-24 by tomesto due to IE
function sortSearchResults() {
  var field = document.getElementById('sortBySelect').value;
  if (!field) {
    return;
  }
  var sortedResults = _sortResults(field);
  var html = "";
  var sortByHeaderClass = 'initialSortByClass';
  var sortByHeaderClassIds = new Array();
  for (var i = 0; i < sortedResults.length; i++) {
    var elm = document.getElementById( "searchResult" + sortedResults[i].id ); 
    if (elm && !elm.style.display.match(/none/)) {
      html += sortedResults[i].html;
      if (field.match(/municipality/)) {
        var headerElm = document.getElementById( "searchResultsHeaderMunicipality" + sortedResults[i].id );
        if (!headerElm.className.match(sortByHeaderClass) && field.match(/municipality/)) {
          sortByHeaderClass = headerElm.className;
          sortByHeaderClassIds.push(headerElm.id);
        }
      }
    }
  }
  document.getElementById("searchResults").innerHTML = html;
  _showSortByHeaderClassIds(sortByHeaderClassIds);
}
//--------------------------------------------------
function _showSortByHeaderClassIds(ids) {
  if (ids.length > 0) {
    for (var i = 0;i < ids.length;i++) {
      document.getElementById(ids[i]).style.display = 'block';
    }
  }
}
//--------------------------------------------------
function _sortResults(field) {
  var sortedResults = searchResults;
  if (field.match(/municipality/)) {
    sortedResults.sort(_sortByMunicipality);
  }
  if (field.match(/infoPageTitle/)) {
    sortedResults.sort(_sortByInfoPageTitle);
  }
  return sortedResults;
}
//--------------------------------------------------
function _sortByMunicipality(a, b) {
  if (a.municipality > b.municipality) {
    return 1;
  }
  if (a.municipality < b.municipality) {
    return -1;
  }
  return 0;
}
//--------------------------------------------------
function _sortByInfoPageTitle(a, b) {
  if (a.infoPageTitle > b.infoPageTitle) {
    return 1;
  }
  if (a.infoPageTitle < b.infoPageTitle) {
    return -1;
  }
  return 0;
}
//--------------------------------------------------
