﻿/*
var pageTracker1 = _gat._getTracker("UA-4946594-1");
pageTracker1._initData();
pageTracker1._setDomainName(".responsiblesports.com");
//pageTracker1._trackPageview();

var pageTracker2 = _gat._getTracker("UA-4946594-4");
pageTracker2._setDomainName(".responsiblesports.net");
//pageTracker2._trackPageview();
*/

var currentVideoTitle = '';
var vids = new Object();
var showDescription = true;

var SHOW_DEBUG_ALERTS = false;
var FEED_BATCH_SIZE = 40;
var entries = [];
var currentTag = "";

/*
function trackHit(url) {
    url = url.replace('$currentVideoTitle$', currentVideoTitle);
    pageTracker1._trackPageview(url);
    pageTracker2._trackPageview(url);
}
*/

function formatVideoTitle(title) {
    return title.replace(/[^a-zA-Z0-9]+/g, '');
}

function loadVideo(playerUrl, autoplay, title, description, commentsLink) {
    $('#videoTitle').text(title);
    if (showDescription) {
        $('#videoSummary').text(description);
        $('#videoSummary').show();
    }
    else {
        $('#videoSummary').hide();
    }
    swfobject.embedSWF(
                playerUrl + '&rel=1&border=0&fs=1&autoplay=' +
                (autoplay ? 1 : 0), 'player', '427', '257', '9.0.0', false,
                false, { allowfullscreen: 'true',wmode: 'opaque' });
    // Populate comments
    if (commentsLink) {
        $('#div-comments-disabled').hide();
        $('#div-comments-enabled').show();
        $('#comments').html('Loading comments...');
        $.get("/common/ashx/youtube_comments_proxy.ashx?url=" + commentsLink + "&vurl=" + playerUrl, function(data) { eval(data.toString()); });
    }
    else {
        $('#div-comments-enabled').hide();
        $('#div-comments-disabled').show();
    }
    // Populate the Link textbox
    $('#txtLink').val(baseUrl + '?vid=' + escape(playerUrl));
    currentVideoTitle = formatVideoTitle(title);
    resetForms();
    //trackHit('/Media/Library/Video/' + formatVideoTitle(title));
}

function trimTitle(title) {
    if (title.length > 21) {
        if (title.substring(0, 21) == "Responsible Sports - ") {
            title = title.substring(20);
        }
    }
    return title;
}

function loadVideoById(id) {
    var entry = vids[id];
    var title = trimTitle(entry.title.$t);
    var description = entry.media$group.media$description.$t;
    if (description.length > 27) {
        description = description.substring(26);
    } else {
        description = "";
    }
    var commentsUrl = (typeof entry.gd$comments !== "undefined") ? entry.gd$comments.gd$feedLink.href : null;
    var playerUrl = entry.media$group.media$content[0].url.replace('?','&');
    loadVideo(playerUrl, true, title, description, commentsUrl);
}

function showMyVideos(data) {
    var feed = data.feed;
    var newEntries = feed.entry || [];
    if (SHOW_DEBUG_ALERTS)
        alert("adding " + newEntries.length + " new entries");
    entries = entries.concat(newEntries);

    if (newEntries.length == FEED_BATCH_SIZE) {
        GetResultsBatch();
    }
    else {
        if (SHOW_DEBUG_ALERTS)
            alert("have entire list, beginning parse");

        var hfSortText = $('.hfSortText');
        if (hfSortText.length > 0 && hfSortText.val() != 'NULL' && hfSortText.val() != 'SortSelected') {
            var sort = hfSortText.val().toLowerCase();
            hfSortText.val('SortSelected');
            switch (sort) {
                case "parenting":
                    tagSearch('Parenting');
                    setSelected('tagParenting');
                    break;
                case "coaching":
                    tagSearch('Coaching');
                    setSelected('tagCoaching');
                    break;
                case "football":
                    tagSearch('Football');
                    setSelected('tagFootball');
                    break;
                case "hockey":
                    tagSearch('Hockey');
                    setSelected('tagHockey');
                    break;
                case "soccer":
                    tagSearch('Soccer');
                    setSelected('tagSoccer');
                    break;
                case "softball":
                    tagSearch('Softball');
                    setSelected('tagSoftball');
                    break;
                case "elm":
                    tagSearch('ELM');
                    setSelected('tagELM');
                    break;
                case "mastery":
                    tagSearch('Mastery');
                    setSelected('tagMastery');
                    break;
                case "honoring":
                    tagSearch('Honoring');
                    setSelected('tagHonoring');
                    break;
                case "candrea":
                    tagSearch('Candrea');
                    setSelected('tagCandrea');
                    break;
                case "granato":
                    tagSearch('Granato');
                    setSelected('tagGranato');
                    break;
                case "mendoza":
                    tagSearch('Mendoza');
                    setSelected('tagMendoza');
                    break;
                case "miles":
                    tagSearch('Miles');
                    setSelected('tagMiles');
                    break;
                case "Schiano":
                    tagSearch('Schiano');
                    setSelected('tagSchiano');
                    break;
                case "wrestling":
                    tagSearch('Wrestling');
                    setSelected('tagWrestling');
                    break;
                case "lacrosse":
                    tagSearch('Lacrosse');
                    setSelected('tagLacrosse');
                    break;
                case "basketball":
                    tagSearch('Basketball');
                    setSelected('tagBasketball');
                    break;
                case "":
                default:
                    tagSearch('');
                    setSelected('tagAll');
                    break;
            }
        } else {
            if (entries.length == 0) {
                $('#videos').html('No videos found.');
                $('#numClips').text('(0)');
                return;
            }

            $('#videos').html('<ul>');
            var defaultVideoIndex = 0;
            var msg = "default: " + defaultVideo + "\n";

            for (var i = 0; i < entries.length; i++) {
                var entry = entries[i];
                var title = trimTitle(entry.title.$t);
                var description = entry.media$group.media$description.$t;
                if (description.length > 27) {
                    description = description.substring(26);
                } else {
                    description = "";
                }
                var commentsUrl = (typeof entry.gd$comments !== "undefined") ? entry.gd$comments.gd$feedLink.href : null;
                var durationS = entry.media$group.yt$duration.seconds;
                var duration = (Math.floor(durationS / 60)) + ':' + (((durationS % 60) < 10) ? '0' : '') + (durationS % 60);
                var thumbnailUrl = entry.media$group.media$thumbnail[0].url;
                var playerUrl = entry.media$group.media$content[0].url.replace('?', '&');
                msg = msg + playerUrl + "\n";

                if (playerUrl.replace("?", "&").split("&")[0] == defaultVideo.split("&")[0]) { defaultVideoIndex = i; }

                var li = $('<li id="' + formatVideoTitle(title) + '">');
                if (showDescription) {
                    li.append('<div class="resultWrapper">' +
                          '<div class="videoAvatar"><img src="' + thumbnailUrl + '" width="90" /></div>' +
                          '<div class="videoDetails"><div class="title">' + title + '</div>' +
                          '<div class="description">' + description + '</div>' +
                          '<div class="duration">' + duration + '</div></div>' +
                          '<br class="clear" />' +
                          '</div>');
                }
                else {
                    li.append('<div class="resultWrapper">' +
                          '<div class="videoAvatar"><img src="' + thumbnailUrl + '" width="90" /></div>' +
                          '<div class="videoDetails"><div class="title">' + title + '</div>' +
                          '<div class="duration">' + duration + '</div></div>' +
                          '<br class="clear" />' +
                          '</div>');
                }
                $('#videos ul').append(li);

                vids[formatVideoTitle(title)] = entry;
                //li.click(function() { trackHit('/Media/Library/Video/$currentVideoTitle$/ClickClip/' + formatVideoTitle(title)); });
                li.click(function() { loadVideoById($(this).attr('id')) });
            }
            //alert(msg);

            var defaultDescription = entries[defaultVideoIndex].media$group.media$description.$t.replace('&#39;', "'");
            if (defaultDescription.length > 27) {
                defaultDescription = defaultDescription.substring(26);
            } else {
                defaultDescription = "";
            }

            loadVideo(
                        entries[defaultVideoIndex].media$group.media$content[0].url.replace('?', '&'),
                        false,
                        trimTitle(entries[defaultVideoIndex].title.$t.replace('&#39;', "'")),
                        defaultDescription,
                        (typeof entries[defaultVideoIndex].gd$comments !== "undefined") ? entries[defaultVideoIndex].gd$comments.gd$feedLink.href : null);

            $('#numClips').text('(' + entries.length.toString() + ')');
        }
    }
}

function GetResultsBatch() {
    var categoryString = "";
    if (currentTag != "") {
        categoryString = "&category=" + currentTag
    }
    if (SHOW_DEBUG_ALERTS)
        alert("[currentTag = "+currentTag+"] [categoryString = "+categoryString+"] getting " + FEED_BATCH_SIZE + " more starting at " + (entries.length + 1));
    $.ajax({
        type: "GET",
        url: "http://gdata.youtube.com/feeds/users/responsiblesports/uploads?"+
                "alt=json-in-script&"+
                "max-results="+FEED_BATCH_SIZE+"&"+
                "start-index="+(entries.length+1)+"&"+
                "format=5&" +
                "orderby=published&" +
                "callback=AddToMyVideos&key=AI39si7Dn7S1F_OOqD8E0-LfhMjRENIcxD8DzcK5lXvKHe9YTpJJanXzsT1W4SLGZwqz7_SVYzH-KcKhG9-mmKpCTnbxupg1-Q" +
                categoryString,
        dataType: "script"
    });
}

function AddToMyVideos(data) {
    showMyVideos(data);
}


function showComments(data) {
    var feed = data.feed;
    var entries = feed.entry || [];
    var html = ['<ul>'];

    if (entries.length == 0) {
        $('#comments').html('No comments found');
        return;
    }
    for (var i = 0; i < entries.length; i++) {
        var entry = entries[i];
        var commenter = entry.author[0].name.$t;
        var published = new Date();
        published.setISO8601(entry.published.$t);
        var publishedAgo = $.timeago(published);
        var commentText = entry.content.$t;
        html.push('<li><span class="commenter">', commenter, '</span>&nbsp;<span class="published">(', publishedAgo, ')</span><br/><span class="commentText">', commentText, '</span><hr/></li>');
    }

    html.push('</ul>');
    $('#comments').html(html.join(''));
}

function tagSearch(tag) {
    if (tag == '') {
        showDescription = true;
    }
    else {
        showDescription = false;
    }
    $('#videos').html('<img src="/common/images/ajax-loader.gif" alt="Retrieving videos..." /> &nbsp;&nbsp;Retrieving videos...');
    //trackHit('/Media/Library/Video/$currentVideoTitle$/ClickTag/' + tag);

    currentTag = tag;
    entries = [];
    GetResultsBatch();
}

function tabClicked(tab) {
    //trackHit('/Media/Library/Video/$currentVideoTitle$/ClickTab/' + tab);
}

function commentSubmitted() {
    alert(sender);
}

function commentSubmit() {
    if ($('#btnCommentSubmit').val() == 'Posting Comment...') {
        return false;
    }
    $('#btnCommentSubmit').val('Posting Comment...');
    var url = "/common/ashx/video_forms_request_handler.ashx?f=0&c=$comment$&vu=$videoUrl$&vt=$videoTitle$";
    url = url.replace('$comment$', $('#txtComment').val());
    url = url.replace('$videoUrl$', $('#txtLink').val());
    url = url.replace('$videoTitle$', $('#videoTitle').text());
    $.get(url,
        function(data) {
            var r = eval('(' + data + ')');
            var retVal = r.retVal;
            var msg = r.msg || "";
            if (retVal == 0 || retVal == '0') {
                $('#commentV0').hide();
                $('#commentV2').hide();
                $('#commentV1').show();
               // trackHit('/Media/Library/Video/$currentVideoTitle$/Action/CommentSubmitted');
            }
            else {
                $('#commentError').html(msg);
                $('#commentV2').show();
            }
        }
    );
    return false;
}

function shareSubmit() {
    if ($('#btnShareSubmit').val() == 'Sending...') {
        return false;
    }
    $('#btnShareSubmit').val('Sending...');
    var url = "/common/ashx/video_forms_request_handler.ashx?f=1&fe=$fromEmail$&fn=$fromName$&vu=$videoUrl$&1n=$f1Name$&1e=$f1Email$&2n=$f2Name$&2e=$f2Email$&vt=$videoTitle$";
    url = url.replace('$fromEmail$', $('#txtYourEmail').val());
    url = url.replace('$fromName$', $('#txtFirstName').val());
    url = url.replace('$videoUrl$', $('#txtLink').val());
    url = url.replace('$f1Name$', $('#txtFriendName1').val());
    url = url.replace('$f1Email$', $('#txtFriendEmail1').val());
    url = url.replace('$f2Name$', $('#txtFriendName2').val());
    url = url.replace('$f2Email$', $('#txtFriendEmail2').val());
    url = url.replace('$videoTitle$', $('#videoTitle').text());
    $.get(url,
        function(data) {
            var r = eval('(' + data + ')');
            var retVal = r.retVal;
            var msg = r.msg || "";
            if (retVal == 0 || retVal == '0') {
                $('#shareV0').hide();
                $('#shareV2').hide();
                $('#shareV1').show();
                //trackHit('/Media/Library/Video/$currentVideoTitle$/Action/ShareVideoSubmitted');
            }
            else {
                $('#shareError').html(msg);
                $('#btnShareSubmit').val('Send');
                $('#shareV2').show();
            }
        }
    );
    return false;
}

function resetForms() {
    $('#commentV0').show();
    $('#commentV1').hide();
    $('#commentV2').hide();
    $('#commentError').html('');
    $('#txtComment').val('');
    $('#btnCommentSubmit').val('Post Comment');

    $('#shareV0').show();
    $('#shareV1').hide();
    $('#shareV2').hide();
    $('#shareError').html('');
    $('#txtYourEmail').val('');
    $('#txtFirstName').val('');
    $('#txtFriendName1').val('');
    $('#txtFriendEmail1').val('');
    $('#txtFriendName2').val('');
    $('#txtFriendEmail2').val('');
    $('#btnShareSubmit').val('Send');
}

$(document).ready(function(e) {
    $('#txtLink').focus(function() {
        //trackHit('/Media/Library/Video/$currentVideoTitle$/Action/CopyLinkClicked');
        $(this).select();
    });
    $('a[rel="popup"]').click(function() {
        window.open($(this).attr('href'));
        return false;
    });
    $('#btnShareSubmit').click(shareSubmit);
    $('#btnCommentSubmit').click(commentSubmit);

    var activeTagName = $(".hfActiveTag").val();
    $("#" + activeTagName).addClass("activeTag");
});

