var fi = fi || {};
fi.component = fi.component || {};
Date.prototype.getMonthStr = function() {
    var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sept', 'Oct', 'Nov', 'Dec'];
    return months[this.getMonth()];
};
fi.component.YouTubeTop10 = function($context) {
    this.$context = $context;
    this.$info = $(".info", this.$context);
    this.$title = $(".info h2", this.$context);
    this.$meta = $(".info p.meta", this.$context);
    this.$likes = $(".info ul.meta-stats li.likes", this.$context);
    this.$disLikes = $(".info ul.meta-stats li.dislikes", this.$context);
    this.$views = $(".info ul.meta-stats li.views", this.$context);
    this.$thumb = $(".thumb", this.$context).clone();
    this.$marquee = $(".grey-marquee", this.$context);
    this.$itemList = $(".items ul", this.$context);
    this.marquee = null;
    this.player = null;
    this.model = null;
    this.index = null;
    this.data = null;
    this.callbacks = {
        onThumbnailClicked: $.proxy(this.onThumbnailClicked, this)
    };
};

fi.component.YouTubeTop10.META_TEMPLATE = 'Uploaded by <a href="http://www.youtube.com/user/${author}" target="_blank"><b>${author}</b></a> on ${date_uploaded}';
fi.component.YouTubeTop10.prototype = {
    init: function() {
        this.model = new fi.models.YouTube();
        this.model.addListener(this.onModelReady, this);
        if (this.$context.hasClass('trending-videos')) {
          fi.component.YouTubeTop10.FEED_URI = "http://gdata.youtube.com/feeds/api/users/sparkleplaylist/favorites?v=2&prettyprint=false&alt=json";
        }
        else {
          fi.component.YouTubeTop10.FEED_URI = "http://gdata.youtube.com/feeds/api/standardfeeds/on_the_web?v=2&prettyprint=false&alt=json&max-results=10";
        }
        this.model.load(fi.component.YouTubeTop10.FEED_URI);
        this.marquee = fi.common.ComponentLoader.findInstanceById("top10-marquee");
        this.player = fi.common.ComponentLoader.findInstanceById("top10-player");
        this.player.embedFlash();
        this.$context.parent().after(this.$marquee);
        this.$thumb.remove();
    },
    populate: function() {
        var video,
        thumb;
        this.index = {};
        for (var i = 0, n = this.data.length; i < n; ++i) {
            video = this.data[i];
            thumb = this.$thumb.clone();
            thumb.attr("data-id", video.id);
            thumb.find("a").remove();
            thumb.find(".image").html("<img>");
            thumb.find(".image img").attr("width", 130);
            thumb.find(".image img").attr("height", 80);
            thumb.find(".image img").attr("src", video.media.thumbs["default"].url);
            thumb.find('h5').html(video.title);
            thumb.bind("click", this.callbacks.onThumbnailClicked);
            this.$itemList.append(thumb);
            this.index[video.id] = video;
        }
        $(".items", this.$context).css("height", 230);
        $("h5", this.$context).css("height", 40);
        this.marquee.init();
        this.play(this.data[0].id);
    },
    play: function(videoID, autoplay) {
        var video = this.index[videoID];
        if (typeof(video) !== "null") {
            var dateString = video.media.uploaded.substring(0, 10).replace(/\-/gi, '/');
            var formattedDate = this.formatUploadDate(new Date(dateString));
            var innerHTML = fi.component.YouTubeTop10.META_TEMPLATE.replace(/\${author}/gi, video.author.name).replace(/\${date_uploaded}/gi, formattedDate);
            this.$title.html(video.title);
            this.$meta.html(innerHTML);
            this.$likes.html(this.addCommas(video.likes.numLikes));
            this.$disLikes.html(this.addCommas(video.likes.numDislikes));
            this.$views.html(this.addCommas(video.statistics.viewCount));
            this.player.play(videoID, !!autoplay);
        }
    },
    formatUploadDate: function(date) {
        return date.getMonthStr() + ' ' + date.getDate() + ', ' + date.getFullYear();
    },
    addCommas: function(num) {
        num = num.split("").reverse().join("");
        num = num.replace(/(\d\d\d)(?=\d)/g, "$1,");
        num = num.split("").reverse().join("");
        return num;
    },
    onThumbnailClicked: function(event) {
        $(".thumb").removeClass("selected");
        var item = $(event.currentTarget);
        item.addClass("selected");
        var video = item.data("id");
        this.play(video, true);
        return false;
    },
    onModelReady: function(videos, scope) {
        scope.data = videos;
        scope.populate();
    }
};
fi.common.ComponentLoader.register("youtube-top10", fi.component.YouTubeTop10);
