var MAX_PROFILE_PERPAGE = 12;
var tipz  = null;

/*$(document).ready(function() { 
	$("#loginTrigger").click(function() { 
		$("#loginContent").slideToggle();

	});
});*/

function swaptext(changee,oldText,newText) {
	//changes text in source element
	var elementToChange = document.getElementById(changee);
	elementToChange.innerHTML = (elementToChange.innerHTML == oldText) ? newText : oldText;
}

/* ABOUT / BLOG / CONTACT PAGE START */

$(document).ready(function() { 
	
	$('#networksubmit').click(AjaxObject);
	$("#loadAll").click(function() { // ALL SHOW
		$("#tefollowBio").slideDown("slow");
		$("#tefollowStats").slideDown("slow");
		$("#tefollowLatest").slideDown("slow");
		$("#tefollowImages").slideDown("slow");
		$("#tefollowIntro").slideDown("slow");	
		//$("#tefollowNetwork").slideDown("slow");		
		//$("#teSubscription").slideDown("slow");		

		$("#borderline1").slideDown("slow");		
		$("#borderline2").slideDown("slow");		
		$("#borderline3").slideDown("slow");		
		$("#borderline4").slideDown("slow");	
		$("#borderline5").slideDown("slow");		
		$("#borderline6").slideUp("slow");		
	});

	$("#loadIntro").click(function() { // INTRO
		$("#tefollowBio").slideUp("slow");
		$("#tefollowStats").slideUp("slow");
		$("#tefollowLatest").slideUp("slow");
		$("#tefollowNetwork").slideUp("slow");		
		$("#teSubscription").slideUp("slow");	
		$("#tefollowImages").slideUp("slow");
		$("#tefollowIntro").slideDown("slow");		
			
		$("#borderline1").slideUp("slow");		
		$("#borderline2").slideUp("slow");		
		$("#borderline3").slideUp("slow");		
		$("#borderline4").slideUp("slow");		
		$("#borderline5").slideUp("slow");		
	});

	$("#loadBio").click(function() { // BIO
		$("#tefollowIntro").slideUp("slow");
		$("#tefollowStats").slideUp("slow");
		$("#tefollowLatest").slideUp("slow");
		$("#tefollowNetwork").slideUp("slow");	
		$("#teSubscription").slideUp("slow");	
		$("#tefollowImages").slideUp("slow");
		$("#tefollowBio").slideDown("slow");		
			
		$("#borderline1").slideUp("slow");		
		$("#borderline2").slideUp("slow");		
		$("#borderline3").slideUp("slow");		
		$("#borderline4").slideUp("slow");		
		$("#borderline5").slideUp("slow");		
	});

	$("#loadStats").click(function() { // STATS
		$("#tefollowIntro").slideUp("slow");
		$("#tefollowBio").slideUp("slow");
		$("#tefollowLatest").slideUp("slow");
		$("#tefollowNetwork").slideUp("slow");		
		$("#teSubscription").slideUp("slow");	
		$("#tefollowImages").slideUp("slow");
		$("#tefollowStats").slideDown("slow");		
			
		$("#borderline1").slideUp("slow");		
		$("#borderline2").slideUp("slow");		
		$("#borderline3").slideUp("slow");		
		$("#borderline4").slideUp("slow");		
		$("#borderline5").slideUp("slow");		
	});

	$("#loadLatest").click(function() { // LATEST
		$("#tefollowIntro").slideUp("slow");
		$("#tefollowBio").slideUp("slow");
		$("#tefollowStats").slideUp("slow");
		$("#tefollowNetwork").slideUp("slow");		
		$("#teSubscription").slideUp("slow");		
		$("#tefollowImages").slideUp("slow");
		$("#tefollowLatest").slideDown("slow");		
			
		$("#borderline1").slideUp("slow");		
		$("#borderline2").slideUp("slow");		
		$("#borderline3").slideUp("slow");		
		$("#borderline4").slideUp("slow");		
		$("#borderline5").slideUp("slow");		
	});
	
	$("#loadNetwork").click(function() { // Network
		$("#tefollowIntro").slideUp("slow");
		$("#tefollowBio").slideUp("slow");
		$("#tefollowStats").slideUp("slow");
		$("#tefollowImages").slideUp("slow");
		$("#tefollowLatest").slideUp("slow");		
		$("#teSubscription").slideUp("slow");	
		$("#tefollowNetwork").slideDown("slow");		
			
		$("#borderline1").slideUp("slow");		
		$("#borderline2").slideUp("slow");		
		$("#borderline3").slideUp("slow");		
		$("#borderline4").slideUp("slow");		
		$("#borderline5").slideUp("slow");
	});

	$("#loadSubscription").click(function() { // Subscription
		$("#tefollowIntro").slideUp("slow");
		$("#tefollowBio").slideUp("slow");
		$("#tefollowStats").slideUp("slow");
		$("#tefollowImages").slideUp("slow");
		$("#tefollowLatest").slideUp("slow");		
		$("#tefollowNetwork").slideUp("slow");	
		$("#teSubscription").slideDown("slow");		
			
		$("#borderline1").slideUp("slow");		
		$("#borderline2").slideUp("slow");		
		$("#borderline3").slideUp("slow");		
		$("#borderline4").slideUp("slow");		
		$("#borderline5").slideUp("slow");
	});

	$("#loadImages").click(function() { // IMAGES
		$("#tefollowIntro").slideUp("slow");
		$("#tefollowBio").slideUp("slow");
		$("#tefollowStats").slideUp("slow");
		$("#tefollowLatest").slideUp("slow");
		$("#tefollowNetwork").slideUp("slow");		
		$("#teSubscription").slideUp("slow");	
		$("#tefollowImages").slideDown("slow");		
			
		$("#borderline1").slideUp("slow");		
		$("#borderline2").slideUp("slow");		
		$("#borderline3").slideUp("slow");		
		$("#borderline4").slideUp("slow");
		$("#borderline5").slideUp("slow");		
	});

	if (window.location.hash=='#subscribe')
	{
		$('#loadSubscription').trigger('click');
	}

	$('#subscribe_form').submit(function() {
		$('#sub_message').css('display', 'none');
		$('#sub_error').css('display', 'none');
		$('#subscribe_preloader').css('display', 'inline');
		var str = $(this).serialize(); 
		$.ajax({
			type: "POST",
			url: "/subscribe.php",
			data: str,
			dataType: "json",
			success: function(msg) {
				$('#subscribe_preloader').css('display', 'none');
				if (msg.status==1000)
				{
					$('#teSubscription form').css('display', 'none');
					$('#sub_message').css('display', 'block')
					.html(msg.message);
				}
				else
				{
					$('#sub_error').css('display', 'block')
					.html(msg.message);
				}
			},
			error: function (XMLHttpRequest, textStatus, errorThrown) {
				$('#subscribe_preloader').css('display', 'none');
				$(this).html(textStatus);
			}
		}); 
		return false; 
	});
});


function printProfile(profile, followOrFriend)
{
	if (!profile)
		return;

	image  = "";
	anchor = "";
	title = profile.screen_name + "::" + profile.name + "::" + profile.location + "::" + profile.followers_count + "::" + profile.friends_count + "::" + profile.statuses_count;
	image += '<img class="profileimg" src="' + profile.profile_image_url + '" alt="' + profile.screen_name +'" tiptitle="' + title +'"/>';
	anchor += '<a href="/' + profile.screen_name +'" target = "_blank">';
	
	var profileDiv = $('<div class= "user"><p>' + anchor + image + '</a></p></div>');

	$(followOrFriend).append(profileDiv);
	var img = $('img', profileDiv);
	$(img).mouseover( function(event) {
		tip(this, event);
	});

	$(img).mouseout( function(event) {
		tooltip.hide();
		$(this).css('border', 'none');
	});
}

//Show transparent tooltip on hovering over profiles
//taken from http://friendorfollow.com/javascript/friendorfollow.js
//The profile details are stored in the image title as andybeal::Andy Beal::Raleigh, NC::6264
function tip(image, e)
{
	//Show border
	$(image).css('border', '2px solid #C2C2C2'); 

	element = $(image);
	if(element.attr("tiptitle") != null)
	{
		var content = element.attr("tiptitle").split('::');
		element.data('tip:title', content[0]);
		var tipString = '<p style="text-align:left">';

		if(content[0] != '')
			tipString += '<span style="color:#95C01F"><strong>' + content[0] + '</strong></span><br/>';
		if(content[1] != '')
			tipString += 'Name: <strong>' + content[1] + '</strong><br/>';
		if(content[2] != '')
			tipString += 'Location: <strong>' + (content[2]? content[2]:'') + '</strong><br/>';
		tipString += 'Followers: <strong>' + (content[3]? content[3]:'') + '</strong><br/>';
		tipString += 'Following: <strong>' + (content[4]? content[4]:'') + '</strong><br/>';
		tipString += 'Updates: <strong>' + (content[5]? content[5]:'') + '</strong><br/>';
		tipString += '</p>';

		element.data('tip:text', tipString);

		tooltip.show(tipString);
	}
}

function setDisplay(id, show)
{
	var current = $(id).css('display');
	if(show == true)
		$(id).css('display','inline');
	else
		$(id).css('display','none');
	var a=10;
}

function FadeOpacity(elemId, fromOpacity, toOpacity, time, fps)               
{                                                                        
    var steps = Math.ceil(fps * (time / 1000));                               
    var delta = (toOpacity - fromOpacity) / steps;                            
                                                                              
    FadeOpacityStep(elemId, 0, steps, fromOpacity,                            
                    delta, (time / steps));                                   
}                                                                             
                                                                              
function FadeOpacityStep(elemId, stepNum, steps, fromOpacity,                 
                         delta, timePerStep)                                  
{                                                                             
    SetOpacity($(elemId), Math.round(parseInt(fromOpacity) + (delta * stepNum)));        
                                                                              
    if (stepNum < steps)                                                      
        setTimeout("FadeOpacityStep('" + elemId + "', " + (stepNum+1)         
                 + ", " + steps + ", " + fromOpacity + ", "                   
                 + delta + ", " + timePerStep + ");",                         
                   timePerStep);     
	else
	{
		setDisplay(elemId, false);
	}
}                                                                             

function showMessage(msg)
{
	if (msg==0) //hide
	{
		//Proceed only if the message box is shown on screen
		if ($('#messageArea').css('display') != 'none')
			FadeOpacity('#messageArea', 100, 0, 500, 8);
	}
	else if (msg==-1) //forcible hide
	{
		setDisplay('#messageArea', false);
	}
	else
	{
		setDisplay("#messageArea", true);
		$('#messageBox').html(msg);
	}
}

function generatePostData(session, relation, from)
{
	var postData = "";
	if (session && relation && from)
	{
		//just send the session id and relation name
		postData += "session=" + session + "&relation=" + relation + "&from=" + from;
	}
	else
	{
		var user1 = $('.user1').val();
		var user2 = $('.user2').val();
		postData += "user1="+user1+"&user2="+user2;
	}
	return postData;
}


function AjaxObject(relation)
{
	var url = "";
	
	if(relation == "followers")
	{
		$('#followersMoreAnchor').unbind('click');
		setDisplay("#followersLoading",true);
		session = $('.session').html();
		from = $('.followersfrom').html();
		url = '/tool.php?'+ generatePostData(session, relation, from);
	}
	else if(relation == "friends") 
	{
		$('#friendsMoreAnchor').unbind('click');
		setDisplay("#friendsLoading",true);
		session = $('.session').html();
		from = $('.friendsfrom').html();	
		url = '/tool.php?'+ generatePostData(session, relation, from);
	}
	else
	{
		$("#followersProfiles").html("");
		$("#friendsProfiles").html("");
		$(".noFriendsDiv").html("");
		$(".noFollowersDiv").html("");
		$('#resultSummary').html("");
		$('#friendsMoreAnchor').unbind('click');
		$('#followersMoreAnchor').unbind('click');
		$('#networksubmit').unbind('click');
		setDisplay("#followersMoreContainer",false);
		setDisplay("#friendsMoreContainer",false);
		setDisplay("#followersLoading",true);
		setDisplay("#friendsLoading",true);
		setDisplay("#friendsHead",true);
		setDisplay("#followersHead",true);
		url = '/tool.php?'+ generatePostData();
	}

	$.get(url,null,function(json)
	{
		setDisplay("#followersLoading",false);
		setDisplay("#friendsLoading",false);
		if (json.statusCode == 1)
		{
			if (!json.message)
				json.message = "We encountered an unexpected error. Please try again in several minutes. If that doesn't work, please let us know.";
			showMessage(json.message);
		}
		else
		{
			//hide the previous message forcibly
			showMessage(-1);

			if(json.session != 0)
			{
				$('.session').html(json.session);
			}
			if (json.statusCode != 0)
			{
				//Check for warnings and show it
				showMessage(json.message);
			}
			if (json.followers != null && json.followers.length > 0)
			{
				for ( i=0 ; i < json.followers.length ; ++i)
					printProfile(json.followers[i], "#followersProfiles");

				var achorElement = $('#followersMoreAnchor');

				if (json.moreFollowers)
				{
					$(achorElement).click( function() {
						AjaxObject('followers');
						return false;
					}, json);
					$('.followersfrom').html(json.fromFollowers);
				}
				setDisplay("#followersMoreContainer", json.moreFollowers);
				//show the more button if required
			}
			else if (!json.repeatRequest)
			{
				$('.noFollowersDiv').html(json.nameList + " have none in common that they follow");
				setDisplay(".noFollowersDiv", true);
			}
			else if (json.relation == 'followers')
			{
				//hide the more button
				setDisplay("#followersMoreContainer", false);
			}
			if (json.friends != null && json.friends.length > 0)
			{
				for ( i=0 ; i < json.friends.length ; ++i)
					printProfile(json.friends[i], "#friendsProfiles");

				var achorElement = $('#friendsMoreAnchor');

				if (json.morefriends)
				{
					$(achorElement).click( function() {
						AjaxObject('friends');
						return false;
					}, json);	
					$('.friendsfrom').html(json.fromFriends);
				}
				//show the more button
				setDisplay("#friendsMoreContainer", json.morefriends);

			}
			else if (!json.repeatRequest)
			{
				$('.noFriendsDiv').html(json.nameList + " are not following any one in common");
				setDisplay(".noFriendsDiv", true);
			}
			else if(json.relation=='friends')
			{
				//hide the more button
				setDisplay("#friendsMoreContainer", false);
			}
			//show the total count of results in a hidden element
			if (!json.repeatRequest)
			{
				setDisplay("#resultSummaryBox",true);
				$('#resultSummary').html('They are followed by ' + json.followersCount + ' and following ' + json.friendsCount + ' Twitter users in common');
			}
		}
		$('#networksubmit').click(AjaxObject);
	}, "json");	
}


