$(document).ready(function() {
  
  // main nav - reveal sub-items on hover (with delay)
  $('#nav-main').superfish({
    animation: {height: 'show'},
    delay: 400,
    speed: 300
  });
  
  //global search field
  var keyval = "Type keywords...";
  var $keywords = $('#keywords');
  $keywords.focus(function() {
    $(this).removeClass('default-text');
    if ($keywords.val() == keyval) {
      $keywords.val('');
    }
  }).blur(searchValue);
  
  
  function searchValue() {
    if ($.trim($keywords.val()) == '' || $keywords.val() == keyval) {
      $keywords.val(keyval).addClass('default-text');
    }
  }
  searchValue();
  $('div.right, div.left').each(function() {
    var $this = $(this),
      imgWidth = $this.find('img').outerWidth();
    $this.find('div.caption').width(imgWidth);
  });
  
  // add gradient to bottom of sidebar
  $('#content-wrapper').append('<div id="content-end"></div>');
  
  // apply fancy first letter
  $('#content:not(:has(#features)),div.message').find('p:first').fancyletter({
    bgImgPath: '/images/alpha/',
    bgImgExt: '.gif'
  });

  // add marker for external links 
  $('#content a').filter(function() {
    return !$('img', this).length && this.hostname !== location.hostname;
  }).css({
    background: 'url(/images/ui/bullet-decor-extlink.gif) no-repeat 100% 60%', paddingRight: '14px'
  });
  
});


// fancy first letter plugin
(function($) {
  $.fn.fancyletter = function(options) {

    return this.each(function() {
      var $this = $(this);
      var opts = $.extend({}, $.fn.fancyletter.defaults, options || {}, $.metadata ? $this.metadata() : $.meta ? $this.data() : {});
      var node = this;
      while (node.childNodes.length) {
    	  node = node.firstChild;
      }
      var text = node.nodeValue && node.nodeValue.replace(/^\s+/,'') || '';
      var firstLetter = text.slice(0,1);
      var re = new RegExp(opts.characters);
      
      if (re.test(firstLetter && text)) {
      	node.nodeValue = text.slice(1);
    	  var $span = $(['<span class="',
    	    opts.commonClass,
    	    ' ',
    	    opts.ltrClassPrefix,
          firstLetter.toLowerCase(),
          '">',
            firstLetter,
          '</span>']
    		.join('')
    		).prependTo(this);
        if (opts.bgImgPath !== null)
         $span.css('backgroundImage', 'url(' + opts.bgImgPath + firstLetter.toLowerCase() + opts.bgImgExt + ')');
        }
    });
  };  

  $.fn.fancyletter.defaults = {
    commonClass:      'fancy-letter', 
    ltrClassPrefix:   'ltr-',
    characters:       '[a-zA-Z]',
    bgImgPath:        null,
    bgImgExt:         null
  };

})(jQuery);
