var tweetHtml = [];
var stopCarousel = false;
jQuery(document).ready(function($){      
    if ($('body').attr('id') == 'tweets-landing') {
        var pageType = 'tweetPage';
        loadTweets('_all','tweetPage');
        
        $('#tweets #tabs a').click(function(){
            $('#tweets #tabs a').parent().removeClass('selected');
            $(this).parent().addClass('selected');
            var tweetCat = $(this).attr('class');
            if (tweetCat == 'all') { tweetCat = '_all'; }
            loadTweets(tweetCat, 'tweetPage');
            return false;
        });
    }
    if ($('div').hasClass('tweets')) {
		var tweetCat = '_all';
        if ($('.tweets').attr('id') != '') {
            tweetCat = $('.tweets').attr('id');
            tweetCat = tweetCat.replace(/-tweets/, '');
            if (tweetCat == 'all') { tweetCat = '_all'; }
        }
	//Start: error somewhere here
	var pageType = 'widget';
        if ($('body').attr('id') == 'home') {
            loadTweets('lifescoop','widget');
            $('.tweets .selectors li').removeClass('selected');
            $('.tweets .selectors li.filter-lifescoop').addClass('selected');
        } else {
            loadTweets(tweetCat,'widget');
        }
	//End: error somewhere here
        
        $('.tweets .selectors li').click(function(){
            if ($(this).attr('class') != '') {
                $('.tweets .selectors li').removeClass('selected');
                var tweetVert = $(this).attr('class').replace(/filter-/, '');
                if (tweetVert == 'all') { tweetVert = '_all'; }
                $(this).addClass('selected');
                loadTweets(tweetVert,'widget');
                if ($(this).hasClass('more')) {
                    return true;
                } else {
                    return false;
                }
            }
        });        
    }
    if ($('body').hasClass('has-carousel')) {
        $('.featured li').css('display','block');
        numStories = $('.featured li').length;
        carouselStatus('1');
        var status, loopCount = 0;
		
        $('.featured').jCarouselLite({
            btnNext: ".next", /*btnNext: "#next-story",*/
            btnPrev: ".prev", /*btnPrev: "#prev-story",*/
            visible: 1,
            pause: true,
            auto: 6000,
            speed: 750,
            circular: false,
            afterEnd: function(a) {
                status = $(a[0]).attr('class');                
                if (parseInt(status.replace('item-', '')) === 5)
                {
                    loopCount ++;
	            if (loopCount === 2) {
                        $(document).trigger('pauseCarousel');
                    }
                }
	    }
        });
    }
    // Creating custom :external selector
    $.expr[':'].external = function(obj){
        return !obj.href.match(/^mailto\:/)
                && (obj.hostname != location.hostname)
                && (obj.hostname != 'www.typepad.com')
                && (obj.hostname != 'community.mylifescoop.com');
    };
    
    // Add 'external' CSS class to all external links
    $('a:external').attr('target','_blank');
    
    // Fix comment count
    $("a.qa-answers").each(function(i){
		if (!$(this).html().match(/comment/)) {
			regex = /[0-9]{1,5}/;
			re = regex.exec($(this).html());
			totalComments = parseInt(re) + parseInt($(this).attr("at:comment-count"));
			$(this).html("Answers (" + totalComments + ")");
		}
	});
	$('.entry-archive .entry-body').ready(function() {
		var text = $('.entry-archive .entry-body').html();
                var pages;
                if (text != null) {
                var pages = text.split('<!-- PAGE BREAK -->');
		if (pages.length <= 1 || $.query.get('page') == 'all') {
			$('.entry-archive .entry-body').show();
		} else {
			var thisPage = parseInt($.query.get('page')) - 1;
			if (isNaN(thisPage)) { thisPage = 0; }
			if (thisPage < 0) { thisPage = 0; }
			if (thisPage >= pages.length) { thisPage = 0; }
			$('.entry-archive .entry-body').html(pages[thisPage]).show();
			$('h1.entry-archive').after('<h4 class="page-number"></h4>').addClass('has-byline');
			$('h4.page-number').html('Page ' + (thisPage + 1) + ' of ' + pages.length);
			$('.entry-archive .entry-body').append('<div id="pagination-nav"></div>');
			if (thisPage - 1 >= 0) {
				var prevPage = thisPage;
				$('#pagination-nav').append('<li><a href="?page=' + prevPage + '">&laquo; Previous</a></li>');
			} 
			$.each(pages, function(i) {
				curPage = i + 1;
				if (i == thisPage) {
					$('#pagination-nav').append('<li>' + curPage + '</li>');						
				} else {
					$('#pagination-nav').append('<li><a href="?page=' + curPage + '">' + curPage + '</a></li>');						
				}
			});
			if (thisPage + 2 <= pages.length) {
				var nextPage = thisPage + 2;
				$('#pagination-nav').append('<li><a href="?page=' + nextPage + '">Next &raquo;</a></li>');
			} 			
		}
                }
	});
});
function autoLink(str) {
    // returns an autolinked string.
    var r = /((ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?)/gi;
    return str.replace(r, '<a href="$1" target="_blank">$1</a>');
};
function loadTweets(vert,loc) {
    if (loc == 'tweetPage') { var container = '#tweet-list ul'; } else { var container = '#the-tweets'; }
    jQuery(container).html('');
    if (!tweetHtml[vert]) {
        jQuery('.loading').show();
        //jQuery.getJSON('http://mylifescoop.com/mt-static/tweets/' + vert + '.json',        
        jQuery.getJSON('/mt-static/tweets/' + vert + '.json',                
        function(data){
                if (loc == 'tweetPage') {
                    jQuery.each(data[0],function(i,item) {
                        
                        jQuery('#tweet-list ul').append('<li><p><a href="http://twitter.com/' + item.from_user + '" class="username" target="_blank">' + item.from_user + '</a> ' + autoLink(item.text) + ' <a href="http://twitter.com/' + item.from_user + '/statuses/' + item.id + '">' + relative_time(item.created_at) + '</a> <a href="http://twitter.com/home?status=@' + item.from_user + ' &in_reply_to_status_id=' + item.id + '&in_reply_to=' + item.from_user + '" class="response" target="_blank">REPLY</a><a href="http://twitter.com/home?status=' + item.text + ' (via @' + item.from_user + ')" class="response" target="_blank">RT</a></p></li>');
                    });
                    jQuery('#tweet-list li:odd').addClass('zebra');
                } else {
                    jQuery.each(data[0],function(i,item){
                        jQuery('#the-tweets').append('<li><span><a href="http://twitter.com/' + item.from_user + '" class="username" target="_blank">' + item.from_user + '</a></span> ' + autoLink(item.text) + '</li>');
                        if (i == 2) return false;
                    });
                    jQuery('#the-tweets li:odd').addClass('zebra');
                }
            
            jQuery('.loading').hide();
            tweetHtml[vert] = jQuery(container).html();
        });
    } else {
        jQuery(container).html(tweetHtml[vert]);
    }
}
// From http://ralphwhitbeck.com/content/binary/twitter-json-jquery.html
// Modified to fit the date format returned by the search API
function relative_time(time_value) {
	var values = time_value.split(" ");
	time_value = values[2] + " " + values[1] + ", " + values[3] + " " + values[4];
	var parsed_date = Date.parse(time_value);
	var relative_to = (arguments.length > 1) ? arguments[1] : new Date();
	var delta = parseInt((relative_to.getTime() - parsed_date) / 1000);
	delta = delta + (relative_to.getTimezoneOffset() * 60);
	
	var r = '';
	if (delta < 60) {
	r = 'a minute ago';
	} else if(delta < 120) {
	r = 'couple of minutes ago';
	} else if(delta < (45*60)) {
	r = (parseInt(delta / 60)).toString() + ' minutes ago';
	} else if(delta < (90*60)) {
	r = 'an hour ago';
	} else if(delta < (24*60*60)) {
	r = '' + (parseInt(delta / 3600)).toString() + ' hours ago';
	} else if(delta < (48*60*60)) {
	r = '1 day ago';
	} else {
	r = (parseInt(delta / 86400)).toString() + ' days ago';
	}
	
	return r;
}
function carouselStatus(status) {
    jQuery('#featured-status').html(status + ' of ' + numStories);
}