if (typeof console == "undefined") var console = { log: function() {} };

/**
*
*	Javascript sprintf
*	http://www.webtoolkit.info/
*
*
**/

function parse_date(string) {  
	var date = new Date();  
	var parts = String(string).split(/[- :]/);  
	date.setFullYear(parts[0]);  
	date.setMonth(parts[1] - 1);  
	date.setDate(parts[2]);  
	date.setHours(parts[3]);  
	date.setMinutes(parts[4]);  
	date.setSeconds(parts[5]);  
	date.setMilliseconds(0);  
	return date;  
}
 
sprintfWrapper = {
 
	init : function () {
 
		if (typeof arguments == "undefined") { return null; }
		if (arguments.length < 1) { return null; }
		if (typeof arguments[0] != "string") { return null; }
		if (typeof RegExp == "undefined") { return null; }
 
		var string = arguments[0];
		var exp = new RegExp(/(%([%]|(\-)?(\+|\x20)?(0)?(\d+)?(\.(\d)?)?([bcdfosxX])))/g);
		var matches = new Array();
		var strings = new Array();
		var convCount = 0;
		var stringPosStart = 0;
		var stringPosEnd = 0;
		var matchPosEnd = 0;
		var newString = '';
		var match = null;
 
		while (match = exp.exec(string)) {
			if (match[9]) { convCount += 1; }
 
			stringPosStart = matchPosEnd;
			stringPosEnd = exp.lastIndex - match[0].length;
			strings[strings.length] = string.substring(stringPosStart, stringPosEnd);
 
			matchPosEnd = exp.lastIndex;
			matches[matches.length] = {
				match: match[0],
				left: match[3] ? true : false,
				sign: match[4] || '',
				pad: match[5] || ' ',
				min: match[6] || 0,
				precision: match[8],
				code: match[9] || '%',
				negative: parseInt(arguments[convCount]) < 0 ? true : false,
				argument: String(arguments[convCount])
			};
		}
		strings[strings.length] = string.substring(matchPosEnd);
 
		if (matches.length == 0) { return string; }
		if ((arguments.length - 1) < convCount) { return null; }
 
		var code = null;
		var match = null;
		var i = null;
 
		for (i=0; i<matches.length; i++) {
 
			if (matches[i].code == '%') { substitution = '%' }
			else if (matches[i].code == 'b') {
				matches[i].argument = String(Math.abs(parseInt(matches[i].argument)).toString(2));
				substitution = sprintfWrapper.convert(matches[i], true);
			}
			else if (matches[i].code == 'c') {
				matches[i].argument = String(String.fromCharCode(parseInt(Math.abs(parseInt(matches[i].argument)))));
				substitution = sprintfWrapper.convert(matches[i], true);
			}
			else if (matches[i].code == 'd') {
				matches[i].argument = String(Math.abs(parseInt(matches[i].argument)));
				substitution = sprintfWrapper.convert(matches[i]);
			}
			else if (matches[i].code == 'f') {
				matches[i].argument = String(Math.abs(parseFloat(matches[i].argument)).toFixed(matches[i].precision ? matches[i].precision : 6));
				substitution = sprintfWrapper.convert(matches[i]);
			}
			else if (matches[i].code == 'o') {
				matches[i].argument = String(Math.abs(parseInt(matches[i].argument)).toString(8));
				substitution = sprintfWrapper.convert(matches[i]);
			}
			else if (matches[i].code == 's') {
				matches[i].argument = matches[i].argument.substring(0, matches[i].precision ? matches[i].precision : matches[i].argument.length)
				substitution = sprintfWrapper.convert(matches[i], true);
			}
			else if (matches[i].code == 'x') {
				matches[i].argument = String(Math.abs(parseInt(matches[i].argument)).toString(16));
				substitution = sprintfWrapper.convert(matches[i]);
			}
			else if (matches[i].code == 'X') {
				matches[i].argument = String(Math.abs(parseInt(matches[i].argument)).toString(16));
				substitution = sprintfWrapper.convert(matches[i]).toUpperCase();
			}
			else {
				substitution = matches[i].match;
			}
 
			newString += strings[i];
			newString += substitution;
 
		}
		newString += strings[i];
 
		return newString;
 
	},
 
	convert : function(match, nosign){
		if (nosign) {
			match.sign = '';
		} else {
			match.sign = match.negative ? '-' : match.sign;
		}
		var l = match.min - match.argument.length + 1 - match.sign.length;
		var pad = new Array(l < 0 ? 0 : l).join(match.pad);
		if (!match.left) {
			if (match.pad == "0" || nosign) {
				return match.sign + pad + match.argument;
			} else {
				return pad + match.sign + match.argument;
			}
		} else {
			if (match.pad == "0" || nosign) {
				return match.sign + match.argument + pad.replace(/0/g, ' ');
			} else {
				return match.sign + match.argument + pad;
			}
		}
	}
}
 
sprintf = sprintfWrapper.init;

if(!window['onlocation']) {
	window['onlocation'] = {};
	var onlocation = window['onlocation'];
}

if( typeof jQuery == 'undefined' ) {
	document.write('<script src="', 'http://ajax.googleapis.com/ajax/libs/jquery/1.4.1/jquery.min.js', '"><\/script>');
}

onlocation.loader = setInterval(function(){
	if(typeof jQuery != 'undefined') {
		clearInterval(onlocation.loader);
		jQuery.noConflict();
		jQuery.browser.mobile = (navigator.userAgent.toLowerCase().match('iphone') || navigator.userAgent.toLowerCase().match('ipod') || navigator.userAgent.toLowerCase().match('android') || navigator.userAgent.toLowerCase().match('palm'));

		(function($){
			onlocation.live = {};

			$(document).ready(function() {
				var css = document.createElement('link');
				css.setAttribute('type','text/css');
				css.setAttribute('rel', 'stylesheet');
				css.setAttribute('href','http://static.chattarati.com/css/onlocationlive.css');
				document.getElementsByTagName('head')[0].appendChild(css);
				onlocation.container = $('#ol-placeholder');
				onlocation.eventID = onlocation.container.attr('data-event-id');
				onlocation.hashtag = onlocation.container.attr('data-event-hashtag');
				onlocation.commentID = onlocation.container.attr('data-event-comment-id');
				onlocation.ol = onlocation.container.find('ol.ol-posts').size() ? onlocation.container.find('ol.ol-posts') : $('<ol class="ol-posts" />').appendTo(onlocation.container);
				onlocation.live.updater();
				onlocation.live.links();
				onlocation.archive();
			});

			onlocation.live.flashVersion = function() { 
				// ie 
				try { 
					try { 
						// avoid fp6 minor version lookup issues 
						// see: http://blog.deconcept.com/2006/01/11/getvariable-setvariable-crash-internet-explorer-flash-6/ 
						var axo = new ActiveXObject('ShockwaveFlash.ShockwaveFlash.6'); 
						try { axo.AllowScriptAccess = 'always'; } 
						catch(e) { return '6'; } 
					} catch(e) {} 
					try {
						return new ActiveXObject('ShockwaveFlash.ShockwaveFlash').GetVariable('$version').replace(/\D+/g, ',').match(/^,?(.+),?$/)[1].split(',').shift(); 
					} catch(e) {
						throw e;
					}
				// other browsers 
				} catch(e) { 
					try { 
						if(navigator.mimeTypes["application/x-shockwave-flash"].enabledPlugin){ 
							return (navigator.plugins["Shockwave Flash 2.0"] || navigator.plugins["Shockwave Flash"]).description.replace(/\D+/g, ",").match(/^,?(.+),?$/)[1].split(',').shift(); 
						} 
					} catch(e) {} 
				} 
				return false; 
			} 

			onlocation.live.updater = function() {
				onlocation.live.updater.since_ids = {};
				onlocation.live.updater.since_ids.onlocation = 0;
				onlocation.live.updater.since_ids.twitter = 0;
				onlocation.live.updater.since_ids.comments = 0;

				onlocation.live.updater.blacklist = {};
				onlocation.live.updater.blacklist.flickr = [];
				onlocation.live.updater.blacklist.twitter = [];
				onlocation.live.updater.blacklist.comments = [];

				onlocation.live.updater.updateBlacklists(function() {
					onlocation.live.updater.onlocation();
					onlocation.live.updater.twitter();
					onlocation.live.updater.comments();
					onlocation.live.updater.flickr();
				});
				setInterval(function() {
					onlocation.ol.find('li.new').removeClass('new');
					onlocation.live.updater.updateBlacklists(function() {
						onlocation.live.updater.onlocation();
						onlocation.live.updater.twitter();
						onlocation.live.updater.comments();
						onlocation.live.updater.flickr();
					});
				}, 60 * 1000);
			}

			onlocation.live.updater.onlocation = function() {
			if( ! onlocation.eventID ) { return; }
				$.getJSON(
					'http://onlocation.chattarati.com/posts.json?callback=?',
					{
						'event_id': onlocation.eventID,
						'since_id': onlocation.live.updater.since_ids.onlocation
					},
					function(data){
						try {
							var posts = data.posts;
							onlocation.live.updater.since_ids.onlocation = data.since_id;
							$.each(posts, function() {
								var post = this;
								var li = $(jQuery('<li />'));
								var timestamp = Date.parse(post.published);
								li.attr({
									'id': 'post-' + post.id,
									'timestamp': timestamp
								});
								li.addClass('onlocation').addClass('new');
								li.html('<span class="service-icon"></span><span class="author">' + (post.author.avatar ? '<img src="' + post.author.avatar + '" />' : '') + post.author.name + '</span><span class="published" rel="' + post.published + '">' + post.published + '</span>' + post.text);
								onlocation.live.updater.addItem(li);
							});
							onlocation.live.relativeTimestamps();
						} catch(err) {
							console.log(err);
						}
					}
				);
			}

			onlocation.live.updater.twitter = function() {
				if( ! onlocation.hashtag ) { return; }
				$('li[id^=tweet]').each(function() {
					if($.inArray($(this).attr('id').replace('tweet-',''), onlocation.live.updater.blacklist.twitter) != -1 || $.inArray($(this).find('.author a').text(), onlocation.live.updater.blacklist.twitter) != -1) { $(this).hide(); return true; } else { $(this).show(); }
				});
				$.getJSON(
					'http://search.twitter.com/search.json?&callback=?',
					{
						'tag': onlocation.hashtag,
						'since_id': onlocation.live.updater.since_ids.twitter
					},
					function(data) {
						try {
							var tweets = data.results;
							onlocation.live.updater.since_ids.twitter = data.max_id;
							$.each(tweets, function() {
								var tweet = this;
								if($.inArray(tweet.id, onlocation.live.updater.blacklist.twitter) != -1 || $.inArray(tweet.from_user, onlocation.live.updater.blacklist.twitter) != -1) { $('li#tweet-' + tweet.id).remove(); return true; }
								var li = $(jQuery('<li />'));
								var timestamp = Date.parse(tweet.created_at.replace(/-/g,' '));
								li.attr({
									'id': 'tweet-' + tweet.id,
									'timestamp': timestamp
								});
								if( tweet.text.indexOf('http://yfrog.') > -1 ) {
									var yfrogurl_start	=	tweet.text.search(/http:\/\/yfrog\.com\/([A-Z0-9]+)/i);
									var yfrogurl_end	=	tweet.text.substr(yfrogurl_start + 17).search(/(\s|$)/);
									if( yfrogurl_start == -1 ) {
										yfrogurl_start	=	tweet.text.search(/http:\/\/yfrog\.([a-z]{2})\/([A-Z0-9]+)/i);
										yfrogurl_end	=	tweet.text.substr(yfrogurl_start + 16).search(/(\s|$)/);
									}
									var yfrogurl		=	tweet.text.substr(yfrogurl_start, yfrogurl_start + yfrogurl_end);
									try {
										yfrogurl		=	yfrogurl.split(' ')[0];
									} catch(e) { console.log(e); }
									var yfrogid			=	yfrogurl.split('/');
									yfrogid				=	yfrogid[yfrogid.length - 1];
									$.getJSON(
										'http://query.yahooapis.com/v1/public/yql?callback=?',
										{
											'q':		'select files from xml where url=\'http://yfrog.com/api/xmlInfo?path=' + yfrogid + '\'',
											'format':	'json'
										},
										function(data) {
											var img = data.query.results.imginfo.files.image;
											if(img['content-type'].indexOf('image') > -1) {
												var yfrogimg = '<p><a href="' + yfrogurl + '" target="_blank"><img src="' + yfrogurl + '.th.jpg" /></a></p>';
											} else if(img['content-type'].indexOf('video') > -1) {
												if( $.browser.mobile ) {
													var yfrogimg = '<p><video src="' + yfrogurl + ':iphone" poster="' + yfrogurl + ':frame" /></p>';
												} else {
													var yfrogimg = '<p><object classid="clsid:02BF25D5-8C17-4B23-BC80-D3488ABDDC6B" codebase="http://www.apple.com/qtactivex/qtplugin.cab" width="480" height="340"><param name="src" value="' + yfrogurl + ':iphone" /><param name="autoplay" value="false" /><param name="controller" value="true" /><embed src="' + yfrogurl + ':iphone" autoplay="false" controller="true" pluginspage="http://www.apple.com/quicktime/download/" width="480" height="340"></embed></object></p>';
												}
											} else {
												var yfrogimg = '';
											}
											tweet.text = tweet.text.replace(yfrogurl, '');
											tweet.text = tweet.text.replace(/(http:\/\/([^\s]+))/g, '<a href="$1" target="_blank">$1</a>').replace(/@([A-Za-z0-9_-]+)/g, '<a href="http://twitter.com/$1" target="_blank">@$1</a>').replace(/#([A-Za-z0-9_-]+)/g, '<a href="http://twitter.com/search?q=%23$1" target="_blank">#$1</a>');
											li.addClass('twitter').addClass('new');
											li.html('<span class="service-icon"></span><span class="author"><a href="http://twitter.com/' + tweet.from_user + '/" target="_blank">' + tweet.from_user + '</a><img src="' + tweet.profile_image_url + '" /></span><span class="published" rel="' + tweet.created_at.replace(/-/g, ' ') + '">' + tweet.created_at.replace(/-/g, ' ') + '</span><p>' + tweet.text + '</p>' + yfrogimg);
											onlocation.live.updater.addItem(li);
										}
									);
								} else {
									tweet.text = tweet.text.replace(/(http:\/\/([^\s]+))/g, '<a href="$1" target="_blank">$1</a>').replace(/@([A-Za-z0-9_-]+)/g, '<a href="http://twitter.com/$1" target="_blank">@$1</a>').replace(/#([A-Za-z0-9_-]+)/g, '<a href="http://twitter.com/search?q=%23$1" target="_blank">#$1</a>');
									li.addClass('twitter').addClass('new');
									li.html('<span class="service-icon"></span><span class="author"><a href="http://twitter.com/' + tweet.from_user + '/" target="_blank">' + tweet.from_user + '</a><img src="' + tweet.profile_image_url + '" /></span><span class="published" rel="' + tweet.created_at.replace(/-/g, ' ') + '">' + tweet.created_at.replace(/-/g, ' ') + '</span><p>' + tweet.text + '</p>');
									onlocation.live.updater.addItem(li);
								}
							});
							onlocation.live.relativeTimestamps();
						} catch(err) {
							console.log(err);
						}
					}
				);
			}

			onlocation.live.updater.comments = function() {
				if( ! onlocation.commentID ) { return; }
				$.getJSON(
					'http://chattarati.com/comments.json?callback=?',
					{
						'article-id': onlocation.commentID,
						'since-id':   onlocation.live.updater.since_ids.comments
					},
					function(data) {
						try {
							var now = new Date();
							var comments = data.results.comments;
							$.each(comments, function(i) {
								var comment = this;
								if(!$('li#comment-' + comment.id).size()) {
									var li = $(jQuery('<li />'));
									var datetime = new Date(comment.timestamp.replace(/-/g,' '));
									var timestamp = Date.parse(datetime);
									li.attr({
										'id': 'comment-' + comment.id,
										'timestamp': timestamp
									});
									li.addClass('comment').addClass('new');
									var author = comment.name;
									li.html('<span class="service-icon"></span><span class="author">' + author + '</span><span class="published" rel="' + datetime + '">' + datetime + '</span><p>' + comment.comment.replace(/\n/, '<br /><br />') + '</p>');
									onlocation.live.updater.addItem(li);
								}
							});
							onlocation.live.relativeTimestamps();
						} catch(err) {
							console.log(err);
						}
					}
				);
			}

			onlocation.live.updater.flickr = function() {
				if( ! onlocation.hashtag ) { return; }
				var icon_url = 'http://farm%d.static.flickr.com/%d/buddyicons/%s.jpg';
				var photo_url = 'http://farm%d.static.flickr.com/%d/%d_%s_m.jpg';
				var min_date = Date.parse(parse_date($('#main article .meta .published').attr('title')));
				$.getJSON('http://api.flickr.com/services/rest/?&jsoncallback=?',
					{
						'api_key':					'e26fab7b9d7e059e45d58f2c6feec99e',
						'method':					 'flickr.photos.search',
						'tags':						 onlocation.hashtag,
						'format':					 'json',
						'safe_search':			1,
						'content_type':		 4,
						'extras':					 'owner_name,icon_server,date_upload',
						'privacy_filter':	 1
					},
					function(data) {
						try {
							var photos = data.photos.photo;
							$.each(photos, function() {
								var photo = this;
								if($.inArray(photo.id, onlocation.live.updater.blacklist.flickr) != -1 || $.inArray(photo.owner, onlocation.live.updater.blacklist.flickr) != -1) { $('li#photo-' + photo.id).remove(); return true; }
								if($('li#photo-' + photo.id).size()) { return true; }
								var li = $(jQuery('<li />'));
								var timestamp = photo.dateupload * 1000; // convert to milliseconds for js
								console.log(timestamp, min_date);
								// if( timestamp < min_date ) { return; }
								li.attr({
									'id': 'photo-' + photo.id,
									'timestamp': timestamp
								});
								li.addClass('flickr').addClass('new');
								li.html('<span class="service-icon"></span><span class="author"><a href="http://flickr.com/photos/' + photo.owner + '/" target="_blank">' + photo.ownername + '</a><img src="' + (photo.iconfarm ? sprintf(icon_url, photo.iconfarm, photo.iconserver, photo.owner) : 'http://www.flickr.com/images/buddyicon.jpg')+ '" /></span><span class="published" rel="' + (new Date(timestamp)) + '">' + (new Date(timestamp)) + '</span><p><a href="http://flickr.com/photos/' + photo.owner + '/' + photo.id + '/" title="View Photos" target="_blank"><img src="' + sprintf(photo_url, photo.farm, photo.server, photo.id, photo.secret) + '" /></a></p>');
								onlocation.live.updater.addItem(li);
							});
							onlocation.live.relativeTimestamps();
						} catch(e) {
							console.log(e)
						}
					}
				);
			}

			onlocation.live.updater.addItem = function(item) {
				if(typeof item != 'object') { return; }
				item.hide();
				var closest = onlocation.ol.children('li').filter(function() { return $(this).attr('timestamp') < item.attr('timestamp')}).eq(0);
				if(closest.size()) {
					closest.before(item);
				} else {
					onlocation.ol.append(item);
				}
				if(onlocation.ol.find('li').size() > 1) {
					item.slideDown('normal');
				} else {
					item.show();
				}
			}

			onlocation.live.relativeTimestamps = function() {
				var now = Date.parse(new Date());

				$('span.published').each(function() {
					var span = $(this);
					var timestamp = Date.parse(span.attr('rel'));
					var diff = now - timestamp;
					var nicetext = "";
					time = {};
					time.year =	 Math.floor( diff / 31536000000 ); // 365 time.day. Fuck leap year.;
					time.month =	Math.floor( ( diff - ( time.year * 31536000000 ) ) / 2592000000 ); // Assuming a month is 30 time.day. Close enough.;
					time.week =	 Math.floor( ( diff - ( time.year * 31536000000 ) - ( time.month * 2592000000 ) ) / 604800000 );
					time.day =		Math.floor( ( diff - ( time.year * 31536000000 ) - ( time.month * 2592000000 ) - ( time.week * 604800000 ) ) / 86400000 );
					time.hour =	 Math.floor( ( diff - ( time.year * 31536000000 ) - ( time.month * 2592000000 ) - ( time.week * 604800000 ) - ( time.day * 86400000 ) ) / 3600000);
					time.minute = Math.round( ( diff - ( time.year * 31536000000 ) - ( time.month * 2592000000 ) - ( time.week * 604800000 ) - ( time.day * 86400000 ) - ( time.hour * 3600000 ) ) / 60000 );

					for(var key in time) {
						if(time[key] > 0) {
							switch(key) {
								case 'minute':
									if ( time.month > 0 || time.year > 0	|| time.hour > 12 || time.week > 0 || time.day > 0 ) { continue; }
								case 'hour':
									if( time.week > 0 || time.month > 0 || time.year > 0 ) { continue; }
								case 'day':
									if( time.year > 0 || ( time.week > 0 && time.month > 0 ) ) { continue; }
								default:
									// keep going
							}
							nicetext = nicetext + " " + time[key] + " " + key + (time[key] > 1 ? "s," : ",");
						}
					}
					if(diff <= 30000) {
						nicetext = "now"
					} else if(nicetext == "") {
						nicetext = span.text();
					} else {
						nicetext = nicetext.substr(0,nicetext.length - 1) + " ago";
					}

					span.text(nicetext);
				});
			}

			onlocation.live.links = function() {
			}

			onlocation.live.updater.updateBlacklists = function(data) {
				if(typeof data == 'undefined' || typeof data == 'function') { // this is the intervaled ping. grab the json file. run the callback if given.
					$.getJSON('http://static.chattarati.com/js/blacklists.json?callback=?',
						{},
						function() {
							// do nothing, the parent function will get called by the file
						}
					);
					if(typeof data == 'function') { // do the callback
						data();
					}
				} else { // this is the json results. update the arrays.
					try {
						onlocation.live.updater.blacklist = data.blacklists;
					} catch(e) {
						console.log(e);
					}
				}
			}

			onlocation.archive = function() {
				if( ! $('body').is('.superuser') ) { return; }
				var link = $('<a href="#export-archive" class="export">Export Archive</a>');
				link.click(function(c) {
					c.preventDefault();
					var textarea = $('textarea#ol-export').size() ? $('textarea#ol-export') : $('<textarea id="ol-export" />');
					textarea.val($('#ol-placeholder').html().replace(/ style="display: block;"/g, ''));
					try {
						chattarati.lightbox.target.append(textarea);
						chattarati.lightbox.container.css({'width': '', 'height': ''});
						chattarati.lightbox.overlay.add(chattarati.lightbox.container).fadeIn(1000);
					} catch(e) {
						textarea.prependTo('#main');
					}
				});
				var li = $('<li />');
				li.append(link).appendTo($('ul.tools'));
			}

		})(jQuery);
	}
},100);
