var MyChannel = function(options){
(function($){  
    
    this.options = {
        user : null,
        maxPageSize : 20,
        container : null,
		listtype : "uploads",
		showfirst : false,
		channellink : false
    };
	
	this.miniv = new Array();
	
    this.initialize = function(){
        if (options){
            for (var opt in options)
                this.options[opt] = options[opt];
        }

        var flashVersion = swfobject.getFlashPlayerVersion().major;
        if (flashVersion < 8) 
            alert("You are running version " + flashVersion + " of Adobe Flash player. YouTube player requires Adobe Flash player 8 or higher installed to view everything correctly.");

        this.container = $("#" + this.options.container);
        if (!this.container.length) 
            alert("Could not find '" + this.options.container + "' element!");
        else {
            this.container.addClass("mychannel");
            this.container.append('<div class="player"><div id="' + this.options.container + '_playerpanel"></div><div class="controls"></div></div><div class="videos"><div class="scroll"></div></div><div class="showVideoPanel"><img class="loading" src="modules/mod_jxtc_ytchannel/images/loadinfo.gif"></div><div class="visitMyChannel"></div>');
            
            var _this = this;
            var showVideosPanel = this.container.find(".showVideoPanel");
            var showVidesBtn = jQuery(document.createElement("a")).attr({
                "href" : "javascript:", 
                "class" : "showVidesBtn"
            }).append("See all videos").click(function(){
                _this.openVideosPanel();
            });

            var loadMoreVideosBtn = jQuery(document.createElement("a")).attr({
                "href" : "javascript:", 
                "class" : "loadMoreVideosBtn"
            }).append("Load more videos").click(function(){
                if (_this.state.nextPageLink){
                    _this.loadingState(true);
                    jQuery.getJSON(_this.state.nextPageLink + "&callback=?", function(response){
                        _this.workoutSearchResponse(response);
                        _this.loadingState(false);
                        _this.openVideosPanel(true);
                    });
                }
            });
			
			var visitMyChannel = this.container.find(".visitMyChannel");
			var visitMyYC = jQuery(document.createElement("a")).attr({
                "href" : "http://www.youtube.com/user/" + this.options.user,
				"target" : "_blank"
            }).append("Visit my youtube video channel")

            showVideosPanel.append(showVidesBtn     );    
            showVideosPanel.append(loadMoreVideosBtn);
			if (this.options.channellink) {
				visitMyChannel.append(visitMyYC);
			}else {
				visitMyChannel.css({
					"display": "none"
				});
			}
            this.search();
        }
    };
    
    this.search = function() {
        var url   = "http://gdata.youtube.com/feeds/api/users/" + this.options.user + "/" + this.options.listtype + "?callback=?&alt=json-in-script&orderby=published&max-results=" + this.options.maxPageSize;
        var _this = this;
        this.loadingState(true);
        jQuery.getJSON(url, function(response){
            _this.workoutSearchResponse(response);
            _this.loadingState(false);
            _this.openVideosPanel(true);
        });
    };
    
    this.workoutSearchResponse = function(response){
        var feed = response.feed;
        if (!feed) return;
        
        if (!this.state) {
            this.state = {
                data         : [],
                nextPageLink : "",
                printedTo    : 0
            };        
        }
        
        for (var i = 0; i < feed.entry.length; i++){
            var entry = feed.entry[i];
            this.state.data.push({
                description : entry.content.$t,
                title       : entry.title.$t,
                thumb       : entry.media$group.media$thumbnail[1].url,
                url         : entry.media$group.media$content  [0].url,
                duration    : entry.media$group.yt$duration.seconds
            });

            var d = entry.media$group.media$player[0].url.split("=");
            this.state.data[this.state.data.length - 1].id = (d[1]) ? d[1] : null;
        }

        for (var i = 0; i < feed.link.length; i++) 
            this.state.nextPageLink = (feed.link[i].rel == "next") ? feed.link[i].href : null;

        this.renderSearchResults();            
    };
    
    this.renderSearchResults = function() {
        var html   = "";    
        var img    = null;
        var videos = this.container.find(".videos");
        var scroll = videos.find(".scroll");

        if (!scroll.length) {
            var scroll = jQuery(document.createElement("div")).attr({"class": "scroll"});
            videos.append(scroll);
        }
        
        var _this  = this;
        for (var i = this.state.printedTo; i < this.state.data.length; i++){
            var d        = this.state.data[i];
            var thumbURL = {"background-image": "url(" + d.thumb + ")", "background-repeat": "no-repeat"};

            var li = jQuery(document.createElement("div")).bind("click", d, function(e){
                    _this.onThumbnailClick(e);
            });
			li.append("<img src='" + d.thumb + "' alt='' />");
			li.append("<p>" + d.title + "</p>").attr({"class" : "title"});
            scroll.append(li);
			
			if(i==0 && this.options.showfirst) li.click();
        }
        
        this.state.printedTo  = i;
        var showVideosPanel   = this.container .find(".showVideoPanel"   );
        var showVideosBtn     = showVideosPanel.find(".showVidesBtn"     );
        var loadMoreVideosBtn = showVideosPanel.find(".loadMoreVideosBtn");

        if (this.state.nextPageLink != null) {
            showVideosPanel  .css({"height" : "20px" });
            loadMoreVideosBtn.css({"display": "block"});
        } else {
            loadMoreVideosBtn.css({"display": "none" });
            showVideosPanel  .css({"height" : "0px"  });
        }
    };

    this.onThumbnailClick = function(event){
        this.createFlashPlayer(event.data);
    };
    
    this.createFlashPlayer = function(videoData){
        var _this = this;
        swfobject.embedSWF(videoData.url + "&fs=1", this.options.container + '_playerpanel', this.options.pwidth, this.options.pheight, "8", null, null, {allowfullscreen: "true"}, null, function(e){
            var panel = _this.container.find(".player");
            panel.animate({"height" : 400, "duration" : "slow"});
            _this.closeVideosPanel();
        });
    };
    
    this.openVideosPanel = function(scrollToBottom){
        var videos            = this.container .find(".videos"           );
        var showVideosPanel   = this.container .find(".showVideoPanel"   );
        var showVidesBtn      = showVideosPanel.find(".showVidesBtn"     );
        var loadMoreVideosBtn = showVideosPanel.find(".loadMoreVideosBtn");
        var scroll            = videos.find(".scroll");

        loadMoreVideosBtn.css({"display": (this.state.nextPageLink) ? "block" : "none"});
        showVidesBtn.css({"display":"none"});
        videos.css({"display" : "block"}).animate({"height" : scroll.innerHeight(), duration: "slow"}, 300);
    };

    this.closeVideosPanel = function(){
        var _this             = this;
        var videos            = this.container .find(".videos"           );
        var showVideosPanel   = this.container .find(".showVideoPanel"   );
        var showVidesBtn      = showVideosPanel.find(".showVidesBtn"     );
        var loadMoreVideosBtn = showVideosPanel.find(".loadMoreVideosBtn");
        
        showVidesBtn     .css({"display":"block"});
        loadMoreVideosBtn.css({"display":"none" });

        showVideosPanel.animate({"height" : 20, duration: "fast"});
        videos.animate({"height" : 0, "duration" : "slow"}, function(){
            videos.css({"display" : "none"});
        });
    };
    
    this.onPlayerLoad = function(player, videoData){
        this.player = player;
        this.setupPlayerEventHandlers();
        player.loadVideoById(videoData.id, "0");

        var panel = this.container.find(".player");
        panel.animate({"height" : 422, "duration" : "slow"});
        this.closeVideosPanel();
    };
    
    this.loadingState = function(on){
        this.container.find(".loading").css({"display" : (on) ? "" : "none"});
    };
    
    this.initialize();
	
})(jQuery);  
};
