﻿var GFOVideoGallery = {

    Load: function(hasbrick, showcomments, terms) {
        var Data = {
            CurrentVideo: '',
            CurrentPager: 0,
            CurrentFilter: '',
            AutoStart: false,
            VideoLoaded: false,
            GalleryLoaded: false,
            PageName: null
        };

        function GetKeyValues(videopage, pager, filter, start) {
            return "video=" + videopage + "&pager=" + pager + "&filter=" + encodeURIComponent(encodeURIComponent(filter)) + "&autostart=" + start;
        }

        var Video = {

            Load: function() {
                function Show(detail) {
                    (detail.embed && GFOVideo.LoadPlayer(detail)) ? $('#embeddiv').show() : $('#embeddiv').hide();
                }

                function Populate(result) {
                    if (Data.CurrentVideo == '') {
                        Data.CurrentVideo = result.page;
                    }

                    $('#videoh1').html(result.title);
                    $('#videobody').html(result.body);
                    $('#videolink').attr('href', result.page);
                    $('#videocomments').remove();
                    $('.videosharing').append($('<div id="videocomments" style="float:left;padding-left:12px;margin-top:4px;"></div>').append("<div class='js-kit-comments' domain='gatesfoundation.org' uniq='" + result.page + "'></div>"));
                    $('#videocomments').unbind('click').click(function() {
                        $('.jskit-container-title').after('<div class=\"commentsTitle\">' + result.title + '</div>').hide();
                        $('.jskit-container-content').append('<div style="font-size:11px;line-height:14px;color:#7a6a55;margin: 0px 8px;">' + terms + '</div>');
                    });
                    document.title = $('#videoh1').text();

                    Show({
                        autostart: Data.AutoStart,
                        container: "videodiv",
                        embed: result.embed,
                        h1: result.h1,
                        height: 364,
                        img: result.img,
                        imgHeight: 344,
                        imgWidth: 611,
                        path: result.path,
                        width: 611
                    });

                    $('#videofail, #videoloading').hide();
                    $('#mainvideo').show();
                }

                $('#videofail, #mainvideo').hide();
                $('#videoloading').show();

                $.ajax({ type: 'POST',
                    url: '/_layouts/VideoGallery.asmx/GetVideo',
                    contentType: 'application/json; charset=utf-8',
                    data: "{'source': '" + window.location.pathname + "','page': '" + Data.CurrentVideo + "'}",
                    dataType: 'json',
                    success: function(result) { Populate(result.d); Data.VideoLoaded = true; },
                    error: function() { $('#videoloading, #mainvideo').hide(); $('#videofail').show(); Data.VideoLoaded = true; }
                });
            }
        }

        var Gallery = {

            Load: function() {

                function CreateThumb(thumb, isEnd) {
                    var videoimageclass = hasbrick ? 'smallvideoimage' : 'videoimage';
                    var videoplayclass = hasbrick ? 'smallvideoplay' : 'videoplay';
                    var videotitleclass = hasbrick ? 'smallvideotitle' : 'videotitle';
                    var videotitlehoverclass = hasbrick ? 'smallvideotitlehover' : 'videotitlehover';
                    var videothumbclass = hasbrick ? "smallvideothumb" : "videothumb";
                    var videothumbmarginclass = hasbrick ? "smallvideothumb smallvideothumbmargin" : "videothumb videothumbmargin";

                    return $("<div class='" + (hasbrick ? "smallvideothumb" + (isEnd ? "" : " smallvideothumbmargin") : "videothumb" + (isEnd ? "" : " videothumbmargin")) + "'></div>")
					.append(
						$('<div></div>').click(function() { $.history.add(GetKeyValues(thumb.page, Data.CurrentPager, Data.CurrentFilter, true)); })
						.hover(
							function() {
							    $(this).children('.' + videotitleclass).removeClass(videotitleclass)
								.addClass(videotitlehoverclass).parent().children('.' + videoimageclass)
								.children('.videoplayoff').removeClass('videoplayoff').addClass(videoplayclass);
							},
							function() {
							    $(this).children('.' + videotitlehoverclass).removeClass(videotitlehoverclass)
								.addClass(videotitleclass).parent().children('.' + videoimageclass)
								.children('.' + videoplayclass).removeClass(videoplayclass).addClass('videoplayoff');
							})
						.append("<div class='" + videoimageclass + "' style='background-image:url(\"/FileReturn.aspx?src=" + thumb.img + "&width=" + (hasbrick ? 170 : 218) + "&height=" + (hasbrick ? 96 : 123) + "&returntype=thumb\");'><div class='videoplayoff'></div></div>")
						.append("<div class='" + videotitleclass + "'>" + thumb.title + "</div>")
						.append("<div class='" + (hasbrick ? 'smallvideobody' : 'videobody') + "'>" + thumb.body + "</div>")
					).append($('<div></div>').append("<div class='js-kit-comments' domain='gatesfoundation.org' uniq='" + thumb.page + "'></div>").click(function() {
					    $('.jskit-container-title').after('<div class=\"commentsTitle\">' + thumb.title + '</div>').hide();
					    $('.jskit-container-content').append('<div style="font-size:11px;line-height:14px;color:#7a6a55;margin: 0px 8px;">' + terms + '</div>');
					}));
                }

                if (!Data.Container) {
                    Data.Container = $('#pagerthumbs').html('');
                    Data.PagerContainer = $('<div></div>');
                    Data.Container.append(Data.PagerContainer);
                    Data.ThumbContainer = $("<div></div>");

                    if (!hasbrick) { Data.Container.append(Data.ThumbContainer); }
                    else {
                        BrowseBrick.Load({
                            FilterSelect: function(page, filterText) { $.history.add(GetKeyValues(page, 0, filterText, false)); },
                            CurrentFilter: Data.CurrentFilter,
                            FilterReset: function() { $.history.add('default'); },
                            Uri: '/_layouts/VideoGallery.asmx/GetNavFilters',
                            Data: "{'page': '" + window.location.pathname + "'}",
                            Container: Data.Container,
                            ThumbContainer: Data.ThumbContainer,
                            Fail: function() { hasbrick = false; Data.Container.append(Data.ThumbContainer); }
                        });
                    }
                }

                MediaThumbs.Load({
                    Container: Data.ThumbContainer,
                    PagerContainer: Data.PagerContainer,
                    SpacerClass: 'videorowspacer',
                    Uri: '/_layouts/VideoGallery.asmx/GetPagerThumbs',
                    Data: "{'page': '" + window.location.pathname + "','index': '" + Data.CurrentPager + "','filter': '" + Data.CurrentFilter + "'}",
                    PagerClick: function(index) { $.history.add(GetKeyValues(Data.CurrentVideo, index, Data.CurrentFilter, Data.AutoStart)); },
                    ShowContainer: function() { $('#thumbfail, #thumbloading').hide(); $('#pagerthumbs').show(); Data.GalleryLoaded = true; },
                    ShowLoading: function() { $('#thumbfail, #pagerthumbs').hide(); $('#thumbloading').show(); },
                    FailLoading: function() { $('#thumbloading, #pagerthumbs').hide(); $('#thumbfail').show(); Data.GalleryLoaded = true; },
                    CreateChild: CreateThumb
                });
            }
        }

        function AddComments() {
            if (showcomments) {
                if (Data.VideoLoaded && Data.GalleryLoaded) {
                    $("#jskit").remove();

                    $('body').append($("<div id='jskit' style='display:none;'></div>").append("<script type=\"text/javascript\" src=\"http://js-kit.com/for/gatesfoundation.org/comments.js\"></script>"));
                }
                else {
                    setTimeout(AddComments, 100);
                }
            }
        }

        function LoadState(init) {
            hash = window.location.hash.replace(/^#/g, '');

            if (Data.PageName == null & typeof (s) != 'undefined') {
                Data.PageName = s.pageName;
            }

            if (hash == '' || hash == 'default') {
                query = ParseKeyValue(window.location.search.replace(/^\?/g, ''));
                Data.CurrentVideo = init && query["video"] ? query["video"] : '';
                Data.CurrentPager = init && !isNaN(query["pager"]) ? Number(query["pager"]) : 0;
                Data.CurrentFilter = init && query["filter"] ? decodeURIComponent(query["filter"]) : '';
                Data.AutoStart = init && query["autostart"] ? (query["autostart"] == 'true') : false;
                Data.VideoLoaded = false;
                Data.GalleryLoaded = false;
                Video.Load();
                Gallery.Load();
                AddComments();
            }
            else {
                var hasharray = ParseKeyValue(hash);

                Data.AutoStart = (hasharray["autostart"] == 'true');

                if (hasharray["video"] != Data.CurrentVideo || init) {
                    Data.CurrentVideo = hasharray["video"];
                    Data.VideoLoaded = false;
                    Video.Load();
                    AddComments();
                }

                var pagenumber = isNaN(hasharray["pager"]) ? 0 : Number(hasharray["pager"]);

                if ((decodeURIComponent(hasharray["filter"]) != Data.CurrentFilter)
					|| (pagenumber != Data.CurrentPager) || init) {
                    Data.CurrentFilter = decodeURIComponent(hasharray["filter"]);
                    Data.CurrentPager = pagenumber;
                    Data.GalleryLoaded = false;
                    Gallery.Load();
                    AddComments();
                }
            }

            if (typeof (s) != 'undefined') {
                s.prop37 = Data.CurrentFilter;

                if (!Data.AutoStart) {
                    TrackPageAction(Data.PageName);
                }
            }

            $(window).data('share', window.location.protocol + '//' + window.location.host + window.location.pathname + '?video=' + Data.CurrentVideo + '&pager=' + Data.CurrentPager + '&filter=' + encodeURIComponent(encodeURIComponent(Data.CurrentFilter)) + '&autostart=' + Data.AutoStart)
        }

        $(document).ready(function() {
            $(window).history(function(e, hash) { LoadState(); });
            $(window).historyadd(function(e, hash) { LoadState(); });
            $('body').append("<script>var JSKitConfig = { 'comments-display-mode' : 'int-popup' };</script>");
            $('body').prepend("<style>"
                    + ".jsk-Pager .jsk-PrevOff, .jsk-Pager .jsk-NextOff {color:#7a6a55;font-size:12px;}"
                    + ".jsk-Pager .jsk-Active {color:#392d1c; font-size:12px;}"
                    + ".jsk-Pager a:link, .jsk-Pager a:visited  {color:#3086ab; font-size:12px;}"
                    + ".jsk-Pager a {border-color:#cfcbc2;}"
                    + ".jsk-Pager a:hover {text-decoration:underline;}"
                    + ".jsk-Pager li {margin:0 0 0 5px;}"
                    + ".js-kit-from-name {font-size:12px; color:#392d1c; font-weight:bold;}"
                    + ".js-singleCommentAdminStar { display: none; !important; }"
                    + ".js-kit-disabledNameField { background-color:#e6f4ff;}"
                    + ".jskit-Dogtag {background-color:#eef3f7;border:1px solid #3086ab;}"
                    + ".jsk-SecondaryBackgroundColor{background-color:#f7f5f4;}"
                    + ".jsk-CommentFormSurface {border:1px solid #dddcd5;}"
                    + ".js-kit-lcf-toField, .js-kit-from-menuAnonymousWrap {border:1px solid #cfcac2;}"
                    + ".jsk-SecondaryFontColor, .jsk-ThreadWrapper a.jsk-SecondaryFontColor {color:#AAA092;}"
                    + ".js-CommentsSkin-echo .jsk-HeaderWrapper {padding-bottom:0;padding-top:0;}"
                    + ".js-CommentsSkin-echo .jsk-ThreadWrapper {padding:3px 0 0 0; margin-bottom:0;}"
                    + ".jsk-PrimaryFont, .jsk-CommentFormSurface input, .js-kit-follow-popup-container input  {font-family:Arial,Helvetica,sans-serif;}"
                    + ".jskit-container-main  {background:none repeat scroll 0 0 #F7F5F4;}"
                    + ".jskit-container-wrapper {border-color:#F7F5F4;}"
                    + ".jskit-container-footer {background-color:#F7F5F4;}"
                    + ".js-LeaveComment {font-weight:bold; margin:5px 0 10px;}</style>");
            LoadState(true);
        });
    }
}