var magSplash = {
	switchSpeed: 6000,
	animateSpeed: 600,
	curKey: -1,
	tickCount: 0,
	isLoaded: 0,
	timeout: null,
	exitLastAnimation: 0, // used as a switch to fix "fast scroll" glitching
	inTransition: 0,
	articleVoteList: [],
	bind: function() {		
		var $children = magSplash.getSplashChildren();

		// preload main images
		for(var i = 0, b = magSplash.data.images.length; i < b; i++) {
			$("<img>").attr('src', magSplash.data.images[i]);
		}
		
		// bind right nav
		$children.filter('img.imgNav').each(function() {
			var key = parseInt($(this).attr('rel'));
			var $imgNavItem = $(this);
			$("div#magSplash > span[rel=" + key + "]").mouseover(function() {
				$imgNavItem.triggerHandler('mouseover');
			});
			$(this).attr('src', magSplash.data.thumbs[key]);
			$(this).mouseover(function(e, auto) {
				$(this).addClass('active');
				$children.filter("span[rel='" + key + "']").addClass('active');
				if (auto) return;
				window.clearTimeout(timeout);
				if (key == magSplash.curKey) return;
				magSplash.tick(key);
			});
			$(this).mouseout(function() {
				magSplash.timer($children);
				if (magSplash.curKey == $(this).attr('rel')) return;
				$(this).removeClass('active');
				$children.filter("span[rel='" + key + "']").removeClass('active');
			});
			$(this).click(function() {
				document.location.href = magSplash.data.links[key];
			});
		});
		
		magSplash.appendAssets();
		magSplash.animateSpeedHalf = Math.round(magSplash.animateSpeed / 2);
		$(window).load(function() {
			magSplash.tick();
			magSplash.arrangeVoteItems();
			magSplash.isLoaded = 1;
		});
	},
	tick: function(key) {		
		if (key == null) {
			var nextKey = magSplash.curKey + 1;
			if (nextKey >= magSplash.data.links.length) nextKey = 0;
			key = nextKey;
		} 
		else { // freeze timeout because they are hovering on a thumb, timeout resumes after they mouseout thumb
			var noTimeout = 1;
		}
		
		if (key < 0) 
			key = magSplash.data.links.length - 1; // max
		
		if (magSplash.inTransition) {
			magSplash.exitLastAnimation = 1;
		}
		
		var $children = magSplash.getSplashChildren();
		
		magSplash.curKey = key;
		$children.filter('img.imgNav').each(function() {
			$(this).triggerHandler('mouseout');
		});

		var $mainImg = $children.filter("div#imgMainContainer").children("img");
		var $contentOverlay = $children.filter("div#contentOverlay"); // just text (no faded base)
		var $contentGroup = $contentOverlay.add("div#contentBaseOverlay"); // full control of floating content
		
		if (magSplash.tickCount >= 1) {
			magSplash.animateOut($mainImg, $contentGroup);
			magSplash.updateReaderStats();
		}
		
		window.setTimeout(function() {
			magSplash.animateIn($children, $mainImg, $contentOverlay, $contentGroup);
		}, magSplash.animateSpeedHalf + 180);		
		
		magSplash.tickCount += 1;

		if (!noTimeout)
			magSplash.timer($children);
	},
	timer: function() {
		window.clearTimeout(timeout);
		timeout = window.setTimeout(function() {
			magSplash.tick();
		}, magSplash.switchSpeed + magSplash.animateSpeed);
	},
	animateIn: function($children, $mainImg, $contentOverlay, $contentGroup) {
		if (magSplash.exitLastAnimation) {
			magSplash.inTransition = 0;
			magSplash.exitLastAnimation = 0;
			return;
		}
		magSplash.inTransition = 1;
		$mainImg.attr('src', magSplash.data.images[magSplash.curKey]).click(function() {
			document.location.href = magSplash.data.links[magSplash.curKey];
		});
		$contentOverlay.children('a').eq(0).html(magSplash.data.titles[magSplash.curKey]).click(function() {
			document.location.href = magSplash.data.links[magSplash.curKey];
		});
		$contentOverlay.children('p').eq(0).html(magSplash.data.blurbs[magSplash.curKey]);
		
		
		
		var imgInTimeout = $mainImg.animate({
			opacity: 1,
			filter: "alpha(opacity = 100)"
		}, magSplash.animateSpeedHalf);
		
		// delay the contentoverlay coming
		var cgInTimeout = window.setTimeout(function() {
			$contentGroup.animate({
				top: '125px'
			}, Math.round( magSplash.animateSpeedHalf * 2.5 ), 
			function() {
				magSplash.inTransition = 0;
			});
		}, ( magSplash.animateSpeed * 2 ) );
		
		$children.filter("img[rel='" + magSplash.curKey + "']").triggerHandler('mouseover', ['auto']);
	},
	animateOut: function($mainImg, $contentGroup) {
		if (magSplash.exitLastAnimation) return;
		magSplash.inTransition = 1;
		var imgOutTimeout = $mainImg.animate({
			opacity: 0.01,
			filter: "alpha(opacity = 1)"
		}, magSplash.animateSpeedHalf);
		
		var cgOutTimeout = $contentGroup.animate({
			top: '200px'
		}, Math.round( magSplash.animateSpeedHalf * 2.5 ));
	},
	updateReaderStats: function() {
		$("div#magSplashStats > div").css('display', 'none');
		$("div#magSplashStats > div[data-splashkey='" + magSplash.curKey + "']")
		.css('display', 'block')
		.children("span.frVote")
		.css('display', 'block');
	},
	arrangeVoteItems: function() {
		// orders all of the dynamically sized vote items in the reader stats area 
		// this function is only called once; on page load
		var $items = $("div#magSplashStats > div > span.frVote");
		var i = 0;
		
		$items.each(function() {
			var key = $(this).parent().attr('data-splashkey');
			var articleId = magSplash.data.links[key].match(/\-([\d]+)$/);
			
			// order sequence (right-to-left):
			// [thumbdown],[negvotes],[thumbup], [posvotes]
			var $thumbDown = $(this).children("img.down");
			var $thumbUp = $(this).children("img.up");
			var $negVotes = $(this).children("span.blue");
			var $posVotes = $(this).children("span.red");
			var rightPos = 0;
			$thumbDown.css('right', rightPos + 'px');
			rightPos += ( $thumbDown.width() - 8 );
			$negVotes.css('right', rightPos + 'px');
			rightPos += $negVotes.outerWidth();
			$thumbUp.css('right', rightPos + 'px');
			rightPos += ( $thumbUp.width() - 8 );
			$posVotes.css('right', rightPos + 'px');
			rightPos += $posVotes.outerWidth();
			
			// assuming we want to show them the first item
			if (i != 0) $(this).css('display', 'none');
			
			$thumbDown.click(function() {
				magSplash.articleVote($(this), articleId[1], -1);
			});
			$thumbUp.click(function() {
				magSplash.articleVote($(this), articleId[1], 1);
			});
			++i;
		});
	},
	articleVote: function($obj, articleId, ratingVal) {
		if (!articleId && alert('Glitch!  No article id sent to article vote.  Please tell a staff member!')) return; 
		if ($.inArray(articleId, magSplash.articleVoteList) != -1) return; // they've already voted on this
		
		var cookieName = "vibe[articleVoteList]";
		var articleVoteList = $.cookie(cookieName);
		if (articleVoteList && 
		    articleVoteList.match(new RegExp("\\b" + articleId + "\\b"))) 
			return;
		
		$.get("http://www.vibe.to/ajax/rateArticle", { articleid: articleId, rating: ratingVal });
		var spanClass = (ratingVal == 1) ? "red" : "blue";
		var $span = $obj.siblings("span." + spanClass).eq(0);
		var curVotes = parseInt($span.text());
		++curVotes;
		$span.html(curVotes);
		magSplash.articleVoteList[magSplash.articleVoteList.length] = articleId;
		magSplash.timer();
		articleVoteList = (articleVoteList) ? articleVoteList + " " + articleId : articleId;
		$.cookie(cookieName, articleVoteList, { expires: 120, path: '/' });
	},
	getSplashChildren: function() {
		return $("div#magSplash").children();
	},
	appendAssets: function() {
		// navigational buttons
		var $buttonForward = $("<img>").attr('src', 'http://images.vibe.to/splashGoRight.gif').attr('title', 'Next Article')
		.click(function() {
			magSplash.tick();
		});
		var $buttonBack = $("<img>").attr('src', 'http://images.vibe.to/splashGoLeft.gif').attr('title', 'Previous Article').css('padding-right', '0px')
		.click(function() {
			magSplash.tick(magSplash.curKey - 1);
		});
		$("div#contentOverlay > span").append($buttonBack).append($buttonForward);
	}
}
$(function() {
	magSplash.bind();
});
fm = { 
	active: '',
	hover: function(t, hash, row, col)
	{
		t.style.border = '1px solid black';

		var div = document.getElementById(hash);
		if (div) {
			if (div.style.display == 'none')
			{
				var coords = fm.getPosition(row, col);
				div.style.left = ( coords[0] - 11 ) + 'px';
				div.style.top = ( coords[1] - 11 ) + 'px';

				fm.active = hash;
				div.style.display = 'block';
				div.style.zIndex = '90';
				t.style.zIndex = '91';
			}
			else
				div.style.display = 'none';
		}			
	},
	blurr: function(t) 
	{
		t.style.border = '1px solid #CCC';
		t.style.zIndex = '89';

		var div = document.getElementById(fm.active);
		if (!div) return;

		div.style.display = 'none';
	},
	getPosition: function(row, col)
	{
		var pad = 5;
		var thumbSize = 64;

		var left = pad;
		var top = pad;
		top += (row * thumbSize) + (row * pad);
		left += (col * thumbSize) + (col * pad);

		return new Array(left, top);
	}
}