if (navigator.userAgent.indexOf('iPhone') !== -1) {
window.scrollTo(0, 1);
}

else if (screen.width <= 481) {
window.scrollTo(0, 1);
}

else {
document.location = "../web/";
}

function hideURLbar() {
	window.scrollTo(0, 1);
}

function setScreen() {
	setTimeout(hideURLbar, 0);
}

addEventListener("load", function() { setTimeout(hideURLbar, 0); }, false);
	
function limitText(limitField, limitCount, limitNum) {
		limitCount.value = limitNum - limitField.value.length;
}
	
$(document).ready(function(){

	String.prototype.linkify = function() {
		return this.replace(/[A-Za-z]+:\/\/[A-Za-z0-9-_]+\.[A-Za-z0-9-_:%&\?\/.=\+]+/, function(m) {
		return m.link(m);
		  }).replace(/@[A-Za-z0-9_]+/g, function(m) {
				return '<a href="#" class="twUser" rel="' + m.substr(1) + '">' + m + '</a>';
			}).replace(/#[a-zA-Z0-9\d\_\-\.\+]+/g, function(m) {
				var tagPref = $.cookie("tagPref");
				if(tagPref == 'pretty') {
					return '<a href="#" class="twTagLink" rel="' + m + '">' + m.substr(1) + '</a>';
				} else {
					return '<a href="#" class="twTagLink" rel="' + m + '">' + m + '</a>';
				}
			});
		 }
		 
	  function relative_time(time_value) {
		  var values = time_value.split(" ");
		  time_value = values[1] + " " + values[2] + ", " + values[5] + " " + values[3];
		  var parsed_date = Date.parse(time_value);
		  var relative_to = (arguments.length > 1) ? arguments[1] : new Date();
		  var delta = parseInt((relative_to.getTime() - parsed_date) / 1000);
		  delta = delta + (relative_to.getTimezoneOffset() * 60);
		  
		  var r = '';
		  if (delta < 60) {
			r = (parseInt(delta / 1)).toString() + ' seconds ago';
		  } else if(delta < 120) {
			r = 'a minute ago';
		  } else if(delta < (45*60)) {
			r = (parseInt(delta / 60)).toString() + ' minutes ago';
		  } else if(delta < (90*60)) {
			r = 'an hour ago';
		  } else if(delta < (24*60*60)) {
			r = '' + (parseInt(delta / 3600)).toString() + ' hours ago';
		  } else if(delta < (48*60*60)) {
			r = '1 day ago';
		  } else {
			r = (parseInt(delta / 86400)).toString() + ' days ago';
		  }

		  return r;
		}
		
	  function relative_time2(time_value) {
		  var values = time_value.split(" ");
		  time_value = values[1] + " " + values[2] + ", " + values[5] + " " + values[3];
		  var parsed_date = Date.parse(time_value);
		  var relative_to = (arguments.length > 1) ? arguments[1] : new Date();
		  var delta = parseInt((relative_to.getTime() - parsed_date) / 1000);
		  delta = delta + (relative_to.getTimezoneOffset() * 60);

		  var r = '';
			r = (parseInt(delta / -60)).toString() + ' minutes';

		  return r;
		}
	
	$(".loginInput").focus(function() {
		var thisInput = $(this).attr("id");
		var thisValue = $(this).attr("value");
		if(thisValue == "username" || thisValue == "") {
			$(this).attr("value","");
			$(this).css({ "font-style":"normal", color: "black", "background-color": "white" });
		}
		if(thisInput = "#twPassword") {
			$(this).css("background","white");
			$(this).css({ "font-style":"normal", color: "black" });
		}
	});
	
	$(".loginInput").blur(function() {
		var thisInput = $(this).attr("id");
		var thisValue = $(this).attr("value");
		if(thisValue == null) {
			$(this).css({ "font-style":"italic", color: "#666" });
			if(thisInput == "twUsername") {
				$(this).attr("value","username");
			} else if(thisInput == "twPassword") {
				$(this).css({ "background": "white url(images/password.gif) no-repeat" });
			}
		}
	});
	
	$("#loginBtn").click(function(){
		var itweet2user = $("#twUsername").val();
		var itweet2pass = $("#twPassword").val();
		var token = $("#sessionToken").val();
		$(".loginNote").hide();
		$("#twLogin").hide();
		$.post("cookie.php", { username: itweet2user, password: itweet2pass, token: token },
			function(data){
			if(data == "ok") {
			$("#logoContainer").hide();
			$("#loginError").remove();
			$(".loadingR").remove();
			$("#footer").hide();
			$("#panel").show();
			$.getJSON("login.php",
			  function(data){
			  $.cookie('itweet2UserID', data.id, { expires: 14 });
			  $.cookie('protected', data.protected, { expires: 14 });
			    $("#twittername").val(itweet2user);
				var device = $.cookie('device');
				$(".twSttgNots").removeClass("optSelect");
				if(device == "sms") {
					$("#twSttgNotsSMS").addClass("optSelect");
				} else if(device == "none") {
					$("#twSttgNotsNone").addClass("optSelect");
				}
				var tagPref = $.cookie('tagPref');
				if(tagPref == "pretty") {
					$("#twSttgPrettyTags").addClass("optSelect");
				} else {
					$("#twSttgLinkTags").addClass("optSelect");
				}
			  $("#tweets").friendLoad();
			  return false;
				});
			  var query = $.query(location.search);
				for (var k in query){
					if(k == "tweetUrl"){
						$.get("bitly.php",
							{ url: decodeURIComponent(query[k]) },
							function(data){
								$("#menu").hide();
								$("#settingsList").hide();
								$("#searchForm").hide();
								$("#twPost").show();
								$("#twMessage").val(data);
								$(".postField").focus();
								$(this).setScreen();
								return false;
							});
					}
				}
			} else {
				$(".loadingR").remove();
				$("#twLoginForm").show();
				alert("Incorrect login or password. Please try again.");
			}
			});
	return false;
	});
	
	$("#logOutLink").click(function(){
		var logOut = confirm("Are you sure you want to log out?");
		if (logOut == true){
			$("#tweets").empty();
			$("#panel").hide();
			$("#menu").hide();
			$("#pagination").hide();
			$("#rateCount").hide();
			$("#footer").show();
			$.cookie('itweet2User', null);
			$.cookie('itweet2Password', null);
			$.cookie('itweet2UserID', null);
			$.cookie('tagPref', null);
			$.cookie('page', null);
			$("#logoContainer").show();
			$("#twLogin").show();
			$(".loginNote").show();
			$("#twLoginForm").show();
		}
		return false;
	});
	
	$(".twFriends").history(function(){
		$("#menu").hide();
		$("#pageNumber").html("1");
		$("#tweets").friendLoad();
		return false;
	});
	
	jQuery.listen( "click", "#emailColby", function(){
		var messageVal = $("#emailColbyMsg").val();
		var usernameVal = $("#twittername").val();
		var token = $("#sessionToken").val();
		if(messageVal == ""){
			alert("Please enter a message!");
			return false;
		}
		$.post("contactForm.php",
			{ username: usernameVal, message: messageVal, token: token },

				function(data){
					$("#emailColbyMsg").fadeOut("normal", function() {				   
						$("#emailColbyMsg").attr("value","");
						$("#emailColbyMsg").fadeIn("normal");
						alert("Message sent! Thanks!");
					});
				});
				return false;
		  });
	
	$("#btnMenu").click(function(){
					$("#twPost").hide();
					$("#twDirectPost").hide();
					$("#settingsList").hide();
					$("#searchForm").hide();
					$("#menu").toggle();
					return false;
					});
					
	$("#btnPost").click(function(){
					$("#tweets").stopTime();
					$("#menu").hide();
					$("#settingsList").hide();
					$("#searchForm").hide();
					$("#twPost").show();
					$(".postField").focus();
					$(this).setScreen();
					return false;
					});
					
	$("#cancelBtn").click(function(){
					$("#twMessage").attr("value","");
					$("#countdown").attr("value","140");
					$(".postField").blur();
					$("#twPost").hide();
					});
					
	$("#cancelDirectBtn").click(function(){
					$("#twMessage").attr("value","");
					$("#countdown").attr("value","140");
					$("#directID").attr("value","");
					$(".postField").blur();
					$("#twDirectPost").hide();
					});
					
	$("#btnSearch").click(function(){
					$("#menu").hide();
					$("#settingsList").hide();
					$("#twPost").hide();
					$("#searchForm").toggle();
					var thisField = $("#searchInput").css("display");
					if(thisField == "block") {
						$("#searchInput").focus();
					} else {
						$("#searchInput").blur();
					}
					return false;
					});
					
	$("#btnSettings").click(function(){
					$("#menu").hide();
					$("#twPost").hide();
					$("#searchForm").hide();
					$("#settingsList").toggle();
					return false;
					});
					
	$("#settingsClose").click(function(){
					$("#settingsList").hide();
					return false;
					});

		jQuery.listen( "click", ".rtBtn", function(){
					$("#menu").hide();
					$("#searchForm").hide();
					$("#settingsList").hide();
					$("#twPost").show();
					var rtText = $(this).parent().children(".twText").text();
					var retweet = "RT @"+$(this).attr('rel')+": "+rtText;
					$("#twMessage").focus();
					$("#twMessage").val(retweet);
					var max = '140';
					var charcount = retweet.length;
					//  if(charcount > max){
					//	$(".postField").css("color","#a00");
					//	} else {
					//	$(".postField").css("color","black");
					//	}
					var left = max-charcount;
					$("#countdown").val(left.toString());
					$("#twMessage").focus();
					$(this).setScreen();
					return false;
					});
	
	jQuery.listen( "click", ".replyBtn", function(){
					$("#menu").hide();
					$("#searchForm").hide();
					$("#settingsList").hide();
					$("#twPost").show();
					var replyTo = "@"+$(this).attr('id')+" ";
					$("#twMessage").focus();
					$("#twMessage").val(replyTo);
					$(this).setScreen();
					return false;
					});
					
	jQuery.listen( "click", ".favBtn", function(){
					$(this).favPost();
					return false;
					});
					
	jQuery.listen( "click", ".favUnstar", function(){
					$(this).favDestroy();
					return false;
					});
					
	jQuery.listen( "click", ".destroyBtn", function(){
					$(this).destroyTweet();
					return false;
					});
					
	jQuery.listen( "click", ".destroyDirect", function(){
					$(this).destroyDirect();
					return false;
					});

	jQuery.listen( "click", ".twNotsOn", function(){
					$(this).notsOn();
					return false;
					});
	
	jQuery.listen( "click", ".twNotsOff", function(){
					$(this).notsOff();
					return false;
					});
					
	jQuery.listen( "click", ".followOn", function(){
					$(this).followOn();
					return false;
					});
	
	jQuery.listen( "click", ".followOff", function(){
					$(this).followOff();
					return false;
					});
					
	jQuery.listen( "click", ".blockOn", function(){
					$(this).blockOn();
					return false;
					});
	
	jQuery.listen( "click", ".blockOff", function(){
					$(this).blockOff();
					return false;
					});
					
	jQuery.listen( "click", "#followCheck", function(){
					var them = $(this).parent().attr("rel");
					var you = $("#twittername").val();
					$.getJSON("friendship_exists.php",
						{ user_a: them, user_b: you },
						function(data){
							if(data.error){
							alert(data.error);
							return false;
							}
						  if(data == "true") {
							$("#followCheck").html("@"+them+" is following you!");
							$("#followCheck").attr("id", "followChecked");
						  }
						  if(data == "false") {
							$("#followCheck").html("@"+them+" is not following you!");
							$("#followCheck").attr("id", "followChecked");
						  }
						  if(data == true) {
							$("#followCheck").html("@"+them+" is following you!");
							$("#followCheck").attr("id", "followChecked");
						  }
						  if(data == false) {
							$("#followCheck").html("@"+them+" is not following you!");
							$("#followCheck").attr("id", "followChecked");
						  }
						  return false;
						  });
					return false;
					});
					
	jQuery.listen( "click", ".twSttgNots", function(){
					$(".twSttgNots").removeClass("optSelect");
					$(this).addClass("optSelect");
					$(this).setDevice();
					return false;
					});
					
	$(".twSttgTags").click(function(){
					$(".twSttgTags").removeClass("optSelect");
					$(this).addClass("optSelect");
					var tagPref = $(this).attr("rel");
					$.cookie('tagPref', tagPref);
					return false;
					});
					
	$("#locBtnGo").click(function(){
		var location = $("#locInputMain").val();
		if(location == "") {
			alert("Please enter your location.");
			return false;
		}
		$(this).setLocation();
		$("#locInputMain").attr("value","");
		$("#locContainer").html(location);
		$("#settingsList").hide();
		return false;
		});
					
	$("#twTest").click(function(){
					$.getJSON("http://twitter.com/help/test.json?callback=?",
						function(data){
							if(data.error){
							alert(data.error);
							return false;
							}
						  if(data == "ok") {
							alert("Test ping to Twitter returned successfully!");
						  } else {
							alert("Oh noes! Test ping to Twitter = FAIL");
						  }
						  });
					});
					
	jQuery.fn.rateCount = function() {
		$.getJSON("rateCount.php",
			function(data){
				if(data.error){
					alert(data.error);
					return false;
					}
				$("#rateCount").html(data.remaining_hits);
				return false;
			});
	}
	
	$("#twRateCheck").click(function(){
		$.getJSON("rateCount.php",
			function(data){
				if(data.error){
					alert(data.error);
					return false;
					}
				var rateLeft = data.remaining_hits;
				var rateTotal = data.hourly_limit;
				var rateTimeLeft = relative_time2(data.reset_time);
				alert(rateLeft + " of " + rateTotal + " hits remaining. Counter will reset in "+ rateTimeLeft);
				return false;
			});
	});
					
	jQuery.listen( "click", ".twAvatar", function(){
					var myRow = $(this).parent();
					$(myRow).children(".tweetBio").toggle();
					return false;
					});
					
	jQuery.listen( "click", ".twUser", function(){
					$("#pageNumber").html("1");
					$(this).getUser();
					return false;
					});
					
	jQuery.listen( "click", ".twProfile", function(){
					$(this).getProfile();
					return false;
					});
					
	jQuery.listen( "click", ".twName", function(){
					$("#pageNumber").html("1");
					$(this).getUser();
					return false;
					});
					
	jQuery.listen( "click", "#twPostBtn", function(){
					$(this).twPost();
					return false;
					});
	
	jQuery.listen( "click", "#twDirectPostBtn", function(){
					$(this).twDirectPost();
					return false;
					});
	
	jQuery.listen( "click", ".directPost", function(){
					$("#menu").hide();
					$("#twPost").hide();
					$("#twDirectPost").show();
					$("#directID").val("");
					$(".postField").val("");
					$("#directID").focus();
					});
					
	jQuery.listen("click", ".sendDirect", function(){
					$("#menu").hide();
					$("#twDirectPost").show();
					var directTo = $(this).attr("title");
					$(".postField").val("");
					$("#directID").val(directTo);
					$(".postField").focus();
	});
	
	jQuery.listen("click", ".searchFrom", function(){
		$("#searchInputMain").val("from:");
		$("#searchInputMain").focus();
		return false;
	});
	
	jQuery.listen("click", ".searchTo", function(){
		$("#searchInputMain").val("to:");
		$("#searchInputMain").focus();
		return false;
	});
	
	jQuery.listen("click", ".searchRefs", function(){
		$("#searchInputMain").val("@");
		$("#searchInputMain").focus();
		return false;
	});
	
	jQuery.listen("click", ".searchTag", function(){
		$("#searchInputMain").val("#");
		$("#searchInputMain").focus();
		return false;
	});
	
	jQuery.listen("click", ".inReplyTo", function(){
			var tweetId = $(this).attr("id");
			var tweetRow = $(this).parent();
			var replyBtn = $(this);
			var replyVar = "status.php?status="+tweetId;
			$.get(replyVar,
				 function(data){
				 	$(replyBtn).hide();
				  	$(tweetRow).append(data);
			});
		});
			
	$(".twPublic").history(function(){
		$("#menu").hide();
		$("#pagination").hide();
		$(this).twPublic();
		return false;
		});
		
	$(".twAbout").history(function(){
		$("#menu").hide();
		$("#pagination").hide();
		$("#tweets").empty();
		$("#tweets").load("about.php");
		return false;
		});
		
	$(".twHowTo").history(function(){
		$("#menu").hide();
		$("#pagination").hide();
		$("#tweets").empty();
		$("#tweets").load("howto.php");
		return false;
		});
		
	jQuery.listen("click", "#locContainer", function(){
		$.getJSON("login.php",
			  function(data){
				$("#locContainer").html(data.location);
			  });
		return false;
	});
	
	jQuery.fn.twPublic = function() {
		$.cookie('page', 'public');
		$("#pagination").hide();
		$("#tweets").empty();
		$("#tweets").html('<img src="images/loading.gif" alt="Loading" class="loading" />');
		$.get("public.php",
			function(data){
			if(data.error){
				alert(data.error);
				}
			$(".loading").remove();
			$(".row").remove();
			$(".colLSubTitle").remove();
			$(".colLSubTitleLink").remove();
			$("<h2 class='colLSubTitle' id='publicTitle'>Public Timeline</h2>").appendTo("#tweets");
			$("#tweets").append(data);
			});
	return false;
	}
	
	$("a.twReplies").history(function(){
		$("#menu").hide();
		$("#pageNumber").html("1");
		$("#tweets").twReplies();
		return false;
		});
		
	$.ajaxHistory.initialize();
	
	jQuery.fn.twReplies = function() {
		$.cookie('page', 'replies');
		$("#tweets").empty();
		$("#pagination").show();
		$("#tweets").append('<img src="images/loading.gif" alt="Loading" class="loading" />');
		var pageNum = $("#pageNumber").html();
		$.get("replies.php",
			{ page: pageNum },
			function(data){
			if(data.error){
				alert(data.error);
				}
			$(".loading").remove();
			$(".row").remove();
			$(".colLSubTitle").remove();
			$(".colLSubTitleLink").remove();
			$("<h2 class='colLSubTitle'>Replies</h2>").appendTo("#tweets");
			$("#tweets").append(data);
			$("#pagination").paginate();
			});
		$("#rateCount").rateCount();
	return false;
	}
	
	$(".twDirect").history(function(){
		$("#menu").hide();
		$("#pageNumber").html("1");
		$(this).twDirect();
		return false;
		});
		
	jQuery.listen( "click", ".twDirectInbox", function(){
		$("#menu").hide();
		$("#pageNumber").html("1");
		$(this).twDirect();
		return false;
		});
	
	jQuery.fn.twDirect = function(){
		$.cookie('page', 'direct');
		$("#tweets").empty();
		$("#pagination").show();
		$("#tweets").append('<img src="images/loading.gif" alt="Loading" class="loading" />');
		var pageNum = $("#pageNumber").html();
		$.get("direct.php",
			{ page: pageNum },
			function(data){
			if(data.error){
				alert(data.error);
				}
			$(".loading").remove();
			$(".row").remove();
			$(".colLSubTitle").remove();
			$(".colLSubTitleLink").remove();
			$("<h2 class='colLSubTitle'>DM Inbox</h2><span class='colLSubTitleLink twDirectSent'>Go to Outbox</span>").appendTo("#tweets");
			$("#tweets").append(data);
			$("#pagination").paginate();
			});
		$("#rateCount").rateCount();
	return false;
	}
	
	jQuery.listen( "click", ".twDirectSent", function(){
		$("#pageNumber").html("1");
		$(this).twDirectSent();
		return false;
		});
	
	jQuery.fn.twDirectSent = function(){
		$.cookie('page', 'directSent');
		$("#tweets").empty();
		$("#pagination").show();
		$("#tweets").append('<img src="images/loading.gif" alt="Loading" class="loading" />');
		var pageNum = $("#pageNumber").html();
		$.get("directSent.php",
			{ page: pageNum },
			function(data){
			if(data.error){
				alert(data.error);
				}
			$(".loading").remove();
			$(".row").remove();
			$(".colLSubTitle").remove();
			$(".colLSubTitleLink").remove();
			$("<h2 class='colLSubTitle' id='directTitle'>DM Outbox</h2><span class='colLSubTitleLink twDirectInbox'>Go To Inbox</span>").appendTo("#tweets");
			$("#tweets").append(data);
			$("#pagination").paginate();
			});
		$("#rateCount").rateCount();
	return false;
	}
	
	$(".twFavs").history(function(){
		$("#menu").hide();
		$("#pageNumber").html("1");
		$(this).twFavs();
		return false;
		});
	
	jQuery.fn.twFavs = function(){
		$.cookie('page', 'favs');
		$("#tweets").empty();
		$("#pagination").show();
		$("#tweets").append('<img src="images/loading.gif" alt="Loading" class="loading" />');
		var pageNum = $("#pageNumber").html();
		$.get("favs.php",
			{ page: pageNum },
			function(data){
			if(data.error){
				alert(data.error);
				}
			$(".loading").remove();
			$(".row").remove();
			$(".colLSubTitle").remove();
			$(".colLSubTitleLink").remove();
			$("<h2 class='colLSubTitle'>Favorites</h2>").appendTo("#tweets");
			$("#tweets").append(data);
			$("#pagination").paginate();
			});
		$("#rateCount").rateCount();
	return false;
	}
	
	$(".twFollowing").history(function(){
		$("#menu").hide();
		$("#pageNumber").html("1");
		$(this).twFollowing();
		return false;
		});
	
	jQuery.fn.twFollowing = function(){
		$.cookie('page', 'following');
		$("#tweets").empty();
		$("#pagination").show();
		$("#tweets").append('<img src="images/loading.gif" alt="Loading" class="loading" />');
		var pageNum = $("#pageNumber").html();
		$.get("following.php",
			{ page: pageNum },
			function(data){
			if(data.error){
				alert(data.error);
				}
			$(".loading").remove();
			$(".row").remove();
			$(".colLSubTitle").remove();
			$(".colLSubTitleLink").remove();
			$("<h2 class='colLSubTitle'>Following</h2>").appendTo("#tweets");
			$("#tweets").append(data);
			$("#pagination").paginate();
			});
		$("#rateCount").rateCount();
	return false;
	}
	
	$(".twFollowers").history(function(){
		$("#menu").hide();
		$("#pageNumber").html("1");
		$(this).twFollowers();
		return false;
		});
	
	jQuery.fn.twFollowers = function(){
		$.cookie('page', 'followers');
		$("#tweets").empty();
		$("#pagination").show();
		$("#tweets").html('<img src="images/loading.gif" alt="Loading" class="loading" />');
		var pageNum = $("#pageNumber").html();
		$.get("followers.php",
			{ page: pageNum },
			function(data){
			if(data.error){
				alert(data.error);
				}
			$(".loading").remove();
			$(".row").remove();
			$(".colLSubTitle").remove();
			$(".colLSubTitleLink").remove();
			$("<h2 class='colLSubTitle'>Followers</h2>").appendTo("#tweets");
			$("#tweets").append(data);
			$("#pagination").paginate();
			});
		$("#rateCount").rateCount();
	return false;
	}
	
	$(".twArchive").history(function(){
		$("#menu").hide();
		$("#pageNumber").html("1");
		$(this).twArchive();
		return false;
		});
	
	jQuery.fn.twArchive = function() {
		$.cookie('page', 'archive');
		$("#tweets").empty();
		$("#pagination").show();
		$("#tweets").append('<img src="images/loading.gif" alt="Loading" class="loading" />');
		var pageNum = $("#pageNumber").html();
		$.get("archive.php",
			{ page: pageNum },
			function(data){
			if(data.error){
				alert(data.error);
				}
			$(".loading").remove();
			$(".row").remove();
			$(".colLSubTitle").remove();
			$(".colLSubTitleLink").remove();
			$("<h2 class='colLSubTitle' id='archiveTitle'>Archive</h2>").appendTo("#tweets");
			$("#tweets").append(data);
			$("#pagination").paginate();
			});
		$("#rateCount").rateCount();
	return false;
	}
	
	jQuery.listen("click", ".twTagLink", function(){
		var searchTerm = $(this).attr("rel");
		if(searchTerm == "#") {
			alert("There is no query term connected to this hashtag.");
			return false;
		}
		$("#searchInputMain").val(searchTerm);
		$("#pageNumber").html("1");
		$("#pageNumber").attr("rel", null);
		$("#pageNumber").attr("title", null);
		$("#pageOlder").attr("rel", "1");
		$("#pageNewer").attr("rel", "2");
		$(this).twSearch();
		$("#searchForm").hide();
		return false;
		});
	
	$(".searchBtn").click(function(){
		var searchTerm = $("#searchInputMain").val();
		if(searchTerm == "") {
			alert("Please enter a search term.");
			return false;
		}
		$("#pageNumber").html("1");
		$("#pageNumber").attr("rel", null);
		$("#pageNumber").attr("title", null);
		$("#pageOlder").attr("rel", "1");
		$("#pageNewer").attr("rel", "2");
		$(this).twSearch();
		$("#searchForm").hide();
		return false;
		});
		
	jQuery.listen("click", ".searchTrends", function(){
			$.cookie('page', 'searchTrends');
			$("#pagination").hide();
			$("#searchForm").hide();
			$(this).twSearchTrends();
			return false;
		});
		
	jQuery.listen("click", ".trendLink", function(){
			var searchTerm = $(this).html();
			if(searchTerm == "") {
				alert("D'oh! Invalid search term!");
				return false;
			}
			$("#searchInputMain").val(searchTerm);
			$("#pageNumber").html("1");
			$("#pageNumber").attr("rel", null);
			$("#pageNumber").attr("title", null);
			$("#pageOlder").attr("rel", "1");
			$("#pageNewer").attr("rel", "2");
			$(this).twSearch();
			return false;
			});
			
	jQuery.fn.twSearchTrends = function() {
		$("#tweets").empty();
		$("#tweets").append('<img src="images/loading.gif" alt="Loading" class="loading" />');
		$.getJSON("http://search.twitter.com/trends.json?callback=?",
			function(data){
				if(data.error){
				alert(data.error);
				}
				$(".loading").remove();
				$(".colLSubTitle").remove();
				$("#colLRefresh").remove();
				$(".colLSubTitleLink").remove();
				$("<h2 class='colLSubTitle'>Current Twitter Trends:</h2>").appendTo("#tweets");
				$.each(data.trends, function(i,item){
					$("<div class='trendLink'>"+item.name+"</div>").appendTo("#tweets");
				});
			});
		return false;
	}
	
	jQuery.fn.twSearch = function() {
		$.cookie('page', 'search');
		$("#tweets").empty();
		$("#pagination").show();
		$("#tweets").append('<img src="images/loading.gif" alt="Loading" class="loading" />');
		var pageNum = $("#pageNumber").html();
		var searchTerm = $("#searchInputMain").val();
		$.get("search.php",
			{ q: searchTerm, page: pageNum },
			function(data){
			$(".loading").remove();
			$(".row").remove();
			$(".colLSubTitle").remove();
			$(".colLSubTitleLink").remove();
			$("<h2 class='colLSubTitle' id='searchTitle'>Search: </h2>").appendTo("#tweets");
			$("#searchTitle").append(searchTerm);
			var queryTerm = data.query;
			var maxID = data.max_id;
			$("#pageOlder").attr("rel", (parseInt(pageNum) + 1));
			$("#pageNewer").attr("rel", (parseInt(pageNum) - 1));
			$("#pageNumber").attr("rel", searchTerm);
			$("#tweets").append(data);
			$("#pagination").paginate();
			});
	return false;
	}

	jQuery.fn.getUser = function() {
		var userRequested = $(this).attr("rel");
		if(userRequested == undefined) {
			var userRequested = $(".colLSubTitle").attr("rel");
		}
		$.cookie('page', 'user');
		$("#tweets").empty();
		$("#pagination").show();
		$("#tweets").append('<img src="images/loading.gif" alt="Loading" class="loading" />');
		var pageNum = $("#pageNumber").html();
		$.ajax({
			type: "GET",
			url: "user.php",
			data: "userRequested=" + userRequested + "&page=" + pageNum,
			cache: false,
			success: function(data){
			$(".loading").remove();
			$(".row").remove();
			$(".colLSubTitle").remove();
			$(".colLSubTitleLink").remove();
			$("<h2 class='colLSubTitle' rel='"+userRequested+"'>User: @"+userRequested+"</h2>").appendTo("#tweets");
			$("#tweets").append(data);
			$("#pagination").paginate();
			}
			});
		$("#rateCount").rateCount();
	return false;
	}
	
	jQuery.fn.getProfile = function() {
		var userRequested = $(this).attr("rel");
		$.cookie('page', 'profile');
		$("#tweets").empty();
		$("#pagination").hide();
		$("#tweets").append('<img src="images/loading.gif" alt="Loading" class="loading" />');
		$.ajax({
			type: "GET",
			url: "show_xml.php",
			data: "userRequested=" + userRequested,
			cache: false,
			success: function(data){
			$(".loading").remove();
			$(".colLSubTitle").remove();
			$(".colLSubTitleLink").remove();
			$("<h2 class='colLSubTitle' rel='"+userRequested+"'>User: @"+userRequested+"</h2>").appendTo("#tweets");
			$("#tweets").append(data);
			}
			});
		$("#rateCount").rateCount();
	return false;
	}
			
	jQuery.fn.plusOne = function() {
		var numString = $(this).html();
		var oldNum = parseInt(numString);
		var newNum = (oldNum + 1);
		$(this).html(newNum);
	}
	
	jQuery.fn.minusOne = function() {
		var numString = $(this).html();
		var oldNum = parseInt(numString);
		var newNum = (oldNum - 1);
		$(this).html(newNum);
	}
	
	jQuery.fn.twPost = function() {
		var messageVal = $("#twMessage").val();
		var token = $("#sessionToken").val();
		$.post("post.php",
		{ message: messageVal, token: token },
			function(data){
				$("#twMessage").fadeOut();
				$("#twMessage").attr("value","");
				$("#countdown").val("140");
				$("#twMessage").fadeIn();
				$("#twPost").hide();
				$("#twMessage").blur();
				location.search = "";
				if($.cookie("page") == 'friends'){
					$("#tweets").friendLoad();
					}
			});
		return false;
	}
	
	jQuery.fn.twDirectPost = function() {
		var messageVal = $("#twDirectMessage").val();
		var directTo = $("#directID").val();
		var token = $("#sessionToken").val();
		if(directTo == "") {
			alert('Please enter the username of the person you want to DM!');
			$('#directID').focus();
			return false;
			
		} else if(messageVal == "") {
			alert("Please enter a message!");
			$("#twDirectMessage").focus();
			return false;
		} else {
			$.getJSON("directPost.php",
			{ directTo: directTo, message: messageVal, token: token },
				function(data){
					if(data.error) {
						alert(data.error);
						return false;
						}
					$("#twDirectPost").hide();
					$("#twDirectMessage").attr("value","");
					$("#directID").attr("value","");
					$("#countdown").val("140");
					$("#twDirectMessage").blur();
					alert("Message sent!");
				}
			);
			return false;
		}
	}
	
	jQuery.fn.favPost = function() {
		var favId = $(this).attr('id');
		var token = $("#sessionToken").val();
		$.post("fav_post.php",
		{ status_id: favId, token: token },
		 function(data){
			if(data.error){
				alert(data.error);
			  }
			  return false;
		}, "json");
		var favStar = "images/fav_on.png";
		$(this).attr("src",favStar);
		$(this).attr("class","favUnstar");
		return false;
	}
	
	jQuery.fn.favDestroy = function() {
		var favId = $(this).attr('id');
		var token = $("#sessionToken").val();
		$.post("fav_destroy.php",
		{ status_id: favId, token: token },
		 function(data){
			if(data.error){
				alert(data.error);
			  }
			  return false;
		}, "json");
		var favStar = "images/fav_over.png";
		$(this).attr("src",favStar);
		$(this).attr("class","favBtn");
		return false;
	}
	
	jQuery.fn.destroyTweet = function() {
		var deleteTweet = confirm("Are you sure you want to delete this tweet? There is no undo.");
		if (deleteTweet == true){
			var destroyID = $(this).attr("title");
			var DestroyRow = $(this).parent();
			var token = $("#sessionToken").val();
			$.post("destroy.php",
			{ status_id: destroyID, token: token },
				function(data){
					if(data.error){
					alert(data.error);
					}
					$(DestroyRow).hide().remove();
					return false;
				}, "json");
				return false;
		}
		return false;
	}
	
	jQuery.fn.destroyDirect = function() {
		var destroyID = $(this).attr("title");
		var DestroyRow = $(this).parent();
		var token = $("#sessionToken").val();
		$.post("destroyDirect.php",
		{ status_id: destroyID, token: token },
			function(data){
				if(data.error){
				alert(data.error);
				}
				$(DestroyRow).hide().remove();
				return false;
			}, "json");
			return false;
	}
	
	jQuery.fn.notsOn = function() {
		var notsId = $(this).parent().attr('rel');
		var token = $("#sessionToken").val();
		$.post("notifications_on.php",
		 { user_id: notsId, token: token },
			function(data){
			if(data.error){
				alert(data.error);
			  }
			return false;
		}, "json");
		$(this).attr("class", "twNotsOff");
		$("#notsStatus").html("ON");
		$(this).html("Turn notifications off?");
		alert("Notifications on!");
	}
	
	jQuery.fn.notsOff = function() {
		var notsId = $(this).parent().attr('rel');
		var token = $("#sessionToken").val();
		$.post("notifications_off.php",
		 { user_id: notsId, token: token },
			function(data){
			if(data.error){
				alert(data.error);
			  }
			 return false;
		}, "json");
		$(this).attr("class", "twNotsOn");
		$("#notsStatus").html("OFF");
		$(this).html("Turn notifications on?");
		alert("Notifications off!");
	}
	
	jQuery.fn.followOn = function() {
		var followOn = confirm("Are you sure you want to follow this person?");
		if (followOn == true){
			var followUser = $(this).attr("rel");
			var followUserId = $(this).parent().attr('rel');
			var token = $("#sessionToken").val();
			$.post("follow_on.php",
			 { user_id: followUserId, token: token },
				function(data){
				if(data.error){
					alert(data.error);
					return false;
				  }
				alert("You are now following @" + followUser);
				return false;
			}, "json");
			$(this).attr("class", "followOff");
			$("#followStatus").empty();
			$(this).html("Stop following?");
		}
		return false;
	}
	
	jQuery.fn.followOff = function() {
		var followOff = confirm("Are you sure you want to unfollow this person?");
		if (followOff == true){
			var followUser = $(this).attr("rel");
			var followUserId = $(this).parent().attr('rel');
			var token = $("#sessionToken").val();
			$.post("follow_off.php",
			 { user_id: followUserId, token: token },
				function(data){
				if(data.error){
					alert(data.error);
					return false;
				  }
				alert("You are no longer following @" + followUser);
				return false;
			}, "json");
			$(this).attr("class", "followOn");
			$("#followStatus").html("not");
			$(this).html("Follow?");
		}
		return false;
	}
	
	jQuery.fn.blockOn = function() {
		var blockOn = confirm("Are you sure you want to block this person?");
		if (blockOn == true){
			var blockUser = $(this).next("span").attr("rel");
			var blockUserId = $(this).parent().attr('rel');
			var token = $("#sessionToken").val();
			$.post("block_on.php",
			 { user_id: blockUserId, token: token },
				function(data){
				if(data.error){
					alert(data.error);
					return false;
				  }
				alert("You have blocked @" + blockUser);
				return false;
			}, "json");
			$(this).attr("class", "blockOff");
			$(this).html("Unblock?");
		}
		return false;
	}
	
	jQuery.fn.blockOff = function() {
		var blockOff = confirm("Are you sure you want to unblock this person?");
		if (blockOff == true){
			var blockUser = $(this).next("span").attr("rel");
			var blockUserId = $(this).parent().attr('rel');
			var token = $("#sessionToken").val();
			$.post("block_off.php",
			 { user_id: blockUserId, token: token },
				function(data){
				if(data.error){
					alert(data.error);
					return false;
				  }
				alert("You have unblocked @" + blockUser);
				return false;
			}, "json");
			$(this).attr("class", "blockOn");
			$(this).html("Block?");
		}
		return false;
	}
	
	jQuery.fn.setDevice = function() {
		var device = $(this).attr("rel");
		var token = $("#sessionToken").val();
		$.post("device.php",
		 { device: device, token: token },
			function(data){
			if(data.error){
				alert(data.error);
				return false;
			  }
			$.cookie('device', device, { expires: 14 });
			alert("Notification device is now: " + device);
		}, "json");
	}
	
	jQuery.fn.setLocation = function() {
		var location = $("#locInputMain").val();
		var token = $("#sessionToken").val();
		$.post("location.php",
		 { location: location, token: token },
			function(data){
			if(data.error){
				alert(data.error);
				return false;
			  }
			alert("Location Updated: " + location);
		}, "json");
	}
	
	jQuery.fn.paginate = function() {
		var pageNum = $("#pageNumber").html();
		var numRows = $('.row').size();
		var thisPage = $.cookie('page');
		if(thisPage == "followers") {
			var pageAmount = 100;
		} else if(thisPage == "followers") {
			var pageAmount = 100;
		} else {
			var pageAmount = 20;
			}
		if((pageNum == "1") && (numRows < pageAmount)){
			$("#pagination").css({ visibility: "hidden" });
			}
		if((pageNum == "1") && (numRows == pageAmount)){
			$("#pagination").css({ visibility: "visible" });
			$("#pageNewer").css({ visibility: "hidden" });
			$("#pageOlder").css({ visibility: "visible" });
			}
		if((pageNum > "1") && (numRows == pageAmount)){
				$("#pagination").css({ visibility: "visible" });
				$("#pageNewer").css({ visibility: "visible" });
				$("#pageOlder").css({ visibility: "visible" });
			}
		if((pageNum > "1") && (numRows < pageAmount)){
				$("#pagination").css({ visibility: "visible" });
				$("#pageNewer").css({ visibility: "visible" });
				$("#pageOlder").css({ visibility: "hidden" });
			}
		}
		
	$("#pageNewer").click(function(){
		$("#pageNumber").minusOne();
		$("#pagination").paginate();
		var thisPage = $.cookie('page');
		if(thisPage == "friends") {
			$("#tweets").friendLoad();
		} else if(thisPage == "replies") {
			$("#tweets").twReplies();
		} else if(thisPage == "direct") {
			$("#tweets").twDirect();
		} else if(thisPage == "directSent") {
			$("#tweets").twDirectSent();
		} else if(thisPage == "favs") {
			$("#tweets").twFavs();
		} else if(thisPage == "following") {
			$("#tweets").twFollowing();
		} else if(thisPage == "followers") {
			$("#tweets").twFollowers();
		} else if(thisPage == "archive") {
			$("#tweets").twArchive();
		} else if(thisPage == "search") {
			$("#tweets").twSearch();
		} else if(thisPage == "user") {
			$("#tweets").getUser();
		}
	});
	
	$("#pageOlder").click(function(){
		$("#pageNumber").plusOne();
		$("#pagination").paginate();
		var thisPage = $.cookie('page');
		if(thisPage == "friends") {
			$("#tweets").friendLoad();
		} else if(thisPage == "replies") {
			$("#tweets").twReplies();
		} else if(thisPage == "direct") {
			$("#tweets").twDirect();
		} else if(thisPage == "directSent") {
			$("#tweets").twDirectSent();
		} else if(thisPage == "favs") {
			$("#tweets").twFavs();
		} else if(thisPage == "following") {
			$("#tweets").twFollowing();
		} else if(thisPage == "followers") {
			$("#tweets").twFollowers();
		} else if(thisPage == "archive") {
			$("#tweets").twArchive();
		} else if(thisPage == "search") {
			$("#tweets").twSearch();
		} else if(thisPage == "user") {
			$("#tweets").getUser();
		}
	});
	
	$("#btnRefresh").click(function(){
		$("#pagination").paginate();
		var thisPage = $.cookie('page');
		if(thisPage == "friends") {
			$("#tweets").friendLoad();
		} else if(thisPage == "replies") {
			$("#tweets").twReplies();
		} else if(thisPage == "user") {
			$("#tweets").getUser();
		} else if(thisPage == "direct") {
			$("#tweets").twDirect();
		} else if(thisPage == "directSent") {
			$("#tweets").twDirectSent();
		} else if(thisPage == "favs") {
			$("#tweets").twFavs();
		} else if(thisPage == "following") {
			$("#tweets").twFollowing();
		} else if(thisPage == "followers") {
			$("#tweets").twFollowers();
		} else if(thisPage == "archive") {
			$("#tweets").twArchive();
		} else if(thisPage == "search") {
			$("#tweets").twSearch();
		} else if(thisPage == "searchTrends") {
			$("#tweets").twSearchTrends();
		} else if(thisPage == "public") {
			$("#tweets").twPublic();
		}
	});
		
	jQuery.fn.friendLoad = function() {
		$.cookie('page', 'friends');
		$("#tweets").empty();
		$("#pagination").show();
		$("#tweets").html('<img src="images/loading.gif" alt="Loading" class="loading" />');
		var pageNum = $("#pageNumber").html();
		$.ajax({
			type: "GET",
			url: "friends.php",
			data: "page=" + pageNum,
			cache: false,
			success: function(data){
			$(".loading").remove();
			$(".row").remove();
			$(".colLSubTitle").remove();
			$(".colLSubTitleLink").remove();
			var usernameVal = $("#twittername").val();
			$("#tweets").append(data);
			$("#pagination").paginate();
			}
			});
		$("#rateCount").rateCount();
	return false;
	}
		
	var twLoggedIn = $.cookie("itweet2User");
	
	if(twLoggedIn){
		$("#twLoginForm").after('<img src="images/loading.gif" alt="Loading" class="loading" />');
		var device = $.cookie('device');
		$(".twSttgNots").removeClass("optSelect");
		if(device == "sms") {
				$("#twSttgNotsSMS").addClass("optSelect");
			} else if(device == "none") {
				$("#twSttgNotsNone").addClass("optSelect");
			}
		var tagPref = $.cookie('tagPref');
		if(tagPref == "default") {
			$("#twSttgLinkTags").addClass("optSelect");
			} else if(tagPref == "pretty") {
				$("#twSttgPrettyTags").addClass("optSelect");
			} else {
				$("#twSttgLinkTags").addClass("optSelect");
			}
		$("#tweets").friendLoad();
		return false;
	} else {
		$("#panel").hide();
		$("#menu").hide();
		$("#logoContainer").show();
		$("#twLogin").show();
		$("#footer").show();
	}
	
});