/** Internal / state variables **/
var defaultVolume       = 75;
var progressBarWidth    = 310; // Could be determined from the css (.width()) but not if the player is hidden by css..
var allowSeeking        = false;
var swf                 = null;
var progressTimer       = null;
var pixelsPerSecond     = 0;
var isLive              = true;
var isPlaying           = false;
var streamStarted       = false;
var currentVolume       = null;
var cookiedomain        = '/';
var refresh_rate_set    = false; //whether the now playing refresh has been set

//these are opacicity settings for the overlay
//settings
var on_opacity  = 0.4;
var off_opacity = 0.0;
var duration    = 1000;


////////////////////////////////////////////////////////////////////////////////
//
// Functionality for initialising the radio player
//
////////////////////////////////////////////////////////////////////////////////

// Detect presence of Flash and version
var FlashDetect=new function(){var self=this;self.installed=false;self.raw="";self.major=-1;self.minor=-1;self.revision=-1;self.revisionStr="";var activeXDetectRules=[{"name":"ShockwaveFlash.ShockwaveFlash.7","version":function(obj){return getActiveXVersion(obj);}},{"name":"ShockwaveFlash.ShockwaveFlash.6","version":function(obj){var version="6,0,21";try{obj.AllowScriptAccess="always";version=getActiveXVersion(obj);}catch(err){}
return version;}},{"name":"ShockwaveFlash.ShockwaveFlash","version":function(obj){return getActiveXVersion(obj);}}];var getActiveXVersion=function(activeXObj){var version=-1;try{version=activeXObj.GetVariable("jQueryversion");}catch(err){}
return version;};var getActiveXObject=function(name){var obj=-1;try{obj=new ActiveXObject(name);}catch(err){obj={activeXError:true};}
return obj;};var parseActiveXVersion=function(str){var versionArray=str.split(",");return{"raw":str,"major":parseInt(versionArray[0].split(" ")[1],10),"minor":parseInt(versionArray[1],10),"revision":parseInt(versionArray[2],10),"revisionStr":versionArray[2]};};var parseStandardVersion=function(str){var descParts=str.split(/ +/);var majorMinor=descParts[2].split(/\./);var revisionStr=descParts[3];return{"raw":str,"major":parseInt(majorMinor[0],10),"minor":parseInt(majorMinor[1],10),"revisionStr":revisionStr,"revision":parseRevisionStrToInt(revisionStr)};};var parseRevisionStrToInt=function(str){return parseInt(str.replace(/[a-zA-Z]/g,""),10)||self.revision;};self.majorAtLeast=function(version){return self.major>=version;};self.minorAtLeast=function(version){return self.minor>=version;};self.revisionAtLeast=function(version){return self.revision>=version;};self.versionAtLeast=function(major){var properties=[self.major,self.minor,self.revision];var len=Math.min(properties.length,arguments.length);for(i=0;i<len;i++){if(properties[i]>=arguments[i]){if(i+1<len&&properties[i]==arguments[i]){continue;}else{return true;}}else{return false;}}};self.FlashDetect=function(){if(navigator.plugins&&navigator.plugins.length>0){var type='application/x-shockwave-flash';var mimeTypes=navigator.mimeTypes;if(mimeTypes&&mimeTypes[type]&&mimeTypes[type].enabledPlugin&&mimeTypes[type].enabledPlugin.description){var version=mimeTypes[type].enabledPlugin.description;var versionObj=parseStandardVersion(version);self.raw=versionObj.raw;self.major=versionObj.major;self.minor=versionObj.minor;self.revisionStr=versionObj.revisionStr;self.revision=versionObj.revision;self.installed=true;}}else if(navigator.appVersion.indexOf("Mac")==-1&&window.execScript){var version=-1;for(var i=0;i<activeXDetectRules.length&&version==-1;i++){var obj=getActiveXObject(activeXDetectRules[i].name);if(!obj.activeXError){self.installed=true;version=activeXDetectRules[i].version(obj);if(version!=-1){var versionObj=parseActiveXVersion(version);self.raw=versionObj.raw;self.major=versionObj.major;self.minor=versionObj.minor;self.revision=versionObj.revision;self.revisionStr=versionObj.revisionStr;}}}}}();};FlashDetect.JS_RELEASE="1.0.4";

// Format a a string to HH:MM:SS format.
function formatTime(totalSeconds)
{
    var tempDate = new Date(totalSeconds * 1000);
    return (tempDate.getUTCHours() < 10 ? "0" : "") + tempDate.getUTCHours() + ":" + (tempDate.getUTCMinutes() < 10 ? "0" : "") + tempDate.getUTCMinutes() + ":" + (tempDate.getUTCSeconds() < 10 ? "0" : "") + tempDate.getUTCSeconds();
}

// Grab SWF movie
function getSWF(movieName)
{
    if (navigator.appName.indexOf("Microsoft") != -1)
    {
        return window[movieName];
    }
    else
    {
        return document[movieName];
    }
}

// Load the flash object. It will call the onLoad_playerInit() function via a
// callback when the object and stage has initialised.
function onLoad_playerEmbed()
{
    swfobject.switchOffAutoHideShow();
    if (swfobject.hasFlashPlayerVersion("9")) {
        swfobject.embedSWF(
            "/swf/player2.swf",
            "hidden",
            "0", "0",
            "9.0.0",
            '',
            {onLoad: 'onLoad_playerInit'},
            {},
            { id: "radioplayer", name: "radioplayer" }
        );
    }
    else
    {
        $('#now-playing-image').css('display', 'none');
        $('#image-overlay').css('display', 'none');
        $('#main-content-song-wrapper h2').css('display', 'none');
        $('#playpausestop').css('display', 'none');
        $('#volume').css('display', 'none');
        $('#album-pic').css('display', 'none');
        $('#overlay').html('<div class="no-flash">You need to have Flash 9.0.0 or above to use this site, click <a target="_blank" href="http://get.adobe.com/flashplayer/">here</a> to get the latest version of Flash</div>');
    }
}

// Initialise player
function onLoad_playerInit()
{
    // Grab the radio player object and check version of Flash.
    if((navigator.appName.indexOf("Microsoft") != -1) && (navigator.userAgent.toLowerCase().indexOf("win") != -1))
    {
        window.radioplayer = document.getElementById('radioplayer');
    }

    if(FlashDetect.installed && FlashDetect.major >= 9)
    {
        radioplayer = getSWF("radioplayer");
    }
    
    // Bind the playback controls.
    $('#beginning').click(function(){ btnClick_beginning(); });
    $('#playpausestop').click(function(){ btnClick_playPauseStop(); });
    $('#image-overlay').click(function(){ btnClick_playPauseStop(); });
    $('#forward5').click(function(){ btnClick_forward5(); });

    //immediately set the opacity of the overlay
    $('#overlay').css('opacity', on_opacity);

    // Callback to the layout - can we pass this as a parameter?
    initPlayer_flashComplete();
}


// Set the volume slider position - will not work if the player and slider are not visible.
function init_volumeSlider()
{
    $('#volume').mouseenter(function() {
          $('#volume-slider').fadeIn("fast");
          return false;
    });

    $('#volume').mouseleave(function() {
          $('#volume-slider').fadeOut("fast");
          return false;
    });

    
    $('#volume-click').click(function() {
        //if they click and the volume is already 0 then we need to "un-mute"
        //the volume, otherwise we need to "mute" the volume
        if(currentVolume == 0)
        {
            currentVolume = defaultVolume;
        }
        else
        {
            currentVolume = 0;
        }
        
        control_setVolume(currentVolume);
        $.cookie('js_volume', 0, { expires: 365, path: '/', domain: cookiedomain });
        $("#slider").slider('option', 'value', currentVolume);
        return false;
    });

    $("#slider").slider({
        min: 0,
        max: 100,
        orientation: 'vertical',
        animate: true,
        slide:
            function(event, ui) {
                control_setVolume(ui.value);
            },
        change:
            function(event, ui) {
                control_setVolume(ui.value);
                $.cookie('js_volume', currentVolume, { expires: 365, path: '/', domain: cookiedomain });
            }
    });

    init_volume_level(); //set the volume to the default level
}

//initialise the progress slider
function init_progressSlider()
{
    // Set up the progressbar slider arguments.
    $("#progressbar").slider({
            min: 0,
            max: progressBarWidth,
            animate: true,
            disabled: true,
            slide:
                function(event, ui) {
                    clearTimeout(progressTimer); $('#position').html(formatTime(ui.value * (1/pixelsPerSecond)));
                },
            change:
                function(event, ui) {
                    control_seekStream(ui.value / pixelsPerSecond); progressTimer = setTimeout('updateProgress()', 950);
                }
    });
}

// Finish processing page load - after flash is loaded fully.
function initPlayer_flashComplete()
{
    if(streamName == 'm4c')
    {
        event_listenAgain();
    }
    else
    {
        event_playLive();
    }
    $('#status').html('Stopped');
    $('#position').html('00:00:00');
    init_volumeSlider();
    liveRefresh(); //populate the information about what show is on
}

//initialises the position of the volume on the volume slider
function init_volume_level()
{
    // Read volume from cookie, or set default.
    if ($.cookie('js_volume') && $.cookie('js_volume') >= 0 && $.cookie('js_volume') <= 100)
    {
        currentVolume = $.cookie('js_volume');
    }
    else
    {
        currentVolume = defaultVolume;
    }

    $("#slider").slider('option', 'value', currentVolume);
}

////////////////////////////////////////////////////////////////////////////////
//
// Functionality for controlling the radio player
//
////////////////////////////////////////////////////////////////////////////////
function control_playRadio()
{
    //fade out the "click to play" overlay
    $('#image-overlay').fadeOut(duration);
    $('#overlay').fadeTo(duration, off_opacity);
    $('#overlay').css('display', 'none');

    if (radioplayer != null) radioplayer.playradio(0);
    isPlaying = true;
    
    if (isLive)
    {
        //set the button to "Stop"
        $('#playpausestop').removeClass().attr('class', 'stop');
    }
    else
    {
        $('#playpausestop').attr('class', 'pause');
    }

    track_event('play');
    $('#volume').css('zIndex', 9);
    updateProgress();
}

//stop the radio player and set the UI to reflect that the radio player
//has been stoppped
function control_stopRadio()
{
    //fade in the overlay
    $('#image-overlay').fadeIn(duration);
    $('#overlay').css('display', 'block');
    $('#overlay').fadeTo(duration, on_opacity);

    //tell the radio player to stop
    if (radioplayer != null) radioplayer.stopradio();

    //reset the play parameters
    isPlaying       = false;
    streamStarted   = false;
    //reset the timing functionailty
    $('#position').html('00:00:00');
    $('#status').html('Stopped');
    $('#progressbar').slider("option", 'value', 0);
    $('#playpausestop').attr('class', 'play');

    //reset the progress time
    clearTimeout(progressTimer);

    //only track if the player is listen live, the user cannot stop a listen
    //again stream, they can only pause. the only time that stop is called is when
    //the listen again track stops. This is an automated process and not a result
    //of human interaction, therefore don't record it as an event
    if(isLive)
    {
        track_event('stop');
    }
    else
    {
        $("#progressbar").slider("option", "disabled", true);
    }
    //bring the volume to the top
    $('#volume').css('zIndex', 100);
}

//pause the radio player and set the UI to reflect that the radio player has been
//paused
function control_pauseRadio()
{
    if (!isLive) {
        if (radioplayer != null) radioplayer.pauseradio();
        isPlaying = false;

        //fade in the overlay
        $('#image-overlay').fadeIn(duration);
        $('#overlay').css('display', 'block');
        $('#overlay').fadeTo(duration, on_opacity);
        $('#playpausestop').attr('class', 'play');

        track_event('pause');
    }
}

//unpause the radio player and set the UI to reflect that the radio player has been
//unpaused
function control_unPauseRadio()
{
    if (!isLive)
    {
        if (radioplayer != null) radioplayer.pauseradio();
        isPlaying = true;
        $('#image-overlay').fadeOut(duration);
        //fade out the overlay
        $('#overlay').fadeTo(duration, off_opacity);
        $('#overlay').css('display', 'none');
        $('#playpausestop').attr('class', 'play');
        $('#playpausestop').attr('class', 'pause');

        track_event('resume');
    }
}

//set the volume in the radio player and adjust the volume to slider to reflect this
function control_setVolume(volume)
{
    currentVolume = volume;
    
    if (radioplayer != null) radioplayer.setVolume(currentVolume/100);
    //make sure that the correct volume button is showing
    if(currentVolume == 0)
    {
        $('#volume').css({backgroundPosition: 'bottom left'});
    }
    else
    {
        $('#volume').css({backgroundPosition: 'top left'});
    }

    track_event('setvolume');
}

function control_seekStream(position)
{
    if (!isLive) if (radioplayer != null) radioplayer.seek(position);
}

// Handle click of the play/pause/stop control.
function btnClick_playPauseStop()
{
    //if the radio player is playing then we will have to
    //stop it / pause it (depending on whether we are listening to live or
    //listen again)
    if (isPlaying)
    {
        if (isLive)
        {
            control_stopRadio();
        }
        else
        {
            control_pauseRadio();
        }
    }
    else
    {
        if (isLive || !streamStarted)
        {
            streamStarted = true;
            control_playRadio();
        }
        else
        {
            control_unPauseRadio();
        }
    }
}

// Seek to the beginning of the current track.
function btnClick_beginning()
{
    if (!isLive) control_seekStream(0);
}

// Seek to the beginning of the current track.
function btnClick_forward5()
{
    control_seekStream(radioplayer.currentPosition() + 300);
}

//event for when someone wants to listen live
function event_playLive()
{
    isLive          = true;
    allowSeeking    = false;
    streamStarted   = true;
    $('#progressbar-wrapper').hide();

    radioplayer.initRadioPlayer(streamName, true, prerollName, autoplay);
}

//event for when someone wants to listen again
function event_listenAgain()
{
    isLive          = false;
    streamStarted   = false;
    allowSeeking    = true;

    //radioplayer.setStream('mp3:/magic/pressplay/audrey-niffenegger_192.mp3');
    radioplayer.setStream('kiss100od/m4c.m4a', false);
    $('#progressbar-wrapper').show();
    init_progressSlider();
}

// Update the progress bar / position timer
function updateProgress()
{
    // Clear any existing timer.
    clearTimeout(progressTimer);

    // If seeking is allowed, and a stream length has been returned, enable the slider.
    if (allowSeeking && radioplayer.streamLength() > 0) $("#progressbar").slider('enable');

    // Show the time, and if a listen again stream, also the duration.
    var currentPosition;
    if (isNaN(radioplayer.currentPosition())) currentPosition = 0;
    else currentPosition = radioplayer.currentPosition();

    $('#position').html(formatTime(currentPosition));
    if (!isLive) $('#progressbar .streamlength').html(formatTime(radioplayer.streamLength()));

    // If not a live stream, update the progress bar indicator.
    var progressBarPosition;
    if (!isLive)
    {
        if (isNaN(radioplayer.streamLength()) || radioplayer.streamLength() == 0)
        {
                progressBarPosition = 0;
        }
        else
        {
                pixelsPerSecond = (progressBarWidth / radioplayer.streamLength());
                progressBarPosition = pixelsPerSecond * currentPosition;
        }

        //update the progress bar
        $('#progressbar').slider("option", 'value', progressBarPosition);
    }

    // Update the playback status.
    $('#status').html(radioplayer.playState());

    // Refresh once per second.
    progressTimer = setTimeout('updateProgress()', 950);

}

///////////////////////////////////////////////////////////////////////////////
//
// functions used to anhance radio player functionality get now playing info
//
///////////////////////////////////////////////////////////////////////////////

// Global timerId variable
var liveRefreshTimerId = 0;

// Return lowercase, only alphanumeric string (with - as space).
function stripText(strText){
    // set to lowercase
    strText = strText.toLowerCase();
    // replace spaces with -
    strText = strText.replace(/ /g, "-");
    // remove all non-alphanumeric (but keep -)
    strText = strText.replace(/[^a-zA-Z0-9-]/g, "");
    return strText;
}

// Update the now/next track information.
function nownext_status(stream_title)
{
    if(nowNextInfo) //only get the nownext if the radio player is configured to do so
    {
        if(stream_title != '')
        {
            stream_title += ' - ' + stationName;
            stream_title = $.md5(stream_title);
            
            $.getJSON(domain + "/uploads/nownext/" + stream_title + '.json', function(data){
                  //if an artist has been supplied and their song hasn't finished too long ago then set now playing
                  var change = check_track_change(data.id, data.artist, data.track, data.average, data.amazon_thumb_small, data.amazon_url, data.itunes_url);

                  if(change)
                  {
                      $('#main-content-song h2').html('<div id="now-artist">' + data.artist + '</div>');
                      $('#main-content-song h3').html('<div id="now-track">' + data.track + '</div>');
                      $('#album-info').css('display', 'block');
                      $('#album-info #rate-new-track h4').html('Rate this Track:');
                      $('#twitter_update').attr('href', data.tweet);
                      $('#facebook_update').attr('href', data.facebook);
                      $('#now-playing-image').attr('src', data.amazon_thumb);

                      if(data.amazon_url != '' || data.itunes_url != '')
                      {
                          $('#retailer_link').css("display", "block");
                          
                          var list_html = '';
                          
                          if(data.amazon_url != '')
                          {
                            list_html += '<a class="list-retailers-item" href="' + data.amazon_url + '" target="_blank">Amazon</a>';
                          }

                          if(data.itunes_url != '')
                          {
                            list_html += '<a class="list-retailers-item" href="' + data.itunes_url + '" target="_blank">iTunes</a>';
                          }

                          $('#retailer_links_lrg').html(list_html);
                      }
                      else
                      {
                          $('#retailer_link').css("display", "none");
                      }


                      //reset the stars
                      $('#rate-new-track_1').css('cursor', 'pointer');
                      $('#rate-new-track_1').css('backgroundPosition', 'bottom left');
                      $('#rate-new-track_2').css('cursor', 'pointer');
                      $('#rate-new-track_2').css('backgroundPosition', 'bottom left');
                      $('#rate-new-track_3').css('cursor', 'pointer');
                      $('#rate-new-track_3').css('backgroundPosition', 'bottom left');
                      $('#rate-new-track_4').css('cursor', 'pointer');
                      $('#rate-new-track_4').css('backgroundPosition', 'bottom left');
                      $('#rate-new-track_5').css('cursor', 'pointer');
                      $('#rate-new-track_5').css('backgroundPosition', 'bottom left');


                      //add hover events to the rating stars
                      $('#rate-new-track_1').hover(function() { highlight_tracks('rate-new-track', 1); });
                      $('#rate-new-track_1').click(function() { set_rating(data.id, 'rate-new-track', 'rate-new-track', 1) });
                      $('#rate-new-track_2').hover(function() { highlight_tracks('rate-new-track', 2); });
                      $('#rate-new-track_2').click(function() { set_rating(data.id, 'rate-new-track', 'rate-new-track', 2) });
                      $('#rate-new-track_3').hover(function() { highlight_tracks('rate-new-track', 3); });
                      $('#rate-new-track_3').click(function() { set_rating(data.id, 'rate-new-track', 'rate-new-track', 3) });
                      $('#rate-new-track_4').hover(function() { highlight_tracks('rate-new-track', 4); });
                      $('#rate-new-track_4').click(function() { set_rating(data.id, 'rate-new-track', 'rate-new-track', 4) });
                      $('#rate-new-track_5').hover(function() { highlight_tracks('rate-new-track', 5); });
                      $('#rate-new-track_5').click(function() { set_rating(data.id, 'rate-new-track', 'rate-new-track', 5) });
                  }
            });
        }
        else
        {
            var change3 = check_track_change(null, null, null, null, null, null, null);

            $('#main-content-song h2').html(nosong);
            $('#main-content-song h3').html('&nbsp;');
            $('#album-info').css('display', 'none');
            $('#twitter_update').attr('href', '#');
            $('#facebook_update').attr('href', '#');

            $('#now-playing-image').attr('src', defaultArtwork);
            $('#album-info p.links a.btn-big').attr('href', '#');
            $('#album-info p.links a.btn-big').css("display", "none");
        }
    }
}

//checks whether the "now playing" track has changed. if it has then 
//we need to add the track to the play history list
function check_track_change(new_track_id, new_track_artist, new_track_title, new_average, new_amazon_image, new_amazon_url, new_itunes_url)
{
    //if track_id is null then we have just loaded the player so
    //populate it with an initial value
    if($.cookie('track_id') == null)
    {
       $.cookie('track_id',     new_track_id);
       $.cookie('track_artist', new_track_artist);
       $.cookie('track_title',  new_track_title);
       $.cookie('average',      new_average);

       //create the array of elements that are going to represent the
        //tracks retailer tracks
        var retailer_ar2 = new Array();
        retailer_ar2[0]    = '';
        retailer_ar2[1]    = new_amazon_image;
        retailer_ar2[2]    = new_amazon_url;
        retailer_ar2[3]    = new_itunes_url;

        //add the array to a cookie, i have had to searalize it (sort of)
        $.cookie('retailer', retailer_ar2.join(';'));

        return true;
    }

    //if the track has changed
    if(new_track_id != $.cookie("track_id"))
    {
        //if the track cookie is null it means that the last track to be played
        //was actually "this song is not available.." so we don't want to add that to
        //the last played
        if($.cookie('track_id') != null)
        {
            //retrieve the retailer affiliate info as this will provide the artwork
            var retailer_ar = $.cookie('retailer');

            //if these parameters are null it means there was no match from retailer
            //so we need to display the default
            var recently_played_image   = ''
            var amazon_buy_now_link     = '';
            var itunes_url              = '';
            if(retailer_ar == null)
            {
                recently_played_image  = defaultThumb;
                amazon_buy_now_link    = '';
                itunes_url             = '';
            }
            else
            {
                retailer_ar = retailer_ar.split(';');
                recently_played_image   = retailer_ar[1];
                amazon_buy_now_link     = retailer_ar[2];
                itunes_url              = retailer_ar[3];
            }

            prependLastPlayedTrack($.cookie('track_artist'), $.cookie('track_title'), recently_played_image, amazon_buy_now_link, $.cookie('average'), itunes_url)

            //create the array of elements that are going to represent the
            //tracks retailer tracks
            var retailer_ar2   = new Array();
            retailer_ar2[0]    = '';
            retailer_ar2[1]    = new_amazon_image;
            retailer_ar2[2]    = new_amazon_url;
            retailer_ar2[3]    = new_itunes_url;

            //add the array to a cookie, i have had to searalize it (sort of)
            $.cookie('retailer', retailer_ar2.join(';'));

            //set the new track id cookie
            $.cookie('track_id',        new_track_id);
            $.cookie('track_artist',    new_track_artist);
            $.cookie('track_title',     new_track_title);
            $.cookie('average',         new_average);

            $(document).pngFix();
        }
      
        return true;
    }
    else
    {
        return false;
    }
}

//highlights the stars for a rating depending on the mouse hover
function highlight_tracks(rating_id, rating)
{
    //set all the stars to unselected
    for(var j = 1; j <= 5; j++)
    {
        $('#' + rating_id + '_' + j).css('backgroundPosition', 'bottom left');
    }

    

    //highlight the current element and set all the previous ones to selected
    for(var i = 1; i <= rating; i++)
    {
       $('#' + rating_id + '_' + i).css('backgroundPosition', 'top left');
    }
}

//sets a track's rating
function set_rating(track_id, container_element, rating_id, rating)
{
    $.getJSON(domain + "/services/rate_track.php?t=" + track_id + "&r=" + rating + "&s=" + station_id, function(data){
        //check if an error has occurred during the rating
        if(data.error == "true"){}
        else
        {
            //there was no error so return the average rating
            $('#' + container_element).fadeOut('slow', function(){
                //set the new rating
                for(var j = 1; j <= 5; j++)
                {
                    $('#' + rating_id + '_' + j).css('backgroundPosition', 'bottom left');
                    $('#' + rating_id + '_' + j).unbind('mouseenter mouseleave')
                    $('#' + rating_id + '_' + j).unbind('click')
                    $('#' + rating_id + '_' + j).css('cursor', 'default');
                }

                //highlight the current element and set all the previous ones to selected
                for(var i = 1; i <= data.average; i++)
                {
                    $('#' + rating_id + '_' + i).css('backgroundPosition', 'top left');
                }

                $.cookie('average', data.average);

                $('#album-info #rate-new-track h4').html('Average Rating:');
                $('#' + container_element).fadeIn('slow');
            });
        }
    });

    track_event('ratetrack');
}

//gets the last tracks that were played
function getLastPlayed()
{
    $.getJSON(domain + "/services/latest_tracks.php?s=" + station_id, function(data){
        //check if an error has occurred during the rating
        if(data.error == "true"){}
        else
        {
            for(var i = 0; i < data.played.length; i++)
            {
                prependLastPlayedTrack(data.played[i].artist_name, data.played[i].title, data.played[i].amazon_thumb, data.played[i].amazon_url, data.played[i].average, data.played[i].itunes_url);
            }
        }

        $(document).pngFix();
    });
}

//prepends a track to the previously played list
function prependLastPlayedTrack(artist_name, track_title, artist_thumb, amazon_buy_now_link, average_rating, itunes_link)
{
    var rating = average_rating;

    var ratings_str = '';
    for(var i = 1; i <= 5; i++)
    {
        ratings_str += '<div class="'
        if(i > rating)
        {
            ratings_str += 'not-';
        }
        ratings_str += 'selected-small">&nbsp;</div>';

    }

    var buy_now_html = '';

    if((amazon_buy_now_link != '' && (typeof amazon_buy_now_link) != 'undefined') || (itunes_link != '' && (typeof itunes_link) != 'undefined'))
    {
        var random  = Math.floor(Math.random() * 10000);
        var div_id  = 'parent_' + random;
        var div_id2 = 'list_' + random;
        
        buy_now_html += '<div id="' + div_id + '" class="retailer-link-list-small">';
        buy_now_html += '<a href="javascript:void(0);" class="btn-pound-sm">&nbsp;</a>';
        buy_now_html += '<div id="' + div_id2 + '" class="list-retailers">';

       if(amazon_buy_now_link != '' && (typeof amazon_buy_now_link) != 'undefined')
       {
            buy_now_html += '<a class="list-retailers-item" href="' + amazon_buy_now_link + '" target="_blank">Amazon</a>';
       }
       if(itunes_link != '' && (typeof itunes_link) != 'undefined')
       {
            buy_now_html += '<a class="list-retailers-item" href="' + itunes_link + '" target="_blank">iTunes</a>';
       }

       buy_now_html += '</div></div>';
    }

    $('#tab-wrapper ul').prepend('<li>'
                                + '<img src="' + artist_thumb + '" alt="" class="thumb" />'
                                + '<div class="text">'
                                    + '<h4>' + artist_name + '</h4>'
                                    + '<h5>' + track_title + '</h5>'
                                    + '<div class="average-ratings">'
                                        + '<p>Average Rating:</p>'
                                        + ratings_str
                                    + '</div>'
                                    + '<div class="buy-nows">'
                                        +  buy_now_html
                                        + '<div class="clear">&nbsp;</div>'
                                    + '</div>'
                                    + '<div class="clear">&nbsp;</div>'
                                + '</div>'
                          + '</li>');
    
    if(amazon_buy_now_link != '' || itunes_link != '')
    {
        $('#' + div_id).mouseenter(function() {
              listRetailerLinks(div_id2);
              return false;
        });

        $('#' + div_id).mouseleave(function() {
              listRetailerLinks(div_id2);
              return false;
        });
    }
}

//diplay a link
function listRetailerLinks(retailer_obj)
{
    if($('#' + retailer_obj).is(":hidden"))
    {
        $('#' + retailer_obj).css('display', 'block');
    }
    else
    {
        $('#' + retailer_obj).css('display', 'none');
    }
}

//toggles the right tab
function toggleTab()
{
    $('#tab-wrapper').animate({width: 'toggle'});
    $('a#recent-tab').toggleClass('active');

    track_event('recentlyplayed');
}

//toggles the radio station list
function toggleStationList()
{
    $('#radiostations-wrapper').toggle(0);
    $('a#radiostation-link').toggleClass('active');

    track_event('stationlist');
}

//if GA has been added then track the event
function track_event(action)
{
    if((typeof pageTracker) != 'undefined')
    {
        if(isLive)
        {
            var listenMode = 'listenlive';
        }
        else
        {
            var listenMode = 'listenagain';
        }

        pageTracker._trackEvent('radioplayer', action, listenMode);
    }
}

///////////////////////////////////////////////////////////////////////////////
//
// Init the player when the document has loaded
//
////////////////////////////////////////////////////////////////////////////////

$(document).ready(function(){
        $('#tab-wrapper').hide();

        //assign actions to the recent tab
	$('a#recent-tab').click(function() {
            toggleTab();
            return false;
        });

        //assign actions to the radio stations link
        $('a#radiostation-link').click(function() {
            toggleStationList();
            return false;
        });
        
        //retailer links
        $('#retailer_links_lrg_wrapper').mouseenter(function() {
              listRetailerLinks('retailer_links_lrg');
              return false;
        });

        $('#retailer_links_lrg_wrapper').mouseleave(function() {
              listRetailerLinks('retailer_links_lrg');
              return false;
        });

        //set the listen type to null, this is used to determine what information
        //the user needs to be displayed
        $.cookie('listentype', null);
        $.cookie('track_id', null);

        getLastPlayed();
        onLoad_playerEmbed(); //embed the player
});
