//Function loading the news feed.  To be called on load
function loadNewsFeed()
{
	var feedURL = "http://www.riskcenter.com/ieca_articles_xml.php";
	var feedURL = "FeedsResources/GetNewsFeed.php?url=" + feedURL;	
	/*	parmaters are 
	1] url of the riskcenter feed 
	2] id of element where feed is displayed 
	3] id of hidden <div> where the news details are stored and displayed by DHTML window component
	*/
	xmlhttpPost(feedURL, "newsTable", "displayFeedDetails"); 
}



//detecting the browser version
var bname = navigator.appName;
var isIE = false;
if (bname == "Microsoft Internet Explorer"){
	isIE = true;
}
else{
	isIE = false;
}


//RiskCenter news feed object : 
//
function newsArticle(id, headline, tLocation, tDate, author, intro, articleBody) { 
	this.id = id;
	this.headline = headline;
	this.tLocation = tLocation;
	this.tDate = tDate;
	this.author = author;
	this.intro = intro;
	this.articleBody = articleBody;
}

/*
 * Function used to get the most recent verison of MSXML2.XMLHTTP object
 */
function createXMLHttp() {
    var aVersions = [ "MSXML2.XMLHttp.5.0",
        "MSXML2.XMLHttp.4.0","MSXML2.XMLHttp.3.0",
        "MSXML2.XMLHttp","Microsoft.XMLHttp"
    ];

    for (var i = 0; i < aVersions.length; i++) {
        try {
            var oXmlHttp = new ActiveXObject(aVersions[i]);
            return oXmlHttp;
        } catch (oError) {
            //Do nothing
        }
    }
    throw new Error("MSXML is not installed.");
}


/*
 * Gets the RiskCenter News Feed from the specified URL 'strFullUrl' and displays the feed in 
 * the <div> element identified by 'sNewsDispId'. Also save the news feed details in the sDetailsDispId
 */
function xmlhttpPost(strFullUrl, sNewsDispId, sDetailsDispId) {
	var strURL = encodeURI(strFullUrl);
		
	dispLoadMsg(sNewsDispId);
    
	var xmlHttpReq = false;
	// Mozilla/Safari
    if (window.XMLHttpRequest) {
        xmlHttpReq = new XMLHttpRequest();
    }
    // IE
    else if (window.ActiveXObject) {
		try { 
			xmlHttpReq = createXMLHttp();
		} catch (e1) { 	// first method failed 
			try {
				xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (e2) { //second method failed
				 errGettingXmlHttpObj(sNewsDispId);
			} 
		}

    }
	//post the url to the server
    xmlHttpReq.open('GET', strURL, true); //using GET in perl implementation as having problem with perl script reading POST
    xmlHttpReq.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    xmlHttpReq.onreadystatechange = function() {
        if (xmlHttpReq.readyState == 4) { 
			if (xmlHttpReq.status == 200) {		
				populateFeedItems(sNewsDispId, sDetailsDispId, xmlHttpReq.responseXML);				
			}
			else{//Error
				errGettingXmlResp(sNewsDispId, xmlHttpReq.status);
			}
        }
    }
    xmlHttpReq.send(null);
}


/*
* Parse the XML reponse and create a newsArticle object and store it in an array
*/
function populateFeedItems(sNewsDispId, sDetailsDispId, xmlDoc)
{
	
	if(isIE){
		if(xmlDoc.parseError.errorCode != 0 ){
			if(document.getElementById(sNewsDispId) != null){
				/*
				var dispElem = document.getElementById(sNewsDispId);
				dispElem.innerHTML = "<i>errorCode: " + xmlDoc.parseError.errorCode+ "<br>" + "filepos: " + xmlDoc.parseError.filepos + "<br>" + "line: " + xmlDoc.parseError.line + "<br>" +  "linepos: " + xmlDoc.parseError.linepos + "<br>" + "reason: " + xmlDoc.parseError.reason + "<br>" + "srcText: " + xmlDoc.parseError.srcText + "<br>" + "url: " + xmlDoc.parseError.url + "</i>";
				*/

  				var dispElem = document.getElementById(sNewsDispId);
				dispElem.innerHTML = "<span class='smallText'>Industry news update is in progress.<br> Please see this section after sometime.<br> Sorry for the inconvenience.</span>";

			}
			else{
				alert("errorCode: " + xmlDoc.parseError.errorCode+ "\n" + "filepos: " + xmlDoc.parseError.filepos + "\n" + "line: " + xmlDoc.parseError.line + "\n" +  "linepos: " + xmlDoc.parseError.linepos + "\n" + "reason: " + xmlDoc.parseError.reason + "\n" + "srcText: " + xmlDoc.parseError.srcText + "\n" + "url: " + xmlDoc.parseError.url);
			}
			return
		}
	}
	
	
	
	//All news articles are read
	var x = xmlDoc.getElementsByTagName("ARTICLE");

	if(x.length == 0)
	{
		document.getElementById(sNewsDispId).innerHTML = "<i>No articles found..</i>";
		return;
	}
	var feedArticles = new Array();
	for (i=0;i<x.length;i++)
	{
		//read the ID
		var tmpId = x[i].getElementsByTagName("ID")[0];
		if(tmpId != null)
			idData = tmpId.childNodes[0].nodeValue;
		else
			idData = "";

		//get the HEADLINE
		var tmpHeadLine = x[i].getElementsByTagName("HEADLINE")[0];
		if(tmpHeadLine != null)
			headlineData = tmpHeadLine.childNodes[0].nodeValue;
		else
			headlineData = "";

		//get the LOCATION
		var tmpLocation = x[i].getElementsByTagName("LOCATION")[0];
		if(tmpLocation != null)
			locationData = tmpLocation.childNodes[0].nodeValue;
		else
			locationData ="";

		//read the DATE
		var tmpDate = x[i].getElementsByTagName("DATE")[0];
		if(tmpDate != null)
			dateData = tmpDate.childNodes[0].nodeValue;
		else
			dateData = "";

		//get the AUTHOR
		var tmpAuthor = x[i].getElementsByTagName("AUTHOR")[0];
		if(tmpAuthor != null)
			authorData = tmpAuthor.childNodes[0].nodeValue;
		else
			authorData = "";

		//get the INTRO
		var tmpIntro = x[i].getElementsByTagName("INTRO")[0];
		if(tmpIntro != null)
			introData = tmpIntro.childNodes[0].nodeValue;
		else
			introData ="";

		//get the ARTICLE_BODY
		var tmpArticleBody = x[i].getElementsByTagName("ARTICLE_BODY")[0];
		articleBodyData = "";
		if(tmpArticleBody != null){
			//FireFox has text's size in a node limited to 4096 character. Applying 'for loop' for it.
			for(j=0; j<tmpArticleBody.childNodes.length; j++){
				articleBodyData += tmpArticleBody.childNodes[j].nodeValue;
			}
		}
		else{
			articleBodyData ="";
		}

		var feedArticle = new newsArticle(idData, headlineData, locationData, dateData, authorData, introData, articleBodyData);
		feedArticles.push(feedArticle);
	}
	listFeedItems(sNewsDispId, sDetailsDispId, feedArticles);

}


/*
* Read newsArticle object array and implements the actual code to display the data
*/
function listFeedItems(sNewsDispId, sDetailsDispId, feedArticles)
{
	var newsDetails = "";
	document.getElementById(sNewsDispId).innerHTML = "";

	var scrollElem = document.createElement("Marquee");
	scrollElem.setAttribute("direction", "up");
	scrollElem.setAttribute("behavior", "Scroll");
	scrollElem.setAttribute("scrollAmount", "2");
	scrollElem.setAttribute("scrollDelay", "0");

	if(isIE){ //setting the height and width to the enclosed <div> tag 
		scrollElem.setAttribute("height", "167px");
		scrollElem.setAttribute("width", "90%");
	}
	else
	{
		scrollElem.setAttribute("style", "height:260px; width:90%;");
	}
	
	if(isIE){
		scrollElem.onmouseover = new Function("this.stop()");
		scrollElem.onmouseout = new Function("this.start()");
	}
	else{
		scrollElem.setAttribute("onmouseover", "this.stop()");
		scrollElem.setAttribute("onmouseout", "this.start()");
	}

	var newTableEl = document.createElement("TABLE");
	newTableEl.setAttribute("border", "0");
	newTableEl.setAttribute("align", "center");
	newTableEl.setAttribute("cellPadding", "0");
	newTableEl.setAttribute("cellSpacing", "0");
	
	if(isIE){
		newTableEl.setAttribute("width", "100%");
		newTableEl.setAttribute("className", "newstext");
	}
	else{
		newTableEl.setAttribute("style", "width:100%;");
		newTableEl.setAttribute("class", "newstext");
	}

	var newTBodyEl = document.createElement("TBODY");
	
	for (i=0;i<feedArticles.length;i++)
	{
		var newRowEl = document.createElement("TR");
		
		var newColEl = document.createElement("TD");
		newRowEl.appendChild(newColEl);
		
		
		//create a link for the DHTML popup window
		var newLinkEl = document.createElement("A");
		newLinkEl.setAttribute("style", "cursor:pointer;cursor:hand;");
				
		if(isIE){
			//displays in only one window declared in the html file
			newLinkEl.onclick = new Function("divWin.load('div', 'Div"+i+"', 'Article Details'); divWin.show();");
			newLinkEl.onmouseover = new Function("this.style.cursor='hand';"); //used for IE
			newLinkEl.className = "newstext";
		}
		else{			
			//displays in only one window declared in the html file
			newLinkEl.setAttribute("onclick", "divWin.load('div', 'Div"+i+"', 'Article Details'); divWin.show(); return false");
			newLinkEl.setAttribute("class", "newstext");
		}
		newColEl.appendChild(newLinkEl);

		var newStrongEl = document.createElement("STRONG");
		
		//read the title
		var fmtDate = formatDate(feedArticles[i].tDate, "F d");
		newStrongEl.innerHTML = fmtDate + " : " + feedArticles[i].headline;
		newLinkEl.appendChild(newStrongEl);

		newColEl.appendChild(document.createElement("BR"));

		//get the description
		var newSpanEl = document.createElement("SPAN");
		newSpanEl.innerHTML = feedArticles[i].intro;		
		newColEl.appendChild(newSpanEl);

		newTBodyEl.appendChild(newRowEl);
					
		//add a horizontal line except the last one
		if(i != feedArticles.length-1){
			var newRowEl2 = document.createElement("TR");
		
			var newColEl2 = document.createElement("TD");
			newColEl2.setAttribute("align", "left");
			newRowEl2.appendChild(newColEl2);

			var newHREl = document.createElement("HR");
			newHREl.setAttribute("width", "95%");
	
			newColEl2.appendChild(newHREl);

			newTBodyEl.appendChild(newRowEl2);
		}

		//create the details html in a <div> tag as required by the DHTML popup window script
		newsDetails += "<div id='Div"+i+"'>";
		newsDetails += "<b>" + feedArticles[i].headline + "</b></br>";
		newsDetails += "<b><i> Author : " + feedArticles[i].author + "</i></b></br>";
		newsDetails += "<i> Date : "+formatDate(feedArticles[i].tDate, "dS F Y") + "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Location : " + feedArticles[i].tLocation+"</i><hr>";
		newsDetails	+= feedArticles[i].articleBody+"</div>"; 		
	}

	newTableEl.appendChild(newTBodyEl);	
	scrollElem.appendChild(newTableEl);
	
	document.getElementById(sNewsDispId).appendChild(scrollElem);
	scrollElem.start();

	document.getElementById(sDetailsDispId).innerHTML = newsDetails;
}

/*
*  Error message displayed when XMLHttpRequest object not created
*/
function errGettingXmlHttpObj(sNewsDispId) {
	if(document.getElementById(sNewsDispId) != null){
		var dispElem = document.getElementById(sNewsDispId);
		dispElem.innerHTML = "<b>Err : Could not create XML HTTP Request.</b>";
	}
	else{
		alert("Could not create XML HTTP Request.");
	}
}


/*
*  Error message displayed when error occured in the response
*/
function errGettingXmlResp(sNewsDispId, errMsg) {
	if(document.getElementById(sNewsDispId) != null){
		var dispElem = document.getElementById(sNewsDispId);
		dispElem.innerHTML = "<b>Err : "+errMsg+"</b>"; 
	}
	else{
		alert("Err : "+errMsg);
	}

}


/*
*  Displays the initial loading message
*/
function dispLoadMsg(sNewsDispId) {
	if(document.getElementById(sNewsDispId) != null){
		var dispElem = document.getElementById(sNewsDispId);
		dispElem.innerHTML = "<span class='newstext'><i>Loading...<img src='FeedsResources/indicator_mozilla_blu.gif'></i></span>"; 
	}
}



//function to format the date sent
//the date available from riskcenter is in the format yyyy-MM-dd
function formatDate(strDate, strFormat){

	var dateparts = strDate.split("-");
	var tmpDate = new Date(parseInt(dateparts[0], 10), parseInt(dateparts[1], 10)-1, parseInt(dateparts[2], 10));
	return DateFormatter.format(tmpDate, strFormat);
}

