﻿Viostream.VideoInfo.MediaChangedCallback = function(e, mb) {
    //$(this).empty(); //remove the littleloader
    if (mb.MediaURLs.length > 0) {
        trace('Viostream.VideoInfo.MediaChangedCallback()');
        //trace(this);
        trace(mb);
        var displayDate = mb.DisplayTime.fullYear + "-" + mb.DisplayTime.month + "-" + mb.DisplayTime.day + " " + mb.DisplayTime.hours + ":" + mb.DisplayTime.minutes + ":" + mb.DisplayTime.seconds;

        var desc = mb.MediaDescription;
        if (Viostream.UserIsLoggedIn) {
            desc += "<br/><a href=\"javascript:void(0);\" onclick=\"Viostream.SBox.Show('#moreInformation')\">Would you like more information?</a>"
        }

        //$(this).show();
        $("#" + Viostream.VideoInfo.Title).html(mb.MediaTitle);
        $("#" + Viostream.VideoInfo.Description).html(desc);
        $("#" + Viostream.VideoInfo.DateAdded).html(displayDate);
        $("#" + Viostream.VideoInfo.Views).html(mb.ViewCount);
        $("#" + Viostream.VideoInfo.Duration).html(Viostream.parseDuration(mb.MediaURLs[0].Duration));
        $("#" + Viostream.VideoInfo.Thumbnail).attr("src", mb.Thumbnails[0].Path);


        //make call to
        //http://localhost:54938/Service/Transitions.asmx
        $.ajax({
            url: "/Service/Transitions.asmx/ListViocastResources",
            success: function(o) { Viostream.VideoInfo.AddViocastData(o); },
            data: {
                mediaId: Viostream.MediaId
            }
        });

        if (typeof (mb.Channel) != undefined) {
            $("#" + Viostream.VideoInfo.Channel).html(mb.Channel);
        }

        if (typeof (mb.AuthorName) != undefined) {
            $("#" + Viostream.VideoInfo.Author).html(mb.AuthorName);
        }

        return this;
    }
}

Viostream.OnLoad(function() {

    Viostream.Category.GetHandleSuccess = function(oXML, pageIndex, sortOrder, categoryId, mediaType) {
        /// <summary> Takes the category info and then calls the MediaList </summary>        
        if (!Viostream.AjaxObject.DisplayErrors(oXML, "Get Category")) {
            var description = $(oXML).find("Description").text();
            var title = $(oXML).find("Title").text().replace(/(&nbsp;)/g, " ");

            ///Add Category title and discription
            $("#" + this.CategoryTitle).html("<span>" + title + "</span>");
            $("#" + this.CategoryDescription).html(description);

            //hide Contact Us form Show Search Form if it's not the Viostream.firstCategory
            if (categoryId == Viostream.firstCategoryId) {
                $("div#ContactUs").show();
                $("div#ctl00_PageContent_search").hide();
            } else {
                $("div#ContactUs").hide();
                $("div#ctl00_PageContent_search").show();
                $("div#ctl00_PageContent_search p.searchdetail").remove();
                $("div#ctl00_PageContent_search").append("<p class=\"searchdetail\">currently searching in '" + title + "'</p>");


                //1. Add addendum to search box that says: currently seraching in {currentCategory}
                //2. Add drop-down to search form that contains the subcategories of the current category
                Viostream.search.getSubs(categoryId);
            }


            // Check for any Generic HTML items
            $(oXML).find("GenericHTMLModule").each(function() {
                var HtmlElementId = $(this).find("HtmlElementId").text();
                if (HtmlElementId.length > 0) {
                    $("#" + HtmlElementId).html($(this).find("Content").text());
                }
            });

            Viostream.CurrentCategory = categoryId;
            Viostream.CurrentPageIndex = pageIndex;
            Viostream.SortOrder = sortOrder;

            this.MediaList(categoryId, title, pageIndex, sortOrder, mediaType);
            document.title = Viostream.PortalName + " : " + title;
        }
    }


    Viostream.VideoInfo.AddViocastData = function(oXml) {
        if (!Viostream.AjaxObject.DisplayErrors(oXml, "AddViocastData")) {
            var desc = "";

            $(oXml).find("ResourceResponse").each(function(i) {
                var $this = $(this);
                var span = "<span";
                var downloadType = $this.find("ResourceDownloadType").text();
                var filesize = $this.find("Size").text();
                var title = $this.find("Title").text();
                var path = $this.find("Path").text();
                //change class of span to "downloadType [ResourceDownLoadType]"
                span += " class=\"downloadType " + downloadType.toLowerCase() + "\">";
                span += "<a href=\"" + path + "\" target=\"_blank\">" + title + "</a> (" + filesize + ")</span>";
                desc += span;
            });

            if (desc != "") {
                var vidInfo = $("#" + Viostream.VideoInfo.PanelId).find("dl.vs-info");
                vidInfo.children(".pres").remove();
                vidInfo.append("<dt class=\"pres\">Presentations</dt>");
                vidInfo.append("<dd class=\"pres\">" + desc + "</dd>");
            }
        }
    };

    if (typeof (Viostream.Animation) == "undefined") {
        Viostream.Animation = {};
    }


    Viostream.ScrollTo = function(elem) {
        /// <summary>Performs the scrolling for login/registration boxes. Can be overridden to prevent scrolling.</summary>    
        var wh = window.innerHeight || document.documentElement.clientHeight;
        var wt = window.scrollTop || document.documentElement.scrollTop;
        var ot = $(elem).offset({ relativeTo: "body" }).top;
        if ((ot < wt) || (ot > (wt + wh))) elem.scrollIntoView();
    };

    Viostream.TogglePassword = function() {
        $("#" + Viostream.User.forgotpassword.panelId).slideToggle(Viostream.User.forgotpassword.Duration,
                    function() {
                        if ($(this).is(":visible")) {
                            //fire event - retgistration form has opened
                            //Viostream.Animation.onPasswordOpen();
                            Viostream.ScrollTo(this);
                        }
                        else {
                            //fire event - retgistration form has closed
                            //Viostream.Animation.onPasswordClose();
                        }
                    }
                 );
        $("#" + Viostream.User.register.panelId + ", #" + Viostream.User.login.panelId).slideUp(Viostream.User.forgotpassword.Duration);
    };

    Viostream.ToggleRegistration = function() {
        var $this = $("#" + Viostream.User.register.panelId);
        if ($this.is(":visible")) {
            Viostream.Sbox.Hide();
        } else {
            Viostream.SBox.Show("#" + Viostream.User.register.panelId);
        }
    }

    Viostream.ToggleLogin = function() {
        var $this = $("#" + Viostream.User.login.panelId);
        if ($this.is(":visible")) {
            Viostream.Sbox.Hide();
        } else {
            Viostream.SBox.Show("#" + Viostream.User.login.panelId);
        }
    }

    Viostream.SBox = {
        id: null,
        Init: function() {
            this.id = "div#sb-container";

        },
        Show: function(o) {

            $(o).show();
            $(this.id).css('display', 'block');
            $("div#sb-overlay").fadeTo('fast', '0.8');
            //pause player
            swf.mediaPause();
        },
        Hide: function(o) {

            $("div#sb-overlay").fadeTo('fast', '0.1', function() {
                $(Viostream.SBox.id).css('display', 'none');
                $("#" + Viostream.User.register.panelId).hide();
                $("#" + Viostream.User.login.panelId).hide();
                $("#" + Viostream.User.forgotpassword.panelId).hide();
                $("#moreInformation").hide();
                //start player
                swf.mediaPlay();
            });

        },
        ResizeToFit: function() {
            //var targ = $(o);
            var sbcontent = $("div#sb-container div#sb-content");
            sbcontent.slideDown();
        }
    };

    Viostream.SBox.Init();

    $("div#masthead a#registerlink").click(function() {

        Viostream.SBox.Show("#" + Viostream.User.register.panelId);
    });
    $("div#masthead a#loginlink").click(function() {

        Viostream.SBox.Show("#" + Viostream.User.login.panelId);
    });

    Viostream.CloseLogin = Viostream.CloseRegistration = function() {
        Viostream.SBox.Hide();
    };




    Viostream.MediaBase.prototype.AddToPlayList = function(evt) {
        /// <summary> 
        /// Adds this media item to the current playlist. If there is
        /// no playlist, it will create one and then add the item to it.
        /// </summary>
        try {

            if (Viostream.CurrentCategory == Viostream.firstCategoryId || Viostream.UserIsLoggedIn) {

                var mb;
                var playNow;

                if (typeof (evt) == "undefined") {
                    mb = this;
                    playNow = true;
                }
                else {
                    mb = evt.data.mb;
                    playNow = evt.data.playnow;
                }

                if (typeof (Viostream.PlayList) != "undefined") {
                    Viostream.PlayList.ClientSidePlaylist.push(mb);
                }

                var txtPlayListId = ($gE("txtPlayListId") == null) ? document.forms[0].eval("txtPlayListId") : $gE("txtPlayListId");

                var playListId = txtPlayListId.value;

                //no current playlist
                if (typeof (Viostream.PlayList) != "undefined") {
                    if (playListId.length == 0) {
                        ///Create a new playlist
                        trace("Viostream.PlayList.Create");
                        Viostream.PlayList.Create(mb.MediaId, txtPlayListId);
                    } else {
                        //add mediId GUID to playlist
                        Viostream.PlayList.AddMedia(txtPlayListId.value, mb.MediaId, playNow);
                        trace("Viostream.PlayList.AddMedia");
                    }
                }

                trace("Viostream.MediaBase.prototype.AddToPlayList()");
                jQuery.event.trigger("AddToPlayList", mb);
            } else {
                window.alert("You must be registered and logged in before you can view content outside of the 'Home' Category");
                var el = document.getElementById("masthead");
                el.scrollIntoView(true);
            }
        }
        catch (e) {
            notify("AddToPlayList(playGUID) " + e.message, true);
        }
    };

    Viostream.Extend(
        Viostream.search, {
            categories: new Array(),

            getSubsSuccess: function(json, categoryId) {
                trace("getSubsSuccess : " + json);

                $("div#ctl00_PageContent_search select#searchSelect").remove();

                var parentId = categoryId;
                /*for (var x = 0; x < json.d.Item.length; x++) {
                if (json.d.Item[x].Id == categoryId)
                parentId = json.d.Item[x].ParentId;
                }*/
                if (parentId != null) {
                    var o = null;
                    var sellist = null;
                    for (var i = 0; i < json.d.Item.length; i++) {
                        if (json.d.Item[i].ParentId == parentId) {
                            o = json.d.Item[i];
                            sellist += "<option value=\"" + o.Id + "\">" + o.Title + "</option>";
                        }
                    }
                    if (sellist != null) {
                        $("div#ctl00_PageContent_search").append("<select id=\"searchSelect\"><option value=\"\">Choose a subcategory</option>" + sellist + "</select>");
                    }
                }
            },
            getSubs: function(catId) {
                trace("Viostream.search.getSubs()");
                $.ajax({
                    type: "POST",
                    url: "/Service/Core.asmx/CategoryList",
                    data: "{}",
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function(o) { Viostream.search.getSubsSuccess(o, catId); }
                });
            }
        }
    );

    //listen for UserLoggedIn Event
    $("#moreInformation").bind("UserLoggedIn", function(e, userdata) {
        $("#moreinfoUserEmail").val(userdata.FirstName + " " + userdata.LastName);
        $("#moreinfoVideoURL").val(userdata.EmailAddress);
    });


    jQuery.extend(Viostream, {
        Search: function(SearchWord, PageIndex, MediaFilter) {
            /// <summary> Performs the search </summary>


            if (typeof (MediaFilter) == "undefined") MediaFilter = this.MediaType;
            var cat = this.CurrentCategory;
            // change the current variables so that we can sort and filter the search results
            this.CurrentCategory = "searchterm";
            this.CurrentPageIndex = PageIndex;
            this.MediaType = MediaFilter;
            this.SearchTerm = SearchWord;

            var SearchHandleSuccess = function(o) {
                /// <summary> AJAX search response </summary>
                if (!Viostream.AjaxObject.DisplayErrors(o, "Search")) {
                    $("div.pagination-controls").empty().hide(); // search does not paginate
                    if (Viostream.redrawMedia(o) == 0) {
                        notify("Search result doesn't return any data");
                    }
                }
                Viostream.Category.hideLoader();
                $("#" + Viostream.Category.CategoryTitle).html("<span>Search Results</span>");
                $("#" + Viostream.Category.CategoryDescription).html("<p>Displaying search results for the search term:" + SearchWord + "</p>");
                //$(".menu-controls").hide();
            };


            Viostream.Category.showLoader();
            var selval = $("div#ctl00_PageContent_search select#searchSelect option:selected").val();
            trace("selvala = " + selval);

            catId = (selval == "" || typeof (selval) == "undefined") ? cat : selval;

            $.ajax({
                url: Viostream.WSUrl + "MediaSearchCategory",
                data: { searchWord: SearchWord, pageIndex: PageIndex, categoryId: catId },
                success: SearchHandleSuccess
            });


        }
    });

    Viostream.MoreInfo = {
        Send: function() {
            vioId = Viostream.MediaId; //currentlyplaying
            com = $("textarea#moreinfoComment").text();
            $.ajax({
                url: "/Service/Extras.asmx/MoreInfoRequest",
                success: function(o) { Viostream.MoreInfo.HandleResponse(o); },
                data: {
                    mediaId: vioId,
                    userId: Viostream.user.Id,
                    comment: com
                }
            });
        },
        HandleResponse: function(oXml) {

            if (!Viostream.AjaxObject.DisplayErrors(oXML, "Request More Information")) {
                window.alert("An email requesting more information about the currently playing Video has been sent to the site administrator.");
                Viostream.SBox.Hide();
            }
        }

    };

    trace("Viostream.extension.onload");

});


Viostream.PostLoad(function() {

    

    trace("Viostream.extension.postload");
});

