// State for event handlers
var state = 'init';

// Used only to remember last song title
var clipTitle = '';  

// Timeout to scrobble track ater minimum time passes
var scrobbleTimeout = null;

// Glabal constant for the song container ....
var CONTAINER_SELECTOR = '#playerSongInfo';


$(function(){   
	$(CONTAINER_SELECTOR).live('DOMSubtreeModified', function(e) {

		if ($(CONTAINER_SELECTOR).length > 0) {
			updateNowPlaying();
			return;    
		}

   });
   
   console.log("Last.fm Scrobbler: starting Google Music connector")
   
   // first load
   updateNowPlaying();
});

/**
 * Called every time we load a new song
 */ 
function updateNowPlaying(){
    var parsedInfo = parseInfo();
    artist   = parsedInfo['artist']; 	//global
    track    = parsedInfo['track'];	//global
    duration = parsedInfo['duration']; 	//global
	
    if (artist == '' || track == '' || duration == 0) {return;}
    
    // check if the same track is being played and we have been called again
    // if the same track is being played we return
    if (clipTitle == track) {
	return;
    }
    clipTitle = track;
    
    chrome.extension.sendRequest({type: 'validate', artist: artist, track: track}, function(response) {
	if (response != false) {
	    chrome.extension.sendRequest({type: 'nowPlaying', artist: artist, track: track, duration: duration});
	}
         // on failure send nowPlaying 'unknown song'
         else {
            chrome.extension.sendRequest({type: 'nowPlaying', duration: duration});
         }
    });
}


function parseInfo() {
    var artist   = '';
    var track    = '';
    var duration = 0;

    // Get artist and song names
    var artistValue = $("div#player-artist").text();
    var trackParent = $("div#playerSongTitle");
    var durationValue = $("span#duration").text();
    
    try {
        if (null != artistValue) {
            artist = artistValue.replace(/^\s+|\s+$/g,'');
        }
        if (null != trackParent) {
            track = $("div.fade-out-content", trackParent).text();
            track = track.replace(/^\s+|\s+$/g,'');
        }
        if (null != durationValue) {
            duration = parseDuration(durationValue);
        }
    } catch(err) {
        return {artist: '', track: '', duration: 0};
    }
    
	//console.log("artist: " + artist + ", track: " + track + ", duration: " + duration);
	
    return {artist: artist, track: track, duration: duration};
}

function parseDuration(artistTitle) {
	try {
		match = artistTitle.match(/\d+:\d+/g)[0]

		mins    = match.substring(0, match.indexOf(':'));
		seconds = match.substring(match.indexOf(':')+1);
		return parseInt(mins*60) + parseInt(seconds);
	} catch(err){
		return 0;
	}
}


/**
 * Simply request the scrobbler.js to submit song previusly specified by calling updateNowPlaying()
 */ 
function scrobbleTrack() {
   // stats
   chrome.extension.sendRequest({type: 'trackStats', text: 'The Google Music song scrobbled'});
   
   // scrobble
   chrome.extension.sendRequest({type: 'submit'});
}



/**
 * Listen for requests from scrobbler.js
 */ 
chrome.extension.onRequest.addListener(
	function(request, sender, sendResponse) {
		switch(request.type) {
    	// called after track has been successfully marked as 'now playing' at the server
      case 'nowPlayingOK':
         /*
        var min_time = (240 < (duration/2)) ? 240 : (duration/2); //The minimum time is 240 seconds or half the track's total length. Duration comes from updateNowPlaying()
        
				// cancel any previous timeout
        if (scrobbleTimeout != null)
      		clearTimeout(scrobbleTimeout);
               
       		// set up a new timeout
        	scrobbleTimeout = setTimeout(function(){setTimeout(scrobbleTrack, 2000);}, min_time*1000); 
            */
          break;
            
        // not used yet
        case 'submitOK':
       		break;

        // not used yet
        case 'submitFAIL':
          break; 
    }
	}
);
@@ -778,24 +778,60 @@
 %5D;%09//global%0A
+    album    = parsedInfo%5B'album'%5D;%0A
     duration
@@ -1345,32 +1345,46 @@
 t, track: track,
+ album: album,
  duration: durat
@@ -1631,32 +1631,55 @@
  track    = '';%0A
+    var album    = '';%0A
     var duration
@@ -1784,22 +1784,21 @@
 ar track
-Parent
+Value
  = $(%22di
@@ -1816,16 +1816,74 @@
 gTitle%22)
+.text();%0A    var albumValue = $(%22div.player-album%22).text()
 ;%0A    va
@@ -1907,13 +1907,27 @@
  $(%22
-span#
+div#time_container_
 dura
@@ -2085,22 +2085,21 @@
 != track
-Parent
+Value
 ) %7B%0A    
@@ -2118,67 +2118,63 @@
 k = 
-$(%22div.fade-out-content%22, trackParent).text(
+trackValue.replace(/%5E%5Cs+%7C%5Cs+$/g,''
 );%0A    
+    %7D%0A
         
 trac
@@ -2169,29 +2169,72 @@
         
-track = track
+if (null != albumValue) %7B%0A            album = albumValue
 .replace
@@ -2506,16 +2506,38 @@
 ack + %22,
+ album: %22 + album + %22,
  duratio
@@ -2597,16 +2597,30 @@
 : track,
+ album: album,
  duratio

add album parsing to google music