﻿var playerSeconds;
var playerDuration;
var pageCategory = 'Undefined';
var savingTime = false;

function querySt(ji) {
    hu = window.location.search.substring(1);
    gy = hu.split("&");
    for (i = 0; i < gy.length; i++) {
        ft = gy[i].split("=");
        if (ft[0] == ji) {
            return ft[1];
        }
    }
}


function OnToggleStarEpisodeComplete(result, userContext) {
    SetStarredResult(result, userContext);
    CastThree.ChannelService.GetStarredEpisodes(OnGetStarredEpisodesComplete);
}

function ToggleEpisodeShared(episodeId, note) {
    CastThree.ChannelService.ToggleEpisodeShared(episodeId, note, OnToggleshareEpisodeComplete, null, episodeId, null);

    if ($(".episode[episodeId=" + episodeId + "] li.share .desc").html().match("Undo")) {
        SetSharedResult(false, episodeId);
        $('#fade').html("<div>Removed from shared episodes</div>");
    }
    else {
        SetSharedResult(true, episodeId);
        $('#fade').html("<div>Episode shared with your contacts</div>");
    }
    DoFade();
}

function OnCheckEpisodeStarredComplete(result, userContext) {
    SetStarredResult(result, userContext);
}

function SetStarredResult(result, episodeId) {
    var text;
    if (result) {
        text = "Undo Star";
        $('.episode[episodeId=' + episodeId + '] li.star').addClass("star-active");
    } else {
        text = "Star";
        $('.episode[episodeId=' + episodeId + '] li.star').removeClass("star-active");
    }

    $('.episode[episodeId=' + episodeId + '] li.star').text(text);

}



function OnToggleshareEpisodeComplete(result, userContext) {
    SetSharedResult(result, userContext);

    CastThree.ChannelService.GetSharedEpisodes(OnGetSharedEpisodesComplete);

}

function OnCheckEpisodeSharedComplete(result, userContext) {
    SetSharedResult(result, userContext);

}

function SetSharedResult(result, episodeId) {
    var text;
    if (result) {
        text = "Undo share";
        $('.episode[episodeId=' + episodeId + '] li.share').addClass("share-active");
    } else {
        text = "Share";
        $('.episode[episodeId=' + episodeId + '] li.share').removeClass("share-active");
    }

    $('.episode[episodeId=' + episodeId + '] li.share .desc').text(text);
}


function OnGetPlayerComplete(result, userContext) {
    $('#playerContent').html(result);

    $('.episode[episodeId=' + userContext + '] li.play').text("Stop");
    $('#popout').click(function(e) {
        window.open($(this).attr('url'), "popout", "toolbar=no,width=" + $(this).attr('popwidth') + ",height=" + $(this).attr('popheight'));
        $('#player').slideUp();
    });
}

function OnGetStarredEpisodesComplete(result) {
    $('#channelBar').show();
    $('#channelBar h3').text("Starred Episodes");
    $('#channelBar .content').html(result);
}

function OnGetSharedEpisodesComplete(result) {
    $('#channelBar').show();
    $('#channelBar h3').text("Shared Episodes");
    $('#channelBar .content').html(result);
}

function HideSharePanel(panel) {
    $(panel).slideUp(function(e) { $(panel).remove(); });
}

function OnGetSharePanelComplete(result, episodeId) {
    $('.episode[episodeId=' + episodeId + '] li.share').append(result);

    var panel = $('.episode[episodeId=' + episodeId + '] li.share .sharePanel');
    $(panel).slideDown();

    $(panel).children('.shareNote').click(function(e) {
        $(panel).children('.note').slideDown();
        return false;
    });

    $(panel).children('.shareContact').click(function(e) {
        $(panel).children('.contacts').slideDown(function() {
            $(panel).children('.note').slideDown();
        });



        return false;
    });

    $(panel).children('.note').children('.sbutton').click(function(e) {
        var contactId = parseInt($('select#contacts').val());
        var note = $(panel).children('.note').children('textarea').val();
        if (contactId == 0) {
            ToggleEpisodeShared(episodeId, note);
        } else {
            CastThree.ChannelService.ShareEpisodeContact(episodeId, note, contactId, null, null, episodeId, null);
            $('#fade').html("<div>Episode shared with single contact</div>");
            DoFade();
        }

        HideSharePanel(panel);
    });

    $(panel).children('.note').children('.cbutton').click(function(e) {
        HideSharePanel(panel);
    });

    $(panel).hover(function(e) { }, function(e) {
        if ($(panel).children('.note:visible').length == 0) {
            HideSharePanel(panel);
        }
    });

}
function DoFade()
{
    $('#fade div').fadeIn("slow").animate({opacity: 1.0}, 3000).fadeOut("slow");
}

function RequireLogin(message) {
    var userId = $.cookie('userId');

    if (userId && userId > 0) {
        return true;
    } else {
    $('#popupMessage').html(message);
    $('#popupInfo').show();
        $('.popupLogin').show();
        return false;
    }
}

var player = null;

function getCurrentIndex() {
    var allItems = $('.playlist li');

    for (var i = 0; i < allItems.length; i++) {
        if ($(allItems[i]).hasClass('playing')) {
            return i;
        }
    }
}

function playNext() {
    var allItems = $('.playlist li');

    var nextIndex = (getCurrentIndex() + 1) % allItems.length;

    playItem($(allItems[nextIndex]).children('a:first'));
}

function playerState(obj) {
    currentState = obj.newstate;
    var percent = Math.round(playerSeconds / playerDuration * 100);
    if (currentState == "COMPLETED") {
        pageTracker._trackEvent(pageCategory, 'Stop', player.getPlaylist()[0].file, 100);
        pageTracker._trackEvent(pageCategory, 'Complete', player.getPlaylist()[0].file);
        playNext();
    } else if (currentState == "BUFFERING") {

    } else if (currentState == "PLAYING") {
        if (querySt('start') != null) {
            var start = parseInt( querySt('start') );
            if (start > 0) {
                pageTracker._trackEvent(pageCategory, 'Resume', player.getPlaylist()[0].file, start);
                player.sendEvent('SEEK', start);
            }
            
        } else {
            pageTracker._trackEvent(pageCategory, 'Play', player.getPlaylist()[0].file);
        }
    } else if (currentState == "PAUSED") {
        pageTracker._trackEvent(pageCategory, 'Pause', player.getPlaylist()[0].file, percent);
    } else if (obj.oldstate == "PLAYING" && currentState == "IDLE") {
        pageTracker._trackEvent(pageCategory, 'Stop', player.getPlaylist()[0].file, percent);
    }
}

function OnMarkEpisodePlayedComplete() {
    savingTime = false;
}

function playerTime(obj) {
    playerDuration = obj.duration;
    playerSeconds = obj.position;

    if ( !savingTime && ( playerSeconds % 30 == 0 || ( playerSeconds < 10 && playerSeconds % 2 == 0 ) ) ) {
        var episodeId = parseInt($('li.playing').find('a').attr("episodeId"));
        if (episodeId > 0) {
            savingTime = true;
            CastThree.PlayerService.MarkEpisodePlayed(episodeId, playerSeconds + "," + playerDuration, OnMarkEpisodePlayedComplete, null, null);
    
        }
    }

}

function playFile(file, image) {
    player.sendEvent('LOAD', { file: file, image: image });
    player.sendEvent('PLAY');
    savingTime = false;
}


function playerReady(thePlayer) {
    savingTime = false;
    player = window.document[thePlayer.id];
    player.addModelListener("STATE", "playerState");
    player.addModelListener("TIME", "playerTime");

    if (querySt('start') != null) {
        player.sendEvent('PLAY');
    }
}

function playItem(item) {
    if ($(item).parents('li').hasClass('playing')) {
        // Already playing, take to the episode page
        window.location = $(item).attr("href") + '?start=' + playerSeconds;
    } else {
        var file = $(item).attr('file');
        var image = $(item).attr('image');
        $('.playlist li').removeClass('playing');
        playFile(file, image);
        $(item).parents('li').addClass('playing');



    }
}

$(function() {




    var userId = $.cookie('userId');


    $('.menuArrow').bind("click", function(e) {
        var menu = $(this).attr("menu");
        var match = $('#' + menu + ':visible');
        if (match.length > 0) {
            $('#' + menu).slideUp();
        } else {
            $('.topMenu:visible').hide();
            $('#' + menu).slideDown("fast");
        }
    });

    $('.topMenu').hover(
                function() { },
                function() {
                    $(this).slideUp();
                });

    $('#player .close').click(function(e) {
        $('#player').slideUp();
        $('.play').text('Play');
    });


    $('#channelBar .close').click(function(e) {
        $('#channelBar').hide();
    });

    if ($('#fade div').length > 0) {
        DoFade();
    }

    if (userId && userId > 0) {




    } else {

        $('.loginButton').click(function(e) {
            $('.popupLogin').show();
        });

        $('.popupLogin .close').click(function(e) {
            $('.popupLogin').hide();
            $('#popupInfo').hide();
        });

        $('.share .drop').hide();
        $('.channel .drop').hide();
    }


    $('.feedSelector').hover(function(e) { }, function(e) { $(this).slideUp() });

    $('.subscribe').click(function(e) {
        $('.feedSelector').slideToggle();
    });

    $('.playlist li:first').addClass('playing');

    $('.playlist a').live('click', function() {
        playItem(this);
        return false;
    });

    $('.moreEpisodes li.episode a').click(function() {


        var episodeId = $(this).attr('episodeId');

        var match = $('.playlist a[episodeid=' + episodeId + ']');

        if (match.length > 0) {
            playItem(match);
        } else {
            var file = $(this).attr('file');
            var podcastName = $(this).attr('podcastName');
            var name = $(this).attr('name');
            var image = $(this).attr('image');
            var url = $(this).attr('href');

            var resizedImage = "http://si.cstrlr.com/40/40/" + image.replace("http://", "");


            var newItem = '<li><a class="' + $(this).attr('class') + '" episodeid="' + episodeId + '" file="' + file + '" href="' + url + '" image="' + image + '"><span class="series-art"><img src="' + resizedImage + '"/></span><div class="details"><strong>' + podcastName + '</strong><br/>' + name + "</div></a></li>";

            $(newItem).insertAfter('.playlist li.playing');
            playItem($('.playlist li a')[getCurrentIndex() + 1]);


        }

        return false;

    });

    $('.moreEpisodes ul ul:first').show();
    $('ul.moreTabs li:first').addClass('active');

    $('ul.moreTabs li').click(function() {
        var category = $(this).html();
        $('.moreEpisodes ul ul').hide();

        $('.moreEpisodes li[category=' + category + '] ul').fadeIn();

        $('ul.moreTabs li').removeClass('active');
        $(this).addClass('active');

    });

    $('.actions .play').click(function(ex) {
        if ($(this).text() == "Stop") {
            $('#player').slideUp();
            $(this).text('Play');
        } else {

            var episodeId = parseInt($(this).parents(".episode:first").attr("episodeId"));
            pageTracker._trackEvent(pageCategory, 'ListPlay', episodeId);
            CastThree.PlayerService.GetPlayer(episodeId, true, OnGetPlayerComplete, null, episodeId, null);
            $('#player').slideDown();
            $('.play').text("Play");
            $(this).text('Loading');
        }
    });

    $('.actions .star').click(function(e) {

        if (RequireLogin("Please log in to star this episode")) {


            var episodeId = parseInt($(this).parents(".episode:first").attr("episodeId"));

            CastThree.ChannelService.ToggleEpisodeStar(episodeId, OnToggleStarEpisodeComplete, null, episodeId, null);

            if ($(this).html().match("Undo")) {
                SetStarredResult(false, episodeId);
                $('#fade').html("<div>Removed from starred episodes</div>");
            }
            else {
                SetStarredResult(true, episodeId);
                $('#fade').html("<div>Episode starred</div>");
            }
            DoFade();
        }

    });

    $('.actions .star').each(function(e) {

        var episodeId = parseInt($(this).parents(".episode:first").attr("episodeId"));
        CastThree.ChannelService.CheckEpisodeStarred(episodeId, OnCheckEpisodeStarredComplete, null, episodeId, null);

    });

    $('.actions .share .desc').click(function(e) {
        if (RequireLogin("Please log in to share this episode on CastRoller")) {
            var episodeId = parseInt($(this).parents(".episode:first").attr("episodeId"));

            ToggleEpisodeShared(episodeId, "");
        }
    });

    $('.actions .share .drop').click(function(e) {
        if (RequireLogin("Please log in to share this episode on CastRoller")) {
            var episodeId = parseInt($(this).parents(".episode:first").attr("episodeId"));
            CastThree.PodcastService.GetSharePanel(episodeId, OnGetSharePanelComplete, null, episodeId, null);
        }
    });

    $('.actions .share').each(function(ex) {
        var episodeId = parseInt($(this).parents(".episode:first").attr("episodeId"));
        CastThree.ChannelService.CheckEpisodeShared(episodeId, OnCheckEpisodeSharedComplete, null, episodeId, null);
    });


});