(function($) {	
	
	$.fn.brightslide = function(options) {
		options = $.extend({}, $.fn.brightslide.defaults, options);
		
		// hide on load
		$(this).hide();
		
		// push our items into an array
		var items = $('.media-items').find('li');
		
		// setup our thumbnails
		build_thumbnails();
		var thumbnails = $('#media-nav').find('li');
		
		// set the current thumbnail (highlight)
		var current;
		var first = $('#media-nav').find('li:first-child');
		var last	= $('#media-nav').find('li:last-child');
		set_current($(first));
		
		// fade in and begin the "brightslide"
		$(this).fadeIn(600);
		
		/////////////////////////////////////////////////////////////////////////////////////
		// THUMBNAILS
		/////////////////////////////////////////////////////////////////////////////////////
		
		$(thumbnails).each(function(){
			var opts = $.fn.brightslide.elementOptions(this, options);
			var timeout = null;
			
			// HOVER *************************************************************************
			
			if (opts.thumbnail) {
				$(this).hover(function() {
					var self = this;
					timeout = setTimeout(function() {
						$.data(self, 'cancel.thumbnail', true);
						var tip = $.data(self, 'active.thumbnail');
						if (!tip) {
							tip = $('<div class="thumbnail"><div class="thumbnail-inner"/></div>');
							tip.css({position: 'absolute', zIndex: 100000});
							$.data(self, 'active.thumbnail', tip);
						}

						tip.find('.thumbnail-inner')[opts.html ? 'html' : 'text']('<img src="' + $(self).attr('thumbnail') + '" />');

						var pos = $.extend({}, $(self).offset(), {width: self.offsetWidth, height: self.offsetHeight});
						tip.get(0).className = 'thumbnail'; // reset classname in case of dynamic gravity
						tip.remove().css({top: 0, left: 0, visibility: 'hidden', display: 'block'}).appendTo(document.body);
						var actualWidth = tip[0].offsetWidth, actualHeight = tip[0].offsetHeight;
						var gravity = (typeof opts.gravity == 'function') ? opts.gravity.call(self) : opts.gravity;

						switch (gravity.charAt(0)) {
							case 'n':
								tip.css({top: pos.top + pos.height, left: pos.left + pos.width / 2 - actualWidth / 2}).addClass('thumbnail-north');
								break;
							case 's':
								tip.css({top: pos.top - actualHeight, left: pos.left + pos.width / 2 - actualWidth / 2}).addClass('thumbnail-south');
								break;
							case 'e':
								tip.css({top: pos.top + pos.height / 2 - actualHeight / 2, left: pos.left - actualWidth}).addClass('thumbnail-east');
								break;
							case 'w':
								tip.css({top: pos.top + pos.height / 2 - actualHeight / 2, left: pos.left + pos.width}).addClass('thumbnail-west');
								break;
						}

						if (opts.fade) {
							tip.stop().css({opacity: 0, display: 'block', visibility: 'visible'}).animate({opacity: opts.opacity}, 150);
						} else {
							tip.css({visibility: 'visible', opacity: opts.opacity});
						}
					}, opts.delayIn);
				}, function() {
					$.data(this, 'cancel.thumbnail', false);
					var self = this;
					clearTimeout(timeout);
					setTimeout(function() {
						if ($.data(this, 'cancel.thumbnail')) return;
						var tip = $.data(self, 'active.thumbnail');
						if (opts.fade) {
							tip.stop().fadeOut(200, function() { $(this).remove(); });
						} else if (tip) {
							tip.remove();
						}
					}, opts.delayOut);
				});
			}
			
			// CLICK *************************************************************************
			
			$(this).bind('click',function() {
				set_current($(this));
			});
		
		});
		
		function load_item(item) {
			if($(item).attr('video')=="true") {
				html = '<div class="flv" id="video_' + $(item).attr('index') + '" which-video="video_' + $(item).attr('index') + '"></div><script type="text/javascript">video_' + $(item).attr('index') + ' = new FAVideo("video_' + $(item).attr('index') + '", "' + $(item).attr('file') + '", 678, 435, { autoLoad:true, autoPlay:false });</script>';
			} else {
				html = '<img src="' + $(item).attr('thumbnail') + '" style="width: 678px; height: 435px" />';
			}
			$('.media-items')['html'](html);
			$('.media-items').fadeIn(200);
		};
		
		function set_current(el) {
			$(current).find('.preview').removeClass('active');
			$(el).find('.preview').addClass('active');
			current = $(el);
			$('.media-items').fadeOut(100, function(){
				load_item($(el));
			});
		};
		
		function build_thumbnails() {
			html = '<ul id="media-nav-items">';
			$(items).each(function(){
				if($(this).attr('index')==$(first).attr('index')){css = "first";};
				if($(this).attr('index')==$(last).attr('index')){css = "last";};
				html += '<li id="thumbnail-' + $(this).attr('index') + '" thumbnail="' + $(this).attr('thumbnail') + '" video="' + $(this).attr('video') + '" index="' + $(this).attr('index') + '" file="' + $(this).attr('file') + '"><span class="preview"></span></li>';
			});
			html += '</ul>';
			$('#media-nav').append(html);
		};
		
	};
	
	$.fn.brightslide.elementOptions = function(ele, options) {
		return $.metadata ? $.extend({}, options, $(ele).metadata()) : options;
	};
	
	$.fn.brightslide.defaults = {
		delayIn: 100,
		thumbnail: true,
		delayOut: 100,
		fade: true,
		fallback: '',
		gravity: 's',
		html: true,
		opacity: 1,
		title: 'title'
	};
	
	$.fn.brightslide.autoNS = function() {
		return $(this).offset().top > ($(document).scrollTop() + $(window).height() / 2) ? 's' : 'n';
	};
    
	$.fn.brightslide.autoWE = function() {
		return $(this).offset().left > ($(document).scrollLeft() + $(window).width() / 2) ? 'e' : 'w';
	};
	
})(jQuery);

// Accordion on home page
;(function($){
	$.fn.accordion = function(options) {
		options = $.extend({
			current_div:'1',
			previous_div:'',
			vertical: false,
			defaultid:0,
			current_counter:0,
			intervalid:0,
			autodelay:0,
			event:"click",
			alldivs_array:new Array()
		}, options);
		
		$(this).addClass("accordionWrapper");
		$(this).css({});
		
		var elementid = $(this).attr("id");
		var allDivs = this.children();
		
		if(options.autodelay>0)  {
			$("#"+ elementid +" > div").bind("mouseenter", function(){ 
				pause(); 
			});
			$("#"+ elementid +" > div").bind("mouseleave", function(){ 
				startPlay(); 
			});
		}
		
		allDivs.each(function(current) {
			var active = current;
			var title_id = elementid+"_title_"+(active);
			var content_id = title_id+"_content_"+(active);
			var current_div = allDivs[active];
			var total_children = current_div.childNodes.length;
			var title_div = $(current_div).find("div.title");
			title_div.attr("id", title_id);
			var content_div = $(current_div).find("div.content");
			content_div.attr("id", content_id);
			options.alldivs_array.push(title_id);
			$("#"+title_id).bind(options.event, function(){
				$(this).stop();
				open(title_id);
			});
		});
		
		$("#"+elementid +" > div").css({display:"block", float:"none", clear:"both"});
		$("#"+elementid +" > div > div.title").css({display:"block", float:"none", clear:"both"});
		$("#"+elementid +" > div > div.content").css({clear:"both"});
		
		//open default
		open(elementid+"_title_"+options.defaultid);
		
		if(options.autodelay>0) { startPlay(); };
		
		function open(id) {
			var title_id = id;
			var active = title_id.split("_")[title_id.split("_").length-1];
			options.current_counter = active;
			var content_id = id+"_content_"+active;
			if($("#"+content_id).css("display")=="none") {
				if(options.previous_div!="") {
					close(options.previous_div);
				};
				$("#"+content_id).stop().animate({
					"height":"toggle",
					"opacity":"toggle"
				}, {queue:false, duration:600});
				options.current_div = content_id;
				options.previous_div = options.current_div;
			};
		};
		
		function close(div) {
			$("#"+div).stop().animate({
				"height":"toggle",
				"opacity":"toggle"
			}, {queue:false, duration:300});
		};	
		
		function startPlay() {
			options.intervalid = window.setInterval(play, options.autodelay*1000);
		};
		
		function play() {
			var title_id = options.alldivs_array[options.current_counter];
			open(title_id);
			options.current_counter++;
			if(options.current_counter==options.alldivs_array.length) options.current_counter = 0;
		};
		
		function pause() {
			window.clearInterval(options.intervalid);
		};
	}
})(jQuery);

// Caption slide on about page

;(function($) {
	$.fn.capify = function(options) {
		options = $.extend({
			capcolor		: 'white',
			capbgcolor	: 'black',
			capborder		: '1px solid #fff'
		}, options);
		
		return this.each(function() {
			$this = $(this);
			
			// setup image
			var w = '130px';
			var h = '193px';
			
			// hide the copy, just leave the name
			$this.find('.caption').css('display','block');
			$this.find('.caption-text').css('display','none');
			
			// set style for our caption
			$('.caption',$this).css({'color':options.capcolor,'background-color':options.capbgcolor,'bottom':'0px','width':w});
			$this.css({'width':w , 'height':h, 'border':options.capborder});
			
			// hover functionality
			$this.hover(
				function() {
					$('.caption-text',$(this)).slideDown(300);
				},
				function() {
					$('.caption-text',$(this)).slideUp(300);
				}
			); // end hover
			
			$(this).click(function(){
				window.open($(this).attr('link'), '_self');
			});
			
		});
	};
})(jQuery);

// Refresh the latest tweets section and slide down new ones

function refreshTweets() {
	$.get('/latest', {since: latestTweet}, function(data) {
		$('.tweets').prepend(data);
		$('div.latest').slideDown('medium');
		$('.tweets div:gt(9)').slideUp();
			setTimeout(refreshTweets, 10000);
	});
}

// The tabs that are found under work

$(document).ready(function(){
	
	// case study thumb
	$('.thumb').hover(
		function() {
			$(this).addClass('thumb-hover');
		},
		function() {
			$(this).removeClass('thumb-hover');
		}
	); // end hover
});