// Artist JS Functions for Younilife Music v2.0 //

sm_spacing = 36;
sm_offset  = -1;

artist = {
	
	id: 0,
	tracks: [],
	
	get: function() {
		this.tracks = [];
		$.get('/rankings/ajax/ylm-client.php?tracks&id=' + artist.id + '&r=' + Math.random(), '', artist.response, 'xml');		
	},
	
	init: function() {
		artist.get();
		artist.photos.get();
		
		if (photos_dir.charAt(0) == '/')
			photos_dir = photos_dir.substr(1);
	},

	is_aa: function() {
		try {
			if (typeof(aa) == 'undefined')
				aa = null;
		} catch (e) {
			aa = null;
		}
		return aa ? true : false;
	},

	// Fill tracks array from XML node //
	load_tracks: function(node) {

		artist.tracks = [];
		track = node.firstChild;
		
		while (track) {

			var data = new Object();
			var track_node = track.firstChild;
			while (track_node) {
				data[track_node.nodeName] = track_node.firstChild.nodeValue;
				track_node = track_node.nextSibling;
			}
			artist.tracks.push(data);
			track = track.nextSibling;
		}
		
	},
	
	// Refresh playlist from internal array //
	refresh_tracks: function() {
		
		var html = '', a = artist.is_aa();
		artist.sound.clear();
		
		for (var i=0;i<artist.tracks.length;i++) {
			var the_track = artist.tracks[i];
			artist.sound.create(i, the_track.id, the_track.filename);
			html += '<div id="track' + i + '" class="l_track"><div class="track_right" id="tr' + i + '">' + (a ? aa.track.div(i, the_track.id, (!i)) : 
					 artist.track.vote.div(i, the_track.id, the_track.rating)) + '</div><div id="track_name' + i + '" class="l_track_name">' + 
					 the_track.title + '</div>' + (a ? aa.track.editor(i, the_track.id, the_track.title) : '' ) + '</div>';
		}
		
		artist.sound.refresh_display();
		
		if (a) {
			html += aa.profile.refresh_waiting();
			aa.track.onload();
		}
		$('#boxm_content').html(html);
		
	},
	
	response: function(doc, status) {

		if (status != 'success') {
			alert(status);
			return;
		}
		
		var track, 
			node = doc.firstChild.firstChild,
			status = node.firstChild.nodeValue;
		
		if (status == 'ok') {
			artist.load_tracks(node.nextSibling);
			artist.refresh_tracks();
		} else if (status == 'empty') {
			$('#boxm_content').html('<div class="l_track_empty">No tracks to display</div>');
		} else {
			alert("Error - status: " + status);	
		}
		if (artist.is_aa())
			aa.track.onload();
		$('#boxm_waiting').hide();
		
	},
	
	sound: {
		
		display_init: false,
		tracks: [],
		managers: [],
		sm2ids: [],
		level: 71,
		autoplay: 0,
		current: 1,
		
		addSound: function(id) {
			with (artist.sound) {
				for (var i=0;i<sm2ids.length;i++)
					if (sm2ids[i] == id)
						return;
				sm2ids.push(id);
				soundManager.setVolume(id, level);
			}
		},
		
		
		attachSound: function(id, url) {	// Add id of created sm2 object to the appropriate manager object in array
			with (artist.sound) {
				for (var i=0;i<managers.length;i++) {
					if (managers[i]['file'] == url) {
						managers[i]['sound'] = id;
						return;
					}
				}
			}
		},
		
		
		clear: function() {
			artist.sound.managers = [];	
			artist.sound.tracks   = [];
		},
		
		create: function(div_id, track_id, filename) {
			artist.sound.tracks.push({
				div: div_id, track: track_id, file: filename				  
			});
		},
		
		next: function() {
			with (artist.sound)
				playpause(current = (current == tracks.length ? 1 : current + 1));
		},
		
		playpause: function(num) {
			with (artist.sound) {
				current = num || current;
				threeSixtyPlayer.handleClick(document.getElementById('playlink' + (current - 1)), true);	
			}
		},
		
		previous: function() {
			with (artist.sound)
				playpause(current = (current == 1 ? tracks.length : current - 1));
		},
		
		refresh_display: function() {
			
			with (artist.sound) {
				
				managers = [];
				for (var k=0;k<max_tracks;k++)
					$('#player'+k).hide();
					  
				if (!managers.length) {		// If we don't have an SM2 stack, build it
					var i=0;
					while (track = tracks[i]) {
						$('#playlink' + i).attr({href: path_to(track.file)});
						managers.push({				// Copy track properties to manager object with linked div and sm2
							div:track.div, track:track.track, file: path_to(track.file), linkedto: track.div/* , sound: sm2*/
						});
						$('#player'+i).show().css({top:(i*sm_spacing)+sm_offset});
						
						// Fuck knows what's going on with IE here - I don't think I even care anymore
						if (navigator.userAgent.match(/msie/i) && display_init)
							if ($('#player'+i).show().css('left') == '51px')
								$('#player'+i).show().css({left:50});
							else
								$('#player'+i).show().css({left:51});
							

						i++;
					}
				
				} else {
					
				}
				// If we have an autoplay set, do that
				if (autoplay) {
					setTimeout('artist.sound.playpause(artist.sound.autoplay); artist.sound.autoplay = 0;', 500); // Set autoplay to 0 afterwards, to prevent it playing again if the display is refreshed
					
				}
				display_init = true;
					
			}
		},
		
		// Used by 360 player to set current track
		setCurrentByURL: function(url) {
			for (var i=0;i<this.tracks.length;i++) {
				if (http_host + path_to(this.tracks[i].file) == url) {
					this.current = ++i;
					return;
				}
			}
		},
		
		stopAll: function() {
			with (threeSixtyPlayer)
				if (lastSound)
					stopSound(lastSound);
		},
		
		volume: function(v) {
			with (artist.sound) {
				level = v;
				for (var i=0;i<sm2ids.length;i++)
					soundManager.setVolume(sm2ids[i], level);
			}
		}
		
	},
	
	photos: {
		
		current_image: 0,
		images: [],
		imgcache: [],	
		loaded: false,
		
		cache: function() {
			
			with (artist.photos) {
				var s = imgcache.length;
				for (var i=0;i<arguments.length;i++) {
					imgcache[s+i] = new Image();
					imgcache[s+i].src = arguments[i];
				}
			}
		},
		
		get: function() {
			$.post('/rankings/ajax/ylm-client.php?photos', 'p=' + artist.id, this.response, 'xml');			
		},
		
		// Fill tracks array from XML node //
		load_images: function(node, append) {
			
			if (!append)
				artist.photos.images = [];
			image = node.firstChild;
			
			while (image) {
			
				var data = new Object();
				var image_node = image.firstChild;
				while (image_node) {
					data[image_node.nodeName] = image_node.firstChild.nodeValue;
					image_node = image_node.nextSibling;
				}
				
				with (artist.photos) { 
					images.push(data);
					if (!loaded || data.add == 'yes')
						cache(path_to_lthumb(data.filename), path_to_sthumb(data.filename, true), 
									path_to_sthumb(data.filename, false));
				}
				image = image.nextSibling;
			}
			
			artist.photos.loaded = true;
			
		},
		
		path_to_lthumb: function(imgfile) {
			return '/imgcache.php?mode=crop&size=180x180&image=' + path_to_photo(imgfile);
		},
		
		path_to_sthumb: function(imgfile, bw) {
			return '/imgcache.php?' + (bw ? 'mode=gray&mode2=crop' : 'mode=crop') + '&size=55x55&image=' + 
					path_to_photo(imgfile);
		},
		
		response: function(doc, status) {
			//alert(doc);return;
			if (status != 'success') {
				alert(status);
				return;
			}
			
			var track, 
				node = doc.firstChild.firstChild,
				status = node.firstChild.nodeValue;
			
			if (status == 'ok') {
	
				with (artist.photos) {
					load_images(node = node.nextSibling);
					refresh_images();
					if (artist.is_aa() && !current_image)
						aa.photos.setcheckbox(images[0].main);
				}
					
				$('#photos_loading').hide();
				$('#photos_main, #photos_thumbs').show();
				
			} else if (status == 'empty') {
				$('#photos_loading, #photos_main, #thumbs_header, #thumbs_footer, #photos_thumbs').hide();
				$('#photos_empty').show();
			} else {
				alert(status);
			}
			
		
		},
		
		refresh_images: function() {
			
			var html = '', a = artist.is_aa();
			/*
			var length = a ? artist.photos.images.length + aa.photos.waiting.length : artist.photos.images.length;
			
			if (length > 1)
				$('#photos_thumbs').show();
			else
				$('#photos_thumbs').hide();
			*/
			
			for (var i=0;i<artist.photos.images.length;i++) {
				var the_photo = artist.photos.images[i];
				with (artist.photos)
					html += '<div class="mphoto_thumb"><img id="artist_thumb' + i + '" src="' + path_to_sthumb(the_photo.filename, (current_image == i ? false : true)) +
							'" onmouseover="artist.photos.swap(this, \'' + path_to_sthumb(the_photo.filename) + 
							'\')" onmouseout="artist.photos.swap(this, \'' + path_to_sthumb(the_photo.filename, true) + 
							'\')" onclick="artist.photos.transport.jumpto(' + i + ')" /></div>';
			}
	
			if (a)
				html += aa.photos.display_waiting();
				
			if (artist.photos.images.length) {
				$('#main_artist_image').attr({src:artist.photos.path_to_lthumb(artist.photos.images[artist.photos.current_image]['filename'])});
				$('#hslink').attr({href:main_photo(artist.photos.images[artist.photos.current_image])});
				$('#photos_main, #thumbs_header, #thumbs_footer').show();
			} else {
				$('#photos_main, #thumbs_header, #thumbs_footer').hide();	
			}
			
			$('#photos_thumbs').html(html);		
		},
		
		swap: function(e, img) {
			if (e.id == ('artist_thumb' + artist.photos.current_image))
				return;
			e.src = img;
		},
		
		transport: {
			
			backwards: function() {
				with (artist.photos)
					transport.jumpto((!current_image ? images.length - 1 : current_image - 1));
			},
			
			forwards: function() {
				with (artist.photos)
					transport.jumpto((current_image + 1) % images.length);				
			},
			
			jumpto: function(i) {
				
				with (artist.photos) {
					
					$('#main_artist_image').attr({src: path_to_lthumb(images[i].filename)});
					$('#artist_thumb' + i).attr({src: path_to_sthumb(images[i].filename)});
					$('#artist_thumb' + current_image).attr({src: path_to_sthumb(images[current_image].filename, true)});
					document.getElementById('hslink').href = main_photo(images[i]);
					current_image = i;
					
					if (artist.is_aa())
						aa.photos.setcheckbox(images[i].main);
				}
	
			}
		}
		
	},
	
	track: {
		
		volume: {
			
			dragging: false,
			ele_x: 0,
			start_x: 0,
			start_y: 0,
			
			onDrag: function(e) {
				
				e = e || window.event;
				
				with (artist.track.volume) {
					var x = ele_x + (e.clientX - start_x);
					x = x < 8 ? 8 : x > 85 ? 85 : x;
					$('#volume_knob').css({left: x}); 
					artist.sound.volume(Math.round(((x - 8) / 77) * 100));
				}

			},
			
			startDrag: function(e) {
				
				e = e || window.event;
				
				with (artist.track.volume) {
					start_x = e.clientX;
					start_y = e.clientY;
					ele_x   = parseInt($('#volume_knob').css('left').replace('px', ''));
				}
				
				// Register listeners {
				with (artist.track.volume) {
					if (document.addEventListener)
						document.addEventListener('mousemove', onDrag, true);
					else
						document.attachEvent('onmousemove', onDrag);
					dragging = true;
				}
				// Hide from other potential interceptees
				if (e.stopPropagation)
					e.stopPropagation(); 		// DOM
				else
					e.cancelBubble = true;		// IE
					
				// Prevent any default action
				if (e.preventDefault)
					e.preventDefault();			// DOM
				else
					e.returnValue = false;		// IE
			
			},
			
			stopDrag: function(e) {
				
				e = e || window.event;
				
				// Remove mousemove listener
				with (artist.track.volume) {
					if (document.removeEventListener)
						document.removeEventListener('mousemove', onDrag, true);	// DOM	
					else
						document.detachEvent('onmousemove', onDrag);				// IE5+
					dragging = false;
				}
				// Don't allow event to propagate further
				if (e.stopPropagation)
					e.stopPropagation();	// DOM
				else
					e.cancelBubble = true;	// IE
			}
			
		},
		
		vote: {
			
			fading: [],
			
			div: function(div_id, track_id, current_rating) {
				var html  = '<div class="track_rating"><div id="rate_popup' + div_id + '" class="rate_popup">' + 
							'<table class="hp_table" cellpadding="0" cellspacing="0"><tr><td class="rp_left"></td>' + 
							'<td id="rp_mid' + div_id + '" class="rp_mid"></td><td class="rp_right"></td></tr>' + 
							'</table></div>', 
					score = Math.round(current_rating / 10) * 10;
					
				for (var i=1; i<=5;i++) {
					this_score = (i - 1) * 20;
					html +=  '<a href="javascript:void(0);" onclick="artist.track.vote.register(' + div_id + 
							 ', ' + track_id + ', ' + (this_score + 20) + ')"><div class="' + (score >= (this_score + 20) ?
							 'star_on' : score >= (this_score + 10) ? 'star_half' : 'star_off') + '" id="star' + 
							  div_id + '_' + i + '" onmouseover="artist.track.vote.rollover(' + div_id + ', ' + i + 
							  ')" onmouseout="artist.track.vote.rollout(' + div_id + ', ' + score + 
							  ')"></div></a>';
				}
				return html + '</div>';
			},
			
			register: function(div_id, track_id, user_rating) {
				
				$.post('/rankings/ajax/ylm-client.php?vote', '&u=' + user.uid + '&s=' + user.sid + 
					   '&p=' + artist.id + '&v=' + user_rating + '&d=' + div_id + '&t=' + track_id, 
					   this.response, 'xml');
				
			},
			
			response: function(doc, status) {
				
				if (status != 'success') {
					alert(status);
					return;
				}
				
				var nodes  = new Object(), 
					node   = doc.firstChild.firstChild,
					status = node.firstChild.nodeValue;
				
				if (status == 'ok') {
			
					while (node = node.nextSibling)
						nodes[node.nodeName] = node.firstChild.nodeValue;
						
					// Rebuild rating div with new score
					$('#tr' + nodes['div']).html(artist.track.vote.div(nodes['div'], nodes['track'], nodes['score']));
					$('#rp_mid' + nodes['div']).html('Thanks for rating!');
					$('#rate_popup' + nodes['div']).show();
					norollover = true;
					artist.track.vote.fading.push(nodes['div']);
					$('#rate_popup' + nodes['div']).fadeTo(2000,0, artist.track.vote.unlock);
					//setTimeout("$('#rate_popup" + track + "').fadeTo(2000,0);", 2000);
				}
				
			},
			
			rollout: function(track, score) {
				if (norollover)
					return;
				for (var i=1; i<=5; i++) {
					this_score = (i - 1) * 20;
					with (document.getElementById('star' + track + '_' + i))
						if (score >= (this_score + 20))
							className = 'star_on';
						else if (score >= (this_score + 10))
							className = 'star_half';
						else
							className = 'star_off';
				}
				$('#rate_popup' + track).hide();
			},
			
			rollover: function(track, star) {
				if (norollover)
					return;
				for (var i=1; i<=5; i++) 
					with (document.getElementById('star' + track + '_' + i))
						className = i <= star ? 'star_on' : 'star_off';
	
				$('#rp_mid' + track).html('Your rating: ' + star + '/5');
				$('#rate_popup' + track).fadeTo(1,1).show();
			},
			
			unlock: function() {
				norollover = false;
				$('#rate_popup' + artist.track.vote.fading.shift()).hide();
			}
			
		}
		
	}

};

user = {
	uid: 0,
	sid: ''	,
	profile: 0
};

// Catch volume drag mouseups, even if they don't occur within the containing element
function docMouseup(e) {
	if (artist.track.volume.dragging)
		artist.track.volume.stopDrag(e);
}

function main_photo(image) {
	if (image.x > photo_x || image.y > photo_y)
		return '/imgcache.php?mode=resize&size=' + photo_x + 'x' + photo_y + '&image=' + photos_dir + 
			image.filename.charAt(0) + "/" + image.filename;
	return '/' + photos_dir + image.filename.charAt(0) + "/" + image.filename;
}

// Generate path from filename
function path_to(file) {
	return music_dir + file.charAt(0) + '/' + file;	
}

function path_to_photo(file) {
	return photos_dir + file.charAt(0) + '/' + file;	
}

window.onload = artist.init;
window.onmouseup = docMouseup;

// Highslide config //

hs.graphicsDir = '/rankings/js/highslide/graphics/';
hs.align = 'center';
hs.wrapperClassName = 'wide-border';
hs.outlineType = 'rounded-white';
hs.showCredits = false;

norollover = false;

// Debugging (remove) //
/*
function test_sound() {
	threeSixtyPlayer.handleClick(document.getElementById('playlink0'), true);	
}

function print_r(arr,level) {
	
	var output = '', padding = '';
	level = level || 0;
	
	for (var j=0;j<level+1;j++)
		padding += "    ";
	
	if (typeof(arr) == 'object') { // Arrays and objects
		for (var item in arr) {
			var value = arr[item];
			
			if (typeof(value) == 'object') { 
				output += padding + "'" + item + "' ...\n";
				output += print_r(value,level+1);
			} else {
				output += padding + "'" + item + "' => \"" + value + "\"\n";
			}
		}
	} else { //Strings, chars, integers etc.
		output = "===>"+arr+"<===("+typeof(arr)+")";
	}
	return output;
}
*/

