// Main js file for www.unmc.edu.
// TODO: Move all of this into a object literal. 

/** Initialises the "Breakthroughs for life" story section at the top left of the main page.**/
function initLargeNews() {
		// All anchor tags on the left side.
	var $largeNewsLinks 	= $("#faid-tabs-nav").find("a"), 
		
		// All divs that are linked to the anchor tags.
		$largeNewsImages 	= $(".sub .tab"), 

		// Used to display a random starting story on page load.
		randomFrontStory 	= 0;//Math.floor(Math.random() * $largeNewsLinks.length); 

	// Set the randomly selected story to active and display it.
	$largeNewsLinks.eq(randomFrontStory).addClass("active");
	$largeNewsImages.eq(randomFrontStory).addClass("active").stop().show();

	$largeNewsLinks.click( function(event) {
		event.preventDefault();

			// Sets the index of the story that was clicked to a variable.
		var $storyClicked = $(this).attr("href").replace("#tab", "") - 1, 

			//Used to determine if the user selected a story that is already active.
			$activeStory  = $largeNewsLinks.filter(".active").attr("href").replace("#tab", "") - 1; 

		// Check to see that the user didn't press the story that is already active.
		// deactivate the old story, fade it out, then active and fade in the new one
		if ($storyClicked !== $activeStory) {
			$largeNewsLinks.filter(".active").removeClass("active");
			$largeNewsImages.filter(".active").removeClass("active").fadeOut();
			$largeNewsLinks.eq($storyClicked).addClass("active");
			$largeNewsImages.eq($storyClicked).addClass("active").fadeIn();
		}
	});
}

// Initializes the top right promo box on the page (3 tabs).
function initTabs() {
	var $tabs 		= $(".tabs ul.tabset .tab"), 
		$tabContent = $(".tab-holder #tabBox1, .tab-holder #tabBox2, .tab-holder #tabBox3");
	
	// Set first tab and it's content to active.
	$tabs.eq(0).addClass("active"); 

	// Show the content within the first tab box. 
	$tabContent.hide().eq(0).show();

	// Click listener for the three tabs.
	$tabs.click( function(event) {
		var $this = $(this),
		$tabSelectedIndex = $this.attr("href").replace("#tabBox", "") - 4,
		$currentContentIndex = null;

		// Used to find the current content box being displayed.
		$.each($tabContent, function(index) {
			if ($(this).css('display') === 'block') {
				$currentContentIndex = index;
			}
		});

		// Changes to the tab that the user selects. 
		if ($tabSelectedIndex !== $currentContentIndex) {
			$tabs.filter(".active").removeClass("active");
			$this.addClass("active");
			$tabContent.hide().eq($tabSelectedIndex).fadeIn(); 
		}

		event.preventDefault();
	});
}

function initGall(random) {
	var $imageDesc 	= $("#gallery .text"),//All Descriptions
		$images 	= $("#gallery .image"),	//All Images
		randImage;

	// Housekeeping to prevent duplication. 
	$imageDesc.hide();
	$images.hide();
	$("#gallery .prev, #gallery .next").unbind('click');
	
	//Allows users to control if their slide show is randomized. 
	if (random === 'Off') {
		randImage = 0;
	}
	else {
		randImage = Math.floor(Math.random() * $images.length); //Random Image to initially display.
	}

	// Show a random image with it's description text.
	$images.eq(randImage).addClass("active").fadeIn();
	$imageDesc.eq(randImage).addClass("active").fadeIn();

	// Event listener for the next button on the gallery. 
	$("#gallery .prev, #gallery .next").click( function(event) {
		event.preventDefault();

		// Current image with description and index for each.
		var $curImg = $images.filter(".active"),
		$curDesc = $imageDesc.filter(".active"),
		$curImgIndex = $images.index($curImg),
		$curDescIndex = $imageDesc.index($curDesc);

		// Fade out image and hide it's desc.
		$curImg.removeClass("active").fadeOut();
		$curDesc.removeClass("active").hide();

		// Check to see which button was pressed (next or prev)
		if ($(this).attr("class") === "prev") {
			prevImage();
		} else {
			nextImage();
		}

		// Switch to the last image.
		function prevImage() {
			// If it's the first image, go to the end of the show.
			if ($curImgIndex === 0) {
				$images.eq($images.length - 1).addClass("active").fadeIn();
				$imageDesc.eq($images.length - 1).addClass("active").show();
			} else {
				$images.eq($curImgIndex - 1).addClass("active").fadeIn();
				$imageDesc.eq($curDescIndex - 1).addClass("active").show();
			}
		}

		// Switch to the next image.
		function nextImage() {
			// If it's the last image, go to the beginning of the show.
			if ($curImgIndex === $images.length - 1) {
				$images.eq(0).addClass("active").fadeIn();
				$imageDesc.eq(0).addClass("active").show();
			} else {
				$images.eq($curImgIndex + 1).addClass("active").fadeIn();
				$imageDesc.eq($curDescIndex + 1).addClass("active").show();
			}
		}

	});
}


// News Feed Portlet - Take a provided feed URL and then parse everything to display nicely in our news box (body or side).
function wwwNewsFeed(feedUrl,limit,portletType, target) {
	$.getJSON(feedUrl, function (data) {
		var $rssFeed 	= data.rss.channel.item,
			$newsFeed 	= $('#newsFeed');

		// Go through each item (up to the limit) and everything to it's proper variables. 
		// Then, depending on the type that is passed, append each one to the proper class/id. 
		// The variable "target" is used to prevent duplication if the users adds more than one news feed. 
		$.each($rssFeed.slice(0, limit), function () {
			var title 	 = this.title,
				desc  	 = portletType === 'body' ? truncateString(this.description, 45) : truncateString(this.description, 80),
				link  	 = this.link,
				image 	 = this.unmcimage,
				category = this.category;
			if (image === undefined || image.indexOf('dev') !== -1) {
				image = 'http://www.unmc.edu/wwwimages/news_placeholder.jpg';
			}

			// Body Portlet //
			if (portletType === 'body') {
				if (!target) {
					target = '.news ul';
				}
				$(target).append('<li><a href="'+ link +'" alt="'+ title +'">' + title + '</a><br />' + desc + '</li>');
			// /Body Portlet //

			// Sidebar Portlet //
			} else if (portletType === 'side') {
				if (!target) {
					target = '.research-news ul';
				}
				$(target).append('<li><a href="'+ link +'" alt="'+ title +'">' + title + '</a></li>');
			// /Sidebar Portlet //

			// This is what is used on WWW to display the news. 
			} else {
				$('<div class="box"></div>').append('<h4>' + category + '</h4><div><a href="' + link + '"><img src="' + image + '" alt="' + title + '"/></a></div><ul><li><a href="' + link + '">' + title + '</a></li><li class="desc">' + desc + '</li></ul>').appendTo($newsFeed);
			}
		});
	});
}


// Calendar Feed Portlet - Take a provided feed URL and then parse everything to display nicely in our calendar box (body or side).
function wwwEventFeed(feedUrl,limit,portletType) {
	$.getJSON(feedUrl, function (data) {
		var $rssFeed = data.rss.channel.item.slice(0, limit);
		if ($rssFeed !== undefined) {
			var feedLength = $rssFeed.length;

			$.each($rssFeed, function (i) {
				var title  	= truncateString(this.title.split(' - ')[1], 70),
				timeAndDate = this.title.split(' - ')[0].replace(/\b\d{4}\b/, ''),
				date		= timeAndDate.split(',')[0].replace(/^\s+|\s+$/g,""),
				time		= timeAndDate.split(',')[1].replace(/^\s+|\s+$/g,""),
				desc  		= this.description,
				link  		= this.link;
				
				if (!time) { time = 'All Day'; }
				
				if (portletType === 'side') {
					var $eventsPortlet = $('.events-portlet'), last = '';
					if(i === feedLength - 1) {last = ' class="last"';}
						$($eventsPortlet).find('.list').append('<li'+ last +'><a href="'+ link +'">'  + title + '</a><br />' + date + ' | ' + time + '</li>');
				} else {
						var $calendarFeed = portletType === 'body' ? $('.container .calendar') : $('.events .content');
						$('<div class="eventline"></div>').append('<div class="timedate"><p>' + 
							date + '</p><p class="time">' + 
							time + '</p></div><div class="title"><a href="' + link + '">' + 
							title + '</a></div><div class="cf"></div>').appendTo($calendarFeed);
					}
			});
		} else {
        	if (portletType === 'side') {
				var $eventsPortlet = $('.events-portlet'), url = location.href;
				if(url.toLowerCase().indexOf('reddot') !== -1) {
       				 $($eventsPortlet).find('.list').append('<li><p>There are no current events in your calendar.</p><p>Please visit <a href="http://cal.unmc.edu">cal.unmc.edu</A> to add events.</p></li>');
     			} else {
        			$($eventsPortlet).find('.list').append('<li>No current events at this time</li>');
				 }
					
			}
		}
	});
}

// Used by the wwwEventFeed and wwwNewsFeed functions to cut down on string length easily.  
function truncateString(targetString, charLimit) {
	if (targetString.length > charLimit) {
		return $.trim(targetString.substring(0, charLimit).replace(/\s*[^\s]+$/, '')) + "...";
	} else {
		return targetString
	}
}

//Takes a grouping of images that have the random-img class and shows a random one on page load. 
function randomImg(){
	var $images = $(".random-img").find("img"),
	imagesIndex = Math.floor(Math.random() * $images.length);
	$images.eq(imagesIndex).attr('style', 'display:block !important');
}

/** Hides the inline search label when the input is focused **/
function searchToggle() {
	$('#searchui').focus(function(){
		$this = $(this);
		if($this.val() === 'Search') {
			$this.val('');
		}
	});

	$('#searchui').blur(function(){
		var $this = $(this);
		if($this.val() === '') {
			$this.val('Search');
		}
	});
}

/** Checks the url or breadcrumb to highlight the currently selected green tab**/
function greenTabHack() {
	var path = window.location.pathname,
		$tabs = $('.main-nav ul a'),
		$breadcrumbs = $('.breadcrumbs a, .breadcrumb a');

	$.each($tabs, function(){
			var $tab  = $(this);

		if ($tab.attr('href') === path) {
			$tab.addClass('currentTab');
		} 

		$.each($breadcrumbs, function() {
			if($(this).text() === $tab.text()) {
				$tab.addClass('currentTab');
			}
		});
	});
}

$(document).ready( function() {
	randomImg();
	initGall();
	searchToggle();
	greenTabHack();
});
