(function ($) {
  $(document).ready(function() {
    $('#navigation .menu ul').each(function() {
      $(this).append('<div class="submenu_footer"></div>');
    });

    $('#navigation .menu li').hover(
      function() {
        $(this).find('ul').addClass('menu-visible');
      },
      function() {
        $(this).find('ul').removeClass('menu-visible');
      }
    );
  });

  // Initialize harol object.
  Drupal.harol = Drupal.harol || {};

  // Automatically clears the default value of an input field and puts it back
  // if nothing is filled in. Also adds a class to the field for styling
  // purposes if needed.
  Drupal.harol.autoClear = function($selector, $default_text, $default_class) {
    $default_text = (typeof $default_text == 'undefined') ? $selector.val() : $default_text;
    $default_class = (typeof $default_class == 'undefined') ? 'default-input' : $default_class;

    // Set the default text and class.
    $selector.val($default_text);
    $selector.addClass($default_class);

    $selector
      // When the input becomes inactive and does not contain user-entered
      // content, set the default text again.
      .blur(function() {
        $this = $(this);
        if ($.trim($this.val()) == '') {
          $this.val($default_text);
          $this.addClass($default_class);
        }
      })
      // When focussing on the input, remove the default text and class.
      .focus(function() {
        $this = $(this);
        if ($this.val() == $default_text) {
          $this.val('');
          $this.removeClass($default_class);
        }
      });
  }

  // Attach behaviors related to site search.
  Drupal.behaviors.autoClear = {
    attach: function(context) {
      Drupal.harol.autoClear($('#search-block-form .form-text', context), Drupal.t('Search...'));
      if ($('#edit-c-p', context).hasClass('default')) {
        Drupal.harol.autoClear($('#edit-c-p', context));
      }
    }
  }

  /**
   * Behavior that takes care of the back functionality on a dealer detail.
   * This way a visitor can go back to the dealerlist without refreshing the
   * page.
   */
  Drupal.behaviors.dealerlist = {
    attach: function(context) {
      if ($('.view-dealer-locator', context).length) {
        if (getParameterByName('circle_op')) {
          if (!getParameterByName('c[value]') && $('.view-dealer-locator .view-display-id-attachment_1 .view-content').length) {
            $showMore = '<div id="show-more">' + Drupal.t('Do you wish to expand your search area? Click here.') + '</div>';
            $('.view-display-id-attachment_2').html($showMore);
            $('#show-more').click(function() {
              window.location = updateQueryStringParameter(window.location.toString(), 'c[value]', '10');
            });
          }
        }
      }

      // If there is a dealer detail loaded, hide the lists and add a back link.
      if ($('.view-dealer-locator #dealer-detail').text()) {
        // Hide both dealer lists.
        $('.view-dealer-locator .attachment-after .view-content').hide();

        // Add a back link.
        $('.view-dealer-locator #dealer-detail').prepend('<div class="go-back-link"><a href="#" title="' + Drupal.t('Go back to the overview page') + '">' + Drupal.t('Go back') + '</a></div>');

        // Set the action of the back link.
        $('.view-dealer-locator #dealer-detail .go-back-link a').click(function() {
          // Remove the dealer detail and show the list again.
          $('.view-dealer-locator #dealer-detail').html('');
          $('.view-dealer-locator .attachment-after .view-content').show();
          return false;
        });
      }
    }
  }

  /**
   * Behavior that takes care of the back functionality on a foreign dealer
   * detail. This way a visitor can go back to the dealerlist without refreshing
   * the page.
   */
  Drupal.behaviors.dealerlistforeign = {
    attach: function(context) {
      // If there is a dealer detail loaded, hide the lists and add a back link.
      if ($('.view-dealer-locator-foreign #dealer-detail').text()) {
        // Hide both dealer lists.
        $('.view-dealer-locator-foreign > .view-content').hide();
        $('.view-dealer-locator-foreign .attachment-after .view-content').hide();

        // Add a back link.
        $('.view-dealer-locator-foreign #dealer-detail').prepend('<div class="go-back-link"><a href="#" title="' + Drupal.t('Go back to the overview page') + '" id="go-back-foreign">' + Drupal.t('Go back') + '</a></div>');

        // Set the action of the back link.
        $('a#go-back-foreign').click(function() {
          // Remove the dealer detail and show the list again.
          $('.view-dealer-locator-foreign #dealer-detail').html('');
          $('.view-dealer-locator-foreign > .view-content').show();
          $('.view-dealer-locator-foreign .attachment-after .view-content').show();
          return false;
        });
      }
    }
  }

  Drupal.behaviors.replaceFilters = {
    attach: function(context) {
      var parents = {
        // Filters on the products page.
        0: '#edit-pproduct-wrapper',
        1: '#edit-plocation-wrapper',
        2: '#edit-paudience-wrapper',
        // Province filter on the dealer locator The Netherlands.
        3: '#edit-field-dealer-province-nl-tid-i18n-wrapper',
        // Province filter on the dealer locator France.
        4: '#edit-field-dealer-province-fr-tid-i18n-wrapper',
        // Province filter on the dealer locator Germany.
        5: '#edit-field-dealer-province-de-tid-i18n-wrapper'
      }
      // Store the keys for the edaler locator filters in an array.
      var dealer_locator_keys = [3, 4, 5];

      $.each(parents, function(key, parent) {
        $(parent).once(function() {
          // Add a class to the label.
          $(parent + ' label').addClass('filterlinks-label');
          // Hide the option select form elements.
          $(parent + ' select').hide();
          // Hide the submit button.
          $('#edit-submit-product-overview').hide();

          // Recreate all options
          options = '';
          if ($(parent + ' select').size() == 1) {
            // Loop through all options.
            $(parent + ' select option').each(function($index) {
              if ($(this).text() != '- Any -') {
                // Check if there is an option selected.
                selected = '';
                hrefvalue = $(this).val();
                if ($(this).attr('selected')) {
                  selected = 'selected';
                  // If not a dealer locator filter, change clicked link href to
                  // 'All', so choice can be unchecked.
                  if (!inArray(key, dealer_locator_keys)) {
                    hrefvalue = 'All';
                  }
                }
                // Create the option in a link.
                options += '<a href="' + hrefvalue + '" class="tax-select tax-filter-class-' + $(this).val() + ' ' + selected + '" rel="' + $(this).val() + '">' + $(this).text() + '</a>';
              }
            });
          }

          // Add option links in html
          html = '<div class="filterlinks tax-filters">' + options + '</div>';
          $(parent).append(html);

          // Add click functions to the option links.
          $(parent + ' .filterlinks a.tax-select').click(function(event) {
            // Prevent following the link.
            event.preventDefault();

            // Check if the clicked link has already the class 'selected'.
            if($(this).hasClass('selected')) { // Yes it has => unclick
              // Remove class "selected" in all links.
              $(parent + ' .filterlinks a').removeClass('selected');
              // Change the select and force a refresh.
              $(parent + ' select').val($(this).attr('href'));
              // Change href value to the rel value for all links.
              $(parent + ' .filterlinks a.tax-select').each(function(index){
                $(this).attr('href', $(this).attr('rel'));
              });
            }
            else { // No it hasn't => click
              // Remove class "selected" in all links.
              $(parent + ' .filterlinks a').removeClass('selected');
              // Add class "selected" to the clicked link.
              $(this).addClass('selected');
              // Change the select and force a refresh.
              $(parent + ' select').val($(this).attr('href'));
              // Change href value to the rel value for all links.
              $(parent + ' .filterlinks a.tax-select').each(function(index){
                $(this).attr('href', $(this).attr('rel'));
              });
              // If not a dealer locator filter, change clicked link href to
              // 'All', so choice can be unchecked.
              if (!inArray(key, dealer_locator_keys)) {
                $(this).attr('href', 'All');
              }
            }
            // Click the apply button.
            // Products page and dealer locator page both have 'submit', each
            // has its own submit button. Key for dealer locator is '3'
            if (inArray(key, dealer_locator_keys)) {
              $('#edit-submit-dealer-locator-foreign').click();
              // Scrol down the page, because the results load with ajax and the
              // user cannot see the results below the map on smaller screens.
              $(window).scrollTop(700);
            }
            else {
              $('#edit-submit-product-overview').click();
            }
          });
        });
      });
    }
  };

  Drupal.behaviors.equalHeight = {
    attach: function(context) {
      equalHeight(".view-homepage-blocks td .views-field");
      equalHeight(".view-homepage-blocks td .homepage_block_content");
    }
  };

  function equalHeight(group) {
    var tallest = 0;
    $(group).each(function() {
      var thisHeight = $(this).height();
      if(thisHeight > tallest) {
        tallest = thisHeight;
      }
    });
    $(group).height(tallest);
  }

  function inArray(needle, haystack) {
    var length = haystack.length;
    for(var i = 0; i < length; i++) {
      if(haystack[i] == needle) return true;
    }
    return false;
  }

})(jQuery);

/*
 * Get a querystring parameter.
 */
function getParameterByName(name) {
  name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
  var regexS = "[\\?&]" + name + "=([^&#]*)",
      regex = new RegExp(regexS),
      results = regex.exec(window.location.href);

  if (results == null) {
    return "";
  }
  else {
    return decodeURIComponent(results[1].replace(/\+/g, " "));
  }
}

/*
 * Add a querystring parameter.
 */
function updateQueryStringParameter(a, k, v) {
  var re = new RegExp("([?|&])" + k + "=.*?(&|$)", "i"),
      separator = a.indexOf('?') !== -1 ? "&" : "?";

  if (a.match(re)) {
    return a.replace(re, '$1' + k + "=" + v + '$2');
  }
  else {
    return a + separator + k + "=" + v;
  }
};
(function($) {
  $(document).ready(function(){
    // Hide language list.
    var language_list = $('#block-locale-language .content ul');

    // Track that the mouse is hovering the language switcher.
    var mouseOverActiveElement = false;
    $(language_list).append('<div class="submenu_footer"></div>');
    language_list.hide();
    // Get active language.
    $('#block-locale-language .content ul li').each(function(key, element){
      if ($(element).find('a').hasClass('active')) {
        // Prepend this element in the content class div.
        $('#block-locale-language .content').prepend('<div class="active-language"><span class="active-language-left"></span><span class="active-language-middle">' + $(element).children('a').html() + '</span><span class="active-language-right"></span></div>');
      }
    });
    $('#block-locale-language .content').live('mouseenter', function(){
      mouseOverActiveElement = true;
    }).live('mouseleave', function(){
      mouseOverActiveElement = false;
    });
    // Bind click event to open the language switcher popup.
    $('.active-language').click(function(){
      if (language_list.is(':visible')) {
        language_list.hide();
      }
      else {
        language_list.show();
      }
    });
    // bind click event listener on the HTML to be able to close the language
    // switcher popup when clicking outside of it.
    $("html").click(function(){
      if (!mouseOverActiveElement) {
        language_list.hide();
      }
    });
  });
})(jQuery);
;

