/*
itunes.js

PHP Based iTunes Library Browser
Copyright (C) 2007-2009  Jason Barrie Morley
http://www.jbmorley.co.uk

This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
*/

var count       = 0;
var tracks      = new Array();
var track_idx   = new Array(); 
var current     = -1;
var current_idx = -1;
var search      = "";
var type        = "Music";
var page        = 0;
var do_next     = false;

function load_page() {

	var url    = "api/music.php?type=" + type + "&page=" + page;
	if (search != "") {
		url = url + "&search=" + search;
	}

	new Ajax.Request
		(
		url,
		{
	  	method: 'get',
		onSuccess: function(transport)
			{
			var items = interpret(transport.responseText);
			if (page == 0)
				{
				clear_items();
				}
			else
				{
				remove_load_more();
				}
			add_items(items);
			add_load_more(items);
			select_playing();

			if (do_next)
				{
				next();
				do_next = false;
				}
				
	  		}
		});
	
}

function search_update(id) {
	search = $(id).value;
	page = 0;
	load_page();
}

function search_clear(id) {
	$(id).value = "";
	search_update(id);
}

function set_type(new_type) {
	type = new_type;
	page = 0;
	load_page();
}

function clear_items() {
	
	count = 0;
	$('link_table_body').update('');
	
}

function remove_load_more() {

	var row = $('load_more_row');
	if (row) {
		$('link_table_body').removeChild($('link_table_body').lastChild);
	}

}

function add_load_more(items) {

	// Only add the load more items row if required
	if (items.length == 30) {

		// Add the table to handle loading more items
		var row = Builder.node('tr');
		var td  = Builder.node('td');
		td.colSpan = 7;
		
		row.onclick = function() {
			page++;
			load_page();
		}
		
		row.insert(td);
		row.id = 'load_more_row';
		td.insert('Load more tracks...');
		$('link_table_body').insert(row);
		
		td.id = 'load_more';

		make_selectable(row, current);
		
	}

}

function add_items(items) {

	for (var i=0; i<items.length; i++) {
		add_row(items[i]);
	}
	
}

function add_row(item) {

	tracks.push(item);
	var index = tracks.length-1;
	
	// Store a lookup so we can play tracks by database id
	track_idx[item.id] = index;

	var row = Builder.node('tr');
	row.id = "track_" + index;
	
	var cell_l = Builder.node('td', item.id);
	cell_l.addClassName('left');
	
	row.insert(cell_l);
	
	var name = Builder.node('table');
	var name_row = Builder.node('tr');
	name_row.insert(Builder.node('td', item.name));

	if (item.location != "") {
		var download = Builder.node('img');
		download.src = "images/download.png";
		var download_td = Builder.node('td', download);
		download.onclick = function(event) {
			event.stop();
			window.location.href ="api/download.php?id=" + item.id;
		}
		download_td.addClassName('download');
		name_row.insert(download_td);
	}
	

	name.insert(name_row);
	name.addClassName('name');
	row.insert(Builder.node('td', name));
	
	row.insert(Builder.node('td', item.artist));
	row.insert(Builder.node('td', item.album));
	row.insert(Builder.node('td', item.genre));
	row.insert(Builder.node('td', item.type));
	
	make_selectable(row, current);
	
	var cell_r = Builder.node('td');
	if (item.rating > 0) {
		cell_r.insert("<img src='images/rating" + item.rating + ".gif' />");
	}
	cell_r.addClassName('right');
	row.insert(cell_r);
	
	if (count % 2 == 0) {
		row.addClassName('even');
	}
	
	// Determine the row select behaviour.
	if (item.location != "") {
		row.onclick = function() { play_by_idx(item.id); }
	} else {
		var artist = item.artist;
		var track  = item.name;
		
		artist = artist.replace(/\s+/g, "+");
		track  = track.replace(/\s+/g, "+");
		
		row.onclick =
			function()
				{
				window.location.href = "http://www.last.fm/music/"+artist+"/_/"+track;
				};

	}
	
	$('link_table_body').insert(row);
	count++;

}


function make_selectable(row, id) {

	row.onmousemove =
		function() { this.addClassName('selected'); };
	row.onmouseout =
		function() {
			if (this.id != "track_" + id) this.removeClassName('selected');
			select_playing();
			};
	row.style.cursor = "pointer";

}


function select_playing() {
	if (current > -1) {
		var item = $('track_'+track_idx[current_idx]);
		if (item) {
			item.addClassName('selected');
		}
	}
}


function deselect_playing() {
	if (current > -1) {
		var current_track = $('track_'+current);
		if (current_track) {
			current_track.removeClassName('selected');
		}
	}
}


function play_by_idx(idx) {
	var index = track_idx[idx];
	play(index);
}


function play(index) {
	deselect_playing();
	if (current == -1) {
		Effect.Appear('play_controls_div');
	}
	current = index;
	current_idx = tracks[index].id;
	Sound.play( tracks[index].location, {replace: true} );
	select_playing();
}


function next() {
	if (current > -1) {
	
		if (current >= tracks.length-1) {
			page++;
			do_next = true;
			load_page();
		} else {
			play(current+1);
		}
	}
}


function previous() {
	if (current > -1) {
		play(current-1);
	}
}


function stop() {
	// We play a non-existant file here as firefox complains otherwise
	Sound.play('stop.mp3', {replace:true});
	deselect_playing();
	current = -1;
	Effect.Fade('play_controls_div');
}


function interpret(json) {
	var text = "var ret = " + json;
	eval(text);
	return ret;
}
