/* BEGIN: collectionwidget/collectionwidget_controller */

var SHOWS_VIEW = 0,
    EPISODES_VIEW = 1;

function CollectionWidget()
{
    this.preloadedChannels = [];
}

CollectionWidget.prototype.init = function(_collectionWidgetModel) {

    this.collectionView = new CollectionWidgetView();

    rolloverController.init();

    var view = SettingsManager.getValue("collectionwidgetview");
    if (view) {
        this.options.view = view;
    }

    if(_collectionWidgetModel) {
        
        pageModel.addPlaylistEpisodes(_collectionWidgetModel.AllPlaylistEpisodes);
    
        this.CurrentChannel = _collectionWidgetModel.CurrentChannel;
        this.Channels = _collectionWidgetModel.Channels;
        
        this.updateChannelCovers(this.getCurrentChannelIndex());
        this.addPreloadedChannel(this.CurrentChannel);
    }
}


/***************************************************************
 * View Changer
 ***************************************************************/

CollectionWidget.prototype.toggleView = function(_view) {

    this.options.view = SettingsManager.setValue("collectionwidgetview", _view);
    this.collectionView.toggleView(_view);
    
    this.newestEpisodes();
}


/***************************************************************
 * Channel Changer
 ***************************************************************/

CollectionWidget.prototype.getChannels = function() {
    return this.Channels;
}

CollectionWidget.prototype.refresh = function() {

    if (this.CurrentChannel) {
    
        for(var i=0; i < this.preloadedChannels.length; i++) {
            if (this.preloadedChannels[i].Slug == this.CurrentChannel.Slug) {
                this.preloadedChannels.splice(i, 1);
                return;
            }
        }

        this.getChannel();
    }
}

CollectionWidget.prototype.channelLeft = function() {

    for(var i=0; i < this.Channels.length; i++) {
        if(this.Channels[i].Slug == this.CurrentChannel.Slug) {
            if(--i < 0) i = this.Channels.length-1;
            this.CurrentChannel = this.Channels[i];
            this.updateChannelCovers(i);
            
            this.getChannel();
            
            return;
        }
    }
}

CollectionWidget.prototype.channelRight = function() {

    for(var i=0; i < this.Channels.length; i++) {
        if(this.Channels[i].Slug == this.CurrentChannel.Slug) {
            i = (i+1) % this.Channels.length;
            this.CurrentChannel = this.Channels[i];
            this.updateChannelCovers(i);

            this.getChannel();

            return;
        }
    }
}

CollectionWidget.prototype.getCurrentChannelIndex = function() {

    for(var i=0; i < this.Channels.length; i++) {
        if(this.Channels[i].Slug == this.CurrentChannel.Slug) {
            return i;
        }
    }
    
    return 0;
}

CollectionWidget.prototype.getCurrentChannelSlug = function() {

    return this.CurrentChannel.Slug;
}

CollectionWidget.prototype.updateChannelCovers = function(_currentIndex) {
    this.collectionView.updateChannelCovers(_currentIndex, this.CurrentChannel);
}


/***************************************************************
 * Get it on
 ***************************************************************/

CollectionWidget.prototype.getItOn = function (_type, _channelSlug) {

    if (!_channelSlug)
        _channelSlug = this.CurrentChannel.Slug;

    rssController.launch(_type, _channelSlug);
}


/***************************************************************
 * Add & Remove episodes
 ***************************************************************/

CollectionWidget.prototype.addShow = function(_episode) {
    this.collectionView.addShow(_episode);
}

CollectionWidget.prototype.removeShow = function(_episode) {
    this.collectionView.removeShow(_episode);
}

CollectionWidget.prototype.addEpisodes = function(_episodes) {

    for(var i=0; i < _episodes.length; i++) {
        this.collectionView.addEpisode(_episodes[i]);
    }

    for(var i=0; i < _episodes.length; i++) {
        this.collectionView.showEpisode(_episodes[i]);
    }
}

CollectionWidget.prototype.removeEpisode = function(_episode) {
    this.collectionView.removeEpisode(_episode);
}



/***************************************************************
 * Add & Remove episodes
 ***************************************************************/

CollectionWidget.prototype.olderEpisodes = function() {

    if(this.options.view == "shows") {
        this.pagingNumber(this.CurrentChannel.ShowsPagingModel.Page+1);
    } else {
        this.pagingNumber(this.CurrentChannel.EpisodesPagingModel.Page+1);
    }
}

CollectionWidget.prototype.oldestEpisodes = function() {

    if(this.options.view == "shows") {
        this.pagingNumber(this.CurrentChannel.ShowsPagingModel.Pages);
    } else {
        this.pagingNumber(this.CurrentChannel.EpisodesPagingModel.Pages);
    }
}

CollectionWidget.prototype.newerEpisodes = function() {

    if(this.options.view == "shows") {
        this.pagingNumber(this.CurrentChannel.ShowsPagingModel.Page-1);
    } else {
        this.pagingNumber(this.CurrentChannel.EpisodesPagingModel.Page-1);
    }
}

CollectionWidget.prototype.newestEpisodes = function() {
    this.pagingNumber(1);
}

CollectionWidget.prototype.pagingNumber = function(_num) {

    if(this.options.view == "shows") {
        this.CurrentChannel.ShowsPagingModel.Page = _num;
        this.collectionView.pagePlaylist(this.CurrentChannel.ShowsPagingModel);
    } else {
        this.CurrentChannel.EpisodesPagingModel.Page = _num;
        this.collectionView.pagePlaylist(this.CurrentChannel.EpisodesPagingModel);
    }
}



CollectionWidget.prototype.getChannel = function() {

    if (isSpecialChannel(this.CurrentChannel.Slug)) {
        SettingsManager.setValue("collectionwidgetchannel", this.CurrentChannel.Slug);
    } else {
        SettingsManager.setValue("collectionwidgetchannel", this.CurrentChannel.Path);
    }

    this.collectionView.hidePlaylist();
    
    if(this.channelPreloaded(this.CurrentChannel)) {
        this.newestEpisodes();
    } else {
        var params = {
            displayLoader : false,
            doRefresh : false,
            onSuccess : function(_result) { collectionWidget.getChannelHandler(_result) },
            method : '/WebServices/CollectionWidgetService_v1_0.asmx/GetChannel',
            args : {channelSlug : this.CurrentChannel.Slug}
        };
        
        webService.invoke(params);
        
        this.collectionView.beginLoading();
    }
}

CollectionWidget.prototype.channelPreloaded = function(_currentChannel) {
    
    for(var i=0; i < this.preloadedChannels.length; i++) {
        if(this.preloadedChannels[i].Slug == _currentChannel.Slug || this.preloadedChannels[i].Slug == ALL_CHANNEL_SLUG) {
            return true;        
        }
    }
    
    return false;
}

CollectionWidget.prototype.addPreloadedChannel = function(_currentChannel) {
    this.preloadedChannels.push(_currentChannel);    
}

CollectionWidget.prototype.getChannelHandler = function(_result) {

    if(_result && _result.length > 0) {
        pageModel.addPlaylistEpisodes(_result);
        
        for (var i=0; i < _result.length; i++) {
            this.collectionView.addEpisode(_result[i]);
            this.collectionView.addShow(_result[i]);
        }
    }
    
    this.addPreloadedChannel(this.CurrentChannel);
    this.collectionView.endLoading();
        
    this.newestEpisodes();

    rolloverController.bindListeners();
}

/* BEGIN: collectionwidget/collectionwidget_view */

var MAX_EPISODES = 25;
var MAX_SHOWS = 18;
var PAGING_WIDTH = 120;

function CollectionWidgetView()
{
    this.bigCoverTemplate = TrimPath.parseDOMTemplate("bigCoverTemplate");
    this.mediumCoverTemplate = TrimPath.parseDOMTemplate("mediumCoverTemplate");
    this.smallCoverTemplate = TrimPath.parseDOMTemplate("smallCoverTemplate");
    
    this.playlistEpisodeTemplate = TrimPath.parseDOMTemplate("playlistEpisodeTemplate");
    this.playlistShowTemplate = TrimPath.parseDOMTemplate("playlistShowTemplate");
    
    this.collectionPagingTemplate = TrimPath.parseDOMTemplate("collectionPagingTemplate");
}

/***************************************************************
 * View Changer
 ***************************************************************/

CollectionWidgetView.prototype.toggleView = function(_view) {

    if(_view == SHOWS_VIEW) {
    
        $(".collectionEpisodesBrowser").hide();
        $(".collectionShowsBrowser").show();

    } else {

        $(".collectionEpisodesBrowser").show();
        $(".collectionShowsBrowser").hide();
    }
}


CollectionWidgetView.prototype.updateChannelCovers = function(_currentIndex, _currentChannel) {

    $('#selectedChannel').html(_currentChannel.Name);
    
    var channels = collectionWidget.getChannels();
    
    var a = [];
    for(var i=-2; i <= 2; i++) {
        
        var index = _currentIndex + i;
        if (index < 0) {
            index = channels.length - Math.abs(index);
        } else if(index > channels.length - 1) {
            index -= channels.length;
        }
        
        var channel = channels[index];
        channel.MarginLeft = 0;
                
        a.push(channel);
    }
    var channelFlipper = new Array(a[0], a[1], a[4], a[3], a[2]);

    var channelHtml = new StringBuilder();
    for(var i=0; i < channelFlipper.length; i++) {
    
        var channel = channelFlipper[i];
        channel.MarginLeft = 0;
        channel.MarginRight = 0;
    
        switch(i)
        {
        case 0:                
            channelHtml.append(this.smallCoverTemplate.process(channel));
            break;

        case 1:
            channel.MarginLeft = -18;
            channelHtml.append(this.mediumCoverTemplate.process(channel));
            break;
            
        case 4:
            channel.MarginLeft = -80;
            channelHtml.append(this.bigCoverTemplate.process(channel));
            break;
            
        case 3:
            channel.MarginLeft = 31;
            channel.MarginRight = -52;
            channelHtml.append(this.mediumCoverTemplate.process(channel));
            break;

        case 2:
            channel.MarginLeft = 87;
            channel.MarginRight = -121;
            channelHtml.append(this.smallCoverTemplate.process(channel));
            break;
        }    
    }
    
    $('.channelFlipperCovers').html(channelHtml.toString());
    
    if(_currentChannel.EpisodeSlug) {
        rolloverController.bindListeners();
    }
    
    var view = SettingsManager.getValue("collectionwidgetview");
    if(view == "shows") {
        this.updateWidgetPaging(_currentChannel.ShowsPagingModel);
    } else {
        this.updateWidgetPaging(_currentChannel.EpisodesPagingModel);
    }
}


/***************************************************************
 * Add & Remove episodes
 ***************************************************************/

CollectionWidgetView.prototype.addShow = function(_episode) {

    if ($('.collectionShows').find('.collectionShow.' + _episode.Show.Slug).size() == 0)
    {
        var html = this.playlistShowTemplate.process(_episode);
        
        var added = false;    
        $('.collectionShow').each(function() {
                
            if(!added) {

                var age = $(this).attr('age');
                if(_episode.SecondsOld > age) {
                    $(this).before(html);
                    added = true;
                }
            }
        });

        if (!added) {
            $('.collectionShows').prepend(html);
        }
        
        $('.collectionShows').find('.collectionShow.' + _episode.Show.Slug + ' > *').hide().oneTime(500, "showFadeIn", function() {
            $(this).fadeIn(500, null);
        });
    }
}

CollectionWidgetView.prototype.removeShow = function(_episode) {
    var div = $('.collectionShows').find('.collectionShow.' + _episode.Show.Slug);
    div.fadeOut(500, remove(div));
}

CollectionWidgetView.prototype.addEpisode = function(_episode) {

    if ($('.collectionEpisodes').find('.collectionEpisode.' + _episode.Slug).size() == 0)
    {
        var html = this.playlistEpisodeTemplate.process(_episode);    

        var added = false;    
        $('.collectionEpisode').each(function() {

            if(!added) {
                var age = $(this).attr('age');
                if(_episode.SecondsOld > age) {
                    $(this).before(html);
                    added = true;
                }
            }
        });
        
        if(!added) {
            $('.collectionEpisodes').append(html);
        }   
    } 
}

CollectionWidgetView.prototype.showEpisode = function(_episode) {
    $('.collectionEpisodes').find('.collectionEpisode.' + _episode.Slug).show();//"blind", {}, 750);
}

CollectionWidgetView.prototype.removeEpisode = function(_episode) {
    var div = $('.collectionEpisodes').find('.collectionEpisode.' + _episode.Slug);
    div.hide("blind", {}, 750, remove(div));
}

function remove(_div) {

    try {
    
	    setTimeout(function(){
		    _div.remove();
	    }, 1000);
	
	} catch(e) {}
};



/***************************************************************
 * Paging
 ***************************************************************/

CollectionWidgetView.prototype.pagePlaylist = function(_pagingModel) {
    
    var page = _pagingModel.Page;

    var showBegin = (page-1) * MAX_SHOWS;
    var showEnd = page * MAX_SHOWS;

    var showCount = 0;
    $('.collectionShow').each(function(){
        if($(this).hasClass(collectionWidget.CurrentChannel.Slug)) {
            if(showCount >= showBegin && showCount < showEnd) {
                $(this).show();
            } else {
                $(this).hide();
            }
            
            showCount++;
            
        } else {
            $(this).hide();
        }
    });
    
    if(showCount == 0) {
        $('#collectionShowsEmpty').show();
    } else {
        $('#collectionShowsEmpty').hide();
    }
    
    
    var episodeBegin = (page-1) * MAX_EPISODES;
    var episodeEnd = page * MAX_EPISODES;
    
    var episodeCount = 0;
    $('.collectionEpisode').each(function(){
        if($(this).hasClass(collectionWidget.CurrentChannel.Slug)) {
            if(episodeCount >= episodeBegin && episodeCount < episodeEnd) {
                $(this).show();
            } else {
                $(this).hide();
            }
            
            episodeCount++;
            
        } else {
            $(this).hide();
        }
    });
    
    if(episodeCount == 0) {
        $('#collectionEpisodesEmpty').show();
    } else {
        $('#collectionEpisodesEmpty').hide();
    }
    
    this.updateWidgetPaging(_pagingModel);
}

CollectionWidgetView.prototype.updateWidgetPaging = function(_pagingModel) {

    var page = _pagingModel.Page;
        
    var pagingObject = {
        pages : new Array()
    }
        
    var min = ((Math.ceil(page / PAGING_MAX) - 1) * PAGING_MAX) + 1;
    var max = (_pagingModel.Pages > min + (PAGING_MAX-1)) ? min + (PAGING_MAX-1) : _pagingModel.Pages;
    
    for(var i=min; i <= max; i++) {
        var inc = {
            number : ((min+max)-i),
            width : (PAGING_WIDTH / ((max-min)+1)) - 2
        };
        
        pagingObject.pages.push(inc);
    }
    
    var pagingHtml = this.collectionPagingTemplate.process(pagingObject);
    $('.collectionPaging').html(pagingHtml);
    
    $('.' + page + '_collectionPage').css("background", "#8c90d6").css("border", "solid 1px #3e44b6");

    
    if(page == 1) {
        $('.newerCollectionEpisodes').hide();
        $('.newerCollectionEpisodesInactive').show();
    } else {
        $('.newerCollectionEpisodes').show();
        $('.newerCollectionEpisodesInactive').hide();
    }
    
    if(page == _pagingModel.Pages) {
        $('.olderCollectionEpisodes').hide();
        $('.olderCollectionEpisodesInactive').show();
    } else {
        $('.olderCollectionEpisodes').show();
        $('.olderCollectionEpisodesInactive').hide();
    }
    
    if(pagingObject.pages[0].number == _pagingModel.Pages) {
        $('.lessCollectionArrow').hide();
    } else {
        $('.lessCollectionArrow').show();
    }
    
    if(pagingObject.pages[pagingObject.pages.length-1].number == 1) {
        $('.moreCollectionArrow').hide();
    } else {
        $('.moreCollectionArrow').show();        
    }
}

CollectionWidgetView.prototype.beginLoading = function() {
    $('.playlistLoader').show();
}

CollectionWidgetView.prototype.endLoading = function() {
    $('.playlistLoader').hide();
}


CollectionWidgetView.prototype.hidePlaylist = function() {

    $('.collectionEpisode').hide();
    $('.collectionShow').hide();
}

