//$ is taken somewhere, not sure where, but rolling with it.
var spinner, pullTweets;

(function($){
	
	$(function(){
		stickyFields();
		// setTimeout();
		//Search
		$(".archives .expand").click(function(){
			$("#footer").fadeOut(100);
			setTimeout('resizefunc(); fadeInFooter();', 700);
		});
		
		$(".search_icon").click(function(){
			if($(this).hasClass("active")){
				if($(this).val("Search")){
					return false;
				}
				document.getElementById("searchform").submit();
				return false;
			}else{
				searchResponder($(this));
			}
			
		});
		$("#searchField .close").click(function(){
			searchResponder($(this));
		});
		
		
		
		
		//
		if( $("ul.filters").length > 0 ) // the film grid page
		{
			$("h2.sortfiltertabs a").click(function(){
				var selectedClass = $(this).attr("id");
				
				$("h2.sortfiltertabs a.active").removeClass("active");
				$(this).addClass("active");
				$(".filters").addClass("hidden");
				$("." + selectedClass).removeClass("hidden");
				
				return false;
			});
			
			$('p.close a').click(function(){
				if($(this).hasClass("active")){
					$(this).removeClass("active");
					$(this).html("Close");
					$(".filterdrawer").removeClass('collapsed');
					$(".filterdrawer").slideDown(200, function(){ resizefunc(); });
				}else{
					$(this).addClass("active");
					$(this).html("Open");
					$(".filterdrawer").addClass('collapsed');
					$(".filterdrawer").slideUp(200, function(){ resizefunc(); });
				}
				
				return false;
			});
			
		}// the film grid page
		
		
		var yearTitles = $('.recipientsListing h2 a');
		if(yearTitles.length > 0)
		{
			slideAllFilmsUp()
			yearTitles.click(function(){
				var _ele = $(this);
				if(_ele.hasClass("expanded")){
					_ele.removeClass("expanded");
					$("#" + _ele.attr("rel")).slideUp(700, function(){ resizefunc(); });
				}else{
					_ele.addClass("expanded");
					$("#footer").fadeOut(100);
					setTimeout('resizefunc(); fadeInFooter();', 700);
					$("#" + _ele.attr("rel")).slideDown(700);
				}
				return false;
			});
		}
		
	});
	
	resizefunc = function(){
		if($(".content .info").length >= 1){
			var infoTop = $(".content .info").css("top").substr(0,$(".content .info").css("top").length-2)*1+90;
			if($(".content .blogSidebar").length){
				var height = ($(".content .info").height() > $(".content .blogSidebar").height()) ? 
					$(".content .info").height() : 	($(".content .blogSidebar").height() + 120);
			}else{
				var height = ($(".content .info").height() > $(".content .sidebar").height()) ? 
					$(".content .info").height() : 	$(".content .sidebar").height();
			}
			
			$("#wrapper").css({height: height+infoTop+"px"});
		}
	}
	fadeInFooter = function(){
		$("#footer").fadeIn(100);
	}
	resizefunc();
	
	searchResponder = function(element){
		var wrapper = $("#searchwrapper");
		var searchContainer = $('#searchField');
		var icon = $("#searchcontainer .search_icon");
		if(searchContainer.hasClass("hidden"))
		{
			//showing it now
			icon.addClass("active");
			searchContainer.removeClass("hidden");
			searchContainer.animate({ 'left': '-8px', }, 150);
		}
		else
		{
			//hiding it now
			icon.removeClass("active");
			searchContainer.animate({ 'left': '300px', }, 150, function(){
				searchContainer.addClass("hidden");
			});
		}
		
		return false;
	}
	
	slideAllFilmsUp = function(){
		$('.recipientsListing h2 a:first').addClass("expanded");
		$(".yeargroup:not(:first)").slideUp(200, function(){ resizefunc(); });
	}
	
	pullTweets = function(twitterName){
		var opts = {
		  lines: 10, // The number of lines to draw
		  length: 3, // The length of each line
		  width: 4, // The line thickness
		  radius: 9, // The radius of the inner circle
		  color: '#000', // #rgb or #rrggbb
		  speed: 1.3, // Rounds per second
		  trail: 65, // Afterglow percentage
		  shadow: false // Whether to render a shadow
		};
		var target = document.getElementById('loading');
		spinner = new Spinner(opts).spin(target);
		
		$.ajax({
		  url: 'http://search.twitter.com/search.json?q=from:' + twitterName,
			dataType: 'jsonp',
			type: 'GET',
			success: function( data ) {
				populateTwitterFeed(data.results);
				twttr.anywhere(function (T) {
					T("#twitterfeed").hovercards();
				});
			},
			error: function() { 
				alert("error"); 
			}
		});
	}
	
	
	function populateTwitterFeed(data){
		//clear spinner
		spinner.stop();
		
		var htmlContainer = $(".twitter-items");
		var template = htmlContainer.find("li:first-child");
		if(data.length < 1){
			htmlContainer.append('<li><p class="tweet_content">No current tweets available.</p></li>');
		}else{
			for(var i = 0, count = data.length; i < 3; i ++){
				if(data[i]){
					var item = template.clone();
					item.removeClass("hidden");

					var timeage = timeAgo(data[i].created_at, (new Date().getTime() / 1000), 4);
					if(!timeage){
						var _date = new Date(data[i].created_at);
						timeage = getMonthName(_date.getMonth()) + " " + _date.getDate() + ", " + _date.getFullYear()
					}

					item.find("p.ago").html('<a href="http://www.twitter.com/' + data[i].from_user + '/status/' + data[i].id_str + '" target="_blank">' + timeage + '</a>');
					item.find("p.tweet_content span.thecontent").html(linkify(data[i].text));
					htmlContainer.append(item);	
				}
			}
		}
		template.remove();
		$("#loading").remove();
	}
	
	
	
	function stickyFields(){       
		//store jQuery obj for Preformance
		var element = $('#search');
		//store their default value using "data( key, value )"
		element.data('defaultVal', element.val());
		//attach the focus and unfocus events.
		element.focus(function(){ fieldFocus(this) });
		element.blur(function(){ fieldBlur(this) });
		
	}
	
	function fieldFocus(element){
		var element = $(element);
		var defaultVal = element.data('defaultVal');
		//on focus, we test to see if the val = default val using "data(key)".
		if(element.val() == defaultVal){
			//if it is, clear the field.
			element.val('');
		}
	}

  function fieldBlur(element){
		var element = $(element);
		var defaultVal = element.data('defaultVal');
		//on blur, we test to see if val is blank.
		if(element.val() == '' || element.val() == ' '){
			//if it is, we set val to default using "data(key)".
			element.val( defaultVal );
		}
	}
	
	
})(jQuery);

function getMonthName(monthNum){
	var month = [
		'January',
		'February',
		'March',
		'April',
		'May',
		'June',
		'July',
		'August',
		'September',
		'October',
		'November',
		'December',
	]
	return month[monthNum];
}

linkify = function(tweet) {
	return tweet.replace(/\b(((https*\:\/\/)|www\.)[^\"\']+?)(([!?,.\)]+)?(\s|$))/g, function(link, m1, m2, m3, m4) {
		var http = m2.match(/w/) ? 'http://' : '';
		return '<a class="twtr-hyperlink" target="_blank" href="' + http + m1 + '" target="_blank">' + 
			((m1.length > 25) ? m1.substr(0, 24) + '...' : m1) + '</a>' + m4;
	});
}


//takes in two dates and sends back a string with the time that has elapsed
function timeAgo(date1, date2, granularity){
	var self = this;
	var ago = true;
	periods = [];
	periods['week'] = 604800;
	periods['day'] = 86400;
	periods['hour'] = 3600;
	periods['minute'] = 60;
	periods['second'] = 1;
	if(!granularity){
		granularity = 5;
	}
	(typeof(date1) == 'string') ? date1 = new Date(date1).getTime() / 1000 : date1 = new Date().getTime() / 1000;
	(typeof(date2) == 'string') ? date2 = new Date(date2).getTime() / 1000 : date2 = new Date().getTime() / 1000;
	if(date1 > date2){
		difference = date1 - date2;
	}else{
		difference = date2 - date1;
	}
	output = '';
	for(var period in periods){
		var value = periods[period];
		
		if(difference >= value){
			
			if(periods[period] >= 86400){
				ago = false;
				break;
			}
			
			
			time = Math.floor(difference / value);
			difference %= value;
			
			output = output +  time + ' ';
			
			if(time > 1){
				output = output + period + 's ';
			}else{
				output = output + period + ' ';
			}
		}
		granularity--;
		if(granularity == 0){
			break;
		}	
	}
	if(ago){
		output = output + 'ago'
	}else{
		output = false;
	}
	return output;
}



//Spinner http://fgnass.github.com/spin.js/
//fgnass.github.com/spin.js#v1.2
(function(a,b,c){function n(a){var b={x:a.offsetLeft,y:a.offsetTop};while(a=a.offsetParent)b.x+=a.offsetLeft,b.y+=a.offsetTop;return b}function m(a,b){for(var d in b)a[d]===c&&(a[d]=b[d]);return a}function l(a,b){for(var c in b)a.style[k(a,c)||c]=b[c];return a}function k(a,b){var e=a.style,f,g;if(e[b]!==c)return b;b=b.charAt(0).toUpperCase()+b.slice(1);for(g=0;g<d.length;g++){f=d[g]+b;if(e[f]!==c)return f}}function j(a,b,c,d){var g=["opacity",b,~~(a*100),c,d].join("-"),h=.01+c/d*100,j=Math.max(1-(1-a)/b*(100-h),a),k=f.substring(0,f.indexOf("Animation")).toLowerCase(),l=k&&"-"+k+"-"||"";e[g]||(i.insertRule("@"+l+"keyframes "+g+"{"+"0%{opacity:"+j+"}"+h+"%{opacity:"+a+"}"+(h+.01)+"%{opacity:1}"+(h+b)%100+"%{opacity:"+a+"}"+"100%{opacity:"+j+"}"+"}",0),e[g]=1);return g}function h(a,b,c){c&&!c.parentNode&&h(a,c),a.insertBefore(b,c||null);return a}function g(a,c){var d=b.createElement(a||"div"),e;for(e in c)d[e]=c[e];return d}var d=["webkit","Moz","ms","O"],e={},f;h(b.getElementsByTagName("head")[0],g("style"));var i=b.styleSheets[b.styleSheets.length-1],o=function q(a){if(!this.spin)return new q(a);this.opts=m(a||{},{lines:12,length:7,width:5,radius:10,color:"#000",speed:1,trail:100,opacity:.25,fps:20})},p=o.prototype={spin:function(a){this.stop();var b=this,c=b.el=l(g(),{position:"relative"}),d,e;a&&(e=n(h(a,c,a.firstChild)),d=n(c),l(c,{left:(a.offsetWidth>>1)-d.x+e.x+"px",top:(a.offsetHeight>>1)-d.y+e.y+"px"})),c.setAttribute("aria-role","progressbar"),b.lines(c,b.opts);if(!f){var i=b.opts,j=0,k=i.fps,m=k/i.speed,o=(1-i.opacity)/(m*i.trail/100),p=m/i.lines;(function q(){j++;for(var a=i.lines;a;a--){var d=Math.max(1-(j+a*p)%m*o,i.opacity);b.opacity(c,i.lines-a,d,i)}b.timeout=b.el&&setTimeout(q,~~(1e3/k))})()}return b},stop:function(){var a=this.el;a&&(clearTimeout(this.timeout),a.parentNode&&a.parentNode.removeChild(a),this.el=c);return this}};p.lines=function(a,b){function e(a,d){return l(g(),{position:"absolute",width:b.length+b.width+"px",height:b.width+"px",background:a,boxShadow:d,transformOrigin:"left",transform:"rotate("+~~(360/b.lines*c)+"deg) translate("+b.radius+"px"+",0)",borderRadius:(b.width>>1)+"px"})}var c=0,d;for(;c<b.lines;c++)d=l(g(),{position:"absolute",top:1+~(b.width/2)+"px",transform:"translate3d(0,0,0)",opacity:b.opacity,animation:f&&j(b.opacity,b.trail,c,b.lines)+" "+1/b.speed+"s linear infinite"}),b.shadow&&h(d,l(e("#000","0 0 4px #000"),{top:"2px"})),h(a,h(d,e(b.color,"0 0 1px rgba(0,0,0,.1)")));return a},p.opacity=function(a,b,c){a.childNodes[b].style.opacity=c},function(){var a=l(g("group"),{behavior:"url(#default#VML)"}),b;if(!k(a,"transform")&&a.adj){for(b=4;b--;)i.addRule(["group","roundrect","fill","stroke"][b],"behavior:url(#default#VML)");p.lines=function(a,b){function k(a,d,i){h(f,h(l(e(),{rotation:360/b.lines*a+"deg",left:~~d}),h(l(g("roundrect",{arcsize:1}),{width:c,height:b.width,left:b.radius,top:-b.width>>1,filter:i}),g("fill",{color:b.color,opacity:b.opacity}),g("stroke",{opacity:0}))))}function e(){return l(g("group",{coordsize:d+" "+d,coordorigin:-c+" "+ -c}),{width:d,height:d})}var c=b.length+b.width,d=2*c,f=e(),i=~(b.length+b.radius+b.width)+"px",j;if(b.shadow)for(j=1;j<=b.lines;j++)k(j,-2,"progid:DXImageTransform.Microsoft.Blur(pixelradius=2,makeshadow=1,shadowopacity=.3)");for(j=1;j<=b.lines;j++)k(j);return h(l(a,{margin:i+" 0 0 "+i,zoom:1}),f)},p.opacity=function(a,b,c,d){d=d.shadow&&d.lines||0,a.firstChild.childNodes[b+d].firstChild.firstChild.opacity=c}}else f=k(a,"animation")}(),a.Spinner=o})(window,document)
