// JavaScript Document

// Jqueryfordesigners.com code

$.fn.infiniteCarousel = function () {

    function repeat(str, num) {
        return new Array( num + 1 ).join( str );
    }
  
    return this.each(function () {
        var $wrapper = $('> div', this).css('overflow', 'hidden'),
            $slider = $wrapper.find('> ul'),
            $items = $slider.find('> li'),
            $single = $items.filter(':first'),
            
            singleWidth = $single.outerWidth(), 
            visible = Math.ceil($wrapper.innerWidth() / singleWidth),
            currentPage = 1,
            pages = Math.ceil($items.length / visible);            


        // 1. Pad so that 'visible' number will always be seen, otherwise create empty items
        if (($items.length % visible) != 0) {
            $slider.append(repeat('<li class="empty" />', visible - ($items.length % visible)));
            $items = $slider.find('> li');
        }

        // 2. Top and tail the list with 'visible' number of items, top has the last section, and tail has the first
        $items.filter(':first').before($items.slice(- visible).clone().addClass('cloned'));
        $items.filter(':last').after($items.slice(0, visible).clone().addClass('cloned'));
        $items = $slider.find('> li'); // reselect
        
        // 3. Set the left position to the first 'real' item
        $wrapper.scrollLeft(singleWidth * visible);
        
        // 4. paging function
        function gotoPage(page) {
            var dir = page < currentPage ? -1 : 1,
                n = Math.abs(currentPage - page),
                left = singleWidth * dir * visible * n;
            
            $wrapper.filter(':not(:animated)').animate({
                scrollLeft : '+=' + left
            }, 500, function () {
                if (page == 0) {
                    $wrapper.scrollLeft(singleWidth * visible * pages);
                    page = pages;
                } else if (page > pages) {
                    $wrapper.scrollLeft(singleWidth * visible);
                    // reset back to start position
                    page = 1;
                } 

                currentPage = page;
            });                
            
            return false;
        }
        
        $wrapper.after('<a class="arrow back"></a><a class="arrow forward"></a>');
        
        // 5. Bind to the forward and back buttons
        $('a.back', this).click(function () {
            return gotoPage(currentPage - 1);                
        });
        
        $('a.forward', this).click(function () {
            return gotoPage(currentPage + 1);
        });
        
        // create a public interface to move to a specific page
        $(this).bind('goto', function (event, page) {
            gotoPage(page);
        });
		
		// THIS IS NEW CODE FOR THE AUTOMATIC INFINITE CAROUSEL
		$(this).bind('next', function () {
        	gotoPage(currentPage + 1);
        });
    });  
};

$(document).ready(function() { // $(function(){
	
	$('#currentFeature').anythingSlider({
        easing: "swing",
		startStopped: false,            // If autoPlay is on, this can force it to start stopped
        delay: 5200,                    // How long between slide transitions in AutoPlay mode
        animationTime: 300,             // How long the slide transition takes
        hashTags: false,                 // Should links change the hashtag in the URL?
        buildNavigation: false,          // If true, builds and list of anchor links to link to each slide
        startText: "",             // Start text
        stopText: "",               // Stop text
        navigationFormatter: null       // Details at the top of the file on this use (advanced use)
	});
	
	$('#resourcesGallery').anythingSlider({
        easing: "swing",
		autoPlay: false,
		startStopped: false,            // If autoPlay is on, this can force it to start stopped
        animationTime: 200,             // How long the slide transition takes
        hashTags: true,                 // Should links change the hashtag in the URL?
        buildNavigation: false,          // If true, builds and list of anchor links to link to each slide
        startText: "",             // Start text
        stopText: "",               // Stop text
        navigationFormatter: null       // Details at the top of the file on this use (advanced use)
	});
	
	$('#homeSelector').hover(function() {
		$('#landingLogo').css('background-position','center -76px');							  
	}, function() {
		$('#landingLogo').css('background-position','center 0');							  
	});
		   
	$('ul.tabs').tabs('div.panes > div', {
		effect: 'fade',
		history: true
	});
	
	$('li.narrowLink a').css('width',0);
	
	// Sliding quick links animation
	$('li.narrowLink')
		.mouseover(function(){
			$(this).find('a').stop().animate({ width:'178px'}, {duration:200})
		})
		.mouseout(function(){
			$(this).find('a').stop().animate({ width:'0px' }, {duration:200})
		});
		
	$('li.bigLink a')
		.mouseover(function(){
			$(this).find('span').stop().animate({ width:"178px" }, {duration:200})
		})
		.mouseout(function(){
			$(this).find('span').stop().animate({ width:"0px" }, {duration:200})
		});

    $('#dropdown').superfish({
		animation: { height: 'toggle' },
		speed: 300,
		autoArrows: false
	});
	
	
    $("#nav li ul li:has(ul)").find("a:first").append(" &raquo; ");

	// init the carousels
	$('#featureCarousel').infiniteCarousel();
	
	var autoscrolling = true;
    
    $('.gearCarousel').infiniteCarousel().mouseover(function () {
        autoscrolling = false;
    }).mouseout(function () {
        autoscrolling = true;
    });
    
    setInterval(function () {
        if (autoscrolling) {
            $('.gearCarousel').trigger('next');
        }
    }, 7000);
	
	// change the big What's New image
	$('a.featureJump').hover(function() {
		
		jumpTo = parseInt($(this).attr('rel')) + 1;
		$('#currentFeature').anythingSlider(jumpTo);
		
	}, function(){});
	
	// change the Resources panel
	$('a.resourceJump').click(function(e) {
		
		jumpTo = parseInt($(this).attr('rel'));
		$('#resourcesGallery').anythingSlider(jumpTo);
		e.preventDefault();
		
	});
	
	// change the main gallery text
	$('a.mediaLink').click(function(event) {
		newAlt = $(this).find('img').attr('alt');
		newTitle = $(this).find('img').attr('title');		
		
		
		$('#viewDescription .title').empty().append(newTitle);
		$('#viewDescription .caption').empty().append(newAlt);
	});
	
	// minimize all TNF athlete testimonials
	$('div.tnfAthlete').css({'height': '140px', 'overflow': 'hidden'});
	
	
	// slide TNF athlete testimonials
	$('div.tnfAthlete').click(function(e){
		
		if ($(this).hasClass('open')) {
			$(this).animate({ 
				height: '140px'
			}).removeClass('open');
			$(this).children('.tnfToggleVisible').css('background-position','0 -20px');
		} else {
			$(this).animate({ 
				height: '593px'
			}).addClass('open');
			$(this).children('.tnfToggleVisible').css('background-position','0 0');
		}
		
	});
		
	// setting fancybox pop-ups
	$("a.testimonialLink, a#enewsletterBtn").fancybox({
		'titlePosition': 'inside',
		'padding': 0,
		'centerOnScroll': true,
		'overlayOpacity': .8,
		'overlayColor': '#232323',
		'width': 400,
		'height': 400,
		'hideOnContentClick': false
	});
	
	$("a#requestBtn").fancybox({
		'titlePosition': 'inside',
		'padding': 0,
		'centerOnScroll': true,
		'overlayOpacity': .8,
		'overlayColor': '#232323',
		'width': 400,
		'height': 560,
		'hideOnContentClick': false		
	});
	
	// custom formatting for Fancybox titles
	function formatTitle(title, currentArray, currentIndex, currentOpts) {
		return '<span>' + (title && title.length ? title : '' ) + '</span>';
	}
	
	$("a[rel|=fancy]").fancybox({
		'width': 600,
		'height': 400,
		'titlePosition': 'inside',
		'padding': 0,
		'centerOnScroll': true,
		'overlayOpacity': .8,
		'overlayColor': '#232323',
		'titleFormat': formatTitle
	});
	
	// hiding and revealing the comment form
	$('.commentForm').css('display','none');
	$('.enterComment').click(function(){
		$('.commentForm').slideToggle(400); 
	});
	
	// Fancybox YouTube videos
	$("a.fancytube").click(function() {
        $.fancybox({
            'padding'       : 0,
            'autoScale'     : false,
            'transitionIn'  : 'none',
            'transitionOut' : 'none',
            'title'         : this.title,
            'width'         : 640,
            'height'        : 385,
            'href'          : this.href.replace(new RegExp("watch\\?v=", "i"), 'v/'),
            'type'          : 'swf',
            'swf'           : {
            'wmode'             : 'transparent',
            'allowfullscreen'   : 'true'
            }
        });
        return false;
    });
	
	// pop-up video
	$("#fancyBanff").fancybox({
		'width': 480,
		'height': 272,
		'overlayOpacity': .8,
		'overlayColor': '#232323'
	});
	
	// trigger a hidden link
	$("#hiddenLink").fancybox({
		'width': 320,
		'height': 180,
		'overlayOpacity': .8,
		'overlayColor': '#232323'
	}).trigger('click');
	
	// tooltip call
	// $("#careIcons img[title]").tooltip();
});
