(function ($) {
  /*
   * Extends jQuery, adding a new method that will close the parent colorbox,
   * if present.
   */
  $.fn.extend({
    closeColorBoxWithinIFrame: function(){
      if (parent != undefined) {
        if (parent.jQuery.fn.colorbox != undefined) {
          parent.jQuery.fn.colorbox.close();
        }
      }
    }
  });
  /**
   * On window load.
   */
  $(document).ready(function () {
    if ($('body').hasClass('front')) {
      Drupal.Bulletin.homepageSlideshow();
    }
    if ($('body').hasClass('page-features')) {
      // Make the entire featured item clickable instead of just the links.
      $('.view-features .attachment .group-footer').click(
        function(e) {
          location.href = $(this).find('a').attr('href');
        }
      ).addClass('clickable');
    }

    Drupal.Bulletin.searchAutoclear();
    Drupal.Bulletin.loginAndRegister();
    Drupal.Bulletin.reportAbuseBootstrap();

    Drupal.Bulletin.putOverlayOnLink($('a.login'));

    // If a user entered link is to long we want to shorten it. Css support is
    // not that good yet for different browsers.
    $('.node-type-question #content a, .node-type-classified #content a').each(function() {
      if ($(this).find('.comment-count').length == 0) {
        if ($(this).text().length > 50) {
          $(this).text($(this).text().substring(0, 47) + '...');
        }
      }
    });
  });

  Drupal.Bulletin = {};

  /**
   * Create the big slideshow on the homepage and sync it with the small one.
   */
  Drupal.Bulletin.homepageSlideshow = function() {
    // Used to prevent all browsers to trigger the jcarousel call on page load.
    var $bootstrap = true;
    $('.pane-slideshow-slideshow-big .view-content').cycle({
      timeout: 10000,
      fx: 'none',
      speed: 0,
      before: function() {
        if (!$bootstrap) {
          var small_carousel = $('.jcarousel-view--slideshow--slideshow-small').data('jcarousel');
          small_carousel.funcNext();
        }
        else {
          // Called once at bootstrap phase. Setting it to false will allow the
          // script to run as designed.
          $bootstrap = false;
        }
      }
    });
  }

  /**
   * Attach autoclear to search form
   */
  Drupal.Bulletin.searchAutoclear = function() {
    // Attach autoclear to search form and pass the class name for the default
    // value styling.
    $('#search-block-form .form-text').autoclear('search-default-value');
    $('#search-form .form-text').autoclear('search-default-value');
  }

  /**
   * Adds functionality for the login and register overlay.
   */
  Drupal.Bulletin.loginAndRegister = function() {
    // For which links the overlay should open.
    var $allowedPagesColorbox = ["register", "log in"];
    $('#block-system-user-menu .content a').each(function() {
      $test = $(this).text().toLowerCase();
      if (jQuery.inArray($test, $allowedPagesColorbox) >= 0) {
        Drupal.Bulletin.putOverlayOnLink($(this));
      }
    });

    // Links that are in overlay should open in the overlay.
    $('#overlay-wrapper a').each(function() {
      var $href = $(this).attr('href');
      $(this).attr('href', $href + '?overlay=true');
    });

    // Redirect on the succes page, this refreshes the parent page so the
    // colorbox closes and the user is logged in.
    if ($('#page-title').text().toLowerCase() == 'success') {
      setTimeout(
        function() {
          $(this).closeColorBoxWithinIFrame();
        },
        5000
      );
    }

    // We don't want this functionality from logintoboggan.
    Drupal.behaviors.unifiedLogin = null;
  }

  Drupal.Bulletin.reportAbuseBootstrap = function() {
    // Hide all unreport buttons except those that are in the views and on the classifieds pages.
    if ((!$('.page-reported-questions').size()) && (!$('body.page-reported-answers').size()) && (!$('.node-type-classified').size()) && !($('.page-user').size())) {
      if ($('.unflag-action').length) {
        $('.unflag-action').each(function(k, item){
          $(item).remove();
        });
      }
    }
    // Attach colorbox.
    if ($('.flag-link-confirm').length) {
      $('.flag-link-confirm').each(function(index, link){
        var href = $(link).attr('href');
        $(link).attr('href', href + '&overlay=true');
        $(link).colorbox({
          height: 550,
          iframe: true,
          onClosed: function() {
            location.reload(true);
          }
        })
      });

    }

    // Close the colorbox if the form has been canceled.
    if ($('#edit-cancel').length) {
      $('#edit-cancel').click(function(){
        $(this).closeColorBoxWithinIFrame();
      });
    }
  }

  Drupal.Bulletin.putOverlayOnLink = function($field) {
    $field.each(function() {
      // Add a query so the correct tpl is loaded.
      var $href = $(this).attr('href');
      $(this).attr('href', $href + '?overlay=true');
      // Use colorbox for these links
      $(this).colorbox({
        height: 575,
        iframe: true,
        onClosed: function() {
          location.reload(true);
        }
      });
    });
  };

  Drupal.behaviors.replaceFilters = {
    attach: function(context) {
      $parent = '#views-exposed-form-Events-overview-events';
      $($parent).once('timezone', function() {

        $($parent + ' label').hide();
        $($parent + ' select').hide();
        $($parent + ' #edit-submit-events').hide();

        // Recreate all options
        $options = '';
        if ($($parent + ' select').size() == 1) {
          $($parent + ' select option').each(function($index) {
            if ($(this).text() == '- Any -') {
              $seeAll = '<a href="' + $(this).val() + '" class="tax-filter-class-' + $(this).val() + '">See All</a>';
            }
            else {
              $options += '<a href="' + $(this).val() + '" class="tax-select tax-filter-class-' + $(this).val() + '">' + $(this).text() + '</a>';
            }
          });
        }

        $options += $seeAll;

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

        $($parent + ' .tax-filter-class-All').click(function(event) {
          event.preventDefault();
          $('#edit-field-events-time-value-1-value-datepicker-popup-0').val('');
          $($parent + ' .filterlinks a').each(function() {
            $(this).removeClass('selected');
          });
          // Change the select and force a refresh
          $a = $(this);
          $($parent + ' select').val($a.attr('href'));
          $($parent + ' select').change();
          $a.addClass('selected');
          $('#edit-submit-events').click();
        });

        // Add click functions
        $($parent + ' .filterlinks a.tax-select').click(function(event) {
          event.preventDefault();
          $($parent + ' .filterlinks a').each(function() {
            $(this).removeClass('selected');
          });
          // Change the select and force a refresh
          $a = $(this);
          $($parent + ' select').val($a.attr('href'));
          $($parent + ' select').change();
          $a.addClass('selected');
          $('#edit-submit-events').click();
        });

        // Add change function to the date filter
        $('#edit-field-events-time-value-1-value-datepicker-popup-0').change(function() {
          $('#edit-submit-events').click();
        });

      });
    }
  };

  Drupal.behaviors.replaceFiltersQandA = {
    attach: function(context) {
      // Add colorbox to header and footer links
      $('.view-id-questions .view-header a, .view-id-questions .view-footer a, .node-type-question .pane-custom a').each(function() {
        // Add a query so the correct tpl is loaded.
        var $href = $(this).attr('href');
        // When a link has a '#' we don't want to use the overlay
        if ($href.search("#") != 0) {
          $(this).attr('href', $href + '?overlay=true');
          // Use colorbox for these links
          $(this).colorbox({
            height: 550,
            iframe: true,
            onClosed: function() {
              location.reload(true);
            }
          });
        }
      });

      // Replace our form elements with normal links
      $('#views-exposed-form-questions-questions-overview').once('processed', function() {
        // Attach autoclear to search form
        $('.views-widget-filter-keys #edit-keys').autoclear('search-default-value');

        // Hide the sort order.
        $('.views-widget-sort-order').hide();

        // Replace the order by select.
        var $parent = '.views-widget-sort-by';
        $($parent + ' select').hide();

        // Recreate options
        $options = '';
        if ($($parent + ' select').length) {
          $($parent + ' select option').each(function() {
            if ($(this).attr('selected')) {
              $options += '<a href="' + $(this).val() + '" class="selected">' + $(this).text() + '</a>';
            }
            else {
              $options += '<a href="' + $(this).val() + '">' + $(this).text() + '</a>';
            }
          });
        }
        $html = '<div class="sort-by-links">' + $options + '</div>';
        $($parent).append($html);

        // Add click functions
        $($parent + ' .sort-by-links a').click(function(event) {
          event.preventDefault();

          $($parent + ' .sort-by-links a').each(function() {
            $(this).removeClass('selected');
          });
          // Change the select and force a refresh
          $a = $(this);
          $($parent + ' select').val($a.attr('href'));
          $a.addClass('selected');
          $($parent).parent().find('input:submit').click();
        });

        // Replace the category select.
        var $parent2 = '.views-widget-filter-tid';
        $($parent2 + ' .views-widget').hide();

        // Replace the category select.
        $options = '';
        if ($($parent2 + ' select').length) {
          $($parent2 + ' select option').each(function() {
            $text = $(this).text();
            $extra_class = '';
            if ($(this).val() == 'All') {
              $text = 'All categories';
              $extra_class = ' all-categories';
            }
            if ($(this).attr('selected')) {
              $options += '<a href="' + $(this).val() + '" class="selected' + $extra_class + '">' + $text + '</a>';
            }
            else {
              $options += '<a href="' + $(this).val() + '" class="' + $extra_class + '">' + $text + '</a>';
            }
          });
        }
        $html = '<div class="category-links">' + $options + '</div>';
        $($parent2).append($html);


        // Add click functions
        $($parent2 + ' .category-links a').click(function(event) {
          event.preventDefault();

          $($parent2 + ' .category-links a').each(function() {
            $(this).removeClass('selected');
          });

          // Change the title of the page with the category.
          $('#page-title').text(Drupal.t('Q&A') + ' - ' + $(this).text());
          $('title').text(Drupal.t('Q&A') + ' - ' + $(this).text() + ' | ' + Drupal.settings.site_name);

          // Change the select and force a refresh
          $a = $(this);
          $($parent2 + ' select').val($a.attr('href'));
          $a.addClass('selected');
          $($parent2).parent().find('input:submit').click();
        });
      });
    }
  };

  Drupal.behaviors.replaceFiltersClassified = {
    attach: function(context) {
      // Attach autoclear to search form
      $('#thebulletin-custom-search-block #edit-keys').autoclear('search-default-value');

      // Replace our form elements with normal links
      $('#views-exposed-form-classifieds-classifieds-overview').once('processed', function() {

        // Hide the sort order.
        $('.views-widget-sort-order').hide();

        // Replace the order by select.
        var $parent = '.views-widget-sort-by';
        $($parent + ' select').hide();

        // Recreate options
        $options = '';
        if ($($parent + ' select').length) {
          $($parent + ' select option').each(function() {
            if ($(this).attr('selected')) {
              $options += '<a href="' + $(this).val() + '" class="selected">' + $(this).text() + '</a>';
            }
            else {
              $options += '<a href="' + $(this).val() + '">' + $(this).text() + '</a>';
            }
          });
        }
        $html = '<div class="sort-by-links">' + $options + '</div>';
        $($parent).append($html);

        // Add click functions
        $($parent + ' .sort-by-links a').click(function(event) {
          event.preventDefault();

          $($parent + ' .sort-by-links a').each(function() {
            $(this).removeClass('selected');
          });
          // Change the select and force a refresh
          $a = $(this);
          $($parent + ' select').val($a.attr('href'));
          $a.addClass('selected');
          $($parent).parent().find('input:submit').click();
        });
      });
    }
  };

  Drupal.behaviors.scrollToTop = {
    attach: function(context) {
      // We scroll to top if user loads a new page with the pager.
      $('.page-classified .pager').once('at-top', function() {
        $(this).find('a').click(function() {
          // 195px is the height of the page-title.
          $(window).scrollTop(195);
        });
      });
    }
  };

})(jQuery);;
/**
 * Apply a helper value to text fields quickly &amp; easily.
 *
 * The easiest way to use is $('your-selector').autoclear(). All the defaults
 * in the settings object are used. For more advanced cases, and complete
 * reference, @see http://www.mattlunn.me.uk/projects/autoclear
 *
 * @author Matt Lunn
 * @version 7
 * @param  Object / String
 * @return Object jQuery
 * @see http://www.mattlunn.me.uk/projects/autoclear
 * @see README
 */
;(function(d){function k(a){return a===undefined||a===""}function g(a){return l.apply(a,p.call(arguments,1))}function m(a){a=d(a);a.val()===""&&g(a,"").trigger("other.autoclear");return a}function h(a){a=d(a);jQuery.trim(a.val())===""?a.trigger("default.autoclear"):a.trigger("other.autoclear");return a}var p=[].slice,l=jQuery.fn.val;jQuery.fn.autoclear=function(a){var c={defaultClass:"default",otherClass:"other",defaultValue:"",useDefaultOnReset:true,clearDefaultOnSubmit:true};if(arguments.length)switch(typeof a){case "string":c.defaultClass=a;break;case "object":c=jQuery.extend(c,a)}return this.bind({"default.autoclear":function(){var b=d(this).removeClass(c.otherClass).addClass(c.defaultClass);g(b,b.data("default.autoclear"))},"other.autoclear":function(){d(this).removeClass(c.defaultClass).addClass(c.otherClass)},"focus.autoclear blur.autoclear":function(b){(b.type==="focus"?m:h)(this)}}).each(function(){var b=d(this),n=b.closest("form"),i=jQuery.trim(g(b)),e=b.attr("title");if(k(e))e=i===""?c.defaultValue:i;b.data("default.autoclear",e);n.bind("reset.autoclear",function(j){var f=j.originalEvent;setTimeout(function(){if(!(f.defaultPrevented||f.returnValue===false||f.getPreventDefault&&f.getPreventDefault())){var o;o=c.useDefaultOnReset?"":b.attr("defaultValue");b.val(o)}},0)});if(c.useDefaultOnReset||k(jQuery.trim(b.attr("defaultValue"))))b.attr("defaultValue",e).val(i);c.clearDefaultOnSubmit&&n.bind("submit.autoclear",function(j){if(!j.isDefaultPrevented()){m(b);setTimeout(function(){h(b)},0)}});h(this)})};jQuery.fn.val=function(){var a=l.apply(this,arguments),c;if(typeof a==="string"){c=this.first().data("default.autoclear");if(c!==undefined&&a===c)a=""}else this.each(function(){var b=d(this);b.data("default.autoclear")!==undefined&&b.val()===""?b.trigger("default.autoclear"):b.trigger("other.autoclear")});return a}})(jQuery);;

