$(function(){
	
	$('#submit').click(function(){
		to = $('#to').val();
		tweet = $('#tweet').val();		
		if(to != '' && to != '@yourvalentine'){
			$('#form').fadeTo('fast', 0.2);
			$.post("update.php", {to: to, tweet: tweet},
				function(data){
					if(data != 'fail'){
						$('#to').val('');
						to = to.replace('@', "");
						data = data.replace(/http:\/\/(\S+)/, "<a href=\"http://$1\">http://$1</a>");
						$('#tweetlist').prepend('<li class="latesttweet"><a href="http://twitter.com/'+to+'">@'+to+'</a>'+data+'</li><li id="bloodyuglyspacehack"></li>');
						$('#form').css({background: '#79DA39'}).fadeTo('fast', 1);						
					}
					else {
						alert('Valentine is over! Try next year...');
					}
				}
			);			
		}
		else {
			alert("You must send to somebody!");
		}
		return false;
	});
	
	$('#to').focus(function(){
		$(this).val('');	
	});
	
	$('#to').blur(function(){
		if($(this).val() == ''){
			$(this).val('@yourvalentine');
		}	
	});
	
	$.pullTweets = function(){
	 	$.ajax({
	        url: 'http://search.twitter.com/search.json?rpp=5&from=Fr0mTheH34RT_&lang=all',
	        dataType: 'jsonp',
			cache: 'false',
	        success: function(data) {	
				$.each(data.results, function(i, entry){
					status = entry.text.replace(/@(\S+)/, "");
					status = status.replace(/http:\/\/(\S+)/, "<a href=\"http://$1\">http://$1</a>");
					status = "<li><a id=\"username\" href=\"http://twitter.com/"+entry.to_user+"\">@"+entry.to_user+"</a>" + status + "</li>";
					$('#tweetlist').append(status);
				});
	        }
	    });
	}
	$.pullTweets();
	
});