jQuery(document).ready(function($){
   // Fix background image flickering in IE
   try {
     document.execCommand('BackgroundImageCache', false, true);
   } catch(e) { }

   /* Special search behavior */
   var Search = {
     prompt: "Search", // default value - should get real value from markup
     init: function() { this.prompt = jQuery('#searchbox').focus(this.focus).blur(this.blur).val(); },
     focus: function() { if (this.value == Search.prompt) { this.value = ''; } },
     blur: function() { if (this.value.length == 0) { this.value = Search.prompt; } }
   };

   $(document).ready(function() {
     Search.init();
   });

   /* begin - Worldwide Flyout */
   var Worldwide = {
     init: function() {
         $('#Toolbar li.last').hover(this.mouseenter, this.mouseleave);
     },
      mouseenter: function() {
         $(this).children('a').addClass('over');
         $('#WorldwideFlyout').show();
      },
      mouseleave: function() {
         $(this).children('a').removeClass('over');
         $('#WorldwideFlyout').hide();
      }
   };
   $(function() { Worldwide.init(); });
   /* end - Worldwide */

   /* begin - Navigation Primary */
   var NavigationPrimary = {
     init: function() {
         var c = this;
         var n = $('#NavigationPrimary > ul');

         // Use bgiframe to fix dropdowns over selects if it's available.
         $.fn.bgiframe && $('li', n).bgiframe();

         // Mark parent elements so that we can style them with CSS
         $('> li', n).each(function() { c.markParents(this); });

      // Use the hoverintent plugin if it's available
      // if ($.fn.hoverIntent)
      //     {
      //   $('li', n).hoverIntent( {
      //     sensitivity: 1,
      //     over: this.mouseenter,
      //     out: this.mouseleave,
      //     timeout: 100
      //   });
      //     }
      // else
        $('li', n).hover(this.mouseenter, this.mouseleave);
     },
     markParents: function(li) {
       var c = this;
       if ($('> ul', li).size() > 0)
          $(li).addClass('parent').find('> a').addClass('parent').end().find('> ul li').each( function() { c.markParents(this); });
      },
      mouseenter: function() { $(this).addClass('over').children('a').addClass('over'); },
      mouseleave: function() { $(this).removeClass('over').children('a').removeClass('over'); }
   };
   $(function() { NavigationPrimary.init(); });
   /* end - Primary Navigation */

   var DD_belatedPNG;
   if (DD_belatedPNG) {
      DD_belatedPNG.fix('#WorldwideFlyout .channel, #WorldwideFlyout .footer');
      DD_belatedPNG.fix('#NavigationPrimary .channel, #NavigationPrimary ul ul.navCols');
      DD_belatedPNG.fix('#NavigationSecondary .flyout, #NavigationSecondary .flyout .content');
      DD_belatedPNG.fix('#Content .productIntro .productDesc .freeEval, #Content .productIntro .productDesc .freeEval a, a.pp_close');
      DD_belatedPNG.fix('#Content .featureBox .channel .content .button ul li, #Content .featureBox .channel .content .button a');
      DD_belatedPNG.fix('.tabbedColumnBlock ul.columns li.one .content, .tabbedColumnBlock ul.columns li.one, img, .tabContent ul.buttons a, .tabContent ul.buttons span');
      DD_belatedPNG.fix('.highlightBox .channel, p a.pdf, p a.video, .eventLogManagementBlock ul.columns li.one .content, #Banner ul.controls li.three a');
   }
   // Convert on-tabbed display into tabbed display and activate tabs
   $(document).ready(function() {
      var $tabs = $('div.tabs');
      if ($tabs.length == 0)
         return;

      var $tabnav = $tabs.find('ul.tabNav');
      if ($tabnav.length == 0) {
         $tabnav = $tabs.prepend('<ul class="tabNav selfClear"></ul>').find('> ul');
         $tabs	.find('> div')
            .each( function(i) {
               var id = this.id;
               var title = $(this).metadata().tabTitle;
               $tabnav.append('<li><a href="#' + id + '" class="noPopup"><span>' + title + '</span></a></li>');
            });
            // Need delay for browsers to get their DOM in order
            setTimeout(
               function() {
                  $tabs.tabs();

                  // Enable links to tabs to activate tab
                  $('a.tabLink').click(function() { // bind click event to link
                     $tabs.tabs('select', this.hash);
                     return false;
                  });

                  // Scroll back to top if there's a tab to select.
                  // Need to do this because we have a delay before tabs are built and browsers will
                  // scroll down to where the tab content was before the tab was built.
                  if (document.location.hash)
                     $.scrollTo(0);
               },
               500
            );
      }
   });



   function mycarousel_itemVisibleInCallback(carousel, item, i, state, evt)
   {
      // The index() method calculates the index from a
      // given index who is out of the actual item range.
      var idx = carousel.index(i, mycarousel_itemList.length);
      carousel.add(i, mycarousel_getItemHTML(mycarousel_itemList[idx - 1]));
      $('.imageryNav a.control').removeClass("active").filter(':contains(' + idx + ')').addClass('active');
   };

   function mycarousel_itemVisibleOutCallback(carousel, item, i, state, evt)
   {
      carousel.remove(i);
   };

   /**
    * Item html creation helper.
    */
   function mycarousel_getItemHTML(item)
   {
      if (item.large) {
         return '<a href="' + item.large + '"><img src="' + item.url + '" width="304" height="209" alt="' + item.title + '" /></a>';
      } else {
         return '<img src="' + item.url + '" width="304" height="209" alt="' + item.title + '" />';
      }
   };

   function mycarousel_initCallback(carousel) {
      $('.imageryNav a.control').bind('click', function() {
         carousel.scroll(jQuery.jcarousel.intval($(this).text()));
         $('.imageryNav a.control').removeClass("active");
         $(this).addClass("active");
         return false;
      });

      $('.imageryNav a.next').bind('click', function() {
         carousel.next();
         return false;
      });

      $('.imageryNav a.previous').bind('click', function() {
         carousel.prev();
         return false;
      });
   }

   $(document).ready(function() {
      if ($.fn.jcarousel) {
         $('#ProductCarousel').jcarousel({
            wrap: 'circular',
            scroll: 1,
            // visible: 1,
            initCallback: mycarousel_initCallback,
            itemVisibleInCallback: {onBeforeAnimation: mycarousel_itemVisibleInCallback},
            itemVisibleOutCallback: {onAfterAnimation: mycarousel_itemVisibleOutCallback}
         }).find('a').live('click', viewLargerImage);
      }
   });

   var viewLargerImage = function(e) {
      e.preventDefault();
      if ($.prettyPhoto) {
         $.prettyPhoto.open(this.href,  $(this).find('img').attr('alt'), '');
      }
   };

   /* Carousel for mast on homepage  */
   $(document).ready(function() {
      if ($.fn.jCarouselLite) {
         $("#VideoCarousel").jCarouselLite({
            scroll: 1,
            speed: 500,
            visible: 5,
            btnNext: ".videoCarouselContainer .next a",
            btnPrev: ".videoCarouselContainer .previous a"
         });
      }
   });

   $(document).ready(function(){
      if ($.fn.prettyPhoto) {
         if ($('body.home').length == 1) {
            var options = {
               flash_markup: '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" width="{width}" height="{height}" id="viddler"><param name="movie" value="{path}" /><param name="allowScriptAccess" value="always" /><param name="allowFullScreen" value="true" /><param name="flashvars" value="fake=1"/><embed src="{path}" width="{width}" height="{height}" type="application/x-shockwave-flash" allowScriptAccess="always" allowFullScreen="true" flashvars="fake=1" name="viddler" ></embed></object>',
               theme: 'facebook'
            };
            $("a[rel^='prettyPhoto'], a.prettyPhoto, a.prettyPhotoViddler").prettyPhoto(options);
         } else {
            $("a[rel^='prettyPhoto'], a.prettyPhoto").prettyPhoto({theme: 'facebook'});
         }
      }
   });

   // Custom jQuery selector for elements with non-empty title attribute
   $.expr[':'].withTitle = function(obj){
     return ($(obj).attr('title') != '');
   };

   var SecondaryNavFlyouts = {
      init: function() {
         $('#NavigationSecondary a:withTitle').each(function(i) {
            var $$ = $(this).hover(SecondaryNavFlyouts.mouseover, SecondaryNavFlyouts.mouseout);
            var text = $$.attr('title');
            // Get rid of the title to prevent view on hover
            $$.attr('title', '');
            var $div = $('<div class="flyout"><div class="content"><p>' + text + '</p></div></div>');
            $$.before($div);
         });
      },
      mouseover: function(e) {
         $(this).addClass('over').prev('div.flyout').show().parent('li').addClass('over');
      },
      mouseout: function(e) {
         $(this).removeClass('over').prev('div.flyout').hide().parent('li').removeClass('over');
      }
   };
   $(document).ready(SecondaryNavFlyouts.init);

   var PluginList = {
      init: function() {
         $('ul.pluginList > li > a').each(function(i) {
            $(this).mouseover(PluginList.mouseover);
         }).eq(0).mouseover();
      },
      mouseover: function(e) {
         $(this).parent().siblings('li').find('> a').removeClass('over').siblings('div.details').hide();
         $(this).addClass('over').siblings('div.details').show();
      }
   };
   $(document).ready(PluginList.init);

   var TechnologyList = {
      init: function() {
         $('ul.technologyList > li > a').each(function(i) {
            $(this).mouseover(TechnologyList.mouseover);
         }).eq(0).mouseover();
      },
      mouseover: function(e) {
         $(this).parent().siblings('li').find('> a').removeClass('over').siblings('div.details').hide();
         $(this).addClass('over').siblings('div.details').show();
      }
   };
   $(document).ready(TechnologyList.init);

   var quotes;
   var CalloutBoxQuotes = {
      idx: 0,
      _quote: null,
      time: 5000,
      init: function() {
         if (! quotes)
            return;
         $('.calloutBox .quote').each(function(i) {
            CalloutBoxQuotes._quote = $(this);
            CalloutBoxQuotes.showQuote();
         });
      },
      showQuote: function() {
         var i = CalloutBoxQuotes.idx;
         var $$ = CalloutBoxQuotes._quote;
         $$.fadeOut(function() {
            $$	.find('q')
               .text(quotes[i][0])
               .end()
               .find('cite')
               .text(quotes[i][1])
               .end()
               .fadeIn(CalloutBoxQuotes.scheduleChange);
         });
         CalloutBoxQuotes.idx = i + 1;
         if (CalloutBoxQuotes.idx >= quotes.length)
            CalloutBoxQuotes.idx = 0;
      },
      scheduleChange: function() {
         setTimeout(CalloutBoxQuotes.showQuote, CalloutBoxQuotes.time);
      }
   };
   $(document).ready(CalloutBoxQuotes.init);

   var HomepageBanner = {
      init: function() {
         var $$ = $('#Banner');
         $$	.find('.banner')
            .click(HomepageBanner.bannerClick)
            .filter(':gt(0)')
            .hide()
            .end()
            .filter(':eq(0)')
            .each(function(e) {
               $$.find('a[href="#' + this.id + '"]').addClass('active');
            })
            .end()
            .end()
            .find('ul.controls a')
            .hover(HomepageBanner.mouseover, HomepageBanner.mouseout)
            .click(HomepageBanner.controlClick);
         // preload images
         // $("<img>").attr("src", "../images/hp/banner1.jpg");
         // $("<img>").attr("src", "../images/hp/banner2.jpg");
         // $("<img>").attr("src", "../images/hp/banner3.jpg");
      },
      mouseover: function(e) {
         var $$ = $(this);
         $$.addClass('active').parent().siblings().find('a').removeClass('active');
         $('#Banner')
            .find('div.banner:visible').hide().end().find(this.hash).show();
      },
      mouseout: function(e) {
         // do nothing
      },
      bannerClick: function(e) {
         e.preventDefault();
         e.stopPropagation();
         document.location.href = $(this).find('a.more').attr('href');
      },
      controlClick: function(e) {
         e.preventDefault();
         e.stopPropagation();
         $('#Banner').find(this.hash).click();
      }
   };
   $(document).ready(HomepageBanner.init);
});
