/**
 * Global variables
--------------------------------------------------- */
var statusLimit = 20;
var searchURL = "workers/twittersearch.php?q=";
var statusURL = "workers/getstatus.php?user=";
var latestSearchID = [];
var latestStatusID = 0;
var preloadedSponsors = [];
var currentSponsor = 0;
// Define national sponsors
var sponsors = [baseurl+"images/sponsors/gold_kajak.jpg",
                baseurl+"images/sponsors/gold_microsoft_black.jpg",
                baseurl+"images/sponsors/gold_nokia_black.jpg",
                baseurl+"images/sponsors/gold_paf_black.jpg",
                baseurl+"images/sponsors/silver_ludocraft.jpg"];


/**
 * DOM Ready
--------------------------------------------------- */
window.addEvent('domready', function() {
	/*var localfeed = $('twitter_status').getElement('#user').getElement('span');
	localfeed.addEvent('click', function(e) { if(e) {e.stop();}	
		input = '<input name="inputBox" id="inputBox" type="text" />'
	});*/

	
	// Initialize columns
	// (Set a bit of time difference between updates, to run the animation smoother)
	setTimeout("initColumn('column1', '#GGJ10', 5)", 1000);
	setTimeout("initColumn('column2', '#FGJ', 5)", 2000);
	
});





/**
 * Set status update
 *  
 * @param user			Username
 * @param interval		Update interval (in seconds)
 */
function initStatus(user, interval) {
	// Update column headers
	element = $('twitter_status').getElement('#user').getElement('span');
	element.innerHTML = user;
	
	// Get status 
	getTwitterStatus(user);

	// Timed refresh for status update (rate limit is 150 requests per hour = 24 sec interval)
	refresh = function(){ getTwitterStatus(user, latestStatusID); }
	refresh.periodical(interval*1000, this);
}



/**
 * Set column
 * 
 * @param id			Column id
 * @param query			Search query
 * @param interval		Update interval in seconds
--------------------------------------------------- */
function initColumn(target, query, interval) {
	// Update column headers
	element = $(target).getElement('.column_header').getElement('span');
	element.innerHTML = query;

	// Escape the query (#->%23 etc.)
	query = escape(query); 
	
	// Do the initial search
	doTwitterSearch(target, query);
	
	// Timed refresh
	refresh = function(){ doTwitterSearch(target, query, latestSearchID[target]); }
	refresh.periodical(interval*1000, this);
}



/**
 * Initialize sponsor roulette
 * 
 * @param interval		Update interval (in seconds)
 * @return
 */
function initSponsors(interval) {
	// Preload sponsors and do first update
	preloadSponsors();
	updateSponsor();
	
	// Set up timed sponsor change
	refresh = function(){ updateSponsor(); }
	refresh.periodical(interval*1000, this);		
}








/**
 * Get status from Twitter
 * 
 * username			Username
--------------------------------------------------- */
function getTwitterStatus(username, id) {
	
	// Fix up the search url
	url = baseurl + statusURL + username;
	// Add the id limit, if one is defined
	if (id)
		url += "&since=" + id;
	// Add dummy value to prevent caching
	url += "&dummy=" + ($time() + $random(0, 100)); 
	
	/*
	 * JSON Request
	 */
	var req = new Request.JSON({
		url: url,

		// Page loaded, handle results
		onComplete: function(json) {
			if (json == null || json.length < 1)
				return;
		
			var element = $('twitter_status').getElement('#text');
			
			// Update latest ID
			latestStatusID = json[0].id;
			var status = json[0].text;
			
			// Animate status change
			var elementFX = new Fx.Tween(element, {duration: 'long'});
			elementFX.start('opacity', 0).chain(function() {				
				element.innerHTML = status;
				this.callChain();
				
			}).chain(function() {
				elementFX.start('opacity', 1);
			});

		},	
		
		// The page wasn't found
		onFailure: function() {
							
		}
		
	}).send();
}



/**
 * Twitter search
 * 
 * target		Target div for update
 * query		Search query
 * id			(optional) Id for currently most recent update
--------------------------------------------------- */
function doTwitterSearch(target, query, id) {
	
	// Fix up the search url
	url = baseurl+searchURL+query;
	// Add the id limit, if one is defined
	if (id)
		url += "&since=" + id;
	// Add dummy value to prevent caching
	url += "&dummy=" + ($time() + $random(0, 100)); 
	
	/*
	 * JSON Request
	 */
	var req = new Request.JSON({
		url: url,

		// Page loaded, handle results
		onComplete: function(json) {
			if (json == null || json.length < 1)
				return;
		
			// Update latest ID
			latestSearchID[target] = json[0].id;
			
			// Reverse the results, so that when injected the most recent hit is in top
			json.reverse();
			
			// Remove recent hightlights
			removeRecentTags(target);

			
			// Go through results
			json.each(function(value, key) {
				
				// Create status html
				status = '';
				status += '<img src="'+value.profile_image_url+'" class="twitter_image">';
				status += value.text;
				status += '<hr /><div class="twitter_author">by <strong>';
				status += '<a href="http://www.twitter.com/'+value.from_user+'" target="_blank">'+value.from_user+'</a></strong>';
				status += '</div>';
				
				// Inject new status content
				var newContent = new Element(
					'div', {  
						'class': 'twitter_status twitter_recent',
						'html': status,
				//}).inject(target,'top').hide().reveal();
	            }).inject(target,'top');
				
				// Slide the new content to visible
				newContent.slide('hide').slide('in');
				
				// Remove excess content
				removeExcessContent(target);
			});
		},
		
		// The page wasn't found
		onFailure: function() {
						
		}
		
	}).send();
}

/**
 * Remove recent tags from updates
 * 
 * target		Target div
--------------------------------------------------- */
function removeRecentTags(target) {
	// Get the recent updates within the target
	var highlights = $$('div#'+target+' div.twitter_recent');
	highlights.each(function(element, key) {
		// Fade the old updates
		var fx = new Fx.Tween(element, {duration: 'long'});
		fx.start('opacity', '0.5');
		
		// Remove recent tag
		element.removeClass('twitter_recent');
	});
}


/**
 * Removes excess content for better performance
 * 
 * target		Target div
--------------------------------------------------- */
function removeExcessContent(target) {
	var excess = $$($(target).getElements('div.twitter_status').getParent('div').slice(statusLimit));
	excess.destroy();
}


/**
 * Preload sponsor images
 * 
--------------------------------------------------- */
function preloadSponsors() {
	new Asset.images(sponsors, {
		onProgress: function(i) {
			preloadedSponsors[i] = this;
		},
		onComplete: function() {}
	});
}



/**
 * Update sponsor image
 * 
--------------------------------------------------- */
function updateSponsor() {
	element = $('sponsor');
	
	// Check that we haven't run over the sponsor image array
	currentSponsor++;
	if (currentSponsor > (preloadedSponsors.length - 1))
		currentSponsor = 0;
	
	// Animate sponsor change
	var elementFX = new Fx.Tween(element, {duration: 'long'});
	elementFX.start('opacity', 0).chain(function() {
		$('sponsor').empty();
		preloadedSponsors[currentSponsor].inject($('sponsor'));
		
		this.callChain();
	}).chain(function() {
		elementFX.start('opacity', 1);
	});	
			
}
 


/**
 * Get base url of the script
 * 
 * @return					Base URL
--------------------------------------------------- */
function getBaseURL() {
    var url = location.href;  // entire url including querystring - also: window.location.href;
    var baseURL = url.substring(0, url.indexOf('/', 14));


    if (baseURL.indexOf('http://localhost') != -1) {
        // Base Url for localhost
        var url = location.href;  // window.location.href;
        var pathname = location.pathname;  // window.location.pathname;
        var index1 = url.indexOf(pathname);
        var index2 = url.indexOf("/", index1 + 1);
        var baseLocalUrl = url.substr(0, index2);

        return baseLocalUrl + "/";
    }
    else {
        // Root Url for domain name
        return baseURL + "/";
    }

}