Sources.youtube = function() {
    var id = "youtube";
    var baseURL = 'api://www.youtube.com/?';
    Sources.register(id);
    
    var jsonScriptTag = null;
    
    channels = null;
    
    var catSearch = function(val)
    {
        var val = $("#youtube-channel").val();
        var url = 'http://gdata.youtube.com/feeds/api/channels?v=2&q=' + encodeURIComponent(val) + '&alt=json-in-script&callback=?';
        
        $.getJSON(url, ytCatCallback);
    };
    
    var ytCatCallback = function(json)
    {
        //console.log('yt callback1! ' + json.feed.title.$t);
        var q = json.feed.title.$t.replace('YouTube Channels matching query: ', '');
        var val = $("#youtube-channel").val();
       // console.log('q: ' + q);
        if (q != val)
        {
            //console.log('query does not match; rejecting');
            return;
        }
        
        var t;
        var e;
        var v;
        var id;
        var h = '<option style="font-weight: bold;;" value="">No results found, try a different search</option>';
        
        channels = new Array();
        
        if (json.feed.entry) {
            for (var i = 0; i < json.feed.entry.length; i++) {
                e = json.feed.entry[i];
                t = e.title.$t;
                //console.log(e.title.$t);
                
                for (var j=0; j < e.link.length; j++) {
                    if (e.link[j].rel == "alternate") {
                        if (!v) h = '';
                        v = e.link[j].href;
                    } else if (e.link[j].rel == "self") {
                        
                        var hr = e.link[j].href;
                        id = hr.substring(hr.lastIndexOf("/")+1, hr.indexOf("?"));
                        
                        //console.log('id: ' + id);
                    }
                }
                
                var fl = e.gd$feedLink[0];
                channels.push({ id:id, t:t, href:v, feed: fl.href, count: fl.countHint });
                
                if (!t)
                {
                    t = e.author[0].name.$t + "'s Channel";
                }
                if (t) {
                    // t += '   (' + fl.countHint + ' videos)';
                    h += '<option id="yt-channel-option-' + i + '" value="' + i + '">' + t + '</option>';
                }
                
                
            }
        }
        
        var sel = $("#youtube-channel-select");
        sel.html(h);
        sel.change(
             function(event)
             {
                 //console.log('youtube channel change');
                 var channel = channels[event.target.value];
                 showChannelInfo(channel.href);
                 
                 Wall.preview();
                // cooliris.embed.setFeedURL(channel.feed);
             }
        );
        //sel[0].selectedIndex=0;
        //sel.change();
        
        
    };
    
    var showChannelInfo = function(url)
    {
        if (url != '')
        {
            $("#youtube-channel-info").css("display", "block");
            $("#youtube-channel-link").attr("href", url);
            $("#youtube-channel-link").html(url);
            $("#youtube-channel-hint").text("Note: If no videos appear, make sure embedding is turned on in the channel.");
        } else {
            $("#youtube-channel-info").css("display", "none");
        }
    };
    
    return {
        id: id,
        displayName: 'YouTube',
        type: 'video',

        catSearch: catSearch,
        init: function() {
            $("#yt-category-section").hide();

            // time options
            $("#youtube-standard").change(
            function(event) {
                var yto = $("#youtube-time-options");
                if ($(this).find(":selected").hasClass("yt_time"))
                {
                    yto.show();
                    // $(this).after(yto);
                }
                else
                {
                    yto.hide();
                }
            });

            $("#youtube-channel").keyup(
                function(event) {
                    var kc = event.keyCode;

                    if (kc > 40 || kc == 8 || kc == 13)
                    {
                        catSearch($("#youtube-channel").val());
                    }
                    else if (kc == 40)
                    {
                        $("#youtube-channel-select").focus();
                    }
                    
                    event.preventDefault();
                });
            
            $("youtube-channel-select").keyup(
                    function(event)
                    {
                       // console.log('keycode: ' + event.keyCode);
                        if (event.keyCode == 38 && this.selectedIndex == 0)
                        {
                            $("#youtube-channel").focus();
                        }
                    });

            if ($("#youtube-channel").val() != '')
            {
                catSearch($("#youtube-channel").val());
            }
            
            $("#tab-what-youtube select").change(function() {
                if (!$(this).hasClass("no_preview")) {
                    Wall.preview();
                }
            });
            
            $("#youtube-opts").change(function(){
                if ($(this).val() == "standard") {
                    Wall.preview();
                }
            });
        },

        setState: function(feed) {
            $("#item-tab-what-youtube").click();
            
            var params = explodeQueryString(decodeURIComponent(feed.replace(baseURL, "")));
            console.log(params);
            if (params["user"]) {
                $("#youtube-opts").val("user").change();
                $('#youtube-user').val(params["user"]);
                if (params["type"]) {
                    $("#youtube-user-feed-opts").val(params["type"]);
                }
            }
            else if (params["search"]) {
                $("#youtube-opts").val("search").change();
                $('#youtube-keywords').val(params["search"]);
                if (params["sort"]) {
                    $("#youtube-orderby").val(params["sort"]);
                }
                if (params["time"]) {
                    $("#youtube-search-time").val(params["time"]);
                }
            }
            else if (params["type"]) {
                $("#youtube-opts").val("standard");
                $("#youtube-standard").val(params["type"]);
                if (params["time"]) {
                    $("#youtube-time").val(params["time"]);
                }
            }
        },
        
        getFeedURL: function() {
            var feedURL = baseURL;
            var feedType = $("#youtube-opts").val();
            var v;
            switch (feedType)
            {
            case 'search':
                v = $('#youtube-keywords').val();
                if (!v) feedURL = '';
                else
                {
                    feedURL += 'search=' + v;
                    v = $('#youtube-category').val();
                    if (v != "")
                        feedURL += '&category=' + v;
                    feedURL += '&time=' + $("#youtube-search-time").val();
                    feedURL += '&sort=' + $("#youtube-orderby").val();
                }
                break;
            case 'user':
                v = $('#youtube-user').val();
                if (!v) feedURL = '';
                else
                {
                    if (v.indexOf("http://www.youtube.com/user/") == 0) {
                        v = /http:\/\/www\.youtube\.com\/user\/(\w*)/.exec(v)[1];
                    }
                    feedURL += 'user=' + v;
                    v = $('#youtube-user-feed-opts').val();
                    if (v)
                        feedURL += '&type=' + v;
                }
                break;
            case 'channel':
                // use the straight up feed from the channel
                v = $('#youtube-channel-select').val();
                if (v)
                    feedURL = channels[v].feed;
                else
                    feedURL = '';
                break;
            case 'standard':
                var type = $("#youtube-standard").val();
                feedURL += 'type=' + type;
                var yto = $('#youtube-time-options');
                var has_time_section = {
                    'top_rated': true,
                    'top_favorites': true,
                    'most_viewed': true,
                    'most_discussed': true,
                    'most_responded': true
                };
                if (has_time_section[type])
                {
                    feedURL += '&time=' + $("#youtube-time").val();
                }
                break;
            }

            return feedURL;
        },

        isFeedURL: function(feedURL) {
            return (feedURL.indexOf(baseURL) == 0);
            // return false;
        }
    };
}();
    

