var artist_index;
var artist_table_dom;
var artist_table_dt;
var album_index;
var album_table_dom;
var album_table_dt;
var music_index;
var music_table_dom;
var music_table_dt;
var curr_time;
var curr_music_id;


function CreateMusicFunctions(dom_row, dt_row) {

	// Add event listener for opening and closing details
	$( $( $('#music'+ dt_row.data().id ), 'tbody') ).on('click', 'td.play-control', function () {
		var tr = $(this).parent().closest('tr');
		music_index = tr.index();
		var row = music_table_dt.row(tr);
		console.log('tocando  ' + row.data().name );

		var req_url = '/music/' + row.data().id;


		console.log('curr_music_id  ' + curr_music_id);
		console.log('row.data().id  ' + row.data().id);
		if(curr_music_id == row.data().id)
		{
			console.log('curr_time  ' + curr_time);
			//same music
			$('#player').prop("currentTime", curr_time);
			$('#player').trigger("play");
		}
		else
		{
			$('#player').trigger("pause");
			$('#player').removeAttr('src');
			$('#player').prop('src', req_url);
			$('#player').trigger("play");			
		}
		curr_music_id = row.data().id;
		$(this).removeAttr('class');
		$(this).prop('class', "paused-control");
		

	} );
	
	$( $( $('#music'+ dt_row.data().id ), 'tbody') ).on('click', 'td.paused-control', function () {
		
		$('#player').trigger("pause");
		curr_time = $('#player').prop("currentTime");
		console.log('curr_time  ' + curr_time);
		var tr = $(this).parent().closest('tr');
		var row = music_table_dt.row(tr);
		console.log('pausou  ' + row.data().name );
		$(this).removeAttr('class');
		$(this).prop('class', "play-control");
	} );
	
}


function CreateAlbumFunctions(dom_row, dt_row) {
	// Add event listener for opening and closing details
	$( $( $('#album'+ dt_row.data().id ), 'tbody') ).on('click', 'td.details-control', function () {
		var tr = $(this).parent().closest('tr');
		album_index = tr.index();
		var row = album_table_dt.row(tr);
		console.log('clicou em ' + row.data().name )

		if( $( $(tr).parent().parent()).not('.music' ).length > 0 ) {
			if ( row.child.isShown() ) {
			    // This row is already open - close it
			    row.child.hide();
			    tr.removeClass('shown');
			}
			else {
			    // Open this row
			    music_table_dom = music(artist_table_dt.row(artist_index).data().albuns[album_index]);
			    row.child(
					music_table_dom
				     ).show();
			    tr.addClass('shown');

			    if(artist_table_dt.row(artist_index).data().albuns[album_index].musics.length > 0 ) {

				music_table_dt = $('#music'+ artist_table_dt.row(artist_index).data().albuns[album_index].id  ).DataTable( {
					"data":  jQuery.parseJSON( JSON.stringify(artist_table_dt.row(artist_index).data().albuns[album_index].musics) ),
					"columns": [
					    {
						"className":      'play-control',
						"orderable":      false,
						"data":           null,
						"defaultContent": ''
					    },
					    { "data": "number" },
					    { "data": "name" }

					],
					"order": [[1, 'asc']],
					"searching": false,
					"paging": false
				    } );
				CreateMusicFunctions(tr, row);
		   	  }	    

			}
		}
	} );	
}

function music(albun_data) {
  	var return_val = '<table id="music' + albun_data.id + '" class="music"  cellpadding="5" cellspacing="0" border="0" style="padding-right:100px;">';
	return_val += '<thead>'
		return_val += '<tr>'
			return_val += '<th></th>'
			return_val += '<th>Número</th>'
			return_val += '<th>Nome</th>'
		return_val += '</tr>'
	return_val += '</thead>'
	
	for(var i =0; i < albun_data.musics.length; i++) {
		return_val += '<tr>'+
					'<td class="play-control"></td>'+
					'<td>'+albun_data.musics[i].number+'</td>'+
					'<td>'+albun_data.musics[i].name+'</td>'+
				'</tr>';
	}
	
	return_val += '</table>';
	return return_val;
}

function albuns(artist_data) {
	
  	var return_val = '<table id="album' + artist_data.id + '" class="album"  cellpadding="5" cellspacing="0" border="0" style="padding-right:100px;">';
	return_val += '<thead>'
		return_val += '<tr>'
			return_val += '<th></th>'
			return_val += '<th>Album</th>'
			return_val += '<th>Ano</th>'
		return_val += '</tr>'
	return_val += '</thead>'
	
	for(var i =0; i < artist_data.albuns.length; i++) {
		return_val += '<tr>'+
					'<td class="details-control"></td>'+
					'<td>'+artist_data.albuns[i].name+'</td>'+
					'<td>'+artist_data.albuns[i].year+'</td>'+
				'</tr>';
	}
	
	return_val += '</table>';
	return return_val;
}
 
$(document).ready(function() {
    artist_table_dt = $('#artist').DataTable( {
        "ajax": "ajax/data/objects.txt",
        "columns": [
            {
                "className":      'details-control',
                "orderable":      false,
                "data":           null,
                "defaultContent": ''
            },
            { "data": "name" }
        ],
        "order": [[1, 'asc']],
	"searching": false, 
	"paging": false
    } );
     
    // Add event listener for opening and closing details
    $('#artist tbody').on('click', 'td.details-control', function () {
        var tr = $(this).closest('tr');
        var row = artist_table_dt.row( tr );
	console.log('clicou em ' + row.data().name )
	artist_index = tr.index();
	if( $( $(tr).parent().parent()).not('.album' ).length > 0 ) {
		//  trigger only when click on Artist List
       		if ( row.child.isShown() ) {
	            // This row is already open - close it
       		     row.child.hide();
	            tr.removeClass('shown');
       		}
	        else {
       		     // Open this row
		    album_table_dom =  albuns( row.data() );
		    row.child(
				album_table_dom
		     ).show();
       		     tr.addClass('shown');
		     // create dt		     
		     if(row.data().albuns.length > 0 ) {	
			album_table_dt = $('#album'+ row.data().id  ).DataTable( {
			"data":  jQuery.parseJSON( JSON.stringify(row.data().albuns) ),
			"columns": [
			    {
				"className":      'details-control',
				"orderable":      false,
				"data":           null,
				"defaultContent": ''
			    },
			    { "data": "name" },
			    { "data": "year" }

			],
			"order": [[1, 'asc']],
			"searching": false, 
			"paging": false
		    } );
		CreateAlbumFunctions(tr, row);
		   }

	        }
	}
    } );

    console.log('artist_table.rows: '+ artist_table_dt.data().length.toString());
	
} );
