$(function() {

//Replace the arrows with gifs for good ol IE6
if (!($.browser.msie && $.browser.version.substr(0,1) < 7)) {

	/* Remove all elements that should only appear if javascript is not available */
	$('.js_remove').remove();
	
	
	/* Add the HTML markup to create containers for the featured article and rolodex sections */
	$(""+
	"<div id='featured_wrap'>"+
	"<div id='rolodex_background'>"+
		"<div id='rolodex_wrap'>"+
			"<div id='rolodex_container'>"+
				"<div id='rolodex'></div>"+
				"<div id='top_gradient' ></div>"+
				"<div id='bottom_gradient' ></div>"+
			"</div>"+
			"<div id='rolodex_foreground'>"+
				"<div id='left_rolodex_cap'></div>"+
				"<div id='right_rolodex_cap'>"+
					"<div id='rolodex_up_arrow' class='rolodex_nav_up'><img src='"+$.media.url+"images/rolodex_up.png'/></div><div id='rolodex_down_arrow' class='rolodex_nav_down'><img src='"+$.media.url+"images/rolodex_down.png'/></div>"+
				"</div>"+
			"</div>"+
		"</div>"+
		"<div class='clear_both'></div>"+
	"</div>"+
		
		"<div id='preview'></div>"+

	"</div>"+
	"").appendTo('#index_left_column');
	
	//Fix the bug in IE that selects text when the rolodex is clicked and dragged
	var ie_select_fix = document.getElementById('rolodex_background');
	ie_select_fix.onselectstart = function() {return false;}
	
	/* Get all of the featured articles in a wrapped set, hide them for later acces, add classes to the article headings and put clones of these in the rolodex*/
	$('.featured_article').hide()
	.find('.article_title').clone().each(function() {
			$(this).addClass('rolodex_title').removeClass('article_title').appendTo('#rolodex');
			$('#rolodex').height($('#rolodex').height());	
		}).filter(':first').addClass('focus_rolodex_title');
	

	
	/* VARIABLE LIST */
	var articleIndex = 0;
	var numArticles = $('.featured_article').size();
	
	/* START-UP SETTINGS */
	
	/* Fade in first article*/
	$('.featured_article').slice(0,1)
	.clone()
		.appendTo('#preview').fadeIn('slow');

	/* Set up the first rolodex entry to be properly positioned*/
	$('#rolodex').css("top",function() {
		return $('#rolodex_container').height() / 2 - ($('.focus_rolodex_title').outerHeight() / 2); 
	});
		
	/* Set up the auto cycle */
	var cycleFeaturedArticles = setInterval(function() {
	
	if (articleIndex == numArticles - 1) {
		clearInterval(cycleFeaturedArticles);
	} else {
		featuredArticle("up");
	}
	}, 10000); 

	/* INTERACTION SETTINGS */

	/* Click anywhere in the 'Featured Area' to stop the cycling */
	$('#featured_wrap').bind('mousedown', function() {
		clearInterval(cycleFeaturedArticles);
	});

	/* Click the arrows to navigate the rolodex up or down */
	$('.rolodex_nav_up').click(function() {
		featuredArticle("down");
	}).hover(function() {
	$(this).css('background',"url('"+$.media.url+"images/rolodex_up_back.png') no-repeat top left")
	}, function(){
	$(this).css('background','')
	});

	$('.rolodex_nav_down').click(function() {
		featuredArticle("up");
	}).hover(function() {
	$(this).css('background',"url('"+$.media.url+"images/rolodex_down_back.png') no-repeat top left")
	}, function(){
	$(this).css('background','')
	});


	/* Click and drag the rolodex*/

	$('#rolodex_container').bind('mousedown', function (event) {
	 
	
	/* Get rid of the bloody Firefox image drag feature for the rolodex*/
	if(event.preventDefault) {
		 event.preventDefault();
 	};
	
	var data = { 
		y : event.pageY,
		top : $('#rolodex').css('top').replace('px','') * 1
	};
	
	$('body').bind('mousemove', data, function (event) {
		
		$('#rolodex').css({
			top : data.top + event.pageY - data.y
		});
		
		var indexCenter = [];
		var newIndex;
		var dropPosition = $('#rolodex').css('top').replace('px','') * 1 - ($('#rolodex_container').height() / 2);
		var distanceFrom = 1000000;
		$('.rolodex_title').each(function(i){
			indexCenter[i] = $(this).position().top + ($(this).outerHeight() / 2) + dropPosition;
			if (distanceFrom >= Math.abs(indexCenter[i])) {
				newIndex = i;
				distanceFrom = Math.abs(indexCenter[i]);
			};		
		});
		if(!$('.rolodex_title').slice(newIndex,newIndex+1).hasClass('.focus_temp_rolodex_title')) {
			$('.rolodex_title').removeClass('focus_rolodex_title')
				.slice(newIndex,newIndex+1).addClass('focus_rolodex_title');
		}
			
			/* if near the end, load more articles */
			var totalIndex = $('.rolodex_title').size();
			if (totalIndex - newIndex <= 5 ) {
				grabArticles();
			}
		
	});
	
	$('body').bind('mouseup mouseleave', function () {
		
		$('body').unbind('mousemove');
		
		var indexCenter = [];
		var newIndex;
		var dropPosition = $('#rolodex').css('top').replace('px','') * 1 - ($('#rolodex_container').height() / 2);
		var distanceFrom = 1000000;
		$('.rolodex_title').each(function(i){
			indexCenter[i] = $(this).position().top + ($(this).outerHeight() / 2) + dropPosition;
			if (distanceFrom >= Math.abs(indexCenter[i])) {
				newIndex = i;
				distanceFrom = Math.abs(indexCenter[i]);
			};		
		});
		featuredArticle(newIndex);
		
		$('body').unbind('mouseup mouseleave');
		
	});
	
	
		
	});
	

	/* FUNCTION LIST */

	/* This function fades out the current featured article and fades in the next one */
	function featuredArticle(index) {
		
		if (numArticles - articleIndex <= 5) {
			grabArticles();
		}
		
	if ((index == "up" && articleIndex < numArticles - 1) || (index == "down" && articleIndex != 0) || (index >= 0)) {
		if (index == "up") {
			articleIndex++;
			/*Change the focused title in the rolodex*/
			$('.focus_rolodex_title').removeClass('focus_rolodex_title').next().addClass('focus_rolodex_title');
		} else if (index =="down") {
			articleIndex--;

			$('.focus_rolodex_title').removeClass('focus_rolodex_title').prev().addClass('focus_rolodex_title');
		} else if (index >= 0 ) {
			articleIndex = index;
			$('.focus_rolodex_title').removeClass('focus_rolodex_title');
			$('.rolodex_title').slice(index,index+1).addClass('focus_rolodex_title');
		};

		var i = articleIndex;
		var j = articleIndex + 1;
		
		/* Update Featured Article Preview */
		$('#preview').children().fadeOut().remove();
		$('.featured_article').slice(i,j)
			.clone()
				.appendTo('#preview').fadeIn('slow');
	
		/* Update Rolodex */		
		
		var newTop = $('#rolodex_container').height() / 2 - ($('.focus_rolodex_title').outerHeight() / 2) - $('.focus_rolodex_title').position().top;
	
		$('#rolodex').animate(
			{
				top : newTop
			}, 'normal', 'linear');
	};
	
	
	};
	
	$('#footer').click(function() {grabArticles()});
	
	function grabArticles() {
		
		if ($('#loading_articles').size() == 0 ) {
			
			var data = {};
			
			var articles = $('#featured_articles');
			
			if (articles.attr('data-featured')) {
				data['featured'] = true;
			}
			
			var exclusion_list = '';
			
			articles.children('li.featured_article').each( function() {
				exclusion_list += ',' + $(this).attr('data-id');
			});
			
			if (exclusion_list != '') {
				exclusion_list = exclusion_list.slice(1); //get rid of the starting ','
			}
			
			data['exclude'] = exclusion_list;
			
			if (articles.attr('data-tag')) {
				data['tag'] = articles.attr('data-tag');
			}
			
			$('#rolodex').append('<h2 id="loading_articles" class="rolodex_title">Loading More Articles...</h2>');
			
			$.ajax({
					url: '/grab-articles/',
					type: 'GET',
					data: data,
					dataType: 'html',
					success: function(data) {
						if ($(data).filter('li.featured_article').size() != 0) {
							$(data).filter('li.featured_article').each(function() {
							
									$(this).hide().appendTo('#featured_articles');
									$(this).find('.article_title').clone().removeClass('article_title').addClass('rolodex_title').appendTo('#rolodex');
							})
														
							$('#loading_articles').remove();
							
							numArticles = $('.featured_article').size();
							
						} else {
							$('#loading_articles').text('There are no more articles');
						}
					
					}
					
			});
		}
	}

};
});



