﻿// Set constants
var _cstmEnrHomePromoImageSeconds = 4;


// Reset event tracker flag (don't want to track mouseenter/click events during initialization)
var _cstmEnrHomeEnableEventTracker = false;

//=========================================================================================
// Social Tabs on flash (Twitter and TagCloud)
//=========================================================================================
function _cstmEnrHome_initSocialTab() {
  // Check if the tweets tab is displayed
  if ($('#tab-tweets').parent().hasClass('active')) {

    // initialize scrollpane
    //$('#tab-tweets .scrollpane').jScrollPane();

    // Resume the twitter feed
    if (typeof tweetEnergizer === "object" && typeof tweetEnergizerBunny === "object") {
      tweetEnergizer.start();
      tweetEnergizerBunny.start();
    }
  }
  else {
    // Pause the twitter feed
    if (typeof tweetEnergizer === "object" && typeof tweetEnergizerBunny === "object") {
      tweetEnergizer.stop();
      tweetEnergizerBunny.stop();
    }
  }

  if ($('#tab-cloud').parent().hasClass('active')) {
    // initialize scrollpane
    $('#tab-cloud .scrollpane').jScrollPane();
  }
}


//=========================================================================================
// Promo/Program Strip 
//=========================================================================================

// Scroll carousel on hover
function _cstmEnrHome_initCarouselScroller(theButton) {
  var interval;
  $(theButton).hover(
    function () { interval = setInterval("$('" + theButton + "').click()", 600); $(theButton).click(); },
    function () { clearInterval(interval); }
  );
}

// When mouse hovers on carousel item, then display its title and caption in the #promocaption area
function _cstmEnrHome_setPromoMouseEnterHandler(item) {
  var trkLabel = "program";
  if ($(item).parents("div.carousel").attr("id") === "tabPromos") {
    trkLabel = "promo";
  }

  $(item).each(function () {
    try {
      // Check first if there's already a mouseenter handler
      var handler = $(this).data("events").mouseenter;

    } catch (ex) {
      // Set the mouseenter handler
      $(this).mouseenter(function () {

        // Hide previous caption
        $(this).siblings().removeClass('itemactive');
        $(this).removeClass('itemactive').addClass('itemactive');

        // Show the caption associated with the item
        $('#promocaption').hide();
        $('#promocaption').html("");
        $('#promocaption').html("<h4>" + $(this).find('span.title').html() + "</h4>" + $(this).find('div.caption').html());

        if (jQuery.support.opacity) {
          $('#promocaption').fadeIn();
        } else {
          $('#promocaption').show();
        }

        // Track events
        if (_cstmEnrHomeEnableEventTracker && typeof pageTracker === "object") {
          pageTracker._trackEvent("top_nav_hover", $(this).find("a.itemimage").attr("href"), trkLabel);
        }
      });
    }

  });
};


function _cstmEnrHome_setPromoClickHandler(item) {
  if (typeof pageTracker === "object") {
    var trkLabel = "program";
    if ($(item).parents("div.carousel").attr("id") === "tabPromos") {
      trkLabel = "promo";
    }

    // When promo/prog item is clicked, track it before continuing with the click
    $(item).find("a.itemimage img").each(function () {

      try {
        // Check first if there's already a click handler
        var handler = $(this).data("events").click;

      } catch (ex) {
        var lnk = $(this).parent();

        // Set the click handler
        $(this).click(function () {
          // Track click event
          pageTracker._trackEvent("exit", $(lnk).attr("href"), trkLabel);

          // Track page view
          //pageTracker._trackPageview("Home: " + $(lnk).find("span.title").html());
        });
      }
    });
  }
};


function _cstmEnrHome_promoCarousel_itemVisibleInCallback(carousel, item, idx, state) {
  _cstmEnrHome_setPromoMouseEnterHandler(item);
  _cstmEnrHome_setPromoClickHandler(item);
  $(item).mouseenter();
}


function _cstmEnrHome_selectFirstItemInActiveCarousel() {
  $($('#promos ul.tabs .selected a').attr('href') + ' .jcarouselstrip .jcarousel-item-1').mouseenter();
}

function _cstmEnrHome_resetPromoCarousel() {

  // Find active tab
  var activetab = $('#promos ul.tabs .selected a').attr('href');

  // Disable mouseenter event tracker during carousel load
  var save_cstmEnrHomeEnableEventTracker = _cstmEnrHomeEnableEventTracker;
  _cstmEnrHomeEnableEventTracker = false;

  if ($(activetab + " .jcarouselstrip").children().length > 3) {

    // Find carousel object for active tab
    var carousel = $(activetab + ' .jcarouselstrip').data('jcarousel');

    if (carousel == null) {
      _cstmEnrHome_initCarousel(activetab, _cstmEnrHome_promoCarousel_itemVisibleInCallback);
      carousel = $(activetab + ' .jcarouselstrip').data('jcarousel');
    }

    // Go to the first item in the carousel and trigger it to be the selected item
    carousel.scroll(1, false);
    _cstmEnrHome_selectFirstItemInActiveCarousel();

  } else {
    // Not enough items for a scroller.  Just set the mouseenter handler for items and select the first.
    _cstmEnrHome_setPromoMouseEnterHandler(activetab + " .jcarouselstrip li");
    $(activetab + " .jcarouselstrip > li:first").mouseenter();
  }

  _cstmEnrHome_setPromoClickHandler($(activetab + " .jcarouselstrip"));

  _cstmEnrHomeEnableEventTracker = save_cstmEnrHomeEnableEventTracker;


  // Track event for the tab click
  if (_cstmEnrHomeEnableEventTracker && typeof pageTracker === "object") {
    if (activetab === "#tabPromos") {
      pageTracker._trackEvent("top_nav", "promo", "tab");
    } else {
      pageTracker._trackEvent("top_nav", "program", "tab");
    }
  }
};

//=========================================================================================
// Product carousel 
//=========================================================================================
function _cstmEnrHome_TrackProductSubhead(prodlink) {
  if (prodlink != null) {
    $(prodlink).click(function () {
      var prodname = $(this).closest("div.rollovercontent").children("p:first").children("a").text();
      pageTracker._trackEvent("bottom_nav", prodname, $(this).text());
    });
  }
}

function _cstmEnrHome_prodCarousel_itemVisibleInCallback(carousel, item, idx, state) {
  try {
    var handler = $(item).data("events").mouseenter;
  } catch (ex) {
    $(item).mouseenter(function () {
      // Hide previous content 
      $(this).siblings().removeClass('itemactive');
      $(this).removeClass('itemactive').addClass('itemactive');

      // Show content associated with current item
      $('#prodContentDisplay').hide();
      $('#prodContentDisplay').html("");
      $('#prodContentDisplay').removeClass();
      $('#prodContentDisplay').html($(this).find('div.rollovercontent').html());
      $('#prodContentDisplay').addClass($(this).find('div.rollovercontent').attr('class'));
      if (jQuery.support.opacity) {
        $('#prodContentDisplay').fadeIn(300);
      } else {
        //$('#prodContentDisplay').fadeIn(300, function() {this.style.removeAttribute("filter");});
        $('#prodContentDisplay').show(0);
      }

      var pos = $(this).position().left + $(this).parent().position().left;
      if (pos < 300) {
        $('#prodContentDisplay').css({ 'left': '0', 'right': 'auto' });
      } else if (pos < 400) {
        $('#prodContentDisplay').css({ 'left': '32px', 'right': 'auto' });
      } else {
        $('#prodContentDisplay').css({ 'left': 'auto', 'right': '0' });
      };

      // Event tracking
      if (typeof pageTracker === "object") {
        var prodlink = $("#prodContentContainer div.rollovercontent > p:first > a");
        pageTracker._trackEvent("bottom_nav", $(prodlink).text(), "preview");

        // Track clicks on product popup main title
        $(prodlink).click(function () {
          pageTracker._trackEvent("bottom_nav", $(this).text(), "link");
        });

        // Track clicks on product popup subhead titles
        prodlink = $("#prodContentContainer div.rollovercontent > table.rolloverContentTable > tbody > tr > td:nth-child(2) > p:first > a");
        _cstmEnrHome_TrackProductSubhead(prodlink);

        prodlink = $("#prodContentContainer div.rollovercontent > table.rolloverContentTable > tbody > tr > td:nth-child(5) > p:first > a");
        _cstmEnrHome_TrackProductSubhead(prodlink);

        prodlink = $("#prodContentContainer div.rollovercontent > table.rolloverContentTable > tbody > tr > td:nth-child(8) > p:first > a");
        _cstmEnrHome_TrackProductSubhead(prodlink);
      }
    });
  }
};

function _cstmEnrHome_hideProdContentDisplay() {
  $('#productCarousel').find('.itemactive').removeClass('itemactive');
  $('#prodContentDisplay').hide();
  $('#prodContentDisplay').html("");
  $('#prodContentDisplay').removeClass();
};


//=========================================================================================
// Initialize carousel -- used for all carousels on the page
//=========================================================================================
function _cstmEnrHome_initCarousel(tab, itemVisibleInCallbackFunction) {
  var hidden = false;

  // If tab is hidden, then show it (otherwise jcarousel won't initialize properly).
  if ($(tab).css('display') === 'none') {
    $(tab).show();
    hidden = true;
  }

  // Initialize the carousel
  $(tab + ' .jcarouselstrip').jcarousel({
    wrap: 'circular',
    scroll: 1,
    itemVisibleInCallback: itemVisibleInCallbackFunction
  });

  if (hidden) {
    // Re-hide the tab
    $(tab).hide();
  }

  // Functions for prev/next scrollers
  _cstmEnrHome_initCarouselScroller(tab + " .jcarousel-next");
  _cstmEnrHome_initCarouselScroller(tab + " .jcarousel-prev");
}


//=========================================================================================
// Promo Strip Initial Image:
// Stay on for 4 seconds, fade out, and then fade back in after 4 seconds of inactivity. 
// Have inactivity timer that gets reset every time they click on something in the promo/program strip.  
// Maintain current position in the strip so won't have to search for it again if it fades.
//=========================================================================================

function _cstmEnrHome_showPromoInitialImage() {
  _cstmEnrHome_pickPromoInitialImage();
  $("#promoinitialimage").fadeIn(1000, _cstmEnrHome_setTimeoutForPromoInitialImage(true));
};

function _cstmEnrHome_hidePromoInitialImage(isReset) {
  if (isReset) {
    clearTimeout($("#promoinitialimage").data("timeOutID"));
    $("#promoinitialimage").hide();
  } else {
    $("#promoinitialimage").fadeOut(1000, _cstmEnrHome_setTimeoutForPromoInitialImage(false));
  }
};

function _cstmEnrHome_setTimeoutForPromoInitialImage(isVisible) {
  // Clear timers
  clearTimeout($("#promoinitialimage").data("timeOutID"));

  // Reset timer 
  var timeOutID = null;
  if (isVisible) {
    timeOutID = setTimeout("_cstmEnrHome_hidePromoInitialImage(false)", _cstmEnrHomePromoImageSeconds * 1000);
  } else {
    timeOutID = setTimeout(_cstmEnrHome_showPromoInitialImage, _cstmEnrHomePromoImageSeconds * 1000);
  };

  // Store timer handlers
  $("#promoinitialimage").data("timeOutID", timeOutID);
};

function _cstmEnrHome_pickPromoInitialImage() {
  // See Frank deRosa's answer from http://stackoverflow.com/questions/1764160/jquery-select-random-elements.
  // To get the outerHtml, see Volomike's answer from http://stackoverflow.com/questions/2419749/jquery-get-selected-elements-outer-html.
  var index = Math.floor(Math.random() * $("#promoinitialimagepool a").length);
  var promo = $("#promoinitialimagepool a:eq(" + index + ")").clone().wrap("<div></div>").parent().html();
  $("#promoinitialimage").html(promo);
};

//=========================================================================================
// The following initializations occur after page load 
//=========================================================================================
$(function () {

  // Initialize Twitter/TagCloud accordion tabs
  $('#socialaccordion ul.socialtab').qAccordion({
    activeClass: 'active'
    , speed: 'normal'
    , pageTracker: 'false'
    , tabcontent: 'div.tabcontent'
    , tablink: 'a.tablink'
    , onAfterClick: _cstmEnrHome_initSocialTab
  });

  // Initialize Promos/Programs tab strip
  $('#promos').qTabs({
    className: 'selected'
    , speed: 'slow'
    , contentClass: 'carousel'
    , tabList: '#promos ul.tabs'
    , onAfterActivate: _cstmEnrHome_resetPromoCarousel
  });


  // Promo and program carousels:  activate promo carousel; the program one will be initialized as needed when that tab is clicked.
  // (Initializing the program carousel here causes an error on Safari because of visibility issues.)
  _cstmEnrHome_resetPromoCarousel();

  // Hide the div containing images that will be used on #promoinitialimage
  $("#promoinitialimagepool").hide();

  // Show promo initial image, if any
  if ($("#promoinitialimage").find("img") != null) {

    _cstmEnrHome_showPromoInitialImage();  // show it immediately
    //_cstmEnrHome_setTimeoutForPromoInitialImage(true);

    // Disable timeout if mouseover the initial image (don't let it disappear if they're hovering over it)
    $("#promoinitialimage").hover(
      function () { clearTimeout($("#promoinitialimage").data("timeOutID")); },
      function () { _cstmEnrHome_setTimeoutForPromoInitialImage(true); }
    );

    // Reset timeout when mouse is on the rest of the promo strip
    $("#promoinitialimage").siblings().hover(
      function () { _cstmEnrHome_hidePromoInitialImage(true); },
      function () { _cstmEnrHome_setTimeoutForPromoInitialImage(false); }
    );
  };


  // Initialize the Product carousel
  _cstmEnrHome_initCarousel('#productCarousel', _cstmEnrHome_prodCarousel_itemVisibleInCallback);
  $('#productCarousel .jcarousel-next').click(function () { _cstmEnrHome_hideProdContentDisplay(); });
  $('#productCarousel .jcarousel-prev').click(function () { _cstmEnrHome_hideProdContentDisplay(); });
  $('#prodContentDisplay').mouseleave(function () { _cstmEnrHome_hideProdContentDisplay(); });
  $('#featureprod').mouseleave(function () { _cstmEnrHome_hideProdContentDisplay(); });


  // Adjust position of social popup for homepage
  $("#banner .sociallinks a").mouseenter(function () {
    var tmpClass = "homebannersocialpopup";
    if ($("#recallContainer").css("display") === "block") {
      tmpClass += " homebannersocialpopuplower";
    }
    $("#socialpopup").show().removeClass().addClass(tmpClass);
  });

  // Set event tracker flag after all initialization
  _cstmEnrHomeEnableEventTracker = true;
});

//=========================================================================================
// More Event Tracking
//=========================================================================================
$(function () {
  if (typeof pageTracker === "object") {

    // Track if tab on social accordion was clicked to expand (active)
    $("#socialaccordion .tablabel a.tablink").click(function () {
      if ($(this).parent().parent().hasClass('active')) {
        if ($(this).attr("href") === "#tab-cloud") {
          pageTracker._trackEvent("search", "wordcloud", "expand");
        } else {
          pageTracker._trackEvent("twitter", "expand", "");
        }
      }
    });

    // Track if term in tag cloud was clicked
    $("#socialaccordion #tab-cloud .scrollpane a").click(function () {
      pageTracker._trackEvent("search", "wordcloud", $(this).text());
    });

    // Track scrollers on product carousel
    $("#productCarousel .jcarousel-prev").mouseenter(function () {
      pageTracker._trackEvent("bottom_nav", "scroll_left", "");
    });
    $("#productCarousel .jcarousel-next").mouseenter(function () {
      pageTracker._trackEvent("bottom_nav", "scroll_right", "");
    });


    // Set tracking for promo initial image link click
    $("#promoinitialimage a").click(function () {
      pageTracker._trackEvent("exit", $(this).attr("href"), "promo_banner");
    });
  }
});
  

