var allowEvents = true;

willow.ready(function($){
	var twitterAcnt = "schacademy";
	var anythingOptions = { // Builds anythign slider for photos
		buildNavigation: false,
		buildStartStop: false
	}
	
	$('#search').pdSearch({showButton: true,showButtonClass: 'searchButton',showButtonText: ''});//Podium Search
	$("#Form1").bulletin({
		showBarComplete:function(){
			$("#trayWrapper").animate({top:37});
			$("#headerWrapper").animate({"padding-top":74});
			$(".L2-container").css("top","164px");
		},
		data:[{type:"news",id:12850}]
	});// EM bulletin
	
	willow.getTweets(1, twitterAcnt, $("#tmplTweet"), $("#footer-tweet"), false); // Gets single tweet for footer section
	willow.getTweets(20, twitterAcnt, $("#scrollTmplTweet"), $("#scrollTweets"), true); // Gets tweets for tweet scroll section
	
	// You tube videos
	willow.youTube();
	$(".youTubeVideo").live("click", function() {
		$.fancybox({
				'padding'		: 0,
				'autoScale'		: false,
				'transitionIn'	: 'none',
				'transitionOut'	: 'none',
				'title'			: this.title,
				'width'		: 680,
				'height'		: 495,
				'href'			: this.href.replace(new RegExp("watch\\?v=", "i"), 'v/'),
				'type'			: 'iframe'
			});

		return false;
	});
	
	$("#newsiCast .newsEventDate").each(function(){
		$(this).html(willow.formatDate($(this).html(), true));
	});
	$("#events .newsEventDate").each(function(){
		$(this).html(willow.formatDate($(this).html(), true));
	});
	
	var startIdx = willow.GetRandomNumberBetween(0,($(".photo").length-1));
	$("#photos").cycle({timeout: 0, startingSlide: startIdx, next: $("#nextPhoto"), prev: $("#prevPhoto"), slideResize: 0, fx:'scrollVert'});
	
	$(".nextArrow, .prevArrow, #nextPhoto, #prevPhoto").click(function(e){e.preventDefault();});
	$("#newsArticles").cycle({timeout: 0, next: $("#nextStory"), prev: $("#prevStory")});
	$("#eventItems").cycle({timeout: 0, next: $("#nextEvent"), prev: $("#prevEvent")});
});

willow.youTube = function(){
	$.getJSON("https://gdata.youtube.com/feeds/api/videos?v=2&alt=jsonc&author=SpringsideViDCAST&max-results=5&orderby=published&callback=?",function(data){
		var videoCount = 0;
		$("#youTubeFeaturedTmpl").tmpl(data.data.items[0]).appendTo("#youTubeFeatured");
		$("#youTubeTmpl").tmpl(data.data.items,{
			firstVid : function(){
				videoCount++;
				if(videoCount >= 2){
					return true;
				}else{
					return false;
				}
			}
		}).appendTo("#youTubeLinks");
	});
};

// Function to get tweet data, takes number of tweets, account name, template name, append to id, and bool for scrolling tweets call
willow.getTweets = function(cnt, sn, $tmplObj, $apnd, scroll){
	// Twitter stuff in contact footer section
	$.getJSON("http://api.twitter.com/1/account/rate_limit_status.json?callback=?",function(data){
		if(parseInt(data.remaining_hits) > 0){
			$.getJSON("https://api.twitter.com/1/statuses/user_timeline.json?callback=?",{count:cnt,screen_name:sn,include_rts:1},function(data){
				var $tmplTweets = $tmplObj.tmpl( data,{
					replaceURLs : function(text){
						text = text.replace(/(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig,"<a href='$1' target='_blank'>$1</a>");
						text = text.replace(/(^|\s)@(\w+)/g,"$1<a class='user' href='http://www.twitter.com/$2' target='_blank'>@$2</a>");
						text = text.replace(/(^|\s)#(\w+)/g,"$1<a class='hashtag' href='http://search.twitter.com/search?q=%23$2' target='_blank'>#$2</a>");
						return text;
					},
					formatTwitterDate : willow.formatDate
				});
				$apnd.html($tmplTweets);
				if(scroll){willow.tweetScroll($tmplTweets);} // If tweets data was for scrolling section, add actions to tweets
			});
		}
	});
};

// Initializes position of tweets, takes jQuery array of tweet objects
willow.tweetScroll = function($tweets){
	for(var i = 0; i < $tweets.length; i++){
		var $curTweet = $tweets.eq(i);
		(i === $tweets.length-1 && $tweets.length > 3) ? $curTweet.css("left","-312px") : $curTweet.css("left",(i*$curTweet.width())+"px");
		willow.checkPosition($tweets, $curTweet);
	}
	// Creates click events if there are more then 3 tweets
	if($tweets.length > 3){
		// Sets up click events for moving tweets to the left
		$("#moveTweetsLeft").click(function(e){
			e.preventDefault();
			willow.moveTweetsLeft($(".scrollTweet"), 400);
		}).removeClass("hideEl");
		
		// Sets up click events for moving tweets to the right
		$("#moveTweetsRight").click(function(e){
			e.preventDefault();
			willow.moveTweetsRight($(".scrollTweet"), 400);
		}).removeClass("hideEl");
	}
};

// Updates classes on tweets to control what action is done on a move, takes all tweets for last position and single tweet object
willow.checkPosition = function($tweets, $tweet){
	var pos = $tweet.position().left,
		lastPos = ($tweets.length-2) * 312;

	switch(pos){
		case -312: $tweet.addClass("tweetLeft").removeClass("tweet_1 tweet_2 tweet_3 tweetRight tweetLast"); break;
		case 0: $tweet.addClass("tweet_1").removeClass("tweet_2 tweet_3 tweetRight tweetLeft tweetLast"); break;
		case 312: $tweet.addClass("tweet_2").removeClass("tweet_1 tweet_3 tweetRight tweetLeft tweetLast"); break;
		case 624: $tweet.addClass("tweet_3").removeClass("tweet_1 tweet_2 tweetRight tweetLeft tweetLast"); break;
		case 936: $tweet.addClass("tweetRight").removeClass("tweet_1 tweet_2 tweet_3 tweetLeft tweetLast"); break;
		case lastPos: $tweet.addClass("tweetLast").removeClass("tweet_1 tweet_2 tweet_3 tweetRight tweetLeft"); break;
		default: $tweet.removeClass("tweet_1 tweet_2 tweet_3 tweetRight tweetLeft tweetLast"); break;
	}
};

// Shifts tweets left function, takes jQuery array of tweet objects, and timing in milisecons to execute animations
willow.moveTweetsLeft = function($tweets, timing){

	for(var i = 0; i < $tweets.length; i++){
		var $curTweet = $tweets.eq(i);
		
		if($curTweet.hasClass("tweet_1") && allowEvents){
			var $tweet1 = $curTweet;
			allowEvents = false;
			$tweet1.fadeOut(timing, function(){
				$tweet1.css("left", "-312px");
				$tweet1.fadeIn(); // Need this so .position().left on the faded out tweet would be -312 instead of 0 for the checkPostion function
				if($tweets.length-2 == 2){ // if only 4 tweets
					$tweet1.siblings(".tweetLeft").css("left","936px").removeClass("tweetLeft").addClass("tweetRight");
				}else{
					$tweet1.siblings(".tweetLeft").css("left",(($tweets.length-2)*312)+"px");
				}
				$tweet1.siblings(".tweet_2").animate({left: "-=312"}, timing);
				$tweet1.siblings(".tweet_3").animate({left: "-=312"}, timing, function(){
					$tweet1.siblings(".tweetRight").css({"display":"none", "left":"624px"}).fadeIn(timing,function(){
						allowEvents = true;
						for(var j = 0; j < $tweets.length; j++){
							var $moveTweet = $tweets.eq(j);
							if(!$moveTweet.hasClass("tweet_1") && !$moveTweet.hasClass("tweet_2") && !$moveTweet.hasClass("tweet_3") && !$moveTweet.hasClass("tweetRight") && !$moveTweet.hasClass("tweetLeft")){
								$moveTweet.css("left",($moveTweet.position().left-312)+"px");
							}
							willow.checkPosition($tweets, $moveTweet);
						}
					});
				});
			});
		}
	}
};

// Shifts tweets left function, takes jQuery array of tweet objects, and timing in milisecons to execute animations
willow.moveTweetsRight = function($tweets, timing){
	for(var i = 0; i < $tweets.length; i++){
		var $curTweet = $tweets.eq(i);
			
		if($curTweet.hasClass("tweet_3") && allowEvents){
			var $tweet1 = $curTweet;
			allowEvents = false;
			$tweet1.fadeOut(timing, function(){
				$tweet1.css("left", "936px");
				$tweet1.fadeIn(); // Need this so .position().left on the faded out tweet would be 936 instead of 0 for the checkPostion function
				if($tweets.length-2 == 2){ // if only 4 tweets
					$tweet1.siblings(".tweetRight").css("left","-312px").removeClass("tweetRight").addClass("tweetLeft");
				}else{
					$tweet1.siblings(".tweetLast").css("left","-312px");
				}
				$tweet1.siblings(".tweet_2").animate({left: "+=312"}, timing);
				$tweet1.siblings(".tweet_1").animate({left: "+=312"}, timing, function(){
					$tweet1.siblings(".tweetLeft").css({"display":"none", "left":"0"}).fadeIn(timing,function(){
						allowEvents = true;
						for(var j = 0; j < $tweets.length; j++){
							var $moveTweet = $tweets.eq(j);
							if(!$moveTweet.hasClass("tweet_1") && !$moveTweet.hasClass("tweet_2") && !$moveTweet.hasClass("tweet_3") && !$moveTweet.hasClass("tweetLast") && !$moveTweet.hasClass("tweetLeft")){
								$moveTweet.css("left",($moveTweet.position().left+312)+"px");
							}
							willow.checkPosition($tweets, $moveTweet);
						}
					});
				});
			});
		}
	}
};

willow.formatDate = function(date, isNews){
	var months = {
		abbr:["jan","feb","mar","apr","may","june","july","aug","sept","oct","nov","dec"],
		full:["janruary","february","march","april","may","june","july","august","september","october","november","december"]
	};
	var tweetDate;
	
	($.browser.msie && !isNews) ? tweetDate = new Date(parseTweetDateForIE(date)) : tweetDate = new Date(date);
	
	var today = new Date(),timeDiff = "",
	minDiff = Math.ceil((today.getTime()-tweetDate.getTime())/(60*1000)),
	hourDiff = Math.ceil((today.getTime()-tweetDate.getTime())/(60*60*1000)),
	dayDiff = Math.ceil((today.getTime()-tweetDate.getTime())/(24*60*60*1000)),
	monthDiff = Math.floor((today.getTime()-tweetDate.getTime())/(30*24*60*60*1000));
	

	if(isNews){
		if(minDiff < 59){
			timeDiff = minDiff+" minutes ago";
		}else if(hourDiff < 24){
			timeDiff = hourDiff+"h";
		}else if(dayDiff < 7){
			timeDiff = dayDiff+"d";
		}else if(dayDiff < 14){
			timeDiff = "1w - 2w"
		}else if(dayDiff < 21){
			timeDiff = "2w - 3w"
		}else if(dayDiff < 30){
			timeDiff = "3w - 1m"
		}else{
			timeDiff = monthDiff+"m";
		}
	}else{
		if(minDiff < 59){
			timeDiff = minDiff+" minutes ago";
		}else if(hourDiff < 24){
			timeDiff = hourDiff+"h";
		}else if(dayDiff < 5){
			timeDiff = dayDiff+"d";
		}else{
			var AMPM = "PM";
			var myHours;
			if(tweetDate.getHours() < 12){
				AMPM = "AM";
				if(tweetDate.getHours() == 0){
					myHours = "12";
				}else{
					myHours = tweetDate.getHours();
				}
			}else if (tweetDate.getHours() > 12){
				myHours = tweetDate.getHours()-12;
			}
			else{
				myHours = tweetDate.getHours();
			}

			var myDate = tweetDate.getDate() +"th";
			if(tweetDate.getDate() == 1 || tweetDate.getDate() == 21 || tweetDate.getDate() == 31){
				myDate = tweetDate.getDate() +"st";
			}else if(tweetDate.getDate() == 2 || tweetDate.getDate() == 22){
				myDate = tweetDate.getDate() +"nd";
			}else if(tweetDate.getDate() == 3 || tweetDate.getDate() == 23){
				myDate = tweetDate.getDate() +"rd";
			}
			
			var min = 0;
			(tweetDate.getMinutes() < 10) ? min = "0"+tweetDate.getMinutes() : min = tweetDate.getMinutes();
			timeDiff = myHours+":"+min+" "+AMPM+" "+months.abbr[tweetDate.getMonth()]+" "+myDate;
		}
	}
	return timeDiff;
};

function parseTweetDateForIE(str) {
  var v=str.split(' ');
  return new Date(Date.parse(v[1]+" "+v[2]+", "+v[5]+" "+v[3]+" UTC"));
};

