﻿
// http://code.google.com/apis/youtube/js_api_reference.html

// scope the functionality (removing it from global scope)

(function(){

var ytplayer;
var rater;
var loginModal;

function onPlayerStateChange(newState)
{
    if (ytplayer)
    {
        var playerState = ytplayer.getPlayerState();
        if (playerState === 0)
        {
            $('#player').hide();
            setTimeout(renderVideoPlayer, 20);
        }
    }
}

function onYouTubePlayerReady(playerId) 
{
    ytplayer = document.getElementById("player");
    window.ytplayer = ytplayer;
    
    ytplayer.addEventListener("onStateChange", "onPlayerStateChange");
    
    // autoplay?
    //ytplayer.playVideo();
}

window.onYouTubePlayerReady = onYouTubePlayerReady;
window.onPlayerStateChange = onPlayerStateChange;


function renderVideoPlayer()
{
    var videoId = getVideoID();
    swfobject.embedSWF("http://www.youtube.com/v/" + videoId + "&hl=en&fs=1&showinfo=0&enablejsapi=1&playerapiid=ytplayer", 
        "player", "640", "360", 
        "9.0.0", null, null, 
        { allowScriptAccess: "always", wmode : "opaque" }, { id: "player" });
}

function updateVideoSummary(summary)
{
    $('.tipSummary').text(summary.Rating + ' / ' + summary.NumberOfRaters + ' votes');
        
    rater._ratingValue = Math.round(summary.Rating);
    rater.set_ReadOnly(false);
    
    $('h1.VideoTitle').text(summary.Title);
    $('p.VideoDescription').text(summary.Description);
    $('.tipSummary').text(summary.Rating + ' / ' + summary.NumberOfRaters + ' votes');
    
    $('a.SubmitVideo').attr('href', summary.VideoResponsesUrl);
    
    var comments = '<ul>';
    var i = 0;
    for (i=0;i<summary.Comments.length;i++)
    {
        var comment = summary.Comments[i];
        comments += '<li><span>' + comment.AuthorName + '</span> ' + comment.Text + '</li>';
    }
    comments += '</ul>';
    
    $('span.VideoComments').html(comments);
}

function changeVideo(videoId)
{
    if (videoId !== getVideoID())
    {
        YouTube.GetVideoSummary(videoId, function(summary){
//            if ($.browser.msie) {
//            } else {
//                location.hash = summary.VideoID;
//            }
            rater.set_Tag(summary.VideoID);
            renderVideoPlayer();
            updateVideoSummary(summary);
            
            if ($('div.Survey:visible').length === 0)
            {
                $('div.Survey').slideDown();
            }
        });
    }
}

function getVideoID()
{
    return rater.get_Tag();
}

function showLoginModal()
{
    if ($('.youTubeLoginModal:visible').length === 0)
    {
        $('#Main').before(loginModal);
        $('.youTubeLoginModal').centerElement({ position : 'absolute' }).
            show().
            find('a.CancelButton').
            click(function(){
            $('.youTubeLoginModal').fadeOut();
            $(this).blur();
        });
    }
}

function attachEvents()
{

    var onFail = function(ex)
    {
        logError(ex._message);
    };
    
    var showFeedback = function(context, message)
    {
        $('.Feedback', context).html('<b style="color: blue;">' + message + '</b>').fadeIn();
        setTimeout(function()
            {
                $('.Feedback', context).fadeOut().empty();
            }, 4000);
    };
    
    $('a.PostAComment').click(function(){
        if (!isYouTubeAuthenticated)
        {
            showLoginModal();
        }
        else
        {
            $('#CommentBox').slideDown();

            var videoId = getVideoID();
            YouTube.GetVideoSummary(videoId, function(summary){
                rater.set_Tag(summary.VideoID);
                updateVideoSummary(summary);
            });
        }
            
        $(this).blur();
        return false;
    });
    
    $('#CommentBox a.Cancel').click(function(){
        $('#CommentBox').slideUp();
    });

    $('div#VideoSelector a').click(function()
    {
        var href = $(this).attr('href');
        var videoId = href.substr(1);
        changeVideo(videoId);
        
        $(this).blur();
        return false;
    });
    
    $('a.SubmitSurvey').click(function()
    {
        showFeedback($('#SurveyBox'), 'Submitting feedback!');
        
        var helpful = ('true' === $('#SurveyBox .HelpfulRadioButtonList input:checked').val());
        var comeback = ('true' === $('#SurveyBox .ComeBackRadioButtonList input:checked').val());
        var comment = $('#SurveyBox .SurveyComment').val();
        var videoId = getVideoID();
        
        YouTube.SubmitSurvey(helpful, comeback, comment, videoId, function()
            {
                $('#SurveyBox .SurveyComment').val('');
                showFeedback($('#SurveyBox'), 'Thanks for the feedback!');
                setTimeout(function(){
                    $('div.Survey').slideUp();
                }, 4000);
            }, onFail);
        
        $(this).blur();
        return false;
    });
    
    $('a.SubmitComment').click(function()
    {
        if (isYouTubeAuthenticated)
        {
            showFeedback($('#CommentBox'), 'Submitting comment!');
        
            var videoId = getVideoID();
            var comment = $('#CommentBox .CommentText').val();
            
            YouTube.InsertComment(videoId, comment, function()
                {
                    $('#CommentBox .CommentText').val('');
                    showFeedback($('#CommentBox'), 'Thanks for the comment!');
                    setTimeout(function(){
                        $('#CommentBox').slideUp();
                    }, 4000);
                }, onFail);
        }
        else
        {
            alert('You are not logged into YouTube!');
        }
        
        $(this).blur();
        return false;
    });
    
}

function adjustRatingControl()
{
    $('div.tipRating a[href="#"]').attr('href', 'javascript:void(0);');
    
    rater.set_Rating = function(value)
    {
        if (isYouTubeAuthenticated)
        {
            this._ratingValue = value;
            this._currentRating = value;

            if (this.get_isInitialized()) {
                if ((value < 0) || (value > this._maxRatingValue)) {
                    return;
                }

                this._update();

                AjaxControlToolkit.RatingBehavior.callBaseMethod(this, 'set_ClientState', [this._ratingValue]);
                this.raisePropertyChanged('Rating');
                this.raiseRated(this._currentRating);
                this._waitingMode(true);
                
                YouTube.InsertRating(this.get_Tag(), this.get_Rating(), function() {
                    var result = rater.get_Tag() + ':' + rater.get_Rating();
                    rater._receiveServerData.apply(rater, [result, rater]);
                    rater.set_ReadOnly(true);
                    
                    YouTube.GetVideoSummary(rater.get_Tag(), function(summary){
                        updateVideoSummary(summary);
                    });
                });
                
            }
        }
        else
        {
            showLoginModal();
        }
    };

}

Sys.Application.add_load(function(){
    if (!rater)
    {
        rater = $find(videoRatingBehaviorID);
    }
    
    if (!loginModal)
    {
        loginModal= $('#YouTubeLoginModal').html();
        $('#YouTubeLoginModal').remove();
    }

    renderVideoPlayer();
    attachEvents();
    adjustRatingControl();
    
//    if (location.hash) {
//        changeVideo(location.hash.substr(1));
//    }
});

})();
