var since=1; // last message id retrieved
var page=1; // set the page to 1 as the starting point
var content_update=null; // this will be the pointer to the page content refresh timer
var countdown_update=null; // this is the pointer to the countdown refresh timer
var time_left=60; //refresh timer countdown value
var timeline = "tweets"; //which timeline are we showing right now?
var tracked = "";// if we're viewing a tracked users timeline, which one?
var logged_in="logged_out";
var cookie_life=120;
var is_reply=false; // is the current tweet to be sent a reply?
var in_reply_to_id=0; // if the current tweet to be sent is a reply, what is the ID of the original tweet?
var refresh_interval=60000; // this is in milliseconds, for the actual timer
var refresh_interval_seconds=60;  // this is for the countdown

$(document).ready(function(){
	
	$(".send_tweet").dialog({
								autoOpen: false,
								position: 'center',
								modal:true,
								resizable:false,
								draggable:false,
								height:250,
								width:505,
								title:"Send a Tweet."
								});
	$(".suggest").dialog({
								autoOpen: false,
								position: 'center',
								modal:true,
								resizable:false,
								draggable:false,
								width:355,
								title:"Suggest someone to follow."
								});
	
	login(get_cookie('tusername'),get_cookie('tpassword'));
	view(logged_in);
		
	set_cloud();
	
	set_timeline(timeline);
	
	$("#previous_control").click(function(event){
	    event.preventDefault();
		since=1;
		page--;
		if(page>1) {
			$("#previous_control").show(); // turn off the page refresh and countdown
			clearInterval(content_update);
			clearInterval(countdown_update);
		}else{
			$("#previous_control").hide();  // turn the page refresh and countdown back on
			content_update=setInterval("retrieve(timeline,page)", refresh_interval);
			time_left=refresh_interval_seconds; 
			countdown_update = setInterval("countdown()", 1000);
			retrieve(timeline,page);
		}
		if(page<1) {
			page=1;
			$("#tweets_list").html("");// turn the page refresh and countdown on
			content_update=setInterval("retrieve(timeline,page)", refresh_interval);
			time_left=refresh_interval_seconds; 
			countdown_update = setInterval("countdown()", 1000);
			retrieve(timeline,page);
		}
	});

	$("#next_control").click(function(event){
		event.preventDefault();	
		since=1;
		page++;
		if(page>1) {
			$("#previous_control").show();// turn off the page refresh and countdown
			clearInterval(content_update);
			clearInterval(countdown_update);
		}else{
			$("#previous_control").hide();// turn the page refresh and countdown back on
			content_update=setInterval("retrieve(timeline,page)", refresh_interval);
			time_left=refresh_interval_seconds; 
			countdown_update = setInterval("countdown()", 1000);
		}
		if(page<1) page=1;
		$("#tweets_list").html("");
		retrieve(timeline,page);
	});
		
	$("#previous_control").hide();
	
});

function suggest(suggested,suggestor){
	$.ajax({
		type: "get",
		url: "api.php",
		data: "request=suggest&suggested="+suggested+"&suggestor="+suggestor,
		async: false,
		cache: false,
		dataType: 'json',
		success: function(data){
			if(data.success){
				$(".suggest_open").hide();
				$(".suggest_close").show();
			}
		},
		error: function(data){
			//alert("Server communication error. Sorry!  Please try again in a minute or two.");
		}
	});	
}

function login(username,password){
	$.ajax({
		type: "get",
		url: "api.php",
		data: "request=login&username="+username+"&password="+encodeURIComponent(password),
		async: false,
		cache: false,
		dataType: 'json',
		success: function(data){
			if(data.screen_name){
				logged_in="logged_in";
				set_cookie('tusername',username,cookie_life);
				set_cookie('tpassword',password,cookie_life);
			}else{
				logged_in="logged_out";
				set_cookie('tusername',"",-999);
				set_cookie('tpassword',"",-999);
			}
			if(data.error==401){
				logged_in="Bad username/password combination";
			}
		},
		error: function(data){
			//alert("Server communication error. Sorry!  Please try again in a minute or two.");
		}
	});
	view(logged_in);
}

function logout(){
	set_cookie("tusername","",-999);
	set_cookie("tpassword","",-999);
	logged_in="logged_out";
	view(logged_in);
}

function remember_me(){
	if($("#remember_me").attr("checked")){
		cookie_life=120;
	}else{
		cookie_life=0;
	}
}

function view(status){
	if(status=="logged_in"){
		$(".logged_in").show();
		$("#screen_name").text(get_cookie('tusername'));
		$("#login_controls").hide();
	}else{
		$(".logged_in").hide();
		$("#login_controls").show();
	}
	
	if(get_cookie('admin-username')&&get_cookie('admin-password')&&timeline=="favorites"){
		flag = get_cookie('admin-username');
		if(flag!="logged_out"){
			$(".admin").show();
		}
	}
}

function retrieve(timeline,page){
	$.ajax({
		type: "get",
		url: "api.php",
		data: "request=retrieve&timeline="+timeline+"&page="+page+"&since="+since+"&tracked="+tracked,
		async: false,
		cache: false,
		dataType: 'json',
		success: function(data){
			//alert("Success "+data);
			if(timeline=="following"){
				insert_following(data);
			}else{
				insert_tweets(data);
			}
		},
		error: function(data){
			//alert("Server communication error. Sorry!  Please try again in a minute or two.");
		}
	});
	time_left=refresh_interval_seconds;
	view(logged_in);
} 

function set_timeline(new_timeline){
	timeline = new_timeline;
	page = 1;
	since = 1;
	$("#tweets_list").html("");
	$("#timeline_title").text("Latest Tweets");
	if(timeline=="favorites"){
		$("#timeline_title").text("Site Favorites");
	}else if(timeline=="following"){
		$("#timeline_title").text("Who We're Following");
	}
	retrieve(new_timeline,page);
	
	clearInterval(content_update);
	clearInterval(countdown_update);
	if (new_timeline == "following") {
	// dont set the update interval, no refresh needed for this list
	}else{
		content_update = setInterval("retrieve(timeline,page)", refresh_interval);
		countdown_update = setInterval("countdown()", 1000);
	}
	return true;
}

function countdown(){
	time_left--;
	if(time_left<=0) time_left=refresh_interval_seconds;
	$("#reload_count").text(time_left);
	//$("#content_header").text(time_left);
}

function insert_tweets(data){
	data=data.reverse();
	for (var tweet in data){
		var date = new Date(data[tweet].created_at * 1000);
		dayArr = new Array('Sun', 'Mon', 'Tue', 'Wed', 'Thu','Fri','Sat');
		day = date.getDay();
		day = dayArr[day];
		monthArr = new Array('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'July', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec');
		month = date.getMonth();
		month = monthArr[month];
		mDay=date.getDate();
		year = date.getFullYear();
		timestamp = day+ " " +month+" "+mDay+", "+year;
		message_text = create_links(data[tweet].text);
		fav_image="images/favorite_false.gif";
		if(data[tweet].site_favorited==1) fav_image="images/favorite_true.gif";
		//screen_name=data[tweet].user_screen_name;
		msg="<li class='"+data[tweet].user_screen_name+"_li'>"+				
				"<span id='"+data[tweet].id+"_tip' style='display:none;'>"+	
					"<table class='tip_table'>"+
						"<tr>"+
							"<td><h3>Tweeter:</h3></td>"+
							"<td><h3>"+
								"<a href='http://twitter.com/"+data[tweet].user_screen_name+"' target='_blank' title='http://twitter.com/"+data[tweet].user_screen_name+"'>"+data[tweet].user_screen_name+"</a>"+
							"</h3></td>"+
						"</tr>"+
						"<tr><td><b>Name:</b></td><td>"+data[tweet].user_name+"</td></tr>"+
						"<tr><td><b>Following:</b></td><td>"+data[tweet].user_friends_count+"</td></tr>"+
						"<tr><td><b>Followers:</b>&nbsp&nbsp</td><td>"+data[tweet].user_followers_count+"</td></tr>"+
						"<tr><td><b>Statuses: </b></td><td>"+data[tweet].user_statuses_count+"</td></tr>"+
						"<tr><td><b>Web:</b></td><td><a href='"+data[tweet].user_url+"' target='_blank'>"+data[tweet].user_url+"</a></td></tr>"+
					"</table>"+
				"</span>"+	
				"<table class='tweet_table'><tr>"+
					"<td id='"+data[tweet].id+"_avatar' class='avatar_cell'>"+
						"<img src='"+data[tweet].user_profile_image_url+"' class='avatar sf-avatar'>"+
					"</td>"+
					"<td class='bl_cell'></td>"+
					"<td class='tweet_cell'>"+
						"<p class='tweet_text'>\""+message_text+"\"</p>"+
						"posted by <span class='tweet_sender'>"+data[tweet].user_screen_name+"</span>"+
						" | <span class='tweet_date'> "+timestamp+ "</span>" +
						"<span class='message_controls'>"+
							"<span class='logged_in'> | "+
								"<a href='#' onclick='favorite("+data[tweet].id+");return false;' title='Favorite this tweet'><img id='"+data[tweet].id+"_fav_image' src='"+fav_image+"'></a>"+
								"<a href='#' onclick='reply(\""+data[tweet].user_screen_name+"\","+data[tweet].id+");return false;' title='Reply to this tweet'><img src='images/reply.gif'></a>"+
								"<a href='#' onclick='retweet(\""+data[tweet].user_screen_name+"\",\""+escape(data[tweet].text)+"\");return false;' title='Retweet this tweet'><img src='images/retweet.gif'></a>"+
								"<a href='#' onclick='unfavorite(\""+data[tweet].id+"\");' title='Unfavorite this tweet' class='admin' style='display:none;'><img src='images/unfavorite.png' class='admin' style='display:none;'></a>"+
							"</span>"+
						"</span>"+
					"</td>"+
				"</tr></table>"+
			"</li>";
		$("#tweets_list").hide().prepend(msg).fadeIn("slow");
		// this is the last message retrieved, set the 'since' var for the next timeline request
		since = data[tweet].id;
		list_len=$("#tweets_list > li");
		if (list_len.length>15){
			// remove the oldest tweet if the list is over 15 long
			$("#tweets_list > li:last").remove();
		}
	
		$("#"+data[tweet].id+"_avatar").qtip({
			content: $("#"+data[tweet].id+"_tip").html(),
	      	style:{
				border: {
					width: 2,
		         	radius: 8,
		         	color: '#e7e8e9'
			 	},
				width: 300
			},
			position: {
		      corner: {
		         target: 'center',
		         tooltip: 'leftMiddle'
		      }
			},
			show: 'mouseover',
			hide: { when: 'mouseout', fixed: true }
		});
	}
}
function insert_following(data){
	
	for (var tracked in data){
		msg="<li id='"+data[tracked].screen_name+"_li'><table class='tweet_table'><tr>"+
					"<td class='avatar_cell'>"+
						"<a href='http://twitter.com/"+data[tracked].screen_name+"' target='_blank' title='http://twitter.com/"+data[tracked].screen_name+"'>"+
							"<img src='"+data[tracked].profile_image_url+"' class='avatar'>"+
						"</a>"+
					"</td>"+
					"<td class='bl_cell'></td>"+
					"<td class='tweet_cell'>"+
						"<ul>"+
							"<li><b>Name:&nbsp</b>"+data[tracked].screen_name+"&nbsp("+data[tracked].name+")</li>"+
							"<li><b>Following:&nbsp</b>"+data[tracked].friends_count+"</li>"+
							"<li><b>Followers:&nbsp</b>"+data[tracked].followers_count+"</li>"+
							"<li><b>Statuses:&nbsp</b>"+data[tracked].statuses_count+"</li>"+
							"<li><b>Web:&nbsp</b><a href='"+data[tracked].url+"' target='_blank'>"+data[tracked].url+"</a></li>"+
						"</ul>"+
					"</td>"+
				"</tr></table></li>";
		$("#tweets_list").hide().prepend(msg).fadeIn("slow");
		// this is the last message retrieved, set the 'since' var for the next timeline request
		since = 1; //we're not following a live list of messages here, just tracked user accounts
		list_len=$("#tweets_list > li");
		if (list_len.length>15){
			// remove the oldest tweet if the list is over 15 long
			$("#tweets_list > li:last").remove();
		}
	}
}

function set_cloud(){
	$.ajax({
		type: "get",
		url: "api.php",
		data: "request=tracking",
		async: false,
		dataType: 'json',
		cache: false,
		success: function(data){
			//alert("Success "+data);
			populate_cloud(data);
		},
		error: function(data){
			//alert("Server communication error. Sorry!  Please try again in a minute or two.");
		}
	});
}

function populate_cloud(data){
	$(".cloud").html("");
	for(i in data){
		$(".cloud").append("<a href='#' class='cloud_item' onclick='tracked=\""+data[i].screen_name+"\";set_timeline(\"tracked\");'> "+data[i].screen_name+" </a>");
	}
}

function send_tweet(text,tweet_is_reply,tweet_id){
	//alert("text: "+text+" reply: "+tweet_is_reply+" id: "+tweet_id);	
	$.ajax({
		type: "get",
		url: "api.php",
		data: "request=send_tweet&text="+encodeURIComponent(text)+"&is_reply="+tweet_is_reply+"&tweet_id="+tweet_id+"&username="+get_cookie('tusername')+"&password="+encodeURIComponent(get_cookie('tpassword')),
		async: false,
		cache: false,
		dataType: 'json',
		success: function(data){
			// success? close send dialog, otherwise notify user and keep dialog open
			if(data['user']['screen_name']){
				$(".send_tweet").dialog('close');
			}
		},
		error: function(data){
			//alert("Server communication error. Sorry!  Please try again in a minute or two.");
		}
	});
	is_reply=false;
	in_reply_to_id=0;
}

function reply(reply_to_screen_name, reply_to_message_id){
	is_reply=true;
	in_reply_to_id=reply_to_message_id;
	$("#tweet_input").val();
	$("#tweet_input").val("@"+reply_to_screen_name+" ");
	$(".send_tweet").dialog('open');
	//alert(reply_to_message_id+":"+reply_to_screen_name);
}

function retweet(screen_name,message_text){
	is_reply=false;
	$("#tweet_input").val();
	$("#tweet_input").val("RT @"+screen_name+": "+unescape(message_text));
	$(".send_tweet").dialog('open');
	//alert(screen_name);
	//alert(unescape(message_text));
}
function favorite(tweet_id){
// mark the tweet as site_favorited=1
// if the user is logged in, also mark it favorited for their twitter account
	if(get_cookie('tusername')){
		username=get_cookie('tusername');
	}else{
		username=0;
	}
	if(get_cookie('tpassword')){
		password=get_cookie('tpassword');
	}else{
		password=0;
	}
	$.ajax({
		type: "get",
		url: "api.php",
		data: "request=favorite&tweet_id="+tweet_id+"&username="+username+"&password="+encodeURIComponent(password),
		async: false,
		dataType: 'json',
		success: function(data){
			// success? set tweet favorite button to "on"
			if(data['success']){
				$("#"+tweet_id+"_fav_image").attr("src","images/favorite_true.gif");
			}else{

			}
		},
		error: function(data){
			//alert("Server communication error. Sorry!  Please try again in a minute or two.");
		}
	});
}

function unfavorite(tweet_id){
// mark the tweet as site_favorited=0
// this should only be available to logged in admins
	if(get_cookie('admin-username')){
		username=get_cookie('admin-username');
	}else{
		username=0;
	}
	if(get_cookie('admin-password')){
		password=get_cookie('admin-password');
	}else{
		password=0;
	}
	$.ajax({
		type: "get",
		url: "api.php",
		data: "request=unfavorite&tweet_id="+tweet_id+"&admin_username="+username+"&admin_password="+encodeURIComponent(password),
		async: false,
		dataType: 'json',
		success: function(data){
			// success? set tweet favorite button to "on"
			if(data['success']){
				$("#"+tweet_id+"_fav_image").attr("src","images/favorite_false.gif");
			}else{

			}
		},
		error: function(data){
			//alert("Server communication error. Sorry!  Please try again in a minute or two.");
		}
	});
}
function update_char_counter(){
	//** COUNTDOWN monitors textarea and updates "characters left" count
	var value = $("#tweet_input").val();
	
	$("#char_counter").html(140 - value.length);
	if (value.length > 130) {
		$("#char_counter").css("color", '#a7a9ac');
	} else if (value.length > 120) {
		$("#char_counter").css("color", '#5c0002');
	} else {
		$("#char_counter").css("color", '#aaaaaa');
	}

}

//
// UTILS
//
	
// CREATELINKS
function create_links(messageText){
		// create links of URLs
	var pattern = /(((ht|f)tp(s?))\:\/\/{1}[-a-zA-Z0-9@:%_\+.~#?&\/\/=]+)/ig;
	urlArray = messageText.match(pattern);
	var linkVal = "";
	if(urlArray){
		$.each(urlArray, function(key, val){
			//shorten links for disply
			//if(val.length>20){
			//	linkVal =val.slice(0,16);
			//	linkVal+="...";
			//}else{
				linkVal=val;
			//}
			messageText=messageText.replace(val, "<a href=\""+val+"\" target=\"_blank\" title=\""+val+"\">"+linkVal+"</a>");
		});
	}
	//create links of @ references
	pattern = /@{1}[-a-zA-Z0-9%_\+~&\/\/=]+/ig;				
	atArray = messageText.match(pattern);
	if(atArray){
		$.each(atArray, function(key, val){
			shortVal = val.replace(/@/,"");
			messageText=messageText.replace(val, "<a href=\"http://twitter.com/"+shortVal+"\" target=\"_blank\"  title=\"http://twitter.com/"+shortVal+"\">"+val+"</a>");
		});
	}
	//create links of # references
	pattern = /#{1}[-a-zA-Z0-9%_\+~&\/\/=]+/ig;				
	hashArray = messageText.match(pattern);
	if(hashArray){
		$.each(hashArray, function(key, val){
			//shortVal = val.replace(/#/,"");
			messageText=messageText.replace(val, "<a href=\"http://search.twitter.com/search?q="+encodeURIComponent(val)+"\" target=\"_blank\" title=\"Search Twitter for "+val+"\">"+val+"</a>");
		});
	}
	return(messageText);
}


//** SET_COOKIE
	function set_cookie(c_name,value,expiredays){
		var exdate=new Date();
		exdate.setDate(exdate.getDate()+expiredays);
		document.cookie=c_name+ "=" +escape(value)+
		((expiredays==null) ? "" : ";expires="+exdate.toGMTString());
	}

// GET_COOKIE
	function get_cookie(c_name){
		if (document.cookie.length>0){
			c_start=document.cookie.indexOf(c_name + "=");
			if (c_start!=-1)
			{ 
				c_start=c_start + c_name.length+1; 
				c_end=document.cookie.indexOf(";",c_start);
				if (c_end==-1) c_end=document.cookie.length;
				return unescape(document.cookie.substring(c_start,c_end));
			} 
		}
		return "";
	}

function print_r(theObj){
	if(theObj.constructor == Array || theObj.constructor == Object){
		document.write("<ul>");
		for(var p in theObj){
			if(theObj[p].constructor == Array || theObj[p].constructor == Object){
				document.write("<li>["+p+"] => "+typeof(theObj)+"</li>");
				document.write("<ul>");
				print_r(theObj[p]);
				document.write("</ul>");
			} else {
				document.write("<li>["+p+"] => "+theObj[p]+"</li>");
			}
		}
		document.write("</ul>");
	}
}
