willow.tweetIndex = -1;
willow.videoCount = -1;
willow.audioCount = -1;

willow.videoData = {};
willow.videoDataLoaded = false;
willow.listClass = "even";

$(document).ready(function() {
	//search
	
	
	//flickr
	$.flickr.api({
		apikey:"33fd5b05871593ec5fba3fab455c3739",
	    apiObject:{
	    	method:"flickr.groups.pools.getPhotos",
	    	group_id:"1331260@N21"
	    },
	    callback:function(data){	    	
	    	var photos = data.photos.photo,
	    		photoString = "", 
	    		$flickrphotos = $(".flickrphotos");
	    	
	    	for(i = 0; i < photos.length; i++){
        		if(i === 6){
        			break;
        		}    			
        		$flickrphotos.append("<div class='flickr-photo'><a id='photo_"+photos[i].id+"' href='http://www.flickr.com/photos/"+photos[i].owner+"/"+photos[i].id+"/in/pool-1331260@N21' target='_blank'></a></div>");
        		
        		$.flickr.api({
					apikey:"33fd5b05871593ec5fba3fab455c3739",
				    apiObject:{
				    	method:"flickr.photos.getSizes",
				    	photo_id:photos[i].id
				    },
				    callback:function(data){
				    	$("#photo_"+this.apiObject.photo_id).append("<img src='"+data.sizes.size[0].source+"' border='0'/>").attr("href",data.sizes.size[3].source);
				 						    	
				    }
				});
        	}
	    }
	});
	
	setTimeout(function(){
		$(".flickr-photo a").fancybox({
			onComplete:function(){
				//fancybox additions
				$("#fancybox-content").after("<div class='fancy-footer clearfix'><a href='http://www.flickr.com/groups/1331260@N21/' target='_blank'>See more on Flickr</a></div>");
			},
			onCleanup:function(){
				$(".fancy-footer").remove();
			}
		});
		
	},2000);
	
	//podcast rss links
	$(".podcast .rss").hover(function(){
		$("#podcast-links").children("p").show();
	},function(){
		subscribeTimeout = setTimeout(function(){
			$("#podcast-links").children("p").hide();
		},250);
		
	});
	
	$("#podcast-links").hover(function(){
		clearTimeout(subscribeTimeout);
	},function(){
		subscribeTimeout = setTimeout(function(){
			$("#podcast-links").children("p").hide();
		},250);
		
	});
	
	//twitter stuff - using the jquery template plugin to make the markup easy to change
	//pulling from the public twitter list instead of the commented out search below.
	/*
	$.getJSON("http://api.twitter.com/1/proctoracademy/lists/proctor-campus-team/statuses.json?callback=?&per_page=4",function(tweets){
    	
        $( "#twitterTemplate" ).tmpl(tweets,{
        	alternate : function(){
		    	willow.tweetIndex++;
		    	
		    	var tweetClass= " tweet-"+willow.tweetIndex;
		    	
		    	return ($.inArray( this.data, tweets ) % 2) ? "tweet-odd" + tweetClass : "tweet-even" + tweetClass;
		    },
		    getTweetIndex : function(){
		    	return willow.tweetIndex;
		    },
		    fixTweetURLs : willow.replaceURLs,
		    fixTweetDate : willow.writeTweetDate
        }).appendTo(".tweets")
        .parent().css("height",function(){
            var height = $(this).height()-45;
            
            return height+"px";
        });
       
    });
	
	*/
	
	$.getJSON("http://search.twitter.com/search.json?callback=?&rpp=4&tag=proctoracademy",function(data){
    	if(typeof data.error !== "undefined"){
        	base.$el.html("error: " + data.error);
        	return;
        }
        $.each(data, function(i, tweets){
            if (typeof tweets.length != "undefined"){                   			
           		if (typeof tweets[0] != "undefined"){
           			if (typeof tweets[0].created_at != "undefined"){
           				//console.debug(tweets);
           				$( "#twitterTemplate" ).tmpl(tweets,{
           					alternate : function(){
								willow.tweetIndex++;
								
								var tweetClass= " tweet-"+willow.tweetIndex;
								
								return ($.inArray( this.data, tweets ) % 2) ? "tweet-odd" + tweetClass : "tweet-even" + tweetClass;
							},
							getTweetIndex : function(){
								return willow.tweetIndex;
							},
							fixTweetURLs : willow.replaceURLs,
							fixTweetDate : willow.writeTweetDate
           				}).appendTo(".tweets")
           				.parent().css("height",function(){
           					var height = $(this).height()-45;
           					
           					return height+"px";
           				});
           				
           			}
           		}
           	}
        });
    });
    
	
	//brightcove api calls
	//http://api.brightcove.com/services/library?command=find_playlist_by_id&playlist_id=123&token=OPVk6Uvw6cz2kZ_kAKv5vKmW4s1vFQ78yPhfucNQu-8PvhcRjbh5MQ..
		
	//new new video stuff
	willow.loadVideoData();
		
	//new audio stuff
	setTimeout(function(){
		willow.getAudio(17078,function(data){

			$( "#audioTemplate" ).tmpl(data.audio.files,{
				getCount : function(){
					willow.audioCount++;
					if(willow.audioCount < 4){
						return true;
					}
					return false;
				},
				returnCount : function(){
					return 	willow.audioCount;
				}

			}).appendTo("#audio");

			for(var i = 0; i < data.audio.files.length; i++){
				if(i > 3){return;}

				$("#player_"+i).jPlayer({
					ready: function () {
						$(this).jPlayer("setMedia", {
							mp3: "http://proctoracademy.org"+data.audio.files[$(this).attr("id").split("_")[1]].path
						});
					},
					cssSelectorAncestor:"#jp_interface_"+i,
					swfPath:"/script/plugins"
				}).bind($.jPlayer.event.play, function() {
					$(this).jPlayer("pauseOthers");
				});
			}
		});
		
	},2000);
	
		
	$('#search').pdSearch({showButton:true,showButtonText:""});
	
	willow.getNews("7936",function(data){
		//console.debug("testing: " + data);
		$('#Form1').bulletin(data,{
			emButtonPosition: "right",
			emButton: false
		});
	},{"backlink":window.location});
	
});

/*========loads the video templates on the homepage===========*/
willow.loadVideoTemplates = function(){
	//console.debug(willow.videoData);
	willow.mainVideo = Array();
	willow.videoArray = Array();
	for(var i = 0; i < willow.videoData.length; i++){
		if(i === 0){
			willow.mainVideo[willow.mainVideo.length] = willow.videoData[i].items[0];
		}else{
			willow.videoArray[willow.videoArray.length] = willow.videoData[i].items[0];
		}	
	}
	
	$( "#mainVideoTemplate" ).tmpl(willow.mainVideo,{
		checkWidth : function(width){
			if(width < 600){
				return 600;
			}
		}
	}).appendTo(".main-video");
		
	$( "#videoList" ).tmpl(willow.videoArray,{
		getVideoCount : function(){
			willow.videoCount++;
			if(willow.videoCount < 4){
				return true;
			}
			return false;
		},
		getClass : function(){
			if(willow.listClass === "even"){
				willow.listClass = "odd";
				return willow.listClass;
			}
			
			willow.listClass = "even";
			return willow.listClass;
		},
		checkWidth : function(width){
			if(width < 600){
				return 600;
			}
		}
	}).appendTo(".video-list");
		
	$(".fancy-atag").each(function(){
		var $obj = $(this);

	    var dWidth 	= parseInt($(this).attr('href').match(/width=[0-9]+/i)[0].replace('width=',''));
       	var dHeight = parseInt($(this).attr('href').match(/height=[0-9]+/i)[0].replace('height=',''));
	    
	    $obj.fancybox({
	    	onComplete:function(){
	    		//fancybox additions
	    		$("#fancybox-content").after("<div class='fancy-footer-video clearfix'><a href='/podium/default.aspx?t=52560' target='_blank'>Video Archive Page</a></div>");
	    	},
	    	onCleanup:function(){
	    		$(".fancy-footer-video").remove();
	    	},
	    	'width':dWidth,
	    	'height':dHeight,
	    	'autoScale'     	: false,
	    	'transitionIn'		: 'elastic',
	    	'transitionOut'		: 'elastic',
	    	'type'			: 'iframe'
	    });			
	});	
	
	$(".video-list li a .video-title").html(function(index,oldHTML){
		return oldHTML.substr(0,30);
	});
	$(".video-data .video-title").html(function(index,oldHTML){
		return oldHTML.substr(0,22);
	});
	
}

/*===========new video functions for data gathering=========*/
willow.loadVideoData = function(){
	willow.getVideoByAlbum(23038,function(data){
		willow.videoData = data.video.albums;
		for(var i = 0; i < willow.videoData.length; i++){
			willow.getVideoDataBC(willow.videoData[i].items[0]);
		}
	});
}
//gets the data, and when all data is collected we start splitting it up
willow.getVideoDataBC = function(obj){
	$.getJSON("http://api.brightcove.com/services/library?callback=?",{
	    command:"find_video_by_reference_id",
	    reference_id:obj.id,
	    token:"OPVk6Uvw6cz2kZ_kAKv5vKmW4s1vFQ78yPhfucNQu-8PvhcRjbh5MQ.."
	},function(data){
	    willow.dataLoadedCallback(obj.id,data);
	});
}
willow.dataLoadedCallback = function(id,data){
	if(willow.trafficCop(id,data)){
    	//if(!willow.videoDataLoaded){
    		//run some code to get all sizes of flickr photos  		
    		willow.loadVideoTemplates();
    		//willow.videoDataLoaded = true;
    	//}
    }
}
willow.trafficCop = function(id,data){
	for(var i = 0; i < willow.videoData.length; i++){
		if(id === willow.videoData[i].items[0].id){
			willow.videoData[i].items[0].bcloaded = true;
			willow.videoData[i].items[0].bcData = data;
		}
	}
	for(var i = 0; i < willow.videoData.length; i++){
		if(typeof willow.videoData[i].items[0].bcData === "undefined"){
			return false;
		}
	}
	return true;
}
/*===========new video functions for data gathering=========*/

willow.getAudio = function(id,callback){
	$.getJSON('/data/json.asp?type=audio&id=' + id,function(data){
		if($.isFunction(callback)){
	    	callback.call(this, data);
	    }else{
	    	console.debug("audio callback error");
	    }
	});
}

willow.getVideoByAlbum = function(id,callback){
	$.getJSON('/data/json.asp?type=videobyalbum&id=' + id,function(data){
		if($.isFunction(callback)){
	    	callback.call(this, data);
	    }else{
	    	console.debug("video callback error");
	    }
	});
}

willow.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;
}

willow.writeTweetDate = function(date){
	//alert(date);
	
	var months = ["January","February","March","April","May","June","July","August","September","October","November","December"];
	var tweetDate = new Date(date),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));
           
    //alert(tweetDate);
                           					
    if(minDiff < 59){
        timeDiff = minDiff+" minutes ago";
    }else if(hourDiff < 24){
        timeDiff = hourDiff+" hours ago";
    }else if(dayDiff < 5){
        timeDiff = dayDiff+" days ago";
    }else{
        var AMPM = "PM";
        var myHours;
        if(tweetDate.getHours() < 12){
        	AMPM = "AM";
        	if(tweetDate.getHours() == 0){
        		myHours = "12";
        	}else{
        		myHours = tweetDate.getHours();
        	}
        }else{
        	myHours = tweetDate.getHours()-12;
        }
        
        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";
        }
        timeDiff = myHours+":"+tweetDate.getMinutes()+"&nbsp;"+AMPM+"&nbsp;"+months[tweetDate.getMonth()]+"&nbsp;"+myDate;
    }
    return timeDiff;
};
