////////////// begin global functions for interacting with profiles (outside of profile view //////////

var defaultLastUsedTab = "#discover";
var lastUsedTab        = defaultLastUsedTab;

// fn: getProfile() creates, populates, and switches
// to a profile view for a specified entity
function getProfile(pType, pID, tabTitle, fromTab) {
	$("#topNav").children('#profilesTabli').show();
	var panelID = pType+"-"+pID;
	var panelIDHash = '#' + panelID;

	if (pType == 'songs') { // just in case someone tries to get the profile for a song - play it
		ActivePlaylist.playSong(pID);
	}
	else {
		// save tab we were on:
		if (fromTab != null && typeof(fromTab) != "undefined" && fromTab != "undefined") {
			lastUsedTab = fromTab;
		} else {
			lastUsedTab = defaultLastUsedTab;
		}

		// fall back to a self-generated tab title if one wasn't provided
		if (typeof(tabTitle) == "undefined" || tabTitle == null || tabTitle == "undefined") {
			tabTitle = "Profile "+pType+":"+pID;
		}

		// select the profile tab on the MAIN tab bar,
		// or add it if necessary
		$tabs.tabs("select", "#profileTab");

		// Now select or add the appropriate profile tab (sub-tab bar)
		if ($(panelIDHash).length > 0) {
			// a profile sub-tab already exists for this profile
			// so just switch to it:
			$profileTabs.tabs("select", panelIDHash);
		}
		else {
			// Profile tab has not been created yet:
			// 1. Load content via ajax call to getProfile
			// 2. Add new tab to profileTabs and link it with profile content

			// getProfile.php
			$("<div><div style='text-align:center; margin-top:20px;'>" +
					"<img src='/assets/images/ajaxload/loader-circle1.gif' alt='Loading' /><br>" +
					"<p>Loading Profile</p></div>" +
					"</div>")
				.attr('id', panelID)
				.load("/scripts/profiles/getProfile.php", { type: pType, id: pID})
				.appendTo("body");

			// add new tab for this profile
			$profileTabs.tabs("add", panelIDHash, tabTitle);
		}
	}


}

// fn: profile_checkIfLast() is called
// each time a profile-tab is closed -- if it was the
// last remaining profile tab, the MAIN tabs bar switches
// to the previously used tab. (Usually the dashboard or search)
function profile_checkIfLast(event, ui) {
	if ($profileTabs.tabs("length") == 0) {
		// switch back to the lastUsedTab
		$tabs.tabs("select", lastUsedTab);
		$("#topNav").children('#profilesTabli').hide();
	}
}

// fn: switchToProfile() -- when user clicks on a band member
// or a band from within someone else's profile -- this fn will
// switch to the new profile.
function switchToProfile($clickedObj, profileType) {
	var targetID = $clickedObj.attr("rel");
	if (targetID != null && targetID != "") {
		var tabTitle = $clickedObj.find(".tabtitle").html();
		getProfile(profileType, targetID, tabTitle);
	}
}

