﻿/// <reference path="~/TopletsResources/js/jquery.js" />

/**
* Scripts for the use in VideoZone
*/

/** changing category for videbox **/
function selectVideoBox(link, page, init) {    
    if (!!link) {
        jQuery('.td-video_subnav li').removeClass('ts-tab_active');
        jQuery(link).closest('li').addClass('ts-tab_active');
    }
    if (!jQuery('.td-video_subnav .ts-tab_active').length) {
        jQuery('.td-video_subnav a[rel="featured"]').closest('li').addClass('ts-tab_active');
    }
    var cat = jQuery.map(jQuery('.td-video_subnav .ts-tab_active a').attr('rel').split(','), function(catID) {
        return "catIDnPath:" + catID + "/*";
    }).join(' OR ');
    var query = jQuery('.td-video_subnav .ts-tab_active a').attr('rel') == 'featured' ? 'mode=featured' : 'Query=' + cat + '';
    var paging = (page) ? '&PageNumber=' + page : '';

    var timer = setTimeout(function() {
        jQuery("#videoBox #ajaxLoader").fadeIn("fast");
    }, 200);
    updateVideoBox(query + paging, false, query + paging, function() {
        jQuery('a.playlist-button').trigger('update');
        clearTimeout(timer);
    });
}

/** changing page for videobox **/
function selectVideoBoxPage(page) {
    selectVideoBox(null, page);
}

// Video panels
var VideoPanels = {
    Related: {
        pendingRequest: new Function(),
        refresh: function(keywords, excludeUID) {
            // fallback if updateRelated is not yet available
            if (typeof updateRelated === 'undefined') {
                this.pendingRequest = function() { this.refresh(keywords, excludeUID); }
                return;
            }
            var lucene = jQuery.map(keywords.split(','), function(tag) {
                if (!!tag) return 'keywords:"' + jQuery.trim(tag) + '"';
            }).join(' OR ');
            var exclude = (!!excludeUID) ? '&Exclude=' + excludeUID : '';
            var query = 'Query=' + encodeURIComponent(lucene) + exclude;
            updateRelated(query, false, query, function() {
                jQuery('a.playlist-button').trigger('update');
            });
        }
    },
    Playlist: {
        pendingRequest: new Function(),
        isPlaying: false,
        isRepeat: false,
        isInPlaylist: function(uid) {
            var uids = VideoPanels.Playlist.get();
            return $.inArray(uid, uids) > -1;
        },
        get: function() {
            var uids = TD.Framework.ReadCookie("videoplaylist");
            return (!uids) ? [] : uids.split(",");
        },
        clear: function() {
            // update cookie and panel
            TD.Framework.WriteCookie("videoplaylist", "", -1, "/");
            VideoPanels.Playlist.refresh();
        },
        add: function(uid) {
            // update cookie and panel
            var uidsArray = VideoPanels.Playlist.get();
            if (uidsArray.length == 10) {
                Shadowbox.open({
                    player: 'html',
                    content: '<p class="td-popup_message">Maximum of 10 items in playlist has been reached.  Please remove item(s) from the playlist before adding anymore.</p>',
                    height: 80,
                    width: 250,
                    title: "Alert"
                });
                return;
            }
            uidsArray.push(uid);
            TD.Framework.WriteCookie("videoplaylist", uidsArray.join(","), null, "/");
            VideoPanels.Playlist.refresh();
        },
        remove: function(uid) {
            // update cookie and panel
            var uidsArray = VideoPanels.Playlist.get();
            var uids = jQuery.grep(uidsArray, function(id) { if (typeof id !== "undefined") return id !== uid; }).join(',');
            TD.Framework.WriteCookie("videoplaylist", uids, null, "/");
            // play the next video if the removing video is the one playing in playlist and there're video remaining in the playlist after removal
            if (VideoPanels.Playlist.isPlaying && VideoPlayer.Players.currentPlayer.metaData.uid === uid && !TD.Framework.ReadCookie("videoplaylist")) {
                VideoPanels.Playlist.next();
            }
            VideoPanels.Playlist.refresh();
        },
        refresh: function() {
            // fallback if updatePlayList is not yet available
            if (typeof updatePlayList === 'undefined') {
                this.pendingRequest = function() { this.refresh(); }
                setTimeout(function() {
                    jQuery('a.playlist-button').trigger('update');
                }, 20);
                return;
            }
            // update panel
            try {
                var uids = TD.Framework.ReadCookie("videoplaylist") || "";
                var query = "UIDs=" + uids;
                updatePlayList(query, false, query, function() {
                    // update buttons
                    setTimeout(function() {
                        jQuery('a.playlist-button').trigger('update');
                    }, 20);
                });
            } catch (e) {
                setTimeout(function() {
                    jQuery('a.playlist-button').trigger('update');
                }, 20);
            }
        },
        next: function() {
        var $nextVideoItem = jQuery(".td-playlist_tab_content .videoItem[uid='" + VideoPlayer.Players.currentPlayer.metaData.uid + "']").next(".videoItem");
            // Repeat the playlist if repeat is On and the current video is the last one in the playlist
            if (VideoPanels.Playlist.isRepeat && !$nextVideoItem.length) {
                $nextVideoItem = jQuery(".td-playlist_tab_content .videoItem:first");
            }

            if ($nextVideoItem.length) {
                VideoPlayer.update($nextVideoItem.attr("uid"));
            } else {
                VideoPanels.Playlist.isPlaying = false;
            }
        },
        toggleRepeat: function() {
            VideoPanels.Playlist.isRepeat = !VideoPanels.Playlist.isRepeat;
            jQuery('#playlist-repeat').html("Repeat: " + (VideoPanels.Playlist.isRepeat ? 'On' : 'Off'));
        }
    },
    History: {
        pendingRequest: new Function(),
        get: function() {
            var uids = TD.Framework.ReadCookie("videohistory");
            return (!uids) ? [] : uids.split(",");
        },
        clear: function() {
            TD.Framework.WriteCookie("videohistory", "", -1, "/");
            VideoPanels.History.refresh();
        },
        refresh: function() {
            // fallback if updatePlayList is not yet available
            if (typeof updateHistory === 'undefined') {
                this.pendingRequest = function() { this.refresh(); }
                return;
            }
            // refresh history tab
            try {
                var uids = TD.Framework.ReadCookie("videohistory") || "";
                var query = "UIDs=" + uids;
                updateHistory(query, false, query, function() {
                    setTimeout(function() {
                        jQuery('a.playlist-button').trigger('update');
                    }, 20);
                });
            } catch (e) { }
        },
        add: function(uid) {
            var uidsArray = jQuery.grep(VideoPanels.History.get().slice(0, 9), function(n) {
                if (n != uid) return n;
            });
            uidsArray.unshift(uid);
            uidsArray = jQuery.unique(uidsArray).slice(0, 10);
            TD.Framework.WriteCookie("videohistory", uidsArray.join(","), null, "/");
            VideoPanels.History.refresh();
        }
    }
}

/**
* Scripts for the use of video player
*/
var VideoPlayer = {
    Src: null,
    Ads: {
        Preroll: null,
        Postroll: null
    },
    Players: {
        VideoZonePlayer: {
            pendingRequest: new Function()
        }
    }, // video player flash object
    setCategories: function(selector, defaultCategory) {
        var categoryTree = jQuery.map(defaultCategory.split('|'), function(n) {
            return encodeURI(n);
        });

        function getAnchor(categorySubtree) {
            return jQuery("<a href=\"/videozone/searchresults?Query=FullCategory:%22%2f" + categorySubtree.join('/') + "%22\">" + unescape(categorySubtree.pop()) + "</a>");
        }

        function getSeperator() {
            return jQuery("<span> &gt; </span>");
        }

        (function() {
            if (!categoryTree.length) return;
            getAnchor(categoryTree).prependTo(selector);
            if (categoryTree.length) getSeperator().prependTo(selector);
            arguments.callee();
        })();
    },
    update: function(uid) {
        var query = "AssetUID=" + uid + "&PlayVideo=true";
        updateVideoPlayer(query, false, query);
        jQuery('html,body').animate({ 'scrollTop': $(".td-Video").offset().top }, 'normal');
    },
    play: function(url) {
        if (!!this.Players.VideoZonePlayer.flash) {
            if (VideoPlayer.Ads.Preroll) this.Players.VideoZonePlayer.flash.updateConfig("prerollPath", VideoPlayer.Ads.Preroll + new Date().getTime());
            if (VideoPlayer.Ads.Postroll) this.Players.VideoZonePlayer.flash.updateConfig("postrollPath", VideoPlayer.Ads.Postroll + new Date().getTime());
            this.Players.VideoZonePlayer.flash.updateConfig("videoPathHighQ", url);
            this.Players.VideoZonePlayer.flash.commandPlayer("reset", null, null);
        } else {
            var _this = this;
            this.Players.VideoZonePlayer.pendingRequest = function() { _this.play(url); }
        }
    }
}

/**
* Called by video player for event handling
* s - Omniture object
*/
function handlePlayerEvent(eventType, param) {
    var metadata = VideoPlayer.Players.currentPlayer.metaData;
    var s = s_gi('thestarprod');
    switch (eventType) {
        case "StartingPreRoll":
            if (!!s)
                setTimeout(function() {
                    s.Media.trackEvents = "event3";
                    s.Media.track();
                }, 20);
            break;
        case "FinishedPreRoll":
            if (!!s)
                setTimeout(function() {
                    s.Media.trackEvents = "event4";
                    s.Media.track();
                }, 20);
            break;            
        case "Play":
            if (!!s)
                setTimeout(function() {
                    try { s.Media.play(metadata.uid + "-" + metadata.title, param); } catch (e) { }
                }, 20);
            break;
        case "Stop":
            if (!!s)
                setTimeout(function() {
                    try { s.Media.stop(metadata.uid + "-" + metadata.title, param); } catch (e) { }
                }, 20);
            break;
        case "Pause":
            if (!!s)
                setTimeout(function() {
                    try { s.Media.stop(metadata.uid + "-" + metadata.title, param); } catch (e) { }
                }, 20);
            break;
        case "StartingMainVideo":
            VideoPanels.History.add(metadata.uid);
            if (!!s)
                setTimeout(function() {
                    try {
                        s.Media.open(metadata.uid + "-" + metadata.title, param, "VideoZone Player");
                        s.Media.play(metadata.uid + "-" + metadata.title, 0);
                    } catch (e) { }
                }, 20);
            break;
        case "FinishedMainVideo":
            if (!!s)
                setTimeout(function() {
                    try {
                        s.Media.stop(metadata.uid + "-" + metadata.title, param);
                        s.Media.close(metadata.uid + "-" + metadata.title);
                    } catch (e) { }
                }, 20);
            if (VideoPanels.Playlist.isPlaying) VideoPanels.Playlist.next();
            break;
    }
}



/*****************************************
* Binding Events
******************************************/
(function($) {
    // initialize videobox event
    $('.td-video_subnav a[rel]').live('click', function() {
        selectVideoBox(this); 
    });
    // playing playlist video
    $('.td-playlist_tab_content a.playUID').live('click', function() {
        VideoPanels.Playlist.isPlaying = true; 
    });
    // play video item
    $('a.playUID').live('click', function(event) {
        if (event.button === 0) {
            var $this = $(this);
            var uid = $this.closest('.videoItem').attr('uid');
            event.preventDefault();
            VideoPlayer.update(uid);
        }
    });
    // playlist button
    $('a.playlist-button')
        .live('update', function() {
            var $this = $(this);
            var uid = $this.closest('.videoItem').attr('uid');
            if (VideoPanels.Playlist.isInPlaylist(uid)) {
                $this.find('span').html("Remove from Playlist");
            } else {
                $this.find('span').html("Add to Playlist");
            }
        }).live('click', function(event) {
            event.preventDefault();
            var $this = $(this);
            var uid = $this.closest('.videoItem').attr('uid');
            if (VideoPanels.Playlist.isInPlaylist(uid)) {
                VideoPanels.Playlist.remove(uid);
            } else {
                VideoPanels.Playlist.add(uid);
            }
        });
    // toolbox buttons
    $(".td-help a, .td-video_info_input")
        .live("click", function(event) {
            $(this).parent().find("input").focus().select();
        });

})(jQuery);

/********************************************
* Generic Events handling
*********************************************/

/**
* Form Wrapper
*/
(function() {
    function getInvalidInputs($formWrapper) {
        return jQuery(":input", $formWrapper).map(function(i, elem) {
            if (jQuery(elem).data("valid") === false) return elem;
        });
    }

    function submit($formWrapper) {
        if (getInvalidInputs($formWrapper).length === 0) {
            location.href = $formWrapper.attr('action') + "?" + $.stripTags(decodeURI(TD.ProjectTheStar.SerializeInputs($formWrapper)));
        }
    }

    jQuery('.form-wrapper :text:enabled').live('keydown', function(event) {
        if (event.keyCode === 13 || event.which === 13) {
            event.preventDefault();
            var $formWrapper = $(this).closest('.form-wrapper');
            submit($formWrapper);
        }
    });

    jQuery('.form-wrapper :image, .form-wrapper :submit').live('click', function(event) {
        event.preventDefault();
        var $formWrapper = $(this).closest('.form-wrapper');
        submit($formWrapper);
    });

})();

/************************************************
* Document ready
*************************************************/
// video search box
jQuery(function() {
    jQuery("#td-video_search_field")
        .focus(function() { if (!$(this).data('clicked')) $(this).val('').data('clicked', true).data("valid", true); })
        .blur(function() { if (!$(this).val()) $(this).val('Video Search').data('clicked', false).data("valid", false); })
        .data("valid", false);
});