/*
 ******************************************************************************
 ** Copyright BrightTALK Ltd, 2009.
 ** All Rights Reserved.
 ** $Id: bt.categories.js 22975 2010-11-18 17:09:41Z acairns $
 ******************************************************************************
 *
 * Attach behaviours for the categories menu.
 *
 * Depends:
 *   jquery.superfish
 *   jquery.corner
 *
 * @package Portal
 * @subpackage JavaScript
 */

jQuery(document).ready(function($) {

  var viewportwidth;
  var viewportheight;

  $(document).bind('updateViewPortSize', function () {
    // the more standards compliant browsers (mozilla/netscape/opera/IE7) use window.innerWidth and window.innerHeight
    if (typeof window.innerWidth != 'undefined')
    {
      viewportwidth = window.innerWidth,
      viewportheight = window.innerHeight
    }
    // IE6 in standards compliant mode (i.e. with a valid doctype as the first line in the document)
    else if (typeof document.documentElement != 'undefined'
      && typeof document.documentElement.clientWidth !=
      'undefined' && document.documentElement.clientWidth != 0)
    {
      viewportwidth = document.documentElement.clientWidth,
      viewportheight = document.documentElement.clientHeight
    }
    // older versions of IE
    else
    {
      viewportwidth = document.getElementsByTagName('body')[0].clientWidth,
      viewportheight = document.getElementsByTagName('body')[0].clientHeight
    }
  });
  $(document).trigger('updateViewPortSize');

  var categorySelector = $('#category-selector');
  var isHomePage = categorySelector.length === 0;
  var isIE6 = $.browser.msie && $.browser.version < 7;

  $("ul.sf-menu").superfish({
    onShow: function () {
      $(document).trigger('updateViewPortSize');
    var moveDistance = 0;
    var centerDistance = (Math.floor($(this).height()-30)/2);
    //if centered and still over move to bottom
    if ((Math.floor($(this).offset().top-centerDistance)+$(this).height()) > viewportheight) {
      moveDistance = $(this).height()-30;
      //center the sucker
    } else if (viewportheight < parseInt(($(this).height()+$(this).offset().top+10))) {
      moveDistance = centerDistance;
    }
      $(this).animate({
        'margin-top': '-'+moveDistance+'px'
      });
  },
    onBeforeShow: function () {
      $(this).css({
      'margin-top': '0'
    });
    },
    dropShadows: true,
    //animation: {width:'show'},   // slide-down effect without fade-in
    delay:     300              // 0.5 second delay on mouseout
  });

  // If IE6 don't use bgIframe as it can result in the word 'false' being added to the ul
  if (!isIE6) {
    $("ul.sf-menu").find('ul').bgIframe({opacity:true});
  }

  // disable nodes unless they are at the end of the tree path
  $("a.sf-with-ul").click(function() {
    return false;
  })

  $('sf-menu').css('z-index', 1000);
  $('#content').css('z-index', 0);

  /* fix z-index issue within menu, make the li's towards the bottom
   * be behind the ones above, so that the sub menus are always
   * over the lower top level items
   */
  var startZIndex = 50;
  $(".sf-menu > li").each(function(i) {
    $(this).css('z-index', startZIndex - i)
  });

  //toggle the event count items on the home page
  if (isHomePage) {
    $('.sf-menu > li, .sf-menu > ul > li').hover(
      function () {
      if ($(this).parent().hasClass('sf-menu')) {
        $(this).find('.entry-count:eq(0)').hide();
      }
    },function () {
      if ($(this).parent().hasClass('sf-menu')) {
        $(this).find('.entry-count:eq(0)').fadeIn('fast');
      }
    });
  }

  // listing page menu
  if (!isHomePage) {

    var categories = $('#categories');
    var triggers = $('#category-selector-trigger, #category-selector .title'); // also previously
    var isOverCategories = false;

    var hideCategories = function() {
      //change anim based on browser - due to opacity fade issues.
      if ($.browser.msie) {
        categories.slideUp();
      } else {
        categories.fadeOut();
      }
      categorySelector.removeClass('active');
      isOverCategories = false;
    };

    var showCategories = function() {
      categorySelector.addClass('active');
      // Set the position to be under the selector
      if (!this.setOffset) {
        // reset the left as on mouse over jquery gets it wrong for some reason
        var leftOffset = -80;
        $('#category-selector > *').each(function() {
          leftOffset += $(this).width();
        });
        categories.css('left', leftOffset + 'px');
        this.setOffset = true;
      }
      categories.show();
    };

    var hideIfNotOverCategories = function() {
      if (!isOverCategories) {
        hideCategories();
      }
    }
    var hideIfOverCategories = function() {
      if (isOverCategories) {
        hideCategories();
      }
    }
    var setIsOverCategories = function() {
      isOverCategories = true;
    }

    //handle open and close of the cat menu non homepage
    var timeoutVar;
    var timeoutDuration = (1000*30);

    $(triggers).click(function (event) {
      if (!categorySelector.hasClass('active')) {
        showCategories();
        timeoutVar = setTimeout(hideCategories,timeoutDuration);
      } else {
        hideCategories();
        clearTimeout(timeoutVar);
      }
    });
    $("body").click(function(event) {
      var thisTrig = event.target;
      var triggerString1 = 'category-selector-trigger';
      var triggerString2 = 'category-selector-title';
      if (categorySelector.hasClass('active') 
        && $(thisTrig).attr('id') != triggerString1 
        && $(thisTrig).attr('id') != triggerString2) {
        hideCategories();
        clearTimeout(timeoutVar);
      } 
    });
    
    //trigger the menu to fade out after entering submenu at all
    $('#categories .sf-menu ul li').bind('mouseenter',setIsOverCategories);
    $('#categories > .sf-menu').bind('mouseleave',hideIfOverCategories);

  }

  // Fix IE6 Styling
  // @todo probably move this to IE6.js or somethign

  if (isHomePage && isIE6) {
  $("#categories .sf-menu ul > li").hover(
    function () {
      $(this).parent().parent().css({ 'background-color': '#585858'});
    },function () {
      $(this).parent().parent().css({ 'background-color': 'transparent'});
    }
    );
  }

  if (!isHomePage && isIE6) {

    $("#categories").css({
      'background-color': '#FAFAFA',
      'padding': '0px',
      'margin': '0px',
      'top': '96px',
      'width': '188px',
      'border': 'solid 1px #CCC'
    });

    //global
    $("#categories .sf-menu, #categories .sf-menu ul, #categories .sf-menu ul li").css({
      'padding': '0px',
      'margin': '0px'
    });

  //top item
    $("#categories .sf-vertical li.horizontal_bars").css({
      'width': '180px'
    });

    //primary menu
    $(".sf-menu a.sf-with-ul").css({
      'background-image': 'url(/css/6/images/bulletblack.gif)',
      'background-position': '185px 10px',
      'background-repeat': 'no-repeat'
    });
    $("#categories .sfHover a").css({
      'background-image': 'url(/css/6/images/bulletgreen.gif)'
    });


    //submenu
    $("#categories .sf-menu ul").css({
      'background': '#FAFAFA',
      'top': '0px',
      'border': 'solid 1px #CCC',
      'margin-left': '-3px'
    });
    $("#categories .sf-menu ul li > a").css({
      'padding': '7px',
      'width': '256px'
    });
    $("#categories .sf-menu ul ").css({
      'width': '295px',
      'background': 'transparent url(/css/6/ie6-images/submenu_level_two_bg.jpg) no-repeat scroll'
    });

    $("#categories .sf-menu > li").hover(
      function () {
        $(this).css({ 'background-color': '#CCC'});
      },function () {
        $(this).css({ 'background-color': 'transparent'});
      }
    );

    $("#categories .sf-menu ul > li").hover(
      function () {
        $(this).css({ 'background-color': '#33CC33'});
        $(this).find('a').css({ 'color': '#FFF'});
      },function () {
        $(this).css({ 'background-color': '#FFF'});
        $(this).find('a').css({ 'color': '#000'});
      }
    );

   //end if ie6 special case
   }

 });
