﻿function OnToggleChannelPodcastsCollectionComplete(result, userContext) {
  
    var text;
    if (result) {
        text = "Remove podcasts from Collection";
    } else {
        text = "Add podcasts to Collection";
    }

    $('div[channelId=' + userContext + '] li.collection').text(text);

    CastThree.ChannelService.GetCollectionPodcasts(OnGetCollectionComplete);
    
}

function OnCheckChannelPodcastsCollectionComplete(result, userContext) {
    var text;
    if (result) {
        text = "Remove podcasts from Collection";
    } else {
        text = "Add podcasts to Collection";
    }

    $('div[channelId=' + userContext + '] li.collection').text(text);
}

function OnGetCollectionComplete(result) {
    $('#channelBar').show();
    $('#channelBar h3').text("Your Collection");
    $('#channelBar .content').html(result);
}

function OnUpdateChannelComplete(result, userContext) {


    if (result > 0) {
        window.location = window.location + "?newEpisodes=" + result.toString();
    } else {
        $('div[channelId=' + userContext + '] li.refresh').text("Found no new episodes");
        $('div[channelId=' + userContext + '] li.refresh').removeClass("refresh-active");
    }

}



$(function() {
    pageCategory = 'Channel';

    $('.actions .collection').click(function(ex) {


        var channelId = parseInt($(this).parents("div:first").attr("channelId"));
        try {
            CastThree.ChannelService.ToggleChannelPodcastsCollection(channelId, OnToggleChannelPodcastsCollectionComplete, null, channelId, null);
        } catch (ex) {
            alert(ex);
        }

    });

    $('.actions .collection').each(function(ex) {

        var channelId = parseInt($(this).parents("div:first").attr("channelId"));
        CastThree.ChannelService.CheckChannelPodcastsCollection(channelId, OnCheckChannelPodcastsCollectionComplete, null, channelId, null);
    });

    $('.actions .refresh').click(function(e) {
        var podcastId = parseInt($(this).parents("div:first").attr("channelId"));
        $(this).text("Updating");
        $(this).addClass("refresh-active");
        CastThree.ChannelService.UpdateChannel(podcastId, OnUpdateChannelComplete, null, podcastId, null);
    });

    var newEpisodes = querySt("newEpisodes");
    if (newEpisodes) {
        if (newEpisodes > 1) {
            text = "Found " + newEpisodes + " new episodes";
        } else if (newEpisodes == 1) {
            text = "Found one new episode"
        }
        $('div li.refresh').text(text);
    }


});