jQuery(function(){
	if(jQuery('#ngg-gallery-1-5').length) {
		jQuery('div.ngg-clear').remove();
		jQuery('#ngg-gallery-1-5').cycle({
			fx: 'scrollHorz',
			timeout: 6000,
			next: '#nextpic',
			prev: '#prevpic',
			speed: 600
		});
		jQuery('div.ngg-gallery-thumbnail').click(function(){
			jQuery('#ngg-gallery-1-5').cycle('pause');
		});
		jQuery( "body" ).bind( "DOMNodeRemoved", function( objEvent ){
			if(jQuery(objEvent.target).attr('id') == 'TB_overlay') {
				jQuery('#ngg-gallery-1-5').cycle('resume');
			}
		});
		 
	}
	
	var twitterFeed = jQuery('#twitterFeed');
	if(twitterFeed.length) {
		getTweets('LemoloBaggage',showTweets, twitterFeed);
	}
});


function getTweets(_user, _callback, _place) {
	jQuery.ajax({
		dataType: 'jsonp',
		url: "http://rhapi.com/twitter/"+_user+"?limit=5",
		success: function(resp){
			_callback(resp, _place);
		}
	});
}

function showTweets(_data, _div) {
	_div.append('<a href="https://twitter.com/lemolobaggage">Lemolo Baggage on Twitter</a>');
	jQuery.each(_data, function(i,tweet){
		var html = '<div class="tweet">'
		// if(tweet.retweeted_status) {
			// html += '<img src="'+tweet.retweeted_status.user.profile_image_url_https+'" />';
		// }
		// else {
			// html += '<img src="'+tweet.user.profile_image_url_https+'" />';
		// }
		html += '<p>'+linkify(tweet.text)+'</p>';
		html += '<a href="https://twitter.com/LemoloBaggage/status/'+tweet.id_str+'">'+timeAgo(tweet.created_at)+'</a>';
		html += '</div>';
		_div.append(html);
	});
	_div.append('<a href="https://twitter.com/lemolobaggage" style="float: right;">View All Updates</a>');
}

function linkify(text) {
    text = text.replace(/(^|)@(\w+)/gi, function (s) {
        return '<a href="https://twitter.com/' + s + '">' + s + '</a>';
    });

    text = text.replace(/(^|)#(\w+)/gi, function (s) {
        return '<a href="https://search.twitter.com/search?q=' + s.replace(/#/,'%23') + '">' + s + '</a>';
     });
    return text;
}
function timeAgo(_date) {
	var now = new Date();
	var then = new Date(_date);
	var time = now-then;
	if(time < 60000) { //seconds
		return Math.floor(time/1000)+' seconds ago';
	}
	if(time < 3600000) { //minutes
		return Math.floor(time/60000)+' minutes ago';
	} 
	else if(time < 86400000) { //hours
		return Math.floor(time/3600000)+' hours ago';
	}
	else if(time < 604800000) { //days
		return Math.floor(time/86400000)+' days ago';
	}
	else if(time < 31557600000) { //weeks
		return Math.floor(time/604800000)+' weeks ago';
	}
	else { //years
		return Math.floor(time/31557600000)+' years ago';
	}
	
}

