/**
 * @fileoverview Main JavaScript file for sacbee.com.  Houses global functions.
 */

// configuration variables
var topnav_default = '';
var topnav_over_main = '';
var topnav_over_sub = '';
var subnav_default = jQuery('#main-nav .subnav li.active');
var subnav_over = '';
var subsubnav_default = jQuery('.subsubnav li.active');
var subsubnav_over = '';
var URL_images = 'http://media.sacbee.com/static/img/'; // URL of where the blank.gif image will live.
var multimediabar_enabled = false;
var mini_slideshow_enabled = false;
var big_slideshow_enabled = false;	// temporary, remove with enable_big_slideshow()


/**
 * Enables the main (top) bar of the navigation bar.
 */
function manage_topnav(){
	var showmenu = '';
	if(topnav_over_main || topnav_over_sub){
		if(topnav_over_main && !topnav_over_sub){
			showmenu = topnav_over_main;
		}else if(!topnav_over_main && topnav_over_sub){
			showmenu = topnav_over_sub;
		}else{
			if(topnav_over_main==topnav_over_sub){
				showmenu = topnav_over_main;
			}
		}
		jQuery('#main-nav>ul>li.active').removeClass('active');
		jQuery(showmenu).addClass('active')
	}else{
		if(jQuery(topnav_default).attr('class') != 'active'){
			jQuery('#main-nav>ul>li.active').removeClass('active');
			jQuery(topnav_default).addClass('active');
		}
	}
}

/**
 * Enables the subnav bar.
 */
function manage_subnav(){
	var showmenu = '';

	if(subnav_over) {
		var html = jQuery('#main-nav .subnav li.active').eq(0).html();
			if(jQuery(subnav_over).html() != html){
			jQuery('#main-nav .subnav li.active').removeClass('active');
			jQuery(subnav_over).addClass('active')
		}
	} else {
		if(!jQuery(subnav_default).hasClass('active')){
			jQuery('#main-nav .subnav li.active').removeClass('active');
			jQuery(subnav_default).addClass('active');
		}
	}
}

/**
 * Enables the sub-subnav bar (which we don't use).
 */
function manage_subsubnav(){
	var showmenu = '';

	if(subsubnav_over) {
		var html = jQuery('.subsubnav li.active').eq(0).html();
			if(jQuery(subsubnav_over).html() != html){
			jQuery('.subsubnav li.active').removeClass('active');
			jQuery(subsubnav_over).addClass('active')
		}
	} else {
		if(!jQuery(subsubnav_default).hasClass('active')){
			jQuery('.subsubnav li.active').removeClass('active');
			jQuery(subsubnav_default).addClass('active');
		}
	}
}

/**
 * Highlights the proper tab in the navbar.  Called after the navbar loads.
 * @param {String} nav_id the ID of the top tab to highlight
 * @param {String} subnav_str a substring of the subnav link to highlight
 */
function set_nav_subnav (nav_id, subnav_str) {
	jQuery("#main-nav li").removeClass("active");
	topnav_default = nav_id;

	if (subnav_str) {
		var subnav_element = jQuery(topnav_default + " li a:contains(" + subnav_str + ")").parent();

		subnav_default = subnav_element;
		subnav_element.addClass("active").parent().parent().addClass("active");
	}

	manage_topnav();
}

/**
 * Enables the main navigation bar.  Fired inline on all pages just after the navbar loads.
 */
function enable_navbar () {
	// Top navigation menu
	topnav_default = '#' + jQuery('div#main-nav ul li.active').attr('id');
	var timeo;
	jQuery('div#main-nav ul:first>li').hover(
		//function(){ topnav_over_main = '#'+jQuery(this).attr('id'); manage_topnav(); },
		function(){ topnav_over_main = '#'+jQuery(this).attr('id'); clearTimeout(timeo); manage_topnav(); },
		//function(){ topnav_over_main = ''; manage_topnav(); }
		function(){ topnav_over_main = ''; timeo = setTimeout("manage_topnav();", 500); }
	);
	jQuery('div#main-nav ul ul').hover(
		function(){ topnav_over_sub = '#'+jQuery(this).parents('li').attr('id'); manage_topnav(); },
		function(){ topnav_over_sub = ''; manage_topnav(); }
	);

	// Sub navigation menu
	subnav_default = jQuery('#main-nav .subnav li.active');
	jQuery('#main-nav .subnav li').hover(
		function(){ subnav_over = jQuery(this); manage_subnav(); },
		function(){ subnav_over = ''; manage_subnav(); }
	);

	// Optional third level navigation menu
	if(jQuery('.subsubnav').length) {
		subsubnav_default = jQuery('.subsubnav li.active');
		jQuery('.subsubnav li').hover(
			function(){ subsubnav_over = jQuery(this); manage_subsubnav(); },
			function(){ subsubnav_over = ''; manage_subsubnav(); }
		);
	}
}

/**
 * Enables the dynamic search box.  Fired inline on all pages.
 */
function enable_searchbox () {
	searchbox = 1;
	jQuery('div.searchmain input:text').focus(function(){
		jQuery('div.searchmain div.controller span:hidden').css('cursor','pointer').show();
		jQuery('div.searchdropdown:hidden').show();
		jQuery(this).css('background-position','0 -18px')
	});
	jQuery('div.searchmain input:text').blur(function(){
		if (jQuery('div.searchmain input:text').val() == "") {
			jQuery(this).css('background-position','0 0');
		}
	});
	jQuery('div.searchmain div.controller span').click(function(){
		jQuery(this).hide();
		jQuery('div.searchdropdown:visible').hide();
		if (jQuery('div.searchmain input:text').val() == "") {
			jQuery(this).css('background-position','0 0');
		}
	});
}

/**
 * Enables the Reader Servives menu(s).  Fired inline on all pages on all pages.
 */
function enable_readerservices_menus () {
	jQuery('div.readerservices-menu').parent().hover(
		function () {
			jQuery(this).addClass('active');
		},
		function () {
			jQuery(this).removeClass('active');
		}
	);

//	readerservices_menus = 1;
//	jQuery('div.readerservices-menu').toggle(
//		function(){
//			jQuery.each(jQuery('div.readerservices-menu'), function(){
//				if(jQuery(this).parent('.active').get(0)){
//					jQuery(this).find('a').trigger('click');
//				}
//			});
//			jQuery(this).parent().addClass('active');
//		},
//		function(){
//			jQuery(this).parent().removeClass('active');
//		}
//	);

// Can go away when (if) we remove the link from readerservices-menu
	jQuery('div.readerservices-menu a').click(function(){
//		jQuery(this).parent().trigger('click');
		return false;
	});

//	jQuery('div.readerservices-menu a').focus(function(){
//		this.blur();
//	});
}

/**
 * Enables the Multimedia Bar.  Called either inline immediatly after the
 * multimedia bar (in the page element) or from the ready() function below.
 */
function enable_multimediabar () {
	jQuery('div#multimediabar .mm-links li:first').addClass('active');
	jQuery('div#multimediabar div.mm-panelset').each(function(i){
		var thePanelset = i+1;
		jQuery('div.mm-panels',this).cycle({
			fx: 'scrollHorz',
			speed: 500,
			timeout: 0,
			cleartypeNoBg: true,
			next: '#mm-panelset'+thePanelset+' .mm-right a',
			prev: '#mm-panelset'+thePanelset+' .mm-left a',
			pagerAnchorBuilder: function(idx,slide){
				return '<a href="#"><img src="'+URL_images+'blank.gif" alt=""><\/a>';
			}
		});
	});
	jQuery('#multimediabar .mm-left a, #multimediabar .mm-right a').focus(function(){ this.blur(); });

	// pause all except the first panelset
	jQuery('div#multimediabar div.mm-panelset:not(#mm-panelset1) div.mm-panels').cycle('pause');

	// tabs switch panelsets
	jQuery('div#multimediabar .mm-links a').click(function(){
		jQuery(this).parents('ul').find('.active').removeClass('active');
		jQuery(this).parent('li').addClass('active');
		jQuery('div#multimediabar div.mm-panels').cycle('stop');
		var nextPanelset = '#'+jQuery(this).attr('class');

		jQuery(this).parents('ul').removeClass();
		jQuery(this).parents('ul').removeClass();

		jQuery(this).parents('ul').addClass("mm-links");
		jQuery(this).parents('ul').addClass(jQuery(this).attr('class'));

		jQuery('.mm-panelset:not('+nextPanelset+')').fadeOut('normal', function(){
			jQuery(nextPanelset).fadeIn(
				'normal',
				function(){
				jQuery(nextPanelset+' div.mm-panels').cycle('resume');
			});
		});
		this.blur();
		return false;
	});

	// set this so we can test for it in the ready() function belore and not run twice
	multimediabar_enabled = true;
}

/**
 * Enables a mini-slideshow.  Called either inline immediatly after the mini-slideshow
 * or from the ready() function.
 */
function enable_mini_slideshow () {
	jQuery('#mini-slideshow div.slides ul').cycle(
		{
			fx: 'scrollHorz',
			speed: 200,
			timeout: 0,
			prev: '#mini-slideshow span.prev a',
			next: '#mini-slideshow span.next a',
			pager: '#mini-slideshow span.indicator',
			pagerAnchorBuilder: function (idx, slide) {
				return '<a href="#"><img src="' + URL_images + 'blank.gif" alt=""\/><\/a>';
			},
			after: function () {
				jQuery('#mini-slideshow div.slides ul').animate(
					{
						height: parseInt(jQuery('img', this).attr('height') + 1) + 'px'
					},
					"fast");
				jQuery('#mini-slideshow div.captions').hide().html(jQuery('.txt', this).html()).show();
			}
		}
	);

	jQuery('#mini-slideshow-loader').hide();
	jQuery('#mini-slideshow div.txt').hide();

	// Create a caption block outside of the cycled block and fill it with the first caption.
	// Later we'll put the other captions in here
	jQuery('#mini-slideshow div.slides').after(jQuery('<div/>').addClass('captions').html(jQuery('#mini-slideshow ul li:first .txt').html()));

	// Needed for Safari so the first image shows...
 	jQuery('#mini-slideshow div.slides ul li').css('height', parseInt(jQuery('#mini-slideshow ul li:first img').attr('height') + 1) + 'px');

 	// set this so we can test for it in the ready() function belore and not run twice
 	mini_slideshow_enabled = true;
}

/**
 * Enable a full-sized slideshow.  Called inline on gallery-detail pages
 */
function enable_big_slideshow2 () {
	jQuery('div#big-slideshow div.slides ul').cycle(
		{
			fx: 'scrollHorz',
			speed: 200,
			timeout: 0,
			cleartypeNoBg: true,
			prev: 'div#big-slideshow span.prev a',
			next: 'div#big-slideshow span.next a',
			pager: 'div#big-slideshow span.indicator',
			pagerAnchorBuilder:function(idx, slide) {
				return '<a href="#"><img src="' + URL_images + 'blank.gif" alt=""><\/a>';
			},
			after: function (currSlideElement, nextSlideElement) {
				// Update the counter
			//	jQuery('.bigIndex').html(this.nodeIndex);	// Doesn't work in webkit
				jQuery('.bigIndex').html(jQuery(this).prevAll().length + 1);

				jQuery('#big-slideshow div.slides ul').animate(
					{
						height: parseInt(jQuery('img', this).attr('height') + 1) + 'px'
					},
					"fast");
				jQuery('#big-slideshow div.captions').hide().html(jQuery('div.gallerycaption', this).html()).show();

				// If we can, reload the ads and update the stats
				if (jQuery('#railads').length) {
					if (typeof(s) != "undefined")	// "s" is for "stupid" (needed because s isn't set on preview)
						mistats_resend();
					jQuery('#railads').attr('src', jQuery('#railads').attr('src'));
				}
			}
		}
	);

	jQuery('#big-slideshow-loader').hide();
	jQuery('#big-slideshow div.gallerycaption').hide();

	// Create a caption block outside of the cycled block and fill it with the first caption.
	jQuery('<div/>').addClass('captions').html(jQuery('#big-slideshow ul li:first div.gallerycaption').html()).appendTo('#big-slideshow div.slides');

	// Here's a trick: if there's only one image then cycle() will exit and it won't be displayed
	if (jQuery('div#big-slideshow div.slides ul li').length == 1) {
		jQuery('div#big-slideshow div.slides ul li').show();
	}

	big_slideshow_enabled = true;	// temporary, remove with enable_big_slideshow()
}

/**
 * Enable a full-sized slideshow.  Added to the ready() function below.
 * @deprecated call {@link enable_big_slideshow2} inline
 */
function enable_big_slideshow () {
	if(jQuery(".totalcount")) {
		var slidecount = jQuery(".slides li").length;
		jQuery(".totalcount").html(slidecount);
	}

	jQuery('div#big-slideshow ul').cycle(
		{
			fx: 'scrollHorz',
			speed: 1,
			timeout: 0,
			prev:'div#big-slideshow span.prev a',
			next:'div#big-slideshow span.next a',
			pager:'div#big-slideshow span.indicator',
			pagerAnchorBuilder:function(idx,slide) {
				return '<a href="#"><img src="' + URL_images + 'blank.gif" alt=""><\/a>';
			},
			after: function () {
				//mistats_resend();
				////window.galleryad1.location.reload();
				var thisHeight = parseInt(jQuery('img.main_image', this).attr('height'));
				var calcHeight = parseInt(thisHeight)+220;
				jQuery('#big-slideshow').css('height', calcHeight+'px');
				jQuery('#big-slideshow div.slides ul').css('height', calcHeight+'px');
				jQuery('#galleryad1').attr("src", function(){
					var url = location.href.toString();
					var i = url.indexOf('/',7);
					var surl = url.slice(i);
					var j = surl.indexOf('/',1);
					var first = surl.substr(0,j);
					var last = surl.slice(j);
					var ad = '/v-ad';
					var nurl = first+ad+last;
					return nurl;
				});
				jQuery('#big-slideshow-loader').hide();
			}
		}
	);
}

/* Search logging.  Uncomment and Comment next function to activate.  PHP needs to be moved. */
//var current_search_submitted_form;
//
//function sacbee_search (form) {
//	current_search_submitted_form = form;
//	jQuery.ajax({
//		type: "GET",
//		url: "http://www.sacbee.com/static/metrics/search.php",
//		data: "term=" + form.keywords.value,
//		success: function () {
//			form = current_search_submitted_form;
//			if (jQuery("#blog_search").attr('checked')) {
//				location.href = "http://www.sacbee.com/cgi-bin/mt/mt-search.cgi?IncludeBlogs=" + form.IncludeBlogs.value + "&search=" + form.keywords.value;
//			} else if (jQuery("#uber2").attr('checked')) {
//				var encoded_keywords = encodeURIComponent(form.keywords.value); // keyword name is q for sacbee
//				var section_num = '171'; //Sacbee front, for the moment until yahoo section created
//				var url_version = 'ysr';
//				var params = 'product=Yahoo%2COverture&' +
//					'collection=WEB&' +
//					'live_template=http%3A%2F%2Fwww.sacbee.com%2F' + section_num + '%2Fv-' + url_version + '%2Findex.html&' +
//					'error_template=http%3A%2F%2Fwww.sacbee.com%2F' + section_num + '%2Fv-yerr%2Findex.html&' +
//					'preview_template=http%3A%2F%2Fpreview.sacbee.com%2F' + section_num + '%2Fv-' + url_version + '%2Findex.html&' +
//					'results_per_page=10' +
//					'&prop_dym=1&prop_related=1';
//				location.href = "http://search2.sacbee.com/search-bin/search.pl.cgi?sf_Keywords=" + encoded_keywords + '&' + params;
//			} else {
//				form.submit();
//			}
//		}
//	});
//	return false;
//}

/**
 * Search onsubmit handler.  Allows the user to choose alternate searches, in this case a web search
 * (search2.sacbee.com) and, on the blogs, a blog-centric search.  Called from the search on all
 * pages.
 * @deprecated MI has their own search code now, use that.
 */
function sacbee_search (form) {
	if (jQuery("#blog_search").attr('checked')) {
		location.href = "http://www.sacbee.com/cgi-bin/mt/mt-search.cgi?IncludeBlogs=" + form.IncludeBlogs.value + "&search=" + form.keywords.value;
		return false;
	} else if (jQuery("#uber2").attr('checked')) {
		var encoded_keywords = encodeURIComponent(form.keywords.value); // keyword name is q for sacbee
		var section_num = '171'; //Sacbee front, for the moment until yahoo section created
		var url_version = 'ysr';
		var params = 'product=Yahoo%2COverture&' +
			'collection=WEB&' +
			'live_template=http%3A%2F%2Fwww.sacbee.com%2F' + section_num + '%2Fv-' + url_version + '%2Findex.html&' +
			'error_template=http%3A%2F%2Fwww.sacbee.com%2F' + section_num + '%2Fv-yerr%2Findex.html&' +
			'preview_template=http%3A%2F%2Fpreview.sacbee.com%2F' + section_num + '%2Fv-' + url_version + '%2Findex.html&' +
			'results_per_page=10' +
			'&prop_dym=1&prop_related=1';
		location.href = "http://search2.sacbee.com/search-bin/search.pl.cgi?sf_Keywords=" + encoded_keywords + '&' + params;
		return false;
	}
	return true;
}

/**
 * Custom implementation of the Pluck SolicitPhoto widget.  Modified to show the most recent photo instead of the
 * default thumbnail. Generally on the Our Town pages.
 * @param {String} galleryId the Pluck gallery ID
 */
 function getRecentPhotoByGallery(galleryId) {
	var requestBatch = new RequestBatch();
	var galleryKey = new GalleryKey(galleryId);
	var contentPage = new PhotoPage(galleryKey, 10, 1,"TimeStampDescending");

	requestBatch.AddToRequest(galleryKey);
	requestBatch.AddToRequest(contentPage);

	requestBatch.BeginRequest(serverUrl, function (responseBatch) {
		if (responseBatch.Responses.length == 0 || !responseBatch.Responses[0].Gallery) {
			console.log('Gallery not found');
		} else {
			var galleryDetails = responseBatch.Responses[0].Gallery;

			//var galleryType = galleryDetails.MediaType.Name;
			var galleryId = galleryDetails.GalleryKey.Key;
			//var galleryTitle = galleryDetails.Title;
			var galleryDescription = galleryDetails.Description;
			//var galleryTags = galleryDetails.Tags;
			var galleryPromoTitle = galleryDetails.GalleryPromo.Title;
			var galleryPromoBody = galleryDetails.GalleryPromo.Body;
			//var galleryPromoImg = galleryDetails.GalleryPromo.Image.Small;

			var response = responseBatch.Responses[1];
			var mediaType;
			var media;
			var galleryKey;
			if (response.PhotoPage != null) {
				mediaType = 'Photo';
				media = response.PhotoPage.Photos;
				galleryKey = response.PhotoPage.GalleryKey;
			} else {
				mediaType = 'Video';
				media = response.VideoPage.Videos;
				galleryKey = response.VideoPage.GalleryKey;
			}

			var photo = media[0];

			jQuery("#plck" + galleryId).html(
				'<div class="SolicitPhoto_Container story story-top story-top-img">\n' +
				'	<div class="SolicitPhoto_SectionHead">' + galleryPromoTitle + '</div>\n' +
				'	<div class="SolicitPhoto_Photo">\n' +
				'		<a href="/pluck_photo_gallery/index.html?plckGalleryID=' + galleryId + '"><img src="' + photo.Image.Medium + '" /></a>\n' +
				'	</div>\n' +
				'	<div class="SolicitPhoto_Details title">\n' +
				'		<a href="/pluck_photo_gallery/index.html?plckGalleryID=' + galleryId + '">' + galleryDescription + '</a>\n' +
				'	</div>\n' +
				'	<ul class="links">\n' +
				'		<li><a href="/pluck_photoupload/index.html?plckGalleryID=' + galleryId + '">Share your photos</a></li>\n' +
				'	</ul>\n' +
				'</div>\n'
			);
		}
	});
}

/**
* Shows the "Popular Comment" asset box on story pages. Added to the ready() function above each story.
* @param {Number} articleId the article the comment is on
* @param {Bool} [onStoryPage=false] is this going on the same story's page
*/
function showMostRecommendedComment (articleId, onStoryPage) {
	var articleKey = new ArticleKey(document.domain + '_' + articleId);
	var commentPage = new CommentPage(articleKey, 10, 1, "RecommendationsDescending");

	var requestBatch = new RequestBatch();
	requestBatch.AddToRequest(articleKey);
	requestBatch.AddToRequest(commentPage);
	requestBatch.BeginRequest(serverUrl, function(responseBatch) {
		var sbShowMostRecommendedThreshold = 0;

		if (responseBatch.Responses.length == 0) {
			console.log("Article #" + articleId + " not found in Pluck.");
		} else if (responseBatch.Responses.length == 1) {
			// There are no comments... which is fine
		} else {
			var article = responseBatch.Responses[0].Article;
			var commentPage = responseBatch.Responses[1].CommentPage;
			//var comment = commentPage.Comments[0];	// gets the first comment
			//var mrCommentDate = comment.PostedAtTime;

			// Step through the comments and get the first non-blocked comment from a non-blocked author
			var comment;
			for (var i = 0; i < commentPage.Comments.length; i++) {
				if (commentPage.Comments[i].Author.IsBlocked == "False" && commentPage.Comments[i].ContentBlockingState == "Unblocked") {	// Yo, this is NOT boolean
					comment = commentPage.Comments[i];
					break;
				}
			}

			if (onStoryPage) {
				anchorTag = '<a href="#comments">Leave your comment</a>';
			} else {
				anchorTag = '<a href="' + article.PageUrl + '">' + article.PageTitle + '</a>';
			}

			if (comment && comment.NumberOfRecommendations > 0) {
				jQuery("#mrComment").html(
					'<div class="boxshade">\n' +
					'	<div class="header">Popular Comment</div>\n' +
					'	<q>' + comment.CommentBody + '</q>\n' +
					'	<p> -- ' + comment.Author.DisplayName + '</p>\n' +
					'	<span class="icon-comment"></span>' + anchorTag + '\n' +
					'</div>\n' +
					'<div class="boxshade-end"></div><div id="commentabout" style="display:none"></div>\n'
				);
			}
		}
	});
}

/**
 * Get comment count.  Used on the blogs to get counts for multiple blog posts (like on a blog index).
 * Added to the ready() function after every post.  Also on the blog entry page.
 * @param {Number} articleId the article id to get a count on
 * @param {String} element the DOM element to update
 * @deprecated Use {@link getMultipleCommentCounts} in blog_scripts.js
 */
function getCommentCountForStory(articleId, element) {
	var articleKey = new ArticleKey(document.domain + '_' + articleId);

	var requestBatch = new RequestBatch();
	requestBatch.AddToRequest(articleKey);
	requestBatch.BeginRequest(serverUrl,
		function (responseBatch) {
			if (responseBatch.Responses.length == 0) {
			   console.log("Blog post #" + articleId + " not found in Pluck.");
			} else {
				var article = responseBatch.Responses[0].Article;

				jQuery(element).html(article.Comments.NumberOfComments);
				//var recommendCount.innerHTML = article.Recommendations.NumberOfRecommendations;
				//var ratingCount.innerHTML = article.Ratings.NumberOfRatings;
			}
		}
	);
}

/**
 * Filter HTML from Pluck comments.  Called from the document ready() function
 */
function filterPluckComments() {
	if (document.getElementById('commenting_inputForm')) {
		var q = new NYX.CommentInput('null');
		function cot(){
			var c=document.getElementById('commentBody').value,sc=_stripTags(c);
			if (c != sc) {
				document.getElementById("CommentError").innerHTML = "Sorry, due to abuse we've had to prohibit the submission of HTML tags.";
				return false;
			}else{return true;}
		}
		$('#commenting_inputForm').unbind('submit').bind('submit',function(){if (cot() === true) {q.submit();} return false;});
	}
}

/**
 * Support function for filterPluckComments().
 * @param {String} str
 * @private
 * @return {String}
 */
function _stripTags(str) {
	return str.replace(/<([^>]+)>/g,'');
}

/**
 * Grabs a cookie based on cookie, and optionally sub value (for cookies like AT).
 * Works with cookies that use '&' delimited sub values.
 * @param {String} cookieName a cookie to pull
 * @param {String} [valueName] a sub value to pull
 * @return {String}
 */
function grabCookie(cookieName, valueName) {
	var cookiearray = document.cookie.split("; ");
	var value = "";
	var returnvalue = "";
	for (var cookie in cookiearray) {
		var namevalue = cookiearray[cookie].split("=");
		if (namevalue[0] == cookieName) value = namevalue[1];
	}
	if (valueName == "") return value;

	value = unescape(value);
	valuearray = value.split("&");
	for (var valuepair in valuearray) {
		var namevalue = valuearray[valuepair].split("=");
		if (namevalue[0] == valueName) returnvalue = namevalue[1];
	}
	return returnvalue;
}

/**
 * Called to send a user to their Pluck profile, or to the login page if logged out.
 */
function goToPluckProfile() {
	userid = grabCookie("AT","u");
	if (userid == "") {
		url = "http://www.sacbee.com/static/insite/slogin.html?;goto="+location.href;
	}
	else {
		url = "http://www.sacbee.com/personas/?plckUserId="+userid+"&insiteUserId="+userid;
	}
	location.href = url;
}

/**
 * Returns a pretty "Monday, November 24, 2008".  Called inline on all pages.
 * @return {String} a date string
 */
function display_date_str () {
	var sbMiNow = new Date();
	var sbMiDayOfWeek = new Array("Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday");
	var sbMiMonth = new Array("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December");

	return sbMiDayOfWeek[sbMiNow.getDay()] + ", " + sbMiMonth[sbMiNow.getMonth()] + " " + sbMiNow.getDate() + ", " + sbMiNow.getFullYear();
}

/**
 * Hides the Pluck abuse button if you're not logged in.  Added to the ready() function below.
 * Note: Enters race condition with Pluck so doesn't always work.
 */
function pluck_disable_report_button () {
	if (document.cookie.indexOf("sacbee_user_auth") == -1) {
		jQuery(".commentAbuse").hide();
	} else {
//		jQuery.getJSON("http://www.sacbee.com/cgi-bin/userinfo/getuser.cgi?user=" + getInsiteUserName("sacbee_user_auth") + "&callback=?", function (user) {
//			if (!user.error && user.blockCommentReporting) {
//				console.info("Hiding 'Report abuse' link.");
//				console.log(jQuery(".commentAbuse").length);
//				jQuery(".commentAbuse").hide();
//			}
//		});
	}
}

/**
 * Enables the button that toggles comments on and off.  Called in the main ready loop.  Assumes a button construct on the page along the lines of:
 * <pre>&lt;div id="comment_toggle" style="display: none"&gt;
 *     &lt;img src="http://media.sacbee.com/static/images/hide_comments_btn.gif" alt="hide comments" /&gt;
 * &lt;/div&gt;</pre>
 */
function enable_comment_toggle () {
	if (jQuery('#comment_toggle').length) {
		if (jQuery.cookie('global_comment_pref') == "hide") {
			jQuery('#comment_toggle img').attr('src', '/static/images/comments/commentsShow.gif').attr('alt', 'show comments');
			jQuery('.comment_guidelines').hide();
			jQuery('#mrComment').hide();
		} else {
			jQuery('#comment_toggle img').attr('src', '/static/images/comments/commentsHide.gif').attr('alt', 'hide comments');
			jQuery('.comment_guidelines').show();
			jQuery('#mrComment').show();
		}
		jQuery('#comment_toggle').show();

		jQuery('#comment_toggle').click(function () {
			if (jQuery.cookie('global_comment_pref') == "hide") {
				jQuery.cookie('global_comment_pref', 'show', { path: '/', expires: 0 });
				if (typeof(s) != "undefined")
					s.tl(this,'o','Comments-show');	// Omniture click counter
			} else {
				jQuery.cookie('global_comment_pref', 'hide', { path: '/', expires: 365 });
				if (typeof(s) != "undefined")
					s.tl(this,'o','Comments-hide');	// Omniture click counter
			}

			window.location.reload();
		});
	}
}


/*
 * jQuery ready-loop code
 */
jQuery(document).ready(function(){
// zebra lists and tables
	jQuery('ul.zebra').each(function(){
		jQuery('li:nth-child(odd)',this).addClass('odd');
	});
	jQuery('table.zebra').each(function(){
		jQuery('tr:nth-child(odd)',this).addClass('odd');
	});

// create tabbed content areas
// uses jQuery UI tabs plugin - http://ui.jquery.com/
	if (jQuery('div.tabbed').length) {
		jQuery('div.tabbed').tabs({ cookie: { expires: 30 } });
		//jQuery('div.tabbed').tabs();		// ui.tabs 1.7
		//jQuery('div.tabbed>ul').tabs();		// ui.tabs 1.5
		jQuery('div.tabbed ul.tabs li a').focus(function(){
			this.blur();
		});
	}

// social bookmark tool
	jQuery('div#socialwidget li#social-dropdown div.ctrl a').toggle(
		function(){
			jQuery(this).addClass('active');
			jQuery(this).parents('li#social-dropdown').find('div.dropdown').show();
		},
		function(){
			jQuery(this).removeClass('active');
			jQuery(this).parents('li#social-dropdown').find('div.dropdown').hide();
		}
	);
	jQuery('div#socialwidget li#social-dropdown div.ctrl a').focus(function(){
		this.blur();
	});

// close open dropdowns when clicking empty space
	jQuery('body').click(function(){
		if(jQuery('li#social-dropdown div.dropdown:visible').get(0)){
			jQuery('div#socialwidget li#social-dropdown div.ctrl a').trigger('click');
		}

		jQuery.each(jQuery('div.readerservices-menu'), function(){
			if(jQuery(this).parent('.active').get(0)){
				jQuery(this).find('a').trigger('click');
			}
		});
	});

// multimedia bar
	if (jQuery('#multimediabar').length && !multimediabar_enabled)
		enable_multimediabar();

// mini-slideshow
	if (jQuery('#mini-slideshow').length && !mini_slideshow_enabled)
		enable_mini_slideshow();

// big slideshows
	if (jQuery('#big-slideshow').length && !big_slideshow_enabled)
		enable_big_slideshow();

//Factbox Expander
	jQuery('div.factbox_header a').click( function() {
		var id = this.id;
		if (jQuery('div.'+id).is(":hidden")) {
			jQuery('span.'+id).removeClass('icon-down');
			jQuery('span.'+id).addClass('icon-up');
		}
		else {
			jQuery('span.'+id).removeClass('icon-up');
			jQuery('span.'+id).addClass('icon-down');
		}
		jQuery('div.'+id).slideToggle("normal");
	});

	// open the first factbox...
	jQuery('div.factbox_header a:first').click();

//Comment Guidelines Expander
	jQuery('div.comment_guidelines a').click( function() {
		var id = this.id;
		if (jQuery('div.'+id).is(":hidden")) {
			jQuery('span.'+id).removeClass('icon-down');
			jQuery('span.'+id).addClass('icon-up');
		}
		else {
			jQuery('span.'+id).removeClass('icon-up');
			jQuery('span.'+id).addClass('icon-down');
		}
		jQuery('div.'+id).slideToggle("normal");
	});


	// Fix up the story list .stories class list items to have a last class, per the
	// NavArts design.
	// Easier to use jquery for this than trying to get the tmplsys to put class="last"
	// on every  variant story stack.
	jQuery(".stories li:last-child").addClass("last");
	jQuery(".links li:last-child").addClass("last");

	jQuery(".highlights .story:last").addClass("last");
	jQuery(".gallery_index .grid-a .story:last").removeClass("last");
	jQuery(".gallery_index .grid-d .story:last").removeClass("last");
	jQuery("#bloggers dd:last").addClass("last");
	jQuery("#commented li:last").addClass("last");
	jQuery(".cartoon").removeClass("last");
	jQuery(".story-top").removeClass("last");
	jQuery("div.boxshade .story-top").addClass("last");

	var count = jQuery("#latest li").length;
	if(count < 10) {
		jQuery("#latest .stories >li:last").removeClass("last");
		jQuery("#extrastories >li:last").addClass("last");
	}

	jQuery("div.button a button").click(function () {
		document.location = jQuery(this).parent().attr("href");
	});

	pluck_disable_report_button();
	enable_comment_toggle();
	filterPluckComments();
});
