jcc.home = new JCC_Home();
$(document).ready(function() {
		setTimeout(jcc.home.init, 50);
	
	twitter_search();
});

function JCC_Home() {
	var featured;
	var rotator;
	
	this.init = init;
	function init() {
		setupFeatured('#featured-stories');
		setupRotator('#rotator');
		setupTabs();
		$('#page-sidebar2 > div.scroller ul.panel').each(function() {
			jcc.setupAlternateStyles($(this), '> li');
		});
	}
	
	this.getFeatured = getFeatured;
	function getFeatured() {
		return featured;
	}
	
	this.getRotator = getRotator;
	function getRotator() {
		return rotator;
	}
	
	function setupTabs() {
		// program tabs
		var programs = $('#program-block');
		var tabs = programs.find('> ul.tabs > li');
		var stories = programs.find('> div.stories');
		tabs.each(function() {
			var li = $(this);
			li.find('a').click(function() {
				var parent = $(this).parent();
				tabs.parent().find('.selected').removeClass('selected');
				parent.addClass('selected');
				stories.find('> .selected').removeClass('selected');
				$('#pPanel-' + String(parent.get(0).id).split('-')[1]).addClass('selected');
				return false;
			});
		});
		
		// news tabs
		$('#news-tab, #events-tab, #updates-tab').click(function() {
			var anchor = $(this);
			var scroller = anchor.parents('div.scroller');
			scroller.find('.selected').removeClass('selected');
			anchor.parent('li').addClass('selected');
			$('#' + String(this.id).split('-')[0] + '-panel').addClass('selected');

			var newClass;
			switch ($(this).attr('id')) {
			case 'updates-tab':
				newClass = '.updates';
				break;
			case 'events-tab':
				newClass = '.events';
				break;
			default:
				newClass = '.articles';
			}
			$('.all').hide();
			$(newClass).show();
			
			return false;
		});
	}
	
	function setupFeatured(selector) {
		featured = new JCC_HOME_FEATURED();
		featured.init(selector);
	}
	
	function setupRotator(selector) {
		rotator = new JCC_HOME_ROTATOR();
		rotator.init(selector);
	}
	
}

function JCC_HOME_FEATURED() {
	var DURATION = 1.5;	// number of seconds for transition
	var base;	// the base DOM element
	var slider;	// the DOM element being animated
	var storyGroups = [];	// jQuery/DOM elements for groups of stories
	var next, prev;	// DOM elements for the controls
	var pagesEl, currentPageEl, totalPagesEl;	// DOM element for pages display
	var currentIndex = 0, totalPages;	// paging variables
	
	this.init = init;
	function init(selector) {
		base = $(selector);
		slider = base.find('> .stories > .all-stories');
		slider.find('> .story-group').each(function() {	// build storyGroups array
			storyGroups.push($(this));
		});
		totalPages = storyGroups.length;
		pagesEl = base.prev().find('> .pages');
		currentPageEl = pagesEl.find('.num');
		totalPagesEl = pagesEl.find('.tot');
		next = base.find('> .controls > .next').click(function() {
			nextItem();
			return false;
		});
		prev = base.find('> .controls > .prev').click(function() {
			prevItem();
			return false;
		});
		if (totalPages > 1) {
			currentPageEl.text(currentIndex + 1);
			totalPagesEl.text(totalPages);
		} else {
			pagesEl.hide();
			next.hide();
			prev.hide();
		}
	}
	
	this.nextItem = nextItem;
	function nextItem(count) {
		var lastIndex = currentIndex;
		var offset;
		if (Math.floor(count) != count) count = 1;
		currentIndex = (currentIndex + count) % totalPages;
		while (currentIndex < 0) currentIndex = currentIndex + totalPages;
		offset = storyGroups[currentIndex].position().left;
		slider.stop().animate({ left: 0 - offset }, { duration: DURATION * 1000 });
		currentPageEl.text(currentIndex + 1);
	}
	
	this.prevItem = prevItem;
	function prevItem() {
		nextItem(-1);
	}
	
}


function JCC_HOME_ROTATOR() {
	var	 	captionEl,
			captionDefault,
			container,
			controls,
			currentIndex = 0,
			fadeDuration = 0.5, // number of seconds for each fade out/in
			linkEl,
			inTransition = false,
			isPlaying,
			pauseDuration = 8,	// number of seconds to wait before moving to next image
			slides = [],
			timer;
	
	this.init = init;
	function init(selector) {
		container = $(selector);
		captionEl = container.find('> .caption > .primary');
		captionDefault = captionEl.text();
		controls = {
			next: container.find('> div.controls a.next'),
			pause: container.find('> div.controls a.pause'),
			prev: container.find('> div.controls a.prev')
		};
		controls.next.click(function() {
			next();
			$(this).blur();
			return false;
		});
		controls.pause.click(function() {
			if (isPlaying) {
				pause();
				container.addClass('paused');
			}
			else {
				play();
				container.removeClass('paused');
			}
			$(this).blur();
			return false;
		});
		controls.prev.click(function() {
			prev();
			$(this).blur();
			return false;
		});
		container.find('.slides img').each(function(i, img) {
			if (i == 0) $(img).addClass('show');
			else $(img).removeClass('show');
			slides.push($(img));
		});
		fadeDuration *= 1000;
		linkEl = container.find('> a.link');
		if (slides.length > 1) {
			play();
		} else {
			container.find('> div.controls').hide();
		}
	}
	
	this.next = next;
	function next(reverseFlag) {
		if (!inTransition) {
			pause();
			inTransition = true;
			var previousIndex = currentIndex;
			if (reverseFlag) {
				currentIndex--;
				if (currentIndex == -1) currentIndex = slides.length - 1;
			} else {
				currentIndex = (currentIndex + 1) % slides.length;
			}
			var prevCaption = captionEl.text();
			var nextCaption = (slides[currentIndex].attr('alt')) ? slides[currentIndex].attr('alt') : captionDefault;
			if (prevCaption != nextCaption) { // captions are different, so trasition them
				captionEl.fadeOut(fadeDuration, function() {
					captionEl.text(nextCaption).fadeIn(fadeDuration);
				});
			}
			slides[currentIndex].stop().hide().addClass('show');
			slides[previousIndex].fadeOut(fadeDuration, function() { $(this).removeClass('show'); });
			setTimeout(function() {
				slides[currentIndex].fadeIn(fadeDuration, function() {
					if (slides[currentIndex].attr('rel')) {
						linkEl.attr('href', slides[currentIndex].attr('rel'));
						linkEl.addClass('show');
					} else {
						linkEl.removeClass('show');
					}
					inTransition = false;
					play();
				});
			}, fadeDuration * 0.8);
		}
	}
	
	this.pause = pause;
	function pause() {
		if (isPlaying && slides.length) {
			clearInterval(timer);
			isPlaying = false;
		}
	}
	
	this.play = play;
	function play() {
		if (slides.length) {
			clearInterval(timer);
			timer = setInterval(next, pauseDuration * 1000);
			isPlaying = true;
		}
	}
	
	this.prev = prev;
	function prev() {
		next(true);
	}


	


	
}

/*
	Homepage Twitter search
*/

		function twitter_search()	 
		{			
			var results = "";	 

			var search_query = "from%3Ajccpgh"; //Not using this, but would be used to dynamically find someone's Tweets

			$.post("/social_media/get_tweets", {query: search_query},	function(xml){	 
				$('entry',xml).each(function(i){	 
					var title = $(this).find("title").text();
					var image = $(this).find("link[type='image/png']").attr('href');
					var tweet_link = $(this).find("id").text().split(':');

					title = build_links(title);
					title = build_twitter_links(title);

					var name = $(this).find("name").text();
					var namearray = name.split(" ");

					var updated = $(this).find("updated").text(); 

					updated = updated.replace(/T/," ");
					updated = updated.replace(/Z/," ");

					results = results + "<li style='overflow:hidden;padding-left:4px;word-wrap:break-word;'> <span class='desc'> " + title + "</span> <a href='http://twitter.com/jccpgh/status/" + tweet_link[2] + "' target='_blank' style='font-weight:normal;'><span class='date'>From Twitter on " + updated + "</span></a> </li><br />";	 
				});	 

				$("#updates-panel").html(results);	 
			});	 




		}

		//From Twitter response, build out links
 		function build_links(plaintext)
 		{
			regexp=/(http:\/\/[^\s]*)/ig;
			var matches = plaintext.match(regexp);
			var plainlinks = "";

			if(matches != null)
			{
				plainlinks = matches.join("\n");
				var result = plaintext.replace(regexp,"<a href=\"$1\" title=\"$1\" target='_blank'>\$1\</a>");

				return result;
			}
			else
			{
				return plaintext;
			}
 		}

		//From Twitter response, build out @ links for other Twitter users
 		function build_twitter_links(plaintext)
 		{
 			plaintext = plaintext.replace(/(^|\s|-)+@(\w+)/g, "<a href='http://www.twitter.com/$2' target='_blank'>$&</a>");
 			return plaintext;

 		}


