// JavaScript Document

	/*
	 *
	 *
	 *
	 *
	 *
	 */

//http://172.22.1.176

	var newsXMLSource = new Array;
//		newsXMLSource [0] = "A-832832-0.xml";
//		newsXMLSource [1] = "B-837748-0.xml";
		newsXMLSource [0] = "/includes/00832/832832/views/832832-0.extract.xml"	// Latest News - Trimmed
		newsXMLSource [1] = "/includes/00864/864395/views/864395-0.extract.xml"	// In the Community - Trimmed
		newsXMLSource [2] = "/includes/00832/832832/views/832832-0.xml"			// Latest News - Full
		newsXMLSource [3] = "/includes/00864/864395/views/864395-0.xml"			// In the Community - Full

	
	var newsOutputTarget = new Array;
		newsOutputTarget [0] = "#RBTT_LatestNewsTab";	// Latest News - Horz Tab Box (Section Landing Pages)		
		newsOutputTarget [1] = "#RBTT_InTheCommunityTab";	// In the Community - Horz Tab Box (Section Landing Pages)
		newsOutputTarget [2] = "#RBTT_LatestNews";		// Latest News Box - About RBTT Section		
		newsOutputTarget [3] = "#RBTT_InTheCommunity";	// In the Community Box - About RBTT Section

	var isNewsTabOutput = new Array;
		isNewsTabOutput [0] = true;		// Latest News - Horz Tab Box (Section Landing Pages)		
		isNewsTabOutput [1] = true;		// In the Community - Horz Tab Box (Section Landing Pages)
		isNewsTabOutput [2] = false;	// Latest News Box - About RBTT Section		
		isNewsTabOutput [3] = false;	// In the Community Box - About RBTT Section

	var newsTabCount = 6;

	var newsListClass = "bullets-arrow";	// if we want to define a class for the unordered list generated
	var newsMaxChars = 50;
	
	// var horzTabNavMaxChars = 60;
	// var aboutRBTTNewsMaxChars = 75;
	
	// for testing truncate function
	var newsLinkString = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras lectus orci, suscipit a pulvinar in, semper vitae felis."


// ==============================================================================================
//
//  Browser Console / Log Function - So error is not thrown if not console not present
//
// ==============================================================================================

	function devConsole(msg) {
		if (typeof(console) !== 'undefined' && console != null) {
			console.log(msg);
		}	
	}


// ==============================================================================================
//  Document Ready
// ==============================================================================================

	$(document).ready(function()
	{
		if(newsXMLSource.length == newsOutputTarget.length) {
			for (i = 0; i < newsXMLSource.length; i++) {
				// if the ID exists on the page, start processing
				if($(newsOutputTarget[i]).length) {
					// add the 'loading' html while processing occurs
					$(newsOutputTarget[i]).append("<div class='loadingImg'></div>");
					
					// send the values off to be fetched via ajax
					fetchNewsListData(newsXMLSource[i], newsOutputTarget[i], isNewsTabOutput[i]);
				}
			}
		} else {
			// do we throw some kind of error if the arrays are mismatch sizes??
		}
	});
	
	
	
	// grab xml from url, upon success pass it newsXmlToList function for parsing
	function fetchNewsListData(inputURL, outputID, isTabOutput) {
				
		// this method of doing the ajax call is a little beefier than required.  
		//	- allows us to test local XML files as well with IE
		//	- allows us to pass addtional arguments with the success / error functions.
		$.ajax({
			type: "GET",
			url: inputURL,
			cache: true,
			dataType: ($.browser.msie) ? "text/xml" : "xml",
			success: function(data) {
						var xml;
						if (typeof data == "string") {
							xml = new ActiveXObject("Microsoft.XMLDOM");
							xml.async = false;
							xml.loadXML(data);
						} else {
							xml = data;
						}
						newsXmlToList(xml, outputID, isTabOutput);
			},
			error: function(xhr, textStatus, errorThrown) {
						// devConsole('Problem Occured: \n' + xhr.statusText + " | " + textStatus + " | " + errorThrown);
						newsErrorMsg(outputID);
			}
		});				
	}
	
	// truncate given string to given length
	function truncate(str, limit) {
		var chars;
		var i;
		
		// check if what was passed as a string is actually a string
		if ( typeof(str) != 'string') {
			return '';
		}
		
		// create an array of the chars in the string
		chars = str.split('');
		
		// if the length is greater than the set limit, process for truncating
		if (chars.length > limit) {
			// while the char count is greater than the limit,
			for (i = chars.length - 1; i > -1; --i) {
				// if char count is still greater, redefine the array size to the value of i
				if (i > limit) {
					chars.length = i;
				}
				// if char count is less than the limit keep going until you hit a space
				// and redefine the array size to the value of i
				else if (' ' === chars[i]) {
					chars.length = i;
					break;
				}
			}
			// add elipsis to the end of the array
			chars.push('...');
		}
		// return the array as a string
		return chars.join('');
	}
	
	// based on file extension, return the image filename and title text
	function fileType(ext) {

		var extImage;
		var titleText;

		switch (ext) {
			
			case "jpg":
				extImage = "generic.gif"; // there is no UOS image icon
				titleText = "JPG image";
				break;
			case "gif":
				extImage = "generic.gif"; // there is no UOS image icon
				titleText = "GIF image";
				break;
			case "png":
				extImage = "generic.gif"; // there is no UOS image icon
				titleText = "PNG image";
				break;
			case "pdf":
				extImage = "pdf.gif";
				titleText = "opens PDF in new window";				
				break;
			case "xls":
				extImage = "excel.gif";
				titleText = "Excel Document";				
				break;
			case "xlsx":
				extImage = "excel.gif";
				titleText = "Excel Document";				
				break;				
			case "doc":
				extImage = "word.gif";
				titleText = "Word Document";
				break;
			case "docx":
				extImage = "word.gif";
				titleText = "Word Document";
				break;
			case "ppt":
				extImage = "powerpoint.gif";
				titleText = "Powerpoint Document";
				break;
			case "pps":
				extImage = "powerpoint.gif";
				titleText = "Powerpoint Document";
				break;					
			default:
				extImage = "generic.gif";
				titleText = "Unknown File Type";				
				break;
		}		
		
		return [extImage, titleText];
	}
	
	// Parse XML and create an unorder list of news items
	function newsXmlToList(xmlData, targetID, isTabOutput)
	{
	// == TODO ==
		// protocol (http, https, mailto, ftp, news, javascript)
		// target (self, blank, parent)
		// flag (1 = selected, else "")
		// pin (1 = selected, else "")
		
		var counter = 0;
		var pagesize;
		var newsList = "<ul class='" + newsListClass +"'>";
		var listItem = "";
		var liRowClass = "";
		var errorOccurred = false;
		var errorComment = "Unsupported or Invalid News Item";
		
		// if outputting to a tab interface, use defined count from xml, else output all news items
		(isTabOutput == true) ? pagesize = newsTabCount : pagesize = 0;
		
		$(xmlData).find("listitem").each(function()
		{
			var linkType = $(this).attr("type");
			var aProtocol = $(this).attr("protocol");
			var aLabel = $(this).find("label").text();
			var aUrl = $(this).attr("url");
			var aTitle = $(this).attr("title");
			var aTarget = $(this).attr("target");
			
			//aLabel = newsLinkString;	// for testing truncating function
			
			// make sure URL does not contain the protocol already
			if (aUrl.indexOf("http://") != -1) {
				aUrl = aUrl.replace("http://","");	// http is allowed strip from url
				aProtocol = "http:";				// and ensure the protocol is changed to handle it.
			}

			if (aUrl.indexOf("https://") != -1) {
				aUrl = aUrl.replace("https://","");	// https is allowed strip from url
				aProtocol = "https:";				// and ensure the protocol is changed to handle it.
			}
			
			if (aUrl.indexOf("//") != -1) {
				aUrl = aUrl.replace("//","");		// ewcms list functionality adds double slashes to urls selected
				aProtocol = "http:";				// in a different domain, when going through the GUI,  also give it a link
				linkType = "link";					// type of 'page', change to 'link' type in order to process correctly
			}			

			if (aUrl.indexOf("mailto:") != -1) {
				aUrl = aUrl.replace("mailto:","");	// mailto is allowed strip from url
				aProtocol = "mailto:";				// and ensure the protocol is changed to handle it.
			}

			if ( (aUrl.indexOf("ftp:") != -1) || (aProtocol == "ftp:") ) {
				linkType = "";	// protocol not allowed, linkType will now go to 'default' in switch statement below
			}
			
			if ( (aUrl.indexOf("news:") != -1) || (aProtocol == "news:") ) {
				linkType = "";	// protocol not allowed, linkType will now go to 'default' in switch statement below
			}
			
			if ( (aUrl.indexOf("javascript:") != -1) || (aProtocol == "javascript:") ) {
				linkType = "";	// protocol not allowed, linkType will now go to 'default' in switch statement below
			}			
			
			// if protocol is blank default to http
			if (aProtocol == "") {
				aProtocol = "http:";
			}
			
			// define CSS class for alternate rows
			(liRowClass == "news_li_odd") ? liRowClass = "news_li_even" : liRowClass = "news_li_odd";			

			switch (linkType) {
				case "file":	// Local file (relative)
					// call function to detect type of file and associated Title Text
					var fileDetails = fileType($(this).find("file").attr("ext"));
					aLabel = truncate(aLabel, newsMaxChars - 5); // account for space required by the filetype icon
					// start list item
					listItem += "<li class='" + liRowClass + "'>";
					listItem += "<a href='" + aUrl + "'" + "onclick='return popupNonhtml(this.href)' target='_blank' title='(" + fileDetails[1] + ")' class='linkedtextandicon'>";
					listItem += "<span>" + aLabel + "</span>";
					listItem += "&nbsp;<img src='../../files/static/uos/images/icons/" + fileDetails[0] +"' alt='(" + fileDetails[1] + ")' class='icon' />";
					listItem += "</a>";
					listItem += "</li>";					
					// <a href="/uos-nonstandard/documents/test.pdf" onclick="return popupNonhtml(this.href)" target="_blank" title="(opens PDF in new window)" class="linkedtextandicon"><span>Document</span> <img src="/uos/_assets/images/icons/pdf.gif" alt="(opens PDF in new window)" class="icon" /></a>
					
					break;
					
				case "link":	// external link (all non-relative, including external files)
					aLabel = truncate(aLabel, newsMaxChars);	// truncate label so it does not wrap
					// add slashes to protocol if not mailto:, and different link format
					// for mail since it does not require the onclick functionality
					if (aProtocol == "mailto:") {	
						var protocol = aProtocol;
						listItem += "<li class='" + liRowClass + "'>";
						listItem += "<a href='" + protocol + aUrl + "'>";
						listItem += "<span>" + aLabel + "</span>";
						listItem += "</a>";
						listItem += "</li>";					
					} else {
						var protocol = aProtocol + "//";
						listItem += "<li class='" + liRowClass + "'>";
						listItem += "<a href='" + protocol + aUrl + "'" + "onclick='return popupNewbrowser(this.href)' target='_blank' title='(opens external website in new window)' class='linkedtextandicon'>";
						listItem += "<span>" + aLabel + "</span>";
						listItem += "&nbsp;<img src='../../files/static/uos/images/icons/externallink.gif' alt='(opens external website in new window)' class='icon' />";
						listItem += "</a>";
						listItem += "</li>";					
						// <a href="http://www.google.com" onclick="return popupNewbrowser(this.href)" title="(opens external website in new window)" target="_blank" class="linkedtextandicon"><span>External Website</span> <img src="/uos/_assets/images/icons/externallink.gif" alt="(opens external website in new window)" class="icon" /></a>
					}
					break;
					
				case "page":	// internal link (relative)
					aLabel = truncate(aLabel, newsMaxChars);	// truncate label so it does not wrap
					listItem += "<li class='" + liRowClass + "'>";
					listItem += "<a href='" + aUrl + "'" + " title='" + aTitle + "'>";
					listItem += "<span>" + aLabel + "</span>";
					listItem += "</a>";
					listItem += "</li>";
					break;
				
				default :
					// Just in case, output html comment with error msg
					listItem += "\<\!-- ERROR - " +  aLabel + ": " + errorComment + " --\>";
					// RESET CSS class for alternate rows - puts it back to previously defined value
					// so that unsupported news items that are not displayed do not count
					// ex: avoids two odds or evens appearing in sequence
					(liRowClass == "news_li_odd") ? liRowClass = "news_li_even" : liRowClass = "news_li_odd";
					errorOccurred = true;
					break;			
			}

			// devConsole("listItem Output: " + listItem);
			
			newsList += listItem; // add list item to the news list
			listItem = "" // reset list item to start fresh (just in case)

			// check if output is to a tab interface, if so check for errors and loop counts
			if (isTabOutput == true) {
				if (errorOccurred == true) {
					// do not increase counter if error occurred
					// to insure the proper qty of news items gets generated
				} else {
					counter++;	// adjust counter plus one
				}				
				// continues to loop if resolves to true, otherwise break the loop.
				return (pagesize != counter);
			}

			errorOccurred = false; // reset error detection var

		});
		
		newsList += "</ul>";

		if ( (isTabOutput == true) && ($(xmlData).find("more").text() != "") ) {
			// ad 'More / Archive' link if one has been specified in the xml - Relative
			newsList += "<div class='more_link_wrapper'><a class='more_link' href=" + $(xmlData).find("more").text() + ">More News</a></div>";
			// devConsole('entered More link logic:' + $(xmlData).find("more").text());
		}
		

		$(targetID + ' .loadingImg').hide();	// hide loading div
		
		$(targetID).append(newsList);	// replace the target div content with the list created above
	}
	
	// Problem occured with XML or data Connection
	function  newsErrorMsg(targetID) {
		errorMsg = "<div class='errormsg'>Data Connection Error</div>";
		$(targetID + ' .loadingImg').hide();	// hide loading div
		$(targetID).append(errorMsg);	// replace the target div content with the error msg
	}

