// 
// Functions
// 

// Anchor Scrolling
function Scroller(link, speed) {
	if (!speed) var speed = 500;

	$(link).click(function() {
		this.blur();
		this.hideFocus = true;
		this.style.outline = 'none';
		
		var elementClicked = $(this).attr("href");
		var destination = $(elementClicked).offset().top;
		$("html:not(:animated),body:not(:animated)").animate({ scrollTop: destination-30}, speed );
		return false;
	});
}


// Slideshow
function Slideshow(container, speed, fadein, fadeout) {
	
	var container = $(container);
	
	// Create the Navigation
	var navigationHTML =  '<div id="feature-navigation">';
		navigationHTML += '<a id="previous" href="#">Previous</a>';
		navigationHTML += '<a id="next" href="#">Next</a>';
		navigationHTML += '<div id="indicators"></div>';
		navigationHTML += '</div>';
	container.after(navigationHTML);

	var navigation = $('#feature-navigation');
	
	// Hide the Forward and Back buttons
	navigation.children('a').hide();
	
	// Show them on hover
	container.hover(
		function () {
			navigation.children('a').stop(true,true).fadeIn('slow');
		},
		function () {
			navigation.children('a').stop(true,true).fadeOut('slow');
		}
	)
	navigation.hover(
		function () {
			navigation.children('a').stop(true,true).fadeIn('slow');
		},
		function () {
			navigation.children('a').stop(true,true).fadeOut('slow');
		}
	)

	// Wait until the first slide image has loaded... (not working)
	// $container.find('ol li img').eq(0).bind('load', function (e) {
		
		var speed = 7000;
		var fadein = 800;
		var fadeout = 800;
		
		// Cycle - Replace with homebrew rotation rather than using a plugin
		container.cycle({ 
			activePagerClass: 'active',
		    fx: 'fade',
			next: '#next',
			pager: '#indicators',
			pause: 1,
			pauseOnPagerHover: 1,
			prev: '#previous',
			timeout: speed,
		    speedIn: fadein,
			speedOut: fadeout,
			sync: 1
		});
		
	// });
	
	// Pause the slideshow when hovering over the Navigation
	navigation.hover(
		function () {
			container.cycle('pause');
		},
		function () {
			container.delay(1000).cycle('resume');
		}
	);

	
	// Remove the focus outline on Navigation items when clicked
	navigation.find('a').keypress(function() {
		this.blur();
		this.hideFocus = false;
		this.style.outline = null;
	});
	navigation.find('a').mousedown(function() {
		this.blur();
		this.hideFocus = true;
		this.style.outline = 'none';
	});
	
	
}

// Carousel used in the Press section
function Carousel(container) {

	var container = $(container);
	var wrapper = container.children();
	var items = wrapper.children();
	var cutoff = 4;
    var containerID = container.attr('id');
    
	var navigationHTML =  '<div id="' + containerID + '-navigation">';
		navigationHTML += '<a class="previous" href="#">Previous</a>';
		navigationHTML += '<a class="next" href="#">Next</a>';
		navigationHTML += '<div class="indicators"></div>';
		navigationHTML += '</div>';

	container.after(navigationHTML);

	var navigation = $('#' + containerID + '-navigation');

	for(var i = 0; i < items.length; i+=cutoff) {
		items.slice(i, i+cutoff).wrapAll('<div class="panel"></div>');
	}
	
    var panels = wrapper.children('.panel');
    var container_width = panels.first().width() * panels.size();
    
    // panels.each(function (index) {
    //    $(this).attr('id', 'panel-' + index);
    //    navigation.children('div').append('<a href="#panel-' + index + '">' + index + '</a>');
    // });

    wrapper.css('width', container_width + 'px');
    
    var speed = 0;
	var fadein = 300;
	var fadeout = 300;

	// Cycle - Replace with homebrew rotation rather than using a plugin
	wrapper.cycle({ 
	    activePagerClass: 'current',
	    fx: 'scrollHorz',
		next: '#' + containerID + '-navigation .next',
		pager: '#' + containerID + '-navigation .indicators',
		prev: '#' + containerID + '-navigation .previous',
		timeout: speed,
		rev: 0,
	    speedIn: fadein,
		speedOut: fadeout,
		sync: 1
	});

}


// Coda Style Slider
// when the DOM is ready...
function Coda(panels, container, nav) {

    var $panels = $(panels);
    var $container = $(container);
	var $nav = $(nav);
    // if false, we'll float all the panels left and fix the width 
    // of the container
    var horizontal = true;

    // float the panels left if we're going horizontal
    if (horizontal) {
        $panels.css({
            'float' : 'left',
            'position' : 'relative' // IE fix to ensure overflow is hidden
        });

        // calculate a new width for the container (so it holds all panels)
        $container.css('width', $panels[0].offsetWidth * $panels.length);
    }

    // collect the scroll object, at the same time apply the hidden overflow
    // to remove the default scrollbars that will appear
    var $scroll = $('#slider .scroll').css('overflow', 'hidden');

    // apply our left + right buttons
    $scroll
        .before('<img class="scrollButtons left" src="images/scroll_left.png" />')
        .after('<img class="scrollButtons right" src="images/scroll_right.png" />');

    // handle nav selection
    function selectNav() {
        $(this)
            .parents('ul:first')
                .find('a')
                    .removeClass('selected')
                .end()
            .end()
            .addClass('selected');
    }

    $('#slider .navigation').find('a').click(selectNav);

    // go find the navigation link that has this target and select the nav
    function trigger(data) {
        var el = $('#slider .navigation').find('a[href$="' + data.id + '"]').get(0);
        selectNav.call(el);
    }

    if (window.location.hash) {
        trigger({ id : window.location.hash.substr(1) });
    } else {
        $('ul.navigation a:first').click();
    }

    // offset is used to move to *exactly* the right place, since I'm using
    // padding on my example, I need to subtract the amount of padding to
    // the offset.  Try removing this to get a good idea of the effect
    var offset = parseInt((horizontal ? 
        $container.css('paddingTop') : 
        $container.css('paddingLeft')) 
        || 0) * -1;


    var scrollOptions = {
        target: $scroll, // the element that has the overflow

        // can be a selector which will be relative to the target
        items: $panels,

        navigation: '.navigation a',

        // selectors are NOT relative to document, i.e. make sure they're unique
        prev: 'img.left', 
        next: 'img.right',

        // allow the scroll effect to run both directions
        axis: 'xy',

        onAfter: trigger, // our final callback

        offset: offset,

        // duration of the sliding effect
        duration: 500,

        // easing - can be used with the easing plugin: 
        // http://gsgd.co.uk/sandbox/jquery/easing/
        easing: 'swing'
    };

    // apply serialScroll to the slider - we chose this plugin because it 
    // supports// the indexed next and previous scroll along with hooking 
    // in to our navigation.
    $('#slider').serialScroll(scrollOptions);

    // now apply localScroll to hook any other arbitrary links to trigger 
    // the effect
    $.localScroll(scrollOptions);

    // finally, if the URL has a hash, move the slider in to position, 
    // setting the duration to 1 because I don't want it to scroll in the
    // very first page load.  We don't always need this, but it ensures
    // the positioning is absolutely spot on when the pages loads.
    scrollOptions.duration = 1;
    $.localScroll.hash(scrollOptions);

}


function simpleTabs (container, children) {
	
	var container = $(container);
	var triggers = container.children('nav').find('a');
	var panels = container.children().not('nav, header');
	
	if (children == true) {
		var panels = $(panels).children();
	} else {
		var panels = container.children().not('nav, header');
	};
	
	triggers.first().attr('class', 'current');
	panels.eq(0).addClass('active-slide');
	panels.slice(1).addClass('inactive-slide');
	
	triggers.click(function(e) {
		e.preventDefault();
		triggers.removeAttr('class');
		$(this).attr('class', 'current');
		
		var currentslide = $(this).attr('href');
		
		panels.not(currentslide).removeClass('active-slide').addClass('inactive-slide');
		panels.filter(currentslide).removeClass('inactive-slide').addClass('active-slide');
		
	});
	
}



// Tabbed Interaction
function Tabs(triggers, slides, transition) {
	
	var triggers = $(triggers);
	var slides = $(slides);
	var transition = $(transition);
	
	if (slides.parent().attr('id')) {
		slides.wrapAll('<div class="' + slides.parent().attr('id') + '-content"></div>');
	} else {
		slides.wrapAll('<div class="content"></div>');
	}
	
	var wrapper = slides.parent();	
	
	slides.hide();
	slides.parent().css('position', 'relative');
	slides.css('position', 'absolute');
	slides.eq(0).show();
	wrapper.css('height', slides.eq(0).css('height'));
	
	
	triggers.eq(0).parent('li').addClass('current');
	

	
	triggers.click(function(e) {

		e.preventDefault();

		triggers.parents('li').removeAttr('class');
		$(this).parents('li').attr('class', 'current');
		
		var anchor = $(this).attr('href');
		var current_slide = $(anchor);
		
		if (transition.length>0) {
			if (transition='fade') {
				var slideheight = current_slide.css('height');
				slides.fadeOut('normal');
				current_slide.fadeIn('slow');
				wrapper.animate({
					height: slideheight
				}, 500);			
			}
		} else {
			slides.fadeOut('normal');
			current_slide.fadeIn('slow');
		};

		
	});	
	
}

function RemoveFocus(element) {

	$(element).keypress(function() {
	     this.blur();
	     this.hideFocus = false;
	     this.style.outline = null;
	});
	$(element).mousedown(function() {
	     this.blur();
	     this.hideFocus = true;
	     this.style.outline = 'none';
	});

}

function Overlay(img_link, external_link) {
	
	$(img_link).fancybox({
			'autoScale'     :   true,
			'transitionIn'	:	'fade',
			'transitionOut'	:	'fade',
			'speedIn'		:	800, 
			'speedOut'		:	200, 
			'overlayColor'  :   '#fff',
			'overlayOpacity':   0.6,
			'overlayShow'	:	true,
			'titlePosition' :   'over'
	});

	$(external_link).fancybox({
			'autoScale'     :   true,
			'transitionIn'	:	'fade',
			'transitionOut'	:	'fade',
			'speedIn'		:	800, 
			'speedOut'		:	200, 
			'overlayColor'  :   '#fff',
			'overlayOpacity':   0.6,
			'overlayShow'	:	true,
			'titlePosition' :   'over',
			'height'        :   530,
			'width'         :   800
	});		
}

// Shop: Product Image Interaction
function fnbProductImages (imageContainer) {
	
	var imageContainer = $(imageContainer);
	var productImages = imageContainer.children();
	var imageNavigation = $('<div id="image-navigation"></div>');
	var productThumbs = productImages.clone();

	// Insert the navigation container
	imageNavigation.insertAfter(productImages.parent());

	// Set the height of the image container to the height of the first image
	productImages.eq(0).imagesLoaded(function(){
		imageContainer.css('height', imageContainer.children('img').eq(0).height() + 'px');
	});
	
	productImages.imagesLoaded(function(){
		// Add the cloned images to the navigation as thumbnails
		productThumbs.appendTo(imageNavigation);
		// Change each taget on rollover
		imageNavigation.children('img').mouseover(function() {
			i = $(this).index();
	
			productImages.eq(i).stop().show();
			productImages.eq(i).siblings('img').stop().hide();
		});
	
		productImages.css({
			position: 'absolute',
			left: '50%',
			marginLeft: '-' + ($(this).width() * 0.5) + 'px'
		});
		productImages.eq(0).nextAll().hide();
		
	});
	
}


// Image Gallery
function Gallery (gallery) {

	var trigger = $(gallery).children('a').eq(0);
	
	$(gallery).css('position','relative');
	$(gallery).children('a:gt(0)').css({
		'position': 'absolute',
		'left': '-9999px'
	});
	
	// Modal Window
	$(gallery).children('a').fancybox({
			'autoScale'     :   true,
			'transitionIn'	:	'fade',
			'transitionOut'	:	'fade',
			'speedIn'		:	800, 
			'speedOut'		:	200, 
			'overlayColor'  :   '#000',
			'overlayOpacity':   0.9,
			'overlayShow'	:	true,
			'titlePosition' :   'over'
	});
	
	// Hover Effect
	$('<div class="window-shade" style="left: 50%; margin-left: -28%; position: absolute; text-align: center; top: 40%; width: 50%;">View Gallery</div>').appendTo(trigger).hide();
	
	trigger.hover(
		function(){
			$(this).children('.window-shade').fadeTo('fast', 1.0);
		},
		function(){
			$(this).children('.window-shade').fadeTo('fast', 0);
		}
	);

}





// $('img.photo',this).imagesLoaded(myFunction)
// execute a callback when all images have loaded.
// needed because .load() doesn't work on cached images
// ----------------------------------------------------
// mit license. paul irish. 2010.
// webkit fix from Oren Solomianik. thx!
// ----------------------------------------------------
// callback function is passed the last image to load
//   as an argument, and the collection as `this`
$.fn.imagesLoaded = function(callback){
  var elems = this.filter('img'),
      len   = elems.length;
      
  elems.bind('load',function(){
      if (--len <= 0){ callback.call(elems,this); }
  }).each(function(){
     // cached images don't fire load sometimes, so we reset src.
     if (this.complete || this.complete === undefined){
        var src = this.src;
        // webkit hack from http://groups.google.com/group/jquery-dev/browse_thread/thread/eee6ab7b2da50e1f
        // data uri bypasses webkit log warning (thx doug jones)
        this.src = "data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw==";
        this.src = src;
     }  
  }); 

  return this;
};
