// schiros added generic usefullness js crap
var playerArray = new Array();
var playerCounter = 0;

Position.includeScrollOffsets = true;

var player;
var playerInfoArray;
var currentPlaylistItem;
var currentTimeInSeconds;
var startIsPlaying;
function playerReady(playerInfo) {
	player = $("aplayer");
	player.addControllerListener("ITEM","updatePlayerCurrentSongInfo");
	player.addModelListener("TIME","updatePlayerCurrentPosition");
	player.addControllerListener("VOLUME","updatePlayerCurrentVolume");
	player.addModelListener("STATE","updatePlayerIsPlaying");
	setTimeout("jumpToCurrent()",1000);
}

function resetPlayer() {
	if(startIsPlaying) {
		doStart = 'true';
	}
	else {
		doStart = 'false';
	}
	if(doStart) {
		setTimeout("jumpToCurrent()",200);
	}
}

function jumpToCurrent() {
	player.sendEvent("SEEK",currentTimeInSeconds);
}

function updateTrackFeedbackRating(trackFeedbackID,trackFeedbackRatingID) {
	new Ajax.Request('/ajax_actions.php?action=update_track_feedback_rating&track_feedback_id='+trackFeedbackID+'&track_feedback_rating_type_id='+trackFeedbackRatingID,{asynchronous: true});
	new Effect.Fade('comment_functions_'+trackFeedbackID,{duration: .3});
}

function deleteTrackFeedback(trackFeedbackID) {
	if(confirm('Are you sure you want to delete this comment?')) {
		new Ajax.Request('/ajax_actions.php?action=delete_track_feedback&track_feedback_id='+trackFeedbackID,{asynchronous: true});
		if($('track_feedback_'+trackFeedbackID)) {
			new Effect.Fade('track_feedback_'+trackFeedbackID,{duration: .3});
		}
	}
}

function expandAdvancedSearch(targetHeight) {
	var secondTarget = targetHeight + 75;
	new Effect.GrowTo('SearchWrapper', {height: targetHeight, duration: .3}); 
	new Effect.GrowTo('Header', {height: secondTarget, duration: .3}); 
	if($('HeaderInner')) {
		new Effect.GrowTo('HeaderInner', {height: secondTarget, duration: .3}); 
	}
	else {
		new Effect.GrowTo('HeaderInnerMinimal', {height: secondTarget, duration: .3}); 
	}
	new Effect.Appear('SearchAdv', {duration:.3}); 
	new Effect.Fade('SearchSimple', {duration: .3}); return false;
}

function contractAdvancedSearch(targetHeight) {
	new Effect.ShrinkBack('SearchWrapper', {height: targetHeight, duration: .3}); 
	new Effect.ShrinkBack('Header', {height: targetHeight, duration: .3}); 
	if($('HeaderInner')) {
		new Effect.ShrinkBack('HeaderInner', {height: targetHeight, duration: .3}); 
	}
	else {
		new Effect.ShrinkBack('HeaderInnerMinimal', {height: targetHeight, duration: .3}); 
	}
	new Effect.Fade('SearchAdv', {duration:.3}); 
	new Effect.Appear('SearchSimple', {duration: .3});
}

function getAudioPlayer(playerID) {
	movieName = 'player_'+playerID;
	if (navigator.appName.indexOf("Microsoft") != -1) {
	  if(window[movieName]) {
			return window[movieName];
	  }
	} else {
		if(document[movieName]) {
	  	return document[movieName];
		}
	}
	return false;
}

function stopAllPlayers(currentPlayerID) {
	$$('object').each(function (element) {
		if(AudioPlayer.getPlayer(element.identify()) && element.identify() != "chart" && element.identify() != currentPlayerID) {
			AudioPlayer.close(element.identify());
		}
	});

}

function loadPlayer(playerID,playerURLs,randomNumber,titles,artists) {

	$$('object').each(function (element) {
		if(AudioPlayer.getPlayer(element.identify()) && element.identify() != "chart" && element.identify() != 'player_'+playerID) {
			AudioPlayer.close(element.identify());
		}
	});
	logPlay(playerURLs);
	AudioPlayer.embed('player_'+playerID, {
		soundFile: playerURLs,
		autostart: 'yes',
		titles: titles,
		artists: artists
	});
	playerArray[playerCounter] = playerID;
	playerCounter++;
	/*$('player_'+trackID).style.display='block';
	
	$('player_launcher_'+trackID).style.display='none';*/
	
}

var currentAccordian = '';

function toggleAccordian(accordianID) {
	if(accordianID != currentAccordian) {
		if($(accordianID).style.display == 'none') {
			$(currentAccordian).style.display = 'none';
			$(accordianID).style.display = 'block';
			$(accordianID+"_link").className = "tabberactive";
			$(currentAccordian+"_link").className = "";
			new Ajax.Request("/ajax_actions.php?action=update_accordian&accordian_value="+accordianID);
			currentAccordian = accordianID;
		}
	}
}

var currentTabber = '';

function switchTabber(tabberID) {
	playerID = 0;
	for(i = 0; i < playerArray.length; i++) {
		if(playerArray[i] && getAudioPlayer(playerArray[i])) {
			if(playerArray[i] != playerID) {
				try {
					getAudioPlayer(playerArray[i]).SetVariable('closePlayer',1);
					getAudioPlayer(playerArray[i]).SetVariable('autostart',0);
				}
				catch (error) {

				}
			}
			else {
				getAudioPlayer(playerArray[i]).SetVariable('closePlayer',0);
			}
		}
	}

	if(tabberID != currentTabber) {
		if($(tabberID).style.display == 'none') {
			if(currentTabber) {
				$(currentTabber).style.display = 'none';
			}
			$(tabberID).style.display = 'block';
			$(tabberID+"_link").className = "tabberactive";
			if(currentTabber) {
				$(currentTabber+"_link").className = "";
			}
			currentTabber = tabberID;
		}
	}
}

function unlockAccordian(accordianID) {
	accordianLock[accordianID] = false;
}

function rsvpSubmit(eventID) {
   var firstName = $('first_name_'+eventID);
   var lastName = $('last_name_'+eventID);
   var emailAddress = $('email_'+eventID);
   var firstNameLabel = $('label_first_name_'+eventID);
   var lastNameLabel = $('label_last_name_'+eventID);
   var emailLabel = $('label_email_'+eventID);
   hasError = false;
   if(!firstName.value) {
      firstNameLabel.className = "Error";
      hasError = true;
   }

   if(!lastName.value) {
      lastNameLabel.className = "Error";
      hasError = true;
   }

   if(!emailAddress.value) {
      emailLabel.className = "Error";
      hasError = true;
   }

   if(hasError) {
      return false;
   }

   new Ajax.Request('/ajax_actions.php?action=rsvp&event_id='+eventID+'&first_name='+URLEncode(firstName.value)+'&last_name='+URLEncode(lastName.value)+'&email_address='+URLEncode(emailAddress.value),Object.extend({ asynchronous:true, method: 'post'   }));
   new Effect.Fade('form_'+eventID);
   new Effect.Appear("thanks_"+eventID);
}

function updateEmailFeedback(checked) {
	var doEmail = "0";
	if(checked) {
		new Effect.Appear('frequency',{duration: .3});
		doEmail = "1";
	}
	else {
		new Effect.Fade('frequency',{duration: .3});
	}
	new Ajax.Request('/ajax_actions.php?action=update_email_feedback&do_email_feedback='+doEmail,Object.extend({ asynchronous:true, method: 'post' }));
	
}

function updateEmailFrequency(emailFrequencyID) {
	new Ajax.Updater('ef_disp','/ajax_actions.php?action=update_email_frequency&email_frequency_id='+emailFrequencyID,Object.extend({ asynchronous:true, method: 'post' }));
	$('ef_edit').style.display = 'none';
	$('ef_disp').style.display = '';
}
function changeClass(id,newClass){
	targetElement = $(id);
	if(targetElement) {
		targetElement.className = newClass;
	}
}
function updateAutoComplete(textElement,li) {
	textElement.value = li.id;
}

function updateOrderAutocomplete(textElement,li) {
	textElement.value = li.id;
	new Effect.BlindDown('order_details',{duration: .3});
}
function checkAllByIDRange(base,start,finish,checkedValue) {
	for(i=start;i<=finish;i++) {
	
		elementName = base+i;
		if(i == 1) {
		}	
		toCheck = $(elementName);
		if(toCheck) {
			if(i == 1) {
			}		
			checktoggle(toCheck);
		}
	}
}

function updateProviderDateRange() {
	providerID = $('provider_id').value;
	new Ajax.Request('/ajax_actions.php?action=get_payday_hash&provider_id='+URLEncode(providerID),
		{
			onSuccess: function (response) {
				var optionArray = new Array();
				var providerSelect = $('date_range');
				optionArray[0] = new Option('--- All Time ---','1');
				optionArray[1] = new Option('--- Custom Range ---','2');
				var paydayArray = response.responseText.split("|");
				
				for(i = 0; i < paydayArray.length; i++) {
					var paydayInfoArray = paydayArray[i].split("###");
					var j = i+2;
					optionArray[j] = new Option(paydayInfoArray[0],'payday_'+paydayInfoArray[1]);
				}
				providerSelect.options.length = 0;
				for(i = 0; i <= optionArray.length; i++) {
					
					providerSelect.options[i] = optionArray[i];
				}
			}
		});
}

function toggleCheckboxesByIdAndMax(id,max,checked) {
	var checkElement;
	if(checked) {
		doCheck = false;
	}
	else {
		doCheck = true;
	}
	for(i=0;i<=max;i++) {
		checkElement = $(id+i);
		if(checkElement) {
			checkElement.checked = true;
		}
	}
}

function changePassword() {
	var currentPassword = $('current_password');
	var newPassword = $('new_password');
	var newPasswordConfirm = $('new_password_confirm');
	var hasError = false;
	if(currentPassword.value == '') {
		$('old_label').className = "Error";
		hasError = true;
	}
	
	if(newPassword.value == ''){ 
		$('new_label').className = "Error";
		hasError = true;
	}
	else if(newPasswordConfirm.value == '') {
		$('new_label_confirm').className = "Error";
		hasError = true;
	}
	else if(newPassword.value != newPasswordConfirm.value) {
		$('new_label').className = "Error";
		$('new_label_confirm').className = "Error";
		hasError = true;
	}
	
	if(hasError) {
		return false;
	}
	else {
		new Ajax.Updater( 'password_note', '/ajax_actions.php?action=change_password',
		{	method: 'post',
			parameters: 'current_password='+currentPassword.value+'&new_password='+newPassword.value,
			asynchronous: true
		} );
		new Effect.Fade('editPassword');
		new Effect.Appear("UserAboutPassword");
		new Effect.Appear("password_note");
	}
}

function displayFadingError() {
	new Effect.toggle('ErrorMessage','appear', {duration: .05}); 
	new Effect.Highlight('ErrorMessage', {startcolor:'#FF3333', endcolor:'#993333', restorecolor:'#993333', duration: 3,keepBackgroundImage: true}); 
}

function displayFadingInfo() {
	new Effect.toggle('InfoMessage','appear', {duration: .05}); 
	new Effect.Highlight('InfoMessage', {startcolor:'#f8b92e', endcolor:'#fce193', restorecolor:'#fce193', duration: 3, keepBackgroundImage: true});
}

function textViewSaveTrack(trackID) {
	$('InfoMessage').style.display = 'none';
	new Ajax.Updater('InfoMessageContent','/ajax_actions.php?action=save_track_text&track_id='+trackID);
	displayFadingInfo();
}

function updatePromoTotals()
{
	var pricePerPack = new Array();
	pricePerPack[10] = 10.0;
	pricePerPack[100] = 90.0;
	pricePerPack[1000] = 850.0;
	pricePerPack[10000] = 8000.0;
	
	var quantityArray = new Array();
	quantityArray[0] = 10;
	quantityArray[1] = 100;
	quantityArray[2] = 1000;
	quantityArray[3] = 10000;
	
	var promoTotal = 0;
	var promoPriceTotal = 0;
	var rowPrice = 0;
	
	for(i = 0; i < quantityArray.length; i++) {
		quantity = quantityArray[i];
		origQuantity = quantity;
		price = pricePerPack[origQuantity];
		quantitySelected = $('promo_'+quantity).value;
		quantity = quantity * quantitySelected;
		rowPrice = price * quantitySelected;
		$('PromoTotal'+origQuantity).innerHTML = '$'+rowPrice+'.00';
		promoTotal += quantity;
		promoPriceTotal += rowPrice;
	}
	
	$('totalPromos').innerHTML = promoTotal;
	$('grandTotalPromosCost').innerHTML = '$'+promoPriceTotal+'.00';
}
function URLEncode(valueToEncode)
{
	// The Javascript escape and unescape functions do not correspond
	// with what browsers actually do...
	var SAFECHARS = "0123456789" +					// Numeric
					"ABCDEFGHIJKLMNOPQRSTUVWXYZ" +	// Alphabetic
					"abcdefghijklmnopqrstuvwxyz" +
					"-_.!~*'()";					// RFC2396 Mark characters
	var HEX = "0123456789ABCDEF";

	var plaintext = valueToEncode;
	var encoded = "";
	for (var i = 0; i < plaintext.length; i++ ) {
		var ch = plaintext.charAt(i);
	    if (ch == " ") {
		    encoded += "+";				// x-www-urlencoded, rather than %20
		} else if (SAFECHARS.indexOf(ch) != -1) {
		    encoded += ch;
		} else {
		    var charCode = ch.charCodeAt(0);
			if (charCode > 255) {

				encoded += "+";
			} else {
				encoded += "%";
				encoded += HEX.charAt((charCode >> 4) & 0xF);
				encoded += HEX.charAt(charCode & 0xF);
			}
		}
	} // for
	return encoded;
}

/* hide the state display when your country isn't "US" */

function checkCountryForStateDisplay(country) {
	var stateDiv = $('state_div');
	if(stateDiv) {
		if(country != "United States") {
			stateDiv.style.display = "none";
		}
		else {
			stateDiv.style.display = '';
		}
	}
}

/*
	I can't get Ajax.InPlaceCheckboxEditor to work, and it's not part of the scriptalcous lib, 
	so theres zero documentation out there for it.  This is my solution.
*/

function resetTrackFeedback(trackID,idPrefix) {
	var tagList = $(idPrefix+'tag_list'+trackID);
	var comments = $(idPrefix+'feedback'+trackID);
	var rating = $(idPrefix+'trackRating'+trackID);
	var ratingError = $(idPrefix+'rating_error'+trackID);
	var feedbackError = $(idPrefix+'feedback_error'+trackID);
	var initialTagList = $(idPrefix+'initial_tag_list'+trackID);
	var initialComments = $(idPrefix+'initial_comments'+trackID);
	var initialRating = $(idPrefix+'initial_rating'+trackID);
	if(idPrefix == "Player") {
		togglePlayerRating(trackID);
	}
	else {
		Effect.toggle(idPrefix+'TrackFeedback'+trackID, 'blind', {duration: .3}); 
	}

	ratingError.innerHTML = '';
	feedbackError.innerHTML = '';
	tagList.value = initialTagList.value;
	comments.value = initialComments.value;
	setTrackRating(trackID,initialRating.value,idPrefix);
}



function updateTrackFeedback(trackID,idPrefix) {
	var tagList = $(idPrefix+'tag_list'+trackID);
	var tagError = $(idPrefix+'tag_error_'+trackID);
	var comments = $(idPrefix+'feedback'+trackID);
	var rating = $(idPrefix+'trackRating'+trackID);
	var ratingError = $(idPrefix+'rating_error'+trackID);
	var feedbackError = $(idPrefix+'feedback_error'+trackID);
	var requiresFeedback = $(idPrefix+'requiresFeedback'+trackID);
	var hasError = false;

	tagError.innerHTML = '';
	feedbackError.innerHTML = '';
	ratingError.innerHTML = '';
	
	if(!rating.value) {
		ratingError.innerHTML = "You must rate this song.";
		hasError = true;
	}

	if(!comments.value) {
		feedbackError.innerHTML = "You must leave your comments on this song.";
		hasError = true;
	}
	
	if(!tagList.value) {
		tagError.innerHTML = "You must tag this song.";
		hasError = true;
	}
	
	if(hasError) {
		return false;
	}

	new Ajax.Request('/ajax_actions.php?action=update_track_tags&track_id='+trackID, Object.extend({
		parameters: 'value=' +URLEncode( tagList.value) ,
		asynchronous:true,
		onComplete: function () {
			new Ajax.Request('/ajax_actions.php?action=update_feedback&track_id='+trackID, Object.extend({
				parameters: 'value=' + URLEncode(comments.value) ,
				asynchronous:true,
				onComplete: function () {
					new Ajax.Request('/ajax_actions.php?action=update_track_rating&track_id='+trackID, Object.extend({
						parameters: 'value=' +URLEncode(rating.value) ,
						asynchronous:true,
						onComplete: function () {
							if(idPrefix == 'Player') {
								togglePlayerRating(trackID);
							}
							else {
								Effect.toggle(idPrefix+'TrackFeedback'+trackID, 'blind', {duration: .3}); 	
							}
							if(requiresFeedback) {
								requiresFeedback.innerHTML = ' <a href="#" onclick="addTrackToCrate('+trackID+',\'buyLink'+trackID+'\'); setTimeout(\'downloadPromo('+trackID+')\',1000);return false;" id="buyLink'+trackID+'Link" class="BtnBuy" title="Download this promo song for 1 promo point."><span>DOWNLOAD 1 PT</span></a>';
							}
						},
						method: 'post'	}));		
				},
				method: 'post'	}));
			
		},
		method: 'post'	}));
}



function rsvpSubmit(eventID) {
	var firstName = $('first_name_'+eventID);
	var lastName = $('last_name_'+eventID);
	var emailAddress = $('email_'+eventID);
	var firstNameLabel = $('label_first_name_'+eventID);
	var lastNameLabel = $('label_last_name_'+eventID);
	var emailLabel = $('label_email_'+eventID);
	hasError = false;
	if(!firstName.value) {
		firstNameLabel.className = "Error";
		hasError = true;
	}
	
	if(!lastName.value) {
		lastNameLabel.className = "Error";
		hasError = true;
	}
	
	if(!emailAddress.value) {
		emailLabel.className = "Error";
		hasError = true;
	}
	
	if(hasError) {
		return false;
	}
	
	new Ajax.Request('/ajax_actions.php?action=rsvp&event_id='+eventID+'&first_name='+URLEncode(firstName.value)+'&last_name='+URLEncode(lastName.value)+'&email_address='+URLEncode(emailAddress.value),Object.extend({ asynchronous:true, method: 'post'	}));
	new Effect.Fade('form_'+eventID);
	new Effect.Appear("thanks_"+eventID);
}

function logPlay(trackURL) {
	new Ajax.Request('/ajax_actions.php?action=log_play&trackURL='+trackURL, Object.extend({ asynchronous:true, method: 'post'	}));
}

function updateDjType(id) {
	var djTypeElement = $(id);
	var djTypeID = djTypeElement.value;
	var isChecked = djTypeElement.checked;
	var value = 0;
	if(isChecked) {	
		value = 1;
	}
	var updateURL = 'EditUserDetails.php?id='+userID+'&field=dj_type_id&type='+djTypeID;
	new Ajax.Request( updateURL, Object.extend({
         parameters: 'value=' + value ,
         asynchronous:true,
			method: 'post'	}));
}

function updateRequiresFeedback(trackID,requireFeedback) {
	if(requireFeedback) {
		value = '1';
	}
	else {
		value = '0';
	}
	var updateURL = '/ajax_actions.php?track_id='+trackID+'&action=do_require_feedback';
	new Ajax.Request( updateURL, Object.extend({
			parameters: 'value=' + value ,
			asynchronous: true,
			method: 'post' }));
}

function updateRequiresPromoPoint(trackID,requireFeedback) {
	if(requireFeedback) {
		value = '1';
	}
	else {
		value = '0';
	}
	var updateURL = '/ajax_actions.php?action=do_require_promo_point&track_id='+trackID;
	new Ajax.Request( updateURL, Object.extend({
			parameters: 'value=' + value ,
			asynchronous: true,
			method: 'post' }));
}


function createPromoterApp(id,userID) {
	var promoterElement = $(id);
	var contentSourceID = promoterElement.value;
	var providerBox = $('provider_box');
	
	var updateURL = 'EditUserDetails.php?id='+userID+'&field=promoter_app';
	new Ajax.Request( updateURL, Object.extend({
         parameters: 'value=' + contentSourceID ,
         asynchronous:true,
			method: 'post'	}));
			
	providerBox.innerHTML = 'Your application is pending.  We will notify you after we have reviewed it.';
}
function createProviderApp(id,userID) {
	var providerElement = $(id);
	if(providerElement) {
		var contentSourceID = providerElement.value;
		if(contentSourceID) {
			var providerBox = $('provider_box');
			var updateURL = 'EditUserDetails.php?id='+userID+'&field=provider_app';
			new Ajax.Request( updateURL, Object.extend({
		         parameters: 'value=' + contentSourceID ,
		         asynchronous:true,
					method: 'post'	}));
			
			providerBox.innerHTML = 'Your application is pending.  We will notify you after we have reviewed it.';
		}
	}
}

function doCheck(toCheck) {
	if($(toCheck)) {
		$(toCheck).checked = true;	
	}
}

function promProvCheckUpdate(elementToCheck) {
	var provBox = $('UsersAdvpendingArtist');
	var promoBox = $('UsersAdvpendingPromoter');
	
	if(elementToCheck == 'provider') {
		provBox.checked = true;
		doUncheckAdvSearchBoxes('promoter');	
	}
	else if (elementToCheck == 'promoter') {
		promoBox.checked = true;
		doUncheckAdvSearchBoxes('provider');
	}
}

function switchPromProv(type) {
	var idArray = new Array();
	idArray['promoter'] = new Array('UsersAdvpendingPromoter','UsersAdvPromoterLabel','UsersAdvPromoterCompany','UsersAdvPromoterIndiv');
	idArray['provider'] = new Array('UsersAdvpendingArtist','UsersAdvProviderLabel','UsersAdvProviderDistr','UsersAdvProviderArtist','UsersAdvProviderProducer');
	var proElement;
	if(type == "promoter") {
		proElement = $('UsersAdvpendingPromoter');
	}
	else {
		proElement = $('UsersAdvpendingArtist');	
	}
	
	for(i=0;i<idArray[type].length;i++) {
		$(idArray[type][i]).checked = proElement.checked;	
	}
}


function toggleDJ() {
	var idArray = new Array();
	idArray['dj'] = new Array('UsersAdvDj','UsersAdvRadioCollege','UsersAdvRadioCommercial','UsersAdvRadioSatellite','UsersAdvRadioInternet',
						'UsersAdvDJTypeClubSmall','UsersAdvDJTypeClubMedium','UsersAdvDJTypeClubLarge','UsersAdvDJTypeMixCD','UsersAdvDJTypeTurntablist',
						'UsersAdvDJTypeMobile','UsersAdvDJTypePerformance','UsersAdvDJTypeOther','UsersAdvRadioCollege','UsersAdvRadioCommercial','UsersAdvRadioSatellite','UsersAdvRadioInternet',
						'UsersAdvDJTypeClubSmall','UsersAdvDJTypeClubMedium','UsersAdvDJTypeClubLarge');
	var proElement = $('UsersAdvDj');
	
	for(i=0;i<idArray['dj'].length;i++) {
		$(idArray['dj'][i]).checked = proElement.checked;	
	}
	
}
function doUncheckAdvSearchBoxes(type) {
	var idArray = new Array();
	idArray['promoter'] = new Array('UsersAdvpendingPromoter','UsersAdvPromoterLabel','UsersAdvPromoterCompany','UsersAdvPromoterIndiv');
	idArray['provider'] = new Array('UsersAdvpendingArtist','UsersAdvProviderLabel','UsersAdvProviderDistr','UsersAdvProviderArtist','UsersAdvProviderProducer');
	
	for(i=0;i<idArray[type].length;i++) {
		$(idArray[type][i]).checked = false;	
	}
}



var djChecked = 0;
var providerChecked = 0;
var promoterChecked = 0;



function properFade(checkedID) {
	checkedElement = $(checkedID);
	var didFade = false;
	
	var uncheckList = new Array();
	if(checkedElement) {
		switch(checkedID) {		
			case "Enthusiast":
				Effect.Fade('DjType', {duration: .3}); 
				didFade = true;
				uncheckList[0] = 'Dj';
				djChecked = 0;
				break;
			
			case "Dj":
				if(!djChecked) {
					Effect.BlindDown('DjType', {duration: .3});
					didFade = true;
					uncheckList[0] = "Enthusiast";
					djChecked = 1;
				}
				break;
			
			case "UserAboutDJTypeRadio":
				Effect.toggle('TypeRadio', 'blind', {duration: .3}); 
				Effect.toggle('RadioVerify', 'appear', {duration: .3});
				break;
			
			case "RadioCollege":
			case "RadioCommercial":
			case "RadioSatellite":
			case "RadioInternet":
				fadeRadio(checkedID);
				break;
			
			case "pendingArtist":
				if(providerChecked == 0) {
					Effect.BlindDown("ProviderType",{duration:.3});
					uncheckList[0] = "pendingPromoter";
					Effect.Fade("PromoterType",{duration:.3});
					providerChecked = 1;
					promoterChecked = 0;
				}
				break;
				
			case "pendingPromoter":
				if(promoterChecked == 0) {
					
					Effect.BlindDown("PromoterType",{duration:.3});
					uncheckList[0] = "pendingArtist";
					Effect.Fade("ProviderType",{duration:.3});
					promoterChecked = 1;
					providerChecked = 0;
				}
				break;
				
				
			
		}
	}
	
	for(i=0;i<=uncheckList.length;i++) {
		var uncheck = uncheckList[i];
		var uncheckElement = $(uncheck);
		if(uncheckElement) {	
		//	Effect.Fade(uncheck, {duration: .3});
			uncheckElement.checked = false;	
		}
	}
}

var currentRadioChecked = '';

function fadeRadio(currentElement) {
	var radioTypes = new Array(4);
	radioTypes[0] = "RadioCollegeDetails";
	radioTypes[1] = "RadioCommercialDetails";
	radioTypes[2] = "RadioSatelliteDetails";
	radioTypes[3] = "RadioInternetDetails";
	
	for(i=0;i<=radioTypes.length;i++) {
		var currentType = $(radioTypes[i]);
		if(currentType) {	
			if(currentType.id == currentElement+"Details" && currentRadioChecked != currentElement) {	
				Effect.BlindDown(currentType.id);	
				currentRadioChecked = currentElement;
			}
			else if(currentType.id != currentElement+"Details") {
				Effect.Fade(currentType.id,{duration:.3});
				var uid = currentType.id;
				var uncheckedId = uid.replace(/Details/,'');
				var boxToUncheck = $(uncheckedId);
				if(boxToUncheck) {
					boxToUncheck.checked = false;	
				}
			}
		}
	}
}




  function findPosX(obj)
  {
    var curleft = 0;
    if(obj.offsetParent)
        while(1) 
        {
          curleft += obj.offsetLeft;
          if(!obj.offsetParent)
            break;
          obj = obj.offsetParent;
        }
    else if(obj.x)
        curleft += obj.x;
    return curleft;
  }

  function findPosY(obj)
  {
    var curtop = 0;
    if(obj.offsetParent)
        while(1)
        {
          curtop += obj.offsetTop;
          if(!obj.offsetParent)
            break;
          obj = obj.offsetParent;
        }
    else if(obj.y)
        curtop += obj.y;
    return curtop;
  }

  function opacity(id, opacStart, opacEnd, millisec) {
      var speed = Math.round(millisec / 100);
      var timer = 0;

      if(opacStart > opacEnd) {
			for(i = opacStart; i >= opacEnd; i--) {
            setTimeout("changeOpac(" + i + ",'" + id + "')",(timer * speed));
            timer++;
         }
		}
		else if(opacStart < opacEnd) {
			for(i = opacStart; i <= opacEnd; i++) {
				setTimeout("changeOpac(" + i + ",'" + id + "')",(timer * speed));
				timer++;
         }
      }
   }

//change the opacity for different browsers
   function changeOpac(opacity, id) {
		var object = $(id).style;
		object.opacity = (opacity / 100);
		object.MozOpacity = (opacity / 100);
		object.KhtmlOpacity = (opacity / 100);
		object.filter = "alpha(opacity=" + opacity + ")";
   }



function checktoggle( checkBox )
{	// First, figure out which row we need to decorate by climbing the DOM.
	var elementToDecorate = checkBox;
	while ( elementToDecorate.tagName.toUpperCase() != 'TR' )
		elementToDecorate = elementToDecorate.parentNode;

	// Then figure out which class to use.
	if ( checkBox.checked )
	{	elementToDecorate.oldClassName = elementToDecorate.className;
		elementToDecorate.className = 'ContentTableRowOn';
	}
	else
	{
		elementToDecorate.className = elementToDecorate.oldClassName;
	}
}


function addContact(userID,targetID) {
	new Ajax.Updater(targetID,'/ajax_actions.php?action=add_contact&user_id='+userID);
	new Effect.Pulsate(targetID);
}


function buyAlbum(albumID,buyLinkID) {
	if(!buyLinkID || buyLinkID == '') {
		buyLinkID = 'buyLink';
	}
	var currentCSSClass = $(buyLinkID+'Link').className;
	new Ajax.Updater(buyLinkID,'/ajax_actions.php?action=add_album_to_checkout_crate&album_id='+albumID+'&css_class='+currentCSSClass);
	new Effect.Pulsate(buyLinkID);
}

function downloadPromo(trackID) {
	new Ajax.Request('/ajax_actions.php?action=can_download&track_id='+trackID,{
			onComplete: function (response) {
				if(response.responseText == 'true') {
					window.location = "/mp3s/"+trackID+".mp3";				
				}
			}
		}
	)
}

function downloadPromoAlbum(albumID) {
	window.location = "/md.php?album_id="+albumID;
}

function addTrackToCrateFromText(trackID) {
	$('InfoMessage').style.display = "none";
	new Ajax.Updater('InfoMessageContent','/ajax_actions.php?action=add_track_to_checkout_crate_text&track_id='+trackID);
	displayFadingInfo();
}

function addAlbumToCrateFromText(albumID) {
	$('InfoMessage').style.display = "none";
	new Ajax.Updater('InfoMessageContent','/ajax_actions.php?action=add_album_to_checkout_crate_text&album_id='+albumID);
	displayFadingInfo();
}

function saveAlbumFromText(albumID) {
	$('InfoMessage').style.display = "none";
	new Ajax.Updater('InfoMessageContent','/ajax_actions.php?action=save_album_from_text&album_id='+albumID);
	displayFadingInfo();
}
function addTrackToCrate(trackID,buyLinkID) {
	if(!buyLinkID) {
		buyLinkID = 'buyLink';
	}
	var currentCSSClass = $(buyLinkID+'Link').className;
	new Ajax.Updater(buyLinkID,'/ajax_actions.php?action=add_track_to_checkout_crate&track_id='+trackID+'&css_class='+currentCSSClass);
	setTimeout('pulsateBuyLink("'+buyLinkID+'")',1000);
	
}

function pulsateBuyLink(buyLinkID) {
	new Effect.Pulsate(buyLinkID);	
}

function promoAlbum(trackList,buyLinkID) {
	var trackID;
	if(!buyLinkID) {
		buyLinkID = 'link_wrapper';
	}
	for(x=0;x<=trackList.length;x++) {	
		trackID = trackList[x];
		new Ajax.Request('/Music/PromoTrack.php?id='+trackID);
		new Effect.Pulsate(buyLinkID);
	}
}

loadCrate = function( crateIndex, doSaveSelected, doRemoveFromBuy, doRemoveFromSaved, doBuyFromSaved )
{	
	switch(crateIndex) {
		case 0:
			crateURL = '/Crates/checkout.html';
			break;
		case 1:
			crateURL = '/Crates/saved.html';
			break;
		
		case 2:
			crateURL = '/Crates/purchased.html';
			break;
	
	}
	
	window.location = crateURL;
};


// Image root that gets prepended to all images.
var swImageRoot = '/images/'

//	Defines the possible main navigation sections.
//		[0]: string to look for in the URL to identify we're in a section.
//		[1]: ID of the image that we should manipulate the src of, or null if none should be highlighted.
NAV_MAP = 
	[ 
		[ 'mode=register', null,                ],
		[ '/Forums/',      'HeaderForums',		],
		[ '/Articles/',        'HeaderArticles',	],
		[ '/Music/',       'HeaderMusic',		],
		[ '/Users/',       'HeaderUsers',		],
		[ '/Charts/',      'HeaderCharts',		],
		[ '/About/',       'HeaderAbout',		]
	];

// Call this right after displaying the main navigation to highlight the right image.
function fixNavImages()
{	
	// Search for each URL piece in the document location.
	var foundIt = 0;
	for ( var navIndex=0; navIndex<NAV_MAP.length; navIndex++ )
	{	var stringAndName = NAV_MAP[navIndex];
		// If this is the first match, set the image (unless it's a null).
		if ( (!foundIt) && document.location.pathname.split( stringAndName[0] ).length > 1 )
		{	if ( stringAndName[1] != null ) fixImages( stringAndName[1] );
			foundIt = 1;
		}
	}

	// Fall back on the home tab if all else fails.
	if (!foundIt) fixImages( 'HeaderHome', 'HeaderHomeActive.gif' );
}

//	Causes all images to go inactive except the specified one.
//	Inactive Images use src=Name+'Inactive.gif', e.g. HeaderForums -> HeaderForumsInactive.gif
//	Active Images use src=Name+'Active.gif', e.g. HeaderForums -> HeaderForumsActive.gif
function fixImages( activeName )
{
	NAV_MAP.each( function( stringAndName )
	{	if ( stringAndName[1] ) 
			fixImage( stringAndName[1], stringAndName[1] + 'Inactive.gif');
	} );
	fixImage( activeName, activeName + 'Active.gif' );
}

// Swap Image Script
function fixImage(imageName, imageSrc)
{
    thisImage = top.document.images[imageName];
	if ( !thisImage ) thisImage = document.images[imageName];
	if ( !thisImage ) alert( 'invalid image name "' + imageName + '" specified' );
	else thisImage.src = swImageRoot + imageSrc;
}

// Gets called by forums and articles to patch stuff up.
//	getIdFromIndex: should convert a category index into a link ID to highlight.
//	getIndexFromLocation: should return an index from document href, or null if not possible.
//	qualifyLinkAsPointer: given a URL found in a link, determine if it might have the index in it.
//	getIndexFromLink: convert a qualified URL into an index, or null if not possible.
//	cookieName: a unique name for storing previous state, for last resort fallback.
//	finalFallbackIndex: index to use if all else fails.
function highlightSecondNav( 
	getIdFromIndex, 
	getIndexFromLocation,
	qualifyLinkAsPointer,
	getIndexFromLink,
	cookieName,
	finalFallbackIndex )
{
	// We'll try several means of populating this.
	var selArticleLink = 0;

	// First see if we can't parse it right out of the URL.
	var locationIndex = getIndexFromLocation( document.location.href );
	if ( locationIndex != null )
		selArticleLink = $( getIdFromIndex( locationIndex ) );

	// Then see if we can't find a link in the document.
	if ( !selArticleLink )
	{	var postingLinks = $$( 'li' ).findAll( qualifyLinkAsPointer );
		var selArticleNums = postingLinks.collect( getIndexFromLink ).compact();
		if ( selArticleNums.length )
			selArticleLink = $( getIdFromIndex( selArticleNums[0] ) );
	}

	// The next is seeing if we have a cookie for that, yo.
	if ( !selArticleLink )
	{
		var cookieString = '' + document.cookie;
		var index1 = cookieString.indexOf( cookieName )
		if ( index1!=-1 )
		{
			// Yep.  Grab its value.
			var index2 = cookieString.indexOf( ';', index1 );
			index2 = ( index2 == -1 ? cookieString.length : index2 );
			var persistedState = cookieString.substring( index1 + cookieName.length + 1, index2 );
			selArticleLink = $( unescape( persistedState ) );
		}
	}

	// Lastly, fall back on the index they specify, but still be safe!
	if ( !selArticleLink ) 
		selArticleLink = $( getIdFromIndex( finalFallbackIndex ) )
	if ( selArticleLink ) 
	{	selArticleLink.className = 'current_sub';
		document.cookie = cookieName + '=' + escape( '' + selArticleLink.id );
	}
}

function file_name_only(str) 
{
	var slash = '/'
	if (str.match(/\\/)) slash = '\\'
	return str.substring(str.lastIndexOf(slash) + 1, str.lastIndexOf('.'))
}

// Handles the alternating row colors for divs in a list

function alternateListRowColors()
{
	$$( '.ListRowSet' ).each( 
		function(listRowSet) 
		{	
			var listRows = listRowSet.select('.ListRow');
			for(x = 0; x < listRows.length; x++) {
				if(x % 2 == 0) {
					className = "ListRow";
				}
				else {
					className = "ListRowOdd";
				}
				listRows[x].className = className;
			}
			
			/*
				var listRows = 
					$A( lrs.childNodes ).findAll( 
						function(cn) { return cn.className && Element.hasClassName( cn, 'ListRow' ); } );
				for ( var i=1; i<listRows.length; i+=2 )
					listRows[i].className = 'ListRowOdd';
			*/
		} );
}
// Causes the login panel(s) to update based on current state.

function loadLoginWrapper()
{
	// Figure out the complete URL to the loginwrapper.
	var loginPanelUrl = '/SsiLoginRight.php';
	var sidPieces = ( '' + document.location ).split( 'sid=' );
	if ( sidPieces.length > 1 )
		loginPanelUrl = loginPanelUrl + '?sid=' + sidPieces[1].split( '&' )[0];

	getUrlIntoDiv( loginPanelUrl, 'loginWrapperRight', 
		new Array( 
			function()
			{	
				if ( ( '' + document.location ).indexOf('checkoutcrate=') != -1 ) 
				{	loadCrate(0);
				}
				else if ( ( '' + document.location ).indexOf('savedcrate=') != -1 ) 
				{	loadCrate(1);
				}
				else if ( ( '' + document.location ).indexOf('purchasedcrate=') != -1 ) 
				{	loadCrate(2);
				}
			},
			function()
			{   var redirInput = $('redirectToInput');
				if ( redirInput ) redirInput.value = document.location;
			} ) );
}


function setTrackRating(trackId,trackRating,idPrefix) {
	$(idPrefix+'trackRating'+trackId).value = trackRating;
	$(idPrefix+'userRating'+trackId+'Display').style.width = (trackRating * 20) + 'px';
}

function checkAllBoxes(formID,currentBox) {
   var formElement = $(formID);
   var checkboxElements = formElement.getElementsByTagName('input');
   for(i = 0; i< checkboxElements.length; i++) {
      if(checkboxElements[i].getAttribute('type') == "checkbox" && checkboxElements[i].getAttribute('name') != currentBox.name) {
         checkboxElements[i].checked = currentBox.checked;
         checkboxElements[i].onclick();
      }
   }
}

function highlightTableText(searchString) {
	
}

function highlightSearchText(searchString) {
	var resultList = $$('div.result_info');
	for(var x = 0; x < resultList.length; x++) {
		highlightText(resultList[x].identify(),searchString);
	}
}

function highlightText(highlightTextID,searchString) {
  // Get search string
	
	
	// Starting node, parent to all nodes you want to search
	var textContainerNode = $(highlightTextID);
	
	// Informational message for search
	
	// Split search terms on '|' and iterate over resulting array
	var searchTerms = searchString.split(' ');
	var searchInfo = '';
	for (i=0; i< searchTerms.length; i++) 	{
	  // The regex is the secret, it prevents text within tag declarations to be affected
		try {
		  	//var regex = new RegExp(">([^<]*)?("+searchTerms[i]+")([^>]*)?<","ig");
			if(searchTerms[i].length >= 3) {
				highlightTextNodes(textContainerNode, searchTerms[i]);
			}
			// Add to info-string
		}
		catch (error) {
			
		}
	 }
}

function highlightTextNodes(element, searchTerm) {
  highlightStartTag = '<span class="highlighted">';
  highlightEndTag = '</span>';
  var bodyText = element.innerHTML;
  var newText = "";
  var i = -1;
  var lcSearchTerm = searchTerm.toLowerCase();
  var lcBodyText = bodyText.toLowerCase();
   
  while (bodyText.length > 0) {
    i = lcBodyText.indexOf(lcSearchTerm, i+1);
    if (i < 0) {
      newText += bodyText;
      bodyText = "";
    } else {
      // skip anything inside an HTML tag
      if (bodyText.lastIndexOf(">", i) >= bodyText.lastIndexOf("<", i)) {
        // skip anything inside a <script> block
        if (lcBodyText.lastIndexOf("/script>", i) >= lcBodyText.lastIndexOf("<script", i)) {
          newText += bodyText.substring(0, i) + highlightStartTag + bodyText.substr(i, searchTerm.length) + highlightEndTag;
          bodyText = bodyText.substr(i + searchTerm.length);
          lcBodyText = bodyText.toLowerCase();
          i = -1;
        }
      }
    }
  }
  element.update(newText);
}


var Preloader = {
  callbacks: [],
  images: [],
  loadedImages: [],
  imagesLoaded: 0,

  add: function(image){
    if (typeof image == 'string') this.images.push(image);
    if (typeof image == 'array' || typeof image == 'object'){
      for (var i=0; i< image.length; i++){
        this.images.push(image[i]);
      }
    }
  },
  onFinish: function(func){
    if (typeof func == 'function') this.callbacks.push(func);
    if (typeof func == 'array' || typeof func == 'object'){
      for (var i=0; i< func.length; i++){
        this.callbacks.push(func[i]);
      }
    }
  },
  load: function(){
    for(var i=0; i<this.images.length; i++){
      this.loadedImages[i] = new Image();
      this.loadedImages[i].onload = function(){ Preloader.checkFinished.apply(Preloader) }
      this.loadedImages[i].src = this.images[i];
    }
  },

  checkFinished: function(){
    this.imagesLoaded++;
    if (this.imagesLoaded == this.images.length) this.fireFinish();
  },
  fireFinish: function(){
    for (var i=0; i<this.callbacks.length; i++){
      this.callbacks[i]();
    }
    this.images = [];
    this.loadedImages = [];
    this.imagesLoaded = 0;
    this.callbacks = [];
  }
}

var FeaturedCarousel = Class.create( {
	initialize: function(targetID,size) {
		this.stepCounter = 0;
		this.featuredImages = new Array();
		this.targetElement = $(targetID);
	},
	
	addFeaturedImage: function (featuredImageID,caption,link) {
		counter = this.featuredImages.length;
		this.featuredImages[counter] = $H({ featured_image_id: featuredImageID,caption: caption, link: link });
	}

});

var imageShifters = new Array();

var ImageShifter = Class.create({
	initialize: function(targetDivID,imageShifterID,prefix,autoPlay) {
		this.targetDivID = targetDivID;
		this.targetDiv = $(targetDivID);
		this.prefix = prefix;
		this.imageShifterID = imageShifterID;

		this.leftArrow = new Element('a',{className: 'left_arrow',title: 'View previous feature'});
		this.leftArrow.observe('click',this.moveBackward.bindAsEventListener(this));

		this.rightArrow = new Element('a',{className: 'right_arrow',title: 'View next feature'});
		this.rightArrow.observe('click',this.moveForward.bindAsEventListener(this));

		this.currentCounter = 0;
		imageShifters[imageShifterID] = this;
		this.autoPlay = true;
	},
	setWidth: function(width) {
		this.width = width;
	},
	setHeight: function(height) {
		this.height = height;
	},
	setNumElements: function(numElements) {
		this.numElements = numElements;
	},
	setCounter: function (counter) {
		this.currentCounter = counter;
	},
	render: function() {
		this.targetDiv.insert(this.leftArrow,{position: 'top'});
		this.targetDiv.insert(this.rightArrow,{position: 'bottom'});
		this.targetDiv.select('div').each(function (element) { element.style.position = 'absolute';});
/*		setInterval(function(thisObj) { thisObj.moveForward(1); },8000,this);*/
		setInterval(this.autoPlayMoveForward.bindAsEventListener(this),8000);
	},
	autoPlayMoveForward: function () {
		this.moveForward(1);	
	},
	moveForward: function(isAutoPlay) {
		if(isAutoPlay == 1) {
			if(!this.autoPlay) {
				return false;
			}
		}
		else {
			this.autoPlay = false;
		}
		if(!this.locked) {
			this.lock();
			
			if(this.currentCounter == (this.numElements - 1)) {
				/*
				new Effect.Move(this.containerDivId,{x: (this.width*(this.numElements-1)) ,method:'relative',duration: .3,afterFinish: this.unlock.bindAsEventListener(this)});
				this.currentCounter = 0;
				*/
				newCounter = 0;
			}
			else {
				/*new Effect.Move(this.containerDivId,{x: -this.width ,method:'relative',duration: .3,afterFinish: this.unlock.bindAsEventListener(this)});*/
				newCounter = this.currentCounter+1;
			}
			this.swapImages(this.currentCounter,newCounter);
			
		}
	},
	moveBackward: function() {
		this.autoPlay = false;
		if(!this.locked) {
		this.lock();
			if(this.currentCounter == 0) {
				/*new Effect.Move(this.containerDivId,{x: -(this.width*(this.numElements-1)) ,method:'relative',duration: .3,afterFinish: this.unlock.bindAsEventListener(this)});
				this.currentCounter = (this.numElements - 1);*/
				newCounter = this.numElements - 1;
			}
			else {
				/*new Effect.Move(this.containerDivId,{x: this.width ,method:'relative',duration: .3,afterFinish: this.unlock.bindAsEventListener(this)});
				this.currentCounter--;
				*/
				newCounter = this.currentCounter-1;
			}
			this.swapImages(this.currentCounter,newCounter);
		}
	},
	swapImages: function (oldKey,newKey) {
		$(this.prefix+oldKey).fade({duration: .3});
		$(this.prefix+newKey).appear({duration: .3, afterFinish: this.unlock.bindAsEventListener(this)});
		this.currentCounter = newKey;
	},
	lock: function() {
		this.locked = true;
	},

	unlock: function() {
		this.locked = false;
	}
});

tourCounter = 0;

function tourScroll(direction) {
	originalCounter = tourCounter;
	if(direction == 'left') {
		if(tourCounter == 0) {
			tourCounter = 3;
			movementAmount = -3*625;
		}
		else {
			tourCounter--;
			movementAmount = 625;
		}
	}
	else if (direction == "right") {
		if(tourCounter == 3) {
			tourCounter = 0;
			movementAmount = 3*625;
		}
		else {
			tourCounter++;
			movementAmount = -625;
		}
	}
	new Effect.Move($('tour_container'),{
			x: movementAmount,
			method:'relative',
			duration: .3,
			afterFinish: function () {
				$('tour_link_'+originalCounter).removeClassName('active');
				$('tour_link_'+tourCounter).addClassName('active');
			}
	});
	
}


function tourPosition(position) {
	if(tourCounter > position) {
		multiplier = tourCounter - position;
	}
	else if (tourCounter < position ) {
		multiplier = -1*(position - tourCounter);
	}
	else {
		multiplier = 0;
	}
	
	if(multiplier) {
		var movementAmount = multiplier * 625;
		new Effect.Move($('tour_container'),{x: movementAmount,duration: .3});
	}
	$('tour_link_'+tourCounter).removeClassName('active');
	$('tour_link_'+position).addClassName('active');
	tourCounter = position;
}

Event.observe(window,'load',function() { 
		$('loading').style.display = 'none';
		$('page_mainbody').style.display = 'block';
		
		gotoAnchor();

		var inputs = $$('input');
		for(i = 0; i < inputs.length;i++) {
			Event.observe(inputs[i],'keypress',function(event) {
					if(event.keyCode == 13) {
						event.findElement('form').submit();
					}
			});
		}
		if($('upcoming_image_0')) {
			setInterval('rotateUpcoming()',10000);
		}

		

		AudioPlayer.setup("/player/new_player.swf", 
			{
				width: 315,
			/*	noinfo: "yes",*/
				initialvolume: "60",
				transparentpagebg: "yes",
				bg: "2E2E2E",
				leftbg: "EEEEEE",
				lefticon: "666666",
				voltrack: "CCCCCC",
				volslider: "666666",
				rightbg: "CCCCCC",
				rightbghover: "999999",
				righticon: "666666",
				righticonhover: "F0F0F0",
				loader: "aeaeae",
				track: "2E2E2E",
				tracker: "badf57",
				border: "2E2E2E",
				skip: "CCCCCC",
				text: "F0F0F0",
				autostart: "yes"
			});
			(function(){
			  var bsa = document.createElement('script');
				  bsa.type = 'text/javascript';
				  bsa.async = true;
				  bsa.src = '//s3.buysellads.com/ac/bsa.js';
			  (document.getElementsByTagName('head')[0]||document.getElementsByTagName('body')[0]).appendChild(bsa);
			})();

	});
	
function gotoAnchor() {
	var anchorName = document.location.hash.substring(1);
	if(anchorName) {
		if($(anchorName)) {
			new Effect.ScrollTo(anchorName,{duration: .1});
		}
		else {
			new Effect.ScrollTo(document.getElementsByName(anchorName)[0].identify(),{duration: .1});
		}
	}
}

var activeAccordion = '';

function accordionToggle(accordionID) {
	if(activeAccordion) {
		oldHeader = $('accordion'+activeAccordion+'Header');
		oldContent = $('accordion'+activeAccordion+'Content');
		oldHeader.removeClassName('AccordionHeaderActive');
		oldHeader.addClassName('AccordionHeader');
		new Effect.BlindUp(oldContent,{duration: .15});
	}
	
	if(accordionID != activeAccordion) {
		
		header = $('accordion'+accordionID+'Header');
		content = $('accordion'+accordionID+'Content');
		
		header.removeClassName('AccordionHeader');
		header.addClassName('AccordionHeaderActive');
		new Effect.BlindDown(content,{duration: .15});
		activeAccordion = accordionID;
	}
	else {
		activeAccordion = '';
	}
	new Ajax.Request('/ajax_actions.php?action=right_accordion&value='+activeAccordion);
}

var activePromoPackage = '';
var packagePrices = new Array();

packagePrices['choiceA'] = '1080';
packagePrices['choiceB'] = '483';
packagePrices['choiceC'] = '166';
packagePrices['choiceD'] = '0';
packagePrices['choiceE'] = '0';

packagePrices['choice1'] = '150';
packagePrices['choice2'] = '100';
packagePrices['choice3'] = '50';
packagePrices['choice4'] = '300';


var hugeCost = 100;
var largeCost = 75;
var smallCost = 50;

var notificationCost = 5;
var statsCost = 5;
var emailCost = 20;
var songCost = 20;

var featureMatrix = new Array();
featureMatrix["choiceA"] = new Array();
featureMatrix["choiceA"]["huge"] = 2;
featureMatrix["choiceA"]["large"] = 2;
featureMatrix["choiceA"]["small"] = 2;

featureMatrix["choiceB"] = new Array();
featureMatrix["choiceB"]["huge"] = 1;
featureMatrix["choiceB"]["large"] = 1;
featureMatrix["choiceB"]["small"] = 1;

featureMatrix["choiceC"] = new Array();
featureMatrix["choiceC"]["huge"] = 0;
featureMatrix["choiceC"]["large"] = 0;
featureMatrix["choiceC"]["small"] = 1;


var activeInfo = '';

function promoTableHide(element) {
	element.removeClassName('on');
	if(!element.hasClassName('side')) {
		element.style.display = 'none';
	}
}

function promoTableShow(element) {
	element.addClassName('on');
	element.style.display = '';
}

function showPromoPackage(promoPackage) {
	var table = $('SalesPriceTable');
	var form = $('SalesBuyContainer');
	var customize = $('SalesCustomize');
	
	// first, remove the 'on' class from all other th's
	var ths = table.select('th').each(function (element) {
			promoTableHide(element);
		}
	);
	
	
	var tds = table.select('td').each(function (element) {
			promoTableHide(element);
		}
	);
	
	// now, add the class 'on' to the selected th
	var newths = $$('th.'+promoPackage).each(function (element) {
			promoTableShow(element);
		}
	);
	
	// and finally, add the class 'on' to the selected td
	var newtds = $$('td.'+promoPackage).each(function (element) {
			promoTableShow(element);
		}
	);
	// show the form!
	// form.style.display = 'block'; REMOVED FOR SCRIPTACULOUS FADE BELOW
	Effect.Appear(form, {duration:.3});	
	
	Effect.Appear(customize, {duration:.3});		
	if(promoPackage != "choiceE") {
		for (x in featureMatrix[promoPackage]) {
			if($(x+'_image_qty')) {
				$(x+'_image_qty').innerHTML = featureMatrix[promoPackage][x];
				if(featureMatrix[promoPackage][x] != 0) {
					$(x+'_image_default').update(new Element('div',{className: 'darkCheck'}));
				}
				else {
					$(x+'_image_default').update('--');
				}
			}
		}
	}
	
	
	if(promoPackage == 'choiceE') {
		table.select('span.custom_default').invoke('fade',{duration: .1});
		table.select('span.custom_option').invoke('appear',{duration: .1});
		customize.select('span.custom_default').invoke('fade',{duration: .1});
		customize.select('span.custom_option').invoke('appear',{duration: .1});
	}
	
	$('total_cost').innerHTML = packagePrices[promoPackage];
	packageChoiceLetter = promoPackage.replace(/choice/,'');
	switch(packageChoiceLetter) {
		case "A":
			packageChoice = 1;
			$('checkout_type').value = 3;
			break;
		
		case "B":
			packageChoice = 2;
			$('checkout_type').value = 3;
			break;
			
		case "C":
			packageChoice = 3;
			$('checkout_type').value = 3;
			break;
			
		default: 
			packageChoice = 4;
			$('checkout_type').value = 4;
	}
	
	$('promo_pack_id').value = packageChoice;
	Effect.Fade('chooseLink'+promoPackage, {duration:.1});
	activePromoPackage = promoPackage;
}

function cancelPromoSelection() {
	// get the form
	var form = $('SalesBuyContainer');
	var customize = $('SalesCustomize');	
	// hide the form
	// form.style.display = 'none'; REMOVED FOR SCRIPTACULOUS FADE BELOW
	Effect.Fade(form, {duration:.1});	
	Effect.Fade(customize, {duration:.1});		
	
	// now get the hidden table cells and show them again
	var table = $('SalesPriceTable');
	var tds = table.select('td');
	for (var i=0; i<tds.length; i++) {
		tds[i].style.display = '';
	}
	var ths = table.select('th');
	for (var k=0; k<ths.length; k++) {
		ths[k].style.display = '';
	}
	if(activePromoPackage == 'choiceE') {
		table.select('span.custom_option').invoke('fade',{duration: .1});
		table.select('span.custom_default').invoke('appear',{duration: .1});
		customize.select('span.custom_option').invoke('fade',{duration: .1});
		customize.select('span.custom_default').invoke('appear',{duration: .1});
	}
	Effect.Appear('chooseLink'+activePromoPackage,{duration: .1});
}

function showPromoOptionInfo(promoOption) {
	if(promoOption != activeInfo) {
		if(activeInfo) {
			$('MoreInfo'+activeInfo).fade({duration: .1});
		}
		$('MoreInfo'+promoOption).appear({duration: .3});
		activeInfo = promoOption;
	}
}

function updateCustomTotal() {
	var customTotal = 0;
	customTotal += calculateFeatureImageCost();
	customTotal += $('custom_song_count').value * songCost;
	if($('custom_notification').checked) {
		customTotal += $('custom_song_count').value * notificationCost;
	}
	
	if($('custom_email').checked) {
		customTotal += $('custom_song_count').value * emailCost;
	}
	
	if($('custom_stats').checked) {
		customTotal += $('custom_song_count').value * statsCost;
		
	}
	
	$('total_cost').innerHTML = customTotal;
	$('custom_total').innerHTML = '$' + customTotal;
}

function calculateFeatureImageCost() {
	featureImageTotal = 0;
	if($('huge_checkbox').checked) {
		featureImageTotal += $('huge_qty').value * hugeCost;
	}
	if($('large_checkbox').checked) {
		featureImageTotal += $('large_qty').value * largeCost;
	}	
	
	if($('small_checkbox').checked) {
		featureImageTotal += $('small_qty').value * smallCost;
	}
	
	return featureImageTotal;
}

function updateAdPrice(monthCount) {
	$('total_cost').update(packagePrices[activePromoPackage] * monthCount);
}
function activateAdSlot(adSlotID) {
		$('ad_slot_activate_'+adSlotID).style.display = 'none';
		if($('ad_slot_deactivate_'+adSlotID)) {
			$('ad_slot_deactivate_'+adSlotID).appear({duration: .3});
		}
		new Ajax.Request('/ajax_actions.php?action=activate_ad_slot&ad_slot_id='+adSlotID);
}

function deactivateAdSlot(adSlotID) {
		$('ad_slot_deactivate_'+adSlotID).style.display = 'none';
		if($('ad_slot_activate_'+adSlotID)) {
			$('ad_slot_activate_'+adSlotID).appear({duration: .3});
		}
		new Ajax.Request('/ajax_actions.php?action=deactivate_ad_slot&ad_slot_id='+adSlotID);
}

function deleteAlbum(albumID) {
	if(confirm('Are you sure you want to delete this album?')) {
		new Ajax.Request('/ajax_actions.php?action=delete_album&album_id='+albumID);
		window.location = '/Music/MusicLatestArrivals.php';
	}
}

var uploadPageType = 'edit';
var uploadTrackID;

function createNewTrack(contestID) {
	if($('file').value=="") { 
		$("ErrorMessageContent").update('You must choose a file to upload.'); 
		$("ErrorMessage").appear({duration: .3});
		return;
	} //no file, no upload)
	if($('whatnext')) {
		$('whatnext').fade({duration: .3});
	}
	promoTrackType = '';
	if($('promo_song_basic')) {
		if($('promo_song_basic').checked) {
			promoTrackType = $('promo_song_basic').value;
		}
		else if($('promo_song_plus').checked) {
			promoTrackType = $('promo_song_plus').value;
		}
	}
	if(!uploadTrackID) {
		new Ajax.Request('/ajax_actions.php',{
			parameters: {
				action: 'create_track',
				promo_track_type: promoTrackType,
				contest_id: contestID
			},
			evalJSON: 'force',
			onComplete: function (response) {
				trackResponse = response.responseJSON;
				if(trackResponse.type == 'error') {
					$('ErrorMessageContent').update(trackResponse.message);
					$('ErrorMessage').appear({duration: .3});
					
				}
				else if(trackResponse.type == "success") {
					$('ErrorMessage').style.display = 'none';
					uploadTrackID = trackResponse.message;
					$("InfoMessageContent").update("Your track has been created, with an ID of "+uploadTrackID+".  Uploading begins now.");
					$("InfoMessage").appear({duration: .3});
					new Effect.Pulsate("InfoMessage");
					uploadTrack();
				}
				else {
					$('ErrorMessageContent').update('An unexpected error has occurred.  GigaCrate.com administrators have been notified. Thank you for your patience');
					$('ErrorMessage').appear({duration: .3});
				}
			}
		});
	}
	else {
		uploadTrack();
	}
}


function completeUpload(uploadTypeID,response) {
	if(uploadTypeID == 1) {
		completeTrackUpload(response);
	}
	else if(uploadTypeID == 2) {
		completeArtUpload(response);
	}
}
var suckit;
var lastresponse = 'hello!';
function completeTrackUpload(response) {
	
	switch(uploadPageType) {
		case 'create':
			createResponse = response.responseJSON;
			lastresponse = createResponse;
			if(createResponse.type == 'error') {
				$("InfoMessage").style.display = 'none';
				errorMessage = 'Errors have occurred.<ul>';
				for(x = 0; x < createResponse.messages.length; x++) {
					errorMessage += '<li>'+createResponse.messages[x]+'</li>';
				}
				errorMessage += '</ul>';
				$("ErrorMessageContent").update(errorMessage);
				$("ErrorMessage").appear({duration: .3});
				$('upload_pb').style.display = 'none';
				$('track_upload_form').style.display = '';
			}
			else {
				$('track_container').style.display = 'none';
				$("InfoMessageContent").update("Your track has finished uploading, and is queued for processing.  It may take up to 8 hours for your track to process. <br><br><a href='/Users/UsersDetails.php?tab=3'>Return to your Pending Songs tab</a>.");
				$("InfoMessage").appear();
				new Effect.Pulsate("InfoMessage");
				window.location.href = '/Music/MusicDetails.php?id='+createResponse.track_id;
			}
			
			break;
			
		case 'edit':
			createResponse = response.responseJSON;
			if(createResponse.type == 'error') {
				$("InfoMessage").style.display = 'none';
				errorMessage = 'Errors have occurred.<ul>';
				for(x = 0; x < createResponse.messages.length; x++) {
					errorMessage += '<li>'+createResponse.messages[x]+'</li>';
				}
				errorMessage += '</ul>';
				$("ErrorMessageContent").update(errorMessage);
				$("ErrorMessage").appear({duration: .3});
				$('upload_pb').style.display = 'none';
				$('track_upload_form').style.display = '';
			}
			else {
				if($('track_container')) {
					$('track_container').style.display = 'none';
					$('mp3FileLink').appear({duration: .2});
					$('flacFileLink').appear({duration: .2}); 
					$('flac_label').appear({duration: .2}); 
					$('mp3_label').appear({duration: .2});
				}
				$('finished_container').appear({duration: .3});
			}
			
			break;
	}
}

function uploadTrack() {
	if($('ErrorMessage')) {
		$("ErrorMessage").style.display = 'none';
	}
	beginUpload($('sid').innerHTML,$('track_upload_form'),'upload_filename', 'upload_pb', 'upload_progress', 'upload_iframe','1',uploadTrackID);
}

function completeArtUpload(responseText) {
	switch(uploadPageType)	{
		case 'create':
			$('art_container').fade({duration: .3});
			$('album_form_complete').update(responseText).appear({duration: .3});
			if(responseText.indexOf("Error") > 0) {
				
			}
			else {
				$('track_container').appear({duration: .3});
			}
			new Effect.Pulsate('album_form_complete');
			break;
			
		case 'edit':
		
			break;
	}
}

function retryArtUpload() {
	$('album_art_form').style.display = 'block';
	$('upload_art_pb').style.display = 'none';
	$('art_container').appear({duration: .3});
	$('album_form_complete').fade({duration: .3});
	$('upload_art_progress').style.width = '0px';
	
}

function retryTrackUpload() {
	$('track_upload_form').style.display = 'block';
	$('upload_pb').style.display = 'none';
	$('track_container').appear({duration: .3});
	$('album_form_complete').fade({duration: .3});
	$('upload_art_progress').style.width = '0px';
	
}


function continueCreateTrack() {
	sid = $('sid').innerHTML;
	
}


function massSongAction(actionType) {
	$('promo_list').style.display = 'none';
	$('album_list').style.display = 'none';
	if($('provider_list')) {
		$('provider_list').style.display = 'none';
	}
	tempActionList = $$('.massbox');
	if(tempActionList.length) {
		switch(actionType) {
			case "1":
				$('album_list').appear({duration: .3});
				break;
				
			case "2":
				$('promo_list').appear({duration: .3});
				break;
				
			case "3":
				actionList = $$('.massbox');
				for(x = 0; x < actionList.length; x++) {
					actionID = actionList[x].id.replace(/massbox_/,'');
					if(actionList[x].checked) {
						new Ajax.Request('/ajax_actions.php',{
							parameters: {
								action: 'set_for_sale',
								action_id: actionID,
								action_key_type: actionKeyType
							}
						});
						if(actionKeyType == 'track') {
							$('promo_relationship_'+actionID).update('For Sale');
						}
						actionList[x].checked = false;
						$(actionKeyType+'_manage_row_'+actionID).className = '';
						$('massActions').value = 0;
						$('InfoMessageContent').update('The selected '+actionKeyType+'s have been set to sell.').style.display = '';
						new Effect.Pulsate('InfoMessage',
											{
												afterFinish: function () { 
													$('InfoMessage').fade({duration: 2});
												}
											});
						new Effect.Pulsate(actionKeyType+'_manage_row_'+actionID);
						
					}
					
				}
				break;
				
			case "4":
				actionList = $$('.massbox');
				for(x = 0; x < actionList.length; x++) {
					actionID = actionList[x].id.replace(/massbox_/,'');
					if(actionList[x].checked) {
						new Ajax.Request('/ajax_actions.php',{
							parameters: {
								action: 'do_require_feedback',
								action_id: actionID,
								action_key_type: actionKeyType
							}
						});
						actionList[x].checked = false;
						$(actionKeyType+'_manage_row_'+actionID).className = '';
						$('massActions').value = 0;
						$('InfoMessageContent').update('The selected '+actionKeyType+'s have been set to require feedback.').style.display = '';
						new Effect.Pulsate('InfoMessage',
										{
											afterFinish: function () { 
												$('InfoMessage').fade({duration: 2});
											}
										});
										
						new Effect.Pulsate(actionKeyType+'_manage_row_'+actionID);
					}
					
					
					
				}
				break;
				
			case "5":
			
				break;
		}
	}
}

function assignTracksToAlbum(albumID) {
	actionList = $$('.massbox');
	for(x = 0; x < actionList.length; x++) {
		actionID = actionList[x].id.replace(/massbox_/,'');
		if(actionList[x].checked) {
			new Ajax.Updater(actionKeyType+'_manage_row_'+actionID,'/ajax_actions.php',{
				parameters: {
					action: 'update_album',
					action_id: actionID,
					album_id: albumID,
					action_key_type: actionKeyType
				},
				onComplete: function (response) {
					$('InfoMessageContent').update('The selected '+actionKeyType+'s have been set to the album you selected.').style.display = '';
					if(actionKeyType == 'album') {
						if($('album_manage_row_'+albumID)) {
							$('album_manage_row_'+actionID).fade({duration: .3});
						}
					}
				}
			});
			new Effect.Pulsate(actionKeyType+'_manage_row_'+actionID);
			$(actionKeyType+'_manage_row_'+actionID).className = '';
		}
	}
	$('album_list').fade({duration: .3});
	$('album_list_dropdown').value = 0;
	$('massActions').value = 0;
	
	new Effect.Pulsate('InfoMessage',
						{
							afterFinish: function () { 
								$('InfoMessage').fade({duration: 2});
							}
						});
}

function massPromoTo(groupLabel) {
	var groupArray = groupLabel.split("_");
	groupID = groupArray[1];
	actionList = $$('.massbox');
	for(x = 0; x < actionList.length; x++) {
		actionID = actionList[x].id.replace(/massbox_/,'');
		if(actionList[x].checked) {
			new Ajax.Updater(actionKeyType+'_manage_row_'+actionID,'/ajax_actions.php',{
				parameters: {
					action: 'update_promo_relationship',
					action_id: actionID,
					group_type: groupArray[0],
					group_id: groupArray[1],
					action_key_type: actionKeyType
				},
				onComplete: function (response) {
					$('InfoMessageContent').update('The selected '+actionKeyType+'s have been set to promo to your specified group.').style.display = '';
					if(actionKeyType == 'album') {
						if($('album_manage_row_'+albumID)) {
							$('album_manage_row_'+actionID).fade({duration: .3});
						}
					}
				}
			});
			new Effect.Pulsate(actionKeyType+'_manage_row_'+actionID);
			$(actionKeyType+'_manage_row_'+actionID).className = '';
		}
	}
	$('promo_list').fade({duration: .3});
	$('promo_list_dropdown').value = 0;
	$('massActions').value = 0;
	
	new Effect.Pulsate('InfoMessage',
						{
							afterFinish: function () { 
								$('InfoMessage').fade({duration: 2});
							}
						});
}


function updateFeaturedImageLink(featuredImageID) {
	var featuredImageTargetTypeID = $('link_type_dropdown_'+featuredImageID).value;
	var featuredImageTargetTypeKeyID = '';
	switch(featuredImageTargetTypeID) {
		case '2':
			featuredImageTargetTypeKeyID = $('link_album_'+featuredImageID).value;
			break;
		case '1':
			featuredImageTargetTypeKeyID = $('link_track_'+featuredImageID).value;
			break;
		case '3':
			featuredImageTargetTypeKeyID = $('user_select_'+featuredImageID).value;
			break;
	}
	
	if(featuredImageTargetTypeKeyID) {
		new Ajax.Updater('featured_image_link_container_'+featuredImageID,'/ajax_actions.php',{
			parameters: {
				action: 'update_featured_image_link',
				featured_image_id: featuredImageID,
				featured_image_target_type_id: featuredImageTargetTypeID,
				featured_image_target_type_key_id: featuredImageTargetTypeKeyID
			},
			onComplete: function () {
				$('featured_image_link_select_'+featuredImageID).style.display='none';
				$('featured_image_link_'+featuredImageID).style.display='';
			}
		});
	}
}

function updateAdminFeaturedImageLink(featuredImageID) {
	var featuredImageTargetTypeID = $('link_type_dropdown_'+featuredImageID).value;
	var featuredImageTargetTypeKeyID = $('link_target_key_'+featuredImageID).value;
	
	if(featuredImageTargetTypeKeyID) {
		new Ajax.Updater('featured_image_link_container_'+featuredImageID,'/ajax_actions.php',{
			parameters: {
				action: 'update_featured_image_link',
				featured_image_id: featuredImageID,
				featured_image_target_type_id: featuredImageTargetTypeID,
				featured_image_target_type_key_id: featuredImageTargetTypeKeyID
			},
			onComplete: function () {
				$('featured_image_link_select_'+featuredImageID).style.display='none';
				$('featured_image_link_'+featuredImageID).style.display='';

				checkCanMakeFeatureLive(featuredImageID);
			}
		});
	}
}

function checkCanMakeFeatureLive(featuredImageID) {
	new Ajax.Request('/ajax_actions.php',{
				parameters: {
					action: 'check_can_make_feature_live',
					featured_image_id: featuredImageID
				},
				onComplete: function (response) {
					if(response.responseText == 'y') {
						if($('live_link_'+featuredImageID)) {
							$('live_link_'+featuredImageID).show();
						}
					}
					else if(response.responseText == "n") {
						if($('live_link_'+featuredImageID)) {
							$('live_link_'+featuredImageID).hide();
						}
					}

				}
			});
}

function showFeaturedImageTargetTypeDropdowns(featuredImageID) {
	var targetTypeID = $('link_type_dropdown_'+featuredImageID).value;
	switch(targetTypeID) {
		case "1":
			$('link_album_select_'+featuredImageID).style.display = 'none';
			$('link_track_select_'+featuredImageID).style.display = '';
			
			break;
		case "2":
			$('link_album_select_'+featuredImageID).style.display = '';
			$('link_track_select_'+featuredImageID).style.display = 'none';
			break;
	}
}

function makeFeaturedImageLive(featuredImageID) {
	new Ajax.Request('/ajax_actions.php?action=make_featured_image_live&featured_image_id='+featuredImageID,{
		onComplete: function () {
			$('active_set').insert({top: $('featured_image_display_'+featuredImageID).remove()});
			$('live_link_'+featuredImageID).hide();
			if($('offline_link_'+featuredImageID)) {
				$('offline_link_'+featuredImageID).show();
			}
		}
	});
}

function retireFeaturedImage(featuredImageID) {
	new Ajax.Request('/ajax_actions.php?action=retire_featured_image&featured_image_id='+featuredImageID,{
		onComplete: function () {
			$('featured_image_display_'+featuredImageID).remove();
		}
	});
}

function setFeaturedImageOffline(featuredImageID) {
	new Ajax.Request('/ajax_actions.php?action=set_featured_image_offline&featured_image_id='+featuredImageID, {
				onComplete: function () {
					tempFeaturedImage = 	$('featured_image_display_'+featuredImageID);
					$('featured_image_display_'+featuredImageID).remove();
					$('unused_set').insert({top: tempFeaturedImage});
					$('offline_link_'+featuredImageID).hide();
					$('live_link_'+featuredImageID).show();
				}
				});
}

function addFeaturedImage() {
	new Ajax.Request('/ajax_actions.php',{
		parameters: {
			action: 'add_featured_image'
		},
		onSuccess: function (response) {
			var containerDiv = new Element('div',{className: "ListRow"});
			containerDiv.update(response.responseText);
			$('unused_set').insert({top: containerDiv});
			setActiveFeaturedImagesTab('unused');
			new Effect.Pulsate(containerDiv);
		}
	});
}

function setActiveFeaturedImagesTab(type) {
	$('unused_featured_images').style.display = 'none'; 
	$('inactive_featured_images').style.display = 'none'; 
	$('active_featured_images').style.display = 'none';
	$(type+"_featured_images").style.display = '';
	var tabList = $$('#FeaturesTabber .tabberactive');
	for(x = 0; x < tabList.length; x++) {
		tabList[x].removeClassName('tabberactive');
	}
	$(type+'_tab').addClassName('tabberactive');
}

function removePromoRelationship(promoRelationshipID) {
	new Ajax.Request('/ajax_actions.php',{
		parameters: {
			action: 'remove_promo_relationship',
			promo_relationship_id: promoRelationshipID
		},
		onComplete: function () {
			$('promo_relationship_display_'+promoRelationshipID).fade({duration: .3});
		}
	});
}

function checkGetPassword() {
	new Ajax.Request('/ajax_actions.php',{
		parameters: { 
			action: 'get_username_from_email',
			email_address: $('ForgotEmail').value
		},
		onSuccess: function (response) {
			if(response.responseText == "0" || response.responseText == "1") {
				$('passform').submit();
			}
			else {
				$('user_list').update(response.responseText);
				new Effect.BlindDown('multiple_users_list',{duration: .3});
			}
		}

	});
}



function setActiveAdSlotsTab(type) {
	$('unused_ad_slots').style.display = 'none'; 
	$('inactive_ad_slots').style.display = 'none'; 
	$('active_ad_slots').style.display = 'none';
	$(type+"_ad_slots").style.display = '';
	var tabList = $$('#adsTabber .tabberactive');
	for(x = 0; x < tabList.length; x++) {
		tabList[x].removeClassName('tabberactive');
	}
	$(type+'_tab').addClassName('tabberactive');
}

function checkShowEmailBlastSubmit(albumID) {
	if(albumID) {
		$('email_blast_submit_button').appear({duration: .3});
	}
}

function updateWebFlagStatus(trackID) {
	new Ajax.Request('/ajax_actions.php',{
		parameters: {
			action: 'get_web_flag_status',
			track_id: trackID
		},
		onComplete: function (response) {
			statusResponse = response.responseJSON;
			if(statusResponse.type == "success" && !trackIsLive) {
				if($("ErrorMessage")) {
					$("ErrorMessage").fade({duration: .3});
				}
				$("InfoMessageContent").update(statusResponse.output);
				$("InfoMessage").appear({duration: .3});
				new Effect.Pulsate($("InfoMessage"));
				trackIsLive = true;
			}
			else if(statusResponse.type == "fail") {
				if($("InfoMessage")) {
					$("InfoMessage").fade({duration: .3});
				}
				$("ErrorMessageContent").update(statusResponse.output);
				$("ErrorMessage").appear({duration: .3});
				new Effect.Pulsate($("ErrorMessage"));
				trackIsLive = false;
			}
		},
		evalJSON: 'force'
	});
}

function updatePromoToList(trackID) {
	new Ajax.Updater('promo_relationship_list','/ajax_actions.php',{
		parameters: {
			action: 'get_promo_to_list',
			track_id: trackID
		},
		evalScripts: true,
		onComplete: function () {
			$('promo_options').appear({duration: .3});
			
		}
	});
}
var successCount = 0;
var failCount = 0;
function setPendingSongsLive() {
	$('ErrorMessage').hide();
	$('InfoMessage').hide();
	successCount = 0;
	failCount = 0;
	approvalCount = 0;
	tempCheckboxList = $('UserMusicPendingTableTbody').select(".pending_check");
	var checkboxList = new Array();
	var y = 0;
	for(x = 0; x < tempCheckboxList.length; x++) {
		if(tempCheckboxList[x].checked) {
			checkboxList[y] = tempCheckboxList[x];
			y++;
		}
	}
	
	for(x = 0; x < checkboxList.length; x++) {
		element = checkboxList[x];
		
		if(element.checked) {
			new Ajax.Request('/ajax_actions.php',{
				parameters: {
					action: 'set_track_live',
					track_id: element.value
				},
				onComplete: function (response) {
					if(response.responseText == 'success' || response.responseText == 'approval') {
						if(response.responseText == 'approval') {
							approvalCount++;
						}
						successCount++;
						$('pending_track_'+element.value).remove();
					}
					else {
						failCount++;
					}
					if(x == (checkboxList.length)) {
						if(failCount > 0) {
							if(successCount > 0) {
								message = successCount+" songs were successfully set live, but "+failCount+" songs are not ready to be live yet.  Please review their status' in the table below.";
							}
							else {
								message = "Your songs could not be set live.  Please review the status' of your songs in the table below.";
							}
							$('ErrorMessageContent').update(message).show();
							new Effect.Pulsate('ErrorMessage');
							
						}
						else {
							if(!approvalCount) {
								$('InfoMessageContent').update("Your song(s) were successfully set live.").show();
							}
							else {
								$('InfoMessageContent').update("Your song(s) have been submitted for approval.  You will be notified when they are live.").show();
							}
							new Effect.Pulsate("InfoMessage");
						}
					}
				}
			});
		}
	}
}


function deletePendingTracks() {
	$('ErrorMessage').hide();
	$('InfoMessage').hide();
	successCount = 0;
	failCount = 0;
	tempCheckboxList = $('UserMusicPendingTableTbody').select(".pending_check");
	var checkboxList = new Array();
	var y = 0;
	for(x = 0; x < tempCheckboxList.length; x++) {
		if(tempCheckboxList[x].checked) {
			checkboxList[y] = tempCheckboxList[x];
			y++;
		}
	}
	
	for(x = 0; x < checkboxList.length; x++) {
		element = checkboxList[x];
		
		if(element.checked) {
			new Ajax.Request('/ajax_actions.php',{
				parameters: {
					action: 'delete_pending_track',
					track_id: element.value
				},
				onComplete: function (response) {
					$('pending_track_'+element.value).remove();
				}
			});
		}
	}
}

function addFeedbackReply(trackFeedbackID) {
	new Ajax.Request('/ajax_actions.php',{
		parameters: {
			action: 'add_feedback_reply',
			track_feedback_id: trackFeedbackID,
			feedback: $('feedback_reply_'+trackFeedbackID).value
		},
		onComplete: function (response) {
			$('feedback_reply_'+trackFeedbackID).value = '';
			new Effect.BlindUp('track_feedback_reply_'+trackFeedbackID,{duration: .3});
			replyContainer = new Element('div');
			replyContainer.update(response.responseText);
			$('feedback_replies_'+trackFeedbackID).insert(replyContainer);
			new Effect.Pulsate(replyContainer.identify());
			
		}
	});
}

function toggleNotifyOnFeedbackReply(checkedValue) {
	if(checkedValue) {
		checkedValue = 1;
	}
	else {
		checkedValue = 0;
	}
	new Ajax.Request('/ajax_actions.php', {
			parameters: {
				action: 'update_do_notify_on_feedback_reply',
				do_notify: checkedValue
			}
		}
	);
}
var currentCommentPage = 1;
function showCommentsPage(pageNumber,numPages) {
	newPage = 0;
	if(pageNumber == 'previous') {
		if(currentCommentPage > 1) {
			newPage = currentCommentPage - 1;
		}
	}
	else if (pageNumber == 'next') {
		if(currentCommentPage < numPages) {
			newPage = currentCommentPage + 1;
		}
	}
	else {
		if(pageNumber <= numPages && pageNumber != currentCommentPage) {
			newPage = pageNumber;
		}
	}
	
	if(newPage) {
		$('comment_page_link_'+currentCommentPage).removeClassName('CurrentPage');
		$('comment_page_link_'+newPage).addClassName("CurrentPage");
		$('comment_page_'+currentCommentPage).hide();
		$('comment_page_'+newPage).show();
		currentCommentPage = newPage;
		if(currentCommentPage == 1) {
			$('comment_previous').hide();
			$('comment_next').show();
		}
		else if(currentCommentPage == numPages) {
			$('comment_previous').show();
			$('comment_next').hide();			
		}
		else {
			$('comment_previous').show();
			$('comment_next').show();			
		}
			
	}
}
var currentChartType = '';
function changeChartReport(chartReportType,chartReportTargetTypeID,chartReportTargetTypeKeyID) {
	url = '/chart_report.xml?report_type='+chartReportTargetTypeID+'|'+chartReportTargetTypeKeyID+'|'+chartReportType;
	$('chart').Update_URL( url,true,30,2,'reset');
	if(chartReportType != currentChartType) {
		if(currentChartType) {
			$('chart_note_'+currentChartType).hide();
		}
		$('chart_note_'+chartReportType).show();
		
		if($('stats_'+currentChartType)) {
			$('stats_'+currentChartType).hide();
		}
		if($('stats_'+chartReportType)) {
			$('stats_'+chartReportType).show();
		}
		
		currentChartType = chartReportType;
	}
}

function blogAction(blogID,actionType) {
	new Ajax.Request('/ajax_actions.php',{
		parameters: {
			action: 'do_blog_action',
			action_type: actionType,
			music_blog_id: blogID
		},
		onComplete: function () {
			$('blog_'+blogID).fade({duration: .3});
		}
	});
}

function doApprovalAction(trackID,approvalTypeID) {
	new Ajax.Request('/ajax_actions.php',{
		parameters: {
			action: 'do_approval_action',
			track_id: trackID,
			approval_type_id: approvalTypeID
		},
		onComplete: function () {
			$('track_approve_'+trackID).fade({duration: .3});
		}
	});
}

var upcomingImageCount;
var currentImageKey = 0;
var currentImage;
var oldImageKey;
function rotateUpcoming() {

	oldImageKey = currentImageKey;
	currentImageKey++;
	if(currentImageKey >= upcomingImageCount) {
		currentImageKey = 0;
	}
	$('upcoming_image_'+oldImageKey).fade({duration: .5});
	$('upcoming_image_'+currentImageKey).appear({duration: .5});
	

}

function swapUpcomingImage() {
}

function updateBadAlbumCriteria(badAlbumCriteriaID) {
	$$('.criteria_extension').each(function (element) { if(element.id != 'criteria_extension_'+badAlbumCriteriaID) {element.hide();}});
	if(badAlbumCriteriaID) {
		$('criteria_extension_'+badAlbumCriteriaID).show();
	}
}


function addJudgeToContest(contestID) {
	new Ajax.Updater('judge_list','/ajax_actions.php',{
		parameters: {
			action: 'add_judge_to_contest',
			contest_id: contestID,
			contest_judge_id: $('new_contest_judge_id').value,
			judge_name: $('new_judge_name').value,
			judge_bio: $('new_judge_bio').value
		},
		insertion: 'bottom',
		onComplete: function () {
			$('new_judge').hide();
		}
	});
}

function removeJudgeFromContest(contestJudgeID,contestID) {
	new Ajax.Request('/ajax_actions.php',{
		parameters: {
			action: 'remove_judge_from_contest',
			contest_id: contestID,
			contest_judge_id: contestJudgeID
		},
		onComplete: function () {
			$('contest_judge_'+contestJudgeID).hide();
		}
	});
}

function togglePlayerLocation() {
	daPlayer = document.getElementById('PlayerContainer');
	if (daPlayer) {
		if (daPlayer.className == 'PlayerInFooter') {
			daPlayer.className = 'PlayerInRight';
		} else {
			daPlayer.className = 'PlayerInFooter';
		}
	}
	new Ajax.Request('/ajax_actions.php',{
		parameters: {
			action: 'set_current_player_class',
			player_class: daPlayer.className
		}
	});
}

function togglePlayerPlaylist() {
	daPlayer = document.getElementById('PlayerWrapper');
	if (daPlayer) {
		if ($('PlayerPlaylist').style.display == 'none') {
			daPlayer.className = 'PlayerExpandedPlaylist';
			if($('PlayerRating')) {
				$('PlayerRating').hide();
			}
			$('PlayerPlaylist').show();

		} else {
			daPlayer.className = 'PlayerCollapsed';
			$('PlayerPlaylist').hide();

		}
	}
}

function togglePlayerRating(trackID) {
	aplayer = $('PlayerWrapper');
	if($('PlayerRating').style.display == 'none') {
		$('PlayerPlaylist').hide();
		$('PlayerRating').show();
		aplayer.className = 'PlayerExpandedRating';
		/*new Effect.BlindDown('PlayerTrackFeedback'+trackID,{duration: .3});*/
	
	}
	else {
		$('PlayerRating').hide();
		aplayer.className = 'PlayerCollapsed';
		/*new Effect.BlindUp('PlayerTrackFeedback'+trackID,{duration: .3});*/

	}

}

function listAddAndPlay(playlistObjectTypeKeyID,playlistObjectTypeID) {
/*
	do this shit later, not sure it makes sense in all contexts
	Effect.Appear('6029FlashAudioState2', {duration:.01}); 
	Effect.Fade('6029FlashAudioState1', {duration:.01}); 
	$('6029FlashAudioState1').up('.ListRowOdd').addClassName('ListRowActive');
*/

	addAndPlay(playlistObjectTypeKeyID,playlistObjectTypeID);
	
}

function addAndPlay(playlistObjectTypeKeyID,playlistObjectTypeID) {
	new Ajax.Request('/ajax_actions.php',{
		parameters: {
			action: 'add_object_to_playlist',
			playlist_object_type_id: playlistObjectTypeID,
			playlist_object_type_key_id: playlistObjectTypeKeyID
		},
		onComplete: function () {
			currentPlaylistItem = 0;
			currentTimeInSeconds = 0;
			loadPlaylistAndPlay();
		}
	});
}

function displayPlaylist() {
	
}

function loadPlaylist() {
	player.sendEvent("STOP");
	player.sendEvent("LOAD","/playlist.xspf");
	currentPlaylistItem = 0;
	currentPlaylistDisplay = $('PlayerPlaylist').style.display;

	if($("playlist_display")) {
		new Ajax.Updater('playlist_display','/ajax_actions.php',{
			parameters: {
				action: 'get_playlist_display',
				current_playlist_item: '0'
			},
			onComplete: function () {
				$('PlayerPlaylist').style.display = currentPlaylistDisplay;
			},
			evalScripts: true
		});
	}
}

function loadPlaylistAndPlay() {
	player.sendEvent("STOP");
	currentPlaylistItem = 0;
	currentTimeInSeconds = 0;
	currentPlaylistDisplay = $('PlayerPlaylist').style.display;

	player.sendEvent("LOAD","/playlist.xspf");
	new Ajax.Updater('playlist_display','/ajax_actions.php',{
		parameters: {
			action: 'get_playlist_display',
			current_playlist_item: '0'
		},
		onComplete: function () {
			$('PlayerPlaylist').style.display = currentPlaylistDisplay;
		},
		evalScripts: true
	});
	setTimeout("getPlayer().sendEvent('ITEM','0')",1000);
	setTimeout("playerPlay()",1500);
}

function getPlaylistDisplay() {
	currentPlaylistDisplay = $('PlayerPlaylist').style.display;
	new Ajax.Updater('playlist_display','/ajax_actions.php',{
		parameters: {
			action: 'get_playlist_display'
		},
		onComplete: function () {
			$('PlayerPlaylist').style.display = currentPlaylistDisplay;
		},
		evalScripts: true
	});
}



function playerPlay() {
	player.sendEvent("PLAY","true");
}

function playerPause() {
	player.sendEvent("PLAY","false");
}
var latestResponse;
var currentInfoPosition = 0;
var doPauseInfoScroll = true;
var newresp;
function updatePlayerCurrentSongInfo(responseObject) {
	doPauseInfoScroll = true;
	$('player_title_scroller').update("Loading...");
	currentPlaylistItem = String(responseObject.index);
	latestResponse = responseObject;
	newresp = responseObject;
	currentInfoPosition = 0;
	/*new Ajax.Updater('current_song_info','/ajax_actions.php',{
		parameters: {
			action: 'get_player_current_song_info',
			current_item: currentPlaylistItem
		},
		evalScripts: true,
		onComplete: function () {
			$$('.Playing').each(function (element) {
				if(element.identify() != 'item_'+currentPlaylistItem) {
					element.removeClassName('Playing');
				}
			});
			$('item_'+currentPlaylistItem).addClassName('Playing');
		}
	});
	*/
	detailsText = getPlayer().getPlaylist()[currentPlaylistItem].author+' "'+getPlayer().getPlaylist()[currentPlaylistItem].title+'"';
	linkText = '<a href="'+getPlayer().getPlaylist()[currentPlaylistItem].link+'" title=\'View details of '+detailsText+'\'>';
	$('player_art').update(linkText+'<img src="'+getPlayer().getPlaylist()[currentPlaylistItem].image+'"></a>');
	$('player_title_scroller').style.left = '0px';
	$('player_title_scroller').update(linkText+detailsText+'</a>');
	$$('.Playing').each(function (element) {
		if(element.identify() != 'item_'+currentPlaylistItem) {
			element.removeClassName('Playing');
		}
	});
	$('item_'+currentPlaylistItem).addClassName('Playing');
	new Ajax.Updater('player_functions','/ajax_actions.php',{
		parameters: {
			action: 'get_player_functions',
			current_item: currentPlaylistItem
		},
		evalScripts: true
	});
	new Ajax.Updater('player_rate','/ajax_actions.php',{
		parameters: {
			action: 'get_player_rate',
			current_item: currentPlaylistItem
		},
		evalScripts: true
	});
	doPauseInfoScroll = false;
}

function playerInfoScroller() {
	
		if(currentInfoPosition == 0) {
			totalWidthToMove = $('player_title_scroller').offsetWidth - $('title_scroller_container').offsetWidth;
			if(totalWidthToMove > 0) {
				new Effect.Move('player_title_scroller',{
					x: '-'+totalWidthToMove,
					duration: 2,
					mode: 'absolute',
					afterFinish: function () {
						currentInfoPosition = totalWidthToMove;
						setTimeout('playerInfoScroller()',2000);
					}
					
				});
			}
		}
		else {
			new Effect.Move('player_title_scroller',{
				x: '0',
				mode: 'absolute',
				duration: 2,
				afterFinish: function () {
					currentInfoPosition = 0;
					setTimeout('playerInfoScroller()',2000);
				}
			});
		}
	
}

var positionCallCount = 0;
function updatePlayerCurrentPosition(responseObject) {
	if(positionCallCount && positionCallCount % 50 == 0) {
		currentTimeInSeconds = responseObject.position;
		new Ajax.Request('/ajax_actions.php',{
			parameters: {
				action: 'update_playlist_position',
				current_time_in_seconds: responseObject.position,
				current_item: currentPlaylistItem
			}
		});
		positionCallCount = 0;
	}
	positionCallCount++;
}

var currentVolume = 75;

function updatePlayerCurrentVolume(newVolume) {
	new Ajax.Request('/ajax_actions.php',{ 
		parameters: {
			action: 'update_player_current_volume',
			current_volume: newVolume.percentage
		},
		onComplete: function () {
			currentVolume = newVolume;
		}

	});
}

currentIsPlaying = 0;
function updatePlayerIsPlaying(isPlaying) {
	switch(isPlaying.newstate) {
		case 'IDLE':
		case 'PAUSED':
		case 'COMPLETED':
			playingStatus = 0;
			break;

		case 'BUFFERING':
		case 'PLAYING':
			playingStatus = 1;
			break;
	}
	if(playingStatus != currentIsPlaying) {

		new Ajax.Request('/ajax_actions.php',{ 
			parameters: {
				action: 'update_player_is_playing',
				is_playing: playingStatus
			}
		});
		currentIsPlaying = playingStatus;
	}
}

function removeTrackFromPlaylist(trackID,sortOrder) {
	new Effect.Fade('item_'+sortOrder,{
		duration: .3,
		afterFinish: function () {
			
				new Ajax.Request('/ajax_actions.php',{
					parameters: {
						action: 'remove_track_from_playlist',
						track_id: trackID
					},
					onComplete: function () {
						getPlaylistDisplay();
					}
				});
		}
		});
}

function playerPlayItem(item) {
	player.sendEvent("ITEM",item);
}
var currentSearchType;
var currentSearchCriteria;
function updateSearchResults(newValues) {
	$('search_results').hide();
	$('search_loading').show();
	new Ajax.Updater('search_results','/ajax_actions.php',{
		parameters: {
			action: 'get_search_results',
			get_vars: currentSearchCriteria,
			new_vars: newValues.toJSON(),
			search_type: currentSearchType
		},
		evalScripts: true,
		onComplete: function () {

/*
			$('search_loading').hide();
			$('search_results').show();
			currentSearchCriteria.each(function (pair) {
				alert('key: '+pair.key);
				History.set(pair.key,pair.value);
				alert('value: '+pair.value);
			});
			newValues.each(function (pair) {
				History.set(pair.key,pair.value);
			});
			
			History.set("foo","bar");
*/
			$('search_loading').hide();
			$('search_results').show();
		}
	}
	);
}

function showTextResults() {
	Effect.Fade('iconDisplayText', {duration:.01}); 
	Effect.Appear('iconDisplayTextInactive', {duration:.01}); 
	Effect.Appear('iconDisplayGrid', {duration:.01}); 
	Effect.Fade('iconDisplayGridInactive', {duration:.01}); 
	Effect.Appear('iconDisplayList', {duration:.01}); 
	Effect.Fade('iconDisplayListInactive', {duration:.01});
	updateSearchResults($H({result_type: '2'}));
}

function updateBPMRange(bpmMin,bpmMax) {
	updateSearchResults($H({bpm_min: bpmMin,bpm_max: bpmMax}));
}

function updateRatingRange(ratingMin,ratingMax) {
	updateSearchResults($H({rating_min: ratingMin, rating_max: ratingMax}));
}

function showResultsPage(pageNumber) {
	updateSearchResults($H({page_number: pageNumber}));
	new Effect.ScrollTo('page_mainbody', {duration:.5});
}

function showGridResults() {
	Effect.Appear('iconDisplayText', {duration:.01}); 
	Effect.Fade('iconDisplayTextInactive', {duration:.01}); 
	Effect.Fade('iconDisplayGrid', {duration:.01}); 
	Effect.Appear('iconDisplayGridInactive', {duration:.01}); 
	Effect.Appear('iconDisplayList', {duration:.01}); 
	Effect.Fade('iconDisplayListInactive', {duration:.01}); 
	updateSearchResults($H({result_type: '3'}));
}

function showNormalResults() {
	Effect.Appear('iconDisplayText', {duration:.01}); 
	Effect.Fade('iconDisplayTextInactive', {duration:.01}); 
	Effect.Appear('iconDisplayGrid', {duration:.01}); 
	Effect.Fade('iconDisplayGridInactive', {duration:.01}); 
	Effect.Fade('iconDisplayList', {duration:.01}); 
	Effect.Appear('iconDisplayListInactive', {duration:.01}); 
	updateSearchResults($H({result_type: '1'}));
}

function updateResultTypeDisplay() {
	updateSearchResults($H({
		updated_result_type: 1,
		do_show_promos: $('PromoSongsFilter').checked,
		do_show_blogs: $('BlogSongsFilter').checked,
		do_show_for_sale: $('ForSaleSongsFilter').checked
	}));
	
}

function showTrackResults() {
	Effect.Fade('resultViewSongs', {duration:.01}); 
	Effect.Appear('resultViewSongsInactive', {duration:.01}); 
	Effect.Fade('resultViewAlbumsInactive', {duration:.01}); 
	Effect.Appear('resultViewAlbums', {duration:.01});
	updateSearchResults($H({group: 'songs',page_number: '1'}));
}

function showAlbumResults() {
	Effect.Appear('resultViewSongs', {duration:.01}); 
	Effect.Fade('resultViewSongsInactive', {duration:.01}); 
	Effect.Appear('resultViewAlbumsInactive', {duration:.01}); 
	Effect.Fade('resultViewAlbums', {duration:.01});
	updateSearchResults($H({group: 'album',page_number: '1'}));
}

function updateDateRangeResults() {
	updateSearchResults($H({date_range: $('search_date_range').value,page_number: '1'}));
}

function updateSortOrderResults() {
	updateSearchResults($H({sort_order: $('search_sort_order').value,page_number: '1'}));
}

function showFeaturedImageUpload(featuredImageID,featuredImageTypeID) {
	
	var targetID = 'featured_image_type_'+featuredImageID+'_'+featuredImageTypeID;
	$$('.featured_image_type_list').each(function (element){
		if(element.identify() != targetID) {
			element.hide();
		}
	});
	$(targetID).show();
	$('miTabberImageTab_'+featuredImageID).style.display = 'none'; 
	$('miTabberUploadTab_'+featuredImageID).style.display = 'block'; 
	$('featured_image_type_id_'+featuredImageID).value = featuredImageTypeID;
}

function updateHiddenAccount(isChecked) {
	if(isChecked) {
		doHide = 1;
	}
	else {
		doHide = 0;
	}
	new Ajax.Request('/ajax_actions.php',{
		parameters: {
			action: 'update_do_hide_account',
			do_hide: doHide
		}
	});
}
