var MyChannel = function(options){
    
    this.options = {
        user : null,
        maxPageSize : 20,
        container : null
    };

    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="../wp-content/themes/val2010/youtube/images/loadinfo.gif"></div>');
            
            var _this = this;
            var showVideosPanel = this.container.find(".showVideoPanel");
            var showVidesBtn = jQuery(document.createElement("a")).attr({
                "href" : "javascript:", 
                "class" : "showVidesBtn"
            }).append("Visa filmer").click(function(){
                _this.openVideosPanel();
            });

            var loadMoreVideosBtn = jQuery(document.createElement("a")).attr({
                "href" : "javascript:", 
                "class" : "loadMoreVideosBtn"
            }).append("Visa fler").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);
                    });
                }
            });

            showVideosPanel.append(showVidesBtn     );    
            showVideosPanel.append(loadMoreVideosBtn);    

            this.search();
        }
    };
    
    this.search = function() {
        var url   = "http://gdata.youtube.com/feeds/api/users/" + this.options.user + "/uploads?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({
                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")).css(thumbURL).bind("click", d, function(e){
                    _this.onThumbnailClick(e);
            }).append("<p>" + d.title + "</p>").attr({"class" : "title"});
            
            scroll.append(li);
        }
        
        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" : "40px" });
            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&rel=0", this.options.container + '_playerpanel', "480", "385", "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"}, function(){
            
        });
    };

    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" : 40, 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" : 385, "duration" : "slow"});
        this.closeVideosPanel();
    };
    
    this.loadingState = function(on){
        this.container.find(".loading").css({"display" : (on) ? "" : "none"});
    };
    
    this.initialize();
};
