var initialTransitionsOn /** used for video playback **/
var topslideEnabled = true; /** helper field for toggling between video and photo views **/
var mode;
var photos = new Array();
var labels = new Array();

var SLIDE_WIDTH = 714;
var SLIDE_HEIGHT = 513;
var MAX_IMG_WIDTH = 640;
var MAX_IMG_HEIGHT = 480;

var	prevPhotoIdx = 0;

var curPlayCallbackId = 0;
var retryNextSlideCallbackId = 0;
var retryPrevSlideCallbackId = 0;
var retryJumpToPhotoCallbackId = 0;

var nextFade;
var curImgElId;
var nextImgElId;

var prev_state;

var opacity = 0;
var opacityIncrement = 0.25;
var fadeInterval = 20;
var fadeOpacityCallback;      
var timestamp = 0;
var TIMEOUT_VAL = 1000;

var showAddToCartLabel = false;
var relaunchableSummary = false;

var wellCellImgs;
var processedWellImgs = false;
var allowWell = true;
var allowWellHoverImgs = true;
var curWellCell = -1;

var WELLCELL_MAX_RIGHT;
var WELL_V_OFFSET = -80;  // how far above well the thumbnail preview should appear
var WELL_H_OFFSET = 0;
var THUMB_HEIGHT = 18;	//vertical height of thumbnail image



var wellPhotos = new Array();

var addToCartBinAlbumList = new Array();



function addToWell(photo) {
	wellPhotos[wellPhotos.length] = photo;
}

/*** OBJECTS ***/
function Collection(id, title, ownerName, createDate) {
	this.id = id;
	this.title = title;
	this.ownerName = ownerName;
	this.createDate = createDate;
	this.photos = new Array();
}

function Photo(id, url, title, width, height, ownerId, hasMedia, videoPath, videoWidth, videoHeight, inCart) {
	this.id = id;
	this.url = url;
	this.title = title;
	this.width = width;
	this.height = height;
	this.imgObj = null;
	this.comments = new Array();
	this.ownerId = ownerId;
    this.hasMedia = hasMedia;
    this.videoPath = videoPath;
    this.videoWidth = videoWidth;
    this.videoHeight = videoHeight;
    this.inCart = inCart;

}

function initPage() {
    deSerializeAddToCartBin();
    addAlbumToCartBinArray(albumIndex);

    	// show the "added to cart" label if we added to cart with
	// xmlhttp disabled, so we are coming back from a page refresh
	// to execute the add to cart action
	if (showAddToCartLabel == true) {
        addPhotoToCartBin(albumIndex, curPhotoIdx);
	}


	// the transition effect is achieved by maintaining two divs, each with an image
	// the top div is faded in and out, either with opacity cycling (moz) or using
	// some proprietary MS image filter
	curImgElId = "botslideimg";
	nextImgElId = "topslideimg";
    
	// browser- and context-specific settings
	if (is_win && is_ie) {
		nextFade = fadeInTop_PCIE;
	}
	else {
		nextFade = fadeInTop;
		var topSlide = document.getElementById("topslide");
		setOpacity(topSlide, opacity);
		topSlide.style.visibility = "visible";
	}

	// no transitions for dialup, opera, or macie
	if (connectionSpeed == CONNECTION_SPEED_DIALUP || is_opera || (is_mac && is_ie5up)) { 
		transitionsOn = false;
		document.getElementById("topslide").style.display = "none";
        topslideEnabled = false;
	}

    //cache this value, as we will disable transitions for videos and need to restore the setting
    initialTransitionsOn = transitionsOn;
	
	// no hover images over the blue ticks (what we call the "pseudowell")
	// for dialup, opera, macie
	if (connectionSpeed == CONNECTION_SPEED_DIALUP || is_opera || is_mac && is_ie) {
		allowWellHoverImgs = false;
	}
    
	initWell();
	
	// constrain the well hover images on the far right so they don't wander off the frame
	var slide = document.getElementById("slide");
	WELLCELL_MAX_RIGHT = findPosX(slide) + findWidth(slide) - 5;
	
	// continue playing if we were playing before in dial up mode
	// (in dialup mode, we refresh the screen each time the image changes,
	// which means a param is passed back by the bean to remember that we were playing)
	if (state == STATE_PLAYING)
		handlePlay(true);

	resetDisplay();
        

	// set auto-pause for action of perusing print sizes
	document.getElementById("printsizes").onfocus = handlePause;

	// set auto-pause for writing a comment
	if (isSignedIn) {
		document.getElementById("comment").onfocus = handlePause;
	}

	// jump down to the comment area if xmlhttp disabled
	// so we are coming back from a page refresh to execute the 
	// add comment action
	if (handledCommentId == COMMENT_DELETED_FLAG)
		scrollToCommentArea();
	else if (handledCommentId != 0)
		setTimeout(scrollToHandledComment, 50);

	// if we are coming back from the page refresh to execute 
	// the launch summary action, then we have generated all the html for the summary dialog
	// (in DialogSlideshowSummary.inc), so launch that pseudo-modal
	if (launchSummary == true)
		launch_DialogSlideshowSummary();

	initSinglePhotoShare();
}

/*** display utilities ***/
function setCurPhotoIdx(newIdx) {
	prevPhotoIdx = curPhotoIdx;
	curPhotoIdx = newIdx;
}

function resetDisplay(skipPhoto) {
    if (skipPhoto)
		renderTitle();
	else
		renderPhoto();

	renderWell();
	renderComments();

	clearAddCommentArea();
}

function initWell() {
	var newLink;
	var wellParentLink;
	for (var i=0; i < wellPhotos.length; i++) {
		wellParentLink = document.getElementById("well_" + i);
		newLink = createWellImg(i);
		wellPhotos[i].thumbObj = newLink;
		wellParentLink.appendChild(newLink);

		wellParentLink.targetIdx = i;
		wellParentLink.href = "javascript:void(" + i + ");";
		wellParentLink.onclick = function() {
							if (state == STATE_SWAPPING) {
								// dbg("WELL CLICK BLOCKED by swapstate");
								return;
							}
							handlePause();
							jumpToPhoto(this.targetIdx);
							return false;
						}
	}
}


function createWellImg(photoIdx) {
	var thumb = document.createElement("img");
	thumb.src = wellPhotos[photoIdx].url;
	thumb.height = THUMB_HEIGHT;
	thumb.width = (THUMB_HEIGHT * wellPhotos[photoIdx].width) / wellPhotos[photoIdx].height;
	thumb.id = "well_img_" + photoIdx;
	if (photoIdx == curPhotoIdx) {
		thumb.className = "hilite";
	}
	else {
		thumb.className = "unhilite";
	}
	return thumb;
}


function updateWellHilite() {
	var hiliteImg = document.getElementById("well_img_" + curPhotoIdx);
	if (hiliteImg)
		hiliteImg.className = "hilite";
	if (prevPhotoIdx != curPhotoIdx) {
		var unhiliteImg = document.getElementById("well_img_" + prevPhotoIdx);
		if (unhiliteImg)
			unhiliteImg.className = "unhilite";
	}
}


function renderPhoto(skipTitle) {

    var videospacer = document.getElementById("videospacer");
    var get_qt = document.getElementById("get_qt");
    var botslide = document.getElementById("botslide");
    var topslide = document.getElementById("topslide");
    var cartui = document.getElementById("cart_ui");
	if (document.getElementById("phone_ui"))
		var phoneui = document.getElementById("phone_ui");
    var videoEl = document.getElementById("video");
    var settingsLink = document.getElementById("settingslink");

	var photo = photos[curPhotoIdx];
 	if (photo == null) {
       return;
    }

	if (false == preload(photo)) {
		setTimeout("renderPhoto()", 300);
        return;
	}
    
    if (photo.inCart) {
        document.getElementById("printadded").style.visibility = "visible";
    } else {
        document.getElementById("printadded").style.visibility = "hidden";
    }

    if (!photo.hasMedia) {
		if (phoneui) {
            phoneui.style.display = "inline";
			updatePhoneLink(photo.id);
		}
        cartui.style.visibility = "visible";
        videospacer.style.display = "none";
        botslide.style.display = "block";
        settingsLink.style.display = "inline";
        if (topslideEnabled) {
            topslide.style.display = "block";
        }
        

        // dbg("renderPhoto: photo[" + photo.id + "] imgObj.width = " + photo.imgObj.width +  " imgObj.height=" + photo.imgObj.height);
        scaleImg(photo.imgObj, photo.imgObj.width, photo.imgObj.height, MAX_IMG_WIDTH, MAX_IMG_HEIGHT, false);
        // dbg("renderPhoto, post-scale: photo[" + photo.id + "] imgObj.width = " + photo.imgObj.width +  " imgObj.height=" + photo.imgObj.height);

        var slideImg = document.getElementById(curImgElId);
        // dbg("loading " + photo.id + " into new slideImg: " + curImgElId);
        var replaceImg = document.createElement("img");
        replaceImg.width = photo.imgObj.width;
        replaceImg.height = photo.imgObj.height;
        replaceImg.style.left = ((SLIDE_WIDTH - replaceImg.width) / 2) + "px";
        replaceImg.style.top = ((SLIDE_HEIGHT - replaceImg.height) / 2) + "px";
        // dbg("replaceImg dimensions, according to the browser: " + replaceImg.width + ", " + replaceImg.height);

        // replace img element instead of just resetting src over and over
        // on the same img element, in order to avoid sizing problems
        if (is_opera) {
            var parent = slideImg.parentNode;
            parent.removeChild(slideImg);
            parent.appendChild(replaceImg);
        }
        else {
            slideImg.parentNode.replaceChild(replaceImg, slideImg);
        }

        replaceImg.src = photo.imgObj.src;
        replaceImg.id = curImgElId;

    }  else {     // this is a video

        handlePause();
		if (phoneui)
			phoneui.style.display = "none";
        cartui.style.visibility = "hidden";
        topslide.style.display = "none";
        botslide.style.display = "none";
        videospacer.style.visibility = "visible";
        settingsLink.style.display = "none";
        
        if (haveqt) {  // browser has quicktime capability; show the movie       
            get_qt.style.display = "none";
            videoEl.style.display = "block";
        } else { // this is a video, but browser is not quicktime-enabled

            videoEl.style.display = "none";
            get_qt.style.display = "inline";
        }

    }

	// preload adjacent imgs
	if (curPhotoIdx+1 < photos.length) {
		// dbg("renderPhoto: preloading next img: " + (curPhotoIdx+1));
		preload(photos[curPhotoIdx+1]);
	}

	if (curPhotoIdx - 1 > -1) {
		// dbg("renderPhoto: preloading prev img: " + (curPhotoIdx-1));
		preload(photos[curPhotoIdx-1]);
	}

	// update "image 1 of 3" if the text exists
	var onphotoSpan = document.getElementById("on-photo");
	if (onphotoSpan) {
		onphotoSpan.innerHTML = new String(curPhotoIdx + 1);
	}

	// this skipTitle bit added so rendering of image coincides
	// more intuitively with the rendering of the title.
	// this should be refactored.
	if (skipTitle)
		;
	else
		renderTitle();


	var isLastAlbum = false;
	var isFirstAlbum = false;

	if (albumIndex + 1 >= numAlbums) {
		isLastAlbum = true;
	}

	if (albumIndex <= 0) {
		isFirstAlbum = true;
	}


    if(PID == photo.ownerId && !isNewGallery){
        if((curPhotoIdx == 0) && (isFirstAlbum)){
            //alert("renderPhoto - disabling (isfirstalbum)");
            disableNav("prevlink");

        }else {
             //alert("renderPhoto - enabling");
             enableNav("prevlink");
        }

        if((curPhotoIdx + 1 == photos.length) && (isLastAlbum)){
            //alert("renderPhoto - disabling (islastalbum)");
            disableNav("nextlink");

        } else {
                //alert("renderPhoto - enabling (multi album)");
            enableNav("nextlink");
        }
    }


    transitionsOn = initialTransitionsOn;
}

function disableNav(divId){
    if(document.getElementById(divId).className.indexOf("disabled") < 0){
        var div = document.getElementById(divId);
        var linkId= div.id + "a";
        var a = document.getElementById(linkId);

        var divClass= div.className + "-disabled";

        var newa = document.createElement("a");
        newa.className = a.className;
        newa.innerHTML = a.innerHTML;
        newa.id = a.id;

        div.replaceChild(newa,a);
        div.className=divClass;
    }
}


function enableNav(divId){
    if(document.getElementById(divId).className.indexOf("disabled") >= 0){
        var div = document.getElementById(divId);
        var linkId= div.id + "a";
        var a = document.getElementById(linkId);

        var disableClass = div.className;
        var divClass = disableClass.substring(0, disableClass.length - 9);

        var newa = document.createElement("a");
        newa.href="javascript:void(0);";
        newa.className = a.className;
        newa.innerHTML = a.innerHTML;
        newa.id = a.id;

        if(divId=="prevlink"){
            newa.onclick=handlePrevSlide;
        } else {
            newa.onclick=handleNextSlide;
        }

        div.replaceChild(newa,a);
        div.className=divClass;
    }
}


function renderTitle() {
	var photo = photos[curPhotoIdx];
	var phototitle = document.getElementById("phototitle");
	if (photo.title == "")
		phototitle.innerHTML = "&nbsp;";
	else
		phototitle.innerHTML = photo.title;
}

function renderWell() {
	if (allowWell == true)
		renderPseudoWell();
}

function renderPseudoWell(hoverIdx) {
	var wellimgs = document.getElementById("wellimgs");
	if (!wellimgs)
		return;

	if (!wellCellImgs)
		wellCellImgs = wellimgs.getElementsByTagName("img");

	if (processedWellImgs == false) {
		processedWellImgs = true;
		for (var idx=0; idx < wellPhotos.length; idx++) {
			var a = document.getElementById("well_" + idx);
			a.targetIdx = idx;
			a.href = "javascript:void(0)";
			a.onclick = function() {
							if (state == STATE_SWAPPING) {
								dbg("WELL CLICK BLOCKED by swapstate");
								return;
							}
							if (this.hoverImg != null)
								this.hoverImg.style.visibility = "hidden";

							handlePause();

							// check if we're still hovering over
							// the same guy
							dbg("curWellCell: " + curWellCell + " this.targetIdx:" + this.targetIdx);
							if (curWellCell == this.targetIdx)
								jumpToPhoto(this.targetIdx);
							return false;
						}
			a.onmouseover = function() {
								curWellCell = this.targetIdx;
								if (allowWellHoverImgs)
									renderPseudoWell(this.targetIdx);
							}
			a.onmouseout = function() {
								curWellCell = -1;
								if (this.hoverImg != null)
									this.hoverImg.style.visibility = "hidden";
								if (allowWellHoverImgs)
									renderPseudoWell();
							}
		}
	}
	else {
		if (hoverIdx != null && hoverIdx == curWellCell) {
			var targetAnchor = document.getElementById("well_" + hoverIdx);

			if (targetAnchor.hoverImg == null) {
				var thumbUrl = wellPhotos[hoverIdx].url;
				var hoverImg = document.createElement("img");
				hoverImg.src = thumbUrl;
				hoverImg.style.position = "absolute";
				scaleImg(hoverImg, wellPhotos[hoverIdx].width, wellPhotos[hoverIdx].height, 96, 72);
				targetAnchor.hoverImg = hoverImg;
				setHoverImgPosition(hoverIdx, hoverImg);
				targetAnchor.appendChild(hoverImg);
			}

			// reposition, photo title might have shifted things around
			setHoverImgPosition(hoverIdx, targetAnchor.hoverImg);
		}
	}

	// update hilite on selected well image
	updateWellHilite();

}

function setHoverImgPosition(hoverIdx, hoverImg) {
	var targetDot = document.getElementById("well_img_" + hoverIdx);
	var left = findPosX(targetDot) + WELL_H_OFFSET;
	if (DEBUG)
		targetDot.title = wellPhotos[hoverIdx].id;

	var slidebottom = document.getElementById("slide-bottomcap");
	var top = findPosY(slidebottom) + WELL_V_OFFSET;
	hoverImg.style.top = top + "px";

	var right = left + wellPhotos[hoverIdx].width;
	// don't let the right-most wellcells wander off the frame
	if (mode == MODE_FROM_SITE && right > WELLCELL_MAX_RIGHT)
		left = WELLCELL_MAX_RIGHT - wellPhotos[hoverIdx].width;
	hoverImg.style.left = left + "px";
	hoverImg.style.border = "1px solid #999";
	hoverImg.style.visibility = "visible";
}

// if no display vals set yet, assumes #1 is displayed and #2 is not
function swapDisplayValues(id1, id2) {
	var el = document.getElementById(id1);
	var el2 = document.getElementById(id2);
	if (!el || !el2)
		return;
	el.style.display = "block";
	el2.style.display = "none";
}

/*** TRANSITIONS ***/
function fadeInTop() {
	var topSlide = document.getElementById("topslide");

	opacity += opacityIncrement;
	if (opacity >= 1)
		opacity = .99;
		
	setOpacity(topSlide, opacity);
	
	if (opacity == .99) {
		clearInterval(fadeOpacityCallback);
		revertState();
		nextFade = fadeOutTop;
		if (!is_safari)
			document.getElementById("botslide").visibility = "hidden";
		resetDisplay(true);
		continuePlay();
	}
}

function fadeOutTop() {
	if (opacity == .99 && !is_safari)
		document.getElementById("botslide").visibility = "visible";

	var topSlide = document.getElementById("topslide");
	opacity -= opacityIncrement;
	setOpacity(topSlide, opacity);
	if (opacity <= 0) {
		opacity = 0;
		setOpacity(topSlide, 0);
		clearInterval(fadeOpacityCallback);
		revertState();
		nextFade = fadeInTop;
		resetDisplay(true);
		continuePlay();
	}
}

function fadeInTop_PCIE() {
	var topSlide = document.getElementById("topslide");
	try {
		topSlide.style.filter="blendTrans(duration=0.3)";
		// Make sure the filter is not playing.
		if (topSlide.filters.blendTrans.status != 2) {
			topSlide.filters.blendTrans.apply();
		   //  dbg("fadeInTop_PCIE: showing topslide");
			topSlide.style.visibility="visible";
			topSlide.filters.blendTrans.play();
		}
	}
	catch (e) {
		// dbg("fadeInTop_PCIE: " + e.message);
		topSlide.style.visibility="visible";
	}
	nextImg = document.getElementById("botslideImg");
	nextFade = fadeOutTop_PCIE;
	setupNextFade_PCIE();
}

function fadeOutTop_PCIE() {
	var topSlide = document.getElementById("topslide");
	try {
		topSlide.style.filter="blendTrans(duration=0.3)";
		// Make sure the filter is not playing.
		if (topSlide.filters.blendTrans.status != 2) {
		   //  dbg("fadeOutTop_PCIE: hiding topslide"); 
			topSlide.filters.blendTrans.apply();
			topSlide.style.visibility="hidden";
			topSlide.filters.blendTrans.play();
		}
	}
	catch (e) {
		// dbg("fadeOutTop_PCIE: " + e.message);
		topSlide.style.visibility="hidden";
	}
	nextImg = document.getElementById("topslideImg");
	nextFade = fadeInTop_PCIE;
	setupNextFade_PCIE();
}

function setupNextFade_PCIE() {
	try {
		var topSlide = document.getElementById("topslide");
		if (topSlide.filters.blendTrans.status != 2) {
			revertState();
			resetDisplay(true);
			continuePlay();			
		}
		else {
			setTimeout(setupNextFade_PCIE, 50);
			return;
		}
	}
	catch (e) {
	   //  dbg("setupNextFade_PCIE: " + e.message); 
		revertState();
		resetDisplay(true);
		continuePlay();			
	}
}

function revertState() {
   //  dbg("revertState: going to prev_state " + prev_state); 
	state = prev_state;
}

function continuePlay() {
	// dbg("continuePlay(): state = " + state);
	renderWell();
	renderComments();

	if (state == STATE_PLAYING) {
		clearTimeout(curPlayCallbackId);
		curPlayCallbackId = setTimeout("handleNextSlide(true)", transitionsDelay);
	}
}

/*** HANDLERS ***/
function handlePlay(auto) {
	if (state != STATE_PAUSED && !auto)
		return;
	state = STATE_PLAYING;
	swapDisplayValues("pauselink", "playlink");
	continuePlay();
}

function handlePause() {
	if (state != STATE_PLAYING)
		return;
	state = STATE_PAUSED;
	clearTimeout(curPlayCallbackId);
	swapDisplayValues("playlink", "pauselink");
}

function stopVideo() {
    if (is_mac && is_ie) {
        return false;
    }
    if ((curPhotoIdx > -1 && curPhotoIdx < photos.length) && photos[curPhotoIdx].hasMedia) {
        if (document.videoObj) {
            try {
                document.videoObj.Stop();
            }
            catch (err) {
                dbg("stopVideo exception: " + err);
            }
            
        }
    }
}

function handleNextSlide(auto) {

    stopVideo();

	if (state == STATE_PLAYING && auto != true) {
		handlePause();
	}
	else if (state == STATE_SWAPPING) {
	   //  dbg("handleNextSlide: skipping due to STATE_SWAPPING");
		return;
	}

	if (curPhotoIdx+1 < photos.length) {
		if (false == preload(photos[curPhotoIdx+1])) {
			// dbg("handleNextSlide: BLOCKED, next img not ready");
			retryNextSlideCallbackId = setTimeout("handleNextSlide(" + auto + ")", 100);
			return false;
		}
	}
	clearTimeout(retryNextSlideCallbackId);

    setCurPhotoIdx(curPhotoIdx + 1);
    try {

        if (curPhotoIdx < photos.length && photos[curPhotoIdx].hasMedia) {
            // we're about to display video
            doSubmit();
    		return false;        
        }
    	if (connectionSpeed == CONNECTION_SPEED_DIALUP || curPhotoIdx == photos.length || photos[prevPhotoIdx].hasMedia) {
    		doSubmit();
    		return false;
    	}
        if (photos[curPhotoIdx].hasMedia || photos[prevPhotoIdx].hasMedia) {
            transitionsOn = false;
        }
    } catch (err) {
        dbg("handleNextSlide array out of bounds: " + err);
    }
	
    if (transitionsOn == true) {
		prepTransition();
		renderPhoto(true);
		continueTransition();
	}
	else {
		resetDisplay();
		continuePlay();
	}
    
	return false;
}

function handlePrevSlide() {

    stopVideo();
    	
    if (state == STATE_PLAYING) {
		handlePause();
	}
	else if (state == STATE_SWAPPING) {
		// dbg("handlePrevSlide: skipping due to STATE_SWAPPING");
		return;
	}

	if (curPhotoIdx-1 > -1) {
		if (false == preload(photos[curPhotoIdx-1])) {
			// dbg("handlePrevSlide: BLOCKED, next img not ready");
			retryPrevSlideCallbackId = setTimeout("handlePrevSlide()", 300);
			return false;
		}
		else {
			clearTimeout(retryPrevSlideCallbackId);
		}
	}

	setCurPhotoIdx(curPhotoIdx - 1);
    try {
        if (curPhotoIdx > -1 && photos[curPhotoIdx].hasMedia) {
            // we're about to display video
    		doSubmit();
    		return false;        
        }
    
    	if (connectionSpeed == CONNECTION_SPEED_DIALUP || curPhotoIdx < 0 || photos[prevPhotoIdx].hasMedia) {
    		doSubmit();
    		return false;
    	}
    
       if (photos[curPhotoIdx].hasMedia || photos[prevPhotoIdx].hasMedia) {
            transitionsOn = false;
        }
    
    } catch (err) {
        dbg("handlePrevSlide array out of bounds: " + err);
    }
	if (transitionsOn == true) {
		prepTransition();
		renderPhoto(true);
		continueTransition();
	}
	else {
		resetDisplay();
	}
	return false;
}

function jumpToPhoto(targetIdx) {

    stopVideo();
    try {
    	if (connectionSpeed == CONNECTION_SPEED_DIALUP || photos[targetIdx].hasMedia || photos[curPhotoIdx].hasMedia) {
    		setCurPhotoIdx(targetIdx);
    		doSubmit();
    		return;
    	}

    } catch (err) {
       dbg("jumpToPhoto array out of bound error :" + err);
    }

	if (state == STATE_SWAPPING) {
		return;
	}

	if (photos[targetIdx]) {
		if (false == preload(photos[targetIdx])) {
			retryJumpToPhotoCallbackId = setTimeout("jumpToPhoto(" + targetIdx + ")", 300);
			return;
		}
	}
	else {
		return;
	}
	
    setCurPhotoIdx(targetIdx);

    try {
        if (photos[prevPhotoIdx].hasMedia || photos[targetIdx].hasMedia) {
            transitionsOn = false;
        }

    } catch (err) {
        dbg("jumpToPhoto array out of bound error :" + err);
    }

	if (transitionsOn == true) {
		prepTransition();
		renderPhoto();
		continueTransition();
	}
	else {
		resetDisplay();
	}
}

function prepTransition() {
	if (state != STATE_SWAPPING) {
		prev_state = state;
		// dbg("prepTransition: setting state to " + STATE_SWAPPING);
		state = STATE_SWAPPING;
	}

	var tmp = curImgElId;
	curImgElId = nextImgElId;
	nextImgElId = tmp;
}

function continueTransition() {
	var now = new Date().getTime();
	if (timestamp == 0) 
		timestamp = now;

	if ((now > timestamp + TIMEOUT_VAL) || document.getElementById(curImgElId).complete == true || is_safari) {
		timestamp = 0;
		// dbg("continueTransition: " + curImgElId + " is complete, proceeding...");
		if (is_win && is_ie)
			setTimeout(nextFade, 10);
		else
			fadeOpacityCallback = setInterval(nextFade, fadeInterval);
	}
	else {
		// dbg("continueTransition: waiting on " + curImgElId + " (curPhotoIdx=" + curPhotoIdx + " src=" + document.getElementById(curImgElId).src + "  to load");
		setTimeout(continueTransition, 100);
	}
}

function handleAddToCart() {
	
   	if (state == STATE_SWAPPING)
		return;

	var select = document.getElementById("printsizes");
	var selectIdx = select.selectedIndex;
	var wareId = select.options[selectIdx].value;

	var queryStr = "/" + thisPageName + "?Ubase_handle=";
	var baseHandleStr = "action=buy_photo;";
	baseHandleStr += "photoid=" + photos[curPhotoIdx].id;
	baseHandleStr += ";add=" + wareId + "=1";
	baseHandleStr = escape(baseHandleStr);
	queryStr += baseHandleStr;

	queryStr += "&" + NUM_ITEMS_IN_CART_PARAM + "=" + document.getElementById(NUM_ITEMS_IN_CART_PARAM).value;

	var albumIndexLocal = albumIndex;
	var curPhotoIdxLocal = curPhotoIdx;
	
	if (xmlhttp)
		doXmlHttpSubmit(callback, queryStr);
	else
		doSubmit(queryStr);	
	
	return false;
	
	function callback() {
		
		if (xmlhttp.readyState != 4)
		return;
		
		
	
		var xml = xmlhttp.responseXML;
		var response = xml.getElementsByTagName('response').item(0);
		if (xml) {
			if (getElAttrValue(response, "status") == "ok") {
				addPhotoToCartBin(albumIndexLocal, curPhotoIdxLocal);
	            document.getElementById("printadded").style.visibility = "visible";	            
				var	qty = getElText(xml, 'qty');
				document.getElementById(NUM_ITEMS_IN_CART_PARAM).value = qty;
			}
		}
	}
}

function callbackResponse_AddToCart() {
	if (xmlhttp.readyState != 4)
		return;
	
	var xml = xmlhttp.responseXML;
	var response = xml.getElementsByTagName('response').item(0);
	if (xml) {
		if (getElAttrValue(response, "status") == "ok") {
            document.getElementById("printadded").style.visibility = "visible";
            addPhotoToCartBin(albumIndex, curPhotoIdx);
			var	qty = getElText(xml, 'qty');
			document.getElementById(NUM_ITEMS_IN_CART_PARAM).value = qty;
		}
	}
}

  function clearAddToCartLabel() {
  	var printAdded = document.getElementById("printadded");
  	if (printAdded.style.visibility == "visible")
  		printAdded.style.visibility = "hidden";
  }

function handleLaunchSettingsDialog() {
	if (state == STATE_SWAPPING)
		return;

	handlePause();

	if (launch_DialogSlideshowSettings)
		return launch_DialogSlideshowSettings();
}

function handleLaunchSummaryDialog() {
	if (state == STATE_SWAPPING)
		return;

	handlePause();

	// don't bother to reload if we've already loaded the alb summ
	// and we only have 1 album in this show
	if (relaunchableSummary == true) {
		launch_DialogSlideshowSummary();
	}
	else {
		document.getElementById(NEXT_ACTION_PARAM_ID).value = ACTION_SUMMARY;
		if (xmlhttp) {
			relaunchableSummary = true;
			var content = formatAsQueryStr(document.getElementById("mainfrm"));
			postViaXmlHttp("DialogSlideshowSummary.jsp?xml_http=true&" + addtoken, content, callbackResponse_LaunchSummary);
		}
		else {
			doSubmit(thisPageName);
		}
	}

	return false;
}

function callbackResponse_LaunchSummary() {
	if (xmlhttp.readyState != 4)
		return;
	
	try {
		var dialog = document.getElementById("dialogSlideshowSummary");
		dialog.innerHTML = xmlhttp.responseText;
		document.getElementById(NEXT_ACTION_PARAM_ID).value = "";
		launch_DialogSlideshowSummary();
	}
	catch (e) {
		return "";
	}
}

function callbackDialogSlideshowSummary(collId, collIdx, photoIdx, photoId) {
	
	var origAlbumIdx = document.getElementById(CURRENT_ALBUM_INDEX_PARAM).value;
	setCurPhotoIdx(photoIdx);

	document.getElementById(CURRENT_ALBUM_ID_PARAM).value = collId;
	document.getElementById(CURRENT_ALBUM_INDEX_PARAM).value = collIdx;
	document.getElementById(CURRENT_ALBUM_PHOTO_INDEX_PARAM).value = photoIdx;
	document.getElementById(CURRENT_PHOTO_ID_PARAM).value = photoId;
	
	handlePause();

	if (origAlbumIdx != collIdx) {
		//note skip standard doSubmit() bcs it will 
		//also call setNavInputs(), which will overwrite the values above
		//with values that assume the coll is still 
		//the same, and the curPhotoIdx therefore is valid...
		setStateInputs();
        serializeAddToCartBin();
		document.getElementById("mainfrm").submit();
	}
	else {
		resetDisplay();
	}
	return false;
}

function handleSinglePhotoShare() {
	handlePause();
	document.getElementById(NEXT_ACTION_PARAM_ID).value = ACTION_SHOW_SHARE_DIALOG;
	doSubmit();
	return false;
}

function handleEndSlideshow() {
	document.getElementById(NEXT_ACTION_PARAM_ID).value = ACTION_END_SLIDESHOW;
	doSubmit();
	return false;
}


function updatePhoneLink(id) {
    if (document.getElementById("phone_ui")) {
		var phoneui = document.getElementById("phone_ui");
		phoneui.href = "WallpaperRedirect.jsp?photoid=" + id + "&collid=" + curAlbum.id;
	}
	return false;
}

/*** POSTING ***/

function doSubmit(queryStr, jumpanchor) {
	setNavInputs();
	setStateInputs();
    serializeAddToCartBin();

	var frm = document.getElementById("mainfrm");
	if (queryStr) {
		if (addtoken.length > 0) {
            if (queryStr.indexOf("?")<0) {
                queryStr += ("?" + addtoken);
            } else {
                queryStr += ("&" + addtoken);
            } 
		}
		if (jumpanchor) {
			queryStr += "#" + jumpanchor;
		}
		frm.action = queryStr;
	}

	frm.submit();
}

function doXmlHttpSubmit(callback, queryStr) {
	var content = null;
	if (typeof queryStr != 'undefined') {
		queryStr += "&xml_http=true";
		if (addtoken.length > 0)
			queryStr += "&" + addtoken;
	}
	else {
		setNavInputs();
		setStateInputs();
		
		queryStr = "/" + thisPageName + "?xml_http=true&";
		content = formatAsQueryStr(document.getElementById("mainfrm"));
		if (addtoken.length > 0) {
			queryStr += "&" + addtoken;
		}
	}

	postViaXmlHttp(queryStr, content, callback);
}

function setNavInputs() {
	document.getElementById(CURRENT_ALBUM_PHOTO_INDEX_PARAM).value = curPhotoIdx;
	if (photos[curPhotoIdx]) {
		document.getElementById(CURRENT_PHOTO_ID_PARAM).value = photos[curPhotoIdx].id;
		document.getElementById(PHOTO_OWNER_ID_PARAM).value = photos[curPhotoIdx].ownerId;
	}
}

function setStateInputs() {
	// don't persist 'swap' bcs we don't want to wake up on the other side of album-boundary
	// refresh in an unactionable state 
	if (state == STATE_SWAPPING)
		document.getElementById(TRANSITION_STATE_PARAM).value = STATE_PLAYING;
	else
		document.getElementById(TRANSITION_STATE_PARAM).value = state;

	document.getElementById(SETTINGS_TRANSITIONS_ENABLED_PARAM).value = transitionsOn;
	document.getElementById(SETTINGS_TRANSITIONS_DELAY_PARAM).value = transitionsDelay;
	document.getElementById(SETTINGS_PREFERRED_IMAGE_SIZE_PARAM).value = preferredImageSize;
	document.getElementById(CONNECTION_SPEED_PARAM).value = connectionSpeed;
}

function transferFormValues(frmName) {
	var targetfrm = document.getElementById(frmName);
	// exit if the targetfrm does not exist
	if (targetfrm == null)
		return;
	var mainfrm = document.getElementById("mainfrm");
	
	var inputs = mainfrm.getElementsByTagName("input");
	//loop through the form inputs
	for (var idx=0; idx<inputs.length; idx++) {
		var el = inputs[idx];
		// don't copy the form element if it already exists
		if (!formElementExists(frmName,el.name)) {  	
			var clone = el.cloneNode(false);
			clone.id = clone.id + "_cloned";	
			targetfrm.appendChild(clone);
		}
	}
}

function formElementExists(frmName,element){
	 var targetfrm = document.getElementById(frmName);
	 // exit if the targetfrm does not exist
	 if (targetfrm == null)
		return;
	 var inputs = targetfrm.getElementsByTagName("input");

	 // loop through the inputs to check for a match
	 for (var i=0;i<inputs.length;i++) {
		 var el = inputs[i];
		 if (el.name==element) {
			 return true;
		 }
	 }

}

// Utilities for Add-To-Cart Messaging Persistance

function addAlbumToCartBinArray(albumIndex){
    if (typeof(addToCartBinAlbumList[albumIndex]) == "undefined") {
        addToCartBinAlbumList[albumIndex] = new Array();
    }
}

function addPhotoToCartBin(albumIndex, photoIndex) {
    var photoArrayLength = addToCartBinAlbumList[albumIndex].length;
    // check to see if the album array exists
    if (typeof(addToCartBinAlbumList[albumIndex]) != "undefined") {
        addToCartBinAlbumList[albumIndex][photoArrayLength] = photoIndex; 
    }
    photos[photoIndex].inCart = true;   
}

function serializeAddToCartBin() {
    var albListLength = addToCartBinAlbumList.length;
    var str = "";
    if (albListLength > 0) {   
        for (i=0; i<albListLength; i++ ) { 
                str += addToCartBinAlbumList[i].toString();
                str += (i == (albListLength - 1))?"":"|"; 
        } 
    }
    str = (str=="")?"|":str;
    document.getElementById(ADD_TO_CART_BIN_PARAM).value = str;
}

function deSerializeAddToCartBin() {
  if (addToCartBin == "") {
       return true;
  }
  var albArray = addToCartBin.split("|");
  for (i=0;i<albArray.length;i++) {
      var photoArray = albArray[i].split(",");
      addToCartBinAlbumList[i] = photoArray;
      if (albumIndex == i && photoArray.length> 0) {         
          for (j=0;j<photoArray.length;j++) {
              if (photoArray[j] != "") {
                 photos[photoArray[j]].inCart = true;
             }   
         }
      }
  }

}

// UTILITIES
function preload(photo) {
    if (photo.hasMedia) {
        return true;
    }
	if (photo == null)
		return false;

	if (photo.imgObj == null) {
		if (is_safari || (is_mac && is_ie)) {
			photo.imgObj = document.createElement("img");
			photo.imgObj.style.visibility = "hidden";
			photo.imgObj.style.position = "absolute";
			photo.imgObj.style.left = "0";
			photo.imgObj.style.top = "0";
			document.getElementsByTagName("body").item(0).appendChild(photo.imgObj);
		}
		else {
			photo.imgObj = new Image();
		}

        photo.imgObj.src = photo.url;
        
    }  
	if (is_safari) {
		// dbg("preload safari: photos["+photo.id+"] loaded.");
		return (photo.imgObj.complete == true || (photo.imgObj.width > 0 && photo.imgObj.height > 0));
	}

	// dbg("preload: photos["+photo.id+"].imgObj.complete=" + photo.imgObj.complete);
	return (photo.imgObj.complete == true);
}

function dbg(s) {
	var dbgpane = document.getElementById("debugpane");
	if (dbgpane)
		dbgpane.value = s + " \n " + dbgpane.value;
}

/* used by editComments.js */
function getCurrentPhoto() {
	return photos[curPhotoIdx];
}

function currentlyBusy() {
	return (state == STATE_SWAPPING);
}



