var tw_http_request = false;

firstBlogPostPosition = -1;
firstTweetPostPosition = -1;

function makeTWRequest(url, parameters) {
	tw_http_request = false;
	if (window.XMLHttpRequest) { // Mozilla, Safari,...
	tw_http_request = new XMLHttpRequest();
	if (tw_http_request.overrideMimeType) {
		tw_http_request.overrideMimeType('text/xml');
	}
	}
	else if (window.ActiveXObject) { // IE
		try {
			tw_http_request = new ActiveXObject("Msxml2.XMLHTTP");
	 	}
		catch (e) {
			try {
		   		tw_http_request = new ActiveXObject("Microsoft.XMLHTTP");
			}
			catch (e) {}
	 	}
	}
	if (!tw_http_request) {
		alert('Cannot create XMLHTTP instance');
		return false;
	}
	tw_http_request.onreadystatechange = renderContents;
	tw_http_request.open('GET', url + parameters, true);
	tw_http_request.send(null);
}

function renderContents() {
	var docBlogOutput = "";
	var docTweetOutput = "";
	
	var validBlogPostsCounter = 0;
	var validTweetPostsCounter = 0;
	
	var showBlogPosts = false;
	var showTweetPosts = false;
	
	var nodeIndex = 0;
	
	var commentsPP = 10;
	var commentsStart = 0;
	var unadjustedCommentsStart = 0;
	
	var actualCommentsStart = 0;

	if (tw_http_request.readyState == 4) {
		if (tw_http_request.status == 200) {
			var xmldoc = tw_http_request.responseXML;
			var doc_nodes = xmldoc.getElementsByTagName("document");
			
			for (nodeIndex = 0; nodeIndex < doc_nodes.length; nodeIndex++) {
				if (doc_nodes[nodeIndex].getAttribute("type")=="micro") {
					validTweetPostsCounter++;
				}
				else if (doc_nodes[nodeIndex].getAttribute("type")=="blog") {
					validBlogPostsCounter++;
				}
			}
	
			if (arguments.length > 2) {
				if (arguments[2]=="blog") {
					showBlogPosts = true;
				}
				else if (arguments[2]=="micro") {
					showTweetPosts = true;
				}
				else {
					showBlogPosts = true;
					showTweetPosts = true;
				}
			}
			else {
				showBlogPosts = true;
				showTweetPosts = true;
			}

			if (showBlogPosts && document.getElementById("twinglyBlogCommentsList")) {
				if (arguments.length > 1) {
					if (arguments[1]<validBlogPostsCounter) {
						commentsStart = arguments[1];
					}
					else {
						commentsStart = validBlogPostsCounter - commentsPP;
					}
					
					unadjustedCommentsStart = commentsStart;
					
					for (nodeIndex = 0; nodeIndex < doc_nodes.length; nodeIndex++) {
						if (doc_nodes[nodeIndex].getAttribute("type")=="blog" && actualCommentsStart < commentsStart) {
							actualCommentsStart++;
						}
						else if (doc_nodes[nodeIndex].getAttribute("type")=="blog" && actualCommentsStart >= commentsStart) {
							break;	
						}
					}
					commentsStart = nodeIndex;
				}
				
				if (commentsStart>0) {
					/*docBlogOutput = "<a href=\"Javascript://F&ouml;rsta\" onclick=\"renderContents(null, 0, 'blog');\">&laquo;&nbsp;F&ouml;rsta</a><a href=\"Javascript://F&ouml;rra\" onclick=\"renderContents(null, " + (unadjustedCommentsStart-commentsPP) + ", 'blog');\">F&ouml;rra</a>";*/
				}

				if (docBlogOutput != "") {
					//docBlogOutput = docBlogOutput + "&nbsp;&nbsp;&nbsp;&nbsp;";
				}
				
				
				/*if (commentsStart+commentsPP<validBlogPostsCounter) {
					docBlogOutput = docBlogOutput + "<a href=\"Javascript://N&auml;sta\" onclick=\"renderContents(null, " + (unadjustedCommentsStart+commentsPP) + ", 'blog');\">N&auml;sta</a><a class=last href=\"Javascript://Sista\" onclick=\"renderContents(null, " + (Math.floor( validBlogPostsCounter / commentsPP )*10) + ", 'blog');\">Sista&nbsp;&raquo;</a>";
					maxComments = commentsStart+commentsPP;
				}
				else {
					maxComments = validBlogPostsCounter;
				}*/
	
				if (docBlogOutput != "") {
					//docBlogOutput = "<li class=\"pagination\">" + docBlogOutput + "</li>"; //tar bort första i varje spalt
				}
	
				//docBlogOutput = docBlogOutput + "<br />";

				currentViewBlogPostsCounter = 0;

				for (nodeIndex = commentsStart; nodeIndex < doc_nodes.length; nodeIndex++) {
					if (doc_nodes[nodeIndex].getAttribute("type")=="blog" && currentViewBlogPostsCounter < commentsPP) {
						url_node = doc_nodes[nodeIndex].getElementsByTagName("url");
						link_node = doc_nodes[nodeIndex].getElementsByTagName("link");
						title_node = doc_nodes[nodeIndex].getElementsByTagName("title");
						websiteName_node = doc_nodes[nodeIndex].getElementsByTagName("websiteName");
						date_node = doc_nodes[nodeIndex].getElementsByTagName("date");
						
						if (date_node[0].firstChild) {
							date_value = date_node[0].firstChild.nodeValue;
						}
						else {
							date_value = "1/1/2009 0:00:00 AM";
						}
						
						if (link_node[0].firstChild) {
							commentedArticleLink = link_node[0].firstChild.nodeValue;
						}
						else {
							commentedArticleLink = "#";	
						}

						if (thisURL != commentedArticleLink && validBlogPostsCounter<numOfPosts) {
							if (firstBlogPostPosition == -1) {
								firstBlogPostPosition = nodeIndex;
							}
							
							postDay=date_value.substr(date_value.indexOf("/")+1, date_value.indexOf("/", date_value.indexOf("/")+1)-(date_value.indexOf("/")+1));
							postMonth=date_value.substr(0, date_value.indexOf("/"));
							postYear=date_value.substr(date_value.indexOf("/", date_value.indexOf("/")+1)+1, date_value.indexOf(" ")-date_value.indexOf("/", date_value.indexOf("/")+1)-1);
							postTime=trim(date_value.substr(date_value.indexOf(" ")+1, date_value.indexOf(" ", date_value.indexOf(" "))-2));
		
							postDate=postYear + "-" + postMonth + "-" + postDay + "T" + postTime + "Z";
							currentViewBlogPostsCounter++;
							docBlogOutput = docBlogOutput + "<li class=clearfix>\n";
							docBlogOutput = docBlogOutput + "<h2><a target=\"_blank\" href=\"" + url_node[0].firstChild.nodeValue + "\" title=\"" + websiteName_node[0].firstChild.nodeValue + "\">" + websiteName_node[0].firstChild.nodeValue + "</a></h2>\n";
							docBlogOutput = docBlogOutput + "<p>" + title_node[0].firstChild.nodeValue + "</p>\n";
							docBlogOutput = docBlogOutput + "<p class=\"commentmetadata\">" + prettyDate(postDate) + "</p>\n";
							docBlogOutput = docBlogOutput + "<div class=\"abuse clearfix\" id=\"reportLabel" + nodeIndex + "\">\n";
							docBlogOutput = docBlogOutput + "<form name=\"reportCommentForm" + nodeIndex + "\" method=\"GET\" action=\"\">\n";
							docBlogOutput = docBlogOutput + "<input type=\"hidden\" name=\"refurl\" value=\"" + commentedArticleLink + "\" />\n";
							docBlogOutput = docBlogOutput + "<input type=\"hidden\" name=\"url\" value=\"" + url_node[0].firstChild.nodeValue + "\" />\n";
							docBlogOutput = docBlogOutput + "<input type=\"hidden\" name=\"commentIndex\" value=\"" + nodeIndex + "\" />\n";
							docBlogOutput = docBlogOutput + "<a  id=\"reportLink" + nodeIndex + "\" href=\"Javascript://\" onclick=\"showCommentReporting(" + nodeIndex + ");\" title=\"Anm&auml;l\">Anm&auml;l</a>\n";
							//docBlogOutput = docBlogOutput + "<span id=\"reportDisplay" + nodeIndex + "\" style=\"display:block;\">\n";
							//docBlogOutput = docBlogOutput + "<span id=\"reportSpan\">";
							docBlogOutput = docBlogOutput + "<select id=\"reportDisplay" + nodeIndex + "\" style=\"display:none;\" size=1 name=\"action\" onchange=\"reportComment(this);\">\n";
							docBlogOutput = docBlogOutput + "<option value=\"\">- Anm&auml;l -</option>\n";
							docBlogOutput = docBlogOutput + "<option value=\"spam\">Spam</option>\n";
							docBlogOutput = docBlogOutput + "<option value=\"opassande\">Opassande</option>\n";
							docBlogOutput = docBlogOutput + "<option value=\"irrelevant\">Irrelevant</option>\n";
							docBlogOutput = docBlogOutput + "</select>\n";
							//docBlogOutput = docBlogOutput + "</span>\n"					
							//docBlogOutput = docBlogOutput + "</span>\n"
							docBlogOutput = docBlogOutput + "</form>\n";
							docBlogOutput = docBlogOutput + "</div>\n";
							docBlogOutput = docBlogOutput + "</li>\n";
						}
					}
				}
				
				if (docBlogOutput != "") {
				
					docBlogOutput = docBlogOutput + "<li class=\"pagination\">";
					
					if (commentsStart>firstBlogPostPosition) {
						docBlogOutput = docBlogOutput +  "<a href=\"Javascript://F&ouml;rsta\" onclick=\"renderContents(null, 0, 'blog');\">&laquo;&nbsp;F&ouml;rsta</a><a href=\"Javascript://F&ouml;rra\" onclick=\"renderContents(null, " + (unadjustedCommentsStart-commentsPP) + ", 'blog');\">F&ouml;rra</a>";
					}
					
					if (docBlogOutput != "") {
						//docBlogOutput = docBlogOutput + "&nbsp;"; //make css
					}
				
					if (commentsStart+commentsPP<validBlogPostsCounter) {
						docBlogOutput = docBlogOutput + "<a href=\"Javascript://N&auml;sta\" onclick=\"renderContents(null, " + (unadjustedCommentsStart+commentsPP) + ", 'blog');\">N&auml;sta</a><a class=last href=\"Javascript://Sista\" onclick=\"renderContents(null, " + (Math.floor( validBlogPostsCounter / commentsPP )*10) + ", 'blog');\">Sista&nbsp;&raquo;</a>";
					}
					
					docBlogOutput = docBlogOutput + "</li>";
				
					document.getElementById("twinglyBlogCommentsList").innerHTML = docBlogOutput;
				}
			}
						
			if (showTweetPosts && document.getElementById("twinglyTweetCommentsList")) {
				if (arguments.length > 1) {
					if (arguments[1]<validTweetPostsCounter) {
						commentsStart = arguments[1];
					}
					else {
						commentsStart = validTweetPostsCounter - commentsPP;
					}
					
					unadjustedCommentsStart = commentsStart;
					
					for (nodeIndex = 0; nodeIndex < doc_nodes.length; nodeIndex++) {
						if (doc_nodes[nodeIndex].getAttribute("type")=="micro" && actualCommentsStart < commentsStart) {
							actualCommentsStart++;
						}
						else if (doc_nodes[nodeIndex].getAttribute("type")=="micro" && actualCommentsStart >= commentsStart) {
							break;	
						}
					}
					commentsStart = nodeIndex;
				}
				
				if (commentsStart>0) {
					/*docTweetOutput = "<a href=\"Javascript://F&ouml;rsta\" onclick=\"renderContents(null, 0, 'micro');\">&laquo;&nbsp;F&ouml;rsta</a><a href=\"Javascript://F&ouml;rra\" onclick=\"renderContents(null, " + (unadjustedCommentsStart-commentsPP) + ", 'micro');\">F&ouml;rra</a>";*/
				}

				if (docTweetOutput != "") {
					//docTweetOutput = docTweetOutput + "&nbsp;"; //make css
				}
				
				/*if (commentsStart+commentsPP<validTweetPostsCounter) {
					docTweetOutput = docTweetOutput + "<a href=\"Javascript://N&auml;sta\" onclick=\"renderContents(null, " + (unadjustedCommentsStart+commentsPP) + ", 'micro');\">N&auml;sta</a><a class=last href=\"Javascript://Sista\" onclick=\"renderContents(null, " + (Math.floor( validTweetPostsCounter / commentsPP )*10) + ", 'micro');\">Sista&nbsp;&raquo;</a>";
					maxComments = commentsStart+commentsPP;
				}
				else {
					maxComments = validTweetPostsCounter;
				}*/
	
				if (docTweetOutput != "") {
					//docTweetOutput = "<li class=\"pagination\">" + docTweetOutput + "</li>"; //ta bort sista i varje spalt
				}
	
				//docTweetOutput = docTweetOutput + "<br />";

				currentViewTweetPostsCounter = 0;
									
				for (nodeIndex = commentsStart; nodeIndex < doc_nodes.length; nodeIndex++) {
					if (doc_nodes[nodeIndex].getAttribute("type")=="micro" && currentViewTweetPostsCounter < commentsPP) {
						url_node = doc_nodes[nodeIndex].getElementsByTagName("url");
						link_node = doc_nodes[nodeIndex].getElementsByTagName("link");
						title_node = doc_nodes[nodeIndex].getElementsByTagName("title");
						websiteName_node = doc_nodes[nodeIndex].getElementsByTagName("websiteName");
						date_node = doc_nodes[nodeIndex].getElementsByTagName("date");
						
						if (date_node[0].firstChild) {
							date_value = date_node[0].firstChild.nodeValue;
						}
						else {
							date_value = "1/1/2009 0:00:00 AM";
						}
						
						if (link_node[0].firstChild) {
							commentedArticleLink = link_node[0].firstChild.nodeValue;
						}
						else {
							commentedArticleLink = "#";	
						}

						if (thisURL != commentedArticleLink && validTweetPostsCounter<numOfPosts) {
							if (firstTweetPostPosition == -1) {
								firstTweetPostPosition = nodeIndex;
							}
						
							postDay=date_value.substr(date_value.indexOf("/")+1, date_value.indexOf("/", date_value.indexOf("/")+1)-(date_value.indexOf("/")+1));
							postMonth=date_value.substr(0, date_value.indexOf("/"));
							postYear=date_value.substr(date_value.indexOf("/", date_value.indexOf("/")+1)+1, date_value.indexOf(" ")-date_value.indexOf("/", date_value.indexOf("/")+1)-1);
							postTime=trim(date_value.substr(date_value.indexOf(" ")+1, date_value.indexOf(" ", date_value.indexOf(" "))-2));
		
							postDate=postYear + "-" + postMonth + "-" + postDay + "T" + postTime + "Z";
							currentViewTweetPostsCounter++;
							docTweetOutput = docTweetOutput + "<li class=clearfix>\n";
							docTweetOutput = docTweetOutput + "<h2><a target=\"_blank\" href=\"" + url_node[0].firstChild.nodeValue + "\" title=\"" + websiteName_node[0].firstChild.nodeValue + "\">" + websiteName_node[0].firstChild.nodeValue + "</a></h2>\n";
							docTweetOutput = docTweetOutput + "<p>" + title_node[0].firstChild.nodeValue + "</p>\n";
							docTweetOutput = docTweetOutput + "<p class=\"commentmetadata\">" + prettyDate(postDate) + "</p>\n";
							
							docTweetOutput = docTweetOutput + "<div class=\"abuse clearfix\" id=\"reportLabel" + nodeIndex + "\">\n";
							docTweetOutput = docTweetOutput + "<form name=\"reportCommentForm" + nodeIndex + "\" method=\"GET\" action=\"\">\n";
							docTweetOutput = docTweetOutput + "<input type=\"hidden\" name=\"refurl\" value=\"" + commentedArticleLink + "\" />\n";
							docTweetOutput = docTweetOutput + "<input type=\"hidden\" name=\"url\" value=\"" + url_node[0].firstChild.nodeValue + "\" />\n";
							docTweetOutput = docTweetOutput + "<input type=\"hidden\" name=\"commentIndex\" value=\"" + nodeIndex + "\" />\n";
							docTweetOutput = docTweetOutput + "<a id=\"reportLink" + nodeIndex + "\" href=\"Javascript://\" onclick=\"showCommentReporting(" + nodeIndex + ");\" title=\"Anm&auml;l\">Anm&auml;l</a>\n";
							//docTweetOutput = docTweetOutput + "<span id=\"reportDisplay" + nodeIndex + "\" style=\"display:none;\">\n";
							//docTweetOutput = docTweetOutput + "<span id=\"reportSpan\">";
							docTweetOutput = docTweetOutput + "<select id=\"reportDisplay" + nodeIndex + "\" style=\"display:none;\" size=1 name=\"action\" onchange=\"reportComment(this);\">\n";
							docTweetOutput = docTweetOutput + "<option value=\"\">- Anm&auml;l -</option>\n";
							docTweetOutput = docTweetOutput + "<option value=\"spam\">Spam</option>\n";
							docTweetOutput = docTweetOutput + "<option value=\"opassande\">Opassande</option>\n";
							docTweetOutput = docTweetOutput + "<option value=\"irrelevant\">Irrelevant</option>\n";
							docTweetOutput = docTweetOutput + "</select>\n";
							//docTweetOutput = docTweetOutput + "</span>\n"					
							//docTweetOutput = docTweetOutput + "</span>\n"
							docTweetOutput = docTweetOutput + "</form>\n";
							docTweetOutput = docTweetOutput + "</div>\n";

							docTweetOutput = docTweetOutput + "</li>\n";
						}
					}
				}
				
				
				if (docTweetOutput != "") {
				
					docTweetOutput = docTweetOutput + "<li class=\"pagination\">";

					if (commentsStart>firstTweetPostPosition) {
						docTweetOutput = docTweetOutput +  "<a href=\"Javascript://F&ouml;rsta\" onclick=\"renderContents(null, 0, 'micro');\">&laquo;&nbsp;F&ouml;rsta</a><a href=\"Javascript://F&ouml;rra\" onclick=\"renderContents(null, " + (unadjustedCommentsStart-commentsPP) + ", 'micro');\">F&ouml;rra</a>";
					}
					
					if (docTweetOutput != "") {
						//docTweetOutput = docTweetOutput + "&nbsp;"; //make css
					}
				
					if (commentsStart+commentsPP<validTweetPostsCounter) {
						docTweetOutput = docTweetOutput + "<a href=\"Javascript://N&auml;sta\" onclick=\"renderContents(null, " + (unadjustedCommentsStart+commentsPP) + ", 'micro');\">N&auml;sta</a><a class=last href=\"Javascript://Sista\" onclick=\"renderContents(null, " + (Math.floor( validTweetPostsCounter / commentsPP )*10) + ", 'micro');\">Sista&nbsp;&raquo;</a>";
					}
					
					docTweetOutput = docTweetOutput + "</li>";
				
					document.getElementById("twinglyTweetCommentsList").innerHTML = docTweetOutput;
				}
			}
			
			var twingly_summary_stats_widget_nodes = xmldoc.getElementsByTagName("widget");
			
			if (twingly_summary_stats_widget_nodes) {
				uniqueNumberOfLinkingMicroblogs = twingly_summary_stats_widget_nodes[0].getAttribute("uniqueNumberOfLinkingMicroblogs");
				uniqueNumberOfLinkingBlogs = twingly_summary_stats_widget_nodes[0].getAttribute("uniqueNumberOfLinkingBlogs");
					
				updateFlash('numBlogPosts', uniqueNumberOfLinkingBlogs);
				updateFlash('numMicroblogPosts', uniqueNumberOfLinkingMicroblogs);
				updateFlash('numForumPosts', familjeliv_numPosts);
				updateFlash('numComments', numcomms);

				varsLoaded = true;
			}
		}
	}
}

function getMicroPostsTotals() {
	if (tw_http_request.readyState == 4) {
		if (tw_http_request.status == 200) {

			var xmldoc = tw_http_request.responseXML;
						
			var twingly_summary_stats_widget_nodes = xmldoc.getElementsByTagName("widget");
			
			if (twingly_summary_stats_widget_nodes) {
				//document.getElementById("microcounter").innerHTML = twingly_summary_stats_widget_nodes[0].getAttribute("uniqueNumberOfLinkingMicroblogs");
				updateFlash('numMicroblogPosts', twingly_summary_stats_widget_nodes[0].getAttribute("uniqueNumberOfLinkingMicroblogs"));
			}
			
			calculateTotalCommentsPosts();
		}
	}
}

function showCommentReporting(commentIndex) {
	document.getElementById("reportDisplay" + commentIndex).style.display="block";
	document.getElementById("reportLink" + commentIndex).style.display="none";
}

function reportComment(sel) {
	frm = sel.form;
	getTwinglyData("/getTwinglyCounter.php?webAddress=http://api.twingly.com/widget/abusereport.ashx?url=" + urlencode(frm.url.value) + "%26action=" + sel[sel.selectedIndex].value + "%26refurl=" + urlencode(frm.refurl.value) + "%23respond", frm.commentIndex.value, "handleReceivedAbuseReport");
}

function handleReceivedAbuseReport() {
	if (receiveReq.readyState == 4) {
		document.getElementById("reportDisplay" + displayID).style.display="none";
		document.getElementById("reportLabel" + displayID).style.display="none";
	}
}

function addrow(tablename, arr) {
	var tbl = document.getElementById(tablename);
	var lastRow = tbl.rows.length;
	var row = tbl.insertRow(lastRow);
	for (r = 0; r < arr.length; r++) {   
		var cell = row.insertCell(r);
		cell.innerHTML = arr[r];
	}
}

function prettyDate(time){
	var date = new Date((time || "").replace(/-/g,"/").replace(/[TZ]/g," ")),
		diff = (((new Date()).getTime() - date.getTime()) / 1000),
		day_diff = Math.floor(diff / 86400);

	if ( isNaN(day_diff) || day_diff < 0 )
		return "";

	return day_diff == 0 && (
			diff < 60 && "just nu" ||
			diff < 120 && "1 minut sedan" ||
			diff < 3600 && Math.floor( diff / 60 ) + " minuter sedan" ||
			diff < 7200 && "1 timme sedan" ||
			diff < 86400 && Math.floor( diff / 3600 ) + " timmar sedan") ||
		day_diff == 1 && "Ig&aring;r" ||
		day_diff < 7 && day_diff + " dagar sedan" ||
		day_diff < 9000 && Math.ceil( day_diff / 7 ) + " veckor sedan";
}

function urlencode( str ) {
    var ret = str;
    
    ret = ret.toString();
    ret = encodeURIComponent(ret);
    ret = ret.replace(/%20/g, '+');
 
    return ret;
}

// If jQuery is included in the page, adds a jQuery plugin to handle it as well
if ( typeof jQuery != "undefined" ) {
	jQuery.fn.prettyDate = function(){
		return this.each(function(){
			var date = prettyDate(this.title);
			if ( date )
				jQuery(this).text( date );
		});
	};
}

function trim(str, chars) {
	return ltrim(rtrim(str, chars), chars);
}
 
function ltrim(str, chars) {
	chars = chars || "\\s";
	return str.replace(new RegExp("^[" + chars + "]+", "g"), "");
}
 
function rtrim(str, chars) {
	chars = chars || "\\s";
	return str.replace(new RegExp("[" + chars + "]+$", "g"), "");
}