$(function(){
    $('ul.track-list li a.audio-track').click(function(){
        $('ul.track-list li.current').removeClass('current');
        $(this).parent().addClass('current');
        
        var trackId = $(this).attr('rel');
        
        //Not needed: changeLyrics(trackId);
        
        playTrack(trackId);       
        return false;
    });
    
    $('a.preview-player').click(function(){
        
        if($(this).parent().hasClass('preview-player-wrapper-small')){
            var size = 36;    
        }else{
            var size = 66;
        }
        
        var song_id = $(this).attr('rel');
        
        $('#thePlayer').next('a.preview-player').show();
        $('#thePlayer').remove();
        
        $(this).parent().prepend('<div style="width:66px; height:66px;" class="left" id="preview-player"></div>');
        
        var flashvars = {};
            //flashvars.xmlFile = "/do/songbank/song/audioxml/song/" + song_id;
            flashvars.xmlFile = $(this).attr('href');
            //flashvars.trackID = "";

        var params = {};
            params.allowscriptaccess = "always";

        var attributes = {};
            attributes.name = "thePlayer";
            attributes.id = "thePlayer";

        var suPlayer = swfobject.embedSWF("/fileadmin/templates/player_preview.swf", "preview-player", size, size, "9.0.0", false, flashvars, params, attributes, startPreview);
        $(this).hide();

        $('#thePlayer').addClass('left');
        return false;       
    });
    
});

function startPreview(){
    //wait a second for the interface to become available... 
    //need to test this on an old pc
    setTimeout(function(){
        var suPlayer = document.getElementById('thePlayer');
        if(typeof(suPlayer.play_mp3) != 'function'){
            startPreview();
        } else {
            suPlayer.play_mp3('');
        }
    }, 1000);
    
}

function isReady()
{
	//alert('player ready');
	return true;
}

/*
function onStop(trackId)
{
	if($.cookie("stream") != ''){
	   sendStream(trackId, 'stream_end');
	}	
}

function onStart(trackId)
{
	if($.cookie("stream") != ''){
	   sendStream(trackId, 'stream_start');
	}
}

function sendStream(trackId, cookieName)
{
    if($.cookie("stream") != ''){
        $.ajax({
            url : '/do/songbank/resource/logstream/track/' + trackId,
            success : function(cookieName){
                var cookieValue = Math.round(new Date().getTime() / 1000);
                setLogCookie(cookieName, cookieValue);
            }
        });
    }
}
*/

function onStart(trackId)
{
    if($.cookie("stream") != ''){
        sendTimer();
    }
    startTimer(trackId);
}

function onStop()
{
    stopTimer();
    if($.cookie("stream") != ''){
        sendTimer();
    }
}

function startTimer(trackId)
{
    var i = 0;
    streamTimer = setInterval(function(){
        i++;
        var log = trackId+','+i;        
        setLogCookie('stream', log);
    }, 1000);
}

function stopTimer()
{
    clearInterval(streamTimer);
}

function sendTimer()
{
    $.ajax({ url : '/do/songbank/resource/logstream' })
}

function setLogCookie(cookieName, cookieValue)
{
    var nDays = 28;
    var today = new Date();
    var expire = new Date();
    if (nDays==null || nDays==0) nDays=1;
    expire.setTime(today.getTime() + 3600000*24*nDays);
    document.cookie = cookieName+"="+escape(cookieValue)
         + ";expires="+expire.toGMTString()
         + ";path=/";
}


function newTrack(trackId){
    $('.track-list li.current').removeClass('current');
    $('#track-'+trackId).addClass('current');
    if($('#playlist-wrapper').length>0){
        changeLyrics(trackId);
    }        
}

function changeLyrics(trackId, attempts){
    // Initial the number of attempts at loading this
    if(typeof attempts == 'undefined') {
        attempts = 0
    }
    
    $.ajaxSetup({ timeout: 5000 });
    $.ajaxSetup({cache: false});
    $.ajax({
        cache: false,
        
        url: '/do/songbank/song/getlyrics/?_='+Math.floor(Math.random()*99999),
        dataType: 'json',
        data: {'trackid' : trackId},
        success: function(data) {
            if(data.normal){
                $('#lang1').html(data.normal);
                $('#normal a').click();
            }
            
            if(data.translated){
                $('#lang2').html(data.translated);
                $('#translated').show();
            }else{
                $('#translated').hide();
                $('#lang2').empty();
            }
            
            if(data.phonetic){
                $('#lang3').html(data.phonetic);
                $('#phonetic').show();
            }else{
                $('#phonetic').hide();
                $('#lang3').empty();
            }
        },
        error : function(XMLHttpRequest, textStatus, errorThrown) {
            // WAS: alert('fail: ' + textStatus);
            // We will try again twice more 
            if(attempts < 3) {
                console.log("Try: " + attempts);
                changeLyrics(trackId, (attempts + 1));
            }
            // ...Otherwise it's a permanent error. User will be able to click to try again.
        }
    });
    return;
    
    $.getJSON('/do/songbank/song/getlyrics/', {'trackid' : trackId},
        function(data){
        
        if(data.normal){
            $('#lang1').html(data.normal);
            $('#normal a').click();
        }
        
        if(data.translated){
            $('#lang2').html(data.translated);
            $('#translated').show();
        }else{
            $('#translated').hide();
            $('#lang2').empty();
        }
        
        if(data.phonetic){
            $('#lang3').html(data.phonetic);
            $('#phonetic').show();
        }else{
            $('#phonetic').hide();
            $('#lang3').empty();
        }
    });
}

function playTrack(trackID)
{
  if(!document.getElementById) return true;

   var suPlayer = document.getElementById('thePlayer');
   if (suPlayer != null)
    	{
			if (trackID)
			{
				suPlayer.play_mp3(trackID);
			} else
			{
				suPlayer.play_mp3("");
			}
				
		}
}
