/*
 * Chrome-Last.fm-Scrobbler jango.com connector
 * (c) 2012 Stephen Hamer <stephen.hamer@gmail.com>
 */

// The attach_artist_pic method gets called in the evaluated javascript
// returned when songs are switched to update the pictures associated with the
// artist. This method is used as the trigger for scrobbling the song.
var orig_attach_artist_pic;

function chromeLastFMUpdateNowPlaying(skip_callback){
  var sm = _jp.soundManager;
  var duration = sm.sounds[sm.soundIDs[sm.soundIDs.length - 1]].duration / 1000;

  // We can start updating the attached pics before the sound manager has
  // loaded the track (and knows the duration). If so, poll the sound manager for
  // duration.
  if (duration === 0) {
    setTimeout(function() { chromeLastFMUpdateNowPlaying(true) }, 1000);
  } else {
    var songInfo = {'title': _jm.song_info.song, 'artist': _jm.song_info.artist, 'duration': duration};
    var commDiv = document.getElementById('chromeLastFM');
    commDiv.innerText = JSON.stringify(songInfo);
  }

  // Only call the original method once, don't call it each time we poll the
  // sound manager for the song duration
  if (!skip_callback) {
    orig_attach_artist_pic();
  }
}

function waitUi() {
  //console.log("waiting for _jui");
  if (window["_jui"] === undefined || _jui.jango_player === undefined) {
    setTimeout(waitUi, 1000);
    return;
  }
  orig_attach_artist_pic = _jui.jango_player.attach_artist_pic.bind(_jui.jango_player);
  _jui.jango_player.attach_artist_pic = chromeLastFMUpdateNowPlaying;
}
waitUi();

@@ -439,143 +439,30 @@
 er;%0A
+%0A
   
-var duration = sm.sounds%5Bsm.soundIDs%5Bsm.soundIDs.length - 1%5D%5D.duration / 1000;%0A%0A  // We can start updating the attached pics before t
+if (!sm) %7B%0A    // T
 he s
@@ -481,21 +481,19 @@
  has
-%0A  //
+n't
  loaded 
 the 
@@ -492,116 +492,64 @@
 ded 
-the track (and knows the duration). If so, poll the sound manager for%0A  // duration.%0A  if (duration === 0) %7B
+yet, poll for it to load so we can get the song details.
 %0A   
@@ -618,16 +618,17 @@
  1000);%0A
+%0A
   %7D else
@@ -630,16 +630,573 @@
  else %7B%0A
+    var latest_sound = sm.sounds%5Bsm.soundIDs%5Bsm.soundIDs.length - 1%5D%5D;%0A%0A    var duration = null;%0A    if (latest_sound.bytesLoaded === null %7C%7C latest_sound.bytesLoaded != latest_sound.bytesTotal) %7B%0A      // The soung is still loading, continue to poll for it to load.%0A      setTimeout(function() %7B chromeLastFMUpdateNowPlaying(true) %7D, 5000);%0A    %7D else %7B%0A      duration = latest_sound.duration / 1000;%0A    %7D%0A%0A    // We can start updating the attached pics before the sound manager has%0A    // loaded the track (and knows the duration).%0A    if (duration) %7B%0A  
     var 
@@ -1291,16 +1291,18 @@
 ation%7D;%0A
+  
     var 
@@ -1356,16 +1356,18 @@
 ');%0A    
+  
 commDiv.
@@ -1404,16 +1404,22 @@
 gInfo);%0A
+    %7D%0A
   %7D%0A%0A  /

fix incorrect song duration from jango connector