var naugthyCutoff = 0.065;
var nRatio;

function tweetThis() {
	var result;

	if(nRatio > naugthyCutoff) {
		$("img#response").attr("src","images/sign_naughty.gif");
		result = "#NAUGHTY";
	} else {
		$("img#response").attr("src","images/sign_nice.gif");
		result = "#NICE";
	}

	var url = "http://twitter.com/?status=" + escape("Ho ho ho! @Twitta_Claus says I've been " + result + " this year! Find out if you've been Naughty or Nice at http://www.twitta-claus.com");
	window.open(url);
}

$(document).ready(function() {

	$("input[type=text]").focus(function(){
	    this.select();
	});

	$("input[name=submit]").unbind("click").click(
		function() {
			var username = $("input[name=username]").val();
			getTweets(username);
			return false;
		}
	);

	$("#jquery_jplayer").jPlayer( {
		ready: function () {
			$(this).setFile("http://www.twitta-claus.com/bg.mp3").play();
		},
		swfPath: "lib"
	});
	
	$("#jquery_jplayer").onSoundComplete( function() {
	  $(this).play();
	});
	
	function getTweets(username) {
		
		$("img#response").attr("src","images/sign_loading.gif");

		$.getJSON("http://twitter.com/statuses/user_timeline/" + username + ".json?count=100&callback=?", function(data) {
			/*
				Twitter ID: data[0].user.id
				Twitter name: data[0].user.screen_name
				Number of tweets: data.length
			*/

			var naughtyIndex = 0;
			for(i = 0; i < data.length; i++) {
				naughtyIndex += checkNaughtyWords(data[i].text);
			}
			nRatio = naughtyIndex / data.length;

			$("#share").css("display", "inline");
			if(jQuery.browser.safari) {
				$("#submit").css("top", 128);
				$("#username").css("top", 72);
			} else {
				$("#submit").css("top", 128);
				$("#username").css("top", 71);
			}

			$("#footer").css("top", 384);
			
			var list;
			if(nRatio > naugthyCutoff) {
				list = "naughty";
				$("img#response").attr("src","images/sign_naughty.gif");
			} else {
				list = "nice";
				$("img#response").attr("src","images/sign_nice.gif");
			}
			
			addToList(data[0].user.id, list);
		});
	}
	
	function addToList(userId, list) {
		$.post("addtolist.php", { userid: userId, listname: list } );
	}

	function checkNaughtyWords(tweet) {
		var naughtyIndex = 0;
		for(j = 0; j < list_naughty.length; j++) {
			if(list_naughty[j].search(" ") != -1) {
				if(tweet.toLowerCase().search(list_naughty[j]) != -1) {
					naughtyIndex++;
				}
			} else {
				var words = tweet.split(" ");
				for(k = 0; k < words.length; k++) {
					if(words[k] == list_naughty[j]) {
						naughtyIndex++;
					}
				}
			}
		}
		return naughtyIndex;
	}
});