//------------------------------ document.ready
$(function() {
	/* Overcome IE's absence of String.trim() function */
	if (!('trim' in String.prototype)) {   
		String.prototype.trim = function() { return this.replace(/^\s+|\s+$/g,""); };    
	} 	
	
	$("#follower-tabs").tabs();
	$('form').submit(function(e){findFollowees(e);});
	window.follow = {
			Me : {},
			MyFriends:{}, 
			FavSrc:{}, 
			iCount: 0,
			iDisp: 0
	};
	window.iMaxFriends = 20;
	
	$("#alert_dialog").dialog({
		autoOpen: false,
		bgiframe: true,
		modal: true,
		buttons: {
			Ok: function() {
				$(this).dialog('close');
			}
		}
	});
	
	$("#favorites_dialog").dialog({
		autoOpen: false,
		width:600
	});
	
	/*
	for (var i=0; i<3; ++i){
		$("#tweeters").append('<table><tr><td>'+
		'<div class="user" id="user_profile_image_url"><img src="http://a1.twimg.com/profile_images/409333558/hozi-jamila-wdng-small_normal.jpg" alt="user_profile_picture"></img></div>'+
        '</td><td width="100%">'+
		'<div class="user" id="user_url"><span>Web</span><a href="http://huzaifazoom.blogspot.com">http://huzaifazoom.blogspot.com</a></div>'+
		'<div class="user" id="user_screen_name"><a href="http://www.twitter.com/huzaifazoom">huzaifazoom</a></div>'+
		'<div class="user" id="user_location">Karachi</div>'+
		'<div class="user" id="user_name">Huzaifa Zoomkawala</div>'+
		
		'<div class="user" id="user_description"><span>Bio</span>dabble dabble</div>'+
		'<div class="user" id="user_status">The gene, </div>'+
		'<div class="user" id="user_friends_count"><span>Following</span>11</div>'+
		'<div class="user" id="user_followers_count"><span>Followers</span>27</div>'+
		'<div class="user" id="user_statuses_count"><span>Tweets</span>233</div>'+
		'<div class="user" id="user_favourites_count"><span>Favorites</span>0</div>'+
		'<div class="user" id="get_more"><a href="" id="'+i+'">more</a></div>'+
	    '</td></tr></table>');
		
		$("#tweeters").append('<div class="user" id="user_separator"></div>');
		
		$("#tweeters #get_more #"+i).click(function(e){
			getMyFavs($(this).attr('id'), true);
			e.preventDefault();
		});
	}
	*/
});

function test(sParam){
   //alert(sParam);
   $.get('default.css', 
       function(data){
	       alert(data);
	   });
}

//------------------------------ waitCursor
function waitCursor(){
	$('#wrapper').css('cursor','wait');	
}

//------------------------------ autoCursor
function autoCursor(){
	$('#wrapper').css('cursor','auto');
}

//------------------------------ checkRateError
function checkRateError(sErrMsg){
	$.jsonp({
		url: "http://twitter.com/account/rate_limit_status.json?format=json&callback=?",
	    success: function(data){
		    if (data.remaining_hits == 0)
		    	showAlertDlg("Requests to Twitter have exceeded allowable rate of requests per hour ("+
		    			data.hourly_limit+").\nReset time is at: "+data.reset_time, "Oops", 
		    			"I have set it to work with the current default rate given by Twitter. Please let me know "+
		    			"if you feel this is not sufficient.");
			else
				showAlertDlg(sErrMsg, "Dot i's, cross t's, and hope to die?");
		    }
	});
}

//------------------------------ showAlertDlg
function showAlertDlg(sErrMsg, sTitle, sNote){
	showRemainingHits();
	
	if (sTitle !== undefined)
		$("#alert_dialog").dialog('option', 'title', sTitle);
	else
		$("#alert_dialog").dialog('option', 'title', "We seem to have a situation here");
	
	$("#alert_dialog #msg").html(sErrMsg);
	
	if (sNote !== undefined)
		$("#alert_dialog #note").html('<p></p>'+sNote);
	
	$("#alert_dialog").dialog('open');
	
}

//------------------------------ showFavDlg
function showFavDlg(sTitle, sFav){	
	$("#favorites_dialog").dialog('option', 'title', sTitle);
	$("#favorites_dialog #fav").html(sFav);
	$("#favorites_dialog").dialog('open');	
}

//------------------------------ findFollowees
function findFollowees(e){
	var sUser = $('#search-text').val().trim();
	if (sUser.length == 0) return;

	getMeMyFriendsAndFavs(sUser);		
	e.preventDefault();	
}

//------------------------------ getMeMyFriendsAndFavs
function getMeMyFriendsAndFavs(sUser){
	waitCursor();
	$("#status").html('Getting user info..');

	window.follow.Me = {};

	$.jsonp({
		url: "http://twitter.com/users/show/"+sUser+".json?callback=?",
		
		success: 
			function(data){
		        if (data.error !== undefined){
		        	autoCursor();
		        	showAlertDlg("Could not retrieve user information for "+sUser);		        	
		        }else{
		        	window.follow.Me = data;
					$("#status").html('Getting user info: done');
					autoCursor();
		            getMyFriendsAndFavs(sUser);
		        }		        
			},
		
		error: 
			function (XMLHttpRequest, sError) {
				autoCursor();
				checkRateError("Could not find: "+ sUser);				
			}
	});
}


//------------------------------ getMyFriendsAndFavs
function getMyFriendsAndFavs(sUser){
	waitCursor();
	$("#status").html('Getting Friends..');

	window.follow.MyFriends = {};
	$.jsonp({
		url: "http://twitter.com/friends/ids/"+sUser+".json?callback=?", 
		success: 
			function(data){
		        if (data.length == 0){
		        	autoCursor();
		        	showAlertDlg("Could not retrieve friend information for "+sUser);		        	
		        }else{
		        	$("#status").html('Getting Friends: done');
		        	autoCursor();		        	
		        	for (var i=0, l=data.length; i<l; ++i)
		        		window.follow.MyFriends[data[i]] = 1;
		        	
		        	getMyFavs(sUser);
		        }
			},
				
		error: 
			function (XMLHttpRequest, sError) {
				autoCursor();
				checkRateError("Unexpected error in getting friends: "+ sError);
			}			
	});	
}

//------------------------------ getMyFavs
function getMyFavs(sUser, bMore){
	waitCursor();
	$("#status").html('Getting Favorites..');
	var sTabId = bMore ? "#more":"#tweeters";
	var iTabId = bMore ? 1:0;
	
	$("#more").empty();
	if (!bMore) $("#tweeters").empty();
	
	$.jsonp({
		url: "http://twitter.com/favorites/"+sUser+".json?callback=?",
	    success:	
	    	function(data){
		        if (data.length == 0){
		        	autoCursor();
		        	showAlertDlg("Could not retrieve favorite information for "+sUser);		        	
		        }else{		        	
			        var id;
			        $("#status").html('Getting Favorites: done');
			        autoCursor();
			        window.follow.FavSrc = {};
			        window.follow.iCount=0;
			        for (var i=0, l=data.length; i<l && window.follow.iCount < window.iMaxFriends; ++i){		        	
			        	id = data[i].user.id;
			        	if (id != window.follow.Me.id && window.follow.FavSrc[id] === undefined){
			        		window.follow.iCount++;
			        		window.follow.FavSrc[id]=data[i].text;
			        	}else
			        		if (window.follow.FavSrc[id] !== undefined)
			        			window.follow.FavSrc[id] += '<p></p>'+data[i].text;
			        }		        
			        
			        if (window.follow.iCount > 0){
			        	waitCursor();
			        	$('#follower-tabs').tabs('option', 'selected', iTabId)
			        	window.follow.iDisp=0;
			        	for (var source_id in window.follow.FavSrc)
			        		showUsers(source_id, sTabId);			        	
			        }else{
			        	autoCursor();
			        	showAlertDlg("No favorites to work with or all favorited tweeters are already being followed.", 
			        		"Fresh out of favorites",
			        		"Hint: try out some popular users with lots of favorites like <i>aplusk</i> and <i>ryanseacrest<i/>");
			        }
		        }
			},

		error: 
			function (XMLHttpRequest, sError) {
				autoCursor();
				checkRateError("Unexpected error in getting favorites: "+ sError);			  
			}
			
	});
} // getMyFavs

//--------------------------------- showRemainingHits
function showRemainingHits(){
	$.jsonp({
		url: "http://twitter.com/account/rate_limit_status.json?format=json&callback=?",
	    success: function(data){
			$("#status").html('Remaining Hits: '+data.remaining_hits+'. Reset at: '+data.reset_time);
		}
	});
} // showRemainingHits

//--------------------------------- showUsers
function showUsers(sID, sTabId){
	waitCursor();
	$.jsonp({
		url: "http://twitter.com/users/show/"+sID+".json?callback=?",
		success:
		    function(data){
		        if (data.error !== undefined){
		        	$("#status").html("Could not retrieve user information for "+sUser);		        	
		        }else{			
					$(sTabId).append('<table><tr><td>'+
						'<div class="user" id="user_profile_image_url"><img src="'+data.profile_image_url+'" alt="profile pic" userid='+sID+' username='+data.screen_name+'></img></div>'+
				        '</td><td width="100%">'+
						(data.url == null ? '' : '<div class="user" id="user_url"><span>Web</span><a href="'+data.url+'">'+data.url+'</a></div>')+
						'<div class="user" id="user_screen_name"><a href="http://www.twitter.com/'+data.screen_name+'">'+data.screen_name+'</a></div>'+
						(data.location == null ? '' : '<div class="user" id="user_location">'+data.location+'</div>')+
						'<div class="user" id="user_name">'+data.name+'</div>'+					
						(data.description == null ? '' : '<div class="user" id="user_description"><span>Bio</span>'+data.description+'</div>')+
						'<div class="user" id="user_status">'+data.status.text+'</div>'+
						'<div class="user" id="user_friends_count"><span>Following</span>'+data.friends_count+'</div>'+
						'<div class="user" id="user_followers_count"><span>Followers</span>'+data.followers_count+'</div>'+
						'<div class="user" id="user_statuses_count"><span>Tweets</span>'+data.statuses_count+'</div>'+
						'<div class="user" id="user_favourites_count"><span>Favorites</span>'+data.favourites_count+'</div>'+
						((sTabId == "#more") || (data.favourites_count == 0) ? '': '<div class="user" id="get_more"><a href="" id="'+sID+'">more</a></div>')+
					    '</td></tr></table>');
						
					$(sTabId).append('<div class="user" id="user_separator"></div>');
					
					if ((data.favourites_count > 0) && (sTabId != "#more"))
						$(sTabId+" #get_more #"+sID).click(function(e){
							getMyFavs($(this).attr('id'), true);
							e.preventDefault();
						});				
		        } // else
		    },
		
		error: 
			function (XMLHttpRequest, sError) {
	    	   $("#status").html("Unexpected error in getting info for: "+ sID);	    	   
			},
	
		complete:
			function (XMLHttpRequest, sStatus) {
				
				$("#user_profile_image_url img").hover(
						function(e){
							showFavDlg($(e.target).attr('username'), window.follow.FavSrc[$(e.target).attr('userid')]);
						},
						function(e){
							$("#favorites_dialog").dialog('close');	
						}
				);
				
		       window.follow.iDisp++;
		       if (window.follow.iDisp == window.follow.iCount){
		    	   autoCursor();
		    	   showRemainingHits();
		       }
			}			
	});
	
} // showUsers



