var type;
var url;
var username;
var orderby;
var currentPage;
var ids;
var firstCall = 1;

var showProtected = 1;
var showVerified = 1;
var showOthers = 1;

var updateIds = [];
var updateIdsTimeOut = null;
function e(source, twitter_id)
{
    source.onerror = "";
    source.src = "http://s.twimg.com/a/1268333781/images/default_profile_3_normal.png";
    updateIds.push(twitter_id);
    
    clearTimeout(updateIdsTimeOut);
	updateIdsTimeOut = setTimeout("updateBrokenImgProfiles()", 10000);
	
    return true;
}

function updateBrokenImgProfiles(){
	postUrl = 'http://' + document.domain + '/updateid/'
	$.ajax({
		type: "POST",
		url: postUrl,
		processData: false,
		data: 'ids=' + updateIds
	});
	updateIds = [];
}

function clearOldResults()
{
	ids = null;
	firstCall = 1;
}

function enableInputs()
{	
	$('#orderby').removeAttr("disabled");
	$('#showProtected').removeAttr("disabled");
	$('#showVerified').removeAttr("disabled");
	$('#showOthers').removeAttr("disabled");

	$('#orderby-label').css("color", "#fff");
	$('#orderby').val(orderby);
	
	loadCheckboxValues();
}

function disableInputs()
{
	saveCheckboxValues();
	orderby = $("#orderby").val();
	
	$('#orderby').attr("disabled", true);
	$('#showProtected').attr("disabled", true);
	$('#showVerified').attr("disabled", true);
	$('#showOthers').attr("disabled", true);
	
	$('#orderby-label').css("color", "#999");
	
}

jQuery.fn.exists = function(){return jQuery(this).length>0;}

function saveCheckboxValues()
{
	if($('#showProtected').exists())
	{
		if ($("input[name='showProtected']:checked").is(':checked')) { showProtected = 1; } else { showProtected = 0; }
		if ($("input[name='showVerified']:checked").is(':checked')) { showVerified = 1; } else { showVerified = 0; }
		if ($("input[name='showOthers']:checked").is(':checked')) { showOthers = 1; } else { showOthers = 0; }
	}
}

function loadCheckboxValues()
{
	$('#showProtected').attr('checked', showProtected);
	$('#showVerified').attr('checked', showVerified);
	$('#showOthers').attr('checked', showOthers);
}

function postResults(ids, missFire, orderby, type, currentPage, idsHaventChanged)
{
	$.ajax({
		type: "POST",
		url: url,
		processData: false,
		data: 'i=' + ids + '&missFire=' + missFire + '&orderby=' + orderby + '&type=' + type + '&page=' + currentPage 
		+ '&idsHaventChanged=' + idsHaventChanged + '&showProtected=' + showProtected + '&showVerified=' + showVerified + '&showOthers=' + showOthers,
		success: function(data) {
			$('#result').html(data);
			enableInputs();
		}
	});
}

var clearOldResultsTimeOut = null;
function loadResults(page){
	clearTimeout(clearOldResultsTimeOut);
	clearOldResultsTimeOut = setTimeout("clearOldResults()", 300000);

	//$(".iButton").iButton("repaint");
	
	currentPage = page;
	loadNavigation(currentPage);
	disableInputs();

	if(firstCall == 1)
	{
		$("#result").html('<div id="loading-between-tabs"><img id="loadingImage" height="45" width="45" src="http://cdn.cloudfiles.rackspacecloud.com/c84462/loading.gif" /> <h2>Loading...</h2><p>(If you\'re popular this might take awhile)</p></div>');
	}
	else
		$("#userList").html('<div id="loading-between-tabs"><img id="loadingImage" height="45" width="45" src="http://cdn.cloudfiles.rackspacecloud.com/c84462/loading.gif" /> <h2>Loading...</h2><p>(If you\'re popular this might take awhile)</p></div>');

	timeOutEvent = null;
	url = window.location.href;
	url = url.replace(/\?.*$/, "");
	
	// get type
	if(url.indexOf('fans') > -1)
	{
		type = 'fans';
		url = url.replace('/fans', '');
	}
	else if(url.indexOf('friends') > -1)
	{
		type = 'friends';
		url = url.replace('/friends', '');
	}
	else
	{
		type = 'following';
		url = url.replace('/following', '');
	}
	
	username = url.replace('http://', '').replace('friendorfollow.com/', '').replace('dev.', '').replace('test.', '').replace('/', '');
	
	protectedAccount = $("#protected").val();
	
	if(protectedAccount == "false" && ids == null)
	{
		firstCall = 1;
		getFriendsIds(username, -1);
		getFollowersIds(username, -1);
	}
	
	// get ordey by value
	orderby = "screen_name";
	orderby = $("#orderby").val();
	
	// add trailing slash if needed
	if(url.lastIndexOf('/') + 1 != url.length)
		url = url + '/';
	
	url = url + "results/?" + window.location.search.substring(1);
	
	if(protectedAccount == "true")
	{
		postResults(null, 'true', orderby, type, currentPage, 0);
	}
	else if(ids != null)
	{
		idsHaventChanged = 1;
		postResults(ids, missFire, orderby, type, currentPage, idsHaventChanged);
	}
	else
	{
		runAjaxStopOnce = 0;
		$(document).ajaxStop(function() {
	
			if(runAjaxStopOnce == 0)
			{
				clearTimeout(timeOutEvent);
				runAjaxStopOnce++;
				
				missFire = false;
				if(calledGetFriendsIds == false || calledGetFollowersIds == false)
					missFire = true;
				else
				{
					if(ids == null)
					{
						if(type == 'fans')
							ids = array_diff(followersIds, friendsIds);
						else if(type == 'friends')
							ids = array_mutual(followersIds, friendsIds);
						else
							ids = array_diff(friendsIds, followersIds);
					}
				}
				firstCall = 0;
				postResults(ids, missFire, orderby, type, currentPage, 0);
			}
		});
	}
}

var timeOutEvent = null;
function setTimeOut()
{
	if(timeOutEvent == null)
		timeOutEvent = setTimeout('failWhale()', 5000);
}

function failWhale()
{
	//$("#result").load(url, {'i[]': null, 'missFire': true, 'orderby':orderby, 'type':type, 'page':currentPage}, function(){enableInputs();});

	postResults(null, 'true', orderby, type, currentPage, 0);
}

var friendsIds = [];
var calledGetFriendsIds = false;
function getFriendsIds(username, cursor)
{
	setTimeOut();
	var url = "http://api.twitter.com/1/friends/ids.json?screen_name=" + username + "&callback=?";
	$.getJSON(url,
		function(data){
			clearTimeout(timeOutEvent);
			calledGetFriendsIds = true;
			friendsIds = jQuery.makeArray(data);
		});
}

var followersIds = [];
var calledGetFollowersIds = false;
function getFollowersIds(username, cursor)
{
	setTimeOut();
	var url = "http://api.twitter.com/1/followers/ids.json?screen_name=" + username + "&callback=?";
	$.getJSON(url,
        function(data){
        	clearTimeout(timeOutEvent);
        	calledGetFollowersIds = true;
        	followersIds = jQuery.makeArray(data);
		});
}

/* Using Cursors */
/*var friendsIds = [];
var calledGetFriendsIds = false;
function getFriendsIds(username, cursor)
{
	setTimeOut();
	var url = "http://api.twitter.com/1/friends/ids.json?screen_name=" + username + "&cursor=" + cursor + "&callback=?";
	$.getJSON(url,
		function(data){
			clearTimeout(timeOutEvent);
			calledGetFriendsIds = true;
			cursor = data.next_cursor;
			
			if(cursor > 0)
				getFriendsIds(username, cursor);
			
			moreFriendsIds = jQuery.makeArray(data.ids);
			$.merge(friendsIds, moreFriendsIds);
		});
}

var followersIds = [];
var calledGetFollowersIds = false;
function getFollowersIds(username, cursor)
{
	setTimeOut();
	var url = "http://api.twitter.com/1/followers/ids.json?screen_name=" + username + "&cursor=" + cursor + "&callback=?";
	$.getJSON(url,
        function(data){
        	clearTimeout(timeOutEvent);
			calledGetFollowersIds = true;
			cursor = data.next_cursor;
			
			if(cursor > 0)
				getFollowersIds(username, cursor);
			
			moreFollowersIds = jQuery.makeArray(data.ids);
			$.merge(followersIds, moreFollowersIds);
		});
}
*/

function array_mutual(array1, array2)
{
	var diff = array1.slice(0);
	var match = array2.slice(0);
	var mutual = [];
	
	diff = unique(diff);
	match = unique(match);
	
	var ml = match.length;
	for(var i = 0; i < ml; i++)
	{
		var found = binarySearch(diff, match[i]);
		
		if(found != -1)
		{
			mutual.push(diff[found]);
		}
	}
	return mutual;
}


function array_diff(array1, array2)
{
	//var time = new Date().getTime();
	
	var diff = array1.slice(0);
	var match = array2.slice(0);
	
	diff = unique(diff);
	
	var ml = match.length;
	for(var i = 0; i < ml; i++)
	{
		var found = binarySearch(diff, match[i]);
		
		if(found != -1)
		{
			diff.splice(found, 1);
		}
	}
	
	//alert(new Date().getTime() - time);
	
	return diff;
}

function sortNumber(a,b)
{
return a - b;
}

function unique(a){
	a.sort(sortNumber);
	for(var i = 1;i < a.length;){
		if(a[i-1] == a[i]){a.splice(i, 1);}
		else{i++;}
	}
	return a;
}

function binarySearch(items, value){
	var startIndex = 0,
	    stopIndex = items.length - 1,
	    middle = Math.floor((stopIndex + startIndex)/2);
	    
	while(items[middle] != value && startIndex < stopIndex){
	
	    //adjust search area
	    if (value < items[middle]){
	        stopIndex = middle - 1;
	    } else if (value > items[middle]){
	        startIndex = middle + 1;
	    }
	    
	    //recalculate middle
	    middle = Math.floor((stopIndex + startIndex)/2);
	}
	
	//make sure it's the right value
	return (items[middle] != value) ? -1 : middle;
}

function loadNavigation(currentPage)
{

	totalPages = $("#totalPages").html();
	newPageNavigation = pageNavigation(currentPage, totalPages);

	$(".pagination").html(newPageNavigation);
}

function pageNavigation(current_page, total_pages)
{
	if(total_pages <= 1)
		return '';
		
	var html = '';
	var previous_page;
	var next_page;
	var difference = total_pages - current_page;
	var low_range = current_page - 3;
	var high_range = current_page + 4;

    if (total_pages <= 10) {
        for (i=1; i<=total_pages; i++) {
        	if(i == current_page && current_page == total_pages)
            	html += " <strong>" + i + "</strong>";
        	else if(current_page == i)
	            html += " <strong>" + i + "</strong> | ";
            else
            	html += i + " | ";
        }
    } else if (total_pages > 10 && difference < 5) {
    	if(current_page == i)
            html += " <strong>" + i + "</strong> ";
        else
        	html += " 1 | ... ";
        for (i=(total_pages-5); i<=total_pages; i++) {
        	if(current_page == i)
	            html += " | <strong>" + i + "</strong> ";
	        else
        	    html += " | " + i;
        }
    } else if (total_pages > 10) {
        if (current_page < 6) {
            for (i=1; i<7; i++) {
            	if(current_page == i)
            		html += " <strong>" + i + "</strong> | ";
            	else
                	html += i + " | ";
            }
            html += " ... | " + total_pages + " | ";
        } else {
            html = " 1 | ... |";
            for (i=low_range; i<high_range; i++) {
            	if(current_page == i)
            		html +=  " <strong>" + i + "</strong> | ";
            	else
                	html += i + " | ";
            }
            html += " ... | " + total_pages + " | ";
        }
    }
    if (current_page == 1) {
        previous_page = '';
    } else {
    	prev = current_page - 1;
        previous_page = " &#171; prev | ";
    }
    if (current_page == total_pages) {
        next_page = '';
    } else {
    	next = current_page + 1;
        next_page = " next &#187; ";
    }
    html = '<div class="pagebox"><span style="color:#999;text-decoration:none;cursor:default;">' + previous_page + html + next_page + '</span><span style="display:none" id="totalPages">' + total_pages + '</span></div>';

    return html;
}