// remove the "$" namespace from jQuery, avoids conflicts with other libraries
jQuery.noConflict();

// closure, mapping jQuery to $, window, document and undefined - useful for minifing tools
(function($, window, document, undefined) {

   // document ready method
   $(function() {

      if ($.fn.jCarouselLite) {
         var slideshow1 = $('#slideshow1');
         if (slideshow1.length) {
            slideshow1.append('<p class="nav"><a href="#" class="prev"><span></span></a><a href="#" class="next"><span></span></a></p>');
            slideshow1.find('.slider').jCarouselLite({
               btnPrev: 'a.prev',
               btnNext: 'a.next',
               visible: 1,
               scroll: 1,
               speed: 300,
               auto: 5000,
               vertical: true,
               circular: true
            });
         }

         var slideshow2 = $('.slideshow2');
         if (slideshow2.length) {
            var sl = slideshow2.find('.slider');
            var to_int = function(s) { return parseInt(s.replace('px')); }
            var set_width = sl.width() - to_int(sl.css('margin-left')) - to_int(sl.css('margin-right'));
            slideshow2.append('<p class="nav"><a href="#" class="prev"><span></span></a><a href="#" class="next"><span></span></a></p>');
            sl.jCarouselLite({
               btnPrev: 'a.prev',
               btnNext: 'a.next',
               visible: 6,
               scroll: 1,
               speed: 300,
               circular: true
            });
            sl.width(set_width - 1);
         }
      }

      if ($.fn.tabs) {
         $('.tab-area').tabs();
      }

      if ($.fn.boxLinks) {
         //$('#resources li').boxLinks({ trigger: 'a.title' });
         //$('.list-cols li, #videos li, #videos2 li, #case-studies li').boxLinks();
         $('.list-cols li, #videos2 li, #case-studies li').boxLinks();
      }

      if ($.fn.equalHeights) {
         $('#menu').find('.dd').each(function() {
            $(this).children().equalHeights();
         });
         $('#menu-footer').children().equalHeights();
         $('#videos2').children().equalHeights({ 'videos2-content': 4 });
      }



      var $menu = $('#menu');
      if ($menu.length) {
         function closeDDs() {
            $menu.find('.bar li').removeClass('expanded');
            $dropdowns.css({ left: '-999em', right: 'auto' });
         }

         var $dropdowns = $menu.find('.dd'), timerDD = null;

         $menu.find('.bar li').hover(function() {
            clearTimeout(timerDD);
            var li = $(this), dd = $(li.children()[0].hash), pos = li.position(),
				other = $menu.find('.bar li.expanded'),
				w = $(window).width(), mpos = $menu.offset(), delta = 428, l;

            if (li.hasClass('expanded')) return;

            if (!li.hasClass('expanded') && other.length)
               closeDDs();

            if (dd.length) {
               l = Math.floor(pos['left'] + 1);
               if (l + mpos['left'] + delta >= w)
                  dd.css({ left: 'auto', right: ($menu.width() - pos['left'] - li.outerWidth() + 1) + 'px' });
               else
                  dd.css({ left: l + 'px' });
               dd.removeClass('extended').
					find('.level-1 a').removeClass('active').end().
					find('.level-2').hide();
               li.addClass('expanded');
            }
         }, function() {
            timerDD = setTimeout(closeDDs, 300);
         });

         $dropdowns.each(function() {
            var dd = $(this),
				level1s = dd.find('.level-1 a'),
				level2s = dd.find('.level-2');

            level1s.bind('mouseenter', function() {
               level1s.removeClass('active');

               var a = $(this).addClass('active'), level2 = $(this.hash);

               level2s.hide();
               if (level2.length && $(level2).find('li').length > 0) {
                  dd.addClass('extended');
                  level2.show();
               }
               else
                  dd.removeClass('extended');
            });
         }).hover(function() {
            clearTimeout(timerDD);
         }, function() {
            timerDD = setTimeout(closeDDs, 300);
         });
      }



      var ticker = $('#ticker');
      if (ticker.length) {

         var sliderContainer = $(ticker).find('.slider');
         var scrollingArea = $(ticker).find('.slider ul');
         //begin edit SteveR
         //copy existing li elements and add to list 
         var slider1 = sliderContainer;
         if (slider1.length) {
            var w = slider1.width();
            var els = slider1.find('li');
            els.each(function() {
               var e = $(this).clone();
               this.parentNode.appendChild(e[0]);
            });
         }
         //setup the scrolling elements
         var el = scrollingArea[0].firstChild;
         var total_width = 0;
         var els = [];
         while (el) {
            //ensure only getting the li els
            if (el.nodeName == 'LI') {
               total_width += $(el).width();
               els.push(el);
            }
            el = el.nextSibling;
         }
         scrollingArea.css('width', (total_width + 30) + 'px');

         //define constants
         //break between animates in sec
         var pause = 0;
         //arbitary speed
         var speed = 20;
         //wheather to ease in between each element 
         var easing = false;
         //how far beyond the border to animate to.
         var offset = 0;

         var cb = function(curr_w) {
            //20px padding or some unaccounted amount subject to css and makrup changes
            scrollingArea.css('left', (parseInt(scrollingArea.css('left').replace('px', '')) + curr_w + offset) + 'px');
            var el = els.shift();
            scrollingArea[0].removeChild(el);
            scrollingArea[0].appendChild(el);
            els.push(el);
            if (pause > 0) {
               setTimeout(function() { _animate(els[0]) }, (pause * 1000));
            } else {
               _animate(els[0]);
            }
         }
         var _animate = function(el) {
            var w = $(el).outerWidth(true);
            scrollingArea.animate({ left: '-=' + (w + offset) + 'px' }, ((w + offset)) * speed, (easing ? 'swing' : 'linear'), function() { cb(w); });
         };
         _animate(els[0]);
         scrollingArea.mouseover(function() {
            scrollingArea.stop();
         });
         scrollingArea.mouseout(function() {
            _animate(els[0]);
         });
      }


   });

   // plugins

   // tabs - jQuery plugin - creates a tab area
   $.fn.tabs = function(args) {
      if (!this.length) return this;

      //ADAM: 2011-10-05 - calculates width of children (li/tabs) and sets menu (ul) width accordingly
      //assumption of menu across single line
      var width = 2;
      $(this).children(".tabs").children("li").each(function() { width += $(this).outerWidth(); });
      $(this).children(".tabs").css("width", width);
      //end calculation

      var opts = $.extend({
         triggers: '.tabs a',
         tabs: '.tab'
      }, args || {});

      return this.each(function() {
         var parent = $(this), triggers = parent.find(opts.triggers), tabs = parent.find(opts.tabs);

         triggers.click(function() {
            var id = this.hash.substr(1), tab = $('#' + id);
            if (!tab.length)
               return false;

            parent.trigger('tabsChange', [triggers, tabs, tab]);

            tabs.hide();
            tab.show();

            triggers.removeClass('active');
            $(this).addClass('active');

            return false;
         });
         tabs.hide();

         var active = (triggers.filter('.active').length) ? triggers.filter('.active') : triggers.eq(0);
         active.click();
      });
   };

   // boxLinks - jQuery plugin - transforms block elements into clickable items
   $.fn.boxLinks = function(args) {
      if (!this.length) return this;

      var opts = $.extend({
         trigger: 'a',
         classHover: 'hover',
         classFocus: 'focus',
         onEnter: null,
         onLeave: null,
         onClick: function() {
            window.location = $(this).attr('href');
         }
      }, args || {});

      this.has(opts.trigger)
		.each(function() {
		   var self = $(this), t = self.css('cursor', 'pointer').find(opts.trigger);
		   $.data(this, 'trigger', t);
		   $.data(t[0], 'parent', self);
		}).bind('mouseenter', function() {
		   var t = $.data(this, 'trigger'), self = $(this).addClass(opts.classHover);
		   opts.onEnter && opts.onEnter(self);
		   window.status = t.attr('href');
		}).bind('mouseleave', function() {
		   var self = $(this).removeClass(opts.classHover);
		   opts.onLeave && opts.onLeave(self);
		   window.status = '';
		}).bind('click', function(ev) {
		   var t = $.data(this, 'trigger');
		   t.trigger('click');
		   ev.stopPropagation();
		   return false;
		});

      this.find(opts.trigger).addClass('trigger')
		.bind('focus', function() {
		   var p = $.data(this, 'parent');
		   p.addClass(opts.classFocus);
		}).bind('blur', function() {
		   var p = $.data(this, 'parent');
		   p.removeClass(opts.classFocus);
		}).click(function(ev) {
		   opts.onClick.apply(this);
		   ev.stopPropagation();
		   return false;
		});

      this.find('a').not(opts.trigger).click(function(ev) {
         ev.stopPropagation();
      });

      return this;
   };

   // equalHeights - jQuery plugin - forces elements to have the same height (maximum)
   $.fn.equalHeights = function(add) {
      var m = 0;
      this.each(function() {
         m = Math.max(m, $(this).outerHeight());
      });
      return this.each(function() {
         var t = $(this), p = 0;
         $.each(['borderTopWidth', 'paddingTop', 'paddingBottom', 'borderBottomWidth'], function(i, n) {
            var v = parseInt(t.css(n));
            p += (isNaN(v) ? 0 : v);
         });
         var h = m - p;
         if (add && add[this.id])
            h += add[this.id];
         if ($.browser.msie && $.browser.version <= 6)
            t.css('height', h);
         t.css('min-height', h);
      });
   };


})(jQuery, window, document);

