function grooveId(url){
    var urlre = /song\/.*?\/(\d*?)([\?\/].*)?$/;
    var matches = urlre.exec(url)
    if(matches!=null){
        return matches[1];
    }
    else{
        return null;
    }
}

musicSource = { grooveshark:0, youtube:1 }

function searchGoogle(term, start){
    if(start === undefined){
        start=0;
    }
    $.getJSON('http://ajax.googleapis.com/ajax/services/search/web?v=1.0&q='
      +encodeURIComponent('site:listen.grooveshark.com inurl:"grooveshark.com/song/" ' + term)
      +'&start='+start+'&callback=?',function(d){
        var results=d['responseData']['results'];
        var $resultsul=$('#grooveresults ul');
        if(start==0){
            $resultsul.empty();
        }
        if(results.length==0){
           $resultsul.append('<li>No results :(</li>');
           $('#grooveresults .more').empty();
           return;
        }
        $.each(results,function(i,r){
            var url=r['unescapedUrl'];
            var title=r['titleNoFormatting'];
            var id=grooveId(url);
            if(id!=null){
            var $chooselink=$('<a/>').attr('class','result').attr('href',url).click(function(e){
                e.preventDefault();
                pickSong($(this).html(),musicSource.grooveshark,id)
            }).append(title.replace(/ \|.*/,""));
            var $listitem = $('<li/>');
            $chooselink.appendTo($listitem);
            playButton(musicSource.grooveshark,id).appendTo($listitem);
            $listitem.appendTo($resultsul);
            }
        });
        // Add more link if appropriate
        if(d['responseData']['cursor']['pages'].length>start/4+1){
            var $more = $('<a/>').attr('href','#')
                        .text('More...')
                        .click(function(e){
                            e.preventDefault();
                            searchGoogle(term, start+4);
                        });
            $more.appendTo($('#grooveresults .more').empty());
        }else{
            $('#grooveresults .more').empty();
        }

    });

}

function searchYoutube(term, start){
    var maxresults=6;
    if(start === undefined){
        var start=1;
    }
    $.getJSON('http://gdata.youtube.com/feeds/api/videos?q='
              +encodeURIComponent(term)
              +'&v=2&alt=jsonc&max-results='+maxresults+'&start-index='+start+'&format=5&restriction=ES&category=Music&callback=?',
          function(d){
                var $resultsul=$('#youtuberesults ul');
                if(start==1){
                    // New search, the empty list
                    $resultsul.empty();
                }
                if(typeof d['data']['items'] == 'undefined'){
                    // No results
                    $resultsul.append('<li>No results :(</li>');
                    $('#youtuberesults .more').empty();
                    return;
                } else{
                    var results=d['data']['items'];
                }
                var resultcount=0;
                $.each(results, function(i,r){
                    // Check if video is unavailable in any country
                    if(typeof r['restrictions']=='undefined'){
                        // Create the links for the results
                        var $chooselink=$('<a/>')
                            .attr('href','#')
                            .attr('class','result')
                            .click(function(e){
                                e.preventDefault();
                                pickSong($(this).html(),musicSource.youtube,r['id']);
                                })
                            .append(r['title']);
                        var $listitem = $('<li/>');
                        $chooselink.appendTo($listitem);
                        playButton(musicSource.youtube,r['id']).appendTo($listitem);
                        $listitem.appendTo($resultsul);
                        resultcount++;
                   }
                });

                var newstart;
                //if(start==1){
                //    newstart=maxresults;
                //}
                //else{
                    newstart=start+maxresults;
                //}
                if(newstart<d['data']['totalItems'] && newstart<1000){
                    //Search again if too many results discarded
                    if(resultcount<3){
                        searchYoutube(term, newstart);
                        return;
                    }
                    //Add more link
                    var $more = $('<a/>').attr('href','#')
                            .text('More...')
                            .click(function(e){
                                e.preventDefault();
                                searchYoutube(term, newstart);
                            });
                    $more.appendTo($('#youtuberesults .more').empty());

                }else{
                    $('#youtuberesults .more').empty();
                }
          });
}

function searchSong(term){
    searchGoogle(term);
    searchYoutube(term);
    $('#searchresults').show();
    $('#chosensongcontainer').hide();
    clearSong();
}

function setSong(source, id){
    $('#id_grooveid').val(id);
    if(source==musicSource.grooveshark){
        $('#id_source').val('grooveshark');
    }
    else{
        $('#id_source').val('youtube');
    }
}

function clearSong(){
    setSong(0,'');
}

function pickSong(title, source, id){
    setSong(source, id);
    $('#searchresults').hide();
    $('#chosensong').html('<span>' + title + '</span>').append(playButton(source,id)).parent().show();
}

function playButton(source, id){
    var button = $('<a/>')
                 .attr('href','#')
                 .attr('class','playbutton')
                 .click(function(e){
                     e.preventDefault();
                     if($(this).attr('class')=='playbutton'){
                         // Remove other previews
                         $('#searchresults .preview').remove();
                         $('#searchresults .stopbutton').attr('class','playbutton');

                         // Change to stop button
                         $(this).attr('class','stopbutton');

                         // Embed player
                         if(source==musicSource.youtube){
                             $(this).parent().append('<div class="preview"><object width="550" height="150"><param name="movie" value="http://www.youtube.com/v/' + id + '"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed src="http://www.youtube.com/v/' + id + '" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="550" height="150"></embed></object></div>');}
                         else if(source==musicSource.grooveshark){
                             $(this).parent().append('<div class="preview"><object width="250" height="40" data="http://listen.grooveshark.com/songWidget.swf?hostname=cowbell.grooveshark.com&songID=' + id + '&style=metal" type="application/x-shockwave-flash"> <param value="http://listen.grooveshark.com/songWidget.swf?hostname=cowbell.grooveshark.com&songID=' + id + '&style=metal" name="movie"/> <param value="always" name="allowScriptAccess"/></object></div>');   
                         }

                         // Select the song
                         setSong(source,id);

                     }
                     else{
                         // Remove preview and set to play button
                         $(this).siblings('.preview').remove();
                         $(this).attr('class','playbutton');
                         
                         // Unset song if played from search results
                         if($(this).parent().attr('id')!='chosensong'){
                             clearSong();
                         }

                     }
                 });
    return button;
}

$(document).ready(function(){

    $('#searchform').submit(function(e){
        e.preventDefault();
        var term=$('#searchtext').val();
        if(term==''){
            $('#songerrorbox').empty().text('You didn\'t enter a song');
        }else{
            $('#songerrorbox').empty();
            searchSong(term);
        }
    });

    $('#mainform').submit(function(e){
        if($('#id_grooveid').val()===''){
            $('#songerrorbox').empty().text('You didn\'t choose a song');
            return false;
        }else if($('#id_message').val()===''){
            $('#messageerrorbox').empty().text('You didn\'t enter a message');
            return false;
        }
    });

});
