// This is an ARRAY of currently open tabs.
var open_tabs = new Array();

// This is a boolean flag. When a search is "in progress", no other search can be made until the current one finishes.
var previous_search_complete = true;

//Tab paging info.
var offset = 0;
var left_hidden_tab = 0;
var right_hidden_tab = 0;
window.carousel_obj = "";

// This is for the current active tab. Used in the event handlers section as well as in the SaveActiveTab() function.
var current_active_tab = 0;

// #################################################
function SearchSubmit() {
	// See if a search term at all was entered. If nothing was entered, just return false. Don't perform any actual search.
	if($(window.global_search_term).val().length < 1) return false;

	// See if the search term is ONLY a q-trigger.
	if(IsTrigger($(window.global_search_term).val())) {
		return false;
	}

	// Serialize data.
	serialized_data = GetSerializedTabs();

	// See if the previous search is complete. If it's not, do not process another one yet. Causes conflicts.
	if(!previous_search_complete) return false;

	previous_search_complete = false;

	// Use active tab or not? If they want to use active tab, at least 1 tab must be open.
	var use_active_tab = 0;
	if($('#create_new_tab').is(':checked') == false && GetActiveTabId())
		use_active_tab = 1;

	//Add the loading image to the search bar
	AddLoadingImage();

	$.ajax({
		type:		"GET",
		url:		"ajax/search.php",
		dataType:	"json",
		data:		serialized_data + "search_term=" + encodeURIComponent($(window.global_search_term).val()) + "&use_active_tab=" + use_active_tab + "&active_tab="+GetActiveTabId()+"&action=",
		ifModified:	false,
		success:	function(obj) {
						CreateTab(obj);
					}
	});

	return false; // return false so no submit actually happens.
}

// #################################################
function IsTrigger(value) {
	var retval = false;
	$.each(triggers, function(i) {
//		console.log(triggers[i]);


		if(value.toLowerCase() == 'h:') {
			retval = true;
			TwerqHive();
		} else if(value.toLowerCase() == triggers[i].toLowerCase()) {
			retval = true;
		}
	});

	return retval;
}

// #################################################
function SerializeObject(object) {
	var buf = "action=serialized";
	$.each(object, function(name,value) {
		buf += "&"+name+"="+encodeURIComponent(value);
	});

	return buf;
}

// #################################################
function Expand_ShortlistImage(id, keyword, shortlist_url, shortlist_id, thumbnail_url, thumb_height, thumb_width, image_size, referer_url, title, tab_id, index) {
	var id_obj = $('#'+id);
	if($(id_obj).css('display') == 'none') {
		var parameters = {
			"id":				id,
			"keyword":			keyword,
			"shortlist_url":	shortlist_url,
			"shortlist_id":		shortlist_id,
			"thumbnail_url":	thumbnail_url,
			"thumb_height":		thumb_height,
			"thumb_width":		thumb_width,
			"image_size":		image_size,
			"referer_url":		referer_url,
			"title":			title,
			"tab_id":			tab_id,
			"index":			index};

		var query_string = SerializeObject(parameters);

		$.ajax({
			type:		"GET",
			url:		"/ajax/get_shortlist_image.php",
			dataType:	"html",
			data:		query_string,
			success:	function(html) {
				$('#inner_div_'+id).html(html);
				$(id_obj).show();
			}
		});

	} else {
		$(id_obj).hide();
	}
}

// #################################################
function ExpandShortlist(id, title, snippet, url, tab_id, key, search_engine,thumbnail_url) {
	var id_obj = $('#'+id);
	if($(id_obj).css('display') == 'none') {
		var parameters = {
			"id":				id,
			"title":			title,
			"snippet":			snippet,
			"url":				url,
			"tab_id":			tab_id,
			"key":				key,
			"search_engine":	search_engine,
			"thumbnail_url":	thumbnail_url
		};

		var query_string = SerializeObject(parameters);

		$.ajax({
			type:		"GET",
			url:		"/ajax/get_shortlist_other.php",
			dataType:	"html",
			data:		query_string,
			success:	function(html) {
				$('#inner_div_'+id).html(html);
				$(id_obj).show();
			}
		});

	} else {
		$(id_obj).hide();
	}
}

// #################################################
function ShowAnnouncement(announcement_id) {
	ChangeSection('/ajax/templates/show_announcement.php?id='+announcement_id);
}

// #################################################
function ToggleAnnouncementDate(id) {
	var id_obj = $('#'+id);
	if($(id_obj).css('display') == 'none') {
		$(id_obj).css('display', 'block');
	} else {
		$(id_obj).css('display', 'none');
	}
}

// #################################################
function RetrievePasswordSubmit() {
	$.ajax({
		type:		"POST",
		url:		"/forgot_password.php",
		data:		ParseForm('retrieve_password_form'),
		dataType:	"html",
		success:	function(html) {
			$('#retrieve_password_response').html(html);
		}
	});

	return false;
}

// #################################################
function TWERQSafeSetPassword() {
	var query_string = ParseForm('twerq_safe_set_password');

	$.ajax({
		type:		"POST",
		url:		"/ajax/twerq_safe_set_password.php",
		dataType:	"html",
		data:		query_string,
		success:	function(html) {
			window.location = "/index.html";
		}

	});

	return false;
}

// #################################################
function TWERQSafeLogin() {
	var query_string = ParseForm('twerq_safe_login');

	$.ajax({
		type:		"POST",
		url:		"/ajax/twerq_safe_login.php",
		dataType:	"html",
		data:		query_string,
		success:	function(html) {
			window.location = "/index.html";
		}

	});

	return false;
}

// #################################################
function TWERQSafeLogout() {
	$.ajax({
		type:		"POST",
		url:		"/ajax/twerq_safe_logout.php",
		dataType:	"html",
		success:	function(html) {
			window.location = "/index.html";
		}

	});

	return false;
}

// #################################################
function EditTWERQSafe() {
	var query_string = ParseForm('edit_twerq_safe');

	$.ajax({
		type:		"POST",
		url:		"/ajax/edit_twerq_safe.php",
		dataType:	"html",
		data:		query_string,
		data:		query_string,
		success:	function(html) {
			window.location = "/index.html";
		}

	});

	return false;
}


// THIS FUNCTION IS NO LONGER USED. (TWERQSafe)
// #################################################
function TWERQSafe() {
	// Serialize data.
	serialized_data = GetSerializedTabs();

	// See if the previous search is complete. If it's not, do not process another one yet. Causes conflicts.
	if(!previous_search_complete) return false;

	var use_active_tab = 0;

	previous_search_complete = false;

	//Add the loading image to the search bar
	AddLoadingImage();

	$.ajax({
		type:		"GET",
		url:		"/ajax/twerq_safe.php",
		dataType:	"json",
		data:		serialized_data + "&use_active_tab=" + use_active_tab + "&active_tab="+GetActiveTabId(),
		ifModified:	true,
		success:	function(obj) {
						CreateTab(obj);
					}
	});
}

// #################################################
function SubmitTwerqSafe(tab_id) {
	// Get data.
	var query_string = "action=twerq_safe";
	query_string += "&keywords="+encodeURIComponent( $('#keywords_'+tab_id).val() );

	if($('#activate_twerq_safe_'+tab_id).attr('checked') == true) {
		query_string += "&activate_twerq_safe=yes";
	} else {
		query_string += "&activate_twerq_safe=no";
	}

	query_string += "&twerq_safe_password="+encodeURIComponent( $('#twerq_safe_password_'+tab_id).val() );

	$.ajax({
		type:		"POST",
		url:		"/ajax/twerq_safe_submit.php",
		dataType:	"html",
		data:		query_string,
		success:	function(html) {
//			alert(html);
			window.location = "/index.html";
		}
	});

	return false; // so the form does not submit.
}


// #################################################
function SubmitContactUs(tab_id) {
	// Get data.
	var query_string = "action=contact_us";
	$('#contact_form :input').each(function(i) {
		query_string += "&"+$(this).attr('name')+"="+encodeURIComponent($(this).val());
	});

	$.ajax({
		type:		"POST",
		url:		"/ajax/contact_submit.php",
		dataType:	"html",
		data:		query_string,
		success:	function(html) {
			ChangeSection('/ajax/templates/contact_thankyou.html');
		}
	});

	return false; // so the form does not submit.
}

// #################################################
function TwerqHive() {
	// Serialize data.
	serialized_data = GetSerializedTabs();

	// See if the previous search is complete. If it's not, do not process another one yet. Causes conflicts.
	if(!previous_search_complete) { return false; }

	// Is the tab already open?
	var tmp = $('#tabs li[@title=TWERQ Hive]');
	if(tmp.html()) {
		var tab_id = $(tmp).attr('id').split("_")[1];
		SetActiveTab(tab_id);
		window.carousel_obj.scroll(GetTabIndex(GetTabIndex(tab_id)));
		return;
	}

	var use_active_tab = 0;

	previous_search_complete = false;

	//Add the loading image to the search bar
	AddLoadingImage();

	$.ajax({
		type:		"GET",
		url:		"/ajax/twerq_hive.php",
		dataType:	"json",
		data:		serialized_data + "&use_active_tab=" + use_active_tab + "&active_tab="+GetActiveTabId(),
		ifModified:	true,
		success:	function(obj) {
						if(obj.do_not_create == 1) {
//							alert("tab already exists. Tab ID: + " + obj.switch_tab_id);
							SetActiveTab(obj.switch_tab_id);

							previous_search_complete = true;
							//Take off the loading image.
							RemoveLoadingImage();
						} else {
							CreateTab(obj);
						}

						Hive.InitializeBrowseHives();
					}
	});
}

// #################################################
function SponsorSignup() {
	// Serialize data.
	serialized_data = GetSerializedTabs();

	// See if the previous search is complete. If it's not, do not process another one yet. Causes conflicts.
	if(!previous_search_complete) { return false; }

	var use_active_tab = 0;

	previous_search_complete = false;

	//Add the loading image to the search bar
	AddLoadingImage();

	$.ajax({
		type:		"GET",
		url:		"/ajax/sponsor_signup.php",
		dataType:	"json",
		data:		serialized_data + "&use_active_tab=" + use_active_tab + "&active_tab="+GetActiveTabId(),
		ifModified:	true,
		success:	function(obj) {
						if(obj.do_not_create == 1) {
//							alert("tab already exists. Tab ID: + " + obj.switch_tab_id);
							SetActiveTab(obj.switch_tab_id);

							previous_search_complete = true;
							//Take off the loading image.
							RemoveLoadingImage();
						} else {
							CreateTab(obj);
						}
					}
	});
}

// #################################################
function Zoho() {
	// Serialize data.
	serialized_data = GetSerializedTabs();

	// See if the previous search is complete. If it's not, do not process another one yet. Causes conflicts.
	if(!previous_search_complete) { return false; }

	var use_active_tab = 0;

	previous_search_complete = false;

	//Add the loading image to the search bar
	AddLoadingImage();

	$.ajax({
		type:		"GET",
		url:		"/ajax/zoho.php",
		dataType:	"json",
		data:		serialized_data + "&use_active_tab=" + use_active_tab + "&active_tab="+GetActiveTabId(),
		ifModified:	true,
		success:	function(obj) {
						if(obj.do_not_create == 1) {
//							alert("tab already exists. Tab ID: + " + obj.switch_tab_id);
							SetActiveTab(obj.switch_tab_id);

							previous_search_complete = true;
							//Take off the loading image.
							RemoveLoadingImage();
						} else {
							CreateTab(obj);
						}
					}
	});
}

// #################################################
function ChangeSection(url) {
	var active_tab = GetActiveTabId();

	$.ajax({
		type:		"GET",
		url:		url,
		dataType:	"html",
		success:	function(html) {
			$('#about_'+active_tab).html(html);
			Hive.addDropDowns();
		}
	});
}

// #################################################
function Features() {
	// Serialize data.
	serialized_data = GetSerializedTabs();

	// See if the previous search is complete. If it's not, do not process another one yet. Causes conflicts.
	if(!previous_search_complete) return false;

	var use_active_tab = 0;

	previous_search_complete = false;

	//Add the loading image to the search bar
	AddLoadingImage();

	$.ajax({
		type:		"GET",
		url:		"/ajax/features.php",
		dataType:	"json",
		data:		serialized_data + "&use_active_tab=" + use_active_tab + "&active_tab="+GetActiveTabId(),
		ifModified:	true,
		success:	function(obj) {
						if(obj.do_not_create == 1) {
							SetActiveTab(obj.switch_tab_id);

							//Take off the loading image.
							previous_search_complete = true;
							RemoveLoadingImage();
						} else {
							CreateTab(obj);
						}
					}
	});
}


// #################################################
// LUCKYDAY FUNCTIONS
// #################################################

// PRIZE ITEM FUNCTIONS
// #################################################
function ShowPrizeForm(id) {
	var id_obj = $('#'+id);
	if( $(id_obj).css('display') == 'none' ) {
		$(id_obj).show().slideDown();
	}
}

// #################################################
function ShowPrizeForm2(id) {
	$.ajax({
		type:		"GET",
		url:		"/ajax/sp_money.php",
		dataType:	"html",
		data:		"id="+id,
		success:	function(html) {
					}
	});
}

// #################################################
function ClaimPrizeItem(id) {
	var error_obj = $('#error_'+id);
	$(error_obj).html(""); // Clear out any pre-existing errors.

	var remember_info = "0";

	var errors = new Array();
	var hash = new Array();

	$('#'+id+' :input').each(function(i) {
		if( $(this).attr('name') == 'remember') {
			 if( $(this).attr('checked') == true ) {
				remember_info = "1";
			 }
		} else {
			// Get all fields. Do error checking next.
			hash[$(this).attr('name')] = $(this).val();
		}
	});

	// We have our data... perform error checking on it.
	// Error checking.
	if(hash['name'].length < 1) {
		errors.push("Please enter full name.");
	}

	if(hash['address'].length < 1) {
		errors.push("Please enter shipping address.");
	}

	if(hash['city'].length < 1) {
		errors.push("Please enter your city.");
	}

	if(hash['state'].length < 1) {
		errors.push("Please enter your state.");
	}

	if(hash['country'].length < 1) {
		errors.push("Please enter your country.");
	}

	if(hash['zip'].length < 1) {
		errors.push("Please enter your zip.");
	}

	if(hash['phone'].length < 1) {
		errors.push("Please enter your phone.");
	}

	// Any errors?
	if(errors.length > 0) {
		$(error_obj).html( errors.join("<br>\n") );
	} else {
		var query_string = "action=claim_prize&remember_info="+remember_info;

		$('#'+id+' :input').each(function(i) {
			query_string += "&"+$(this).attr("name")+"="+encodeURIComponent($(this).val());
		});

		var tab_id = GetActiveTabId();
		var link_obj = $('#link_'+id);

		$.ajax({
			type:		"GET",
			url:		"/ajax/claim_prize_item.php?"+query_string+"&tab_id="+tab_id,
			dataType:	"html",
			success:	function(html) {
				$(link_obj).html(html); // set the html for it.
				$('#'+id).html(""); // remove the html for the form.
				var tmp = html.split("|", 3);
				var claims_today = tmp[0];
				var claims_limit = tmp[1];
				var new_html = tmp[2];
				if(claims_today && claims_limit && new_html) {
					$(link_obj).html(new_html); // set the html for it.
					$('span.items_claimed').html('<!--claims_today_start-->' + claims_today + '<!--claims_today_end-->/' + claims_limit + ' Claimed'); // Update ALL tabs with the new claims information.
				} else {
					$(link_obj).html(html); // set the html for it.
				}

				var sponsors_html = $('#tabfeatures_'+tab_id).html();
				$.ajax({
					type:		"POST",
					url:		"/ajax/update_sponsor.php",
					data:		{
									'tab_id':	tab_id,
									'html':		encodeURIComponent(sponsors_html)
								},
					dataType:	"html",
					success:	function(html) {
								}
					});
			}
		});
	}
}


// MONEY ITEM FUNCTIONS
// #################################################
function ShowMoneyForm(id) {
	var link_obj = $('#link_'+id);
	var id_obj = $('#'+id);

	// See if they have already activated qbank.
	if( $('#response_'+id).html() == id) {
		var tab_id = GetActiveTabId();
		$.ajax({
			type:		"GET",
			url:		"/ajax/claim_money_item.php",
			dataType:	"html",
			data:		"key="+id+"&item_id="+$('#'+tab_id+'_item_id').val()+"&tab_id="+tab_id,
			ifModified:	true,
			success:	function(html) {
							var tmp = html.split("|", 3);
							var claims_today = tmp[0];
							var claims_limit = tmp[1];
							var new_html = tmp[2];
							if(claims_today && claims_limit && new_html) {
								$(link_obj).html(new_html); // set the html for it.
								$('span.items_claimed').html('<!--claims_today_start-->' + claims_today + '<!--claims_today_end-->/' + claims_limit + ' Claimed'); // Update ALL tabs with the new claims information.
							} else {
								$(link_obj).html(html); // set the html for it.
							}



							var sponsors_html = $('#tabfeatures_'+tab_id).html();
							console.log(sponsors_html);
							$.ajax({
								type:		"POST",
								url:		"/ajax/update_sponsor.php",
								data:		{
												'tab_id':	tab_id,
												'html':		encodeURIComponent(sponsors_html)
											},
								dataType:	"html",
								success:	function(html) {
											}
							});
						}
		});
	// Else, qbank was not activated yet.
	} else {
		if( $(id_obj).css('display') == 'none' ) {
			$(id_obj).show().slideDown();
		}
	}
}


// #################################################
function SettingsPanel_ActivateQBank() {
	var obj = HashForm('settings_panel_activate_qbank');
	var errors = new Array();
	var qbank_errors_obj = $('#settings_panel_activate_qbank_errors');

	// Paypal email exist?
	if(obj.data['paypal_email'].length < 1) {
		errors.push('Please enter your Paypal email address.');
	}

	// Do passwords match?
	if(obj.data['password'] != obj.data['confirm_password']) {
		// Do not match.
		errors.push('Your passwords do not match.');
	}

	if(obj.data['password'].length < 1 && obj.data['confirm_password'].length < 1) {
		errors.push('Please enter a QBank password.');
	}

	if(errors.length > 0) {
		// Errors exist.
		$(qbank_errors_obj).html( errors.join("<br/>\n") + "<br/>" );
		return false;
	}

	// Else, all is OK! Fire off an Ajax call.
	$.ajax({
		type:		"POST",
		url:		"/ajax/settings_panel_activate_qbank.php",
		dataType:	"html",
		data:		obj.query_string,
		success:	function(data) {
			if(data=='success') {
				TwerqSettingsPanel(3);
			} else {
				$(qbank_errors_obj).html(data + "<br/>");
			}
		}
	});
}


// #################################################
function ActivateQBank(id) {
	var error_obj = $('#error_'+id);
	$(error_obj).html("");

	var hash = new Array();

	$('#'+id+' :input').each(function(i) {
		hash[$(this).attr("name")] = $(this).val();
	});

	var errors = new Array();
	if(hash['paypal_email'].length < 1) {
		errors.push("Please enter Paypal email.");
	}

	if((hash['password'].length > 0 || hash['confirm_password'].length > 0) && (hash['password'] != hash['confirm_password'])) {
		errors.push("Your passwords do not match.");
	}

	if(hash['password'].length < 1 && hash['confirm_password'].length < 1) {
		errors.push("Please enter a password.");
	}

	if(errors.length > 0) {
		$('#error_'+id).html( errors.join("<br>\n") );
	} else {
		var query_string = "action=activate_qbank";
		$('#'+id+' :input').each(function(i) {
			query_string += "&"+$(this).attr("name")+"="+encodeURIComponent($(this).val());
		});

		var tab_id = GetActiveTabId();

		$.ajax({
			type:		"GET",
			url:		"/ajax/activate_qbank.php",
			dataType:	"html",
			data:		query_string+"&tab_id="+tab_id,
			ifModified:	true,
			success:	function(html) {
							// Was there an error?
							if(html.substr(0,2) == 'E:') {
								// Yes.
								var error = html.substr(2, html.length - 2);
								$('#error_'+id).html(error);
								return false;
							}

							$('#link_'+id).html(html);
							$('#'+id).html("");

							var sponsors_html = $('#tabfeatures_'+tab_id).html();
							$.ajax({
								type:		"POST",
								url:		"/ajax/update_sponsor.php",
								data:		{
												'tab_id':	tab_id,
												'html':		encodeURIComponent(sponsors_html)
											},
								dataType:	"html",
								success:	function(html) {

											}
							});
						}
		});
	}
}

// #################################################
// END LUCKYDAY FUNCTIONS
// #################################################






// #################################################
// TWERQ2GO FUNCTIONS
// #################################################

// #################################################
function SaveSearch() {
	// See if the Open/Save Search Results (TWERQ2GO Search Results) tab is already open.
	var tab_open = false;
	var tab_id = 0;
	var active_tab_id = '';

	var open_save_tab = $('#tabs li[@title=Open/Save]');
	if(open_save_tab) {
		if(open_save_tab.length) {
			tab_open = true;
			var tmp_array = $(open_save_tab).attr('id').split("_", 2);
			tab_id = tmp_array[1];
		}
	};

	if(tab_open) {
		// Need to use this tab_id...
		active_tab_id = tab_id;
	}

	// Iterate through the tabs.
	var tab_string = "";
	$('#tabs>li>a').each(function(i) {
		tab_string += $(this).attr('id') +"="+ $(this).parent().attr('title')+"&";
	});

	var selected_id = GetActiveTabId();

	//Add the loading image to the search bar
	AddLoadingImage();

	// Use active_tab_id
	if(active_tab_id.length > 0) {
		SetActiveTab(active_tab_id);
		$.ajax({
			data:		"tab_id="+selected_id+"&" + tab_string+"&active_tab_id="+active_tab_id,
			dataType:	"json",
			type:		"GET",
			url:		"/ajax/save_search.php",
			success:	function(obj) {
							CreateTab(obj);
							InitializeSavedSearch();
						}
		});
	// Else, don't use active_tab_id
	} else {
		$.ajax({
			data:		"tab_id="+selected_id+"&" + tab_string,
			dataType:	"json",
			type:		"GET",
			url:		"/ajax/save_search.php",
			success:	function(obj) {
							CreateTab(obj);
							InitializeSavedSearch();
						}
		});
	}
}

// #################################################
function InitializeSavedSearch() {
	var divs = $('div.saved_search_active_searches');
	$(divs).unbind('mouseover').bind('mouseover', SavedSearchMouseOver);
	$(divs).unbind('mouseout').bind('mouseout', SavedSearchMouseOut);

//	alert('after divs');

	var groups = $('div.saved_search_existing_groups');
	$(groups).unbind('mouseover').bind('mouseover', ExistingGroupsMouseOver);
	$(groups).unbind('mouseout').bind('mouseout', ExistingGroupsMouseOut);

//	alert('after groups');

	var subgroups = $('div.subgroup');
	$(subgroups).unbind('mouseover').bind('mouseover', SubGroupMouseOver);
	$(subgroups).unbind('mouseout').bind('mouseout', SubGroupMouseOut);

//	alert('after sub groups');
}

// #################################################
function SavedSearchMouseOver() {
	$(this).addClass('saved_search_over');
	$('img.active_search_x', this).css('visibility','visible');
}

// #################################################
function SavedSearchMouseOut() {
	$(this).removeClass('saved_search_over');
	$('img.active_search_x', this).css('visibility','hidden');
}

// #################################################
function ExistingGroupsMouseOver() {
	$(this).addClass('saved_search_existing_groups_over');
	$('img.existing_groups_x', this).css('visibility','visible');
	$('a.existing_groups_create_quicktag', this).css('visibility','visible');
}

// #################################################
function ExistingGroupsMouseOut() {
	$(this).removeClass('saved_search_existing_groups_over');
	$('img.existing_groups_x', this).css('visibility','hidden');
	$('a.existing_groups_create_quicktag', this).css('visibility','hidden');
}

// #################################################
function SubGroupMouseOver() {
	$(this).addClass('subgroup_over');
	$('img.subgroup_x', this).css('visibility','visible');
}

// #################################################
function SubGroupMouseOut() {
	$(this).removeClass('subgroup_over');
	$('img.subgroup_x', this).css('visibility','hidden');
}

// #################################################
function RemoveActiveSearch(tab_id,id) {
	$('#'+id).remove();
	CloseTab(tab_id, 1);
}

// #################################################
function RemoveGroup(group_id,div_id) {
	$.ajax({
		type:		"GET",
		url:		"/ajax/remove_group.php",
		dataType:	"html",
		data:		"group_id="+group_id,
		success:	function(data) {
			$('#'+div_id).html("");
			$('li#'+div_id).remove();
		}
	});
}

// #################################################
function RemoveSavedSearch(search_id,div_id) {
	$.ajax({
		type:		"GET",
		url:		"/ajax/remove_saved_search.php",
		dataType:	"html",
		data:		"search_id="+search_id,
		success:	function(data) {
			$('#'+div_id).remove();
		}
	});
}
// #################################################
function TWERQ2GOAddToGroup() {
	$('#form_action').val('add_to_group');
	document.twerq2go_form.submit();
}

// #################################################
function TWERQ2GOSaveSelected() {
	$('#form_action').val('save_selected');
	document.twerq2go_form.submit();
}

// #################################################
function TWERQ2GOSearch() {
	var search_string = "action=generate_search_string";

	// Active Searches
	$('#twerq2go_form input:checkbox.active_searches').each(function(i) {
		if($(this).attr('checked') == true) {
			// FORMAT: Tab ID|Search Term
			var tmp_array = $(this).val().split("|", 2);
			tab_id = tmp_array[0];
			search_term = tmp_array[1];

			if(search_term.toLowerCase() == 'twerq settings panel') {
				TwerqSettingsPanel(0);
			} else {
				search_string += "&tab_ids[]="+tab_id;
			}
		}
	});

	// Groups
	$('#existing_groups input:checkbox.group_checkbox').each(function(i) {
		if($(this).attr('checked') == true) {
			// FORMAT: Group ID|Group Name
			var tmp_array = $(this).val().split("|", 2);
			var group_id = tmp_array[0];
			var group_name = tmp_array[1];

			search_string += "&groups[]="+group_id;
		}
	});

	// Saved Searches WITHIN Groups
	$('#existing_groups input:checkbox.saved_searches_checkbox').each(function(i) {
		if($(this).attr('checked') == true) {
			// FORMAT: saved_searches ID|Group ID|saved_searches keyword
			var tmp_array = $(this).val().split("|", 3);
			var saved_searches_id = tmp_array[0];
			var group_id = tmp_array[1];
			var saved_searches_keyword = tmp_array[2];

			if(saved_searches_keyword.toLowerCase() == 'twerq settings panel') {
				TwerqSettingsPanel(0);
			} else {
				search_string += "&saved_searches[]="+saved_searches_id;
			}
		}
	});

	// Fire off an Ajax call to get back the query string to use via OpenTabs(...).
	$.ajax({
		type:		"GET",
		url:		"/ajax/generate_search_string.php",
		dataType:	"json",
		data:		search_string,
		success:	function(obj) {
			if(obj.data.length > 0) {
				OpenTabs(obj);
			}
		}
	});
}

// #################################################
function OpenGroup(group_id) {
	var search_string = "action=generate_search_string";

	// Groups
	$('#group_'+group_id+' input:checkbox').each(function(i) {
		// FORMAT: Group ID|Group Name
		var tmp_array = $(this).val().split("|", 2);
		var group_id = tmp_array[0];
		var group_name = tmp_array[1];

		search_string += "&groups[]="+group_id;
	});

	// Fire off an Ajax call to get back the query string to use via OpenTabs(...).
	$.ajax({
		type:		"GET",
		url:		"/ajax/generate_search_string.php",
		dataType:	"json",
		data:		search_string,
		success:	function(obj) {
			if(obj.data.length > 0 || obj.has_settings_panel == 1) {
				OpenTabs(obj);
			}
		}
	});
}

// #################################################
function OpenTabs(obj) {
	var search_term = obj.data;

	if(search_term.length < 1) { return false; }

	// Serialize data.
	serialized_data = GetSerializedTabs();


	// See if the previous search is complete. If it's not, do not process another one yet. Causes conflicts.
	if(!previous_search_complete) { return false; }

	//Add the loading image to the search bar
	AddLoadingImage();

	//Do we need to open the settings panel?
	if(obj.has_settings_panel == 1) {
		TwerqSettingsPanel(0);
	}

	//Add the loading image to the search bar
	AddLoadingImage();

	var use_active_tab = 0;

	previous_search_complete = false;

	$.ajax({
		type:		"POST",
		url:		"ajax/search.php",
		dataType:	"json",
		data:		serialized_data + "search_term=" + encodeURIComponent(search_term) + "&use_active_tab=" + use_active_tab + "&active_tab="+GetActiveTabId(),
		ifModified:	true,
		success:	function(tab_obj) {
						CreateTab(tab_obj);
					}
	});
}
// #################################################
// END TWERQ2GO FUNCTIONS
// #################################################


// #################################################
function SubmitRSS(quick_term) {
	// HIVE
	// Is there an active hive on this tab, or is this tab related to other hive's? Need an array of hive id's.
	var hive_id_url = GetHiveIDUrlParams();

	// Get title.
	var title = encodeURIComponent(quick_term);

	// Get search term.
	var search_term = encodeURIComponent(quick_term) + '))';
	// END HIVE

	quick_term = quick_term + '))';

	// Serialize data.
	serialized_data = GetSerializedTabs();

	// See if the previous search is complete. If it's not, do not process another one yet. Causes conflicts.
	if(!previous_search_complete) { return false; }

	previous_search_complete = false;

	// Use active tab or not? If they want to use active tab, at least 1 tab must be open.
	var use_active_tab = 0;
	if($('#create_new_tab').is(':checked') == false && GetActiveTabId()) {
		use_active_tab = 1;
	}

	//Add the loading image to the search bar
	AddLoadingImage();

	$.ajax({
		type:		"POST",
		url:		"ajax/search.php",
		dataType:	"json",
		data:		serialized_data + "search_term=" + quick_term + "&rss_click=1&use_active_tab=" + use_active_tab + "&active_tab="+GetActiveTabId() + hive_id_url,
		ifModified:	true,
		success:	function(obj) { CreateTab(obj, 'title='+title+'&search_term='+search_term+hive_id_url); }
	});

	return false; // return false so no submit actually happens.
}

// #################################################
function RefreshRSS(quick_term,page_num) {
	quick_term = quick_term + '))';
	// Serialize data.
	serialized_data = GetSerializedTabs();

	// See if the previous search is complete. If it's not, do not process another one yet. Causes conflicts.
	if(!previous_search_complete) { return false; }

	previous_search_complete = false;

	// Use active tab or not? If they want to use active tab, at least 1 tab must be open.
	var use_active_tab = 1;

	//Add the loading image to the search bar
	AddLoadingImage();

	$.ajax({
		type:		"POST",
		url:		"ajax/search.php",
		dataType:	"json",
		data:		serialized_data + "search_term=" + quick_term + "&use_active_tab=" + use_active_tab + "&active_tab="+GetActiveTabId() + '&page_number=' + page_num,
		ifModified:	true,
		success:	function(obj) { CreateTab(obj); }
	});

	return false; // return false so no submit actually happens.
}

// #################################################
function RevisedSearch(quick_term,search_engine) {

    if (search_engine){ search_engine = 'e:'+search_engine+':'; }

	// Serialize data.
	serialized_data = GetSerializedTabs();

	// See if the previous search is complete. If it's not, do not process another one yet. Causes conflicts.
	if(!previous_search_complete) { return false; }

	previous_search_complete = false;

	// Use active tab or not? If they want to use active tab, at least 1 tab must be open.
	var use_active_tab = 0;
	if($('#create_new_tab').is(':checked') == false && GetActiveTabId()) {
		use_active_tab = 0;//1;
	}

	//Add the loading image to the search bar
	AddLoadingImage();

    //window.alert(search_engine + quick_term);

	$.ajax({
		type:		"POST",
		url:		"ajax/search.php",
		dataType:	"json",
		data:		serialized_data + "search_term=" + search_engine + quick_term + "&use_active_tab=0&active_tab="+GetActiveTabId(),
		ifModified:	true,
		success:	function(obj) { CreateTab(obj); }
	});

	return false; // return false so no submit actually happens.
}

// #################################################
function CreateTab(obj,hive_id_url) {
	$('#tabs').css('display','block');
	$('#tab_area').css('display','block');
	var tabs_object = $('#tabs');
	var container = $('#container');

	if(container) {
		if(container.width() > 0) {
//			alert("got here.. container.width()="+container.width());
			tabs_object.css('width', container.width() + 'px');
		}
	} else {
//		alert("got here.. 100");
		tabs_object.css('width','100');//width(100);
	}


	// Regardless of what we are doing... we need to check for a past_searches property (array).
	// If it exists.. we need to re-populate our past_searches array with the new data.
	if(typeof obj.past_searches == 'object') {
		// Ok. It does exist. Do we have data within it?
		if(obj.past_searches.length > 0) {
			// We sure do. Now.. lets populate our global past_searches array.
			SearchHistory.init(obj.past_searches);
		}
	}
	// IMPORTANT... do we need to create multiple tabs??
	//Are we in the index.html file? If not, re-direct immediately
	var loc = ""+window.location;
	if(loc.search("index.html") == -1) {
		window.location = "/index.html";
	}

	// Is this a quicktag that was entered.. and if it was, is it a URL?
	if(obj.is_url) {
		if(open_result_links_new_window == false) {
			window.location = obj.url;
		} else {
			window.open(obj.url, "quicktag_window");
		}

		previous_search_complete = true; // Set flag to true because this search is complete.

		//Take off the loading image.
		RemoveLoadingImage();
		return;
	}

	if(obj.do_not_create != 1 && ! obj.previous_tab_id > 0) { //If this is 1, we're purposesly not creating a tab.
		Hive.groups = [];
		if(CountTabs() > 0) {
//			if(obj["Hive.groups"]) {
				Hive.groups = obj["Hive.groups"];
				Hive.active_hives = obj["Hive.active_hives"];
//			}
		}

// #################################################
// #################################################
// #################################################
		// update the comb data for the Hive
		if(obj.multiple_tabs == 1) {
			var master_tab_content = "";
			var master_section_content = "";

			// Iterate through the tabs.. creating a new tab for each one.
			var tab_content = "";
			for(i = 0; i < obj.total_tabs; i++) {
				if(obj.tabs[i].search_term) {
					$(tabs_object).append(obj.tabs[i].tab_content); // Create the tab since the section is available now.
					$('#container').append(obj.tabs[i].section_content); // Create the section first.
//					$('li.tabitem', tabs_object).show();

					// Tab coloring for hive tabs.
					if(obj.is_hive == 0) {
						$('li:last', tabs_object).removeClass('hive-tabs-selected');
					}

					if(enable_drag_drop_tabs == 1) {
						$(tabs_object).SortableAddItem($('#tabs li:last').get(0));
					}
				}
			} // end of for loop.

//			$('li.tabitem', tabs_object).css({'width': window.carousel_item_width, 'display': 'block'});

			// Re-create the "tabs" functionality.
			$.tabs("container");

			// Get active tab id.. and then hide that "section" for that tab.
			if(!Hive.groups) {
					Hive.groups = [];
			}

			Hive.init();
			Hive.colourTabs();
			Hive.SetResultClickHandlers();
// #################################################
// #################################################
// #################################################

		} else {
			var new_section_obj = $('#section_'+obj.new_tab);

			// IMPORTANT... do not have multiple tabs. Proceed as usual.
			// Do we need to use the active tab or create a new tab?
			if(obj.use_active_tab == 1 && obj.active_tab && $('#tab_'+obj.active_tab).html()) {
				// USE ACTIVE TAB
				if(obj.search_term) {
					var section_obj = $('#section_'+obj.active_tab);
					var tab_obj = $('#tab_'+obj.active_tab);

					// Replace active tab's content.
					section_obj.html(obj.section_content);
					tab_obj.html(obj.tab_content);
					//Set the title.  Prevents a bug where clicking off the newly changed acive tab reverted it to the original.
					tab_obj.attr('title',obj.search_term);
				}

			} else {
				// CREATE A NEW TAB
				if(obj.search_term) {
					// Append the data returned inside the object to the actual page.
					// Container is first. This is the DIV. JSON: obj.section_content
					$('#container').append(obj.section_content);

					// Next, add the tab. JSON: obj.tab_content
					$(tabs_object)
						.append(obj.tab_content);

					if(enable_drag_drop_tabs == 1)
						$(tabs_object).SortableAddItem($('#tabs li:last').get(0));

					if(!Hive.groups) {
						Hive.groups = [];
					}

					Hive.init();
					Hive.colourTabs();

					//Reset the tabs.
					$.tabs("container");

					// Remove the 'selected' class for the active tab... and then mark the new one selected & display that new selected tab's "section".
					$('#section_'+obj.new_tab).show();
				}

			}
			Hive.InitializeTabs(GetActiveTabId());

			if(hive_id_url) {
				// This tab needs to show the feedback bar.
				new_section_obj.find('div.feedback_bar').show();
				new_section_obj.find('div.feedback_bar').find('.rss_hiveid').val(hive_id_url);
			}
		}
	} //end of outer most if

	if(obj.previous_tab_id > 0) {
		SetActiveTab(obj.previous_tab_id,true);
	} else {
//		InitializeCarousel(); //Add this to the ride :) // This will be handled in the ShrinkTabs() call below.
		SetActiveTab(obj.new_tab,false);
	}

	previous_search_complete = true; // Set flag to true because this search is complete.

	//Do we need to open the settings panel?
	if(obj.has_settings_panel == 1) {
		TwerqSettingsPanel(0);
	}

	//Take off the loading image.
	RemoveLoadingImage();

//	AddTabClickHandlers(); // called via LoadEventHandlers()
//	AddCloseButtonHandlers(); // called via LoadEventHandlers()
	Hive.attachPanelEvents();
	Hive.addDropDowns();
	Hive.SetResultClickHandlers();

	// Tab coloring for hive tabs.
	var tab_obj = "";
	if(obj.previous_tab_id > 0) {
		tab_obj = $('#tab_'+obj.previous_tab_id);
	} else {
		tab_obj = $('#tab_'+obj.new_tab);
	}


	var tab_title = $(tab_obj).attr('title');
	var tab_trigger = tab_title.substring(0,2).toLowerCase();

	if(obj.is_hive == 0 && tab_trigger == 'h:') {
//		$('#tabs li:last').removeClass('hive-tabs-selected');
	}

	if($('#quicktags_table').html()) {
		$.get("/ajax/refresh_settings_quicktag.php", function(html) {
			$('#quicktags_table').html(html);
			Hive.addDropDowns();
			SetupQuicktagsSorting();
		});
	}

	// Do we have new content to add to the TWERQ2GO Search Results (saved searches) tab? PHP checks if the tab is open or not already.
	if(obj.active_searches_html) {
		$('div#div_active_searches').replace(obj.active_searches_html);
	}

//	InitializeSavedSearch(); // called via LoadEventHandlers()
	Hive.InitializeTabs(GetActiveTabId());
//	SetTipLinks(); // called via InitializeTwerqTips, which is called via LoadEventHandlers()
	InitializeLockTab();
	LoadEventHandlers();

//	if(CountTabs() > GetItemsVisible()) {
		ShrinkTabs();
//	}
//	InitializeTwerqTips(); // called via LoadEventHandlers()
//	InitializeSponsorPaging(); // called via LoadEventHandlers()
}

// #################################################
function AlterTab(obj) {
	var tab_obj = $('#tab_'+obj.active_tab);

	//This updates a tab in the background.
	if(obj.use_active_tab == 1 && obj.active_tab && $('#tab_'+obj.active_tab).html()) {
		// Replace the tab's content.
		$('#section_'+obj.active_tab).html(obj.section_content);
		tab_obj.html(obj.tab_content);

		//Set the title.  Prevents a bug where clicking off the newly changed acive tab reverted it to the original.
		tab_obj.attr('title',obj.search_term);
	}


	previous_search_complete = true; // Set flag to true because this search is complete.

	if(obj.make_active != 'false' && obj.make_active != false) {
		SetActiveTab(obj.active_tab,false);
	}

	AddTabClickHandlers();
	AddCloseButtonHandlers();
	Hive.InitializeTabs(GetActiveTabId());
	LoadEventHandlers();

	//Take off the loading image.
	RemoveLoadingImage();
}

// #################################################
function ReachEnd() {
	//Calculate the tab we need to reach.
	var end_tab = (CountTabs() - max_tabs)+2;
	var counter = 0;

	$('#tabs li.tabitem').each( function(i) {
		//Increment counter.
		counter++;

		if(counter < end_tab) {
			$(this).css('display','none');
		} else {
			$(this).css('display', 'block');
		}
	});
}

// #################################################
function CloseAllTabs() {
	var current_tab = "";
	var search_term_obj = $(window.global_search_term);

	$.ajax({
		type:		"GET",
		url:		"/ajax/close_all_tabs.php",
		dataType:	"json",
		success:	function(obj) {

						if(obj.length == 0) {
							//We're closing all tabs, if they don't have landing page disabled send them there.
							if(disable_landing_page == false) {
								window.location = "/";
								return false;
							}


							$('#tabs').css('display','none');

							$('#tabs > .tabitem, #container > .fragment').remove();
							current_active_tab = 0;

							SaveActiveTab();
							$(search_term_obj).val("");
							$(search_term_obj).focus();

							// Hide scroll arrows.
							$('#previous_tab_page,#next_tab_page').hide();
							$('div.jcarousel-clip').hide(); // this caused a spacing issue when u closed all tabs and had no tabs left.
							ShrinkTabs();
						} else {
							//Go through the tabs and remove each tab not in the array
							$('#tabs li.tabitem').each(function() {
								var id = this.id.split("_")[1];
								var locked = false;

								$.each(obj, function(i, locked_tab_id){
									if (locked_tab_id == id)
										locked = true;
								});

								// don't close locked tabs
								if (locked) return;

								// Remove the tab's "section".
								$('#section_'+id).remove();
								// Remove the tab next.
								$('#tab_'+id).remove();
								// Shift the leftmost hidden tab over.
								$('#tab_'+left_hidden_tab).show();
							});

							// fix weird Firefox bug that prevents right-click more than once
							$('div.map0').each(function(){
							  $(this).parent().append($(this).remove());
							});
						}

						// Remove the 'selected' class for the active tab... and then mark the new one selected & display that new selected tab's "section".
						$('#container>ul>li').removeClass('tabs-selected');

						var selected_id = $('#tabs li:last').attr('id').split("_")[1];

						SetActiveTab(selected_id);
						current_active_tab = selected_id;
						Hive.addDropDowns();

						// Hide scroll arrows.
						$('#previous_tab_page,#next_tab_page').hide();
						ShrinkTabs();
					}
	});
}

// #################################################
function CloseTab(tab_id, update_saved_searches) {
	var this_active_tab = GetActiveTabId();

	if(tab_id) {
		this_active_tab = tab_id;
	}

	// don't close locked tabs (oddly 'tab_unlocked' means the tab is locked)
	if ($('#lock_tab_'+this_active_tab).is('.tab_locked')) return;

	// if there is only one tab, then we are closing all tabs
	var is_last_tab = false;
	if ($('#tabs li.tabitem').length == 1) {
//		CloseAllTabs();
//		return false;
		is_last_tab = true;
	}


	// Need to remove the section_# area and the actual tab itself. Then post to an Ajax script with the updated tabs list/order.
	var selected_id = this_active_tab;

	if(!selected_id) { return; } // No tab to close!

	$.get("/ajax/close_tab.php", "tab_id="+selected_id,
			function(msg) {
				if(update_saved_searches) {
					$.ajax({
						type:		"GET",
						url:		"/ajax/update_saved_searches.php"
					});
				}

				//If they have not disabled the landing page, send them there if that was the last tab.
				if(!msg.length) { msg = selected_id; }

				// Was this the last tab? // THIS WAS ADDED BY MIKE. DO NOT MODIFY.
				if(is_last_tab) {
//					$('#tabs').css('display','none');
//					$('#tab_area').css('display','none');

					$(window.global_search_term).val('');
					if(disable_landing_page == false) {
						window.location = "/splash.html";
						return false;
					}
				}

				// Lets see if the Open/Save tab is open.
				var open_save = $('#tabs li[@title=Open/Save]');
				if($(open_save).html()) {
					// Yes. It's open.
					var this_tab_id = selected_id;
					var this_search_term = $('#tab_'+selected_id).attr('title');

					// EXAMPLE: <input type="checkbox" value="8|b" class="active_searches" name="active_searches[]"/>
					var this_value = this_tab_id+'|'+this_search_term;
					var this_input = $('input.active_searches[@value="'+this_value+'"]');

					if($(this_input).val()) {
						// It exists within the Open/Save tab. We need to remove it.
						$(this_input).parent().parent().parent().remove();
					}
				}

				// msg contains the tab id to be used.
				// Remove the tab's "section".
				$('#section_'+selected_id).remove();

				// Remove the tab next.
				$('#tab_'+selected_id).remove();

				// Make sure tab id 'msg' exists..
				if(!$('#tab_'+msg).html()) {
					// Get the very first tab ID.
					var first_tab = $('#tabs li:first').attr('id').split("_")[1];
					msg = first_tab;
				}
				SetActiveTab(msg);

				InitializeCarousel(msg); //Remove this to the ride :)
				window.carousel_obj.scroll(GetTabIndex(msg));

				current_active_tab = 0;
				Hive.addDropDowns();
	});
}

// #################################################
function SetActiveTab(tab_id,update_hive) {
	if(!$('#tab_'+tab_id).html()) { // If this tab does not exist... look for the very first tab.
		$("#container").tabs();
		var selected_id = GetActiveTabId();
		$('#section_'+selected_id).show();

		return;
	}

	var section_obj = $('#section_'+tab_id);
	var tab_obj = $('#tab_'+tab_id);

	$.tabs("container");

	// hide all sections, then show the new active section
	$('#container > div.fragment').hide();
	section_obj.show();

	// remove the class 'hive-tabs-selected' for this tab.
//	tab_obj.removeClass('hive-tabs-selected');

	var selecttab = tab_obj;
	var alltabs = $("#tabs li.tabitem");

	// Is this tab an active hive tab?
	var hive_tabs = $('#hive_tabs_'+tab_id);

	// Remove the 'selected' class for the active tab... and then mark the new one selected & display that new selected tab's "section".
	alltabs.removeClass('tabs-selected');
	alltabs.removeClass('hive-tabs-selected');
//	alltabs.removeClass('rss-tabs-selected');
	selecttab.addClass('tabs-selected');

	Hive.colourTabs();

	var tab_title = $(tab_obj).attr('title');
	var tab_trigger = tab_title.substring(0,2).toLowerCase();

	if( hive_tabs.length || tab_trigger == 'h:' ) {
		// Yes.
		$(tab_obj).addClass('hive-tabs-selected');
	}

	// Is this an RSS tab? If so, use class: .rss-tabs-selected
/*
	tab_trigger = tab_title.substring(0,3).toLowerCase(); // Updated to pull the first THREE characters instead of 2.
	if( tab_trigger == triggers['rss_feed'] ) {
		$(tab_obj).addClass('rss-tabs-selected');
	}
*/

	// Ok, lets check the LAST two characters.
/*
	tab_trigger = tab_title.substring(tab_title.length - 2).toLowerCase();
	if( tab_trigger == triggers['tabbed_rss_feed'] ) {
		$(tab_obj).addClass('rss-tabs-selected');
	}
*/

	// if tab is not visible, we need to 'scroll' to it
	if (!selecttab.is(':visible')) {
		// count how many visible tabs there are supposed to be
		var num_visible = alltabs.filter(':visible').length;

		// find out where in the tab list the selected tab is
		var tab_index = alltabs.index(selecttab.get(0));

		// find the left and right hidden cut-off indexes (but default to 0 and 9999 if not found)
		var left_hidden_index = Math.max(0, alltabs.index($('#tab_' + left_hidden_tab).get(0)));
		var right_hidden_index = Math.min(9999, alltabs.index($('#tab_' + right_hidden_tab).get(0)));

		var left, right;

		// if hidden on the left, it will be the new leftmost
		if (tab_index <= left_hidden_index) {
			left = tab_index;
			right = tab_index + num_visible - 1;

		// if hidden on the right, it will be the new rightmost
		} else if (tab_index >= right_hidden_index) {
			left = tab_index - num_visible + 1;
			right = tab_index;

		}
	}

	current_active_tab = tab_id;

	// See if this tab's section has a hive panel.
	var panel = $('#section_'+tab_id+' div.hive-panel');
	if(panel.length > 0) {
		// Yes it does.
		var search_term = $('#tab_'+tab_id).attr('title');
		$(window.global_search_term).val(search_term);
	}

	SaveActiveTab(update_hive);
}

// #################################################
function CountTabs() {
	return $("#tabs li.tabitem").length;
}

// #################################################
function GetSerializedTabs() {
	var tabs = '';
	$('#tabs li').each(function() {
		tabs += 'tabs[]=' + this.id + '&';
	});
	return tabs;
}

// #################################################
function GetActiveTabId() {
	var selected_tab = $('#tabs li.tabs-selected');

	if (!selected_tab.length) {
		//Check for a hive tab before we give up.
		selected_tab = $('#tabs li.hive-tabs-selected');
	}

	if (!selected_tab.length) {
		return false; // No more tabs open!
	}

	var selected_id = selected_tab.attr('id');

//	alert("selected id="+selected_id); // tab_# is returned
	var id_array = selected_id.split("_");
	selected_id = id_array[1];

	current_active_tab = selected_id;

	selected_tab = null;
	return selected_id;
}

// #################################################
function SaveActiveTab(update_hive) {
//	return; // TEST BY MIKE
	// Get the active tab ID.
	var tab_id = current_active_tab;
	if(!tab_id) {
		tab_id = GetActiveTabId();
	}

	if(!tab_id) {
		tab_id = 0;
		current_active_tab = 0;
		return false;
	}

	$.ajax({
		type:		"GET",
		url:		"/ajax/save_active_tab.php",
		data:		"tab_id="+tab_id,
		success:	function(msg) {
			if(update_hive) {
				if(HaveActiveHive()) {
					UpdateAllHivePanels();
				}
			}
		}
	});

	// onclick handlers for 1st image map (close tab)
	AddCloseButtonHandlers();

	// See if the current tab has a hive panel. If it DOES, it's not an internal area.
	var panel = $('#section_'+tab_id+' div.hive-panel');
	var is_shortlist = false;

	var tab_obj = $('#tab_'+tab_id);
	var search_term_obj = $(window.global_search_term);

	var shortlist_trigger = triggers['shortlist'];
	if($(tab_obj).attr('title').substr(0, shortlist_trigger.length) == shortlist_trigger) {
		is_shortlist = true;
	}

	if(panel.length > 0 || is_shortlist) {
		$(search_term_obj)
			.val( $(tab_obj).attr('title') )
			.each(function(){
				if (this.disabled) return;
				this.focus();
				this.select();
				$(this).attr('unedited', 'true');
			});
	} else {
		$(search_term_obj)
			.val('')
			.each(function(){
				if (this.disabled) return;
				this.focus();
				this.select();
				$(this).attr('unedited', 'true');
			});
	}
}

// #################################################
function TwerqSettingsPanel(template) {
	// Serialize the tabs for use of generating new tab id.
	serialized_data = GetSerializedTabs();

	// See if the previous search is complete. If it's not, do not process another one yet. Causes conflicts.
	if(!previous_search_complete) { return false; }

	previous_search_complete = false;

	// Use active tab or not? If they want to use active tab, at least 1 tab must be open.
	var use_active_tab = 1;
	if(! document.getElementById('create_new_tab').checked || GetActiveTabId() == false) {
		use_active_tab = 0;
	}

	// if template==0 then that means it was clicked via button.. not attempting to switch templates.
	if(template == 0) {
		var switch_tab_id = 0;
		var settings_panel_tab = $('#tabs li[@title=TWERQ Settings Panel]');
		if(settings_panel_tab) {
			if(settings_panel_tab.length) {
				// This is the TWERQ settings panel.
				var tab_id = $(settings_panel_tab).attr('id');
				var tmp_array = tab_id.split("_");
				switch_tab_id = tmp_array[1];
			}
		}

		if(switch_tab_id > 0) {
			// TWERQ Settings Panel was found.
			SetActiveTab(switch_tab_id);
			previous_search_complete = true;
			//Take off the loading image.
			RemoveLoadingImage();

			return false;
		} else {
			template = 1; // Set the template to the default of 1.
		}
	}

	//Add the loading image to the search bar
	AddLoadingImage();

	$.ajax({
		type:		"GET",
		url:		"/ajax/twerq_settings_panel.php",
		dataType:	"json",
		data:		serialized_data + "use_active_tab=0&active_tab="+GetActiveTabId()+"&template="+template,
		success:	function(obj) {
						if(obj.do_not_create != 1) {
							var newstring = obj.section_content;
							obj.section_content = newstring.replace(/%n%/g,"\n");
							SetActiveTab(obj.new_tab);
						}

						CreateTab(obj);
						previous_search_complete = true;

						// set up drag-n-drop quicktags
						SetupQuicktagsSorting();
					}
	});
}

// #################################################
function SubmitRSSFeedTab(url) {

	// Serialize the tabs for use of generating new tab id.
	serialized_data = GetSerializedTabs();

	// See if the previous search is complete. If it's not, do not process another one yet. Causes conflicts.
	if(!previous_search_complete) { return false; }

	previous_search_complete = false;

	$.ajax({
		type:		"GET",
		url:		"/ajax/submit_rss_feed_tab.php",
		dataType:	"json",
		data:		serialized_data + "use_active_tab=0&active_tab="+GetActiveTabId()+"&url="+encodeURIComponent(url),
		success:	function(obj) {
						if(obj.use_active_tab == 1) {
							ChangeSection('/ajax/templates/submit_feed.html');
						} else {
							CreateTab(obj);
						}
						previous_search_complete = true;

						// set up drag-n-drop quicktags
						SetupQuicktagsSorting();
					}
	});
}

// #################################################
function AddRSSFeed() {
	var query_string = ParseForm('submit_rss_form');

	$.ajax({
		type:		"GET",
		url:		"/ajax/submit_feed.php",
		data:		query_string,
		success:	function(html) {
			$('#rss_form_errors').html(html);
		}
	});
	return false;
}

// #################################################
function SetupQuicktagsSorting() {
	var quicktags = $('#quicktags_table');
	quicktags.Sortable({
		'accept':		'quicktag-row',
		//'containment':	'parent',
		'helper':		'quicktag-drag-helper',
		'handle':		'.quicktag-handle',
		'floats':		true,
		'tolerance':	'intersect',
		'axis':			'vertically',
		'revert':		true,
		'onStart':		function() {
							$(quicktags).height($(quicktags).height());
						},
		'onStop':		function() {
							// should be done automatically but sometimes isn't
							$('#sortHelper').hide();
							$(quicktags).height('auto');
						}
	});
}

// #################################################
function Twerq2Go() {

	// Serialize the tabs for use of generating new tab id.
	serialized_data = GetSerializedTabs();

	// See if the previous search is complete. If it's not, do not process another one yet. Causes conflicts.
	if(!previous_search_complete) { return false; }

	previous_search_complete = false;

	// Use active tab or not? If they want to use active tab, at least 1 tab must be open.
	var use_active_tab = 1;
	if(! document.getElementById('create_new_tab').checked || GetActiveTabId() == false) {
		use_active_tab = 0;
	}

	$.ajax({
		type:		"GET",
		url:		"/ajax/twerq2go.php",
		dataType:	"json",
		data:		serialized_data + "use_active_tab=0&active_tab="+GetActiveTabId(),
		success:	function(obj) {
						if(obj.panel_exists != 1) {
							CreateTab(obj);
						}

						previous_search_complete = true;
					}
	});
}

// #################################################
function AddCloseButtonHandlers() {
	// onclick handlers for 1st image map (close tab)
	$('area.close_tab_map_1').unbind('click').click( function() { SwapClose('map0'); } );
	$('area.close_tab_map_2').unbind('click').click( function() { CloseTab(); });

	// onclick handlers for 2nd image map (close all tabs)
	$('area.close_all_tabs_map_1').unbind('click').click( function() { SwapClose('map1'); } );
	$('area.close_all_tabs_map_2').unbind('click').click( function() { CloseAllTabs(); SwapClose('map1'); } );
}

// #################################################
// onclick handler for selecting a new tab. Should save the new active tab.
function AddTabClickHandlers() {
	$('#tabs a').unbind('click').click(function(e) {
		$('ul.tab-list').remove();
		$('div.tab-list-select').removeClass('tab-list-select-uparrow');
		HideQTriggers();

		// remove the class 'hive-tabs-selected' for this tab.
		$('#tabs li').removeClass('hive-tabs-selected');

		// Get the tab being selected. (IE does not like this otherwise)
		var tab_num = $(this).attr('id'); // tabid_# is the format.
		var tmp = tab_num.split("_");
		current_active_tab = tmp[1]; // Set the global variable.

		SetActiveTab(tmp[1],true);

//		UpdateAllHivePanels();
		e.preventDefault();
	});

	Hive.addDropDowns();
}

// #################################################
function SelectTab() {
	// Get the tab being selected. (IE does not like this otherwise)
	var tab_num = $(this).attr('id'); // tabid_# is the format.
	var tmp = tab_num.split("_");
	current_active_tab = tmp[1]; // Set the global variable.

	SetActiveTab(tmp[1]);

	return false;
}

// #################################################
function SubmitBug() {
	var query_string = ParseForm('report_bug_form');

	$.ajax({
		type:		"GET",
		url:		"/ajax/report_bug.php",
		data:		query_string,
		success:	function(html) {
			ChangeSection('/ajax/templates/report_bug_thankyou.html');
		}
	});
	return false;
}

// #################################################
function SubmitTAF() {
	var query_string = ParseForm('taf_form');

	$.ajax({
		type:		"POST",
		url:		"/ajax/submit_taf.php",
		data:		query_string,
		dataType:	"html",
		success:	function(html) {
			$('#taf_success').html(html);
		}
	});

	return false;
}

// #################################################
function SubmitSettings() {
	var data = ParseForm('settings_form', 'submit_settings');

	$.post("/ajax/save_settings.php", data, function() { window.location = "/index.html"; });
	return false;
}

// #################################################
function CreateNewQuicktag() {
	var new_key = parseInt($('#next_key').val());
	$('#next_key').val(parseInt(new_key)+1);

	$.ajax({
		url:		"/ajax/create_new_quicktag.php",
		type:		"POST",
		data:		"new_key="+new_key,
		dataType:	"json",
		success:	function(object) {
						$('#quicktags_table')
							.append(object.html)
							.SortableAddItem($('#quicktags_table li:last').get(0));
						SetupQuicktagsSorting();
						Hive.addDropDowns();
		}
	});
}

// #################################################
function RemoveQuicktag(key) {
	//Remove the tag from the settings panel.
	var quicktag = $('#quicktag_input_'+key).val();

	$('#quicktag_'+key).remove();
	$('#quicktag_link_'+key).remove();

	//Remove the tag from the database and from the session.
	$.ajax({
		type:		"GET",
		url:		"/ajax/remove_quicktag.php",
		dataType:	"html",
		data:		"key="+key+"&quicktag="+encodeURIComponent(quicktag),
		success:	function(msg) {
//						alert(msg);
//						$('#quicktags_dl').html(msg);
		}
	});

}
// #################################################
function AddToSearch(data) {
	$(window.global_search_term).val( $(window.global_search_term).val() + data );
}

// This function is used for the close/close all buttons.
// #################################################
function SwapClose(div_id) {
	if(div_id == 'map0') {
		$('div.map0').hide();
		$('div.map1').show();
	} else {
		$('div.map1').hide();
		$('div.map0').show();
	}
}

// #################################################
function GetLastTabId() {
	var last_tab_id = 0;

	$('#tabs li.tabitem:last').each(
		function() {
			var tmp = this.id;
			var tmp_array = tmp.split("_");
			last_tab_id = tmp_array[1];
		}
	);

	return last_tab_id;
}

// #################################################
function ToggleResult(obj, snippet_id, no_animation) {
	var snippet = $('#'+snippet_id);

	if(snippet.css('display') == "block") {
		$(obj).attr({ src: "/images/plus.gif", 'alt': 'Expand', 'title': 'Expand' });

		if (no_animation)
			snippet.hide();
		else
			snippet.slideUp(150);
	} else {
		$(obj).attr({ src: "/images/minus.gif", 'alt': 'Collapse', 'title': 'Collapse' });
		if (no_animation)
			snippet.show();
		else
			snippet.slideDown(150);
	}
}

// #################################################
function ClearCache() {
	$.ajax({
		url:		"/ajax/clear_cache.php",
		success:	function(obj) { $('#clear_cache').html('Cache Cleared'); }
	});
}

// #################################################
function ClearCookie() {
	$.ajax({
		url:		"/ajax/clear_cookie.php",
		success:	function(obj) { window.location = "/index.html"; }
	});
}

// #################################################
function AddToShortlist(search_term, title, url, description, link_text, search_engine, rss_search_term, thumbnail_url) {
	// Was a search term passed? If not, extract it.
	if(typeof search_term != 'string') {
		// Get the search term from the title.
		search_term = $(search_term).attr('title');
	}

	//Send the url, tab_id, and search_term to be entered into the shortlist table.
	tab_id = GetActiveTabId();

	var link_id = $(link_text).parent().parent().attr('id');
	var link_obj = $(link_text).parent().parent();
	var expand_obj = $('#expand_'+link_id);

	//Change the link to text and alter the class.
	$(link_obj).html('<br>Shortlisted');
	$(expand_obj).hide();
	$(link_obj).attr('class', 'shortlisted_text');

	// Per request of Josh.
	$('span.shortlist_as_link').css('display','inline');

	$.ajax({
		type:		"POST",
		url:		"/ajax/add_shortlist.php",
		dataType:	"json",
		data:		"title="+encodeURIComponent(title)+"&url="+url+"&description="+encodeURIComponent(description)+"&tab_id="+tab_id+"&search_term="+search_term+"&shortlist_id="+link_id+"&search_engine="+search_engine+"&rss_search_term="+rss_search_term+"&thumbnail_url="+encodeURIComponent(thumbnail_url),
		success:	function(obj) {
//						alert(msg);
						$(link_obj).html(obj.html);
						if(obj.use_active_tab == 1) {
							AlterTab(obj);
						}
					}
	});

	$('#expand_'+link_text).hide(); // hide the shortlist as box
	$('span#'+link_text).html("<br/>Shortlisted"); // mark as shortlisted.
}

// #################################################
function AddCustomShortlist(form_object,search_term, title, url, description, link_text, search_engine, rss_search_term, thumbnail_url) {
	//Send the url, tab_id, and search_term to be entered into the shortlist table.
	tab_id = GetActiveTabId();

	var link_id = $(link_text).parent().parent().attr('id');
	var link_obj = $(link_text).parent().parent();
	var expand_obj = $('#expand_'+link_id);

	//Change the link to text and alter the class.
	$(link_obj).html('<br>Shortlisted');
	$(expand_obj).hide();
	$(link_obj).attr('class', 'shortlisted_text');

	// Per request of Josh.
	$('span.shortlist_as_link').css('display','inline');

	// Get the custom title.
	var custom_title = $('input[@name=shortlist_field]', form_object).val();
	if(custom_title.length < 1) {
		return false;
	}

	search_term = custom_title;

	$.ajax({
		type:		"GET",
		url:		"/ajax/add_shortlist.php",
		dataType:	"json",
		data:		"title="+encodeURIComponent(title)+"&url="+url+"&description="+encodeURIComponent(description)+"&tab_id="+tab_id+"&search_term="+search_term+"&shortlist_id="+link_id+"&search_engine="+search_engine+"&rss_search_term="+rss_search_term+"&thumbnail_url="+encodeURIComponent(thumbnail_url),
		success:	function(obj) {
//						alert(msg);
						$(link_obj).html(obj.html);
						if(obj.use_active_tab == 1) {
							AlterTab(obj);
						}
					}
	});

	$('#expand_'+link_text).hide(); // hide the shortlist as box.
	$('span#'+link_text).html("<br/>Shortlisted"); // mark as shortlisted.
	return false;
}

// #################################################
function ShortlistImage(search_term,url,shortlist_id,thumbnail_url,thumb_height,thumb_width,image_size,referer_url,title) {
	// Get the search term.
	var tab_id = GetActiveTabId();

	if(typeof search_term != 'string') {
		// We were passed an object, not a string.
		search_term = $(search_term).attr('title');
	}

	$.ajax({
		type:		"GET",
		url:		"/ajax/shortlist_image.php",
		dataType:	"json",
		data:		"search_term="+search_term+"&url="+url+"&tab_id="+tab_id+"&search_term="+search_term+"&shortlist_id="+shortlist_id+"&thumbnail_url="+thumbnail_url+"&thumb_height="+thumb_height+"&thumb_width="+thumb_width+"&image_size="+image_size+"&referer_url="+referer_url+"&title="+title,
		success:	function(obj) {
			var shortlist_obj = $('#'+shortlist_id);
			var expand_shortlist_obj = $('#expand_shortlist_'+shortlist_id);

			$(shortlist_obj).html(obj.html); // Change text to "Shortlisted"
			$(expand_shortlist_obj).hide(); // Hide the box.

			$(shortlist_obj).attr('class', 'shortlisted_text');

			// Per request of Josh.
			$('span.shortlist_as_link').css('display','inline');
			if(obj.use_active_tab == 1) {
					AlterTab(obj);
			}
		}
	});
}

// #################################################
function AddCustomImageShortlist(form_object, search_term,url,shortlist_id,thumbnail_url,thumb_height,thumb_width,image_size,referer_url,title) {
	// Get the search term.
	var tab_id = GetActiveTabId();

	// Get the custom title.
	var custom_title = $('input[@name=shortlist_field]', form_object).val();
	if(custom_title.length < 1) {
		return false;
	}

	search_term = custom_title;

	$.ajax({
		type:		"GET",
		url:		"/ajax/shortlist_image.php",
		dataType:	"json",
		data:		"search_term="+search_term+"&url="+url+"&tab_id="+tab_id+"&search_term="+search_term+"&shortlist_id="+shortlist_id+"&thumbnail_url="+thumbnail_url+"&thumb_height="+thumb_height+"&thumb_width="+thumb_width+"&image_size="+image_size+"&referer_url="+referer_url+"&title="+title,
		success:	function(obj) {
			var shortlist_obj = $('#'+shortlist_id);
			var expand_shortlist_obj = $('#expand_shortlist_'+shortlist_id);

			$(shortlist_obj).html(obj.html); // Change text to "Shortlisted"
			$(expand_shortlist_obj).hide(); // Hide the box.

			$(shortlist_obj).attr('class', 'shortlisted_text');

			// Per request of Josh.
			$('span.shortlist_as_link').css('display','inline');
			if(obj.use_active_tab == 1) {
					AlterTab(obj);
			}
		}
	});

	return false;
}

// #################################################
function RemoveShortlist(db_id,shortlist_id) {
	$('#'+shortlist_id).remove();

	var active_tab = GetActiveTabId();

	$.ajax({
		type:		"GET",
		url:		"/ajax/remove_shortlist.php",
		data:		"id="+db_id+"&active_tab="+active_tab,
		success:	function(msg) {
//						alert(msg);
						//Change the link to text and alter the class.

						//Update the tabs information in the session.
//						UpdateTabs();
					}
	});
}

// #################################################
function RemoveHiveShortlist(db_id,shortlist_id) {
	$('#'+shortlist_id).remove();

	var active_tab = GetActiveTabId();

	$.ajax({
		type:		"GET",
		url:		"/ajax/hive/remove_hive_shortlist.php",
		data:		"id="+db_id+"&active_tab="+active_tab,
		success:	function(msg) {
//						alert(msg);
						//Change the link to text and alter the class.

						//Update the tabs information in the session.
//						UpdateTabs();
					}
	});
}

// #################################################
function RemoveAllShortlists(search_term) {
	var active_tab = GetActiveTabId();
	var tmp = $('#tab_'+active_tab).attr('title');
	search_term = tmp.substring(2,tmp.length);

	$.ajax({
		type:		"GET",
		url:		"/ajax/remove_shortlist.php",
		data:		'remove_all=1'+'&active_tab='+active_tab+'&search_term='+search_term,
		dataType:	"json",
		success:	function(obj) {
			$.each(obj, function(key, val){
				var child = $('#'+key);
				var parent = $(child).parent();

				$(parent).html('<br/>'+val);
			});

			// Update all "Shortlisted" links for this Shortlist that was just cleared out... give the Shortlist option.
			CloseTab();
		}
	});
}

// #################################################4/21/2007
function UpdateTabs() {
	//Updates all the content for the tabs.  Good for changes, might need to make this more specific and modular later.
	$.get('ajax/tab_order.php?' + $.SortSerialize('tabs').hash);
}

// #################################################
function findPos(obj) {
	var curleft = curtop = 0;
	if (obj.offsetParent) {
		curleft = obj.offsetLeft;
		curtop = obj.offsetTop;
		while (obj = obj.offsetParent) {
			curleft += obj.offsetLeft;
			curtop += obj.offsetTop;
		}
	}
	return {x:curleft, y:curtop};
}

// #################################################
function ShrinkTabs() {
	InitializeCarousel(GetTabIndex(GetActiveTabId()));
	if($('#shortlist_list')) {
		$('#shortlist_list').remove();
	}
}

// #################################################
function getY( oElement ) {
	var iReturnValue = 0;
	while( oElement != null ) {
		iReturnValue += oElement.offsetTop;
		oElement = oElement.offsetParent;
	}
	return iReturnValue;
}

// #################################################
function EditAccount() {
	// ID = edit_account_form
//	var query_string = "action=edit_account";
/*
	$('#edit_account_form :input').each(function(i) {
		// Is this a checkbox?
		if( $(this).attr('type') == 'checkbox' ) {
			// Yes. Is it checked?
			if( $(this).attr('checked') == true ) {
				query_string += "&"+$(this).attr('name')+"="+encodeURIComponent( $(this).val() );
			} // Else not checked, don't send it.
		} else {
			// Not a checkbox. Send it.
			query_string += "&"+$(this).attr('name')+"="+encodeURIComponent( $(this).val() );
		}
	});
*/
	var query_string = ParseForm('edit_account_form', 'edit_account');

	$.ajax({
		type:		"GET",
		dataType:	"html",
		url:		"/ajax/edit_account.php",
		data:		query_string,
		success:	function(msg) {
//						alert(msg);
						window.location = "/index.html";
					}
	});

	return false;

}

// #################################################
function EditQBank() {
	// ID = edit_qbank_form
	/*
	var query_string = "action=edit_account";
	$('#edit_qbank_form :input').each(function(i) {
		// Is this a checkbox?
		if( $(this).attr('type') == 'checkbox' ) {
			// Yes. Is it checked?
			if( $(this).attr('checked') == true ) {
				query_string += "&"+$(this).attr('name')+"="+encodeURIComponent( $(this).val() );
			} // Else not checked, don't send it.
		} else if( $(this).attr('type') == 'radio' ) {
			// Radio button. Is it selected?
			if( $(this).attr('checked') == true ) {
				// Yes.
				query_string += "&"+$(this).attr('name')+"="+encodeURIComponent( $(this).val() );
			} // Else, it's not selected. Don't send it.
		} else {
			// Not a checkbox or radio button.. Send it.
			query_string += "&"+$(this).attr('name')+"="+encodeURIComponent( $(this).val() );
		}
	});
	*/
	var query_string = ParseForm('edit_qbank_form', 'edit_qbank');

	$.ajax({
		type:		"GET",
		dataType:	"html",
		url:		"/ajax/edit_qbank.php",
		data:		query_string,
		success:	function(msg) {
//						alert(msg);
//						window.location = "/index.html";
						$('#edit_qbank_error').html(msg);
					}
	});

	return false;

}

// #################################################
function ParseForm(form_id,action_val) {
	var query_string = "action=";

	// allow form_id to be an actual form
	var form;
	if (typeof form_id == 'string')
		form = $('#' + form_id);
	else
		form = $(form_id);

	if(action_val == null) {
		query_string += "parse_form";
	} else {
		query_string += action_val;
	}

	$(':input', form).each(function(i) {
		var this_name = $(this).attr('name');
		var this_type = $(this).attr('type');
		var this_val = $(this).val();

		// Is this a checkbox?
		if( this_type == 'checkbox' ) {
			// Yes. Is it checked?
			if( $(this).attr('checked') == true ) {
				query_string += "&"+this_name+"="+encodeURIComponent( this_val );
			} else {
				// Else not checked, don't send a "true" value.
				query_string += "&"+this_name+"=0";
			}
		} else if( this_type == 'radio' ) {
			// Radio button. Is it selected?
			if( $(this).attr('checked') == true ) {
				// Yes.
				query_string += "&"+this_name+"="+encodeURIComponent( this_val );
			} // Else, it's not selected. Don't send it.
		} else {
			// Not a checkbox or radio button.. Send it.
			query_string += "&"+this_name+"="+encodeURIComponent( this_val );
		}
	});

	return query_string;
}

// #################################################
function HashForm(form_id,action_val) {
	var query_string = "action=";
	var hash = new Array();

	if(action_val == null) {
		query_string += "parse_form";
	} else {
		query_string += action_val;
	}

	$('#'+form_id+' :input').each(function(i) {
		var this_type = $(this).attr('type');
		var this_val = $(this).val();
		var this_name = $(this).attr('name');

		// Is this a checkbox?
		if( this_type == 'checkbox' ) {
			// Yes. Is it checked?
			if( $(this).attr('checked') == true ) {
				query_string += "&"+this_name+"="+encodeURIComponent( this_val );
				hash[this_name] = this_val;
			} // Else not checked, don't send it.
		} else if( this_type == 'radio' ) {
			// Radio button. Is it selected?
			if( $(this).attr('checked') == true ) {
				// Yes.
				query_string += "&"+this_name+"="+encodeURIComponent( this_val );
				hash[this_name] = this_val;
			} // Else, it's not selected. Don't send it.
		} else {
			// Not a checkbox or radio button.. Send it.
			query_string += "&"+this_name+"="+encodeURIComponent( this_val );
			hash[this_name] = this_val;
		}
	});

	return {
		data:			hash,
		query_string:	query_string
	};
}

// #################################################
function RequestWithdrawal() {
	// ID = edit_account_form
	var query_string = "action=request_withdrawal";

	$('#request_withdrawal_form :input').each(function(i) {
		// Is this a checkbox?
		if( $(this).attr('type') == 'checkbox' ) {
			// Yes. Is it checked?
			if( $(this).attr('checked') == true ) {
				query_string += "&"+$(this).attr('name')+"="+encodeURIComponent( $(this).val() );
			} // Else not checked, don't send it.
		} else if( $(this).attr('type') == 'radio' ) {
			// Radio button. Is it selected?
			if( $(this).attr('checked') == true ) {
				// Yes.
				query_string += "&"+$(this).attr('name')+"="+encodeURIComponent( $(this).val() );
			} // Else, it's not selected. Don't send it.
		} else {
			// Not a checkbox or radio button.. Send it.
			query_string += "&"+$(this).attr('name')+"="+encodeURIComponent( $(this).val() );
		}
	});

	$('#qbank_withdrawl_error').html('');

	$.ajax({
		type:		"GET",
		dataType:	"html",
		url:		"/ajax/request_withdrawal.php",
		data:		query_string,
		success:	function(msg) {
//						alert(msg);
						if(msg != "SUCCESS") {
							if(msg == 'NOT_ACTIVATED') {
								//Show the activation form, their qbank isn't activated.
								TwerqSettingsPanel(5);
							} else {
								$('#qbank_withdrawl_error').html(msg).show();
							}

							return false;
						} else {
							//window.location = "/index.html";
							$('#qbank_withdrawl_error').html(msg).show();
						}
					}
	});

	return false;

}

// #################################################
function QuickTagDepot() {

	// Serialize the tabs for use of generating new tab id.
	serialized_data = GetSerializedTabs();

	// See if the previous search is complete. If it's not, do not process another one yet. Causes conflicts.
	if(!previous_search_complete) { return false; }

	previous_search_complete = false;

	// Use active tab or not? If they want to use active tab, at least 1 tab must be open.
	var use_active_tab = 1;
	if(! document.getElementById('create_new_tab').checked || GetActiveTabId() == false) {
		use_active_tab = 0;
	}

	$.ajax({
		type:		"GET",
		url:		"/ajax/quicktag_depot.php",
		dataType:	"json",
		data:		serialized_data + "use_active_tab=0&active_tab="+GetActiveTabId(),
		success:	function(obj) {
						if(obj.do_not_create == 1) {
//							alert("tab already exists. Tab ID: + " + obj.switch_tab_id);
							SetActiveTab(obj.switch_tab_id);

							previous_search_complete = true;
							//Take off the loading image.
							RemoveLoadingImage();
						} else {
							CreateTab(obj);
						}
						Hive.InitializeTooltips();
					}
	});

}

// #################################################
function AddQuickTag(shortcutname,shortcutcommand,object,description,obj) {
	$('#tooltip').hide();

	if(obj) {
		$(obj).parent().html('<span class=\"grabbed_quicktag hive_quicktag_link\" title=\"'+description+'\">'+shortcutname+'</span>');
	}
	Hive.InitializeTooltips();

	$.ajax({
		type:		"GET",
		url:		"/ajax/add_quicktag.php",
		dataType:	"html",
		data:		{
			shortcutname: shortcutname,
			shortcutcommand: shortcutcommand,
			shortcutfeature: 1,
			description: description
		},
		success:	function(msg) {
			$.ajax({
				type:		"GET",
				url:		"/ajax/update_quicktags.php",
				dataType:	"html",
				success:	function(html) {
					UpdateAllHivePanels();

					$('#quicktags_dl').html(html);
					//$('#quicktags dl a').click(quickTagOnClick);
					addQuickTagEvents();
					if (object) $("#"+object).html("Grabbed");

					var parameters = "action=refresh_quicktags";
					$.get("/ajax/add_settings_quicktag.php", parameters, function(html) {
									if($('#quicktags_table')) {
										$('#quicktags_table').html(html);
										Hive.addDropDowns();
									}
					});
				}
			});
			$('#tooltip').hide();
		}
	});


}

// #################################################
function HivePortal_AddQuickTag(shortcutname,shortcutcommand,object,description) {
	$.ajax({
		type:		"GET",
		url:		"/ajax/hive/hiveportal_add_quicktag.php",
		dataType:	"html",
		data:		{
			shortcutname:		shortcutname,
			shortcutcommand:	shortcutcommand,
			shortcutfeature:	1,
			description:		description
		},
		success:	function(msg) {
			$.ajax({
				type:		"GET",
				url:		"/ajax/update_quicktags.php",
				dataType:	"html",
				success:	function(html) {
					$('#quicktags_dl').html(html);
					//$('#quicktags dl a').click(quickTagOnClick);
					addQuickTagEvents();
					$("#"+object).html("Grabbed");

					var parameters = "action=refresh_quicktags";
					$.get("/ajax/add_settings_quicktag.php", parameters, function(html) {
									if($('#quicktags_table')) {
										$('#quicktags_table').html(html);
										Hive.addDropDowns();
									}
								});
				}
			});
					}
	});
}

// #################################################
function IncreaseClaimLimit() {
	// Serialize the tabs for use of generating new tab id.
	serialized_data = GetSerializedTabs();

	// See if the previous search is complete. If it's not, do not process another one yet. Causes conflicts.
	if(!previous_search_complete) { return false; }

	previous_search_complete = false;

	// Use active tab or not? If they want to use active tab, at least 1 tab must be open.
	var use_active_tab = 1;
	if(! document.getElementById('create_new_tab').checked || GetActiveTabId() == false) {
		use_active_tab = 0;
	}

	$.ajax({
		type:		"GET",
		url:		"/ajax/increase_claim_limit.php",
		dataType:	"json",
		data:		serialized_data + "use_active_tab=0&active_tab="+GetActiveTabId(),
		success:	function(obj) {
						if(obj.panel_exists != 1) {
							CreateTab(obj);
						}

						previous_search_complete = true;
					}
	});
}

// #################################################
function EditQBankSettings() {
	//Reset message area.
	$('#qbank_message').html('');

	var qbank_goal = $('#qbank_goal').val();
	var qbank_notify1 = $('#qbank_notify1').attr('checked');
	var qbank_notify2 = $('#qbank_notify2').attr('checked');

	//Assign the notification type. 1: Just Notify - 2: Notify and Withdraw.
	var qbank_notify = 0;
	if(qbank_notify1) {
		qbank_notify = 1;
	} else {
		qbank_notify = 2;
	}

//	alert("Goal: "+qbank_goal+"\nNotify: "+qbank_notify);

	$.ajax({
		type:		"GET",
		url:		"/ajax/edit_qbank_settings.php",
		data:		"qbank_goal="+qbank_goal+"&qbank_notify="+qbank_notify,
		success:	function(msg) {
//						alert(msg);
						//Change the link to text and alter the class.
						$('#qbank_message').html(msg);
					}
	});

	return false;

}

// #################################################
function ResetUserSettings() {
	$.ajax({
		type:		"GET",
		data:		"html",
		url:		"/ajax/reset_user_settings.php",
		success:	function(msg) {
//						alert(msg);
						window.location = "/index.html";
					}
	});
}

// #################################################
function SwapNews(target_id) {
	// This function is used for displaying/hiding news sections.
	var target = document.getElementById(target_id);

	if(target.style.display == "block") {
		target.style.display = "none";
	} else {
		target.style.display = "block";
	}
}

// This function is used for the TWERQit buttons (checked/unchecked).
// #################################################
function SwapButton(div_id) {
	if(div_id == 'twerqit_map0') {
		$('#twerqit_map0').css('display', 'none');
		$('#twerqit_map1').css('display', 'block');
		document.getElementById('create_new_tab').checked = true;
	} else {
		$('#twerqit_map1').css('display', 'none');
		$('#twerqit_map0').css('display', 'block');
		document.getElementById('create_new_tab').checked = false;
	}
}


// #################################################
function print_r(obj,id) {
	var buffer = "";
	$.each(obj,
		function(i) {
			buffer = buffer + i + ": " + this + "\n";
		}
	);

	if(id) {
		$('#'+id).html(buffer);
	} else {
		alert(buffer);
	}
}

// #################################################
function ChangePage(page_num, search_engine) {
	//Pull the search term from the search bar.  This is our search term obviously.
	search_term = $(window.global_search_term).val();
	tab_id = GetActiveTabId();

	var results_per_page = 10;

	//Make sure that the paging links work with search engine triggers.

	if(search_engine == 1) {
//		search_engine = 'y:';
	} else if(search_engine == 2) {
//		search_engine = 'g:';
	} else if(search_engine == 3) {
//		search_engine = 'i:';
		results_per_page = 12;
	} else if(search_engine == 6) {
//		search_engine = 'm:';
	} else if(search_engine == 7) {
//		search_engine = 'v:';
		results_per_page = 6;
	}
	else if(search_engine == 8) {
//		search_engine = 'v:';
		results_per_page = 10;
	}

	var start = (page_num * results_per_page) - results_per_page;
	if(page_num == 1) {
		start = 0;
	}

	//Add the loading image to the search bar
	AddLoadingImage();

	$.ajax({
		type:		"POST",
		url:		"/ajax/search.php",
		dataType:	"json",
		data:		"search_term="+encodeURIComponent(search_term)+"&use_active_tab=1&active_tab="+tab_id+"&start="+start+'&page_number='+page_num,
		success:	function(obj) { CreateTab(obj); }
	});
}

// #################################################
function ToggleExpand(id) {
	var tmp = id;
	var tmp_array = tmp.split('_');
	var section_id = 'section_'+tmp_array[3];
	var snippet = '#'+section_id+' .snippet';

	var id_obj = $('#'+id);

	if(id_obj.is('.expand_all')) {
		$(snippet).show();//slideDown(250);
		id_obj.html("Collapse All");
		id_obj.attr({ 'class': 'collapse_all header-link' });
		$('#'+section_id+' img.toggle_image').attr({ src: "/images/minus.gif", 'alt': 'Collapse', 'title': 'Collapse' });

	} else {
		$(snippet).hide();//slideUp(250);
		id_obj.html("Expand All");
		id_obj.attr({ 'class': 'expand_all header-link' });
		$('#'+section_id+' img.toggle_image').attr({ src: "/images/plus.gif", 'alt': 'Expand', 'title': 'Expand' });
	}
}

// #################################################
var Hive = {
	// an associative array keeping track of which tabs have joined a hive
	active_hives: {},

	// a 2-dimension array containing which tabs are related
	// (each tab has an array listing the tabs that are related)
	groups: {},

	// #################################################
	init: function(){
		Hive.attachPanelEvents();
		Hive.colourTabs();
		Hive.SetUpdateDelay();
	},

	// #################################################
	// add events to the forms and links in the panel
	attachPanelEvents: function(){
		// find all the panels
		$('div.hive-panel')
			// attach Close Hive click event
			.find('span.hive-close')
				.unbind()
				.click(Hive.leave)
			.end()
			// attach Learn More click event
			.find('span.hive-learn-more')
				.unbind()
				.click(TwerqHive)
			.end()
			// add click handler for the Create links to display forms
			.find('span.hive-create-public, span.hive-create-private')
				.unbind()
				.click(function(){
					// find the create form that is a child of the span's parent
					var local = $('form.hive-create-private, form.hive-create-public', $(this).parent());

					// hide any visible forms that are a child of the span's parents' parent (except the one we want to show)
					$('form:visible', $(this).parent().parent()).not(local).slideUp('slow');

					// show the form
					local.slideToggle('slow');
				})
			.end()
			// attach Create form submit event
			.find('form.hive-create-private, form.hive-create-public')
				.unbind()
				.submit(Hive.submitCreate)
			.end()
			// add click handler for displaying Join forms
			.find('span.hive-select-a-hive, span.hive-join-private')
				.unbind()
				.click(function(){
					// find the join form that is a child of the span's parent
					var local = $('form.hive-join-private, form.hive-join-public', $(this).parent());

					// hide any visible forms that are a child of the span's parents' parent (except the one we want to show)
					$('form:visible', $(this).parent().parent()).not(local).slideUp('slow');

					// show the form
					local.slideToggle('slow');
				})
			.end()
			// attach public join submitting
			.find('form.hive-join-public')
				.unbind()
				.submit(Hive.submitJoin)
			.end()
			// attach private join submitting
			.find('form.hive-join-private')
				.unbind()
				.submit(Hive.submitJoinPrivate)
			.end()
			// Make the mouseovers work.
			.find('div.hive_related_link')
				.unbind()
				.hover(function(){
					HiveRelatedOver(this)
				}, function(){
					HiveRelatedOut(this)
				})
			.end()
			.find('div.hive_quicktag_link')
				.unbind()
				.hover(function(){
					HiveQuickTagOver(this)
				}, function(){
					HiveQuickTagOut(this)
				})
			.end();

			AddCloseButtonHandlers();
	},

	// #################################################
	submitCreate: function() {
		var active_tab = GetActiveTabId();
		var form = $(this);

		//Creates a new hive.
		var query_string = ParseForm(this, 'create_new_hive');

		// clear out the error message
		$('.error', form).empty();

		$.ajax({
			type:		"GET",
			url:		"/ajax/hive/create_hive.php",
			data:		query_string,
			dataType:	"json",
			success:	function(object) {
							Hive.SetResultClickHandlers();
//							alert("Data sent: " + data);
							// Check for error(s).
							if(object.result == "FAILED") {
								// display the error message
								$('.error', form).html(object.html);
							} else if(object.result == "SUCCESS") {
								// update the panel with the new HTML
								Hive.updatePanel(active_tab, object.html);

								// add the current tab to the list of active hives
								Hive.active_hives[active_tab] = true;

								// Color the tab that we're on that we just joined a hive for.
								$('#tab_'+active_tab).addClass('hive-tabs-selected');
							}
						}
		});

		return false;
	},

	// #################################################
	updatePanel: function(tab, html, tab_start_index) {
		// replace the hive panel with new html

		var panel = $('#section_' + tab + ' div.hive-panel');

		// remember how the box had scrolled
		var scrollbox = $('div.hive_related_link', panel).parent();
		var scrollTop = 0;
		if (scrollbox.length) {
			scrollTop = scrollbox.get(0).scrollTop;
		}

		// Replace old panel with new panel.
		$(panel).replace(html);

		if(window.hive_tabs_start) {
			if(window.hive_tabs_start[tab]) {
				tab_start_index = window.hive_tabs_start[tab];
			}
		}

		if(tab_start_index) {
			// Generate a "link" variable.
			var link = "";
			if(tab_start_index == 1) {
				link = "hive_related_links_"+tab;
			} else if(tab_start_index == 2) {
				link = "hive_quicktags_"+tab;
			} else if(tab_start_index == 3) {
				link = "hive_shortlists_"+tab;
			} else {
				link = "hive_related_links_"+tab;
			}

			// Remove the class hive-tabs-selected.. and hide the old hive fragment (hive_fragment).
			$('#section_'+tab+' div.tabfeatures ul.hive_anchors li').removeClass('hive-tabs-selected');
			$('#hive_tabs_'+tab+' div.hive_fragment').hide();

			// Add the class hive-tabs-selected for tab_start_index.. and show the new hive fragment (hive_fragment).
			$('#section_'+tab+' div.tabfeatures ul.hive_anchors li a[@index='+tab_start_index+']').parent().addClass('hive-tabs-selected');
			$('#div_'+link).css('display', 'block');
		}

		// restore scrolling
		scrollbox = $('#section_' + tab + ' div.hive_related_link').parent();
		if (scrollbox.length) {
			scrollbox.get(0).scrollTop = scrollTop;
		}

		// attach all events in the new hive panel
		Hive.attachPanelEvents();
		Hive.InitializeTooltips();
		Hive.InitializeTabs(GetActiveTabId());
//		Hive.InitializeTabs(GetActiveTabId(), tab_start_index);

		delete tab;
		delete html;
		delete tab_start_index;
	},

	// #################################################
	join: function(data, form){
		var active_tab = GetActiveTabId();
		Hive.SetResultClickHandlers();

		// if a number is passed as 'data', assume it is the ID
		if (typeof data != 'object')
			data = { id: data };

		// clear out the error message, if we have a form to do so in
		if (form != null)
			$('.error', form).empty();

		$.ajax({
				type:		"GET",
				url:		"/ajax/hive/join_hive.php",
				dataType:	"json",
				data:		data,
				success:	function(object) {
								if(object.result == "FAILED") {
									// if there is a form, set the error message
									if (form != null)
										$('.error', form).html(object.html);
								} else if(object.result == "SUCCESS") {
									// update the panel with the new html
									Hive.updatePanel(active_tab, object.html);

//									Hive.InitializeTabs(active_tab,1);

									// update the hive and comb data
									Hive.groups = object.comb_data;
									Hive.active_hives = object.active_hives;

									// recolour the tabs
									Hive.colourTabs();

									// Color the tab that we're on that we just joined a hive for.
									$('#tab_'+active_tab).addClass('hive-tabs-selected');

									// Set up settings panel quicktags for hive.
									if($('#quicktags_table')) {
										$.get("/ajax/refresh_settings_quicktag.php", function(html) {
											$('#quicktags_table').html(html);
											Hive.addDropDowns();
											SetupQuicktagsSorting();
										});
									}
								}
							}
		});
	},

	// #################################################
	InitializeTabs: function(tab_id, tab_start_index) {
		// Initialize tabs for "hived as related" box.
		// Check for a tab_start_index

		if(!tab_id) {
			tab_id = GetActiveTabId();
		}

		if(!window.hive_tabs_start) {
			window.hive_tabs_start = [];
		}

		var tmp_typeof = typeof window.hive_tabs_start;
		if(tmp_typeof.toLowerCase() != "object") {
			window.hive_tabs_start = [];
		}

		if(!tab_start_index) {
			if(window.hive_tabs_start[tab_id]) {
				tab_start_index = window.hive_tabs_start[tab_id];
			} else {
				tab_start_index = $('#section_'+GetActiveTabId()+' ul.hive_anchors li.hive-tabs-selected a').attr('index');
			}
		}

		var hive_tabs_obj = $('#hive_tabs_'+tab_id);
		if(tab_start_index) {
			var hive_fragments = $('#section_'+tab_id+' div.hive_fragment');
			var hive_tabs = $('#section_'+tab_id+' ul.hive_anchors li');
			var tab_start_ID = $('#section_'+tab_id+' ul.hive_anchors li a[@index='+tab_start_index+']').attr('id');

			// Initialize tabs.
//			$(hive_tabs_obj).tabs(parseInt(tab_start_index), {'selectedClass': 'hive-tabs-selected'});

//			THIS SEGMENT CAUSED "BLINKING" ISSUES. -- do not remove this comment block.. it's for reference.
/*
			$(hive_tabs).removeClass('hive-tabs-selected'); // remove hive-tabs-selected class from all tabs.
			$(hive_fragments).hide(); // hide all fragments.
			$('#'+tab_start_ID).parent().addClass('hive-tabs-selected'); // add hive-tabs-selected class to this starting tab.
			$('#div_'+tab_start_ID).show(); // show starting fragment
*/
		}

		// click handler.
		$('li.hive_tabitem a').unbind('click').click(function(e) {
			$('ul.tab-list').remove();
			$('div.tab-list-select').removeClass('tab-list-select-uparrow');
			HideQTriggers();

			//Reset the timer to make sure the tabs don't revert back.
			window.clearTimeout(window.hive_update_timer);
			window.hive_update_timer = window.setTimeout('UpdateAllHivePanels()', Hive.update_delay);

			$.get('/ajax/hive/set_tabs_start.php?index='+$(this).attr('index'));
			if(! window.hive_tabs_start) {
				window.hive_tabs_start = [];
			}

			window.hive_tabs_start[GetActiveTabId()] = $(this).attr('index');

			var tab_id = GetActiveTabId();
			var link = $(this).attr('id');
			$('.hive_fragment', hive_tabs_obj).css('display', 'none');
			$('#div_'+link).css('display', 'block');

			// Now swap out the hive-tabs-selected class for the one just clicked.
			$('li', hive_tabs_obj).removeClass('hive-tabs-selected');
			$(this).parent().addClass('hive-tabs-selected');

			// Prevent the link's action. Similar to return false;
			e.preventDefault();
			return false;
		});
	},

	// #################################################
	submitJoin: function() {
		// join the hive that was selected in the select box
		var select = $('select', this).get(0);
		var select_id = select.options[select.selectedIndex].value;

		Hive.join(select_id, this);

		return false;
	},

	// #################################################
	submitJoinPrivate: function() {
		// join the hive based on the name and password
		Hive.join({
			name: $('input:text', this).val(),
			password: $('input:password', this).val()
		}, this);

		return false;
	},

	// #################################################
	leave: function(){
		var active_tab = GetActiveTabId();

		$.ajax({
				type:		"GET",
				url:		'/ajax/hive/leave_hive.php',
				dataType:	'json',
				success:	function(object) {
								// remove the current tab from the list of active hives
								Hive.active_hives[active_tab] = false;

								// clear out the related tabs for the current tab
								Hive.groups[active_tab] = {};

								// Is this a "Hive List" tab? Prefixed with h:.. or triggers[hive_shortlist]
								var this_li = $('#tab_'+active_tab).attr('title');
								if(this_li.substr(0, triggers.hive_shortlist.length).toLowerCase() == triggers.hive_shortlist.toLowerCase()) {
									// It is. Strip off the trigger and run a normal search.
									// Close this tab.
									CloseTab(GetActiveTabId());

									var new_search_term = this_li.substr(triggers.hive_shortlist.length);
									$(window.global_search_term).val(new_search_term);
									SearchSubmit();
									return;
								}

								// update the new panel HTML and attach events
								Hive.updatePanel(active_tab, object.html);
								Hive.attachPanelEvents();

								// recolour the tabs
								Hive.colourTabs();

								// Set up settings panel quicktags for hive.
								if($('#quicktags_table')) {
									$.get("/ajax/refresh_settings_quicktag.php", function(html) {
										$('#quicktags_table').html(html);
										Hive.addDropDowns();
										SetupQuicktagsSorting();
									});
								}

								// remove the hive class..
								$('#tab_'+active_tab).removeClass('hive-tabs-selected');
							}
		});
	},

	// #################################################
	addDropDowns: function(){
		// remove all the dropdowns
		$('div.tab-list-select').remove();
		$('div.tab-list-select').removeClass('tab-list-select-uparrow');
		HideQTriggers();

		// only show the dropdown arrow if there is more than 1 tab
		if ($('#tabs li.tabitem').length >= 2) {
			// reattach the dropdowns to the start of each searchnav
			$('div.searchnav')
				.prepend('<div class="tab-list-select"></div>')
				.find('div.tab-list-select')
					.click(this.showDropDown);
		}

		// #################################################
		// add quicktag dropdowns if the quicktags table is on the page
		var qtable = $('#quicktags_table');
		if (qtable.length > 0) {

			// add dropdown arrow before each 'Remove' link in the table
			$('li.quicktag-row a', qtable).parent().find('.hive-list-select').remove();
			$('li.quicktag-row a', qtable)
                .before('<div class="hive-list-select"></div>')
				// find the attached div and add a click handler
                .prev().click(function(){
					// Is the div.hive-quicktag-dropdown currently visible? If so, that means it's slid DOWN.. and the arrow should be UP.
					// Otherwise, the arrow should be DOWN (currently NOT visible).
					if( $(this).siblings('div.hive-quicktag-dropdown').css('display') == 'block' ) {
						//alert("Set to DOWN arrow");
						$(this).removeClass('hive-list-select-close').addClass('hive-list-select');
					} else {
						//alert("Set to UP arrow");
						$(this).parent().parent().find('div.hive-quicktag-dropdown:visible').slideUp('fast');
						$(this).parent().parent().find('div.hive-list-select-close').addClass('hive-list-select').removeClass('hive-list-select-close');
						$(this).removeClass('hive-list-select').addClass('hive-list-select-close');
//						alert( $(this).parent().parent().html() );
//						console.log( $(this).parent().html() );
					}
//					$(this).siblings('div.hive-quicktag-dropdown').slideUp('fast');
					// slide the local hive dropdown
					$(this).siblings('div.hive-quicktag-dropdown').slideToggle('fast');
				});

			// Now we have each LIST ITEM (li) in this drop-down.
			$('div.hive-quicktag-dropdown', qtable)
				.find('li')
					// CLICK HANDLER FOR QUICKTAG COMBS!
					// attach click events to combs (the whole row really - combs are just a background)
					.unbind('click').click(function(obj){
						// A comb was clicked.
						var this_id = $(this).attr('id'); // ie: quicktag_QUICKTAG-ID_TAB-ID
						var this_id_array = this_id.split("_");
						var quicktag_id = this_id_array[1];
						var hive_id = this_id_array[2];

						$(this).find('div.qt_error').remove(); // remove any error if it existed.

						if ($(this).is('.unchecked')) {
							var this_li = this;
							// The item _WAS_ unchecked, but is now checked.
							$.ajax({
								url:		"/ajax/hive/quicktag_comb.php",
								type:		"POST",
								dataType:	"json",
								data:		"quicktag_id="+quicktag_id+"&hive_id="+hive_id,
								success:	function(object) {
												if(object.error) {
													$(this_li).html( $(this_li).html() + "<div class=\"qt_error\" style=\"display:inline;position:relative;top:5px;\">"+object.error+"</div>" );
												} else {
													//$(this_li).attr({'class': 'checked'});
													$(this_li).removeClass('unchecked').addClass('checked');
													var tmp_value = $('input.quicktag_hidden', this_li).val();
													var tmp_array = tmp_value.split("|");
													$('input.quicktag_hidden').val(tmp_array[0]+'|'+'checked');
												}
												return false;
								}
							});

							// ajax to tell the server this hiveid/qtagid is no longer related
						} else {
							// The item _WAS_ checked, but is now unchecked.
							var this_li = $(this);
							$(this_li).attr({'class': 'unchecked'});
							var tmp_value = $('input.quicktag_hidden', this_li).val();
							var tmp_array = tmp_value.split("|");
							$('input.quicktag_hidden').val(tmp_array[0]+'|'+'checked');

							$.ajax({
								url:		"/ajax/hive/quicktag_uncomb.php",
								type:		"POST",
								dataType:	"json",
								data:		"quicktag_id="+quicktag_id+"&hive_id="+hive_id,
								success:	function(object) {
												return false;
								}
							});

							// ajax to tell the server this hiveid/qtagid is now related
						}
					})
					// remove any previously attached script-generated combs
					.filter('.script-generated')
						.remove()
					.end()
				.end()
		}
	},

	// #################################################
	showDropDown: function(){
		// if there is already a drop down showing, just hide it and stop
		var existing = $('ul.tab-list:visible');
		if (existing.length) {
			existing.hide();
			$('div.tab-list-select').removeClass('tab-list-select-uparrow');
			return false;
		}

		// align the drop down to the bottom left corner of the arrow
		var pos = findPos(this);
		pos.x += $(this).width();
		pos.y += $(this).height();

		// adjust by one pixel for opera
		if ($.browser.opera) pos.y--;

		var active_tab = GetActiveTabId();
		var tabs = $('#tabs li.tabitem');

		// if there are less than 2 tabs, don't show anything
		if (tabs.length < 2) return;

//		$(Hive.groups).debug();
		// create a dropdown list and position it
		HideQTriggers();
		$('ul.tab-list').remove(); // remove any previous tab lists.
		$('div.tab-list-select').removeClass('tab-list-select-uparrow');
		var dropdown = $('<ul class="tab-list"></ul>')
							.css({ left: pos.x, top: pos.y })
							.appendTo('body');

		// create a new list of related tabs if there isnt already one
		if(Hive.groups) {
			Hive.groups[active_tab] = Hive.groups[active_tab];
		} else {
			Hive.groups = [];
			Hive.groups[active_tab] = {};
		}

		// for all tabs except the current (selected) one
		tabs.not('.tabs-selected').each(function() {
			var tab = $(this);
			var id = this.id.split("_")[1];

			// get the name from the title attribute of each tab
			var name = tab.attr('title');

			// attach an item to the list (dropdown)
			var li = $('<li onmouseover="$(\'#tablist_x_'+id+'\').show(); $(this).css({ \'background\': \'url(images/tab_list_hover_bg.gif) repeat-x\' });" onmouseout="$(\'#tablist_x_'+id+'\').hide(); $(this).css({ \'background\': \'#F2FBE8\' });" style="background: #F2FBE8; margin: 0; padding: 0;" id="tablist_dropdown_li_'+id+'"><div style="float:left; height: 22px;"><span class="carousel_dropdown" id="'+id+'">' + name + '</span></div><img src="/images/x_gray.gif" id="tablist_x_'+id+'" onclick="TabListDropdown_Remove(this, '+id+');" onmouseover="$(this).attr(\'src\',\'/images/x_red.gif\');" onmouseout="$(this).attr(\'src\',\'/images/x_gray.gif\');" style="float:right;margin: 5px 2px 0 0;display:none;"></li>')
						.appendTo(dropdown)
						// add hover effects
						.hover(function(){
							$(this).addClass('hover');
						}, function(){
							$(this).removeClass('hover');
						})
						// when you click a list item, remove the dropdown and change to that tab
						.click(function(){
							$('ul.tab-list').remove();
							$('div.tab-list-select').removeClass('tab-list-select-uparrow');
							HideQTriggers();
							TablistDropdown_SetActiveTab(id);
							window.carousel_obj.scroll(GetTabIndex(id));
						});

			// if the current tab is in a hive, show the combs
			if (Hive.active_hives[active_tab]) {
				var comb = $('<div class="hive-group-comb"></div>');

				// THIS IS THE SECTION THAT GETS EXECUTED WHEN A COMB IS CLICKED (RELATING)
				// only include comb for tabs that contain <div class="hive-panel">
				var this_title = $('#tab_'+id).attr('title');
				var is_shortlist = 0;

				if ($('#section_' + id + ' div.hive-panel').length > 0 || this_title.indexOf('**') == 0 || this_title.indexOf('--') == 0) {
					comb.click(function(){
						Hive.groups[active_tab][id] = !Hive.groups[active_tab][id];

						// colour/uncolour the comb
						$(this).toggleClass('checked');
						Hive.colourTabs();

						var this_title = $('#tab_'+id).attr('title');
						if(this_title.indexOf('**') == 0 || this_title.indexOf('--') == 0) {
							is_shortlist = 1;
						}

						// if the comb was just checked, send an ajax request
						if ($(this).is('.checked')) {
							$.ajax({
								type:		"POST",
								url:		"/ajax/hive/hive_related.php",
								dataType:	"json",
								data:		{
									hive_id:	$('#section_'+active_tab+' input.hiveid').val(),
									related_id:	id
								},
								success:	function(object) {
										// update the panel with new html
										Hive.updatePanel(active_tab, object.html);
										Hive.attachPanelEvents();
								}
							});

						} else {
//							// if the comb was just checked, send an ajax request
							if(is_shortlist == 1) {
								//Make a seperate call for shortlist tabs. blahblah
								$.ajax({
									type:		"POST",
									url:		"/ajax/hive/hive_not_related_shortlist.php",
	//								dataType:	"json",
									data:		{
										hive_id:	$('#section_'+active_tab+' input.hiveid').val(),
										related_id:	id
									},
									success:	function(object) {
											// update the panel with new html
											//Hive.updatePanel(active_tab, object.html);
											//Hive.attachPanelEvents();
									}
								});
							} else {
								$.ajax({
									type:		"POST",
									url:		"/ajax/hive/hive_personal_unrelate.php",
	//								dataType:	"json",
									data:		{
										hive_id:	$('#section_'+active_tab+' input.hiveid').val(),
										related_id:	id
									},
									success:	function(object) {
											// update the panel with new html
											//Hive.updatePanel(active_tab, object.html);
											//Hive.attachPanelEvents();
									}
								});
							}
						}

						return false;
					});


					// if the tab is related, colour the comb yellow to begin with
					if(Hive.groups) {
						if (Hive.groups[active_tab]) {
							if(Hive.groups[active_tab][id]) {
								comb.addClass('checked');
							}
						}
					}
				} else {
					// for settings pages, etc., make this comb an unclickable placeholder
					comb.addClass('comb-placeholder');
				}

				comb.prependTo(li);
			}
		});

		// if you click anywhere on the body, make it remove the dropdown
		$('body').not('div.tab-list-select').unbind('click').bind('click', function(){
				$('ul.tab-list').remove();
				$('div.tab-list-select').removeClass('tab-list-select-uparrow');
		});

		// display with an animation
		dropdown.show();//.slideDown('fast');
		$('div.tab-list-select').addClass('tab-list-select-uparrow');

		// size the dropdown to match the longest list item
		var highest_width = 0;
//		$('span.carousel_dropdown').each(function() { alert( $(this).width() ); });
		$('span.carousel_dropdown', dropdown).each(function(){
			var tmp_width = $(this).width();
			if (Hive.active_hives[active_tab])
				tmp_width += 25; // comb plus a bit
			highest_width = Math.max(tmp_width, highest_width);
		});
		var buffer = 30;
		dropdown.width(highest_width+buffer);
		$('li', dropdown).width(highest_width+buffer);

		return false;
	},

	// #################################################
	setGroup: function(active_tab, related_tab, state) {
		// set the related state for these tabs (true = related, false = not)
		Hive.groups[active_tab] = Hive.groups[active_tab] || {};
		Hive.groups[active_tab][active_tab] = state;
		// recolour the tabs
		Hive.colourTabs();
	},

	/*
	[12:26] jessephrenic: it says, if the active tab is in a hive && the other tab (id) is related to this one, OR, the other tab is in the hive && this tab is related to the other one
	*/
	// #################################################
	colourTabs: function(){
//		alert("Hive.colourTabs() was called.");
		if(!Hive.groups) {
			Hive.groups = [];
		}

		var active_tab = GetActiveTabId();

		Hive.groups[active_tab] = Hive.groups[active_tab] || {};
		$('#tabs li.tabitem').each(function() {
			var id = this.id.split("_")[1];

			// initialize the related array for this tab
			Hive.groups[id] = Hive.groups[id] || {};

			var debug_active_tab = Hive.active_hives[active_tab];
			var debug_group = Hive.groups[active_tab][id];

			// if these tabs are related and active in the hive (2-way relationship)
			if ((Hive.active_hives[active_tab] && Hive.groups[active_tab][id])
				|| (Hive.active_hives[id] && Hive.groups[id][active_tab])) {
					// colour the tab to show it's related
					$(this).addClass('tab-grouped');
			} else {
				// remove 'related' colouring
				$(this).removeClass('tab-grouped');
			}
		});

	},

	// #################################################
	SetResultClickHandlers: function() {
		// CLICK HANDLER FOR REGULAR SEARCH RESULTS, RSS FEED RESULTS.
		// Regular search results and RSS feeds use a.search_title
		$('a.search_title').unbind('click').click( function() {
			var hive_id_url = GetHiveIDUrlParams();

			// if we have any hive ids in the list
			if (hive_id_url != '') {
				var url = $(this).attr('href');
				var thumbnail = $(this).parent().parent().parent().find('.video-thumbnail');
				var tab_id = GetActiveTabId();
				var title = $(this).html();
				var snippet = $(this).parent().parent().find('p.snippet').html();
				//Was this an image that was clicked?
				if($(title).is('img')) {
					var thumbnail_url = $(title).attr('src');
				} else {
					var thumbnail_url = $(thumbnail).attr('src');
				}
				if(thumbnail_url) {
					title = $(thumbnail).attr('title');
				}

				// Open in a new window?
				if($(this).attr('target') == '_blank') {
					// Yes.
					window.open("/feedback_frame.html?thumbnail_url="+encodeURIComponent(thumbnail_url)+"&url="+encodeURIComponent(url)+"&tab_id="+tab_id+hive_id_url+"&title="+encodeURIComponent(title)+"&snippet="+encodeURIComponent(snippet),"TWERQ");
					return false; // return false so the link doesn't open how it "normally" should.
				} else {
					// No.
					parent.location.href = "/feedback_frame.html?thumbnail_url="+encodeURIComponent(thumbnail_url)+"&url="+encodeURIComponent(url)+"&tab_id="+tab_id+hive_id_url+"&title="+encodeURIComponent(title)+"&snippet="+encodeURIComponent(snippet);
					return false;
				}
			} else {
//				alert("No active hive found.");
			}
		});

		// RSS searches use a.rss_search_title
//		$('a.rss_search_title').unbind('click').click( function() {	}); // Look at line 980 (approx) for this.

// 		#################################################
//		THIS IS FOR IMAGES ONLY
// 		#################################################
		// Images are a little more tricky. Images are encompassed within a td that has a class of image_search_thumbnail.
		$('td.image_search_thumbnail > a').unbind('click').click( function() {
			var hive_id_url = GetHiveIDUrlParams();
			if(hive_id_url) {
				var url = $(this).attr('href');
				var tab_id = GetActiveTabId();

				// Get the hive data.
				var hive_data = $(this).parent().find('input.hive_image').val();

				// Open in a new window?
				if($(this).attr('target') == '_blank') {
					// Yes.
					window.open("/feedback_frame.html?url="+encodeURIComponent(url)+"&tab_id="+tab_id+hive_id_url+"&serialized="+hive_data,"TWERQ");
					return false; // return false so the link doesn't open how it "normally" should.
				} else {
					// No.
					parent.location.href = "/feedback_frame.html?url="+encodeURIComponent(url)+"&tab_id="+tab_id+hive_id_url+"&serialized="+hive_data;
					return false;
				}
			} else {
//				alert("No active hive found.");
			}
		});

	},

	// #################################################
	CloseRSSFeedbackBar: function(object) {
		var active_tab = GetActiveTabId();
		$('#section_'+active_tab).find('div.feedback_bar').parent().find('div:first-child').remove();//remove();
		$('#section_'+active_tab).find('ul.search_result_ul').css('width','');
	},

	// ##################################################
	RSSFeedback: function(value) {
		var active_tab = GetActiveTabId();
		var query_string = $('#section_'+active_tab).find('div.feedback_bar').find('.rss_hiveid').val(); // This is the hive id that this RSS feed is relevant for.
		$('#section_'+active_tab).find('div.feedback_bar').hide();

		if(value == 1) {
			// Yes. It's relevant.
			$.ajax({
				url:		"/ajax/hive/rss_feedback.php",
				type:		"POST",
				dataType:	"json",
				data:		query_string+"&update_session=0&value="+value,
				success:	function(object) {
//								alert(object.debug);
				}
			});
		} else if(value == 0) {
			// No. It's not relevant.
			$.ajax({
				url:		"/ajax/hive/rss_feedback.php",
				type:		"POST",
				dataType:	"json",
				data:		query_string+"&update_session=1&value="+value,
				success:	function(object) {
//								alert(object.debug);
				}
			});
		}
	},

	// ##################################################
	ResultFeedback: function(serialized,value) {
		/*
		$data = array(
		'url' => $url,
		'thumbnail' => $thumbnail,
		'hive_id' => $hive_id,
		'tab_id' => $tab_id,
		'title' => $title,
		'snippet' => $snippet);
		*/

		if(value == 1) {
			$.ajax({
				url:		"/ajax/hive/result_feedback.php",
				type:		"POST",
				dataType:	"json",
				data:		"serialized="+serialized+"&value="+value,
				success:	function(object) {
//					alert(object.debug);
					parent.location.href = object.url;
				}
			});
		} else {
			$.ajax({
				url:		"/ajax/hive/result_feedback.php",
				type:		"POST",
				dataType:	"json",
				data:		"serialized="+serialized+"&value="+value,
				success:	function(object) {
					parent.location.href = object.url;
				}
			});
		}
	},

	// #################################################
	SetUpdateDelay: function() {
		// Calculate total open tabs.
		var total_tabs = 0;
		var tabs = $('#tabs li');
		if(tabs) {
			if(tabs.length) {
				total_tabs = tabs.length;
			}
		}
	},

	// #################################################
	InviteToHive:	function() {
		var active_tab = GetActiveTabId();
		var invite_div = $('#invite_to_hive_'+active_tab);

		if($(invite_div).is(':visible')) {
			$(invite_div).slideUp('fast');
		} else {
			Hive.HideLinks();
			$(invite_div).slideDown('fast');
		}
	},

	// #################################################
	SendHiveInvite: function () {
		var active_tab = GetActiveTabId();
		var query_string = ParseForm('invite_form_'+active_tab, $('#invite_form_'+active_tab).attr('name'));

		$('#error_invite_to_hive_'+active_tab).html('');

		$.ajax({
			type:		"POST",
			url:		"/ajax/hive/send_hive_invite.php",
			data:		query_string,
			dataType:	"json",
			success:	function(object) {
				if(object.errors.length > 0) {
					// Errors exist.
					$('#error_invite_to_hive_'+active_tab).html(object.errors);
				} else {
					$('#error_invite_to_hive_'+active_tab).html(object.html);
				}
			}
		});

		return false;
	},

	// #################################################
	ChangeHivePassword:	function() {
		var active_tab = GetActiveTabId();
		var change_hive_password = $('#change_hive_password_'+active_tab);

		if($(change_hive_password).is(':visible')) {
			$(change_hive_password).slideUp('fast');
		} else {
			Hive.HideLinks();
			$(change_hive_password).slideDown('fast');
		}

		delete active_tab;
		delete export_private_hive;
	},

	// #################################################
	ChangeHivePasswordSubmit: function() {
		var active_tab = GetActiveTabId();
		var query_string = ParseForm('change_hive_password_'+active_tab, 'change_hive_password');

		$('#error_change_hive_password_form_'+active_tab).html('');

		$.ajax({
			url:		"/ajax/hive/change_private_password.php",
			type:		"GET",
			data:		query_string,
			dataType:	"json",
			success:	function(object) {
				$('#error_change_hive_password_form_'+active_tab).html(object.text);
			}
		});

		delete active_tab;
		delete query_string;

		return false;
	},

	// #################################################
	ExportPrivateHive:	function() {
		var active_tab = GetActiveTabId();
		var export_private_hive = $('#export_private_hive_'+active_tab);

		if($(export_private_hive).is(':visible')) {
			$(export_private_hive).slideUp('fast');
		} else {
			Hive.HideLinks();
			$(export_private_hive).slideDown('fast');
		}

		delete active_tab;
		delete export_private_hive;
	},

	// #################################################
	ChangeModeratorPassword:	function() {
		var active_tab = GetActiveTabId();
		var change_moderator_password = $('#change_moderator_password_'+active_tab);

		if($(change_moderator_password).is(':visible')) {
			$(change_moderator_password).slideUp('fast');
		} else {
			Hive.HideLinks();
			$(change_moderator_password).slideDown('fast');
		}

		delete active_tab;
		delete export_private_hive;
	},

	// #################################################
	ChangeModeratorPasswordSubmit: function() {
		var active_tab = GetActiveTabId();
		var query_string = ParseForm('change_moderator_password_'+active_tab, 'change_moderator_password');

		$('#error_change_moderator_password_form_'+active_tab).html('');

		$.ajax({
			url:		"/ajax/hive/change_moderator_password.php",
			type:		"GET",
			data:		query_string,
			dataType:	"json",
			success:	function(object) {
				$('#error_change_moderator_password_form_'+active_tab).html(object.text);
			}
		});

		delete active_tab;
		delete query_string;

		return false;
	},

	// #################################################
	HideLinks: function() {
		var active_tab = GetActiveTabId();

		// See if the INVITE TO HIVE form is visible...
		var invite_div = $('#invite_to_hive_'+active_tab);
		if($(invite_div).is(':visible')) {
			$(invite_div).slideUp('fast');
		}

		// See if the REQUEST COLLABORATION form is visible...
		var request_collaboration = $('#request_collaboration_'+active_tab);
		if($(request_collaboration).is(':visible')) {
			$(request_collaboration).slideUp('fast');
		}

		// See if the EXPORT HIVE form is visible...
		var export_private_hive = $('#export_private_hive_'+active_tab);
		if($(export_private_hive).is(':visible')) {
			$(export_private_hive).slideUp('fast');
		}

		// See if the MODERATOR LOGIN form is visible...
		var private_moderator_login = $('#private_moderator_login_'+active_tab);
		if($(private_moderator_login).is(':visible')) {
			$(private_moderator_login).slideUp('fast');
		}

		// See if the CHANGE HIVE PASSWORD form is visible...
		var change_hive_password = $('#change_hive_password_'+active_tab);
		if($(change_hive_password).is(':visible')) {
			$(change_hive_password).slideUp('fast');
		}

		// See if the CHANGE MODERATOR PASSWORD form is visible...
		var change_moderator_password = $('#change_moderator_password_'+active_tab);
		if($(change_moderator_password).is(':visible')) {
			$(change_moderator_password).slideUp('fast');
		}
	},

	// #################################################
	ExportPrivateHiveSubmit: function() {
		var active_tab = GetActiveTabId();
		var query_string = ParseForm('export_private_hive_form_'+active_tab, 'export_private_hive');

		$('#error_export_private_form_'+active_tab).html('');

		$.ajax({
			url:		"/ajax/hive/export_private_hive.php",
			type:		"GET",
			data:		query_string,
			dataType:	"json",
			success:	function(object) {
				if(object.errors.length > 0) {
					// Error(s)!
					$('#error_export_private_form_'+active_tab).html(object.errors);
				} else {
					// No errors.
					$(window.global_search_term).val('h:'+object.search_term);
					SearchSubmit();
				}
			}
		});

		delete active_tab;
		delete query_string;

		return false;
	},

	// #################################################
	RequestCollaboration:	function() {
		var active_tab = GetActiveTabId();
		var request_collaboration = $('#request_collaboration_'+active_tab);

		if($(request_collaboration).is(':visible')) {
			$(request_collaboration).slideUp('fast');
		} else {
			Hive.HideLinks();
			$(request_collaboration).slideDown('fast');
		}
	},


	// #################################################
	DisplayPrivateModeratorLogin:	function() {
		var active_tab = GetActiveTabId();
		var form = $('#private_moderator_login_'+active_tab);

		if($(form).is(':visible')) {
			$(form).slideUp('fast');
		} else {
			Hive.HideLinks();
			$(form).slideDown('fast');
		}
	},


	// #################################################
	PrivateModeratorLogin:	function(object) {
		var active_tab = GetActiveTabId();
		var query_string = ParseForm('form_private_moderator_login_'+active_tab, 'private_moderator_login');

		$('#error_private_moderator_login_'+active_tab).html('');

		$.ajax({
			type:		"POST",
			url:		"/ajax/hive/private_hive_moderator_login.php",
			data:		query_string,
			dataType:	"json",
			success:	function(object) {
				if(object.errors.length > 0) {
					// Error(s)!
					$('#error_private_moderator_login_'+active_tab).html(object.errors);
				} else {
					// No errors.
//					$('#error_private_moderator_login_'+active_tab).html(object.html);
					$('#private_moderator_login_'+active_tab).css('display', 'none');
					UpdateAllHivePanels();
				}
			}
		});

		return false;
	},


	// #################################################
	RequestCollaborationSubmit: function() {
		var active_tab = GetActiveTabId();
		var query_string = ParseForm('request_collaboration_form_'+active_tab, 'request_collaboration');

		$('#error_request_collaboration_'+active_tab).html('');

		$.ajax({
			type:		"POST",
			url:		"/ajax/hive/request_collaboration.php",
			data:		query_string,
			dataType:	"json",
			success:	function(object) {
				if(object.errors.length > 0) {
					// Error(s)!
					$('#error_request_collaboration_'+active_tab).html(object.errors);
				} else {
					// No errors.
					$('#error_request_collaboration_'+active_tab).html(object.html);
				}
			}
		});

		return false;
	},

	// 	#################################################
	InitializeBrowseHives: function() {
		$('table.hive_portal_list-hives tr:even').not('.header').addClass('hive_portal_even');
		$('table.hive_portal_list-hives tr').mouseover(function() {
			$(this).addClass('browse_hives_mouseover');
		}).mouseout(function() {
			$(this).removeClass('browse_hives_mouseover');
		});
	},

	// #################################################
	ToggleCollaborationBox: function(object) {
		var active_tab = GetActiveTabId();
		var box = $('#section_'+active_tab+' div.collaboration_goal_bottom');

		if($(box).is(':visible')) {
			// The box is visible. Hide it.
			$(box).slideUp('fast');
			$(object).html('[+]');
		} else {
			// The box is hidden. Display it.
			$(box).slideDown('fast');
			$(object).html('[-]');
		}
	},

	// 	#################################################
	InitializeTooltips: function() {
		$('a.hive_quicktag_link').Tooltip({
				showURL:	false,
				track:		true
		});

		$('strong.quicktag_tooltip').Tooltip({
				showURL:	false,
				track:		true
		});

		$('a.quicktag_tooltip').Tooltip({
				showURL:	false,
				track:		true
		});
	}
};

// #################################################
function HiveRelatedOver(object) {
	$(object).addClass('hive_related_over');
	$(object).children().next().css('visibility','visible');
}

// #################################################
function HiveRelatedOut(object) {
	if(!$(object).is('.hive_related_link')) { return; }
	$(object).removeClass('hive_related_over');
	$(object).children().next().css('visibility','hidden');
}

// #################################################
function HiveQuickTagOver(object) {
	$(object).addClass('hive_quicktag_over');
	$(object).children().next().css('visibility','visible');
}

// #################################################
function HiveQuickTagOut(object) {
	if(!$(object).is('.hive_quicktag_link')) { return; }
	$(object).removeClass('hive_quicktag_over');
	$(object).children().next().css('visibility','hidden');
}

// #################################################
function HiveNotRelated(hive_related_id, object) {
	$.ajax({
		type:		"GET",
		url:		"/ajax/hive/hive_not_related.php",
		dataType:	"json",
		data:		"hive_related_id="+hive_related_id,
		success:	function(obj) {
						//set these, then call the colourtabs
						Hive.groups = obj["Hive.groups"];
						Hive.active_hives = obj["Hive.active_hives"];
						Hive.colourTabs();

						$(object).parent().parent().css({'display': 'none'});
						Hive.setGroup(GetActiveTabId(), hive_related_id, false);
		}
	});
}

// #################################################
function HiveNotRelatedShortlist(related_shortlist_id, object) {
	$.ajax({
		type:		"GET",
		url:		"/ajax/hive/hive_not_related_shortlist.php",
		dataType:	"html",
		data:		"related_shortlist_id="+related_shortlist_id,
		success:	function(html) {
						$(object).parent().parent().css({'display': 'none'});
						Hive.setGroup(GetActiveTabId(), hive_related_id, false);
		}
	});
}

// #################################################
function HiveQuickTagNotRelated(hive_quicktag_id, object) {
	$.ajax({
		type:		"GET",
		url:		"/ajax/hive/quicktag_not_related.php",
		dataType:	"json",
		data:		"quicktag_id="+hive_quicktag_id,
		success:	function(obj) {
			$(object).parent().parent().css({'display': 'none'});
		}
	});
}

// #################################################
function HiveOpenRelated(search_term) {
	if(search_term.length < 1) return false;

	// Serialize data.
	serialized_data = GetSerializedTabs();

	// See if the previous search is complete. If it's not, do not process another one yet. Causes conflicts.
	if(!previous_search_complete) return false;

	previous_search_complete = false;

	// Use active tab or not? If they want to use active tab, at least 1 tab must be open.
	var use_active_tab = 0;
	if($('#create_new_tab').is(':checked') == false && GetActiveTabId())
		use_active_tab = 1;

	//Add the loading image to the search bar
	AddLoadingImage();

	var active_tab = GetActiveTabId();

	$.ajax({
		type:		"POST",
		url:		"ajax/search.php",
		dataType:	"json",
		data:		serialized_data + "search_term=" + encodeURIComponent(search_term) + "&use_active_tab=" + use_active_tab + "&active_tab="+GetActiveTabId(),
		ifModified:	false,
		success:	function(obj) {
						CreateTab(obj);
						// make this tab related to original tab
						var new_active_tab = GetActiveTabId();
						Hive.setGroup(active_tab, new_active_tab, true);
					}
	});

	return false; // return false so no submit actually happens.
}

// #################################################
function InitializeLockTab() {
	$('a.locktab').unbind('click').click(LockTab);
}

// #################################################
function LockTab() {
	var label = $(this);
	var setting;

//	print_r(label);

	if($(label).is('.tab_unlocked')) {
		$(label).html("Unlock Tab")
			 .removeClass('header-link tab_unlocked')
			 .addClass('header-link tab_locked');
		setting = 0;
	} else {
		$(label).html("Lock Tab")
			 .removeClass('header-link tab_locked')
			 .addClass('header-link tab_unlocked');
		setting = 1;
	}

	$.post("/ajax/tab_lock.php", "setting="+setting);
}

// #################################################
function UpdateAllHivePanels() {
	window.clearTimeout(window.hive_update_timer);
	window.hive_update_timer = null;

//	RefresHiveList(active_tab);
//	return;

	// See if hive panels are not enabled.
	if(window.enable_hive_display == 'none') {
		return;
	}

	// See if we have a hive panel on the current active tab.
	var active_tab = GetActiveTabId();
	var hive_panel = $('#section_'+active_tab+' div.hive-panel');
	var tab_start_index = -1; // start off -1.. if found, then it'll set correctly.

	if(hive_panel.length > 0) {
		// Yes. hive panel was found.
		// If they currently have a form slid down into view.. we do not want to update that hive.
		var panel = $('#section_'+active_tab+' div.hive-panel');
		if( $(panel).find('form.hive-create-public').css('display') == 'block' ||
			$(panel).find('form.hive-create-private').css('display') == 'block' ||
			$(panel).find('form.hive-join-private').css('display') == 'block' ||
			$('#invite_to_hive_'+active_tab).css('display') == 'block' ||
			$('#private_moderator_login_'+active_tab).css('display') == 'block' ||
			$('#request_collaboration_'+active_tab).css('display') == 'block' ||
			$('#export_private_hive_'+active_tab).css('display') == 'block' ||
			$('form.hive-create-public', panel).is(':visible') ||
			$('form.hive-join-public', panel).is(':visible') ||
			$('#change_hive_password_'+active_tab, panel).css('display') == 'block' ||
			$('#change_moderator_password_'+active_tab, panel).css('display') == 'block' ) {
		window.hive_update_timer = window.setTimeout('UpdateAllHivePanels()', Hive.update_delay);
			active_tab = null;
			hive_panel = null;
			hive_list = null;
			return;
		}
	} else {
		window.hive_update_timer = window.setTimeout('UpdateAllHivePanels()', Hive.update_delay);
		active_tab = null;
		hive_panel = null;
		hive_list = null;
		return;
	}

	// Is this tab a "Hive List" tab?
	var hive_list = $('#section_'+active_tab+' div.fragment-body');
	if($(hive_list).is('.is_hive_shortlist')) {
//		alert("UpdateAllHivePanels() is being called.. which is about to call RefreshHiveList()");
//		alert("UpdateAllHivePanels() has been called. Calling RefreshHiveList(). active_tab=" + GetActiveTabId());
		RefreshHiveList(active_tab);
	}


	// Collaboration Goal Criteria box...
	var box = $('#section_'+active_tab+' div.collaboration_goal_bottom');
	var box_exists = 0;
	var box_visible = 0;
	if(box) {
		box_exists = 1;
		// get the box's current state.
		if($(box).is(':visible')) {
			box_visible = 1;
		}
	}

	$.ajax({
		url:		"/ajax/hive/update_all_hive_panels.php",
		type:		"POST",
		data:		"box_exists="+box_exists+"&box_visible="+box_visible+"&not_active=1",
		dataType:	"json",
		success:	CB_UpdateAllHivePanels
	});

	active_tab = null;
	hive_panel = null;
	hive_list = null;

	InitializeSponsorPaging();

	window.hive_update_timer = window.setTimeout('UpdateAllHivePanels()', Hive.update_delay);
}
function CB_UpdateAllHivePanels(object) {
	var tab_start_index = 0;
	// Get the current hive tab selected.. if there is one.
	var hive_tabs = $('#hive_tabs_'+GetActiveTabId());
	if(hive_tabs.length > 0) {
		// Tabs exist. Which one is currently active?
		tab_start_index = $('ul.hive_anchors/li.hive-tabs-selected a', hive_tabs).attr('index');
	}
	// Now we just want to update the current active tab....
	var tmp = GetScrollCoordinates();

	Hive.updatePanel(object.tab_id, object.html, tab_start_index);

	window.scrollTo(tmp.x,tmp.y);

	delete tmp;
	delete object;
	delete tab_start_index;
}

// #################################################
function HaveActiveHive() {
	var active_tab = GetActiveTabId();

	var active_hive = $('#section_'+active_tab).find('input.hiveid');
	if($(active_hive).val() > 0) {
		return $(active_hive).val();
	} else {
		return false;
	}
}

// Base64 module.
//eval(function(p,a,c,k,e,r){e=function(c){return(c<a?'':e(parseInt(c/a)))+((c=c%a)>35?String.fromCharCode(c+29):c.toString(36))};if(!''.replace(/^/,String)){while(c--)r[e(c)]=k[c]||e(c);k=[function(e){return r[e]}];e=function(){return'\\w+'};c=1};while(c--)if(k[c])p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k[c]);return p}('5 E={e:"X+/=",U:x(a){5 b="";5 c,m,j,C,q,f,h;5 i=0;a=E.K(a);F(i<a.z){c=a.k(i++);m=a.k(i++);j=a.k(i++);C=c>>2;q=((c&3)<<4)|(m>>4);f=((m&D)<<2)|(j>>6);h=j&s;l(J(m)){f=h=w}v l(J(j)){h=w}b=b+p.e.o(C)+p.e.o(q)+p.e.o(f)+p.e.o(h)}B b},Y:x(a){5 b="";5 c,m,j;5 d,q,f,h;5 i=0;a=a.L(/[^A-W-V-9\\+\\/\\=]/g,"");F(i<a.z){d=p.e.y(a.o(i++));q=p.e.y(a.o(i++));f=p.e.y(a.o(i++));h=p.e.y(a.o(i++));c=(d<<2)|(q>>4);m=((q&D)<<4)|(f>>2);j=((f&3)<<6)|h;b=b+7.8(c);l(f!=w){b=b+7.8(m)}l(h!=w){b=b+7.8(j)}}b=E.I(b);B b},K:x(a){a=a.L(/\\r\\n/g,"\\n");5 b="";T(5 n=0;n<a.z;n++){5 c=a.k(n);l(c<t){b+=7.8(c)}v l((c>S)&&(c<R)){b+=7.8((c>>6)|Q);b+=7.8((c&s)|t)}v{b+=7.8((c>>H)|G);b+=7.8(((c>>6)&s)|t);b+=7.8((c&s)|t)}}B b},I:x(a){5 b="";5 i=0;5 c=P=u=0;F(i<a.z){c=a.k(i);l(c<t){b+=7.8(c);i++}v l((c>O)&&(c<G)){u=a.k(i+1);b+=7.8(((c&N)<<6)|(u&s));i+=2}v{u=a.k(i+1);M=a.k(i+2);b+=7.8(((c&D)<<H)|((u&s)<<6)|(M&s));i+=3}}B b}}',61,61,'|||||var||String|fromCharCode||||||_keyStr|enc3||enc4||chr3|charCodeAt|if|chr2||charAt|this|enc2||63|128|c2|else|64|function|indexOf|length||return|enc1|15|Base64|while|224|12|_utf8_decode|isNaN|_utf8_encode|replace|c3|31|191|c1|192|2048|127|for|encode|z0|Za|ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789|decode'.split('|'),0,{}))

// #################################################
function OpenHiveResults(type,use_loading,tab_id) {
	OpenHiveShortlist(type,'',use_loading,tab_id);
}

// #################################################
function SortHiveShortlist(link,search_type,hive_id,tab_id) {
	if($(link).is('.sort_date')) {
		//Change the link and move on.
		$(link).html('Sort by Relevance')
			.removeClass('sort_date')
			.addClass('sort_relevance');

		$.get('/ajax/hive/sort_hive_list.php?sort_by=timestamp', function() {
			//Refresh the hive list.
			OpenHiveShortlist(search_type, hive_id, '', tab_id, 'timestamp');
		});
	} else {
		//Change the link and move on.
		$(link).html('Sort by date')
			.removeClass('sort_relevance')
			.addClass('sort_date');
		$.get('/ajax/hive/sort_hive_list.php?sort_by=score', function() {
			//Refresh the hive list.
			OpenHiveShortlist(search_type, hive_id, '', tab_id, 'score');
		});
	}
}

// #################################################
function OpenHiveShortlist(search_type, hive_id, use_loading, tab_id, sort_by) {
	var tmp = GetScrollCoordinates();

	if(!sort_by) {
//		sort_by = 'score';
	}

	if(!hive_id) {
		hive_id = 0;
	}

	if(!tab_id) {
		tab_id = GetActiveTabId();
	}

	if(typeof(use_loading) == 'undefined') {
		use_loading = 1;
	}

	if(typeof(sort_by) == 'undefined') {
		sort_by = '';
	}

	// Serialize data.
	serialized_data = GetSerializedTabs();

	// See if the previous search is complete. If it's not, do not process another one yet. Causes conflicts.
	if(!previous_search_complete) {return false;}

	var use_active_tab = 0;

	previous_search_complete = false;

	if(use_loading) {
		//Add the loading image to the search bar
		AddLoadingImage();
	}

	$.ajax({
		type:		"GET",
		url:		"/ajax/hive/open_hive_shortlist.php",
		dataType:	"json",
		data:		serialized_data + "use_active_tab=" + use_active_tab + "&hive_id=" + hive_id + "&active_tab="+tab_id+"&search_type="+search_type+"&password="+password+"&sort_by="+sort_by,
		ifModified:	true,
		success:	function(obj) {
						previous_search_complete = true;
						if(obj.previous_tab_id > 0 && obj.previous_tab_id != tab_id) {
							//We have a previous tab with this search term, and it's not the active tab.  Set to active tab.
							SetActiveTab(obj.previous_tab_id);
							RemoveLoadingImage();
						} else {
							if(obj.alter_tab != 1) {
								//Open this tab.
								CreateTab(obj);
							} else {
								if(obj.do_not_update != 1) {
									//Update the content of this hive list.
									var tmp_area = $('#section_'+tab_id+' div.result-header');
									$(tmp_area).addClass('old_copy');
									$(tmp_area).siblings().addClass('old_copy');

									$('#section_'+tab_id).prepend(obj.section_content); // prepend new content.
									$('#section_'+tab_id+' .old_copy').remove(); // remove old content.

									Hive.groups = [];
									if(CountTabs() > 0) {
										Hive.groups = obj["Hive.groups"];
										Hive.active_hives = obj["Hive.active_hives"];
									}

									Hive.addDropDowns();
									Hive.attachPanelEvents();
									Hive.InitializeTabs(GetActiveTabId());

//									window.scrollTo(tmp.x,tmp.y);
								}
								if(use_loading) {
									RemoveLoadingImage();
								}
							}
						}

						delete tmp;
						InitializeSponsorPaging();
					}
	});
}

// #################################################
function GetHiveIDUrlParams() {
	var active_tab = GetActiveTabId();
	var hive_id = HaveActiveHive();
	var hive_id_url = '';

	// add the hive id to the list
	if (hive_id) {
		hive_id_url = '&hive_id[]=' + hive_id;
	}

	// go through each related-tab-list searching for the current tab
	if(Hive.groups) {
		$.each(Hive.groups, function(tab_id, group){
			if(!group) {  } else {
				// if the other tab is in a hive, and the current tab is related,
				if (Hive.active_hives[tab_id] && group[active_tab]) {
					// get the other tab's hive ID
					var new_hive_id = $('#section_' + tab_id + ' input.hiveid').val();

					// add that tab's hive ID to the list of hive IDs
					hive_id_url += '&hive_id[]=' + new_hive_id;
				}
			}
		});
	}

	return hive_id_url;
}

// #################################################
function Heartbeat() {
	if(previous_search_complete == false) {
		return;
	}
	// The purpose of this function is to keep sessions alive while the user is on the site.
	$.ajax({
		url:		"/heartbeat.php",
		type:		"POST",
		data:		"not_active=1",
		dataType:	"json",
		type:		"GET",
		success:	function(object) {
			if(object.url.length) {
				window.location = object.url;
				delete object;
			} else {
				delete object;
				return;
			}
		}
	});
}

// #################################################
function ImportAsShortlist() {
	$.ajax({
		url:		"/ajax/hive/import_shortlist.php",
		type:		"GET",
		dataType:	"html",
		success:	function(text) {
			$(window.global_search_term).val('**'+text);
			SearchSubmit();
		}
	});
}

// #################################################
function ImportHivedShortlist(id) {
	$.ajax({
		url:		"/ajax/hive/import_hived_shortlist.php",
		type:		"GET",
		data:		"id="+id,
		success:	function(text) {
			$(window.global_search_term).val('**'+text);
			SearchSubmit();
		}
	});
}

// #################################################
function HivePortalDropdown(object) {
	var value = $('[@selected]', object).val();
	var html = $('[@selected]', object).html();

	BrowseHivesPaging('', value); // use BrowseHivesPaging() for sorting order.. instead of paging.. in THIS instance.
}

// #################################################
function BrowseHivesPaging(page_number,sort_by) {
	var active_tab = GetActiveTabId();
	var browse_hives_div = $('#section_'+active_tab+' div.browse_hives');

	$.ajax({
		type:		"GET",
		url:		"/ajax/hive/browse_hives.php",
		data:		"page_number="+page_number+"&sort_by="+sort_by,
		dataType:	"json",
		success:	function(object) {
			$(browse_hives_div).html(object.html);
			Hive.InitializeBrowseHives();
		}
	});
}

// #################################################
function RefreshHiveList(tab_id) {
	OpenHiveResults(-1,0,tab_id);
	window.previous_search_complete = true;
}

// THIS FUNCTION IS NOT TO BE USED.
// #################################################
function HivePanelFix() {
	// This is to fix the "indention" problem with IE6 with the "Related" hive panel tab.
	var active_tab = GetActiveTabId();
	var panel = $('#section_'+active_tab+' div.hive-panel');
	HiveRelatedOut($('div.hive_related_link', panel));
}

// #################################################
function BrowseQuicktagsPaging(page_number,prefix) {
	$.ajax({
		type:		"GET",
		url:		"/ajax/hive/browse_quicktags_paging.php",
		data:		"page_number="+page_number+"&prefix="+prefix,
		dataType:	"html",
		success:	function(html) {
			$('#'+prefix+'hive_portal_quicktags').html(html);
			Hive.InitializeTooltips();
		}
	});
}

// #################################################
function TWERQQuicktagsPaging(page_number) {
	$.ajax({
		type:		"GET",
		url:		"/ajax/twerq_quicktags_paging.php",
		data:		"page_number="+page_number,
		dataType:	"html",
		success:	function(html) {
			$('#quicktag_depot_twerq_quicktags').html(html);
			Hive.InitializeTooltips();
		}
	});
}

// #################################################
function TWERQ2GO_Login() {
	// Get username & password.
	var email = $('#twerq2go_login_form input[@name=email]').val();
	var password = $('#twerq2go_login_form input[@name=password]').val();

	var retval = false;
	// Send off an Ajax call to see if a person is already logged in.
	$.ajax({
		type:		"GET",
		async:		false,
		url:		"http://labs.twerq.com/ajax/check_logged_in.php",
		data:		"email="+encodeURIComponent(email)+"&password="+encodeURIComponent(password),
		dataType:	"json",
		success:	function(object) {
			if(object.already_logged_in == 1) {
				// Person is already logged in.
				var answer = confirm("You are already logged in from another location. Are you sure you want to log in from this location?");
				if(answer) {
					$('#twerq2go_login_form input[@name=new_loc]').val('1');
					retval = true;
				} else {
					retval = false;
				}
			} else {
				// Person is not already logged in.
				retval = true;
			}
		}
	});
	return retval;
}

// #################################################
function Sponsor_Description(object) {
	var buf = $('#demo_description');

	$(buf).html($(object).val());
}

// #################################################
function Sponsor_Company(object) {
	$('#demo_link_url').html( $(object).val() );
}

// #################################################
function Sponsor_Website(object) {
	$('#demo_website_url').html( $(object).val() );
}

// #################################################
function CheckMaxLength(object,max_length,id) {
	if(!max_length) {
		max_length = 10;
	}
	var value = $(object).val();

	if(value.length > max_length) {
		value = value.substr(0,max_length);
		$(object).val( value );
	}

	$('#demo_link'+id).html(value);
}

// #################################################
function SponsorAction(action) {
	$('#sponsor_action').val(action);
}

// #################################################
function SponsorApplication_Update() {
	var data = ParseForm('twerq_sponsor_signup');
	$.ajax({
		url:		"/ajax/sponsor_application_update.php",
		type:		"POST",
		data:		data,
		dataType:	"json",
		success:	function(object) {
			$('#sponsor_num_keywords').html(object.num_keywords);
			$('#sponsor_duration').html(object.duration);
			$('#sponsor_discount_percent').html(object.discount_percent);
			$('#sponsor_subtotal').html(object.subtotal);
			$('#sponsor_discount_amount').html(object.discount_amount);
			$('#sponsor_total').html(object.total);
		}
	});
}

// #################################################
function SponsorSignup() {
	// submit action
	return true;
}

// #################################################
function GetItemsVisible() {
	var container = $("#container");
	var fragment = $('div.fragment:last');
	var tab_id = GetActiveTabId();
	var section = document.getElementById('section_'+tab_id);

	if(section) {
		var container_width = section.clientWidth;//container.width();
		var container_length = container.children().length;
		var buffer = 7;

		if(container_width > 0) {
		//		alert( Math.floor( (container_width - 16) / (window.carousel_item_width+buffer) ) );
			return Math.floor( (container_width - 16) / (window.carousel_item_width+buffer) ); // 14px = tab arrows (both of them), +3=margin-right:3px; for class="tabitem"
		} else {
			return 0;
		}
	}

	return 0;
}

// #################################################
function InitializeCarousel(item_start) {
	if(!item_start) {
		item_start = 1;
	}
	window.carousel_items_visible = GetItemsVisible();

	// Do we have any tabs?
	if(!CountTabs()) {
		// Nope. Just return.
		$('div.jcarousel-clip').hide();
		return;
	}

//	alert("Start: " + item_start + "\nWidth: " + window.carousel_item_width + "\nItems Visible; " + window.carousel_items_visible);

	if(window.carousel_items_visible > 0) { // && window.current_carousel_items != window.carousel_items_visible) {
		window.carousel_executed = true;
		$('#mycarousel').jcarousel({
			itemScroll:				1,
			itemStart:				item_start,
			noButtons:				false,
			itemWidth:				window.carousel_item_width,
			flexibleWidth:			false,
			itemVisible:			window.carousel_items_visible,
			itemFirstInHandler:		itemFirstInHandler,
			nextButtonStateHandler: nextButtonStateHandler,
			prevButtonStateHandler: prevButtonStateHandler,
			wrap:					false,
			wrapPrev:				false,
			scrollAnimation:		0//"fast"
		});

		window.current_carousel_items = GetItemsVisible();
	}
}

// #################################################
function itemFirstInHandler(carousel, li, idx, state) {
	window.carousel_obj = carousel;
}

// #################################################
function nextButtonStateHandler(carousel, control_element, flag) {
	window.carousel_obj = carousel;

	if(!flag) {
		$('#next_tab_page').css('display', 'none');
//		alert("Next arrow should be gone");
	} else {
		$('#next_tab_page').css('display', 'block');
//		alert("Next arrow should be shown");
	}
}

// #################################################
function prevButtonStateHandler(carousel, control_element, flag) {
	window.carousel_obj = carousel;

	if(!flag) {
		$('#previous_tab_page').css('display', 'none');
//		alert("Previous arrow should be gone");
	} else {
		$('#previous_tab_page').css('display', 'block');
//		alert("Previous arrow should be shown");
	}
}

// #################################################
function GetTabIndex(tab_id) {
	return $('#tabs').children().index( $('#tab_'+tab_id)[0] ) + 1;
}

// #################################################
function TablistDropdown_SetActiveTab(id) {
	SetActiveTab(id,true);
	window.carousel_obj.scroll(GetTabIndex(id));
}

// #################################################
function GetScrollCoordinates() {
	var tmp = {};
	var iebody=(document.compatMode && document.compatMode != "BackCompat")? document.documentElement : document.body;

	tmp.x = document.all ? iebody.scrollLeft : window.pageXOffset;
	tmp.y = document.all ? iebody.scrollTop : window.pageYOffset;

	return tmp;
}

// #################################################
function GetBodyDimensions() {
	var body = $(document.body);
}

// #################################################
function EnableQuicktags() {
	$.ajax({
		type:		"GET",
		url:		"/ajax/enable_quicktags.php",
		success:	function() {
			var hide_quicktags_field = $('#settings_form input[@name=hide_quicktags]');
			if(hide_quicktags_field) {
				$(hide_quicktags_field).attr('checked','true');
			}
			$('#quicktags').show();
		}
	});
}

// #################################################
function ShowRenameShortlist(tab_id) {
	var area = $('#section_'+GetActiveTabId()+' div.searchnav_right');
	var tmp = area.html();
	var shortlist = tmp.substr(2, tmp.length-2);

	// Make sure there is not a form already... if there is, then they had already clicked on the "Rename Shortlist" link.
	if( $('form', area).length ) {
		delete area;
		delete tmp;
		delete shortlist;
		delete tab_id;
		return;
	}

	// Send off an Ajax call to get the template.
	$.ajax({
		type:		"GET",
		url:		"/ajax/templates/rename_shortlist.html",
		data:		"shortlist="+encodeURIComponent(shortlist)+"&tab_id="+tab_id,
		dataType:	"json",
		success:	function(obj) {
			area.html(obj.html);
			delete obj;
		}
	});

	delete tmp;
	delete tab_id;
	delete shortlist;
}

// #################################################
function ShowExportShortlist(tab_id) {
	var area = $('#section_'+GetActiveTabId()+' div.searchnav_right');
	var tmp = area.html();
	var shortlist = tmp.substr(2, tmp.length-2);

	// Make sure there is not a form already... if there is, then they had already clicked on the "Rename Shortlist" link.
	if( $('form', area).length ) {
		delete area;
		delete tmp;
		delete shortlist;
		delete tab_id;
		return;
	}

	// Send off an Ajax call to get the template.
	$.ajax({
		type:		"GET",
		url:		"/ajax/templates/export_shortlist.html",
		data:		"shortlist="+encodeURIComponent(shortlist)+"&tab_id="+tab_id,
		dataType:	"json",
		success:	function(obj) {
			area.html(obj.html);
			delete obj;
		}
	});

	delete tmp;
	delete tab_id;
	delete shortlist;
}

// #################################################
function SubmitRenameShortlist(form_obj) {
	var area = $('#section_'+GetActiveTabId()+' div.searchnav_right');
	var query_string = ParseForm(form_obj);

	if($('form input[@name=shortlist_name]', area).val().length < 1) {
		delete form_obj;
		return false;
	}

	delete form_obj;

	$.ajax({
		type:		"GET",
		url:		"/ajax/rename_shortlist.php",
		dataType:	"json",
		data:		query_string,
		success:	function(object) {
			// Replace the tab info and the section content header here.
			$(area).html(object.search_term);
			$('#tabid_'+GetActiveTabId()).html(object.summarized_search_term);
			$('#tabid_'+GetActiveTabId()).attr('title',object.search_term);

			// Replace the search bar.
			$('#search_term').val(object.search_term);

			// Replace a portion of the results header.
			//<span class="shortlist_search_term">**search term</span>
			$('#section_'+GetActiveTabId()+' span.shortlist_search_term').html(object.search_term);

			delete object;
			return false;
		}
	});

	return false;
}

// #################################################
function SubmitExportShortlist(form_obj) {
	var area = $('#section_'+GetActiveTabId()+' div.searchnav_right');
	var query_string = ParseForm(form_obj);

	if($('form input[@name=name]', area).val().length < 1) {
		delete form_obj;
		return false;
	}

	delete form_obj;

	area.html( window.global_search_term.val() );

	$.ajax({
		type:		"GET",
		url:		"/ajax/hive/export_shortlist.php",
		dataType:	"json",
		data:		query_string,
		success:	function(object) {
			OpenHiveShortlist(0, object.hive_id, '', GetActiveTabId(), 'timestamp');

			delete hive_id;
			delete area;
			delete query_string;
			return false;
		}
	});

	return false;
}

// #################################################
function GetSearchTerm(tab_id) {
	if(!tab_id) {
		// No tab ID. Lets use the active tab.
		tab_id = GetActiveTabId();
		if(!tab_id) {
			// No tabs are open.
			return;
		}
	}
	// Now lets extract the search term.
	return $('#tab_'+tab_id).attr('title');
}

// #################################################
function AddLoadingImage() {
	$(window.global_search_bar).addClass('loading');
	$(window.global_search_term).attr('disabled', true);
}

// #################################################
function RemoveLoadingImage() {
	//Take off the loading image.
	$(window.global_search_bar).removeClass('loading');
	$(window.global_search_term).attr('disabled', false).each(function(){
		this.blur();
		this.focus();
		this.select();
		$(this).attr('disabled',false);
		$(this).attr('unedited', 'true');
	});
}

// #################################################
var SearchHistory = {
	past_searches: [],
	current_index: -1,

	// 	#################################################
	init:	function(searches) { // searches = array.. same as what's returned via search.php in CreateTab().
		past_searches = searches;

		if(typeof past_searches == 'object') {
			if(past_searches.length > 0) {
				current_index = searches.length - 1; // the very last element.

				return true;
			}
		}

		// If it gets here, the above did not return true. Use defaults.
		current_index = -1; // Set to -1.

		return true;
	},

	// 	#################################################
	cycleUp:	function() {
		// Need to move UP once.
		// First check to see if we have any searches.
		if(past_searches.length > 0) {
			// We do have searches. What is the highest index?
			var last = past_searches.length - 1;

			// Is our current index the first index?
			if(current_index == 0) {
				// Lets cycle DOWN instead.
				current_index = last-1;
				SearchHistory.cycleDown();
				return;
			}

			// Ok, it wasn't the first index. Lets move on up!
			$(window.global_search_term).val( past_searches[current_index-1] );
			current_index--;
		}
	},

	// 	#################################################
	cycleDown:	function() {
		if(!enable_keystroke_tab_selection) return;
		// Need to move DOWN once.
		// First check to see if we have any searches.
		if(past_searches.length > 0) {
			// We do have searches. What is the highest index?
			var last = past_searches.length - 1;

			// Is our current index the last index?
			if(current_index == last) {
				// Lets cycle UP instead.
				current_index = 1;
				SearchHistory.cycleUp();
				return;
			}

			// Ok, it wasn't the last index. Lets move on up!
			$(window.global_search_term).val( past_searches[current_index+1] );
			current_index++;
		}
	}
};


// #################################################
var Tabs = {
	scrollLeft:		function() {
		if(!enable_keystroke_tab_selection) { return; }
		// Do we have any tabs to the left?
		var this_tab_index = GetTabIndex(GetActiveTabId());
		var prev_tab_index = this_tab_index - 1;

		var eq = prev_tab_index - 1;
		var prev_tab = $('#tabs li:eq('+eq+')');

		if(prev_tab.html()) {
			// We have a previous tab.
			SetActiveTab(prev_tab.attr('id').split("_")[1]);
			window.carousel_obj.scroll(GetTabIndex(eq));
		} else {
			// No previous tab. Do we have more than 1 tab?
			if(CountTabs() > 1) {
				// We do! Lets go to the very LAST tab.
				var last_tab_id = $('#tabs li.tabitem:last').attr('id').split("_")[1];
				SetActiveTab(last_tab_id);
				window.carousel_obj.scroll(GetTabIndex(last_tab_id));
			}
		}
	},

	scrollRight:	function() {
		if(!enable_keystroke_tab_selection) { return; }
		// Do we have any tabs to the right?
		var this_tab_index = GetTabIndex(GetActiveTabId());
		var next_tab_index = this_tab_index + 1;

		var eq = next_tab_index - 1;
		var next_tab = $('#tabs li:eq('+eq+')');

		if(next_tab.html()) {
			// We do have a next tab.
			SetActiveTab(next_tab.attr('id').split("_")[1]);
			window.carousel_obj.scroll(GetTabIndex(eq));
		} else {
			// No next tab. Do we have more than 1 tab?
			if(CountTabs() > 1) {
				// Sure do. Lets go to the very FIRST tab.
				var first_tab_id = $('#tabs li.tabitem:first').attr('id').split("_")[1];
				SetActiveTab(first_tab_id);
				window.carousel_obj.scroll(GetTabIndex(first_tab_id));
			}
		}
	}
};


// #################################################
function LoadEventHandlers(active_tab_flag) {
	// Event Handlers
	// onsubmit handler for the search form.
	$('#search_form')
		.unbind()
		.submit( SearchSubmit );

	$(window.global_search_term)
		.unbind()
		.click(function(){
			$(this).attr('unedited', 'false');
		})
		.keydown(function(e){
			var unedited = $(this).attr('unedited');
			$(this).attr('unedited', 'false');
//			alert("unedited="+unedited+ " AND keyCode="+e.keyCode);
			if (unedited == 'true' && e.keyCode == 32) {
				this.value += ' ';
				// move cursor to end of the text field (for IE)
				if (this.createTextRange) {
					var range = this.createTextRange();
					range.moveStart('character', this.value.length);
					range.select();
				}
				this.focus();
				return false;
			}

			// KeyDown handler for the search term text box.. and for Page Up & Page Down handlers.
			switch(e.keyCode) {
				case 33: // Page Up
					Tabs.scrollLeft();
					$(window.global_search_term).focus();
					$(window.global_search_term).select();
					return false;
				break;

				case 34: // Page Down
					Tabs.scrollRight();
					$(window.global_search_term).focus();
					$(window.global_search_term).select();
					return false;
				break;

				case 38: // Up Arrow
					SearchHistory.cycleUp();
				break;

				case 40: // Down Arrow
					SearchHistory.cycleDown();
				break;
			}
		});




	// right click on close button closes all tabs
	$(document).unbind('contextmenu').bind('contextmenu', function(e) {
		var map = $(e.target || e.srcElement).parents('.map0');
		if (map.length) {
			CloseAllTabs();
			e.preventDefault();
		}
	});

	// onclick handler for [Twerq Settings Panel]
	$('#twerq_settings_panel').unbind().click( function() { TwerqSettingsPanel(0); });

	// Detect keydown event... for spacebar.
	$(document).unbind('keydown').keydown(function(event) {
		if(event.keyCode == 32) {
			if( $(event.target).is('input[@type=text]') || $(event.target).is('textarea')) {
				return;
			}

			scroll(0,0);
			$(window.global_search_term).focus();
			$(window.global_search_term).select();
			event.preventDefault();
			return false;
		}
	});

	AddCloseButtonHandlers();
	AddTabClickHandlers();
	InitializeSavedSearch();
	InitializeTwerqTips();
	InitializeSponsorPaging();
	InitializeQTriggers();
}

// #################################################
function OpenSave_ToggleSelect(object) {
	var checkboxes = $('input.active_searches');

	if($(object).html() == 'Select All') {
		// Select all... then change it to Deselect All.
		$(checkboxes).attr('checked','checked');
		$(object).html('Deselect All');
	} else {
		// Deselect all... then cahnge it to Select All.
		$(checkboxes).attr('checked', '');
		$(object).html('Select All');
	}
}

// #################################################
function SetTipLinks() {
	//Add this so that the links in the tips box will work like the qtrigger menu.
	$('span.twerq-tips a').not('a.twerq_tip_next,a.twerq_tip_prev').unbind('click').click(function(){
		var search = window.global_search_term; //$('#search_term');
		var search_text = search.val();

		if (this.rel == 'before')
			search_text = this.innerHTML + search_text;
		else
			search_text += this.innerHTML;

		search.val(search_text);
		search.get(0).focus();

		delete search;
		delete search_text;
	});
}

// #################################################
function TabListDropdown_Remove(object, tab_id) {
	$('#tablist_dropdown_li_'+tab_id).remove();
	CloseTab(tab_id);
}

// #################################################
function InitializeTwerqTips() {
	SetTipLinks();

	$('a.twerq_tip_next').unbind('click').click(function() {
		var parent = $(this).parent();

		$.ajax({
			type:		"POST",
			url:		"/ajax/twerq_tip_next.php",
			dataType:	"json",
			success:	function(object) {
				$(parent).html( object.next_tip );
				InitializeTwerqTips();
			}
		});
	});

	$('a.twerq_tip_prev').unbind('click').click(function() {
		var parent = $(this).parent();

		$.ajax({
			type:		"POST",
			url:		"/ajax/twerq_tip_prev.php",
			dataType:	"json",
			success:	function(object) {
				$(parent).html( object.next_tip );
				InitializeTwerqTips();
			}
		});
	});
}

// #################################################
function InitializeSponsorPaging() {
	$('a.sponsor_next').unbind('click').click(function() {
		var parent = $(this).parent();

		$.ajax({
			type:		"POST",
			url:		"/ajax/next_sponsor.php",
			dataType:	"json",
			success:	function(obj) {
				var active_tab = GetActiveTabId();
				$('#tabfeatures_'+active_tab+' #sponsors').replace(obj.html);
				InitializeSponsorPaging();
				delete active_tab;
			}
		});
	});

	$('a.sponsor_prev').unbind('click').click(function() {
		var parent = $(this).parent();

		$.ajax({
			type:		"POST",
			url:		"/ajax/prev_sponsor.php",
			dataType:	"json",
			success:	function(obj) {
				var active_tab = GetActiveTabId();
				$('#tabfeatures_'+active_tab+' #sponsors').replace(obj.html);
				InitializeSponsorPaging();
				delete active_tab;
			}
		});
	});
}

// #################################################
function OpenSearch(search_term) {
	window.global_search_term.val(search_term);
	SearchSubmit();
}

// #################################################
function MasterReset() {
	var msg = "Resetting your account will remove all saved information.\nDo you wish to continue?";

	if(confirm(msg)) {
		$.get('/ajax/master_reset.php', function() {
			window.location = "/";
		});
	}
}

// #################################################
function InitializeQTriggers() {
	$('#qtriggers_wrapper div.qtrigger_item:first').removeClass('first_item').addClass('first_item').css('border-top','0');
	$('#qtriggers_wrapper div.qtrigger_item:last').removeClass('last_item').addClass('last_item').css('border-bottom','0');

	$('div.qtrigger_item').unbind('mouseover').mouseover(function() {
		$(this).addClass('qtrigger_item_hover');
		$(this).children().addClass('qtrigger_item_hover_children');
		$(this).children().children().addClass('qtrigger_item_hover_children');

		if( $(this).is('.first_item') ) {
			$(this).css('border-top','0');
		}

		if( $(this).is('.last_item') ) {
			$(this).css('border-bottom','0');
		}
	});

	$('div.qtrigger_item').unbind('mouseout').mouseout(function() {
		$(this).removeClass('qtrigger_item_hover');
		$(this).children().removeClass('qtrigger_item_hover_children');
		$(this).children().children().removeClass('qtrigger_item_hover_children');
	});

	// if you click anywhere on the body, make it remove the dropdown
	$(document).unbind('click').bind('click', function(event){
		if($(event.target).is('#qtriggers_button')) {
			return false;
		}

		if($(event.target).parent().is('div#qtriggers') && qtrigger_mode == 1) {
			return false;
		}

		HideQTriggers();
	});
}

// #################################################
function HideQTriggers() {
	$('#qtriggers').hide();
	$('#qtriggers_button').attr('src','/imgs/qtrigger_down.gif');
}

// #################################################
function SponsorLoginSubmit() {
	$('#sponsor_login_errors').html('').hide(); // remove any errors & hide the errors section.

	var data = ParseForm('sponsor_login_form');

	$.ajax({
		url:		"/ajax/sponsor_login.php",
		type:		"POST",
		data:		data,
		dataType:	"json",
		success:	function(object) {
			if(object.errors.length) {
				// We have errors.
				$('#sponsor_login_errors').html(object.errors).show();
				return false;
			} else {
				// No errors.
				window.location = object.redirect_url;
				return false;
			}
		}
	});
}
