/* Sorry about the mess.  It started out nice but things went downhill as requirements changed... */
$(function(){
  // Font replacement
  Cufon.replace('.brand');
  Cufon.replace('.brand-shadow', {textShadow: '#316134 2px 2px 2px'});

  image_cycle($('.header-switch'), 1000, 10000);

  // Ensure Scroll-bar is attached when window becomes smaller than the wrapper
  // (Hack to make sure the extra-wide header images don't trigger the scroll-bar)
  if ($(window).width() < 960) {
    $('html').css('overflow-x', 'auto');
    $('#header').css('overflow-x', 'hidden');
  }
  $(window).resize(function(){
    if ($(this).width() < 960) {
      $('html').css('overflow-x', 'auto');
      $('#header').css('overflow-x', 'hidden');
    }
    else {
      $('html').css('overflow-x', 'hidden');
      $('#header').css('overflow-x', 'visible');
    }
    return false;
  });

  // Primary Navigation
  $('.nav-0').parent('li').hover(
    // Hover on
    function(){
      var sub_nav = $(this).children('.sub-nav');
      display(sub_nav, true);

      // Set the width of the hover-tab on primary navigation
      var width = $(this).width() - 5;
      sub_nav.children('.a-wrapper').css('width', width);
      sub_nav.children('.a-wrapper').children('.slider').css('left', width);

      var a_width = get_sub_links_width(sub_nav);

      // Make the bottom of the primary nav hover-tab for elements with no children
      if (!sub_nav.children('ul').length) {
        set_sub_width(sub_nav, width);
      }
      // Set the width of the sub-nav
      else {
        set_sub_width(sub_nav, a_width + 30);
      }

      sub_nav.find('.sub-nav-divider').css('width', a_width + 10);

      return false;
    },
    // Hover off
    function(){
      var sub_nav = $(this).children('.sub-nav');
      display(sub_nav, false);

      return false;
    }
  );
  // Sub-nav
  $('.sub-nav ul li.nav-0-sec').hover(
    // Hover on
    function(){
      var sub_nav = $(this).parent().parent();
      var sub_nav_wrapper = $(this).children('.sub-nav-wrapper');
      var a_width = get_sub_links_width(sub_nav);

      display(sub_nav_wrapper, true);

      $(this).css('width', a_width + 100 );
      $(this).children('a').css('width', a_width );

      // Show the hover-over image
      var x_offset = a_width + 10;
      $(this).css('background', 'url("/media/img/navigation/sub-nav-hover-end.gif") ' + x_offset + 'px  center no-repeat');
      $(this).children('a').css('background', 'url("/media/img/navigation/sub-nav-hover.png") left center no-repeat');

      // Set dimensions
      var width = a_width;
      if (sub_nav_wrapper.children('.sub-nav-image').length)
	  width += 370;
      else
	  width += 285;

      set_sub_width(sub_nav, width);
      sub_nav_wrapper.css('left', a_width + 30);
      set_sub_height(sub_nav_wrapper, sub_nav);

      return false;
    },
    // Hover off
    function(e){
      var sub_nav = $(this).parent().parent();
      var sub_nav_wrapper = $(this).children('.sub-nav-wrapper');
      var a_width = get_sub_links_width(sub_nav);

      display(sub_nav_wrapper, false);

      $(this).css('background', 'none');
      $(this).children('a').css('background', 'none');
      $(this).css('width', 'auto');
      $(this).children('a').css('width', 'auto');

      // set dimensions
      set_sub_width(sub_nav, a_width + 30);
      set_sub_height(sub_nav_wrapper, sub_nav);

      // make sure the menu disappears when the mouse moves quickly away from it
      if (!in_element(e.pageX, e.pageY, sub_nav) && !in_element(e.pageX, e.pageY, sub_nav.parent()) )
        sub_nav.parent().trigger('mouseout');

      return false;
    }
  );
});

// Check if the x and y coordinates given are within a given (jquery) element's location
function in_element(x, y, jelement) {
  var ax = jelement.offset().left;
  var ay = jelement.offset().top;
  var bx = ax + jelement.width();
  var by = ay + jelement.height();

  return (ax <= x && x <= bx) && (ay <= y && y <= by);
}


// How to hide / show things
function display(jelement, show) {
    if (show)
      jelement.show();
    else
      jelement.hide();
}


function get_sub_links_width(sub_nav) {
  // Calculate the max width needed for the labels in the sub-nav
  // (by creating an array of widths and working out the max of that array)
  var a_width = Math.max.apply(Math, jQuery.map(sub_nav.find('ul li.nav-0-sec a.secondary'), function(x, i){ return $(x).width(); }));
  a_width = Math.max(60, a_width); // set a minimun value
  a_width += 5; // a bit of extra padding at the end of the arrow

  return a_width;
}

function set_sub_width(sub_nav, width) {
  var sub_width = Math.min(495, width); // maximum width (based on image size)
  sub_nav.css('width', sub_width + 5);
  sub_nav.children('.sub-nav-bottom').css('width', sub_width);
  sub_nav.children('.sub-nav-bottom').children('.slider').css('left', sub_width);
  sub_nav.find('.sub-nav-wrapper').css('width', sub_width - get_sub_links_width(sub_nav) - 45);
}

function set_sub_height(sub_nav_wrapper, sub_nav) {
  // Make sure we have a minimum height for the sub-nav-wrapper
  var ul_height = sub_nav_wrapper.parent().parent().height() + 5;
  var snw_height = Math.max(sub_nav_wrapper.children('.sub-nav-text').height(), sub_nav_wrapper.children('.sub-nav-image').height() + 10, ul_height);

  // Set the height
  sub_nav.css('height', snw_height + 20);
  sub_nav_wrapper.css('height', snw_height + 10);
}


// Cycle through a jquery set fading elements in and out
// using cookies for cross page consistency
function image_cycle(elms, speed, interval) {
  if ($.cookie('banner_index') == null)
    $.cookie('banner_index', 0, {path: '/'});

  var length = elms.length;
  var index = parseInt($.cookie('banner_index'));

  if (!index || index >= length)
    index = 0;

  // Display the first one
  $(elms[index]).show();

  // The intervalled event
  window.setInterval(
    function(){ 
      $(elms[index]).fadeOut(speed);

      if (index < length - 1)
        index++;
      else
        index = 0;

      $.cookie('banner_index', index, {path: '/'});

      $(elms[index]).fadeIn(speed);
    }
    , interval);
}



/**
 * Cookie plugin
 *
 * Copyright (c) 2006 Klaus Hartl (stilbuero.de)
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 *
 */

/**
 * Create a cookie with the given name and value and other optional parameters.
 *
 * @example $.cookie('the_cookie', 'the_value');
 * @desc Set the value of a cookie.
 * @example $.cookie('the_cookie', 'the_value', { expires: 7, path: '/', domain: 'jquery.com', secure: true });
 * @desc Create a cookie with all available options.
 * @example $.cookie('the_cookie', 'the_value');
 * @desc Create a session cookie.
 * @example $.cookie('the_cookie', null);
 * @desc Delete a cookie by passing null as value. Keep in mind that you have to use the same path and domain
 *       used when the cookie was set.
 *
 * @param String name The name of the cookie.
 * @param String value The value of the cookie.
 * @param Object options An object literal containing key/value pairs to provide optional cookie attributes.
 * @option Number|Date expires Either an integer specifying the expiration date from now on in days or a Date object.
 *                             If a negative value is specified (e.g. a date in the past), the cookie will be deleted.
 *                             If set to null or omitted, the cookie will be a session cookie and will not be retained
 *                             when the the browser exits.
 * @option String path The value of the path atribute of the cookie (default: path of page that created the cookie).
 * @option String domain The value of the domain attribute of the cookie (default: domain of page that created the cookie).
 * @option Boolean secure If true, the secure attribute of the cookie will be set and the cookie transmission will
 *                        require a secure protocol (like HTTPS).
 * @type undefined
 *
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */

/**
 * Get the value of a cookie with the given name.
 *
 * @example $.cookie('the_cookie');
 * @desc Get the value of a cookie.
 *
 * @param String name The name of the cookie.
 * @return The value of the cookie.
 * @type String
 *
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */
jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
        }
        // CAUTION: Needed to parenthesize options.path and options.domain
        // in the following expressions, otherwise they evaluate to undefined
        // in the packed version for some reason...
        var path = options.path ? '; path=' + (options.path) : '';
        var domain = options.domain ? '; domain=' + (options.domain) : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else { // only name given, get cookie
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};
