function onYouTubePlayerReady(id){
    var player=document.getElementById('ytplayer');
    player.playVideo();
    player.unMute();
    player.setVolume(100);
    player.addEventListener("onStateChange", "youtubeStateChange");
    player.addEventListener("onError", "youtubeError");
}

function youtubeError(code){
    var player=document.getElementById('ytplayer');
    if(code==100){
        document.getElementById('error').innerHTML='The video does not appear to be available in your region :(';
    }
    else if(code==101 || code==150){
        document.getElementById('error').innerHTML="This video isn't embeddable in your region, <a target='_blank' href='" + player.getVideoUrl() + "'>watch on Youtube</a>";
    }
}


function youtubeStateChange(state){
    if(state==1){ //playing
        document.getElementById('playpause').style.backgroundPosition="50px 0";
    }
    else if(state==2 || state==0){ //paused
        document.getElementById('playpause').style.backgroundPosition="0 0";
    }
}

function searchYoutube(term){
    $.getJSON('http://gdata.youtube.com/feeds/api/videos?q='+encodeURIComponent(term)+'&v=2&alt=jsonc&max-results=10&format=5&callback=?',function(d){
        var videos=d['data']['items']
        var $results=$('#searchresults ul');
        $results.html('');
        $.each(videos,function(i,v){
            var id=v['id']
            var thumb=''
            if(typeof v['thumbnail']['sqDefault'] != 'undefined'){
                thumb='<img src="' + v['thumbnail']['sqDefault'] + '">';
            }
            var $swaplink=$('<a/>').attr('href','http://youtube.com/watch?v='+id).click(function(e){
                e.preventDefault();
                $('#id_videoid').val($(this).attr('href'));
                document.location.href='#videoform';
            }).append('Swap');
            var $listitem = $('<li/>');
            $listitem.append('<a href="http://youtube.com/watch?v=' + id + '" target="_blank">' + thumb + v['title'] + '</a> | ');
            $swaplink.appendTo($listitem);
            $listitem.appendTo($results);
            });
        document.location.href='#searchform';
    });

}

$(document).ready(function(){
    $('#playpause').click(function(){
    var player=$('#ytplayer')[0];
    var state=player.getPlayerState();
        if(state==1){ //playing
            player.pauseVideo();
        }
        else if(state==2){ //paused
            player.playVideo();
        }
        else if(state==0){ //ended
            player.seekTo(0);
            player.playVideo();
        }
            
    });    

    $('#searchform').submit(function(e){
        e.preventDefault();
        searchYoutube($('#searchtext').val());
    });
});

