/* Scripts for handling the news navigation */

// javascript init stuff for this section
function initNewsSidebar() {
    $("#news_sidebar_content").accordion({
	    header: '.news_sidebar_header',
	    autoHeight: false
	});
	$(".news_sidebar_article").click(function() {
        newsSidebarArticleSelected(this);
	});
	$("#news_sidebar_latest_articles").click(function() {
	    loadArticlesPage(1);
	});
	$(".news_sidebar_item").hover(function() {
	    // TODO calculate 30% of mood color
	    if(!$(this).hasClass("selected")) {
	        $(this).css("background-color", "#fff2b4");
	    }
	}, function() {
	    if(!$(this).hasClass("selected")) {
	        $(this).css("background-color", "#FFFFFF");
        }
	});
	
	shrinkMoodCopy();
	
	positionNewsSidebar();
}

function shrinkMoodCopy() {
    var fontSize = 31;
	while($("#today_mood").width() > 800) {
	    $("#today_mood").css("font-size", "" + fontSize + "pt");
	    fontSize -= 1;
	}
}

// 'latest articles' article selected
function newsSidebarArticleSelected(element) {
    //scroll to article.  If it doesn't exist, load it
    var id = element.id.match(/\d+/)[0];
    if($("#article_" + id).length == 0) {
        loadArticlesPage(currPage, "#article_" + id);
    } else {
        scrollWindow("#article_" + id, {'offset': -174})
    }
}

function highlightArticleSidebar(element) {
    $(element).addClass("selected");
    $(element).css("background-color", moodColor);
    $(element).css("color", "#1b1b1b");
}

function resetArticleSidebarStyles() {
    $(".news_sidebar_item").removeClass("selected");
    $(".news_sidebar_item").css("background-color", "#ffffff");
    $(".news_sidebar_item").find("div.title").css("color", "#2c2a2a");
    $(".news_sidebar_item").find("div.date").css("color", "#565656");
}

function loadArticles(url, loadingElement) {
    return newsAjax(url, loadingElement, function() {
        // create the twitter buttons
    	$('a.twitter-share-button').each(function() {
    		var tweet_button = new twttr.TweetButton( $( this ).get( 0 ) );
    		tweet_button.render();
    	});
    	// update the sidebar articles
    	$(".article").each(function(index) {
            var sidebarDiv = $(".news_sidebar_article")[index];
            sidebarDiv.id = "article_link_" + this.id.match(/\d+/)[0];
            $(".date", sidebarDiv).html($(this).find(".article_date").html());
            $(".title", sidebarDiv).html($(this).find(".article_title").html());
    	});
    	
    	// hide any extra articles if we're on the last page of results
    	$(".news_sidebar_article").show();
    	var numArticles = $(".article").length;
    	var lastPageArticleCount = $(".news_sidebar_article").length - numArticles;
    	if( lastPageArticleCount > 0) {
    	    $(".news_sidebar_article").each(function(index) {
    	        if(index + 1 > numArticles) {
    	            $(this).hide();
    	        } 
    	    });
    	}
    	
    	//show or hide the nav buttons
    	$("#news_sidebar_articles_nav > .prev").toggle($("#news_articles_nav > .prev").is(':visible'));
    	$("#news_sidebar_articles_nav > .next").toggle($("#news_articles_nav > .next").is(':visible'));
    	resetArticleSidebarStyles();
        applyMood();
        /*
        if($(loadingElement).parent().parent().attr("id") == $("#news_categories").attr("id")) {
            highlightArticleSidebar($(loadingElement).parent());
        } else {
            
        }*/
        highlightArticleInSidebar();
	});
}

function loadArticlesInCat(url, id) {
    scrollWindow('#news_content_wrapper', {'offset': -20});
    return loadArticles(url, "#news_categories [cat_id='" + id + "'] .loader");
}

// Called when a user wants to go to an article directly from an external source
function loadArticlesPage(page, scrollTo) {
    currPage = page;
    scrollWindow(scrollTo, {'offset': -174});
    return loadArticles(loadArticlesUrl + "?page=" + page, "#news_sidebar_latest_articles .loader");
}

function loadArticlesPage(page) {
    currPage = page;
    scrollWindow('#news_content_wrapper', {'offset': -20});
    return loadArticles(loadArticlesUrl + "?page=" + page, "#news_sidebar_latest_articles .loader");
}

function applyMood() { 
	$.each([".mood", ".article_title p"], function(index, value) {
	    $(value).css("background-color", moodColor);
	});
	$(".mood_foreground").css("color", moodColor);
	$("#today_mood").html(moodText);
	$("#articles_sidebar .selected").css("background-color", moodColor);
}

// Handles fixed vs absolute positioning of the sidebar, based on where we are in main page
function positionNewsSidebar() {
    var pos = $(window).scrollTop();
    var newsTop = featuredHeight;
    var sidebar = $("#news_sidebar");
    var newsHeader = $("#news_today");
    if(pos < newsTop) {
        sidebar.css("position", "absolute");
        sidebar.css("top", 190);
        newsHeader.css("position", "absolute");
        newsHeader.css("top", 42);
    } else if(pos > newsTop + $("#news .section_content").height() - sidebar.height() - 225) {
        sidebar.css("position", "absolute");
        sidebar.css("top", $("#news .section_content").height() - sidebar.height() - 35);
        newsHeader.css("position", "absolute");
        newsHeader.css("top", $("#news .section_content").height() - sidebar.height() - 183);
    } else {
        if(isMobile) {
            sidebar.css("top", (pos - newsTop + 190) + "px");
            newsHeader.css("top", (pos - newsTop + 42) + "px");
        } else {
            sidebar.css("position", "fixed");
            sidebar.css("top", 190);
            newsHeader.css("position", "fixed");
            newsHeader.css("top", 42);
        }
    }
    
    //highlight the appropriate article
    highlightArticleInSidebar();
}

// highlights the current article in the sidebar when scrolling through articles
function highlightArticleInSidebar() {
    var pos = $(window).scrollTop();
    var articles = $(".article");
    for(var i = 0; i < articles.length; i++) {
	    var sidebarElement = $("#article_link_" + articles[i].id.match(/\d+/)[0]);
	    if(i == articles.length - 1) {
	        resetArticleSidebarStyles();
	        highlightArticleSidebar(sidebarElement);
	        break;
	    }
	    var scrollThreshold = $("#news").offset().top + $(articles[i]).position().top - 20 + ($(articles[i]).height() - $(window).height() / 2);
		if(pos < scrollThreshold) {
		    resetArticleSidebarStyles();
			highlightArticleSidebar(sidebarElement);
			break;
		}
	}
}

function showTweets(url, loadingSelector) {
    return newsAjax(url, loadingSelector, function() {
        enhanceTweets();
        $(".tweet .article_footer a").addClass("mood_foreground");
        applyMood();
        
        scrollWindow("#news_content_wrapper", {'offset': -42});
	});
}

function showNews() {
    return newsAjax(getNewsUrl, "#sidebar_google_news .loader", function() {
        $(".news_content a").addClass("mood");
        applyMood();
        scrollWindow("#news_content_wrapper", {'offset': -42});
	});
}

//put mood spans around the urls, user mentions and hashtags
function enhanceTweets() {
    $.each($(".tweet"), function() {
        var toReplace = $(this).find(".tweet_content").html();
        //Decorate URLs
        $.each($(this).find(".tweet_url"), function() {
            var href = $(this).html();
            toReplace = toReplace.replace(href, "<span class='mood'><a href='" + href + "'>" + href + "</a></span>");
        });
        //Decorate user mentions
        $.each($(this).find(".tweet_mention"), function() {
            var mention = $(this).html();
            toReplace = toReplace.replace(new RegExp("@" + mention, "i"), "<span class='mood'>@" + mention + "</span>");
        });
        //Decorate hashtags
        $.each($(this).find(".tweet_hashtag"), function() {
            var hashtag = $(this).html();
            toReplace = toReplace.replace("#" + hashtag, "<span class='mood'>#" + hashtag + "</span>");
        });
        $(this).find(".tweet_content").html(toReplace);
    });
}

// A common AJAX function for loading content into the news section
function newsAjax(url, loadingSelector, callback) {
    $(loadingSelector).show();
    $("#news_content").load(url, function() {
        $("#news_content").css("min-height", $("#news_sidebar").height() + 20);
	    $(loadingSelector).hide();
        callback();
        //fix section height based on new content
        //setNewsHeight();
	});
	return false;
}

// Calculates a minimum height for the news section
function setNewsHeight() {
    $("#news").css("min-height", $(window).height());
}

function newsImage(article_id, media_id) {
    var article_selector = "#article_" + article_id;
    $(article_selector + " .news_image_navigation li").removeClass("on");
    $(article_selector + " .article_media div").hide();
    $(article_selector + " li[mediaid=" + media_id + "]").addClass("on");
    $(article_selector + " .article_media div[mediaid=" + media_id + "]").show();
    return false;
}

// Scrolls to an article if it was accessed from an external source, then sets the height of the section.
// Called on document.load, after all the images are loaded
function scrollToArticle() {
    var match = document.location.href.match(/article\/(\d+)/i);
    if(match != null) {
        scrollWindow('#news_content_wrapper', {'offset': -20});
    }
}

function loadTodayStats() {
    $.getJSON(getTodayStatsUrl, function(response) {
        $("#today_tweets").html(response["tweets"]);
        $("#videos_count").html(response["videos"]);
        $("#today_meetings").html(response["meetings"]);
        $("#next_barrel_house").html(response["barrel_house_hours"]);
        moodColor = "#" + response["mood_color"];
        moodText = response["mood_copy"];
        applyMood();
        shrinkMoodCopy();
        $("#today_stats .loading").hide();
        $("#today_stats .loaded").show();
    });
}
