/*
    This script file is heavily dependent on variables set elsewhere
*/

var PortfolioDetailsViewManager = {

    currentPage: 1,
    currentGalleryImages: [],
    currentPageName:"portfolioImages",
    currentMode:"single",
    pagingHandler: null,
    enableUpdates: true,

    Init: function(portfolioId,
                   currentImageId,
                   //currentImageUrl,
                   numberOfPages,
                   currentGallery,
                   galleries,
                   thumbnailsPerPage,
                   //numberOfPortfolioImages,
                   images,
                   imageKeys,
                   wbPages,
                   portfolioFavorite) {

        this.portfolioId = portfolioId;
        this.portfolioFavorite = portfolioFavorite;
        this.currentImageId = currentImageId;

        //this.currentImageUrl = currentImageUrl;
        this.numberOfPages = numberOfPages;
        this.currentGallery = currentGallery;
        this.galleries = galleries;
        this.thumbnailsPerPage = thumbnailsPerPage;
        //this.numberOfPortfolioImages = numberOfPortfolioImages

        this.images = images;
        this.imageKeys = imageKeys;
        this.wbPages = wbPages;

        if (this.currentImageId == null) {
            this.currentImageUrl = null;
        } else {
            this.currentImageUrl = this.images[this.currentImageId].largeThumbnailUrl;
        }
    },

    LoadPageImages: function() {
        if (this.currentGallery != 0) {
            this.FilterByGallery(this.currentGallery);
        } else {
            this.BuildImageDisplay();
        }
    },

    BuildImageDisplay: function()  {
        var imageDisplay = this.GetImageDisplayElement(); 
        var imageHtml = "";
        if (this.currentMode == "single") {
            imageHtml = this.BuildSingleImageDisplay();
        } else {
            imageHtml = this.BuildThumbnailDisplay();
        }
        imageDisplay.innerHTML=imageHtml;
        this.ResetFavoriteDisplay();
        this.EnableDisableNavLinks();
    },

    GetTotalPagesElement: function () {
        var pagesIndicator = document.getElementById("totalPagesIndicator");
        if (pagesIndicator == null) { 
            pagesIndicator = parent.document.getElementById("portTotalPagesIndicator");
        }
        return pagesIndicator;
    },

    GetCurrentPageElement: function () {
        var currentIndicator = document.getElementById("currentPageIndicator");
        if (currentIndicator == null) {
            currentIndicator = parent.document.getElementById("portCurrentPageIndicator");
        }
        return currentIndicator;
    },

    BuildSingleImageDisplay: function () {
        var index;

        var totalPages;

        if (!this.currentGallery) {
            //totalPages = this.numberOfPortfolioImages;
            totalPages = this.imageKeys.length;
            index = IndexOfArrayElement(this.imageKeys, this.currentImageId);
        } else {
            totalPages = this.currentGalleryImages.length;
            index = IndexOfArrayElement(this.currentGalleryImages, this.currentImageId);
        }

        var pagesIndicator = this.GetTotalPagesElement();
        pagesIndicator.innerHTML = totalPages;

        var currentIndicator = this.GetCurrentPageElement();
        currentIndicator.innerHTML = index + 1;

        /*
        Doc.GetElement("totalPagesIndicator").innerHTML = totalPages;
        Doc.GetElement("currentPageIndicator").innerHTML = index + 1;
        */

        if (this.currentImageId != null) {
            var imageHtml = '<div class="portImageWrapper">';
            if (this.images[this.currentImageId].title || this.images[this.currentImageId].caption) {
                imageHtml += '<div class="portImageToolTip" id="portCaption">';
                imageHtml += '<a href="javascript:void(PortDetailCaption.HideCaption())" class="portImageToolTipClose"><img src="/static/images/close-dialogs.gif" /></a>';
            }
            if (this.images[this.currentImageId].title) {
                imageHtml += '<div class="portImageToolTipTitle">' + HtmlEscape(this.images[this.currentImageId].title) + '</div>';
            }
            if (this.images[this.currentImageId].caption) {
                imageHtml += '<div class="portImageToolTipContent">' + HtmlEscape(this.images[this.currentImageId].caption) + '</div>';
            }
            if (this.images[this.currentImageId].title || this.images[this.currentImageId].caption) {
                imageHtml += '</div>';
            }
            imageHtml += '<img src="' + this.currentImageUrl + '"/>'+
                '</div>';
        } else {
            var imageHtml = "";
        }

        if (this.enableUpdates) {
            this.StatsImageView(this.currentImageId);
        }

        this.PreloadPrevNextImages();

        return imageHtml
        
    },

    CalculateImagePage: function (imageId) {
        var images = (this.currentGallery) ? this.currentGalleryImages : this.imageKeys;
        
        for (var i = 0;  i < images.length; ++i) {
            if (images[i] == imageId) {
                return Math.floor(i/this.thumbnailsPerPage) + 1;
            }
        }
        return null;
    },

    BuildThumbnailDisplay: function () {

        var imageHtml ='<ul class="portfolioList">'; 
        var currentImageIndex = (this.currentPage-1) * this.thumbnailsPerPage;
        var index = 0;           

        var images = (this.currentGallery) ? this.currentGalleryImages : this.imageKeys;

        this.numberOfPages = Math.ceil(images.length/this.thumbnailsPerPage);
    
        /*
        Doc.GetElement("currentPageIndicator").innerHTML = this.currentPage;
        Doc.GetElement("totalPagesIndicator").innerHTML = this.numberOfPages;
        */
        var pagesIndicator = this.GetTotalPagesElement();
        pagesIndicator.innerHTML = this.numberOfPages;
        var currentIndicator = this.GetCurrentPageElement();
        currentIndicator.innerHTML = this.currentPage;

        while (index < this.thumbnailsPerPage && currentImageIndex < images.length)
        {
            var imageId = images[currentImageIndex];

            imageUrl = this.images[imageId].smallThumbnailUrl;

            if (imageUrl) 
            {
                imageHtml+= '<li class="portfolioListItem"><a href="javascript:void(ShowSingleImage(' + imageId + '))"> <img width="109" height="73" src="' + imageUrl + '" style="border:0px"/></a></li>';
            }
            currentImageIndex += 1;
            index += 1;
        }
        imageHtml += "</ul>";

        if (this.enableUpdates) {
            this.StatsImageView(null);
        }

        return imageHtml;
    },

    ShowSingleImage: function(imageId){
        this.currentMode= "single";
        this.currentImageId = imageId;
        this.currentImageUrl = this.images[this.currentImageId].largeThumbnailUrl;
        this.BuildImageDisplay();
        this.SetToggleLinks();
        PortDetailCaption.UpdateCaptionLink();
    },

    SetActiveGallery: function (galleryId) {
        var galleryList = document.getElementById("galleryList");
        if (galleryList == null) 
        {
            galleryList = document.getElementById("galleryListP");
        }
        var galleryItems = galleryList.getElementsByTagName("li");

        for (var i=0; i<galleryItems.length; ++i) {
            var m = galleryItems[i].id.match(/galleryItem_(\d+)/);
            if (m) {
                if (m[1]*1 == galleryId) {
                    galleryItems[i].className = "active"
                } else {
                    galleryItems[i].className = "";
                }
            }
        }
    },

    FixSidebarActiveLink: function () {
        var item = null;
        this.SetActiveGallery((this.currentPageName == "portfolioImages") ? this.currentGallery : -1);
        item = document.getElementById("wbGalleryItem");
        if (item) {
            item.className = (this.currentPageName == "workbookImages") ? "active": "";
        }
        item = document.getElementById("contactPageLink");
        if (item) {
            item.className = (this.currentPageName == "artistContact") ? "active": "";
        }
        item = document.getElementById("aboutPageLink");
        if (item) {
            item.className = (this.currentPageName == "artistBio") ? "active": "";
        }
    },

    LoadWbPage: function (pageNumber) {
        var item = this.wbPages[pageNumber-1];
        var container = document.getElementById("workbookImages");
        container.innerHTML = "";

        for (var i=0; i<item.length; ++i) {
            var img = document.createElement("img");
            img.src = item[i];
            img.className = "workbookImage";
            container.appendChild(img);
        }

        var pagesIndicator = this.GetTotalPagesElement();
        pagesIndicator.innerHTML = this.wbPages.length;

        var currentIndicator = this.GetCurrentPageElement();
        currentIndicator.innerHTML = pageNumber;

        this.currentPage = pageNumber;

        if (pageNumber <= 1) {
            this.DisablePrevNavLink();
        } else {
            this.EnablePrevNavLink();
        }

        if (pageNumber >= this.wbPages.length) {
            this.DisableNextNavLink();
        } else {
            this.EnableNextNavLink();
        }
        ShowHideToggle("portFullView", false);
        ShowHideToggle("portThumbView", false);
        this.SetActiveGallery(null);
        var wbItem = document.getElementById("wbGalleryItem");
        wbItem.className = "active";

        this.StatsWorkbookView();
    },

    FilterByGallery:function (galleryId) {

        this.currentGallery = galleryId;
        //var allImages = Doc.GetElement("allimages")
        var display="none";

        this.SetActiveGallery(galleryId);

        if (galleryId > 0) {
            display="block";
            this.currentGalleryImages = this.galleries[this.currentGallery].images;
            this.currentImageId = this.currentGalleryImages[0];
        } else {
            if (this.imageKeys.length == 0) {
                this.currentImageId = null;
            } else {
                this.currentImageId = this.imageKeys[0];
            }
        }
        this.currentPage = 1;

        if (this.currentImageId == null) {
            this.currentImageUrl = null;
        } else {
            this.currentImageUrl = this.images[this.currentImageId].largeThumbnailUrl;
        }
       
       //if (allImages) {allImages.style.display=display};
        this.BuildImageDisplay();
       //ShowOnly('portfolioImages');
    },


    ToggleImageMode: function(newMode)  {
        if (this.pagingHandler != null) {
            this.currentMode = newMode;
            this.currentPage = 1;
            this.pagingHandler.ToggleThumbMode(newMode != "single");
        } else {
            this.currentMode = newMode;
            if (newMode == "thumbnail") {
                var newPage = this.CalculateImagePage(this.currentImageId);
                this.currentPage = (newPage === null) ? 1 : newPage;
            } else {
                this.currentPage = 1;
            }
            this.BuildImageDisplay();
        }
        this.SetToggleLinks()
        PortDetailCaption.UpdateCaptionLink();
    },

    GetFullViewModeImage: function() {
        var result = document.getElementById("portFullView");
        if (result) {
            return result;
        }
        result = parent.document.getElementById("portFullView");
        return result;
    },

    GetThumbViewModeImage: function() {
        var result = document.getElementById("portThumbView");
        if (result) { 
            return result;
        }
        result = parent.document.getElementById("portThumbView");
        return result;
    },

    SetToggleLinks: function() {
        if (this.currentMode == "single") {
            this.GetFullViewModeImage().src = "/static/images/port_full_active.gif";
            this.GetThumbViewModeImage().src = "/static/images/port_thumb_inactive.gif";
        } else {
            this.GetFullViewModeImage().src = "/static/images/port_full_inactive.gif";
            this.GetThumbViewModeImage().src = "/static/images/port_thumb_active.gif";
        }
    },

    FindPrevNavLink: function () {
        var link = null;
        if (parent) {
            // This can fail when called via the standalone port viewer if embedded in a frame
            try {
                link = parent.document.getElementById("portPrevLink");
            }
            catch (e) {
                link = null;
            }
        }
        if (link == null) {
            link = document.getElementById("portPrevLink");
        }
        return link;
    },

    DisablePrevNavLink: function () {
        var link = this.FindPrevNavLink();
        if (link) {
            link.innerHTML = '<span class="disabled">previous</span>';
        }
    },

    EnablePrevNavLink: function () {
        var link = this.FindPrevNavLink();
        if (link) {
            link.innerHTML = '<a href="javascript:void(PortPrevOrNextImage(\'prev\'))">previous</a>';
        }
    },

    FindNextNavLink: function () {
        var link = null;
        if (parent) {
            // This can fail when called via the standalone port viewer if embedded in a frame
            try {
                link = parent.document.getElementById("portNextLink");
            }
            catch (e) {
                link = null;
            }
        }
        if (link == null) {
            link = document.getElementById("portNextLink");
        }
        return link;
    },

    DisableNextNavLink: function () {
        var link = this.FindNextNavLink();
        if (link) {
            link.innerHTML = '<span class="disabled">next</span>';
        }
    },

    EnableNextNavLink: function () { 
        var link = this.FindNextNavLink();
        if (link) {
            link.innerHTML = '<a href="javascript:void(PortPrevOrNextImage(\'next\'))">next</a>';
        }
    },

    EnableDisableNavLinks: function () {
        if (this.pagingHandler != null) {
            if (this.currentPage == 1) {
                this.DisablePrevNavLink();
            } else {
                this.EnablePrevNavLink();
            }

            if (this.currentPage == this.pagingHandler.pageCount) {
                this.DisableNextNavLink();
            } else {
                this.EnableNextNavLink();
            }
        } else {
            // TODO: Move this to a paging handler
            if (this.currentMode == "single") {
                var images = (this.currentGallery) ? this.currentGalleryImages: this.imageKeys;
                var index = IndexOfArrayElement(images, this.currentImageId);

                if (index == 0) {
                    this.DisablePrevNavLink();
                } else {
                    this.EnablePrevNavLink();
                }
                if (index == images.length-1) {
                    this.DisableNextNavLink();
                } else {
                    this.EnableNextNavLink();
                }
            } else {
                if (this.currentPage == 1) {
                    this.DisablePrevNavLink();
                } else {
                    this.EnablePrevNavLink();
                }
                if (this.currentPage == this.numberOfPages) {
                    this.DisableNextNavLink();
                } else {
                    this.EnableNextNavLink();
                }
            }
        }
        PortDetailCaption.UpdateCaptionLink();
    },

    PrevOrNextImage: function (tag) {
        if (this.pagingHandler != null) {
            if (tag == "next") {
                this.currentPage += 1;
                if (this.currentPage > this.pagingHandler.pageCount) {
                    this.currentPage = this.pagingHandler.pageCount;
                }
            } else {
                this.currentPage -= 1;
                if (this.currentPage < 1) {
                    this.currentPage = 1;
                }
            }
            var indicator = this.GetCurrentPageElement();
            indicator.innerHTML = this.currentPage;

            this.pagingHandler.ShowPage(this.currentPage);
            this.EnableDisableNavLinks();
        } else {
            // TODO: Move this to a paging handler
            if (this.currentPageName == "workbookImages") {
                if (tag == "next") {
                    this.currentPage += 1;
                    if (this.currentPage > this.wbPages.length) {
                        this.currentPage = this.wbPages.length;
                    }
                } else {
                    this.currentPage -= 1;
                    if (this.currentPage < 1) {
                        this.currentPage = 1;
                    }
                }
                this.LoadWbPage(this.currentPage);
            } else {
                if (this.currentMode == "single"){
                   if (tag=="next") {
                       this.NextImage();
                   } else {
                       this.PrevImage();
                   }
                } else {
                    if (tag == "next") {
                        this.currentPage +=1;
                        if (this.currentPage > this.numberOfPages) {
                            //this.currentPage = 1
                            this.currentPage = this.numberOfPages;
                        };
                    } else {
                        this.currentPage -= 1;
                        if (this.currentPage < 1) {
                            //this.currentPage = this.numberOfPages
                            this.currentPage = 1;
                        }
                    }
                }
                this.BuildImageDisplay();
            }
        }
    },

    StatsImageView: function (imageId) {
        var statsData = {
            portfolioId: (this.portfolioId == 0)?null:this.portfolioId,
            galleryId: (this.currentGallery == 0)?null:this.currentGallery,
            imageId: (imageId == null || imageId == 0)?null: 1*imageId
        };
        var statsDataJson = JSONstring.make(statsData);
        ajaxPostData("/stats/image_view", statsDataJson, null, null, "application/x-workbook-image-view");
    },

    StatsWorkbookView: function () {
        var statsData = {
            portfolioId: (this.portfolioId == 0)?null:this.portfolioId
        };
        var statsDataJson = JSONstring.make(statsData);
        ajaxPostData("/stats/workbook_view", statsDataJson, null, null, "application/x-workbook-wb-view");
    },

    GetPrevImageInfo: function () {
        if (this.imageKeys.length == 0 || (this.currentGallery && this.currentGalleryImages.length == 0)) {
            return null;
        } else {
            var images = (this.currentGallery) ? this.currentGalleryImages: this.imageKeys;
            var index = IndexOfArrayElement(images, this.currentImageId);

            var newImageId = null;

            while (newImageId == null) {
                index -= 1;
                if (index < 0) {
                    index = 0;
                }
                newImageId = images[index];
            }
            return {
                index: index,
                imageId: newImageId,
                thumbnailUrl: this.images[newImageId].largeThumbnailUrl
            };
        }
    },

    GetNextImageInfo: function () {
        if (this.imageKeys.length == 0 || (this.currentGallery && this.currentGalleryImages.length == 0)) {
            return null;
        } else {
            var images = (this.currentGallery) ? this.currentGalleryImages: this.imageKeys;
            var index = IndexOfArrayElement(images, this.currentImageId);
            var newImageId = null;

            while (newImageId == null) {
                index += 1;

                if (index == images.length) {
                    index = images.length-1;
                }

                newImageId = images[index];
            }

            return {
                index: index,
                imageId: newImageId,
                thumbnailUrl: this.images[newImageId].largeThumbnailUrl
            }
        }
    },

    NextImage:function () {
        var info = this.GetNextImageInfo();
        
        if (info) {
            // Doc.GetElement("currentPageIndicator").innerHTML = info.index+1;
            var currentIndicator = this.GetCurrentPageElement();
            currentIndicator.innerHTML = info.index + 1;
            this.currentImageId = info.imageId;
            this.currentImageUrl = info.thumbnailUrl;
            this.PreloadPrevNextImages();
        }
    },

    PrevImage: function () {
        var info = this.GetPrevImageInfo();

        if (info) {
            //Doc.GetElement("currentPageIndicator").innerHTML = info.index+1;
            var currentIndicator = this.GetCurrentPageElement();
            currentIndicator.innerHTML = info.index + 1;
            this.currentImageId = info.imageId;
            this.currentImageUrl = info.thumbnailUrl;
            this.PreloadPrevNextImages();
        }
    },

    PreloadPrevNextImages: function () {
        var prevInfo = this.GetPrevImageInfo();
        var nextInfo = this.GetNextImageInfo();

        if (prevInfo) {
            var prevCacheImage = document.getElementById("prevCacheImage");
            prevCacheImage.src = prevInfo.thumbnailUrl;
        }

        if (nextInfo) {
            var nextCacheImage = document.getElementById("nextCacheImage");
            nextCacheImage.src = nextInfo.thumbnailUrl;
        }
    },

    SetFavoriteStatus: function(favorite) {
        if (this.currentMode == "single") {
            this.GetCurrentImage().favorite = favorite;
        } else {
            if (this.currentGallery == 0) {
                this.portfolioFavorite = favorite;
            } else {
                this.GetCurrentGallery().favorite = favorite;
            }
        }
        this.ResetFavoriteDisplay();

        /*
        var image = document.getElementById("portBookmarkToggle");

        if (image) {
            if (favorite) {
                image.src = "/static/images/bookmarkTrue.gif";
            } else {
                image.src = "/static/images/bookmarkFalse.gif";
            }
        }
        */
    },

    ResetFavoriteDisplay: function() {
        var favorite;
        if (this.currentMode == "single") {
            var image = this.GetCurrentImage();
            if (image != null) {
                favorite = this.GetCurrentImage().favorite;
            } else {
                favorite = null;
            }
        } else {
            if (this.currentGallery == 0) {
                favorite = this.portfolioFavorite;
            } else {
                favorite = this.GetCurrentGallery().favorite;
            }
        }
        UpdateFavoriteDisplay(favorite);
    },

    GetCurrentImage: function() {
        return this.images[this.currentImageId]
    },

    GetCurrentGallery: function() {
        return this.galleries[this.currentGallery];
    },

    GetImageDisplayElement: function () {
        return Doc.GetElement("portfolioImages");    
    },

    LoadPage: function (url, onLoad) {
        var pageHolder = document.getElementById("portfolioInnerPage");
        ajaxGet(url, 
            function (responseText) {
                pageHolder.innerHTML = responseText;
                if (onLoad) {
                    onLoad();
                }
            },

            function (responseStatus, responseText) {
                pageHolder.innerHTML = responseText;
            }
        );
    },

    SetPagingHandler: function (handler) {
        this.pagingHandler = handler;
        this.currentPage = 1;
        var indicator =  this.GetTotalPagesElement();
        indicator.innerHTML = this.pagingHandler.pageCount;
        indicator = this.GetCurrentPageElement();
        indicator.innerHTML = this.currentPage;
        this.pagingHandler.ShowPage(this.currentPage);
        this.EnableDisableNavLinks();

        if (this.pagingHandler.showNavLinks) {
            ShowPortNavLinks();
            ShowHideToggle("portFullView", this.pagingHandler.showToggleThumb);
            ShowHideToggle("portThumbView", this.pagingHandler.showToggleThumb);
        } else {
            HidePortNavLinks();
        }
    }
} //end PortfolioDetailsViewManager 


var RepGalleryPageHandler = {
    kRepGalleriesPerPage: 24,
    pageCount: 0, 
    showToggleThumb: false,
    showNavLinks: true,

    ShowPage: function (num) {
        var container = document.getElementById("rosterPortfolios");
        var items = container.getElementsByTagName("li");
        for (var i=0; i<items.length; ++i) {
            var m = items[i].id.match(/repGallery_p(\d+)_(\d+)/);
            if (m) {
                if (m[1] == num-1) {
                    items[i].style.display = "";
                } else {
                    items[i].style.display = "none";
                }
            }
        }
    },

    ToggleThumbMode: function (mode) {
    }
};

var RepRosterPageHandler = {
    pageCount: 0,
    showToggleThumb: false,
    showNavLinks: true,

    ShowPage: function (num) {
        var rosterList = document.getElementById("rosterList");
        var items = rosterList.getElementsByTagName("li");
        for (var i=0; i<items.length; ++i) {
            var m = items[i].id.match(/repRoster_p(\d+)_(\d+)/);
            if (m) {
                if (m[1] == num-1) {
                    items[i].style.display = "";
                } else {
                    items[i].style.display = "none";
                }
            }
        }
    },

    ToggleThumbMode: function (mode) {
    }
};

var NullPageHandler = {
    pageCount: 0,
    showToggleThumb: false,
    showNavLinks: false,

    ShowPage: function (num) {
    },

    ToggleThumbMode: function (mode) {
    }
};


function ShowPrevNextArtist()
{
    var prevArtistLink = document.getElementById("repPrevArtist");
    if (prevArtistLink) {
        prevArtistLink.style.visibility = "";
    }

    var sepArtistLink = document.getElementById("repSepArtist");
    if (sepArtistLink) {
        sepArtistLink.style.visibility = "";
    }

    var nextArtistLink = document.getElementById("repNextArtist");
    if (nextArtistLink) {
        nextArtistLink.style.visibility = "";
    }
    RepArtistManager.EnableDisablePrevNextArtist();
}

function HidePrevNextArtist()
{
    var prevArtistLink = document.getElementById("repPrevArtist");
    if (prevArtistLink) {
        prevArtistLink.style.visibility = "hidden";
    }

    var sepArtistLink = document.getElementById("repSepArtist");
    if (sepArtistLink) {
        sepArtistLink.style.visibility = "hidden";
    }

    var nextArtistLink = document.getElementById("repNextArtist");
    if (nextArtistLink) {
        nextArtistLink.style.visibility = "hidden";
    }
}



var RepArtistManager = {
    currentSource: 3,
    repId: null,
    portfolios: [],
    currentPortfolio: null,
    firstSourceIndex: null,
    lastSourceIndex: null,

    ChooseSource: function (source) {
        this.firstSourceIndex = null;
        this.lastSourceIndex = null;

        this.currentSource = source;
        for (var i=0; i<this.portfolios.length; ++i) {
            if ((this.portfolios[i].section & source) != 0) {
                this.firstSourceIndex = i;
                break;
            }
        }
        for (var i=this.portfolios.length-1; i>=0; --i) {
            if ((this.portfolios[i].section & source) != 0) {
                this.lastSourceIndex = i;
                break;
            }
        }
    },

    EnableDisablePrevNextArtist: function () {
        var disablePrev = false;
        var disableNext = false;

        if (this.currentPortfolio == null || this.firstSourceIndex == null || this.lastSourceIndex == null) {
            disablePrev = true;
            disableNext = true;
        } else {
            var foundIndex = null;
            for (var i=0; i<this.portfolios.length; ++i) {
                if (this.portfolios[i].id == this.currentPortfolio) {
                    foundIndex = i;
                    break;
                }
            }
            if (foundIndex == null) {
                disablePrev = true;
                disableNext = true;
            } else {
                disablePrev = (foundIndex == this.firstSourceIndex);
                disableNext = (foundIndex == this.lastSourceIndex);
            }
        }

        var prevArtistLink = document.getElementById("repPrevArtist");
        if (prevArtistLink) {
            if (disablePrev) {
                prevArtistLink.className = "disabled";
            } else {
                prevArtistLink.className = "";
            }
        }

        var nextArtistLink = document.getElementById("repNextArtist");
        if (nextArtistLink) {
            if (disableNext) {
                nextArtistLink.className = "disabled";
            } else {
                nextArtistLink.className = "";
            }
        }
    },

    PrevArtist: function () {
        var foundIndex = null;
        for (var i=0; i<this.portfolios.length; ++i) {
            if (this.portfolios[i].id == this.currentPortfolio) {
                foundIndex = i;
                break;
            }
        }
        if (foundIndex != null && this.firstSourceIndex != null && this.lastSourceIndex != null) {
            if (foundIndex > this.firstSourceIndex) {
                var newPortfolio = this.portfolios[foundIndex-1].id;
                LoadRepPortfolio(this.repId, newPortfolio);
            }
        }
    },

    NextArtist: function () {
        var foundIndex = null;
        for (var i=0; i<this.portfolios.length; ++i) {
            if (this.portfolios[i].id == this.currentPortfolio) {
                foundIndex = i;
                break;
            }
        }
        if (foundIndex != null && this.firstSourceIndex != null && this.lastSourceIndex != null) {
            if (foundIndex < this.lastSourceIndex) {
                var newPortfolio = this.portfolios[foundIndex+1].id;
                LoadRepPortfolio(this.repId, newPortfolio);
            }
        }
    }
};


function RepNextArtist() {
    RepArtistManager.NextArtist();
}


function RepPrevArtist() {
    RepArtistManager.PrevArtist();
}


function ActivateRepLink(id)
{
    var repLinks = document.getElementById('repLinks');
    var links = repLinks.getElementsByTagName('li');
    for (var i=0; i<links.length; ++i) {
        if (links[i].id == id) {
            links[i].className = "active";
        } else {
            links[i].className = "";
        }
    }
}

function Trim(value) {
   var temp = value;
   var obj = /^(\s*)([\W\w]*)(\b\s*$)/;
   if (obj.test(temp)) { temp = temp.replace(obj, '$2'); }
   //var obj = /  /g;
   //while (temp.match(obj)) { temp = temp.replace(obj, " "); }
   return temp;
}


function AddClass(elem, className)
{
    var classString = elem.className;
    if (classString.indexOf(className) == -1) {
        classString += " " + className;
        elem.className = classString;
    }
}

function RemoveClass(elem, className)
{
    var classString = elem.className;
    classString = Trim(classString.replace(className, ""));
    elem.className = classString;
}


function InitializeRepRoster() 
{
    var artistSide = document.getElementById("artistSide");
    artistSide.innerHTML = "";

    var title = document.getElementById("portViewerTitle");
    RemoveClass(title, "artistFromRep");

    var rosterList = document.getElementById("rosterList");
    var elements = rosterList.getElementsByTagName("li");
    RepRosterPageHandler.pageCount = 1 * (elements[elements.length-1].id.match(/repRoster_p(\d+)_(\d+)/)[1]) + 1;
    viewManager.SetPagingHandler(RepRosterPageHandler);
    HidePrevNextArtist();
    ActivateRepLink('repRoster');

    RepArtistManager.ChooseSource(1 | 2);
}

function InitializeRepGallery()
{
    var artistSide = document.getElementById("artistSide");
    artistSide.innerHTML = "";

    var title = document.getElementById("portViewerTitle");
    RemoveClass(title, "artistFromRep");

    var portfolioList = document.getElementById("repPortfolioList");
    var elements = portfolioList.getElementsByTagName("li");
    RepGalleryPageHandler.pageCount = 1 * (elements[elements.length-1].id.match(/repGallery_p(\d+)_(\d+)/)[1]) + 1;
    viewManager.SetPagingHandler(RepGalleryPageHandler);
    HidePrevNextArtist();
}


function InitializeRepPhoto()
{
    InitializeRepGallery();
    ActivateRepLink('repGalleryPhoto');
    
    RepArtistManager.ChooseSource(1);
}


function InitializeRepIllus()
{
    InitializeRepGallery();
    ActivateRepLink('repGalleryIllus');

    RepArtistManager.ChooseSource(2);
}


function InitializeRepContactPage() 
{
    var artistSide = document.getElementById("artistSide");
    artistSide.innerHTML = "";
    viewManager.SetPagingHandler(NullPageHandler);
    CheckEmailForm();
    HidePrevNextArtist();
}


function InitializeRepContact()
{
    InitializeRepContactPage();
    ActivateRepLink('repContact');
}


function InitializeRepAbout() 
{
    InitializeRepContactPage();
    ActivateRepLink('repAbout');
}

/// Global functions
function LoadPortfolioDetails(url, portfolioId, postLoadCallback) {
    ajaxGet(url, DataLoaded, DataNotLoaded, postLoadCallback);
}

function DataLoaded(response, postLoad) {
    var data = JSONstring.toObject(response);

    var portfolio =JSONstring.toObject(data.portfolio);

    if (data.currentGallery) {
        currentGallery = data.currentGallery
    } else {
        currentGallery = 0
    }

    viewManager.Init(portfolio.portfolioId,
                     data.initialImageId,
                     //portfolio.largeThumbnailUrl,
                     portfolio.numberOfPages,
                     currentGallery,
                     portfolio.galleries,
                     data.thumbnailsPerPage,
                     //portfolio.numberOfImages,
                     portfolio.images,
                     portfolio.imageKeys,
                     portfolio.portfolioFavorite);

    viewManager.LoadPageImages();
    if (postLoad) {
        postLoad(portfolio);
    }
}


function DataNotLoaded(status, response) {

    alert ("error loading portfolio data") ;
}
function LoadPageImages () {

    viewManager.LoadPageImages() ;
}

function ShowSingleImage(imageId) {
    viewManager.ShowSingleImage(imageId);
}

function ToggleImageMode(mode) {
    viewManager.ToggleImageMode(mode);
}

function PrevOrNextImage(tag) {
    viewManager.PrevOrNextImage(tag);
}

function ToggleShowCaption() {
    PortDetailCaption.ToggleCaption();
}


function FilterByGallery(galleryId) {
    viewManager.FilterByGallery(galleryId);

}

function UpdateFavoriteDisplay(favorite) {
    var image = document.getElementById("portBookmarkToggle");

    if (image) {
        if (favorite) {
            image.src = "/static/images/bookmarkTrue.gif";
        } else {
            image.src = "/static/images/bookmarkFalse.gif";
        }
    }
}

viewManager = PortfolioDetailsViewManager;


function EmailPortfolio() {
    ajaxPostForm(document.emailPortfolioForm, kEmailPortfolioUrl, 
        function (response) {
            if (PostSucceeded(response.status)) {
                var theForm = document.getElementById("emailPortfolioForm");
                theForm.style.display = "none";
                var theConfirm = document.getElementById("confirmMessage");
                theConfirm.style.display = "block";
            /*
                Validation.ShowMessages("validationMessages", [{
                    message: "Email sent",
                    isSuccess: true
                }]);
            */
            } else {
                if (response.status == 400) {
                    messages = [{ message: "Please revisit form for required information." }]
                } else if (response.status == 409) {
                    messages = [{ message: "One or more of the email addresses supplied is invalid." }]
                } else {
                    messages = [{ message: "An error (HTTP " + response.status + ") occurred while sending your email." }]
                }
                Validation.ShowMessages("validationMessages", messages);
            }
        }
    );
}
