// Replaces the #newsroom-content div on the national home page with headline feed from info.evergreen.ca
// Requires jQuery in order to be called on page load.
// Eli McIlveen, 30 Nov 2011

function newsInsertHeadlines(xmlRequest) {
	var title, url, articleDate, i, newsroomDiv, par, strong, link;

	var response = xmlRequest.responseXML;
	var articles = response.getElementsByTagName("articles")[0].getElementsByTagName("article");

	// Empty out existing content
	newsroomDiv = document.getElementById("newsroom-content");
	newsroomDiv.innerHTML = '';
	
	// Cycle through the feed, create link + surrounding paragraph, then add it
	for (i=0; i<2; i++) {
		title = articles[i].getElementsByTagName("title")[0].textContent;
		url = articles[i].getElementsByTagName("url")[0].textContent;
		articleDate = articles[i].getElementsByTagName("date")[0].textContent;

		link = document.createElement('a');
		link.innerHTML = title;
		link.setAttribute('href', url);
		par = document.createElement('p');
		par.innerHTML = articleDate + ': ';
		par.appendChild(link);
		newsroomDiv.appendChild(par);				
	}

	// Similarly, add the "More articles" link
	link = document.createElement('a');
	link.innerHTML = 'More articles';
	link.setAttribute('href', 'http://info.evergreen.ca/');
	strong = document.createElement('strong');
	strong.appendChild(link);
	par = document.createElement('p');
	par.appendChild(strong);
	newsroomDiv.appendChild(par);
}

function newsInsertHeadlinesIE(xmlRequest) {
	var title, url, articleDate, i, newsroomDiv;

	var response = xmlRequest.responseText;

	// Empty out existing content
	newsroomDiv = document.getElementById("newsroom-content");
	newsroomDiv.innerHTML = response;
}

function newsLoadContent() {
	var xmlRequest;

	try {
		if ('withCredentials' in new XMLHttpRequest()) {
			// Supports CORS standard cross-domain requests
 			xmlRequest= new XMLHttpRequest();
			xmlRequest.open("GET", "http://info.evergreen.ca/en/national-newsroom.xml", true);
			xmlRequest.onreadystatechange = function() {
				if (xmlRequest.readyState == 4 && xmlRequest.status == 200) {
					// Completed without HTTP error
					newsInsertHeadlines(xmlRequest);
				}
			};
			xmlRequest.send(null);
		}
		else {
			if (typeof XDomainRequest !== "undefined") {
				// IE with CORS
				// XDomainRequest doesn't parse XML, so load in an HTML version instead
				xmlRequest = new XDomainRequest();
				xmlRequest.open("GET", "http://info.evergreen.ca/en/national-newsroom-ie.xml");
				xmlRequest.onload = function(){
					newsInsertHeadlinesIE(xmlRequest);
				};
				xmlRequest.send();
		  } else {
			// No cross-domain support; do nothing and leave default content
		  }
		}
	} catch(error) {
		// Something went wrong; do nothing and leave default content
	}
}

$(function() { newsLoadContent(); });

