/*
	http://cbsides.com/javascript/cb.blog.js
*/
(function(blog) {
  var toTopOffset = 0,
      $toTop,
      $commentText,
      testToTop = function() {
        $toTop.toggleClass('persist', ($(window).scrollTop() >= (toTopOffset - 16)));
      };
  
  blog.init = function() {
    
      //  Dynamic right positioning of form / to-top link:
      $toTop = $('#to-top');
      toTopOffset = $toTop.offset().top;
      testToTop();
      $(window).scroll(testToTop);
      
      //  Emphasize comment form on focus
      $('#comment-form :input').focus(function() {
        $('#comment-form').addClass('active');
      });
      $('#comment-form :input').blur(function() {
        $('#comment-form').removeClass('active');
      });
      
      //  Clear comment help text on focus
      $commentText = $('#comment-text');
      if ($commentText.length) {
        $commentText.focus(function() {
          if (!this.getAttribute('pretext') && this.value.indexOf('Enter your comment...') === 0) {
            this.setAttribute('pretext', this.value);
            this.value = '';
          }
        });
        $commentText.blur(function() {
          if (this.getAttribute('pretext') && this.value === '') {
            this.value = this.getAttribute('pretext');
            this.setAttribute('pretext', '');
          }
        });
      }
      
      //  Focus form on error
      if ($('#comment-form > p.error').length > 0) {
        window.location.hash = '#new-comment';
        document.getElementById('comment-name').focus();
      }
      //  Focus form on "new comment" link
      $('#newComment').unbind('click').click(function() {
        document.getElementById('comment-name').focus();
        return false;
      });
      
      //  Wire up dynamic labels
      if (cb.label) {
        cb.label('.meta dd');
        cb.label('#paging-post-prev a,#paging-post-next a');
      }
      
      //  Expand code examples on hover
      $('pre').each(function() {
        
        var $this = $(this),
            codeWidth = this.scrollWidth,
            diff = codeWidth - $this.width();
        if (diff > 5) {
          $this.bind('mouseover', function() {
            $this.animate({
              width: codeWidth + 'px',
              marginLeft: -diff + 'px'
            }, 500);
          });
        }
         
      });
  };
  
  $(document).ready(blog.init);
})(cb.blog = cb.blog || {});
