$(document).ready(function() {
  $("ul#nav ul").show();

  $('ul#nav > li').each(function() {
    $(this).find('a:first').next().wrapAll(
      $('<div/>', {
        'class': 'sub'
      })
    );
  });

  $('ul#nav .sub').each(function() {
    $(this).find('> ul > li').unwrap();
    // Wrap any links that have sublinks in groups of 2.
    if($(this).find('ul').length) {
      $(this).find('> li:has(ul)').wrapInChunks('<ul class="column"/>', 2).appendTo($(this));
    }
    // Wrap stand-alone links in a single column.
    $(this).find('> li').wrapAll('<ul class="column"/>');

    $(this).find('.column:last').css({
     'border-right': 0,
     'margin-right': 0,
     'padding-right': 0
    });

    var width = 0;
    var innerWidth = 0;
    var outerWidth = 0;
    var additional = 20;
    var height = 0;

    $(this).find('.column').each(function() {
      height = $(this).height() > height ? $(this).height() : height;

      innerWidth = $(this).innerWidth();
      outerWidth = $(this).outerWidth(true);

      if(innerWidth > 1000 || outerWidth > 1000) {
        height = height + 60;
        innerWidth = innerWidth / 10;
        outerWidth = outerWidth / 10;
      }

      width = innerWidth + additional > width ? innerWidth + additional : width;
      outerWidth = outerWidth > width ? outerWidth : width;
    }).width(width).height(height);
    
    $(this).width(outerWidth * $(this).find('.column').length);
  });

  $("ul#nav .sub h2").each(function() {
    if($(this).children().length > 0) {
      $(this).children().css('display', 'block');
      $(this).css('border-bottom', 0);
    }
  });

  $('ul#nav .sub').hide();

  // Hide all select boxes (if there are any) before showing nav, IE6 revokes hover state on hides so wait for callback.
  if ($.browser.msie && $.browser.version.substr(0,1) < 7 && $("select").length) {
    $("ul#nav > li").hover(function() {
      var li = this;
      $("select").hide(0, function() {
        $(li).find(".sub").show().siblings("a:first").addClass('active')
      })
    }, function() {
      var li = this;
      $("select").show(0, function() {
        $(li).find(".sub").hide().siblings("a:first").removeClass('active')
      })
    })
  } else {
    // Saves a bit of processing for good browsers.
    $("ul#nav > li").hover(function() {
      $(this).find(".sub").show().siblings("a:first").addClass('active')
    }, function() {
      $(this).find(".sub").hide().siblings("a:first").removeClass('active')
    })
  }
  
  // For keyboard navigation.
  $("ul#nav > li > a").focus(function() {
    $("ul#nav").each(function() {
      $(this).find(".sub:visible").hide().siblings("a:first").removeClass('active');
    })

    $(this).addClass('active').parent().find(".sub").stop().fadeTo('fast', 100, function() {
      $(this).show();
    })
  })

  // Google Search Field Swap
  $("#home_search").each(function() {
    var search = this;
    $(this).find(".search_toggle .google").click(function() {
      $(this).parent().siblings().find("a").css('background-position', '0 0');
      $(this).css('background-position', '0 16px');
      $(search).find("form:not(.google_search)").hide();
      $(search).find(".google_search").show().find(".query").focus();
      return false;
    })
    $(this).find(".search_toggle .sconty").click(function() {
      $(this).parent().siblings().find("a").css('background-position', '0 0');
      $(this).css('background-position', '0 16px');
      $(search).find("form:not(.sconty_search)").hide();
      $(search).find(".sconty_search").show().find(".query").focus();
      return false;
    })
    $(this).find(".query:visible").live('change', function() {
      $(search).find(".query:hidden").val($(this).val());
    })
  })
  
  // Only show the first row of search filters, with an expand link.
  $('.filters').each(function() {
    $(this).find('.dropdowns').after($('<a/>', {'href': '#', 'class': 'filterToggle'}).text('+ filters'))

    $(this).find('.filter').unwrap()
    
    $(this).find('> .filter:last').wrap($('<ul/>', {'class': 'more'})).parent().hide()
    $(this).find('> .filter').wrap($('<ul/>'))

    $(this).find('.filterToggle').toggle(function() {
      $(this).siblings('.more').slideDown()
      $(this).text('- filters')
    }, function() {
      $(this).siblings('.more').slideUp()
      $(this).text('+ filters')
    })
  })

  $(window).load(function() {
    resize()
  });
  
  function applyFancybox() {
    $("a[rel=fancybox]").fancybox({
      'zoomOpacity'			: true,
      'overlayShow'			: true,
      'zoomSpeedIn'			: 500,
      'zoomSpeedOut'		: 500,
      'easingIn'				: 'easeOutBack',
      'easingOut'				: 'easeInBack',
      'transitionIn'    : 'elastic',
      'transitionOut'   : 'elastic',
      'centerOnScroll'  : 'true',
      'scrolling'       : 'yes'
    })
  }

  $("a.fancyajax").fancybox({
    'zoomOpacity'			: true,
    'overlayShow'			: true,
    'zoomSpeedIn'			: 500,
    'zoomSpeedOut'		: 500,
    'easingIn'				: 'easeOutBack',
    'easingOut'				: 'easeInBack',
    'transitionIn'    : 'elastic',
    'transitionOut'   : 'elastic',
    'centerOnScroll'  : 'true',
    'ajax'            : {}
  })

  applyFancybox()
})


$(window).resize(function() {resize()});

function resize() {
  var viewportWidth = window.innerWidth ? window.innerWidth : $(window).width();

  if (jQuery.browser.msie) {
    if(parseInt(jQuery.browser.version) == 7) {
      viewportWidth -= 3;
    }
  }

  $('ul#nav .sub').each(function() {
    $(this).css({
      'display': 'block',
      'left': ''
    })
    var offset = $(this).offset().left + $(this).outerWidth(true) + 10;

    if(offset > viewportWidth) {
      if ($.browser.msie && $.browser.version.substr(0,1)<7) {
        ie6offset = 30;
      } else {
        ie6offset = 0
      }
      $(this).css({
        'left': -(offset + 10 - viewportWidth) - ie6offset
      });
    }

    $(this).css({
      'display': 'none'
    })
  })
}

$.fn.wrapInChunks = function(html, chunkSize) {
  chunkSize = chunkSize || 1;
  var items = this.get(),
    rows = [],
    cur = rows[0] = $(html);
  while (items[0]) {
    if (rows[rows.length - 1].children().length === chunkSize) {
        cur = rows[rows.length] = $(html);
    }
    cur.append( items.shift() );
  }
  return this.pushStack(rows);
};