(function($) {

$(document).ready(function() {

	init_flickr_widget();
	init_twitter_widget();
	init_slider_shortcode();

});

function init_flickr_widget() {

	// Initialize flickr widgets
	var c = 1;
	$(".widget.widget_flickr")
	.each(function() {
		var self = $(this),
			imagesDiv = self.find('.flickr-gallery'),
			id = 'rising_' + self.attr('id'),
			storageID = id;

		imagesDiv.attr('id', id);

		function getFlickrData() {
			var query = self.find('.query').attr('href');
			query = encodeURIComponent($.base64Encode(query));
			var url = template_directory + "/includes/ajax/flickr_ajax.php?id=" + id + "&q=" + query;
			$.ajax({
				url: url,
				cache: false,
				success: function(code){
					try {
						eval(code);
						imagesDiv.append('<div class="clear"></div>');
						imagesDiv.find('a').attr('target','_blank');
					} catch(e) {
						console.log('Flickr Widget: Unable to retrieve data. Restart Apache or enable fopen() on the server.');
						return false;
					}

					if (js_caching_enabled) {
						var	now = Math.floor(new Date().getTime()/1000), // UNIX Epoch (seconds)
							expires = now + js_cache_expires * 60,
							data = $.base64Encode($.toJSON({expires: expires, code: code}));
						Rising.localStorage.set(storageID, data);
						console.log('Cached new data for ' + storageID);
					}
				}
			});
		}

		if ( js_caching_enabled ) {
			var cached = Rising.localStorage.get(storageID);
			if ( cached != null ) {
				var data = $.evalJSON($.base64Decode(cached)),
					now = Math.floor(new Date().getTime()/1000); // UNIX Epoch (seconds)
				if ( now < data.expires ) { // Only use data if it has not expired
					var code = data.code;
					eval(code);
					imagesDiv.append('<div class="clear"></div>'); imagesDiv.find('a').attr('target','_blank');
				} else getFlickrData(); // cache expired, fetch & cache new data
			} else getFlickrData(); // cached is null, fetch & cache new data
		} else getFlickrData(); // Caching disabled,  fetch & cache new data

	});
}

function init_twitter_widget() {

	var twitterWidgets = $('.widget.twitter_widget'),
		count = 0;

	// Tweet callback
	function tweetCallback(tweetsUl, tweets) {
		var html = [];
		_.each(tweets, function(tweet) {
			html.push(_.sprintf('<li>%s <small><a href="%s">%s</a></small></li>', tweet.text, tweet.status, tweet.time));
		});
		tweetsUl.html(html.join("\n"));
		if ( ++count == twitterWidgets.length ) Rising.colorAnimations(); // Refresh link animations
	}

	// Reusable callback
	function getTwitterData(storageID, query, tweetsUl) {
		twitter_fetch(query.username, query.count, function(tweets) {
			if ( js_caching_enabled ) {
				var	now = Math.floor(new Date().getTime()/1000), // UNIX Epoch (seconds)
					expires = now + js_cache_expires * 60,
					data = $.base64Encode($.toJSON({expires: expires, tweets: tweets}));
				Rising.localStorage.set(storageID, data);
				console.log('Cached new data for ' + storageID);
			}
			tweetCallback(tweetsUl, tweets);
		});
	}

	$('.widget.twitter_widget').each(function() {
		var self = $(this),
			tweetsUl = self.find('ul.tweets'),
			query = $.evalJSON($.base64Decode(self.find('span.options').attr('data-twitter-query'))),
			storageID = 'twitter_' + query.username;

		if ( js_caching_enabled ) {
			var cached = Rising.localStorage.get(storageID);
			if ( cached != null ) {
				var data = $.evalJSON($.base64Decode(cached)),
					now = Math.floor(new Date().getTime()/1000); // UNIX Epoch (seconds)
				if ( now < data.expires ) {  // data hasn't expired
					tweetCallback(tweetsUl, data.tweets);
				} else getTwitterData(storageID, query, tweetsUl); // data expired
			} else getTwitterData(storageID, query, tweetsUl) // data not cached
		} else getTwitterData(storageID, query, tweetsUl); // js caching disabled

	});

}

function twitter_fetch(username, count, callback) {
	var tweets = [],
		self = this,
		url ='http://twitter.com/statuses/user_timeline/' + username +'.json?count=' + count +'&callback=?';

	$.getJSON(url, function(data) {
		$.each(data, function(i) {
			tweets.push({
				text: data[i].text
					.replace(/(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig,'<a target="_blank" href="$&">$&</a> ')
					.replace(/@([a-zA-Z0-9_]+)/g, '<a target="_blank" href="http://twitter.com/$1">@$1</a>')
					.replace(/#([a-zA-Z0-9_]+)/g,'<a target="_blank" href="http://twitter.com/search/$1">#$1</a>'),
				time: relative_time(data[i].created_at),
				status: 'http://twitter.com/' + username + '/status/' + data[i].id_str
			});
		});
		if ( typeof callback == 'function' ) callback.call(self, tweets);
	});
}

function relative_time(time_value) { // http://twitter.com/javascripts/blogger.js
	var values = time_value.split(" ");
	time_value = values[1] + " " + values[2] + ", " + values[5] + " " + values[3];
	var parsed_date = Date.parse(time_value);
	var relative_to = (arguments.length > 1) ? arguments[1] : new Date();
	var delta = parseInt((relative_to.getTime() - parsed_date) / 1000);
	delta = delta + (relative_to.getTimezoneOffset() * 60);
	if (delta < 60) {return 'less than a minute ago';}
	else if(delta < 120) {return 'about a minute ago';}
	else if(delta < (60*60)) {return (parseInt(delta / 60)).toString() + ' minutes ago';}
	else if(delta < (120*60)) {return 'about an hour ago';}
	else if(delta < (24*60*60)) {return 'about ' + (parseInt(delta / 3600)).toString() + ' hours ago';}
	else if(delta < (48*60*60)) {return '1 day ago';}
	else {return (parseInt(delta / 86400)).toString() + ' days ago';}
}

function init_slider_shortcode() {

	$('.slider-sc').each(function() {
		var slider = $(this),
			images = slider.find('img'),
			nivoSettings = $.evalJSON($(this).attr('data-nivo-settings')),
			nivoData = slider.nivoSlider(nivoSettings).data('nivo:vars');

		// Touch wipe support
		var nextNav = slider.find('.nivo-nextNav'),
			prevNav = slider.find('.nivo-prevNav');

		slider.touchwipe({
			 wipeLeft: function() { nextNav.click(); },
			 wipeRight: function() { prevNav.click(); },
			 preventDefaultEvents: false
		});
	});

}

})(jQuery);
