// =========================================
// UPDATE IMAGES CLASS
// =========================================
// Actually updates the $('images') element.
// Populates with a list of images.

var updateImages =
{
    //Defaults
    pageNumber : 1,
    // CSS Styles
    listMargin : 0,
    imageWidth : 219,
    imageHeight : 219,
    smallImageWidth : 120,
    smallImageHeight : 120,
    imageSizeCutOff : 20,
    useSmallImages : false,
    imageBorderWidth : 1,
    imageBorderColor : "#000",
    imageShadow : true,
    imageMargin : 5,
    imageHeaderHeight : 100,
    parentId : 'images',
    cleanUrl : false,
    resetValue : false,
    
    request : function (url, parentId, menuObject)
    {
        menuObject          = (menuObject) ? menuObject : false;
        parentId            = (parentId) ? parentId : this.parentId;
        url                 = (url) ? url : this.cleanUrl;
        
        this.disablePages();
        this.menuObject     = (menuObject && menuObject.parentId) ? menuObject : false;
        if (menuObject && !this.menuObject && (typeof menuObject == "string"))
        {
            this.menuObject = ($(menuObject)) ? $(menuObject) : false;
            if (this.menuObject)
                this.menuObject.parentId    = menuObject;
        }
        this.loading();
        this.windowSize        = this.getWindowSize();
        this.getWindowImageCount();
        parentObject    = this;    
        if (!this.cleanUrl)
            this.cleanUrl        = url;
        if (url && (this.cleanUrl != url))
            this.cleanUrl       = url;
        if (this.cleanUrl.search(/\?/) == -1)
        {
            url = this.cleanUrl+'?';
        } else if (this.cleanUrl[-1] != '&') {
            url += '&';
        }
        url    += "count="+this.countOfImages+"&page="+this.pageNumber;    
        url = url.replace("&&", "&").replace("??", "?");
        var myXHR = new XHR({
            method: 'get',
            onSuccess: function () {
                eval("parentObject.init("+this.response.text+");");
            }
        }).send(url);
        if ($('debug'))
            $('debug').innerHTML    = url;
    },    
    
    init : function (jsonElement)
    {
        if (!jsonElement)
        {
            alert("There is an error with the category -- \nperhaps there are invalid characters in the feed?");
            this.finishedLoading();
            return false;
        }
        this.images                = (jsonElement.images) ? jsonElement.images : false;
        this.fakeImageLists        = new Array();
        this.jsonElement        = jsonElement;
        this.imageStats         = jsonElement.stats;
        this.getPageNumber();
        parentObject            = this;
        if ($('imagePageNextButton'))
            $('imagePageNextButton').parentNode.removeChild($('imagePageNextButton'));
        if ($('imagePagePrevButton'))
            $('imagePagePrevButton').parentNode.removeChild($('imagePagePrevButton'));  
        if (this.imageList && this.imageContainer)
        {
            this.oldImageList                    = this.imageList;
            this.imageContainer.style.width        = (this.windowSize.width-(this.listMargin*2))+"px";
            this.imageContainer.style.height    = (this.imageBoxHeight*this.imageRows)+"px";
        } else {
            this.imageContainer                    = document.createElement('div');
            this.imageContainer.style.width        = (this.windowSize.width-(this.listMargin*2))+"px";
            this.imageContainer.style.height    = (this.imageBoxHeight*this.imageRows)+"px";
            this.imageContainer.id                = "image-container";
            this.imageContainer.style.overflow    = "hidden";
            this.imageContainer.style.margin    = "0";
            this.imageContainer.style.padding    = "0";
            this.parentElement.appendChild(this.imageContainer);
            this.imageContainer                 = $('image-container');
            this.imageContainer.parentNode.style.width    = "100%";
            this.imageContainer.parentNode.style.overflow    = "hidden";
            this.imageMenu.id                    = "imageMenu";
        }
        if (this.pageNumber > 1)
        {
            this.prevButton = document.createElement('a');
            this.prevButton.href                = "#";
            this.prevButton.id                  = "imagePagePrevButton";
            this.prevButton.style.display       = "none";
            this.prevButton.style.cssFloat        = "left";
            this.prevButton.style.styleFloat    = "left";
            this.prevButton.style.width         = "0";
            this.prevButton.style.height        = "0";
            this.prevButton.style.padding       = "100px 0 0 100px";
            this.prevButton.style.overflow      = "hidden";
            this.prevButton.style.background    = "url(images/imagebank/prev_page.png) top left no-repeat"
            this.prevButton.style.position      = "absolute";
            this.prevButton.style.left          = "5px";
            this.prevButton.style.marginLeft    = "5px";
            this.prevButton.style.top           = "200px";
            this.prevButton.style.zIndex        = 1;
            this.prevButton.appendChild(document.createTextNode('PREVIOUS PAGE'));
            this.imageContainer.appendChild(this.prevButton);
            this.prevButton                     = $('imagePagePrevButton');
            parentPageObject    = this;
            this.prevButton.addEvent('click', function () {
                parentPageObject.prevPage();
            });   
        }
        if (this.imageStats && this.imageStats.pages && (parseInt(this.imageStats.pages) > this.pageNumber))
        {
            this.nextButton = document.createElement('a');
            this.nextButton.href                = "#";
            this.nextButton.id                  = "imagePageNextButton";
            this.nextButton.style.display       = "none";
            this.nextButton.style.cssFloat        = "right";
            this.nextButton.style.styleFloat    = "right";
            this.nextButton.style.width         = "0";
            this.nextButton.style.height        = "0";
            this.nextButton.style.padding       = "100px 0 0 100px";
            this.nextButton.style.overflow      = "hidden";
            this.nextButton.style.background    = "url(images/imagebank/next_page.png) top left no-repeat"
            this.nextButton.style.position      = "absolute";
            this.nextButton.style.right          = "5px";
            this.nextButton.style.top           = "200px";
            this.nextButton.style.zIndex        = 1;
            this.nextButton.style.marginRight   = "5px";
            this.nextButton.appendChild(document.createTextNode('NEXT PAGE'));
            this.imageContainer.appendChild(this.nextButton);
            this.nextButton                     = $('imagePageNextButton');
            parentPageObject    = this;
            this.nextButton.addEvent('click', function () {
                parentPageObject.nextPage();
            });
        }
            
        this.pageDiff   = (this.oldPageNumber) ? this.pageNumber-this.oldPageNumber : 1;
            
        if (this.pageDiff)
        {
            if (this.pageDiff < 1)
                this.pageDiff   = this.pageDiff*-1;
            if (this.pageDiff > 1)
            {
                if (this.pageDiff > 3)
                    this.pageDiff   = 3;
                for (fi=0;fi<(this.pageDiff-1);fi++)
                {
                    this.fakeImageLists[this.fakeImageLists.length]    = this.createImageList(true);
                }
            }
        }
        this.imageList    = this.createImageList();
        this.swapPages();
        this.loadPageNumbers();
        this.finishedLoading();
        parentKeyObject        = this;
        /*
        document.onkeyup    = function (e) { 
            parentKeyObject.checkKeyPress();
        }
        */
    },
    
    createImageList : function (fakeVal)
    {
        
        newImageListContainer                   = document.createElement('div');
        newImageListContainer.style.width       = this.imageContainer.style.width;
        newImageListContainer.style.height      = this.imageBoxHeight*this.imageRows+"px";
        newImageListContainer.style.cssFloat    = "left";
        newImageListContainer.style.styleFloat  = "left";
        newImageListContainer.style.overflow    = "hidden";
        newImageList                    = document.createElement('ul');
        newImageList.style.width        = this.imageCols*this.imageBoxWidth+"px";
        newImageList.style.margin       = "0 "+((this.windowSize.width-parseInt(newImageList.style.width.replace("px", "")))/2)+"px";
        newImageList.style.overflow     = "hidden";
        newImageList.style.listStyle    = "none";
        newImageList.style.cssFloat        = "left";
        newImageList.style.styleFloat    = "left";
        newImageList.style.padding         = "0";
        newImageList.id                    = "image-list";
        
        if (this.useSmallImages == true)
        {
            this.imageWidth     = this.smallImageWidth;
            this.imageHeight    = this.smallImageHeight;
        }
        
        
        colCount    = 0;    
        if (fakeVal)
        {
            for(i=0; i<this.countOfImages; i++)
            {
                imageListItem                    = document.createElement('li');
                imageListItem.style.height        = this.imageHeight+"px";
                imageListItem.style.width        = this.imageWidth+"px";
                imageListItem.style.border        = this.imageBorderWidth+"px solid "+this.imageBorderColor;
                imageListItem.style.margin      = "0"
                imageListItem.style.marginLeft  = this.imageMargin+"px";
                imageListItem.style.marginTop   = this.imageMargin+"px";
                imageListItem.style.overflow    = "hidden";
                imageListItem.style.cssFloat    = "left";
                imageListItem.style.styleFloat    = "left";
                imageListItem.style.background  = "url(images/imagebank/spinning_image_loading_icon.gif) top left no-repeat";
                if (this.imageShadow)
                {
                    imageListItem.style.borderRightWidth    = (this.imageBorderWidth*2)+"px";
                    imageListItem.style.borderBottomWidth    = (this.imageBorderWidth*2)+"px";
                }
                if (colCount >= this.imageCols)
                {
                    colCount    = 0;
                    imageListItem.style.clear   = "left";
                }
                newImageList.appendChild(imageListItem);
                colCount++;
            }
        } else {
            for (i=0; i<this.images.length; i++)
            {
                if (this.images[i])
                {
                    imageSource                        = this.images[i].thumb_name;
                    replaceRegEx                    = /(\[[A-Z]{2}\])*.jpg/;
                    imageListItem                    = document.createElement('li');
                    imageListItemA                    = document.createElement('a');
                    imageListItemA.href                = this.images[i].medium_name;
                    imageListItemA.rel                = "lightbox[imageBank]";
                    imageListItemA.title            = "Photographer: <a href='mailto:"+this.images[i].photog_email+"'>"+this.images[i].photog_name+"</a> | Download <a target='_blank' href='"+imageListItemA.href+"'>this photo</a> ("+"<a target='_blank' href='"+this.images[i].original_name+"'>Hi-Res</a>).";
                    imageListItemImg                = document.createElement('img');
                    imageListItem.style.height        = this.imageHeight+"px";
                    imageListItem.style.width        = this.imageWidth+"px";
                    imageListItem.style.marginLeft  = this.imageMargin+"px";
                    imageListItem.style.marginTop   = this.imageMargin+"px";
                    imageListItem.style.backgroundImage  = "url(images/imagebank/spinning_image_loading_icon.gif)";
                    imageListItem.style.backgroundRepeat    = "no-repeat";
                    imageListItem.style.backgroundPosition  = "center";
                    imageListItemImg.style.height    = this.imageHeight+"px";
                    imageListItemImg.style.width    = this.imageWidth+"px";
                    imageListItemImg.style.border    = "0 solid #000";
                    imageListItem.style.border        = this.imageBorderWidth+"px solid "+this.imageBorderColor;
                    imageListItem.style.overflow    = "hidden";
                    imageListItem.style.cssFloat    = "left";
                    imageListItem.style.styleFloat    = "left";
                    if (this.imageShadow)
                    {
                        imageListItem.style.borderRightWidth    = (this.imageBorderWidth*2)+"px";
                        imageListItem.style.borderBottomWidth    = (this.imageBorderWidth*2)+"px";
                    }
                    imageListItemImg.src        = imageSource;
                    if ($('debug'))
                        $('debug').innerHTML        += "<br/>"+i+": "+imageSource;
                    imageListCaption            = document.createElement('div');
                    imageListItemA.appendChild(imageListItemImg);
                    imageListItem.appendChild(imageListItemA);
                    if (colCount >= this.imageCols)
                    {
                        colCount    = 0;
                        imageListItem.style.clear   = "left";
                    }
                    newImageList.appendChild(imageListItem);
                    colCount++;
                }
            }
        }
        newImageListContainer.appendChild(newImageList);
        return newImageListContainer;
    },
    
    swapPages : function ()
    {
        if (this.oldImageList)
        {
            originalContainerWidth            = this.imageContainer.style.width.replace("px", "");
            containerWidthMultiplier        = this.fakeImageLists.length+2;
            expandedContainerWidth            = (Math.round(parseInt(this.windowSize.width)*containerWidthMultiplier));
            marginDirection                 = "margin-left";
            marginDifference                = (this.windowSize.width-expandedContainerWidth);
            marginStartVal                  = 0;
            marginEndVal                    = marginDifference;
            this.imageContainer.style.width    = expandedContainerWidth+"px";
            if (this.oldPageNumber && (parseInt(this.oldPageNumber) > parseInt(this.pageNumber)))
            {
                this.imageContainer.style.marginLeft    = marginDifference+"px";
                for (i=0;i<this.fakeImageLists.length;i++)
                    this.imageContainer.insertBefore(this.fakeImageLists[i], this.imageContainer.firstChild);
                this.imageContainer.insertBefore(this.imageList, this.imageContainer.firstChild);
                marginStartVal                          = marginDifference;
                marginEndVal                            = 0;
                this.imageList.style.cssFloat, this.imageList.style.styleFloat    = "left";
            } else {
                for (i=0;i<this.fakeImageLists.length;i++)
                    this.imageContainer.appendChild(this.fakeImageLists[i]);
                this.imageContainer.appendChild(this.imageList);
            }
            parentFxObject            = this;
            this.containerMarginFx    = new Fx.Style(this.imageContainer.id, marginDirection, {duration:1000,transition:Fx.Transitions.Back.easeInOut});
            this.containerWidthFx    = new Fx.Style(this.imageContainer.id, 'width');
            this.containerMarginFx.start(marginStartVal+"px", marginEndVal+"px").chain(function () {
                if (parentFxObject.oldImageList)
                    parentFxObject.imageContainer.removeChild(parentFxObject.oldImageList);
                for (i=0; i<parentFxObject.fakeImageLists.length;i++)
                    parentFxObject.imageContainer.removeChild(parentFxObject.fakeImageLists[i]);
                parentFxObject.imageContainer.style.marginLeft    = "0";
                parentFxObject.imageContainer.style.width        = originalContainerWidth+"px";
                parentFxObject.enablePages();
            });
        } else {
            // Animagically 
            this.imageContainer.appendChild(this.imageList);
            this.enablePages();
        }
    },
    
    nextPage : function ()
    {
        this.oldPageNumber  = this.pageNumber;
        this.pageNumber++;
        this.request(this.cleanUrl);
    },
    
    prevPage : function ()
    {
        this.oldPageNumber  = this.pageNumber;
        this.pageNumber--;
        this.request(this.cleanUrl);
    },
    
    disablePages : function ()
    {
        if (this.nextButton)
            this.nextButton.style.display       = "none";
        if (this.prevButton)
            this.prevButton.style.display       = "none";
        if (this.pageNumberElement)
            this.pageNumberElement.style.display   = "none";
    },
    
    enablePages : function ()
    {
        if (this.nextButton)
            this.nextButton.style.display       = "block";
        if (this.prevButton)
            this.prevButton.style.display       = "block";
        if (this.pageNumberElement)
            this.pageNumberElement.style.display   = "block";
    },
    
    loading : function ()
    {
        if (!this.parentElement)
            this.parentElement    = (this.parentId && $(this.parentId)) ? $(this.parentId) : document.getElementsByTagName('body')[0]; 
        if (!this.imageMenu)
        {
            this.imageMenu    = document.createElement("div");
            this.imageMenu.id                       = "imageMenu";
            //this.imageMenu.style.height                ="33px";
            this.imageMenu.style.overflow           = "hidden";
            if (this.menuObject)
            {
                $(this.menuObject.parentId).appendChild(this.imageMenu);
            } else {
                document.getElementsByTagName('body')[0].appendChild(this.imageMenu);
            }
        }    
        if (!this.loadingElement)
        {
            this.loadingElement    = document.createElement('div');
            this.loadingElement.className    = 'progress-bar';
            this.loadingElement.appendChild(document.createTextNode('Loading Images...'));
            this.loadingElement.style.display    = "none";
            this.imageMenu.appendChild(this.loadingElement);
        }
        this.loadingElement.style.display    = "block";
        if (!this.pageNumberElement)
        {
            this.pageNumberElement  = document.createElement("div");
            this.pageNumberElement.id   = "pageNumberContainer";
            this.pageNumberElement.style.display    = "none";
            this.imageMenu.appendChild(this.pageNumberElement);
        } else {
            this.pageNumberElement.style.display    = "none";
        }
        
    },
    
    finishedLoading: function () 
    {
        this.loadingElement.style.display    = "none";
        Lightbox.init();
        parentRefreshObject    = this;
        window.updateImagesObject   = this;
        window.onresize                = this.refreshWindow;
    },
    
    loadPageNumbers: function ()
    {
        if (this.pageNumberElement.hasChildNodes())
        {
            while (this.pageNumberElement.hasChildNodes())
                this.pageNumberElement.removeChild(this.pageNumberElement.firstChild);
        }
        this.pageNumberElement.appendChild(document.createTextNode("Page"));
        this.pageNumberMenu     = document.createElement("select");
        this.pageNumberMenu.id  = 'pageNumberMenu';
        for (i=0;i<parseInt(this.imageStats.pages);i++)
        {
            newPageNumberOption = document.createElement('option');
            newPageNumberOption.value   = i+1;
            newPageNumberOption.appendChild(document.createTextNode((i+1)));
            this.pageNumberMenu.appendChild(newPageNumberOption);
        }
        this.pageNumberMenu.selectedIndex   = this.pageNumber-1;
        this.pageNumberElement.appendChild(this.pageNumberMenu);
        this.pageNumberMenu     = $('pageNumberMenu');
        parentPageNumberMenuObject  = this;
        this.pageNumberMenu.addEvent("change", function () {
            parentPageNumberMenuObject.oldPageNumber    = parentPageNumberMenuObject.pageNumber;
            parentPageNumberMenuObject.pageNumber   = parentPageNumberMenuObject.pageNumberMenu.value;
            parentPageNumberMenuObject.request(parentPageNumberMenuObject.cleanUrl);
        });
        this.pageNumberElement.appendChild(document.createTextNode("of "+this.imageStats.pages));
    },
    
    getPageNumber : function ()
    {
        getVars         = this.jsonElement.get_vars;
        this.pageNumber = getVars.page;
    },

    refreshWindow : function ()
    {
        ourLocation             = window.location.pathname;
        window.location.href = ourLocation+"?page="+window.updateImagesObject.pageNumber;
    },
    
    resetImages : function ()
    {
        this.countOfImages  = false;
        this.useSmallImages = false;
        if (this.imageContainer)
            this.imageContainer.parentNode.removeChild(this.imageContainer);
        if (this.imageList)
            this.imageList.parentNode.removeChild(this.imageList);
        if (this.nextButton)
            this.nextButton.parentNode.removeChild(this.nextButton);
        if (this.prevButton)
            this.prevButton.parentNode.removeChild(this.prevButton);
        
        this.imageContainer = false;
        this.imageList      = false;
        this.nextButton     = false;
        this.prevButton     = false;
    },

    checkKeyPress : function (e)
    {
        if (!this.keyPressDisabled)
        {
            var keyCode = (window.event) ? event.keyCode : e.keyCode;
            if (keyCode == 37)
                this.prevPage();
            if (keyCode == 39)
                this.nextPage();
        }
    },
            
    getWindowSize : function () 
    {
        var myWidth = 0, myHeight = 0;
        var returnVar    = new Object();
        if( typeof( window.innerWidth ) == 'number' ) {
            //Non-IE
            myWidth = window.innerWidth;
            myHeight = window.innerHeight;
        } else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
            //IE 6+ in 'standards compliant mode'
            myWidth = document.documentElement.clientWidth;
            myHeight = document.documentElement.clientHeight;
        } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
            //IE 4 compatible
            myWidth = document.body.clientWidth;
            myHeight = document.body.clientHeight;
        }
        returnVar.width        = myWidth;
        returnVar.height    = myHeight;
        return returnVar;
    },
    
    getWindowImageCount : function () 
    {
        tempImageWidth          = this.imageWidth;
        tempImageHeight         = this.imageHeight;
        if (this.useSmallImages == true)
        {
            tempImageWidth      = this.smallImageWidth;
            tempImageHeight     = this.smallImageHeight;
        }
        countOfImages           = 0;
        this.imageBoxWidth      = (tempImageWidth+this.imageBorderWidth+(this.imageMargin*2));
        this.imageBoxHeight     = (tempImageHeight+this.imageBorderWidth+(this.imageMargin*2));
        this.imageCols          = Math.floor(((this.windowSize.width-(this.listMargin*2))/this.imageBoxWidth));
        this.imageRows          = Math.round(((this.windowSize.height-this.imageHeaderHeight)/this.imageBoxHeight));
        countOfImages           = (this.imageCols*this.imageRows);
        
        if (countOfImages < 1)
            countOfImages    = 1;
            
        if ((countOfImages < this.imageSizeCutOff) && (!this.useSmallImages))
        {   
            this.useSmallImages = true;
            this.getWindowImageCount(); 
        } else {  
        this.countOfImages    = countOfImages;
        }
    }
}
