﻿/*****************

  (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.

  Restructured & commented by Rens 13/10/2006
*****************/

function CountryAndArea() 
{ 
  Spif.DOMEvents.attach(window, "load", this.init); 
}

CountryAndArea.prototype =
{
  currentSelectedCountry: -1,
  usedCountries: true,
  resetMap: false,
  execSelectCountry: true, // used for working around the Firefox 'initialize flash when showing flashobject' bug

  init: function() {
    // Initialize the country-and-area searchsection
    var countryDDL = document.getElementById("selCountry");
    if (countryDDL) {
      countryAndArea.currentSelectedCountry = parseInt(countryDDL.options[countryDDL.selectedIndex].value)
      Spif.DOMEvents.attach(countryDDL, "change", countryAndArea.doChangeCountry);

      // if this is a page reload and we already selected a country on the previous load,
      // FF needs the selectedindex/focus changing to get the list of areas to show
      if (countryAndArea.currentSelectedCountry > -1) {
        var divEl = document.getElementById("AreaList-" + countryAndArea.currentSelectedCountry);
        if (divEl) {
          divEl.style.display = "block";
        }
      }
    }

    var areaUL = document.getElementById('areaUL');
    if (areaUL) {
      var inputs = areaUL.getElementsByTagName('input');
      for (var i = 0; i < inputs.length; i++) {
        if (inputs[i].type == "checkbox")
          Spif.DOMEvents.attach(inputs[i], "click", countryAndArea.doChangeCheckBox);
      }
    }

    var allCountries = document.getElementById('allCountries');
    if (allCountries) {
      var inputs = allCountries.getElementsByTagName('input');
      for (var i = 0; i < inputs.length; i++) {
        if (inputs[i].type == "checkbox")
          Spif.DOMEvents.attach(inputs[i], "click", countryAndArea.doChangeCountriesCheckBox);
      }
    }

    countryAndArea.updateSummary();
  },

  changeToCountryNew: function(countryId, updateTotal) {
    countryAndArea.doResetCountries();
    
    // 1. Oude selecties verwijderen
    countryAndArea.disableUnusedSelections();
    countryAndArea.resetAllAreaCheckBoxes();
    // 2. Vervangen countrypanel door nieuwe countrypanel
    countryAndArea.changeCountryPanel(countryId);
    // 3. Vink voor "heel (land)"
    countryAndArea.checkAllAreasCheckBox(countryId);
    // 4. ActiveCountryId & RegionIds store updaten
    countryAndArea.currentSelectedCountry = countryId;
    flashMap.countryId = countryId;
    flashMap.regionIds = [];
    // 5. FLASHMAP updaten
    flashMap.setMap();
    // 6. Summary updaten
    countryAndArea.updateSummary();
    if (updateTotal) {
      dataCollector.getTotals();

      var sel = document.getElementById("selCountry");
      var theText = resources.RemoveDiacritics(sel.options[sel.selectedIndex].innerHTML);
      //FireFox has a \n\t in the string
      theText = theText.replace('\n', '').replace('\t', '');

      ClickTracker.trackClick(new Click(resources.messages.clicktracker.ct_search_ca_country + theText));
    }
  },

  changeToCountry: function(countryId) {
    countryAndArea.changeToCountryNew(countryId, countryId != countryAndArea.currentSelectedCountry);
  },

  toggleRegion: function(regionId) {
    countryAndArea.doResetCountries();
    
    // 1. Wanneer destination geselecteerd, dan ook parent-area selecteren
    //processOtherCheckBoxes(el);
    // 2. All areas checkbox uitvinken
    countryAndArea.updateAllAreasCheckBox(countryAndArea.currentSelectedCountry);
    // 3. RegionIds store updaten met nieuwe regionId
    flashMap.updateRegionStoreByToggling(regionId);
    // 4. FLASHMAP updaten
    flashMap.setMap();
    // 5. Summary updaten
    countryAndArea.updateSummary();
    // 6. Aantal resultaten updaten
    dataCollector.getTotals();
    ClickTracker.trackClick(new Click(resources.messages.clicktracker.ct_search_ca_area + regionId));
  },

  selectCountryFromlist: function(countryId) {
    // Select the right country from the country-dropdownlist
    var countryDropDown = document.getElementById("selCountry");
    var options = countryDropDown.getElementsByTagName("option");
    for (var i = 0; i < options.length; i++) {
      if (options[i].getAttribute("value") == countryId)
        options[i].selected = true;
    }
    return;
  },

  selectAreaFromList: function(areaId) {
    // Select the right region from the regionlist
    if (document.getElementById(areaId))
      document.getElementById(areaId).checked = true;
    return;
  },

  deselectAreaFromList: function(areaId) {
    // Deselect the right region from the regionlist
    if (document.getElementById(areaId))
      document.getElementById(areaId).checked = false;
    return;
  },

  disableUnusedSelections: function() {
    // Set all unused regions and countries to disabled    
    // so that our NameValueCollection isn't growing too big, to save bandwidth and enable
    // the browser to store our settings in a cookie.
    var countryDropDownList = document.getElementById('selCountry');

    for (var i = 0; i < countryDropDownList.options.length; i++) {
      var option = countryDropDownList.options[i];
      var disable = (countryDropDownList.selectedIndex != i);
      var div = document.getElementById("AreaList-" + option.value);
      if (div) {
        var areaCheckBoxes = div.getElementsByTagName("input");
        for (var j = 0; j < areaCheckBoxes.length; j++) {
          var areaCheckBox = areaCheckBoxes.item(j);
          if (areaCheckBox.type == "checkbox")
            if (disable)
            areaCheckBox.disabled = true;
          else
            areaCheckBox.removeAttribute("disabled");
        }
      }
    }
  },

  changeCountryPanel: function(toCountryId) {
    // Hide the current countrypanel and show the newly selected panel   
    var oldCountryPanel = document.getElementById("AreaList-" + countryAndArea.currentSelectedCountry);
    if (oldCountryPanel)
      oldCountryPanel.style.display = "none";
    var newCountryPanel = document.getElementById("AreaList-" + toCountryId);
    if (newCountryPanel)
      newCountryPanel.style.display = "block";
  },

  toggleAllAreasCheckBox: function(countryId) {
    // Check or uncheck the all areas checkbox of the country with given countryId
    var allAreasCheckBox = document.getElementById('all-areas-' + countryId);
    if (allAreasCheckBox.checked == false)
      allAreasCheckBox.checked = true;
    else
      allAreasCheckBox.checked = false;
  },

  doChangeCheckBox: function(evt, el) {
    if (!el) return;

    countryAndArea.doResetCountries();
    if (countryAndArea.isAllAreasCheckBox(el)) // CLICKED ON ALL AREAS
    {
      //1. If allareas is checked, reset/uncheck all (children) area checkboxes
      if (el.checked == true)
        countryAndArea.resetAllAreaCheckBoxes()
      else
        el.checked = true; // set back to true if trying to uncheck
      // 2. Update RegionIds
      flashMap.regionIds = []; // checked or unchecked, always clear the region store
    }
    else // CLICKED ON AREA OR DESTINATION CHECKBOX
    {
      var allAreasCheckBox = document.getElementById('all-areas-' + countryAndArea.currentSelectedCountry);
      countryAndArea.updateAllAreasCheckBox(countryAndArea.currentSelectedCountry); // if all areas checkbox is checked, uncheck it
      // 2. Update RegionIds
      flashMap.updateRegionStoreByToggling(el.id);
    }

    // 3. Update Flashmap
    flashMap.setMap();

    var regionId = el.id.replace('area-', '').split('-')[1];
    ClickTracker.trackClick(new Click(resources.messages.clicktracker.ct_search_ca_area + regionId));

    // 4. Update summary
    countryAndArea.updateSummary();

  },

  isAllAreasCheckBox: function(element) // return true if element is the all areas checkbox of the currently selected country
  {
    var allAreasCheckBox = document.getElementById('all-areas-' + countryAndArea.currentSelectedCountry);
    if (element == allAreasCheckBox)
      return true;
    else
      return false;
  },

  isAllAreasCountriesCheckBox: function(element) {
    if (element.id.indexOf('all-careas-') == 0)
      return true;
    else
      return false;
  },

  doChangeCountry: function() {
    // Update the page when another country is selected from the dropdown list with countries
    var countryDropDownList = document.getElementById('selCountry');
    var countryId = parseInt(countryDropDownList.options[countryDropDownList.selectedIndex].value);
    countryAndArea.changeToCountry(countryId);
  },

  uncheckAllAreasCheckBox: function() {
    if (countryAndArea.currentSelectedCountry > 0) {
      var allAreasCheckBox = document.getElementById('all-areas-' + countryAndArea.currentSelectedCountry);
      allAreasCheckBox.checked = false;
    }
  },

  checkAllAreasCheckBox: function() {
    if (countryAndArea.currentSelectedCountry > 0) {
      var allAreasCheckBox = document.getElementById('all-areas-' + countryAndArea.currentSelectedCountry);
      allAreasCheckBox.checked = true;
    }
  },

  updateAllAreasCheckBox: function(countryId) {
    var allAreasCheckBox = document.getElementById('all-areas-' + countryAndArea.currentSelectedCountry);
    var areaCheckBoxes = allAreasCheckBox.parentNode.getElementsByTagName('input');
    var checkedareaCheckBoxes = 0;

    // Count the number of checked areas
    for (var i = 1; i < areaCheckBoxes.length; i++) {
      if (areaCheckBoxes[i].checked == true)
        checkedareaCheckBoxes++;
    }

    // allAreasCheckBox is checked if no areaCheckBoxes are checked
    if (checkedareaCheckBoxes == 0)
      allAreasCheckBox.checked = true;

    // allAreasCheckBox is unchecked if there are any areaCheckBoxes checked
    else if (checkedareaCheckBoxes > 0)
      allAreasCheckBox.checked = false;
  },

  updateAllAreasCountriesCheckBox: function(element) {
    var countryId = element.id.replace('carea-', '').split('-')[0];
    var allAreas = document.getElementById('table-areas-' + countryId);
    var allAreasCheckBox = document.getElementById('all-careas-' + countryId);
    var areaCheckBoxes = allAreas.getElementsByTagName('input');
    var checkedareaCheckBoxes = 0;

    // Count the number of checked areas
    for (var i = 1; i < areaCheckBoxes.length; i++) {
      if (areaCheckBoxes[i].checked == true)
        checkedareaCheckBoxes++;
    }

    // allAreasCheckBox is unchecked if there are any areaCheckBoxes checked
    if (checkedareaCheckBoxes > 0) allAreasCheckBox.checked = false;
  },

  updateSummary: function() {
    // Update the summary text of the country-and-area searchsection
    var el = document.getElementById("countryandarea-summary");
    if (el) {
      var sel = document.getElementById("selCountry");
      var selectedCountry = sel.options[sel.selectedIndex].innerHTML; // option value
      var countryId = sel.options[sel.selectedIndex].value;

      if (selectedCountry.indexOf('(') > 0) {
        selectedCountry = selectedCountry.substr(0, selectedCountry.indexOf('(') - 1);
      }

      var summary = selectedCountry;
      // all areas?
      var allAreasSel = document.getElementById("all-areas-" + countryId);
      if (allAreasSel && !allAreasSel.checked) { // all areas does exist but is not checked
        // search all areas
        var total = 0;
        var checked = 0;
        var areanames = "";
        var children = allAreasSel.parentNode.getElementsByTagName("input");
        for (var i = 0; i < children.length; i++) {
          var child = children.item(i);
          if (child.type == "checkbox" && child != allAreasSel && child.id.indexOf("area-") == 0) {
            total++;
            if (child.checked) {
              checked++;
              var areaNameLabel = getElementsByTagNameAttributeValue(allAreasSel.parentNode, "label", "for", child.id)[0];
              var areaName = areaNameLabel.innerHTML;
              if (areaName.toLowerCase().indexOf('<span') > 0) {
                areaName = areaName.substr(0, areaName.toLowerCase().indexOf('<span') - 1);
              }

              areanames += areaName + ", ";
            }
          }
        }

        if (checked < total && checked > 0) {
          areanames = areanames.substring(0, areanames.length - 2);
          var areanameSummary = "";

          if ((summary + " (" + areanames + ")").length > 60) {
            areanamesArr = areanames.split(", ");
            var counter = 0;
            while ((summary + " (" + areanameSummary + areanamesArr[counter]).length <= 60 && counter <= areanamesArr.length - 1) {
              areanameSummary += areanamesArr[counter] + ", ";
              counter++;
            }
            areanameSummary = areanameSummary.substring(0, areanameSummary.length - 2) + "...";
          }
          else {
            areanameSummary = areanames;
          }

          if (areanameSummary.length > 0)
            summary += " (" + areanameSummary + ")";
        }
      }

      var allCountries = document.getElementById("allCountries");
      if (allCountries) {
        var tmpSummary = '';
        var children = allCountries.getElementsByTagName("input");
        var curCountry = '';
        var newCountry = true;
        var newArea = true;
        var areaNameLabel = null;
        for (var i = 0; i < children.length; i++) {
          var child = children.item(i);
          if (child.id.indexOf('all-careas-') == 0) {
            newArea = true;
            areaNameLabel = getElementsByTagNameAttributeValue(child.parentNode, "label", "for", child.id)[0];
            curCountry = areaNameLabel.innerHTML.split(' ')[1];
            if (child.checked == true) {
              newCountry = false;
              if (tmpSummary == '') tmpSummary += curCountry;
              else tmpSummary += ', ' + curCountry;
            }
            else {
              newCountry = true;
            }
          }
          else if (child.checked == true) {
            if (newCountry) {
              newCountry = false;
              if (tmpSummary == '') tmpSummary += curCountry;
              else tmpSummary += ', ' + curCountry;
            }
            if (newArea) {
              newArea = false;
              tmpSummary += ' (...)';
            }
          }
        }

        if (tmpSummary != '') {
          if (tmpSummary.length > 60) tmpSummary = tmpSummary.substring(0, 57) + "...";
          summary = tmpSummary;
        }
      }

      // Change the classname of the summary so a different layout is used, depending on the selection			
      elementId = "countryandarea-summary";

      toggleSummaryClass(summary, elementId);
      el.innerHTML = summary; // new contents or the initial " Geen voorkeur " 

      //Reset Map bounds info
      if (typeof (GoogleMapSearch) != "undefined") GoogleMapSearch.resetForFlash();
    }

    countryAndArea.createSubmitUrl();
  },


  /**
  * reset the current choices in areas and country
  */
  doReset: function(el) {
    var countryDDL = document.getElementById("selCountry");
    if (countryDDL != null) {
      // 1. Reset country dropdown
      countryDDL.selectedIndex = 0;

      // 2. Do the other cleanup work by changing to country -1
      countryAndArea.changeToCountry("-1");
    }
    // 3. Aantal resultaten updaten
    dataCollector.getTotals();
    ClickTracker.trackClick(new Click(resources.messages.clicktracker.ct_search_ca_reset));
  },

  doResetForMap: function() {
    var countryDDL = document.getElementById("selCountry");
    if (countryDDL != null) {
      if (countryAndArea.currentSelectedCountry == -1) return;

      countryDDL.selectedIndex = 0;

      // 2. Do the other cleanup work by changing to country -1
      countryAndArea.changeToCountryNew("-1", false);
    }
  },

  resetToDefault: function() {
    countryAndArea.changeToCountry("-1");
  },

  resetAllAreaCheckBoxes: function() {
    var selCountry = document.getElementById('selCountry');
    var selCountryId = selCountry.options[selCountry.selectedIndex].value;

    var allAreas = document.getElementById('all-areas-' + selCountryId);
    if (allAreas) {
      var areaElements = allAreas.parentNode.getElementsByTagName('input');
      areaElements[0].checked = true;
      for (i = 1; i < areaElements.length; i++)
        if (areaElements[i].checked == true)
        areaElements[i].checked = false;
    }
  },

  resetAllAreaCountriesCheckBoxes: function(element) {
    var selCountryId = element.id.substring(11);

    var allAreas = document.getElementById('table-areas-' + selCountryId);
    if (allAreas) {
      var areaElements = allAreas.getElementsByTagName('input');
      areaElements[0].checked = true;
      for (i = 1; i < areaElements.length; i++)
        if (areaElements[i].checked == true)
        areaElements[i].checked = false;
    }
  },

  doOk: function() {
    // Fired when the 'ok' button is clicked
    // 1. update the summary
    countryAndArea.updateSummary();
    // 2. Get new results
    dataCollector.getTotals();
  },

  createSubmitUrl: function() {
    // timeout already running?
    if (countryAndArea.waiting) {
      // clear!
      clearTimeout(countryAndArea.waiting);
      countryAndArea.waiting = null;
    }

    var areaIds = "";

    if (this.currentSelectedCountry > 1) {
      var allAreasSel = document.getElementById("all-areas-" + this.currentSelectedCountry);
      if (!allAreasSel.checked) {
        var children = allAreasSel.parentNode.getElementsByTagName("input");
        for (var i = 0; i < children.length; i++) {
          var child = children.item(i);
          if (child.type == "checkbox" && child != allAreasSel && child.id.indexOf("area-") == 0)
            if (child.checked)
            areaIds += child.getAttribute("name") + ", ";
        }
      }
    }

    var cmd = function() {
      xmlhttp.request("/Search/SubmitURL.aspx?countryId=" + countryAndArea.currentSelectedCountry + "&areaIds=" + areaIds, null, true, "countryAndArea.processSubmit", false);
    }

    countryAndArea.waiting = setTimeout(cmd, 1000);
  },
  processSubmit: function() {
    if (xmlhttp.req["countryAndArea.processSubmit"].readyState == 4) {
      if (xmlhttp.req["countryAndArea.processSubmit"].status == 200) {
        var submitUrl = xmlhttp.req["countryAndArea.processSubmit"].responseText;
        if (submitUrl.indexOf(" ") != -1) alert("createSubmitUrl:\n\n" + submitUrl);
        else if (document.getElementById("search-full-panel")) document.getElementById("search-full-panel").setAttribute("action", submitUrl);
      }
    }
  },
  doChangeCountriesCheckBox: function(evt, el) {
    if (!el) return;

    // Reset Flashmap
    countryAndArea.doResetForMap();
    countryAndArea.usedCountries = true;

    if (countryAndArea.isAllAreasCountriesCheckBox(el)) // CLICKED ON ALL AREAS
    {
      //1. If allareas is checked, reset/uncheck all (children) area checkboxes
      if (el.checked == true) countryAndArea.resetAllAreaCountriesCheckBoxes(el)
    }
    else // CLICKED ON AREA OR DESTINATION CHECKBOX
    {
      countryAndArea.updateAllAreasCountriesCheckBox(el);
    }

    //var regionId = el.id.replace('area-', '').split('-')[1];
    //ClickTracker.trackClick(new Click(resources.messages.clicktracker.ct_search_ca_area + regionId));

    // 4. Update summary
    countryAndArea.updateSummary();
  },
  doResetCountries: function(updateTotal, updateSummary) {
    if (!countryAndArea.usedCountries) return;
    var allCountries = document.getElementById("allCountries");
    if (allCountries) {
      var children = allCountries.getElementsByTagName("input");
      for (var i = 0; i < children.length; i++) {
        var child = children.item(i);
        if (child.checked == true) child.checked = false;
      }
    }

    countryAndArea.usedCountries = false;
    if (updateTotal) dataCollector.getTotals();
    if (updateSummary) countryAndArea.updateSummary();
  }
};

var countryAndArea = new CountryAndArea();