YE.on(window, 'load', init);

var pageNavTop,
    pageNavBottom,
    photosPerPage = 15,
    ajaxMainPhotoSize = 'Medium',
    ajaxThumbPhotoSize = 'Tiny',
    selectLastImageOnPage = false,
    photoInfo = {},
    loadedImage = [],
    throbbingCount = 0,
    goGetSlideshowSWF = false,
    imageRequest;

photoInfo.size = 0;

var hashUpdated = new YAHOO.util.CustomEvent('hashChanged', window, false, YAHOO.util.CustomEvent.FLAT);

SM.history = function() {
    var ua = navigator.userAgent.toLowerCase();
    var prevHash = '';

    if (Yua.webkit && Yua.webkit < 522) {
        var hashHistory = [];
    }

    return {
        init: function(entry) {
            /*
            if (YE.isIE) {
                var historyFrame = document.createElement('iframe');
                historyFrame.id = 'historyFrame';
                historyFrame.name = 'historyFrame';

                YD.setStyle(historyFrame, 'width', '0px');
                YD.setStyle(historyFrame, 'height', '0px');
                YD.setStyle(historyFrame, 'border', '0px');
                YD.setStyle(historyFrame, 'visibility', 'hidden');
                YD.setStyle(historyFrame, 'zIndex', '-1');

                document.body.appendChild(historyFrame);
            }
            */

            YE.on(document.body,'click',function(e) {
                var el = YE.getTarget(e);

                while (el.tagName.toLowerCase() !== "body") {
                    if (el.tagName.toLowerCase() === "a") {
                        if (el.href && el.href.indexOf('#') > -1) {
                            this.add(el.href.split('#')[1]);
                        }

                        break;
                    }

                    el = el.parentNode;
                }
            },this,true);

            var urlHash = window.location.href.split('#');

            if (urlHash[1]) {
                //entry = urlHash[1].match(/[^_]+/);
                entry = urlHash[1];
            }

            this.add(entry);

            if(window.onhashchange) {
                window.onhashchange = this.watch();  
            }
            else {
                window.setInterval(this.watch, 100);
            }
        },

        add: function(entry) {
            if (entry) {
                
                if (Yua.webkit && Yua.webkit < 522) {
                    if (hashHistory.length === 0) {
                        hashHistory[history.length] = entry;
                    } else {
                        hashHistory[history.length + 1] = entry;
                    }
                } else if (Yua.ie && Yua.ie <= 7) {
                    var historyFrame = window.frames.historyFrame;

                    if (historyFrame) {
                        historyFrame.document.execCommand('Stop');
                        historyFrame.location.href = '/mimic.mg?q=' + entry + '&t=' + document.title;
                    }
                } else {
                    setTimeout( function() {
                        var locHash = window.location.href.split("#");
                        if (locHash[1] != entry) {
                            location.replace(locHash[0] + '#' + entry);
                        }
                    }, 200);
                }
            }
        },

        watch: function() {
            var curHash;

            if (Yua.webkit && Yua.webkit < 522) {
                if (hashHistory[history.length]) {
                    curHash = hashHistory[history.length].toString(10);
                }
            } else if (Yua.ie && Yua.ie <= 7) {
                var historyFrame = window.frames.historyFrame;

                if (historyFrame) {
                    curHash = historyFrame.location.href.split('&')[0];
                    curHash = curHash.split('=')[1];
                }
            } else {
                if (location.hash !== '') {
                    curHash = window.location.href.split("#")[1];
                }
            }
            if (curHash && prevHash != curHash) {
                if (Yua.ie && window.location.href.split("#")[1] != curHash) {
                    location.hash = curHash;
                }

                hashUpdated.fire(curHash);
                prevHash = curHash;
            }
        }
    };
}();

hashUpdated.subscribe(function(navHash) {
    var foundPhoto,
        findPosition,
        currentPosition,
        lbSize;

    var pieces = navHash.toString().split('-');
    var photoId = (pieces ? pieces[0] : navHash.toString()).match(/[^_]+/);
    
    if (pieces[0] === 'P') {
        if (getPageOn(navHash) == pageOn) {
            window.clearTimeout(trySwapAgain);
            foundPhoto = false;
            findPosition = ((pieces[1] - 1) * pieces[2]) + 1;

            for (var i in photoInfo) {
                currentPosition = parseInt(photoInfo[ImageID].position, 10);

                if (parseInt(photoInfo[i].position, 10) == findPosition && findPosition != currentPosition) {
                    swapOutPrimary(i);
                    foundPhoto = true;
                }
            }

            if (!foundPhoto) {
                getPhotos(getPageOn(navHash));
            }
        } else {
            getPhotos(getPageOn(navHash));
        }
    } else if (pieces[2] === 'LB') {
        lbSize = findSize(pieces[1]);

        if (YD.inDocument('fsssButton') && goGetSlideshowSWF) {
            SM.buttons.slideshowButton.getFlash().pauseFetch();
        }

        //openLB(pieces[0], lbSize);
        openLBOptions(pieces[0], lbSize, null, {'allowDetails': true});
    } else if (YAHOO.lang.isNumber(pieces) || /(\d+)_([a-z0-9]{5})/i.test(pieces)) {
    
        if (photoId !== ImageID && photoInfo[photoId] !== undefined) {
            if (photoInfo[photoId].pageOn != pageOn) {
                pageOn = photoInfo[photoId].pageOn;
                refreshPage(pageOn, photoId);
            } else {
                window.clearTimeout(trySwapAgain);
                swapOutPrimary(photoId);
            }
        } else if (photoInfo[photoId] === undefined) {
            ImageID = photoId;
            getPhotos('');
        }
        
    }
    else {
      getPhotos('');
    }

    if (pieces[2] !== 'LB') {
        closeLightBox('');
    }
});

function init() {
    if (typeof ImageID !== 'undefined' && ImageID != '' && YD.inDocument('photos')) {
        var stretchyInfo = SM.stretchy.init(stretchyAttr);
        findLightBoxSize();
        photosPerPage = stretchyInfo[0];
        ajaxMainPhotoSize = stretchyInfo[1];

        YE.addListener(document, "keydown", keyDown);

        SM.history.init(ImageID + '_' + ImageKey);
    }
}

//YE.onDOMReady(init);

var selectLastImageOnPage = false;
var ignoreFirstKeydown = false;

function keyDown(e) {
    if (YE.getTarget(e).nodeName.toLowerCase() === "input" || YE.getTarget(e).nodeName.toLowerCase() === "textarea" || e.metaKey) {
        return;
    }

    if (ignoreFirstKeydown) {
        ignoreFirstKeydown = true;
        return;
    }

    if (photoInfo[ImageID]) {
        var currentPosition = parseInt(photoInfo[ImageID].position, 10);
        var currentPage = parseInt(photoInfo[ImageID].pageOn, 10);
    }

    var newPosition = '';
    var newPage = '';
    var thisHash = '';
    var lightBox = YD.getStyle('lightBoxStage', 'display') === 'block' ? true : false;

    switch (e.keyCode) {
        case 37:
            // left key
            if (!lightBox) {
                if (Yua.webkit && Yua.webkit < 522) {
                    ignoreFirstKeydown = true;
                }
                
                if (e.shiftKey) {
                    newPage = currentPage - 1;
                } else {
                    newPosition = currentPosition - 1;
                }

                YE.stopEvent(e);
            }

            break;
        case 39:
            // right key
            if (!lightBox) {
                if (Yua.webkit && Yua.webkit < 522) {
                    ignoreFirstKeydown = true;
                }

                if (e.shiftKey) {
                    newPage = currentPage + 1;
                } else {
                    newPosition = currentPosition + 1;
               }

               YE.stopEvent(e);
            }

            break;
        case 83:
            // S key
            if (lightBox) {
                thisHash = lightBoxImageID + '_' + photoInfo[lightBoxImageID].ImageKey + '-S-LB';
            } else {
                thisHash = ImageID + '_' + photoInfo[ImageID].ImageKey + '-S-LB';
            }

            location.hash = thisHash;
            SM.history.add(thisHash);

            break;
        case 77:
            // M key
            if (lightBox) {
                thisHash = lightBoxImageID + '_' + photoInfo[lightBoxImageID].ImageKey + '-M-LB';
            } else {
                thisHash = ImageID + '_' + photoInfo[ImageID].ImageKey + '-M-LB';
            }

            location.hash = thisHash;
            SM.history.add(thisHash);

            break;
        case 76:
            // L key
            if (lightBox) {
                thisHash = lightBoxImageID + '_' + photoInfo[lightBoxImageID].ImageKey + '-L-LB';
            } else {
                thisHash = ImageID + '_' + photoInfo[ImageID].ImageKey + '-L-LB';
            }
            location.hash = thisHash;
            SM.history.add(thisHash);

            break;
        case 79:
            // O key
            if (lightBox) {
                thisHash = lightBoxImageID + '_' + photoInfo[lightBoxImageID].ImageKey + '-O-LB';
            } else {
                thisHash = ImageID + '_' + photoInfo[ImageID].ImageKey + '-O-LB';
            }
            location.hash = thisHash;
            SM.history.add(thisHash);

            break;
        case 49:
            // 1 key
            if (lightBox) {
                thisHash = lightBoxImageID + '_' + photoInfo[lightBoxImageID].ImageKey + '-XL-LB';
            } else {
                thisHash = ImageID + '_' + photoInfo[ImageID].ImageKey + '-XL-LB';
            }
            location.hash = thisHash;
            SM.history.add(thisHash);

            break;
        case 50:
            // 2 key
            if (lightBox) {
                thisHash = lightBoxImageID + '_' + photoInfo[lightBoxImageID].ImageKey + '-X2-LB';
            } else {
                thisHash = ImageID + '_' + photoInfo[ImageID].ImageKey + '-X2-LB';
            }
            location.hash = thisHash;
            SM.history.add(thisHash);

            break;
        case 51:
            // 3 key
            if (lightBox) {
                thisHash = lightBoxImageID + '_' + photoInfo[lightBoxImageID].ImageKey + '-X3-LB';
            } else {
                thisHash = ImageID + '_' + photoInfo[ImageID].ImageKey + '-X3-LB';
            }
            location.hash = thisHash;
            SM.history.add(thisHash);

            break;
        case 65:
            // O key
            if (lightBox) {
                thisHash = lightBoxImageID + '_' + photoInfo[lightBoxImageID].ImageKey + '-A-LB';
            } else {
                thisHash = ImageID + '_' + photoInfo[ImageID].ImageKey + '-A-LB';
            }
            location.hash = thisHash;
            SM.history.add(thisHash);

            break;
        case 88:
            // x key
            if (lightBox) {
                thisHash = lightBoxImageID + '_'+ lightBoxImageKey;
                location.hash = thisHash;
                SM.history.add(thisHash);
            }

            break;
        default:
            return;
    }

    if (newPosition !== '') {
       if (newPosition < 1) {
           newPosition = 1;
       }

       if (newPosition > totalPhotos) {
           newPosition = position;
       }

       // got the position, find the photo
       for (var i in photoInfo) {
            if (parseInt(photoInfo[i].position, 10) == newPosition && newPosition != currentPosition) {
                thisHash = photoInfo[i].ImageID + '_' + photoInfo[i].ImageKey;
            }
       }

       // can't find the image, may be on another page
        if (thisHash === '') {
            if (newPosition > currentPosition) {
                newPage = photoInfo[ImageID].pageOn + 1;
            } else {
                newPage = photoInfo[ImageID].pageOn - 1;
                selectLastImageOnPage = true;
            }
        }
    }

    if (newPage !== '') {
        if (newPage < 1) {
            newPage = 1;
        }

        if (newPage > Math.ceil(totalPhotos / photosPerPage)) {
            newPage = Math.ceil(totalPhotos / photosPerPage);
        }

        if (newPage != currentPage) {
            thisHash = 'P-' + newPage + '-' + photosPerPage;
        }
    }

    if (thisHash !== '') {
        if (selectLastImageOnPage === true) {
            getPhotos(newPage);
        } else {
            location.hash = thisHash;
            SM.history.add(thisHash);
        }

        closePhotoBar();
    }
}

function getPageOn(navHash) {
    var oldPage;
    var pieces = navHash.split('-');

    if (photosPerPage == pieces[2]) {
        return pieces[1];
    } else {
        oldPage = pieces[1] * pieces[2];
        return Math.ceil(oldPage / photosPerPage);
    }
}

var totalThrobbingCount = 0;
var skipPrimary = false;

function refreshPage(matchingPage, selectImageID) {
    if (YD.inDocument('fsssButton') && goGetSlideshowSWF) {
        SM.buttons.slideshowButton.getFlash().pauseFetch();
    }
        
    window.clearTimeout(trySwapAgain);

    if (skipPrimary) {
        swapOutPrimary(selectImageID, false);
        skipPrimary = false;
    } else {
        swapOutPrimary(selectImageID, true);
    }
    
    YAHOO.lang.later(10,this,function(){
        drawAjaxThumbs(matchingPage, selectImageID);
    });
    
    }

function drawAjaxThumbs(matchingPage, selectImageID) {
    totalThrobbingCount = 0;

    var purgeObj = YD.get('thumbnails');

    YE.purgeElement(purgeObj, true);
    
    while (purgeObj.hasChildNodes()) {
        purgeObj.removeChild(purgeObj.childNodes[0]);
    }

    var doOnce = true;
    var position = ((pageOn - 1) * photosPerPage) + 1;
    var stopPosition = position + photosPerPage;

    if (stopPosition > totalPhotos) {
        stopPosition = totalPhotos + 1;
    }

    totalThrobbingCount = stopPosition - position;

    var i, photoID, photoKey, photoDiv, anchor, photo;

    while (position < stopPosition) {
        for (i in photoInfo) {
            if (photoInfo[i].position == position && position < stopPosition) {
                if (doOnce === true) {
                    purgeObj = YD.get('thumbnails');
                    YE.purgeElement(purgeObj, true);

                    while (purgeObj.hasChildNodes()) {
                        purgeObj.removeChild(purgeObj.childNodes[0]);
                    }

                    doOnce = false;
                }

                photoID = photoInfo[i].ImageID;
                photoKey = photoInfo[i].ImageKey;
                photoDiv = document.createElement('div');
                photoDiv.setAttribute('id', 'photoBox_' + photoID);

                YD.addClass(photoDiv,'photo');
                YD.addClass(photoDiv,'size_' + ajaxThumbPhotoSize);
                
                var photoWrapper = document.createElement('div');

                if (photoInfo[photoID][ajaxThumbPhotoSize + 'Width'] != 0) {
                    YD.setStyle(photoWrapper, 'width', photoInfo[photoID][ajaxThumbPhotoSize + 'Width'] + 'px');
                }
                
                if (photoInfo[photoID][ajaxThumbPhotoSize + 'Height'] != 0) {
                    YD.setStyle(photoWrapper, 'height', photoInfo[photoID][ajaxThumbPhotoSize + 'Height'] + 'px');
                }
                
                YD.setStyle(photoWrapper, 'position', 'relative');
                YD.setStyle(photoWrapper, 'margin', '0 auto');

                anchor = document.createElement('a');
                anchor.setAttribute("href", '#' + photoID + '_' + photoKey);
                //anchor.setAttribute("href", '#' + photoID);
                anchor.setAttribute('id', 'Anchor_' + ajaxThumbPhotoSize + '_' + photoID);

                photo = document.createElement('img');
                YD.addClass(photo,'draggable');
                YD.addClass(photo,'imgBorder');
                photo.setAttribute("alt", photoInfo[i].altCaption);
                photo.setAttribute("title", photoInfo[i].altCaption);
                photo.setAttribute('id', ajaxThumbPhotoSize + '_' + photoID);
                YD.setStyle(photo, 'cursor', 'pointer');

                if (photoInfo[photoID][ajaxThumbPhotoSize + 'Width'] != 0) {
                    YD.setStyle(photo, 'width', photoInfo[photoID][ajaxThumbPhotoSize + 'Width'] + 'px');
                }

                if (photoInfo[photoID][ajaxThumbPhotoSize + 'Height'] != 0) {
                    YD.setStyle(photo, 'height', photoInfo[photoID][ajaxThumbPhotoSize + 'Height'] + 'px');
                }
                
                if (!Yua.ie) {
                    if(!loadedImage[photoInfo[i][ajaxThumbPhotoSize + 'Src'].split('/')[2]]) {
                        YD.setStyle(photo, 'opacity', 0);
                    }
                }


                YE.addListener(photo, 'mouseover', function(e) {
                    swapImgBorder(this.id, 'over');
                });

                YE.addListener(photo, 'mouseout', function(e) {
                    swapImgBorder(this.id, 'out');
                });


                YE.addListener(photo, 'load', function(e) {
                    if (!Yua.ie) {
                        YD.setStyle(this,'opacity',1);
                    }

                    turnOffThrobber();
                });


                YE.addListener(photo, 'error', function(e) {
                    turnOffThrobber();
                });

                YE.addListener(photo, 'abort', function(e) {
                    turnOffThrobber();
                });

                anchor.appendChild(photo);

                photoWrapper.appendChild(anchor);
                
                if (photoInfo[i].Format === "MPG" || photoInfo[i].Format === "MP4" && photoInfo[i].Status !== 'Preprocess') {
                    var playMovieDiv = document.createElement('div');
                    YD.addClass(playMovieDiv,'moviePlayButton');
                    anchor.appendChild(playMovieDiv);
                }
                
                if (photoInfo[i].Archive) {
                    var archiveButton = document.createElement('div');
                    archiveButton.setAttribute('title', 'SmugVault File');
                    
                    YE.on(archiveButton,'click',function() {
                        location.href='/homepage/smugvault.mg?browseOpen=1&AlbumID='+AlbumID;
                    });
                    
                    YD.addClass(archiveButton,'archiveButton');
                    
                    photoWrapper.appendChild(archiveButton);
                }

                photoDiv.appendChild(photoWrapper);
                
                YD.removeClass(photo, 'protected');
                YD.removeClass(photo, 'vault_Tiny');
                YD.removeClass(photo, 'vault_Thumb');

                YD.get('thumbnails').appendChild(photoDiv);
                
                if (photoInfo[i].Format === "ARC") {
                    photo.setAttribute('src', '/img/spacer.gif');
                    YD.addClass(photo, 'vault_' + ajaxThumbPhotoSize);
                } else if (!photoInfo[i]['protected'] || photoInfo[photoID][ajaxThumbPhotoSize + 'Height'] == 0 || photoInfo[photoID][ajaxThumbPhotoSize + 'Width'] == 0) {
                    YD.setStyle(photo, 'background-image', 'none');
                    photo.setAttribute('src', photoInfo[i][ajaxThumbPhotoSize + 'Src']);
                    if (photoInfo[ImageID]['protected']) {
                        YD.addClass(displayImage, 'protected');
                    }
                } else {
                    photo.setAttribute('src', '/img/spacer.gif');
                    YD.setStyle(photo, 'background-image', 'url(' + photoInfo[i][ajaxThumbPhotoSize + 'Src'] + ')');
                    YD.addClass(photo, 'protected');
                }

                position++;
            }
        }
    }

    if (movePhotosAjaxTool === true) {
        movePhotosAjax(true);
    }


    // is the fullscreen slideshow button here?
    if (YD.inDocument('fsssButton') && goGetSlideshowSWF == false) {
        goGetSlideshowSWF = true;
        setTimeout(function() {
            SM.buttons.slideshowButton.getFlash().loadSlideSWF();
        }, 2000);
    }
    
    if (YD.inDocument('fsssButton') && goGetSlideshowSWF) {
        SM.buttons.slideshowButton.getFlash().resumeFetch();
    }

    //setTimeout(function(){drawGalleryNav(totalPhotos, photosPerPage, pageOn);}, 0);
    drawGalleryNav(totalPhotos, photosPerPage, pageOn);

    }

function turnOffThrobber() {
    throbbingCount++;

    if (throbbingCount >= totalThrobbingCount) {
        ajaxThrobber('off');
        throbbingCount = 0;
    }
}



var totalPhotos = 0;
var photoInfo = {};

function swapImgBorder(PhotoID, state) {
    if (getImageID(PhotoID) != ImageID) {
        if (state === "over") {
            YD.replaceClass(PhotoID, 'imgBorder', 'imgBorderOn');
        } else if (state === "out") {
            YD.replaceClass(PhotoID, 'imgBorderOn', 'imgBorder');
        }
    }
}

function getImageID(takeApart) {
    var parts = takeApart.split("_");
    return parts[parts.length-1];
}

function canBuyPhoto() {
    if(YD.inDocument('buyButton')) {
        if (photoInfo[ImageID].canBuy) {
            SM.buttons.buyButton.enableSingleBuy();
        } else {
            SM.buttons.buyButton.disableSingleBuy(); 
        }
    }
}

function updateToolsMenu() {
    if(YD.inDocument('toolsButton')) {
        SM.buttons.toolsButton.quickUpdate();
    }
}

function showShareButton() {
    if(YD.inDocument('shareButton')) {
        if (photoInfo[ImageID].shareLink !== '' &&  photoInfo[ImageID].Status.toLowerCase() !== "hidden") {
            //SM.buttons.shareButton.enable();
        } else {
            //SM.buttons.shareButton.disable();
        }
    }
}

function updateCaption() {
    var useThis, updateType, purgeObj, editBox, captionTop, captionBottom;

    if (photoInfo[ImageID].canEdit) {
        useThis = photoInfo[ImageID].editCaption;

        var nct = YD.get('newCaption_top');
        var ncb = YD.get('newCaption_bottom');

        if (ncb) {
            ncb.value = useThis;
        }

        if (nct) {
            nct.value = useThis;
        }

        if (photoInfo[ImageID].editCaption !== '') {
            updateType = "edit";
        } else {
            updateType = "add caption";
        }

        captionTop = photoInfo[ImageID].caption + " <a href=\"javascript:toggleDIV('editCaption_top','caption_top', 'block');\">" + updateType + "<\/a>";
        captionBottom = photoInfo[ImageID].caption + " <a href=\"javascript:toggleDIV('editCaption_bottom','caption_bottom', 'block');\">" + updateType + "<\/a>";
    } else {
        captionTop = photoInfo[ImageID].caption;
        captionBottom = photoInfo[ImageID].caption;
    }

    purgeObj = YD.get('caption_top');

    if (purgeObj) {
        YE.purgeElement(purgeObj, true);

        while (purgeObj.hasChildNodes()) {
            purgeObj.removeChild(purgeObj.childNodes[0]);
        }

        purgeObj.innerHTML = captionTop;

        editBox = YD.getNextSibling(purgeObj);
        
        if (editBox && YD.getStyle(editBox, 'display') === 'block') {
            YD.setStyle(purgeObj, 'display', 'block');
            YD.setStyle(editBox, 'display', 'none');
        }
    }

    purgeObj = YD.get('caption_bottom');

    if (purgeObj) {
        YE.purgeElement(purgeObj, true);

        while (purgeObj.hasChildNodes()) {
            purgeObj.removeChild(purgeObj.childNodes[0]);
        }

        purgeObj.innerHTML = captionBottom;

        editBox = YD.getNextSibling(purgeObj);
        
        if (editBox && YD.getStyle(editBox, 'display') === 'block') {
            YD.setStyle(purgeObj, 'display', 'block');
            YD.setStyle(editBox, 'display', 'none');
        }
    }

    var mainImage = YD.get('mainImage');

    if (mainImage) {
        var altCaption = photoInfo[ImageID].altCaption;
        mainImage.setAttribute('alt', altCaption);
        mainImage.setAttribute('title', altCaption);
    }
}


function fadeInPhoto() {
    // we may not allow the picked size
    var photoSize = findClosestSize(photoInfo[ImageID],ajaxMainPhotoSize);

    var borderOn = YD.getElementsByClassName('imgBorderOn', 'img', 'thumbnails');

    if (borderOn) {
        YD.batch(borderOn, function(el) {
            YD.replaceClass(el, 'imgBorderOn', 'imgBorder');
        });
    }

    YD.replaceClass(YD.get('Tiny_' + ImageID), 'imgBorder', 'imgBorderOn');

    updateCaption();
    


    if (YD.inDocument('hidePhotoTool')) {
        if (photoInfo[ImageID].Format !== "ARC") {
            YD.setStyle('hidePhotoBox','display','inline');
       
            if (photoInfo[ImageID].Status.toLowerCase() === "hidden") {
                YD.get('hidePhotoTool').checked = true;
                YD.addClass('hidePhotoText','title');
            } else {
                YD.get('hidePhotoTool').checked = false;
                YD.removeClass('hidePhotoText','title');
            }
        } else {
            YD.setStyle('hidePhotoBox','display','none');
        }
    }

    var photoBy = YD.get('photoBy');

    if (photoInfo[ImageID].photoBy !== '') {
        YD.setStyle(photoBy, 'display', 'block');
        YE.purgeElement(photoBy, true);

        while (photoBy.hasChildNodes()) {
          photoBy.removeChild(photoBy.childNodes[0]);
        }

        photoBy.innerHTML = photoInfo[ImageID].photoBy;
    } else {
        photoBy.innerHTML = '';
        YD.setStyle(photoBy, 'display', 'none');
    }

    var fileNameBox = YD.get('fileNameBox');

    if (photoInfo[ImageID].fileName !== '') {
        YD.setStyle(fileNameBox, 'display', 'block');
        fileNameBox.innerHTML = '<span class=\"title\">Filename:</span> ' + photoInfo[ImageID].fileName;
    } else {
        fileNameBox.innerHTML = '';
        YD.setStyle(fileNameBox, 'display', 'none');
    }

    var el = YD.get('mainImage');
    var attachToMe = YD.get('ajaxPhotoBox');
    attachToMe.innerHTML = '';
    
    var photoWrapper = document.createElement('div');
    if (photoInfo[ImageID][ajaxThumbPhotoSize + 'Width'] != 0) {
        YD.setStyle(photoWrapper, 'width', photoInfo[ImageID][photoSize + 'Width'] + 'px');
    }
    
    if (photoInfo[ImageID][ajaxThumbPhotoSize + 'Height'] != 0) {
        YD.setStyle(photoWrapper, 'height', photoInfo[ImageID][photoSize + 'Height'] + 'px');
    }
    
    YD.setStyle(photoWrapper, 'position', 'relative');
    YD.setStyle(photoWrapper, 'margin', '0 auto');

    displayAnchor = document.createElement('a');
    
    if (photoInfo[ImageID].Status !== 'Preprocess' && photoInfo[ImageID].Format !== 'ARC') {
        anchorHref = ImageID + '_' + photoInfo[ImageID].ImageKey + '-A-LB';
    } else {
        anchorHref = ImageID;
    }
    
    displayAnchor.href = '#' + anchorHref;

    if (Yua.webkit && Yua.webkit < 522) {
        YE.on(displayAnchor,'click', function(e) {
            SM.history.add(this.href.split('#')[1]);
        });
    }

    displayAnchor.id = 'mainImageLink';

    displayImage = document.createElement('img');
    YD.addClass(displayImage,'imgBorder');
    displayImage.id = 'mainImage';
    displayImage.setAttribute('galleryimg', 'no');

    YE.on(displayImage, 'mouseover', function(e) {
        photoHover(this.id, ImageID);
    });

    displayAnchor.appendChild(displayImage);
    photoWrapper.appendChild(displayAnchor);

    if (photoInfo[ImageID].Format === "MPG" || photoInfo[ImageID].Format === "MP4" && photoInfo[ImageID].Status !== 'Preprocess') {
        var playMovieDiv = document.createElement('div');
        YD.addClass(playMovieDiv,'moviePlayButton');
        displayAnchor.appendChild(playMovieDiv);
    }
    
    if (photoInfo[ImageID].Archive) {
        var archiveButton = document.createElement('div');
        archiveButton.setAttribute('title', 'SmugVault File');
        YE.on(archiveButton,'click',function() {
            location.href='/homepage/smugvault.mg?browseOpen=1&AlbumID='+AlbumID;
        });
        
        YD.addClass(archiveButton,'archiveButton');
        
        photoWrapper.appendChild(archiveButton);
    }
    

    if (Yua.gecko && 1 === 2) {
        if (photoInfo[ImageID][photoSize + 'Width'] % 2 === 1) {
            YD.setStyle(displayImage, 'marginLeft', '1px');
        } else {
            YD.setStyle(displayImage, 'marginLeft', '0');
        }
    }

    if (photoInfo[ImageID][photoSize + 'Width'] != 0) {
        YD.setStyle(displayImage, 'width', photoInfo[ImageID][photoSize + 'Width'] + 'px');
    } else {
        YD.setStyle(displayImage, 'width', '');
    }

    if (photoInfo[ImageID][photoSize + 'Height'] != 0) {
        YD.setStyle(displayImage, 'height', photoInfo[ImageID][photoSize + 'Height'] + 'px');
    } else {
        YD.setStyle(displayImage, 'height', '');
    }

    if (YD.inDocument('EmbedMovie')) {
        removeFromDOM('EmbedMovie');
    }

    var ajaxPhotoBox = YD.get('ajaxPhotoBox');
    var ajaxMovieBox = YD.get('ajaxMovieBox');

    ajaxMovieBox.innerHTML = '';

    if (photoInfo[ImageID].movieURL === '') {
        if(photoInfo[ImageID].Format === "MPG" || photoInfo[ImageID].Format === "MP4") {
            YD.addClass('ajaxPhotoBox','isMovie');
        }
        else {
            YD.removeClass('ajaxPhotoBox','isMovie');
        }

        YD.setStyle(ajaxPhotoBox, 'display', 'block');
        YD.setStyle(ajaxMovieBox, 'display', 'none');
        ajaxMovieBox.innerHTML = '';
        
        YD.removeClass(displayImage, 'protected');
        YD.removeClass(displayImage, 'vault_Small');
        YD.removeClass(displayImage, 'vault_Medium');
        YD.removeClass(displayImage, 'vault_Large');
        YD.removeClass(displayImage, 'vault_XLarge');
        YD.removeClass(displayImage, 'vault_X2Large');
        YD.removeClass(displayImage, 'vault_X3Large');
        
        if (photoInfo[ImageID].Format === "ARC") {
            displayImage.setAttribute('src', '/img/spacer.gif');
            YD.addClass(displayImage, 'vault_'+photoSize);
        }
        else if (!photoInfo[ImageID]['protected'] || photoInfo[ImageID][photoSize + 'Width'] == 0 || photoInfo[ImageID][photoSize + 'Height'] == 0) {
            YD.setStyle(displayImage, 'background-image', 'none');
            displayImage.setAttribute('src', photoInfo[ImageID][photoSize + 'Src']);
            YAHOO.lang.later(500, window, loadedImageRPC, [ImageID, photoSize, ImageKey]);
            //loadedImageRPC(ImageID,photoSize,ImageKey);

            if (photoInfo[ImageID]['protected']) {
                YD.addClass(displayImage, 'protected');
            }
        } else {
            displayImage.setAttribute('src', '/img/spacer.gif');
            YD.setStyle(displayImage, 'background-image', 'url(' + photoInfo[ImageID][photoSize + 'Src'] + ')');
            YAHOO.lang.later(500, window, loadedImageRPC, [ImageID, photoSize, ImageKey]);
            //loadedImageRPC(ImageID,photoSize,ImageKey);

            YD.addClass(displayImage, 'protected');
        }

        var altCaption = photoInfo[ImageID].altCaption;
        displayImage.setAttribute('alt', altCaption);
        displayImage.setAttribute('title', altCaption);
    } else {
        YD.setStyle(ajaxPhotoBox, 'display', 'none');
        YD.setStyle(ajaxMovieBox, 'display', 'block');

        var movieInfo = photoInfo[ImageID].movieURL.split('**|**');

        var EmbedMovie = document.createElement('embed');
        EmbedMovie.setAttribute('id', 'EmbedMovie');
        EmbedMovie.setAttribute('name', 'EmbedMovie');
        EmbedMovie.setAttribute('stretchtofit', 'false');
        EmbedMovie.setAttribute('controls', 'smallconsole');
        EmbedMovie.setAttribute('autostart', 'true');
        YD.setStyle(EmbedMovie,'height', parseInt(movieInfo[2], 10) + 16 + 'px');
        YD.setStyle(EmbedMovie,'width', movieInfo[1] + 'px');
        YD.addClass(EmbedMovie,'movie');
        EmbedMovie.setAttribute("src", movieInfo[0]);
        ajaxMovieBox.appendChild(EmbedMovie);

        var movieHelper = document.createElement("p");
        YD.addClass(movieHelper, 'note');
        ajaxMovieBox.appendChild(movieHelper);
        movieHelper.innerHTML = 'To view this movie, you need to have an MPEG1-capable player like <a href="http://windowsmedia.com/download">Windows Media Player</a> or <a href="http://www.apple.com/quicktime/">Quicktime</a> installed. If you\'re having problems, double-check that you have the very latest version installed. We do not recommend Real Player, as it seems to be prone to error. If youd like to save this movie, right-click <a href="' + movieInfo[0] + '">this link</a> and choose save as. Then you can play it at larger sizes, etc.';
    }

    drawPhotoNav();
    canBuyPhoto();
    updateToolsMenu();
    showShareButton();
    drawKeywords();
    drawComments();

    YD.setStyle('addImageComment','display','none');

    attachToMe.appendChild(photoWrapper);

    if ((photoInfo[ImageID].Format === "MPG" || photoInfo[ImageID].Format === "MP4") && 1 === 2) {
        var movieHelper = document.createElement("p");
        YD.addClass(movieHelper, 'note');
        attachToMe.appendChild(movieHelper);
        movieHelper.innerHTML = 'To view this movie, you need to have an MPEG4-capable player like <a href="http://windowsmedia.com/download">Windows Media Player</a> or <a href="http://www.apple.com/quicktime/">Quicktime</a> installed. If you\'re having problems, double-check that you have the very latest version installed. We do not recommend Real Player, as it seems to be prone to error. If youd like to save this movie, right-click <a href="' + photoInfo[ImageID].MovieSrc + '">this link</a> and choose save as. Then you can play it at larger sizes, etc.';
    }

    if (SM.currentContext.exifBox) {
        SM.currentContext.exifBox.set('imageId_Key', ImageID + '_' + photoInfo[ImageID].ImageKey);
    }
    
    if (YD.inDocument('fsssButton') && goGetSlideshowSWF) {
        SM.buttons.slideshowButton.getFlash().resumeFetch();
    }

    }


function drawKeywords() {
    if (photoInfo[ImageID].showKeywords && ((!photoInfo[ImageID].canEdit && photoInfo[ImageID].keywords !== '') || photoInfo[ImageID].canEdit)) {
        var output = '';

        YD.setStyle('editKeywords', 'display', 'none');
        output = '<span class=\"title\">keywords:<\/span> ' + photoInfo[ImageID].keywords;

        if (photoInfo[ImageID].canEdit) {
            if (photoInfo[ImageID].editKeywords === '') {
                output += ' &#183; <a href=\"javascript:toggleDIV(\'editKeywords\',\'photoKeywords\',\'block\');\">add<\/a>';
            } else {
                output += ' &#183; <a href=\"javascript:toggleDIV(\'editKeywords\',\'photoKeywords\',\'block\');\">edit<\/a>';
            }

            document.getElementById('newKeywords').value = photoInfo[ImageID].editKeywords;
        }

        YD.get('photoKeywords').innerHTML = output;
        YD.setStyle('imageInfo', 'display', 'block');
    } else {
        // remove the keywords boxes
        YD.setStyle('imageInfo', 'display', 'none');
        YD.setStyle('editKeywords', 'display', 'none');
    }
}

var trySwapAgain = '';

function swapOutPrimary(PhotoID, force) {
    if (photoInfo[PhotoID]) {
        if (YD.inDocument('fsssButton') && goGetSlideshowSWF) {
            SM.buttons.slideshowButton.getFlash().pauseFetch();
        }

        if (PhotoID != ImageID || force === true) {
            ImageID = PhotoID;
            ImageKey = photoInfo[PhotoID].ImageKey;
            AlbumID = photoInfo[PhotoID].AlbumID;
            AlbumKey = photoInfo[PhotoID].AlbumKey;

            fadeInPhoto();
        }
    }

    }

function drawComments() {
    if (photoInfo[ImageID].showComments && photoInfo[ImageID].Format !== "ARC") {
        YAHOO.lang.later(200, window, showCommentPage);
        //showCommentPage('');

        YD.setStyle('comment', 'display', 'block');

        if (photoInfo[ImageID].commentApprovalReqd) {
            YD.setStyle('commentApproval', 'display', 'inline');
        } else {
            YD.setStyle('commentApproval', 'display', 'none');
        }
    } else {
        YD.setStyle('comment', 'display', 'none');
    }
}

function drawGalleryNav(totalPhotos, photosPerPage, pageOn) {
    var totalPages = Math.ceil(totalPhotos / photosPerPage);
    var pnt = YD.get('pageNavigation_top');
    var pnb = YD.get('pageNavigation_bottom');

    if (pnt) {
        var pageNavTop = SM.currentContext.pageNavTop;
    
        if (pageNavTop) {
            pageNavTop.set('currentPage', pageOn);
            pageNavTop.set('totalPages', totalPages);
            pageNavTop.set('photosPerPage', photosPerPage);
        } else {
            SM.currentContext.pageNavTop = new SM.navigation.PageNav(pnt, {'totalPages': totalPages, 'currentPage': pageOn, 'photosPerPage': photosPerPage});
        }
    }

    if (pnb) {
        var pageNavBottom = SM.currentContext.pageNavBottom;

        if (pageNavBottom) {
            pageNavBottom.set('currentPage', pageOn);
            pageNavBottom.set('totalPages', totalPages);
            pageNavBottom.set('photosPerPage', photosPerPage);
        } else {
            SM.currentContext.pageNavBottom = new SM.navigation.PageNav(pnb, {'totalPages': totalPages, 'currentPage': pageOn, 'photosPerPage': photosPerPage});
        }
    }
}

function drawPhotoNav() {
    var output = '';
    var targetPosition = parseInt(photoInfo[ImageID].position, 10);

    if ((targetPosition - 1) % photosPerPage == 0) {
        if (targetPosition != 1) {
            output += '<a href="#P-' + (pageOn - 1) + '-' + photosPerPage + '" onmouseup="selectLastImageOnPage=true" class="nav prev">&lt;<span class="extraNav"> Prev<\/span><\/a>';
            //selectLastImageOnPage = true;
        }
    } else {
        for (var i in photoInfo) {
            if (photoInfo[i].position == targetPosition - 1) {
                output += '<a href="#' + photoInfo[i].ImageID + '_' + photoInfo[i].ImageKey + '" class="nav prev">&lt;<span class="extraNav"> Prev<\/span><\/a>';
            }
        }
    }

    if (output === '') {
        output += '<a href="javascript:void(\'0\')" class="nav prev" style="visibility: hidden">&lt;<span class="extraNav"> Prev<\/span><\/a>';
    }

    output += '<span class="title">' + photoInfo[ImageID].position + ' of ' + totalPhotos + '<\/span>';

    if (photoInfo[ImageID].position % photosPerPage == 0) {
        if (pageOn != Math.ceil(totalPhotos / photosPerPage)) {
            output += '<a href="#P-' + (pageOn + 1) + '-' + photosPerPage + '" class="nav next"><span class="extraNav">Next <\/span>&gt;<\/a>';
        }
    } else {
        for (var i in photoInfo) {
            if (photoInfo[i].position == targetPosition + 1) {
                output += '<a href="#' + photoInfo[i].ImageID + '_' + photoInfo[i].ImageKey + '" class="nav next"><span class="extraNav">Next <\/span>&gt;<\/a>';
            }
        }
    }

    var purgeObj = YD.get('photoNavTop');

    if (purgeObj) {
        YE.purgeElement(purgeObj, true);

        while (purgeObj.hasChildNodes()) {
            purgeObj.removeChild(purgeObj.childNodes[0]);
        }

        purgeObj.innerHTML = output;
    }

    purgeObj = YD.get('photoNavBottom');

    if (purgeObj) {
        YE.purgeElement(purgeObj, true);

        while (purgeObj.hasChildNodes()) {
            purgeObj.removeChild(purgeObj.childNodes[0]);
        }

        purgeObj.innerHTML = output;
    }
}

// move tool globals
var movePhotosAjaxTool = false;
var moveablePhoto = '';
var potentialMovers = [];
var moveSpots = [];
var countMoves = 1;

// turn on the tool - mark EVERYTHING as moveable
function movePhotosAjax(forceOn) {
    potentialMovers = [];
    potentialMovers = YD.getElementsByClassName('draggable', 'img', 'thumbnails');

    if (!movePhotosAjaxTool || forceOn) {
        movePhotosAjaxTool = true;

        YD.addClass('arrangePhotosText','title');
        
        for (var i = 0, len = potentialMovers.length; i < len; i++) {
            YE.addListener(potentialMovers[i], 'mouseover', potentialDrag, potentialMovers[i].id);
            YE.addListener(potentialMovers[i], 'mouseout', undoPotentialDrag, potentialMovers[i].id);
        }
    } else {
        movePhotosAjaxTool = false;

        YD.removeClass('arrangePhotosText','title');
        
        for (var j = 0; j < countMoves; j++) {
            for (var i = 0, len = potentialMovers.length; i < len; i++) {
                YE.removeListener(potentialMovers[i], 'mouseover', potentialDrag);
                YE.removeListener(potentialMovers[i], 'mouseout', undoPotentialDrag);
                YD.setStyle(potentialMovers[i],'cursor','pointer');
            }
        }
    }
}

var movingPhoto = false;

// these are moveable
function potentialDrag(e, id) {
    if (!movingPhoto) {
        moveablePhoto = new YAHOO.util.DD(id, 'draggablePhotos');
        YAHOO.util.DDM.mode = YAHOO.util.DDM.INTERSECT;
        YD.setStyle(id, 'cursor', 'move');

        // they want to move the photo
        moveablePhoto.onMouseDown = function(e) {
            YD.setStyle(moveablePhoto.id, 'zIndex', 9999);
            movingPhoto = true;

            // turn off the listeners for all of the others
            var slots = [];

            for (var i = 0, len = potentialMovers.length; i < len; i++) {
                if (potentialMovers[i].id != moveablePhoto.id) {
                    YD.setStyle(potentialMovers[i].id, 'zIndex', 0);
                    slots[i] = new YAHOO.util.DDTarget(potentialMovers[i].id, 'draggablePhotos');
                }
            }
        };

        moveablePhoto.onMouseUp = function(e) {
            movingPhoto = false;
            YD.setStyle(moveablePhoto.id, 'zIndex', 0);
        };

        var dragOnPhoto = false;

        moveablePhoto.endDrag = function(e) {
            movingPhoto = false;

            if (!dragOnPhoto) {
                for (var i = 0, len = potentialMovers.length; i < len; i++) {
                    YD.setStyle(potentialMovers[i].parentNode.parentNode, 'opacity', 1);
                }

                var myAnim = new YAHOO.util.Anim(moveablePhoto.id);
                myAnim.attributes.left = { to: 0 };
                myAnim.attributes.top = { to: 0 };
                myAnim.duration = .1;

                myAnim.animate();
                YD.setStyle(moveablePhoto.id, 'zIndex', 0);
            }
        };

        moveablePhoto.onDragOver = function(e, id) {
            for (var i = 0, len = potentialMovers.length; i < len; i++) {
                YD.setStyle(potentialMovers[i], 'opacity', 1);
            }

            //var targetDiv = YD.get(YAHOO.util.DragDropMgr.getBestMatch(id).id).parentNode.parentNode;
            YD.setStyle(YAHOO.util.DragDropMgr.getBestMatch(id).id, 'opacity', .25);
        };

        moveablePhoto.onDragOut = function(e, id) {
            for (var i = 0, len = potentialMovers.length; i < len; i++) {
                YD.setStyle(potentialMovers[i], 'opacity', 1);
            }
        };

        moveablePhoto.onDragDrop = function(e, id) {
            dragOnPhoto = true;
            movingPhoto = false;

            for (var i = 0, len = potentialMovers.length; i < len; i++) {
                YD.setStyle(potentialMovers[i],'opacity',1);
            }

            var startPosition = parseInt(photoInfo[getImageID(moveablePhoto.id)].position, 10);
            var startHere = startPosition;
            
            var endPosition = parseInt(photoInfo[getImageID(YAHOO.util.DragDropMgr.getBestMatch(id).id)].position, 10);
            var endHere = endPosition;

            var startDiv = YD.get(moveablePhoto.id).parentNode.parentNode.parentNode;
            var endDiv = YD.get(YAHOO.util.DragDropMgr.getBestMatch(id).id).parentNode.parentNode.parentNode;

            YD.setStyle(moveablePhoto.id, 'top', '0px');
            YD.setStyle(moveablePhoto.id, 'left', '0px');

            //var clone = YD.get(moveablePhoto.id).parentNode.parentNode.cloneNode(true);
            //startDiv = clone;

            if(endDiv.parentNode.lastChild == endDiv) {
                endDiv.parentNode.appendChild(startDiv);
            } else {
                if (startPosition < endPosition) {
                    swapDiv = endDiv.nextSibling;
                } else {
                    swapDiv = endDiv;
                }

                swapDiv.parentNode.insertBefore(startDiv,swapDiv);
            }

            //removeFromDOM(YD.get(moveablePhoto.id).parentNode.parentNode.id);

            // submit new positions
            //var postArray = [];
            //postArray['tool'] = 'renumberGallery';
            //postArray['AlbumID'] = AlbumID;
            //postArray['AlbumKey'] = AlbumKey;
            var movedImages = [];

            if (startPosition > endPosition) {
                for (var i in photoInfo) {
                    if (photoInfo[i].position >= endPosition && photoInfo[i].position < startPosition) {
                        photoInfo[i].position++;
                    }
                }

                startHere = endPosition;
                endHere = startPosition;
            } else {
                for (var i in photoInfo) {
                    if (photoInfo[i].position > startPosition && photoInfo[i].position <= endPosition) {
                        photoInfo[i].position--;
                    }
                }

                startHere = parseInt(startPosition, 10);
                endHere = parseInt(endPosition, 10);
            }

            photoInfo[getImageID(moveablePhoto.id)].position = endPosition;
            //postArray['startPosition'] = startHere;
            var startPosition = startHere;

            while (startHere <= endHere) {
                for (var photo in photoInfo) {
                    if (parseInt(photoInfo[photo].position, 10) == startHere && startHere <= endHere) {
                        movedImages.push(photo);
                        startHere++;
                    }
                }
            }

            //postArray['ImageIDs'] = movedImages.join(",");
            YD.setStyle(moveablePhoto.id, 'zIndex', 0);

            movePhotosAjax(true);
            countMoves++;

            renumberGallery(AlbumID, AlbumKey, movedImages, startPosition - 1);
            //ajax_query(removePageWorking, '/rpc/gallery.mg', postArray, true);

            drawPhotoNav();
        };
    }
}

// these are moveable
function undoPotentialDrag(e,id) {
    if (movingPhoto === false) {
        moveablePhoto.unreg();
    }

    YD.setStyle(id, 'cursor', 'auto');
}

 function purge(d) {
    var a = d.attributes, i, l, n;

    if (a) {
        l = a.length;

        for (i = 0; i < l; i += 1) {
            n = a[i].name;

            if (typeof d[n] === 'function') {
                d[n] = null;
            }
        }
    }

    a = d.childNodes;

    if (a) {
        l = a.length;

        for (i = 0; i < l; i += 1) {
            purge(d.childNodes[i]);
        }
    }
}

function findClosestSize(photo,size) {
    if (size === "X3Large") {
        if (photo[size + 'Src']) {
            size = "X3Large";
        }
        else {
            size = "X2Large";
        }
    }

    if (size === "X2Large") {
        if (photo[size + 'Src']) {
            size = "X2Large";
        }
        else {
            size = "XLarge";
        }
    }

    if (size === "XLarge") {
        if (photo[size + 'Src']) {
            size = "XLarge";
        }
        else {
            size = "Large";
        }
    }

    if (size === "Large") {
        if (photo[size + 'Src']) {
            size = "Large";
        }
        else {
            size = "Medium";
        }
    }
    
    if (size === "Medium") {
        if (photo[size + 'Src']) {
            size = "Medium";
        }
        else {
            size = "Small";
        }
    }
    
    if (size === "Small") {
        if (photo[size + 'Src']) {
            size = "Small";
        }
        else {
            size = "Thumb";
        }
    }
    
    if (size === "Thumb") {
        if (photo[size + 'Src']) {
            size = "Thumb";
        }
        else {
            size = "Tiny";
        }
    }

    return size;

}


SM.stretchy = function() {

    var thumbsPerPage = 15;
    var mainPhotoSize = 'Medium';
    var largestSize = 'X3Large';
    var forceWidth = 'auto';
    var autoThumbSize = true;
    var alterScreenHeight = 0;

    var oThis = this;

    var thWidth = [];
    var thHeight = [];
    var thumbColumnPadding;
    var photoColumnPadding;
    var mainPhotoPadding;
    var photosPadding;
    var scrollBarWidth;

    var goGetThumbs;
    var autoSize = false;

    return {
        init: function(attr) {
            if (attr) {
                if (attr.thumbsPerPage) {
                    thumbsPerPage = attr.thumbsPerPage;
                }
                if (attr.mainPhotoSize) {
                    mainPhotoSize = attr.mainPhotoSize;
                }
                if (attr.largestSize) {
                    largestSize = attr.largestSize;
                }
                if (attr.forceWidth) {
                    forceWidth = attr.forceWidth;
                }
                if (attr.overrideLargestSize) {
                    largestSize = attr.overrideLargestSize;
                }
                if (attr.autoThumbSize !== undefined) {
                    autoThumbSize = attr.autoThumbSize;
                }
                if (attr.alterScreenHeight !== undefined) {
                    alterScreenHeight = attr.alterScreenHeight;
                }
            }

            // three different sizes to pick from
            switch (forceWidth.toLowerCase()) {
                case 'small':
                    YD.replaceClass(document.body, 'smugmug', 'smugmug_small');
                    YE.onAvailable('smugmug', function(e) {
                        var template = YD.get('smugmug');
                        YD.replaceClass(template, 'smugmug', 'smugmug_small');
                        template.id = 'smugmug_small';
                    });
                    thumbsPerPage = 9;
                    mainPhotoSize = 'Small';
                break;
                case 'large':
                    thumbsPerPage = 15;
                    mainPhotoSize = 'Medium';
                break;
                default:
                    if(Yua.ie && Yua.ie <= 7) {
                        var exp = YD.get('smugmug').style.getExpression('width');
                        var currStyle = YD.get('smugmug').currentStyle.width;
                        if((exp && (exp.indexOf('auto') > -1 || exp.indexOf('%') > -1)) || (currStyle && (currStyle.indexOf('auto') > -1 || currStyle.indexOf('%') > -1))) {
                            autoSize = true;
                            this.findSizes();
                            var thumbsAndSize = this.autoCheckWidth();
                        }
                        else {
                            var thumbsAndSize = this.oldCheckWidth();
                        }
                        YE.on(window,'maximize',this.checkWidth,this,true);
                        YE.on(window,'minimize',this.checkWidth,this,true);
                    }
                    else {
                        // computedStyle sucks balls, clone to find out if it is auto width
                        var container = document.createElement('div');
                        YD.setStyle(container,'position','absolute');
                        YD.setStyle(container,'visibility','hidden');
                        YD.setStyle(container,'top','5000px');
                        YD.setStyle(container,'left','-5000px');
                        YD.setStyle(container,'width','4000px');
                        document.body.appendChild(container);
                        var smCopy = YD.get('smugmug').cloneNode(true);
                        smCopy.innerHTML = '';
                        container.appendChild(smCopy);
                        var width1 = parseInt(YD.getStyle(smCopy,'width'), 10);
                        YD.setStyle(container,'width','4900px');
                        var width2 = parseInt(YD.getStyle(smCopy,'width'), 10);
                        document.body.removeChild(container);
                        if (width1 != width2) {
                            autoSize = true;
                            this.findSizes();
                            var thumbsAndSize = this.autoCheckWidth();
                        }
                        else {
                            var thumbsAndSize = this.oldCheckWidth();
                        }
                    }
                    thumbsPerPage = thumbsAndSize[0];
                    mainPhotoSize = thumbsAndSize[1];
                    if(thumbsAndSize[2]) {
                        ajaxThumbPhotoSize = thumbsAndSize[2];
                    }
                    YE.on(window,'resize',this.checkWidth,this,true);
                break;
            }

            return [thumbsPerPage, mainPhotoSize];
        },

        oldCheckWidth: function(ignoreGet) {
            // the old fashioned check for resizing
            if (YD.getViewportWidth() <= 980) {
                if (YD.hasClass(document.body, 'smugmug')) {
                    YD.replaceClass(document.body, 'smugmug', 'smugmug_small');
                    YE.onAvailable('smugmug', function(e) {
                        var template = YD.get('smugmug');
                        YD.replaceClass(template, 'smugmug', 'smugmug_small');
                        template.id = 'smugmug_small';
                    });
                }
                var newThumbCount = 9;
                var newSize = 'Small';
                return [newThumbCount, newSize];
            }
            else {
                if (YD.hasClass(document.body, 'smugmug_small')) {
                    YD.replaceClass(document.body, 'smugmug_small', 'smugmug');
                    YE.onAvailable('smugmug_small', function(e) {
                        var template = YD.get('smugmug_small');
                        YD.replaceClass(template, 'smugmug_small', 'smugmug');
                        template.id = 'smugmug';
                    });
                }
                var newThumbCount = 15;
                var newSize = 'Medium';
                return [newThumbCount, newSize];
            }
        },

        findSizes: function() {
            // how big is a thumb?
            var trueSize = this.findTrueSize('TinyPhotoSample');
            thWidth.Tiny = trueSize.width;
            thHeight.Tiny = trueSize.height;

            if(autoThumbSize) {
                var trueSize = this.findTrueSize('ThumbPhotoSample');
                thWidth.Thumb = trueSize.width;
                thHeight.Thumb = trueSize.height;
            }

            // find out how wide misc columns are
            photosPadding = this.findPadding('photos');
            thumbColumnPadding = YD.get('thumbnails').offsetWidth - parseInt(YD.getStyle('thumbnails','width'), 10);
            photoColumnPadding = YD.get('displayPhoto').offsetWidth - parseInt(YD.getStyle('displayPhoto','width'), 10);
            mainPhotoPadding = YD.get('mainImage').offsetWidth - parseInt(YD.getStyle('mainImage','width'), 10);

            // we are letting pros alter this, sigh
            var tempAlterHeight = YD.getY('TinyPhotoSample');
            
            if (tempAlterHeight > 200) {
                tempAlterHeight = 200;
            }
            
            alterScreenHeight += tempAlterHeight;

            // find scrollbar width for nonIE
            if (!Yua.ie || Yua.ie >= 8) {
                var inner = document.createElement('p');
                YD.setStyle(inner,'width','100%');
                YD.setStyle(inner,'height','200px');
                var outer = document.createElement('div');
                YD.setStyle(outer,'position','absolute');
                YD.setStyle(outer,'top','0');
                YD.setStyle(outer,'left','0');
                YD.setStyle(outer,'visibility','hidden');
                YD.setStyle(outer,'width','200px');
                YD.setStyle(outer,'height','150px');
                YD.setStyle(outer,'overflow','hidden');
                outer.appendChild (inner);
                document.body.appendChild (outer);
                var w1 = inner.offsetWidth;
                YD.setStyle(outer,'overflow','scroll');
                var w2 = inner.offsetWidth;
                if (w1 == w2) {
                    w2 = outer.clientWidth;
                }
                document.body.removeChild (outer);
                scrollBarWidth = (w1 - w2);
                if (scrollBarWidth == 0) {
                    scrollBarWidth = 16;
                }
                if(navigator.userAgent.toLowerCase().indexOf('opera') > -1) {
                    scrollBarWidth += 11;
                }
            }
        },

        findPadding: function(el) {
            if(typeof(el) === "string") {
                el = YD.get(el);
            }
            
            var value = 0;
            var tempValue = 0;

            // border can return medium in IE - so lame
            tempValue = parseInt(YD.getStyle(el, 'borderLeftWidth'), 10);

            if(!isNaN(tempValue)) {
                value += tempValue;
            }

            tempValue = parseInt(YD.getStyle(el, 'borderRightWidth'), 10);

            if(!isNaN(tempValue)) {
                value += tempValue;
            }

            tempValue = parseInt(YD.getStyle(el, 'paddingLeft'), 10);

            if(!isNaN(tempValue)) {
                value += tempValue;
            }

            tempValue = parseInt(YD.getStyle(el, 'paddingRight'), 10);

            if(!isNaN(tempValue)) {
                value += tempValue;
            }

            return value;
        },

        findTrueSize: function(el) {
            if (typeof(el) === 'string') {
                el = YD.get(el);
            }
            
            var size = [];
            
            size.width = 0;
            size.height = 0;
            
            var marginLeft = parseInt(YD.getStyle(el, 'marginLeft'), 10);
            
            if (!isNaN(marginLeft)) {
                size.width += marginLeft;
            }
            
            var marginRight = parseInt(YD.getStyle(el, 'marginRight'), 10);
            
            if (!isNaN(marginRight)) {
                size.width += marginRight;
            }
            
            var marginTop = parseInt(YD.getStyle(el, 'marginTop'), 10);
            
            if (!isNaN(marginTop)) {
                size.height += marginTop;
            }
            
            var marginBottom = parseInt(YD.getStyle(el, 'marginBottom'), 10);
            
            if (!isNaN(marginBottom)) {
                size.height += marginBottom;
            }
            
            size.width += el.offsetWidth;
            size.height += el.offsetHeight;
            
            return size;
        },


        checkWidth: function() {
            if (autoSize && !YD.inDocument('smugmug_small')) {
                var thumbsAndSize = this.autoCheckWidth();
            } else {
                var thumbsAndSize = this.oldCheckWidth();
            }

            // new thumb size?
            if (thumbsAndSize[2] && ajaxThumbPhotoSize != thumbsAndSize[2]) {
                ajaxThumbPhotoSize = thumbsAndSize[2];
                
                var divPhotos = YD.getElementsByClassName('photo', 'div', 'thumbnails');
                
                if (ajaxThumbPhotoSize === "Thumb") {
                    YD.addClass(divPhotos,'size_Thumb');
                    YD.removeClass(divPhotos,'size_Tiny');
                } else {
                    YD.addClass(divPhotos,'size_Tiny');
                    YD.removeClass(divPhotos,'size_Thumb');
                }

                // loop through the thumbs and update their size
                for (var i=0; i<divPhotos.length; i++) {
                    if (divPhotos[i].hasChildNodes && divPhotos[i].childNodes[0].hasChildNodes) {
                        var photoWrapper = divPhotos[i].childNodes[0];
                        var thumbIMG = photoWrapper.childNodes[0].childNodes[0];
                        var thumbImageID = getImageID(thumbIMG.id);
                    
                        if (photoInfo && photoInfo[thumbImageID]) {
                            // set width/height of image
                            if (photoInfo[thumbImageID][ajaxThumbPhotoSize + 'Width'] != 0) {
                                YD.setStyle(photoWrapper, 'width', photoInfo[thumbImageID][ajaxThumbPhotoSize + 'Width'] + 'px');
                                YD.setStyle(thumbIMG, 'width', photoInfo[thumbImageID][ajaxThumbPhotoSize + 'Width'] + 'px');
                            } else {
                                YD.setStyle(thumbIMG, 'width', '');
                            }
                            
                            if (photoInfo[thumbImageID][ajaxThumbPhotoSize + 'Height'] != 0) {
                                YD.setStyle(photoWrapper, 'height', photoInfo[thumbImageID][ajaxThumbPhotoSize + 'Height'] + 'px');
                                YD.setStyle(thumbIMG, 'height', photoInfo[thumbImageID][ajaxThumbPhotoSize + 'Height'] + 'px');
                            } else {
                                YD.setStyle(thumbIMG, 'height', '');
                            }
                            // set the source
                            
                            YD.removeClass(thumbIMG, 'protected');
                            YD.removeClass(thumbIMG, 'vault_Tiny');
                            YD.removeClass(thumbIMG, 'vault_Thumb');
            
                            if (photoInfo[thumbImageID].Format === "ARC") {
                                thumbIMG.setAttribute('src', '/img/spacer.gif');
                                YD.addClass(thumbIMG, 'vault_'+ajaxThumbPhotoSize);
                            } else if (!photoInfo[thumbImageID]['protected'] || photoInfo[thumbImageID][ajaxThumbPhotoSize + 'Width'] == 0 || photoInfo[thumbImageID][ajaxThumbPhotoSize + 'Height'] == 0) {
                                thumbIMG.setAttribute('src', photoInfo[thumbImageID][ajaxThumbPhotoSize + 'Src']);
                            } else {
                                YD.setStyle(thumbIMG, 'background-image', 'url(' + photoInfo[thumbImageID][ajaxThumbPhotoSize + 'Src'] + ')');
                            }
                            
                            if (photoInfo[thumbImageID].Archive) {
                                var archiveButton = YD.getElementsByClassName('archiveButton', 'div', divPhotos[i]);
                                YD.setStyle(archiveButton,'top',(-photoInfo[thumbImageID][ajaxThumbPhotoSize + 'Height'])-3 + 'px');
                                YD.setStyle(archiveButton,'left',Math.floor(-photoInfo[thumbImageID][ajaxThumbPhotoSize + 'Width']/2)+10 + 'px');
                            }
                        }
                    }
                }
            }

            // only update if needed
            if (thumbsPerPage != thumbsAndSize[0]) {
                thumbsPerPage = thumbsAndSize[0];
                photosPerPage = thumbsPerPage;
                window.clearTimeout(goGetThumbs);
                
                if (YD.getStyle('lightBoxStage', 'display') !== 'block') {
                    var oThis = this;
                    goGetThumbs = setTimeout( function() {
                        skipPrimary = true;
                        getPhotos();
                    }, 250);
                }
            }
            
            if (mainPhotoSize != thumbsAndSize[1]) {
                mainPhotoSize = thumbsAndSize[1];
                ajaxMainPhotoSize = mainPhotoSize;
                
                if (YD.getStyle('lightBoxStage', 'display') !== 'block') {
                    if (photoInfo && photoInfo[ImageID] && photoInfo[ImageID][ajaxMainPhotoSize+'Src']) {
                        var photoSize = findClosestSize(photoInfo[ImageID],ajaxMainPhotoSize);
                        var displayImage = YD.get('mainImage');
                        var photoWrapper = displayImage.parentNode.parentNode;

                        // set width/height of image
                        if (photoInfo[ImageID][photoSize + 'Width'] != 0) {
                            YD.setStyle(displayImage, 'width', photoInfo[ImageID][photoSize + 'Width'] + 'px');
                            YD.setStyle(photoWrapper, 'width', photoInfo[ImageID][photoSize + 'Width'] + 'px');
                        } else {
                            YD.setStyle(displayImage, 'width', '');
                        }
                        
                        if (photoInfo[ImageID][photoSize + 'Height'] != 0) {
                            YD.setStyle(displayImage, 'height', photoInfo[ImageID][photoSize + 'Height'] + 'px');
                            YD.setStyle(photoWrapper, 'height', photoInfo[ImageID][photoSize + 'Height'] + 'px');
                        } else {
                            YD.setStyle(displayImage, 'height', '');
                        }
                        
                        YD.removeClass(displayImage, 'protected');
                        YD.removeClass(displayImage, 'vault_Small');
                        YD.removeClass(displayImage, 'vault_Medium');
                        YD.removeClass(displayImage, 'vault_Large');
                        YD.removeClass(displayImage, 'vault_XLarge');
                        YD.removeClass(displayImage, 'vault_X2Large');
                        YD.removeClass(displayImage, 'vault_X3Large');

                        // set the source
                        if (photoInfo[ImageID].Format === "ARC") {
                            displayImage.setAttribute('src', '/img/spacer.gif');
                            YD.addClass(displayImage, 'vault_'+photoSize);
                            YD.removeClass(displayImage , 'protected');
                        } else if (!photoInfo[ImageID]['protected'] || photoInfo[ImageID][photoSize + 'Width'] == 0 || photoInfo[ImageID][photoSize + 'Height'] == 0) {
                            YD.setStyle(displayImage, 'background-image', 'none');
                            displayImage.setAttribute('src', photoInfo[ImageID][photoSize + 'Src']);
                            YAHOO.lang.later(500, window, loadedImageRPC, [ImageID, photoSize, ImageKey]);
                            //loadedImageRPC(ImageID,photoSize,ImageKey);

                            if (photoInfo[ImageID]['protected']) {
                                YD.addClass(displayImage, 'protected');
                            }
                        } else {
                            displayImage.setAttribute('src', '/img/spacer.gif');
                            YD.setStyle(displayImage, 'background-image', 'url(' + photoInfo[ImageID][photoSize + 'Src'] + ')');
                            YAHOO.lang.later(500, window, loadedImageRPC, [ImageID, photoSize, ImageKey]);
                            //loadedImageRPC(ImageID,photoSize,ImageKey);

                            YD.addClass(displayImage, 'protected');
                        }
                    }
                }
            }

            },

        autoCheckWidth: function() {
            var photosWidth = YD.get('photos').offsetWidth;

            // sometimes the scroll bar screws us up, take it out if needed
            //alert(YD.getDocumentHeight()+" "+YD.getViewportHeight());
            if ((!Yua.ie || Yua.ie >= 8) && YD.getDocumentHeight() <=  YD.getViewportHeight()) {
               photosWidth -= scrollBarWidth;
            }

            // larger displays should get at least 4 across
            var minThumbsPC = 3;

            // switch to using thumbs if possible
            if (photosWidth > 1600 && autoThumbSize) {
                var proposedThumbSize = 'Thumb';
            } else {
                var proposedThumbSize = 'Tiny';
                
                if (photosWidth > 1280) {
                    minThumbsPC = 4;
                }
            }

            var thumbWidth = thWidth[proposedThumbSize];
            var thumbHeight = thHeight[proposedThumbSize];

            // must have at LEAST three or 4 thumbs across
            var maxWidth = photosWidth-photosPadding-thumbColumnPadding-photoColumnPadding-mainPhotoPadding-(thumbWidth*minThumbsPC);

            // what size can we show?
            if (maxWidth <= 599) {
                var newSize = "Small";
            } else if (maxWidth >= 600 && maxWidth <= 799) {
                var newSize = "Medium";
            } else if (maxWidth >= 800 && maxWidth <= 1023) {
                var newSize = "Large";
            } else if (maxWidth >= 1024 && maxWidth <= 1279) {
                var newSize = "XLarge";
            } else if (maxWidth >= 1280 && maxWidth <= 1599) {
                var newSize = "X2Large";
            } else if (maxWidth >= 1600) {
                var newSize = "X3Large";
            }

            //double check that the size is good for height
            var targetHeight = Math.round(screenHeight()-alterScreenHeight);

            // what size can we show?
            
            if (targetHeight <= 399) {
                var horizSize = "Small";
            } else if (targetHeight >= 400 && targetHeight <= 599) {
                var horizSize = "Medium";
            } else if (targetHeight >= 600 && targetHeight <= 767) {
                var horizSize = "Large";
            } else if (targetHeight >= 768 && targetHeight <= 959) {
                var horizSize = "XLarge";
            } else if (targetHeight >= 960 && targetHeight <= 1199) {
                var horizSize = "X2Large";
            } else if (targetHeight >= 1200) {
                var horizSize = "X3Large";
            }
            
            // which one is smaller?
            if (assignSizeNum(horizSize) < assignSizeNum(newSize)) {
                newSize = horizSize;
            }
            
            // sigh, some pros don't allow larger sizes - learn to use watermark!
            if (largestSize === "X2Large" && (newSize === "X3Large")) {
                newSize = "X2Large";
            }
            
            if (largestSize === "XLarge" && (newSize === "X3Large" || newSize === "X2Large")) {
                newSize = "XLarge";
            }
            
            if (largestSize === "Large" && (newSize === "X3Large" || newSize === "X2Large" || newSize === "XLarge")) {
                newSize = "Large";
            }
            
            if (largestSize === "Medium" && (newSize === "X3Large" || newSize === "X2Large" || newSize === "XLarge" || newSize === "Large")) {
                newSize = "Medium";
            }

            // how much room for the new size?
            switch(newSize) {
                case "Small":
                    var newMainHoriz = 400;
                    var thumbsPerColumn = 3;
                    if(proposedThumbSize === "Thumb") {
                        var thumbsPerColumn = 2;
                    }
                break;
                case "Medium":
                    var newMainHoriz = 600;
                    var thumbsPerColumn = 4;
                    if(proposedThumbSize === "Thumb") {
                        var thumbsPerColumn = 3;
                    }
                break;
                case "Large":
                    var newMainHoriz = 800;
                    var thumbsPerColumn = Math.round(600/thumbHeight);
                break;
                case "XLarge":
                    var newMainHoriz = 1024;
                    var thumbsPerColumn = Math.round(768/thumbHeight);
                break
                case "X2Large":
                    var newMainHoriz = 1280;
                    var thumbsPerColumn = Math.round(960/thumbHeight);
                break;
                case "X3Large":
                    var newMainHoriz = 1600;
                    var thumbsPerColumn = Math.round(1200/thumbHeight);
                break;
            }


            // calculate room for thumbs
            var newThumbHoriz = Math.floor((photosWidth-photosPadding-thumbColumnPadding-photoColumnPadding-mainPhotoPadding-newMainHoriz)/thumbWidth);

            //alert(photosWidth+" "+photosPadding+" "+thumbColumnPadding+" "+photoColumnPadding+" "+mainPhotoPadding+" "+newMainHoriz+" "+thumbWidth+" "+newThumbHoriz);


            // change the width of the left column to allow that many thumbs
            var leftColumn = YD.getElementsByClassName('leftColumn', 'div', 'smugmug',function(el) {
                if(Yua.ie === 0 || (Yua.ie && el.offsetHeight > 0)) {
                    YD.setStyle(el,'width',(newThumbHoriz*thumbWidth)+"px");
                }
            });
            
            // how much room is left for the right hand column?
            // why the -2? text zooming seems to break wrapping and I am unsure why
            var whatsLeft = photosWidth - parseInt(YD.get('thumbnails').offsetWidth, 10) - photosPadding-photoColumnPadding - 2;
            var rightColumn = YD.getElementsByClassName('rightColumn', 'div', 'smugmug',function(el) {
                if(Yua.ie === 0 || (Yua.ie && el.offsetHeight > 0)) {
                    YD.setStyle(el,'width',whatsLeft+"px");
                }
            });

            // for now we need to remove the extra cart text
            var extraCartNav = YD.getElementsByClassName('extraNav', 'span', 'albumNav_top');
            if (extraCartNav.length > 0) {
                if (newSize === "Small") {
                    YD.setStyle(extraCartNav,'display','none');
                }
                else {
                    YD.setStyle(extraCartNav,'display','inline');
                }
            }

            // calculate thumbs
            var newThumbCount = newThumbHoriz*thumbsPerColumn;

            //YD.get('header').innerHTML =   photosWidth+" "+photosPadding+" "+thumbColumnPadding+" "+photoColumnPadding+" "+mainPhotoPadding+" "+newMainHoriz+" "+thumbWidth+" "+newThumbHoriz+" "+whatsLeft

            // send back what we think it should be
            return [newThumbCount, newSize, proposedThumbSize];
        }

   }
}();

function assignSizeNum(size) {
    var value = 1;
    
    switch(size) {
        case "Tiny":
            value = 0;
            break;
        case "Thumb":
            value = 1;
            break;
        case "Small":
            value = 2;
            break;
        case "Medium":
            value = 3;
            break;
        case "Large":
            value = 4;
            break;
        case "XLarge":
            value = 5;
            break;
        case "X2Large":
            value = 6;
            break;
        case "X3Large":
            value = 7;
            break;
    }

    return value;
}


/**
 * Gets photos for smugmug_ajax
 * only called for smugmug_ajax galleries
 * move to gallery_ajax.js
 */
function getPhotos(newPage) {
    if (YD.inDocument('fsssButton') && goGetSlideshowSWF) {
        SM.buttons.slideshowButton.getFlash().pauseFetch();
    }
    throbbingCount = 0;
    
    var handleSuccess = function(o){
        if (o.responseText !== undefined){
            try {
                var returnedData = YAHOO.lang.JSON.parse(o.responseText);
            }
            catch (x) {
                //alert("JSON Parse failed!");
                return;
            }

            var tempImages = returnedData.Images;
            var pageDetails = returnedData.pageDetails;

            totalPhotos = pageDetails.totalImages;

            if (selectLastImageOnPage) {
                selectLastImageOnPage = false;

                for (var i in tempImages) {
                    ImageID = i;
                    ImageKey = tempImages[i].ImageKey;
                }

                pageOn = pageDetails.pageOn;

                location.hash = ImageID;
            } else {
                if(ImageID != pageDetails.ImageID) {
                    location.hash = pageDetails.ImageID+"_"+pageDetails.ImageKey;
                }
                ImageID = pageDetails.ImageID;
                ImageKey = pageDetails.ImageKey;
                pageOn = pageDetails.pageOn;
            }

            for (var i in tempImages) {
                if (!photoInfo[i]) {
                    photoInfo.size++;
                }

                photoInfo[i] = tempImages[i];
            }

            refreshPage(pageOn,ImageID);
        }
    };

    var handleFailure = function(o){
        //alert("Something is wrong in Nottingham.");
    };

    var callback = {
        'success': handleSuccess,
        'failure': handleFailure,
        'scope': this
    };

    if (imageIDs.length > 0) { 
        ajaxThrobber('on');
    }

    var postArray = [];

    if (window.location.href.indexOf("#") > -1) {
        navHash = window.location.href.split("#")[1];

        if (navHash.indexOf('P-') > -1 && navHash.split('-')[2] != photosPerPage) {
            postArray.convertPosition = ((navHash.split('-')[1] - 1) * navHash.split('-')[2]) + 1;
        }
    }

    if (newPage && newPage !== undefined) {
        pageOn = newPage;
        postArray.getNewPage = true;
    } else {
        postArray.getNewPage = false;
    }

    postArray.pageOn = pageOn;
    postArray.pageType = pageType;
    postArray.AlbumID = AlbumID;
    postArray.AlbumKey = AlbumKey;
    postArray.ImageID = ImageID;

    if (typeof siteUser !== 'undefined') {
        postArray.siteUser = siteUser;
    }

    postArray.pageScope = pageScope;
    postArray.community = community;
    postArray.pageDrawBy = pageDrawBy;
    postArray.pageTypeDetails = pageTypeDetails;
    postArray.galleryStyle = galleryStyle;
    postArray.photosPerPage = photosPerPage;
    postArray.photoSizes = 'all';
    postArray.thumbSize = ajaxThumbPhotoSize;
    postArray.mainPhotoSize = ajaxMainPhotoSize;
    postArray.lightboxSize = lightboxSize;
        

    var postData = "tool=ajaxGallery";

    for (var i in postArray) {
        postData += "&" + i + "=" + postArray[i];
    }

    var sUrl = "/rpc/gallery.mg";

    // cancel previous call if necessary
    if (typeof imageRequest === 'object') {
        YAHOO.util.Connect.abort(imageRequest);
    }

    imageRequest = YAHOO.util.Connect.asyncRequest('POST', sUrl, callback, postData);
}


YE.on(window,'resize',findLightBoxSize);
function findLightBoxSize() {

    // find the perfect lightbox size
    var screenWidth = YD.getViewportWidth() - 40;
    var screenHeight = YD.getViewportHeight() - 40;

    if (screenWidth <= 600 - 1) {
        widthSize = 1;
    } else if (screenWidth >= 600 && screenWidth <= 800 - 1) {
        widthSize = 2;
    } else if (screenWidth >= 800 && screenWidth <= 1024 - 1) {
        widthSize = 3;
    } else if (screenWidth >= 1024 && screenWidth <= 1280 - 1) {
        widthSize = 4;
    } else if (screenWidth >= 1280 && screenWidth <= 1600- 1) {
        widthSize = 5;
    } else if (screenWidth >= 1600) {
        widthSize = 6;
    }

    if (screenHeight <= 400 - 1) {
        heightSize = 1;
    } else if (screenHeight >= 400 && screenHeight <= 600 - 1) {
        heightSize = 2;
    } else if (screenHeight >= 600 && screenHeight <= 768 - 1) {
        heightSize = 3;
    } else if (screenHeight >= 768 && screenHeight <= 960 - 1) {
        heightSize = 4;
    } else if (screenHeight >= 960 && screenHeight <= 1200 - 1) {
        heightSize = 5;
    } else if (screenHeight >= 1200) {
        heightSize = 6;
    }
    
    var perfectSize = Math.min(heightSize, widthSize);
    
    switch (perfectSize) {
        case 1:
            lightboxSize = 'Small';
            break;
        case 2:
            lightboxSize = 'Medium';
            break;
        case 3:
            lightboxSize = 'Large';
            break;
        case 4:
            lightboxSize = 'XLarge';
            break;
        case 5:
            lightboxSize = 'X2Large';
            break;
        case 6:
            lightboxSize = 'X3Large';
            break;
    }
}
