$( document ).ready( function() { 
	$('#id_types').val(''); 
	update_buddies('');
}); 

$( document ).ajaxStart( function() {  
	$( '#spinner' ).show();
});

$( document ).ajaxStop( function() {  
	$( '#spinner' ).hide();
});

function toggle_type(type){ 
	old_val = $("#id_types").val();
	type_array = old_val.split(',');
	type = type.toLowerCase(); 
	
	type_index = -1;  
	for(i=0; i < type_array.length; i++){
		if(type_array[i] == type) {
			type_index = i;
			break;
		}
	}
	
	type_id = '#type_' + type.replace(/ /g, "-").toLowerCase();
	if (type_index == -1) { // type didn't exist, so add it
		type_array.splice(type_array.length,0,type);
		$(type_id).attr("class", "selected"); 
		update_buddies(type_array.join()); 
	} else {  // type existed, remove it 
		type_array.splice(type_index,1);
		$(type_id).attr("class", "unselected"); 
		update_buddies(type_array.join());
	}

	$("#id_types").val(type_array);
} 

function update_buddies(types, page){ 
	if(!page) { page = 1; }
	$.post(url_buddies_with_type_profile_slug, {types:types, page:page}, 
	function(data){
		if (data.success) { 
			$('#more_buddies' ).html(data.html);
			ajaxpages_bindscroll();
			
			$('#followed_by_count' ).html("(" + data.followed_by_count + ")");
			$('#following_count' ).html("(" + data.following_count + ")");
			$('#mutual_count' ).html("(" + data.mutual_count + ")");
			$('#all_buddies_count' ).html("(" + data.all_buddies_count + ")");
		} else {
			if (data.error) alert(data.error); 
			else alert ('Oops! An error has occurred!');
		}
	}, "json");
}

function load_page(page) { 
	types = $("#id_types").val();
	update_buddies(types, page); 
}

function clear_types() { 
	old_val = $("#id_types").val();
	type_array = old_val.split(',');
	
	// unselect all the types 
	for(i=0; i < type_array.length; i++){
		type = type_array[i]; 
		type_id = '#type_' + type.replace(/ /g, "-").toLowerCase(); 
		$(type_id).attr("class", "unselected"); 
	}
	
	// clear types field 
	$("#id_types").val("");
	
	// show all films 
	update_buddies("");
}
