/* Title: newsTicker
*  Author: Peter Wyss / Atelier Kaempfer, Burgdorf, Switzerland
*  Last Modification: March 28, 2011
*  
*  This script reads the messages from the twitter account ####,
*  writes them into the div #twitterNews and displays them in
*  a jquery UI dialog. The news are updated every 2 minutes.
*  
*  The script is triggered by #showNews.
*  
*  This script requires the jquery and the jquery UI.
*
*/


/* deletes leading and trailing white spaces from strings */
function trimStr (str) {
    return str.replace(/[\n\r]/g, '').replace(/ +/g, ' ').replace(/^\s+/g, '').replace(/\s+$/g, '');
}


/* Converts the date and time provided by Twitter into the local format
 */

function parseTwitterDate(text) {
	text = text.replace(/\s\+00\d\d\s/, ' ');
	var timeMask = /[0-2]?\d\:[0-5]?\d\:[0-5]?\d/;
	var timeString = timeMask.exec(text);
	var dateString = text.replace(timeMask, '');
	return dateString + ' | ' + timeString;
}


/* Inserts hyperlinks, assuming that there could be more than one per
 * tweed ...
 */

function insertHyperLinks(twitterData) {
	textBuffer = twitterData;
	twitterData = '';
	while ((linkPos = textBuffer.indexOf('http://')) != -1) {
		twitterData += textBuffer.substr(0,linkPos);
		textBuffer = textBuffer.slice(linkPos);
		if ((endOfLink = textBuffer.indexOf(' ')) != -1) {
			linkBuffer = textBuffer.slice(0,endOfLink);
			textBuffer = textBuffer.slice(endOfLink);
		} else {
			linkBuffer = textBuffer;
			textBuffer = '';
		}
		twitterData += '<a target="_new" href=' +'"' + linkBuffer + '">' + '&nbsp;>>> ' + '</a>';;
	}
	return twitterData + textBuffer;
}



/* Reads the messages from the twitter account #### and returns them in an string.
 * The messages are packed in paragraphs (<p>). Each paragraph consists of two lines,
 * separated with a <br />. Noramlly the first line contains the message, the second line
 * the time and date. Sometimes, however, a date is transmitted without message. 
 * A class is assigned to each paragraph. This class is alternating
 * between .oddLine and .evenLine. 
 */

function displayTwitterNews(data){
  if ($('#twitterNews').length > 0) {$('#twitterNews').remove();}
  messages = '';
  messageContent = '';
  messageDate = '';
    var paragraphClass = 'even';
    for (i = 0; i < data.length; i++) {
        jQuery.each(data[i], function(index, value){
            if (index == 'text') {
                paragraphClass = (paragraphClass == 'odd') ? 'even' : 'odd';
                messageContent = '<p class="' + paragraphClass + '">' +
                insertHyperLinks(value) +
                '<br />';
            }
            if (index == 'created_at') {
                messageDate = '<span class="newsDate">' + parseTwitterDate(value) + '</span></p>';
            }
          if (messageDate.length != 0){
            if (messageContent.length != 0) {
              messages += (messageContent + messageDate);
              messageContent = '';
              messageDate = '';
            }
          }
        });
    }
    showNewsDialog(messages);
}

function requestNews() {
	$.ajax({
				url: "http://twitter.com/status/user_timeline/Kalabriench.json?count=10&callback=?",
				dataType: 'json',
				timeout: 3000, //3 second timeout
				success: function(data){
					displayTwitterNews(data)
				}
			});
}


function showNewsDialog(feedback) {
	if (feedback.length == 0) {
		feedback = '<img class="ajaxWait" src="../../../graphics/newsLoader.gif" alt="AJAX Loader" />';
	}
	if ($('#twitterNews').lenght > 0) {
		$('#twitterNews').remove();
	}
	$('#sidebar').after('<div id="twitterNews">'+ feedback + '</div>');
	
	if (newsTicker != null) {newsTicker.dialog('close');}
	
	newsTicker = $("#twitterNews").dialog({
                height: '500',
                position: newsPosition,
                width: '300',
                resizable: false,
                title: 'News',
                beforeClose: function(event, ui){
                    newsPosition = newsTicker.dialog('option', 'position');
                    newsTicker = null;
                },
				close: function(event, ui){
					window.clearInterval(periodicRequest);
				} 
     });	
}


function getTwitterNews(){
	if (newsTicker == null) {
		data = '';
		displayTwitterNews(data);
		requestNews();
		periodicRequest = window.setInterval(function(){
			requestNews();
		}, 120000)
	};
}


$(document).ready(function(){
	newsPosition = [956,59];
	newsTicker = null;
	$('#showNews').click(function(event){
		event.preventDefault();		
        getTwitterNews();
    });	
})




