/* Author:
* Kerrick Long, Web Design & Support, SoutheaslideTime Missouri slideTimeate University
* 
* Edited:
* 2011-05-13
*/
// Winter Snow
//$(document).ready(function(){
//	document.write(unescape('%3Cscript src="http://code.google.com/p/open-source-jquery-snow/downloads/detail?name=snow.js&can=2&q="%3E%3C/script%3E'));
//});
$(document).ready( function() {
	/*
	 * Set up the pageIdLink to show the ID rather than scroll to it
	 */
	$('#pageIdLink').unbind('click').attr('title', 'Click to show the RedDot Page ID').click(function() {
		$(this).css({width: '60px', height: '20px', color: 'black', background: 'white', border: '2px solid black', textIndent: '0', textAlign: 'center', textDecoration: 'none', overflow: 'visible'}).html(document.getElementById('redDotPageID').innerHTML).removeAttr('href').attr('title', 'RedDot Page ID');
		return false;
	});
	/*
	 * Set up the Organic Tabs plugin.
	 */
	if(document.getElementById('newsetc'))
		$('.tabbed').organicTabs();
	/*
	 * Fix any img tags that are missing their height or width.
	 */
	var fixImageAttributes;
	fixImageAttributes = document.getElementsByTagName('img');
	for (var i = fixImageAttributes.length - 1; i >= 0; --i) {
		var thisImage = fixImageAttributes[i];
		if (thisImage.getAttribute('width') == null) {
			thisWidth = $(thisImage).width();
			if (thisWidth > 0) {
				thisImage.setAttribute('width',thisWidth);
			}
		}
		if (thisImage.getAttribute('height') == null) {
			thisHeight = $(thisImage).height();
			if (thisHeight > 0) {
				thisImage.setAttribute('height',thisHeight);
			}
		}
	}
	/*
	 * Find any element with the data-href attribute and make that clickable.
	 */
	 $('*[data-href]').click(function(){
	 	window.location = $(this).attr('data-href');
	 	return false;
	 });
	 
	 /**
	  * If there is a twitter container, grab tweets for it.
	  */
	var twitterContainer = $('*[data-twitter]').first()[0];
	if(twitterContainer) {
		var twitterUsername = twitterContainer.getAttribute('data-twitter');
		twitterContainer.innerHTML = '<ol></ol>'
		$.getJSON('http://api.twitter.com/1/statuses/user_timeline.json?screen_name=' + twitterUsername + '&count=5&trim_user=1&callback=?', function(tweetdata) { 
			var twitterList = $('ol',twitterContainer).first();
			$.each(tweetdata, function(i,tweet) {
				twitterList.append('<li id="twitter-' + twitterUsername + '-' + tweet.id_str + '"><a href="http://twitter.com/' + twitterUsername + '/status/' + tweet.id_str + '"><h3>' + tweet.text + '</h3><time datetime="' + tweet.created_at + '">' + prettyDate(tweet.created_at) + '</time></a></li>')
			});
			twitterList.append('<li id="twitter-' + twitterUsername + '-linkToMore"><a href="http://twitter.com/' + twitterUsername + '"><h3>View ' + twitterUsername + '&rsquo;s Twitter profile</h3><time rel="always">Go to twitter.com/' + twitterUsername + '</time></a></li>');
		});
	}
	
	/**
	  * If there is a youtube container, grab videos for it.
	  * API: http://code.google.com/apis/youtube/2.0/developers_guide_protocol_api_query_parameters.html
	  */
	var youtubeContainer= $('*[data-youtube]').first()[0];
	if(youtubeContainer) {
		var youtubeUsername = youtubeContainer.getAttribute('data-youtube');
		youtubeContainer.innerHTML = '<ol></ol>'
		$.getJSON('http://gdata.youtube.com/feeds/api/users/' + youtubeUsername + '/uploads?v=2&alt=jsonc&max-results=5&callback=?', function(videodata) { 
			var youtubeList = $('ol',youtubeContainer).first();
			$.each(videodata.data.items, function(i) {
				youtubeList.append('<li id="youtube-' + youtubeUsername + '-' + videodata.data.items[i].id + '"><a href="' + videodata.data.items[i].player["default"] + '"><img width="60" height="45" src="' + videodata.data.items[i].thumbnail.sqDefault + '" /><h3>' + videodata.data.items[i].title + ' (' + Math.floor(videodata.data.items[i].duration/60) + ':' + pad(videodata.data.items[i].duration % 60, 2) + ')</h3><time datetime="' + videodata.data.items[i].uploaded + '">' + prettyDate(videodata.data.items[i].uploaded) + '</time></a></li>')
			});
			youtubeList.append('<li id="youtube-' + youtubeUsername + '-linkToMore"><a href="http://www.youtube.com/' + youtubeUsername + '"><h3>View ' + youtubeUsername + '&rsquo;s YouTube channel</h3><time rel="always">Go to www.youtube.com/' + youtubeUsername + '</time></a></li>')
		});
	}
	
	/**
	 * If there is a facebook container, grab posts for it.
	 */
	var facebookContainer= $('*[data-facebook]').first()[0];
	if(facebookContainer) {
		var facebookUsername = facebookContainer.getAttribute('data-facebook');
		facebookContainer.innerHTML = '<ol></ol>';
		$.getJSON('https://graph.facebook.com/' + facebookUsername + '/posts?limit=5&callback=?&access_token=210101972361115|ycrv1fIxL3J0k5PXX-u-cSp-v80', function(posts) { 
			var facebookList = $('ol',facebookContainer).first();
			$.each(posts.data, function(i) {
				var comments = '';
				if (posts.data[i].comments) {
					var word = (posts.data[i].comments.count > 1) ? ' comments' : ' comment';  
					var comments = ' &bull; ' + posts.data[i].comments.count + word;
				}
				var likes = '';
				if (posts.data[i].likes) {
					var word = (posts.data[i].likes.count > 1) ? ' likes' : ' like';
					 var likes = ' &bull; ' + posts.data[i].likes.count + word;
				}
				facebookList.append('<li id="facebook-' + facebookUsername + '-' + posts.data[i].id.split('_')[1] + '"><a href="http://www.facebook.com/' + facebookUsername + '/posts/' + posts.data[i].id.split('_')[1] + '"><h3>' + posts.data[i].message + '</h3><time datetime="' + posts.data[i].created_time + '">' + prettyDate(posts.data[i].created_time) + comments + likes + '</time></a></li>')
			});
			facebookList.append('<li id="facebook-' + facebookUsername + '-linkToMore"><a href="http://www.facebook.com/' + facebookUsername + '"><h3>View ' + facebookUsername + '&rsquo;s Facebook page</h3><time rel="always">Go to www.facebook.com/' + facebookUsername + '</time></a></li>')
		});
	}
	
	/**
	 * If there is a news container, grab stories for it.
	 */
	var newsContainer = $('*[data-news]').first()[0];
	if(newsContainer) {
		var newsURL = 'http://www.semo.edu/xdomain.php?dataType=application%2Frss%2Bxml&url=' + encodeURIComponent(newsContainer.getAttribute('data-news'));
		newsContainer.innerHTML = '<ol></ol>';
		var newsList = $('ol',newsContainer).first();
		$.ajax({
			url: newsURL,
			cache: false,
			type: 'GET',
			dataType: 'xml',
			success: function(data) {
				var showHowMany = 5;
				$(data).find('item').each(function(){
					var item = $(this);
					var link = item.find('guid').text();
					var title = item.find('title').text();
					var time = new Date(item.find('pubDate').text());
					var isoTime = time.getFullYear() + '-' + pad(time.getMonth() + 1,2) + '-' + pad(time.getDate(),2) + 'T' + pad(time.getHours(),2) + ':' + pad(time.getMinutes(),2) + '-06:00';
					var prettyTime = prettyDate(time.getFullYear() + '-' + pad(time.getMonth() + 1,2) + '-' + pad(time.getDate(),2) + 'T' + pad(time.getHours(),2) + ':' + pad(time.getMinutes(),2));
					newsList.append('<li><a href="' + link + '"><h3>' + title + '</h3><time datetime="' + isoTime + '">' + prettyTime + '</time></a></li>');
					showHowMany--;
					if(showHowMany == 0) return false;
				});
				newsList.append('<li><a href="' + $(data).find('link').first().text() + '"><h3>View the news website</h3><time rel="always">Go to ' + $(data).find('link').first().text() + '</time></a></li>');
			},
			error: function(data) {
				newsList.append('<li>Error loading news posts</li>')
			}
		});
	}
	
	/**
	 * If there is a calendar container, grab events for it.
	 */
	var calendarContainer = $('*[data-calendar]').first()[0];
	if(calendarContainer) {
		var calendarURL = 'http://www.semo.edu/xdomain.php?dataType=text&url=' + encodeURIComponent(calendarContainer.getAttribute('data-calendar'));
		calendarURL = calendarURL.replace('webcal','http');
		calendarContainer.innerHTML = '<ol></ol>';
		var calendarList = $('ol',calendarContainer).first();
		$.ajax({
			url: calendarURL,
			cache: false,
			type: 'GET',
			dataType: 'text',
			success: function(data) {
				var showHowMany = 5;
				var calendar = $.icalendar.parse(data);
				var monthsOfYear = ['Jan.','Feb.','March','April','May','June','July','Aug.','Sep.','Oct.','Nov.','Dec.'];
				$.each(calendar.vevent, function() {
					if (this.summary !="undefined"){
						var item = this;
						var link = 'http://calendar.semo.edu/main.php?calendarid=default&view=event&eventid=' + this.uid.split('@')[0];
						var title = this.summary;
						var time = new Date(this.dtstart);
						if(monthsOfYear[time.getMonth()] == undefined) time = this.dtstart._value;
						var isoTime = time.getFullYear() + '-' + pad(time.getMonth() + 1,2) + '-' + pad(time.getDate(),2) + 'T' + pad(time.getHours(),2) + ':' + pad(time.getMinutes(),2) + '-06:00';
						var prettyTime = monthsOfYear[time.getMonth()] + ' ' + time.getDate() + ' at ' + pad(time.getHours(),2) + ':' + pad(time.getMinutes(),2);
						calendarList.append('<li><a href="' + link + '"><time datetime="' + isoTime + '">' + prettyTime + '</time>' + title + '</a></li>');
						showHowMany--;
						if(showHowMany == 0) return false;
					}
				});
				calendarList.append('<li><a href="http://calendar.semo.edu/main.php?calendarid=default&view=month"><time rel="this-month">View more events</time>View the Southeast online Master Calendar</a></li>');
			},
			error: function(data) {
				calendarList.append('<li>Error loading calendar items</li>')
			}
		}); 
	};
	
});
/*
 * Here is the slideshow code.
 */
 
 // Screw ie7...
if ( !($.browser.msie && $.browser.version <= 7.0) ){
	if(document.getElementById('slideshow')) {
		var sliderCount = 1;
		var pictureHeight = 376;
		var toSlide = 1;
		var slideTime = pictureHeight;
		function slide(ms) {
			if(sliderCount < 4 && toSlide === 1) {
				sliderCount++;
				slideAmount = -(sliderCount - 1) * pictureHeight;
			} else if(toSlide === 1) {
				sliderCount = 1;
				slideAmount = 0;
			}
			$('#slideshow .current').removeClass('current');
			$('#slideshow dt:not(.controls)').stop()/*.animate({'opacity':0},ms)*/.animate({'top':slideAmount},ms, function() {
				//$('#slideshow dt:not(.controls)').animate({'opacity':1},ms);
				//Uncomment the line above and the bit of the line above that to use opacity rather than sliding.
			});
			$('#slideshow #slideControl'+sliderCount).addClass('current');
			$('#slideshow dd').fadeOut(.25 * ms);
			$('#slideDescription'+sliderCount).fadeIn(2 * ms);
		}
		function autoSlide(ms) {
			if(toSlide === 1) {
				slide(ms);
				setTimeout ( 'autoSlide(slideTime)', 5000 );
			}
		}
		$(document).ready( function() {
			setTimeout ( 'autoSlide(slideTime)', 5000 );
			$('#slideshow img[data-youtubeid]').click( function() {
				var youtubeId = $(this).attr('data-youtubeid');
				toSlide = 0;
				$(this).parent().html('<iframe width="549" height="366" src="http://www.youtube.com/embed/' + youtubeId + '?autoplay=1&rel=0&fs=1&iv_load_policy=1&modestbranding=0&showinfo=0&theme=dark"></iframe>');
			});
			$('#slideshow .controls').click( function() {
				toSlide = 0;
				var slideNumberid = this.id.split('slideControl');
				sliderCount = slideNumberid[1];
				slideAmount = -(sliderCount - 1) * pictureHeight;
				slide(slideTime);
				return false;
			});
			//$('#slideshow dd').mouseenter(function() { toSlide = 0; }).mouseleave(function() { toSlide = 1; });
		});
	}
};

//<h4> Expand/Collapse Script
//Author: Dean Kelly
//Last Edited: 1/24/2012
$(document).ready(function(){
		$('.expanders h4').addClass('expand');
		$('.expand').each(function(i){
            if($(this).hasClass('collapsed')!=true){
				$(this).nextUntil('h4, h3').wrapAll('<div></div>');};
			$(this).addClass('collapsed');});
        $('.expand:not(:has(a))').wrapInner('<a></a>').next().prepend('<hr/>').append('<hr/>');
        $('.expand').has('a:not([href])').next().hide();
        $('.expand').click(function(event){
            if ($(this).next().hasClass('open')==true) {
                $('.open').stop(true, true).slideUp(500).removeClass('open');   }
            else {
                $('.open').stop(true, true).slideUp(500).removeClass('open');
                $(this).next().slideDown(500).addClass('open');   };  
        });});

