/* Just in case a Firebug console.log request makes it into production */
if (typeof(console) == 'undefined') {
	var console = {
		log: function(str) {
			//do nothing
		}
	};
}

var Cracked = {}; // Global scope
var userAgent = navigator.userAgent.toLowerCase();
var isMobileSafari = userAgent.search('mobile') > -1 && userAgent.search('safari') > -1;

var cur_timestamp = parseInt(new Date().getTime());

/* Horizonatl Slider */
var Slider = function(sectionId, panelWidth, itemsPerPanel) {
	
	//private variables
	var _currentPanel = 0;
	var _totalPanels = 0;
	var _itemsPerPanel = itemsPerPanel;
	var _panelWidth = panelWidth;
	var _sectionId = sectionId;
	var _isAll = false;
	
	//private methods
	var showNextVideo = function() {
		$("."+_sectionId+" .episodeGroup ul").animate({"left": "-=" + _panelWidth + "px"}, "slow");
		$("."+_sectionId+" .Nav4 .arrowLeft").css("visibility", "visible");
		_currentPanel++;
		
		if (_currentPanel == _totalPanels - 1) {
			$("."+_sectionId+" .Nav4 .arrowRight").css("visibility", "hidden");

		}
		return false;
	}

	var showPreviousVideo = function() {
			$("."+_sectionId+" .episodeGroup ul").animate({"left": "+="+_panelWidth+"px"}, "slow");
			$("."+_sectionId+" .Nav4 .arrowRight").css("visibility", "visible");

		
		_currentPanel--;
		if (_currentPanel == 0) {
			$("."+_sectionId+" .Nav4 .arrowLeft").css("visibility", "hidden");
		}
		return false; 
	}

	var toggleShowAll = function() {
		if (_isAll) {
			//set currentPanel back to 0
			_currentPanel = 0;
			$("."+_sectionId+" .Nav4 .arrowLeft").css("visibility", "hidden")
			$("."+_sectionId+" .Nav4 .arrowRight").css("visibility", "visible")

			$(this).html("<a>See All</a>");
			$("."+_sectionId+" .episodeGroup").css("overflow", "hidden");
			$("."+_sectionId+" .episodeGroup ul")
				.css("width", "3000px")
				.css("position", "relative")
				.css("left", 0);
			$("."+_sectionId+" .Nav4 li:eq(1)").show();
			$("."+_sectionId+" .Nav4 li:eq(2)").show();
			_isAll = false;
		}
		else {
			$(this).html("<a>See 4</a>");
			$("."+_sectionId+" .episodeGroup").css("overflow", "visible");
			$("."+_sectionId+" .episodeGroup ul")
				.css("width", "100%")
				.css("position", "static");
			$("."+_sectionId+" .Nav4 li:eq(1)").hide();
			$("."+_sectionId+" .Nav4 li:eq(2)").hide();
			_isAll = true;

		}
	}

	//onload
	$(function() {
		/*
		//get total panels
		var items = $("."+_sectionId+" .episodeGroup ul li").length;
		_totalPanels = Math.ceil(items/_itemsPerPanel);
		if (_totalPanels == 1) {
			$("."+_sectionId+" .Nav4 .arrowRight").css("visibility", "hidden")			
		};
		//initialize click events	
		$("."+_sectionId+" .Nav4 .arrowLeft")
			.css("visibility", "hidden")
			.click(showPreviousVideo);

		$("."+_sectionId+" .Nav4 .arrowRight").click(showNextVideo);

		$("."+_sectionId+" .Nav4 li:eq(0)").click(toggleShowAll);
		*/
	});

};

/* Vertical Slider */
var verticalSlider = function(sectionId, panelHeight, itemsPerPanel) {
	
	//private variables
	var _currentPanel = 0;
	var _totalPanels = 0;
	var _itemsPerPanel = itemsPerPanel;
	var _panelHeight = panelHeight;
	var _sectionId = sectionId;
	var _isAll = false;
	
	//private methods
	var showNextVideo = function() {
		$("#"+_sectionId+" .episodeGroup ul").animate({"top": "-=" + _panelHeight + "px"}, "slow");
		$("#"+_sectionId+" .Nav4 .arrowUp").css("visibility", "visible");
		_currentPanel++;
		
		if (_currentPanel == _totalPanels - 1) {
			$("#"+_sectionId+" .Nav4 .arrowDown").css("visibility", "hidden");

		}
		return false;
	}

	var showPreviousVideo = function() {
			$("#"+_sectionId+" .episodeGroup ul").animate({"top": "+="+_panelHeight+"px"}, "slow");
			$("#"+_sectionId+" .Nav4 .arrowDown").css("visibility", "visible");

		
		_currentPanel--;
		if (_currentPanel == 0) {
			$("#"+_sectionId+" .Nav4 .arrowUp").css("visibility", "hidden");
		}
		return false;
	}

	//onload
	$(function() {
		//get total panels
		var items = $("#"+_sectionId+" .episodeGroup ul li").length;
		_totalPanels = Math.ceil(items/_itemsPerPanel);
		if (_totalPanels == 1) {
			$("#"+_sectionId+" .Nav4 .arrowDown").css("visibility", "hidden")			
		};
		//initialize click events	
		$("#"+_sectionId+" .Nav4 .arrowUp")
			.css("visibility", "hidden")
			.click(showPreviousVideo);

		$("#"+_sectionId+" .Nav4 .arrowDown").click(showNextVideo);

	});

};

var leaderBoardPanel = function (buttonId, containerId) {

	var leaderboard = $("#" +buttonId);
	var closeButton = $("#" +containerId+ " .close");
	
	$(leaderboard).bind("click", function () { 
		var offset = $(this).offset();
		$("#" +containerId)
			.css("left", offset.left -45)
			.css("top", offset.top + 30)
			.slideToggle();
			return false;
			
	});
	
	$(closeButton).bind("click", function() {
		$("#" +containerId)
			.slideToggle();
			return false;
	});
	
	$("#leaderboardCraptions").show();
	
	var _currentPanel = 0;
	var i = 0;
	
	$(".leaderboardSection").hide();
	$(".leaderboardSection:eq("+_currentPanel+")").show();
	$(".TextList4 li:eq("+i+")").addClass("selected");
	
	$(".TextList4 li").bind("click", function(){
		$(this).parent().find("li").removeClass("selected");
		i = $(".TextList4 li").index(this);
		_currentPanel = i;
		
		var leaderboardOverlayText = $(this).find("a").text();
		
		//place to store text
		var leaderboardText = $("#leaderboardButton .arrow");


		// replaced text from .... with placeholder text
		$(leaderboardText).html(leaderboardOverlayText + " Last 30 days");
		
		$(this).addClass("selected");
		$(".leaderboardSection").hide();
		$(".leaderboardSection:eq("+_currentPanel+")").show();
		$(closeButton).click();
		return false;
	});

}

var switcher = function() {
	
	var _currentPanel = 0;
	var _totalPanel = 0;
	var i = 0;	
	

	$(".categoryArticles").hide();
	$(".categoryArticles:eq("+_currentPanel+")").show();
	$(".Nav3 li:eq("+i+")").addClass("selected");
	
	$(".Nav3 li").hover(
		function () {
			$(this).parent().find("li").removeClass("selected");
			i = $(".Nav3 li").index(this);
			_currentPanel = i;
			
			// place where text is shown
			var linkText = $(this).text();
			
			// place to store text
			var catText = $("#catText");
			
			// replaces text from links with placeholder text
			$(catText).html(linkText);		
		
			$(this).addClass("selected");
			$(".categoryArticles").hide();
			$(".categoryArticles:eq("+_currentPanel+")").show();
	
		},
		function () {}
		
	);

		
}


var postComment = function() {
	$(".postComment").click(function () {
		$(".postCommentForm").show();
	});
	
	$(".postCommentForm form .Button1").click(function () {
		$(".submitted").fadeIn('slow', function() { 
			setTimeout(function() {
				$(".submitted").fadeOut('slow');
				$(".postCommentForm").fadeOut('slow');
			}, 1500);
		});
	});
}


var indexPage = function() {
	var newTodaySlider = new Slider('NewToday', '292' , '2');
	
	var popularVideoSlider = new verticalSlider('popular', '564', '6');
	var top50VideoSlider = new verticalSlider('top50', '564', '6');

	var popularVideoSlider = new Slider('PopularVideos', '474', '3');

	
	//onload
	$(function() {
		$(".VideoCharts .Nav2 li:eq(1)").click(function () {
			$(this).addClass("selected");
			$(".VideoCharts .Nav2 li:eq(0)").removeClass("selected");
			$("#popular").hide();
			$("#top50").fadeIn();
		});	
		
		$(".VideoCharts .Nav2 li:eq(0)").click(function () {
			$(this).addClass("selected");
			$(".VideoCharts .Nav2 li:eq(1)").removeClass("selected");
			$("#top50").hide();
			$("#popular").fadeIn();
		});	
		var leaderboardPanel = new leaderBoardPanel('leaderboardButton', 'leaderboardOverlay');
	
		switcher();
	});
	
}

var videoPage = function() {
	var episodeSlider = new Slider('episodeSection', '610', '4');
	var blooperSlider = new Slider('blooperSection', '610', '4');
	var hotCrackedSlider = new Slider('hotCracked', '610', '4');

	//onload
	$(function() {
		$("#aboutSection").hide();
		$(".postCommentForm").hide();

		$(".VideoAboutGroup .Nav2 li:eq(1)").click(function () {
			$(this).addClass("selected");
			$(".VideoAboutGroup .Nav2 li:eq(0)").removeClass("selected");
			$("#videoSection").hide();
			$("#aboutSection").fadeIn();
		});	
		
		$(".VideoAboutGroup .Nav2 li:eq(0)").click(function () {
			$(this).addClass("selected");
			$(".VideoAboutGroup .Nav2 li:eq(1)").removeClass("selected");
			$("#aboutSection").hide();
			$("#videoSection").fadeIn();
		});	

		postComment();
	});
}


var topicsPage = function() {
	var relatedCrackedSlider = new Slider('relatedCrackedContent', '300' , '4');
	
}

var craptionsOpen = function() {
	var pastCraptionsSlider = new Slider('PastCraptionsGroup', '139', '1');
}

function winopen(url, winname, width, height, top, left) {
	var popwin = window.open(url, winname, "width="+width+",height="+height+",menubar=no,status=no,location=no,toolbar=no,scrollbars=no,top=" + top + ",left=" + left);
	popwin.focus();
}

/* Arcannon was here. */
$(document).ready(function() {
	$("img.lazy-load").onVisible({threshold: 100, callback: function() {
		$(this).lazyImage(function() {
			$(this).removeClass('lazy-load');
		});
	}});

	if (jQuery.browser.msie) {
		$('body').addClass('ie');
	}
	
	$.get('/data/nav-featured-items.php?ts=' + cur_timestamp, function(data) {
		var data = $(data);
		$('#articles-recent-items').html( $('#featured-articles', data).html() );
		$('#videos-recent-items').html( $('#featured-videos', data).html() );
		$('#columnists-recent-items').html( $('#featured-columnists', data).html() );
	});	

	var _panelWidth = 617;
	var _currentPanel = 0;
	var _totalPanels = 0;

	$(".episodeNav .seeAll").click(function(){

		var list = $(this).parent().parent().parent().parent().parent().find(".ThumbnailList2");

		if(list.css("width") != "auto") {
			list.css("width", "auto");
			list.css("left", "0px");
			_currentPanel = 0;
			$(this).parent().parent().find(".arrowLeft").css("visibility", "hidden");
			$(this).parent().parent().find(".arrowRight").css("visibility", "hidden");
			this.innerHTML = "<a>Close</a>";
		} else {
			list.css("width", "10000px");
			$(this).parent().parent().find(".arrowLeft").css("visibility", "hidden");
			$(this).parent().parent().find(".arrowRight").css("visibility", "visible");
			this.innerHTML = "<a>See All</a>";
		}
	});

	$(".episodeNav .arrowLeft").click(function() {
		if(_currentPanel <= 0) {
			return;		
		}

		var list = $(this).parent().parent().parent().parent().parent().parent().find(".ThumbnailList2");
		$(list).animate({"left": "+="+_panelWidth+"px"}, "slow");			
		$(this).css("visibility", "visible");
		$(this).parent().parent().find(".arrowRight").css("visibility", "visible");
		_currentPanel--;

		if(_currentPanel <= 0) {
			$(this).css("visibility", "hidden");
		}
	});

	$(".episodeNav .arrowRight").click(function() {
		var list = $(this).parent().parent().parent().parent().parent().parent().find(".ThumbnailList2");
		$(list).animate({"left": "-="+_panelWidth+"px"}, "slow");	
		$(this).parent().parent().find(".arrowLeft").css("visibility", "visible");
		_currentPanel++;

		if(((_currentPanel+1)*4) >= $(list).find("li").length) {
			$(this).css("visibility", "hidden");
		}
	
	});	
});

$(window).load(function(){
	UserAction.execute();
});

/* Global Site config */
var SiteUiConfig = {
	width: 980,
	headerHeight: 170
};

/* Dart utilities */
var DartUtils = {
	takeoverActive: false,
	takeoverClickEnabled: true,
	takeoverCallbacks: new Array(),

	addTakeoverCallback: function(funct) {
		if ($.isFunction(funct)) {
			DartUtils.takeoverCallbacks.push(funct);
		}
	},

	takeover : function(image, bgColor, clickthru, options) {			
			$(function() {
				DartUtils.takeoverActive = true;
				$body = $('body');
				
				$body.css('background-image', 'url('+image+')')
					.css('background-position', 'center 0')
					.css('background-repeat', 'no-repeat')
					.css('background-color', '#' + bgColor.replace('#', ''))
					.addClass('takeover');

				if (options.takeoverBanner) {
					var href = $("<a>").css({
						cursor: 'pointer',
						display: 'block',
						margin: '0 auto 10px auto',
						height: DartUtils.takeoverBannerHeight + 'px',
						width: SiteUiConfig.width + 'px',
						'z-index': 1
					}).attr("href", clickthru).attr('target', '_blank').attr('id', 'takeover-banner');

					$(DartUtils.takeoverBannerPrevElemSelector).after(href);
					
					$body.addClass('takeover-banner');
				}
				if (options.fixedBg) {
					$body.css('background-attachment', 'fixed');
				}

				if (options.bodyClass) {
					$body.addClass(options.bodyClass);
				}

				var window_width = $(window).width();
				var sides_width = (window_width - SiteUiConfig.width)/2;

				$(window).resize(function(){
					window_width = $(window).width();
					sides_width = (window_width - SiteUiConfig.width)/2;
				});

				$(document).mousemove(function(e){
					if (DartUtils.takeoverClickEnabled) {
						if( ((e.clientX < sides_width) || (e.clientX > (SiteUiConfig.width+sides_width))) 
							|| (
							(e.clientY < SiteUiConfig.headerHeight) && ( (e.clientX < sides_width) || (e.clientX > (SiteUiConfig.width+sides_width) ))
						)) {
							document.body.style.cursor = "pointer";
						} else {
							document.body.style.cursor = "default";
						}
					} else {
						document.body.style.cursor = "default";
					}
				});

				$(document).click(function(e) {
					if (DartUtils.takeoverClickEnabled) {
						if( ((e.clientX < sides_width) || (e.clientX > (SiteUiConfig.width+sides_width))) 
							|| (
							(e.clientY < SiteUiConfig.headerHeight) && ( (e.clientX < sides_width) || (e.clientX > (SiteUiConfig.width+sides_width) ))
						)) {
							window.open(clickthru);
						}
					}
				});

				var totalCallbacks = DartUtils.takeoverCallbacks.length;
				for (i = 0; i<totalCallbacks; i++) {
					DartUtils.takeoverCallbacks[i].apply();
				}
			});
	}
};

// Set dart UI configs
DartUtils.takeoverBannerHeight = 130;
DartUtils.takeoverBannerPrevElemSelector = '.Nav';


(function(){
Cracked.overlay = {
	setHeight: function(id) {
		var oc = $('#' + id);
		var contentHeight = oc.outerHeight();
		var windowHeight = $(window).height();
		var wrapPosition = (((windowHeight - contentHeight) / 2) / 2);
		
		$('#overlay-content-wrap').css('top', (wrapPosition > 10 ? wrapPosition : 10) + 'px');
		$('#overlay').height(windowHeight);
	},
	
	show: function(id, clickToExit, speed, opacity) {
		if ($('#' + id).length === 0) {
			throw "Invalid overlay content ID";
		}
		
		if ($('#overlay').length < 1) {
			$('body').append('<div id="overlay"/>');
		}
		
		$('.overlay-content').hide();
			
		this.setHeight(id);
		var _self = this;	
		
		clickToExit = clickToExit || true;
		speed = speed || 'slow';
		opacity = opacity || .50;
		
		
		$(window).bind('resize.overlay.' + id, function(){_self.setHeight(id);});
		
		$('#overlay').show().fadeTo(speed, opacity);
		
		if (clickToExit) {
			$('#overlay').bind('click', function(){
				_self.hide();
			});
		} else {
			$('#overlay').unbind('click');
		}
		
		var oc = $('#' + id)
		$('.close', oc).bind('click', function(){_self.hide();});
		$(oc).show();
	},
	
	hide: function(id) {
		if (typeof(id) == 'undefined') {
			$(window).unbind('resize.overlay');
			$('#overlay').stop(true, true).hide().fadeTo('fast', 0);
			$('.overlay-content').hide();
		} else {
			$(window).unbind('resize.overlay.' + id);
			$('#' + id).hide();
		}
	}
}})();
