Btv.Templating.Register([{id:"Photos2.Viewer",fnc:function($data){var $text = [];var _write = function(text) {$text.push((typeof text == "number")?text:(text||""));};with($data){ SmartAlbumSettings = function(o, cstContextList, strFncSave) {var $text = [];var _write = function(text) {$text.push((typeof text == "number")?text:(text||""));};_write('\r\n\n<div ');_write(o.Elem('sa_main'));_write('  style=\"margin:15px 0px; padding:5px; border:solid 1px #cccccc; display:none;');_write(o.Style());_write('\">');_write(o.InnerHTML());_write('\n<div>\n<span>Auto Album:</span>\n<span style=\"margin-left:20px;\"><input ');_write(o.Elem('sa_btnSave'));_write('  type=\"button\" value=\"Save\" onclick=\"');_write(strFncSave);_write('\" disabled=\"disabled\" style=\"font-size:smaller;');_write(o.Style());_write('\">');_write(o.InnerHTML());_write('</input></span>\n</div>\n<div>\n<div>Contexts:</div>\n<span>');_write(cstContextList.Render());_write('</span>\n</div>\n</div>\n');;return($text.join(""));};Main = function(o, oAdminHeader, oSingleView, oThumbnailView) {var $text = [];var _write = function(text) {$text.push((typeof text == "number")?text:(text||""));};_write('\r\n\n<div>\n');_write(oAdminHeader.Render());_write('\n');_write(oSingleView.Render());_write('\n');_write(oThumbnailView.Render());_write('\n<div ');_write(o.Elem('addPhotosRegion'));_write('  style=\"');_write(o.Style());_write('\">');_write(o.InnerHTML());_write('</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 s, data;
    var oElMan = oThis.ElMan();


    function Render()
    {
        var oModel = new Model(d);

        var oAdminHeader = Btv.Templating.GetInstance('Photos2.AdminHeader', {
            Model: oModel
            , strContextName: 'Album'
        });


        var oSingleView = Btv.Templating.GetInstance('Photos2.SingleView', {
            Model: oModel
        });


        var oThumbnailView = Btv.Templating.GetInstance('Photos2.ThumbnailView', {
            Model: oModel
        });

        var oController = new Controller(oModel, d, oAdminHeader, oSingleView, oThumbnailView);

        return (ui.Main(oThis, oAdminHeader, oSingleView, oThumbnailView));
    }




    function Model(d)
    {
        var oModel = this;
        oModel.onCountChange = new Btv.Event();
        oModel.onAlbumInfoChange = new Btv.Event();

        var htIndexLookup = {};
        var htIDLookup = {};

        function ItemAdded(oItem, iIndex)
        {
            if (oItem)
            {
                htIndexLookup[oItem.ID] = iIndex;
                htIDLookup[iIndex] = oItem.ID;
            }
        }


        d.oDataSource.onItemAdded.Attach(ItemAdded);
        d.oDataSource.Init();
        d.oDataSource.oQuery.ImageId = -1;

        oModel.GetCount = d.oDataSource.GetCount;
        oModel.GetAt = d.oDataSource.GetAt;
        oModel.GetRange = d.oDataSource.GetRange;
        oModel.RatePhoto = d.fncRatePhoto;
        oModel.FlagPhoto = d.fncFlagPhoto;


        oModel.SetActiveImage = function(oImg)
        {
            var strCast, strCategory;
            if (oImg)
            {
                var oMeta = oImg.MetaData;
                for (var i = 0; i < oMeta.length; i++)
                {
                    var iScopeID = oMeta[i].ScopeID;
                    if (!strCast && (iScopeID == 21)) strCast = oMeta[i].Title;
                    if (!strCategory && ((iScopeID == 2) || (iScopeID == 19))) strCategory = oMeta[i].Title;
                }
            }
            Btv.UI.SetPageTitle('BuddyTV Photo Gallery', strCast, strCategory);
            Btv.GoogleAnalytics.Unhold();
        }




        oModel.RemoveItemsByID = function(aImageIds, blnPermDelete, fnc)
        {
            function Removed(bln)
            {
                if (bln)
                {
                    var aIndices = [];
                    for (var i = 0; i < aImageIds.length; i++)
                    {
                        var idx = htIndexLookup[aImageIds[i]];
                        aIndices.push(idx);
                    }
                    d.oDataSource.RemoveAt(aIndices);
                    var aData = d.oDataSource.GetDataArray();
                    htIndexLookup = {};
                    htIDLookup = {};
                    for (var i = 0; i < aData.length; i++) ItemAdded(aData[i], i);
                    oModel.onCountChange.Fire();
                }
                fnc(bln);
            }

            d.fncRemoveImageFromAlbum(d.oDataSource.oQuery.AlbumId, aImageIds, blnPermDelete, Removed);
        }


        oModel.GetAlbumInfo = oModel.GetAlbum = function()
        {
            return ((d.oDataSource.oContext && d.oDataSource.oContext.Album) ? d.oDataSource.oContext.Album : null);
        }
        


        oModel.SaveAlbum = function(oAlbum, fnc)
        {
            function Done(o)
            {
                if (o)
                {
                    d.oDataSource.oContext.Album = oAlbum;
                    oModel.onAlbumInfoChange.Fire();
                }
                fnc();
            }
            d.fncUpdateAlbum(oAlbum, Done);
        }


        oModel.GetViewerUrl = function(oImg)
        {
            return(Btv.PhotoRater.BuildPhotoGalleryUrl(
                d.oDataSource.oQuery.ContentScopeId, 
                d.oDataSource.oQuery.ContentId, 
                oImg.ID, 
                d.oDataSource.oQuery.AlbumId, 
                -1
                ));
        }
        

        oModel.GetIDByIndex = function(iIndex)
        {
            var id = htIDLookup[iIndex];
            return ((id == undefined) ? -1 : id);
        }


        oModel.GetIndexByID = function(id, fnc, bln)
        {
            function RunQueryDone()
            {
                d.oDataSource.oQuery.ImageId = -1;
                oModel.GetIndexByID(id, fnc, true);
            }

            function AsyncReturn(iIndex)
            {
                fnc(iIndex);
            }

            var iIndex = htIndexLookup[id];
            if (iIndex == undefined)
            {
                if (!fnc) return (-1);
                if (bln)
                {
                    AsyncReturn(-1);
                }
                else
                {
                    d.oDataSource.oQuery.ImageId = id;
                    d.oDataSource.RunQuery(RunQueryDone);
                }
            }
            else
            {
                if (!fnc) return (iIndex);
                AsyncReturn(iIndex);
            }
        }
    }


    function ConvertInt(s, d)
    {
        if (d == undefined) d = -1;
        var i = parseInt(s);
        return (isNaN(i) ? d : i);
    }


    function HistoryManager()
    {
        var oHist = this;
        var iVersion = 1;

        oHist.Serialize = function(o)
        {
            return ([
                iVersion
                , (o.initial ? 1 : 0)
                , o.index
                , o.id
                , o.view
                ].join('/'));
        }

        oHist.Deserialize = function(str)
        {
            var a = str.split('/');
            return ({
                initial: (a[1] == 1)
                , index: ConvertInt(a[2])
                , id: ConvertInt(a[3])
                , view: a[4]
            });
        }
    }


    function Controller(oModel, d, oAdminHeader, oSingleView, oThumbnailView)
    {
        var oController = this;
        var oHist = new HistoryManager();

        var oState = {
            index: (d.oDataSource.oContext.FirstIndex || 0)
            , id: -1
            , view: d.InitialView
            , initial: true
        };

        var blnDoHistory = !Btv.Browser.isGecko;

        var strModuleName = 'GalleryViewer';
        var initialState = oHist.Serialize(oState);
        if (blnDoHistory) initialState = YAHOO.util.History.getBookmarkedState(strModuleName) || initialState;

        function AddHistoryState()
        {
            function AdDelay()
            {
                Btv.Ads.Change();
            }
            if (!oState.initial)
            {
                var strState = oHist.Serialize(oState);
                if (blnDoHistory)
                {
                    YAHOO.util.History.navigate(strModuleName, strState);
                }
                else
                {
                    StateChangeHandler(strState, false);
                }                    
                window.setTimeout(AdDelay, 500);
            }
        }

        function StateChangeHandlerCallback(strState)
        {
            StateChangeHandler(strState, false);
        }

        function StateChangeHandler(strState, blnRunOnce)
        {
            function Init()
            {
                oState = oNextState;
                delete (oState.initial);
                if (oModel.GetCount() == 0)
                {
                    Comments(-1);
                }
                else if (oState.view == 't')
                {
                    Comments(-1);
                    oThumbnailView.ShowPageWithImage(oState.index);
                    oSingleView.Display(false);
                    oThumbnailView.Display(true);
                }
                else
                {
                    oThumbnailView.Display(false);
                    oSingleView.Display(true);
                    oSingleView.SetIndex(oState.index);
                }
            }

            function HaveIndex(iIndex)
            {
                oNextState.index = (iIndex == -1) ? 0 : iIndex;
                Init();
            }

            var oNextState = oHist.Deserialize(strState);

            if (blnRunOnce && (oNextState.id != -1))
            {
                oModel.GetIndexByID(oNextState.id, HaveIndex);
            }
            else
            {
                Init();
            }
        }


        if (blnDoHistory) YAHOO.util.History.register(strModuleName, initialState, StateChangeHandlerCallback);


        function Comments(photoID)
        {
            var el = $('commentsiframeDiv');
            if (el) {
                if ((photoID != -1) && (iLastCommentsID != photoID)) {
                    d.CommentViewer.ResetContent(8, photoID);

                    el.style.display = 'block';
                }
                else {
                    el.style.display = 'none';
                }
                iLastCommentsID = photoID;
                
            }
        }
        var iLastCommentsID = -2;


        function DisplayingImage(oImg, iIndex)
        {
            if (oImg) Comments(oImg.ID);
        }


        function DisplayingThumbPage(iIndex)
        {
        }


        function IndexChange(i)
        {
            function HaveImageInfo(oImg)
            {
                oState.index = i;
                oState.id = oImg.ID;
                AddHistoryState();
            }

            if (!oModel.GetAt(i, HaveImageInfo))
            {
                oSingleView.SetIndex(-1, false);
            }
        }


        function PageChange(i)
        {
            oState.index = i;
            oState.id = -1;
            AddHistoryState();
        }


        function ShowSingle(i)
        {
            function HaveImageInfo(oImg)
            {
                oState.index = i;
                oState.view = 's';
                oState.id = oImg.ID;
                AddHistoryState();
            }

            oSingleView.SetIndex(-1, true);
            oModel.GetAt(i, HaveImageInfo);
        }



        function ShowThumbnails(i)
        {
            oState.index = i;
            oState.view = 't';
            oState.id = -1;
            AddHistoryState();
        }



        function ShowHiRes(oImg)
        {
            var strSrc = oImg.Views[oImg.Views.length - 1].Src;
            window.open(
                $F('/photos/HiResViewer.aspx?title={0}&image={1}', encodeURIComponent('High Resolution Image'), encodeURIComponent(strSrc)),
                'HiResPhoto'
                );
        }


        function RatePhoto(oImg)
        {
            if (oImg && oImg.Ratings) oModel.RatePhoto(oImg.ID, oImg.Ratings.RatingUser, Function.NoOp);
        }


        function FlagInappropriatePhoto(oImg)
        {
            if (oImg) oModel.FlagPhoto(38, oImg.ID, Function.NoOp);
        }


        function FlagWrongPhoto(oImg)
        {
            if (oImg) oModel.FlagPhoto(39, oImg.ID, Function.NoOp);
        }


        function ShareFriends(oImg) 
        {
            var share = new Btv.ShareFriends();
            var sizeImageBounds = { width: 100, height: 300 };
            var oImageView = Btv.UI.Images.FindView(oImg.Views, sizeImageBounds, true);
            if (!oImageView && oImg.Views.length > 0) {
                oImageView = oImg.Views[oImg.Views.length - 1];
            }
            var notGregsObject = { id: oImg.ID, title: oImg.Title, imageUrl: oImageView.Src };
            share.Initialize(8, oImg.ID, notGregsObject);
        }


        function UpdateTags(oImg, aWrong)
        {
            function Done()
            {
                Btv.WaitingDialog.Hide();
                oImg.MetaData = aFilteredMetaData;
                oSingleView.RefreshMetaData();
            }

            var a = [];
            var aFilteredMetaData = [];
            for (var i = 0; i < oImg.MetaData.length; i++)
            {
                var oMeta = oImg.MetaData[i];
                var iStatus = aWrong[i] ? 1 : 2;
                a.push({ ContentId: oMeta.ID, ContentScopeId: oMeta.ScopeID, Status: iStatus });
                if (!aWrong[i]) aFilteredMetaData.push(oMeta);
            }
            Btv.WaitingDialog.Show("Saving Tags");
            d.fncUpdateMetaData(oImg.ID, a, Done);
        }


        function PostRemoval(bln)
        {
            if (!bln)
            {
                Btv.SimpleDialog.Show('', 'The photo(s) could not be removed.', Btv.SimpleDialog.buttonsOK);
                return(false);
            }
        
            var iCount = oModel.GetCount();
            if (iCount == 0)
            {
                oThumbnailView.Display(false);
                oSingleView.Display(false);
                Comments(-1);
                Btv.SimpleDialog.Show('', 'There are no more photos in this album.', Btv.SimpleDialog.buttonsOK);
            }
            return (iCount != 0);
        }





        function RemoveImagesFromAlbum(aImageIds, fncPostRemoval, blnDeleteFromSystem)
        {
            function Done(bln)
            {
                Btv.WaitingDialog.Hide();
                if (PostRemoval(bln))
                {
                    if (fncPostRemoval) fncPostRemoval();
                }
            }

            function Confirm(bln)
            {
                if (bln)
                {
                    Btv.WaitingDialog.Show("Removing photo(s)...");
                    oModel.RemoveItemsByID(aImageIds, blnDeleteFromSystem, Done);
                }
            }

            if (aImageIds && aImageIds.length)
            {
                var strMessage = 'Do you want to remove the photo(s) from this album?';
                if (blnDeleteFromSystem) strMessage = 'Do you want to permanently delete the photo(s) from the entire system?<br />\n<br />\nThe photo(s) will be removed from all albums, and the actual image files will be permanently deleted.'
                Btv.SimpleDialog.Show('Confirmation', strMessage, Btv.SimpleDialog.buttonsYesNo, null, Confirm);
            }
        }


        function RemoveSingleImageFromAlbum(idImage, blnDeleteFromSystem)
        {
            function F()
            {
                oSingleView.SetIndex((oState.index == oModel.GetCount()) ? 0 : oState.index, true);
            }
            RemoveImagesFromAlbum([idImage], F, blnDeleteFromSystem);
        }

        function RemoveSingleImageFromAlbumNoPerm(idImage)
        {
            RemoveSingleImageFromAlbum(idImage, false);
        }

        function RemoveSingleImageFromAlbumPerm(idImage)
        {
            RemoveSingleImageFromAlbum(idImage, true);
        }


        function RemoveImagesThumbFromAlbum(blnDeleteFromSystem)
        {
            function F()
            {
                oThumbnailView.ShowPageWithImage(Math.min(oModel.GetCount() - 1, oState.index));
            }
            RemoveImagesFromAlbum(oThumbnailView.GetSelectedPhotos(), F, blnDeleteFromSystem);
        }

        function RemoveImagesThumbFromAlbumNoPerm()
        {
            RemoveImagesThumbFromAlbum(false);
        }

        function RemoveImagesThumbFromAlbumPerm()
        {
            RemoveImagesThumbFromAlbum(true);
        }



        function SetPhotosOrder()
        {
            function Done()
            {
                Btv.WaitingDialog.Hide();
                window.location.reload();
            }
            
            var oAlbum = oModel.GetAlbum();
            if (oAlbum)
            {
                var oData = oThumbnailView.GetOrdinalValues();
                if (oData.ids.length)
                {
                    Btv.WaitingDialog.Show("Setting photos order for this album...");
                    d.fncUpdateAlbumImageOrdinal(oAlbum.AffiliateId, d.oDataSource.oQuery.AlbumId, oData.ids, oData.ordinals, Done)
                }
            }
        }





        function AdminDataChange(strName, oValue, fncDone)
        {
            var oAlbum = Btv.Util.Clone(oModel.GetAlbum());
            oAlbum[strName] = oValue;
            oModel.SaveAlbum(oAlbum, fncDone);
        }
        oAdminHeader.SetDataChangeFunction(AdminDataChange);


        function DeleteAlbum(albumID, blnDeleteFromSystem)
        {
            function Done(o)
            {
                if (o)
                {
                    if (o.Success)
                    {
                        var parentAlbumID = o.ParentAlbumIds[0];
                        document.location.replace('/photos/category.aspx?aid=' + parentAlbumID);
                        return;
                    }
                }
                Btv.WaitingDialog.Hide();
                Btv.SimpleDialog.Show('', 'This album cannot be deleted.', Btv.SimpleDialog.buttonsOK);
            }

            function Confirm(bln)
            {
                if (bln)
                {
                    Btv.WaitingDialog.Show("Deleting album...");
                    d.fncRemoveAlbum(albumID, blnDeleteFromSystem, Done);
                }
            }

            var strMessage = 'Do you want to delete this album?';
            if (blnDeleteFromSystem) strMessage = 'Do you want to delete this album and all it\'s photos?<br />\n<br />\nAll of the images will be permanently deleted from the entire system?<br />\nThese images will be removed from all albums, and the actual image files will be permanently deleted.'

            Btv.SimpleDialog.Show('Confirmation', strMessage, Btv.SimpleDialog.buttonsYesNo, null, Confirm);
        }


        function AddPhotos()
        {
            function Done(blnAddedToAlbum)
            {
                if (blnAddedToAlbum)
                {
                    window.location.reload();
                }
                else
                {
                    oAddPanel.Display(false);
                    StateChangeHandler(oHist.Serialize(oState));
                }
            }
            
            function HavePanel(oPanel)
            {
                Comments(-1);
                oSingleView.Display(false);
                oThumbnailView.Display(false);
                oAddPanel.Display(true, Done);
            }

            function Available()
            {
                Btv.WaitingDialog.Hide();
                oAddPanel = Btv.Templating.GetInstance('Photos2.Admin.AddPhotosPanel', {
                    Model: oModel
                    ,fncSaveImportBatch: d.fncSaveImportBatch
                    });
                $(oThis.htIds['addPhotosRegion']).innerHTML = oAddPanel.Render();
                HavePanel();
            }

            if (oAddPanel)
            {
                HavePanel(oAddPanel);
            }
            else
            {
                Btv.WaitingDialog.Show("Loading...");
                Btv.Templating.NotifyWhenAvailable('Photos2.Admin.AddPhotosPanel', Available);
            }
        }
        var oAddPanel;

        function DeleteAlbumOnly(albumID)
        {
            DeleteAlbum(albumID, false);
        }

        function DeleteAlbumAndPermImages(albumID)
        {
            DeleteAlbum(albumID, true);
        }


        oAdminHeader.SetActions(
            [
                { strLabel: 'Delete Album', strClass: 'admin-delete-btn', fnc: DeleteAlbumOnly }
                , { strLabel: 'Delete Album/Images Permanently!!!', strClass: 'admin-delete-btn', fnc: DeleteAlbumAndPermImages }
                ,{ strLabel: 'Add Photos', strClass: 'admin-add-btn', fnc: AddPhotos }
            ]
        );



        (function()
        {
            function SmartAlbum_OnChange()
            {
                $el('sa_btnSave').disabled = false;
            }

            var fncGetAutoAlbum = Btv.Ajax.MakeFunction(Btv.Photos.DataQueries, 'GetAutoAlbum');
            var fncSetAutoAlbum = Btv.Ajax.MakeFunction(Btv.Photos.DataQueries, 'SetAutoAlbum');


            function UpdateAutoAlbum()
            {
                function F(o)
                {
                    if (o)
                    {
                        $Dalert('Auto-album settings saved.');
                    }
                    else
                    {
                        $Dalert('Error. Auto Album settings could not be saved.');
                        SmartAlbum_OnChange();
                    }
                    Btv.WaitingDialog.Hide();
                }

                Btv.WaitingDialog.Show("Saving auto-album settings...");

                var aiScopeIds = [];
                var aiItemIds = [];
                var aoContexts = cstSmartAlbumContexts.GetContexts() || [];
                for (var i = 0; i < aoContexts.length; i++)
                {
                    aiScopeIds.push(aoContexts[i].ContextType.Id);
                    aiItemIds.push(aoContexts[i].Id);
                }

                $el('sa_btnSave').disabled = true;
                fncSetAutoAlbum(oModel.GetAlbum().Id, 0, aiScopeIds, aiItemIds, F);
            }


            function SmartAlbumInit()
            {
                function F(o)
                {
                    if (o) cstSmartAlbumContexts.AddContexts(o.Contexts);
                    cstSmartAlbumContexts.onChange.Attach(SmartAlbum_OnChange);
                    $el('sa_main').style.display = 'block';
                }

                var oAlbum = oModel.GetAlbum();
                if (oAlbum && oAlbum.Id) fncGetAutoAlbum(oAlbum.Id, F);
            }


            var cstSmartAlbumContexts = Btv.Templating.GetInstance('Input.ContextList', { strLabel: '' });
            oAdminHeader.SetExtraUI([
                ui.SmartAlbumSettings(oThis, cstSmartAlbumContexts, $F('{0}()', $OG(UpdateAutoAlbum)))
                ]);

            oElMan.Function('sa_main', 'sa_mainInit', SmartAlbumInit);
        })();


        oAdminHeader.Display(false);


        oSingleView.onIndexChange.Attach(IndexChange);
        oSingleView.onViewThumbnails.Attach(ShowThumbnails);
        oSingleView.onViewHiRes.Attach(ShowHiRes);
        oSingleView.onRatePhoto.Attach(RatePhoto);
        oSingleView.onInappropriatePhoto.Attach(FlagInappropriatePhoto);
        oSingleView.onWrongPhoto.Attach(FlagWrongPhoto);
        oSingleView.onDisplayingImage.Attach(DisplayingImage);
        oSingleView.onShareFriends.Attach(ShareFriends);
        oSingleView.onUpdateTags.Attach(UpdateTags);
        oSingleView.onRemovePhoto.Attach(RemoveSingleImageFromAlbumNoPerm);
        oSingleView.onDeletePermPhoto.Attach(RemoveSingleImageFromAlbumPerm);
        

        oThumbnailView.onPageChange.Attach(PageChange);
        oThumbnailView.onThumbnailClick.Attach(ShowSingle);
        oThumbnailView.onDisplayingThumbPage.Attach(DisplayingThumbPage);
        oThumbnailView.SetActions(
            [
                { strLabel: 'Remove Selected Photos', strClass: 'admin-delete-btn', fnc: RemoveImagesThumbFromAlbumNoPerm }
                ,{ strLabel: 'Permanently Delete Photos!!!', strClass: 'admin-delete-btn', fnc: RemoveImagesThumbFromAlbumPerm }
                , { strLabel: 'Set Photos Order', strClass: 'admin-pen-btn', fnc: SetPhotosOrder }
            ]
        );



        oSingleView.SetIndex(-1);
        oThumbnailView.ShowPageWithImage(-1);
        oSingleView.Display(false);
        oThumbnailView.Display(false);


        YAHOO.util.History.onReady(function()
        {
            StateChangeHandler(YAHOO.util.History.getCurrentState(strModuleName), true);
        });

        if (blnDoHistory)
        {
            YAHOO.util.History.initialize("yui-history-field", "yui-history-iframe");
        }
        else
        {
            StateChangeHandler(initialState, true);
        }


        var blnAdminMode = false;
        function AdminData(blnAdminMode_, oPermissions)
        {
            var oAlbum = oModel.GetAlbum();
            var bln = blnAdminMode_ && oAlbum && oPermissions.HasPermission(oAlbum.AffiliateId, 'ManagePhotoAlbums');
            if (blnAdminMode != bln)
            {
                blnAdminMode = bln;
                oAdminHeader.Display(bln);
                oSingleView.AdminMode(bln);
                oThumbnailView.AdminMode(bln);
            }
        }
        Btv.Admin.Subscribe(AdminData)
    }



    oThis.DeclareVirtualMethods({
        Render: Render
    });


})($data, {SmartAlbumSettings:SmartAlbumSettings,Main:Main});
}return $text.join("");}},{id:"Photos2.SingleView",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=\"photo09_viewer_left\" style=\"position:relative;\">\n<div class=\"photo09_viewer_head\" style=\"zoom:1; position:relative; z-index:10\">\n<div>');_write(ht.Pager.Render());_write('</div>\n<div style=\"clear:both\"></div>\n</div>\n<div class=\"photo09_viewer_img\">\n<div class=\"photo09_viewer_region_img\">\n<div ');_write(o.Elem('regionLoading'));_write('  style=\"text-align:center; padding-top:100px; display:none;');_write(o.Style());_write('\">');_write(o.InnerHTML());_write('\n<img src=\"/images/spin2.gif\" style=\"border-width:0px; vertical-align:middle;\"><span>Loading image</span> \n</div>\n<div ');_write(o.Elem('regionImage'));_write('  style=\"');_write(o.Style());_write('\">');_write(o.InnerHTML());_write('<img ');_write(o.Elem('imgMain'));_write('  style=\"position:relative; visibility:hidden; cursor:pointer;');_write(o.Style());_write('\">');_write(o.InnerHTML());_write('</img></div>\n</div>\n</div>\n<div ');_write(o.Elem('regionCaption'));_write('  style=\"position:relative; visibility:hidden;');_write(o.Style());_write('\" class=\"photo09_viewer_caption\">');_write(o.InnerHTML());_write('\n<div align=\"center\"><span ');_write(o.Elem('date'));_write('  style=\"');_write(o.Style());_write('\">');_write(o.InnerHTML());_write('</span><span ');_write(o.Elem('dateCreditSep'));_write('  style=\"');_write(o.Style());_write('\">');_write(o.InnerHTML());_write('</span><span ');_write(o.Elem('credit'));_write('  style=\"');_write(o.Style());_write('\">');_write(o.InnerHTML());_write('</span></div>\n<span ');_write(o.Elem('caption'));_write('  style=\"');_write(o.Style());_write('\">');_write(o.InnerHTML());_write('</span>\n</div>\n</div>\n<div class=\"photo09_viewer_right\"><div ');_write(o.Elem('regionRight'));_write('  style=\"position:relative; visibility:hidden;');_write(o.Style());_write('\">');_write(o.InnerHTML());_write('\n<div class=\"photo09_viewer_right_top\">\n<div ');_write(o.Elem('adminRegion'));_write('  style=\"zoom:1; margin-bottom:10px; display:none;');_write(o.Style());_write('\">');_write(o.InnerHTML());_write('\n<div class=\"admin-head\">\n<div class=\"admin-delete-btn\"><a href=\"javascript:');_write($OG(ht.fncDelete));_write('()\">Remove photo from this album</a></div>\n</div>\n<div class=\"admin-head\">\n<div class=\"admin-delete-btn\"><a href=\"javascript:');_write($OG(ht.fncDeletePerm));_write('()\">Delete photo permanently!!!</a></div>\n</div>\n</div>\n<h3>Rate this photo:</h3>\n');_write(ht.Rater.Render());_write('\n<br />\n<div class=\"photo09_view_icon\"><span ');_write(o.Elem('ratings'));_write('  style=\"');_write(o.Style());_write('\">');_write(o.InnerHTML());_write('</span><br /></div>\n<div class=\"photo09_comment_icon\"><a ');_write(o.Elem('comments'));_write('  style=\"');_write(o.Style());_write('\">');_write(o.InnerHTML());_write('</a></div>\n<h3>Tags:</h3>\n<div ');_write(o.Elem('regionTags'));_write('  style=\"padding-left:15px;');_write(o.Style());_write('\">');_write(o.InnerHTML());_write(ht.TagsList.Render());_write('</div>\n<h3>Actions:</h3>\n<div class=\"photo09_action_thumb\"><a ');_write(o.Elem('ThumbnailLink'));_write('  style=\"');_write(o.Style());_write('\">');_write(o.InnerHTML());_write('Thumbnail view</a></div>\n<div class=\"photo09_action_highres\"><a ');_write(o.Elem('HiResLink'));_write('  style=\"');_write(o.Style());_write('\">');_write(o.InnerHTML());_write('View high resolution image</a></div>\n<h3>Report Photo:</h3>\n<div class=\"photo09_action_report\"><a ');_write(o.Elem('reportInappropriate'));_write('  style=\"');_write(o.Style());_write('\">');_write(o.InnerHTML());_write('</a><span ');_write(o.Elem('reportInappropriateThanks'));_write('  style=\"color:Red; padding-left:15px; display:none;');_write(o.Style());_write('\">');_write(o.InnerHTML());_write('Thank you!</span></div>\n<div class=\"photo09_action_wrong\"><a ');_write(o.Elem('reportWrong'));_write('  style=\"');_write(o.Style());_write('\">');_write(o.InnerHTML());_write('</a><span ');_write(o.Elem('reportWrongThanks'));_write('  style=\"color:Red; padding-left:15px; display:none;');_write(o.Style());_write('\">');_write(o.InnerHTML());_write('Thank you!</span></div>\n</div>\n<div>\n<h3>Share:</h3>\n<div>\n<div style=\"margin-bottom:10px; clear:both;\"><div style=\"float:left; width:60px;\">Link:</div><input ');_write(o.Elem('shareLink'));_write('  type=\"text\" onclick=\"this.select()\" style=\"');_write(o.Style());_write('\">');_write(o.InnerHTML());_write('</input></div>\n<div style=\"margin-bottom:10px; clear:both;\"><a ');_write(o.Elem('shareFriends'));_write('  style=\"');_write(o.Style());_write('\">');_write(o.InnerHTML());_write('Share with Friends</a></div>\n</div>\n</div>\n</div></div>\n<div style=\"clear:both;\"></div>\n');;return($text.join(""));};Version3 = function(o, ht) {var $text = [];var _write = function(text) {$text.push((typeof text == "number")?text:(text||""));};_write('\r\n\n<div style=\"position:relative;\">\n<center>\n<div><a ');_write(o.Elem('ThumbnailLink'));_write('  style=\"');_write(o.Style());_write('\">');_write(o.InnerHTML());_write('See all thumbnails</a></div>\n<div class=\"photo09_viewer_head\" style=\"zoom:1; position:relative; z-index:10\">\n<div>');_write(ht.Pager.Render());_write('</div>\n<div style=\"clear:both\"></div>\n</div>\n');_write(ht.Rater.Render());_write('\n<div><span ');_write(o.Elem('ratings'));_write('  style=\"');_write(o.Style());_write('\">');_write(o.InnerHTML());_write('</span><br /></div>\n<div class=\"photo09_viewer_img\">\n<div class=\"photo09_viewer_region_img\" style=\"left:0px;\">\n<div ');_write(o.Elem('regionLoading'));_write('  style=\"text-align:center; padding-top:100px; display:none;');_write(o.Style());_write('\">');_write(o.InnerHTML());_write('\n<img src=\"/images/spin2.gif\" style=\"border-width:0px; vertical-align:middle;\"><span>Loading image</span> \n</div>\n<div ');_write(o.Elem('regionImage'));_write('  style=\"');_write(o.Style());_write('\">');_write(o.InnerHTML());_write('<img ');_write(o.Elem('imgMain'));_write('  style=\"position:relative; visibility:hidden; cursor:pointer;');_write(o.Style());_write('\">');_write(o.InnerHTML());_write('</img></div>\n</div>\n</div>\n</center>\n<div ');_write(o.Elem('regionCaption'));_write('  style=\"position:relative; visibility:hidden;');_write(o.Style());_write('\" class=\"photo09_viewer_caption\">');_write(o.InnerHTML());_write('\n<div align=\"center\"><span ');_write(o.Elem('date'));_write('  style=\"');_write(o.Style());_write('\">');_write(o.InnerHTML());_write('</span><span ');_write(o.Elem('dateCreditSep'));_write('  style=\"');_write(o.Style());_write('\">');_write(o.InnerHTML());_write('</span><span ');_write(o.Elem('credit'));_write('  style=\"');_write(o.Style());_write('\">');_write(o.InnerHTML());_write('</span></div>\n<span ');_write(o.Elem('caption'));_write('  style=\"');_write(o.Style());_write('\">');_write(o.InnerHTML());_write('</span>\n</div>\n<center><table><tr><td>\n<div class=\"photo09_action_highres\"><a ');_write(o.Elem('HiResLink'));_write('  style=\"');_write(o.Style());_write('\">');_write(o.InnerHTML());_write('View high resolution image</a></div>\n<div class=\"photo09_action_report\"><a ');_write(o.Elem('reportInappropriate'));_write('  style=\"');_write(o.Style());_write('\">');_write(o.InnerHTML());_write('</a><span ');_write(o.Elem('reportInappropriateThanks'));_write('  style=\"color:Red; padding-left:15px; display:none;');_write(o.Style());_write('\">');_write(o.InnerHTML());_write('Thank you!</span></div>\n<div class=\"photo09_action_wrong\"><a ');_write(o.Elem('reportWrong'));_write('  style=\"');_write(o.Style());_write('\">');_write(o.InnerHTML());_write('</a><span ');_write(o.Elem('reportWrongThanks'));_write('  style=\"color:Red; padding-left:15px; display:none;');_write(o.Style());_write('\">');_write(o.InnerHTML());_write('Thank you!</span></div>\n<div class=\"photo09_view_icon\"><a ');_write(o.Elem('shareFriends'));_write('  style=\"');_write(o.Style());_write('\">');_write(o.InnerHTML());_write('Share with Friends</a></div>\n</td></tr></table></center>\n<br />\n<div style=\"margin-bottom:10px; clear:both;\"><div style=\"width:100%;\">Link:</div><input ');_write(o.Elem('shareLink'));_write('  style=\"width:100%;');_write(o.Style());_write('\" type=\"text\" onclick=\"this.select()\">');_write(o.InnerHTML());_write('</input></div>\n</div>\n<div style=\"clear:both;\"></div>\n');;return($text.join(""));};ConfirmDialog = function(o, ht) {var $text = [];var _write = function(text) {$text.push((typeof text == "number")?text:(text||""));};_write('\r\n\n<div ');_write(o.Elem('dialogConfirm'));_write('  style=\"');_write(o.Style());_write('\">');_write(o.InnerHTML());_write('Are you sure you want to remove this tag?</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 oPager, oRater, oImageChanger, oBtvModule, tagsList, dialogConfirm;
    var oElMan = oThis.ElMan();
    var blnDisplay = !!d.Display;
    var iCurrentIndex = d.StartIndex;
    var blnForceRefresh = false;
    var oCurrentImg = null;
    var oCurrentImageView = null;
    var oCurrentRating = null;
    var sizeImageBounds = {width:400, height:400};
    var sizeEmbedImageBounds = {width:200, height:200};
    oThis.onIndexChange = new Btv.Event();
    oThis.onViewThumbnails = new Btv.Event();
    oThis.onViewHiRes = new Btv.Event();
    oThis.onRatePhoto = new Btv.Event();
    oThis.onInappropriatePhoto = new Btv.Event();
    oThis.onWrongPhoto = new Btv.Event();
    oThis.onDisplayingImage = new Btv.Event();
    oThis.onShareFriends = new Btv.Event();
    oThis.onUpdateTags = new Btv.Event();
    oThis.onRemovePhoto = new Btv.Event();
    oThis.onDeletePermPhoto = new Btv.Event();
    



    function PreCache()
    {
        function SingleViewLoader(oModel)
        {
            var oLoader = this;
            var oImg;

            oLoader.GetAt = function(iIndex, fnc)
            {
                function HaveInfo(oInfo)
                {
                    function HaveImage(oImg_, bln)
                    {
                        oImg = oImg_;
                        fnc();
                    }

                    if (oInfo)
                    {
                        var oView = Btv.UI.Images.FindView(oInfo.Views, sizeImageBounds);
                        oView ? Btv.UI.Imaging.Load(oView.Src, fnc, oImg, 3) : HaveImage();
                    }
                }

                oModel.GetAt(iIndex, HaveInfo);
            }
        }

        if (!oPreLoader) oPreLoader = new Btv.Data.PreLoader(new SingleViewLoader(d.Model), 2, 5, true);
        oPreLoader.SetState(d.Model.GetCount(), iCurrentIndex);
    }
    var oPreLoader;
    


    
    
    
    
    function OnPagerChanged(iPageNum)
    {
        oThis.onIndexChange.Fire(iPageNum-1);
    }


    function OnViewThumbnails()
    {
        oThis.onViewThumbnails.Fire(iCurrentIndex);
    }


    function OnViewHiRes()
    {
        oThis.onViewHiRes.Fire(oCurrentImg);
    }


    function OnInappropriate()
    {
        htInappropriate[oCurrentImg.ID] = true;
        oElMan.Style('reportInappropriate', 'display', 'none');
        oThis.onInappropriatePhoto.Fire(oCurrentImg);
        oElMan.Style('reportInappropriateThanks', 'display', 'inline');
    }
    var htInappropriate = {};


    function OnWrong()
    {
        htWrong[oCurrentImg.ID] = true;
        oElMan.Style('reportWrong', 'display', 'none');
        oThis.onWrongPhoto.Fire(oCurrentImg);
        oElMan.Style('reportWrongThanks', 'display', 'inline');
    }
    var htWrong = {};


    function OnShareFriends()
    {
        oThis.onShareFriends.Fire(oCurrentImg);
    }


    function OnUpdateTags(oImg, aWrong)
    {
        oThis.onUpdateTags.Fire(oImg, aWrong);
    }


    function RemovePhoto()
    {
        if (oCurrentImg) oThis.onRemovePhoto.Fire(oCurrentImg.ID);
    }


    function DeletePhotoPerm()
    {
        if (oCurrentImg) oThis.onDeletePermPhoto.Fire(oCurrentImg.ID);
    }
    
    
    function CreateHelperObjects()
    {
        
        function CreatePager()
        {
            oPager = Btv.Templating.GetInstance("Navigation.NumericPager", {
                iPageCount: d.Model.GetCount()
                ,iPageStart: ((iCurrentIndex >= 0) ? (iCurrentIndex + 1) : -1)
                ,align: 'center'
                ,classes: {
                    NavFirst: 'photos2_singleView_pager_NavFirst'
                    ,NavLast: 'photos2_singleView_pager_NavLast'
                }
                ,labels: {
                    Back: 'Prev'
                    ,Next: 'Next'
                    ,Page: 'Photo'
                    ,Pages: 'Photos'
                }
                ,blnLoop:true
            });

            oPager.onChange.Attach(OnPagerChanged);
        }



        function CreateRater()
        {
            function Rate(iRating)
            {
                var oR = oCurrentImg.Ratings;
                if (oR.RatingUser <= 0)
                {
                    oR.RatingUser = iRating * 2;
                    oR.RatingAvg = ((oR.RatingAvg * oR.RatingCount) + oR.RatingUser) / (oR.RatingCount + 1);
                    oR.RatingCount += 1;
                    RefreshRater();
                    oThis.onRatePhoto.Fire(oCurrentImg);
                }
            }
        
            oRater = Btv.Templating.GetInstance("Rater.Big", {
                rating: oCurrentImg ? oCurrentImg.Ratings : null
                ,fncRate: Rate
                });
        }


        tagsList = Btv.Templating.GetInstance("Photos2.TagList", {});
        tagsList.onUpdateTags.Attach(OnUpdateTags);

        
        CreatePager();
        CreateRater();
    }



    function RefreshRater()
    {
        oRater.UpdateRating(oCurrentImg.Ratings);
        oElMan.InnerHTML('ratings', (oCurrentImg.Ratings.RatingCount + ' Ratings'));
    }


    function RegionsVisiblity(bln)
    {
        for (var i=0; i < astrRegions.length; i++)
        {
            oElMan.Style(astrRegions[i], 'visibility', (bln ? 'visible' : 'hidden'));
        }
    }
    var astrRegions = ['regionRight', 'regionImage', 'regionCaption'];


    
    function HideLoadingUI()
    {
        ++ShowLoadingUI.idAsync;
        RegionsVisiblity(true);
        oElMan.Style('regionLoading', 'display', 'none');
        oElMan.Style('regionImage', 'display', 'block');
    }
   

    function ShowLoadingUI()
    {
        function Delay()
        {
            if (idAsync == ShowLoadingUI.idAsync)
            {
                RegionsVisiblity(false);
                oElMan.Style('regionLoading', 'display', 'block');
                oElMan.Style('regionImage', 'display', 'none');
            }
        }

        idAsync = ++ShowLoadingUI.idAsync;
        //Delay();
        window.setTimeout(Delay, 500);
    }
    ShowLoadingUI.idAsync = 0;


    function RefreshCount()
    {
        if (oPager) oPager.SetPageCount(d.Model.GetCount());
        blnForceRefresh = true;
    }
    d.Model.onCountChange.Attach(RefreshCount);



    oThis.AdminMode = function(bln)
    {
        blnAdminMode = bln;
        oElMan.Style('adminRegion', 'display', bln ? 'block' : 'none');
    }
    var blnAdminMode = false;



    oThis.RefreshMetaData = function()
    {
        tagsList.SetData(oCurrentImg);
    }


    oThis.SetIndex = function(i, blnClear)
    {
        if (blnForceRefresh || (iCurrentIndex != i))
        {
            iCurrentIndex = i;
            if (!oThis.IsRendered()) return;
            if (blnClear) RegionsVisiblity(false);
            RefreshUI();
        }
        else
        {
            oThis.onDisplayingImage.Fire(oCurrentImg, iCurrentIndex);
        }
        blnForceRefresh = false;
    }



    function UpdateReportLinks()
    {
        Btv.UI.Utility.EnableLink($(oThis.htIds['reportInappropriate']), !htInappropriate[oCurrentImg.ID]);
        oElMan.InnerHTML('reportInappropriate', $F('Report{0} as inappropriate', htInappropriate[oCurrentImg.ID] ? 'ed' : ''));
        
        Btv.UI.Utility.EnableLink($(oThis.htIds['reportWrong']), !htWrong[oCurrentImg.ID]);
        oElMan.InnerHTML('reportWrong', $F('Report{0} as wrong info/picture', htWrong[oCurrentImg.ID] ? 'ed' : ''));
    }

    function UpdateViewer()
    {
        // update all the other attributes of the viewer
        var strDate = Btv.DateTime.Format(oCurrentImg.TakenDate, oCurrentImg.DateGranularity);
        oElMan.InnerHTML('date', strDate);
        oElMan.InnerHTML('dateCreditSep', ((strDate && oCurrentImg.Credit) ? ' - ' : ''));
        oElMan.InnerHTML('credit', oCurrentImg.Credit);
        oElMan.InnerHTML('caption', oCurrentImg.Caption);
        RefreshRater();
        oElMan.InnerHTML('comments', (oCurrentImg.CommentCount + ' Comments'));
        UpdateReportLinks();
        oElMan.Style('reportInappropriate', 'display', 'block');
        oElMan.Style('reportWrong', 'display', 'block');
        oElMan.Style('reportInappropriateThanks', 'display', 'none');
        oElMan.Style('reportWrongThanks', 'display', 'none');
        
        var oEmbedView = Btv.UI.Images.FindView(oCurrentImg.Views, sizeEmbedImageBounds);
        var strLink = d.Model.GetViewerUrl(oCurrentImg);
        oElMan.Attribute('shareLink',
                'value',
                $F('<a href="{0}">Rate a {1} photo on BuddyTV</a>', document.location.href, oCurrentImg.Title)
                );

        oRater.UpdateRating(oCurrentImg.Ratings);
        tagsList.SetData(oCurrentImg);
    }


    function ImageDisplayTimeout()
    {
        oPager.ChangeBy(1);
    }
    var idTimeout;

    
    function RefreshUI()
    {

        function ImageDoneChanging(elImgNew)
        {
            function F()
            {
                if (idAsync != RefreshUI.idAsync) return;
                UpdateViewer();
                PreCache();
            }

            window.clearTimeout(idTimeout);

            var elImg = $(oThis.htIds['imgMain']);
            elImg.style.visibility = 'visible';
            elImg.onclick = OnViewHiRes;
            if (!oImageChanger)
            {
                // first time image loaded successfully
                elImg.removeAttribute('onload');
                elImg.onload = null;
                oImageChanger = new Btv.UI.Imaging.ImageChanger(elImg, Btv.Browser.isGecko);
            }
            if (idAsync == RefreshUI.idAsync)
            {
                HideLoadingUI();
                RegionsVisiblity(true);
                elLastImage = elImgNew;
                window.setTimeout(F, 10);
            }
        }


        function ChangeImage(elImg)
        {
            var sizeScaled = Btv.UI.BindBox({ width: oCurrentImageView.Width, height: oCurrentImageView.Height }, sizeImageBounds);
            oElMan.Style(elImg
                , 'width', (sizeScaled.width + "px")
                , 'height', (sizeScaled.height + "px")
                , 'top', (Math.floor((sizeImageBounds.height - sizeScaled.height - 1) / 2) + 'px')
            );
            if (Btv.iPageVersion != 3)
            {
                oElMan.Style(elImg
                    , 'left', (Math.floor((sizeImageBounds.width - sizeScaled.width - 1) / 2) + 'px')
                );
            }
            
            window.clearTimeout(idTimeout);
            idTimeout = window.setTimeout(ImageDisplayTimeout, 5000);
            
            oElMan.Attribute(elImg
                , 'src', oCurrentImageView.Src
            );
            oThis.onDisplayingImage.Fire(oCurrentImg, iCurrentIndex);
        }


        function InitImage()
        {
            oElMan.Attribute('imgMain', 'onload', ImageDoneChanging);
            ChangeImage('imgMain');
        }


        function HaveImageInfo(oImg)
        {
            if (oImg && (idAsync == RefreshUI.idAsync))
            {
                oCurrentImg = oImg;
                oCurrentImageView = oImg ? Btv.UI.Images.FindView(oImg.Views, sizeImageBounds) : null;

                d.Model.SetActiveImage(oImg);

                if (oImageChanger)
                {
                    oImageChanger.Change(ChangeImage, ImageDoneChanging);
                }
                else
                {
                    InitImage()
                }
            }
        }

        var idAsync = ++RefreshUI.idAsync;
        ShowLoadingUI();
        if (iCurrentIndex >= 0)
        {
            oPager.SetPage(iCurrentIndex + 1);
            d.Model.GetAt(iCurrentIndex, HaveImageInfo);
        }
    }
    RefreshUI.idAsync = 0;

    var elLastImage;

    function ScrollToComments()
    {
        $('commentsiframeDiv').scrollIntoView();
    }

    
    
    function InitElements()
    {
        //oThis.Display(blnDisplay);
        oElMan.Attribute('ThumbnailLink', 'href', $F('javascript:{0}()', $OG(OnViewThumbnails)));
        oElMan.Attribute('HiResLink', 'href', $F('javascript:{0}()', $OG(OnViewHiRes)));
        oElMan.Attribute('reportInappropriate', 'href', $F('javascript:{0}()', $OG(OnInappropriate)));
        oElMan.Attribute('reportWrong', 'href', $F('javascript:{0}()', $OG(OnWrong)));
        oElMan.Attribute('comments', 'href', $F('javascript:{0}()', $OG(ScrollToComments)));
        oElMan.Attribute('shareFriends', 'href', $F('javascript:{0}()', $OG(OnShareFriends)));
    }



    function RenderView()
    {
        CreateHelperObjects();
        InitElements();
        RefreshUI();

        var strUIFunction = (Btv.iPageVersion == 3) ? "Version3" : "Main";
        return (htUI[strUIFunction](oThis, {
            Rater: oRater
            , Pager: oPager
            , TagsList: tagsList
            , fncDelete: RemovePhoto
            , fncDeletePerm: DeletePhotoPerm
        }));
    }


    var oBtvModule = Btv.Templating.GetInstance('Container.BtvModule', {
        body: { Render: RenderView }
        , classes: { Module: 'btv_module photo09_viewer' }
    });
    oThis.Display = oBtvModule.Display;



    oThis.DeclareVirtualMethods({
        Render: oBtvModule.Render
    });

})($data, {Main:Main,Version3:Version3,ConfirmDialog:ConfirmDialog});
}return $text.join("");}},{id:"Photos2.TagList",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('tagsRegion'));_write('  style=\"');_write(o.Style());_write('\">');_write(o.InnerHTML());_write('</div>\n<div ');_write(o.Elem('updateTagsButton'));_write('  style=\"display:');_write(ht.blnAdmin ? 'block' : 'none');_write(';');_write(o.Style());_write('\">');_write(o.InnerHTML());_write('<input type=\"button\" value=\"Update Tags\" onclick=\"javascript:');_write($OG(ht.fncUpdateTags));_write('()\" /></div>\n');;return($text.join(""));};TagRegion = function(o, ht) {var $text = [];var _write = function(text) {$text.push((typeof text == "number")?text:(text||""));};_write('\r\n\n<div>\n<a ');_write(o.Elem('href' + '.' + ht.index));_write('  href=\"/');_write(ht.href);_write('\" style=\"');_write(o.Style());_write('\">');_write(o.InnerHTML());_write(ht.tagTitle);_write('</a>\n<a ');_write(o.Elem('adminWrong' + '.' + ht.index));_write('  href=\"javascript:');_write(ht.fncClick);_write('(');_write(ht.index);_write(')\" style=\"margin-left:10px; font-size:smaller; display:');_write(ht.blnAdmin ? 'inline' : 'none');_write(';');_write(o.Style());_write('\">');_write(o.InnerHTML());_write('</a>\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 oImg, oElMan = oThis.ElMan();
    var aAdminWrongState = [];
    oThis.onUpdateTags = new Btv.Event();
    var blnAdminMode = false;


    function AdminData(blnAdminMode_, oPermissions)
    {
        var bln = blnAdminMode_ && oPermissions.HasPermission(1, 'ModifyPhotoStatus');
        blnAdminMode = bln;
        oElMan.Style('updateTagsButton', 'display', (bln ? 'block' : 'none'));

        for (var i = 0; oImg && (i < oImg.MetaData.length); i++)
        {
            oElMan.Style(('adminWrong.' + i), 'display', (bln ? 'inline' : 'none'));
        }
    }
    Btv.Admin.Subscribe(AdminData)



    function SetTagStatus(i)
    {
        var id = 'adminWrong.' + i;
        oElMan.InnerHTML(id, (aAdminWrongState[i] ? 'wrong' : 'correct'));
        oElMan.Style(id, 'color', (aAdminWrongState[i] ? 'Red' : 'Green'));
    }

    function AdminClick(i)
    {
        aAdminWrongState[i] = !aAdminWrongState[i];
        SetTagStatus(i);
    }


    function UpdateTags()
    {
        for (var i = 0; i < oImg.MetaData.length; i++)
        {
            aAdminWrongState[i] = !!aAdminWrongState[i];
        }
        oThis.onUpdateTags.Fire(oImg, aAdminWrongState);
    }


    oThis.SetData = function(oImg_)
    {

        function CreateRegions(oImg)
        {
            function Tokenize(el)
            {
                RunBtvTokenizer(el, aoOverlayData);
            }

            oThis.DisposeElements(['tagsRegion', 'updateTagsButton'], true);

            var s = '';
            var aoOverlayData = [];
            for (var i = 0; i < oImg.MetaData.length; i++)
            {
                aAdminWrongState[i] = (oImg.MetaData.Status == 1);
                var oMeta = oImg.MetaData[i];
                if (oMeta.OverlayData) aoOverlayData.push(oMeta.OverlayData);
                SetTagStatus(i);
                s += htUI.TagRegion(oThis, {
                    href: oMeta.Url
                    , tagTitle: oMeta.Title
                    , fncClick: $OG(AdminClick)
                    , index: i
                    , blnAdmin: blnAdminMode
                });
            }
            oElMan.InnerHTML('tagsRegion', s);
            oElMan.Function('tagsRegion', 'tokenize', Tokenize);
        }

        oImg = oImg_;
        aAdminWrongState = [];
        CreateRegions(oImg);
    }



    function Render()
    {
        var s = htUI.Main(oThis, { fncUpdateTags: UpdateTags });
        return (s);
    }
    

    oThis.DeclareVirtualMethods({
        Render: Render
    });

})($data, {Main:Main,TagRegion:TagRegion});
}return $text.join("");}},{id:"Photos2.ThumbnailView",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('mainRegion'));_write('  style=\"');_write(o.Style());_write('\">');_write(o.InnerHTML());_write('\n<div ');_write(o.Elem('pagerRegion'));_write('  style=\"margin:3px 0px 20px 0px;');_write(o.Style());_write('\">');_write(o.InnerHTML());_write(ht.Pager ? ht.Pager.Render() : '');_write('</div>\n<div ');_write(o.Elem('regionLoading'));_write('  style=\"text-align:center; padding:20px 0px 20px 0px; display:none;');_write(o.Style());_write('\">');_write(o.InnerHTML());_write('\n<img src=\"/images/spin2.gif\" style=\"border-width:0px; vertical-align:middle;\"><span>Loading</span> \n</div>\n<div ');_write(o.Elem('regionThumbs'));_write('  style=\"');_write(o.Style());_write('\">');_write(o.InnerHTML());_write('\n<div ');_write(o.Elem('adminRegion'));_write('  style=\"zoom:1; margin-bottom:10px; display:none;');_write(o.Style());_write('\">');_write(o.InnerHTML());_write('\n<div style=\"float:left;\">\n<span>Thumbnails:</span>\n<span style=\"padding-right:10px;\">\n<select ');_write(o.Elem('thumbsPerPage'));_write('  onchange=\"');_write($OG(ht.fncThumbsPerPage));_write('()\" style=\"vertical-align:middle;');_write(o.Style());_write('\">');_write(o.InnerHTML());_write('\n<option value=\"30\" selected>30</option>\n<option value=\"120\">120</option>\n<option value=\"300\">300</option>\n</select>\n</span>\n<a href=\"javascript:');_write($OG(ht.fncSelectAll));_write('()\" style=\"padding-right:10px;\">Select All</a>\n<a href=\"javascript:');_write($OG(ht.fncSelectNone));_write('()\" style=\"padding-right:10px;\">Select None</a>\n<a href=\"javascript:');_write($OG(ht.fncSelectInvert));_write('()\" style=\"padding-right:10px;\">Invert Selection</a>\n</div>\n<div class=\"admin-head\" style=\"float:right;\">\n');_write(ht.fncRenderActions());_write('\n<div style=\"clear:both;\"></div>\n</div>\n<div style=\"clear:both;\"></div>\n</div>\n');_write(ht.DynPanel.Render());_write('\n</div>\n<div style=\"clear:both;\"></div>\n<div ');_write(o.Elem('pagerRegion2'));_write('  style=\"margin:8px 0px 3px 0px;');_write(o.Style());_write('\">');_write(o.InnerHTML());_write(ht.Pager2 ? ht.Pager2.Render() : '');_write('</div>\n</div>\n');;return($text.join(""));};Actions = function(o, actions, fnc) {var $text = [];var _write = function(text) {$text.push((typeof text == "number")?text:(text||""));};_write('\r\n\n');if(actions instanceof Array) {for(var i=0; i<actions.length; i++) {_write('\n<div class=\"');_write(actions[i].strClass);_write('\" style=\"float:right;\"><a href=\"javascript:');_write($OG(fnc));_write('(');_write(i);_write(')\">');_write(actions[i].strLabel);_write('</a></div>\n');}} else {for(var i in actions) {_write('\n<div class=\"');_write(actions[i].strClass);_write('\" style=\"float:right;\"><a href=\"javascript:');_write($OG(fnc));_write('(');_write(i);_write(')\">');_write(actions[i].strLabel);_write('</a></div>\n');}}_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 oDynPanel, oPager, oPager2, aItems, aData;
    var iPageSize = ((Btv.iPageVersion == 3) ? 20 : 30);
    var iCurrentPage = -1;
    oThis.onPageChange = new Btv.Event();
    oThis.onThumbnailClick = new Btv.Event();
    oThis.onDisplayingThumbPage = new Btv.Event();
    var blnForceRefresh = false;


    function RenderActions()
    {
        function ActionClicked(i)
        {
            aoActions[i].fnc();
        }

        return (aoActions ? htUI.Actions(oThis, aoActions, ActionClicked) : '');
    }

    oThis.SetActions = function(aoActions_)
    {
        aoActions = aoActions_;
    }
    var aoActions;


    function RefreshCount()
    {
        var iCount = d.Model.GetCount();
        var iPageCount = Math.ceil(iCount / iPageSize);
        if (!iCount) oThis.Display(false);
        if (oPager) oPager.SetPageCount(iPageCount);
        if (oPager2) oPager2.SetPageCount(iPageCount);
        blnForceRefresh = true;
    }


    if (d.Model.onCountChange) d.Model.onCountChange.Attach(RefreshCount);


    function SetPageSize(i)
    {
        var iFirstIndex = GetFirstIndex(iCurrentPage);
        iPageSize = i;
        iCurrentPage = -1;
        RefreshCount();
        CreateAndAddItems();
        InitElements();
        oThis.ShowPageWithImage(iFirstIndex);
    }


    function CreateHelperObjects()
    {
        function CreatePager()
        {
            var iPageCount = Math.ceil(d.Model.GetCount() / iPageSize);
            if (iPageCount > 1)
            {
                oPager = Btv.Templating.GetInstance("Navigation.NumericPager", {
                    iPageCount: iPageCount
                    , iPageStart: iCurrentPage
                    , align: 'center'
                    , labels: {
                        Back: 'Prev'
                        , Next: 'Next'
                        , Page: 'Page'
                        , Pages: 'Pages'
                    }
                });
                oPager.onChange.Attach(OnPageChange);

                oPager2 = Btv.Templating.GetInstance("Navigation.NumericPager", {
                    iPageCount: iPageCount
                    , iPageStart: iCurrentPage
                    , align: 'center'
                    , labels: {
                        Back: 'Prev'
                        , Next: 'Next'
                        , Page: 'Page'
                        , Pages: 'Pages'
                    }
                });
                oPager2.onChange.Attach(OnPageChange);
            }
        }


        oDynPanel = Btv.Templating.GetInstance('Container.DynamicPanel', {
            cols: ((Btv.iPageVersion == 3) ? 4 : 6)
            , Classes: { Outer: 'photo09_photo' }
        });


        CreatePager();
    }


    function CreateAndAddItems()
    {
        aItems = [];
        for (var i = 0; i < iPageSize; i++)
        {
            aItems[i] = Btv.Templating.GetInstance('Photos2.ImageThumbnailSummary', {
                fncClick: OnClickHandler
                , id: i
                , blnNoFooter: !!d.blnNoFooter
            });
            aItems[i].AdminMode(blnAdminMode);
        }
        oDynPanel.SetItems(aItems);
    }



    oThis.AdminMode = function(bln)
    {
        blnAdminMode = bln;
        oElMan.Style('adminRegion', 'display', bln ? 'block' : 'none');
        for (var i = 0; aItems && (i < aItems.length); i++)
        {
            aItems[i].AdminMode(bln);
        }
    }
    var blnAdminMode = false;


    oThis.GetSelectedPhotos = function(blnImageObjects)
    {
        var a = [];
        var iEnd = Math.min(aData.length, aItems.length);
        for (var i = 0; i < iEnd; i++)
        {
            if (aItems[i].IsChecked()) a.push(blnImageObjects ? aData[i] : aData[i].ID);
        }
        return (a);
    }


    oThis.GetOrdinalValues = function()
    {
        var aIds = [];
        var aOrdinals = [];
        var iEnd = Math.min(aData.length, aItems.length);
        for (var i = 0; i < iEnd; i++)
        {
            var iOrdinal = aItems[i].GetOrdinal();
            if (!isNaN(iOrdinal))
            {
                aIds.push(aData[i].ID);
                aOrdinals.push(iOrdinal);
            }
        }
        return ({ ids: aIds, ordinals: aOrdinals });
    }



    function SelectAll()
    {
        for (var i = 0; aItems && (i < aItems.length); i++) aItems[i].SetChecked(true);
    }


    function SelectNone()
    {
        for (var i = 0; aItems && (i < aItems.length); i++) aItems[i].SetChecked(false);
    }


    function SelectInvert()
    {
        for (var i = 0; aItems && (i < aItems.length); i++) aItems[i].SetChecked(!aItems[i].IsChecked());
    }


    function ThumbsPerPage()
    {
        var el = $(oThis.htIds['thumbsPerPage']);
        for (var i = 0; i < el.options.length; i++)
        {
            if (el.options[i].selected)
            {
                SetPageSize(parseInt(el.options[i].value));
                return;
            }
        }
    }


    function GetFirstIndex(iPage)
    {
        return ((iPage > 0) ? ((iPage - 1) * iPageSize) : -1);
    }


    function OnClickHandler(idItem)
    {
        oThis.onThumbnailClick.Fire(GetFirstIndex(iCurrentPage) + idItem);
    }


    function OnPageChange(iPage)
    {
        oThis.onPageChange.Fire(GetFirstIndex(iPage));
    }



    oThis.ShowPageWithImage = function(iImageIndex)
    {
        var i = (iImageIndex >= 0) ? (Math.floor(iImageIndex / iPageSize) + 1) : -1;
        if (blnForceRefresh || (iCurrentPage != i))
        {
            iCurrentPage = i;
            if (!oThis.IsRendered()) return;
            RefreshUI();
        }
        blnForceRefresh = false;
    }


    oThis.Refresh = function()
    {
        if (!oThis.IsRendered()) return;
        RefreshUI();
    }

    function HideLoadingUI()
    {
        ++ShowLoadingUI.idAsync;
        oElMan.Style('regionLoading', 'display', 'none');
        oElMan.Style('regionThumbs', 'display', 'block');
    }


    function ShowLoadingUI()
    {
        function Delay()
        {
            if (idAsync == ShowLoadingUI.idAsync)
            {
                oElMan.Style('regionLoading', 'display', 'block');
                oElMan.Style('regionThumbs', 'display', 'none');
            }
        }

        idAsync = ++ShowLoadingUI.idAsync;
        Delay();
        //window.setTimeout(Delay, 500);
    }
    ShowLoadingUI.idAsync = 0;



    function RefreshUI()
    {
        function HaveData(aData_)
        {
            aData = aData_;
            if (idAsync == RefreshUI.idAsync)
            {
                for (var i = 0; i < aItems.length; i++)
                {
                    if ((i == 0) && d.Model.SetActiveImage) d.Model.SetActiveImage(aData[i]);
                    var oItem = (aData && (i < aData.length)) ? aData[i] : null;
                    aItems[i].SetData(oItem, oItem && d.strNoCheckProp && oItem[d.strNoCheckProp]);
                }
            }
            HideLoadingUI();
            oThis.onDisplayingThumbPage.Fire(GetFirstIndex(iCurrentPage));
        }

        var idAsync = ++RefreshUI.idAsync;
        if (iCurrentPage > 0)
        {
            if (oPager)
            {
                oPager.SetPage(iCurrentPage);
                oPager2.SetPage(iCurrentPage);
            }

            var oRangeNeeded = {
                FirstIndex: GetFirstIndex(iCurrentPage)
                , Count: iPageSize
            };
            SelectNone();
            ShowLoadingUI();
            d.Model.GetRange(oRangeNeeded, HaveData);
        }
    }
    RefreshUI.idAsync = 0;




    function InitElements()
    {
        oElMan.Style('pagerRegion', 'display', (oPager ? 'block' : 'none'));
        oElMan.Style('pagerRegion2', 'display', (oPager2 ? 'block' : 'none'));
    }



    function RenderView()
    {
        CreateHelperObjects();
        CreateAndAddItems();
        InitElements();
        RefreshUI();

        oElMan.Style('mainRegion', 'padding', d.blnNoPadding ? '0px' : '13px');
        
        return (htUI.Main(oThis, {
            DynPanel: oDynPanel
            , Pager: oPager
            , Pager2: oPager2
            , fncSelectAll: SelectAll
            , fncSelectNone: SelectNone
            , fncSelectInvert: SelectInvert
            , fncThumbsPerPage: ThumbsPerPage
            , fncRenderActions: RenderActions
        }));
    }


    var oBtvModule = Btv.Templating.GetInstance('Container.BtvModule', {
        body: { Render: RenderView }
    });

    oThis.Display = oBtvModule.Display;



    oThis.DeclareVirtualMethods({
        Render: oBtvModule.Render
    });


})($data, {Main:Main,Actions:Actions});
}return $text.join("");}},{id:"Photos2.AdminHeader",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=\"admin-labels\">\n<div style=\"margin-top:4px;\">Title:</div>\n<div style=\"margin-top:4px;\">Description:</div>\n</div>\n<div class=\"photo09_category photo09_category_txt\" style=\"width:350px;\">\n<h3 ');_write(o.Elem('title'));_write('  style=\"');_write(o.Style());_write('\">');_write(o.InnerHTML());_write('</h3>\n<div ');_write(o.Elem('description'));_write('  class=\"cat_description\" style=\"');_write(o.Style());_write('\">');_write(o.InnerHTML());_write('</div>\n</div>\n<div class=\"admin-edit-buttons\">\n<div class=\"admin-pen-btn\"><a ');_write(o.Elem('lnkEditTitle'));_write('  href=\"javascript:');_write($OG(ht.fncEditTitle));_write('()\" style=\"');_write(o.Style());_write('\">');_write(o.InnerHTML());_write('Edit title</a></div>\n<div class=\"admin-pen-btn\"><a ');_write(o.Elem('lnkEditDescription'));_write('  href=\"javascript:');_write($OG(ht.fncEditDescription));_write('()\" style=\"');_write(o.Style());_write('\">');_write(o.InnerHTML());_write('Edit description</a></div>\n');_write(ht.fncRenderActions());_write('\n</div>\n<div style=\"clear:both\"></div>\n<div>\n');
for (var i=0; i < ht.astrExtra.length; i++)
{
_write(ht.astrExtra[i]);
}
_write('\n</div>\n');;return($text.join(""));};Actions = function(actions, fnc) {var $text = [];var _write = function(text) {$text.push((typeof text == "number")?text:(text||""));};_write('\r\n\n');if(actions instanceof Array) {for(var i=0; i<actions.length; i++) {_write('\n<div style=\"margin-top:5px;\"><div class=\"');_write(actions[i].strClass);_write('\" style=\"float:none;\"><a href=\"javascript:');_write($OG(fnc));_write('(');_write(i);_write(')\">');_write(actions[i].strLabel);_write('</a></div></div>\n');}} else {for(var i in actions) {_write('\n<div style=\"margin-top:5px;\"><div class=\"');_write(actions[i].strClass);_write('\" style=\"float:none;\"><a href=\"javascript:');_write($OG(fnc));_write('(');_write(i);_write(')\">');_write(actions[i].strLabel);_write('</a></div></div>\n');}}_write('\n');;return($text.join(""));};TextFieldDialog = function(o, ht) {var $text = [];var _write = function(text) {$text.push((typeof text == "number")?text:(text||""));};_write('\r\n\n<h4>Title:</h4>\n<input type=\"text\"\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 oAlbum;

    function Render()
    {
        return (htUI.Main(oThis, {
            strContextName: d.strContextName
            , fncEditTitle: EditTitle
            , fncEditDescription: EditDescription
            , fncRenderActions: RenderActions
            , astrExtra: astrExtra
        }));
    }


    function RenderActions()
    {
        function ActionClicked(i)
        {
            aoActions[i].fnc(oAlbum.Id);
        }

        return (aoActions ? htUI.Actions(aoActions, ActionClicked) : '');
    }


    oThis.SetExtraUI = function(astrExtra_)
    {
        astrExtra = astrExtra_;
    }
    var astrExtra = [];



    oThis.SetActions = function(aoActions_)
    {
        aoActions = aoActions_;
    }
    var aoActions;
    

    oThis.SetAlbumInfo = function()
    {
        oAlbum = Model.Album || Model.GetAlbumInfo();
        oElMan.InnerHTML('title', oAlbum ? oAlbum.Title : '');
        oElMan.InnerHTML('description', oAlbum ? oAlbum.Description : '');
    }
    oThis.SetAlbumInfo();

    d.Model.onAlbumInfoChange.Attach(oThis.SetAlbumInfo);


    oThis.SetDataChangeFunction = function(fncDataChange_)
    {
        d.fncDataChange = fncDataChange_;
    }


    function EditTitle()
    {
        function DoSave(bln, strNewValue, fncClose)
        {
            if (bln)
            {
                d.fncDataChange('Title', strNewValue, fncClose);
                return("Saving data...");
            }
        }
        oDialogPrompt.Display('Edit Album Title', 'Enter the album title here:', (oAlbum ? oAlbum.Title : ''), [oThis.htIds['lnkEditTitle'], 'tr', 'br'], DoSave);
    }


    function EditDescription()
    {
        function DoSave(bln, strNewValue, fncClose)
        {
            if (bln && d.fncDataChange)
            {
                d.fncDataChange('Description', strNewValue, fncClose);
                return("Saving data...");
            }
        }
        oDialogPrompt.Display('Edit Album Description', 'Enter the album description here:', (oAlbum ? oAlbum.Description : ''), [oThis.htIds['lnkEditDescription'], 'tr', 'br'], DoSave);
    }


    var oDialogPrompt = Btv.Templating.GetInstance('Dialog.Prompt', {});

    var oBtvModule = Btv.Templating.GetInstance('Container.AdminBoxModule', {
        body: { Render: Render }
    });
    oThis.Display = oBtvModule.Display;



    oThis.DeclareVirtualMethods({
        Render: oBtvModule.Render
    });

})($data, {Main:Main,Actions:Actions,TextFieldDialog:TextFieldDialog});
}return $text.join("");}},{id:"Container.AdminBoxModule",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=\"admin-grey-box\" style=\"');_write(o.Style());_write('\">');_write(o.InnerHTML());_write('\n');_write(ht.body.Render());_write('\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();

    function Render(s)
    {
        return (htUI.Main(oThis, {
            body: d.body
        }));
    }

    oThis.Display = function(bln)
    {
        oElMan.Style('Root'
            , 'display', (bln ? 'block' : 'none')
            );
    }

    oThis.DeclareVirtualMethods({
        Render: Render
    });
})($data, {Main:Main});
_write('\n');}return $text.join("");}},{id:"Dialog.Prompt",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 style=\"width:400px;\">\n<div ');_write(o.Elem('inputRegion'));_write('  style=\"');_write(o.Style());_write('\">');_write(o.InnerHTML());_write('\n<h4 ');_write(o.Elem('instructions'));_write('  style=\"');_write(o.Style());_write('\">');_write(o.InnerHTML());_write('</h4>\n<input ');_write(o.Elem('textinput'));_write('  type=\"text\" style=\"');_write(o.Style());_write('\">');_write(o.InnerHTML());_write('</input>\n</div>\n<div ');_write(o.Elem('messageRegion'));_write('  style=\"display:none;');_write(o.Style());_write('\">');_write(o.InnerHTML());_write('</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 dialog;

    function Render()
    {
        dialog = Btv.SimpleDialog.GetInstance();
        dialog.SetBody(htUI.Main(oThis, {}));
    }

    oThis.Display = function(strHeader, strInstructions, strValue, context, fncCallback)
    {
        function Callback(bln)
        {
            function Close()
            {
                dialog.Hide();
            }
            
            var strMessage;
            if (fncCallback)
            {
                strMessage = fncCallback(bln, $(oThis.htIds['textinput']).value, Close);
                oElMan.Style('messageRegion', 'display', 'block');
                oElMan.Style('inputRegion', 'display', 'none');
            }
            if (strMessage)
            {
                oElMan.InnerHTML('messageRegion', strMessage);
                oElMan.Style('messageRegion', 'display', 'block');
                oElMan.Style('inputRegion', 'display', 'none');
                return (true);
            }
        }

        oElMan.Style('messageRegion', 'display', 'none');
        oElMan.Style('inputRegion', 'display', 'block');
        oElMan.InnerHTML('instructions', strInstructions);
        oElMan.Attribute('textinput', 'value', strValue);
        dialog.Show(strHeader, null, Btv.SimpleDialog.buttonsCancelOK, context, Callback);
    }

    oThis.DeclareVirtualMethods({
        Render: Render
    });

    oThis.Render();
})($data, {Main:Main});
}return $text.join("");}},{id:"Input.ContextList",fnc:function($data){var $text = [];var _write = function(text) {$text.push((typeof text == "number")?text:(text||""));};with($data){ Main = function(o, d, oContextList) {var $text = [];var _write = function(text) {$text.push((typeof text == "number")?text:(text||""));};_write('\r\n\n<div style=\"position:relative; zoom:1;\">\n<div>\n<div style=\"float:left; margin-right:10px;\">');_write(d.strLabel);_write('</div>\n<div style=\"float:left; width:100%; margin-right:10px;\">');_write(oContextList.Render());_write('</div>\n<div style=\"float:left;\"><a ');_write(o.Elem('lnkAdd'));_write('  style=\"');_write(o.Style());_write('\">');_write(o.InnerHTML());_write('Add</a></div>\n<div style=\"clear:both;\"></div>\n</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 oContextList = Btv.Templating.GetInstance('Input.ItemList', {});
    var cstContextListPicker = Btv.Templating.GetInstance('Dialog.ContextListPicker', {});
    oThis.onChange = new Btv.Event();
    
    oContextList.onChange.Attach(oThis.onChange.Fire);


    function Add_Click()
    {
        cstContextListPicker.Display(oThis.AddContexts);
    }


    oThis.AddContexts = function(ao)
    {
        if (ao && ao.length)
        {
            for (var i = 0; i < ao.length; i++) oContextList.AddItem(ao[i].Id, ao[i].Title, ao[i]);
            oThis.onChange.Fire();
        }
    }



    oThis.GetContexts = function()
    {
        return (oContextList.GetItems());
    }


    oThis.ElementProps = function(id, scope, name, isInit, params, ht)
    {
        switch (scope)
        {
            case "lnkAdd":
                if (isInit) ht.attr.onclick = $F('{0}()', $OG(Add_Click));
                break;
        }
    }



    function Render()
    {
        oListPicker = Btv.Templating.GetInstance('Dialog.ListPicker', {});
        return (ui.Main(oThis, d, oContextList));
    }

    oThis.DeclareVirtualMethods({
        Render: Render
    });
        
})($data, {Main:Main});
}return $text.join("");}},{id:"Input.ItemList",fnc:function($data){var $text = [];var _write = function(text) {$text.push((typeof text == "number")?text:(text||""));};with($data){ Main = function(o) {var $text = [];var _write = function(text) {$text.push((typeof text == "number")?text:(text||""));};_write('\r\n\n<div ');_write(o.Elem('main'));_write('  class=\"item-list-container\" style=\"');_write(o.Style());_write('\">');_write(o.InnerHTML());_write('\n<div class=\"payload\">\n<div ');_write(o.Elem('items'));_write('  style=\"position:relative;');_write(o.Style());_write('\">');_write(o.InnerHTML());_write('</div>\n<div ');_write(o.Elem('inputRegion'));_write('  class=\"suggest-input-open\" style=\"');_write(o.Style());_write('\">');_write(o.InnerHTML());_write('\n<input ');_write(o.Elem('textInput'));_write('  type=\"text\" value=\"Helper text goes here\" maxlength=\"256\" style=\"');_write(o.Style());_write('\">');_write(o.InnerHTML());_write('</input>\n</div>\n<div style=\"clear:both;\"></div>\n</div>\n</div>\n');;return($text.join(""));};Item = function(o, elID, strID, strLabel, fncRemove) {var $text = [];var _write = function(text) {$text.push((typeof text == "number")?text:(text||""));};_write('\r\n\n<div ');_write(o.Elem('item' + '.' + elID));_write('  class=\"item\" style=\"');_write(o.Style());_write('\">');_write(o.InnerHTML());_write('\n<span>');_write(strLabel);_write('</span>\n<a onclick=\"');_write($F('{0}(\'{1}\', \'{2}\')', $OG(fncRemove), elID, strID));_write('\"></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 oList = new Btv.Collections.HybridList();
    oThis.onChange = new Btv.Event();

    oThis.AddItem = function(strID, strLabel, object)
    {
        if (oList.Add(strID, object))
        {
            //oThis.RemoveDefaultText();
            $(oThis.htIds['items']).appendChild(Btv.Dom.Dominize(ui.Item(oThis, $I(), strID, strLabel, oThis.RemoveItem)));
            oThis.onChange.Fire();
        }
    }

    oThis.RemoveItem = function(elID, strID)
    {
        if (oList.Remove(strID))
        {
            oThis.DisposeElem(elID);
            $(oThis.htIds['items']).removeChild($(oThis.htIds['item.' + elID]));
            oThis.onChange.Fire();
        }
    }


    oThis.GetItems = function()
    {
        return (oList.GetList());
    }
    
    
    function Render(s)
    {
        oElMan.Style('inputRegion', 'display', 'none');
        return (htUI.Main(oThis, {
        }));
    }


    oThis.DeclareVirtualMethods({
        Render: Render
    });

})($data, {Main:Main,Item:Item});
_write('\n');}return $text.join("");}},{id:"Dialog.ContextListPicker",fnc:function($data){var $text = [];var _write = function(text) {$text.push((typeof text == "number")?text:(text||""));};with($data){ Main = function(o, fncChangeContextType) {var $text = [];var _write = function(text) {$text.push((typeof text == "number")?text:(text||""));};_write('\r\n\n<div>\n<div>\n<h4 ');_write(o.Elem('instructions'));_write('  style=\"');_write(o.Style());_write('\">');_write(o.InnerHTML());_write('</h4>\n<div>\n<select ');_write(o.Elem('contextType'));_write('  onchange=\"');_write($OG(fncChangeContextType));_write('()\" style=\"');_write(o.Style());_write('\">');_write(o.InnerHTML());_write('</select>\n</div>\n<div ');_write(o.Elem('selListDiv'));_write('  style=\"display:none;');_write(o.Style());_write('\">');_write(o.InnerHTML());_write('\n<select ');_write(o.Elem('selList'));_write('  size=\"20\" multiple=\"multiple\" style=\"');_write(o.Style());_write('\">');_write(o.InnerHTML());_write('</select>\n</div>\n</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 dialog;
    var fncCallback;
    var htLists = {};
    var htContexts = {};
    var aContextTypes;
    var aContexts;
    var fncGetContextTypes = Btv.Ajax.MakeFunction(Btv.CommonCstQueries, 'GetContextTypes');
    var fncGetContextsByContextTypeId = Btv.Ajax.MakeFunction(Btv.CommonCstQueries, 'GetContextsByContextTypeId');

    function ChangeContextType() {
        function haveData(data) {
            aContexts = data;
            htContexts[iContextTypeId] = data;
            BuildContextDropDown();
        }

        Btv.WaitingDialog.Show("Loading...");
        dialog.Hide();
        oElMan.Style('selListDiv', 'display', 'none');
        
        var iContextTypeId = parseInt(oElMan.Attribute('contextType', 'options')[oElMan.Attribute('contextType', 'selectedIndex')].value);

        if (htContexts[iContextTypeId]) {
            aContexts = htContexts[iContextTypeId];
            BuildContextDropDown();
        }
        else {
            fncGetContextsByContextTypeId(iContextTypeId, haveData);
        }
    }

    function BuildContextTypeDropDown() {
        if (aContextTypes) {
            var aOptions = new Array();

            var sDefaultOption = '<option selected="selected" value="0">Select Context Type</option>';
            aOptions.push(sDefaultOption);

            for (var i = 0; i < aContextTypes.length; i++) {
                var sOption = $F('<option value="{0}">{1}</option>', aContextTypes[i].Id, aContextTypes[i].Name);
                aOptions.push(sOption);
            }
            
            oElMan.InnerHTML('contextType', aOptions.join(''));
        }
    }

    function BuildContextDropDown() {
        if (aContexts) {
            var aOptions = new Array();

            for (var i = 0; i < aContexts.length; i++) {
                var sOption = $F('<option value="{0}">{1}</option>', aContexts[i].Id, aContexts[i].Title);
                aOptions.push(sOption);
            }

            oElMan.InnerHTML('selList', aOptions.join(''));
            oElMan.Style('selListDiv', 'display', 'block');
            Btv.WaitingDialog.Hide();
            ShowDialog();        
        }
    }

    function InitElements() {
        function PopulateContextTypes(data) {
            aContextTypes = data;
            BuildContextTypeDropDown();
        }

        fncGetContextTypes(PopulateContextTypes)
    }

    function ShowDialog() {
        function Callback(bln) {
            if (bln) {
                var aContextValues = new Array();
                var aOptions = $(oThis.htIds['selList']).options;
                for (var i = 0; i < aOptions.length; i++) {
                    if (aOptions[i].selected) {
                        for (var j = 0; j < aContexts.length; j++) {
                            if (aOptions[i].value == aContexts[j].Id) {
                                aContextValues.push(aContexts[j]);
                            }
                        }
                    }
                }
                fncCallback(aContextValues);
            }
        }
    
        dialog.Show("Choose Contexts", null, Btv.SimpleDialog.buttonsCancelOK, null, Callback);
    }
    
    function Render()
    {
        InitElements();
        dialog = Btv.SimpleDialog.GetInstance();
        dialog.SetBody(htUI.Main(oThis, ChangeContextType));
    }

    oThis.Display = function(fnc) {
        fncCallback = fnc;
        oElMan.InnerHTML('instructions', "You may select multiple context by holding down Ctrl");
        ShowDialog();
    }

    oThis.DeclareVirtualMethods({
        Render: Render
    });

    oThis.Render();
})($data, {Main:Main});
}return $text.join("");}},{id:"Navigation.NumericPager",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('pager'));_write(' class=\"dropPager\" style=\"position:relative; zoom:1; ');_write(o.Style());_write('\">\n<div ');_write(o.Elem('controlsRegion'));_write(' style=\"zoom:1; ');_write(o.Style());_write('\">\n<span ');_write(o.Elem('backRegion'));_write(' style=\"');_write(o.Style());_write('\">\n<a ');_write(o.Elem('lnkFirst'));_write('><img src=\"/images/double-left.png\" style=\"width:13px; height:9px; margin-right:15px; border-width:0px;\"></a>\n<a ');_write(o.Elem('lnkBack'));_write(' style=\"padding-right:12px;\"><img src=\"/images/single-left.png\" style=\"width:6px; height:9px; padding-right:4px; border-width:0px;\">');_write(o.Labels['Back']);_write('</a>\n</span>\n<span ');_write(o.Elem('photoNumRegion'));_write(' style=\"min-width:120px; text-align:center;\">\n<span style=\"margin-right:2px;\">');_write(o.Labels['Page']);_write('&nbsp;</span><span ');_write(o.Elem('pagePickerHandler'));_write(' style=\"');_write(o.Style());_write('\"><span ');_write(o.Elem('currentPage'));_write(' style=\"margin-right:0px;\">');_write(o.InnerHTML());_write('</span><img src=\"/images/inverted-arrow.png\" style=\"width:13px; height:12px; border-width:0px; vertical-align:middle;\"></span><span style=\"margin-left:2px;\">&nbsp;of&nbsp;</span><span ');_write(o.Elem('totalPages'));_write('>');_write(o.InnerHTML());_write('</span>\n</span>\n<span ');_write(o.Elem('nextRegion'));_write(' style=\"');_write(o.Style());_write('\">\n<a ');_write(o.Elem('lnkNext'));_write(' href=\"#\" style=\"padding-left:12px;\">');_write(o.Labels['Next']);_write('<img src=\"/images/single-right.png\" style=\"width:6px; height:9px; padding-left:4px; border-width:0px;\"></a>\n<a ');_write(o.Elem('lnkLast'));_write(' href=\"#\"><img src=\"/images/double-right.png\" style=\"width:13px; height:9px; margin-left:15px; border-width:0px;\"></a>\n</span>\n<div style=\"clear:both;\"></div>\n</div>\n<div ');_write(o.Elem('pagePickerRegion'));_write(' style=\"display:none; width:100%; position:absolute;\">\n<div style=\"height:5px;\"></div>\n<div class=\"dropPager_PagePicker\" style=\"background-color:#e0e0e0; border:solid 1px #999999; padding:5px;\">\n<div ');_write(o.Elem('pagePickerBackRegion'));_write(' style=\"text-align:left; margin:3px 0px; background-color:#e0e0e0;\"><a ');_write(o.Elem('lnkPagePickerBack'));_write('>&lt;&lt;&nbsp;');_write(o.Labels['Pages']);_write(' <span ');_write(o.Elem('pagePickerBackFirst'));_write('></span>-<span ');_write(o.Elem('pagePickerBackLast'));_write('></span></a></div>\n<table ');_write(o.Elem('tblPagePicker'));_write(' cellpadding=\"0\" cellspacing=\"3\" style=\"zoom:1;\"><tr>\n'); for (var i = 0; i < o.oPagePicker.GetGridSize(); i++)
{
if ((i > 0) && ((i % o.oPagePicker.GetColCount()) == 0))
{
_write('\n</tr><tr>\n'); } _write('\n<td ');_write(o.Elem('dropPager_span.' + i, i));_write('></td>\n'); } _write('\n</script>\n</tr></table>\n<div ');_write(o.Elem('pagePickerNextRegion'));_write(' style=\"text-align:right; margin:3px 0px; background-color:#e0e0e0;\"><a ');_write(o.Elem('lnkPagePickerNext'));_write('>');_write(o.Labels['Pages']);_write(' <span ');_write(o.Elem('pagePickerNextFirst'));_write('></span>- <span ');_write(o.Elem('pagePickerNextLast'));_write('></span>&nbsp;&gt;&gt;</a></div>\n</div>\n</div>\n</div>\n');;return($text.join(""));};_write('\n');
new (function(d, fncMain)
{
var s, oThis = Btv.Lang.Extend(this, Btv.Cst.BaseTemplate, arguments);
var iPages = d.iPageCount;
var iPage = d.iPageStart || 1;
oThis.debugID = 'pager';
d.align = d.align || 'center';
d.labels = d.labels || {};
d.labels.Back = d.labels.Back || 'Back';
d.labels.Next = d.labels.Next || 'Next';
d.labels.Page = d.labels.Page || 'Page';
d.labels.Pages = d.labels.Pages || 'Pages';
oThis.Labels = d.labels; 
oThis.onChange = new Btv.Event();
function GoBy(i)
{
GoTo(iPage + i);
}
oThis.ChangeBy = GoBy;
function Refresh()
{
oThis.UpdateElements();
oPagePicker.SetData(iPages, iPage);
}
function GoTo(i, blnNoEvent)
{
if (iPage == i) return;
if (d.blnLoop) i = (((i-1) + iPages) % iPages) + 1;
iPage = Math.max(1, Math.min(iPages, i));
if (!blnNoEvent) oThis.onChange.Fire(iPage);
oThis.StateChanged(Refresh);
}
oThis.GoTo = GoTo;
oThis.SetPageCount = function(i)
{
d.iPageCount = iPages = i;
Refresh();
}
oThis.SetPage = function(i)
{
GoTo(i, true);
}
function PagePicker(iColCount, iRowCount, iOpenDelay, iCloseDelay, fncGoTo)
{
var oPagePicker = this;
var iPagePickerGridCount = iColCount * iRowCount;
var iPickerActive = -1;
var iPickerCurrent = -1;
var iPagePage = -1;
var iNumPagePages = -1;
var iNumPages = -1;
var iCurrentPage = -1;
var iVisibleRows = -1;
var blnDirty = true;
oPagePicker.ChangeBy = function(iAmount)
{
Prepare(Math.max(0, Math.min(Math.ceil(iPages / iPagePickerGridCount), iPagePage + iAmount)));
oPagePicker.oPickerTracker.Out();
}
oPagePicker.GetGridSize = function()
{
return(iPagePickerGridCount);
}
oPagePicker.GetColCount = function()
{
return(iColCount);
}
oPagePicker.SetData = function(iNumPages_, iCurrentPage_)
{
if (iNumPages != iNumPages_)
{
blnDirty = true;
iNumPages = iNumPages_;
iNumPagePages = Math.ceil(iNumPages / iPagePickerGridCount);
}
iCurrentPage = iCurrentPage_;
}
function Prepare(iPagePage_)
{
function GetChildNodes(elparent, astrTagNames)
{
var a = [];
if (elparent)
{
var ht = Btv.Util.ArrayToHash(astrTagNames, Btv.Util.ToLowerCase);
var aNodes = elparent.childNodes;
for (var i=0; i < aNodes.length; i++)
{
var oNode = aNodes[i];
if (oNode.tagName && ht[oNode.tagName.toLowerCase()])
{
a.push(elparent.childNodes[i]);
}
}
}
return(a);
}
function SaveReferences()
{
if (!aelRows)
{
aelRows = GetChildNodes($(oThis.htIds['tblPagePicker']).childNodes[0], ['tr']);
aelCells = GetChildNodes(aelRows[0], ['td']);
}
}
var aelRows;
var aelCells;
function GetRowElements()
{
SaveReferences();
return(aelRows);
}
function GetFirstRowCells()
{
SaveReferences();
return(aelCells);
}
function PrepareGrid()
{
// only need to do this if the data is dirty
if (!blnDirty) return;
blnDirty = false;
var aelRows = GetRowElements();
iVisibleRows = Math.min(iRowCount, Math.ceil(iNumPages / iColCount));
// reset all the nodes
for (var i=0; i < aelRows.length; i++)
{
for (var j=0; j < aelRows[i].childNodes.length; j++)
{
aelRows[i].childNodes[j].className = '';
}
}
// remove all the current rows, and add back only the ones we need 
var tbody = $(oThis.htIds['tblPagePicker']).childNodes[0];
var aCurrentRows = tbody.childNodes;
for (var i=aCurrentRows.length-1; i >= 0; i--) tbody.removeChild(aCurrentRows[i]);
for (var i=0; i < Math.min(iVisibleRows, aelRows.length); i++) tbody.appendChild(aelRows[i]);
// remove all the current cells from first row, and add back only the ones we need 
if (aCurrentRows.length > 0)
{
var aelCells = GetFirstRowCells();
for (var i=aCurrentRows[0].childNodes.length-1; i >= 0; i--) aCurrentRows[0].removeChild(aCurrentRows[0].childNodes[i]);
for (var i=0; i < Math.min(iNumPages, aelCells.length); i++)
{
aCurrentRows[0].appendChild(aelCells[i]);
} 
}
}
function ClearHighlightedBoxes()
{
function ResetBox(i)
{
if (i != -1) $(oThis.htIds['dropPager_span.' + i]).className = '';
}
ResetBox(iPickerActive);
iPickerActive = -1;
ResetBox(iPickerCurrent);
iPickerCurrent = -1;
}
function SetBoxesData(iFirstPage, iLastPage)
{
var iCount = (iVisibleRows > 1) ? (iVisibleRows * iColCount) : iNumPages;
for (var i = 0; i < iCount; i++)
{
var iPageNum = i + iFirstPage;
var el = $(oThis.htIds['dropPager_span.' + i]);
el.innerHTML = iPageNum;
el.style.visibility = (iPageNum <= iNumPages) ? 'visible' : 'hidden';
if (iCurrentPage == iPageNum)
{
el.className = 'current';
iPickerCurrent = i;
}
}
}
function SetPagingRegions(iFirstPage, iLastPage)
{
function PageSet(str, bln, iFirst, iLast)
{
if (bln)
{
$(oThis.htIds['pagePicker' + str + 'First']).innerHTML = iFirst;
$(oThis.htIds['pagePicker' + str + 'Last']).innerHTML = iLast;
}
$(oThis.htIds['pagePicker' + str + 'Region']).style.display = (iNumPages <= iPagePickerGridCount) ? 'none' : 'block';
$(oThis.htIds['pagePicker' + str + 'Region']).style.visibility = bln ? 'visible' : 'hidden';
}
PageSet('Back', (iFirstPage > 1), iFirstPage - iPagePickerGridCount, iFirstPage - 1);
PageSet('Next', (iNumPages > iLastPage), iLastPage + 1, Math.min(iNumPages, iLastPage + iPagePickerGridCount));
}
function SetSizeAndVisibility()
{
var elPickerRegion = $(oThis.htIds['pagePickerRegion']);
var elControlsRegion = $(oThis.htIds['controlsRegion']);
elPickerRegion.style.visibility = 'hidden';
elPickerRegion.style.display = 'block';
elPickerRegion.style.width = 'auto';
var tbl = $(oThis.htIds['tblPagePicker']);
elPickerRegion.style.right = "";
tbl.style.width = 'auto';
if (iNumPagePages > 1)
{
var iPickerRegionWidth = Math.max(elControlsRegion.clientWidth, elPickerRegion.clientWidth);
elPickerRegion.style.width = iPickerRegionWidth + "px";
tbl.style.width = '100%';
}
var iDiff = elControlsRegion.clientWidth - elPickerRegion.clientWidth;
if (elPickerRegion.parentNode)
{
elPickerRegion.parentNode.removeChild(elPickerRegion);
var pt = Btv.Dom.GetAbsPos(elControlsRegion);
document.body.appendChild(elPickerRegion);
}
elPickerRegion.style.top = (pt.y + elControlsRegion.clientHeight + 10) + 'px';
if ((d.align == 'center') || ((iNumPagePages == 1) && (iDiff > 0)))
{
elPickerRegion.style.left = (pt.x + Math.floor(iDiff / 2)) + "px";
}
else if (d.align == 'left')
{
elPickerRegion.style.left = pt.x + 'px';
}
else
{
elPickerRegion.style.left = (pt.x + elControlsRegion.clientWidth - elPickerRegion.clientWidth) + "px";
}
elPickerRegion.style.visibility = 'visible';
}
iPagePage = iPagePage_;
var iFirstPage = (iPagePage * iPagePickerGridCount) + 1;
var iLastPage = iFirstPage + iPagePickerGridCount - 1;
PrepareGrid();
ClearHighlightedBoxes();
SetBoxesData(iFirstPage, iLastPage);
SetPagingRegions(iFirstPage, iLastPage);
SetSizeAndVisibility();
}
function PickerDisplayHandler(bln)
{
if (bln)
{
Prepare(Math.floor(iCurrentPage / iPagePickerGridCount));
}
else
{
$(oThis.htIds['pagePickerRegion']).style.display = 'none';
}
}
oPagePicker.SetActive = function(i)
{
if (iPickerActive != i)
{
if (iPickerActive != -1)
{
$(oThis.htIds['dropPager_span.' + iPickerActive]).className = '';
}
if (i != iPickerCurrent)
{
iPickerActive = i;
if (iPickerActive != -1)
{
$(oThis.htIds['dropPager_span.' + i]).className = 'active';
}
}
}
}
oPagePicker.Pick = function(i)
{
var iNewPage = (iPagePage * iPagePickerGridCount) + i + 1;
if (iNewPage != iCurrentPage)
{
oPagePicker.oPickerTracker.Out(true);
fncGoTo(iNewPage);
}
}
oPagePicker.oPickerTracker = new Btv.UI.MouseInRegionTracker(PickerDisplayHandler, iOpenDelay, iCloseDelay);
}
var blnBackOn = true; 
var blnNextOn = true; 
oThis.ElementProps = function(id, scope, name, isInit, params, ht)
{
switch(scope)
{
case "pager":
ht.style.display = ((iPage > 0) && (iPages > 1)) ? 'block' : 'none';
if (isInit)
{
ht.style['margin-left'] = ht.style['margin-right'] = 'auto';
if (d.align)
{
if (d.align == 'left') ht.style['margin-left'] = '0px';
if (d.align == 'right') ht.style['margin-right'] = '0px';
}
}
break;
case "currentPage":
ht.innerHTML = iPage;
break;
case "totalPages":
ht.innerHTML = iPages;
break;
case "dropPager_span":
if (isInit)
{
ht.attr.onmouseover = $F('{0}({1})', $OG(oPagePicker.SetActive), params);
ht.attr.onmouseout = $F('{0}({1})', $OG(oPagePicker.SetActive), -1);
ht.attr.onclick = $F('{0}({1})', $OG(oPagePicker.Pick), params);
} 
break;
case "controlsRegion":
ht.style['text-align'] = d.align;
break;
case "backRegion":
if (isInit) ht.style.zoom = 1;
var blnOn = ((iPage > 1) || d.blnLoop);
if (blnBackOn != blnOn) Btv.UI.Opacity.Set(ht, (blnOn ? 100 : 40))
blnBackOn = blnOn;
//if (!isInit) ht.style.visibility = ((iPage > 1) || d.blnLoop) ? 'visible' : 'hidden';
break;
case "nextRegion":
if (isInit) ht.style.zoom = 1;
var blnOn = ((iPage < iPages) || d.blnLoop);
if (blnNextOn != blnOn) Btv.UI.Opacity.Set(ht, (blnOn ? 100 : 40))
blnNextOn = blnOn;
//if (!isInit) ht.style.visibility = ((iPage < iPages) || d.blnLoop) ? 'visible' : 'hidden';
break;
case "lnkFirst":
if (isInit)
{
ht.attr.href = $F('javascript:{0}(1)', $OG(GoTo));
if (d.classes && d.classes['NavFirst']) ht.attr['class'] = d.classes['NavFirst'];
} 
break;
case "lnkLast":
if (isInit)
{
ht.attr.href = $F('javascript:{0}(Number.MAX_VALUE)', $OG(GoTo));
if (d.classes && d.classes['NavLast']) ht.attr['class'] = d.classes['NavLast'];
} 
break;
case "lnkNext":
if (isInit) ht.attr.href = $F('javascript:{0}(1)', $OG(GoBy));
break;
case "lnkBack":
if (isInit) ht.attr.href = $F('javascript:{0}(-1)', $OG(GoBy));
break;
case "pagePickerHandler":
if (isInit) ht.style.cursor = "pointer";
case "pagePickerRegion":
if (isInit) ht.attr.onmouseout = $F('{0}()', $OG(oPagePicker.oPickerTracker.Out));
if (isInit) ht.attr.onmouseover = $F('{0}()', $OG(oPagePicker.oPickerTracker.In));
break;
case "lnkPagePickerBack":
if (isInit) ht.attr.href = $F('javascript:{0}(-1)', $OG(oPagePicker.ChangeBy));
break;
case "lnkPagePickerNext":
if (isInit) ht.attr.href = $F('javascript:{0}(1)', $OG(oPagePicker.ChangeBy));
break;
}
}
oThis.DeclareVirtualMethods({
Render: fncMain
});
var oPagePicker = oThis.oPagePicker = new PagePicker(10, 10, 250, 200, GoTo);
oPagePicker.SetData(iPages, iPage);
})($data, Main);
_write('\n');}return $text.join("");}},{id:"Photos2.ImageThumbnailSummary",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('  style=\"float:left; width:104px; padding-bottom:10px; zoom:1;');_write(o.Style());_write('\">');_write(o.InnerHTML());_write('\n<div ');_write(o.Elem('BackgroundRegion'));_write('  style=\"background-color:transparent; padding:2px 5px 5px 5px; margin:4px;');_write(o.Style());_write('\">');_write(o.InnerHTML());_write('<div ');_write(o.Elem('CheckboxRegion'));_write('  style=\"display:none; margin-bottom:3px;');_write(o.Style());_write('\">');_write(o.InnerHTML());_write('<input ');_write(o.Elem('chk'));_write('  type=\"checkbox\" onclick=\"');_write($OG(ht.fncCheckClick));_write('()\" style=\"');_write(o.Style());_write('\">');_write(o.InnerHTML());_write('</input><input ');_write(o.Elem('ordinal'));_write('  type=\"input\" style=\"width:50px; margin-left:20px;');_write(o.Style());_write('\">');_write(o.InnerHTML());_write('</input></div>\n<div>\n<div ');_write(o.Elem('ImageWrapper'));_write('  class=\"photo09_thumb_view_imgwrapper\" style=\"zoom:1; margin-left:2px;');_write(o.Style());_write('\">');_write(o.InnerHTML());_write(ht.fncRenderImage());_write('</div>\n<div ');_write(o.Elem('Footer'));_write('  style=\"text-align:center;');_write(o.Style());_write('\">');_write(o.InnerHTML());_write('\n<div ');_write(o.Elem('RatingCount'));_write('  class=\"photo09_thumb_view\" style=\"');_write(o.Style());_write('\">');_write(o.InnerHTML());_write('</div>\n<div ');_write(o.Elem('CommentCount'));_write('  class=\"photo09_thumb_comment\" style=\"');_write(o.Style());_write('\">');_write(o.InnerHTML());_write('</div>\n</div>\n</div>\n</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 oImg;
    var sizeImageBounds = { width: 80, height: 80 };
    var blnDisabled = false;

    function OnClick()
    {
        d.fncClick(d.id);
    }


    function BuildImageInfo()
    {
        if (d.info)
        {
            var oImageView = Btv.UI.Images.FindView(d.info.Views, sizeImageBounds, true);
            if (oImageView) return({Src: oImageView.Src, Size: {width: oImageView.Width, height: oImageView.Height}});
        }
        return(null);
    }


    function RenderImage()
    {
        oImg = Btv.Templating.GetInstance("SmartImage", {
                sizeBounds: sizeImageBounds
                , doCrop: true
                , ImageInfo: BuildImageInfo()
                , oCropAnchor: { width: .5, height: .2 }
                , link:{href: $F('javascript:{0}()', $OG(OnClick))}
                , ChangeStrategy: 'Hide'
            });
        return(oImg.Render());
    }



    function Render()
    {
        if (d.blnNoFooter) oElMan.Style('Footer', 'display', 'none');
        return (htUI.Main(oThis, { fncRenderImage: RenderImage, fncCheckClick: CheckClick }));
    }


    oThis.IsChecked = function()
    {
        return (blnChecked);
    }


    oThis.GetOrdinal = function()
    {
        return (parseFloat($(oThis.htIds['ordinal']).value));
    }


    oThis.SetChecked = function(bln)
    {
        if (blnDisabled) return;
        blnChecked = bln;
        oElMan.Attribute('chk', 'checked', bln);
        oThis.RefreshElements();
    }

    function CheckClick()
    {
        oThis.SetChecked($(oThis.htIds['chk']).checked);
    }


    oThis.AdminMode = function(bln)
    {
        blnAdmin = bln;
        oElMan.Style('CheckboxRegion', 'display', bln ? 'block' : 'none');
        if (bln) oElMan.Attribute('chk', 'checked', false);
        blnChecked = false;
        oThis.RefreshElements();
    }
    
    
    var blnChecked = false;
    var blnAdmin = false;


    oThis.SetData = function(info, blnDisabled_) {
        function UpdateImage() {
            oImg.UpdateImage(BuildImageInfo());
            oThis.RefreshElements();
            oThis.UpdateElements();
        }

        blnDisabled = !!blnDisabled_;
        d.info = info;
        oThis.StateChanged(UpdateImage);
    }

    oThis.RefreshElements = function()
    {
        oElMan.Attribute('chk', 'disabled', blnDisabled);
        var strColor = blnDisabled ? '#888888' : (blnChecked ? '#00cc00' : '#cccccc');
        oElMan.Style('BackgroundRegion', 'background-color', (blnAdmin ? strColor : 'transparent'));
    }

    oThis.ElementProps = function(id, scope, name, isInit, params, ht)
    {
        switch (scope)
        {
            case "Root":
                ht.style.display = (d.info) ? 'block' : 'none';
                break;
            case "RatingCount":
                if (d.info) ht.innerHTML = d.info.Ratings ? Math.round(d.info.Ratings.RatingAvg / 2) : '';
                break;
            case "CommentCount":
                if (d.info) ht.innerHTML = (d.info.CommentCount != undefined) ? d.info.CommentCount : '';
                break;
            case "ImageWrapper":
                if (isInit) Btv.Styles.SetSize(ht, sizeImageBounds);
                break;
            case "ordinal":
                if (d.info) ht.attr.value = d.info.OrdinalIndex;
                break;
        }
    }


    oThis.DeclareVirtualMethods({
        Render: Render
    });
        
})($data, {Main:Main});
_write('\n');}return $text.join("");}},{id:"Photos2.CategoryViewer",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');_write(ht.Breadcrumb.Render());_write('\n<div class=\"show_page08_left\">\n<div ');_write(o.Elem('Root'));_write('  class=\"photo09_albums\" style=\"');_write(o.Style());_write('\">');_write(o.InnerHTML());_write('\n');_write(ht.AdminHeader.Render());_write('\n');_write(ht.SubcategoryView.Render());_write('\n');_write(ht.AlbumView.Render());_write('\n');_write(ht.PopularImages.Render());_write('\n</div>\n</div>\n<div class=\"show_page08_right\">\n<div id=\"btv_aja_right300x250Ad\" class=\"ad300\">\n');_write(ht.AdText);_write('\n</div>\n');_write(ht.LatestImages.Render());_write('\n<center>\n<div>\n<link rel=\"stylesheet\" type=\"text/css\" href=\"http://cache.blogads.com/801282331/feed.css\" />\n<script language=\"javascript\" src=\"http://cache.blogads.com/801282331/feed.js\"></script> \n</div>\n</center>\n</div>\n</div>\n');;return($text.join(""));};Version3 = function(o, ht) {var $text = [];var _write = function(text) {$text.push((typeof text == "number")?text:(text||""));};_write('\r\n\n<div style=\"width:100%\">\n');_write(ht.Breadcrumb.Render());_write('\n');_write(ht.AdminHeader.Render());_write('\n<div style=\"display:none\">\n');_write(ht.PopularImages.Render());_write('\n');_write(ht.LatestImages.Render());_write('\n</div>\n<div ');_write(o.Elem('Root'));_write('  class=\"photo09_albums\" style=\"');_write(o.Style());_write('\">');_write(o.InnerHTML());_write('\n');_write(ht.SubcategoryView.Render());_write('\n');_write(ht.AlbumView.Render());_write('\n</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 oSubcategoryView, oAlbumView, oAdminHeader, oBreadcrumb;
    var blnAdminMode = false;

    function AdminData2(blnAdminMode_, oPermissions_)
    {
        if (!blnCheckOnce)
        {
            blnCheckOnce = true;
            blnAdminMode = blnAdminMode_;
        }
    }
    Btv.Admin.Subscribe(AdminData2);
    var blnCheckOnce = false;


    function Render() {
        var oModel = new Model(d.affiliateId, d.oDataSource, d.fncGetCategory, d.fncUpdateAlbum);
        oBreadcrumb = Btv.Templating.GetInstance("Photos2.CategoryBreadcrumb", { albumTree: oModel.Breadcrumbs });

        oAdminHeader = Btv.Templating.GetInstance('Photos2.AdminHeader', {
            Model: oModel
            , strContextName: 'Category'
        });

        oSubcategoryView = Btv.Templating.GetInstance('Photos2.SubcategoryViewer', {
            Model: oModel
            , Display: false
            , viewerUrlFormat: d.viewerUrlFormat
        });

        oAlbumView = Btv.Templating.GetInstance('Photos2.AlbumViewer', {
            Model: oModel
            , Display: false
            , viewerUrlFormat: d.viewerUrlFormat
        });

        InitBreadcrumb(oModel);
        var oLatestImages = Btv.Templating.GetInstance("Photos2.ImageModule", { title: 'Latest Additions', images: oModel.LatestImages, Display: false, numberOfColumns: 3, hideInfo: true, classNames: 'photo09_photo_condensed', Model: oModel });
        var oPopularImages = Btv.Templating.GetInstance("Photos2.ImageModule", { title: 'Popular Photos', images: oModel.PopularImages, Display: false, numberOfColumns: 6, hideInfo: false, classNames: 'photo09_photo', Model: oModel });
        var oState = { affiliateId: (d.affiliateId || 0), albumId: (oModel.Album.Id || 0), categoryFirstIndex: 1, albumFirstIndex: 1, initial: true };
        var oController = new Controller(oState, oModel, oBreadcrumb, oAdminHeader, oSubcategoryView, oAlbumView, oLatestImages, oPopularImages);

        var adText = d.adText.replace(/&lt;/g, "<").replace(/&gt;/g, ">").replace(/&quote;/g, "\"");

        var strUIFunction = (Btv.iPageVersion == 3) ? "Version3" : "Main";
        
        return (htUI[strUIFunction](oThis, {Breadcrumb: oBreadcrumb,
                                AdminHeader: oAdminHeader, 
                                SubcategoryView: oSubcategoryView, 
                                AlbumView: oAlbumView, 
                                PopularImages: oPopularImages,
                                LatestImages: oLatestImages,
                                AdText: adText
                            }));
    }

    function Model(iAffiliateId, oDataSource, fncGetCategory, fncUpdateAlbum) {
        var oModel = this;
        oModel.AffiliateId = iAffiliateId;

        LoadData(oDataSource);

        oModel.BreadcrumbHistory = '';
        oModel.CategoryCurrentPage = 1;
        oModel.AlbumCurrentPage = 1;
        oModel.CategoryPageSize = d.iPageSize || ((Btv.iPageVersion == 3) ? 12 : 12);
        oModel.AlbumPageSize = ((Btv.iPageVersion == 3) ? 9 : 10);
        
        oModel.onAlbumInfoChange = new Btv.Event();
        oModel.onCategoryChange = new Btv.Event();
        oModel.onChangeLatestImages = new Btv.Event();
        oModel.onChangePopularImages = new Btv.Event();


        oModel.GetBreadCrumbHistory = function()
        {
            return (oModel.BreadcrumbHistory);
        }

        function LoadData(oDataSource) {
            for (var i = 0; i < oDataSource.length; i++) {
                var label = oDataSource[i][0];
                
                switch (label) {
                    case 'album':
                        oModel.Album = oDataSource[i][1];
                        AdjustAlbumObject(oModel.Album);
                        break;
                    case 'popularImages':
                        oModel.PopularImages = oDataSource[i][1];
                        break;
                    case 'latestImages':
                        oModel.LatestImages = oDataSource[i][1];
                        break;
                    case 'breadcrumb':
                        oModel.Breadcrumbs = oDataSource[i][1];
                        break;
                }
            }
        }


        function AdjustAlbumObject(oAlbum)
        {
            oAlbum.ChildrenCategoryWithEmptyTotal = oAlbum.ChildrenCategoryTotal;
            oAlbum.ChildrenAlbumWithEmptyTotal = oAlbum.ChildrenAlbumTotal;

            if (!blnAdminMode)
            {
                var a = [];
                for (var i = 0; i < oAlbum.ChildrenCategories.length; i++)
                {
                    if (oAlbum.ChildrenCategories[i].HasImages) a.push(oAlbum.ChildrenCategories[i]);
                    AdjustAlbumObject(oAlbum.ChildrenCategories[i]);
                }
                oAlbum.ChildrenCategories = a;
                oAlbum.ChildrenCategoryTotal = oAlbum.ChildrenCategoryNonEmptyTotal;
                oAlbum.ChildrenAlbumTotal = oAlbum.ChildrenAlbumNonEmptyTotal;
            }

            if (!oAlbum._TotalCategories)
            {
                oAlbum._TotalCategories = oAlbum.ChildrenCategoryTotal + oAlbum.ChildrenAlbumTotal;
            }
        }



        oModel.FetchNewCategoryData = function(initialState, iAlbumId, iCategoryFirstIndex, iAlbumFirstIndex) {
            function haveData(data) {
                if (data) {
                    LoadData(data);
                    oModel.CategoryCurrentPage = Math.floor(iCategoryFirstIndex / oModel.CategoryPageSize) + 1;
                    oModel.AlbumCurrentPage = Math.floor(iAlbumFirstIndex / oModel.AlbumPageSize) + 1;
                    oModel.onCategoryChange.Fire(true);
                    oModel.onAlbumInfoChange.Fire();
                    oModel.onChangeLatestImages.Fire();
                    oModel.onChangePopularImages.Fire();
                }
            }
            
            if (initialState) {
                haveData(oDataSource);
            }
            else {
                var iContentScopeId = -1;
                var iContentId = -1;
                var iCategoryLastIndex = iCategoryFirstIndex + oModel.CategoryPageSize - 1;
                var iAlbumLastIndex = iAlbumFirstIndex + oModel.AlbumPageSize - 1;
                fncGetCategory(oModel.AffiliateId,
                                        iAlbumId,
                                        iContentScopeId,
                                        iContentId,
                                        iCategoryFirstIndex,
                                        iCategoryLastIndex,
                                        iAlbumFirstIndex,
                                        iAlbumLastIndex,
                                        oModel.BreadcrumbHistory,
                                        '',
                                        haveData);
           }
        }

        oModel.SaveAlbum = function(oAlbum, fnc)
        {
            function Done(o)
            {
                if (o)
                {
                    oModel.Album.Title = oAlbum.Title;
                    oModel.Album.Description = oAlbum.Description;
                    oModel.onAlbumInfoChange.Fire();
                }
                fnc();
            }
            fncUpdateAlbum(oAlbum, Done);
        }
    }

    function Controller(oState, oModel, oBreadcrumb, oAdminHeader, oSubcategoryView, oAlbumView, oLatestImages, oPopularImages)
    {        
        oController = this;
        var blnDoHistory = !Btv.Browser.isGecko;
        
        var strModuleName = 'GalleryCategoryViewer';
        var initialState = YAHOO.lang.JSON.stringify(oState);
        if (blnDoHistory) initialState = YAHOO.util.History.getBookmarkedState(strModuleName) || YAHOO.lang.JSON.stringify(oState); 

        function AddHistoryState()
        {
            function AdDelay()
            {
                Btv.Ads.Change();
            }
            
            if (!oState.initial)
            {
                var strState = YAHOO.lang.JSON.stringify(oState);
                if (blnDoHistory) {
                   YAHOO.util.History.navigate(strModuleName, strState);
                }
                else
                {
                    StateChangeHandler(strState);
                }                    
                window.setTimeout(AdDelay, 500);
            }
        }

        function StateChangeHandler(strState) {
            
            var oNextState = YAHOO.lang.JSON.parse(strState);
            var blnSameView = (oNextState.view == oState.view);

            oModel.AffiliateId = oNextState.affiliateId;
            
            if (!oNextState.categoryFirstIndex) {
                oNextState.categoryFirstIndex = 1;
            }

            if (!oNextState.albumFirstIndex) {
                oNextState.albumFirstIndex = 1;
            }
            
            oModel.FetchNewCategoryData(oNextState.initial, oNextState.albumId, oNextState.categoryFirstIndex, oNextState.albumFirstIndex);
            
            oState = oNextState;
            delete (oState.initial);
        }
        
        if (blnDoHistory) YAHOO.util.History.register(strModuleName, initialState, StateChangeHandler);
        
        function FetchNewCategoryData(albumId)
        {
            oState.albumId = albumId;
            oState.categoryFirstIndex = 1;
            oState.albumFirstIndex = 1;
            AddHistoryState();
        }

        function FetchNewCategoryPage(firstIndex) {
            oState.categoryFirstIndex = firstIndex;
            AddHistoryState();
        }

        function FetchNewAlbumPage(firstIndex) {
            oState.albumFirstIndex = firstIndex;
            AddHistoryState();
        }

        function DisplayViews()
        {
            if(oModel.Album.ChildrenCategories.length == 0){
                oSubcategoryView.Display(false);
            }
            else{
                oSubcategoryView.Display(true);
            }
            
            if((oModel.Album.ChildrenAlbums.length == 0) || (oModel.Album.ChildrenCategories.length > 0)){
                oAlbumView.Display(false);
            }
            else{
                oAlbumView.Display(true);
            }

            if (oModel.LatestImages.length == 0) {
                oLatestImages.Display(false);
            }
            else {
                oLatestImages.Display(true);
            }

            if (oModel.PopularImages.length == 0) {
                oPopularImages.Display(false);
            }
            else {
                oPopularImages.Display(true);
            }
        }

        function AddBreadcrumb(albumId, albumTitle, url) {
            if (iFirstBreadCrumbID == -100)
            {
                iFirstBreadCrumbID = albumId;
            }

            //var strTitle = ((iFirstBreadCrumbID == albumId) && (d.blnVersion == 3)) ? $F("All {0} Photos", albumTitle) : albumTitle;
            var strTitle = albumTitle;
            oBreadcrumb.AddCrumb(albumId, strTitle, url);
            oModel.BreadcrumbHistory = oBreadcrumb.GetBreadcrumbHistory();
        }
        var iFirstBreadCrumbID = -100;
        
        function ChangeLatestImages(){
            oLatestImages.SetData(oModel.LatestImages);
        }
        
        function ChangePopularImages(){
            oPopularImages.SetData(oModel.PopularImages);
        }

        oSubcategoryView.onPageChange.Attach(FetchNewCategoryPage);
        oSubcategoryView.onClickSubcategory.Attach(FetchNewCategoryData);
        oSubcategoryView.onAddBreadcrumb.Attach(AddBreadcrumb);
        oAlbumView.onPageChange.Attach(FetchNewAlbumPage);
        oModel.onCategoryChange.Attach(DisplayViews);
        oModel.onChangeLatestImages.Attach(ChangeLatestImages);
        oModel.onChangePopularImages.Attach(ChangePopularImages);

        function AdminDataChange(strName, oValue, fncDone)
        {
            var oAlbumInfo = oModel.Album;
            var oAlbum = {
                Id: oAlbumInfo.Id
                , AffiliateId: oAlbumInfo.AffiliateId
                , Title: oAlbumInfo.Title
                , Description: oAlbumInfo.Description
                , DateCreated: oAlbumInfo.DateCreated
                , DateUpdated: oAlbumInfo.DateUpdated
                , CoverImageId: oAlbumInfo.CoverImageId
            };
            oAlbum[strName] = oValue;
            oModel.SaveAlbum(oAlbum, fncDone);
        }
        oAdminHeader.SetDataChangeFunction(AdminDataChange);

        function DeleteAlbum(albumID)
        {
            function Done(o)
            {
                if (o)
                {
                    if (o.Success)
                    {
                        var parentAlbumID = o.ParentAlbumIds[0];
                        document.location.replace('/photos/category.aspx?aid=' + parentAlbumID);
                        return;
                    }
                }
                Btv.WaitingDialog.Hide();
                Btv.SimpleDialog.Show('', 'This category cannot be deleted.', Btv.SimpleDialog.buttonsOK);
            }

            function Confirm(bln)
            {
                if (bln)
                {
                    Btv.WaitingDialog.Show("Deleting category...");
                    d.fncRemoveAlbum(albumID, false, Done);
                }
            }

            Btv.SimpleDialog.Show('Confirmation', 'This will permanently delete this category from the system.  This category will no longer appear in any of it\'s parent categories.<br /><br />Do you want to delete this category?', Btv.SimpleDialog.buttonsYesNo, null, Confirm);
        }
        
        
        function AddAlbumCategory(parentAlbumID, blnIsCategory, strItemName)
        {
            function DoCreate(bln, strNewValue, fncClose)
            {
                function CreateDone(iAlbumID)
                {
                    Btv.WaitingDialog.Hide();
                    if (iAlbumID && (iAlbumID != -1))
                    {
                        var strUrl = $F((blnIsCategory ? strCategoryUrlTemplate : strAlbumUrlTemplate), iAlbumID);
                        document.location.href = strUrl;
                    }
                }
                
                
                fncClose();
                
                if (bln)
                {
                    fncCreateChildAlbum(parentAlbumID, strNewValue, strNewValue, blnIsCategory, CreateDone);
                    Btv.WaitingDialog.Show($F('Creating{0}', strItemName));
                }
            }
            oDialogPrompt.Display($F('Create new {0}', strItemName), $F('Enter {0} title', strItemName), '', null, DoCreate);
        }
        var strCategoryUrlTemplate = '/photos/category.aspx?aid={0}';
        var strAlbumUrlTemplate = '/photos/galleryviewer.aspx?ai={0}';
        var oDialogPrompt = Btv.Templating.GetInstance('Dialog.Prompt', {});
        var fncCreateChildAlbum = Btv.Ajax.MakeFunction(Btv.Photos.DataQueries, 'CreateChildAlbum');

        
        function AddCategory(albumID)
        {
            AddAlbumCategory(albumID, true, 'category');
        }

        function AddAlbum(albumID)
        {
            AddAlbumCategory(albumID, false, 'album');
        }


        function CopyMoveAlbums(parentAlbumID, blnMove)
        {
            function HavePicker()
            {
                function CategoryAlbumPickerDone(bln)
                {
                    function CopyDone(bln)
                    {
                        if (bln)
                        {
                            document.location.href = $F(strCategoryUrlTemplate, parentAlbumID);
                        }
                        else
                        {
                            Btv.WaitingDialog.Hide();
                            Btv.SimpleDialog.Show('', $F('The {0} failed.', strAction) , Btv.SimpleDialog.buttonsOK);
                        }
                    }
                    
                    function Go()
                    {
                        var aAlbums = Btv.Util.ExtractArrays(oInfo.Albums, ['Id']).Id;
                        var aParents = Btv.Util.ExtractArrays(oInfo.Parents, ['Id']).Id;
                        for (var i=0; i < aParents.length; i++)
                        {
                            if (aParents[i] == undefined) aParents[i] = -1;
                        }
                        fncCopyAlbums(parentAlbumID, aAlbums, blnMove ? aParents : null, CopyDone)
                    }

                    if (bln)
                    {
                        var oInfo = oCatAlbumPicker.GetAlbumsExt(true);
                        Btv.WaitingDialog.Show(blnMove ? "Moving categories/albums..." : "Copying categories/albums...");
                        window.setTimeout(Go, 1);
                    }
                }
                oCatAlbumPicker.Collapse();
                albumPickerDialog.Show($F('Choose categories/albums to {0} to this category', strAction), null, Btv.SimpleDialog.buttonsCancelOK, null, CategoryAlbumPickerDone);
            }

            function Available()
            {
                Btv.WaitingDialog.Hide();
                oCatAlbumPicker = Btv.Templating.GetInstance('Photos2.Admin.CategoryAlbumPicker', {
                    Album: oModel.Album
                    });
                albumPickerDialog = Btv.SimpleDialog.GetInstance();
                albumPickerDialog.SetBody(oCatAlbumPicker.Render());
                HavePicker();
            }

            var strAction = blnMove ? 'move' : 'copy';
            if (oCatAlbumPicker)
            {
                HavePicker();
            }
            else
            {
                Btv.WaitingDialog.Show("Loading...");
                Btv.Templating.NotifyWhenAvailable('Photos2.Admin.CategoryAlbumPicker', Available);
            }
        }
        var oCatAlbumPicker;
        var albumPickerDialog;
        var fncCopyAlbums = Btv.Ajax.MakeFunction(Btv.Photos.DataQueries, 'CopyAlbums');
        


        function CopyAlbums(albumID)
        {
            CopyMoveAlbums(albumID, false);
        }

        function MoveAlbums(albumID)
        {
            CopyMoveAlbums(albumID, true);
        }
        
        
        
        function RemoveChildren(albumID, blnCategories)
        {
            function HavePicker()
            {
                function CategoryAlbumPickerDone(bln)
                {
                    function RemovalDone(bln)
                    {
                        if (bln)
                        {
                            document.location.href = $F(strCategoryUrlTemplate, albumID);
                        }
                        else
                        {
                            Btv.WaitingDialog.Hide();
                            Btv.SimpleDialog.Show('', $F('The {0} could not be removed.', strNoun), Btv.SimpleDialog.buttonsOK);
                        }
                    }
                    
                    function Go()
                    {
                        var aAlbums = Btv.Util.ExtractArrays(aoAlbums, ['Id']).Id;
                        if (aAlbums && aAlbums.length) fncRemoveChildAlbums(aAlbums, albumID, RemovalDone)
                    }

                    if (bln)
                    {
                        var aoAlbums = oChildPicker.GetAlbums(true);
                        Btv.WaitingDialog.Show($F('Removing {0}...', strNoun));
                        window.setTimeout(Go, 1);
                    }
                }
                
                var oChildPicker = Btv.Templating.GetInstance('Photos2.Admin.CategoryAlbumPicker', {
                    Album: oModel.Album
                    , rootAlbumId: albumID
                    , blnOnlyDirectChildren: true
                    , iCategoryChildren: blnCategories ? 1 : 0
                    });
                childPickerDialog.Show($F('Choose {0} to remove from this category', strNoun), oChildPicker.Render(), Btv.SimpleDialog.buttonsCancelOK, null, CategoryAlbumPickerDone);
            }


            function Available()
            {
                Btv.WaitingDialog.Hide();
                childPickerDialog = Btv.SimpleDialog.GetInstance();
                HavePicker();
            }

            var strNoun = blnCategories ? 'sub-categories' : 'albums';
            if (childPickerDialog)
            {
                HavePicker();
            }
            else
            {
                Btv.WaitingDialog.Show("Loading...");
                Btv.Templating.NotifyWhenAvailable('Photos2.Admin.CategoryAlbumPicker', Available);
            }
        }
        var childPickerDialog;
        var fncRemoveChildAlbums = Btv.Ajax.MakeFunction(Btv.Photos.DataQueries, 'RemoveChildAlbums');


        function RemoveCategories(albumID)
        {
            RemoveChildren(albumID, true);
        }

        function RemoveAlbums(albumID)
        {
            RemoveChildren(albumID, false);
        }


        oAdminHeader.SetActions(
            [
                { strLabel: 'Delete this Category', strClass: 'admin-delete-btn', fnc: DeleteAlbum }
                ,{ strLabel: 'Remove SubCategories', strClass: 'admin-delete-btn', fnc: RemoveCategories }
                ,{ strLabel: 'Remove Albums', strClass: 'admin-delete-btn', fnc: RemoveAlbums }
                ,{ strLabel: 'Add New Category', strClass: 'admin-add-btn', fnc: AddCategory }
                ,{ strLabel: 'Add New Album', strClass: 'admin-add-btn', fnc: AddAlbum }
                ,{ strLabel: 'Copy Existing', strClass: 'admin-add-btn', fnc: CopyAlbums }
                ,{ strLabel: 'Move Existing', strClass: 'admin-add-btn', fnc: MoveAlbums }
            ]
        );


        oAdminHeader.Display(false);


        function SetPhotosOrder()
        {
            function Done()
            {
                Btv.WaitingDialog.Hide();
                window.location.href = Btv.Url.AddQuerystringParam(window.location.href, "btvnocache", "1");
            }

            var oData = oSubcategoryView.GetOrdinalValues();
            if (oData.ids.length)
            {
                Btv.WaitingDialog.Show("Setting album order for this category...");
                d.fncUpdateCategoryAlbumOrdinal(oModel.Album.AffiliateId, oModel.Album.Id, oData.ids, oData.ordinals, Done)
            }
        }

        if (oSubcategoryView) oSubcategoryView.SetActions(
            [
                { strLabel: 'Set Album/Category Order', strClass: 'admin-pen-btn', fnc: SetPhotosOrder }
            ]
        );



        function InitHtml(el){
            StateChangeHandler(initialState);
        }
        
        if (blnDoHistory)
        {
            YAHOO.util.History.onReady(function()
            {
                StateChangeHandler(YAHOO.util.History.getCurrentState(strModuleName));
            });
            YAHOO.util.History.initialize("yui-history-field", "yui-history-iframe");
        }
        else
        {   
            fncOnDomReady = InitHtml;
        }
        
        var oPermissions;
        function AdminData(blnAdminMode_, oPermissions_)
        {
            oPermissions = oPermissions_;
            var bln = blnAdminMode_;// && oPermissions && oPermissions.HasPermission(oModel.Album.AffiliateId, 'ManagePhotoAlbums');
            if (blnAdminMode != bln)
            {
                blnAdminMode = bln;
                oAdminHeader.Display(bln);
                oSubcategoryView.AdminMode(bln);
            }
        }
        
        function RefreshAdminData()
        {
            AdminData(blnAdminMode, oPermissions)
        }
        oAdminHeader.Display(blnAdminMode);
        oSubcategoryView.AdminMode(blnAdminMode);
        
        Btv.Admin.Subscribe(AdminData);
        oModel.onCategoryChange.Attach(RefreshAdminData);
    }

    function InitBreadcrumb(oModel) {
        function OnClickHandler(albumId) {
            oSubcategoryView.onClickSubcategory.Fire(albumId);
        }
    
        var url = $F('javascript:{0}({1})', $OG(OnClickHandler), oModel.Album.Id);
        for (var i = 0; i < oBreadcrumb.GetAlbumTree().length; i++) {
            var albumTreeUrl = $F('javascript:{0}({1})', $OG(OnClickHandler), oBreadcrumb.GetAlbumTree()[i].Id);
            oBreadcrumb.AddCrumb(oBreadcrumb.GetAlbumTree()[i].Id, oBreadcrumb.GetAlbumTree()[i].Title, albumTreeUrl);
        }

        oBreadcrumb.AddCrumb(oModel.Album.Id, oModel.Album.Title, url);
        oModel.BreadcrumbHistory = oBreadcrumb.GetBreadcrumbHistory();
    }
    
    var fncOnDomReady;
    
    function OnDomReady(){
        if(fncOnDomReady){
            fncOnDomReady();
        }
    }


    oThis.DeclareVirtualMethods({
        Render: Render,
        OnDomReady: OnDomReady
    });
        
})($data, {Main:Main,Version3:Version3});
}return $text.join("");}},{id:"Photos2.SubcategoryViewer",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('  style=\"');_write(o.Style());_write('\">');_write(o.InnerHTML());_write('\n<h2 ');_write(o.Elem('Title'));_write('  style=\"');_write(o.Style());_write('\">');_write(o.InnerHTML());_write('</h2>\n<div ');_write(o.Elem('Body'));_write('  style=\"');_write(o.Style());_write('\">');_write(o.InnerHTML());_write('\n<div ');_write(o.Elem('pagerRegion'));_write('  style=\"margin:3px 0px 20px 0px;');_write(o.Style());_write('\">');_write(o.InnerHTML());_write(ht.Pager ? ht.Pager.Render() : '');_write('</div>\n<div ');_write(o.Elem('AdminRegion'));_write('  class=\"admin-head\" style=\"float:right; margin-bottom:15px; display:none;');_write(o.Style());_write('\">');_write(o.InnerHTML());_write('\n');_write(ht.fncRenderActions());_write('\n<div style=\"clear:both;\"></div>\n</div>\n<div ');_write(o.Elem('categoryRegion'));_write('  style=\"');_write(o.Style());_write('\">');_write(o.InnerHTML());_write('\n');_write(ht.DynPanel.Render());_write('\n</div>\n<div style=\"clear:both;\"></div>\n</div>\n</div>\n');;return($text.join(""));};Actions = function(o, actions, fnc) {var $text = [];var _write = function(text) {$text.push((typeof text == "number")?text:(text||""));};_write('\r\n\n');if(actions instanceof Array) {for(var i=0; i<actions.length; i++) {_write('\n<div class=\"');_write(actions[i].strClass);_write('\" style=\"float:right;\"><a href=\"javascript:');_write($OG(fnc));_write('(');_write(i);_write(')\">');_write(actions[i].strLabel);_write('</a></div>\n');}} else {for(var i in actions) {_write('\n<div class=\"');_write(actions[i].strClass);_write('\" style=\"float:right;\"><a href=\"javascript:');_write($OG(fnc));_write('(');_write(i);_write(')\">');_write(actions[i].strLabel);_write('</a></div>\n');}}_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 iPageSize = -1;
    var iCurrentPage = 1;
    var oDynPanel, oPager, oPager2, aItems;
    var blnDisplay = !!d.Display;
    var oBtvModule;
    oThis.onPageChange = new Btv.Event();
    oThis.onClickSubcategory = new Btv.Event();
    oThis.onAddBreadcrumb = new Btv.Event();


    function RenderActions()
    {
        function ActionClicked(i)
        {
            aoActions[i].fnc();
        }

        return (aoActions ? htUI.Actions(oThis, aoActions, ActionClicked) : '');
    }

    oThis.SetActions = function(aoActions_)
    {
        aoActions = aoActions_;
    }
    var aoActions;



    oThis.AdminMode = function(bln)
    {
        blnAdminMode = bln;
        oElMan.Style('AdminRegion', 'display', bln ? 'block' : 'none');
        for (var i = 0; aItems && (i < aItems.length); i++)
        {
            aItems[i].AdminMode(bln);
        }
    }
    var blnAdminMode = false;


    oThis.GetOrdinalValues = function()
    {
        var aIds = [];
        var aOrdinals = [];
        for (var i = 0; i < aItems.length; i++)
        {
            var iOrdinal = aItems[i].GetOrdinal();
            if (!isNaN(iOrdinal))
            {
                aIds.push(d.Model.Album.ChildrenCategories[i].Id);
                aOrdinals.push(iOrdinal);
            }
        }
        return ({ ids: aIds, ordinals: aOrdinals });
    }


    function OnPageChange(iPage) {
        oThis.onPageChange.Fire(GetFirstIndex(iPage));
    }
    
    function OnClickHandler(albumId)
    {
        oThis.onClickSubcategory.Fire(albumId);
    }

    function GetFirstIndex(iPage) {
        return ((iPage > 0) ? ((iPage - 1) * iPageSize) : -1);
    }

    function CategoryChanged() {
        iCurrentPage = d.Model.CategoryCurrentPage;
        SetCategoryData();

        var url = $F('javascript:{0}({1})', $OG(OnClickHandler), d.Model.Album.Id);

        oThis.onAddBreadcrumb.Fire(d.Model.Album.Id, d.Model.Album.Title, url);

        oElMan.InnerHTML('Title', d.Model.Album.Title + ' - Subcategories');
        Btv.UI.SetPageTitle('BuddyTV Photo Gallery', d.Model.Album.Title);
        Btv.GoogleAnalytics.Unhold();
    }
    
    var iNumCols = ((Btv.iPageVersion == 3) ? 3 : 4);

    function SetCategoryData()
    {
        aItems = [];
        
        for (var i=0; i < d.Model.Album.ChildrenCategories.length; i++)
        {
            aItems[i] = Btv.Templating.GetInstance('Photos2.SubcategorySummary', { id: d.Model.Album.ChildrenCategories[i].Id, fncClick: OnClickHandler, oModel: d.Model, viewerUrlFormat: (d.viewerUrlFormat || '/photos/galleryviewer.aspx?ai={0}&&pi={1}&bIds={2}') });
            aItems[i].SetData(d.Model.Album.ChildrenCategories[i]);
            aItems[i].AdminMode(blnAdminMode);
        }
        
        oDynPanel.SetItems(aItems);

        var iCount = d.Model.Album._TotalCategories;
        var iPageCount = Math.ceil(iCount / iPageSize);
        if (!iCount) oThis.Display(false);

        if (oPager) {
            oPager.SetPage(iCurrentPage);
            oPager.SetPageCount(iPageCount);
        }
        if (oPager2) {
            oPager2.SetPage(iCurrentPage);
            oPager2.SetPageCount(iPageCount);
        }
    }

    function RenderView() 
    {
        d.Model.onCategoryChange.Attach(CategoryChanged);
        iPageSize = d.Model.CategoryPageSize;
        oThis.Display(blnDisplay);
        CreateHelperObjects();
        InitElements();        
        
        return (htUI.Main(oThis, {
            DynPanel: oDynPanel,
            fncRenderActions: RenderActions,
            Pager: oPager,
            Pager2: oPager2
        }));
    }    
        
    oThis.Display = function(bln)
    {
        blnDisplay = bln;
        oElMan.Style('Root', 'display', (blnDisplay ? 'block' : 'none'));
        oBtvModule.Display(blnDisplay);
    }

    function CreateHelperObjects()
    {
        function CreatePager() {
            var iPageCount = Math.ceil(d.Model.Album.ChildrenCategoryTotal / iPageSize);
            //if (iPageCount > 1) {
                oPager = Btv.Templating.GetInstance("Navigation.NumericPager", {
                    iPageCount: iPageCount
                    , iPageStart: iCurrentPage
                    , align: ((Btv.iPageVersion == 3) ? 'center' : 'center')
                    , labels: {
                        Back: 'Prev'
                        , Next: 'Next'
                        , Page: 'Page'
                        , Pages: 'Pages'
                    }
                });
                oPager.onChange.Attach(OnPageChange);

                oPager2 = Btv.Templating.GetInstance("Navigation.NumericPager", {
                    iPageCount: iPageCount
                    , iPageStart: iCurrentPage
                    , align: ((Btv.iPageVersion == 3) ? 'center' : 'center')
                    , labels: {
                        Back: 'Prev'
                        , Next: 'Next'
                        , Page: 'Page'
                        , Pages: 'Pages'
                    }
                });
                oPager2.onChange.Attach(OnPageChange);
            //}
        }

        oDynPanel = Btv.Templating.GetInstance('Container.DynamicPanel', {
                cols: iNumCols
                , Classes: { Outer: 'photo09_photo' }
             });

        CreatePager();
    }

    function InitElements() {
        oElMan.Style('Root', 'display', (blnDisplay ? 'block' : 'none'));
        oElMan.Style('pagerRegion', 'display', (oPager ? 'block' : 'none'));
        oElMan.Style('pagerRegion2', 'display', (oPager2 ? 'block' : 'none'));
        if (Btv.iPageVersion == 3)
        {
            oElMan.Style('Title', 'display', 'none');
            oElMan.Style('Root', 'margin-left', "25px");
        }
        else
        {
            oElMan.InnerHTML('Title', d.Model.Album.Title + ' - Subcategories');
        }
        Btv.UI.SetPageTitle('BuddyTV Photo Gallery', d.Model.Album.Title);
        Btv.GoogleAnalytics.Unhold();
    }

    oBtvModule = Btv.Templating.GetInstance('Container.BtvModule', {
        body: { Render: RenderView }
        , classes: { Module: 'btv_module' }
    });
    
    oThis.DeclareVirtualMethods({
        Render: ((Btv.iPageVersion == 3) ? RenderView : oBtvModule.Render)
    });
})($data, {Main:Main,Actions:Actions});
}return $text.join("");}},{id:"Photos2.SubcategorySummary",fnc:function($data){var $text = [];var _write = function(text) {$text.push((typeof text == "number")?text:(text||""));};with($data){ _write('\n');CategoryDisplay = function(o, fncRenderImage) {var $text = [];var _write = function(text) {$text.push((typeof text == "number")?text:(text||""));};_write('\n<div ');_write(o.Elem('Root'));_write(' style=\"');_write(o.Style());_write('; margin-bottom:20px;\">\n<div style=\"width:120px; height:105px; background: url(\'/images/MultiAlbum.png\') no-repeat;\" /><div style=\"padding-left:30px; padding-top:17px;\" /><div style=\"border:solid 0px #999999; width:70px; height:70px;\">');_write(fncRenderImage());_write('</div></div></div>\n<div style=\"padding:0px 20px 0px 20px;\">\n<div class=\"gallery_thumb_title\"><a ');_write(o.Elem('CategoryTitle'));_write('>');_write(o.InnerHTML());_write('</a></div>\n<div><span ');_write(o.Elem('AlbumCount'));_write('>');_write(o.InnerHTML());_write('</span></div>\n</div>\n<div ');_write(o.Elem('AdminRegion'));_write(' style=\"');_write(o.Style());_write(' display:none; margin-bottom:3px;\">Order:<input ');_write(o.Elem('ordinal'));_write(' type=\"input\" style=\"width:50px;\" /></div>\n</div>\n');;return($text.join(""));};_write('\n');AlbumDisplay = function(o, fncRenderImage) {var $text = [];var _write = function(text) {$text.push((typeof text == "number")?text:(text||""));};_write('\n<div ');_write(o.Elem('Root'));_write(' style=\"');_write(o.Style());_write('; margin-bottom:20px;\">\n<div style=\"width:120px; height:105px; background: url(\'/images/SingleAlbum.png\') no-repeat;\" /><div style=\"padding-left:22px; padding-top:7px;\" />');_write(fncRenderImage());_write('</div></div>\n<div style=\"\">\n<div class=\"gallery_thumb_title\"><a ');_write(o.Elem('CategoryTitle'));_write('>');_write(o.InnerHTML());_write('</a></div>\n<div><span ');_write(o.Elem('PhotoCount'));_write('>');_write(o.InnerHTML());_write('</span></div>\n</div>\n<div ');_write(o.Elem('AdminRegion'));_write(' style=\"');_write(o.Style());_write(' display:none; margin-bottom:3px;\">Order:<input ');_write(o.Elem('ordinal'));_write(' type=\"input\" style=\"width:50px;\" /></div>\n</div>\n');;return($text.join(""));};_write('\n');
new (function(d, fncCategoryDisplay, fncAlbumDisplay)
{
var s, data, oThis = Btv.Lang.Extend(this, Btv.Cst.BaseTemplate, arguments);
var oElMan = oThis.ElMan();
oThis.d = d;
var oImg;
var sizeCatImageBounds = {width:70, height:70};
var sizeAlbumImageBounds = {width:90, height:90};
function GetBounds()
{
return(d.info.IsCategory ? sizeCatImageBounds : sizeAlbumImageBounds);
}
function OnClick()
{
if (d.info.IsCategory)
{
d.fncClick(d.info.Id);
}
else
{
document.location.href = $F(d.viewerUrlFormat, d.info.Id, -1, d.oModel.GetBreadCrumbHistory());
}
}
function BuildImageInfo()
{
if (d.info)
{
var oImageView = Btv.UI.Images.FindView(d.info.CoverImage.ImageViews, GetBounds(), true);
if (oImageView) return({Src: oImageView.Src, Size: {width: oImageView.Width, height: oImageView.Height}});
}
return(null);
}
function RenderImage()
{
oImg = Btv.Templating.GetInstance("SmartImage", {
sizeBounds: GetBounds()
, doCrop: true
, ImageInfo: BuildImageInfo()
, oCropAnchor: { width: .5, height: .25 }
, link:{href: $F('javascript:{0}()', $OG(OnClick))}
});
return(oImg.Render());
}
function Render()
{
var fnc = d.info.IsCategory ? fncCategoryDisplay : fncAlbumDisplay;
var str = fnc(oThis, RenderImage);
return(str);
}
var blnAdmin = false;
oThis.AdminMode = function(bln)
{
blnAdmin = bln;
oElMan.Style('AdminRegion', 'display', bln ? 'block' : 'none');
}
oThis.GetOrdinal = function()
{
return (parseFloat($(oThis.htIds['ordinal']).value));
}
oThis.SetData = function(info)
{
function UpdateImage()
{
if (idLocal == idSetDataCounter)
{
oImg.UpdateImage(BuildImageInfo());
oThis.UpdateElements();
}
}
d.info = info;
var idLocal = ++idSetDataCounter;
if (blnHasRendered)
{
var elRootName = oThis.htIds['Root'];
if ($(elRootName))
{
UpdateImage();
}
else
{
YAHOO.util.Event.onAvailable(elRootName, UpdateImage);
}
}
}
var idSetDataCounter = 0;
function OnPostRender()
{
blnHasRendered = true;
}
var blnHasRendered = false;
oThis.ElementProps = function(id, scope, name, isInit, params, ht)
{
switch(scope)
{
case "Root":
ht.style.visibility = (d.info) ? 'visible' : 'hidden';
break;
case "CategoryTitle":
if (d.info) ht.innerHTML = d.info.Title;
if(isInit && d.info) ht.attr.onclick = $F('{0}();', $R(OnClick));
break;
case "AlbumCount":
if (d.info) ht.innerHTML = 'Albums: ' + (d.info.ChildrenAlbumTotal + d.info.ChildrenCategoryTotal);
break;
case "PhotoCount":
if (d.info) ht.innerHTML = 'Photos: ' + (d.info.AlbumImageTotal);
break;
case "ordinal":
if (d.info) ht.attr.value = d.info.OrdinalIndex;
break;
}
}
oThis.DeclareVirtualMethods({
Render: Render
,OnPostRender: OnPostRender
});
})($data, CategoryDisplay, AlbumDisplay);
_write('\n');}return $text.join("");}},{id:"Photos2.AlbumViewer",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('  style=\"');_write(o.Style());_write('\">');_write(o.InnerHTML());_write('\n<h2 ');_write(o.Elem('Title'));_write('  style=\"');_write(o.Style());_write('\">');_write(o.InnerHTML());_write('</h2>\n<div ');_write(o.Elem('Body'));_write('  style=\"');_write(o.Style());_write('\">');_write(o.InnerHTML());_write('\n<div ');_write(o.Elem('pagerRegion'));_write('  style=\"margin:3px 0px 20px 0px;');_write(o.Style());_write('\">');_write(o.InnerHTML());_write(ht.Pager ? ht.Pager.Render() : '');_write('</div>\n<div ');_write(o.Elem('albumRegion'));_write('  style=\"');_write(o.Style());_write('\">');_write(o.InnerHTML());_write('\n');_write(ht.DynPanel.Render());_write('\n</div>\n<div style=\"clear:both;\"></div>\n</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 iPageSize = -1;
    var iCurrentPage = 1;
    var oDynPanel, oPager, oPager2, aItems;
    var blnDisplay = !!d.Display;
    var oBtvModule;
    oThis.onPageChange = new Btv.Event();

    function OnPageChange(iPage) {
        oThis.onPageChange.Fire(GetFirstIndex(iPage));
    }

    function GetFirstIndex(iPage) {
        return ((iPage > 0) ? ((iPage - 1) * iPageSize) + 1 : -1);
    }

    var iNumCols = ((Btv.iPageVersion == 3) ? 3 : 5);

    function SetAlbumData() {
   
        aItems = [];
        
        for (var i=0; i < d.Model.Album.ChildrenAlbums.length; i++)
        {
            aItems[i] = Btv.Templating.GetInstance('Photos2.AlbumSummary', { id: d.Model.Album.ChildrenAlbums[i].Id, BreadcrumbHistory: d.Model.BreadcrumbHistory, viewerUrlFormat: d.viewerUrlFormat });
            aItems[i].SetData(d.Model.Album.ChildrenAlbums[i]);
        }

        oDynPanel.SetItems(aItems);

        oElMan.InnerHTML('Title', d.Model.Album.Title + ' - Albums');

        iCurrentPage = d.Model.AlbumCurrentPage;
        var iCount = d.Model.Album.ChildrenAlbumTotal;
        var iPageCount = Math.ceil(iCount / iPageSize);
        if (!iCount) oThis.Display(false);
        if (oPager) {
            oPager.SetPage(iCurrentPage);
            oPager.SetPageCount(iPageCount);
        }
        if (oPager2) {
            oPager2.SetPage(iCurrentPage);
            oPager2.SetPageCount(iPageCount);
        }

        
    }

    function RenderView() {
        d.Model.onCategoryChange.Attach(SetAlbumData);
        iPageSize = d.Model.AlbumPageSize;
        iCurrentPage = 
        oThis.Display(blnDisplay);
        CreateHelperObjects();
        InitElements();

        return (htUI.Main(oThis, {
            DynPanel: oDynPanel,
            Pager: oPager,
            Pager2: oPager2
        }));
    }

    function CreateHelperObjects() {
        function CreatePager() {
            var iPageCount = Math.ceil(d.Model.Album.ChildrenAlbumTotal / iPageSize);
            if (iPageCount > 1) {
                oPager = Btv.Templating.GetInstance("Navigation.NumericPager", {
                    iPageCount: iPageCount
                    , iPageStart: iCurrentPage
                    , align: ((Btv.iPageVersion == 3) ? 'center' : 'center')
                    , labels: {
                        Back: 'Prev'
                        , Next: 'Next'
                        , Page: 'Page'
                        , Pages: 'Pages'
                    }
                });
                oPager.onChange.Attach(OnPageChange);

                oPager2 = Btv.Templating.GetInstance("Navigation.NumericPager", {
                    iPageCount: iPageCount
                    , iPageStart: iCurrentPage
                    , align: ((Btv.iPageVersion == 3) ? 'center' : 'center')
                    , labels: {
                        Back: 'Prev'
                        , Next: 'Next'
                        , Page: 'Page'
                        , Pages: 'Pages'
                    }
                });
                oPager2.onChange.Attach(OnPageChange);
            }
        }

        oDynPanel = Btv.Templating.GetInstance('Container.DynamicPanel', {
                cols: iNumCols
                , Classes: { Outer: 'photo09_albums' }
        });

        CreatePager();
    }
        
    oThis.Display = function(bln)
    {
        blnDisplay = bln;
        oElMan.Style('Root', 'display', (blnDisplay ? 'block' : 'none'));
        oBtvModule.Display(blnDisplay);
    }

    function InitElements() {
        oElMan.Style('Root', 'display', (blnDisplay ? 'block' : 'none'));
        oElMan.Style('pagerRegion', 'display', (oPager ? 'block' : 'none'));
        oElMan.Style('pagerRegion2', 'display', (oPager2 ? 'block' : 'none'));
        if (Btv.iPageVersion == 3)
        {
            oElMan.Style('Title', 'display', 'none');
            oElMan.Style('Root', 'margin-left', "35px");
        }
        else
        {
            oElMan.InnerHTML('Title', d.Model.Album.Title + ' - Albums');
        }
    }

    oBtvModule = Btv.Templating.GetInstance('Container.BtvModule', {
        body: { Render: RenderView }
        , classes: { Module: 'btv_module' }
    });

    oThis.DeclareVirtualMethods({
        Render: ((Btv.iPageVersion == 3) ? RenderView : oBtvModule.Render)
    });
})($data, {Main:Main});
}return $text.join("");}},{id:"Photos2.AlbumSummary",fnc:function($data){var $text = [];var _write = function(text) {$text.push((typeof text == "number")?text:(text||""));};with($data){ _write('\n');Main = function(o, fncRenderImage) {var $text = [];var _write = function(text) {$text.push((typeof text == "number")?text:(text||""));};_write('\n<div ');_write(o.Elem('Root'));_write(' class=\"gallery_thumb_wrap\" style=\"');_write(o.Style());_write('\">\n<div class=\"gallery_thumb_innerwrap\">\n<div class=\"gallery_thumb_shadow2\">\n<div ');_write(o.Elem('ImageWrapper'));_write(' class=\"gallery_thumb_shadow1\" style=\"');_write(o.Style());_write('\">');_write(fncRenderImage());_write('</div>\n</div>\n</div>\n<div class=\"gallery_thumb_title\"><a ');_write(o.Elem('AlbumTitle'));_write('>');_write(o.InnerHTML());_write('</a></div>\n</div>\n');;return($text.join(""));};_write('\n');
new (function(d, fncMain)
{
var s, data, oThis = Btv.Lang.Extend(this, Btv.Cst.BaseTemplate, arguments);
oThis.d = d;
var oImg;
var sizeImageBounds = (Btv.iPageVersion == 3) ? {width:105, height:105} : {width:105, height:105};
d.viewerUrlFormat = d.viewerUrlFormat || '/photos/galleryviewer.aspx?ai={0}&&pi={1}&bIds={2}';
function BuildImageInfo()
{
if (d.info)
{
var oImageView = Btv.UI.Images.FindView(d.info.CoverImage.ImageViews, sizeImageBounds, true);
if (oImageView) return({Src: oImageView.Src, Size: {width: oImageView.Width, height: oImageView.Height}});
}
return(null);
}
function RenderImage()
{
oImg = Btv.Templating.GetInstance("SmartImage", {
sizeBounds: sizeImageBounds
, doCrop: true
, ImageInfo: BuildImageInfo()
, oCropAnchor: { width: .5, height: .25 }
, link:{href: $F(d.viewerUrlFormat, d.info.Id, -1, d.BreadcrumbHistory)}
});
return(oImg.Render());
}
function Render()
{
return(fncMain(oThis, RenderImage));
}
oThis.SetData = function(info)
{
function UpdateImage()
{
if (idLocal == idSetDataCounter)
{
oImg.UpdateImage(BuildImageInfo());
oThis.UpdateElements();
}
}
d.info = info;
var idLocal = ++idSetDataCounter;
if (blnHasRendered)
{
var elRootName = oThis.htIds['Root'];
if ($(elRootName))
{
UpdateImage();
}
else
{
YAHOO.util.Event.onAvailable(elRootName, UpdateImage);
}
}
}
var idSetDataCounter = 0;
function OnPostRender()
{
blnHasRendered = true;
}
var blnHasRendered = false;
oThis.ElementProps = function(id, scope, name, isInit, params, ht)
{
switch(scope)
{
case "Root":
ht.style.visibility = (d.info) ? 'visible' : 'hidden';
break;
case "AlbumTitle":
if(isInit && d.info){
ht.innerHTML = d.info.Title + '&nbsp;<span>' + ((d.info.AlbumImageTotal == 1) ? '<br/>Photo&nbsp;' : '<br/>Photos&nbsp;') + '(' + d.info.AlbumImageTotal + ')</span>';
ht.attr.href = $F(d.viewerUrlFormat, d.info.Id, -1, d.BreadcrumbHistory);
} 
break;
case "ImageWrapper":
if (isInit) Btv.Styles.SetSize(ht, sizeImageBounds);
break;
}
}
oThis.DeclareVirtualMethods({
Render: Render
,OnPostRender: OnPostRender
});
})($data, Main);
_write('\n');}return $text.join("");}},{id:"Photos2.CategoryBreadcrumb",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=\"nooverlay\"><div class=\"bread-crumb-photo\" ');_write(o.Elem('Breadcrumb'));_write(' style=\"font-weight:bold;\">');_write(o.InnerHTML());_write('</div></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 crumbs = new Array();
            
    function Render()
    {
        return (htUI.Main(oThis));
    }
    
    oThis.GetAlbumTree = function(){
        return d.albumTree;
    }

    oThis.AddCrumb = function(categoryId, name, url)
    {
        var crumbExists = false;
        var sliceLoc = -1;

        if (crumbs.length == 0)
        {
            if (Btv.iPageVersion == 3)
            {
                crumbs[0] = { id: 0, name: 'Photos', url: '' };
            }
            else
            {
                crumbs[0] = { id: 0, name: 'Photo', url: '/gallery3/galleries.aspx' };
            }
        }

        for (var i = 0; i < crumbs.length; i++)
        {
            if (crumbs[i].id == categoryId)
            {
                sliceLoc = i + 1;
                crumbExists = true;
                break;
            }
        }

        if (!crumbExists)
        {
            crumbs[crumbs.length] = { id: categoryId, name: name, url: url };
        }
        else
        {
            if (sliceLoc < crumbs.length)
            {
                crumbs = crumbs.slice(0, sliceLoc);
            }
        }
        oThis.BuildCrumbs();
    }

    oThis.BuildCrumbs = function()
    {
        var htmlBits = new Array();
        var bIds = '';

        for (var i = 0; i < crumbs.length; i++)
        {
            if (i == 0)
            {
                var strHtml = (crumbs[i].url) ? $F('<a href="{0}">{1}</a>', crumbs[i].url, crumbs[i].name) : $F('<span>{1}</span>', crumbs[i].url, crumbs[i].name)
                htmlBits.push(strHtml);
            }
            else if (i == crumbs.length - 1)
            {
                htmlBits.push($F('&nbsp;&gt;&nbsp;{0}', crumbs[i].name));
            }
            else
            {
                bIds += crumbs[i].id + ',';
                if (crumbs[i].url.indexOf('javascript:') == -1)
                {
                    htmlBits.push($F('&nbsp;&gt;&nbsp;<a href="{0}&bIds={2}">{1}</a>', crumbs[i].url, crumbs[i].name, bIds));
                }
                else
                {
                    htmlBits.push($F('&nbsp;&gt;&nbsp;<a href="{0}">{1}</a>', crumbs[i].url, crumbs[i].name));
                }
            }
        }

        oElMan.InnerHTML("Breadcrumb", htmlBits.join(""));
    }
    
    oThis.GetBreadcrumbHistory = function(){
        var list = '';
        
        // ignore home entry
        for(var i = 1; i < crumbs.length; i++){
            if(i != (crumbs.length-1)){
                list += crumbs[i].id + ',';
            }
            else{
                list += crumbs[i].id;
            }
        }
        
        return escape(list);
    }

    oThis.DeclareVirtualMethods({
        Render: Render
    });
})($data, {Main:Main});
}return $text.join("");}},{id:"Photos2.ImageModule",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<h2 ');_write(o.Elem('Title'));_write('  style=\"');_write(o.Style());_write('\">');_write(o.InnerHTML());_write('</h2>\n<div ');_write(o.Elem('Root'));_write('  style=\"');_write(o.Style());_write('\">');_write(o.InnerHTML());_write('\n');_write(ht.DynPanel.Render());_write('\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 oBtvModule, oDynPanel, aItems;
    var blnDisplay = !!d.Display;

    oThis.SetData = function(images)
    {
        aItems = [];
        for (var i=0; images && (i < images.length); i++)
        {
            aItems[i] = Btv.Templating.GetInstance('Photos2.ModuleThumbnail', {id: i, HideInfo: d.hideInfo, linkFormat: d.linkFormat});
            aItems[i].SetData(images[i]);
        }
        
        oDynPanel.SetItems(aItems);
    }

    oThis.Display = function(bln)
    {
        blnDisplay = bln;
        if (oBtvModule) oBtvModule.Display(blnDisplay);
    }

    function RenderView() {
        oElMan.InnerHTML("Title", d.title);
        
        oDynPanel = Btv.Templating.GetInstance('Container.DynamicPanel', {
                cols: d.numberOfColumns
                , Classes: { Outer: d.classNames }
        });

        oThis.Display(blnDisplay);

        return (htUI.Main(oThis, {
            DynPanel: oDynPanel
        }));
    }

    oBtvModule = Btv.Templating.GetInstance('Container.BtvModule', {
        body: { Render: RenderView }
        , classes: { Module: 'btv_module' }
    });


    oThis.DeclareVirtualMethods({
        Render: (oBtvModule ? oBtvModule.Render : RenderView)
    });
})($data, {Main:Main});
}return $text.join("");}},{id:"Photos2.ModuleThumbnail",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=\"gallery_single_wrap\" style=\"');_write(o.Style());_write('\">\n<div ');_write(o.Elem('ImageWrapper'));_write(' class=\"photo09_thumb_view_imgwrapper\" style=\"');_write(o.Style());_write('\">');_write(ht.fncRenderImage());_write('</div>\n<div ');_write(o.Elem('ImageInfo'));_write(' class=\"gallery_thumb_title\" style=\"');_write(o.Style());_write('\">\n<div ');_write(o.Elem('RatingCount'));_write(' class=\"photo09_thumb_view\">');_write(o.InnerHTML());_write('</div>\n<div ');_write(o.Elem('CommentCount'));_write(' class=\"photo09_thumb_comment\">');_write(o.InnerHTML());_write('</div>\n</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 s;
        oThis.d = d;
        var oImg;
        var sizeImageBounds = {width:80, height:80};
        var strUrlTemplate = d.linkFormat || '/photos/galleryviewer.aspx?ai={0}&pi={1}&bIds={2}';

        function OnClick()
        {
            d.fncClick(d.id);
        }


        function BuildImageInfo()
        {
            if (d.info)
            {
                var oImageView;
                if(d.info.Views) oImageView = Btv.UI.Images.FindView(d.info.Views, sizeImageBounds, true);
                if(!oImageView && d.info.ImageViews) oImageView = Btv.UI.Images.FindView(d.info.ImageViews, sizeImageBounds, true);
                if (oImageView) return({Src: oImageView.Src, Size: {width: oImageView.Width, height: oImageView.Height}});
            }
            return(null);
        }


        function RenderImage()
        {
            oImg = Btv.Templating.GetInstance("SmartImage", {
                    sizeBounds: sizeImageBounds
                    , doCrop: true
                    , ImageInfo: BuildImageInfo()
                    , oCropAnchor: { width: .5, height: .25 }
                    , link: { href: $F(strUrlTemplate, d.info.AlbumId || -1, d.info.Id, '') }
                    , ChangeStrategy: 'View'
                });
            return(oImg.Render());
        }



        function Render()
        {
            return (htUI.Main(oThis, {
                fncRenderImage: RenderImage
            }));
        }


        oThis.SetData = function(info) {
            function UpdateImage() {
                if (idLocal == idSetDataCounter) {
                    oImg.UpdateImage(BuildImageInfo());
                    oThis.UpdateElements();
                }
            }


            d.info = info;
            var idLocal = ++idSetDataCounter;
            if (blnHasRendered) {
                var elRootName = oThis.htIds['Root'];
                if ($(elRootName)) {
                    UpdateImage();
                }
                else {
                    YAHOO.util.Event.onAvailable(elRootName, UpdateImage);
                }
            }
        }
        var idSetDataCounter = 0;
        
        
        
        function OnPostRender()
        {
            blnHasRendered = true;
        }
        var blnHasRendered = false;
        
        
        

        oThis.ElementProps = function(id, scope, name, isInit, params, ht)
        {
            switch(scope)
            {
                case "Root":
                    ht.style.visibility = (d.info) ? 'visible' : 'hidden';
                    break;
                case "RatingCount":
                    if (d.info) ht.innerHTML = d.info.RatingCount;
                    break;
                case "CommentCount":
                    if (d.info) ht.innerHTML = d.info.CommentCount;
                    break;
                case "ImageWrapper":
                    if (isInit) Btv.Styles.SetSize(ht, sizeImageBounds);
                    break;
                case "ImageInfo":
                    if(isInit && d.HideInfo) ht.style.display = 'none';
            }
        }


    oThis.DeclareVirtualMethods({
        Render: Render
        ,OnPostRender: OnPostRender
    });
        
})($data, {Main:Main});
}return $text.join("");}},{id:"SmartImage",fnc:function($data){var $text = [];var _write = function(text) {$text.push((typeof text == "number")?text:(text||""));};with($data){ Main = function(o, imageUI) {var $text = [];var _write = function(text) {$text.push((typeof text == "number")?text:(text||""));};_write('\r\n \n<div ');_write(o.Elem('outer'));_write('  style=\"position:relative; overflow:hidden; zoom:1;');_write(o.Style());_write('\">');_write(o.InnerHTML());_write('\n');_write(imageUI);_write('\n</div>\n');;return($text.join(""));};WithLink = function(o, ht) {var $text = [];var _write = function(text) {$text.push((typeof text == "number")?text:(text||""));};_write('\r\n\n<a ');_write(o.Elem('link'));_write('  href=\"\" style=\"');_write(o.Style());_write('\">');_write(o.InnerHTML());_write('\n<img ');_write(o.Elem('image1'));_write('  style=\"zoom:1; position:relative; border-width: 0px; visibility: hidden;');_write(o.Style());_write('\">');_write(o.InnerHTML());_write('</img>\n</a>\n');;return($text.join(""));};ImageOnly = function(o, ht) {var $text = [];var _write = function(text) {$text.push((typeof text == "number")?text:(text||""));};_write('\r\n\n<img ');_write(o.Elem('image2'));_write('  style=\"zoom:1; position:relative; border-width: 0px; visibility: hidden;');_write(o.Style());_write('\">');_write(o.InnerHTML());_write('</img>\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;

    oThis.d = d;
    var oElMan = oThis.ElMan();
    var oDefaultAnchor = {width:.5, height:.5};
    var s, img;
    
    function SetImageProperties(cstname, sizeImg)
    {
        function A(s)
        {
            oAnchor = (sizeScaledImage[s] > d.sizeBounds[s]) ? (d.oCropAnchor || oDefaultAnchor) : (d.oBoxAnchor || oDefaultAnchor);
            oElMan.Style(cstname, (s == 'width') ? 'left' : 'top', Math.round((d.sizeBounds[s] - sizeScaledImage[s]) * oAnchor[s]) + "px");
        }
        
        var flScale = Math[d.doCrop ? 'max' : 'min'](d.sizeBounds.height / sizeImg.height, d.sizeBounds.width / sizeImg.width);
        if (d.blnNoUpsize) flScale = Math.min(1, flScale);
        var sizeScaledImage = Btv.UI.Drawing.ScaleSize(sizeImg, flScale, true);
        A('width');
        A('height');
        oElMan.Style(cstname, 'width', sizeScaledImage.width + 'px');
        oElMan.Style(cstname, 'height', sizeScaledImage.height + 'px');
    }
    
    function ImageLoaded(elImg)
    {
        SetImageProperties(elImg, d.ImageInfo.Size);
        elImg.style.visibility = 'visible';
    }

    oThis.UpdateImage = function(oImageInfo) {
        function DoneChanging(elImg) {
            elImg.style.visibility = 'visible';
        }

        function Change(elImg) {
            elImg.style.visibility = 'hidden';
            elImg.src = oImageInfo.Src;
            
            if ($(oThis.htIds['image1'])) SetImageProperties('image1', oImageInfo.Size);
            if ($(oThis.htIds['image2'])) SetImageProperties('image2', oImageInfo.Size);
        }

        d.ImageInfo = oImageInfo;
        if (d.ChangeStrategy == 'Hide') {
            oElMan.Style('image1', 'visibility', 'hidden');
            oElMan.Style('image2', 'visibility', 'hidden');
        }

        if (!oImageChanger1 && $(oThis.htIds['image1'])) {
            oImageChanger1 = new Btv.UI.Imaging.ImageChanger($(oThis.htIds['image1']), true);
        }

        if (!oImageChanger2 && $(oThis.htIds['image2'])) {
            oImageChanger2 = new Btv.UI.Imaging.ImageChanger($(oThis.htIds['image2']), true);
        }

        if (oImageInfo) {
            if (oImageChanger1) oImageChanger1.Change(Change, DoneChanging);
            if (oImageChanger2) oImageChanger2.Change(Change, DoneChanging);
        }
    }
    var oImageChanger1;
    var oImageChanger2;

    function InitElements() {
        function fnc(oImg, bln) {
            if (bln) {
                SetImageProperties('image1', oImg);
                SetImageProperties('image2', oImg);
            }
        }
        
        oElMan.Style('outer', 'width', d.sizeBounds.width + 'px');
        oElMan.Style('outer', 'height', d.sizeBounds.height + 'px');

        if (d.ImageInfo) {
            oElMan.Style('image1', 'visibility', 'visible');
            oElMan.Style('image2', 'visibility', 'visible');
            oElMan.Attribute('image1', 'src', d.ImageInfo.Src);
            oElMan.Attribute('image2', 'src', d.ImageInfo.Src);

            if (d.ImageInfo.Size == null) {
                Btv.UI.Imaging.Load(d.ImageInfo.Src, fnc);
            }
            else {
                SetImageProperties('image1', d.ImageInfo.Size);
                SetImageProperties('image2', d.ImageInfo.Size);
            }
        }
    }

    oThis.ElementProps = function(id, scope, name, isInit, params, ht) {
        switch (scope) {
            case "link":
                if (isInit && d.link) {
                    ht.attr.href = d.link.href;
                    if (d.link.target) ht.attr.target = d.link.target;
                }
                break;
        }
    }

    function Render() {
        var imageUI = '';
        
        if (oThis.d.link == null) {
            imageUI = htUI.ImageOnly(oThis);
        }
        else {
            imageUI = htUI.WithLink(oThis);
        }
        InitElements();
        return (htUI.Main(oThis, imageUI));
    }

    oThis.DeclareVirtualMethods({
        Render: Render
    });

})($data, {Main:Main,WithLink:WithLink,ImageOnly:ImageOnly});
}return $text.join("");}},{id:"Container.DynamicPanel",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=\"');_write(ht.Classes.Outer);_write('\">\n<div ');_write(o.Elem('body'));_write('  style=\"');_write(o.Style());_write('\">');_write(o.InnerHTML());_write('</div>\n<div style=\"clear:both;\"></div>\n</div>\n');;return($text.join(""));};Contents = function(o, ht) {var $text = [];var _write = function(text) {$text.push((typeof text == "number")?text:(text||""));};_write('\r\n\n');
var iNumRows = Math.ceil(ht.aItems.length / ht.iCols);
var iIndex = 0;
for (var iRow=0; iRow < iNumRows; iRow++) {
_write('\n<div style=\"clear:both; width:100%;\">\n'); for (var iCol=0; (iCol < ht.iCols) && ht.aItems[iIndex]; iCol++) { _write(' \n');if((iCol > 0)) {_write(ht.separator ? ht.separator.Render() : '');}_write(' \n');if((!ht.separator)) {_write('<div style=\"float:left; width:');_write((Math.floor(100/ht.iCols)));_write('%;\">');}_write(ht.aItems[iIndex++].Render());if((!ht.separator)) {_write('</div>');}_write('\n'); } _write(' \n</div>\n'); } _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();

    oThis.SetItems = function(aItems)
    {
        var s = RenderContents(aItems);
        oElMan.InnerHTML('body', RenderContents(aItems));
        if (window["RunBtvTokenizer"]) window["RunBtvTokenizer"]();
    }


    function RenderContents(aItems)
    {
        return (htUI.Contents(oThis, {
            aItems: aItems
            , iCols: d.cols
            , separator: d.separator
        }));
    }


    function Render(s)
    {
        if (d.items && d.items.length) oThis.SetItems(d.items);
        return (htUI.Main(oThis, {
            Classes: d.Classes
        }));
    }


    oThis.DeclareVirtualMethods({
        Render: Render
    });

})($data, {Main:Main,Contents:Contents});
}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:"Rater.Big",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('outerDiv'));_write('>\n<a onclick=\"');_write(o.strRater);_write('(5)\" id=\"stars-5\" style=\"cursor:pointer;\"></a>\n<a onclick=\"');_write(o.strRater);_write('(4)\" id=\"stars-4\" style=\"cursor:pointer;\"></a>\n<a onclick=\"');_write(o.strRater);_write('(3)\" id=\"stars-3\" style=\"cursor:pointer;\"></a>\n<a onclick=\"');_write(o.strRater);_write('(2)\" id=\"stars-2\" style=\"cursor:pointer;\"></a>\n<a onclick=\"');_write(o.strRater);_write('(1)\" id=\"stars-1\" style=\"cursor:pointer;\"></a>\n<div ');_write(o.Elem('voteOverlay'));_write(' class=\"big-stars-voted-fill\" style=\"');_write(o.Style());_write('\"></div>\n</div>\n');;return($text.join(""));};_write('\n');
new (function(d, fncMain)
{
var s, oThis = Btv.Lang.Extend(this, Btv.Cst.BaseTemplate, arguments);
oThis.d = d;
function Rate(i)
{
d.fncRate(i);
}
oThis.strRater = $R(Rate);
oThis.Render = function()
{
if (!s) s = fncMain(oThis);
return(s);
}
oThis.UpdateRating = function(rating)
{
d.rating = rating;
oThis.UpdateElements();
}
oThis.ElementProps = function(id, scope, name, isInit, params, ht)
{
switch(scope)
{
case "outerDiv":
ht.attr['class'] = 'rate-stars-big' + ((!d.rating || (d.rating.RatingUser <= 0)) ? '' : ' big-stars-voted');
break;
case "voteOverlay":
var bln = d.rating && (d.rating.RatingUser > 0);
ht.style.visibility = bln ? 'visible' : 'hidden';
if (bln) ht.style.width = (100 - Math.round(d.rating.RatingAvg * 10)) + '%';
break;
case "rate":
if (isInit) ht.attr.onclick = $F('{0}({1})', strRater, params);
break;
}
}
})($data, Main);
_write('\n');}return $text.join("");}},{id:"PhotoPanelPreview",fnc:function($data){var $text = [];var _write = function(text) {$text.push((typeof text == "number")?text:(text||""));};with($data){ _write('\n');
var oView = new (function(c)
{
var oThisView = this;
var myConfig = c;
oThisView.config = c;
if (myConfig.self) myConfig.self.value = oThisView;
var id = YAHOO.Btv.Runtime.GetNextID();
var iMaxHeight = 0;
var iPageSize, iPhotoSummaries, iPagesCount, aoPages, flPageSizeMultiplier, oPageNav;
var fncLinkBuilder = myConfig.fncLinkBuilder;
function PreparePageData(i, a)
{
for (var j=0; j < a.length; j++)
{
a[j] = myConfig.GetPanelItem ? myConfig.GetPanelItem(a[j], (i * iPageSize) + j) : a[j];
}
var iDsPage = DataSourcePage(i);
var iNumPanelPages = Math.round(1 / flPageSizeMultiplier);
var iActualPageSize = (iPageSize == -1) ? iPhotoSummaries : iPageSize;
var iStartPanelPage = Math.round(iDsPage / flPageSizeMultiplier);
for (var k=0; k < iNumPanelPages; k++)
{
var iBegin = k * iActualPageSize;
var iEnd = iBegin + iActualPageSize;
aoPages[k+iStartPanelPage] = YAHOO.Btv.Data.Partition(a.slice(iBegin, iEnd), [{size:myConfig.panelSize.cols}, {name:"summaries"}]);
}
}
function DataSourcePage(i)
{
return(Math.round(i * flPageSizeMultiplier));
}
function InitStaticDataSource()
{
function G(i)
{
function F(a)
{
PreparePageData(i, a);
}
dataSource.GetPartition(DataSourcePage(i), F);
}
for (var i=0; i < iPagesCount; i++) G(i);
for (var j=0; j < iTextSummaries; j++)
{
oThisView.aoTextSummaries[j] = dataSource.GetData(j+iPhotoSummaries);
}
}
oThisView.GetPageSize = function()
{
return((iPageSize == -1) ? iPhotoSummaries : iPageSize);
}
function InitSizes()
{
myConfig.panelSize.pages = myConfig.panelSize.pages || -1;
iPageSize = (myConfig.panelSize.rows == -1) ? -1 : (myConfig.panelSize.rows * myConfig.panelSize.cols);
iPhotoSummaries = ((myConfig.panelSize.pages == -1) || (iPageSize == -1)) ? dataSource.GetCount() : Math.min(dataSource.GetCount(), (myConfig.panelSize.pages * iPageSize));
iTextSummaries = Math.max(0, Math.min(dataSource.GetCount() - iPhotoSummaries, myConfig.textPreviewCount));
iPagesCount = (iPageSize == -1) ? 1 : Math.ceil(iPhotoSummaries / iPageSize);
oThisView.aoPages = aoPages = new Array(iPagesCount);
oThisView.aoTextSummaries = [];
flPageSizeMultiplier = (iPageSize == -1) ? 1 : (iPageSize / dataSource.GetPartitionSize());
if (dataSource.IsStatic()) InitStaticDataSource();
}
InitSizes();
var iCurrentPage = 0;
var astrPageIds = [];
var ablnRenderedPage = [];
oThisView.PageDiv = function(i)
{
astrPageIds[i] = "Div" + id + i;
return(YAHOO.Btv.String.Format('id="{0}" style="display:{1};"', 
astrPageIds[i],
((i == iCurrentPage) ? 'block' : 'none')
));
}
oThisView.BuildData = function(oSummary)
{
return({config:myConfig.summaryTemplate.config, summary:oSummary, link:fncLinkBuilder(oSummary)});
}
function GetPageData(i, fnc)
{
function HaveData(a, iStart, bln)
{
if (bln) InitSizes();
PreparePageData(i, a);
fnc(aoPages[i]);
}
if (aoPages[i])
{
fnc(aoPages[i])
}
else
{
dataSource.GetPartition(DataSourcePage(i), HaveData);
}
}
oThisView.RenderPage = function(i)
{
function F(p)
{
var el = astrPageIds ? $(astrPageIds[i]) : null;
if (el) el.innerHTML = CreatePage(oThisView, p);
ablnRenderedPage[i] = true;
}
if (!ablnRenderedPage[i])
{
GetPageData(i, F);
}
}
oThisView.CreateHtmlForPage = function(i)
{
if ((i == iCurrentPage) && dataSource.IsStatic())
{
ablnRenderedPage[i] = true;
return(CreatePage(oThisView, aoPages[i]));
}
}
oThisView.ShowPage = function(iPage)
{
oPageNav.GoTo(iPage);
}
oThisView.PageNav = function()
{
function F(iPage)
{
if (iCurrentPage == iPage) return;
Btv.Ads.Change();
var elC = $(astrPageIds[iCurrentPage]);
var elN = $(astrPageIds[iPage]);
iMaxHeight = Math.max(iMaxHeight, elC.clientHeight);
if (iMaxHeight > 0) elN.style.minHeight = iMaxHeight + "px";
oThisView.RenderPage(iPage);
elC.style.display = "none";
elN.style.display = "block";
iCurrentPage = iPage;
}
var aoLinks = [];
for (var i=0; i < oThisView.aoPages.length; i++)
{
if (false && dataSource.IsStatic())
{
var p = oThisView.aoPages[i];
var lr = p[p.length - 1];
var ls = lr.summaries[lr.summaries.length - 1];
var strTooltip = p[0].summaries[0].title + " - " + ls.title;
aoLinks.push({tooltip:strTooltip});
}
else
{
aoLinks.push({tooltip:i});
}
}
var oSelfOut = {};
var s= Btv.Templating.Run("PageNavigation", {links:aoLinks, currentIndex:iCurrentPage, callback:F, self:oSelfOut});
oPageNav = oSelfOut.value;
return(s);
}
window.setTimeout(function(){oThisView.RenderPage(iCurrentPage)}, 1);
})(config);
_write('\n');CreatePage = function(oView, oPage) {var $text = [];var _write = function(text) {$text.push((typeof text == "number")?text:(text||""));};_write('\n');var row;if(oPage instanceof Array) {for(var row_index=0; row_index<oPage.length; row_index++) {row = oPage[row_index];_write('\n<div class=\"gallery_thumb_row\" style=\"clear:both;\">\n');var summary;if(row.summaries instanceof Array) {for(var summary_index=0; summary_index<row.summaries.length; summary_index++) {summary = row.summaries[summary_index];_write('\n');_write(Btv.Templating.Run(oView.config.summaryTemplate.name, oView.BuildData(summary)));_write('\n');}} else {for (var summary_index in row.summaries) {summary = row.summaries[summary_index];_write('\n');_write(Btv.Templating.Run(oView.config.summaryTemplate.name, oView.BuildData(summary)));_write('\n');}}_write('\n</div>\n');}} else {for (var row_index in oPage) {row = oPage[row_index];_write('\n<div class=\"gallery_thumb_row\" style=\"clear:both;\">\n');var summary;if(row.summaries instanceof Array) {for(var summary_index=0; summary_index<row.summaries.length; summary_index++) {summary = row.summaries[summary_index];_write('\n');_write(Btv.Templating.Run(oView.config.summaryTemplate.name, oView.BuildData(summary)));_write('\n');}} else {for (var summary_index in row.summaries) {summary = row.summaries[summary_index];_write('\n');_write(Btv.Templating.Run(oView.config.summaryTemplate.name, oView.BuildData(summary)));_write('\n');}}_write('\n</div>\n');}}_write('\n');;return($text.join(""));};_write('\n<div class=\"btv_module\">\n<div class=\"btv_module_head\"><div class=\"c\"></div></div>\n<div class=\"btv_module_body\">\n<div class=\"c\">\n');if(config.header) {_write('\n');if(config.header.seeMore) {_write('<div style=\"float:right;\"><a href=\"');_write(config.header.seeMore.link);_write('\" class=\"see_all_fix\">See All</a></div>');}_write('\n<h2>');_write(config.header.label);_write('</h2>\n');}_write(' \n<div>\n');if(config.paginglabel) {_write('\n<div style=\"float:left;\"><h2>');_write(config.paginglabel);_write('</h2></div>\n');}_write(' \n<div style=\"float:right; margin-right:10px;\"><div style=\"position:relative; height:33px; top:0px; display:');_write((oView.config.panelSize.pages == -1) ? 'none' : 'block');_write('; visibility:');_write((oView.aoPages.length>1) ? 'visible' : 'hidden');_write(';\">');_write(oView.PageNav());_write('</div></div>\n</div>\n<div style=\"clear:both;\"></div>\n');if(oView.aoPages instanceof Array) {for(var iPage=0; iPage<oView.aoPages.length; iPage++) {_write('\n<div ');_write(oView.PageDiv(iPage));_write('>');_write(oView.CreateHtmlForPage(iPage));_write('</div>\n');}} else {for(var iPage in oView.aoPages) {_write('\n<div ');_write(oView.PageDiv(iPage));_write('>');_write(oView.CreateHtmlForPage(iPage));_write('</div>\n');}}_write('\n');if((oView.aoTextSummaries.length > 0)) {_write('\n<div class=\"gallery_list_text\">\n');var summary;if(oView.aoTextSummaries instanceof Array) {for(var summary_index=0; summary_index<oView.aoTextSummaries.length; summary_index++) {summary = oView.aoTextSummaries[summary_index];_write('\n<div><a href=\"\">');_write(summary.title);_write(' (');_write(summary.photoCount);_write(')</a> <span class=\"gallery_comments\">- comments (');_write(summary.commentCount);_write(')</span></div>\n');}} else {for (var summary_index in oView.aoTextSummaries) {summary = oView.aoTextSummaries[summary_index];_write('\n<div><a href=\"\">');_write(summary.title);_write(' (');_write(summary.photoCount);_write(')</a> <span class=\"gallery_comments\">- comments (');_write(summary.commentCount);_write(')</span></div>\n');}}_write('\n</div>\n');}_write(' \n');if(config.footer) {_write('\n<div class=\"gallery_see_all_text\"><a href=\"');_write(config.footer.seeMore.link);_write('\">');_write(config.footer.seeMore.text);_write('</a></div>\n');}_write(' \n<div style=\"clear:both;\"></div>\n</div>\n</div>\n<div class=\"btv_module_foot\"><div class=\"c\"></div></div>\n</div>\n');}return $text.join("");}},{id:"PhotoLink",fnc:function($data){var $text = [];var _write = function(text) {$text.push((typeof text == "number")?text:(text||""));};with($data){ _write('\n<span class=\"');_write(config.outerClass);_write('\"><a href=\"');_write(link);_write('\"><img src=\"');_write(summary.image);_write('\" /></a></span> \n');}return $text.join("");}},{id:"PageNavigation",fnc:function($data){var $text = [];var _write = function(text) {$text.push((typeof text == "number")?text:(text||""));};with($data){ _write('\n');
var oView = new function()
{
var oThisView = this;
if (self) self.value = oThisView;
var iCurrent = currentIndex || 0;;
var id = YAHOO.Btv.Runtime.GetNextID();
oThisView.GoTo = function(i)
{
iNext = Math.max(0, Math.min(links.length-1, i));
if (iCurrent != iNext)
{
$(id + "Link" + iCurrent).className = '';
$(id + "Link" + iNext).className = 'strong';
iCurrent = iNext;
callback(iCurrent);
}
}
function GoBy(i)
{
oThisView.GoTo(iCurrent + i);
}
this.strGoTo = $R(oThisView.GoTo); 
this.strGoBy = $R(GoBy); 
oThisView.PageLink = function(i)
{
return(YAHOO.Btv.String.Format('id="{0}Link{1}" href="#" onclick="{2}({3});return(false);" {4} title="{5}"', 
id, 
i,
this.strGoTo,
i,
((i == iCurrent) ? ' class="strong"' : ''),
links ? links[i].tooltip : ""
));
}
}
_write('\n<div class=\"next-graphic-toggle\" style=\"width:auto;\">\n<div>\n<a href=\"#\" onclick=\"');_write(oView.strGoBy);_write('(-1);return(false);\" class=\"next-graphic-toggle-left\"></a><a href=\"#\" onclick=\"');_write(oView.strGoBy);_write('(1);return(false);\" class=\"next-graphic-toggle-right\"></a>\n</div>\n<div class=\"next-graphic-toggle-position\">\n'); for (var i=0; links && (i < links.length); i++) { _write('\n<a ');_write(oView.PageLink(i));_write('></a>\n'); } _write('\n</div>\n</div>\n');}return $text.join("");}}]);
