willow.ready(function($) {
	// Menu data 
	var menuOptions = {direction:"up",showL3s:false,speed:1,reverseL2:false};
	willow.getMenu("148328|148329|148330|148331|148332",function(data){
		$('#L1').menu(data.menu,menuOptions);
	});
	
	// Emergency Bulletin 
	var emOptions = {emButtonPosition: "right",emButton: false};
	willow.getNews("14698",function(data){$('#Form1').bulletin(data,emOptions);},{"backlink":window.location});
	
	// Podium Search 
	$('#search').pdSearch({showButton:true, showButtonClass:'searchButton', showButtonText:''}); 
	$(".searchButton").css("margin","0");
	
	// Cycle top photo links
	$("#topLinks").cycle({timeout: 7000});
	
	// Cycle pager links
	$("#pLinks").cycle({pager:'#pager',timeout: 5000});
	
	// Cut the news detail off after 110 characters
	$(".newsDetail").fsplit(110);
	
	// Add a scroll bar to the events
	$(".eventsContainer").jScrollPane({verticalDragMaxHeight: 8, verticalDragMinHeight: 8});
	var fbDone = false;
	var twitDone = false;

	// Facebook wall feed, gets the JSON date and passes it through the jQuery template to build out the HTML
	willow.getFacebookToken(function(data){
		$.getJSON("https://graph.facebook.com/lreinyc/feed?callback=?",{limit:3,access_token:data.access_token},function(data) {
			var wall = data.data;
			for(var i = 0; i < 2; i++){ // Most recent wall posts
				if(typeof wall[i] != "undefined"){
					if(typeof wall[i].message !== "undefined"){
						$("#facebookTemplate").tmpl(wall[i],{// Template call
							fixTweetURLs : willow.replaceURLs, // Fixes URLs in wall post
							fixFacebookDate : willow.feedDate // Formats datetime from JSON string to format on homepage
						}).insertBefore("#smDivider");
					}
					else if(typeof wall[i+1].message !== "undefined"){
						$("#facebookTemplate").tmpl(wall[i+1],{// Template call
							fixTweetURLs : willow.replaceURLs, // Fixes URLs in wall post
							fixFacebookDate : willow.feedDate // Formats datetime from JSON string to format on homepage
						}).insertBefore("#smDivider");
					}
					else if(typeof wall[i+2].message !== "undefined"){
						$("#facebookTemplate").tmpl(wall[i+2],{// Template call
							fixTweetURLs : willow.replaceURLs, // Fixes URLs in wall post
							fixFacebookDate : willow.feedDate // Formats datetime from JSON string to format on homepage
						}).insertBefore("#smDivider");
					}// Else if statements are so in case there is no message in the wall post it checks the preivous two for messages
				}
			}
			// Check for adding scroll bar to feeds
			fbDone = true;
			if(twitDone && fbDone){
				$("#feedsContainer").jScrollPane({verticalDragMaxHeight: 8, verticalDragMinHeight: 8});
			}
		});
	});
	// Twitter feed, gets JSON data and passes it through the jQuery template to build out the HTML
	$.getJSON("https://search.twitter.com/search.json?callback=?&rpp=2&q=from:lrei",function(data){
        $.each(data, function(i, tweets){ // Two most recent tweets
            if (typeof tweets.length != "undefined"){
           		if (typeof tweets[0] != "undefined"){
           			if (typeof tweets[0].created_at != "undefined"){
           				$("#twitterTemplate").tmpl(tweets,{// Template call
							fixTweetURLs : willow.replaceURLs, // Fixes URLs in tweet
							fixTweetDate : willow.feedDate, // Formats datetime from JSON string to format on homepage
							fixEncodedHTML : willow.fixEncHTML // Fixes source JSON string showing where the tweet was from
						}).insertAfter("#smDivider");
           			}
           		}
           	}
        });
		// Check for adding scroll bar to feeds
		twitDone = true;
		if(twitDone && fbDone){
			$("#feedsContainer").jScrollPane({verticalDragMaxHeight: 8, verticalDragMinHeight: 8});
		}
    });
	// Add a scroll bar to the feeds
	//setTimeout(function(){$("#feedsContainer").jScrollPane({verticalDragMaxHeight: 8, verticalDragMinHeight: 8});},10000)
	
	// Brightcove video data
	// If the album within the Podium video group gets deleted that this was originally programed with, in order for the video to show
	// &playlist_id=760329125001 in the URL below needs to be updated with the proper playlist ID from Brightcove
	// 760329125001 is the original ID used for programming
	if($("#videoPlayer").length > 0){
		$.getJSON("https://api.brightcove.com/services/library?command=find_playlist_by_id&playlist_id=760329125001&token=DHTjdqknHqQqiOyybKdxmU78ShxjnyoQSjYgVNK1eb7Wd3wnLVRAgg..&callback=?",function(data){
			$( "#brightCoveTemplate" ).tmpl(data.videos[0]).appendTo("#videoPlayer").wrap(function(){
				// Function call to initalize video player, uses wrap function to call the createExperiences once the player is written to the page
				brightcove.createExperiences();
			});
		});
	}
	else{
		$.flickr.api({// Flickr API call to obtain photos
			apikey:"3f7b2776180fbbebb581bbcbf87beb71",
			apiObject:{
				method:"flickr.people.getPublicPhotos",
				user_id:"57343413@N08",
				extras: "url_sq",
				per_page: 8
			},
			callback:function(data){
				var photos = data.photos.photo;
				$("#flkrTmpl").tmpl(photos).appendTo("#topRow");
			}
		});
	}
	
	//Resize footer for smaller browser sizes
	var winWidth = $(window).width();
	if (winWidth < 1086){
		$("#footer")
			.css("width","988px")
			.css("margin","0");
		$("#lmSchool").css("margin-right","10px");
		$("#phone")
			.css("margin-left","10px")
			.css("margin-right","0");
	}
});

// Function to fix URLs inside tweets/wall posts
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;
}

// Function to check tweet source JSON string to see if it's HTML encoded
willow.isEncHTML = function(str){
	if(str.search(/&amp;/g) != -1 || str.search(/&lt;/g) != -1 || str.search(/&gt;/g) != -1 || str.search(/&quot;/g) != -1) 
		return true; 
	else 
		return false;
};

// Function to fix tweet source JSON string from encoded HTML to HTML structure to be written out by the jQuery template
willow.fixEncHTML = function(str){
	if(willow.isEncHTML(str)) 
	  return str.replace(/&amp;/g, '&').replace(/&lt;/g, '<').replace(/&gt;/g, '>').replace(/&quot;/g,"'"); 
	return str; 
};

// Function to format the datetime JSON string from tweets and wall posts to homepage style
willow.feedDate = function(date, bool){
	var months = ["January","February","March","April","May","June","July","August","September","October","November","December"];
	var feedDate = new Date(date);
	var tempDate = new Date(); // Need to initalize a valid date type variable for the setISO8601 function to work in IE
	var h = "", min = "", d = "", mon = "", AMPM = "PM", td = "";

	/*
	datetime JSON string from facebook is in IETF RFC 3339 datetime format which javascript does not natively support
	This checks to see if it's the facebook date coming in, and if it is runs the setISO8601 function to format it to a javascript
	native datetime Date object type
	*/
	if(bool === true){
		tempDate.setISO8601(date);// Use the tempDate varible when formating the datetime JSON string from Facebook, this is for it to work in IE
		feedDate = tempDate;// Once the datetime JSON string has been formated into a string Javascript can recognize as a Date object, set the feedDate to the datetime from Facebook
	}
	
	// Gets the hours, minutes, month, and date from date object
	h = feedDate.getHours();
	min = feedDate.getMinutes();
	mon = months[feedDate.getMonth()];
	d = feedDate.getDate();
	// If minutes is less then 10 add a zero to the beginning for 4:07 format instead of showing 4:7
	if(min < 10){
		min = "0"+min;
	}
	// Check hour time and converts from 24 hour time stamp to 12 hour AM/PM timestamp
	if(h < 12){
		AMPM = "AM";
		if(h == 0){
			h = "12";
		}
	}
	else if(h > 12){
		h = h-12;
	}
	
	// Converts date ojects to string and returns that string to show on the homepage
	td = h + ":" + min + " " + AMPM + " " + mon + " " + d;
    return  td;
}

/*
Function that converts the datetime JSON string from facebook from an IETF RFC 3339 datetime to a datetime string Javascript understands as a Date object
Searched google for answering this problem and found this function
http://dansnetwork.com/2008/11/01/javascript-iso8601rfc3339-date-parser/
January 6, 2011
*/

Date.prototype.setISO8601 = function(dString){
	var regexp = /(\d\d\d\d)(-)?(\d\d)(-)?(\d\d)(T)?(\d\d)(:)?(\d\d)(:)?(\d\d)(\.\d+)?(Z|([+-])(\d\d)(:)?(\d\d))/;

	if (dString.toString().match(new RegExp(regexp))) {
		var d = dString.match(new RegExp(regexp));
		var offset = 0;

		this.setUTCDate(1);
		this.setUTCFullYear(parseInt(d[1],10));
		this.setUTCMonth(parseInt(d[3],10) - 1);
		this.setUTCDate(parseInt(d[5],10));
		this.setUTCHours(parseInt(d[7],10));
		this.setUTCMinutes(parseInt(d[9],10));
		this.setUTCSeconds(parseInt(d[11],10));
		if (d[12])
			this.setUTCMilliseconds(parseFloat(d[12]) * 1000);
		else
			this.setUTCMilliseconds(0);
		if (d[13] != 'Z') {
			offset = (d[15] * 60) + parseInt(d[17],10);
			offset *= ((d[14] == '-') ? -1 : 1);
			this.setTime(this.getTime() - offset * 60 * 1000);
		}
	}
	else {
		this.setTime(Date.parse(dString));
	}
	return this;
};

