(function($, undefined) {

  var $_GET = function(q, s) {
    s = s ? s : window.location.search;
    var re = new RegExp('&' + q + '(?:=([^&]*))?(?=&|$)', 'i');
    return (s=s.replace(/^\?/,'&').match(re)) ? (typeof s[1] == 'undefined' ? '' : decodeURIComponent(s[1])) : undefined;
  }

  Drupal.behaviors.searchForm = {
    attach: function(context, settings) {
      var $form = Drupal.behaviors.searchForm.$form = $(context).find('#views-exposed-form-search-page');
      var $field = Drupal.behaviors.searchForm.$field = $form.find('#edit-for');
      var $direct = Drupal.behaviors.searchForm.$direct = $('<select>').addClass('direct');

      var loadTerm = $_GET('for');
      $field.val(loadTerm);
      
      $direct.append($('<option>').attr('value', '/search').text('Entire Site'));
      $direct.append($('<option>').attr('value', '/search/recipes').text('Recipes'));
      $direct.append($('<option>').attr('value', '/search/products').text('Products'));
      $direct.append($('<option>').attr('value', '/search/news').text('News & Events'));

      if(window.location.href.match(/search\/recipes/)) $direct.val('/search/recipes');
      else if(window.location.href.match(/search\/products/)) $direct.val('/search/products');
      else if(window.location.href.match(/search\/news/)) $direct.val('/search/news');
      else $direct.val('/search');

      $field.after($direct);

      $direct.change(Drupal.behaviors.searchForm.direct);
    },
    
    direct: function(event) {
      var $form = Drupal.behaviors.searchForm.$form;
      $form.attr('action', Drupal.behaviors.searchForm.$direct.val());
      if(Drupal.behaviors.searchForm.$field.val()) {
        $form.submit();
      }
    },

  }

})(jQuery);
;

