/*
 *
 */

$(document).ready(function () {
	// mini-slideshow cycle function, builds pagination and sets transition
	$('div#mini-slideshow div.slides ul').cycle(
		{
			fx: 'scrollHorz',
			speed:1,
			timeout:0,
			prev:'div#mini-slideshow span.prev a',
			next:'div#mini-slideshow span.next a',
			pager:'div#mini-slideshow span.indicator',
			pagerAnchorBuilder:function(idx,slide){
				return '<a href="#"><img src="'+URL_images+'blank.gif" alt=""><\/a>';
			},
			after: after
		}
	);

	function after(){
		var thisHeight = parseInt($('img', this).attr('height'));
		var calcHeight = parseInt(thisHeight)+190; // was 150
		var minidivHeight = parseInt(calcHeight); //+33;
		$('#mini-slideshow').css('height',minidivHeight+'px');
		$('#mini-slideshow div.slides ul').css('height',eval(calcHeight-30)+'px');
		$('#mini-slideshow div.slides ul li').css('height',calcHeight+'px');
		$('#mini-slideshow-loader').hide();
	}

	// set initial size of box according to first slide height
	if($('#mini-slideshow')){
		// sets up a loop to iterate through slides
		// for each slide get css display and opacity properties
		$('#mini-slideshow ul li').each(function(i){
			// if display is set to list-itemthank	  
			// calculate this slides height for the box and ul
			var css = $(this).css('display');
			if( i == '0' ) {
				var thisHeight = parseInt($('img', this).attr('height'));
				var calcHeight = parseInt(thisHeight)+190; // was 150
				var minidivHeight = parseInt(calcHeight); //+33;
				$('#mini-slideshow').css('height',minidivHeight+'px');
				$('#mini-slideshow div.slides ul').css('height',eval(calcHeight-30)+'px');
				$('#mini-slideshow div.slides ul li').css('height',calcHeight+'px');
			}
		});			
	}

	// big slideshows
	if ($("#big-slideshow")) {
		if($(".totalcount")) {
			var slidecount = $(".slides li").length;
			$(".totalcount").html(slidecount);
		}
	}

	$('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: bigAfter
		}
	);
	
	function bigAfter(){
		//mistats_resend();
		////window.galleryad1.location.reload();
		var thisHeight = parseInt($('img.main_image', this).attr('height'));
		var calcHeight = parseInt(thisHeight)+220;
		$('#big-slideshow').css('height',calcHeight+'px');
		$('#big-slideshow div.slides ul').css('height',calcHeight+'px');
		$('#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;
		});
		$('#big-slideshow-loader').hide();
	}

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

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

	var count = $("#latest li").length;

	// 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.
	$(".stories li:last-child").addClass("last");
	$(".links li:last-child").addClass("last");

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

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

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

	//$("#billbo:has(img[src='http://m1.2mdn.net/viewad/817-grey.gif'])").hide();
	//$("#corner:has(img[src='http://m1.2mdn.net/viewad/817-grey.gif'])").hide();
});


function enable_mini_slideshow (element) {
	$(element + ' div.slides').cycle(
		{
			fx: 'scrollHorz',
			speed: 250,
			timeout: 0,
			prev: element + ' span.prev a',
			next: element + ' span.next a',
			pager: element + ' span.indicator',
			pagerAnchorBuilder: function (idx,slide) {
				return '<a href="#"><img src="' + URL_images + 'blank.gif" alt=""\/><\/a>';
			},
			after: function () {
				$(element + ' div.slides').animate(
					{
						height: parseInt($('img', this).attr('height')) + 'px'
					},
					"fast");
				$(element + ' div.captions').hide().html($('.caption', this).html()).slideDown("fast");
			}
		}
	);
}


function sacbee_search (form) {
	if ($("#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 ($("#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;
}

/* Pluck Solicit Photo Widet -- Bee Style */
var globalGalleryOnPage = 1;
var globalMediaOnPage = 1;
function getGlobalMediaOnPage() {
	return globalMediaOnPage;
}
function incrementGlobalMediaOnPage() {
	return globalMediaOnPage++;
}
function setGlobalMediaOnPage(value) {
	globalMediaOnPage = value;
}

function getRecentPhotoByGallery(galleryId) {
	 var requestBatch = new RequestBatch();
	 var galleryKey = new GalleryKey(galleryId);

	 var contentPage;
	 contentPage = new PhotoPage(galleryKey, 10, 1,"TimeStampDescending");
	 requestBatch.AddToRequest(galleryKey);
	 requestBatch.AddToRequest(contentPage);
	 requestBatch.BeginRequest(serverUrl, renderGallery);
}

function renderGallery(responseBatch) {  
	if (responseBatch.Responses.length == 0) {
		console.log('Gallery not found');
	}  
	var mediaType;
	var media;
	var galleryKey;
	var lastMediaPage;
	
	var galleryDetails = responseBatch.Responses[0].Gallery;
	if (galleryDetails != null) {
		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];
	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];
	var html;


	html = '<div class="SolicitPhoto_Container story story-top story-top-img">\n \
	<div class="SolicitPhoto_SectionHead">\n' +
		 galleryPromoTitle + '\n' +
'	 </div>\n \
	<div class="SolicitPhoto_Photo">\n \
		<a href="/pluck_photo_gallery/index.html?plckGalleryID=' + galleryId + '">\n \
			<img src="' + photo.Image.Medium + '" />\n \
		</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_photo_gallery/index.html?plckGalleryID=' + galleryId + '">' + galleryPromoBody + '</a></li>\n \
		<li><a href="/pluck_photoupload/index.html?plckGalleryID=' + galleryId + '">Share your photos</a></li>\n \
	</ul>\n \
</div>\n';
	$("#plck" + galleryId).html(html);

}

/* Most Recommended comment showing in story asset box */

var sbShowMostRecommendedThreshold = 0; 
var sbStoryPage = 0;
function showMostRecommendedComment(articleId,storyPage) {	
	if (typeof storyPage == "undefined") {
		storyPage = 0;
	}
	if(storyPage) {
		sbStoryPage = 1;
	}
	//console.log(articleId);
	//console.log(document.domain);
	var articleKey = new ArticleKey(document.domain + '_' +articleId);	
	var requestBatch = new RequestBatch();	
	//articleKey = new ArticleKey(articleId); 
	var commentPage = new CommentPage(articleKey,10,1,"RecommendationsDescending");
	requestBatch.AddToRequest(articleKey);
	requestBatch.AddToRequest(commentPage);
	requestBatch.BeginRequest(serverUrl, renderCommentPage);
}  

function renderCommentPage(responseBatch) {	 
	var mrCommentBody;
	var mrCommentAuthor;
	var mrCommentDate;
	var mrCommentRecCount = 0;
	var i;
	if (responseBatch.Responses.length == 0) {	
		console.log('Article Not Found.');	
	} else {  
		var article = responseBatch.Responses[0].Article;
		var commentPage = responseBatch.Responses[1].CommentPage;
		var comment = commentPage.Comments[0];
		mrCommentRecCount = comment.NumberOfRecommendations;
		mrCommentBody = comment.CommentBody;
		mrCommentAuthor = comment.Author.DisplayName;
		mrCommentDate = comment.PostedAtTime;
		if(sbStoryPage) {
			anchorTag = '<a href="#comments">Leave your comment</a>';
		} else {
			anchorTag = '<a href="' + article.PageUrl + '">' + article.PageTitle + '</a>';
		}
		if(mrCommentRecCount > sbShowMostRecommendedThreshold) {
			var html = '		<div class="boxshade">\n' +
			'<div class="header">Popular Comment</div>\n' +
				'<q>' + mrCommentBody + '</q>\n' +
				'<p> -- ' + mrCommentAuthor + '</p>\n' +
				'<span class="icon-comment"></span>' + anchorTag + '\n' +
			'</div>\n<div class="boxshade-end"></div><div id="commentabout" style="display:none"></div>';
			//console.log(html);
			$("#mrComment").html(html);
		}
	}  
}

/* get a count of comments for a given story */

function getCommentCountForStory(articleUniqueId, element) {
	var myUniqueId = "sacbee.com_" + articleUniqueId;
	function renderCommentCountTrigger(responseBatch) {
		renderCommentCount(responseBatch,element);
	}
	var articleKey = new ArticleKey(myUniqueId);  
	var requestBatch = new RequestBatch();	
	requestBatch.AddToRequest(articleKey);	 
	requestBatch.BeginRequest(serverUrl, renderCommentCountTrigger);   
}  
		  
function renderCommentCount(responseBatch,element) {  
	if (responseBatch.Responses.length == 0) {	
	   // alert('Article not found');  
	   console.log("Article not found");
	} else {  
		// get article from response  
		var article = responseBatch.Responses[0].Article;  
		var commentCount = article.Comments.NumberOfComments;  
		//console.log(commentCount);
		$(element).html(commentCount);
		//var recommendCount.innerHTML = article.Recommendations.NumberOfRecommendations;  
		//var ratingCount.innerHTML = article.Ratings.NumberOfRatings;	  
	}  
}  

// For live headlines...
function get_live_headlines (headline_selector, is_admin) {
	$.getJSON("/cgi-bin/live_headlines/get_heads.cgi", function (headlines) {
		var ul = $("<ul/>").addClass("stories");

		$.each(headlines, function(i, headline) {
			var li = $("<li/>").addClass("story").append(
				$("<img/>").attr('src', 'http://media.sacbee.com/images/icon_trash.gif').attr('title', 'Delete this headline').addClass('delete_button').css('float', 'right').click(
					function () {
						$(this).hide();
						del_headline(headline.id);
					}
				)
			).append(
				$("<span/>").html(headline.text.replace(/(http:\/\/(?:\w|\/|\.)+)/g, "<a href='$1'>$1</a>").replace(/\@(\w+)/g, "<a href='http://twitter.com/$1'>@$1</a>"))
			).append(
				$("<br/>")
			).append(
				$("<span/>").addClass("updated_when").html(get_relative_age_str(headline.timestamp))
			);

			li.appendTo(ul);

			if (i == 4) {
				li.addClass("last");
			}
			if (i > 4) {
				li.addClass("hideable");
				li.css('display', 'none');
			}
			if (i == 9 || i == headlines.length - 1) {
				li.addClass("last");
				return false;
			}
		});

		$(headline_selector).empty().append(ul);

		$("<div/>").addClass("button").append(
			$("<a/>").append(
				$("<button/>").html('Show More Headlines')
			).toggle(
				function () {
					$(".hideable").slideDown();
					$(this + " button").html("Show Fewer Headlines");
					$(headline_selector + " ul li:nth-child(5)").removeClass("last");
				},
				function () {
					$(".hideable").slideUp();
					$(this + " button").html("Show More Headlines");
					$(headline_selector + " ul li:nth-child(5)").addClass("last");
				}
			)
		).appendTo(headline_selector);

		$("<p/>").css('margin-top', '-5px').css('font-size', '8pt').html("Follow <a href='http://twitter.com/sacbee_news'>@sacbee_news</a> on Twitter.com").appendTo(headline_selector);

		if (is_admin)
			$(headline_selector + " .delete_button").show();
		else
			$(headline_selector + " .delete_button").hide();

		setTimeout('get_live_headlines("'+headline_selector+'")', 60000);
	});
}

function get_relative_age_str (timestamp) {
	var time;
	var s;

	var now = new Date();
	var seconds_ago = (now.getTime()/1000 - timestamp);

	if (seconds_ago < 60) {
		return "updated less than a minute ago";
	} else if (seconds_ago < 3600) {
		time = Math.round(seconds_ago / 60);
		s = (time == 1) ? "" : "s";
		return "updated " + time + " minute" + s + " ago";
	} else if (seconds_ago < 86400) {
		time = Math.floor(seconds_ago / 3600);
		s = (time == 1) ? "" : "s";
		if (time == 1) time = "an";
		return "updated over " + time + " hour" + s + " ago";
	} else {
		time = Math.floor(seconds_ago / 86400);
		s = (time == 1) ? "" : "s";
		return "updated over " + time + " day" + s + " ago";
	}
}

// Grabs a cookie based on cookie, and optionally sub value (for cookies like AT)
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;
}

// Call this 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"
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();
}

