ContentProviders = {};
/* content provider is an object with two public methods:
 * getInitial(cb) does cb(oEmbed)
 * search(query, cb) does cb([oEmbed,...])
 */
if (window.jQuery) {
	function rnd(x) {
		return Math.floor(Math.random() * x);
	}
	function ajax(o) {
		return function (url, handler) {
			var c = 0, r = $.extend({
				url: url,
				timeout: 5000,
				success: handler,
				error: function () {
					if (c < 10) {
						setTimeout(function () {
							$.ajax(r);
						}, rnd(100));
					}
					c += 1;
				}
			}, o);
			$.ajax(r);
		}
	}
	var oEmbed = {
		type: 'image',
		version: 1,
		thumbnail_url: 'http://farm4.static.flickr.com/3542/3495699336_7d57477ff8_s.jpg',
		thumbnail_height: 75,
		thumbnail_width: 75,
		url: 'http://farm4.static.flickr.com/3542/3495699336_7d57477ff8_m.jpg',
		width: 240,
		height: 160,
		author: '',
		author_url: '',
		html: '<img src="http://farm4.static.flickr.com/3542/3495699336_7d57477ff8_m.jpg" alt="No hinting" />'
	};
	var oEmbed = {
		type: 'image',
		version: 1,
		thumbnail_url: 'http://farm1.static.flickr.com/27/98408457_9086b3bd97_s.jpg',
		thumbnail_height: 75,
		thumbnail_width: 75,
		url: 'http://farm1.static.flickr.com/27/98408457_9086b3bd97_m.jpg',
		width: 180,
		height: 240,
		author: 'TahoeSunsets',
		author_url: 'http://www.flickr.com/photos/64149699@N00/',
		html: '<img src="http://farm1.static.flickr.com/27/98408457_9086b3bd97_m.jpg" alt="No hinting" />'
	};
	jQuery(function ($) {
		var b = $('body');
		if (b.hasClass('play')) {
			// content providers
			ContentProviders.flickr = function () {
				function flickr2oEmbed(item) {
					var r = {
						type: 'image',
						version: 1,
						url: 'http://farm' + item.farm + '.static.flickr.com/' + item.server + '/' + item.id + '_' + item.secret+'_m.jpg',
						width: item.width || 240,
						height: item.height || 240,
						thumbnail_url: 'http://farm' + item.farm + '.static.flickr.com/' + item.server + '/' + item.id + '_' + item.secret+'_s.jpg',
						thumbnail_height: 75,
						thumbnail_width: 75,
						author: item.ownername,
						author_url: 'http://www.flickr.com/photos/' + item.owner
					};
					r.html = '<img src="' + r.url + '" alt="Photo by ' + r.author_url + ' from Flickr" title="Photo by ' + r.author_url + ' from Flickr" />';
					return r;
				}
				var r = {
					getInitial: function (cb) {
						var timesince = Math.round(new Date().getTime()/1000) - 60*60*6, // Six hours
							timebefore = Math.round(new Date().getTime()/1000) - 60*60, // One hour
							g = 'http://query.yahooapis.com/v1/public/yql?q=select%20farm%2C%20server%2C%20id%2C%20secret%2C%20owner%2C%20ownername%20from%20flickr.photos.search(10)%20where%20extras%3D%22owner_name%22%20and%20license%3D%221%2C2%2C3%2C4%2C5%2C6%2C7%22%20and%20privacy_filter%3D1%20and%20min_upload_date%3D' + timesince + '%20and%20max_upload_date=' + timebefore + '&format=json&callback=?';
						ajax({dataType:'jsonp'})(g, function (data) {
							c = 0; // reset repeat count
							var idx = Math.floor(Math.random() * data.query.count);
							cb(flickr2oEmbed(data.query.results.photo[idx]));
						});
					},
					search: function (query, cb) {
						var timebefore = Math.round(new Date().getTime()/1000) - 60*60, // One hour
							g = 'http://query.yahooapis.com/v1/public/yql?q=select%20farm%2C%20server%2C%20id%2C%20secret%2C%20owner%2C%20ownername%20from%20flickr.photos.search(8)%20where%20extras%3D%22owner_name%22%20and%20license%3D%221%2C2%2C3%2C4%2C5%2C6%2C7%22%20and%20privacy_filter%3D1%20and%20text%3D%22' + encodeURIComponent(query) + '%22%20and%20max_upload_date=' + timebefore + '&format=json&callback=?';
						ajax({dataType:'jsonp'})(g, function (data) {
							var r = [];
							$.each(data.query.results && data.query.results.photo || [], function (i, n) {
								r.push(flickr2oEmbed(n));
							});
							if (r.length < 8) {
								ContentProviders.zemanta.search(query, cb);
							} else {
								cb(r);
							}
						});
					}
				};
				return r;
			}();
			ContentProviders.zemanta = function () {
				function zemanta2oEmbed(item) {
					var a = $(item.attribution).find('a'), r = {
						type: 'image',
						version: 1,
						url: item.url_m,
						width: item.url_m_w || 240,
						height: item.url_m_h || 240,
						thumbnail_url: item.url_s,
						thumbnail_height: 75,
						thumbnail_width: 75,
						author: a.text(),
						author_url: a.attr('href')
					};
					r.html = '<img src="' + r.url + '" alt="Photo by ' + r.author_url + ' from Flickr" title="Photo by ' + r.author_url + ' from Flickr" />';
					return r;
				}
				var r = {
					search: function (query, cb) {
						var g = '';
						ajax({
							type: 'post',
							data:{
								api_key: '6k29jtvue38kg2v22tjf8ner',
								emphasis: query,
								format: 'wnjson',
								method: 'zemanta.suggest',
								image_types: 'flickr',
								return_images: 1,
								text: ''
							},
							timeout: 30000
						})('http://api.zemanta.com/services/rest/0.0/', function (data) {
							var r = [], data = JSON.parse(data);
							$.each(data && data.images || [], function (i, n) {
								if (i < 8) {
									r.push(zemanta2oEmbed(n));
								}
							});
							cb(r);
						});
					}
				};
				return r;
			}();
	
			var cp = ContentProviders.flickr,
				src = $('#sourcedata'),
				res = $('#matches');
			// make sure we have initial
			if (src.find('img').size() === 0) {
				cp.getInitial(function (o) {
					src.find('.contentbox').html(o.html);
				});
			}
			// attach eventhandler to form
			$('#answerinput').bind('submit', function (ev) {
				var e = $(this),
					v = e.find('#imageis').val(),
					l = $('<div><h2>Loading images...</h2></div>').hide().insertAfter(e);
				ev.preventDefault();
				if ($.trim(v) === '') {
					return;
				}
				src.slideUp();
				e.slideUp();
				l.slideDown();
				cp.search(v, function (o) {
					var list = res.find('ul').empty();
					$.each(o, function (i, n) {
						$('<li><div class="contentbox"><img src="' + n.thumbnail_url + '" alt="Photo by ' + n.author_url + ' from Flickr" title="Photo by ' + n.author_url + ' from Flickr" /></div></li>').data('json', JSON.stringify(n)).appendTo(list);
					});
					$('#matches li').live('click', function (ev) {
						var e = $(this);
						res
							.find('.selected').removeClass('selected').end()
							.find('input.submit').attr('disabled', null).end()
							.find('input[name=content]').val(e.data('json')).end();
						e.addClass('selected');
					});
					l.slideUp(function () {
						l.remove();
					});
					res
						.find('q').html(v).end()
						.find('input[name=answer]').val(v).end()
						.slideDown();
				});
			});
		} else if (b.hasClass('invite')) {
			$('#challenge li a').click(function (ev) {
				if (this.href.indexOf('mailto:') !== 0) {
					ev.preventDefault();
					window.open(this.href);
				}
			});
		} else if (b.hasClass('results')) {
			$('#results abbr.published').prettyDate();
			setInterval(function () {
				$("#results abbr.published").prettyDate();
			}, 5000);
			$('#results span.author').each(function (i, n) {
				var e = $(n), v = e.text();
				if (v.indexOf('@') === 0) {
					e.replaceWith('<a class="' + e.attr('class') + '" href="http://twitter.com/' + v.substr(1) + '">' + v.substr(1) + '</a>');
				}
			});
			$('#results li h3').each(function (i, n) {
				var e = $(n), h = e.height() / 40;
				e.addClass(['', '', 'double'][h] || '');
			});
		} else if (b.hasClass('index')) {
			$('#recent li h3').each(function (i, n) {
				var e = $(n), h = e.height() / 40;
				e.addClass(['', '', 'double', 'triple', 'quadruple'][h] || '');
			});
		}
	});
}