// $Id:$

/**
 * @file
 * JavaScript functions for the tmsheader carousels.
 * 
 * Uses the JTools tabs, slideshow and flowplayser functions
 * @see http://flowplayer.org/tools/documentation/basics.html
 * @see http://flowplayer.org/documentation/configuration/
 */
(function ($) {

  // Attach our behavior to the drupal namespace
  Drupal.behaviors.tmsheader = {
    attach: function(context, settings) {
      // Assign the blurb settings to a var and pass along to our function
      var blurbs = settings.tmsheader.tmsheader_blurbs;
      tmsheader_go(blurbs);
     }
  };

  function tmsheader_go(blurbs) {

    // Set up some values for images
    // TODO: Make these dynamic
    var modulePath = '/sites/all/modules/_custom/tmsheader/';
    var closeImgSrc = modulePath + 'close_button.gif';

    // Get the original blurb for later
    var original_blurb = $("#blurb").html();

    // Create the slideshow
    $(".slidetabs")
      .tabs("#panes > div", {
        // Define the tab with a class so we can use the previous and next items in the list
        tabs: 'a.cnav-item',
        // enable "cross-fading" effect
        effect: 'fade',
        //fadeOutSpeed: "slow",
        // start from the beginning after the last tab
        rotate: true,
        // slideshow autoplay and click both fire this event
        onBeforeClick: function(e, index) {
          updateBlurb(index);
        }
      })
      // use the slideshow plugin. It accepts its own configuration
      .slideshow({
        autoplay: true,
        interval: 6000
	    });
    // end of slidetabs chain

    // Add listener to navigation to have the auto play stop once the user interacts with the controls
    $(".carousel-nav").click(function(){
      $(".slidetabs").data("slideshow").stop(); 
    });

    // Add event listener for case study learn more links
    $(".case-link").click(function() {
      // Pause the slideshow?
      $(".slidetabs").data("slideshow").stop();
      // Hide the page elements
      $('#blurb').hide(500);
      $('#carousel-headlines').hide(500);
      $('.carousel-nav').hide(500);
       // Show a loading animation
      $current = $(this);
      $current.css('background', '#ffffff');
      $current.html('<img src="/sites/all/themes/tms/images/loading.gif" />');
      $current.animate(
        {
          width: '960px',
          height: '310px' /* remember this has 120px padding */
        },
        500
      );
      // Create a slight delay so that the user can actually see the animation
      setTimeout(function(){
         location.href = $current.attr('href');
      }, 300);
      return false;
    });

    // Add event listeners for video play link	  
    $(".video-play").click(function() {
      // Pause the slideshow
      $(".slidetabs").data("slideshow").stop();
      // Animate and expand the canvas
      //DebugTmsHeader('in click event and this is', $(this));
      $current = $(this);
      $current.css('width', '960px');
      $current.css('margin-top', '20px');
      $current.css('height', '410px');
      $current.css('z-index', '130');

      // Add a close button
      $containerDiv = $(this).closest('div');
      $containerDiv.prepend('<div class="video-close"><a href="javascript:;" title="close"><img src="'+ closeImgSrc +'" alt="close" /></a></div>');

      // Hide the slideshow elements
      $('#blurb').hide(100);
      $('#carousel-headlines').hide(200);
      $('.carousel-nav').hide(200);

      // Set the listener for the close button
      $(".video-close").click(function(){
        $(".video-close").remove();
        $current.css('width', '640px');
        $current.css('height', '300px');
        $current.css('margin-top', '0px');
        $current.css('z-index', 'auto');
        // Unload the flowplayer
        $f().unload();
        // Show the slideshow elements
        $('#blurb').show(500);
        $('#carousel-headlines').show(500);
        $('.carousel-nav').show(500);
        return false;
      });
    });

    // Create the flowplayer object
    // /sites/all/modules/_custom/tmsheader/flowplayer.commercial-3.0.7.swf
    // http://releases.flowplayer.org/swf/flowplayer-3.2.7.swf
    $f(".video-play", {src: '/sites/all/modules/_custom/tmsheader/flowplayer-3.2.7.swf', wmode: 'transparent'}, {
      clip: {
        scaling: 'orig',
        onStart: function(c){
        } // attach event listener
      },
      canvas: {
        backgroundColor: '#000000'
        //backgroundImage: 'url(/sites/all/modules/_custom/tmsheader/carousel_headlines_bg.png)',
        //backgroundGradient: 'none'
      }
    });

    /**
     * Update the blurb after the slide has changed.
     * Called form the tabs() onBeforeClick event, 
     * both when a slide auto-advances and when 
     * someone click on the nav to advance the slide.
     * @param index The index number of the slide we are changing to.
     */
    function updateBlurb(index) {

      // If we have a new blurb to show in this spot, replace the blurb content div with it.
      if (blurbs[index]) {
	      $("#blurb-content").html(blurbs[index]);
      }
      // Otherwise, we'll need to drop back to the original blurb, but only if we didn't already.
      else if ($("#blurb-content").html() != original_blurb) {
        $("#blurb-content").html(original_blurb);
      }

      // Check for an empty blurb
      var newBlurbText = $("#blurb-content").text();
      newBlurbText = $.trim(newBlurbText);
      if (newBlurbText.length == 0) {
        // If doesn't already have the empty class
        if (!$("#blurb").hasClass('empty')){
          // Add the empty class
          $("#blurb").addClass('empty');
        } 
      }
      // Otherwise, if not empty...
      else {
        // but does have the empty class
        if ($("#blurb").hasClass('empty')) {
        	// Remove the class
          $("#blurb").removeClass('empty');
        }
      }

    } // end updateBlurb

    // Wrapper for debug messages
    function DebugTmsHeader(sMessage, oObject) {
      if (typeof console !== 'undefined' && 'log' in console) {
        console.log(sMessage, oObject);
      }
    }
    
  } // end tmsheader_go

})(jQuery);
;
// $Id:$

/**
 * @file
 * Gets a tumblr json object and displays in the "Voices" box
 * Added by tmsblocks.module.
 * 
 * Supports two types of display: links and full
 */
(function ($) {
	
    // Attach our behavior to the drupal namespace
    Drupal.behaviors.tmsblocks_tumblr = {
      attach: function(context, settings) {
        // If we have standard tumblr feed data, call our function for that
        if (settings.tmsblocks.tumblr) {
          tmsblocks_tumblrfeed.init("#" + settings.tmsblocks.tumblr.container, 5, settings.tmsblocks.tumblr.feed, false);
        }
        // If we have front news tumblr feed data, call our function for that
        if (settings.tmsblocks.tumblr_frontnews) {
          tmsblocks_tumblrfeed.init("#" + settings.tmsblocks.tumblr_frontnews.container, 5, settings.tmsblocks.tumblr_frontnews.feed, false);
        }
        // If we have front news full data, call our function for that
        if (settings.tmsblocks.tumblr_frontnews_full) {
          tmsblocks_tumblrfeed.init("#" + settings.tmsblocks.tumblr_frontnews_full.container, 5, settings.tmsblocks.tumblr_frontnews_full.feed, true);
        }
      }
    };
    
    /**
     * The main tmsblocks_tumblrfeed functional object
     */
    var tmsblocks_tumblrfeed = function(){
      var pub = {};
      
      // Number of characters to truncate a full post's body down to.
      var fullTruncLength = 400;
      // List of human-readable months for creating the post dates
      var months = [ "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" ];
      
      /**
       * Init function
       * 
       * @param {String} containerSelector - The selector to use when getting the container 
       */
      pub.init = function(containerSelector, limit, feed_url, isFull) {
        pub.debug('called tmsblocks_tumblrfeed.init', feed_url);
        // Sanity check for empty urls
        if (!feed_url) {
          pub.debug('feed_url was empty');
          return;
        }

        // Define our containers
        var $container = $(containerSelector);
        var $containerStatus = $(".feed-status", $container);

        // TODO: Move this image into a JS setting
        $containerStatus.html('<img src="/sites/all/themes/tms/images/loading.gif" alt="Loading..." />');
        var finalUrl = feed_url + '/api/read/json';
        // Make the call
        $.ajax({
          url: finalUrl,
          data: {},
          method: "GET",
          timeout: 9000, // Required to make FF catch errors
          cache: true,
          dataType: "jsonp",
          success: successCallback,
          error: errorCallback
        });
        
        /**
         * Success callback
         */
        function successCallback(json_data){
          $containerStatus.html("");
          // Build the entries
          for(var i = 0; i < limit; i++) {
            // Make sure we have a post (this catches for when there are less posts than the limit
            if (json_data.posts[i]) {
              var $newElem;
              if (!isFull) {
                // Build an item link
                var $containerUL = $('ul', $container);
                $newElem = buildItemLink(json_data, i);
              }
              else {
                // Build an full item display
                var $containerUL = $('.content', $container);
                $newElem = buildItemFull(json_data, i);
              }
              // Add it all to the container
              $newElem.appendTo($containerUL);
              // Add additional functionality if full
              /*
              if (isFull) {
                contentSliderNav.init();
              }
              */
            }
          } 
        }

        /**
         * Builds a standard link DOM element to then be appended to another DOM element
         * @param json_data The JSON data object
         * @param i The index of the item we are building
         * @returns A li DOM element
         */
        function buildItemLink(json_data, i) {
          var $liElem = $("<li />");
          $liElem.addClass(json_data.posts[i].type);
          // Add the title
          var $titleDiv = $("<div />").addClass('post-title');
          var title = json_data.posts[i].slug.replace( /\-/gi," ");
          // If this has not title, use the type as the title
          if (title == "") {
            title = json_data.posts[i].type;
          }
          $("<a />", {href : json_data.posts[i].url, target : "_blank", rel : "external follow", html :  title}).appendTo($titleDiv);
          $titleDiv.appendTo($liElem);
          // Add the date
          var date = new Date(json_data.posts[i].date);
          var dateHtml = 'Posted on '+ months[date.getMonth()] +" "+ date.getDate() +", "+ date.getFullYear();
          $("<div />", {html : dateHtml}).appendTo($liElem).addClass('post-date');
          return $liElem;
        }
        
        /**
         * Builds a full display DOM element to then be appended to another DOM element
         * @param json_data The JSON data object
         * @param i The index of the item we are building
         * @returns A DOM element
         */
        function buildItemFull(json_data, i) {
          /* THIS WAS FOR THE SLIDER CONTENT
          var $newElem = $("<div />").attr('id', 'post-'+ i).addClass('post');
          var $titleDiv = $("<div />").addClass('post-nav-wrapper').addClass(json_data.posts[i].type);
          var title = json_data.posts[i].slug.replace( /\-/gi," ");
          // If this has not title, use the type as the title
          if (title == "") {
            title = json_data.posts[i].type;
          }
          $("<div />", {html :  title}).addClass('title').appendTo($titleDiv);
          // Add the date to the title
          var date = new Date(json_data.posts[i].date);
          var dateHtml = 'Posted on '+ months[date.getMonth()] +" "+ date.getDate() +", "+ date.getFullYear();
          $("<div />", {html : dateHtml}).appendTo($titleDiv).addClass('post-date');
          $titleDiv.appendTo($newElem);
          // Add the content preview
          var bodyHtml = json_data.posts[i]['regular-body'];
          bodyHtml = bodyHtml.replace(/(<([^>]+)>)/ig,"");
          bodyHtml = bodyHtml.substring(0, fullTruncLength);
          bodyHtml = bodyHtml + '....<br />';
          var $bodyDiv = $("<div />").addClass('post-body');
          $bodyTitleElem = $("<h3 />").addClass('title');
          $("<a />", {href : json_data.posts[i].url, target : "_blank", rel : "external follow", html :  title}).appendTo($bodyTitleElem);
          $bodyTitleElem.appendTo($bodyDiv);
          $("<div />", {html : bodyHtml}).appendTo($bodyDiv);
          $("<a />", {href : json_data.posts[i].url, target : "_blank", rel : "external follow", html :  'read more'}).appendTo($bodyDiv);
          $bodyDiv.appendTo($newElem);
          */

          var $newElem = $("<div />").attr('id', 'post-'+ i).addClass('post').addClass(json_data.posts[i].type);
          
          var title = json_data.posts[i]["regular-title"];
          // If this has not title, use the type as the title
          if (title == "") {
            title = json_data.posts[i].type;
          }
          //$("<div />", {html :  title}).addClass('title').appendTo($newElem);
          $titleElem = $("<h3 />").addClass('title');
          $("<a />", {href : json_data.posts[i].url, target : "_blank", rel : "external follow", html :  title}).appendTo($titleElem);
          $titleElem.appendTo($newElem);
          // Add the date
          var date = new Date(json_data.posts[i].date);
          var dateHtml = 'Posted on '+ months[date.getMonth()] +" "+ date.getDate() +", "+ date.getFullYear();
          $("<div />", {html : dateHtml}).addClass('post-date').appendTo($newElem);
          // Add the content preview
          var bodyHtml = json_data.posts[i]['regular-body'];
          bodyHtml = bodyHtml.replace(/(<([^>]+)>)/ig,"");
          bodyHtml = bodyHtml.substring(0, fullTruncLength);
          bodyHtml = bodyHtml + '....<br />';
          var $bodyDiv = $("<div />").addClass('post-body');
          $("<div />", {html : bodyHtml}).appendTo($bodyDiv);
          $("<a />", {href : json_data.posts[i].url, target : "_blank", rel : "external follow", html :  'read more'}).appendTo($bodyDiv);
          $bodyDiv.appendTo($newElem);
          
          // Return our new element
          return $newElem;
        }
        
        /**
         * Error callback
         */
        function errorCallback(data){
          $containerStatus.html('<p>Tumblr feed could not be loaded. Please <a id="tmsblocks-tumblr-refresh" href="javascript:;">try again</a>.</p><br /><br />');
          $("#tmsblocks-tumblr-refresh").click(function(){
            pub.init(containerSelector, limit, feed_url); 
          });
        }
      
      }; // end init

      /**
       * Debug wrapper
       */
      pub.debug = function(sMessage, oObject) {
        if (typeof console !== 'undefined' && 'log' in console) {
          console.log(sMessage, oObject);
        }
      };
      
      return pub;
    }();


    /**
     * Add the slider nav behaviors
     */
    var contentSliderNav = function() {
      var pub = {};
      
      var blockId = 'block-tmsblocks-tmsblocks-tumblr-frontnews-full';
      var blockIdSelector = '#'+ blockId;
      
      var contentType = 'post';
      var displayId = contentType +'-body-display';
      var displayIdSelector = '#'+ displayId;
      
      pub.init = function() {
        // Hide all news-body divs
        $(".post-body").hide();
        
        // Create our div to display cloned news-body divs
        var $blockParentDiv = $(blockIdSelector +" .content:first");
        $blockParentDiv.prepend('<div id="'+ displayId +'" class="'+ contentType +'-body" style="float: right; margin: 0"></div>');
        
        // Expand any that match the hash
        var locHash = location.hash;
        if (locHash.indexOf('#'+ contentType +'-') > -1) {
          newsDisplay.showBody(locHash);
        }
        // If we don't have a good looking hash, pick the first
        else {
          var firstId = $("."+ contentType +":first").attr('id');
          if (firstId.indexOf(contentType +'-') > -1) {
            firstId = '#' + firstId;
            pub.showBody(firstId);
          }
        }
        
        pub.setListeners();
      }
      
      /**
       * 
       */
      pub.showBody = function(locHash) {
        var $activeNodeDiv = $(locHash);
        var $realBodyDiv = $("."+ contentType +"-body", $activeNodeDiv);
        var $bodyDisplayDiv = $(displayIdSelector);
        // Copy the content of the div we want into the display div
        var bodyContent = $realBodyDiv.html();
        $bodyDisplayDiv.html(bodyContent);
        // Set focus to the display div
        $("#main-wrapper").focus();
        // Update the class on the selected nav div
        $("."+ contentType +"-nav-wrapper").removeClass('selected-nav');
        var $selectedNavDiv = $("."+ contentType +"-nav-wrapper", $activeNodeDiv);
        $selectedNavDiv.addClass('selected-nav');
      };
      
      /**
       * Set listeners
       */
      pub.setListeners = function() {
        var $navWrappers = $("."+ contentType +"-nav-wrapper");
        $navWrappers.click(pub.handleClick);
        $navWrappers.hover(function(){
            $(this).css('cursor','pointer');
        });
      };
      
      pub.handleClick = function(e) {
        // Get the node id and build a hash to use
        var nodeDivId = $(this).closest('.'+ contentType).attr('id');
        if (nodeDivId.indexOf(contentType +'-') > -1) {
          nodeDivId = '#' + nodeDivId;
          pub.showBody(nodeDivId);
        }
        return false;       
      }
      
      return pub;
    }(); // End slider nav behaviors
    
})(jQuery);
;
(function ($) {

$(document).ready(function() {

  // Accepts a string; returns the string with regex metacharacters escaped. The returned string
  // can safely be used at any point within a regex to match the provided literal string. Escaped
  // characters are [ ] { } ( ) * + ? - . , \ ^ $ # and whitespace. The character | is excluded
  // in this function as it's used to separate the domains names.
  RegExp.escapeDomains = function(text) {
    return (text) ? text.replace(/[-[\]{}()*+?.,\\^$#\s]/g, "\\$&") : '';
  }

  // Attach onclick event to document only and catch clicks on all elements.
  $(document.body).click(function(event) {
    // Catch the closest surrounding link of a clicked element.
    $(event.target).closest("a,area").each(function() {

      var ga = Drupal.settings.googleanalytics;
      // Expression to check for absolute internal links.
      var isInternal = new RegExp("^(https?):\/\/" + window.location.host, "i");
      // Expression to check for special links like gotwo.module /go/* links.
      var isInternalSpecial = new RegExp("(\/go\/.*)$", "i");
      // Expression to check for download links.
      var isDownload = new RegExp("\\.(" + ga.trackDownloadExtensions + ")$", "i");
      // Expression to check for the sites cross domains.
      var isCrossDomain = new RegExp("^(https?|ftp|news|nntp|telnet|irc|ssh|sftp|webcal):\/\/.*(" + RegExp.escapeDomains(ga.trackCrossDomains) + ")", "i");

      // Is the clicked URL internal?
      if (isInternal.test(this.href)) {
        // Is download tracking activated and the file extension configured for download tracking?
        if (ga.trackDownload && isDownload.test(this.href)) {
          // Download link clicked.
          var extension = isDownload.exec(this.href);
          _gaq.push(["_trackEvent", "Downloads", extension[1].toUpperCase(), this.href.replace(isInternal, '')]);
        }
        else if (isInternalSpecial.test(this.href)) {
          // Keep the internal URL for Google Analytics website overlay intact.
          _gaq.push(["_trackPageview", this.href.replace(isInternal, '')]);
        }
      }
      else {
        if (ga.trackMailto && $(this).is("a[href^=mailto:],area[href^=mailto:]")) {
          // Mailto link clicked.
          _gaq.push(["_trackEvent", "Mails", "Click", this.href.substring(7)]);
        }
        else if (ga.trackOutbound && this.href) {
          if (ga.trackDomainMode == 2 && isCrossDomain.test(this.href)) {
            // Top-level cross domain clicked. document.location is handled by _link internally.
            _gaq.push(["_link", this.href]);
          }
          else if (ga.trackOutboundAsPageview) {
            // Track all external links as page views after URL cleanup.
            // Currently required, if click should be tracked as goal.
            _gaq.push(["_trackPageview", '/outbound/' + this.href.replace(/^(https?|ftp|news|nntp|telnet|irc|ssh|sftp|webcal):\/\//i, '').split('/').join('--')]);
          }
          else {
            // External link clicked.
            _gaq.push(["_trackEvent", "Outbound links", "Click", this.href]);
          }
        }
      }
    });
  });
});

})(jQuery);
;

