
var $profileTabs = null;
var $tabs        = null;
var photo_cdn    = "http://c1268152.cdn.cloudfiles.rackspacecloud.com/";

jQuery(document).ready(function($) {

	$("#bandManagerNewShowVenueName").autocomplete("http://api.bandsintown.com/venues/search.json", {
		minChars: 2,
		mustMatch: false,
		extraParams: {
			app_id: "kNERD",
			location: function() { return $("#bandManagerNewShowCity").val()+", "+$("#newEventStatesSelect").val(); },
			per_page: "100",
			format: "json",
			query: function() {
				return $("#bandManagerNewShowVenueName").val();
			}
		},
		formatItem: function(item) {
			//debugLog("Format item: " + item.name);
			return item.name;
		}
	});

	// band links for the "newest kNERD bands" on welcome tab
	$(".stats-content .new-bands .band-profile-link").click(function(event) {
		event.preventDefault();
		var band_id   = $(this).attr("rel");
		var band_name = $(this).children(".band_name").html();
		getProfile('band', band_id, band_name, '#what-is-knerd');
	});

	// periodically update the online vistior count
	setInterval("updateVisitorCount()", 60000); // once a minute




	$("#editShowDate").datepicker({ changeYear: 'true', yearRange: '-00:+01', dateFormat: 'yy-mm-dd', closeText: 'done' });

	$("#bandManagerNewShowDate").datepicker({ defaultDate: '+1',changeYear: 'true', yearRange: '-00:+01', dateFormat: 'yy-mm-dd',minDate: '-1', constrainInput: false, closeText: 'done' });

	// Any <button> with class="knerd-button" will get jquery UI button styles
	$(".knerd-button").button();

//unhide upload buttons
$("#songsToUpload").change(function() {
	alert("songsToUpload has changed!");
});


//	SAVE ALBUM/SONG INFO
	$("#editBandAlbumDownloadable").change(function() {
		var old_value = $(this).attr("old_value");
		var new_value = $(this).val();
		var this_id = $(this).attr("id");
		var value_type = $(this).attr("value_type");
		var element_type = $(this).attr("element_type");
		var album_id = $("#editBandAlbumId").val();
					if ($('#editBandAlbumDownloadable').is(':checked') == true)
					{
						new_value=1;
						old_value=0;
					} else {
						new_value=0;
						old_value=1;
					}
				var saveData = "new_value=" + escape(new_value) + "&element_type=" + escape(element_type) + "&value_type=" + escape(value_type) + "&album_id=" + escape(album_id);
				$.ajax({ type: 'GET', url: 'scripts/save-ajax-field.php', data: saveData, dataType: 'html',success: function(returnData) {
					if (returnData.length == "6")
					{
						var codeHTML = "download code: " + returnData + "<br/><a href=\"http://www.knerd.com/downloads\">http://www.knerd.com/downloads</a>";
							$("#albumDownloadCode").html(codeHTML);
							$("#editBandAlbumDownloadable").attr('checked', true);

					} else if (returnData == "1"){
						$("#albumDownloadCode").html("");
						$("#editBandAlbumDownloadable").attr('checked', false);
					} else {
						jAlert("There was a problem saving! Please try again. Thanks!");
						$("#albumDownloadCode").html("");
						$("#editBandAlbumDownloadable").attr('checked', false);
					}
				}});


	});


	$(".ajax_field").live("blur",function(){

		var old_value = $(this).attr("old_value");
		var new_value = $(this).val();
		var this_id = $(this).attr("id");
		var value_type = $(this).attr("value_type");
		var element_type = $(this).attr("element_type");

		if ((old_value != new_value) || (this_id == "my_band_bio") || (this_id == "my_band_together_checkbox")  || (this_id == "editBandAlbumDownloadable"))
		{
			if (element_type == "album")
			{
				var album_id = $("#editBandAlbumId").val();
				if (this_id == 'editBandAlbumDownloadable')
				{
					if ($('#editBandAlbumDownloadable').is(':checked') == true)
					{
						new_value=1;
						old_value=0;
					} else {
						new_value=0;
						old_value=1;
					}
				}
				var saveData = "new_value=" + escape(new_value) + "&element_type=" + escape(element_type) + "&value_type=" + escape(value_type) + "&album_id=" + escape(album_id);
				$.ajax({ type: 'GET', url: 'scripts/save-ajax-field.php', data: saveData, dataType: 'html',success: function(returnData) {
					if (returnData == "1")
					{
						$(this).attr({old_value: new_value});
					} else {
						jAlert("There was a problem saving! Please try again. Thanks!");
					}
				}});
			}
			else if (element_type == "song") {
				var song_id = $(this).attr("element_id");
				var saveData = "new_value=" + new_value + "&element_type=" + element_type + "&value_type=" + value_type + "&song_id=" + song_id;
				$.ajax({ type: 'GET', url: 'scripts/save-ajax-field.php', data: saveData, dataType: 'html',success: function(returnData) {
					if (returnData == "1")
					{
						$(this).attr({old_value: new_value});
					} else {
						alert("There was a problem saving! Please try again. Thanks!");
					}
				}});
			}
			else if (element_type == "person") {

			}
			else if (element_type == "band") {
				var band_id = $("#my_band_id").val();

				if (value_type == "band_zip")
				{
					newBandZip('my_band_zip','my_band_city','my_band_state','my_band_country');

					var city = $("#my_band_city");
					var state = $("#my_band_state");
					var zipCode = new_value;

					var getCountry = document.getElementById('my_band_country').value;
					var url = "http://www.geonames.org/postalCodeLookupJSON?&country=" + getCountry + "&callback=?" + "&postalcode=" + zipCode;
					$.getJSON(url, {postalcode: this.value }, function(response) {
						if (response && response.postalcodes.length && response.postalcodes[0].placeName)
						{
							city.val(response.postalcodes[0].placeName);
							state.val(response.postalcodes[0].adminName1);

							var saveData = "new_value=" + new_value + "&element_type=" + element_type + "&value_type=" + value_type + "&band_id=" + band_id + "&state=" + response.postalcodes[0].adminName1 + "&city=" + response.postalcodes[0].placeName;
							$.ajax({ type: 'GET', url: 'scripts/save-ajax-field.php', data: saveData, dataType: 'html',success: function(returnData) {
								if (returnData == "1")
								{
									$(this).attr({old_value: new_value});
									$("#my_band_city").attr({old_value: response.postalcodes[0].placeName});
									$("#my_band_state").attr({old_value: response.postalcodes[0].adminName1});
								}
							}});
						}
					});

				} else {

					var saveData = "new_value=" + new_value + "&element_type=" + element_type + "&value_type=" + value_type + "&band_id=" + band_id;
					$.ajax({ type: 'GET', url: 'scripts/save-ajax-field.php', data: saveData, dataType: 'html',success: function(returnData) {
						if (returnData == "1")
						{
							if (this_id != "my_band_bio")
							{
								$(this).attr({old_value: new_value});

							} else { $("#my_old_band_bio").html(new_value); }


						} else {
							alert("There was a problem saving! Please try again. Thanks!");
						}
					}});
				}
			}
		}
	});

//										ON CHANGE BAND TOGETHER
	$('#my_band_together_checkbox').change(function() {
		var band_id = $("#my_band_id").val();
		if ($('#my_band_together_checkbox').is(':checked'))
		{
			var saveData = "value_type=band_together&new_value=1&element_type=band" + "&band_id=" + band_id;
			$.ajax({ type: 'GET', url: 'scripts/save-ajax-field.php', data: saveData, dataType: 'html',success: function(returnData) {
				if (returnData == "1") {
					$("#my_band_together").hide();
				}
				else {
					jAlert("There was a problem saving! Please try again. Thanks!", "Error");
				}
			}});


			/* THEN AJAX FILL SQL WITH 0000*/

		} else {
			$("#my_band_together").show();
		}
	});

//									THIS IS MY DEFAULT BAND
	$('#my_default_band').change(function() {
		var band_id = $("#my_band_id").val();
		var newDefaultBandID;

		// New value will either be the band ID or 0
		if ($('#my_default_band').is(':checked')) {
			newDefaultBandID = band_id;
		} else {
			newDefaultBandID = 0;
		}

		// Save the new default band id
		$.get("/scripts/save-ajax-field.php", {
				value_type: 'default_band_id',
				new_value: newDefaultBandID,
				element_type: 'person'
			},
			function(returnData) {
				if (returnData != "1") {
					jAlert("Yikes! An error occured, your preferences were not saved. Please try again later.", "Error");

					// revert checkbox back to its previous state
					if ($('#my_default_band').is(":checked")) {
						$('#my_default_band').removeAttr("checked");
					} else {
						$('#my_default_band').attr("checked", "checked");
					}
				}
			},
			'html'
		);
	});



//		SONG PURCHASE LINK SAVE
	$(".songPurchaseURL").live("blur",function(){
		var link_id = $(this).attr("link_id");
		var old_value = $(this).attr("old_value");
		var link_url = $(this).val();

		if (old_value != link_url)
		{
			var saveData = "link_id=" + link_id + "&link_url=" + escape(link_url);
			$.ajax({ type: 'GET', url: 'scripts/save-song-purchase-link.php', data: saveData, dataType: 'html',success: function(returnData) {
				if (returnData == "0")
				{
					jAlert("The save failed! Please try again.");
				} else {
					$(this).attr({old_value: link_url});
				}
			}});
		}
	});

//		ALBUM PURCHASE LINK SAVE
	$(".albumPurchaseURL").live("blur",function(){
		var link_id   = $(this).attr("link_id");
		var old_value = $(this).attr("old_value");
		var link_url  = $(this).val();

		if (old_value != link_url)
		{
			var saveData = "link_id=" + link_id + "&link_url=" + escape(link_url);
			$.ajax({ type: 'GET', url: 'scripts/save-album-purchase-link.php', data: saveData, dataType: 'html',
				success: function(returnData) {
					if (returnData == "0")
					{
						jAlert("The save failed! Please try again.");
					} else {
						$(this).attr({old_value: link_url});
					}
				}
			});
		}
	});

	$("#newSongVideoLinkSave").click(function() {

		//var link_type = $("#editSongVideoLinksSelect").selectedValues();
		var link_url = $("#newSongVideoLinkURL").val();
		var song_id = $("#newSongVideoLinkSongID").val();
		var saveData = "song_id=" + song_id + "&link_url=" + link_url;
		$.ajax({ type: 'GET', url: 'scripts/save-new-song-video-link.php', data: saveData, dataType: 'html',
			success: function(returnData) {
				if (returnData == "0")
				{
					alert("The save failed! Please try again.");
				} else {
					updateSongVideos(song_id);
					$("#newSongVideoLinkURL").val("");
				}
			}
		});
	});


	$("#newSongPurchaseLinkSave").click(function() {

		var link_type = $("#editSongPurchaseLinksSelect").selectedValues();
		var link_url = $("#newSongPurchaseLinkURL").val();
		var song_id = $("#newSongPurchaseLinkSongID").val();
		var saveData = "song_id=" + song_id + "&link_url=" + link_url + "&link_type=" + link_type;
		$.ajax({ type: 'GET', url: 'scripts/save-new-song-purchase-link.php', data: saveData, dataType: 'html',
			success: function(returnData) {
				if (returnData == "0")
				{
					alert("The save failed! Please try again.");
				} else {
					getPurchaseSongLink(song_id);
					$("#newSongPurchaseLinkURL").val("");
				}
			}
		});
	});


	$("#newAlbumPurchaseLinkSave").click(function() {

		var link_type = $("#editAlbumPurchaseLinksSelect").selectedValues();
		var link_url = $("#newAlbumPurchaseLinkURL").val();
		var album_id = $("#editBandAlbumId").val();
		var saveData = "album_id=" + escape(album_id) + "&link_url=" + escape(link_url) + "&link_type=" + escape(link_type);
		$.ajax({ type: 'GET', url: 'scripts/save-new-album-purchase-link.php', data: saveData, dataType: 'html',
			success: function(returnData) {
				if (returnData == "0")
				{
					alert("The save failed! Please try again.");
				} else {
					getPurchaseAlbumLink(album_id);
					$("#newAlbumPurchaseLinkURL").val("");
				}
			}
		});
	});


//							CITY AUTOCOMPLETE
	$("#bandManagerNewShowCity").autocomplete({
		source: function(request, response) {
			$.ajax({
				url: "http://zafon.ws.geonames.org/searchJSON",
				dataType: "jsonp",
				data: {
					featureClass: "P",
					style: "full",
					maxRows: 12,
					name_startsWith: request.term
				},
				success: function(data) {
					response($.map(data.geonames, function(item) {
						return {
							label: item.name + (item.adminName1 ? ", " + item.adminName1 : "") + ", " + item.countryName,
							value: item.name
						};
					}));
				}
			});
		},
		minLength: 2,
		open: function() {
			$(this).removeClass("ui-corner-all").addClass("ui-corner-top");
		},
		close: function() {
			$(this).removeClass("ui-corner-top").addClass("ui-corner-all");
		}
	});

//																		DELETE BAND CLICK
	$("#deleteThisBandButton").click(function() {

		var deleteText1 = "Deleting a band will strip kNERD of all of this band's songs, credits, reviews etc. Doing this may update fans that wrote reviews. It will also cheat people out of their credits in the band that links that to other people. Are you absolutely sure you want to delete this band?";

		var deleteAlert = confirm(deleteText1);
		if(deleteAlert)
		{
			var deleteAlert2 = confirm("One last chance to reconsider, before all data is deleted forever.");
			if(deleteAlert)
			{
				var band_id = $("#myBandsEditorSelect").selectedValues();

				var deleteData = "band_id=" + band_id;
				$.ajax({ type: 'GET', url: 'scripts/delete-band.php', data: deleteData, dataType: 'html',
					success: function(returnData) {
						if (returnData == "1")
						{
							alert("Band deletion successful.");
							$("#myBandsEditorSelect").removeOption(band_id);
							$("#bandManagerBandSelect").removeOption(band_id);
							$("#myBandsEditorSelect").selectOptions("0");
							$("#bandManagerBandSelect").selectOptions("0");
							$("#myBandsEditorSelect").change();
							$("#editBandInfoDialog").dialog('close');
						} else {
							alert(returnData);
						}
					}
				});
			}
		}
	});


//																		UPLOAD SONG
	$('#songsToUpload').uploadify({		'uploader': 'js/uploadify.swf',		'script': 'scripts/uploadify_audio.php',
		onError: function(a, b, c, d) {
	        if (d.status == 404)
	            alert('Could not find upload script. Use a path relative to: ' + '<?= getcwd() ?>');
	        else if (d.type === "HTTP")
	            alert('error ' + d.type + ": " + d.info);
	        else if (d.type === "File Size")
	            alert(c.name + ' ' + d.type + ' Limit: ' + Math.round(d.sizeLimit / 1024) + 'KB');
	        else
	            alert('error ' + d.type + ": " + d.info);
	    },		'folder': 'files/music',
		'method': 'GET',		'cancelImg': '/assets/images/ui/delete.png',
		'multi': true,
		onClearQueue: function() {
			$('#addSongsDialogHelp').html("WAV, AIFF, and MP3 files accepted. WAV and AIFF files are recommended. kNERD will convert them to the best quality MP3 for you. You may upload multiple files at once!");
		},
		onAllComplete: function() {
			$('#addSongsDialogHelp').html("Uploads Completed! kNERD is analyzing your music and converting it to the best sounding MP3. Each song may take up to 5 minutes to be playable.");
		},
		'sizeLimit': '1629145600',
		//'fileExt': '*.mp3',
		'fileExt': '*.mp3;*.aiff;*.aif;*.wav',
		'fileDesc': 'More formats available soon!',
		'scriptData': {'album_id': ''}
	});

//												 ADD AND REMOVE BUTTONS
	$.extend($.ui.dialog.prototype, {
	        'addbutton': function(buttonName, func) {
	                var buttons = this.element.dialog('option', 'buttons');
	                buttons[buttonName] = func;
	                this.element.dialog('option', 'buttons', buttons);
	        }
	});

	$.extend($.ui.dialog.prototype, {
	        'removebutton': function(buttonName) {
	                var buttons = this.element.dialog('option', 'buttons');
	                delete buttons[buttonName];
	                this.element.dialog('option', 'buttons', buttons);
	        }
	});
//																	UPLOAD PERSON PHOTO
	$('#personPhotoFileInput').uploadify({
		'uploader': 'js/uploadify.swf',
		'script':   'js/uploadify-person-photo-cloud.php',
		onError: function(a, b, c, d) {
	        if (d.status == 404)
	            alert('Could not find upload script. Use a path relative to: ' + '<?= getcwd() ?>');
	        else if (d.type === "HTTP")
	            alert('error ' + d.type + ": " + d.info);
	        else if (d.type === "File Size")
	            alert(c.name + ' ' + d.type + ' Limit: ' + Math.round(d.sizeLimit / 1024) + 'KB');
	        else
	            alert('error ' + d.type + ": " + d.info);
	    },
		onClearQueue: function() {
				$('#addMyPhotosDialogHelp').html("Browse for which photos you would like to upload. You may select multiple songs at once by using the shift key while selecting files.");
			},
			onAllComplete: function() {
				$('#addMyPhotosDialogHelp').html("Uploads Completed! To add more photos, browse for which files you would like to upload. You may select multiple songs at once by using the shift key while selecting files.");
			},
	    'folder': 'files/photos',
		'method': 'GET',
		'cancelImg': '/assets/images/ui/delete.png',
		'multi': true,
		'sizeLimit': '12145600',
		'fileExt': '*.gif;*.jpeg;*.jpg;*.png;',
		'fileDesc': 'Please only upload GIF, JPG or PNG.',
		'scriptData': {'person_id': ''}
	});


//																	UPLOAD ALBUM ARTWORK
	$('#albumArtworkFileInput').uploadify({
		'uploader': 'js/uploadify.swf',
		'script': 'js/uploadify-album-photo.php',
		onError: function(a, b, c, d) {
	        if (d.status == 404)
	            alert('Could not find upload script. Use a path relative to: ' + '<?= getcwd() ?>');
	        else if (d.type === "HTTP")
	            alert('error ' + d.type + ": " + d.info);
	        else if (d.type === "File Size")
	            alert(c.name + ' ' + d.type + ' Limit: ' + Math.round(d.sizeLimit / 1024) + 'KB');
	        else
	            alert('error ' + d.type + ": " + d.info);
	    },		'folder': 'files/photos',
		'method': 'GET',		'cancelImg': '/assets/images/ui/delete.png',
		'multi': true,
		'sizeLimit': '12145600',
		'fileExt': '*.gif;*.jpeg;*.jpg;*.png;*.tif;',
		'fileDesc': 'Please only upload GIF, JPG or PNG.',
		'scriptData': {'album_id': ''}
	});

// BAND AUTOMATED LINKS DIALOG

	$("#addBandSocialImportDialog").dialog({
		bgiframe: true,
		autoOpen: false,
		show: 'slide',
		height: 405,
		width: 525,
		modal: true,
		open: function(){
			dialogHeight = $(this).dialog( "option", "height" ) - 5;
			if ($(window).height() < dialogHeight)
			{
				var newHeight = $(window).height() - 2;
				$(this).dialog({ height: newHeight });

			}
		},
		close: function(){
			//alert ("Success! Now let's add the rest of the band members!");
			loadband(function() {
				$("#editBandMembersButton").click();
				$("#editBandInfoButton").click();

			});
			var band_id = $("#my_band_id").val();
				bitData="band_id="+band_id;
				$.ajax({ type: 'GET', url: 'scripts/add_to_bit.php', data: bitData, dataType: 'html',
					success: function(returnData) {

				}});
		},
		open: function() {
			if ($(".remote-band-div").size() > 0) {
				$(".remote-band-div:first").show(); // show first result
			}
			else {
				// there were no results!
				$(this).dialog("close");
			}
		},

		buttons: {
			'yes': function() {
				var band_id = $("#my_band_id").val();
				var $visibleSection = $(".remote-band-div:visible");

				var getDataObj = { };
				var matchedClass = "";

				if ($visibleSection.hasClass("band_itunes_div"))
				{
					matchedClass = "band_itunes_div";
					getDataObj = {
						band_id:      band_id,
						type:         "itunes",
						itunes_id:    $visibleSection.data('itunes_id'),
						itunes_url:   $visibleSection.data('itunes_url'),
						itunes_amgID: $visibleSection.data('itunes_amgID')
					};
				}
				else if ($visibleSection.hasClass("band_facebook_div"))
				{
					matchedClass = "band_facebook_div";
					getDataObj = {
							band_id:                  band_id,
							type:                     "facebook",
							facebook_link:            $visibleSection.data('facebook_link'),
							facebook_large_photo_url: $visibleSection.data('facebook_large_photo_url'),
							facebook_id:              $visibleSection.data('facebook_id')
					};
				}
				else if ($visibleSection.hasClass("band_lastfm_div"))
				{
					matchedClass = "band_lastfm_div";
					getDataObj = {
							band_id:        band_id,
							type:           "lastfm",
							lastfm_url:     $visibleSection.data('lastfm_url'),
							lastfm_mbid:     $visibleSection.data('lastfm_mbid'),
							lastfm_originalImageURL:     $visibleSection.data('lastfm_originalImageURL'),
							lastfm_summary: $visibleSection.data('lastfm_summary')

					};
				}
				else if ($visibleSection.hasClass("band_myspace_div"))
				{
					matchedClass = "band_myspace_div";
					getDataObj = {
							band_id:      band_id,
							type: "myspace",
							myspace_id: $visibleSection.data('myspace_id'),
							myspace_url: $visibleSection.data('myspace_url')
					};
				}
				else {
					// uh oh! they clicked 'yes' but the visibleSection doesn't match any expected type
					jAlert("Uh oh, invalid selection", "Error");
					return;
				}


				// perform ajax call (note: this will NOT finish before continuing with this script)

				showAjaxLoad($("#addBandSocialImportDialog"));
				//debugLog("please wait while loading your band's new data.");
				if ($visibleSection.hasClass("band_itunes_div"))
				{
					jAlert("Linking your kNERD profile to iTunes so listeners may purchase your music.");
				}

				$.get("/scripts/save-new-band-social.php", getDataObj,
					function(returnData) {
						// TODO: Should do checking here to make sure save-new-band-social was successful!

						hideAjaxLoad();

						$visibleSection.hide();						// HIDE
						var $nextSection = $visibleSection.next();	// GET NEXT

						// get the next section that is of a different type, since they already clicked 'yes' for currently displayed type
						while($nextSection.size() > 0 && $nextSection.hasClass(matchedClass)) {
							$nextSection = $nextSection.next();
						}

						if ($nextSection.size() > 0) {				// CHECK IF LAST
							$nextSection.show();
						}
						else {
							// we hit the end!
							$("#addBandSocialImportDialog").dialog("close");				// CLOSE DIALOG

							jAlert ("Success! Now let's give band members their earned credits.");

							//loadband(function() {
							//	$("#editBandMembersButton").click();
							//	$("#editBandInfoButton").click();
							//});
						}
					},
					'html'
				); // end $.get


			}, // end 'yes'

			'no': function() {

				var $visibleSection = $(".remote-band-div:visible");

				if ($visibleSection.size() == 0) {
					// None were visible yet, show the first one..
					$visibleSection.first().show();
				}
				else {
					// Already have a visible section, hide it and show the next() one. Unless it was the last

					$visibleSection.hide();						// HIDE
					var $nextSection = $visibleSection.next();	// GET NEXT

					if ($nextSection.size() > 0) {				// CHECK IF LAST
						$nextSection.show();
					}
					else {
						// we hit the end!

						$(this).dialog("close");				// CLOSE DIALOG

						alert ("Success! Now let's add the rest of the band members!");
						loadband(function() {
							$("#editBandMembersButton").click();
							$("#editBandInfoButton").click();
						});

						//$("#newBandDialog").dialog('close');
					}
				}

			} // end 'no':function
		}
	});





//																	ALERT DELETE EVENT
	$("#editBandEventsDeleteDialog").dialog({
		bgiframe: true,
		autoOpen: false,
		show: 'slide',
		height: 200,
		width: 325,
		modal: true,
		open: function(){
			dialogHeight = $(this).dialog( "option", "height" ) - 5;
			if ($(window).height() < dialogHeight)
			{
				var newHeight = $(window).height() - 2;
				$(this).dialog({ height: newHeight });

			}
		},
		buttons: {
			'delete event': function() {
				var event_id = $("#editEventIDAnchor").val();
				var deleteData = "event_id=" + event_id;
				$.ajax({ type: 'GET', url: 'scripts/delete-band-event.php', data: deleteData, dataType: 'html',
					success: function(returnData) {
						if (returnData == "1")
						{
							$("#editBandEventsDeleteDialog").dialog('close');
							$("#bandEventShowEditor").hide();
							$("#bandEventNewsEditor").hide();
							$('#editBandEventsDialog').dialog('removebutton', 'save changes');
							$('#editBandEventsDialog').dialog('removebutton', 'delete event');
							$("#bandManagerEditEvents").click();
						}
						else { jAlert("Event not deleted due to unexpected error", "Error"); }
					}
				});
			},
			'DO NOT DELETE EVENT': function() {
				$("#editBandEventsDeleteDialog").dialog('close');
			}
		}
	});
//														MY EMAIL PREFERENCES
	$("#myMailSettings").dialog({
		bgiframe: true,
		autoOpen: false,
		show: 'slide',
		height: 300,
		width: 600,
		modal: true,
		open: function(){
			dialogHeight = $(this).dialog( "option", "height" ) - 5;
			if ($(window).height() < dialogHeight)
			{
				var newHeight = $(window).height() - 2;
				$(this).dialog({ height: newHeight });

			}
		},
		buttons: {
			'SAVE': function() {
				//emailData = "credits=" + creditEmail + "&news=" + newsEmail + "&weekly=" + weeklyEmail + "&sponsor=" + sponsorEmail;
				$.get('/scripts/save-email-prefs.php', $("#frmMyMailSettings").formSerialize(),
					function(returnData) {
						var error = false;
						var json = {};
						try {
							json = $.parseJSON(returnData);
							if (json.success) {
								$("#myMailSettings").dialog('close');
							} else {
								error = true;
							}
						} catch (err) {
							error = true;
							debugLog(err);
						}

						if (error) {
							if (json.message) { jAlert(json.message, "Error"); }
							else { jAlert("Uh oh, an error occured. Please try again later", "Error"); }
						}
					},
					'html'
				);
			},
			'CANCEL': function() { $(this).dialog("close");	}
		}
	});



//									BAND URL DIALOG
	$("#bandURLDialog").dialog({
		bgiframe: true,
		autoOpen: false,
		show: 'slide',
		height: 300,
		width: 350,
		modal: true,
		buttons: {
			'check availability': function() {
				$("#bandURLAlert").html("");
				var band_id = $("#my_band_id").val();
				var url = $("#bandURLInput").val();

				var urlData = "type=band&id=" + band_id + "&url=" + url;
				$.ajax({ type: 'GET', url: 'scripts/check-url-availability.php', data: urlData, dataType: 'html',
					success: function(returnData) {
						if (returnData == "1")
						{
							$.trim(url);
							var urlAlertText = "URL AVAILABLE! Your URL will be \"www.knerd.com/bands/" + url + "\". Press OK if you like this URL. Thanks!";
							var urlAlert = confirm(urlAlertText);
							if (urlAlert)
							{
								$.ajax({ type: 'GET', url: 'scripts/commit-url.php', data: urlData, dataType: 'html',
									success: function(returnData) {
										if (returnData == "1")
										{
											var urlHTML="http://www.knerd.com/bands/" + url;

											$("#my_band_url").html(urlHTML);
											$("#bandURLDialog").dialog('close');
											$("#bandURLInput").val("");
										} else {
											alert(returnData);
										}
									}
								});
							}
							else {
								url="";
							}
						} else { $("#bandURLAlert").html(returnData); }
					}
				});
			},
			'cancel': function() {
				$("#bandURLDialog").dialog('close');
			}
		}
	});
//									PERSON URL DIALOG
	$("#personURLDialog").dialog({
		bgiframe: true,
		autoOpen: false,
		show: 'slide',
		height: 250,
		width: 350,
		modal: true,
		buttons: {
			'check availability': function() {
				$("#personURLAlert").html("");
				var person_id = $("#my_person_id").val();
				var url = $("#personURLInput").val();

				var urlData = "type=person" + "&url=" + url;
				$.ajax({ type: 'GET', url: 'scripts/check-url-availability.php', data: urlData, dataType: 'html',success: function(returnData) {
					if (returnData == "1")
					{
						$.trim(url);
						var urlAlertText = "URL AVAILABLE! Your URL will be \"www.knerd.com\/people/" + url + "\". press cancel if you do not want this. Press OK if you like this URL. Thanks!";
						var urlAlert = confirm(urlAlertText);
						if (urlAlert)
						{
							urlData = "type=person&url=" + url;
							$.ajax({ type: 'GET', url: 'scripts/commit-url.php', data: urlData, dataType: 'html',
								success: function(returnData) {
									if (returnData == "1")
									{
										var urlHTML="DIRECT LINK: http://www.knerd.com/people/" + url;

										$("#my_person_url").html(urlHTML);
										$("#personURLInput").val("");
										$("#personURLDialog").dialog('close');
									} else {
										alert(returnData);
									}
								}
							});

						} else {
							url="";
						}
					} else { $("#personURLAlert").html(returnData); }
				}});
			},
			'cancel': function() {
				$("#personURLDialog").dialog('close');
			}
		}
	});


//																			SEARCH PROFILE ALREADY OPENED!
	$("#searchAlreadyExists").dialog({
		bgiframe: true,
		autoOpen: false,
		show: 'slide',
		height: 100,
		width: 250,
		modal: true,
		buttons: {

		'close': function() {
			$(this).dialog('close');
		}
	}});
//														EDIT BAND EVENT
	$("#bandManagerEditEvents").click(function(){
		var band_id = $("#myBandsEditorSelect").val();

		initializeAndOpenEventEditorDialog();

		var bandEventData = "band_id=" + band_id;
		$.ajax({ type: 'GET', url: 'scripts/get-band-event-list.php', data: bandEventData, dataType: 'html',
			success: function(returnData) {
				try {
					var json = $.parseJSON(returnData);
					if (json.success == true)
					{
						var eventListHTML= "<div>";
						$.each(json.band_events, function(key,element){
							eventListHTML += "<div onClick=\"displayEventToEdit('" + element.id + "');\" class=\"bandEventItem\">SHOW: <span>" +  element.date  + ": " + element.venue_name + ", " + element.event_region + "</span></div>";
						});

						eventListHTML += "</div>";
						$("#bandEventListDiv").html(eventListHTML);
					}
				}
				catch (err) {
					jAlert("Unexpected error!", "Yikes");
				}
			}
		});
	});


//														EDIT BAND EVENT DIALOG

	$("#editBandEventsDialog").dialog({// note: dialog shared between 'event' and 'news' editor for bands
		bgiframe: true,
		autoOpen: false,
		show: 'slide',
		height: 435,
		width: 600,
		modal: true,
		open: function(){
			dialogHeight = $(this).dialog( "option", "height" ) - 5;
			if ($(window).height() < dialogHeight)
			{
				var newHeight = $(window).height() - 2;
				$(this).dialog({ height: newHeight });

			}
		},
		buttons: {
			'close': function() {
				$(this).dialog('close');

				$("#bandEventListDiv").html("");

				$("#bandEventShowEditor").hide();
				$("#bandEventNewsEditor").hide();
			}
		}
	});

	function initializeAndOpenEventEditorDialog() {
		$("#editBandEventsDialog").dialog('open');
		$("#editBandEventsDialog").dialog('removebutton', 'save changes');
		$("#editBandEventsDialog").dialog('removebutton', 'delete event');

		$("#bandEventListDiv").html("");

		$("#bandEventShowEditor").hide();
		$("#bandEventNewsEditor").hide();
	}

//												EDIT BAND NEWS
	$("#bandManagerEditNews").click(function(){ // NEW!
		var bandID = $("#myBandsEditorSelect").val();

		initializeAndOpenEventEditorDialog();

		$.getJSON("/scripts/get-band-news.php",
			{ band_id: bandID },
			function(json) {
				if (json.success) {
					// loop through json.band_news
					var eventListHTML= "<div>";
					$.each(json.band_news, function(key,element) {
						eventListHTML += "<div onclick=\"displayNewsToEdit('" + element.id + "');\" class=\"bandEventItem\">NEWS: <span>" + element.news_headline + "</span></div>";
					});
					eventListHTML += "</div>";
					$("#bandEventListDiv").html(eventListHTML);
				}
				else if (!json.logged_in) {
					warnNoLoginSession();
				}
				else {
					// error
					var errorMsg = json.message || "An error occurred, please try again";
					jAlert(errorMsg);
				}
			}
		);
	});


//													SONG PURCHASE LINK EDIT
	$("#editSongPurchaseLinksDialog").dialog({
		bgiframe: true,
		autoOpen: false,
		show: 'slide',
		height: 250,
		width: 300,
		modal: true,
		buttons: {
			'close': function() {

				$("#editNewsHeadline").val("");
				$("#editNewsLink").val("");
				$("#editNewsDescription").val("");
				$("#editEventIDAnchor").val("");
				$("#bandEventShowEditor").hide();
				$("#bandEventNewsEditor").hide();
				$('#editBandEventsDialog').dialog('removebutton', 'save changes');
				$('#editBandEventsDialog').dialog('removebutton', 'delete event');
				//$("#editShowDate").val("");
				//$("#editShowDoorTime").selectedValues("");
				//$("#editShowDoorMinutes").selectedValues("");
				//$("#editShowAmPm").selectedTexts("");
				$("#editEventCountriesSelect").selectedValues("nothing");
				//$("#editEventStatesSelect").selectedTexts("");
				$("#editEventShowCity").val("");
				$("#editShowVenueName").val("");
				$("#editEventShowLink").val("");
				$("#editShowTicketLink").val("");
				$("#editShowTicketPrice").val("");
				$("#editShowTicketDoorPrice").val("");
				$("#editEventShowDescription").val("");

				$(this).dialog('close');
			}
		}
	});

//													ALBUM PURCHASE LINK EDIT
	$("#editAlbumPurchaseLinksDialog").dialog({
		bgiframe: true,
		autoOpen: false,
		show: 'slide',
		height: 375,
		width: 400,
		modal: true,
		open: function(){
			dialogHeight = $(this).dialog( "option", "height" ) - 5;
			if ($(window).height() < dialogHeight)
			{
				var newHeight = $(window).height() - 2;
				$(this).dialog({ height: newHeight });

			}
		},
		buttons: {
			'close': function() {
				$(this).dialog('close');
			}
		}
	});

//													SONG VIDEO LINK
	$("#editSongVideosDialog").dialog({
		bgiframe: true,
		autoOpen: false,
		show: 'slide',
		height: 400,
		width: 400,
		modal: true,
		open: function(){
			dialogHeight = $(this).dialog( "option", "height" ) - 5;
			if ($(window).height() < dialogHeight)
			{
				var newHeight = $(window).height() - 2;
				$(this).dialog({ height: newHeight });

			}
		},
		buttons: {
			'close': function() {
				$(this).dialog('close');
			}
		}
	});


//																	CHANGE PASSWORD DIALOG
	$("#changePaswordDialog").dialog({
		bgiframe: true,
		autoOpen: false,
		show: 'slide',
		height: 250,
		width: 400,
		modal: true,
		close: function() {
				$("#changePasswordAlertBox").html("");
				$("#newPasswordInput").val("");
				$("#newPasswordVerifyInput").val("");
				$("#currentPasswordInput").val("");
		},
		buttons: {
			'change': function() {
				var newPassword       = $("#newPasswordInput").val();
				var newPasswordVerify = $("#newPasswordVerifyInput").val();
				var currentPassword   = $("#currentPasswordInput").val();

				if ((newPassword.length < "7") ) {
					$("#changePasswordAlertBox").html("Your password must be at least 7 characters long.");
				}
				else
				{
					if (newPassword != newPasswordVerify) {
						$("#changePasswordAlertBox").html("Your new passwords to not match, please retype them");
					}
					else { //end of	if (newPassword <> newPasswordVerify)

						if (newPassword != "")
						{
							$.post("/scripts/change-my-password.php", {
									new_password:     $.md5(newPassword),
									current_password: $.md5(currentPassword)
								},
								function(returnData)	{
									var isError = false;
									var errorMsg = "An unexpected error occured. Please try again or <a href='mailto:suggestions@knerd.com'>contact us</a> if the problem persists";
									try {
										var json = $.parseJSON(returnData);
										if (!json.logged_in) { // Not logged in!
											warnNoLoginSession();
										}
										else if (json.success) { // succesfully changed password
											$("#changePasswordAlertBox").html("password changed was successful.");
											$("#changePasswordAlertBox").html("");
											$("#newPasswordInput").val("");
											$("#newPasswordVerifyInput").val("");
											$("#currentPasswordInput").val("");
											$("#changePaswordDialog").dialog('close');
										}
										else { // some error occured, display message
											isError = true;
											if (json.message) { errorMsg = json.message; }
										}
									} catch (err) {
										isError = true;
									}

									if (isError) {
										$("#changePasswordAlertBox").html(errorMsg);
									}
								},
								'html'
							); // end $.post
						}//end of else
					}
				}
			},
			'cancel': function() {
				$(this).dialog('close');
			} // end 'change password' function
		}
	});


	$("#changePasswordButton").click(function(){
		$("#changePaswordDialog").dialog('open');
	});


//																					ADVANCED SEARCH
	$("#memberProfile").dialog({
		bgiframe: true,
		autoOpen: false,
		show: 'slide',
		height: 600,
		width: 600,
		modal: true,
		open: function(){
			dialogHeight = $(this).dialog( "option", "height" ) - 5;
			if ($(window).height() < dialogHeight)
			{
				var newHeight = $(window).height() - 2;
				$(this).dialog({ height: newHeight });

			}
		},
		buttons: {
			'close': function() {
				$(this).dialog('close');
			}
		}
	});

//																					New Band Event Click
	$("#bandManagerNewEventButton").click(function(){
		//get_states('newEventCountriesSelect','newEventStatesSelect');
		$("#addBandEventSelect").show();
	});


//																					UPLOAD BAND PHOTO
	$("#editBandPhotosButton").click(function(){
		var band_id = $("#my_band_id").val();
		KJPhoto.instance.managePhotosFor('band', band_id, 'Edit Band Photos');

		// TODO: remove old band photos functions and dialogs
	//	getBandPhotos(band_id);

	});


//																					NEW ALBUM ARTWORK
	$("#newAlbumArtworkDialog").dialog({
		bgiframe: true,
		autoOpen: false,
		show: 'slide',
		height: 300,
		width: 350,
		modal: true,
		open: function(){
			dialogHeight = $(this).dialog( "option", "height" ) - 5;
			if ($(window).height() < dialogHeight)
			{
				var newHeight = $(window).height() - 2;
				$(this).dialog({ height: newHeight });

			}
		},
		close: function() {
			albumID = $("#editBandAlbumId").val();
			getAlbumArtwork(albumID);
		},
		buttons: {
			'close': function() {
				$(this).dialog('close');
			}
		}
	});

//																					EDIT ALBUM ARTWORK
	$("#editAlbumArtworkDialog").dialog({
		bgiframe: true,
		autoOpen: false,
		show: 'slide',
		height: 500,
		width: 350,
		modal: true,
		open: function(){
			dialogHeight = $(this).dialog( "option", "height" ) - 5;
			if ($(window).height() < dialogHeight)
			{
				var newHeight = $(window).height() - 2;
				$(this).dialog({ height: newHeight });

			}
		},
		close: function() {
			$("#editAlbumArtworkTable").html("");
		},
		buttons: {
			'close': function() {
				$(this).dialog('close');
			},
			'new photo': function() {
				$("#newAlbumArtworkDialog").dialog('open');
			}
		}
	});


//																					UPLOAD MY PHOTOS
//$("#editPersonPhotosDialog").dialog({
//	bgiframe: true,
//	autoOpen: false,
//	height: 400,
//	width: 300,
//	modal: true,
//	close: function() {
//			$("#editPersonPhotosContent").html("");
//		},
//	buttons: {
//		'close': function() {
//			$(this).dialog('close');
//		},
//		'new photo': function() {
//			$("#newPersonPhotoDialog").dialog('open');
//		}
//	}
//});

//$("#newPersonPhotoDialog").dialog({
//	bgiframe: true,
//	autoOpen: false,
//	height: 300,
//	width: 350,
//	modal: true,
//	buttons: {
//		'close': function() {
//			$('#changeMyPhotos').click();
//			$(this).dialog('close');
//		}
//	}
//});

//																					EDIT MY LINKS
	$("#editMyLinksDialog").dialog({
		bgiframe: true,
		autoOpen: false,
		show: 'slide',
		height: 300,
		width: 400,
		modal: true,
		open: function(){
			dialogHeight = $(this).dialog( "option", "height" ) - 5;
			if ($(window).height() < dialogHeight)
			{
				var newHeight = $(window).height() - 2;
				$(this).dialog({ height: newHeight });

			}
		},
		close: function() {
		$("#myNewLinkInputBox").val("");
		},
		buttons: {

			'close': function() {
				$(this).dialog('close');
				$("#myNewLinkInputBox").val("");
			},
			'new link': function() {
				$("#addMyLinksDialog").dialog('open');

			}
		}
	});

//																		ADD MY NEW LINKS
	$("#addMyLinksDialog").dialog({
		bgiframe: true,
		autoOpen: false,
		show: 'slide',
		height: 200,
		width: 300,
		modal: true,
		close: function() {
		$("#myNewLinkInputBox").val("");
		},
		buttons: {
			'save': function() {

				newMyLinkTypeValue = $("#myNewLinkSelect").val();
				newMyLinkURLValue = $("#myNewLinkInputBox").val();

				newMyLinkData = "link_type=" + newMyLinkTypeValue + "&" + "link_url=" + newMyLinkURLValue;
				$.ajax({ type: 'GET', url: 'scripts/save-my-new-link.php', data: newMyLinkData, dataType: 'html',success: function(returnData)	{
					$("#editMyLinks").click();
					$("#addMyLinksDialog").dialog('close');


					}
				});

			},
			'cancel': function() {
				$(this).dialog('close');
			}
		}
	});

//																			GET MY LINKS
	$("#editMyLinks").click(function(){
		$("#myLinkDiv").html("");
		$.ajax({ type: 'GET', url: 'scripts/get-my-links.php', dataType: 'html',
			success: function(returnData) {
				var linkHTML;
				try {
					var json = $.parseJSON(returnData);
					if (json.success == true)
					{
						linkHTML= "<div>";
						$.each(json.my_links, function(key,element){
							linkHTML +=  "<div class=\"socialLink formRow clearfix\" id=\"link" + element.id + "\"><div class=\"editIcons\"><span class=\"ui-icon ui-icon-trash\" onclick=\"deleteMyLink(" + element.id + ");\"  /></div><div class=\"floatleft\"><div class=\"socialIcon " + element.link_type + "\"></div>" + element.site_url + "</div></div>";
						});

						linkHTML += "</div>";
						$("#myLinkDiv").html(linkHTML);
					}
				} catch (err) {
						jAlert("Unexpected error", "Yikes!");
				}

				$('#editMyLinksDialog').dialog('open');
			}
		}); // end $.ajax
	});

//																addBandEventSelect OnChange
	$("#addBandEventSelect").change(function(){
		$("#addNewBandShowDiv").hide();
		//$("#addNewBandNewsDiv").hide(); // left over from when bands and shows shared dialog

		if ($(this).val() != "0")
		{
			get_states('newEventCountriesSelect','newEventStatesSelect');

			if ($(this).val() == "show")
			{
				$("#newBandEventsDialog").dialog('open'); // formerly a shared dialog wrapper
				$("#addNewBandShowDiv").show(); // new show!
			}
			else if ($(this).val() == "news")
			{
				$("#addNewBandNewsDiv").dialog("open"); // band news!
				//$("#addNewBandNewsDiv").show(); // band news!
			}
		}

		// Reset dropdown so additional events/news can be added
		$(this).val("0");
	});

//																EDIT BAND ALBUMS
	$("#editMyBandAlbums").click(function(){
		band_id = $("#my_band_id").val();
		getMyAlbumsData= "band_id=" + band_id;
		$("#editMyBandAlbumsTable ul").html("");
		$.ajax({ type: 'GET', url: 'scripts/get-my-albums.php', data: getMyAlbumsData, dataType: 'html',
			success: function(returnData) {
				albumData = returnData.split("::");
				arrayPlace = "0";
				numAlbums = albumData[arrayPlace];
				arrayPlace++;
				if (numAlbums < "1") {
					editAlbumTableHTML = "<p><a class=\"text\"><ul>This band has no albums yet!</ul><br/> Once an album is added, songs may be uploaded into it. To add an album, click \"add album\" below. </a><br/><br/></p><a>kNERD tip: If you only want to upload a single, create an album with the name as the song title and \"single\".</a>";
					$("#editMyBandAlbumsDialogSongDiv").html("");
					$("#editMyBandAlbumsDialogSongDiv").append(editAlbumTableHTML);
					$("#editMyBandAlbumsDialogSongDiv").show();

					} else {
						editAlbumTableHTML = "";
						albumNum = "1";
						while (albumNum <= numAlbums)
						{

							editAlbumTableHTML = editAlbumTableHTML + "<li><a id=\"album" + albumData[arrayPlace] + "\" class=\"ajax-button\" onclick=\"editAlbum(" + albumData[arrayPlace] + ")\">";
							arrayPlace++;
							editAlbumTableHTML = editAlbumTableHTML + albumData[arrayPlace] + "(";
							arrayPlace++;
							editAlbumTableHTML = editAlbumTableHTML + albumData[arrayPlace] + ")</a></li>";
							arrayPlace++; arrayPlace++;
							albumNum++;

						}
					$("#editMyBandAlbumsTable ul").append(editAlbumTableHTML);
				}
			}
		}); // end $.ajax

		$("#editMyBandAlbumsDialog").dialog('open');

	});

	$("#editMyBandAlbumsDialog").dialog({
		bgiframe: true,
		autoOpen: false,
		show: 'slide',
		show: 'slide',
		height: 500,
		width: 785,
		modal: true,
		open: function(){
			dialogHeight = $(this).dialog( "option", "height" ) - 5;
			if ($(window).height() < dialogHeight)
			{
				var newHeight = $(window).height() - 2;
				$(this).dialog({ height: newHeight });

			}
		},
		close: function() {
			$("#editMyBandAlbumsDialogRIGHT").hide();
			$("#editMyBandAlbumsDialogSongDiv").hide();
			$('#editMyBandAlbumsDialog').dialog('removebutton', 'add songs');
			$('#editMyBandAlbumsDialog').dialog('removebutton', 'edit credits');
			$('#editMyBandAlbumsDialog').dialog('removebutton', 'delete album');
			$('#editMyBandAlbumsDialog').dialog('removebutton', 'artwork');
			$('#editMyBandAlbumsDialog').dialog('removebutton', 'purchase links');
			$("#editBandAlbumId").val("");
			$("#editBandAlbumTitle").val("");
			$("#editBandAlbumCopyright").val("");
			$("#editBandAlbumLabel").val("");
			$("#editBandAlbumPublisher").val("");
			$("#editBandAlbumNumTracks").val("");
			$("#editBandAlbumDescription").val("");
		},
		buttons: {
			'close': function() {
				$("#editMyBandAlbumsDialogSongDiv").html("");
				$(this).dialog('close');
			},

			'add album': function() {
				$("#addNewAlbumDialog").dialog('open');
			}
		}
	});

//																	Save New Song Credit
	$("#saveNewSongCredit").click(function(){
		var newCreditUserID = $("#updateSongCreditsEmailAlert").attr("title");
		var updateSongCreditsEmail = $("#updateSongCreditsEmail").val();
		var updateSongCreditsFirstName = $("#updateSongCreditsFirstName").val();
		var updateSongCreditsLastName = $("#updateSongCreditsLastName").val();
		var updateSongCreditsRole = $("#updateSongCreditsRole").val();


		if ((updateSongCreditsEmail.length < "7") || (updateSongCreditsFirstName == "") || (updateSongCreditsLastName == ""))
		{
			alert("Please be sure that you typed in a complete email address, first name and last name.");
		}
		else {
			if (newCreditUserID != "")
			{
				$("#updateSongCreditsEmailAlert").attr({title: ""});
				$("#updateAlbumCreditsEmailAlert").attr({title: ""});
				var userAlreadyExists = "1";
				var updateSongCreditsRole = $("#updateSongCreditsRole").val();
				var songId = $("#newSongCreditID").attr("title");
				var saveNewSongCreditData = "data=1::" + newCreditUserID + "::" + updateSongCreditsRole + "::" + songId;


			} else {
				var userAlreadyExists = "0";
				$("#updateSongCreditsEmailAlert").attr({title: ""});
				$("#updateAlbumCreditsEmailAlert").attr({title: ""});
				//updateSongCreditsEmail = $("#updateSongCreditsEmail").val();
				//updateSongCreditsFirstName = $("#updateSongCreditsFirstName").val();
				//updateSongCreditsLastName = $("#updateSongCreditsLastName").val();
				//updateSongCreditsRole = $("#updateSongCreditsRole").val();
				var songId = $("#newSongCreditID").attr("title");
				var saveNewSongCreditData = "data=" + userAlreadyExists + "::" + updateSongCreditsEmail + "::" + updateSongCreditsFirstName + "::" + updateSongCreditsLastName + "::" + updateSongCreditsRole + "::" + songId;
			}

			$.ajax({ type: 'GET', url: 'scripts/save-new-song-credit.php', data: saveNewSongCreditData, dataType: 'html',success: function(returnData) {

				$("#newSongCreditID").attr({title: ""});
				$("#updateSongCreditsEmail").val("");
				$("#updateSongCreditsFirstName").val("");
				$("#updateSongCreditsLastName").val("");

				updateSongCredits(songId);
			}});
		}
	});



//																				SAVE ALBUM CREDIT
	$("#saveNewAlbumCredit").click(function(){
		newCreditUserID = $("#updateAlbumCreditsEmailAlert").attr("title");
		//EDIT THIS
		var updateAlbumCreditsEmail = $("#updateAlbumCreditsEmail").val();
		var updateAlbumCreditsFirstName = $("#updateAlbumCreditsFirstName").val();
		var updateAlbumCreditsLastName = $("#updateAlbumCreditsLastName").val();
		var updateAlbumCreditsRole = $("#updateAlbumCreditsRole").val();

		if ((updateAlbumCreditsEmail.length < "7") || (updateAlbumCreditsFirstName == "") || (updateAlbumCreditsLastName == ""))
		{
			alert("Please be sure that you typed in a complete email address, first name and last name.");
		} else {
			// TO HERE FOR ALBUM CREDITS
			if (newCreditUserID != "") {
				var userAlreadyExists = "1";
				$("#updateAlbumCreditsEmailAlert").attr({ title: ""});
				var updateSongCreditsRole = $("#updateAlbumCreditsRole").val();
				var albumId = $("#editBandAlbumId").val();
				var saveNewAlbumCreditData = "data=1::" + newCreditUserID + "::" + updateSongCreditsRole + "::" + albumId;
			}
			else {
				var userAlreadyExists = "0";
				$("#updateAlbumCreditsEmailAlert").attr({ title: ""});
				//updateAlbumCreditsEmail = $("#updateAlbumCreditsEmail").val();
				//updateAlbumCreditsFirstName = $("#updateAlbumCreditsFirstName").val();
				//updateAlbumCreditsLastName = $("#updateAlbumCreditsLastName").val();
				//updateAlbumCreditsRole = $("#updateAlbumCreditsRole").val();
				albumId = $("#editBandAlbumId").val();
				saveNewAlbumCreditData = "data=" + userAlreadyExists + "::" + updateAlbumCreditsEmail + "::" + updateAlbumCreditsFirstName + "::" + updateAlbumCreditsLastName + "::" + updateAlbumCreditsRole + "::" + albumId;
			}

			$.ajax({ type: 'GET', url: 'scripts/save-new-album-credit.php', data: saveNewAlbumCreditData, dataType: 'html',
				success: function(returnData) {
					$("#updateAlbumCreditsEmailAlert").attr({title: ""});
					$("#updateSongCreditsEmailAlert").attr({title: ""});
					$("#updateAlbumCreditsEmail").val("");
					$("#updateAlbumCreditsFirstName").val("");
					$("#updateAlbumCreditsLastName").val("");

					updateAlbumCredits(albumId);
					editBandAlbumCredits();
				}
			});
		}
	});


//																CONFIRM SONG DELETION
	$("#DeleteSongConfirmDialog").dialog({
		bgiframe: true,
		autoOpen: false,
		show: 'slide',
		height: 200,
		width: 300,
		modal: true,
		buttons: {
			'delete': function() {
				var songId = $("#DeleteSongConfirmSpan").attr("title");
				var deleteSongData = "song_id=" + songId;
				$.ajax({ type: 'GET', url: 'scripts/delete-my-song.php', data: deleteSongData, dataType: 'html',success: function(returnData) {
					var trHash = "#songDiv" + songId;
					//alert(trHash);
					$(trHash).remove();

					$("#DeleteSongConfirmSpan").attr({ title: ""});
					$("#DeleteSongConfirmDialog").dialog('close');
				}});
			},
			'cancel': function() {
				$(this).dialog('close');
			}
		}
	});

//															 DELETE ALBUM
$("#deleteAlbumDialog1").dialog({
	bgiframe: true,
	autoOpen: false,
		show: 'slide',
	height: 200,
	width: 300,
	modal: true,
	buttons: {
		'delete': function() {
			$("#deleteAlbumDialog2").dialog('open');
		},
		'cancel': function() {
			$(this).dialog('close');
		}
	}
});

//															CONFIRM DELETE ALBUM
	$("#deleteAlbumDialog2").dialog({
		bgiframe: true,
		autoOpen: false,
		show: 'slide',
		height: 200,
		width: 300,
		modal: true,
		buttons: {
			'delete': function() {
				album_id = $("#editBandAlbumId").val();
				deleteAlbumData = "album_id=" + album_id;
				$.ajax({ type: 'GET', url: 'scripts/delete-my-album.php', data: deleteAlbumData, dataType: 'html',
					success: function(returnData) {

					}
				});

				// TODO: this next block of code should be moved into the callback function of the $.ajax call above..
				$("#editMyBandAlbumsDialogRIGHT").hide();
				$("#editMyBandAlbumsDialogSongDiv").hide();
				$('#editMyBandAlbumsDialog').dialog('removebutton', 'add songs');
				$('#editMyBandAlbumsDialog').dialog('removebutton', 'delete album');
				$('#editMyBandAlbumsDialog').dialog('removebutton', 'artwork');
				$('#editMyBandAlbumsDialog').dialog('removebutton', 'purchase links');
				$('#editMyBandAlbumsDialog').dialog('removebutton', 'edit credits');
				$("#editBandAlbumId").val("");
				$("#editBandAlbumTitle").val("");
				$("#editBandAlbumCopyright").val("");
				$("#editBandAlbumLabel").val("");
				$("#editBandAlbumPublisher").val("");
				$("#editBandAlbumNumTracks").val("");
				$("#editBandAlbumDescription").val("");
				$(this).dialog('close');
				$("#deleteAlbumDialog1").dialog('close');
				$("#editMyBandAlbumsDialogSongDiv").html("");
				$("#editMyBandAlbums").click();
			},
			'cancel': function() {
				$(this).dialog('close');
				$("#deleteAlbumDialog1").dialog('close');
			}
		}
	});

//																	NEW ALBUM
	$("#addNewAlbumDialog").dialog({
		bgiframe: true,
		autoOpen: false,
		show: 'slide',
		height: 350,
		width: 400,
		modal: true,
		open: function(){
			dialogHeight = $(this).dialog( "option", "height" ) - 5;
			if ($(window).height() < dialogHeight)
			{
				var newHeight = $(window).height() - 2;
				$(this).dialog({ height: newHeight });

			}
		},
		close: function() {
			$("#newBandAlbumTitle").val("");
			$("#newBandAlbumNumTracks").val("");
			$("#newBandAlbumLabel").val("");
			$("#newBandAlbumPublisher").val("");
			$("#newBandAlbumDescription").val("");
		},
		buttons: {
			'save': function() {

				var band_id = $("#my_band_id").val();
				var newBandAlbumTitle = $("#newBandAlbumTitle").val();
				var newBandAlbumCopyright = $("#newBandAlbumCopyright").val();
				var newBandAlbumNumTracks = $("#newBandAlbumNumTracks").val();
				var newBandAlbumLabel = $("#newBandAlbumLabel").val();
				var newBandAlbumPublisher = $("#newBandAlbumPublisher").val();
				var newBandAlbumDescription = $("#newBandAlbumDescription").val();
				var saveNewAlbumData = "band_id=" + band_id + "&title=" + newBandAlbumTitle + "&copyright=" + newBandAlbumCopyright +
					"&numTracks=" + newBandAlbumNumTracks + "&label=" + newBandAlbumLabel + "&publisher=" + newBandAlbumPublisher +
					"&description=" + newBandAlbumDescription;

				$.ajax({ type: 'GET', url: 'scripts/save-new-album.php', data: saveNewAlbumData, dataType: 'html',
					success: function(returnData) {
						$("#editMyBandAlbumsDialogRIGHT").hide();
						$("#editMyBandAlbumsDialogSongDiv").hide();
						$("#editMyBandAlbumsDialogSongDiv").html("");
						$('#editMyBandAlbumsDialog').dialog('removebutton', 'add songs');
						$('#editMyBandAlbumsDialog').dialog('removebutton', 'artwork');
						$('#editMyBandAlbumsDialog').dialog('removebutton', 'purchase links');
						$('#editMyBandAlbumsDialog').dialog('removebutton', 'delete album');
						$("#editBandAlbumId").val("");
						$("#editBandAlbumTitle").val("");
						$("#editBandAlbumCopyright").val("");
						$("#editBandAlbumLabel").val("");
						$("#editBandAlbumPublisher").val("");
						$("#editBandAlbumNumTracks").val("");
						$("#editBandAlbumDescription").val("");
						$("#editMyBandAlbums").click();
						$("#addNewAlbumDialog").dialog('close');

					}
				});


			},
			'cancel': function() {
				$("#addNewAlbumDialog").dialog('close');
			}
		}
	});

//																Add New Songs
	$("#addSongsDialogButtonDialog").dialog({
		bgiframe: true,
		autoOpen: false,
		show: 'slide',
		height: 400,
		width: 400,
		modal: true,
		open: function(){
			dialogHeight = $(this).dialog( "option", "height" ) - 5;
			if ($(window).height() < dialogHeight)
			{
				var newHeight = $(window).height() - 2;
				$(this).dialog({ height: newHeight });

			}
		},
		buttons: {
			'close': function() {
				albumId = $("#editBandAlbumId").val();
				editAlbum(albumId);
				$('#addSongsDialogHelp').html("Browse for which .mp3s you would like to upload. You may select multiple songs at once by using the shift key while selecting files.");
				$(this).dialog('close');
			}
		}
	});



//																EDIT SONG CREDITS
	$("#updateSongCreditsDialog").dialog({
		bgiframe: true,
		autoOpen: false,
		show: 'slide',
		height: 400,
		width: 600,
		modal: true,
		open: function(){
			dialogHeight = $(this).dialog( "option", "height" ) - 5;
			if ($(window).height() < dialogHeight)
			{
				var newHeight = $(window).height() - 2;
				$(this).dialog({ height: newHeight });

			}
		},
		close: function() {
			$("#updateSongCreditsEmail").val("");
			$("#updateSongCreditsFirstName").val("");
			$("#updateSongCreditsLastName").val("");
		},
		buttons: {
			'close': function() {
				$(this).dialog('close');
			}
		}
	});


//															EDIT ALBUM CREDITS
	$("#updateAlbumCreditsDialog").dialog({
		bgiframe: true,
		autoOpen: false,
		show: 'slide',
		height: 400,
		width: 600,
		modal: true,
		open: function(){
			dialogHeight = $(this).dialog( "option", "height" ) - 5;
			if ($(window).height() < dialogHeight)
			{
				var newHeight = $(window).height() - 2;
				$(this).dialog({ height: newHeight });

			}
		},
		close: function() {
			$("#updateAlbumCreditsEmail").val("");
			$("#updateAlbumCreditsFirstName").val("");
			$("#updateAlbumCreditsLastName").val("");
		},
		buttons: {
			'close': function() {
				$(this).dialog('close');
			}
		}
	});


//																	VIEW BAND PROFILE
	$("#seeBandProfileButton").click(function(){
		var	band_id = $("#my_band_id").val();
		var band_name = $("#myBandsEditorSelect").selectedTexts();
		getProfile('bands',band_id,band_name,'#bandManagerTab');
	});


//																		EDIT BAND MEMBERSHIP
	$("#editBandMembersButton").click(function(){
		band_id = $("#my_band_id").val();
		getBandMembersEdit(band_id);
		$("#editBandMembersDialog").dialog('open');
	});

	$("#editBandMembersDialog").dialog({
		bgiframe: true,
		autoOpen: false,
		show: 'slide',
		height: 400,
		width: 400,
		modal: false,
		open: function(){
			var dialogHeight = $(this).dialog( "option", "height" ) - 5;
			if ($(window).height() < dialogHeight)
			{
				var newHeight = $(window).height() - 2;
				$(this).dialog({ height: newHeight });
			}
		},
		close: function() {
			$("#editBandMembersTable").html("");
		},
		cancel: function() {
			$("#editBandMembersTable").html("");
		},
		buttons: {
			'close': function() {
				$(this).dialog('close');
			},
			'new member': function() {
				$("#addNewMemberDialog").dialog('open');
			}
		}
	});

	(function(){ // BEGIN encapsulation for adding new band member (via FB or regular)
		//
		// DIALOG
		//
		$("#addNewMemberDialog").dialog({
			autoOpen: false,
			show: 'slide',
			modal: true,
			title: "Edit Band Members",
			width:  'auto',
			height: 'auto',
			open: function() {

				$("#new_member_search").show();
				$("#roles_checkboxes").hide();

				// Must set the band_id in here! cannot set in data{} object because it won't update..
				$("#new_member_band_id").val( $("#my_band_id").val() );

				FB.getLoginStatus(function(response) {
					if (response.session) {
						// user already logged in to FB
						populateAutocomplete();
					} else {
						// user not logged in to FB yet
						$("#fb_friends").bind('focus',function() {
							jConfirm("To use this feature you must be logged into Facebook. Would you like to login now?", 'Facebook', function(resp) {
								if (resp) {
									// PROMPT user to login to Facebook
									$.skip_fb_login_redirect_once = true; // prevents redirect to /login on FB auth
									FB.login(function(response) {
										if (response.session) { // success
											$("#fb_friends").unbind('focus'); // so they're not prompted again
											populateAutocomplete();
										}
									});
								}
							}); // jConfirm
						}); // bind.focus
					}
				}); // end FB.getLoginStatus
			}, // end open()

			buttons: {
				'Cancel': function() { $(this).dialog('close'); }
			}
		});

		// Display roles checkboxes
		$("#new_member_search .btnBandMemberRoles").click(function(e) {
			e.preventDefault();

			if (validateStep1()) {
				$("#new_member_search").hide();
				$("#roles_checkboxes").show();

				var name = "";
				if ($("#chkAddType_FB").is(":checked")) {
					name = $("#fb_friends").val();
				} else {
					name = $("#new_band_member_first_name").val() + " " + $("#new_band_member_last_name").val();
				}
				$("#choose_role_msg > span").text( name );
			}
		});

		// cancel role selection and go back to member name
		$("#btnCancelRoles").click(function(e) {
			e.preventDefault();
			$("#new_member_search").show();
			$("#roles_checkboxes").hide();

			$("#role_opt_form :checkbox").clearFields();
		});


		//
		// AJAX FORM
		//
		$("#role_opt_form").ajaxForm({
			url: '/scripts/add-new-band-member.php',
			dataType: 'json',
			beforeSubmit: function() {
				if ( validateStep2() ) {
					// start 'spinner' activity (will be stopped in 'success:')
					$("#role_opt_form").find("button").button("disable");
					$("#role_opt_form").find(".loading-msg").show();
					return true;
				}
				return false;
			},
			success: function(json, st, xhr, $form) {
				// end 'spinner' activity
				$("#role_opt_form").find("button").button("enable");
				$("#role_opt_form").find(".loading-msg").hide();

				if (json.success) {
					$form.resetForm();
					$("#addNewMemberDialog").dialog("close"); // close dialog
					getBandMembers($("#my_band_id").val());   // refresh read-only band member list
					$("#editBandMembersButton").click();      // refresh band member edit dialog
					$("#memberCheckAlert").text('');
				}
				else if (!json.logged_in) {
					warnNoLoginSession();
				}
				else {
					var msg = json.message || "An error occurred";
					jAlert(msg, "Error Adding Band Member");
				}
			}
		});
		$("#btnAddBandMember").click(function(e) { // Submit form!
			$(this).blur();
			e.preventDefault();
			$("#role_opt_form").submit();
		});

		// 'active' class follows focus
		$("#new_member_search .chk-add-type").change(function() {
			$(this).parent().removeClass("inactive");
			$(this).not(":checked").parent().addClass("inactive");
		}).change();
		$("#new_member_search .add-member-form input").focus(function() {
			// any time a field is focused, make sure its radio box is checked
			$(this).closest(".add-member-form").parent().find("input:radio")
				.attr("checked","checked")
				.change();
		});

		// make sure member name info is entered
		function validateStep1()
		{
			var $fbContainer    = $("#new_member_facebook_fields");
			var $nonFbContainer = $("#new_member_non_facebook_fields");

			// start fresh. Remove 'invalid' from all
			$fbContainer.find("input").add($nonFbContainer.find("input")).removeClass("invalid");

			// Determine which fieldset we're paying attention to
			var $fieldContainer = null;
			if ($("#chkAddType_FB").is(":checked")) {
				$fieldContainer = $fbContainer;    // facebook

				// clear values on other side:
				$nonFbContainer.find("input").clearFields();
			} else {
				$fieldContainer = $nonFbContainer; // non-facebook

				$fbContainer.find("input").clearFields();
			}

			// loop thru fields and add 'invalid' class to any empty fields
			var valid = true;
			$.each( $fieldContainer.find("input"), function(i,input) {
				if ( !$(input).val() || $.trim($(input).val()) == "" ) {
					$(input).addClass("invalid");
					valid = false;
				} else {
					$(input).removeClass("invalid");
				}
			});
			return valid;
		} // end validateStep1


		// make sure at least one role checkbox is selected
		function validateStep2() {
			var $cbs = $("#roles_checkboxes :checkbox:checked");
			if ($cbs.size() == 0) {
				jAlert("You must select at least one role");
				return false;
			}
			return true;
		}

		function populateAutocomplete() {
			FB.api("/me/friends?fields=id,name,first_name,last_name,picture", function(response) {
				try {
					//debugLog(response.data[1]);
					var friend_list = response.data;
					$("#fb_friends").autocomplete(friend_list, {
						autoFill: false,
						mustMatch: true,
						formatItem: function(item) {
							return item.name;
						}
					})
					.result(function(event, data, formatted) {
						if (data && data.id) {
							// store fb data for later
							$("#fb_uid").val(data.id);
							$("#fb_first_name").val(data.first_name);
							$("#fb_last_name").val(data.last_name);
						}
						else {
							//  Uh oh: no FB data associated with result
							$("#fb_uid").val('');
							$("#fb_first_name").val('');
							$("#fb_last_name").val('');
						}
					});
				}
				catch (err) {
					debugLog(err);
				}
			});
		} // end populateAutoComplete

	})();// End anon function encapsulation for adding new band member dialog and its widgets



//																			DELETE A BAND MEMBER

	$("#removeMemberFromBandDialog1").dialog({
		bgiframe: true,
		autoOpen: false,
		show: 'slide',
		height: 250,
		width: 300,
		modal: true,
		buttons: {
			'delete': function() {
				$(this).dialog("close");
				$("#removeMemberFromBandDialog2").dialog('open');
			},
			'cancel': function() {
				$(this).dialog('close');
			}
		}
	});
	$("#removeMemberFromBandDialog2").dialog({
		bgiframe: true,
		autoOpen: false,
		show: 'slide',
		height: 250,
		width: 300,
		modal: true,
		buttons: {
			'delete': function() {
				removeMemberFromBandConfirm();
			},
			'cancel': function() {
				$("#removeMemberFromBandDialog2").dialog('close');
				$("#removeMemberFromBandDialog1").dialog('close');
			}
		}
	});

	// TODO: these tooltips should be done with ONE binding!
	$('#personInfoSocialIcon').mouseover(function() {
		var htmlMouseOver;
		htmlMouseOver ="Click the orange knerd logo to download kNERD icons to put on all your other websites to link to your kNERD profile!";
	  $("#mySettingsHelpDiv").html(htmlMouseOver);
	});

	$('#bandInfoSocialIcon').mouseover(function() {
		var htmlMouseOver;
		htmlMouseOver ="Click the orange knerd logo to download kNERD icons to put on all your other websites to link to your band's kNERD profile!";
	  $("#editBandInfoHelpDiv").html(htmlMouseOver);
	});

	$('#deleteThisBandButton').mouseover(function() {
		var htmlMouseOver;
		htmlMouseOver ="Delete Band: This will remove all songs, reviews, photos and information about this band. There is no return from this. Instead, mark the band as 'disbanded' by unchecking the 'This band is currently together' check box.";
	  $("#editBandInfoHelpDiv").html(htmlMouseOver);
	});

	$('#editMyBandSocialMedia').mouseover(function() {
		var htmlMouseOver;
		htmlMouseOver ="Social Sites: Adding this band's other social accounts here will allow kNERD to update them anytime you make create a new event, show, or upload new music! No more need to update every website seperately.";
	  $("#editBandInfoHelpDiv").html(htmlMouseOver);
	});

	$('#editMyBandLinks').mouseover(function() {
		var htmlMouseOver;
		htmlMouseOver ="Band Links: Adding your band's links, like your MySpace URL, Twitter URL, your band's website, etc, will all show up on this band's knerd.com public profile.";
	  $("#editBandInfoHelpDiv").html(htmlMouseOver);
	});

	$('#my_band_zip').mouseover(function() {
		var htmlMouseOver;
		htmlMouseOver ="Band Location: Your band's city and state/region will auto-populate based on the country and zip/postal code.";
	  $("#editBandInfoHelpDiv").html(htmlMouseOver);
	});

	$('#my_band_country').mouseover(function() {
		var htmlMouseOver;
		htmlMouseOver ="Band Location: Your band's city and state/region will auto-populate based on the country and zip/postal code.";
	  $("#editBandInfoHelpDiv").html(htmlMouseOver);
	});

	$('#my_band_city').mouseover(function() {
		var htmlMouseOver;
		htmlMouseOver ="Band Location: Your band's city and state/region will auto-populate based on the country and zip/postal code.";
	  $("#editBandInfoHelpDiv").html(htmlMouseOver);
	});

	$('#my_band_state').mouseover(function() {
		var htmlMouseOver;
		htmlMouseOver ="Band Location: Your band's city and state/region will auto-populate based on the country and zip/postal code.";
	  $("#editBandInfoHelpDiv").html(htmlMouseOver);
	});

	$('#my_band_bio').mouseover(function() {
		var htmlMouseOver;
		htmlMouseOver ="Band Bio: What is your band's story? How did you form? How did you all meet? Are you still together?";
	  $("#editBandInfoHelpDiv").html(htmlMouseOver);
	});

	$('#my_band_url').mouseover(function() {
		var htmlMouseOver;
		htmlMouseOver ="Band Profile: This is the link to your band's public profile!";
	  $("#editBandInfoHelpDiv").html(htmlMouseOver);
	});

	$('#my_band_alias1').mouseover(function() {
		var htmlMouseOver;
		htmlMouseOver ="Band Alias: Does your band ever go by a different name? For example, Black Rebel Motorcycle Club is sometimes called BMRC.";
	  $("#editBandInfoHelpDiv").html(htmlMouseOver);
	});

	$('#band_email_address_input').mouseover(function() {
		var htmlMouseOver;
		htmlMouseOver ="Band Email Address: This email address will show up on this band's public profile.";
	  $("#editBandInfoHelpDiv").html(htmlMouseOver);
	});

	$('#mySettingsIsArtist').mouseover(function() {
		var htmlMouseOver;
		htmlMouseOver ="This enables the 'BAND EDITOR' and 'BAND DASHBOARD' tabs so you can create bands, upload music and create charts about your fans, song plays etc...";
	  $("#mySettingsHelpDiv").html(htmlMouseOver);
	});

	$('#new_country_iso').mouseover(function() {
		var htmlMouseOver;
		htmlMouseOver ="kNERD.COM uses postal and zip codes to help bands decide where they should book shows. Why play in the big city if all their fans are in a neighboring suburb?";
	  $("#mySettingsHelpDiv").html(htmlMouseOver);
	});

	$('#new_city').mouseover(function() {
		var htmlMouseOver;
		htmlMouseOver ="kNERD.COM uses postal and zip codes to help bands decide where they should book shows. Why play in the big city if all their fans are in a neighboring suburb?";
	  $("#mySettingsHelpDiv").html(htmlMouseOver);
	});
	$('#new_zip').mouseover(function() {
		var htmlMouseOver;
		htmlMouseOver ="kNERD.COM uses postal and zip codes to help bands decide where they should book shows. Why play in the big city if all their fans are in a neighboring suburb?";
	  $("#mySettingsHelpDiv").html(htmlMouseOver);
	});
	$('#new_state').mouseover(function() {
		var htmlMouseOver;
		htmlMouseOver ="kNERD.COM uses postal and zip codes to help bands decide where they should book shows. Why play in the big city if all their fans are in a neighboring suburb?";
	  $("#mySettingsHelpDiv").html(htmlMouseOver);
	});

	$('#new_email').mouseover(function() {
		var htmlMouseOver;
		htmlMouseOver ="Your email address is kept private.";
	  $("#mySettingsHelpDiv").html(htmlMouseOver);
	});

	$('#new_bio').mouseover(function() {
		var htmlMouseOver;
		htmlMouseOver ="Tell the world a little about yourself. Are you a musician? Who are your favorite bands? Do you help promote local music?";
	  $("#mySettingsHelpDiv").html(htmlMouseOver);
	});

	$('#myMailSettingsButton').mouseover(function() {
		var htmlMouseOver;
		htmlMouseOver ="Change your email preferences by clicking this button. Don't want to be updated about kNERD.COM? Want to receive updates if someone gives you credits on an album?";
	  $("#mySettingsHelpDiv").html(htmlMouseOver);
	});
	$('#editMyLinks').mouseover(function() {
		var htmlMouseOver;
		htmlMouseOver ="Have any other social websites like Twitter, Facebook and MySpace? Any sites you add here will be on your kNERD.COM public profile.";
	  $("#mySettingsHelpDiv").html(htmlMouseOver);
	});

//											NEW BAND NEWS
	var $addNewBandNewsForm = $("#addNewBandNewsDiv > form").ajaxForm({
		url: "/scripts/add-new-news.php",
		dataType: 'json',
		data: {
			band_id: $("#myBandsEditorSelect").val()
		},
		success: function(json, statusText, xhr, $form) {
			if (!json.logged_in) {
				warnNoLoginSession();
			}
			else if (json.success) {
				$form.resetForm();

				/********* post to linked social accounts ************/
				if (json.new_event_id > 0) {
					$("#addNewBandNewsDiv").dialog('close');
					postToLinkedAccounts(json.new_event_id, 'news');
				}
				else {
					jAlert("Event NOT saved. Please try again", "Error");
				}
				/*******************************************/
			}
			else {
				var alertMsg = json.message || "Unexpected error. Please try again";
				jAlert(alertMsg, "Error");
			}
		}
	});
	$("#addNewBandNewsDiv").dialog({
		autoOpen: false,
		show: 'slide',
		modal: true,
		width: "auto",
		buttons: {
			'cancel': function() { $(this).dialog("close"); },
			'add news': function() {
				$addNewBandNewsForm.submit();
			}
		}
	});

	// EDIT NEWS
	$("#bandEventNewsEditor > form").ajaxForm({
		url: "/scripts/update-band-news-event.php",
		dataType: 'json',
		data: {
			band_news_id: $("#editEventIDAnchor").val()
		},
		success: function(json, statusText, xhr, $form) {
			if (json.success) {
				$form.clearForm();

				$("#editEventIDAnchor").val("");

				$("#bandEventNewsEditor").hide();
				$("#bandEventShowEditor").hide();

				$("#bandManagerEditNews").click(); // reload the 'event editor' dialog
			}
			else if (!json.logged_in) {
				warnNoLoginSession();
			}
			else {
				var errorMessage = json.message || "An error occurred";
				jAlert(errorMessage, "Error");
			}
		}
	});

//											NEW BAND EVENTS
	$("#newBandEventsDialog").dialog({
		bgiframe: true,
		autoOpen: false,
		show: 'slide',
		height: 500,
		width: 420,
		modal: true,
		open: function(){
			dialogHeight = $(this).dialog( "option", "height" ) - 5;
			if ($(window).height() < dialogHeight)
			{
				var newHeight = $(window).height() - 2;
				$(this).dialog({ height: newHeight });

			}
		},
		close: function() {
			$("#bandManagerNewShowDate").val("");
			$("#bandManagerNewShowVenueName").val("");
			$("#bandManagerNewShowLink").val("http://");
			$("#bandManagerNewShowTicketLink").val("http://");
			$("#bandManagerNewShowTicketPrice").val("");
			$("#bandManagerNewShowTicketDoorPrice").val("");
			$("#bandManagerNewShowDescription").val("");
			$("#bandManagerNewShowCity").val("");
		},
		buttons: {
			'create event': function() {
				var band_id                = $("#myBandsEditorSelect").val();
				var show_date              = $("#bandManagerNewShowDate").val();
				var show_time              = $("#bandManagerNewShowDoorTime").val() + ":" + $("#bandManagerNewShowDoorMinutes").val() + " " + $("#bandManagerNewShowAmPm").val();
				var show_country_iso       = $("#newEventCountriesSelect").val();
				var show_region            = $("#newEventStatesSelect").val();
				var show_city              = $("#bandManagerNewShowCity").val();
				var show_venue_name        = $("#bandManagerNewShowVenueName").val();
				var show_link              = $("#bandManagerNewShowLink").val();
				var show_ticket            = $("#bandManagerNewShowTicketLink").val();
				var show_ticket_price      = $("#bandManagerNewShowTicketPrice").val();
				var show_ticket_door_price = $("#bandManagerNewShowTicketDoorPrice").val();
				var show_description       = $("#bandManagerNewShowDescription").val();

				if (show_date == "" || show_country_iso == "nothing" || show_region == "0" || show_venue_name == "")
				{
					jAlert("Be sure to select a date, time, country, state, city and venue name for this show...");
				} else {
					newShowData = "band_id=" + escape(band_id) + "&show_date=" + escape(show_date) + "&show_time=" + escape(show_time) +
						"&show_country_iso=" + escape(show_country_iso) + "&show_region=" + escape(show_region) + "&show_city=" + escape(show_city) +
						"&show_venue_name=" + escape(show_venue_name) + "&show_link=" + escape(show_link) + "&show_ticket=" + escape(show_ticket) +
						"&show_ticket_price=" + escape(show_ticket_price) + "&show_ticket_door_price=" + escape(show_ticket_door_price) +
						"&show_description=" + escape(show_description);

					$.ajax({ type: 'GET', url: '/scripts/add-new-show.php', data: newShowData, dataType: 'json',
						success: function(json)
						{
							if (json.success)
							{
								var new_event_id = json.new_event_id;

								if (new_event_id > 0)
								{
									$("#bandManagerNewShowDate").val("");
									$("#bandManagerNewShowDoorTime").val("8");
									$("#bandManagerNewShowDoorMinutes").val("00");
									$("#bandManagerNewShowAmPm").val("PM");
									$("#newEventStatesSelect").removeOption(/./);
									$("#bandManagerNewShowCity").val("");
									$("#bandManagerNewShowVenueName").val("");
									$("#bandManagerNewShowLink").val("http://");
									$("#bandManagerNewShowDescription").val("");
									$("#bandManagerNewShowTicketPrice").val("");
									$("#bandManagerNewShowTicketLink").val("");
									$("#bandManagerNewShowTicketDoorPrice").val("");
									$("#addNewBandShowDiv").hide();

									postToLinkedAccounts(new_event_id, 'show');
									$("#newBandEventsDialog").dialog('close');
								}
							}
							else if (!json.logged_in) {
								warnNoLoginSession();
							}
							else {
								var errmsg = json.message || "Event NOT saved. Please try again";
								jAlert(errmsg);
							}
						}
					}); // end $.ajax
				}
			},
			'cancel': function() {
				$("#newBandEventsDialog").dialog('close');
			}
		} // end buttons
	});



//																	EDIT BAND SOCIAL ACCOUNT
	$("#editBandSocialAccountDialog").dialog({
		bgiframe: true,
		autoOpen: false,
		show: 'slide',
		height: 300,
		width: 300,
		modal: true,
		buttons: {
			'save': function() {
					band_id = $("#my_band_id").val();
					account_id=$("#editSocialAccountIDSave").val();
					social_username= $("#myBandSocialMediaEditName").val();
					social_password= $.md5($("#myBandSocialMediaEditPassword").val());
					socialBandData = "band_id=" + escape(band_id) + "&username=" + escape(social_username) +
						"&password=" + escape(social_password) + "&account_id=" + escape(account_id);
					$.ajax({ type: 'GET', url: 'scripts/edit-band-social-account.php', data: socialBandData, dataType: 'html',
						success: function(returnData) {
							$("#editMyBandSocialMedia").click();
							$("#editBandSocialAccountDialog").dialog('close');

							$("#myBandSocialMediaName").val("");
							$("#myBandSocialMediaPassword").val("");
							$("#editSocialAccountIDSave").val("");
						}
					});
				},
			'cancel': function() {
				$("#editMyBandSocialMedia").click();
				$("#editBandSocialAccountDialog").dialog('close');
				$("#myBandSocialMediaName").val("");
				$("#myBandSocialMediaPassword").val("");
				$("#editSocialAccountIDSave").val("");
			}
		}
	});



//														DELETE BAND SOCIAL ACCOUNT
	$("#deleteSocialBandAccount").dialog({
		bgiframe: true,
		autoOpen: false,
		show: 'slide',
		height: 200,
		width: 300,
		modal: true,
		buttons: {
			'delete': function() {
				deleteSocialData = "id=" + $("#deleteSocialAccountVerifyID").val();
				$.ajax({ type: 'GET', url: 'scripts/delete-social-account.php', data: deleteSocialData, dataType: 'html',success: function(returnData) 	{

				}});
				$("#editMyBandSocialMedia").click();
				$("#deleteSocialBandAccount").dialog('close');
			},
			'cancel': function() {
				$("#deleteSocialBandAccount").dialog('close');
				$("#deleteSocialAccountVerifyID").val("");
			}
		}
	});

// 														ADD NEW ROLE FOR NEW BAND MEMBER
	$("#addNewRoleDialog").dialog({
		bgiframe: true,
		autoOpen: false,
		show: 'slide',
		height: 150,
		width: 300,
		modal: true,
		buttons: {
			'save': function() {
				band_id = band_id = $("#my_band_id").val();
				current_band_member_new_role_id = $('#new_band_member_new_role').val();
				current_band_member_name        = $('#newMemberRoleID').val();
				addRole(current_band_member_new_role_id,current_band_member_name,band_id);
			},
			'cancel': function() {
				$(this).dialog('close');
			}
		}
	});


			//																		EDIT BAND MEMBERS ROLES
	$("#editMyBandMemberRolesDialog").dialog({
		bgiframe: true,
		autoOpen: false,
		show: 'slide',
		height: 200,
		width: 300,
		modal: true,
		buttons: {
			'close': function() {
				$(this).dialog('close');
			},
			'add role': function() {
				$('#addNewRoleDialog').dialog('open');
			}
		}
	});

//																					EDIT BAND LINKS
	$("#editMyBandLinksDialog").dialog({
		bgiframe: true,
		autoOpen: false,
		show: 'slide',
		height: 300,
		width: 400,
		modal: true,
		close: function() {
			$("#newLinkInputBox").val("");
		},
		buttons: {
			'close': function() {
				$(this).dialog('close');
				$("#newLinkInputBox").val("");
			},
			'new link': function() {
				$("#addBandLinksDialog").dialog('open');
			}
		}
	});

	$('#welcomeDialog').dialog({
		bgiframe: true,
		autoOpen: false,
		show: 'slide',
		height: 300,
		width: 400,
		modal: true,
		buttons: {
			'ok!': function() {
				$(this).dialog('close');
			}
		}
	});

//																		ADD NEW BAND LINKS
	$("#addBandLinksDialog").dialog({
		bgiframe: true,
		autoOpen: false,
		show: 'slide',
		height: 250,
		width: 300,
		modal: true,
		close: function() {
			$("#newLinkInputBox").val("");
		},
		buttons: {
			'save': function() {
				newBandLinkTypeValue = $("#newLinkSelect").val();
				newBandLinkURLValue = $("#newLinkInputBox").val();
				band_id = $("#my_band_id").val();
				newBandLinkData = "band_id=" + band_id + "&" + "link_type=" + newBandLinkTypeValue + "&" + "link_url=" + newBandLinkURLValue;
				$.ajax({ type: 'GET', url: 'scripts/save-new-link.php', data: newBandLinkData, dataType: 'html',success: function(returnData) {
						$("#editMyBandLinks").click();
						$("#addBandLinksDialog").dialog('close');
					}
				});
			},
			'cancel': function() {
				$(this).dialog('close');
			}
		}
	});

//                                                         EDIT BAND SOCIAL MEDIA LINKS
// barwin - bookmark - social linked accounts
	var contentLoading = "<p>Loading .. please wait</p>";
	$("#editMyBandSocialMediaDialog, #postToLinkedAccountsDialog").dialog({ // setup some dialogs
			autoOpen: false,
		show: 'slide',
			modal: true,
			width: 300,
			buttons: {
				"Close": function() {
					$(this).dialog("close");
				},
				"add new account": function() {
					$("#CreateMyBandSocialMediaDialog").dialog("open");
				}
			}
	});


	$("#editMyBandSocialMedia").click(function() {
		// get dialog content via ajax-php call
		//  * list current links
		//  * give ability to add/edit/delete links
		$("#editMyBandSocialMediaDialog > .dlg-content").html(contentLoading).load("scripts/linked/getLinkedAccounts.php", {
				band_id: $("#my_band_id").val()
		});

		$("#editMyBandSocialMediaDialog").dialog("open");
	});

	$("#postToLinkedAccountsForm").ajaxForm({
		url: "/scripts/linked/postToLinked.php",
		target: null,
		resetForm: false,
		dataType: 'json',
		beforeSubmit: function() { $("#postToLinkedAccountsAjaxResults").html(''); }, // clear out the ajaxresults div
		success: function(json) {
			var ajaxResults = "";
			try {
				ajaxResults = json.html;
				if (!json.success && json.message) {
					jAlert(json.message);
				}
			} catch (err) {
				ajaxResults = "<p>An error occured</p>";
			}

			$("#postToLinkedAccountsAjaxResults").html(ajaxResults).slideDown();
		}
	});


	$("#CreateMyBandSocialMediaDialog").dialog({
		bgiframe: true,
		autoOpen: false,
		show: 'slide',
		height: 300,
		width: 300,
		modal: true,
		buttons: {
			'save': function() {
				var social_type = $("#CreateMyBandSocialMediaSelect").val();
				if (social_type == "none")
				{
					alert("Please choose a social site type.");
				} else {
					var band_id = $("#my_band_id").val();
					var social_username = $("#CreateMyBandSocialMediaName").val();
					var social_password = $("#CreateMyBandSocialMediaPassword").val();
					socialBandData = "band_id=" + band_id + "&type=" + social_type + "&username=" + escape(social_username) + "&password=" + escape(social_password);
					$.ajax({ type: 'POST', url: 'scripts/save-band-social-account.php', data: socialBandData, dataType: 'html',
						success: function(returnData) {
							$("#editMyBandSocialMedia").click();
							$("#CreateMyBandSocialMediaDialog").dialog('close');
							$("#editMyBandSocialMedia").selectOptions('none');
							$("#CreateMyBandSocialMediaName").val("");
							$("#CreateMyBandSocialMediaPassword").val("");
						}
					});
				}
			},
			'cancel': function() {
				$(this).dialog("close");
			}
		}
	});



//																			GET MY BANDS LINKS
	$("#editMyBandLinks").click(function(){
		$("#editMyBandLinksDialog").html("");
		getBandLinksData = "band_id=" + $("#my_band_id").val();

		$.ajax({ type: 'GET', url: 'scripts/get-band-links.php', data: getBandLinksData, dataType: 'html',
			success: function(returnData) {
				var linkHTML;
				try {
					var json = $.parseJSON(returnData);
					if (json.success == true)
					{

						linkHTML= "<div>";
						$.each(json.band_links, function(key,element){
							linkHTML += "<div class=\"socialLink formRow clearfix\" id=\"link" + element.id + "\">";
							linkHTML += "<div class=\"editIcons\"><span class=\"ui-icon ui-icon-trash\" onclick=\"deleteLink(" + element.id + ");\"  /></div>";
							linkHTML += "<div class=\"floatleft\"><div class=\"socialIcon " + element.link_type +"\"></div>" + element.site_url + "</div></div>";
						});

						linkHTML += "</div>";
						$("#editMyBandLinksDialog").html(linkHTML);
						$('#editMyBandLinksDialog').dialog('open');

					}
				} catch (err) {
					$("#editMyBandLinksDialog").html("Add your band's links. They will be displayed on the band's profile so your " +
							"fans will know where else to connect with this band!");
					jAlert("Ouch, unexpected error", "Yikes!");
				}
			} // end success function
		});
	});



//													BAND INFO CLICK
	$("#editBandInfoButton").click(function(){
		$("#editBandInfoDialog").dialog('open');
	});

	$("#editBandInfoDialog").dialog({
		bgiframe: true,
		autoOpen: false,
		show: 'slide',
		height: 565,
		width: 820,
		modal: true,
		open: function(){
			dialogHeight = $(this).dialog( "option", "height" ) - 5;
			if ($(window).height() < dialogHeight)
			{
				var newHeight = $(window).height() - 2;
				$(this).dialog({ height: newHeight });

			}
		},
		buttons: {
			'close': function() {
				$(this).dialog("close");
			}
		}
	});




	var $bday_datepicker = $('#new_birthday_input').datepicker({
		changeYear: 'true',
		yearRange: '1920:2001',
		dateFormat: 'yy-mm-dd',
		//defaultDate: $.datepicker.parseDate("y-m-d", $('#new_birthday').val()), // moved into separate if-block below
		altField: '#new_birthday'
	});

	if ($('#new_birthday').length > 0) {
		$bday_datepicker.datepicker("setDate", $.datepicker.parseDate("y-m-d", $('#new_birthday').val()));
	}


	// barwin - bookmark - tabs-def
	$("#content-loading").remove();

	$tabs = $("#contentDiv").not(".standalone").tabs({
		collapsible:false,
		add: function(event, ui) {
			// immediately select a just added tab
			$tabs.tabs('select', '#' + ui.panel.id);
		},
		select: function(event, ui) {
			// Update address bar .. works for refreshing, but not back-button..
			location.href = '#' + ui.panel.id;

			// Alternative method (for later?):
			// save what tab we're in the session so we can restore on refresh
			//savePageState({ save_tab: ui.panel.id });
		},
		show: function(event, ui) {

			if (ui.panel.id == 'bandManagerTab' && KJGraph1.instance.needsInit) { // special case, trigger graph render
				// User opening BandData tab for the first time, Render graphs!
				KJGraph1.instance.needsInit = false;

				KJGraph1.instance.doGraph1();
				KJGraph2.instance.renderGraph2();
			}
		}
	}).show();

	$profileTabs = $("#profileTab").tabs({
		collapsible:false,
		add: function(event, ui) {
			// immediately select a just added tab
			$profileTabs.tabs('select', '#' + ui.panel.id);
		},
		remove: profile_checkIfLast,
		tabTemplate: '<li><a href="#{href}">#{label}</a> <span class="ui-icon ui-icon-close" style="float:left;">Remove Tab</span></li>'
	}).show();

	// close icon: removing the tab on click
	// note: closable tabs gonna be an option in the future - see http://dev.jqueryui.com/ticket/3924
	$('.tabs span.ui-icon-close').live('click', function() {
		var index = $('li',$profileTabs).index($(this).parent());
		$profileTabs.tabs('remove', index);
	});

	// END profile sub-tabs



	get_tabs(); //hide un-needed tabs - TODO: remove this function entirely. Replaced with server-side code in index.php

	if ($("#myBandsEditorSelect").val() > 0)
	{
		loadband();
	}




//                                 LOAD NEW BAND DIALOG SCREEN
	$("#newBandDialog").dialog({
		bgiframe: true,
		autoOpen: false,
		show: 'slide',
		height: 465,
		width: 560,
		modal: true,
		open: function(){
			dialogHeight = $(this).dialog( "option", "height" ) - 5;
			if ($(window).height() < dialogHeight)
			{
				var newHeight = $(window).height() - 2;
				$(this).dialog({ height: newHeight });

			}
		},
		buttons: {
			'Add Band': function() {
				var new_band_name        = $('#new_band_name').val();
				var new_band_alias       = $('#new_band_alias').val();
				var new_band_genre_1     = $('#new_band_genre_1').val();
				var new_band_genre_2     = $('#new_band_genre_2').val();
				var new_band_country_iso = $('#new_band_country_iso').val();
				var new_band_zip         = $('#new_band_zip').val();
				var new_band_city        = $('#new_band_city').val();
				var new_band_state       = $('#new_band_state').val();
				var new_band_role        = $('#new_band_role').val();

				var newBandFormData = 'band_name=' + escape(new_band_name) +'&band_alias=' + escape(new_band_alias) +
					'&band_genre_1=' + escape(new_band_genre_1) +'&band_genre_2=' + escape(new_band_genre_2) +
					'&band_country_iso=' + escape(new_band_country_iso) +'&band_zip=' + escape(new_band_zip) +
					'&band_city=' + escape(new_band_city) +'&band_state=' + escape(new_band_state) +
					'&role='+escape(new_band_role);

				showAjaxLoad($("#newBandDialog"));
				debugLog("please wait while loading social site stuff");
				jAlert("kNERD is searching for your band's other Internet sites. This will only take a moment.");
				$.ajax({
					type: 'POST',
					url: '/scripts/jquery-new-band.php',
					data: newBandFormData,
					dataType: 'json',
					success: function(json) {
						hideAjaxLoad();

						if (json.success_add_band)
						{
							// clear out and close the 'add new band' dialog
							$('#new_band_name').val("");
							$('#new_band_alias').val("");
							$('#new_band_zip').val("");
							$('#new_band_city').val("");
							$("#newBandDialog").dialog('close');

							var new_band_id = json.new_band_id;

							$("#myBandsEditorSelect").append(  $("<option></option>").val( new_band_id ).text(new_band_name)  );
							$("#myBandsEditorSelect").val( new_band_id );
							$("#myBandsEditorSelect").change(); // triggers call to loadband()

							$("#bandManagerBandSelect").append(  $("<option></option>").val( new_band_id ).text(new_band_name)  );
							$("#bandManagerBandSelect").val( new_band_id );
							$("#bandManagerBandSelect").change();

							socialBandImport(json);

						}
						else if (!json.logged_in) {
							warnNoLoginSession();
						}
						else {
							var msg = json.message || "Yikes! An error occured!";
							jAlert(msg, "Error");
						}

					}
				});// end $.ajax()
			},
			'Cancel': function() {
				$(this).dialog('close');
			}
		}
	});

	$('#newBand').click(function() {
		$('#newBandDialog').dialog('open');
	});


//										CHANGE MY SETTINGS
	$('#changeMySettings').click(function() {
		$('#changeMySettingsDialog').dialog('open');
	});

	$('#changeMyPhotos').click(function() {
		var connectorID = $(this).attr("rel");
		KJPhoto.instance.managePhotosFor('person', connectorID, 'Edit my personal photo');
	});

	$("#changeMySettingsDialog").dialog({
		bgiframe: true,
		autoOpen: false,
		show: 'slide',
		height: 600,
		width: 820,
		modal: true,
		open: function(){
			dialogHeight = $(this).dialog( "option", "height" ) - 5;
			if ($(window).height() < dialogHeight)
			{
				var newHeight = $(window).height() - 2;
				$(this).dialog({ height: newHeight });

			}
		},
		buttons: {
			'Save Settings': function() {
				var isArtist = null;
				if ($("#mySettingsIsArtist").is(':checked')) {
					isArtist = "1";
					$("#topNav").children('#myBandsli').show();
					$("#topNav").children('#bandManagerTabli').show();

				} else {
					isArtist = "0";
					$("#topNav").children('#myBandsli').hide();
					$("#topNav").children('#bandManagerTabli').hide();
				}

				$.post("/scripts/changemysettings.php", {
						first_name:  $("#new_first_name").val(),
						middle_name: $('#new_middle_name').val(),
						last_name:   $("#new_last_name").val(),
						sex:         $("#new_sex").val(),
						country_iso: $("#new_country_iso").val(),
						zip:         $("#new_zip").val(),
						city:        $("#new_city").val(),
						state:       $("#new_state").val(),
						bio:         $("#new_bio").val(),
						birthday:    $("#new_birthday").val(),
						is_artist:   isArtist
					},
					function(returnData) {
						try {
							var json = $.parseJSON(returnData);
							if (!json.logged_in) {
								warnNoLoginSession();
							}
							else if (json.success) {
								$("#changeMySettingsDialog").dialog('close');
							}
							else {
								var errorMsg = "An error occured";
								if (json.message) { errorMsg = json.message; }
								jAlert(errorMsg, "Error");
							}
						} catch (err) {
							jAlert("An error occured", "Error");
						}
					},
					'html'
				); // end $.post
			},
			Cancel: function() {
				$(this).dialog('close');
			}
		}
	});


	/* Global bind to handle textblocks with more/less controls like news, reviews, etc */
	$(".textblock-overflow .padding").live("click", function() { /* show/hide the extended review text */
		var parent= $(this).parent();
		parent.find(".padding").toggle();
		parent.find(".hide").toggle();
	});


	// ATTEND EVENT
	$(".attend-widget input:radio").live("change", function() {
		var eventID = $(this).parent().parent().attr("id");
		attendEvent(eventID, $(this).val());
	});


}); // end of jquery(document).ready()!
//END OF DOCUMENT READY FUNCTION


/**
 * Change rsvp for given event
 *
 * @param eventID
 * @param action (can be 'remove' or 'attend')
 */
function attendEvent(eventID, action) {
	kAjax("get", "/scripts/event-attend.php", {band_event_id: eventID, a: action});
}

function get_tabs()
{
	// TODO: hide/show the profile tab from index.php instead of here
	var profileTabLength;
	profileTabLength = $("#profilesTabli").length;
	if (profileTabLength < "2")
	{
		$("#topNav").children('#profilesTabli').hide();
	} else {
		$("#topNav").children('#profilesTabli').show();
	}
} // end get_tabs()


//																							LOAD BAND
/**
 * @param callback_func optional callback function to be executed after data is loaded
 */
function loadband(callback_func)
{
	var band_id = $("#myBandsEditorSelect").val();
	if (band_id == "0")
	{
		$("#bandEditEventsHiddenButtons").hide();
		$("#edit_band_div").hide();
	}
	else {
		loadBandDataSend= "band_id=" + band_id;

		$.ajax({
			type: 'GET',
			url: '/scripts/get-my-band.php',
			data: loadBandDataSend,
			dataType: 'html',
			success: function(returnData) {
				try {
					var json = $.parseJSON(returnData);

					if (json.success == true)
					{
						if (json.band && json.band.id !== undefined) {
							var element = json.band;

							$("#my_band_id").val(element.id);
							$("#my_band_name").val(element.band_name);
							//$("#my_band_name").attr(element.);
							//$("#my_band_alias1").attr(element.);
							$("#my_band_alias1").val(element.band_alias_1);
							$("#my_band_country").val(element.band_country_iso);
							$("#my_band_zip").val(element.band_zip);
							$("#my_band_city").val(element.band_city);
							$("#my_band_state").val(element.band_state);
							$("#my_band_genre1").val(element.band_genre_id_1);
							$("#my_band_genre2").val(element.band_genre_id_2);
							$("#band_email_address_input").val(element.band_email);
							var band_url = element.profile_slug;

							$("#my_band_name").attr("old_value", element.band_name);
							$("#my_band_alias1").attr({old_value: element.band_alias_1});
							$("#my_band_country").attr({old_value: element.band_country_iso});
							$("#my_band_zip").attr({old_value: element.band_zip});
							$("#my_band_city").attr({old_value: element.band_city});
							$("#my_band_state").attr({old_value: element.band_state});
							$("#my_band_genre1").attr({old_value: element.band_genre_id_1});
							$("#my_band_genre2").attr({old_value: element.band_genre_id_2});
							$("#band_email_address_input").attr({old_value: element.band_email});

							if (element.default_band == element.id) {
								$("#my_default_band").attr({checked: 'checked'});
							} else {
								$("#my_default_band").removeAttr('checked');
							}

							$("#my_band_bio").val(element.band_bio);
							$("#my_old_band_bio").val(element.band_bio);

							$("#myBandDefaultPhoto").attr({src: element.default_photo, title: element.band_name });

							if (element.song_count == null) {
								element.song_count = 0;
							}
							if (element.fan_count == null) {
								element.fan_count = 0;
							}
							if (element.review_count == null) {
								element.review_count = 0;
							}
							$("#quickStatsTotalListens").html(element.song_count);

							$("#quickStatsTotalFans").html(element.fan_count);

							$("#quickStatsTotalReviews").html(element.review_count);


							var urlHTML;
							if (band_url == null)
							{
								var buttonTxt= "CREATE " + element.band_name + "'s KNERD URL!";
								urlHTML="<button class=\"knerd-button ui-button ui-widget ui-state-default ui-corner-all ui-button-text-only\" role=\"button\" aria-disabled=\"false\" id=\"bandURLButton\" onclick=\"$('#bandURLDialog').dialog('open');\">"+ buttonTxt + "</button><p>example: \"http:\/\/www.knerd.com\/bands\/yourbandname\"</p>";
							} else {
								urlHTML="http://www.knerd.com/bands/" + band_url;
							}

							$("#my_band_url").html(urlHTML);

							getBandMembers(band_id);
							$("#edit_band_div").show();
							$("#edit_band_div").show();
							$("#bandEditEventsHiddenButtons").show();
						} // end if (element)

						if (callback_func !== undefined) {
							callback_func();
						}
					}
					else {
						// ajax call to get band info failed, give error message
						// TODO:
					}
				} catch (err) {
					debugLog(err);
				}
			}
		}); // end $.ajax()

	}
} // end fn loadband()



function newBandZip(zipElement,cityElement,stateElement,countryElement)
{
	var cityTemp = "#" + cityElement;
	var city = $(cityTemp);
	var stateTemp = "#" + stateElement;
	var state = $(stateTemp);
	var zipCode = document.getElementById(zipElement).value;
	var getCountry = document.getElementById(countryElement).value;
	var url = "http://www.geonames.org/postalCodeLookupJSON?&country=" + getCountry + "&callback=?" + "&postalcode=" + zipCode;
	$.getJSON(url, {postalcode: this.value }, function(response) {
		if (response && response.postalcodes.length && response.postalcodes[0].placeName) {
			city.val(response.postalcodes[0].placeName);
			state.val(response.postalcodes[0].adminName1);
		}
	});
}

function changeZip()
{
	var city = $("#new_city");
	var state = $("#new_state");
	var zipCode = document.getElementById('new_zip').value;
	var getCountry = document.getElementById('new_country_iso').value;
	var url = "http://www.geonames.org/postalCodeLookupJSON?&country=" + getCountry + "&callback=?" + "&postalcode=" + zipCode;
	$.getJSON(url, {postalcode: this.value }, function(response) {
		if (response && response.postalcodes.length && response.postalcodes[0].placeName) {
			city.val(response.postalcodes[0].placeName);
			state.val(response.postalcodes[0].adminName1);
		}
	});
}

//															EDIT MY BAND MEMBERS ROLES (ABSOLETE!)
function editMyBandMember(memberID, bandID)
{
	getMyBandMemberData = "member_id=" + memberID + "&" + "band_id=" + bandID;
	$.ajax({ type: 'GET', url: 'scripts/getMyBandMember.php', data: getMyBandMemberData, dataType: 'html',success: function(returnData) { $("#editMyBandMemberRolesDialog").html (returnData);}});
	$('#editMyBandMemberRolesDialog').dialog('open');
}

function addRole(roleIDAdd,newRoleMemberId,newRoleBandId)
{
	getMyBandMemberRoleData ="role_id=" + roleIDAdd + "&member_id=" + newRoleMemberId + "&band_id=" + newRoleBandId;

	$.ajax({ type: 'GET', url: 'scripts/add-role.php', data: getMyBandMemberRoleData, dataType: 'html',
		success: function(returnData) {
			getBandMembers(newRoleBandId);
			getBandMembersEdit(newRoleBandId);
			editBandMemberRoles(newRoleMemberId,newRoleBandId);
			$("#addNewRoleDialog").dialog('close');
		}
	});

	return false;
}

function editMyBandLinks(bandId)
{
	$("#editMyBandLinksDialog").dialog('open');
}

function getBandMembers(band_id)
{
	$("#myBandMembersSpan").html("Loading...");

	getBandMembersData = "band_id=" + band_id;
	$.ajax({
		type: 'GET',
		url: '/scripts/get-band-members.php',
		data: getBandMembersData,
		dataType: 'html',
		success: function(returnData)
		{
			var json = null;
			var memberHTML;
			try {
				json = $.parseJSON(returnData);
				if (json.success == true)
				{
					memberHTML= "<ul>";
					$.each(json.band_members, function(key,element){
						memberHTML += "<li>" +
								"<span class=\"memberName\">" + element.member_name + ": </span>" +
								"<span class=\"memberRole\">" + element.roles + "</span>" +
								"</li>";
					});

					memberHTML += "</ul>";
					$("#myBandMembersSpan").html(memberHTML);
				}
			} catch (err) {
					jAlert("An error occured");
					$("#myBandMembersSpan").html("An error occured");
			}
		} // end success function
	});
}

//											GET BAND MEMBERS TO EDIT
function getBandMembersEdit(bandID)
{
	$("#editBandMembersDiv").html("Loading...");
	$.get("/scripts/get-band-members.php", {
			band_id: bandID
		},
		function(returnData) {
			var memberHTML = "";
			try {
				var json = $.parseJSON(returnData);

				if (!json.logged_in) {
					warnNoLoginSession();
				}
				else if (json.success)
				{
					memberHTML= "<div>";
					$.each(json.band_members, function(key,element){
						memberHTML += "<div class=\"formRow clearfix\">";
						memberHTML += "<div class=\"editIcons\"><span title=\"click to edit member roles.\"class=\"ui-icon ui-icon-info\" onclick=\"editBandMemberRoles(" + element.user_id + "," + bandID + ");\"/> <span class=\"ui-icon ui-icon-trash\" onclick=\"removeMemberFromBand(" + element.user_id +");\"/></div> ";
						memberHTML += "<div class=\"floatleft\"><div><span class=\"memberName\">" + element.member_name + ": </span><span class=\"memberRole\">" + element.roles + "</span></div>";
						memberHTML += "<div>";

						if (element.is_current_member == "1") {
							memberHTML += "<input id=\"bandMemberCheck" + bandID + '_' + element.user_id + "\" type=\"checkbox\" onchange=\"changeBandMemberStatus(" + bandID + "," + element.user_id + ");\" checked=\"checked\"  />";
						} else {
							memberHTML += "<input id=\"bandMemberCheck" + bandID + '_' + element.user_id + "\" type=\"checkbox\" onchange=\"changeBandMemberStatus(" + bandID + "," + element.user_id + ");\" />";
						}
						memberHTML += "is current member</div><div>";
						if (element.is_band_admin == "1") {
							memberHTML += "<input id=\"bandAdminCheck" + bandID + element.user_id +"\" type=\"checkbox\" onchange=\"changeBandMemberAdminStatus(" + bandID + "," + element.user_id + ",0);\" checked=\"checked\" />"; }
						else {
							memberHTML += "<input id=\"bandAdminCheck" + bandID + element.user_id +"\" type=\"checkbox\" onchange=\"changeBandMemberAdminStatus(" + bandID + "," + element.user_id + ",1);\" />";
						}
						memberHTML += "can change band settings</div></div></div>";
					});

					memberHTML += "</div>";
				}
			} catch (err) {
					jAlert("An error occured", "Error");
					if (!memberHTML) {
						$("#editBandMembersDiv").html("Could not get band member list because an error occured");
					}
			}
			$("#editBandMembersDiv").html(memberHTML);
		},
		'html'
	);
} // end fn getBandMembersEdit()

//														Change Membership Status
function changeBandMemberStatus(bandID,memberID)
{
	var fieldId = '#bandMemberCheck' + band_id + '_' + memberID;
	var changeTo = null;
	if ($(fieldId).is(":checked")) {
		changeTo = 1;
	} else {
		changeTo = 0;
	}
	$.get("/scripts/change-band-member-status.php", {
		band_id: bandID,
		member_id: memberID,
		new_status: changeTo
	},
	function(returnData) {

		var errorMsg = "An error occured";
		try {
			var json = $.parseJSON(returnData);
			if ( !json.logged_in ) {
				warnNoLoginSession();
			}
			else if ( !json.success ) {
				if (json.message) { errorMsg = json.message; }
				jAlert(errorMsg);
			}
		} catch (err) {
			jAlert(errorMsg, "Error");
		}
	},
	'html'
	);
} // end changeBandMemberStatus()

//														Change Band Admin Status
function changeBandMemberAdminStatus(bandID,memberID,changeTo)
{
	$.get("/scripts/change-band-member-admin-status.php", {
			band_id: bandID,
			member_id: memberID,
			new_status: changeTo
		},
		function(returnData) {

			var errorMsg = "An error occured";
			try {
				var json = $.parseJSON(returnData);
				if ( !json.logged_in ) {
					warnNoLoginSession();
				}
				else if ( !json.success ) {
					elementID = "#bandAdminCheck" + bandID + memberID;
					$(elementID).attr('checked', 'checked');

					if (json.message) { errorMsg = json.message; }
					jAlert(errorMsg);
				}
			} catch (err) {
				jAlert(errorMsg, "Error");
			}
		},
		'html'
	);
} // end changeBandMemberAdminStatus


//														Delete a Link
function deleteLink(link_id)
{
	deleteLinkData = "link_id=" + link_id;
	deleteLinkTR = "#link" + link_id;

	$.ajax({ type: 'GET', url: 'scripts/delete-link.php', data: deleteLinkData, dataType: 'html',success: function(returnData) {}});
	$(deleteLinkTR).remove();
}

function deleteMyLink(link_id)
{
	deleteLinkData = "link_id=" + link_id;
	deleteLinkTR = "#link" + link_id;

	$.ajax({ type: 'GET', url: 'scripts/delete-my-link.php', data: deleteLinkData, dataType: 'html',success: function(returnData) {}});
	$(deleteLinkTR).remove();
}
//														CHECK TO SEE IF PERSON IS MEMBER OR NOT
function checkMemberStatus(elementID,alertElementID)
{
	memberStatusData="";
	$.ajax({ type: 'GET', url: 'scripts/check-member-status.php', data: memberStatusData, dataType: 'html',success: function(returnData) {}});
}

function removeMemberFromBand(member_id)
{
	$('#deleteBandMemberID').val(member_id);
	$("#removeMemberFromBandDialog1").dialog('open');
}

function removeMemberFromBandConfirm()
{
	var bandID = $("#my_band_id").val();

	$.get("/scripts/remove-band-member.php", {
			member_id: $('#deleteBandMemberID').val(),
			band_id:   bandID
		},
		function(returnData) {
			// close delete-confirmation dialog
			$("#removeMemberFromBandDialog2").dialog('close');

			$('#deleteBandMemberID').val('');

			try {
				var json = $.parseJSON(returnData);
				if (!json.logged_in) {
					warnNoLoginSession();
				}
				else if (json.success) {
					// refresh member list:
					$("#editBandMembersButton").click();
				}
				else {
					var errorMsg = (json.message? json.message : "An error occured");
					jAlert(errorMsg, "Error");
				}
			} catch (err) {
				jAlert("An error occured", "Error");
			}
		},
		'html'
	);
}

//													EDIT MEMBER ROLES FUNCTION
function editBandMemberRoles(member_id,band_id)
{
	$("#editRoleBandMemberID").val(member_id);
	getMemberRoleData = "band_id=" + escape(band_id) + "&member_id=" + escape(member_id);
	$('#newMemberRoleID').val(member_id);
	$.ajax({ type: 'GET', url: '/scripts/get-member-roles-to-edit.php', data: getMemberRoleData, dataType: 'html',
		success: function(returnData) {
			$("#editMyBandMemberRolesDiv").html("No roles defined");
			try {
				var json = $.parseJSON(returnData);
				if (!json.logged_in) {
					warnNoLoginSession();
				}
				else if (json.success == true)
				{
					var memberHTML= "<div>";
					var member_name;
					$.each(json.member_name, function(key,element){
						member_name = element.member_name;
						memberHTML += "<div class=\"subhead\">" + member_name + "</div>";
					});

					$.each(json.roles, function(key,element){
						member_name = element.member_name;
						memberHTML += "<div id=\"role" + element.id + "\" class=\"formRow clearfix\"><div class=\"editIcons\"><span class=\"ui-icon ui-icon-trash\" " +
						                   "onclick=\"deleteBandRole("+ "'role" + element.id +"',"+ element.id + ");\"  /></div><div class=\"editInfo\">" + element.role_name + "</div></div>";
					});

					$("#editMyBandMemberRolesDiv").html(memberHTML);

				}
			} catch (err) {
				jAlert("An unexpected error occured", "Error");
			}

			$("#editMyBandMemberRolesDialog").dialog('open');
		}
	});
}

function updateSongVideos(song_id)
{
	$("#newSongVideoLinkSongID").val(song_id);

	$.post('scripts/get-band-song-video-links.php', {
			song_id: song_id
		},
		function(returnData) {
			try {
				var json = $.parseJSON(returnData);
				if (json.success == true)
				{
					$("#editSongVideoLinksDisplayDiv").html("");

					//$displayLinksArea.empty(); // <-- remove previous results
					$.each(json.data, function(key,element){
						// Do something with element (which is an entry in the original $data array from the PHP script)
						// console.debug(element);
						linkData= "<span id=\"songVideoLinkSpan" + element.id + "\"><span class=\"ui-icon ui-icon-trash\" onclick=\"deleteSongVideoLink("+ element.id +")\"></span> <input type=\"text\" id=\"songVideoLinkURL" + element.id + "\" value=\"" + element.video_url + "\" old_value=\"" + element.video_url + "\" size=\"25\" link_id=\"" + element.id + "\" class=\"songVideoURL text ui-widget-content ui-corner-all\" /></span><br/>";

						$("#editSongVideosDialog").append(linkData);

					});
				}
			} catch (err) {
				// json parse error exception ends up here...
			}
		},
		'html'
	);  // end $.post

	$("#editSongVideosDialog").dialog('open');
}


function editAlbum(album_id)
{
	$("#editBandAlbumId").val(album_id);

	getAlbumData = "album_id=" + album_id;
	$.ajax({ type: 'GET', url: 'scripts/edit-album.php', data: getAlbumData, dataType: 'html',
		success: function(returnData) {
			try {
				var json = $.parseJSON(returnData);
				if (json.success == true)
				{

					$("#editMyBandAlbumsDialogSongDiv").html("");
					$.each(json.album_data, function(key,element){
						$("#editBandAlbumTitle").val(element.album_title);
						$("#editBandAlbumTitle").attr({old_value: element.album_title});
						$("#editBandAlbumCopyright").val(element.album_copyright);
						$("#editBandAlbumCopyright").attr({old_value: element.album_copyright});
						$("#editBandAlbumNumTracks").val(element.number_of_tracks);
						$("#editBandAlbumNumTracks").attr({old_value: element.number_of_tracks});
						$("#editBandAlbumLabel").val(element.album_record_label);
						$("#editBandAlbumLabel").attr({old_value: element.album_record_label});
						$("#editBandAlbumPublisher").val(element.album_publisher);
						$("#editBandAlbumPublisher").attr({old_value: element.album_publisher});
						$("#editBandAlbumDescription").val(element.album_description);
						$("#editBandAlbumDescription").attr({old_value: element.album_description});
						if ((element.download_code != "") && (element.download_code != null))
						{
							var codeHTML = "download code: " + element.download_code + "<br/><a href=\"http://www.knerd.com/downloads\">http://www.knerd.com/downloads</a>";
							$("#albumDownloadCode").html(codeHTML);
							$("#editBandAlbumDownloadable").attr('checked', true);

						} else {
							$("#albumDownloadCode").html("");
							$("#editBandAlbumDownloadable").attr('checked', false);
						}
					});

					var songHTML= "<div>";
					$.each(json.songs, function(key,element){
						songHTML += "<div id = \"songDiv" + element.id + "\"><input type=\"text\" size=\"2\" value_type=\"track_num\" element_type=\"song\" element_id = \"" + element.id + "\" name=\"songTrackNum\"" + element.id + "\" id=\"songTrackNum" + element.id + "\" class=\"ajax_field trackNumber text ui-widget-content ui-corner-all\" value=\""+ element.song_track_number +"\" old_value=\""+ element.song_track_number +"\"/><input type=\"text\" size=\"15\" name=\"songTrackTitle" + element.id + "\" element_id = \"" + element.id + "\" id=\"songTrackTitle" + element.id + "\" element_type=\"song\" value_type=\"track_name\" class=\"ajax_field trackTitle text ui-widget-content ui-corner-all\" old_value=\""+ element.song_title +"\" value=\""+ element.song_title +"\"/><div class=\"editAlbumTools\"><span title=\"add a purchase link for this track\" class=\"ui-icon ui-icon-cart\" id = \"purchaseLink" + element.id + "\" onclick=\"getPurchaseSongLink(" + element.id + ")\" /><span id=\"song" + element.id + "\" title=\"edit track credits\" class=\"ui-icon ui-icon-info\" onclick=\"updateSongCredits(" + element.id + ")\" /><span id=\"song" + element.id + "\" title=\"add video links for this track\" class=\"ui-icon ui-icon-video\" onclick=\"updateSongVideos(" + element.id + ")\" /><span title=\"delete this track\" class=\"ui-icon ui-icon-trash\" id = \"delete" + element.id + "\" onclick=\"deleteSong(" + element.id + ")\" /></div></div>";
					});
					songHTML+= "</div>";
					$("#editMyBandAlbumsDialogSongDiv").append(songHTML);
					$('#editMyBandAlbumsDialog').dialog('addbutton', 'add songs', addSongsDialogButton);
					$('#editMyBandAlbumsDialog').dialog('addbutton', 'edit credits', editBandAlbumCredits);
					$('#editMyBandAlbumsDialog').dialog('addbutton', 'artwork', editAlbumArtworkDialogButton);
					$('#editMyBandAlbumsDialog').dialog('addbutton', 'purchase links', editAlbumPurchaseLinksButton);
					$('#editMyBandAlbumsDialog').dialog('addbutton', 'delete album', deleteAlbumDialogButton);
					$("#editMyBandAlbumsDialogRIGHT").show();
					$("#editMyBandAlbumsDialogSongDiv").show();
				}
			} catch (err) {
				jAlert("Unexpected Error", "Yikes!");
			}
		}
	});
}


function locateUser(workingElement,alertElement,firstNameElement,lastNameElement)
{
	var workingElementHash = "#" + workingElement;
	var alertElementHash   = "#" + alertElement;
	$(alertElementHash).html("");
	if ($(workingElementHash).val() != "")
	{
		$.get("/scripts/locate-user.php", {
				user_email: $(workingElementHash).val()
			},
			function(returnData) {
				try {
					var json = $.parseJSON(returnData);
					if ( !json.logged_in ) {
						warnNoLoginSession();
					}
					else if (json.success && json.user) { // found user!

						var userName      = json.user.first_name + " " + json.user.last_name;

						$(alertElementHash).html(userName + " has a kNERD acccount!!");
						$(alertElementHash).attr({ title: json.user.id});
						firstNameElementHash = "#" + firstNameElement;
						lastNameElementHash = "#" + lastNameElement;
						$(firstNameElementHash).val(json.user.first_name);
						$(lastNameElementHash).val(json.user.last_name);
					}
					else {
						$(alertElementHash).html("");
					}

				} catch (err) {
					jAlert("An error has occured");
				}
			},
			'html'
		);
	}
}


function updateSongCredits(songId)
{
	var updateSongCreditsData = "song_id=" + songId;
	$("#newSongCreditID").attr({ title: songId});
	$("#updateSongCreditsTable").html("");

	var bandId = $("#my_band_id").val();
	var getBandMembersData = "band_id=" + escape(bandId);

	$.ajax({ type: 'GET', url: 'scripts/get-band-members.php', data: getBandMembersData, dataType: 'html',
		success: function(returnData) {
			try {
				var json = $.parseJSON(returnData);
				if (json.success)
				{
					var memberHTML = "<p>Band Members and Roles: </p><ul>";
					$.each(json.band_members, function(key,element){
						memberHTML += "<li id=\"memberID" + element.user_id + "\"><A class=\"ajax-button\" onclick=\"bandMemberNewCredit('" + element.user_id + "','updateSongCreditsEmail','updateSongCreditsFirstName','updateSongCreditsLastName')\" >" +element.member_name + ": </a><a>"+ element.roles +"</a></li>";
					});

					memberHTML += "</ul></div>";
					$("#updateSongBandMembersDiv").html(memberHTML);
				}
			} catch (err) {
				jAlert("Unexpected Error. Please try again", "Error");
			}
		}
	});


	$.ajax({ type: 'GET', url: 'scripts/edit-song-credits.php', data: updateSongCreditsData, dataType: 'html',
		success: function(returnData) {
			try {
				var json = $.parseJSON(returnData);
				if (json.success)
				{

					var creditHTML= "";
					if (typeof(json.song_credits) != "undefined")
					{
						$.each(json.song_credits, function(key,element){
							creditHTML += "<div ID=\"roleID" + element.id + "\"><div>" + element.first_name + " " + element.last_name + " - " + element.role_name + " <span class=\"ui-icon ui-icon-trash\" onclick=\"deleteRole("+ element.id + ")\" /></div></div><div style=\"clear:both;\"></div>";
						});

						creditHTML += "</div><br/>";
						$("#updateSongCreditsContent").html(creditHTML);
					}
				}
			} catch (err) {
					alert(err);
			}

			$("#updateSongCreditsDialog").dialog('open');
		}
	});

}

function updateAlbumCredits(albumId)
{
	albumId = $("#editBandAlbumId").val();
	var updateAlbumCreditsData = "album_id=" + albumId;
	var updateAlbumCreditsTableHtml = "";
	$("#updateAlbumCreditsTable").html("");

	$.ajax({ type: 'GET', url: 'scripts/edit-album-credits.php', data: updateAlbumCreditsData, dataType: 'html',
		success: function(returnData) {
			albumData = returnData.split("::");
			arrayPlace = "0";
			numCredits = albumData[arrayPlace];
			arrayPlace++;
			x= "1";
			if (numCredits != "0")
			{
				while (x <= numCredits)
				{
					personId = albumData[arrayPlace];
					arrayPlace++;
					personFirstName = albumData[arrayPlace];
					arrayPlace++;
					personLastName = albumData[arrayPlace];
					personName = personFirstName + " " + personLastName;
					arrayPlace++;
					personRoleId = albumData[arrayPlace];
					arrayPlace++;
					personRoleName = albumData[arrayPlace];
					arrayPlace++;
					updateAlbumCreditsTableHtml = updateAlbumCreditsTableHtml + "<TR ID=\"roleID" + personRoleId + "\"><TD>" + personName + "</TD><TD>" + personRoleName + "</TD><TD><span class=\"ui-icon ui-icon-trash\" onclick=\"deleteAlbumRole("+ personRoleId + ")\" /></TD></TR>";
					x++;
				}
			}

			$("#updateAlbumCreditsTable").append(updateAlbumCreditsTableHtml);

			$("#updateAlbumCreditsDialog").dialog('open');
		}
	});
}

function deleteRole(roleID)
{
	var deleteRoleData = "role_id=" + escape(roleID);
	$.ajax({ type: 'GET', url: 'scripts/delete-my-song-role.php', data: deleteRoleData, dataType: 'html',
		success: function(returnData) {
			trHash = "#roleID" + roleID;
			$(trHash).remove();
		}
	});
}

function deleteBandRole(roleElementID,bcID)
{
	var trHash = "#"+ roleElementID;
	$(trHash).css("min-height","32px"); // so the 'loading' graphic looks decent
	showAjaxLoad($(trHash));
	deleteRoleData = "bc_id=" + escape(bcID);
	$.ajax({ type: 'GET', url: '/scripts/delete-role.php', data: deleteRoleData, dataType: 'html',
		success: function(returnData) {
			hideAjaxLoad();
			try {
				var json = $.parseJSON(returnData);
				if (!json.logged_in) {
					warnNoLoginSession();
				}
				else if (json.success) {
					$(trHash).remove();
					$("#editBandMembersButton").click();
				}
				else {
					var errorMessage = json.message || "Could not delete role";
					jAlert(errorMessage);
				}
			} catch (err) {
				jAlert("An unexpected error occured. Please try again later.", "Error");
			}
		}
	});
}

function deleteAlbumRole(roleID)
{
	deleteRoleData = "role_id=" + roleID;
	$.ajax({ type: 'GET', url: 'scripts/delete-my-album-role.php', data: deleteRoleData, dataType: 'html',success: function(returnData) {
		trHash = "#roleID" + roleID;
		$(trHash).remove();
	}});
}

function deleteSong(songId)
{
	$("#DeleteSongConfirmSpan").attr({ title: songId});
	$("#DeleteSongConfirmDialog").dialog('open');
}

function addSongsDialogButton()
{
	if ($("#editBandAlbumId").val() != "") {
		$("#addSongsDialogButtonDialog").dialog('open');
	}
}

function editAlbumArtworkDialogButton()
{
	if ($("#editBandAlbumId").val() != "")
	{
		KJPhoto.instance.managePhotosFor('album', $("#editBandAlbumId").val(), 'Edit Album Artwork');
		// TODO: remove old album artwork functions
//		getAlbumArtwork();
//		$("#editAlbumArtworkDialog").dialog('open');
	}
}


function deleteAlbumDialogButton()
{
	if ($("#editBandAlbumId").val() != "") {
		$("#deleteAlbumDialog1").dialog('open');
	}
}

function preUploadSongFunction()
{
	var albumId = $("#editBandAlbumId").val();
	$('#songsToUpload').val(escape($('#songsToUpload').val()));
	$('#songsToUpload').uploadifySettings('scriptData', {'album_id' : albumId });
	$('#addSongsDialogHelp').html("As each song in the list below is finished being uploaded and processed, it will disapear from the list. Please do not close this window until all songs are processed. Even if the progress states 100%, it is still not done processing.");
	$('#songsToUpload').uploadifyUpload();
}

function preUploadPersonPhotoFunction()
{
	var personID = document.getElementById('id').value;
	$('#personPhotoFileInput').uploadifySettings('scriptData', {'person_id' : personID });
	$('#addMyPhotosDialogHelp').html("As each photo in the list below is finished being uploaded and processed, it will disapear from the list. Please do not close this window until all songs are processed. Even if the progress states 100%, it is still not done processing.");
	$('#personPhotoFileInput').uploadifyUpload();
}

function preUploadAlbumArtworkFunction()
{
	var albumID = $("#editBandAlbumId").val();
	$('#albumArtworkFileInput').uploadifySettings('scriptData', {'album_id' : albumID });
	$('#albumArtworkFileInput').uploadifyUpload();
}

function bandMemberNewCredit(memberId,emailElement,firstNameElement,lastNameElement)
{
	var bandMemberData = "member_id=" + memberId;

	$.ajax({ type: 'GET', url: 'scripts/get-member-email.php', data: bandMemberData, dataType: 'html',success: function(returnData) {
			var memberHTML;
			try {
				var json = $.parseJSON(returnData);
				if (json.success == true)
				{

					memberHTML= "<div>";
					$.each(json.band_members, function(key,element){
						firstNameElementHash = "#" + firstNameElement;
						lastNameElementHash = "#" + lastNameElement;
						emailElementHash = "#" + emailElement;
						$(emailElementHash).val(element.user_email);
						$(firstNameElementHash).val(element.first_name);
						$(lastNameElementHash).val(element.last_name);
						$("#updateAlbumCreditsEmailAlert").attr({ title: element.id});
						$("#updateSongCreditsEmailAlert").attr({ title: element.id});
					});

				}
			} catch (err) {
				jAlert("Sorry, an unexpected error occurred", "Error");
			}
		}
	});
}

function getBandPhotos(bandID)
{
	var bandPhotoData = "band_id=" + bandID;
	$.ajax({ type: 'GET', url: 'scripts/get-band-photos.php', data: bandPhotoData,
		dataType: 'html',
		success: function(returnData) {
			try {
				var json = $.parseJSON(returnData);
				if (json.success == true)
				{
					var photoHTML= "";
					if (json.band_photos)
					{
						$.each(json.band_photos, function(key,element) {
							var	file_name = photo_cdn + element.cloud_file_name;
							var title     = element.title;
							var photo_id  = element.id;

							photoHTML +=
								"<div id=\"bandPhotoTable"+ photo_id +"\" class=\"formRow clearfix\">" +
									"<div class=\"formRow\"><img src=\"/scripts/image-resizer.php/"+file_name+"?image="+file_name+"&width=160&height=160&cropratio=1:1'\"  /></div>" +
									"<div class=\"formRow\"><input class=\"photocaption text ui-widget-content ui-corner-all\" type=\"text\" value = \"" +title +"\" id =\"photoTitleInput"+photo_id+"\" name=\"photoTitleInput"+photo_id+"\"/> " +
										"<button class=\"knerd-button\" onclick=\"updatePhotoTitle(" + photo_id + ");\">update caption</button></div>" +
									"<div class=\"formRow\"><button class=\"knerd-button\" onclick=\"makeDefaultPhoto(" + photo_id + ",\'band\');\">make profile photo</button></div>" +
									"<div class=\"formRow\"><span class=\"floatleft ui-icon ui-icon-trash\" onclick=\"deleteBandPhoto(" + photo_id + ");\"/> delete photo</div>" +
								"</div>";
						});

							$("#editBandPhotosContent").html("");

							$("#editBandPhotosContent").html(photoHTML);
					}
				}

			} catch (err) {
				$("#editBandPhotosContent").html("Upload some band photos for the world to view!");
				jAlert("Unexpected error!", "Yikes!");
			}
		}
	});
}


function updatePhotoTitle(photoID)
{
	var photoTitleID = "#photoTitleInput" + photoID;
	var photoTitle = $(photoTitleID).val();
	var bandPhotoData = "photo_id=" + photoID + "&photo_title=" + escape(photoTitle);
	$.ajax({ type: 'GET', url: 'scripts/update-photo-title.php', data: bandPhotoData, dataType: 'html',success: function(returnData) {

	}});
}




function makeDefaultPhoto(photoID,photoType)
{
	makeDefaultPhotoData = "photo_id=" + photoID + "&" + "photo_type=" + photoType;
	$.ajax({ type: 'GET', url: 'scripts/make-photo-default.php', data: makeDefaultPhotoData, dataType: 'html',success: function(returnData) {

	}});
}

function deleteBandPhoto(photoID)
{
	deleteBandPhotoData = "photo_id=" + photoID;
	$.ajax({ type: 'GET', url: 'scripts/delete-band-photo.php', data: deleteBandPhotoData, dataType: 'html',success: function(returnData) {
	$("#editBandPhotosButton").click();
	}});
}
//																			GET ALBUM ARTWORK
function getAlbumArtwork()
{	$("#editAlbumArtworkTable").html("");
	albumID = $("#editBandAlbumId").val();
	albumArtworkData = "album_id=" + albumID;
	$.ajax({ type: 'GET', url: 'scripts/get-album-artwork.php', data: albumArtworkData, dataType: 'html',
		success: function(returnData) {
			var json = null;

			try {
				json = $.parseJSON(returnData);
				//console.debug("Parsed response to valid json: " + returnData);

					if (json.success == true)
					{

						var photoHTML= "";
						$.each(json.album_artwork, function(key,element){

							var	file_name = photo_cdn + element.cloud_file_name;
							var title = element.title;
							var photo_id = element.id;

							photoHTML += "<div id=\"albumArtworkTable"+ photo_id +"\" class=\"formRow clearfix\"><div class=\"formRow\"><img src=\"/scripts/image-resizer.php/"+file_name+"?image="+file_name+"&width=160&height=160&cropratio=1:1'\"  /></div><div class=\"formRow\"><input class=\"photocaption text ui-widget-content ui-corner-all\" type=\"text\" value = \"" +title +"\" ID =\"albumArtworkTitle"+photo_id+"\" NAME=\"albumArtworkTitle"+photo_id+"\"/> <button class=\"knerd-button\" onclick=\"updateAlbumPhotoTitle(" + photo_id + ");\">update caption</button></div><div class=\"formRow\"><button class=\"knerd-button\" onclick=\"makeDefaultPhoto(" + photo_id + ",\'album\');\">make profile photo</button> </div><div class=\"formRow\"><span class=\"floatleft ui-icon ui-icon-trash\" onclick=\"deleteAlbumArtwork(" + photo_id + ");\"/>delete photo</div></div>";


							});
							$("#editAlbumArtworkContent").html("");
							$("#editAlbumArtworkContent").html(photoHTML);
						}

				} catch (err) {
						if (err == "TypeError: json is null")
						{
							$("#editAlbumArtworkContent").html("Upload the artwork for this album for the world to see!");
						} else { alert(err); }
				}
	}});

}


function deleteAlbumArtwork(photoID)
{
	deletePhotoData = "photo_id=" + photoID;
	$.ajax({ type: 'GET', url: 'scripts/delete-photo.php', data: deletePhotoData, dataType: 'html',success: function(returnData) {
	trHash = "#albumArtworkTable" + photoID;
	$(trHash).remove();
	}});
}

function updateAlbumPhotoTitle(photoID)
{
	photoTitleID = "#albumArtworkTitle" + photoID;
	photoTitle = $(photoTitleID).val();
	albumPhotoData = "photo_id=" + photoID + "&" + "photo_title=" + photoTitle;
	$.ajax({ type: 'GET', url: 'scripts/update-photo-title.php', data: albumPhotoData, dataType: 'html',success: function(returnData) {

	}});
}

//																			PERSON PHOTO FUNCTIONS
//
// getMyPhotos replaced by KJPhoto js library
//  TODO: delete other dialogs and functions that are no longer needed
//function getMyPhotos()
//{
//	$.ajax({
//		type: 'GET',
//		url: '/scripts/get-person-photos.php',
//		dataType: 'html',
//		success: function(returnData) {
//			var json = null;
//			var eventListHTML;
//			try {
//				json = $.parseJSON(returnData);
//				//console.debug("Parsed response to valid json: " + returnData);
//
//					if (json.success == true)
//					{
//
//						var photoHTML= "";
//						if (typeof(json.person_photos) != "undefined")
//						{
//							$.each(json.person_photos, function(key,element){
//
//								var	file_name = photo_cdn + element.cloud_file_name;
//								var title = element.title;
//								var photo_id = element.id;
//
//								photoHTML += "<div id =\"personPhotoTable"+ photo_id +"\" class=\"formRow clearfix\"><div class=\"formRow\"><img src=\"/scripts/image-resizer.php/"+file_name+"?image="+file_name+"&width=160&height=160&cropratio=1:1'\"  /></div><div class=\"formRow\"><input class=\"photocaption text ui-corner-all\" type=\"text\" value = \"" +title +"\" id=\"photoTitleInput"+photo_id+"\" name=\"photoTitleInput"+photo_id+"\"/><button class=\"knerd-button\" onclick=\"updatePhotoTitle(" + photo_id + ");\">update caption</button></div><div class=\"formRow\"><button class=\"knerd-button\" onclick=\"makeDefaultPhoto(" + photo_id + ",\'person\');\">make profile photo</button></div><div class=\"formRow\"><span class=\"floatleft ui-icon ui-icon-trash\" onclick=\"deletePersonPhoto(" + photo_id + ");\"/>delete photo</div></div>";
//							});
//							$("#editPersonPhotosContent").html("");
//							$("#editPersonPhotosContent").html(photoHTML);
//						}
//					}
//				} catch (err) {
//						if (err == "TypeError: json is null")
//						{
//							$("#editPersonPhotosContent").html("Upload some photos for the world to view!");
//						} else { alert(err); }
//				}
//
//
//		} // end success fn
//	}); // end $.ajax()
//}

function updatePhotoTitle(photoID)
{
	photoTitleID = "#photoTitleInput" + photoID;
	photoTitle = $(photoTitleID).val();
	personPhotoData = "photo_id=" + escape(photoID) + "&photo_title=" + escape(photoTitle);
	$.ajax({ type: 'GET', url: 'scripts/update-photo-title.php', data: personPhotoData, dataType: 'html',success: function(returnData) {

	}});
}

function makeDefaultPhoto(photoID,photoType)
{
	makeDefaultPhotoData = "photo_id=" + photoID + "&photo_type=" + photoType;
	$.ajax({ type: 'GET', url: 'scripts/make-photo-default.php', data: makeDefaultPhotoData, dataType: 'html',success: function(returnData) {

	}});
}

function deletePersonPhoto(photoID)
{
	$.get('/scripts/delete-photo.php', {
			photo_id: photoID
		},
		function() {
			$("#changeMyPhotos").click();
		}
	);
}

function albumSearchClick(album_id)
{
	var albumSearchClickData = "album_id=" + album_id;
	$.ajax({ type: 'GET', url: 'scripts/album-searchclick.php', data: albumSearchClickData, dataType: 'html',
		success: function(returnData) {
			searchData = returnData.split("::");
			arrayPlace = "0";
			album_id = searchData[arrayPlace];
			arrayPlace++;
			create_album_div(album_id);
			album_title = searchData[arrayPlace];
			arrayPlace++;
			album_copyright = searchData[arrayPlace];
			arrayPlace++;
			album_num_tracks = searchData[arrayPlace];
			arrayPlace++;
			album_record_label = searchData[arrayPlace];
			arrayPlace++;
			album_pulisher = searchData[arrayPlace];
			arrayPlace++;
			album_description = searchData[arrayPlace];
			if (album_description == "")
			{
				album_description = "album description has not been created yet...";
			} else
			{
				album_description = "<b>album description: </b><br/>" + album_description;
			}

			arrayPlace++;
			album_default_photo = searchData[arrayPlace];
			arrayPlace++;
			album_band_id = searchData[arrayPlace];
			arrayPlace++;
			album_band_name = searchData[arrayPlace];
			arrayPlace++;

			albumMetricsElement = "#albumMetrics" + album_id;
			albumMetricsHTML = "<b>" + album_title + "</b>" + "<br/>" + "artist: " + "<a onClick=\"displayDataAndConnect('band','album','" + album_band_name + "','" + album_band_id + "');\" class=\"ajax-button\">" + album_band_name + "</a>" + "<br/>" +"copyright: " + album_copyright + "<br/>";
			if (album_record_label != "")
			{
				albumMetricsHTML = albumMetricsHTML + "record_label: " + album_record_label + "<br/>";
			}
			if (album_pulisher != "")
			{
				albumMetricsHTML = albumMetricsHTML + "publisher: " + 	album_pulisher + "<br/>";
			}
			$(albumMetricsElement).html(albumMetricsHTML);

			albumImgElement = "#albumImage" + album_id;
			$(albumImgElement).attr({src: album_default_photo});

			albumDescriptionElement = "#albumDescription" + album_id;
			$(albumDescriptionElement).html(album_description);

			album_num_credits = searchData[arrayPlace];
			albumCreditsHTML = "<b>credits: </b><br/>";
			if (album_num_credits > "0")
			{
				for (var x=0; x < album_num_credits; x++)
				{
					arrayPlace++;
					person_name = searchData[arrayPlace];
					arrayPlace++;
					person_id = searchData[arrayPlace];
					albumCreditsHTML = albumCreditsHTML + "<a onClick=\"displayDataAndConnect('person','album','" + person_name + "','" + person_id + "');\" class=\"ajax-button\">" + person_name + ": </a>";
					arrayPlace++;
					num_roles = searchData[arrayPlace];
					if (num_roles > "0")
					{
						for (var y=1;y<=num_roles;y++)
						{
							arrayPlace++;
							role_name = searchData[arrayPlace];
							if (y < num_roles) {
								albumCreditsHTML = albumCreditsHTML + role_name + ", ";
							}
							else {
								albumCreditsHTML = albumCreditsHTML + role_name;
							}
						}
						albumCreditsHTML = albumCreditsHTML + "<br/>";
					}
				}
				albumCreditsElement = "#albumCredits" + album_id;
				$(albumCreditsElement).html(albumCreditsHTML);
			}
		}
	});
}


// Brings up a dialog for selecting which linked accounts
// to post a just-added-event to.
// E.g. posting a news entry to Twitter
function postToLinkedAccounts(new_event_id, type) {

	var $target = $("#postToLinkedAccountsDialog").find(".dlg-content");
	$target.html("<p>Loading...</p>"); // prepare dialog with "loading" message

	// Show the dialog
	$("#postToLinkedAccountsAjaxResults").html(''); // blank out results
	$("#postToLinkedAccountsDialog").dialog("open"); // open dialog

	// Get list of linked accounts to populate `target`
	$.getJSON("/scripts/linked/postToLinked.php", {
			event_id:   new_event_id,
			event_type: type,
			action: 'list'
		},
		function(json) {
			$target.html(json.html);
			if (!json.success && json.message) {
				jAlert(json.message);
			}
		}
	);
}


function get_states(country_element, state_element, state_value)
{
	var countryElementIDHash = "#" + country_element;
	var stateElementIDHash   = "#" + state_element;

	var $countryDropdown     = $(countryElementIDHash);
	var $stateDropdown       = $(stateElementIDHash);

	$stateDropdown.empty();
	if (state_value) {
		// pre-populate the state dropdown with the current value so there's no delay
		var $defaultOption = $("<option></option>");
		$defaultOption.text(state_value);
		$defaultOption.val(state_value);
		$defaultOption.attr("selected","selected");
		$stateDropdown.append($defaultOption);
	}

	if ($countryDropdown.val())
	{
		$.getJSON("http://zafon.ws.geonames.org/searchJSON?formatted=true&q=&maxRows=100&featureCode=ADM1",
			{  country: $countryDropdown.val() },
			function(data) {
				if (data.geonames == null) {
					alert('No regions'); // TODO: better error handling!!!
				}

				$.each(data.geonames, function(i,item){
					if (item.name != state_value) { // state_value option already added, so skip here
						var $option = $('<option></option>');
						$option.text(item.name);
						$option.val(item.name);
						$stateDropdown.append($option);
					}
				});

				$stateDropdown.sortOptions();
			}
		);
	}
}

function displayNewsToEdit(bandNewsID) {
	$("#bandEventShowEditor").hide();
	$("#bandEventNewsEditor").hide();

	$.getJSON("/scripts/get-band-news.php",
		{ band_news_id: bandNewsID},
		function(json) {
			var isError = false;
			if (json.success) {
				if (json.band_news && json.band_news.length > 0) {
					var bandNews = json.band_news[0]; // first element

					$("#editNewsHeadline"   ).val(bandNews.news_headline);
					$("#editNewsLink"       ).val(bandNews.news_link);
					$("#editNewsDescription").val(bandNews.news_content);
					$("#editEventIDAnchor"  ).val(bandNewsID);

					$("#bandEventNewsEditor").show();

					// formerly: editBandEventDialogButtonSaveChanges
					$('#editBandEventsDialog').dialog('addbutton', 'save changes',
							function() {
								$("#editNewsID").val(bandNewsID);
								$("#bandEventNewsEditor > form").submit();
							}
					);

					// formerly: editBandEventDialogButtonDeleteEvent
					$('#editBandEventsDialog').dialog('addbutton', 'delete event', function() {
						jConfirm("Are you sure you want to delete that news entry?", "Confirm Delete", function(resp) {
							if (resp) {
								$.getJSON("/scripts/delete-band-news.php", { delete_news_id: bandNewsID }, function(json) {
									if (json.success) {
										$("#bandManagerEditNews").click();
									} else if (!json.logged_in) {
										warnNoLoginSession();
									} else {
										var msg = json.message || "An error occurred";
										jAlert(msg, "Error");
									}
								});

							}
						});
					});

				} else {
					isError = true;
				}
			} else if (!json.logged_in) {
				warnNoLoginSession();
			}
			else {
				isError = true;
			}

			if (isError) {
				var errorMessage = json.message || "An error occurred";
				jAlert(errorMessage, "Error");
			}
		}
	);
}

function displayEventToEdit(event_id)
{
	$("#bandEventShowEditor").hide();
	$("#bandEventNewsEditor").hide();
	var dataEvent = "event_id=" + event_id;
	$.ajax({ type: 'GET', url: 'scripts/get-band-event-to-edit.php',data: dataEvent, dataType: 'html',
		success: function(returnData) {
			$('#editBandEventsDialog').dialog('addbutton', 'save changes', editBandEventDialogButtonSaveChanges);
			$('#editBandEventsDialog').dialog('addbutton', 'delete event', editBandEventDialogButtonDeleteEvent);
			try {
				var json = $.parseJSON(returnData);
				if (json.success)
				{
					if (typeof(json.band_events) != "undefined")
					{
						$.each(json.band_events, function(key,element)
						{
							if (element.event_type == "show") {
								var timeArray   = element.door_time.split(":");
								var editHour    = timeArray[0];
								var timeArray2  = timeArray[1].split(" ");
								var editMinutes = timeArray2[0];
								var editAMPM    = timeArray2[1];

								$("#editEventIDAnchor").val(element.id);
								$("#editEventCountriesSelect").val(element.event_country_iso);
								$("#editShowDate").val(element.date);
								$("#editShowDoorTime").selectOptions(editHour);
								$("#editShowDoorMinutes").selectOptions(editMinutes);
								$("#editShowAmPm").selectOptions(editAMPM);
								$("#editEventShowCity").val(element.event_city);
								$("#editShowVenueName").val(element.venue_name);
								$("#editEventShowLink").val(element.event_link);
								$("#editShowTicketLink").val(element.event_ticket_link);
								$("#editShowTicketPrice").val(element.event_ticket_price);
								$("#editShowTicketDoorPrice").val(element.event_ticket_door_price);
								$("#editEventShowDescription").val(element.description);
								$("#bandEventShowEditor").show();
								get_states('editEventCountriesSelect','editEventStatesSelect', element.event_region);
							}
						});
					}
				}
			} catch (err) {
				jAlert("Unexpected error", "Yikes!");
			}
		}
	});
}//end of displayEventToEdit



function editBandEventDialogButtonSaveChanges()
{
	var event_id = $("#editEventIDAnchor").val();

	if ($("#bandEventNewsEditor").is(":hidden")) {
		var show_date              = $("#editShowDate").val();
		var show_time              = $("#editShowDoorTime").val() + ":" + $("#editShowDoorMinutes").val() + " " + $("#editShowAmPm").val();
		var show_country_iso       = $("#editEventCountriesSelect").val();
		var show_region            = $("#editEventStatesSelect").val();
		var show_city              = $("#editEventShowCity").val();
		var show_venue_name        = $("#editShowVenueName").val();
		var show_link              = $("#editEventShowLink").val();
		var show_ticket_link       = $("#editShowTicketLink").val();
		var show_ticket_price      = $("#editShowTicketPrice").val();
		var show_ticket_door_price = $("#editShowTicketDoorPrice").val();
		var show_description       = $("#editEventShowDescription").val();

		if (show_date == "" || show_country_iso == "nothing" || show_region == "0" || show_venue_name == "") {
			jAlert("Be sure to select a date, time, country, state, city and venue name for this show...");
		}
		else {
			saveShowData = "event_id=" + escape(event_id) + "&show_date=" + escape(show_date) + "&show_time=" + escape(show_time) +
				"&show_country_iso=" + escape(show_country_iso) + "&show_region=" + escape(show_region) + "&show_city=" + escape(show_city) +
				"&show_venue_name=" + escape(show_venue_name) + "&show_link=" + escape(show_link) + "&show_description=" + escape(show_description) +
				"&show_ticket_price="+ escape(show_ticket_price) + "&show_ticket_door_price="+ escape(show_ticket_door_price) +
				"&show_ticket_link=" + escape(show_ticket_link);

			$.ajax({ type: 'GET', url: '/scripts/update-band-show-event.php', data: saveShowData, dataType: 'json',
				success: function(json) 	{
					if (json.success) {
						$("#bandEventShowEditor").hide();
						$("#bandEventNewsEditor").hide();
						$('#editBandEventsDialog').dialog('removebutton', 'save changes');
						$('#editBandEventsDialog').dialog('removebutton', 'delete event');
						$("#editEventCountriesSelect").val("nothing");
						$("#editEventShowCity").val("");
						$("#editShowVenueName").val("");
						$("#editEventShowLink").val("");
						$("#editShowTicketLink").val("");
						$("#editShowTicketPrice").val("");
						$("#editShowTicketDoorPrice").val("");
						$("#editEventShowDescription").val("");
						$("#bandManagerEditEvents").click();
					}
					else if (!json.logged_in) {
						warnNoLoginSession();
					}
					else {
						var errorMessage = json.message || "Unexpected error";
						jAlert(errorMessage, "Error");
					}
				} // end success function
			}); // end $.ajax
		}
	} // end "else if"

} // end function editBandEventDialogButtonSaveChanges

function editBandEventDialogButtonDeleteEvent()
{
	$("#editBandEventsDeleteDialog").dialog('open');
}


function deleteBandSocialAccount(account_id)
{
	$("#deleteSocialAccountVerifyID").val(account_id);
	$("#deleteSocialBandAccount").dialog('open');
}

function debugLog(msg) {
	try {
		if(window.console) {
			console.debug(msg);
		}
	} catch (err) { }
}

function editBandSocialAccount(account_id)
{
	editSocialBandData = "account_id=" + escape(account_id);
	$("#editSocialAccountIDSave").val(account_id);
	$.ajax({ type: 'GET', url: '/scripts/get-band-social-account-info.php', data: editSocialBandData, dataType: 'html',
		success: function(returnData) {
			$("#myBandSocialMediaEditName").val(returnData);
		}
	});

	$("#editBandSocialAccountDialog").dialog('open');
}

function getPurchaseSongLink(song_id)
{
	$("#newSongPurchaseLinkSongID").val(song_id);

	$.post('scripts/get-band-song-purchase-links.php', {
			song_id: song_id
		},
		function(returnData)
		{
			try {
				var json = $.parseJSON(returnData);
				if (json.success == true)
				{
					$("#editSongPurchaseLinksDisplayDiv").html("");

					//$displayLinksArea.empty(); // <-- remove previous results
					var linkData = null;
					$.each(json.data, function(key,element){
						// Do something with element (which is an entry in the original $data array from the PHP script)
						// console.debug(element);
						linkData = "<div class=\"formRow clearfix\" id=\"songPurchaseLinkSpan" + element.id + "\"><div class=\"editIcons\"><span class=\"ui-icon ui-icon-trash\" onclick=\"deleteSongPurchaseLink("+ element.id +")\"></span></div><input type=\"text\" id=\"songPurchaseLinkURL" + element.id + "\" value=\"" + element.site_url + "\" old_value=\"" + element.site_url + "\" size=\"25\" link_id=\"" + element.id + "\" class=\"songPurchaseURL text ui-widget-content ui-corner-all\" /><div class=\""+ element.site_type+" floatleft\"></div></div>";

						$("#editSongPurchaseLinksDisplayDiv").append(linkData);
					});
				}
			} catch (err) {
			}
		}
	,
	'html'
	);  // end $.post

	$("#editSongPurchaseLinksDialog").dialog('open');
}

function getPurchaseAlbumLink(album_id)
{
	$("#newAlbumPurchaseLinkAlbumID").val(album_id);

	$.post('scripts/get-band-album-purchase-links.php', {
			album_id: album_id
		},
		function(returnData)
		{
			try {
				var json = $.parseJSON(returnData);
				if (json.success == true)
				{
					$("#editAlbumPurchaseLinksDisplayDiv").html("");

					//$displayLinksArea.empty(); // <-- remove previous results
					var linkData = null;
					$.each(json.data, function(key,element){
						// Do something with element (which is an entry in the original $data array from the PHP script)
						// console.debug(element);
						linkData = "<div id=\"albumPurchageLinkSpan" + element.id + "\" class=\"socialLink formRow clearfix\"><div class=\"editIcons\"><span class=\"ui-icon ui-icon-trash\" onclick=\"deleteAlbumPurchaseLink("+ element.id +")\"></span></div><div class=\"floatLeft\"><div class=\""+ element.site_type+" social-icon\"></div> <input style=\"float: right;\"type=\"text\" id=\"albumPurchaseLinkURL" + element.id + "\" value=\"" + element.site_url + "\" old_value=\"" + element.site_url + "\" size=\"25\" link_id=\"" + element.id + "\" class=\"albumPurchaseURL text ui-widget-content ui-corner-all\" /></div></div><br/>";

						$("#editAlbumPurchaseLinksDisplayDiv").append(linkData);
					});
				}
			}
			catch (err) {
				// json error..
			}
		},
		'html'
	);  // end $.post
}

function deleteAlbumPurchaseLink(link_id)
{
	var x=window.confirm("are you sure you want to delete this link?");
	if (x)
	{
		var deleteData = "link_id=" + link_id;
		$.ajax({ type: 'GET', url: 'scripts/delete-album-purchase-link.php', data: deleteData, dataType: 'html',success: function(returnData) {
			spanID= "#albumPurchageLinkSpan" + link_id;
			$(spanID).remove();
		}});
	}
}


function deleteSongPurchaseLink(link_id)
{
	var x=window.confirm("are you sure you want to delete this link?");
	if (x)
	{
		var deleteData = "link_id=" + link_id;
		$.ajax({ type: 'GET', url: 'scripts/delete-song-purchase-link.php', data: deleteData, dataType: 'html',success: function(returnData) {
			spanID= "#songPurchageLinkSpan" + link_id;
			$(spanID).remove();
		}});
	}
}

function deleteSongVideoLink(link_id)
{
	var x=window.confirm("are you sure you want to delete this video?");
	if (x)
	{
		var deleteData = "link_id=" + link_id;
		$.ajax({ type: 'GET', url: 'scripts/delete-song-video-link.php', data: deleteData, dataType: 'html',success: function(returnData) {
			spanID= "#songVideoLinkSpan" + link_id;
			$(spanID).remove();
		}});
	}
}


function editAlbumPurchaseLinksButton()
{
	if ($("#editBandAlbumId").val() != "")
	{
		var album_id = $("#editBandAlbumId").val();
		getPurchaseAlbumLink(album_id);
		$("#editAlbumPurchaseLinksDialog").dialog('open');
	}
}

function editBandAlbumCredits()
{
	var albumId = $("#editBandAlbumId").val();
	var updateAlbumCreditsData = "album_id=" + albumId;
	var updateAlbumCreditsTableHtml = "";
	var updateAlbumBandMembersTableHtml = "";
	$("#updateAlbumBandMembersDiv").html("");
	$("#updateAlbumCreditsContent").html("");

	var bandId = $("#my_band_id").val();
	var getBandMembersData = "band_id=" + bandId;

	$.ajax({ type: 'GET', url: 'scripts/get-band-members.php', data: getBandMembersData, dataType: 'html',success: function(returnData) {
		try {
			var json = $.parseJSON(returnData);
			if (json.success == true)
			{
				var memberHTML= "<p>Band Members and Roles:</p><ul>";
				$.each(json.band_members, function(key,element){
					memberHTML += "<li id=\"memberID" + element.user_id + "\"><a class=\"ajax-button\" onclick=\"bandMemberNewCredit('" + element.user_id + "','updateAlbumCreditsEmail','updateAlbumCreditsFirstName','updateAlbumCreditsLastName')\" >" +element.member_name + ": </a>"+ element.roles +"</li>";
				});

				memberHTML += "</ul></div>";
				$("#updateAlbumBandMembersDiv").html(memberHTML);
			}
		} catch (err) {
			jAlert("An error occurred. Please try again", "Yikes!");
		}
	}});


	$.ajax({ type: 'GET', url: 'scripts/edit-album-credits.php', data: updateAlbumCreditsData, dataType: 'html',
		success: function(returnData) {
			try {
				var json = $.parseJSON(returnData);
				if (json.success == true)
				{
					var creditHTML= "";
					if (typeof(json.album_credits) != "undefined")
					{
						$.each(json.album_credits, function(key,element){
							creditHTML += "<div><div ID=\"roleID" + element.id + "\"><div>" + element.first_name + " " + element.last_name + " - " + element.role_name + " <span class=\"ui-icon ui-icon-trash\" onclick=\"deleteAlbumRole("+ element.id + ")\" /></div></div><div style=\"clear:both;\"></div>";
						});
						creditHTML += "</div>";
					}
					$("#updateAlbumCreditsContent").html(creditHTML);
				}
			} catch (err) {
				jAlert("An error occurred. Please try again", "Yikes!");
			}

			$("#updateAlbumCreditsDialog").dialog('open');
		}
	});

} // end editBandAlbumCredits()


/**
 * highlight + fade effect. (Custom jquery animated effect by barwin)
 *
 * Will cause the target object's background to fade from yellow to white, thus
 * providing a momentary "highlight" of the object
 *
 * Optionally specify background color (start and end) and also the duration
 * for the animation
 *
 * Usage: $("#object-selector").highlightFade();
 *
 * @param object settings to override default behavior
 * @param function_ref callbackfunc Optional callback function to execute on animation completion
 * @return object this
 */
$.fn.highlightFade = function(settings, callbackfunc) {
	if (typeof(settings) == "undefined" || settings == null || settings == "undefined") {
		settings = {};
	}
	if (typeof(callbackfunc) == "undefined" || callbackfunc == "undefined") {
		callbackfunc = null;
	}
	settings = $.extend({ bg_start: '#FBEC5D', bg_end: '#FFFFFF', duration: 1000 }, settings);
	var use_bg_end = settings.bg_end;
	this.each(function() {

		try {
			use_bg_end = $(this).css("background-color");
			if (!use_bg_end) { use_bg_end = settings.bg_end; }
		} catch (err) {
			// bombed out trying to guess bg_end. defaulting to settings.bg_end
			use_bg_end = settings.bg_end;
		}

		$(this).css({ 'opacity':'0.0', 'background-color': settings.bg_start});
		try {
			$(this)
				.animate({
					opacity: 1.0,
					'background-color': use_bg_end
				}, settings.duration, callbackfunc );
		} catch (err) {
			//debugLog(err);
		}
	});
	return this;
};

/**
 * Build a unordered list of error messages passed in as an array, and add the result
 * to the $target
 *
 * @param $target DOM element to add the <ul> to
 * @param msgarray array of error messages
 * @param defaultMessage will be used if msgarray is empty
 * @return void
 */
function displayErrorMessages($target, msgarray, defaultMessage) {
	$target.empty();
	var $ul = $("<ul class='error-msg'></ul>");
	if (msgarray && msgarray.length > 0) {
		$.each(msgarray, function(i,msg) {
			$("<li></li>").text(msg).appendTo($ul);
		});
	}
	else if (typeof(defaultMessage) != "undefined" && defaultMessage) {
		$("<li></li>").text(defaultMessage).appendTo($ul);
	}
	$target.html($ul);
}

/**
 * If no user session was found, use this function to display a message and login/register links
 * @return void
 */
function warnNoLoginSession() {
	jAlert("To use that feature, you must be logged in.<br /><br />" +
			"<a href='/login'>Login</a> or <a href='/register'>Create an Account</a>",
			"Must Login First");
}

/**
 * update content in visitor_count via ajax call. This runs periodically via setInterval()!
 */
function updateVisitorCount() {
	jQuery("#visitor_count").load("/includes/inc.visitor-count.php");
}

function savePageState(settings) {
	if (settings === undefined) {
		settings = {};
	}
	var data = jQuery.extend({
		save_tab: $tabs.tabs("option", "selected")
		},
		settings
	);
	jQuery.get( "/scripts/page-statesave.php", { save_tab: data.save_tab } );
} // end savePageState

function deleteAccount()
{
	$("#deleteAccountDialog").dialog('open');
}


/**
 * (originally defined in knerd.player.js)
 * A wrapper for jquery's ajax functions that has some error handling built-in.
 * Allows us to do ajax calls without so much repeated error handling code
 *
 * @param type (get or post. 'get' is the default)
 * @param url
 * @param data
 * @param success_callback
 * @param failure_callback
 * @return
 */
function kAjax(type, url, data, success_callback, failure_callback) {
	var ajax_func = jQuery.get;
	if (type == 'post') { ajax_func = jQuery.post; }

	ajax_func(url, data,
		function(data) {
			try {
				var json = jQuery.parseJSON(data);
				if (json.success) {
					if (success_callback) { success_callback(json); }
				}
				else if (json.logged_in !== undefined && !json.logged_in) {
					// only check session if json explicitely set json.logged_in = false.
					warnNoLoginSession();
				}
				else {
					if (failure_callback) { failure_callback(json); }
					else {
						var errorMessage = json.message || "An error occurred. Please try again later";
						jAlert(errorMessage, "Error");
					}
				}
			} catch (err) { jAlert("Yikes! unexpected error! ", err); }
		},
		'html'
	);
}

function socialBandImport(json)
{
	if (json.success == true)
	{
		$("#socialBandDataDiv").empty();

		// ITUNES
		$.each(json.itunes.artists, function(key,artist){
			var $iTunesDiv = $("<div class=\"ui-helper-hidden band_itunes_div remote-band-div\"><span class=\"socialIcon apple\" /> <span><h3>Is this your band's iTunes page?</h3> <i>(click the band name to see.)</i></span><br/><div style=\"clear:both;\"></div>Band Name: <a target=\"_blank\" href=\""+ artist.url +"\">"+artist.name+"</a><br/><div><br/>");

			$.each(artist.albums, function(a,album) {
				if (album.album_title != null)
				{
					$iTunesDiv.append("<div style=\"float: left; margin: 10px 10px 10px 10px;\"><span><u>"+album.album_title+"</u></span><br/><center><span><br/><img src=\""+album.photo_60+"\" alt='' /></span></center></div>");
				}
			} );
			$iTunesDiv.append("</div>");

			$iTunesDiv.data("itunes_id", artist.id);
			$iTunesDiv.data("itunes_url", artist.url);
			$iTunesDiv.data("itunes_amgID", artist.amgID);

			$("#socialBandDataDiv").append($iTunesDiv);
		});


		// FACEBOOK
		$.each(json.facebook, function(key,element){
			//alert(element.location);
			var bandAndLocation;
			if (element.location) {
				bandAndLocation = element.band_name + ": " + element.location;
			}
			else {
				bandAndLocation = element.band_name;
			}

			var $facebookHTML =
				$("<div class=\"ui-helper-hidden band_facebook_div remote-band-div\">" +
					"<span class=\"socialIcon facebook\" /> <h3> Is this the correct Facebook page? </h3> <i>(click the photo to see...)</i> <div style='clear:both;'></div> <br/> <div><a target=\"_blank\" href=\""+ element.link +"\">"+bandAndLocation+"</a><br/><a target=\"_blank\" href=\""+ element.link +"\"><img style=\"margin: 10px 10px 10px 10px;\" src=\""+element.small_photo_url+"\" alt='' /></a></div>" +
				"</div>");

			$facebookHTML.data("facebook_link",element.link);
			$facebookHTML.data("facebook_id",element.id);
			$facebookHTML.data("facebook_large_photo_url",element.large_photo_url);

			$("#socialBandDataDiv").append($facebookHTML);
		});


		// LAST.FM
		//var lastfmSize = json.lastfm.summary.length;
		//alert(lastfmSize);
		json.lastfm.summaryShort = json.lastfm.summary
		if (json.lastfm.summary.length > 466)
		{
			json.lastfm.summaryShort = json.lastfm.summary.substring(0,465)+"...";
		}
		var $lastfmHTML =
			$("<div class=\"ui-helper-hidden band_lastfm_div remote-band-div\">" +
					"<span class=\"socialIcon lastfm\" /> <br/><h3> Is this "+json.lastfm.name+"'s Last.FM page?</h3><br/><div style=\"clear:both;\"></div><a class = \"\" target=\"_blank\" href=\""+ json.lastfm.url +"\">"+json.lastfm.name+ "</a><br/><a target=\"_blank\" href=\""+ json.lastfm.link +"\"></a><br/> <img src=\""+json.lastfm.squareImageURL+"\" alt='' /><p> Summary: "+ json.lastfm.summaryShort+"</p>" +
			"</div>");
		$lastfmHTML.data("lastfm_url",json.lastfm.url);
		$lastfmHTML.data("lastfm_summary",json.lastfm.summary);
		$lastfmHTML.data("lastfm_mbid",json.lastfm.mbid);
		$lastfmHTML.data("lastfm_originalImageURL",json.lastfm.originalImageURL);
		$lastfmHTML.data("lastfm_squareImageURL",json.lastfm.squareImageURL);

		$("#socialBandDataDiv").append($lastfmHTML);


		// MYSPACE
		$.each(json.myspace, function(key,element){
			var $myspaceHTML =
				$("<div class=\"ui-helper-hidden band_myspace_div remote-band-div\">" +
					"<span class=\"socialIcon myspace\" /><br/> <h3> Is this "+element.band_name + "'s MySpace page?</h3> <i>(click the photo to see.)</i><br/><div style=\"clear:both;\"></div><br/><a target=\"_blank\" href=\""+ element.myspace_url +"\" style='text-decoration:underline;'>"+element.band_name + ": "+ element.location +"</a><br/><a target=\"_blank\" href=\""+ element.myspace_url +"\"><img style=\"margin: 10px 10px 10px 10px;\" src=\""+element.photo+"\" alt='' /></a>" +
				"</div>");
			$myspaceHTML.data("myspace_url",element.myspace_url);
			$myspaceHTML.data("myspace_id",element.myspace_id);
			$myspaceHTML.data("myspace_photo",element.photo);

			$("#socialBandDataDiv").append($myspaceHTML);
		});


		//var itunesSize   = $(".band_itunes_div").size();
		//var facebookSize = $(".band_facebook_div").size();
		//var lastfmSize   = $(".band_lastfm_div").size();
		//var myspaceSize  = $(".band_myspace_div").size();

		//var alertVar="iTunes Results: " + itunesSize + " LastFM Results: " + lastfmSize + " facebook Results: " + facebookSize + " MySpace Results: " + myspaceSize;


		$("#addBandSocialImportDialog").dialog('open');
	}
	else {
		var msg = "No social sites were found for this band... If you have any to add, please click on 'Edit Bank Links'.";
		$("#editBandMembersButton").click();
		$("#editBandInfoButton").click();
		jAlert(msg);
	}

} // end socialBandImport

