// JavaScript Document

///////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////
///														    	///
///	  Copyright 2006 Josh Schwartzman / The Design Site LLC		///
///	  		josh@thedesignsite.com								///
///			Some portions of this file by 						///
///			Max Masnick & Matthew Cieplak						///
///	  Created for SelfPortrait (selfportrait.net)				///
///   Last Modified:  July 25, 2006								///
///																///
///																///
///////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////


function redirect(url){
	document.location.href = url;
}

function addFrame(){ // make sure the media player is there -- so reframe if it isn't
	
	if (parent.location.href == self.location.href && (parent.location.href.indexOf('index.php') == -1) && (parent.location.href.indexOf('ipn.php') == -1)) {
		var page = self.location.href;
		if(page.indexOf('selfportrait.net/') === false){ page = ''; }
		else if(self.location.href.indexOf('page=') != -1){
			var page = '?'+page.substr(self.location.href.lastIndexOf('page='), self.location.href.length);
		}else{
			var add = page.substr(self.location.href.lastIndexOf('/') + 1, self.location.href.length).replace('?', '|');
			add = add.replace('&', '|');
			page = '?f='+add;
		}
		window.location.href = 'index.php'+page;
  	}
	
}

function paypalSubmit(){
	document.paypalForm.submit();
}

function clearInput(elementId){
	var element = document.getElementById(elementId);
	if(element){
		element.value = '';
	}
}

function getFlashVersion() {

   var agent = navigator.userAgent.toLowerCase();
       flashVersion = 0; 
   if (agent.indexOf("mozilla/3") != -1 && agent.indexOf("msie") == -1) {
      flashVersion = 0;
   }
   // NS3+, Opera3+, IE5+ Mac (support plugin array):  check for Flash plugin in plugin array
   if (navigator.plugins != null && navigator.plugins.length > 0) {
      var flashPlugin = navigator.plugins['Shockwave Flash']; 
      if (typeof flashPlugin == 'object') {
            for (i=25;i>0;i--) {
                  if (flashPlugin.description.indexOf(i+'.') != -1){ 
                           flashVersion = i;
              }
            }
      }
    }
	return flashVersion;
}



function submitOnEnter(myfield, e){
	var keycode;
	if (window.event) keycode = window.event.keyCode;
	else if (e) keycode = e.which;
	else return true;
	
	if (keycode == 13)
	   {
	   myfield.form.submit();
	   return false;
	   }
	else
	   return true;	
}


function showDays(monthElementId, dayElementId){ // fill a select with the correct number of days for the selected month
	var monthSelect = document.getElementById(monthElementId);
	var daySelect = document.getElementById(dayElementId);
	if(monthSelect && daySelect){
		var month = monthSelect.selectedIndex;
		var selectOptions = '<option value=""></option>';
		if(month != ''){ // only add options if a month is selected
			var days = daysInMonth(month); // get array of days for this month
			for(i=1; i <= days.length; i++){
				selectOptions += '<option value='+i+'>'+i+'</option>';
			}
		}
		daySelect.innerHTML = selectOptions;
	}
}

	// return an array of the correct days for a month
function daysInMonth(month){
	var num_days;
	var day_array = new Array();
	// figure out how many days are in the month
	if(month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12){
		num_days = 31;
	}
	else if(month == 2){
		num_days = 28;	
	}
	else{ num_days = 30; }
	for(i=0; i < num_days; i++){ // make an array with the correct number of days
		day_array.push(i);	
	}
	return day_array;
}

	// redirect to a location with a get variable -- grab from a select option
	// getVarId - the id tag on the select box
function redirectSelectToGet(redirect, getVarId){
	var getVarSelect, getValue;
	getVarSelect = document.getElementById(getVarId);
	getValue = getVarSelect.options[getVarSelect.selectedIndex].value;
	location = redirect+'&'+getVarId+'='+getValue;
}

function hideAndShow(elementId, visibility){
	var element = document.getElementById(elementId);
	var elementStatus = document.getElementById(elementId+'_status');
	if(element && elementStatus && (visibility != elementStatus.value)){
		if(visibility == 'hidden' && elementStatus.value == 'visible'){
			new Effect.Fade(elementId, { duration: 0.5 });
			elementStatus.value = 'hidden';
		}
		else if(visibility == 'visible' && elementStatus.value == 'hidden'){
			new Effect.Appear(elementId, { duration: 0.5 });
			elementStatus.value = 'visible';
		}
	}
}

 /* check if a string is numeric */
function IsNumeric(sText)

   {
   var ValidChars = "0123456789.";
   var IsNumber=true;
   var Char;

 
   for (i = 0; i < sText.length && IsNumber == true; i++) 
      { 
      Char = sText.charAt(i); 
      if (ValidChars.indexOf(Char) == -1) 
         {
         IsNumber = false;
         }
      }
   return IsNumber;
   
   }


/*    ALL DRAG AND DROP FUNCTIONS   */

	sections = ['group1','group2','group3'];
		
	function createNewSection(name) {
		name = $('sectionName').value;
		if (name != '') {
			destroyLineItemSortables();
			destroyGroupSortable();
			
			var newDiv = Builder.node('div', {id: sections.length + 1, className: 'section', style: 'display:none;' }, [
				Builder.node('h3', {className: 'handle'}, name)
			]);
			
			sections[sections.length] = newDiv.id;
			$('page').appendChild(newDiv);
			Effect.Appear(newDiv.id);
			createGroupSortable();
			createLineItemSortables();
		}
	}
	
	function createLineItemSortables() {
		for(var i = 0; i < sections.length; i++) {
			Sortable.create(sections[i],{tag:'div',dropOnEmpty: true, containment: sections,only:'lineitem'});
		}
	}
	
	function destroyLineItemSortables() {
		for(var i = 0; i < sections.length; i++) {
			Sortable.destroy(sections[i]);
		}
	}
	
	function createGroupSortable() {
		Sortable.create('page',{tag:'div',only:'section',handle:'handle'});
	}
	
	function destroyGroupSortable() {
		Sortable.destroy('page');
	}
	
	
	/*
	Debug Functions for checking the group and item order
	*/
	function getGroupOrder() {
		var sections = document.getElementsByClassName('section');
		var alerttext = '';
		for(var i=0;i < sections.length;i++) {
			// alert(Sortable.sequence(sections[i]));
			var sectionID = sections[i].id;
			var order = Sortable.serialize(sectionID);
			alerttext += sectionID + ': ' + Sortable.sequence(sections[i]) + '\n';
		}
		alert(alerttext);
		return false;
	}
	
	
/*   FRIENDS  */
   
   /* prompts user whether they want to really delete this friend */
function friendDeleteConfirm(userId, username){
	var friend = document.getElementById('userFriend'+userId);
	var friendMessage = document.getElementById('userFriend'+userId+'Message');
	var dispStatus = document.getElementById('userFriend'+userId+'DispStatus');
	if(friend && dispStatus && friendMessage){
		if(dispStatus.value == 'visible'){
			new Effect.Fade(friend, { duration: 0.3, to: 0.3 });
			dispStatus.value = 'faded';
			new Element.hide(friendMessage);
			friendMessage.innerHTML = '<input type="hidden" name="friend_id" value="'+userId+'"><input type="hidden" name="confirm" value="y"><input type="hidden" name="a" value="del">Are you sure you want to remove '+username+' from your friends list?<br /><input type="submit" name="submit" value="Remove '+username+'" class="submit">&nbsp;&nbsp;&nbsp;<input type="reset" name="reset" value="cancel" onclick="friendDeleteConfirm('+userId+', \''+username+'\'); return false;" class="reset"><br /><br />';
			new Effect.Appear(friendMessage, { duration: 0.5, to: 1.0 });
		}
		else if(dispStatus.value == 'faded'){ // fade back
			new Effect.Appear(friend, { duration: 0.5, to: 1.0 });
			dispStatus.value = 'visible';
			friendMessage.innerHTML = "";
		}
		
	} else return false;
}

// UPDATING FRIENDS RELATIONSHIP

function AJAXupdateFriendRelationship(friendId, userId){
	var relationship = document.getElementById('userFriend'+friendId+'RelationshipInput').value;
	agent.call('/inc/ajaxfns.php','friendRelationship','AJAXcallbackUpdateFriendRelationship', relationship, friendId, userId);
}

function AJAXcallbackUpdateFriendRelationship(obj){
	if(obj[1]){ // if no relationship was entered, only the user id would be passed
		if(obj[0]){ var text = 'Relationship: '+obj[0]+'&nbsp;&nbsp;'; }else{ var text = ''; }
		var textElement = document.getElementById('userFriend'+obj[1]+'RelationshipText');
		if(textElement){
			textElement.innerHTML = text; // update relationship text
		}
		new Element.toggle('userFriend'+obj[1]+'RelationshipEdit'); // toggle off the relationship editor
		Element.toggle('userFriend'+obj[1]+'Relationship'); // toggle on the relationship
	}
	else return false;
}

/// TOP TEN FRIENDS

	// process checkbox input next to a friend
function topTenProcessCheckbox(elementId, friendId, friendName, userId){
	var checkbox = document.getElementById(elementId);
	if(checkbox){
		if(checkbox.checked == true){ //add the friend
			AJAXupdateTopTenFriends('add', friendId, friendName, userId);
		}
		else{ // remove the friend
			AJAXupdateTopTenFriends('del', friendId, friendName, userId);
		}
	}
}

function AJAXupdateTopTenFriends(action, friendId, friendName, userId){
	// send ajax call to add friend
	var count = document.getElementById('topTenFriendsListCount');
	if((action == 'add' && count.value < 10) || action == 'del'){
		agent.call('/inc/ajaxfns.php','topTenStatus','AJAXcallbackTopTenFriends', action, friendId, friendName, userId);
	}else return false;
}

	// after ajax is called this processes the results
function AJAXcallbackTopTenFriends(obj){
	if(obj[0] == 'add' || obj[0] == 'del'){ // success
		topTenFriendsList(obj[0], obj[1], obj[2], obj[3]);
	}else{
		topTenFriendsList('msg', '', '' ,'', obj[2]+' could not be added to your top ten friends list');
	}
}

	// for editing the top ten friends list box
function topTenFriendsList(action, friendId, friendName, userId, msg){
	var list = document.getElementById('topTenFriendsList');
	var count = document.getElementById('topTenFriendsListCount');
	var friendCheckbox = document.getElementById('userFriend'+friendId+'Checkbox');
	var friend = document.getElementById('userFriend'+friendId);
	if(list && count){
		if(action == 'add'){
			if(count.value < 10){
				if(count.value == 0){ // remove the info message
					message.innerHTML = ''; 
				}
				var newdiv = document.createElement('li');
				newdiv.setAttribute('id','topTenFriend_'+friendId);
				newdiv.setAttribute('className', 'element');
				newdiv.setAttribute('class', 'element');
				newdiv.style.display = 'none';
				newdiv.style.cursor = 'move';
				newdiv.style.margin = '0px 0px 0px -20px;';
				//newdiv.setAttribute('style', 'display:none; cursor: move; margin-left: -20px;');
				if(friend){ friend.setAttribute('style', 'background-color: #eef3f9;'); }
				newdiv.innerHTML = friendName+'&nbsp;&nbsp;&nbsp;<a href="#" onclick="AJAXupdateTopTenFriends(\'del\', '+friendId+', \''+friendName+'\', '+userId+'); return false;"><img src="../images/x.gif" alt="remove '+friendName+' from your top ten friends list" border="0" /></a>';
				list.appendChild(newdiv);
				Sortable.destroy('topTenFriendsList');
				Sortable.create('topTenFriendsList',{ghosting:true,constraint: false, onUpdate: AJAXtopTenFriendsListOrder});
				new Effect.Appear(document.getElementById('topTenFriend_'+friendId), { duration: 0.8});
				count.value++;
				//topTenFriendsListMessage('write', friendName+' has been added:');
			}else{ topTenFriendsListMessage('write','You already have 10 friends on the list.  Please remove a friend before adding a new friend.'); }
			
		}
		else if(action == 'del'){
			var deleteFriend = document.getElementById('topTenFriend_'+friendId);
			if(deleteFriend){
				list.removeChild(deleteFriend);
				count.value--;
				if(friendCheckbox){ friendCheckbox.checked = false; } // turn off checkbox
				if(friend){ friend.setAttribute('style', '');	} // remove highlighting
				topTenFriendsListMessage('write', friendName+' has been removed.');
			}
			else{ topTenFriendsListMessage('write', friendName+' could not be removed.'); }

		}
	}
}

 /* take the array of ids, and save the resorted friends list */
function AJAXtopTenFriendsListOrder(){
	 // serialize the new order of the friends list
	var arrayOrder = Sortable.sequence('topTenFriendsList'); // get comma separated order
	topTenFriendsListMessage('write', processingImage('topTenFriendsProcessing'), 'nofade');
	agent.call('/inc/ajaxfns.php','topTenFriendsListOrder','AJAXcallbackTopTenFriendsListOrder', arrayOrder);
}

function AJAXcallbackTopTenFriendsListOrder(result){
	if(result == true){
		topTenFriendsListMessage('write', "Your top ten friends list has been rearranged.");
	}
}


function topTenFriendsListMessage(action, message, nofade){
	var messageDIV = document.getElementById('topTenFriendsListMessage');
	if(messageDIV){
		if(action == 'write'){ // write message
			messageDIV.innerHTML = message;
			if(nofade != 'nofade'){ setTimeout('topTenFriendsListMessage(\'fade\')',4000); }	 // set the message to fade out in 5 seconds
		}
		else if(action == 'fade'){ // fade out message
			new Effect.Fade(messageDIV, {duration: 0.8});	
		}
	}else return false;	
}

/*      USERS    */

// update a user's address

function AJAXprocessUserAddress(process){
	var message = document.getElementById('userAddressMessage');

	// process the data -- first get all fields
	// tried to do this as an array, but wouldn't transmit correctly to PHP
	var user_name = document.getElementById('user_name').value;
	var user_address = document.getElementById('user_address').value;
	var user_address2 = document.getElementById('user_address2').value;
	var user_city = document.getElementById('user_city').value;
	var user_state = document.getElementById('user_state').value;
	var user_postalcode = document.getElementById('user_postalcode').value;
	var user_country = document.getElementById('user_country').value;
	
	// then call ajax
	agent.call('/inc/ajaxfns.php','updateUserAddress','AJAXcallbackProcessUserAddress', user_name, user_address, user_address2, user_city, user_state, user_postalcode, user_country);
	// show processing
	message.innerHTML = processingImage('addressProcessing');
}

function AJAXcallbackProcessUserAddress(result){
	var message = document.getElementById('userAddressMessage');
	if(result == 'success' && message){
		message.innerHTML = "Your address has been saved.";
	}
	else if(result == 'failed' && message){
		message.innerHTML = "Your address could not be updated at this time.";
	}
	else if(result == 'invalid' && message){
		message.innerHTML = "Please fill out all required fields.";
	}
}


	// return the code for the animated processing gif, with an id given
function processingImage(elementId){
	return '<img src="../images/processing.gif" alt="Processing..." border="0" id="'+elementId+'" />';
}

function AJAXdeleteProfileBackgroundImage(result){
	var del = document.getElementById('deleteProfileBackgroundImageLink');
	if(del){
		if(result == 'failed' || result == 'success'){
			if(result == 'success'){ del.innerHTML = '<b>The image has been deleted</b>'; }
			else if(result == 'failed'){ del.innerHTML = '<b>The image could not be deleted at this time</b>'; }
		}
		else{ agent.call('/inc/ajaxfns.php','deleteProfileBackgroundImage','AJAXdeleteProfileBackgroundImage'); del.innerHTML = processingImage('delBGImage');  }
	}
}


/*   UPLOAD ART  */

 // for showing the correct media upload options (depending on medium selected)
function itemMediaOptions(writing_id, music_id, photography_id, filmmaking_id, computer_arts_id){
	var mediumSelect = document.getElementById('medium_id');
	if(mediumSelect.value == 0){
		var mediumSelect = document.getElementById('non_artist_medium_id');
	}
	var selectedMedium = mediumSelect.options[mediumSelect.selectedIndex].value;
	var label = document.getElementById('mediaTitle');	
	var upload = document.getElementById('mediaUploadBox');
	var typeOfArt = document.getElementById('typeOfArt');
	var itemDescription = document.getElementById('item_description');
	var itemDescriptionLabel = document.getElementById('item_description_label');
	var copyright = document.getElementById('user_medium_copyright').value;
	var uploadForm = document.getElementById('uploadForm');
	var pbf = document.getElementById('progress_bar_form');
	var YouTubeForm = '<div id="YouTubeUrl">YouTube Url: <input type="text" size="30" name="youtube_url" id="youtube_url" onblur="AJAXvalidateYouTubeUrl(\'youtube_url\');"><span id="youtube_url_message"></span></div>';
	var imgUploadLabel = document.getElementById('image_upload_title');
	if(label && upload && typeOfArt && itemDescription && itemDescriptionLabel){
		if(selectedMedium == ''){
			uploadForm.setAttribute('style', 'visibility: hidden;');
			new Element.hide(uploadForm);
			pbf.setAttribute('style', 'visibility: hidden;');
			new Element.hide(pbf);
		}else{
			uploadForm.setAttribute('style', 'visibility: visible; display: inherit;');
			new Element.show(uploadForm);
			pbf.setAttribute('style', 'visibility: visible; display: inherit;');
			new Element.show(pbf);
		}
		// turn copyright info into array
		copyrightArray = new Array();
		copyrightArray = copyright.split(','); // split into array
		
		if(in_array(copyrightArray, selectedMedium)){ // if in the array, show digital upload as an option
			new Element.show('digitalDownload');
		}else{
			new Element.hide('digitalDownload');
		}
		if(selectedMedium == computer_arts_id){
			typeOfArt.setAttribute('style', '');
		}else{ typeOfArt.setAttribute('style', 'display:none;'); }

		if(selectedMedium == writing_id){
			label.innerHTML = 'The Art (Text file):';
			upload.innerHTML = '<input type="file" name="upfile_0" size="40">&nbsp;<span class="optional">.pdf document</span>';
			itemDescription.setAttribute('rows', 20);
			itemDescriptionLabel.innerHTML = '*Text (or excerpt):';
			hideAndShow('image_upload', 'hidden'); // make alternate media upload invisible
		}
		else{
			imgUploadLabel.innerHTML = 'Image to represent the art:';
			if(selectedMedium == music_id){
				label.innerHTML = '*The Art (MP3 File):';
				upload.innerHTML = '<input type="file" name="upfile_0" size="40">&nbsp;<span class="optional">.mp3 file</span>';
				imgUploadLabel.innerHTML = 'Cover Art:';
				hideAndShow('image_upload', 'visible'); // make alternate (album art) upload visible	
			}else if(selectedMedium == filmmaking_id){
				label.innerHTML = '*The Art (Video File):';	
				upload.innerHTML = '<input type="file" name="upfile_0" size="40">&nbsp;<span class="optional">.mov or .wmv file</span><br />OR '+YouTubeForm;
				hideAndShow('image_upload', 'visible'); // make alternate (album art) upload visible	
				// if they have 
			}
			else if(selectedMedium == photography_id){
				label.innerHTML = '*The Art (Image File):';	
				upload.innerHTML = '<input type="file" name="upfile_0" size="40">&nbsp;<span class="optional">.jpg .png .gif</span>';
				hideAndShow('image_upload', 'hidden'); // make alternate (album art) upload hidden	
			}
			else{
				label.innerHTML = '*The Art (Media File):';	
				upload.innerHTML = '<input type="file" name="upfile_0" size="40">&nbsp;<span class="optional">picture, video, audio</span>';
				hideAndShow('image_upload', 'hidden'); // make alternate (album art) upload hidden
			}
			itemDescription.setAttribute('rows', 6);
			itemDescriptionLabel.innerHTML = 'Description:';
		}
	}
}

function AJAXvalidateYouTubeUrl(elementId){
	var url = document.getElementById(elementId);
	var urlMessage = document.getElementById(elementId+'_message');
	if(url && urlMessage){
		agent.call('/inc/ajaxfns.php','validateYouTubeUrl','AJAXcallbackValidateYouTubeUrl', url.value, elementId);	
	}
}

function AJAXcallbackValidateYouTubeUrl(obj){
	var url = document.getElementById(obj[1]);
	var urlMessage = document.getElementById(obj[1]+'_message');
	if(obj[0] == 'success'){
		urlMessage.innerHTML = 'Awesome!';
		url.value = obj[2];
	}else{
		urlMessage.innerHTML = 'Sorry, that video is not available.';
		url.value = '';
	}
}


function in_array(arr, needle){
	for(var i=0;i<arr.length;i++)
	if(arr[i] == needle) return true;
	return false;	
}

/*    MEDIA COLLECTION FUNCTIONS   */

function addMediaUpload(mediaContainer, count){
	var container = document.getElementById(mediaContainer);
	var count = document.getElementById(count);
	if(container && count.value){
		var newCount = count.value + 1;
		container.innerHTML += '<tr id="media_'+newCount+'" style="display:none;"><td><input type="file" name="media_'+newCount+'"></td><td><input type="text" name="media['+newCount+'][title]" size="25"></td><td><input type="text" name="media['+newCount+'][raw_tags]" size="25"></td></tr>';
		new Effect.Appear(document.getElementById('media_'+newCount), { duration: 0.8});
		count.value = newCount;
	} else return false;
}

function AJAXdeleteMediaItem(action, elementId, mcId, mediaId, userId){
	var mediaElement = document.getElementById(elementId);
	var mediaMessage = document.getElementById(elementId+'_message');
	if(mediaElement && mediaId && userId){
		if(action == 'cancel'){
			new Effect.Appear(mediaElement, { duration: 0.5, to: 1.0});
			mediaMessage.innerHTML = '';
		}
		else if(action == 'confirmed'){
			agent.call('/inc/ajaxfns.php','deleteImageFromAlbum','AJAXcallbackDeleteMediaItem', elementId, mcId, mediaId, userId);
		}
		else{
			new Effect.Fade(mediaElement, { duration: 0.3, to: 0.3});	
			mediaMessage.innerHTML = 'Are you sure you want to delete this picture?<br /><input type="submit" name="submit" value="yes, delete it" onclick="AJAXdeleteMediaItem(\'confirmed\', \''+elementId+'\', '+mcId+', '+mediaId+', '+userId+'); return false;" class="submit">&nbsp;&nbsp;&nbsp;<input type="reset" name="reset" value="cancel" class="reset" onclick="AJAXdeleteMediaItem(\'cancel\', \''+elementId+'\', '+mcId+', '+mediaId+', '+userId+'); return false;">';
		}
	}
}

	/* fade out media item if it was deleted */
function AJAXcallbackDeleteMediaItem(elementId){
	if(elementId != false){
		var mediaElement = document.getElementById(elementId);
		var mediaMessage = document.getElementById(elementId+'_message');
		new Effect.Fade(mediaElement, { duration: 0.8});
		mediaMessage.innerHTML = '';
	}
}

 /*    PLAYLIST    */

function flashMP3Player(a, mediaId, userId, type){
	if(a == 'loadXML'){ // load the XML file
		var url = 'http://www.selfportrait.net/playlist.php?a=xml';
		if(userId){ url = url+'&u='+userId; }
		if(type == 'mixtape'){ url = url+'&type=mixtape'; }
		parent.frames[1].controlPlayer('load', url);
	}
	else if(a == 'loadOneItem' && mediaId){ // load just one song with data
		if(type == 'inIframe'){
			parent.parent.frames[1].controlPlayer('load','http://www.selfportrait.net/playlist.php?media_id='+mediaId);
		}else{
			parent.frames[1].controlPlayer('load','http://www.selfportrait.net/playlist.php?media_id='+mediaId);
		}
	}
	else if(a == 'pause'){
		parent.frames[1].controlPlayer('pause')	;
	}
	else if(a == 'playItem'){ // reload playlist and play a specific item
		flashMP3Player('loadXML', '', userId, type);
		setTimeout('parent.frames[1].controlPlayer(\'play\','+mediaId+')', 1000);
	}
}

function playNow(mediaId, inIframe){
	var playLink = document.getElementById('playNow'+mediaId);
	if(playLink){
		flashMP3Player('loadOneItem', mediaId, '', inIframe);
		//playLink.innerHTML = '<a href="#" onclick="playNow('+mediaId+'); return false;"><img src="../images/tango/media-playback-start.gif" alt="Play Now" border="0" style="vertical-align: bottom;" /></a>';
	}
}

function AJAXaddToPlaylist(mediaId){
	agent.call('/inc/ajaxfns.php','addToPlaylist','AJAXcallbackAddToPlaylist', mediaId);
}

	// obj[0] is status, obj[1] is media id
function AJAXcallbackAddToPlaylist(obj){
	var addLink = document.getElementById('addToPlaylist'+obj[1]);
	if(obj[0] == 'success'){
		addLink.innerHTML = '<a href="#" onclick="AJAXdeleteFromPlaylist('+obj[1]+'); return false;"><img src="../images/x.gif" alt="Remove From My Playlist" border="0" style="vertical-align: bottom;" /></a>';	
	}else if(obj[0] == 'limit'){
		alert('Your playlist has reached the limit of '+obj[2]+' songs.  Please remove one to add this song.');
	}else if(addLink){
		// unsuccessfull
		addLink.innerHTML = '<b>Couldn\'t be added</b>';
	}
}
 
function AJAXdeleteFromPlaylist(mediaId){
	agent.call('/inc/ajaxfns.php','deleteFromPlaylist','AJAXcallbackDeleteFromPlaylist', mediaId);
}

 // obj[0] is status, obj[1] is media id
 function AJAXcallbackDeleteFromPlaylist(obj){
	var delItem = document.getElementById('playlistItem'+obj[1]); // this is on the profile page
	var playlistMessage = document.getElementById('playlistMessage');
	var addItem = document.getElementById('addToPlaylist'+obj[1]); // this means it's on their profile
	if(obj[0] == true){
		if(delItem){
			new Effect.Fade(delItem, { duration: 0.8});
			flashMP3Player('loadXML'); // reload the XML file
		}
		else if(addItem){
			addItem.innerHTML = '<a href="#" onclick="AJAXaddToPlaylist('+obj[1]+'); return false;"><img src="../images/cassette.gif" height="18" alt="Save To My Playlist" border="0" style="vertical-align: bottom;" /></a>';	
		}
	}else if(playlistMessage){
		// unsuccessfull
		playlistMessage.innerHTML = '<b>The song could not be removed from your playlist at this time.</b>';
	}
}

function AJAXaddToProfilePlaylist(mediaId){
	agent.call('/inc/ajaxfns.php','addToProfilePlaylist','AJAXcallbackAddToProfilePlaylist', mediaId);
}

	// obj[0] is success or failure, obj[1] is media id
function AJAXcallbackAddToProfilePlaylist(obj){
	var addLink = document.getElementById('addToProfilePlaylist'+obj[1]);
	if(obj[0] == 'success'){
		addLink.innerHTML = '<b>Added</b>';	
	}
}

function AJAXdeleteFromProfilePlaylist(mediaId){
	agent.call('/inc/ajaxfns.php','deleteFromProfilePlaylist','AJAXcallbackDeleteFromProfilePlaylist', mediaId);
}

	// obj[0] is success or failure, obj[1] is media id
function AJAXcallbackDeleteFromProfilePlaylist(obj){
	var mixtapeItem = document.getElementById('mixtapeItem'+obj[1]);
	if(obj[0] == 'success'){
		new Effect.Fade(mixtapeItem, { duration: 0.5});
	}
}

 /* take the array of ids, and save the resorted friends list */
function AJAXmixtapeOrder(){
	 // serialize the new order of the friends list
	var arrayOrder = Sortable.sequence('mixtape'); // get comma separated order
	playlistMixtapeMessage('mixtape', 'write', processingImage('mixtapeProcessing'), 'nofade');
	agent.call('/inc/ajaxfns.php','mixtapeOrder','AJAXcallbackMixtapeOrder', arrayOrder);
}

function AJAXcallbackMixtapeOrder(result){
	if(result == true){
		playlistMixtapeMessage('mixtape', 'write', "Your mixtape has been rearranged.");
	}
}

 /* take the array of ids, and save the resorted friends list */
function AJAXplaylistOrder(){
	 // serialize the new order of the friends list
	var arrayOrder = Sortable.sequence('playlist'); // get comma separated order
	playlistMixtapeMessage('playlist', 'write', processingImage('playlistProcessing'), 'nofade');
	agent.call('/inc/ajaxfns.php','playlistOrder','AJAXcallbackPlaylistOrder', arrayOrder);
}

function AJAXcallbackPlaylistOrder(result){
	if(result == true){
		playlistMixtapeMessage('playlist', 'write', "Your playlist has been rearranged.");
	}
}

function playlistMixtapeMessage(type, action, message, nofade){
	var messageDIV = document.getElementById(type+'Message');
	if(messageDIV){
		if(action == 'write'){ // write message
			messageDIV.innerHTML = message;
			if(nofade != 'nofade'){ setTimeout('playlistMixtapeMessage(\''+type+'\',\'fade\')',4000); }	 // set the message to fade out in 5 seconds
		}
		else if(action == 'fade'){ // fade out message
			new Effect.Fade(messageDIV, {duration: 0.8});	
		}
	}else return false;	
}

 /*  ADDING TAGS  */
 
 function AJAXaddTags(elementId, mediaId){
	var newTags = document.getElementById(elementId+'_field_input');
	if(newTags.value != ''){
		agent.call('/inc/ajaxfns.php','addTags','AJAXcallbackAddTags', newTags.value, mediaId, elementId);
	}
 }
 
 // obj[0] is the elementId to change the tags on, obj[1] is the new list of tags
 function AJAXcallbackAddTags(obj){
	var tags = document.getElementById(obj[0]);
	var tagField = document.getElementById(obj[0]+'_field');
	var tagFieldInput = document.getElementById(obj[0]+'_field_input');
	var tagAddLink = document.getElementById(obj[0]+'_addlink');
	if(tags){
		tags.innerHTML = obj[1]; 
		tagFieldInput.value = '';
		new Effect.Fade(tagField, { duration: 0.0});
		Effect.Appear(tagAddLink, { duration: 0.5});
		
	}
 }

 /* DELETING TAGS */

function AJAXdeleteTag(tagId){
	agent.call('/inc/ajaxfns.php','deleteTag','AJAXcallbackDeleteTag', tagId);
}

function AJAXcallbackDeleteTag(tagId){
	var tagElement = document.getElementById('tag_'+tagId);
	if(tagId && tagElement){
		new Effect.Fade(tagElement, { duration: 0.8});
	}
}

/* CALENDAR */

function cal_setup()
{
/*
	var buttons = document.getElementsByTagName('BUTTON');
	for (var i = 0; i < buttons.length; i++)
	{
		var id = buttons[i].id;
		var expr = /^jscal_trigger_(.*)+$/;
		if (!id.match(expr))
		{
			continue;
		}
		var jscal_uniqid = expr.exec(id)[1];
		var exp = expr.exec(id);
		Calendar.setup({
			inputField     :    'jscal_field_' + jscal_uniqid, // id of the input field
			button         :    'jscal_trigger_' + jscal_uniqid, // trigger for the calendar (button ID)
			ifFormat       :    "%Y-%m-%d %H:%M:%S",       // format of the input field
			showsTime      :    true,
			timeFormat     :    "24",
			weekNumbers    :    false,
			step           :    1
			});
	}
*/
	if (!document.getElementById('jscal_field_438a344851d04') || !document.getElementById('jscal_field_438a344851d05')) return;
	Calendar.setup({
		inputField     :    'jscal_field_438a344851d04', // id of the input field
		button         :    'jscal_trigger_438a344851d04', // trigger for the calendar (button ID)
		ifFormat       :    "%Y-%m-%d %H:%M:%S",       // format of the input field
		showsTime      :    true,
		timeFormat     :    "24",
		weekNumbers    :    false,
		step           :    1
		});
	Calendar.setup({
		inputField     :    'jscal_field_438a344851d05', // id of the input field
		button         :    'jscal_trigger_438a344851d05', // trigger for the calendar (button ID)
		ifFormat       :    "%Y-%m-%d %H:%M:%S",       // format of the input field
		showsTime      :    true,
		timeFormat     :    "24",
		weekNumbers    :    false,
		step           :    1
		});
	
}


function AJAXcallChangeEvents(uid)
{
	agent.call('/inc/ajaxfns.php', "cal_changeEvents", "AJAXcallbackCalMove", uid);
}

function AJAXcallCalMove(month, year)
{
  agent.call('/inc/ajaxfns.php', "cal_moveSmall", "AJAXcallbackCalMove", month, year);
}
function AJAXcallbackCalMove(obj)
{
  var str = ""+obj;
  document.getElementById("divCalendar").innerHTML = str;
}
function AJAXcallRSVP(id, rsvp)
{
  agent.call('/inc/ajaxfns.php', "cal_RSVP", "AJAXcallbackEventDetails", id, rsvp);
}
function AJAXcallEventDetails(id)
{
  agent.call('/inc/ajaxfns.php', "cal_eventDetails", "AJAXcallbackEventDetails", id);
}
function AJAXcallbackEventDetails(obj)
{
  var str = ""+obj;
  var div = document.getElementById("divEventDetails");
  
  /*if (str != "" && div.innerHTML != "")
    {
      new Effect.Fade("divEventDetails", {duration: .5, queue: {position:'end', scope:'ded', limit:2}});
      new Effect.Appear("divEventDetails", {duration: .5, queue: {position:'end', scope:'ded', limit:2}});
      setTimeout('AJAXcallbackEventDetailsHelper(div, str)',500);

      
    }
    else */if (str != "&nbsp;")
    {
      div.innerHTML = str;
      new Effect.Appear("divEventDetails", {duration: .5});
    }

  else if (str == "&nbsp;" && div.innerHTML != "")
    {
	  new Effect.Fade("divEventDetails", {duration: .5});
    }

}
/*
function AJAXcallbackEventDetailsHelper(div, str)
{
  div.innerHTML = str;
}
*/
function AJAXcallEventsList(month, year, limit, startDay, endDay)
{
  agent.call('/inc/ajaxfns.php', "cal_eventsList", "AJAXcallbackEventsList", month, year, limit, startDay, endDay);
}
function AJAXcallbackEventsList(obj)
{
  var str = ""+obj;
  var div = document.getElementById("divEventsList");
  div.innerHTML = str;
}

function AJAXcallAddEvent()
{
  agent.call('/inc/ajaxfns.php', "cal_addEvent", "AJAXcallbackAddEvent");
}

function AJAXcallbackAddEvent(obj)
{
  AJAXcallbackEventDetails(obj);
  cal_setup();
}
function AJAXcallEditEvent(id)
{
  agent.call('/inc/ajaxfns.php', "cal_editEvent", "AJAXcallbackEditEvent", id);
 
}
function AJAXcallbackEditEvent(obj)
{
  AJAXcallbackEventDetails(obj);
  cal_setup();
}
function AJAXcallDoEditEvent()
{
  elements = Form.getElements("eventForm");
  var values = new Object();
  for(i = 0; i < elements.length; i++) {
    element = elements[i];
    if (element.name != '')
    values[element.name] = element.value;
    }
  agent.call('/inc/ajaxfns.php', "cal_doEditEvent", "AJAXcallbackEditEvent", values);
  agent.call('/inc/ajaxfns.php', "AJAXHELPERrefresh", "AJAXcallbackCalMove", "cal_refresh");
}

function AJAXcallDoAddEvent()
{
  elements = Form.getElements("eventForm");
  var values = new Object();
  for(i = 0; i < elements.length; i++) {
    element = elements[i];
    if (element.name != '')
    values[element.name] = element.value;
    }
  agent.call('/inc/ajaxfns.php', "cal_doAddEvent", "AJAXcallbackAddEvent", values);
  agent.call('/inc/ajaxfns.php', "AJAXHELPERrefresh", "AJAXcallbackCalMove", "cal_refresh");
}

function AJAXcallDeleteEvent(id)
{
  agent.call('/inc/ajaxfns.php', "cal_deleteEvent", "AJAXcallbackEventDetails", id);
}
function AJAXcallDoDeleteEvent(id)
{
  agent.call('/inc/ajaxfns.php', "cal_doDeleteEvent", "AJAXcallbackEventDetails", id);
  agent.call('/inc/ajaxfns.php', "AJAXHELPERrefresh", "AJAXcallbackCalMove", "cal_refresh");
}

/* SHOPPING CART */

// empties the shopping cart
function cartEmpty(){
	var cart = document.getElementById('shoppingCart');
	cart.innerHTML = '';
	cartMessage('show', 'Your shopping cart is empty.  Fill it with some awesome art!', 'nofade');
}

function cartUpdateTotals(newQty, newSubtotalPrice, newTotalShipping, newTotalPrice){
	var totalQty = document.getElementById('cart_total_qty');
	var subtotalPrice = document.getElementById('cart_subtotal_price');
	var totalShipping = document.getElementById('cart_total_shipping');
	var totalPrice = document.getElementById('cart_total_price');
	if(totalQty && subtotalPrice && totalShipping && totalPrice){
		totalQty.innerHTML = newQty;
		subtotalPrice.innerHTML = newSubtotalPrice;
		totalShipping.innerHTML = newTotalShipping;
		totalPrice.innerHTML = newTotalPrice;
	}
}

function cartMessage(a, msg, nofade){
	var message = document.getElementById('shoppingCartMessage');
	if(a == 'show'){
		new Effect.Fade(message, { duration: 0.0});
		message.innerHTML = msg;
		new Effect.Appear(message, { duration: 0.5});
		if(nofade != 'nofade'){ setTimeout('cartMessage(\'fade\')',7000);	} // set the message to fade out in 5 seconds
	}
	else if(a == 'fade'){
		new Effect.Fade(message, { duration: 0.8});
	}
}

function AJAXcartRemoveItem(artId, title){
	agent.call('/inc/ajaxfns.php', "cartRemoveItem", "AJAXcallbackCartRemoveItem", artId, title);
}
	// obj[0] is the art_id, obj[1] is the title of the piece, obj[2] is the count of items in the cart - the rest is more cart totals
function AJAXcallbackCartRemoveItem(obj){
	if(obj != false){
		if(obj[2] < 1){
			cartEmpty();
		}else{
			cartUpdateTotals(obj[2], obj[3], obj[4], obj[5]);
			var deleteItem = document.getElementById('cart_'+obj[0]);
			cartMessage('show','"'+obj[1]+'" has been removed from your shopping cart.');
			new Effect.Fade(deleteItem, { duration: 0.8});
		}
	}
}

function AJAXcartChangeQuantity(itemId, title){
	var qty = document.getElementById('cart_'+itemId+'_qty');
	if(IsNumeric(qty.value) || qty.value == ''){
		qty.setAttribute('style', '');
		agent.call('/inc/ajaxfns.php', "cartChangeQuantity", "AJAXcallbackCartChangeQuantity", itemId, title, qty.value);
	}else{ cartMessage('show', 'You need to enter a numeric value for the quantity.'); qty.value = ''; qty.setAttribute('style', 'background-color: #FFFF99;'); }
}
	// obj[0] is item id, obj[1] is new qty, obj[2] is the title, obj[3] is the count of items in the cart, the rest is more cart totals
function AJAXcallbackCartChangeQuantity(obj){
	if(obj != false){
		var qty = document.getElementById('cart_'+obj[0]+'_qty');
		if(obj[3] == 'maxqty'){ // entered above a max quantity for an item
				cartMessage('show','There is only a quantity of <b>'+obj[4]+'</b> available of "'+obj[2]+'":', 'nofade');
				qty.setAttribute('style', 'background-color: #FFFF99;');
				qty.value = '';
		}
		else if(obj[3] == 'digiqty'){
			cartMessage('show','You only need to buy one of each item for a digital download.', 'nofade');
			qty.value = '1';
		}
		else if(obj[3] < 1){ // if total qty is less than 1, empty cart
			cartEmpty();	
		}
		else{
			cartMessage('show','The quantity of "'+obj[2]+'" has been changed:');
			qty.value = obj[1];
			cartUpdateTotals(obj[3], obj[4], obj[5], obj[6]);
		}
	}
}

/*   ORDERS    */

function AJAXupdateOrderStatusItem(itemId, orderId){
	// first get selected item	
	var hiddenStatus = document.getElementById('hiddenOrderStatusItem'+itemId);
	var selectBox = document.getElementById('orderStatusItem'+itemId);
	var message = document.getElementById('orderStatusItem'+itemId+'Message');
	if(selectBox){
		var status = selectBox.options[selectBox.selectedIndex].value;
		if(status == 'x'){
			var answer = confirm("Are you sure you want to refund this item? The purchase amount will be credited to the buyer's account.")
		}else{
			answer = true;
		}
		
		if(answer){
			hiddenStatus.value = status;
			agent.call('/inc/ajaxfns.php', "orderUpdateItemStatus", "AJAXcallbackUpdateOrderStatusItem", status, itemId, orderId);
			message.innerHTML = processingImage('orderStatusItem'+itemId+'Processing');
		}else{
			selectBox.selectedIndex = hiddenStatus.value;
		}
	}
}

// obj[0] is array(success or failure, message) obj[1] is item id, obj[2] is status
function AJAXcallbackUpdateOrderStatusItem(obj){
	var selectBox = document.getElementById('orderStatusItem'+obj[1]);
	var message = document.getElementById('orderStatusItem'+obj[1]+'Message');
	var hiddenStatus = document.getElementById('hiddenOrderStatusItem'+obj[1]);
	
	if(obj[0][0] == 'Success' || obj[0][0] == 'SuccessWithWarning'){
		if(selectBox){
			selectBox.options[selectBox.selectedIndex].value = obj[2];
			hiddenStatus.value = selectBox.selectedIndex;
			message.innerHTML = obj[0][1];
		}
	}else{
		if(selectBox){
			selectBox.selectedIndex = hiddenStatus.value;
			message.innerHTML = '<br />'+obj[0][1];
		}
	}
}


/*  COMMENTS  */

function AJAXeditComment(a, commentId){
	var comment = document.getElementById('comment_'+commentId);
	var commentEdit = document.getElementById('comment_'+commentId+'_edit');
	var commentDelete = document.getElementById('comment_'+commentId+'_delete');
	if(comment && commentId && commentDelete){
		if(a == 'displayEdit' && commentEdit){ // display editing box
			new Element.hide(comment);
			Element.show(commentEdit);
		}
		else if(a == 'cancelEdit'  && commentEdit){ // cancel the edit
			new Element.hide(commentEdit);
			Element.show(comment);
		}
		else if(a == 'submitEdit' && commentEdit){ // submit the comments via AJAX
			var commentValue = document.getElementById('commentForm_'+commentId+'_content');
			var commentColor = getValueRadioButton('commentForm_'+commentId, 'comment_color');
			if(commentColor == -1){ commentColor = ''; }
			agent.call('/inc/ajaxfns.php', "commentEdit", "AJAXcallbackEditComment", commentId, commentValue.value, commentColor);
		}
		else if(a == 'displayDelete'){ // prompt if they want to delete the comment
			new Element.hide(comment);
			Element.show(commentDelete);
		}
		else if(a == 'confirmDelete'){ // use AJAX to delete the comment
			agent.call('/inc/ajaxfns.php', "commentDelete", "AJAXcallbackDeleteComment", commentId);
		}
		else if(a == 'cancelDelete'){
			new Element.hide(commentDelete);
			Element.show(comment);
		}
	}
}
	// obj[0] is comment id, obj[1] is value, obj[2] is color
function AJAXcallbackEditComment(obj){
	if(obj[1] != false){
		var commentContent = document.getElementById('comment_'+obj[0]+'_content');
		if(obj[2] != false){
			var comment = document.getElementById('comment_'+obj[0]);
			comment.setAttribute('class', obj[2]);
			comment.setAttribute('className', obj[2]); // for IE
		}
		commentContent.innerHTML = obj[1];
		AJAXeditComment('cancelEdit', obj[0]);
	}else{ // failed edit
		AJAXeditComment('cancelEdit', obj[0]);
	}
}

	//  obj[0] is the comment id, obj[1] is success or failure
function AJAXcallbackDeleteComment(obj){
	if(obj[1] == 'success'){
		var commentDelete = document.getElementById('comment_'+obj[0]+'_delete');
		new Effect.Fade(commentDelete, {duration: 0.5});
	}
	else{
		AJAXeditComment('cancelDelete', obj[0]);
	}
}

	 // loops through radio buttons to find the one that is selected
function getValueRadioButton(formName, buttonName){
	var radioButton = eval('document.'+formName+'.'+buttonName);
	var intValue = -1;
    try{
        //determine radio value
        for (x = 0; x <= radioButton.length; x++){
            if (radioButton[x].checked == true) {
                intValue = radioButton[x].value; 
                break;
            }
        } 
    }
    catch(e){
        //there has been an error (most likely because no selection was made)
        // return not found value (-1 in this case)
        intValue = false;
    }
    // if it didn't find anything, return the .value  (behaviour of single radio btn)
    return intValue;
	
}

function readMore(elementId){
	var moreText = document.getElementById(elementId);
	var moreTextLink = document.getElementById(elementId+'Link');
	if(moreText && moreTextLink){
		new Effect.Fade(moreTextLink, {duration: 0.3});
		Effect.Appear(moreText, {duration: 0.5});
	}
}

/*   MESSAGING   */

function areYouSureLink(linkID, spanID, path){ // activates an <A href> tag - that has an id elementId, with the path provided
	var alink = document.getElementById(linkID);
	var aspan = document.getElementById(spanID);
	if(alink && aspan){
		alink.innerHTML = "";
		aspan.innerHTML = "<strong style=\"color: red;\">are you sure?</strong> <a id=\""+linkID+"\" href=\""+path+"\">yes</a>/<a href=\"#\" onclick=\"notSureLink('"+spanID+"', '"+path+"'); return false;\">no</a>";
	}
}

function notSureLink(spanID, path)
{
	var aspan = document.getElementById(spanID);
	if(aspan){
		aspan.innerHTML = "<a id=\"deletelink\" href=\""+path+"\" onclick=\"areYouSureLink('deletelink', 'deletespan', '"+path+"'); return false;\">delete</a>";
	}
}

/*   FEEDBACK   */
function AJAXsaveFeedback(Id, user){
	var orderId = document.getElementById('order_id_'+Id).value;
	var receiver = document.getElementById('feedback_receiver_'+Id).value;
	if(Id.indexOf('new') != -1){ // process new feedback
		var content = document.getElementById('feedback_content_'+Id).value;
		var rating = getValueRadioButton('feedback_'+Id, 'feedback_rating_'+Id); if(rating === false){ rating = ''; }
		var userRole = document.getElementById('user_role').value;
		agent.call('/inc/ajaxfns.php', "saveFeedback", "AJAXcallbackSaveFeedback", Id, orderId, receiver, userRole, content, rating);
	}else{ // process edited feedback
		if(user == 'giver'){ // the person is giving feedback
			var content = document.getElementById('feedback_content_'+Id).value;
			var rating = getValueRadioButton('feedback_'+Id, 'feedback_rating_'+Id); if(rating === false){ rating = ''; }
			agent.call('/inc/ajaxfns.php', "saveFeedback", "AJAXcallbackSaveFeedback", Id, orderId, receiver, '', content, rating);
		}
		else if (user == 'receiver'){  // the person is responding to feedback
			var response = document.getElementById('feedback_response_'+Id).value;
			agent.call('/inc/ajaxfns.php', "saveFeedback", "AJAXcallbackSaveFeedback", Id, orderId, receiver, '', '', '', response);
		}
	}
}
	// obj[0] is failure or success, obj[1] is id, obj[2] is code for display (if successful)
function AJAXcallbackSaveFeedback(obj){
	var message = document.getElementById('feedback_message_'+obj[1]);
	var feedbackForm = document.getElementById('feedback_form_'+obj[1]);
	if(feedbackForm && obj[0] == 'success'){
		feedbackForm.innerHTML = obj[2].replace('\\\\', ''); // strip slashes
	}
	else if(message && obj[0] == 'invalid'){
		message.innerHTML = 'Please fill out all of the fields:';
	}
	else if(message){
		message.innerHTML = 'Your feedback could not be processed at this time.';
	}
}


/*  IMAGE MANIPULATION & PRELOADING  */

function preloadImageArray(arr){
	if(typeof(arr)=='object'){
		var i = 0;
		for(i=0;i< arr.length;i++){
			var myImage = new Image;
			myImage.src = arr[i];
		}
	}
}


// to navigate an array of images -- the id is what the ID of all nav elements is prefixed with
// basically changes one image with a new url
function navigateImageArray(id, at, url){
	var imgUrls = document.getElementById('imgArrayValues'+id).value;
	var ids = document.getElementById('imgArrayKeys'+id).value;
	var key = document.getElementById('key'+id).value;
	var prevLink = document.getElementById('prevLink'+id);
	var nextLink = document.getElementById('nextLink'+id);
	var imgLink = document.getElementById('imgLink'+id);
	var img = document.getElementById('img'+id);
	
	if(prevLink && nextLink && img && imgUrls){
		
		// get list of imgs
		imgArray = new Array();
		imgArray = imgUrls.split(','); // split into array
		
		if(ids){
			// get list of ids
			idArray = new Array();
			idArray = ids.split(',');
		}
		
		// preload images
		preloadImageArray(imgArray);
		
		// first assign prev, next links
		var maxValue = imgArray.length - 1;
		if(at == 0){ prevLink.setAttribute('onclick', 'javascript: navigateImageArray(\''+id+'\', '+maxValue+', \''+url+'\'); return false;'); }
		else{ prevLink.setAttribute('onclick', 'javascript: navigateImageArray(\''+id+'\', '+(at - 1)+', \''+url+'\'); return false;'); }
		if(at == maxValue){ nextLink.setAttribute('onclick', 'javascript: navigateImageArray(\''+id+'\', 0, \''+url+'\'); return false;'); }
		else{ nextLink.setAttribute('onclick', 'javascript: navigateImageArray(\''+id+'\', '+(at + 1)+', \''+url+'\'); return false;'); }
		// now write the img src
		img.setAttribute('src', imgArray[at]);
		// set the image link
		if(imgLink && idArray){
			imgLink.setAttribute('href', url+'?'+key+'='+idArray[at]);
		}
	}
	
}

	// when you mouseover an image, it changes the target image with the url supplied in the list of image urls
	// id is the unique id added to each field id, and key is the numerical key of the array to fetch the value for
function mouseImageArray(id, key, targetImage){
	var imgUrls = document.getElementById('imgArrayValues'+id).value;
	var targetImage = document.getElementById(targetImage);
	if(imgUrls && targetImage){	
		// get list of imgs
		imgArray = new Array();
		imgArray = imgUrls.split(','); // split into array
	
		if(imgArray[key]){
			setImgSrc(targetImage, imgArray[key]);
		}
	}
}


function setImgSrc(elementId, url, delay){
	var image = document.getElementById(elementId);
	if(image && url){
		if(delay){ // delay changing url for this many seconds
			setTimeout('setImgSrc(\''+elementId+'\', \''+url+'\')', delay+'000');
		}else{  image.setAttribute('src', url);  }
	} 
}


/// NETWORKS

function addNetworkToField(li){

	// get the network ID and name from the li, and populate the page with them
	var networkID = document.getElementById('network_id');
	var networkName = document.getElementById('network_name');
	var addUser = document.getElementById('network_add_user');
	if(networkID && networkName){
		
		// extract network name
		var searchString = '<span id="element">';
		var startName = li.innerHTML.indexOf(searchString);
		var endName = li.innerHTML.indexOf('</span>');
		if(endName - startName > 0){
			networkName.value = li.innerHTML.substring(startName + searchString.length, endName);
		}
		networkID.value = li.getAttribute('id');
		
		if(addUser.value == 'adduser'){ // now add the user to the network
			agent.call('/inc/ajaxfns.php', "addUserToNetwork", "AJAXcallbackAddUserToNetwork", networkID.value);
		}
	}
}

function AJAXcallbackAddUserToNetwork(result){
	var networkMessage = document.getElementById('network_message');
	if(networkMessage){
		if(result == true){
			networkMessage.innerHTML = 'Added!';
		}
		else{ networkMessage.innerHTML = '<span style="color: #CC0000;">You could not be added</span>'; }
	}
}

/// CITIES

function addCityToField(li){

	// get the network ID and name from the li, and populate the page with them
	var cityID = document.getElementById('city_id');
	var cityName = document.getElementById('city_name');
	if(cityID && cityName){
		if(li.id){cityID.value = li.id; }
		agent.call('/inc/ajaxfns.php', "addUserToCity", "AJAXcallbackAddUserToCity", li.id);
	}
}

function AJAXcallbackAddUserToCity(result){
	var cityMessage = document.getElementById('city_message');
	var cityDisplay = document.getElementById('city_display');
	if(cityMessage){
		if(result == 0){
			cityMessage.innerHTML = '<span style="color: #CC0000;">Sorry, your city could not be selected at this time.</span>';
		}else{ 
			cityDisplay.innerHTML = '<span id="city_selected">' + result + '&nbsp;&nbsp;<span style="color: #666;">[<a href="#" onclick="Effect.Appear(\'city_select\'); Element.hide(\'city_selected\'); return false;">change</a>]</span></span>'; 
			new Element.hide('city_select');
		}
	}
}

function validateForCitySelection(){
	var cityID = document.getElementById('city_id');
	if(cityID && cityID.value.length > 0){
		return true;
	}else return false;
}

//// SEARCH

function showSearch(selectElement){
	getVarSelect = document.getElementById(selectElement);
	getValue = getVarSelect.options[getVarSelect.selectedIndex].value;
	var searchForm = document.getElementById(getValue+'Form');
	var formShowing = document.getElementById('searchTypeSelected');
	var searchFormSpan = document.getElementById('searchFormSpan');
	if(searchForm && searchFormSpan){
		new Effect.Fade(formShowing.value, { duration: 0});
		searchFormSpan.innerHTML = searchForm.innerHTML;
		new Effect.Appear(searchFormSpan, { duration: 0.8 });
		formShowing.value = getValue+'Form';
	}	
}

function appear(element){
	var eid = document.getElementById(element);
	new Effect.Appear(eid, { duration: 0.5 });
}

//// BROWSE

function selectCategory(name){
	var category = document.getElementById(name);
	var category_cancel = document.getElementById(name + '_cancel');
	var category_title = document.getElementById(name + '_title');
	var category_select = document.getElementById(name + '_select');
	if(category_select.selectedIndex == 0){
		unselectCategory(name);
	}
	else if(category && category_cancel){
		category_title.setAttribute('style', 'color: #CC0000; background-color: #000;');
		new Effect.Appear(category_cancel);
	}
}

function unselectCategory(name){
	var category = document.getElementById(name);
	var category_cancel = document.getElementById(name + '_cancel');
	var category_select = document.getElementById(name + '_select');
	var category_title = document.getElementById(name + '_title');
	if(category && category_cancel){
		category_title.setAttribute('style', 'color: #EFEFEF; background-color: #999;');
		category_select.selectedIndex = 0;
		new Element.hide(category_cancel);
	}
}

function menuRollOn(menuOrder){
	document.getElementById('mediumMenu').style.backgroundPosition = "0px -"+29*menuOrder+"px";
}
function menuRollOut(){
	document.getElementById('mediumMenu').style.backgroundPosition = '0px 0px';
}


/*
//// ROLLOVER MENU IE FIX

startList = function() {
if (document.all&&document.getElementById) {
navRoot = document.getElementById("nav");
for (i=0; i<navRoot.childNodes.length; i++) {
node = navRoot.childNodes[i];
if (node.nodeName=="LI") {
node.onmouseover=function() {
this.className+=" over";
  }
  node.onmouseout=function() {
  this.className=this.className.replace»
	(" over", "");
   }
   }
  }
 }
}
window.onload=startList;
*/

//end file