Ektron.ready(function()
{
    if (typeof(Ektron.Widget) == "undefined")
    {
        Ektron.Widget = {};
    }

    if(typeof(Ektron.Widget.BrightcoveVideo) == "undefined")
    {
        Ektron.Widget.BrightcoveVideo =
        {
            // PROPERTIES
            lastPage: 0,
            maxCount: 0,
            pageSize: 5,
            pageNumber: 0,
            webserviceURL: "/widgets/BrightcoveVideo/handler/BCHandler.ashx",
            sortBy: "publish_date", // options include CREATION_DATE, MODIFIED_DATE, PLAYS_TOTAL, PLAYS_TRAILING_WEEK. 
            sortOrder: "DESC",  // options include ascending (ASC) or descending (DESC).
            widgets: [],

            // CLASS OBJECTS
            CreateRequestObject: function (action, id, name, description, fileurl, writetoken) {
                request = {
                    "action": action,
                    "id": id,
                    "title": name,
                    "description": description,
                    "fileurl": fileurl,
                    "writetoken": writetoken
                };
                return Ektron.JSON.stringify(request);
            },

            ProcessRequest: function (action, id, name, description, fileurl, writetoken) {
                var str = Ektron.Widget.BrightcoveVideo.CreateRequestObject(action, id, name, description, fileurl, writetoken);
                var progress = $ektron(".BCProgress");
                switch (action)
                {
                    case "add":
                        progress.html("Uploading " + name + " Video");
                        break;
                    case "update":
                        progress.html("Updating " + name + " Video");
                        break;
                    case "delete":
                        progress.html("Deleting " + name + " Video");
                        break;
                }
                $ektron.ajax({
                    type: "POST",
                    cache: false,
                    async: false,
                    url: Ektron.Widget.BrightcoveVideo.webserviceURL,
                    data: { "request": str },
                    success: function (msg) {
                        progress.html(msg);
                    }
                });

                return false;
            },

            SwitchPane: function (el, panename) {
                var parent = $ektron(el).parents(".brightcove");
                var tablist = parent.find(".ektronWidgetBCTabs li a");
                var panes = parent.children(".pane");
				if(panename != "VideoListTab")
                {
                    $ektron(".BCProgress").html("");
                }
                for (var i = 0; i < tablist.length; i++) {
                    $ektron(tablist[i]).removeClass("selectedTab");
                    if (tablist[i].id == panename) $ektron(tablist[i]).addClass("selectedTab");
                }

                for (var i = 0; i < panes.length; i++) {
                    $ektron(panes[i]).hide();
                    if ($ektron(panes[i]).hasClass(panename)) $ektron(panes[i]).show();
                }

                Ektron.Widget.BrightcoveVideo.ResetPages();
            },

            BrightcoveVideoWidget: function (id, token, writetoken, outputId, titleId, descriptionId, submitButtonId, deleteButtonId, updateButtonId)
            {
                var obj = this;
                obj.id = id;

                obj.token = token;
                obj.submitBtn = $ektron("#" + submitButtonId);
                obj.output = $ektron("#" + outputId);
                obj.writetoken = writetoken;

                if (token.length > 1) 
                {
                    obj.VideoClicked = function(id)
                    {
                        $ektron(".BCProgress").html("");
                        obj.output.attr("value", id);
                        $ektron("input#__EVENTTARGET").attr("value", $ektron("#" + submitButtonId).attr("name"));
                        document.forms[0].submit();
                    };

                    obj.ChangeTabUpdate = function(id, name, description)
                    {
                        $ektron(".BCProgress").html("");
                        obj.output.attr("value", id);
                        Ektron.Widget.BrightcoveVideo.SwitchPane($ektron('.UpdateVideo'), 'UpdateVideo');
                        $ektron(".BCVideoId").val(id);
                        $ektron(".videoname").val(name);
                        $ektron(".videodescription").val(description);
                        return false;
                    };

                    obj.FindVideos = function () {
                        var tag = $ektron("<script><\/script>");
                        tag.attr("type", "text/javascript");
                        Ektron.Widget.BrightcoveVideo.sortOrder = $ektron("#" + id + "sort_order").val();
                        Ektron.Widget.BrightcoveVideo.sortBy = $ektron("#" + id + "sort_by").val();
                        
						var ts = new Date().getTime();
						var fn = "callback" + ts;
						window[fn] = Ektron.Widget.BrightcoveVideo.GetWidget(obj.id).DisplayVideos
						
						tag.attr("src", "http://api.brightcove.com/services/library?command=find_all_videos&callback=" + fn + "&sort_by=" + Ektron.Widget.BrightcoveVideo.sortBy + "&page_size=" + Ektron.Widget.BrightcoveVideo.pageSize + "&page_number=" + Ektron.Widget.BrightcoveVideo.pageNumber + "&sort_order=" + Ektron.Widget.BrightcoveVideo.sortOrder + "&get_item_count=true&fields=id,name,shortDescription,thumbnailURL&token=" + obj.token);
                        $ektron("head").append(tag.get(0));
						
                    };

                    obj.DeleteVideo = function(id)
                    {
                        $ektron(".BCProgress").html("");
                        Ektron.Widget.BrightcoveVideo.ProcessRequest("delete", id, "", "", "", obj.writetoken);
                        obj.FindVideos();
                        return false;
                    };

                    obj.AddVideo = function()
                    {
                        $ektron(".BCProgress").html("");
                        var message = $ektron(".BCProgress");
                        var title = $ektron(".BCAddVideoName").val();
                        var description = $ektron(".BCAddVideoDescription").val();
                        var fileurl = $ektron(".BCAddVideoFile").val();
                        if (title != "" && description != "" && fileurl != "") {
                            Ektron.Widget.BrightcoveVideo.ProcessRequest("add", "", title, description, fileurl, obj.writetoken);
                            obj.FindVideos();
                            Ektron.Widget.BrightcoveVideo.SwitchPane($ektron('.VideoListTab'), 'VideoListTab');
                        } else {
                            message.html("<span style='color:red;'>Fill all the required fields</span>");
                        }
                        return false;
                    };

                    obj.UpdateVideoDetails = function()
                    {
                        $ektron(".BCProgress").html("");
                        var message = $ektron(".BCProgress");
                        var id = $ektron(".BCVideoId").val();
                        var title = $ektron(".videoname").val();
                        var description = $ektron(".videodescription").val();
                        if (title != "" && description != "") {
                            Ektron.Widget.BrightcoveVideo.ProcessRequest("update", id, title, description, "", obj.writetoken);
                            obj.FindVideos();
                            Ektron.Widget.BrightcoveVideo.SwitchPane($ektron('.VideoListTab'), 'VideoListTab');
                        } else {
                            message.html("<span style='color:red;'>Fill all the required fields</span>");
                        }
                        return false;
                    };

                    obj.PreviousVideos = function()
                    {
                        $ektron(".BCProgress").html("");
                        Ektron.Widget.BrightcoveVideo.pageNumber += -1;
                        obj.FindVideos();
                    };

                    obj.NextVideos = function()
                    {
                        $ektron(".BCProgress").html("");
                        Ektron.Widget.BrightcoveVideo.pageNumber += 1;
                        obj.FindVideos();
                    };

                    obj.FirstVideos = function()
                    {
                        $ektron(".BCProgress").html("");
                        Ektron.Widget.BrightcoveVideo.ResetPages();
                        Ektron.Widget.BrightcoveVideo.pageNumber = 0;
                        obj.FindVideos();
                    };

                    obj.LastVideos = function()
                    {
                        $ektron(".BCProgress").html("");
                        Ektron.Widget.BrightcoveVideo.pageNumber = Ektron.Widget.BrightcoveVideo.lastPage;
                        obj.FindVideos();
                    };

                    obj.SearchPreviousVideos = function()
                    {
                        Ektron.Widget.BrightcoveVideo.pageNumber += -1;
                        obj.SearchVideos();
                    };

                    obj.SearchNextVideos = function()
                    {
                        $ektron(".BCProgress").html("");
                        Ektron.Widget.BrightcoveVideo.pageNumber += 1;
                        obj.SearchVideos();
                    };

                    obj.SearchFirstVideos = function()
                    {
                        $ektron(".BCProgress").html("");
                        Ektron.Widget.BrightcoveVideo.ResetPages();
                        Ektron.Widget.BrightcoveVideo.pageNumber = 0;
                        obj.SearchVideos();
                    };

                    obj.SearchLastVideos = function()
                    {
                        Ektron.Widget.BrightcoveVideo.pageNumber = Ektron.Widget.BrightcoveVideo.lastPage;
                        obj.SearchVideos();
                    };

                    obj.SearchVideos = function() 
                    {
                        var tbData = $ektron("#" + id + "SearchText");
                        var text = tbData.val();
                        var searchtype;

                        searchtype = $ektron("#" + id + "searchtype").val();
                        
                        var tag = $ektron("<script><\/script>");
                        tag.attr("type", "text/javascript");

                        var ts = new Date().getTime();
                        var fn = "callback" + ts;
                        window[fn] = Ektron.Widget.BrightcoveVideo.GetWidget(obj.id).DisplaySearchVideos

                        if (searchtype == "TEXT") {
                            tag.attr("src", "http://api.brightcove.com/services/library?command=find_videos_by_text&text=" + escape(text) + "&page_size=" + Ektron.Widget.BrightcoveVideo.pageSize + "&page_number=" + Ektron.Widget.BrightcoveVideo.pageNumber + "&callback=" + fn + "&get_item_count=true&token=" + obj.token);
                        } else if (searchtype == "TAG") {
                            tag.attr("src", "http://api.brightcove.com/services/library?command=find_videos_by_tags&or_tags=" + escape(text) + "&page_size=" + Ektron.Widget.BrightcoveVideo.pageSize + "&page_number=" + Ektron.Widget.BrightcoveVideo.pageNumber + "&callback=" + fn + "&get_item_count=true&token=" + obj.token);
                        }
                        $ektron("head").append(tag.get(0));
                    };

                    obj.MakeVideoThumbnail = function(thumbnailURL)
                    {
                        var thumbnail = $ektron("<img></img>");
                        thumbnail.attr("src", thumbnailURL);
                        thumbnail.attr("class", "thumbnail");
                        return thumbnail;
                    };

                    obj.DeleteVideoLink = function(id, name)
                    {
                        var deleteLink = $ektron("<a></a>");
                        deleteLink.attr("href", "");
                        deleteLink.html('Delete');
                        return deleteLink;
                    };

                    obj.MakeVideoLink = function(id, name)
                    {
                        var videoLink = $ektron("<a></a>");
                        videoLink.attr("href", "");
                        videoLink.html(name);
                        return videoLink;
                    };

                    obj.UpdateVideoLink = function(id, name)
                    {
                        var updateLink = $ektron("<a></a>");
                        updateLink.attr("href", "#");
                        updateLink.html("Update");
                        return updateLink;
                    };

                    obj.MakeVideoShortDescription = function(shortDescription)
                    {
                        var description = $ektron("<span></span>");
                        description.attr("class", "short-description");
                        description.html(shortDescription);
                        return description;
                    };

                    obj.DisplayVideos = function(videoCollection)
                    {
                        var list = $ektron("#" + obj.id + " ul.video-list");
                        list.html("");
                        var alt = false;
                        Ektron.Widget.BrightcoveVideo.maxCount = videoCollection.total_count;
                        for (var i in videoCollection.items) 
                        {
                            var listItem = $ektron("<li></li>");
                            if (i === 0) {
                                listItem.attr("class", "alt1 videoFirst clearfix");
                            }
                            else {
                                listItem.attr("class", (alt = !alt) ? "alt1 clearfix" : "alt2 clearfix");
                            }
							if(videoCollection.items[i].thumbnailURL == null)
                            {
                                videoCollection.items[i].thumbnailURL = "/Widgets/BrightcoveVideo/images/ektronlogo.gif";
                            }
                            var thumbnail = obj.MakeVideoThumbnail(videoCollection.items[i].thumbnailURL);
                            var videoLink = obj.MakeVideoLink(videoCollection.items[i].id, videoCollection.items[i].name);
                            var description = obj.MakeVideoShortDescription(videoCollection.items[i].shortDescription);

                            listItem.append("<div class='videoThumbOuter'></div>");
                            listItem.find(".videoThumbOuter").append("<div class='videoThumbInner'></div>");
                            listItem.find(".videoThumbInner").append(thumbnail.get(0));
                            if(obj.writetoken != "")
                            {
                                var deleteitem = obj.DeleteVideoLink(videoCollection.items[i].id, videoCollection.items[i].name);
                                var updateitem = obj.UpdateVideoLink(videoCollection.items[i].id, videoCollection.items[i].name);
                                listItem.append("<div class='videoDelete'></div>");
                                listItem.append("<div class='videoUpdate'></div>");
                                listItem.find(".videoDelete").append(deleteitem.get(0));
                                listItem.find(".videoUpdate").append(updateitem.get(0));
                            }
                            listItem.append(videoLink.get(0));
                            listItem.append(description.get(0));

                            listItem.hover(function() 
                                { 
                                $ektron(this).addClass('hover');
                            },
                                function() 
                                {
                                    $ektron(this).removeClass('hover');
                                }
                            );
                            if (obj.writetoken != "") {
                                updateitem.click(
                                    (function(id, name, description)
                                        {
                                            return function() 
                                            {
                                            obj.ChangeTabUpdate(id, name, description);
                                            return false;
                                        };
                                    }
                                    )(videoCollection.items[i].id, videoCollection.items[i].name, videoCollection.items[i].shortDescription)
                                );
                                deleteitem.click(
                                    (function(id) 
                                        {
                                            return function() 
                                            {
                                            obj.DeleteVideo(id);
                                            return false;
                                        };
                                    }
                                    )(videoCollection.items[i].id)
                                );
                            }
                            listItem.click(
                                (function(id) 
                                    {
                                        return function() 
                                        {
                                        obj.VideoClicked(id);
                                        return false;
                                    };
                                }
                                )(videoCollection.items[i].id)
                            );
                            list.append(listItem);
                        }
                        Ektron.Widget.BrightcoveVideo.Pagingbuttons(obj.id, Ektron.Widget.BrightcoveVideo.maxCount, i);

                    };

                    obj.DisplaySearchVideos = function(videoCollection) 
                    {
                        var list = $ektron("#" + obj.id + " ul.video-search");
                        list.html("");
                        var alt = false;
                        Ektron.Widget.BrightcoveVideo.maxCount = videoCollection.total_count;
                        for (var i in videoCollection.items) {
                            var listItem = $ektron("<li></li>");
                            if (i == 0) {
                                listItem.attr("class", "alt1 videoFirst clearfix");
                            }
                            else {
                                listItem.attr("class", (alt = !alt) ? "alt1 clearfix" : "alt2 clearfix");
                            }
							if(videoCollection.items[i].thumbnailURL == null)
                            {
                                videoCollection.items[i].thumbnailURL = "/Widgets/BrightcoveVideo/images/ektronlogo.gif";
                            }
                            var thumbnail = obj.MakeVideoThumbnail(videoCollection.items[i].thumbnailURL);
                            var videoLink = obj.MakeVideoLink(videoCollection.items[i].id,
                                                              videoCollection.items[i].name);
                            var description = obj.MakeVideoShortDescription(videoCollection.items[i].shortDescription);
                            listItem.append("<div class='videoThumbOuter'></div>");
                            listItem.find(".videoThumbOuter").append("<div class='videoThumbInner'></div>");
                            listItem.find(".videoThumbInner").append(thumbnail.get(0));
                            listItem.append(videoLink.get(0));
                            listItem.append(description.get(0));

                            listItem.hover(function () { $ektron(this).addClass('hover'); },
                                           function () { $ektron(this).removeClass('hover'); });
                            listItem.click((function (id) {
                                return function () {
                                    obj.VideoClicked(id);
                                    return false;
                                };
                            })(videoCollection.items[i].id));
                            list.append(listItem);
                        }
                        Ektron.Widget.BrightcoveVideo.PagingbuttonsSearch(obj.id, Ektron.Widget.BrightcoveVideo.maxCount, i);
                    };

                    obj.PlayerItem = function(title, id)
                    {
                        var item = $ektron("<li></li>");
                        item.html(title);
                        item.click(function ()
                        {
                            obj.PlayerClicked(title, id);
                        });
                        return item.get(0);
                    };

                    obj.KeyPressHandler = function(elem, event, id) 
                    {                        
                        if (event.keyCode == 13) {
                            if (event.preventDefault) event.preventDefault();
                            if (event.stopPropagation) event.stopPropagation();
                            event.returnValue = false;
                            event.cancel = true;
                            setTimeout('Ektron.Widget.BrightcoveVideo.widgets["' + id + '"].SearchVideos()', 1);
                            return false;

                        }
                    };
                }
            },


            // METHODS

            AddWidget: function(id, token, writetoken, outputId, titleId, descriptionId, submitButtonId, deleteButtonId, updateButtonId)
            {
                var widg = new Ektron.Widget.BrightcoveVideo.BrightcoveVideoWidget(id, token, writetoken, outputId, titleId, descriptionId, submitButtonId, deleteButtonId, updateButtonId);
                Ektron.Widget.BrightcoveVideo.widgets[id] = widg;

                // Create video player list
                $ektron("#" + id + " .player-heading").hover(
                    function(evt) 
                    {
                        var playerHeading = $ektron(this).find("ul");
                        playerHeading.width($ektron(this).width());
                        playerHeading.show();
                    },
                    function() 
                    {
                        playerHeading.hide();
                    }
                );
                Ektron.Widget.BrightcoveVideo.widgets[id].FindVideos();
            },

            GetWidget : function(id)
            {
                return Ektron.Widget.BrightcoveVideo.widgets[id];
            },

            Pagingbuttons: function (id, maxcount, items)
            {
                var numpages = 0;
                var theresults = "Results";
                var pagestart = 0;
                var pageend = parseInt(items);
                if (maxcount > 0)
                {
                    numpages = parseInt((maxcount - 1) / Ektron.Widget.BrightcoveVideo.pageSize);
                }
                if (maxcount > Ektron.Widget.BrightcoveVideo.pageSize) {

                    $ektron("#" + id + "First").css('display', 'inline-block');
                    $ektron("#" + id + "Previous").css('display', 'inline-block');
                    $ektron("#" + id + "Next").css('display', 'inline-block');
                    $ektron("#" + id + "Last").css('display', 'inline-block');

                }
                else {
                    $ektron("#" + id + "First").css('display', 'none');
                    $ektron("#" + id + "Previous").css('display', 'none');
                    $ektron("#" + id + "Next").css('display', 'none');
                    $ektron("#" + id + "Last").css('display', 'none');
                }
                Ektron.Widget.BrightcoveVideo.lastPage = numpages;
                if (Ektron.Widget.BrightcoveVideo.pageNumber == 0)
                {
                    $ektron("#" + id + "First").attr("disabled", true).addClass("ektronWidgetBCFirstDisabled");
                    $ektron("#" + id + "Previous").attr("disabled", true).addClass("ektronWidgetBCPreviousDisabled");
                }
                else
                {
                    $ektron("#" + id + "First").attr("disabled", false).removeClass("ektronWidgetBCFirstDisabled");
                    $ektron("#" + id + "Previous").attr("disabled", false).removeClass("ektronWidgetBCPreviousDisabled");
                }

                if (Ektron.Widget.BrightcoveVideo.pageNumber < numpages)
                {
                    $ektron("#" + id + "Next").attr("disabled", false).removeClass("ektronWidgetBCNextDisabled");
                    $ektron("#" + id + "Last").attr("disabled", false).removeClass("ektronWidgetBCLastDisabled");
                }
                else
                {
                    $ektron("#" + id + "Next").attr("disabled", true).addClass("ektronWidgetBCNextDisabled");
                    $ektron("#" + id + "Last").attr("disabled", true).addClass("ektronWidgetBCLastDisabled"); ;
                }
                if (maxcount > 0) {
                    pagestart = (Ektron.Widget.BrightcoveVideo.pageNumber * Ektron.Widget.BrightcoveVideo.pageSize) + 1;
                    pageend = pageend + pagestart;
                    theresults = "Results " + pagestart + " - " + pageend + " of " + maxcount;
                } else {
                    theresults = "No Results";
                }
                $ektron(".video-result").html("");
                $ektron(".video-result").append(theresults);
            },

            PagingbuttonsSearch: function(id, maxcount, items)
            {
                var numpages = 0;
                var theresults = "Results";
                var pagestart = 0;
                var pageend = parseInt(items);
                if (maxcount > 0)
                {
                    numpages = parseInt((maxcount - 1) / Ektron.Widget.BrightcoveVideo.pageSize);
                }

                if (maxcount > Ektron.Widget.BrightcoveVideo.pageSize)  // first Page check
                {

                    $ektron("#" + id + "FirstSearch").css('display', 'inline-block');
                    $ektron("#" + id + "PreviousSearch").css('display', 'inline-block');
                    $ektron("#" + id + "NextSearch").css('display', 'inline-block');
                    $ektron("#" + id + "LastSearch").css('display', 'inline-block');

                }
                else {
                    $ektron("#" + id + "FirstSearch").css('display', 'none');
                    $ektron("#" + id + "PreviousSearch").css('display', 'none');
                    $ektron("#" + id + "NextSearch").css('display', 'none');
                    $ektron("#" + id + "LastSearch").css('display', 'none');
                }
                Ektron.Widget.BrightcoveVideo.lastPage = numpages;
                if (Ektron.Widget.BrightcoveVideo.pageNumber == 0)
                {
                    $ektron("#" + id + "FirstSearch").attr("disabled", true).addClass("ektronWidgetBCFirstDisabled");
                    $ektron("#" + id + "PreviousSearch").attr("disabled", true).addClass("ektronWidgetBCPreviousDisabled");
                }
                else
                {
                    $ektron("#" + id + "FirstSearch").attr("disabled", false).removeClass("ektronWidgetBCFirstDisabled");
                    $ektron("#" + id + "PreviousSearch").attr("disabled", false).removeClass("ektronWidgetBCPreviousDisabled");
                }

                if (Ektron.Widget.BrightcoveVideo.pageNumber < numpages)
                {
                    $ektron("#" + id + "NextSearch").attr("disabled", false).removeClass("ektronWidgetBCNextDisabled");
                    $ektron("#" + id + "LastSearch").attr("disabled", false).removeClass("ektronWidgetBCLastDisabled");
                }
                else
                {
                    $ektron("#" + id + "NextSearch").attr("disabled", true).addClass("ektronWidgetBCNextDisabled");
                    $ektron("#" + id + "LastSearch").attr("disabled", true).addClass("ektronWidgetBCLastDisabled");
                }

                if (maxcount > 0) {
                    pagestart = (Ektron.Widget.BrightcoveVideo.pageNumber * Ektron.Widget.BrightcoveVideo.pageSize) + 1;
                    pageend = pageend + pagestart;
                    theresults = "Results " + pagestart + " - " + pageend + " of " + maxcount;
                } else {
                    theresults = "No Results";
                }

                $ektron(".video-search-result").html("");
                $ektron(".video-search-result").append(theresults);
            },

            ResetPages: function () {
                Ektron.Widget.BrightcoveVideo.pageNumber = 0;
                Ektron.Widget.BrightcoveVideo.maxCount = 0;
                Ektron.Widget.BrightcoveVideo.lastPage = 0;
            }
        };
    }
});
