// the delay to show each message for
var delayms = 8000;
// the maximum number of items about to come up
var maxUpcoming = 5;
// the div to add the message board to
var targetMsgDivId = "msgboard";
var xmlloc = "applications/messageboard/messages.xml";
var title = "Hautlieu Messages";

var msgdata = new Array();
var msgrotate = true;
$(document).ready(function () {
    $.ajax({
        type: "GET",
        url: xmlloc + "?" + new Date().getTime(),
        dataType: "xml",
        success: function(xml) {
        	$(xml).find("item").each(function () {        		
        		msgdata[msgdata.length] = $(this);
        	});        	
        	rotate(0);
        },
        error : function (xhr, textStatus, e) {
        	$("#"+targetMsgDivId).html('<div class="header2">' + title + '</div><div class="item">No messages are currently available. <br/>' + textStatus + '<br/>' + e + '</div>');
        }
        
    });
});
	function rotate(idx, cancel) {
		idx = idx>=msgdata.length ? 0 : idx;
		var d = msgdata[idx];
		if(cancel) {
			$("#"+targetMsgDivId).stop(true);
		}
		var html = '<div class="header">Hautlieu Messages</div><div class="item"><div class="category">' + d.find("category").text() + 
        		'</div><div class="title">' + d.find("title").text() + 
        		'</div><div class="descrption">' +  Linkify(d.find("description").text()) + '</div></div></div>' + genUpcoming(idx);
		$("#"+targetMsgDivId).html(html).fadeIn().delay(delayms).fadeOut(function() {
					if(msgrotate) {
						rotate(++idx);	
					}
				});
	}
	
function Linkify(inputText) {
    //URLs starting with http://, https://, or ftp://
    var replacePattern1 = /(\b(https?|ftp):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/gim;
    var replacedText = inputText.replace(replacePattern1, '<a href="$1" target="_blank">$1</a>');

    //URLs starting with www. (without // before it, or it'd re-link the ones done above)
    var replacePattern2 = /(^|[^\/])(www\.[\S]+(\b|$))/gim;
    var replacedText = replacedText.replace(replacePattern2, '$1<a href="http://$2" target="_blank">$2</a>');

    //Change email addresses to mailto:: links
    var replacePattern3 = /(\w+@[a-zA-Z_]+?\.[a-zA-Z]{2,6})/gim;
    var replacedText = replacedText.replace(replacePattern3, '<a href="mailto:$1">$1</a>');

    return replacedText
}
	
	function genUpcoming(idx) {
		var max = 3;
		var str = '<div class="upcoming">Upcoming Items:';
		var k = idx+1;		
		for(var j=0;j<max;j++) {
			k = k >= msgdata.length ? 0 : k;
			if(k==idx){
				break;
			}
			str += '<div class="item">' + msgdata[k++].find("title").text() + "</div>";		
		}
		return str + "</div>";		
	}
