function pageInit() {
	//$(".carouselSub").show();
	
	//Add first and last classes to all list items
	$("li:first-child").addClass("first");
	$("li:last-child").addClass("last");
	
	//Add/remove label element to search box
	$(".searchBox").focus(function() {
		//$(this).siblings("label").hide();
		var labelId = $(this).attr('id');
		$('label').filter(function (index) {
                  return $(this).attr("for") == labelId;
                }).hide()
	});
	$(".searchBox").blur(function() {
		if ($(this).val() == "") {
			//$(this).siblings("label").show();
			var labelId = $(this).attr('id');
			$('label').filter(function (index) {
                  return $(this).attr("for") == labelId;
             }).show()
		}
	});
	$('a.clear').click(function() {
		if ($(this).prev().val() != "") {
			$(this).prev().val("");
			$(this).prev().prev().show();
		}
	});
	if ($('#search').val() == "") {
		$('#search').prev().show();
	}
	
	//Detect js for nav
	$("nav.nojs").addClass('js');
	$("nav.nojs").removeClass('nojs');	
	
	//var activeMenu = $("li.mainNav").filter(".active");		
	//$(activeMenu).find("a.mainNavLink").append('<em class="activeLink"></em>');
	
	//Move 'more on this' component up from bottom of the page
	var paraCount = $("div.storyBody").children('p').size();
	var newPara = paraCount - 5;
	if(newPara > 1) {
		$("div.indent.more").insertAfter($("div.storyBody").children("p")[newPara]);
	} else {
		//$("div.indent.more").insertAfter($("div.indent.tools").next("p"));
	}
		
	//Delay the navigation
	var firstLvlCfg = {	
		over: 	function(){$(this).children("div.navbox").fadeIn(100);},  
		timeout: 300,
		out: 	function(){$(this).children("div.navbox").fadeOut(100);} 
	};
	$("nav ul li.subnav").hoverIntent(firstLvlCfg);
}

function recordOutboundLink(link, category, action) {
	var pageTracker = _gat._getTracker("UA-3674985-2");	
	pageTracker._trackEvent(category, action);
	setTimeout('document.location = "' + link.href + '"', 100);
}

function returnMoreBlogs(url, section, jpt, blogParams) {

	var start = $(".blogEntry").length;
	
	var end = start + 9;
	
	var params = {"begin": start, "end": end, "section": section, "jpt": jpt, "currentTimestamp":blogParams};
	
	$.ajax({
 		url: url,
  		data: params,		 			
 		cache: true,
 		success: function(html){
 			displayMoreBlogs(html, start, end);		    			
 		}
	});
	
}

function returnMore(queryParams, fileParams, htmlParams, counter, offset) { 

	var start = $(htmlParams.appendTo).find(".recentArticleWrapper").length;
	if (offset) {		
		start = start + 1;
	}
	var end = start + 9;
	
	if (counter != undefined) {
		end = start + counter;
	}	

	var ajaxData = {
		"begin": start, 
		"end": end, 
		"params": queryParams, 
		"jpt": fileParams.jpt, 
		"vquery": fileParams.vquery
	};
		
	$.ajax({
 		url: fileParams.jspUrl,
 		data: ajaxData,
 		cache: true,
 		success: function(html){ 
 			displayMore(html, start, end, htmlParams);		    			
 		}
	});
}

function returnMorePosts(url, params, jpt, vquery, counter, offset) { 

	var start = $(".recentArticleWrapper").length;
	if (offset) {		
		start = start + 1;
	}
	var end = start + 9;

	if (counter != undefined) {
		end = (start-1) + counter; //start value is +1 because of offset  
	}	

	$.ajax({
 		url: url,
 		data: {"begin": start, "end": end, "params": params, "jpt": jpt, "vquery": vquery},
 		cache: true,
 		success: function(html){ 
 			displayMoreArticles(html, start, end);		    			
 		}
	});
}

function returnMoreArticlesBySection(url, params, jpt, vquery, counter, section, offset) { 

	var start = $(".recentArticleWrapper").length;
	
	if (offset) {		
		start = start + 1;
	}
	var end = start + (counter - 1);
	
	$.ajax({
 		url: url,
 		data: {"begin": start, "end": end, "params": params, "jpt": jpt, "vquery": vquery, "dwpSection": section},
 		cache: true,
 		success: function(html){ 
 			displayMoreArticlesBySection(html, start, end, counter);		    			
 		}
	});
}

function returnMoreArticlesByTopicRC(url, params, jpt, vquery, counter, offset) { 

	var start = $(".recentArticleWrapper").length;
	
	if (offset) {		
		start = start + 1;
	}
	var end = start + (counter - 1);
	
	$.ajax({
 		url: url,
 		data: {"begin": start, "end": end, "params": params, "jpt": jpt, "vquery": vquery},
 		cache: true,
 		success: function(html){ 
 			displayMoreArticlesByTopic(html, start, end);		    			
 		}
	});
}

function returnMoreArticlesByTopic(url, params, jpt, vquery, counter, loid, offsetDisplay) { 

	var start = $(".recentArticleWrapper").length + offsetDisplay - 1;
	
	var end = start + (counter - 1) + offsetDisplay;
	
	var max = offsetDisplay + counter;
	
	$.ajax({
 		url: url,
 		data: {"begin": start, "end": end, "params": params, "jpt": jpt, "vquery": vquery, "loid": loid, "limit":counter},
 		cache: true,
 		success: function(html){ 
 			displayMoreArticlesByTopic(html, start, end, max);		    			
 		}
	});
}

// a generic version of displayMoreArticles
function displayMore(html, start, end, htmlParams) {

	if (jQuery.trim(html).length > 0) {
					
		htmlParams.appendTo.html(htmlParams.appendTo.html() + html);
   		$("#" + htmlParams.currentTabId + " .recentArticleWrapper").slice(start - 1, end - 1).hide().slideDown('slow').show();
   		var articles = $("#" + htmlParams.currentTabId + " .recentArticleWrapper").length;
   		
   		if (articles % 10 != 0) {   			
   			$("#" + htmlParams.currentTabId + " .moreBtn").hide();
   			$("#" + htmlParams.currentTabId + " .moreArticles").hide();
   		}   				
   		
   	   showLandingPageCounts();
   				    			
 	} else {
		$("#" + htmlParams.currentTabId + " .moreBtn").hide();
		$("#" + htmlParams.currentTabId + " .moreArticles").hide();
 	}

}


function displayMoreArticles(html, start, end) {

	if (jQuery.trim(html).length > 0) {	
		
		$("#recentArticles ol").html($("#recentArticles ol").html() + html);
   		$(".recentArticleWrapper").slice(start - 1, end - 1).hide().slideDown('slow').show();   		
		var articles = $("#recentArticles ol .recentArticleWrapper").length;
	
   		if(articles < end) end = articles;   		
   		 $.each($(".recentArticleWrapper").slice(start-1, end), function(i) {  
   		 	 if($(this).index() % 2 != 0)	
	   			$(this).children(".articleTeaser").addClass('even');
	   		 else
	   			$(this).children(".articleTeaser").addClass('odd');
   		});   		   		
   		
   		if (articles % 10 != 0) {  		   				
   			$(".moreBtn").hide();
   			$(".moreArticles").hide();
   		}   				
   		showLandingPageCounts();		    			
 	} else {
 		$(".moreBtn").hide();
 		$(".moreArticles").hide();
 	}

}

function displayMoreBlogs(html, start, end) {

	if (jQuery.trim(html).length > 0) {		
		$(".blogsWrapper").html($(".blogsWrapper").html() + html);
   		$(".blogEntry").slice(start - 1, end - 1).hide().slideDown('slow').show();
   		var blogs = $(".blogEntry").length;
   		if (blogs % 10 != 0) {
   			$(".moreBtn").hide();
   			$(".moreArticles").hide();
   		}
   		
   		if($(".backToTop").length == 0){
   			 $("#content").append("<a class='backToTop' href='#content'>Back to top</a>");   		
   			 $("footer").css({'margin-top':30+"px"});
   		}
   		
   		showLandingPageCounts();	    			
 	} else {
 		$(".moreBtn").hide();
 		$(".moreArticles").hide();
 	}
}

function displayMoreArticlesBySection(html, start, end, counter) {

	if (jQuery.trim(html).length > 0) {		
		$("#recentArticles ol").html($("#recentArticles ol").html() + html);
   		$(".recentArticleWrapper").slice(start - 1, end - 1).hide().slideDown('slow').show();
   		var articles = $("#recentArticles ol .recentArticleWrapper").length;
   		if (articles % counter != 0) {   
   			$(".moreBtn").hide();
   			$(".moreArticles").hide();
   		}   				
   		showLandingPageCounts();		    			
 	} else {
 		$(".moreBtn").hide();
 		$(".moreArticles").hide();
 	}
}

function displayMoreArticlesByTopic(html, start, end, max) {

	if (jQuery.trim(html).length > 0) {		
		$("#recentArticles ol").html($("#recentArticles ol").html() + html);
   		$(".recentArticleWrapper").slice(start - 1, end - 1).hide().slideDown('slow').show();
   		var articles = $("#recentArticles ol .recentArticleWrapper").length;
   		var diff = end - articles;
   		if ((articles % 5 != 0) || (diff > max)) {   
   			$(".moreBtn").hide();
   			$(".moreArticles").hide();
   		}   				
   		showLandingPageCounts();		    			
 	} else {
 		$(".moreBtn").hide();
 		$(".moreArticles").hide();
 	}

}

function refresh(page) {
	if ($('.videoContainer').length == 0 && $('.videoHolderContainer').length == 0) {
		if ($(".pluck-comment-input-box").val() !== undefined) {
			if ($(".pluck-comment-input-box").val() != "" || $(".pluck-comment-input-box").is(":focus")) {				
				setTimeout("refresh('article');",195000);
			} else {		
				reload();
			}	
		} else if ($('#fancybox-wrap').is(':visible')) {
			setTimeout("refresh('article');",195000);
		} else if (document.domain.indexOf('mmstats') > 0 || document.domain.indexOf('rankings') > 0) {
		 	return false;
		}else {
			reload();
		}
	}
}

function reload() {
	location.reload(true);
}


function tabsInit() {
	var url = document.location.href.split('?');
	var tab;
	if (url.length > 1) {
		switch(url[1]) {
			case 'details':
				tab = 'details';
				break;
			case 'subs':
				tab = 'subs';
				break;
			case 'updates':
				tab = 'updates';
				break;
			default:
				tab = $(".tabHeader li:first").attr('class').split(" ")[0];
				break;
		}
	} else {
		tab = $(".tabHeader li:first").attr('class').split(" ")[0];
	}
    showTab(tab);
    bindEvents();
}

function showTab(activeTab){ 			
	$('.tabContent#'+activeTab).fadeIn();
	$('.tabContent:not(#'+activeTab+')').hide();	
	//$('.tabHeader li.active').removeClass('active');
	//$('.tabHeader li.'+activeTab).addClass('active');

	$('li.'+activeTab).siblings().removeClass('active');
	$('.tabHeader li.'+activeTab).addClass('active');						
						
}

function bindEvents() {
	$('ul.tabHeader li a').click(function(e){
		e.preventDefault();			
		tab = $(this).parents("li").attr('class').split(" ")[0];			
		showTab(tab); 
	});	 
  
	$(".editDetail").click(function(){
		$(".tabView").hide()
		$(".tabEdit").fadeIn(500)
	});
	
	$(".cancelEditDetail").click(function(){
		$(".tabView").fadeIn(500)
		$(".tabEdit").hide()
	});
}


function twitter(username,count,renderTweetsParentId) {
	this.username =	username;
	this.count = count;
	this.renderTweetsParentId = renderTweetsParentId;
	this.getTweets = function() {
		var obj = this;
		var items = [];
		var countUrl = "https://api.twitter.com/1/account/rate_limit_status.json?callback=?";
		$.getJSON(countUrl, function(countData) {
			if (parseInt(countData.remaining_hits) > 0) {
				var url = "https://api.twitter.com/1/statuses/user_timeline.json?include_entities=false&include_rts=true&exclude_replies=true&screen_name="+ obj.username +"&count="+ obj.count +"&callback=?"
				$.getJSON(url, function(tweetData) {
					$.each(tweetData, function(key, val) {
						var tweetDataArr = [];
						tweetDataArr['text'] = renderLinks(tweetData[key].text);
						tweetDataArr['date'] = convertToRelativeTime(tweetData[key].created_at);
						items.push(tweetDataArr);
					});
					obj.renderTweetsCallback(items);
				});
			} else {
				var tweetDataArr = [];
				tweetDataArr['text'] = 'Rate limit exceeded';
				tweetDataArr['date'] = '';
				items.push(tweetDataArr);
				obj.renderTweetsCallback(items);
			}
		});
	};
	this.renderTweetsCallback = function(dataArr) {
		var obj = this;
		$('.twitterContainer#' + obj.renderTweetsParentId).empty();
		$.each(dataArr, function(key, val) {
			var html = '<div class="tweet clearfix"><div class="left twitterAccountIcon '+ obj.renderTweetsParentId +'Icon"></div><div class="left tweetData"><p class="tweetText">'+ dataArr[key]['text'] +'</p><p class="tweetTime">'+ dataArr[key]['date'] +'</p></div></div>'
			$('.twitterContainer#' + obj.renderTweetsParentId).append(html);
		});
	};
}

function convertToRelativeTime(a) {
	var K = function () {
		var a = navigator.userAgent;
		return {
			ie: a.match(/MSIE\s([^;]*)/)
		}
	}();
	 
	var b = new Date();
	var c = new Date(a);
	if (K.ie) {
		c = Date.parse(a.replace(/( \+)/, ' UTC$1'))
	}
	var d = b - c;
	var e = 1000,
		minute = e * 60,
		hour = minute * 60,
		day = hour * 24,
		week = day * 7;
	if (isNaN(d) || d < 0) {
		return ""
	}
	if (d < e * 7) {
		return "right now"
	}
	if (d < minute) {
		return Math.floor(d / e) + " seconds ago"
	}
	if (d < minute * 2) {
		return "about 1 minute ago"
	}
	if (d < hour) {
		return Math.floor(d / minute) + " minutes ago"
	}
	if (d < hour * 2) {
		return "about 1 hour ago"
	}
	if (d < day) {
		return Math.floor(d / hour) + " hours ago"
	}
	if (d > day && d < day * 2) {
		return "yesterday"
	}
	if (d < day * 365) {
		return Math.floor(d / day) + " days ago"
	} else {
		return "over a year ago"
	}
}
	
function renderLinks(text) {
	var base_url = 'http://twitter.com/';   // identica: 'http://identi.ca/'
    var hashtag_part = 'search?q=#';        // identica: 'tag/'
    var mention_part = '';              // identica: ''
    // convert URLs into links
    text = text.replace(
        /(>|<a[^<>]+href=['"])?(https?:\/\/([-a-z0-9]+\.)+[a-z]{2,5}(\/[-a-z0-9!#()\/?&.,]*[^ !#?().,])?)/gi,
        function($0, $1, $2) {
            return ($1 ? $0 : '<a href="' + $2 + '" target="_blank">' + $2 + '</a>');
        });
    // convert protocol-less URLs into links
    text = text.replace(
        /(:\/\/|>)?\b(([-a-z0-9]+\.)+[a-z]{2,5}(\/[-a-z0-9!#()\/?&.]*[^ !#?().,])?)/gi,
        function($0, $1, $2) {
            return ($1 ? $0 : '<a href="http://' + $2 + '">' + $2 + '</a>');
        });
    // convert @mentions into follow links
    text = text.replace(
        /(:\/\/|>)?(@([_a-z0-9\-]+))/gi,
        function($0, $1, $2, $3) {
            return ($1 ? $0 : '<a href="' + base_url + mention_part + $3
                + '" title="Follow ' + $3 + '" target="_blank">@' + $3
                + '</a>');
        });
    // convert #hashtags into tag search links
    text = text.replace(
        /(:\/\/[^ <]*|>)?(\#([_a-z0-9\-]+))/gi,
        function($0, $1, $2, $3) {
            return ($1 ? $0 : '<a href="' + base_url + hashtag_part + $3
                + '" title="Search tag: ' + $3 + '" target="_blank">#' + $3
                + '</a>');
        });
    return text;
}

