﻿jQuery(document).ready(function () {
    jQuery("ul.YT_thumbnails").ytplaylist({ playerWidth: 960, playerHeight: 566, addThumbs: true, autoPlay: false, holderId: 'YT_video' });

    var thumbsToMove = 4;
    var sizeUL = jQuery("ul.YT_thumbnails li").size();
    var totWidth = (216 * sizeUL);
    var scrollWidth = jQuery("#YT_ThumbsHolder").width();

    jQuery("#YT_NavLeft").hide();
    if (jQuery("ul.YT_thumbnails li").size() > 4) {
        jQuery("#YT_NavRight").show();
    }
    else {
        jQuery("#YT_NavRight").hide();
    }
    jQuery("ul.YT_thumbnails").css("width", totWidth + "px");

    function scrollLeft() {
        var leftBefore = jQuery(".YT_thumbnails").css("marginLeft").replace("px", "");
        var leftAfter = leftBefore * 1 + (216 * thumbsToMove);

        scroll(leftAfter);
    }

    function scrollRight() {
        var leftBefore = jQuery(".YT_thumbnails").css("marginLeft").replace("px", "");
        var leftAfter = leftBefore * 1 - (216 * thumbsToMove);

        scroll(leftAfter);
    }


    function scroll(margin) {
        if (margin >= 0)
            margin = 0;
        else if (margin * (-1) > Math.floor(sizeUL / 4) * scrollWidth)
            margin = -1 * (Math.floor(sizeUL / 4) * scrollWidth);

        jQuery(".YT_thumbnails").animate({
            marginLeft: margin + "px"
        }, 250 * thumbsToMove, function () {
            var left = jQuery(".YT_thumbnails").css("marginLeft").replace("px", "");

            if (left >= 0) {
                jQuery("#YT_NavLeft").fadeOut();
            }
            if (left < 0) {
                jQuery("#YT_NavLeft").fadeIn();
            }

            var toTheLeft = ((-1) * left / 216);
            if (sizeUL - toTheLeft <= 4) {
                jQuery("#YT_NavRight").fadeOut();
            }
            if (sizeUL - toTheLeft > 4) {
                jQuery("#YT_NavRight").fadeIn();
            }
        });

    }

    jQuery("#YT_NavRight").click(function () {
        if ($(".YT_thumbnails:animated").length == 0) {
            scrollRight();
        }

        jQuery(this).blur();
        return false;

    });

    jQuery("#YT_NavLeft").click(function () {
        if ($(".YT_thumbnails:animated").length == 0) {
            scrollLeft();
        }

        jQuery(this).blur();
        return false;

    });

});
