/*
 * jYoutube 1.0 - YouTube video image getter plugin for jQuery
 *
 * Copyright (c) 2009 jQuery Howto
 *
 * Licensed under the GPL license:
 *   http://www.gnu.org/licenses/gpl.html
 *
 * Plugin home & Author URL:
 *   http://jquery-howto.blogspot.com
 *
 */
(function($){
    $.extend({
        jYoutube: function( url, size ){
            if(url === null){
                return "";
            }

            size = (size === null) ? "big" : size;
            var vid;
            var results;
            var regExp = /^.*((youtu.be\/)|(v\/)|(\/u\/\w\/)|(embed\/)|(watch\?))\??v?=?([^#\&\?]*).*/;
            results = url.match(regExp);

            vid = (results && (results[7].length == 11 )) ? results[7] : "";
        
            if(size == "small"){
                return "http://img.youtube.com/vi/"+vid+"/2.jpg";
            } else {
                return "http://img.youtube.com/vi/"+vid+"/0.jpg";
            }
        }
    })
})(jQuery);

function getYouTubeInfo(url, handleData) {
    if(url === null){
        return "";
    }    
    var regExp = /^.*((youtu.be\/)|(v\/)|(\/u\/\w\/)|(embed\/)|(watch\?))\??v?=?([^#\&\?]*).*/;
    var results = url.match(regExp);
    var vid = (results && (results[7].length == 11 )) ? results[7] : "";
    jQuery.ajax({
        url: "http://gdata.youtube.com/feeds/api/videos/"+vid+"?v=2&alt=json",
        dataType: "jsonp",
        success: function (data) {
            var otitle = data.entry[ "title" ].$t;            
            var ntitle = otitle.match('^(.*) - (.*)$');
            
            var song = (ntitle && (ntitle[2].length > 0 )) ? ntitle[2] : "";
            var artist = (ntitle && (ntitle[1].length > 0 )) ? ntitle[1] : otitle;
            
            handleData(artist, song);
        }
    });
}
