var userlist_width = 530;
var months = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
$(document).ready(function() {	
	//$('#userlist_container').width(($('.userlist').length) * userlist_width);		
	
	$('.userlist li:first').css({'borderTop':'none'});
	
	$('#userlist_container li').live('mouseenter',function(){
		//var offset = Math.floor($(this).parent().parent().position().top + 123);
		var offset = Math.floor($(this).offset().top + 15);
		var name = $('.inner .thumb a', this).attr('rel');
		var user_id = $(this).attr('class').split('_')[1];
		if(connected)
			var following = ($.inArray(parseInt(user_id),friends) != -1);
		if(!mine) {
			$('<a href="#" class="tooltip"><span>'+name+'</span></a>').css('top',offset+'px').appendTo('#wrapper');
			if(connected && $('.tweet .username',this).text() != user.screen_name) {
				if(following)
					$('<a href="#" class="following" rel="'+user_id+'">following</a>').appendTo($(this));
				else
					$('<a href="#" class="follow" rel="'+user_id+'">follow her</a>').appendTo($(this));
			}
		}
			
	}).live('mouseleave',function(){
		$('.tooltip').remove();
		$('.follow, .following').remove();
	});
	
	if(connected) {
		$('#userlist_container li div.inner').each(function() {
			var status_id = $(this).find('.tweet').attr('id').split('_')[1];
			var faved = ($.inArray(parseInt(status_id),favs) != -1) ? ' active' : '';
			if(mine || $('.tweet .username',this).text() == user.screen_name)
				$(this).append('<a href="#" rel="'+status_id+'" class="fav'+faved+'"><div class="actions"><a href="#" rel="'+status_id+'" class="delete">Delete</a>');
			else if(!mine) {
				$(this).append('<a href="#" rel="'+status_id+'" class="fav'+faved+'"></a><div class="actions"><a href="#" rel="'+status_id+'" class="reply">Reply</a><a href="#" class="retweet" rel>Retweet</a>');
		}
		});		
		
		$('a.reply').click(function() {
			$('#mini_menu').hide();
			$('#tweetbox').show();
			//console.log($(this).parents('.tweet').find('.username').text());
			var username = $(this).parents('li').find('.inner .tweet .username').text();
			
			$('#new_tweet').focus();
			$('#new_tweet').val('@'+username+' ');

			charCount();
		});
		
		$('a.retweet').click(function(e) {
			e.preventDefault();
			//var status_id = parseInt($(this).parents('li').find('.tweet').attr('id').split('_')[1]);
			var status_id = $(this).attr('rel');
			$.modal('<div class="content" style="width: 210px;"><p>Retweet this to your followers?</p><p style="margin-left: 10px;"><a href="#" class="button simplemodal-close"><span>Cancel</span></a><a href="#" id="send_retweet" class="button simplemodal-close" rel="'+status_id+'"><span>Retweet</span></a></p><span class="clear"></span></div>',{overlayClose:true});
		});
		
		$('#send_retweet').live('click',function() {
			var status_id = $(this).attr('rel');
			$.post('/twitter.php', {action: 'retweet', status_id: status_id},
				function(data){
					//console.log(data);
					appendNewTweet(data);
					$.modal('<div class="content" style="width: 150px;"><p>Status was retweeted!</p><p><a href="#" class="button simplemodal-close" style="margin-left: 40px;"><span>OK</span></a></p><span class="clear"></span></div>',{overlayClose:true});
				}, 'json');
		});
		
		$('a.delete').click(function(e) {
			e.preventDefault();
			//var status_id = parseInt($(this).parents('li').find('.tweet').attr('id').split('_')[1]);
			var status_id = $(this).attr('rel');
			$.modal('<div class="content" style="width: 210px;"><p>Are you sure you want to delete this tweet?</p><p style="margin-left: 15px;"><a href="#" class="button simplemodal-close"><span>Cancel</span></a> <a href="#" id="delete_tweet" class="button simplemodal-close" rel="'+status_id+'"><span>Delete</span></a></p><span class="clear"></span></div>',{overlayClose:true});
		});
		
		$('#delete_tweet').live('click',function() {
			var status_id = $(this).attr('rel');
			$.post('/twitter.php', {action: 'delete', status_id: status_id},
				function(data){
					//console.log(data);
					$('#status_'+status_id).parent().fadeOut();
					$.modal('<div class="content" style="width: 150px;"><p>Tweet was deleted!</p><p><a href="#" class="button simplemodal-close" style="margin-left: 40px;"><span>OK</span></a></p><span class="clear"></span></div>',{overlayClose:true});
				}, 'json');
		});
		
		$('a.fav').click(function(e) {
			e.preventDefault();
			var status_id = $(this).attr('rel');
			var action = 'favorite';
			if($(this).hasClass('active')) {
				action = 'unfavorite';
				$(this).removeClass('active');
			}
			else
				$(this).addClass('active');
				
			$.post('/twitter.php', {action: action, status_id: status_id});
		});
		
		$('a.follow').live('click',function(e) {
			e.preventDefault();
			var user_id = $(this).attr('rel');
			var user = $(this).parents('li').find('.inner .tweet .username').text();
			$.post('/twitter.php', {action: 'follow', user_id: user_id},
				function(data){
					//console.log(data);
					$.modal('<div class="content" style="width: 200px;"><p>You are now following<br /><b>'+user+'</b></p><p><a href="#" class="button simplemodal-close" style="margin-left: 66px;"><span>OK</span></a></p><span class="clear"></span></div>',{overlayClose:true});
				}, 'json');
		});
		
		$('a.following').live('click',function(e) {
			e.preventDefault();
			var user_id = $(this).attr('rel');
			var user = $(this).parents('li').find('.inner .tweet .username').text();
			$.modal('<div class="content" style="width: 200px;"><p>Do you want to unfollow<br /><b>'+user+'</b>?</p><p><a href="#" class="button simplemodal-close" style="margin-left: 4px;"><span>Cancel</span></a> <a href="#" id="unfollow" rel="'+user_id+'" class="button simplemodal-close"><span>Unfollow</span></a></p><span class="clear"></span></div>',{overlayClose:true});
		});
		
		$('#unfollow').live('click',function() {
			var user_id = $(this).attr('rel');
			var user = $('li.user_'+user_id).find('.inner .tweet .username')[0].text();
			$.post('/twitter.php', {action: 'unfollow', user_id: user_id},
				function(data){
					//console.log(data);
					$('li.user_'+user_id).fadeOut();
					$.modal('<div class="content" style="width: 200px;"><p>You are no longer following<br /><b>'+user+'</b></p><p><a href="#" class="button simplemodal-close" style="margin-left: 66px;"><span>OK</span></a></p><span class="clear"></span></div>',{overlayClose:true});
				}, 'json');
		});
	}
	
	$('#tweet_link').click(function() {
		$('#mini_menu').hide();
		$('#tweetbox').toggle();
		$('#new_tweet').focus();
	});
			
	$('#cancel_tweet').click(function() {
		$('#tweetbox').hide();
		$('#mini_menu').show();
	});
	
	$('#new_tweet').autoResize({extraSpace: 0, limit: 140});
	$('#new_tweet').keyup(charCount);
	$('#new_tweet').bind('paste',charCount);
	$("#new_tweet").maxLength(140);
	
	$('#send_tweet').click(function() {
		var tweet_text = $('#new_tweet').val();
		if(tweet_text != '') {
			$('#tweetbox').hide();
			$('#new_tweet').val('');
			$.post('/twitter.php', {action: 'tweet', status_text: tweet_text},
				function(data){
					//console.log(data);
					appendNewTweet(data);
					$('#mini_menu').show();
				}, 'json');
		}
	});
	
	$('#adduser').click(function() {
		$('#addbox').modal({overlayClose:true});
	});
	
	$('#addme').click(function() {
		var username = $('#username').val();
		if(username != '') {
			$.post('add.php', {user: username},
				function(resp) {
					if(resp == 'success')
						$('#addbox').html('<p class="return">You have been added to our list. We screen and approve all requests, so it may take up to 24 hours for your name to appear.</p>');
					else if(resp == 'dupe')
						$('#addbox').html('<p class="return">You have already been added to our list. We screen and approve all requests, so it may take up to 24 hours for your name to appear.</p>');
					else
						$('#addbox').html('<p class="return">We could not add you to our list at this time. Please try again later.</p>');
					$('#simplemodal-container').height('auto');
			},'text');
		}
	});

	//adjustHeight();
	
});

function toggleTweetBox(){
	if($("#tweetbox").html() == '') {
		twttr.anywhere(function (T) {
		    T("#tweetbox").tweetBox({'height':'35px', 'onTweet':
				function(text,html) {
					console.log(text);
					console.log(html);
				}
			});
		});
	}
	else
		$("#tweetbox").html('');
}

function adjustHeight() {
	$('#userlist_container').height($('.userlist.current').height()+50);
}

function charCount(e) {
	var chars = $('#new_tweet').val().length;
	$('#char_count').text(140-chars);
	/*
	if(chars > 78) {
		$('#new_tweet').height(26);
		//$('#send_tweet').css({'marginTop':'5px'});
	}
	else {
		$('#new_tweet').height(15);
		//$('#send_tweet').css({'marginTop':'0px'});
	}
	*/
	
	if(chars == 0) {
		$('#send_tweet').addClass('disabled');
		$('#char_count').removeClass('orange');
		$('#char_count').removeClass('red');
	}
	else if (chars >= 135 && chars < 140) {
		$('#char_count').removeClass('red');
		$('#char_count').addClass('orange');
	}
	else if (chars >= 140) {
		$('#char_count').removeClass('orange');
		$('#char_count').addClass('red');
	}
	else {
		$('#send_tweet').removeClass('disabled');
		$('#char_count').removeClass('red');
		$('#char_count').removeClass('orange');
	}
}

function appendNewTweet(data) {
	var screen_name = data.user.screen_name;
	var name = data.user.name;
	var pic = data.user.profile_image_url;
	var status_id = data.id;
	var status_text = data.text;
	var d = new Date(data.created_at);
	var hour = d.getHours();
	var mins = (d.getMinutes() < 10) ? '0'+d.getMinutes() : d.getMinutes();
	var ampm = (hour < 12) ? 'am' : 'pm';
	var month = months[d.getMonth()];
	var day = d.getDate();
	$('.userlist').prepend('<li style="display: none;"><div class="inner"><span class="thumb"><a href="http://twitter.com/'+screen_name+'" rel="'+name+'"><img src="'+pic+'" alt="'+name+'"></a></span><span class="tweet"><a class="username" href="http://twitter.com/'+screen_name+'" rel="'+name+'">'+screen_name+'</a> '+twitter_link_hashtags(twitter_link_names(auto_link_urls(status_text)))+'<span class="entry"><a href="http://twitter.com/'+screen_name+'/status/'+status_id+'">'+(hour%12)+':'+mins+' '+ampm+' '+month+' '+day+'</a> from <a href="http://twitgirl.com/" rel="nofollow">Twitgirl</a> </span></span></div></li>');
	$('.userlist li:first').fadeIn();
}

function twitter_link_names(text) {
	return text.replace(/@([a-zA-Z0-9_]+)/g, '<span class="at">@</span><a href="http://twitter.com/$1" target="_blank">$1</a>');
}

function twitter_link_hashtags(text) {
	return text.replace(/(^|\s)#(\w+)/g, '$1<a href="http://search.twitter.com/search?q=%23$2" target="_blank">#$2</a>');
}

function auto_link_urls(text) {
	var reg = new RegExp(/(http:\/\/|\w+\.)[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&amp;:\/~\+#]*[\w\-\@?^=%&amp;\/~\+#])?/g);
	var url = text.match(reg)
	return text.replace(url,'<a href="'+url+'" target="_blank">'+url+'</a>');
}

/*
twttr.anywhere(function (T) {
	T("#userlist_container").hovercards({'infer':true});
});
*/