Lycos.use("util");
Lycos.use("ui");

Lycos.use("webon/modules/mediamanager");
Lycos.use("webon/modules/comments");
//Lycos.use("webon/modules/rater");

/**
 * The class used for a photo album module.
 * @constructor
 * @param {integer} instId The instance id of the module being constructed.
 * @param {integer} subInstId The sub-instance id of the module being constructed.
 * @base Lycos.webon.module
 */
Lycos.webon.modules.photoalbum = function(instId, subInstId) {

    /**
     * The type of module.
     * @see Lycos.webon.module
     */
    this.type = "photoalbum";
    this.lyModule = Lycos.webon.module;
    this.lyModule( instId, subInstId );

    /**
     * A variable holding the text of the JS object initialization.
     */
    this.jsObj = "(Lycos.webon.getInstance('"+this.type+"', "+this.instId+", "+this.subInstId+"))";

    /**
     * The number of bins currently scrolled.
     */
    this.slideBinOffset = 0;

    /**
     * Todo: I don't know what this does.
     */
    this.slideshowId = 0;

    /**
     * Todo: I don't know what this does.
     */
    this.slideshowTimer = null;

    /**
     * A pointer to the table cell being dragged in the photo manager.
     */
    this.draggingTd = null;

    /**
     * Todo: I don't know what this does.
     */
    this.canDelSlide = null;

    /**
     * Todo: I don't know what this does.
     */
    this.isDelSlide = false;

    /**
     * True if spam should be shown to the owner.
     */
    this.showspams = false;

    /** 
     * resize by "width" or by "height" when resizing the album
     */
    this.resizeBy = null;

    /** 
     * max and min values for resizing 
     */
    this.minWidth = 160;
    this.maxWidth = 600;

    /** 
     * minimum width for the photoalbum before we start hiding the bottom slider
     */
    this.hideSlideWidth = 300;

    /** 
     * cache image dimensions
     */
    this.cacheDims = [];

    /** standard thumb sizes */
    this.thumbX = 558;
    this.thumbY = 400;

    var tmp=this;
    this.addEventListener('showManage',function( e ) { tmp.onLightbox( e ); } );
    this.addEventListener('retrieveRemaining',function( e ) { tmp.onRetrieveRemaining( e ); });
    this.addEventListener('getComments',function( e ) { tmp.setCommentsHTML( e ); });
    this.addEventListener('saveRename',function( e ) { tmp.onSaveRename( e ); });
    this.addEventListener('managePhotos',function( e ) { tmp.onManagePhotos( e ); });
    this.addEventListener('rotatePhoto',function( e ) { tmp.onRotatePhoto( e ); });
    this.addEventListener('addMediaByIds',function( e ) { tmp.onAddMediaByIds( e ); });
    this.addEventListener('deletePhotos',function( e ) { tmp.onDeletePhotos( e ); });
    this.addEventListener('switchPhoto',function( e ) { tmp.onSwitchPhoto( e ); });

    /**
     * get the intified version of mainid
     */
    this.getMainId= function() {
        return parseInt(document.getElementById("mainId"+this.instId).innerHTML);
    }

    /**
     * Todo: I don't know what this does.
     */
    this.checkPhoto= function() {

        this.soonHideControls();

        var str = document.location+'';
        if (str.match(/\#photo/) == "#photo") {
            var arr = str.split("#photo");
            var id = arr[arr.length-1];
            if (id.length > 0) {
                return this.switchPhoto(id, true, true);
            }
        }
        var firstId = this.getMainId();
        if (firstId != 0) {
            document.getElementById("photo"+this.instId+"_"+firstId).className += " selected ";
            return this.switchPhoto(firstId, true, true);
        }

    }

    /**
     * show (for the larger player) the previous/play/next controls
     */
    this.showControls = function() {
        this.clearControlTimer();

        var bg = document.getElementById("infoBarBg"+this.instId);
        if (bg) {
            if (bg.style.display != "none") return; // just stop now

            //      Lycos.effects.fadeIn(bg, Lycos.effects.speeds.SLOW, true);
            bg.style.display = "";
        }

        var p = document.getElementById("infoBarP"+this.instId);
        if (p) {
            Lycos.effects.fadeIn(p, Lycos.effects.speeds.SLOW, true);
            p.style.display = "";
        }
    }

    /**
     * set timeout to hide the controls
     */
    this.soonHideControls = function() {
        this.controlTimer = setTimeout(this.jsObj+".hideControls()", 1500);
    }

    /**
     * hide (for the larger player) the previous/play/next controls
     */
    this.hideControls = function() {
        var p = document.getElementById("infoBarP"+this.instId);
        if (p) {
            Lycos.effects.fadeOut(p, Lycos.effects.speeds.SLOW, true);
        }
        var bg = document.getElementById("infoBarBg"+this.instId);
        if (bg) {
            bg.style.display = "none";
        }

        this.clearControlTimer();
    }

    /**
     * clear out the timer
     */
    this.clearControlTimer = function() {
        if (this.controlTimer) {
            clearTimeout(this.controlTimer);
            this.controlTimer = null;
        }
    }

    /**
     * Displays the popup thumbnail of an image.
     */
    this.displayPopup = function(id) {
        document.getElementById("popupImg"+this.instId).src = document.getElementById("smallurl"+this.instId+"_"+id).value;
        var phot = document.getElementById("photo"+this.instId+"_"+id);
        var abs1 = Lycos.util.findAbsPosition(phot);
        var abs2 = Lycos.util.findAbsPosition(phot.parentNode);
        var offsetx = abs1[0]-abs2[0]+this.slideBinOffset;
        var dim = Lycos.util.imageNaturalDimensions(document.getElementById("popupImg"+this.instId));
        var offsety = dim[1];
        var popup = document.getElementById("popup"+this.instId);
        popup.style.left = (23+offsetx)+"px";
        popup.style.top = (-120+(110-offsety))+"px";
        popup.style.display = "";
    }

    /**
     * Hides the popup thumbnail of an image.
     */
    this.hidePopup = function(id) {
        document.getElementById("popup"+this.instId).style.display = "none";
        document.getElementById("popupImg"+this.instId).src = "";
    }

    /**
     * Gets the comments for the current photos.
     */
    this.getCurrentPhotoComments = function () {
        var curr = document.getElementById("photo"+this.instId+"_"+this.slideshowId);
        if (curr) {
            var id = this.getPhotoId(curr);
            this.getComments(id);
        }
    }

    /**
     * Gets the comments for a specific photo.
     */
    this.getComments = function(id) {
        this.lyAjaxObj({showspams:(this.showspams ? "yes" : "no"),id:id, region: this.region}, "getComments");
    }



    /**
     * Retrieve the next batch of photos.
     */
    this.retrieveRemaining = function(postRetrieveCheck) {

        var perslide = 9; /** stays 9 in spite of resizing */
        var photos = [];
        // we've retrieved as many as possible
        if (this.retrieveOffset >= this.allToRetrieve.length) {
            return;
        }

        for (var i = this.retrieveOffset; i < this.retrieveOffset+perslide && i < this.allToRetrieve.length; i++) {
            photos.push(this.allToRetrieve[i]);
        }

        this.retrieveOffset += perslide;

        var count = parseInt(document.getElementById("photoBinCount"+this.instId).innerHTML);
        var pages = parseInt(count/perslide);
        var fullCount = document.getElementById("photoBinFullCount"+this.instId);

        // retrieve more
        if (count % 9 == 0 && fullCount.innerHTML == 0 && photos.length > 0) {
            fullCount.innerHTML = "retrieving";
            this.lyAjaxObj({"photos": photos, "check":(postRetrieveCheck ? true : false)},"retrieveRemaining");
        }
    }

    /**
     * Switch to a different photo.
     */
    this.switchPhoto = function(id, changeLoc, switchData) {

        this.resizeBy = null;

        // can't select photo (isn't there?)
        if( !this.selectPhoto(id) ) {
            // retrieve more to find the photo
            this.retrieveRemaining(true);
            return false;
        }

        this.slideshowId = id;

        if (changeLoc) 
            window.location.hash = "#photo"+id;

        document.getElementById("viewSpanNoComments"+this.instId).style.display="none";
        document.getElementById("viewSpan"+this.instId).style.display="none";

        if (switchData) {
            this.pauseSlideshow();
            document.getElementById("switchingTo"+this.instId).innerHTML = id;
            this.lyAjaxObj({showspams:(this.showspams ? "yes" : "no"),id:id, region: this.region},"switchPhoto");
        }
        else {
            document.getElementById("acl"+this.instId).value = "N";
        }

        /** zero stuff out */
        //    document.getElementById("rater_"+this.instId).innerHTML = "";
        document.getElementById("comments_"+this.instId).innerHTML = "";
        return false;
    }

    /**
     *
     */
    this.findSlideshowId = function(last) {
        if (this.slideshowId == 0) {
            var bin = document.getElementById("photoBin"+this.instId);
            var divs = bin.getElementsByTagName("li");
            if (divs.length > 0) {

                // find the last rather than the first
                if (last)
                    this.slideshowId = this.getPhotoId(divs[divs.length-1]);
                else
                    this.slideshowId = this.getPhotoId(divs[0]);
            }
        }
        return this.slideshowId;

    }


    /**
     * Scroll left one bin.
     */
    this.jumpLeft = function() {

        this.pauseSlideshow();

        var curr = document.getElementById("photo"+this.instId+"_"+this.findSlideshowId());
        if (curr) {
            var next = curr.previousSibling;
            while (next && (next.nodeType != 1 || next.tagName != "LI")) {
                next = next.previousSibling;
            }

            // go left
            if (next)
                this.switchPhoto(this.getPhotoId(next), true, true);
            // wrap around
            else {
                this.slideshowId = 0;
                this.switchPhoto(this.findSlideshowId(true), true, true);
            }
        }
        return false;
    }

    /**
     * Scroll right one bin.
     */
    this.jumpRight = function() {

        this.pauseSlideshow();

        // maybe retrieve more (might need them soon)
        this.retrieveRemaining();

        var curr = document.getElementById("photo"+this.instId+"_"+this.findSlideshowId());
        if (curr) {
            var next = curr.nextSibling;
            while (next && (next.nodeType != 1 || next.tagName != "LI")) {
                next = next.nextSibling;
            }

            if (next)
                this.switchPhoto(this.getPhotoId(next), true, true);
            // wrap around
            else {
                this.slideshowId = 0;
                this.switchPhoto(this.findSlideshowId(), true, true);
            }

        }
        return false;
    }

    /**
     * Start or stops the slideshow depending on state.
     * @see #startSlideshow
     * @see #pauseSlideshow
     */
    this.slideshow = function() {
        if (this.slideshowTimer == null) {
            document.getElementById("slideshowText"+this.instId).innerHTML = "pause"+(this.region == "sidebar" ? "" : " slideshow");
            if (!this.startSlideshow()) {
                document.getElementById("slideshowText"+this.instId).innerHTML = "play"+(this.region == "sidebar" ? "" : " slideshow");
            }
        }
        else {
            this.pauseSlideshow();
            this.switchPhoto(this.slideshowId, true, true);
        }
        return false;
    }

    /**
     * Start the slideshow.
     * @see #pauseSlideshow
     */
    this.startSlideshow = function() {
        if (this.slideshowId == 0) {
            var bin = document.getElementById("photoBin"+this.instId);
            var divs = bin.getElementsByTagName("li");
            if (divs.length == 0) return false;
            this.switchPhoto(this.getPhotoId(divs[0]), false, false);
            this.slideshowTimer = setTimeout(this.jsObj+".runSlideshow()", 3000);
        }
        else {
            this.runSlideshow();
        }
        return true;
    }

    /**
     * Pauses the slideshow.
     * @see #startSlideshow
     */
    this.pauseSlideshow = function() {
        document.getElementById("slideshowText"+this.instId).innerHTML = "play"+(this.region == "sidebar" ? "" : " slideshow");
        clearTimeout(this.slideshowTimer);
        this.slideshowTimer = null;
    }

    /**
     * Used internally to resume playback of a slideshow.
     * @see #startSlideshow
     */
    this.runSlideshow = function () {
        if (this.slideshowId == 0) return;

        var curr = document.getElementById("photo"+this.instId+"_"+this.slideshowId);
        var next = curr.nextSibling;
        while (next && (next.nodeType != 1 || next.tagName != "LI")) {
            next = next.nextSibling;
        }

        if (!next) {

            var bin = document.getElementById("photoBin"+this.instId);
            var divs = bin.getElementsByTagName("li");
            if (divs.length == 0) {
                this.pauseSlideshow();
                return;
            }
            next = divs[0];
        }

        this.switchPhoto(this.getPhotoId(next), false, false);
        this.slideshowTimer = setTimeout(this.jsObj+".runSlideshow()", 3000);

        // maybe retrieve more (might need them soon). do it every other time.
        if (this.toRetrieve) {
            this.retrieveRemaining();
            this.toRetrieve = false;
        }
        else {
            this.toRetrieve = true;
        }

    }

    /**
     * Slides the photos to a different bin.
     * @param {integer} pageoffset The page offset of the bin to go to.
     */
    this.slidePhotos = function(pageoffset) {
        if (!this.perslide)
            this.recalculatePerSlide( document.getElementById("albumOuterDiv"+this.instId).offsetWidth+2);

        var count = parseInt(document.getElementById("photoBinCount"+this.instId).innerHTML);
        var pages = (-1)*count/this.perslide;
        var curroffset = parseInt(document.getElementById("photoBinOffset"+this.instId).innerHTML);
        var newoffset = curroffset+pageoffset;

        if (newoffset > 0 || newoffset <= pages) {
            return false;
        }

        // maybe retrieve more (might need them soon)
        this.retrieveRemaining();

        //var smidge = parseInt(newoffset/2);
        //if (newoffset%2 == 1) {
        // smidge -= (curroffset%2);
        //}
        this.perslide = 8; // TODO fix
        this.slideBinOffset = (newoffset*((this.perslide)*54));
        //this.slideBinOffset += (newoffset*((this.perslide)*9));
        this.slideBinOffset += (newoffset*8*(this.perslide-1));


        this.slideBinOver((new Date()).getTime());
        document.getElementById("photoBinOffset"+this.instId).innerHTML = newoffset;

        return false;
    }

    /**
     * Slides the photos to a different bin.
     * @param {integer} pageoffset The page offset of the bin to go to.
     */
    this.slideBinOver = function(time) {
        var bin = document.getElementById("photoBin"+this.instId);
        Lycos.ui.slideHorizontal(time, bin, this.slideBinOffset, this.jsObj+".slideBinOver"); 
    }

    /**
     * Highlights a photo and updates the display
     * @param {integer} id The id of a photo.
     */
    this.selectPhoto = function(id) {

        /** use this so that ajax doesn't accidentally catch up with the wrong photo */
        document.getElementById("switchingTo"+this.instId).innerHTML = 0;

        var oldId = this.getMainId();
        if (oldId != id && document.getElementById("photo"+this.instId+"_"+id)) {
            var offClass = document.getElementById("photo"+this.instId+"_"+id).className;
            var oldDiv = document.getElementById("photo"+this.instId+"_"+oldId);
            if(oldDiv != undefined)
                oldDiv.className = offClass;
            document.getElementById("photo"+this.instId+"_"+id).className = " selected "+offClass;
        }

        //    document.getElementById("rater_"+this.instId).innerHTML = "";
        document.getElementById("comments_"+this.instId).innerHTML = "";
        if (document.getElementById("url"+this.instId+"_"+id)) {
            document.getElementById("mainId"+this.instId).innerHTML = id;
            var url = document.getElementById("url"+this.instId+"_"+id).value;
            var desc = document.getElementById("desc"+this.instId+"_"+id).value;
            var ind = document.getElementById("index"+this.instId+"_"+id).value;

            /** set the actual image and size */
            var img = document.getElementById("mainImg"+this.instId);
            var tmp = this;
            img.onload = function(){tmp.setImageSize(this);};
            img.style.visibility = "hidden";
            img.src = url;
            document.getElementById("mainDesc"+this.instId).innerHTML = desc;
            document.getElementById("mainIndex"+this.instId).innerHTML = ind;
        }
        if( oldId == id || document.getElementById("photo"+this.instId+"_"+id) )
            return oldId;
        else
            return 0;
    }

    /** 
     * Set the main image's size
     * @param This is the image tag we're using to display images in the main part of the photoalbum (i.e., not the photo strip at the bottom)
     * @param newWidth The new width the image should be resized to
     * @param newHeight The new height the image should be resized to
     */
    this.setImageSize = function(img, newWidth, newHeight) {

        // Find the parent 'photoImage' div
        var parentNode = img.parentNode;

        while (parentNode.tagName != 'DIV') {
            parentNode = parentNode.parentNode;
        }

        var imgW = 0;
        var imgH = 0;

        // If we don't pass in an image object, find the main photo album image 
        if (!img) {
            img = document.getElementById("mainImg"+this.instId);
        }

        // Attempt to get the dimensions of the incoming photo. If we can't get it 
        // (i.e., one of the dimensions comes back as 0), wait 400 ms and call this function again.
        var dims = Lycos.util.imageNaturalDimensions(img); // dims[0] is the width; dims[1] is the height

        if (dims[0] == 0 || dims[1] == 0) {
            setTimeout(this.jsObj+".setImageSize()", 400);
            return;
        }

        // Determine which dimension is larger, then resize by that side
        if (dims[0] > dims[1]) {

            // Compare the dims to the containing element and determine whether to give it 100% width or keep its original width
            if (dims[0] < parseInt(parentNode.offsetWidth)) {
                newWidth = dims[0];
            }
            else {
                newWidth = parseInt(parentNode.offsetWidth);
            }

            // Resizing by width
            imgW = (newWidth - 10) + "px";
            imgH = "auto";
        }
        else {

            // Compare the dims to the containing element and determine whether to give it 100% width or keep its original width
            if (dims[1] < parseInt(parentNode.offsetHeight)) {
                newHeight = dims[1];
            }
            else {
                newHeight = parseInt(parentNode.offsetHeight);
            }

            // Resizing by height
            imgH = (newHeight - 10) + "px";
            imgW = "auto";
        }

        // Set the new dimensions
        img.style.width = imgW;
        img.style.height = imgH;

        // Show the image
        img.style.visibility = 'visible';
    }


    /**
     * Shows the add-photos lightbox.
     */
    this.showAdd = function() {
        var instID = this.instId;
        setTimeout( function() { Lycos.ui.mediapicker.pick("callerid="+instID,null,'image',true); }, true );
    }

    /**
     * Shows the mana-photos lightbox.
     */
    this.showManage = function() {
        Lycos.ui.lightbox.show();
        this.lyAjaxObj( {}, "showManage" );
        return false;
    }


    /**
     * Prompts then deletes a photo.
     */
    this.deletePhoto = function() {
        var id = this.getMainId();
        if (id != 0) {
            resp = confirm("Would you like to remove this photo from the album?");
            if (resp) {
                this.lyAjaxObj({photos:{id:id}},"deletePhotos");
            }
        }
        return false;
    }

    /**
     * Retrieves the photo id from a Dom element.
     * @param {DomElement} elem The element to retrieve the name from.
     */
    this.getPhotoId = function(elem) {
        if (!elem) return 0;
        var loc = elem.id.indexOf("_");
        return elem.id.substr(loc+1);
    }



    /**
     * Pops up the rename form for a photo caption.
     */
    this.startRenamePhoto = function() {
        if (this.getMainId() == 0)
            return;

        this.pauseSlideshow();

        var desc = document.getElementById("mainDesc"+this.instId);
        var tmp = this;

        var f = desc.ownerDocument.createElement("form");
        f.id = "mainDescEditForm"+this.instId;
        f.onsubmit = function(event) { tmp.saveRename(); };
        var i = desc.ownerDocument.createElement("input");
        i.id = "mainDescEdit"+this.instId;
        i.value = desc.innerHTML;
        i.onblur = function(event) { tmp.saveRename(); };

        desc.style.display = "none";
        desc.parentNode.insertBefore(f, desc);
        f.appendChild(i);
        i.focus();
        i.select();
    }

    /**
     * Rotates a photo.
     * @param {integer} id The photo id to rotate.
     */
    this.rotatePhoto = function(id) {
        var id = this.getMainId();
        if (id != 0) {
            var img = document.getElementById("mainImg"+this.instId);
            img.src = "/adm/media/ajax-loader.gif";
            img.style.width = "auto";
            img.style.height = "auto";
            document.getElementById("photo"+this.instId+"_"+id).style.backgroundImage = "";
            this.resizeBy = null;
            this.cacheDims[id+"_"] = null;
            this.lyAjaxObj({id:id},"rotatePhoto");
        }
        return false;
    }

    /**
     * Saves a photo label rename.
     */
    this.saveRename = function() {

        var desc = document.getElementById("mainDesc"+this.instId);
        var newValue = document.getElementById("mainDescEdit"+this.instId).value;
        var frm = document.getElementById("mainDescEditForm"+this.instId);
        if (frm) frm.parentNode.removeChild(frm);

        document.getElementById("mainDesc"+this.instId).style.display = "";

        if (newValue != desc.innerHTML) {
            desc.innerHTML = "...";
            this.lyAjaxObj({
id: this.getMainId(),
newDescription: newValue
},"saveRename");
}
return false;
}

/**
 * Handles events such as adding photos.
 */
this.lyHandleEvents = function ( data ) { 
    if ( data.action == "addMediaByArray" ) {
        Lycos.ui.lightbox.show();

        var newids = [];
        for ( var i=0; i<data.items.length; i++ ) {
            newids.push(data.items[i].id);
        }
        this.lyAjaxObj({ids:newids,tag:data.tag},"addMediaByIds");
    }
    else if ( data.action == "done" )
        Lycos.ui.lightbox.hide();
    return;
}

/**
 * Adds a set of photos to the photo album.
 * @param {array} photos Photo objects.
 */
this.handleAddMedia = function ( photos, noIncrement ) {

    if ( photos == null ) 
        return 0;

    var addCount = 0;
    var currCount = parseInt(document.getElementById("photoBinCount"+this.instId).innerHTML)+1;
    var bin = document.getElementById("photoBin"+this.instId);
    for (i = 0; i < photos.length; i++) {
        bin.innerHTML +=  "<li id=\"photo"+this.instId+"_"+ photos[i].id+"\" class=\"addOnBorder\" onMouseOver=\""+this.jsObj+".displayPopup("+photos[i].id+")\" onMouseOut=\""+this.jsObj+".hidePopup()\" onClick=\"return "+this.jsObj+".switchPhoto("+photos[i].id+", true, true);\"><span class=\"pad\"><img src=\""+photos[i].thumbURL+"\" /></span><input type=\"hidden\" id=\"index"+this.instId+"_"+photos[i].id+"\" value=\""+(currCount++)+"\" /><input type=\"hidden\" id=\"url"+this.instId+"_"+photos[i].id+"\" value=\""+photos[i].largeURL+"\" /><input type=\"hidden\" id=\"smallurl"+this.instId+"_"+photos[i].id+"\" value=\""+photos[i].thumbURL+"\" /><input type=\"hidden\" id=\"desc"+this.instId+"_"+photos[i].id+"\" value=\""+photos[i].caption+"\" />";
        addCount++;
    }

    document.getElementById("photoBinCount"+this.instId).innerHTML = currCount-1;

    // main count doesn't always exactly match photo bin count (retrieveremaining)
    if (!noIncrement) {
        var newCount = parseInt(document.getElementById("mainCount"+this.instId).innerHTML) + addCount;
        document.getElementById("mainCount"+this.instId).innerHTML = newCount;

        document.getElementById("photoBg"+this.instId).className = document.getElementById("photoBg"+this.instId).className.replace(/ gray/, '')+(newCount > 0 ? "" : " gray");
    }
    return addCount;
}

/**
 * slide the slider all the way to the left and select the first image
 */
this.slideToFirst = function (noSwitch) {

    var curroffset = parseInt(document.getElementById("photoBinOffset"+this.instId).innerHTML);
    var bin = document.getElementById("photoBin"+this.instId);
    var divs = bin.getElementsByTagName("li");
    if (divs.length > 0) {
        if (!noSwitch) {
            var firstId = this.getPhotoId(divs[0]);
            this.switchPhoto(firstId, true, true);
        }
        this.slidePhotos(-1*(curroffset));
    }
    else {
        document.getElementById("mainId"+this.instId).innerHTML = 0;
        //      document.getElementById("rater_"+this.instId).innerHTML = "";
        document.getElementById("comments_"+this.instId).innerHTML = "";
        document.getElementById("mainImg"+this.instId).src = "";
        document.getElementById("mainImg"+this.instId).style.visibility = "hidden";
        document.getElementById("mainIndex"+this.instId).innerHTML = "0";
        document.getElementById("mainDesc"+this.instId).innerHTML = "This album has no photos";
        document.getElementById("acl"+this.instId).value = "N";
        this.slideshowId = 0;
    }

    // because this can be called from mediamanager
    document.getElementById("mainCount"+this.instId).innerHTML = divs.length;
    document.getElementById("photoBg"+this.instId).className = document.getElementById("photoBg"+this.instId).className.replace(/ gray/, '')+(divs.length > 0 ? "" : " gray");
}

this.emptyAlbum

/**
 * event that is triggered when comments are added.
 * @param {Event} evt A Javascript event object.
 */
this.onAddComment = function( evt ) {

    // Don't increase the comment count if we're editing a pre-existing comment
    if ( evt.lyResponse.isedit == "yes" ) return;

    // Increase the comment count if the comment was successfully submitted (i.e., an error is not returned)
    if (typeof(evt.lyResponse.error) == 'undefined') {
        commentCount = parseInt(document.getElementById("numComments"+this.instId).innerHTML) + 1;
        document.getElementById("numComments"+this.instId).innerHTML = commentCount; 
        document.getElementById("viewSpanNoComments"+this.instId).style.display="none";
        document.getElementById("viewSpan"+this.instId).style.display="inline";
    }
}

/**
 * event that is triggered when comments are deleted.
 * @param {Event} evt A Javascript event object.
 */
this.onDeleteComment = function( evt ) {
    commentCount = parseInt(document.getElementById("numComments"+this.instId).innerHTML) - 1;
    if (commentCount <= 0) {
        commentCount = 0;
        document.getElementById("viewSpanNoComments"+this.instId).style.display="inline";
        document.getElementById("viewSpan"+this.instId).style.display="none";
    }
    document.getElementById("numComments"+this.instId).innerHTML = commentCount;
}

/**
 * event that is triggered when comments are marked as spam.
 * @param {Event} evt A Javascript event object.
 */
this.onMarkCommentAsSpam = function( evt ) {
    objNumSpams = document.getElementById("numSpams"+this.instId);
    spamCount = parseInt(objNumSpams.innerHTML) + 1;
    document.getElementById("viewSpam"+this.instId).style.display="inline";
    objNumSpams.innerHTML = spamCount;
    this.onDeleteComment( evt );
}

/**
 * event that is triggered when comments are unmarked as spam.
 * @param {Event} evt A Javascript event object.
 */
this.onUnmarkCommentAsSpam = function( evt ) {
    objNumSpams = document.getElementById("numSpams"+this.instId);
    spamCount = parseInt(objNumSpams.innerHTML) - 1;
    if (spamCount <= 0) {
        spamCount = 0;
        document.getElementById("viewSpam"+this.instId).style.display="none";
    }
    objNumSpams.innerHTML = spamCount;    
    this.onAddComment( evt );
}

/**
 * Sets a flag telling whether or not comments should be shown.
 * @param {boolean} b True if spam should be shown.
 */
this.setShowSpams = function(b) {
    this.showspams = b;
}

/**
 * Toggles the show-spam flag and refreshes the comments.
 */
this.toggleShowSpams = function() {
    this.showspams = !this.showspams;
    this.getCurrentPhotoComments();
}

/**
 * Sets the HTML of the comments area.
 * @param {object} data An object containing data used to display comments.
 */
this.setCommentsHTML = function(data) {
    if (data.commentCount > 0) {
        document.getElementById("viewSpanNoComments"+this.instId).style.display="none";
        document.getElementById("viewSpan"+this.instId).style.display="inline";

    }
    else {
        document.getElementById("viewSpan"+this.instId).style.display="none";
        document.getElementById("viewSpanNoComments"+this.instId).style.display="inline";
    }

    try {
        if (data.spamCount > 0) {
            document.getElementById("viewSpam"+this.instId).style.display="inline";
        }
        else {
            document.getElementById("viewSpam"+this.instId).style.display="none";
        }
        document.getElementById("numSpams"+this.instId).innerHTML = data.spamCount;

        document.getElementById("showSpamsLink"+this.instId).innerHTML = this.showspams ? "hide" : "show";
    }
    catch(e) {}

    document.getElementById("numComments"+this.instId).innerHTML = data.commentCount;
    document.getElementById("comments_"+this.instId).innerHTML = data.commentsHTML;

}

/**
 * Event that is triggered when a lightbox should be shown.
 * @param {Event} evt The data for the lightbox to be shown.
 */
this.onLightbox = function( evt ) {
    var data = evt.lyResponse;

    Lycos.ui.lightbox.show();
    Lycos.ui.lightbox.populate(data.html);
    if ( data.onshow ) eval(data.onshow);

}

/**
 * event that is triggered when remaining photos (photos past the first page) are retrieved.
 * @param {Event} evt Object containing an array of photos to add. 
 */
this.onRetrieveRemaining = function( evt ) {

    document.getElementById("photoBinFullCount"+this.instId).innerHTML = 0;

    if (evt.lyResponse.photos.length > 0) {
        this.handleAddMedia(evt.lyResponse.photos, true);
    }
    else {
        document.getElementById("photoBinFullCount"+this.instId).innerHTML = 1;
    }
    if (evt.lyResponse.check) {
        this.checkPhoto();
    }
}

/**
 * event that is triggered when the photo is switched and the response has been retrieved from the server.
 * @param {Event} data Data object returned from the server.
 */
this.onSwitchPhoto = function( evt ) {
    var data = evt.lyResponse;
    /** make sure we still want to be switching to this photo */
    if ((data.subinstance+"") != (document.getElementById("switchingTo"+this.instId).innerHTML+"")) {
        return;
    }

    if (this.getMainId() != data.subinstance)
        this.selectPhoto(data.subinstance);

    document.getElementById("acl"+this.instId).value = data.acl;

    //    document.getElementById("rater_"+this.instId).innerHTML = data.raterHTML;

    if ( data.commentsId > 0 ) {
        this.setCommentsHTML(data);

        document.getElementById("comments_"+this.instId).style.display = "";

        instance = Lycos.webon.getInstance('comments', data.commentsId, data.subinstance);

        if ( !instance["init_cb_"+this.instId] ) {
            instance["init_cb_"+this.instId] = true;

            var tmp = this;
            instance.addEventListener("editComment", function(e) { tmp.onAddComment(e); });
            instance.addEventListener("approve", function(e) { tmp.onAddComment(e); });
            instance.addEventListener("delete", function(e) { tmp.onDeleteComment(e); });
            instance.addEventListener("markSpam", function(e) { tmp.onMarkCommentAsSpam(e); });
            instance.addEventListener("unmarkSpam", function(e) { tmp.onUnmarkCommentAsSpam(e); });
        }

        instance.jsWindow = this.jsWindow;

        if (this.jsWindow.initTinyMCE)      

            this.jsWindow.initTinyMCE();

    }
    /**
      if (data.raterId != 0) {
      if (typeof(raterObj[data.raterId]) == "undefined")
      raterObj[data.raterId] = new Object();
      raterObj[data.raterId][data.subinstance] = Lycos.webon.getInstance("rater",data.raterId,data.subinstance);

      }*/
}

/**
 * event that is triggered when the photo is renamed and the response has been retrieved from the server.
 * @param {Event} evt Data object returned from the server.
 */  
this.onSaveRename = function( evt ) {
    var data = evt.lyResponse;

    document.getElementById("mainDesc"+this.instId).innerHTML = data.newDescription;
    document.getElementById("desc"+this.instId+"_"+data.id).value = data.newDescription;;
}

/**
 * event that is triggered when the manage photos lightbox has been saved and acted upon.
 * @param {Event} evt Data object returned from the server.
 */
this.onManagePhotos = function( evt ) {
    Lycos.ui.lightbox.hide();
    document.getElementById("photoCover"+this.instId).innerHTML = evt.lyResponse.html;
    this.slideToFirst();
}

/**
 * event that is triggered when the photo rotation object is completed.
 * @param {Event} evt Data object returned from the server.
 */
this.onRotatePhoto = function( evt ) {
    var data = evt.lyResponse;

    var mudge = "?z="+(new Date()).getTime();
    document.getElementById("url"+this.instId+"_"+data.id).value = data.largeThumb+mudge;
    document.getElementById("smallurl"+this.instId+"_"+data.id).value = data.smallThumb+mudge;
    var img = document.getElementById("mainImg"+this.instId);
    var tmp = this;
    img.onload = function(){tmp.setImageSize(this);};
    img.src = data.largeThumb+mudge;
    img.style.width = "auto";
    img.style.height = "auto";

    document.getElementById("photo"+this.instId+"_"+data.id).style.backgroundImage = "url("+data.smallThumb+mudge+")";
}

/**
 * event that is triggered when photos are added and the response has been retrieved from the server.
 * @param {Event} evt Data object returned from the server.
 */
this.onAddMediaByIds = function( evt ) {
    var photos = evt.lyResponse.photos;

    Lycos.ui.lightbox.hide();
    var curroffset = parseInt(document.getElementById("photoBinOffset"+this.instId).innerHTML);
    var count = parseInt(document.getElementById("photoBinCount"+this.instId).innerHTML);
    var pages = parseInt((count)/this.perslide);
    if (this.handleAddMedia ( photos ) > 0) {
        this.switchPhoto(photos[0].id, false, true);
        this.slidePhotos((curroffset-pages));
    }
}

/**
 * event that is triggered when photos are deleted and the response has been retrieved from the server.
 * @param {Event} evt Data object returned from the server.
 */
this.onDeletePhotos = function( evt ) {
    var data = evt.lyResponse;

    Lycos.ui.lightbox.hide();
    var curr = this.getMainId();
    var delCount = 0;
    for (i = 0; i < data.photos.length; i++) {
        if (data.photos[i].id == curr) 
            curr = 0;
        var x = document.getElementById("photo"+this.instId+"_"+data.photos[i].id);
        x.parentNode.removeChild(x);
        delCount++;
    }

    document.getElementById("photoBinCount"+this.instId).innerHTML = parseInt(document.getElementById("photoBinCount"+this.instId).innerHTML)-delCount;

    // might be different value because of retrieveremaining
    var newCount = parseInt(document.getElementById("mainCount"+this.instId).innerHTML)-delCount;
    document.getElementById("mainCount"+this.instId).innerHTML = newCount;
    document.getElementById("photoBg"+this.instId).className = document.getElementById("photoBg"+this.instId).className.replace(/ gray/, '')+(newCount > 0 ? "" : " gray");

    this.reindexPhotoSlide();

    var curroffset = parseInt(document.getElementById("photoBinOffset"+this.instId).innerHTML);

    var count = parseInt(document.getElementById("photoBinCount"+this.instId).innerHTML);
    var pages = parseInt((-1*count)/this.perslide);
    this.slidePhotos(-1*(curroffset-pages));

    if (curr == 0) {
        this.slideToFirst();
    }
}

/**
 * recalculate indices of the various photos (for the image 3 of 5) because
 * 
 */
this.reindexPhotoSlide = function() {
    var bin = document.getElementById("photoBin"+this.instId);
    var photos = bin.getElementsByTagName("li");
    for (var i = 0; i < photos.length; i++) {
        var id = photos[i].id.replace(/photo/, "index");
        document.getElementById(id).value = i+1;
    }
}

this.recalculatePerSlide = function (newWidth) {

    /** take away the arrows */
    newWidth = newWidth - 84; 

    /** how many images can you fit in a slide*/
    var newPerSlide = parseInt(newWidth/55); 
    if (newPerSlide > 2 && newPerSlide < 15)
        this.perslide = newPerSlide;

}

/**
 * Function that is automatically called by the page editor when resizing
 * the photo album
 * @param {integer} newWidth The new width of the edit frame (for photo albums
 *                           we only care about this
 * @param {integer} newHeight The new height of the edit frame (n/a here)
 */
this.lyOnResizing = function(newWidth, newHeight) {


    // WOULD NEED UPDATING

    /** minimum and maximum widths */
    Lycos.ui.regionCtrl.startResizePos.minWidth = Math.max(this.minWidth, Lycos.ui.regionCtrl.startResizePos.minWidth);
    Lycos.ui.regionCtrl.startResizePos.maxWidth = Math.min(this.maxWidth, Lycos.ui.regionCtrl.startResizePos.maxWidth);
    newWidth = Math.max(this.minWidth, newWidth);
    newWidth = Math.min(this.maxWidth, newWidth);

    /** if itty bitty, hide the bottom slider */
    if (newWidth >= this.hideSlideWidth) {
        document.getElementById("photoCover"+this.instId).style.display = "";
        document.getElementById("slideshowText"+this.instId).style.display = "";
    }
    else {
        document.getElementById("photoCover"+this.instId).style.display = "none";
        document.getElementById("slideshowText"+this.instId).style.display = "none";
    }

    document.getElementById("albumOuterDiv"+this.instId).style.width = newWidth+"px";

    newHeight = parseInt(newWidth*this.thumbY/this.thumbX);
    /** +6; */ /** plus 6 to have extra black at the bottom */

    document.getElementById("photoOwner"+this.instId).style.width = newWidth+"px";

    document.getElementById("photoBg"+this.instId).style.width = newWidth+"px";
    document.getElementById("photoBg"+this.instId).style.height = newHeight+"px";

    document.getElementById("photoCover"+this.instId).style.width = (newWidth-84)+"px";


    /** recalculate minus the arrows */
    newWidth -= 30;
    newHeight = parseInt(newWidth*this.thumbY/this.thumbX);

    // resize by width first or height first
    var img = document.getElementById("mainImg"+this.instId);
    img.parentNode.style.width = newWidth+"px"
        img.parentNode.style.height = newHeight+"px";

    this.cacheDims = []; /** resizing clears dimension cache */
    this.setImageSize(img);
}

this.lyOnResize = function(newWidth, newHeight) {
    this.slideToFirst(true); /** uh-oh! pages are going to change! */
    this.recalculatePerSlide(newWidth);
}

}

