Btv.Templating.Register([{id:"Feed.FeedTypeSorter",fnc:function($data){var $text = [];var _write = function(text) {$text.push((typeof text == "number")?text:(text||""));};with($data){ Main = function(o, ht) {var $text = [];var _write = function(text) {$text.push((typeof text == "number")?text:(text||""));};_write('\r\n\n<div class=\"feed-sort\"><b>Sort by:</b>&nbsp;');_write(ht.Links);_write('</div>\n');;return($text.join(""));};
new (function(d, ui) {
var oThis = Btv.Lang.Extend(this, Btv.Cst.BaseTemplate, [$data, true]);
var htUI = ui;
var $el = oThis.El;

    var oElMan = oThis.ElMan();
    var currentFeedTypeId;

    function Render() {
        currentFeedTypeId = d.oDefaultFeedType.Id;
    
        var links = '';
        for (i = 0; i < d.aFeedTypes.length; i++) {
            var oFeedType = d.aFeedTypes[i];

            if (i != 0) {
                links += ' | ';
            }
            
            if (d.oDefaultFeedType.Id == oFeedType.Id) {
                links += $F('<a id="feed-type-{1}" href="javascript:{0}({1})" class="feed-sort-strong">{2}</a>', $OG(GetFeedItems), oFeedType.Id, oFeedType.Label);
            }
            else {
                links += $F('<a id="feed-type-{1}" href="javascript:{0}({1})">{2}</a>', $OG(GetFeedItems), oFeedType.Id, oFeedType.Label);
            }
        }

        return (htUI.Main(oThis, {Links: links}));
    }

    function GetFeedItems(feedTypeId) {

        function f(data) {
            $("feed-type-" + currentFeedTypeId).className = "";
            $("feed-type-" + feedTypeId).className = "feed-sort-strong";
            currentFeedTypeId = feedTypeId;

            if (data != null && data.ContextFeed != null && data.ContextFeed.length != 0) {
                $(d.feedId).innerHTML = '';
                aMessages = new Array();

                for (i = 0; i < data.ContextFeed.length; i++) {
                    aMessages.push(data.ContextFeed[i].Message);
                    
                    var oRateItem = Btv.Templating.GetInstance("Feed.RateItem", {associationId: data.ContextFeed[i].AssociationId
                                                                                 , ratingData: data.ContextFeed[i].RatingData
                                                                                });
                    oRateItem.Render();

                    var aComments;

                    for (var j in data.FeedCommentsHash) {
                        for (var k in data.FeedCommentsHash[j]) {
                            if (data.FeedCommentsHash[j][k] == data.ContextFeed[i].AssociationId) {
                                aComments = data.FeedCommentsHash[j][parseInt(k) + 1];
                            }                                 
                        }
                    }

                    var oCommentBox = Btv.Templating.GetInstance("Common.InlineComments", {associationId: data.ContextFeed[i].AssociationId
                                                                                            , comments: aComments
                                                                                            , commentCount: data.ContextFeed[i].CommentCount
                                                                                            , firstComment: 1
                                                                                            , numComments: 15});
                    aMessages.push(oCommentBox.Render());
                }
                $(d.feedId).innerHTML = aMessages.join('');
            }
            else{
                $(d.feedId).innerHTML = "Nothing to display";
            }
        }

        d.fncGetFeed(d.iContextTypeId, d.iContextId, feedTypeId, d.iTotalFeedItems, f);
    }
    
    oThis.DeclareVirtualMethods({
        Render: Render
    });
        
})($data, {Main:Main});
}return $text.join("");}},{id:"Feed.Navigation",fnc:function($data){var $text = [];var _write = function(text) {$text.push((typeof text == "number")?text:(text||""));};with($data){ Main = function(o, tabs, ht) {var $text = [];var _write = function(text) {$text.push((typeof text == "number")?text:(text||""));};_write('\r\n \n<div>\n<div>\n<span>Context Type:</span>\n<span>\n<select ');_write(o.Elem('contextTypeSelector'));_write('  onchange=\"');_write(ht.contextTypeSelectorOnChange);_write('\" style=\"');_write(o.Style());_write('\">');_write(o.InnerHTML());_write('\n<option selected=\"selected\" value=\"0\">Select Context Type</option>\n<option value=\"2\">TV Shows</option>\n<option value=\"19\">Movies</option>\n<option value=\"21\">Cast Member</option>\n</select>\n</span>\n</div>\n<div>\n<span>Context:</span>\n<span>\n<select ');_write(o.Elem('contextSelector'));_write('  onchange=\"');_write(ht.contextSelectorOnChange);_write('\" style=\"');_write(o.Style());_write('\">');_write(o.InnerHTML());_write('\n<option value=\"0\">Select Context Type First</option>\n</select>\n</span>\n</div>\n<div>\n<span>Feed Type:</span>\n<span>\n<select ');_write(o.Elem('feedTypeSelector'));_write('  onchange=\"');_write(ht.feedTypeSelectorOnChange);_write('\" style=\"');_write(o.Style());_write('\">');_write(o.InnerHTML());_write('\n</select>\n</span>\n</div>\n</div>\n');_write(tabs.Render());_write('\n');;return($text.join(""));};
new (function(d, ui) {
var oThis = Btv.Lang.Extend(this, Btv.Cst.BaseTemplate, [$data, true]);
var htUI = ui;
var $el = oThis.El;

    var oElMan = oThis.ElMan();
    var oController;

    function Model(tvshows, movies, castMembers, aFeedTypes, aContentTypes, oManualFeedItem, fncGetFeeds, fncOrderFeeds, fncRemoveFeedItem, fncSaveContentRankings, fncRemoveContentRanking, fncInsertManualFeedItem, fncRemoveManualFeedItem, fncGetLatestManualFeedItems) {
        var oModel = this;
        var iContextTypeId;
        var iContextId;
        var iFeedCount = 15;
        var aFeeds;
        var aContentRankings;
        var aManualFeedItems;
        var oFeedType;

        oModel.GetContextTypeId = function(){
            return iContextTypeId;
        }
        
        oModel.SetContextTypeId = function(id){
            iContextTypeId = id;
        }
        
        oModel.GetContextId = function(){
            return iContextId;
        }
        
        oModel.SetContextId = function(id){
            iContextId = id;
        }

        oModel.GetContentTypes = function() {
            return aContentTypes;
        }
        
        oModel.SetFeedType = function(iFeedTypeId){
            for(var i = 0; i < aFeedTypes.length; i++){
                if(iFeedTypeId == aFeedTypes[i].Id){
                    oFeedType = aFeedTypes[i];
                }
            }
        }
        
        oModel.GetFeeds = function(){
            return aFeeds;
        }

        oModel.SetFeeds = function(feeds) {
            aFeeds = feeds;
        }

        oModel.DumpFeeds = function() {
            aFeeds = [];
        }

        oModel.GetContentRankings = function() {
            return aContentRankings;
        }

        oModel.SetContentRankings = function(rankings) {
            aContentRankings = rankings;
        }

        oModel.DumpContentRankings = function() {
            aContentRankings = [];
        }

        oModel.GetManualFeedItems = function() {
            return aManualFeedItems;
        }

        oModel.GetManualFeedItem = function() {
            return oManualFeedItem;
        }

        oModel.SetManualFeedItem = function(manualFeedItem) {
            oManualFeedItem = manualFeedItem;
        }

        function SetData(data) {
            if (data && data != null) {
                aFeeds = data.ContextFeed;
                aContentRankings = data.ContentRankings;
            }
            else {
                aFeeds = new Array();
                aContentRankings = new Array();
            }
        }

        oModel.RemoveFeedItem = function(iAssociationId, fnc) {
            function haveData(data) {
                SetData(data);
                fnc();
            }

            fncRemoveFeedItem(iAssociationId, iContextTypeId, iContextId, oFeedType.Id, haveData)
        }

        oModel.PopulateFeeds = function(fnc) {
            function haveData(data) {
                SetData(data);
                fnc();
            }

            oModel.PopulateLatestManualFeedItems();
            fncGetFeeds(iContextTypeId, iContextId, oFeedType.Id, haveData);
        }

        oModel.SaveFeedOrder = function(fnc) {
            function haveData(data) {
                fnc();
            }
            fncOrderFeeds(aFeeds, haveData);
        }

        oModel.SaveContentRankings = function(fnc) {
            function haveData(data) {
                fnc();
            }

            fncSaveContentRankings(aContentRankings, haveData);
        }

        oModel.RemoveContentRanking = function(iContentTypeId, fnc) {
            function haveData(data) {
                fnc();
            }
            
            var aNewContentRankings = new Array();
            var oContentRanking;
            for (var i = 0; i < aContentRankings.length; i++) {
                if (iContentTypeId == aContentRankings[i].ContentType.Id) {
                    oContentRanking = aContentRankings[i];
                }
                else {
                    aNewContentRankings.push(aContentRankings[i]);
                }
            }

            oModel.SetContentRankings(aNewContentRankings);
            fncRemoveContentRanking(oContentRanking, haveData);
        }

        oModel.PopulateLatestManualFeedItems = function(fnc) {
            function haveData(data) {
                if (data) {
                    aManualFeedItems = data;
                }
                else {
                    aManualFeedItems = new Array();
                }

                if (fnc) {
                    fnc();
                }
            }


            fncGetLatestManualFeedItems(iContextTypeId, iContextId, 10, haveData);
        }

        oModel.SaveManualFeedItem = function(fnc) {
            function haveData(data) {
                if (data == -1) {
                    alert("Invalid url in either Image Url or Url");
                }
                else {
                    if (fnc) {
                        fnc();
                    }
                }
            }

            fncInsertManualFeedItem(iContextTypeId, iContextId, oManualFeedItem, haveData);
        }

        oModel.RemoveManualFeedItem = function(id, fnc) {
            function haveData(data) {
                if (data) {
                    oModel.PopulateLatestManualFeedItems(fnc);
                }
                else {
                    alert('Error deleting manual feed item.');
                }
            }

            fncRemoveManualFeedItem(id, haveData);
        }
    }

    function Controller(oModel, oFeedRearranger, oFeedRemover, oFeedContentOrdering, oFeedManualAddItem) {
        var oController2 = this;

        oController2.ChangeContextType = function() {
            var iContextTypeId = parseInt(oElMan.Attribute('contextTypeSelector', 'options')[oElMan.Attribute('contextTypeSelector', 'selectedIndex')].value);
            oModel.SetContextTypeId(iContextTypeId);
            var aOptions = new Array();

            switch (iContextTypeId) {
                case 2:
                    var option = '<option value="0">Select TV Show</option>';
                    aOptions.push(option);
                    for (var i = 0; i < tvshows.length; i++) {
                        var option = $F('<option value="{0}">{1}</option>', tvshows[i].Id, tvshows[i].Title);
                        aOptions.push(option);
                    }
                    break;
                case 19:
                    var option = '<option value="0">Select Movie</option>';
                    aOptions.push(option);
                    for (var i = 0; i < movies.length; i++) {
                        var option = $F('<option value="{0}">{1}</option>', movies[i].Id, movies[i].Title);
                        aOptions.push(option);
                    }
                    break;
                case 21:
                    var option = '<option value="0">Select Cast Member</option>';
                    aOptions.push(option);
                    for (var i = 0; i < castMembers.length; i++) {
                        var option = $F('<option value="{0}">{1}</option>', castMembers[i].Id, castMembers[i].Title);
                        aOptions.push(option);
                    }
                    break;
                default:
                    var option = '<option value="0">Select Context Type First</option>';
                    aOptions.push(option);
                    break;
            }

            oElMan.InnerHTML('contextSelector', aOptions.join(''));
            oModel.DumpFeeds();
            oFeedRearranger.ClearFeeds();
        }

        oController2.ChangeContext = function() {
            var iContextId = parseInt(oElMan.Attribute('contextSelector', 'options')[oElMan.Attribute('contextSelector', 'selectedIndex')].value);
            oModel.SetContextId(iContextId);
            PopulateFeeds();
        }

        oController2.ChangeFeedType = function() {
            var iFeedTypeId = parseInt(oElMan.Attribute('feedTypeSelector', 'options')[oElMan.Attribute('feedTypeSelector', 'selectedIndex')].value);
            oModel.SetFeedType(iFeedTypeId);
            PopulateFeeds();
        }

        function UpdateCstData() {
            if (oFeedRearranger.IsRendered()) {
                oFeedRearranger.SetFeedList();
            }

            if (oFeedRemover.IsRendered()) {
                oFeedRemover.SetFeedList();
            }

            if (oFeedContentOrdering.IsRendered()) {
                oFeedContentOrdering.SetContentRankingList();
            }

            if (oFeedManualAddItem.IsRendered()) {
                oFeedManualAddItem.SetManualFeedItems();
            }
        }

        function PopulateFeeds() {
            oModel.PopulateFeeds(UpdateCstData);
        }

        function SaveFeedOrder(fnc) {
            oModel.SaveFeedOrder(fnc);
        }

        function RemoveFeedItem(iAssociationId) {
            oModel.RemoveFeedItem(iAssociationId, UpdateCstData);
        }

        function RemoveContentRanking(iContentTypeId) {
            function fnc() {
                oFeedContentOrdering.SetContentRankingList();
            }

            oModel.RemoveContentRanking(iContentTypeId, fnc);
        }

        function SaveContentRankings(fnc) {
            oModel.SaveContentRankings(fnc);
        }

        function SaveManualFeedItem(fnc) {
            oModel.SaveManualFeedItem(fnc);
        }

        function RemoveManualFeedItem(id, fnc) {
            oModel.RemoveManualFeedItem(id, fnc);
        }

        function PopulateLatestManualFeedItems(fnc) {
            oModel.PopulateLatestManualFeedItems(fnc);
        } 

        oFeedRearranger.onSaveFeedOrder.Attach(SaveFeedOrder);
        oFeedRemover.onRemoveFeedItem.Attach(RemoveFeedItem);
        oFeedContentOrdering.onRemoveContentRanking.Attach(RemoveContentRanking);
        oFeedContentOrdering.onSaveContentRankings.Attach(SaveContentRankings);
        oFeedManualAddItem.onSaveManualFeedItem.Attach(SaveManualFeedItem);
        oFeedManualAddItem.onRemoveManualFeedItem.Attach(RemoveManualFeedItem);
        oFeedManualAddItem.onPopulateManualFeedItems.Attach(PopulateLatestManualFeedItems);
    }

    function Render() {
        var oModel = new Model(d.tvshows, d.movies, d.castMembers, d.feedTypes, d.contentTypes, d.emptyManualFeedItem,
                                d.fncGetFeeds, d.fncOrderFeeds, d.fncRemoveFeedItem, d.fncSaveContentRankings, d.fncRemoveContentRanking,
                                d.fncInsertManualFeedItem, d.fncRemoveManualFeedItem, d.fncGetLatestManualFeedItems);
        oModel.SetFeedType(d.feedTypeId);

        var oFeedRearranger = Btv.Templating.GetInstance("Feed.Rearranger", { Model: oModel });
        var oFeedRemover = Btv.Templating.GetInstance("Feed.FeedRemover", { Model: oModel });
        var oFeedContentOrdering = Btv.Templating.GetInstance("Feed.ContentOrdering", { Model: oModel });
        var oFeedManualAddItem = Btv.Templating.GetInstance("Feed.FeedAddManualItems", { Model: oModel });

        oController = new Controller(oModel, oFeedRearranger, oFeedRemover, oFeedContentOrdering, oFeedManualAddItem);

        var oTabs = Btv.Templating.GetInstance('Container.Tabs', {
            tabs: [
                { label: 'Rearrange Feed', body: oFeedRearranger }
                , { label: 'Remove Feed Items', body: oFeedRemover }
                , { label: 'Content Ordering', body: oFeedContentOrdering }
                , { label: 'Manual Items', body: oFeedManualAddItem }
            ]
        });

        
        InitElements();

        return (htUI.Main(oThis, oTabs, {contextTypeSelectorOnChange: $F('{0}()', $OG(oController.ChangeContextType))
                                         , contextSelectorOnChange: $F('{0}()', $OG(oController.ChangeContext))
                                         , feedTypeSelectorOnChange: $F('{0}()', $OG(oController.ChangeFeedType))
    }));
    }

    function InitElements() {
        var aFeedTypeSelectorHtml = new Array();

        for (var i = 0; i < d.feedTypes.length; i++) {
            var sHtml = $F('<option value="{0}">{1}</option>', d.feedTypes[i].Id, d.feedTypes[i].Label);
        
            if (d.feedTypeId == d.feedTypes[i].Id) {
                sHtml = $F('<option value="{0}" selected="selected">{1}</option>', d.feedTypes[i].Id, d.feedTypes[i].Label);
            }
            
            
            aFeedTypeSelectorHtml.push(sHtml);
        }

        oElMan.InnerHTML('feedTypeSelector', aFeedTypeSelectorHtml.join(''));
    }
    
    oThis.DeclareVirtualMethods({
        Render: Render
    });
})($data, {Main:Main});
}return $text.join("");}},{id:"Feed.Rearranger",fnc:function($data){var $text = [];var _write = function(text) {$text.push((typeof text == "number")?text:(text||""));};with($data){ Main = function(o, ht) {var $text = [];var _write = function(text) {$text.push((typeof text == "number")?text:(text||""));};_write('\r\n \n<span>Drag and drop feed titles to rearrange the order of the feeds.</span>\n<div>\n<a ');_write(o.Elem('saveOrder'));_write('  onclick=\"');_write(ht.saveOrderOnClick);_write('\" style=\"');_write(o.Style());_write('\">');_write(o.InnerHTML());_write('Save Order</a>\n</div>\n<div ');_write(o.Elem('message'));_write('  class=\"cant-yet-text\" style=\"display:none;');_write(o.Style());_write('\">');_write(o.InnerHTML());_write('</div>\n<div class=\"content-container\" style=\"width: 500px;\">\n<ol ');_write(o.Elem('feedList'));_write('  class=\"rearrange-feed\" style=\"');_write(o.Style());_write('\">');_write(o.InnerHTML());_write('</ol>\n</div>\n');;return($text.join(""));};
new (function(d, ui) {
var oThis = Btv.Lang.Extend(this, Btv.Cst.BaseTemplate, [$data, true]);
var htUI = ui;
var $el = oThis.El;

    var oModel;
    var isRendered = false;
    var oElMan = oThis.ElMan();
    var Dom = YAHOO.util.Dom;
    var Event = YAHOO.util.Event;
    var DDM = YAHOO.util.DragDropMgr;
    oThis.onSaveFeedOrder = new Btv.Event();

    function LoadDragDrop() {
        Event.onAvailable(oThis.htIds['feedList'], DDApp.init);
    }

    oThis.IsRendered = function() {
        return isRendered;
    }

    oThis.ClearFeeds = function() {
        oElMan.Style('message', 'display', 'block');
        oElMan.InnerHTML('message', 'You must have feeds before you rearrange them.');
    }

    oThis.ChangeFeedOrder = function(elemId) {
        var iFeedIdMoved = $(elemId).getAttribute('feedid');
        var items = $(oThis.htIds['feedList']).getElementsByTagName("li");
        var newFeeds = new Array();
        var feeds = oModel.GetFeeds();
        var feedOrder = '';
        for (var i = 0; i < items.length; i++) {
            var feedListElemId = items[i];
            var iFeedId = $(feedListElemId).getAttribute('feedid');
            feedOrder += iFeedId + "\n";
            for (var j = 0; j < feeds.length; j++) {
                if (iFeedId == feeds[j].FeedId) {
                    if (iFeedId == iFeedIdMoved  && i != j) {
                        feeds[j].IsMoved = true;
                    }
                    feeds[j].Ordinal = i + 1;
                    newFeeds[i] = feeds[j];
                }
            }
        }

        oModel.SetFeeds(newFeeds);
    }

    oThis.SetFeedList = function() {
        var aHtml = new Array();
        var aFeeds = oModel.GetFeeds();

        for (var i = 0; i < aFeeds.length; i++) {
            if (aFeeds[i].Message.length != 0) {
                var listItem = "<li id='feed_" + (i + 1) + "' feedid='" + aFeeds[i].FeedId + "'>" + aFeeds[i].Message + "</li>"
                aHtml.push(listItem);
            }
        }
        
        oElMan.InnerHTML('feedList', aHtml.join(''));
        LoadDragDrop();
    }

    function SaveOrder() {
        function delay() {
            oElMan.InnerHTML('message', '');
            oElMan.Style('message', 'display', 'none');
        }
    
        function fnc() {
            oElMan.Style('message', 'display', 'block');
            oElMan.InnerHTML('message', 'Your feed order has been saved.');
            setTimeout($F("{0}()", $OG(delay)), 3000);
        }
        
        oThis.onSaveFeedOrder.Fire(fnc);
    }

    function InitElements() {
        oModel = d.Model;
        //Event.onAvailable(oThis.htIds['feedList'], DDApp.init);
    }

    function Render() {
        InitElements();
        isRendered = true;
        return (htUI.Main(oThis, { saveOrderOnClick: $F('{0}();', $OG(SaveOrder)) }));
    }
    
    oThis.DeclareVirtualMethods({
        Render: Render
    });


    var DDApp = {
        init: function() {
            new YAHOO.util.DDTarget(oThis.htIds['feedList']);
            var rows = oModel.GetFeeds().length;

            for (var i = 1; i < rows + 1; i++) {
                new DDList("feed_" + i);
            }
        }
    };

    //////////////////////////////////////////////////////////////////////////////
    // custom drag and drop implementation
    //////////////////////////////////////////////////////////////////////////////

    var DDList = function(id, sGroup, config) {

        DDList.superclass.constructor.call(this, id, sGroup, config);

        this.logger = this.logger || YAHOO;
        var el = this.getDragEl();
        Dom.setStyle(el, "opacity", 0.67); // The proxy is slightly transparent

        this.goingUp = false;
        this.lastY = 0;
    };

    YAHOO.extend(DDList, YAHOO.util.DDProxy, {

        startDrag: function(x, y) {
            this.logger.log(this.id + " startDrag");

            // make the proxy look like the source element
            var dragEl = this.getDragEl();
            var clickEl = this.getEl();
            Dom.setStyle(clickEl, "visibility", "hidden");

            dragEl.innerHTML = clickEl.innerHTML;

            Dom.setStyle(dragEl, "color", Dom.getStyle(clickEl, "color"));
            Dom.setStyle(dragEl, "backgroundColor", Dom.getStyle(clickEl, "backgroundColor"));
            Dom.setStyle(dragEl, "border", "2px solid gray");
        },

        endDrag: function(e) {

            var srcEl = this.getEl();
            var proxy = this.getDragEl();

            // Show the proxy element and animate it to the src element's location
            Dom.setStyle(proxy, "visibility", "");
            var a = new YAHOO.util.Motion(
                proxy, {
                    points: {
                        to: Dom.getXY(srcEl)
                    }
                },
                0.2,
                YAHOO.util.Easing.easeOut
            )
            var proxyid = proxy.id;
            var thisid = this.id;

            // Hide the proxy and show the source element when finished with the animation
            a.onComplete.subscribe(function() {
                Dom.setStyle(proxyid, "visibility", "hidden");
                Dom.setStyle(thisid, "visibility", "");
            });
            a.animate();
        },

        onDragDrop: function(e, id) {

            // If there is one drop interaction, the li was dropped either on the list,
            // or it was dropped on the current location of the source element.
            if (DDM.interactionInfo.drop.length === 1) {

                // The position of the cursor at the time of the drop (YAHOO.util.Point)
                var pt = DDM.interactionInfo.point;

                // The region occupied by the source element at the time of the drop
                var region = DDM.interactionInfo.sourceRegion;

                // Check to see if we are over the source element's location.  We will
                // append to the bottom of the list once we are sure it was a drop in
                // the negative space (the area of the list without any list items)
                if (!region.intersect(pt)) {
                    var destEl = Dom.get(id);
                    var destDD = DDM.getDDById(id);
                    destEl.appendChild(this.getEl());
                    destDD.isEmpty = false;
                    DDM.refreshCache();
                }
                
                // update feed array order
                oThis.ChangeFeedOrder(this.id);
            }
        },

        onDrag: function(e) {

            // Keep track of the direction of the drag for use during onDragOver
            var y = Event.getPageY(e);

            if (y < this.lastY) {
                this.goingUp = true;
            } else if (y > this.lastY) {
                this.goingUp = false;
            }

            this.lastY = y;
        },

        onDragOver: function(e, id) {

            var srcEl = this.getEl();
            var destEl = Dom.get(id);

            // We are only concerned with list items, we ignore the dragover
            // notifications for the list.
            if (destEl.nodeName.toLowerCase() == "li") {
                var orig_p = srcEl.parentNode;
                var p = destEl.parentNode;

                if (this.goingUp) {
                    p.insertBefore(srcEl, destEl); // insert above
                } else {
                    p.insertBefore(srcEl, destEl.nextSibling); // insert below
                }

                DDM.refreshCache();
            }
        }
    });

})($data, {Main:Main});
}return $text.join("");}},{id:"Feed.FeedRemover",fnc:function($data){var $text = [];var _write = function(text) {$text.push((typeof text == "number")?text:(text||""));};with($data){ Main = function(o, ht) {var $text = [];var _write = function(text) {$text.push((typeof text == "number")?text:(text||""));};_write('\r\n \n<div ');_write(o.Elem('feedContainer'));_write('  class=\"content-container feed-container remove-feed-admin\" style=\"');_write(o.Style());_write('\">');_write(o.InnerHTML());_write('</div>\n');;return($text.join(""));};
new (function(d, ui) {
var oThis = Btv.Lang.Extend(this, Btv.Cst.BaseTemplate, [$data, true]);
var htUI = ui;
var $el = oThis.El;

    var oModel;
    var isRendered = false;
    var oElMan = oThis.ElMan();
    oThis.onRemoveFeedItem = new Btv.Event();

    function RemoveFeedItem(iAssociationId) {
        oThis.onRemoveFeedItem.Fire(iAssociationId);
    }

    oThis.UpdateTab = function() {
        oThis.SetFeedList();
    }

    oThis.SetFeedList = function() {
        var aHtml = new Array();
        var aFeeds = oModel.GetFeeds();

        if (aFeeds) {
            for (var i = 0; i < aFeeds.length; i++) {
                if (aFeeds[i].Message.length != 0) {
                    var sItem = $F("<div class=\"remove-feed-link\"><a class=\"remove-feed-admin-link\" onclick=\"{0}({1})\">Remove</a>{2}<div style=\"clear:both;\"></div></div>", $OG(RemoveFeedItem), aFeeds[i].AssociationId, aFeeds[i].Message);
                    aHtml.push(sItem);
                }
            }
        }

        oElMan.InnerHTML('feedContainer', aHtml.join(''));
    }

    oThis.IsRendered = function() {
        return isRendered;
    }
    
    function InitElements() {
        oModel = d.Model;
    }

    function Render() {
        InitElements();
        isRendered = true;
        return (htUI.Main(oThis));
    }
    
    oThis.DeclareVirtualMethods({
        Render: Render
    });
})($data, {Main:Main});
}return $text.join("");}},{id:"Feed.FeedAddManualItems",fnc:function($data){var $text = [];var _write = function(text) {$text.push((typeof text == "number")?text:(text||""));};with($data){ Main = function(o, ht) {var $text = [];var _write = function(text) {$text.push((typeof text == "number")?text:(text||""));};_write('\r\n \n<div>\n<div class=\"feed-admin-feild-table\">\n<div ');_write(o.Elem('message'));_write('  style=\"');_write(o.Style());_write('\">');_write(o.InnerHTML());_write('</div>\n<div>\n<span>Title</span>\n<span><input ');_write(o.Elem('itemTitle'));_write('  type=\"text\" maxlength=\"256\" style=\"');_write(o.Style());_write('\">');_write(o.InnerHTML());_write('</input></span>\n</div>\n<div>\n<span>Description</span>\n<span><input ');_write(o.Elem('itemBlurb'));_write('  type=\"text\" maxlength=\"1000\" style=\"');_write(o.Style());_write('\">');_write(o.InnerHTML());_write('</input></span>\n</div>\n<div>\n<span>Image Url</span>\n<span><input ');_write(o.Elem('itemImageUrl'));_write('  type=\"text\" maxlength=\"500\" style=\"');_write(o.Style());_write('\">');_write(o.InnerHTML());_write('</input></span>\n</div>\n<div>\n<span>Url</span>\n<span><input ');_write(o.Elem('itemUrl'));_write('  type=\"text\" maxlength=\"500\" style=\"');_write(o.Style());_write('\">');_write(o.InnerHTML());_write('</input></span>\n</div>\n<div><a ');_write(o.Elem('saveItem'));_write('  onclick=\"');_write(ht.saveItemOnclick);_write('\" class=\"context-button context-button-right context-submit-button\" style=\"');_write(o.Style());_write('\">');_write(o.InnerHTML());_write('<span>Save</span></a></div>\n</div>\n<div class=\"feed-admin-feild-display\">\n<h3>Latest Manual Feed Items</h3>\n<div ');_write(o.Elem('latestItems'));_write('  style=\"');_write(o.Style());_write('\">');_write(o.InnerHTML());_write('\n</div>\n</div>\n</div>\n');;return($text.join(""));};Item = function(o, ht) {var $text = [];var _write = function(text) {$text.push((typeof text == "number")?text:(text||""));};_write('\r\n\n<div class=\"feed-admin-feild-item\">\n<span class=\"feed-admin-feild-title\">');_write(ht.title);_write('</span>\n<span><a onclick=\"');_write(ht.removeOnclick);_write('\">Remove</a></span>\n</div>\n');;return($text.join(""));};
new (function(d, ui) {
var oThis = Btv.Lang.Extend(this, Btv.Cst.BaseTemplate, [$data, true]);
var htUI = ui;
var $el = oThis.El;

    var oModel;
    var blnIsRendered = false;
    var oElMan = oThis.ElMan();
    oThis.onSaveManualFeedItem = new Btv.Event();
    oThis.onRemoveManualFeedItem = new Btv.Event();
    oThis.onPopulateManualFeedItems = new Btv.Event();

    oThis.UpdateTab = function() {
        PopulateLatestList();
    }

    oThis.SetManualFeedItems = function() {
        PopulateLatestList();
    }

    oThis.IsRendered = function() {
        return blnIsRendered;
    }

    function PopulateLatestList() {
        aManualFeedItems = oModel.GetManualFeedItems();
        var aHtml = new Array();

        if (aManualFeedItems) {
            for (var i = 0; i < aManualFeedItems.length; i++) {
                var html = htUI.Item(oThis, {
                title: aManualFeedItems[i].Title
                    , removeOnclick: $F('{0}({1});', $OG(RemoveManualFeedItem), aManualFeedItems[i].Id)
                });

                aHtml.push(html);
            }
        }

        oElMan.InnerHTML('latestItems', aHtml.join(''));
    }

    function RemoveManualFeedItem(id) {
        oThis.onRemoveManualFeedItem.Fire(id, PopulateLatestList);
    }

    function SaveManualFeedItem() {
        function delay() {
            oElMan.InnerHTML('message', '');
            oElMan.Style('message', 'display', 'none');
        }

        function fnc() {
            oElMan.Style('message', 'display', 'block');
            oElMan.InnerHTML('message', 'Your manual feed item has been saved.');
            ClearData();
            oThis.onPopulateManualFeedItems.Fire(PopulateLatestList);
            setTimeout($F("{0}()", $OG(delay)), 3000);
        }
    
        var oManualFeedItem = oModel.GetManualFeedItem();
        var sErrMsg = '';
        
        if(!oModel.GetContextTypeId() || oModel.GetContextTypeId() < 1){
            sErrMsg += "Need to select a context type.\n";
        }
        
        if(!oModel.GetContextId() || oModel.GetContextId() < 1) {
            sErrMsg += "Need to select a context.\n";   
        }        

        if (oElMan.Attribute('itemTitle', 'value').length == 0) {
            sErrMsg += "Need to add a title.\n";
        }
        else {
            oManualFeedItem.Title = oElMan.Attribute('itemTitle', 'value');
        }

        if (oElMan.Attribute('itemBlurb', 'value').length == 0) {
            sErrMsg += "Need to add a description.\n";
        }
        else {
            oManualFeedItem.Blurb = oElMan.Attribute('itemBlurb', 'value');
        }

        if (oElMan.Attribute('itemImageUrl', 'value').length == 0) {
            sErrMsg += "Need to add an image url.\n";
        }
        else {
            oManualFeedItem.ImageUrl = oElMan.Attribute('itemImageUrl', 'value');
        }

        if (oElMan.Attribute('itemUrl', 'value').length == 0) {
            sErrMsg += "Need to add a url.\n";
        }
        else {
            oManualFeedItem.Url = oElMan.Attribute('itemUrl', 'value');
        }

        if (sErrMsg.length == 0) {
            oThis.onSaveManualFeedItem.Fire(fnc);
        }
        else {
            alert(sErrMsg);
        }
    }

    function ClearData() {
        oElMan.Attribute('itemTitle', 'value', '');
        oElMan.Attribute('itemBlurb', 'value', '');
        oElMan.Attribute('itemImageUrl', 'value', '');
        oElMan.Attribute('itemUrl', 'value', '');
    }

    function InitElements() {
        oModel = d.Model;
    }

    function Render() {
        InitElements();
        blnIsRendered = true;
        return (htUI.Main(oThis, {saveItemOnclick: $F('{0}();', $OG(SaveManualFeedItem))}));
    }
    
    oThis.DeclareVirtualMethods({
        Render: Render
    });
})($data, {Main:Main,Item:Item});
}return $text.join("");}},{id:"Feed.ContentOrdering",fnc:function($data){var $text = [];var _write = function(text) {$text.push((typeof text == "number")?text:(text||""));};with($data){ Main = function(o, ht) {var $text = [];var _write = function(text) {$text.push((typeof text == "number")?text:(text||""));};_write('\r\n \nFuture Feature\n');;return($text.join(""));};ContentRanking = function(o, ht) {var $text = [];var _write = function(text) {$text.push((typeof text == "number")?text:(text||""));};_write('\r\n\n<span>Min Display:</span>\n<span><input id=\"minDisplay-');_write(ht.contentTypeId);_write('\" type=\"text\" value=\"');_write(ht.minDisplayValue);_write('\" maxlength=\"2\" size=\"2\"/></span>\n<span>Max Display:</span>\n<span><input id=\"maxDisplay-');_write(ht.contentTypeId);_write('\" type=\"text\" value=\"');_write(ht.maxDisplayValue);_write('\" maxlength=\"2\" size=\"2\"/></span>\n<span>Max Grouping:</span>\n<span><input id=\"maxGrouping-');_write(ht.contentTypeId);_write('\" type=\"text\" value=\"');_write(ht.maxGroupingValue);_write('\" maxlength=\"2\" size=\"2\"/></span>\n<span><a onclick=\"');_write(ht.removeOnclick);_write('\">Remove</a></span>\n');;return($text.join(""));};
new (function(d, ui) {
var oThis = Btv.Lang.Extend(this, Btv.Cst.BaseTemplate, [$data, true]);
var htUI = ui;
var $el = oThis.El;

    var oModel;
    var isRendered = false;
    var Dom = YAHOO.util.Dom;
    var Event = YAHOO.util.Event;
    var DDM = YAHOO.util.DragDropMgr;
    var oElMan = oThis.ElMan();
    oThis.onRemoveContentRanking = new Btv.Event();
    oThis.onSaveContentRankings = new Btv.Event();

    oThis.UpdateTab = function() {
        oThis.SetContentRankingList();
    }

    oThis.SetContentRankingList = function() {
        var aHtml = new Array();
        var aContentRankings = oModel.GetContentRankings();

        if (aContentRankings) {
            for (var i = 0; i < aContentRankings.length; i++) {
                var html = htUI.ContentRanking(oThis, {
                    contentTypeId: aContentRankings[i].ContentType.Id
                    , minDisplayValue: aContentRankings[i].MinDisplay
                    , maxDisplayValue: aContentRankings[i].MaxDisplay
                    , maxGroupingValue: aContentRankings[i].MaxGrouping
                    , removeOnclick: $F('{0}({1})', $OG(RemoveContentType), aContentRankings[i].ContentType.Id)
                });

                var listItem = $F('<li id="contentRanking_{0}" contenttype="{1}">{2}{3}</li>', (i + 1), aContentRankings[i].ContentType.Id, aContentRankings[i].ContentType.Name, html);
                aHtml.push(listItem);
            }
        }

        oElMan.InnerHTML('contentRankingList', aHtml.join(''));
        LoadDragDrop();
    }

    oThis.ChangeContentRankingOrder = function(elemId) {
        var items = $(oThis.htIds['contentRankingList']).getElementsByTagName("li");
        var aNewContentRankings = new Array();
        var aContentRankings = oModel.GetContentRankings();

        for (var i = 0; i < items.length; i++) {
            var contentRankingListElemId = items[i];
            var iContentTypeId = $(contentRankingListElemId).getAttribute('contenttype');

            for (var j = 0; j < aContentRankings.length; j++) {
                if (iContentTypeId == aContentRankings[j].ContentType.Id) {
                    aContentRankings[j].Ordinal = i + 1;
                    aContentRankings[j].MinDisplay = $('minDisplay-' + iContentTypeId).value;
                    aContentRankings[j].MaxDisplay = $('maxDisplay-' + iContentTypeId).value;
                    aContentRankings[j].MaxGrouping = $('maxGrouping-' + iContentTypeId).value;
                    aNewContentRankings[i] = aContentRankings[j];
                }
            }
        }

        oModel.SetContentRankings(aNewContentRankings);
    }

    oThis.IsRendered = function() {
        return isRendered;
    }

    function LoadDragDrop() {
        Event.onAvailable(oThis.htIds['contentRankingList'], DDApp.init);
    }

    function RemoveContentType(iContentTypeId) {
        oThis.onRemoveContentRanking.Fire(iContentTypeId);
    }

    function SaveOrder() {
        function delay() {
            oElMan.InnerHTML('message', '');
            oElMan.Style('message', 'display', 'none');
        }

        function fnc() {
            oElMan.Style('message', 'display', 'block');
            oElMan.InnerHTML('message', 'Your content rankings have been saved.');
            setTimeout($F("{0}()", $OG(delay)), 3000);
        }
    
        var aContentRankings = oModel.GetContentRankings();
        for (var i = 0; i < aContentRankings.length; i++) {
            var iContentTypeId = aContentRankings[i].ContentType.Id;
            aContentRankings[i].MinDisplay = $('minDisplay-' + iContentTypeId).value;
            aContentRankings[i].MaxDisplay = $('maxDisplay-' + iContentTypeId).value;
            aContentRankings[i].MaxGrouping = $('maxGrouping-' + iContentTypeId).value;
        }

        oModel.SetContentRankings(aContentRankings);
        oThis.onSaveContentRankings.Fire(fnc);
    }
    
    function InitElements() {
        oModel = d.Model;
    }

    function Render() {
        InitElements();
        isRendered = true;
        return (htUI.Main(oThis, { saveOrderOnClick: $F('{0}();', $OG(SaveOrder)) }));
    }
    
    oThis.DeclareVirtualMethods({
        Render: Render
    });

    var DDApp = {
        init: function() {
            new YAHOO.util.DDTarget(oThis.htIds['contentRankingList']);
            var rows = oModel.GetContentRankings().length;

            for (var i = 1; i < rows + 1; i++) {
                new DDList("contentRanking_" + i);
            }
        }
    };

    //////////////////////////////////////////////////////////////////////////////
    // custom drag and drop implementation
    //////////////////////////////////////////////////////////////////////////////

    var DDList = function(id, sGroup, config) {

        DDList.superclass.constructor.call(this, id, sGroup, config);

        this.logger = this.logger || YAHOO;
        var el = this.getDragEl();
        Dom.setStyle(el, "opacity", 0.67); // The proxy is slightly transparent

        this.goingUp = false;
        this.lastY = 0;
    };

    YAHOO.extend(DDList, YAHOO.util.DDProxy, {

        startDrag: function(x, y) {
            this.logger.log(this.id + " startDrag");

            // make the proxy look like the source element
            var dragEl = this.getDragEl();
            var clickEl = this.getEl();
            Dom.setStyle(clickEl, "visibility", "hidden");

            dragEl.innerHTML = clickEl.innerHTML;

            Dom.setStyle(dragEl, "color", Dom.getStyle(clickEl, "color"));
            Dom.setStyle(dragEl, "backgroundColor", Dom.getStyle(clickEl, "backgroundColor"));
            Dom.setStyle(dragEl, "border", "2px solid gray");
        },

        endDrag: function(e) {

            var srcEl = this.getEl();
            var proxy = this.getDragEl();

            // Show the proxy element and animate it to the src element's location
            Dom.setStyle(proxy, "visibility", "");
            var a = new YAHOO.util.Motion(
                proxy, {
                    points: {
                        to: Dom.getXY(srcEl)
                    }
                },
                0.2,
                YAHOO.util.Easing.easeOut
            )
            var proxyid = proxy.id;
            var thisid = this.id;

            // Hide the proxy and show the source element when finished with the animation
            a.onComplete.subscribe(function() {
                Dom.setStyle(proxyid, "visibility", "hidden");
                Dom.setStyle(thisid, "visibility", "");
            });
            a.animate();
        },

        onDragDrop: function(e, id) {

            // If there is one drop interaction, the li was dropped either on the list,
            // or it was dropped on the current location of the source element.
            if (DDM.interactionInfo.drop.length === 1) {

                // The position of the cursor at the time of the drop (YAHOO.util.Point)
                var pt = DDM.interactionInfo.point;

                // The region occupied by the source element at the time of the drop
                var region = DDM.interactionInfo.sourceRegion;

                // Check to see if we are over the source element's location.  We will
                // append to the bottom of the list once we are sure it was a drop in
                // the negative space (the area of the list without any list items)
                if (!region.intersect(pt)) {
                    var destEl = Dom.get(id);
                    var destDD = DDM.getDDById(id);
                    destEl.appendChild(this.getEl());
                    destDD.isEmpty = false;
                    DDM.refreshCache();
                }

                // update content ranking array order
                oThis.ChangeContentRankingOrder(this.id);
            }
        },

        onDrag: function(e) {

            // Keep track of the direction of the drag for use during onDragOver
            var y = Event.getPageY(e);

            if (y < this.lastY) {
                this.goingUp = true;
            } else if (y > this.lastY) {
                this.goingUp = false;
            }

            this.lastY = y;
        },

        onDragOver: function(e, id) {

            var srcEl = this.getEl();
            var destEl = Dom.get(id);

            // We are only concerned with list items, we ignore the dragover
            // notifications for the list.
            if (destEl.nodeName.toLowerCase() == "li") {
                var orig_p = srcEl.parentNode;
                var p = destEl.parentNode;

                if (this.goingUp) {
                    p.insertBefore(srcEl, destEl); // insert above
                } else {
                    p.insertBefore(srcEl, destEl.nextSibling); // insert below
                }

                DDM.refreshCache();
            }
        }
    });
})($data, {Main:Main,ContentRanking:ContentRanking});
}return $text.join("");}},{id:"Container.BtvModule",fnc:function($data){var $text = [];var _write = function(text) {$text.push((typeof text == "number")?text:(text||""));};with($data){ _write('\n');Main = function(o) {var $text = [];var _write = function(text) {$text.push((typeof text == "number")?text:(text||""));};_write('\n<div ');_write(o.Elem('Root'));_write(' class=\"');_write((o.d.classes && o.d.classes.Module) ? o.d.classes.Module : 'btv_module');_write('\" style=\"');_write(o.Style());_write('\">\n<div class=\"btv_module_head\"><div class=\"c\"></div></div>\n<div class=\"btv_module_body\" ');_write(o.d.bodyStyle ? 'style="' + o.d.bodyStyle + '"' : '');_write('>\n<div class=\"c\">');if(o.d.header) {_write('<h2>');_write(o.d.header);_write('</h2>');}_write(o.d.body.Render());_write('</div>\n</div>\n<div class=\"btv_module_foot\"><div class=\"c\"></div></div>\n</div>\n');;return($text.join(""));};_write('\n');Version3 = function(o) {var $text = [];var _write = function(text) {$text.push((typeof text == "number")?text:(text||""));};_write('\n<div ');_write(o.Elem('Root'));_write(' class=\"content-container\">');_write(o.d.body.Render());_write('</div>\n');;return($text.join(""));};_write('\n');
new (function(d, fncMain, fncVersion3)
{
var s, oThis = Btv.Lang.Extend(this, Btv.Cst.BaseTemplate, arguments);
oThis.d = d;
var blnDisplay = true;
function Render()
{
var fnc = (Btv.iPageVersion == 3) ? fncVersion3 : fncMain;
if (!s) s = fnc(oThis);
return(s);
}
oThis.ElementProps = function(id, scope, name, isInit, params, ht)
{
switch(scope)
{
case "Root":
ht.style.display = blnDisplay ? 'block' : 'none';
break;
}
}
oThis.Display = function(bln)
{
blnDisplay = bln;
oThis.ElMan().Style('Root'
, 'display', (blnDisplay ? 'block' : 'none')
);
}
oThis.DeclareVirtualMethods({
Render: Render
});
})($data, Main, Version3);
_write('\n');}return $text.join("");}},{id:"Container.Tabs",fnc:function($data){var $text = [];var _write = function(text) {$text.push((typeof text == "number")?text:(text||""));};with($data){ _write('\n');Body = function(o) {var $text = [];var _write = function(text) {$text.push((typeof text == "number")?text:(text||""));};_write('\n'); for (var i=0; i < o.d.tabs.length; i++) { _write('\n<div ');_write(o.Elem('divTab.' + i, i));_write(' style=\"');_write(o.Style());_write('\">');_write(o.InnerHTML());_write('</div>\n'); } _write('\n');;return($text.join(""));};_write('\n');Main = function(o) {var $text = [];var _write = function(text) {$text.push((typeof text == "number")?text:(text||""));};_write('\n<div class=\"');_write(o.d.outerClass || 'btv_module_tabs');_write('\">\n'); for (var i=0; i < o.d.tabs.length; i++) { _write('\n<a ');_write(o.Elem('lnkTab.' + i, i));_write(' style=\"');_write(o.Style());_write('; \"><span ');_write(o.Elem('labelTab.' + i, i));_write('>');_write(o.InnerHTML());_write('</span></a>\n'); } _write('\n<div class=\"clearfix\"></div>\n</div>\n');_write(o.InitModule());_write('\n');;return($text.join(""));};_write('\n');
new (function(d, fncMain, fncBody)
{
var s, data, oThis = Btv.Lang.Extend(this, Btv.Cst.BaseTemplate, arguments);
oThis.d = d;
var iCurrentTab = d.currentTab || 0;
var ablnTabsRendered = [];
var oElMan = oThis.ElMan();
var ablnTabsVisible = [];
for (var i=0; i < d.tabs.length; i++) ablnTabsVisible[i] = true;
oThis.InitModule = function()
{
function F()
{
return(fncBody(oThis));
}
var oModule = Btv.Templating.GetInstance("Container.BtvModule", {bodyStyle: d.bodyStyle, body:{Render:F}});
return(oModule.Render());
}
oThis.SetTabVisibility = function(i, bln)
{
ablnTabsVisible[i] = bln;
if (!bln && (iCurrentTab == i))
{
for (var j=0; j < ablnTabsVisible.length; j++)
{
if (ablnTabsVisible[j])
{
oThis.ChangeTab(j);
}
}
}
oElMan.Style('divTab.' + i, 'display', bln ? 'block' : 'none');
oElMan.Style('lnkTab.' + i, 'display', bln ? 'inline' : 'none');
}
oThis.ChangeTab = function(i)
{
if (i != iCurrentTab)
{
Btv.Ads.Change();
iCurrentTab = i;
oThis.UpdateElements();
}
}
function Render()
{
if (!s) s = fncMain(oThis);
return(s);
}
oThis.ElementProps = function(id, scope, name, isInit, params, ht)
{
switch(scope)
{
case "lnkTab":
var i = params;
ht.attr['class'] = (iCurrentTab == i) ? 'strong' : '';
if (isInit)
{
ht.attr.onclick = $F('{0}({1})', $R(oThis.ChangeTab), i);
}
break;
case "labelTab":
ht.innerHTML = d.tabs[params].label;
break;
case "divTab":
var i = params;
if ((iCurrentTab == i) && !ablnTabsRendered[i])
{
ablnTabsRendered[i] = true;
ht.innerHTML = d.tabs[i].body.Render();
}
if((iCurrentTab == i) && d.tabs[i].body.UpdateTab){
d.tabs[i].body.UpdateTab();
}
ht.style.display = (iCurrentTab == i) ? 'block' : 'none';
break;
}
}
oThis.DeclareVirtualMethods({
Render: Render
});
})($data, Main, Body);
_write('\n');}return $text.join("");}},{id:"Feed.RateItem",fnc:function($data){var $text = [];var _write = function(text) {$text.push((typeof text == "number")?text:(text||""));};with($data){ Main = function(o, ht) {var $text = [];var _write = function(text) {$text.push((typeof text == "number")?text:(text||""));};_write('\r\n\n<a ');_write(o.Elem('rateUp'));_write('  onclick=\"');_write(ht.rateUpOnclick);_write('\" class=\"rate-up\" style=\"');_write(o.Style());_write('\">');_write(o.InnerHTML());_write('</a><a ');_write(o.Elem('rateDown'));_write('  onclick=\"');_write(ht.rateDownOnclick);_write('\" class=\"rate-down\" style=\"');_write(o.Style());_write('\">');_write(o.InnerHTML());_write('</a>\n');;return($text.join(""));};
new (function(d, ui) {
var oThis = Btv.Lang.Extend(this, Btv.Cst.BaseTemplate, [$data, true]);
var htUI = ui;
var $el = oThis.El;

    var oElMan = oThis.ElMan();
    var fncGetRatings = Btv.Ajax.MakeFunction(Btv.Feed.DataQueries, 'GetRatingsByAssociation');
    var fncSubmitRating = Btv.Ajax.MakeFunction(Btv.Feed.DataQueries, 'SubmitRatingsForAssociationId');
    
    function Populate(data) {
        oElMan.InnerHTML("rateUp", $F("Rate up ({0})", data.RatesUp));
        oElMan.InnerHTML("rateDown", $F("Rate down ({0})", data.RatesDown));
    }

    function PopulateRatings() {
        function haveData(data) {
            Populate(data);
        }

        fncGetRatings(d.associationId, haveData);
    }

    function RateUp() {
        function haveData(data) {
            Populate(data);
        }

        if (!Btv.User.IsLoggedIn()) {
            Btv.User.InitLogin(RateUp);
        }
        else {
            fncSubmitRating(d.associationId, 1, haveData);
        }
    }

    function RateDown() {
        function haveData(data) {
            Populate(data);
        }

        if (!Btv.User.IsLoggedIn()) {
            Btv.User.InitLogin(RateDown);
        }
        else {
            fncSubmitRating(d.associationId, -1, haveData);
        }
    }

    function InitElements() {
        if (d.ratingData) {
            Populate(d.ratingData);
        }
        else {
            PopulateRatings();
        }
    }

    function Render() {
        function displayHtml() {
            $('rating-' + d.associationId).innerHTML = html;
        }
    
        InitElements();

        var html = htUI.Main(oThis, { rateUpOnclick: $F("{0}()", $OG(RateUp))
                                    ,rateDownOnclick: $F("{0}()", $OG(RateDown))} );

        if ($('rating-' + d.associationId)) {
            displayHtml();
        }
        else {
            $E.onAvailable('rating-' + d.associationId, displayHtml);
        }
    }

    oThis.DeclareVirtualMethods({
        Render: Render
    });
        
})($data, {Main:Main});
}return $text.join("");}},{id:"Common.InlineComments",fnc:function($data){var $text = [];var _write = function(text) {$text.push((typeof text == "number")?text:(text||""));};with($data){ Main = function(o, ht) {var $text = [];var _write = function(text) {$text.push((typeof text == "number")?text:(text||""));};_write('\r\n\n<div ');_write(o.Elem('Root'));_write('  class=\"comment-feed-string\" style=\"padding-top:5px;');_write(o.Style());_write('\">');_write(o.InnerHTML());_write('\n<div class=\"comment-feed-string-top\"><div class=\"cc\"></div></div>\n<div class=\"comment-feed-string-body\">\n<div class=\"cc\">\n<div ');_write(o.Elem('comments'));_write('  style=\"');_write(o.Style());_write('\">');_write(o.InnerHTML());_write('</div>\n');_write(ht.makeComment);_write('\n</div>\n</div>\n<div class=\"comment-feed-string-bottom\"><div class=\"cc\"></div></div>\n</div>\n');;return($text.join(""));};Comment = function(o, ht) {var $text = [];var _write = function(text) {$text.push((typeof text == "number")?text:(text||""));};_write('\r\n\n<div class=\"feed-comment\">\n<a href=\"/tvjhome.aspx?tvjid=');_write(ht.userId);_write('\" class=\"feed-comment-img\"><img src=\"');_write(ht.avatar);_write('\" /></a>\n<div class=\"feed-comment-text\">\n<a href=\"/tvjhome.aspx?tvjid=');_write(ht.userId);_write('\">');_write(ht.username);_write('</a> said “');_write(ht.comment);_write('” <span>');_write(ht.postDate.format("m/dd/yy h:MM TT"));_write('</span>\n</div>\n<div style=\"clear:both;\"></div>\n</div>\n');;return($text.join(""));};ViewCommentsLink = function(o, ht) {var $text = [];var _write = function(text) {$text.push((typeof text == "number")?text:(text||""));};_write('\r\n\n<div ');_write(o.Elem('viewCommentsLink'));_write('  class=\"feed-comment-view-all\" style=\"');_write(o.Style());_write('\">');_write(o.InnerHTML());_write('\n<a onclick=\"');_write(ht.onclick);_write('\">View all ');_write(ht.commentCount);_write(' comments</a>\n</div>\n');;return($text.join(""));};ViewCommentsLinkToPage = function(o, ht) {var $text = [];var _write = function(text) {$text.push((typeof text == "number")?text:(text||""));};_write('\r\n\n<div ');_write(o.Elem('viewCommentsLinkToPage'));_write('  class=\"feed-comment-view-all\" style=\"');_write(o.Style());_write('\">');_write(o.InnerHTML());_write('\n<a href=\"');_write(ht.href);_write('\">View all ');_write(ht.commentCount);_write(' comments &raquo;</a>\n</div>\n');;return($text.join(""));};MakeComment = function(o, ht) {var $text = [];var _write = function(text) {$text.push((typeof text == "number")?text:(text||""));};_write('\r\n\n<div class=\"leave-comment-post\">\n<div class=\"feed-comment-input\"><div><input ');_write(o.Elem('commentText'));_write('  onclick=\"');_write(ht.inputOnclick);_write('\" type=\"text\" maxlength=\"1000\" style=\"');_write(o.Style());_write('\">');_write(o.InnerHTML());_write('</input></div></div>\n<a ');_write(o.Elem('submitComment'));_write('  onclick=\"');_write(ht.submitOnclick);_write('\" class=\"context-button context-button-right\" style=\"display:none;');_write(o.Style());_write('\">');_write(o.InnerHTML());_write('<span>Submit</span></a>\n<div style=\"clear:both;\"></div>\n</div>\n');;return($text.join(""));};
new (function(d, ui) {
var oThis = Btv.Lang.Extend(this, Btv.Cst.BaseTemplate, [$data, true]);
var htUI = ui;
var $el = oThis.El;

    var oElMan = oThis.ElMan();
    var aComments, sCommentLink, iCommentCount;
    var fncGetComments = Btv.Ajax.MakeFunction(Btv.CommonCstQueries, 'GetCommentsByAssociation');
    var fncSubmitComment = Btv.Ajax.MakeFunction(Btv.CommonCstQueries, 'SubmitCommentByAssociationId')

    function Populate() {
        if ($('comments-' + d.associationId)) {
            $('comments-' + d.associationId).innerHTML = (iCommentCount == 1) ? $F("Comment ({0})", iCommentCount) : $F("Comments ({0})", iCommentCount);
        }

        if (iCommentCount == 0) {
            oElMan.Style("Root", "display", "none");
        }
        else if (iCommentCount > 0 && iCommentCount <= 3) {
            // show first 3 comments only
            var aCommentsHtml = BuildCommentList(0, aComments.length);
            oElMan.InnerHTML("comments", aCommentsHtml.join(''));
        }
        else if (15 < iCommentCount) {
            // show first 2 comments then a link to view all;

            var aCommentsHtml = BuildCommentList(aComments.length - 2, aComments.length);
            var html = htUI.ViewCommentsLinkToPage(oThis, {
                    commentCount: iCommentCount
                   , href: sCommentLink
            });

            html += aCommentsHtml.join('');
            oElMan.InnerHTML("comments", html);
        }
        else {
            // show first 2 comments then link to display 3 - 15
            var html = htUI.ViewCommentsLink(oThis, {
                    commentCount: iCommentCount
                   , onclick: $F("{0}()", $OG(DisplayAllComments))
            });

            var aCommentsHtml = BuildCommentList(aComments.length - 2, aComments.length);
            html += aCommentsHtml.join('');
            oElMan.InnerHTML("comments", html);
        }
    }

    function PopulateComments() {
        function haveData(data) {
            iCommentCount = data.CommentCount;
            aComments = data.Comments;
            Populate();            
        }

        fncGetComments(d.associationId, d.firstComment, d.numComments, haveData);
    }

    function DisplayAllComments() {
        var aCommentsHtml = BuildCommentList(0, aComments.length);
        oElMan.InnerHTML("comments", aCommentsHtml.join(''));
    }

    function BuildCommentList(iFirstIndex, iLastIndex) {
        aCommentsHtml = new Array();
        for (var i = iFirstIndex; i < iLastIndex; i++) {
            var html = htUI.Comment(oThis, {
                userId: aComments[i].UserId
                , username: aComments[i].AuthorName
                , avatar: aComments[i].UserImage
                , commentId: aComments[i].CommentId
                , comment: aComments[i].Text
                , postDate: aComments[i].PostDateTime
            });
            aCommentsHtml.push(html);
        }

        return aCommentsHtml;
    }
    
    function SubmitComment(){
        function haveData(newComment) {
            aComments.push(newComment);
            oElMan.Attribute("commentText", "value", "");
            var html = htUI.Comment(oThis, {
                                            userId: newComment.UserId
                                            , username: newComment.AuthorName
                                            , avatar: newComment.UserImage
                                            , commentId: newComment.CommentId
                                            , comment: newComment.Text
                                            , postDate: newComment.PostDateTime
            });
            var newHtml = oElMan.InnerHTML("comments") + html;
            oElMan.InnerHTML("comments", newHtml);
        }

        if (!Btv.User.IsLoggedIn()) {
            Btv.User.InitLogin(SubmitComment);
        }
        else {
            var commentText = $(oThis.htIds['commentText']).value;

            if (commentText.length == 0) {
                alert('Must type in a comment before submitting.');
            }
            else {
                fncSubmitComment(Btv.User.GetUser().Id, d.associationId, commentText, haveData);
            }
        }
    }

    function DisplayHideComment() {
        if (oElMan.Style("Root", "display") == "block") {
            oElMan.Style("Root", "display", "none");
            HideSubmitComment();
        }
        else {
            oElMan.Style("Root", "display", "block");
            DisplaySubmitComment();
        }
    }

    function DisplaySubmitComment() {
        oElMan.Style("submitComment", "display", "block");
        if (oElMan.Attribute("commentText", "value") == "Write a comment...") {
            oElMan.Attribute("commentText", "value", "");
        }
    }

    function HideSubmitComment() {
        oElMan.Style("submitComment", "display", "none");
        oElMan.Attribute("commentText", "value", "Write a comment...");
    }
    
    function InitElements() {
        function ModifyCommentLink() {
            var commentElem = $('comments-' + d.associationId);
            if (commentElem) {
                sCommentLink = commentElem.getAttribute("href");
                $E.addListener('comments-' + d.associationId, "click", window[$OG(DisplayHideComment)]);
                commentElem.removeAttribute('href');
            }

            if (d.comments) {
                aComments = d.comments;
                Populate();
            }
            else {
                PopulateComments();
            }
        }

        oElMan.Attribute("commentText", "value", "Write a comment...");

        if (d.commentCount) {
            iCommentCount = d.commentCount;
        }
        else {
            iCommentCount = 0;
        }
        
        if ($('comments-' + d.associationId)) {
            ModifyCommentLink();
        }
        else {
            $E.onAvailable('comments-' + d.associationId, ModifyCommentLink);
        }
    }

    function Render() {
        InitElements();
        var sMakeCommentHtml = htUI.MakeComment(oThis, {
            submitOnclick: $F('{0}()', $OG(SubmitComment))
            , inputOnclick: $F('{0}()', $OG(DisplaySubmitComment))
        });
        
        return htUI.Main(oThis, { makeComment: sMakeCommentHtml });
    }

    oThis.DeclareVirtualMethods({
        Render: Render
    });
})($data, {Main:Main,Comment:Comment,ViewCommentsLink:ViewCommentsLink,ViewCommentsLinkToPage:ViewCommentsLinkToPage,MakeComment:MakeComment});
}return $text.join("");}}]);
