var descList = new Array();
var itemList = "";

function escapeHTML (str)
{
   var div = document.createElement('div');
   var text = document.createTextNode(str);
   div.appendChild(text);
   return div.innerHTML;
};

function truncateParagraph(trunc,len) {
  if (trunc.length> len) {
    trunc = trunc.substring(0, len);
    trunc = trunc.replace(/\w+$/, '');
    trunc += '...';
  }
  
  return trunc;
}

function removeHTMLTags(htmlString){
	htmlString = htmlString.replace(/&(lt|gt);/g, function (strMatch, p1){
		return (p1 == "lt")? "<" : ">";
	});
	var cleanHtmlString = htmlString.replace(/<\/?[^>]+(>|$)/g, "");
	cleanHtmlString = cleanHtmlString.replace(/Â/g, "");

	return cleanHtmlString;	
}

$(document).ready(function() {
  var content = "";
  $.getJSON("news_json.php",
   function(json){
     if(json.count > 0) {
       content = output_feed_items(json);
     } else {
       content = "The request did not return results.";
     }
     $("#pipes-feed-content").html(content);
   }
  );
});

function output_feed_items(json) {
  for (i=0;i<json.count;i++) {
    itemList += make_feed_item(json.value.items[i], i);
  }
  return itemList;
}

function formatDateString(dateString) {
	var formattedDateString = dateString;
	
	if(dateString.length == 20) {
		formattedDateString = dateString.substr(0,10);
	}
	else if (dateString.length == 29 | 31) {
		formattedDateString = dateString.substr(0,16);
	}
	
	return formattedDateString;
}

function make_feed_item(item, item_id) {
  var item ='<p class="texts"><strong>' +
	'<span style="font-size:10.0pt;font-family:&quot;Trebuchet MS&quot;;color:#990000">' + formatDateString(item.pubDate) + '</span></strong></p>' +
	'<p class="MsoNormal"><b><span style="font-size:10.0pt;font-family:&quot;Trebuchet MS&quot;">' + 
	item.title + '</span></b></p>' +
	'<p class="MsoNormal" style="margin-bottom:1.8em">' +
	'<span style="font-size:10.0pt;font-family:&quot;Trebuchet MS&quot;;color:black"> ' + truncateParagraph(removeHTMLTags(item.description),460) +
	'</span>' +
	'<span class="viewArticle" style="font-family: Trebuchet MS">' +
	'<font color="#999999" style="font-size: 9pt; text-decoration:none">' +
	'<a target="_blank" href="' + item.link +
	'"><font color="#999999">' + 'View Full Article' + '</font></a></font></span></span></p><hr align="left" width="400" size="1" noshade>';
	return item;
}
