function closeFeatureImage() {
	DISPATCHER.fire("CANCEL_NEXT_SIM_POPUP");
	DISPATCHER.fire("CANCEL_NEXT_THUMBNAIL_POPUP");
	DISPATCHER.fire("CLOSE_SEARCH_POPUP");

	if ($("feature_wrap").style.width != "0px") {
		$("feature_image").setAttribute("alt", "");
		$("feature_wrap").style.overflow = "hidden";

		if ($("sxDownload_panel")) {
			$("sxDownload_panel").style.display = "none";
			$("sxDownload_panel").style.left = "0px";
		}
		// openSxDownloadContent.set(0);
		openSxDownloadContent.isOpen = false;

		closeAllPanels();
		if ($("feature_zoom").hasChildNodes() && $("theMovie")) {
			$("feature_zoom").removeChild($("theMovie"));
		}

		featureOpen.set(0);
		openToolbarContent.set(0);
		openToolbarContent.isOpen = false;

		$("info_panel").style.left = "0px";

		if ($("totalNumResults").value == 0)
			noResultsOn();

		//featureImageSlider.status = "closing";
		//featureImageSlider.slideOut();

		// Return the search results to their original position if the
		// feature image opening moved them, but only if we're at the
		// beginning of the search results.
		var aLeft = parseInt($("search_results_a").style.left);
		var bLeft = parseInt($("search_results_b").style.left);

		if (aLeft > 0 && bLeft > 0) {
			moveResultsOverA.set(0);
			moveResultsOverB.set(bLeft - aLeft);
		}

		sels = getElementsByClassName("selected");
		for (i = 0; i < sels.length; i++) {
			if (sels[i].className.indexOf('result_image') >= 0) {
				sels[i].className = "result_image";
			}
		}
	}

	$("simsearch").style.display = "none";
	$("feature_ss_action_bar").style.display = "none";
	$("feature_ss_action_message").style.display = "none";
	$("ss_action_bar").style.display = "none";
	if ($("simsearch_wrapper")) {
		$("simsearch_wrapper").style.display = "none";
	}
	$("look_ahead").style.display = "none";
}

var POPUP_TIMEOUT_ID = 0;
var POPUP_BOX = null;

function cancelScheduledThumbnailPopup() {
	if (POPUP_TIMEOUT_ID > 0) {
		clearTimeout(POPUP_TIMEOUT_ID); //all I can do here is pray that timeoutID generated is unique and not reused otherwise i just turned something off :-(
		POPUP_TIMEOUT_ID = 0;
	}
}
DISPATCHER.subscribe("CANCEL_NEXT_THUMBNAIL_POPUP", cancelScheduledThumbnailPopup);

function delayedThumbnailPopup() {
	DISPATCHER.fire("CANCEL_NEXT_THUMBNAIL_POPUP");
	DISPATCHER.fire("CANCEL_NEXT_SIM_POPUP");
	DISPATCHER.fire("CLOSE_SIMSEARCH_POPUP");
	POPUP_TIMEOUT_ID = setTimeout(thumbnailPopup.curryAlt(this.id), 450);   //TIME delay for popup set here
}


function thumbnailPopup(elementID) {
	if (application.preventSearchPopup)
		return true;

	var thisElement = $(elementID);
	windowWidth = ww();

	relativeLeft = parseInt(thisElement.parentNode.style.left) + parseInt(thisElement.style.left);

	if (relativeLeft + application.squareSize >= windowWidth) {   // smart advance
		////DISPATCHER.fire("SNAP_TO_GRID_RIGHT");
	} else if (relativeLeft <= 0) {
		////DISPATCHER.fire("SNAP_TO_GRID_LEFT");
	}

	pop = $("popup");
	if (pop) {
		pop.src = "/images/spacer.gif";
	}
	if (parseInt(pop.style.opacity) < 1)
		return;		// in case we're dragging

	var lic_type = i18n.rfShort2;
	if (thisElement.href.getQueryValue("license") == "RM") {
		lic_type = i18n.rmShort2;
	}

	pop.elementID = thisElement.id;
	pop.setAttribute("alt", thisElement.href.getQueryValue("image") + " (" + lic_type + ")");
	pop.setAttribute("license", lic_type);
	pop.setAttribute("isRFEditorialPriceAvail", thisElement.href.getQueryValue("isRFEditorialPriceAvail"));
	pop.setAttribute("canSxDownload", thisElement.href.getQueryValue("canSxDownload"));

	//pop.setAttribute("title", thisElement.id); // this is useful for debugging. At least Peter thinks so.
	// set this for when we launch and comment the line above, this will give the image code in the tooltip
	//pop.setAttribute("title", thisElement.href.getQueryValue("image") + " result " + thisElement.id.slice(4));
	//pop.setAttribute("title", thisElement.title);
	pop.setAttribute("title", i18nX(i18n.click_to_enlarge, newIndex));
	pop.className = thisElement.id;


	pop.src = application.imageServerURL + getResolvedPath(application.thumbRolloverPrefix, thisElement.href.getQueryValue("thumb"));

	index = parseInt(thisElement.id.slice(4));
	parentOffset = parseInt($(thisElement.parentNode.id + "_offset").value);
	offsetX = relativeLeft; // s * Math.floor((index - parentOffset) / application.colSize);
	offsetY = parseInt(thisElement.style.top);

	var tw;
	var th;
	if (application.em_version == 1 || application.em_version == 3) {
		tw = parseInt(thisElement.href.getQueryValue("erw"));
		th = parseInt(thisElement.href.getQueryValue("erh"));
	}
	else {
		tw = parseInt(thisElement.href.getQueryValue("tw"));
		th = parseInt(thisElement.href.getQueryValue("th"));
	}

	var pLeft = offsetX; // + 70 - (tw / 2);

	pop.style.left = pLeft + "px";

	var pTop = offsetY + parseInt($("header").offsetHeight) + 10;
	if (index % application.colSize == (application.colSize - 1)) {	// bottom row: quick fix for EM-640
		if (th > application.squareSize) {
			pTop -= th - application.squareSize;
			pTop -= 50; // lightbox tooltip
		} else {
			pTop -= 38; // lightbox tooltip
		}
	} else if (index % application.colSize != 0 && application.em_version != 1) { // middle row
		pTop -= 40;
	}

	pop.style.top = pTop + "px";

	if (pLeft + application.squareSize >= windowWidth) {  // smart advance
		pop.style.left = windowWidth - tw + "px";
	} else if (pLeft <= 0) {
		pop.style.left = "0px";
	}

	pop.style.width = tw + "px";
	pop.style.height = th + "px";

	if (tw < 100) {
		var padding = Math.round((100 - tw) / 2);
		if (padding < 6) padding = 6;
		pop.style.paddingLeft = padding + "px";
		pop.style.paddingRight = padding + "px";
		pop.style.backgroundImage = "none";
	} else {
		pop.style.paddingLeft = "6px";
		pop.style.paddingRight = "6px";
	}

	tt = displayToolTip(pop);
	pop.style.display = "block";
	var NW = new MfPoint(pop.offsetLeft, pop.offsetTop);
	var SE = new MfPoint(pop.offsetLeft + tt.offsetWidth, pop.offsetTop + parseInt(pop.style.height) + tt.offsetHeight + 10);
	POPUP_BOX = new MfRectangle(NW, SE); //assign the new popup coords
	debug("[POPUP] created new popup with " + POPUP_BOX);
}

function lbThumbnailPopup() {
	windowWidth = ww();

	relativeLeft = parseInt(this.parentNode.style.left) + parseInt(this.style.left);

	if (relativeLeft + application.squareSize >= windowWidth) {   // smart advance
		////DISPATCHER.fire("SNAP_TO_GRID_RIGHT");
	} else if (relativeLeft <= 0) {
		////DISPATCHER.fire("SNAP_TO_GRID_LEFT");
	}

	pop = $("popup");

	var lic_type = i18n.rfShort2;
	if (this.href.getQueryValue("license") == "RM") {
		lic_type = i18n.rmShort2;
	}
	pop.setAttribute("alt", this.href.getQueryValue("image") + " (" + lic_type + ")");
	pop.setAttribute("title", this.title);
	pop.className = this.id;

	pop.src = application.imageServerURL + getResolvedPath(application.thumbRolloverPrefix, this.href.getQueryValue("thumb"));

	index = parseInt(this.id.slice(4));
	parentOffset = parseInt($(this.parentNode.id + "_offset").value);

	offsetX = relativeLeft;
	offsetY = parseInt(this.style.top);

	var tw;
	var th;
	if (application.em_version == 1 || application.em_version == 3) {
		tw = parseInt(this.href.getQueryValue("erw"));
		th = parseInt(this.href.getQueryValue("erh"));
	}
	else {
		tw = parseInt(this.href.getQueryValue("tw"));
		th = parseInt(this.href.getQueryValue("th"));
	}                                                  copyrightDownloadHRC

	var pLeft = offsetX + 70 - (tw / 2);

	pop.style.left = pLeft + "px";

	var pTop = offsetY + parseInt($("header").offsetHeight) + 30;
	pop.style.top = pTop + "px";

	if (pLeft + application.squareSize >= windowWidth) {  // smart advance
		pop.style.left = windowWidth - tw + "px";
	} else if (pLeft <= 0) {
		pop.style.left = "0px";
	}

	pop.style.width = tw + "px";
	pop.style.height = th + "px";

	if (application.em_version == 1) {
		pop.style.width = (tw * 1.33) + "px";
		pop.style.height = (th * 1.33) + "px";
	}

	displayToolTip(pop);

	pop.style.display = "block";

}

function closeAllPopups() {
	closePopup("popup");
	closePopup("ss_popup");
	//closePopup("la_popup");
	//DISPATCHER.fire("SNAP_TO_GRID_RESET");
}
DISPATCHER.subscribe("CLOSE_SEARCH_POPUP", closePopup.curryAlt("popup"));
DISPATCHER.subscribe("CLOSE_SIMSEARCH_POPUP", closePopup.curryAlt("ss_popup"));

/* This is the onclick event handler for popup thumbnails.  We need to determine
 * the result thumbnail itself before executing the simsearch and feature image
 * fetching functions.
 */
function popupClick(thumb, optAtt) {
	if (thumb && thumb.id) {
		fetchFeatureAndSims(thumb, optAtt);
	} else {
		fetchFeatureAndSims($(this.className), optAtt);
	}
	closeAllPanels();
	return false;
}

/* This is the actual execution of the simsearch and feature image functions.
 * It's in a separate function to allow other thumbnails to call this functionality
 * without going through a popup thumbnail. (Currently only used by User History thumbs.)
 */
function fetchFeatureAndSims(thumb, optAtt) {

	var ssType = 1;

	if (thumb.id.slice(0, 3) == "sim")
		ssType = 2;

	if (thumb.id.slice(0, 3) == "his") {
		if (DWRUtil.getValue("refine_search") == "") {
			DWRUtil.setValue("refine_search", DWRUtil.getValue("auto_pair_keyword"));
		}
	}

	/*
	 var autoPair = true;
	 var keywordQuery = $("auto_pair_keyword").value;
	 if ( !keywordQuery ) {
	 keywordQuery = thumb.href.getQueryValue("keyword");
	 if ( keywordQuery == "undefined" ) {
	 keywordQuery = $("ssKeyword").value;
	 }
	 autoPair = false;
	 }

	 if (!keywordQuery ) {
	 keywordQuery = $("querybox").value;
	 autoPair = false;
	 }
	 */

	fetchFeatureImage(thumb, optAtt);

	if (thumb.href.getQueryValue("keyword")) {
		fetchSimSearchResults({image: thumb.href.getQueryValue("image"), offset: Math.ceilThumb(thumb.href.getQueryValue("width")),
					keyword: thumb.href.getQueryValue("keyword"), type: ssType, license: thumb.href.getQueryValue("license") });
	} else {
		fetchSimSearchResults({image: thumb.href.getQueryValue("image"), offset: Math.ceilThumb(thumb.href.getQueryValue("width")),
					type: ssType, license: thumb.href.getQueryValue("license") });
	}

	return false;
}

function popupClear() {
	closePopup(this);
}

function closePopup(pop) {
	if (typeof(pop) == "string")
		pop = $(pop);

	if (!pop || !pop.id)
		return;

	if (pop.id != "la_popup")
		hideToolTip(pop);

	if (pop.style.display == "block") {
		pop.style.display = "none";
		pop.style.backgroundImage = "url(/images/ei/thumb_wait.gif)";
		if (pop.src) {
			pop.src = "/images/ei/clr.gif";
			pop.alt = "";
		}
		pop.className = "";
	}
	if (pop.id == "popup") {
		POPUP_BOX = null;
	} else if (pop.id == "ss_popup") {
		SIM_POPUP_BOX = null;
	}
}

var SIM_POPUP_TIMEOUT_ID = 0;
var SIM_POPUP_BOX = null;

function cancelScheduledSimsearchThumbnailPopup() {
	if (SIM_POPUP_TIMEOUT_ID > 0) {
		clearTimeout(SIM_POPUP_TIMEOUT_ID); //all I can do here is pray that timeoutID generated is unique and not reused otherwise i just turned something off :-(
		SIM_POPUP_TIMEOUT_ID = 0;
	}
}
DISPATCHER.subscribe("CANCEL_NEXT_SIM_POPUP", cancelScheduledSimsearchThumbnailPopup);

function delayed_ssThumbnailPopup() {

	DISPATCHER.fire("CANCEL_NEXT_SIM_POPUP");
	DISPATCHER.fire("CANCEL_NEXT_THUMBNAIL_POPUP");
	DISPATCHER.fire("CLOSE_SEARCH_POPUP");
	SIM_POPUP_TIMEOUT_ID = setTimeout(ss_thumbnailPopup.curryAlt(this.id), 450);   //TIME delay for popup set here
}

function ss_thumbnailPopup(elementID) {
	if (application.preventSimSearchPopup)
		return;

	var thisElement = $(elementID);

    switch ( thisElement.href.getQueryValue("license")  ) {
        case "RM":
            var licTypeLabel = i18n["rmShort"];
            break;
        case "RF":
            var licTypeLabel = i18n["rfShort"];
            break;
        case "MS":
            var licTypeLabel = i18n["em2_crestock_short"];
            break;
        default:
            var licTypeLabel = "";
    }


	var imgcode = thisElement.href.getQueryValue("image") + " " +  licTypeLabel;

	pop = $("ss_popup");
	if (pop) {
		pop.src = "/images/spacer.gif";
	}

	pop.elementID = thisElement.id;

	pop.setAttribute("alt", thisElement.href.getQueryValue("image") + " " + licTypeLabel);
	pop.setAttribute("isRFEditorialPriceAvail", thisElement.href.getQueryValue("isRFEditorialPriceAvail"));
	//pop.setAttribute("title", thisElement.title);    copyrightDownloadHRC
	pop.setAttribute("title", i18nX(i18n.click_to_enlarge, newIndex));
	pop.setAttribute("canSxDownload", thisElement.href.getQueryValue("canSxDownload"));
	//pop.setAttribute("title", thisElement.id);
	pop.className = thisElement.id;

	pop.src = application.imageServerURL + getResolvedPath(application.thumbRolloverPrefix, thisElement.href.getQueryValue("thumb"));

	// This is where LookAhead is started.
	//window.setTimeout("fetchSimSearchResults('" + imgcode + "', 'look_ahead')", 500);

	index = thisElement.id.slice(8);
	offsetX = application.simSquareSize * index;

	var tw;
	var th;
	if (application.em_version == 3) {
		tw = parseInt(thisElement.href.getQueryValue("erw"));
		th = parseInt(thisElement.href.getQueryValue("erh"));
	}
	else {
		tw = parseInt(thisElement.href.getQueryValue("tw"));
		th = parseInt(thisElement.href.getQueryValue("th"));
	}


	popX = tw / 2 - 70;
	popY = -1 * parseInt(thisElement.style.backgroundPosition.slice(thisElement.style.backgroundPosition.indexOf(" ")));

	pop.style.left = parseInt($("simsearch").style.left) + offsetX + "px";

	var pTop = application.headerHeight +
			(application.squareSize * application.colSize) +
			32 + // Auto-pairing UI
			14;

	pop.style.top = pTop + "px";

	if (application.em_version == 1) {
		tw = tw * 1.33;
		th = th * 1.33;
	}

	pop.style.width = Math.floor(tw) + "px";
	pop.style.height = Math.floor(th) + "px";

	if (tw < 100) {
		var padding = Math.round((100 - tw) / 2);
		if (padding < 6) padding = 6;
		pop.style.paddingLeft = padding + "px";
		pop.style.paddingRight = padding + "px";
		pop.style.backgroundImage = "none";
	} else {
		pop.style.paddingLeft = "6px";
		pop.style.paddingRight = "6px";
	}

	tt = displayToolTip(pop);

	pop.style.display = "block";
	var NW = new MfPoint(pop.offsetLeft, pop.offsetTop);
	var SE = new MfPoint(pop.offsetLeft + tt.offsetWidth, pop.offsetTop + parseInt(pop.style.height) + tt.offsetHeight + 80);
	SIM_POPUP_BOX = new MfRectangle(NW, SE); //assign the new popup coords
	debug("[SIM POPUP] created new popup with " + SIM_POPUP_BOX);
}

function la_thumbnailPopup() {
	pop = $("la_popup");
	pop.className = this.id;
	pop.setAttribute("alt", this.href.getQueryValue("image"));

	pop.src = this.style.backgroundImage.slice(4, -1);

	s = 31;
	index = this.id.slice(13);
	offsetX = s * index;

	pop.style.left = parseInt($("look_ahead").style.left) + offsetX - 2 + "px";

	pop.style.display = "block";
}

//EM-1499
function fetchFeatureImageByImageCode(imageCode) {
	var optAtt = {};
	var pseudoThumb = {};
	//the href looks like the line below so try to make a look alike
	//http://fedor.masterfile.com/em/search/index.html?width=366&height=550&image=859-03038453&tw=100&th=150&erw=133&erh=200&thumb=/03/03/84/859-03038453&wmark=getImage/ODU5LTAzMDM4NDUzZW4uMDAwMDAwMDA=AOuc22/859-03038453en.jpg&license=RM&isRFEditorialPriceAvail=undefined
	pseudoThumb.href = "http://www.masterfle.com/em/search/index.html?width=0&height=0&image=" + imageCode + "&thumb=/xx/xx/xx/" + imageCode;
	pseudoThumb.id = "img_0"; //first image

	optAtt.doSimSearchAfter = true; //this will force populate feature to call simsearch fetch
	fetchFeatureImage(pseudoThumb, optAtt); //regular big pop-up

	//fetchSimSearchResults({image:imageCode, offset: Math.ceilThumb(application.lastSeenLargeWidth)}); //and the auto-pair tab
}

function resetFeatureImagePadding(newHeight) {
	//this resets the padding of enlarged image it was extracted from fetchFeatureImage where this lived originally
	$("feature_inner").style.padding = "0"; // unset feature_inner first
	$("feature_zoom").style.padding = "0"; // unset feature_zoom first

	// if the image has a height lower than a specified height, add some padding to the top of feature_inner (EM-601)
	if (newHeight < 200) {
		$("feature_inner").style.padding = "50px 0 0 0";
		$("feature_zoom").style.padding = "50px 0 0 0";
	}
	if (newHeight < 100) {
		$("feature_inner").style.padding = "100px 0 0 0";
		$("feature_zoom").style.padding = "100px 0 0 0";
	}
}

function fetchFeatureImage(thumb, optAtt) {
	//Console.time("Feature Image Fetch");
	wait("Fetching image info...");

	var newWidth = application.minWidthFeature;

	openToolbarContent.set(0);
	openToolbarContent.isOpen = false;

	openSxDownloadContent.set(0);
	openSxDownloadContent.isOpen = false;

	debug("[FEATURE] newWidth is " + newWidth);

	var imgCode = thumb.href.getQueryValue("image");

	var ssType = 1;
	if (thumb.id.slice(0, 3) == "sim") {
		ssType = 2;
	}
	debug("ssType " + ssType + " " + thumb.id + "  " + thumb.href);
	if (ssType == 1) {
		if (thumb.href.getQueryValue("keyword")) {
			rawSearchString = DWRUtil.getValue("lbIcon" + imgCode + "rawSearchString")
			DWRUtil.setValue("bigRawSearchString", rawSearchString);
			DWRUtil.setValue("bigThumbKeyword", Url.decode(thumb.href.getQueryValue("keyword")));
		} else {
			if (DWRUtil.getValue("querybox").trim().containImageCode() || DWRUtil.getValue("querybox").trim() == "") {
				DWRUtil.setValue("bigThumbKeyword", thumb.href.getQueryValue("image"));
			} else {
				DWRUtil.setValue("bigThumbKeyword", DWRUtil.getValue("querybox").trim());
			}

			DWRUtil.setValue("bigRawSearchString", DWRUtil.getValue("rawSearchString"));

			// EM-629 : default secondary search if its empty
			if ($("auto_pair_keyword")) {
				if (DWRUtil.getValue("auto_pair_keyword").trim() == "") {
					if (DWRUtil.getValue("querybox").containImageCode() == false) {
						DWRUtil.setValue("auto_pair_keyword", DWRUtil.getValue("querybox"));
					} else {
						DWRUtil.setValue("auto_pair_keyword", thumb.href.getQueryValue("image"));
					}
				}
			}
		}
	} else {	// sims
		if (DWRUtil.getValue("ssKeyword").trim().containImageCode()) {
			DWRUtil.setValue("bigThumbKeyword", thumb.href.getQueryValue("image"));
		} else {
			DWRUtil.setValue("bigThumbKeyword", DWRUtil.getValue("ssKeyword"));
		}
		DWRUtil.setValue("bigRawSearchString", DWRUtil.getValue("ssRawSearchString"));
	}

	thumb.className = "result_image selected";

	$("feature_image").style.visibility = "visible";
	var featureImage = $("feature_image");

	//var featureButtons = $("feature_buttons");

	var new_width = thumb.href.getQueryValue("width");
	var new_height = thumb.href.getQueryValue("height");
	var offset_left = 0;

	// check to see what the minimum column width of the feature window is
	if (areWeInLightbox()) { // this is the lightbox page
		// hide the back and forward buttons
		$("feature_previous").style.display = "none";
		$("feature_next").style.display = "none";
	}
	else if (new_height > new_width) { // these are the search pages
		//alert(application.minWidthFeature);
		if (application.em_version == 2) { // this is the small UI
			var referenceOffset = 15;
		}
		else {
			var referenceOffset = 60;
		}
		var offset_left = Math.floor((newWidth - new_width) / 2);
		offset_left = ( offset_left - referenceOffset ); // this is to account for the thumbnail reference at the top left corner of the zoomable image
	}
	$("feature_zoom").style.display = "none";

	if ($("feature_wrap").style.width == "0px") {
		featureImage.src = STATIC_REPOSITORY + "/images/ei/ajax-loader-big.gif";
	}
	featureImage.setAttribute("alt", imgCode);
	featureImage.setAttribute("imgCode", imgCode);
	featureImage.setAttribute("streamClickComp", "y");

	if (POPUP_BOX) {
		if (($("feature_inner").offsetLeft + newWidth) > POPUP_BOX.NW.x) {
			DISPATCHER.fire("CLOSE_SEARCH_POPUP");
		}
	}

	//debug("[FEATURE] Fetching feature image [" + imgCode + "]:  sending request...");

//    var currentPage = getCurrentPage();
//    topLeftIndex = parseInt($(currentPage.id + "_offset").value) + application.colSize * Math.floor(Math.abs(parseInt(currentPage.style.left)) / application.squareSize);

	deleteDomImageDetails();

	var params = {};
	params["imgcode"] = imgCode;
	params["thumb"] = thumb.href.getQueryValue("thumb");
	params["resultPosition"] = thumb.id.slice(4);
	params["wmark"] = thumb.href.getQueryValue("wmark");
	params["enlargedType"] = application.featurePrefix;
	params["feature"] = imgCode;
//    params["index"] = topLeftIndex;
	params["keyword"] = $("bigThumbKeyword").value;
	params["rawSearchString"] = $("bigRawSearchString").value;

	// a trigger to call SaveAction.bsh
	if (optAtt && optAtt.doNotAddToHistory) {
		params["doNotAddToHistory"] = true;
	}

	//un-comment the line below for requesting JSON format
	params["outputFormat"] = "json";

	// a trigger to call SetUserSearchHistory.bsh
	if (window.SetUserSearchHistory) {
		params["SetUserSearchHistory"] = true;
		params["startPosition"] = getLeftIndex() + 1;
		params["feature"] = imgCode;
		params["ss_searchPosition"] = 1;
	}

	ImageFetchAjax.execute(params, {
				callback:function (reply) {

					populateFeature(optAtt, reply);

					if (optAtt && optAtt.showSxDownload && openToolbarContent.isOpen && !ELOCKS.get("UI_IS_BUSY")) {
						try {
							var canSxDownload = reply.data["canSxDownload"];
						} catch(err) {
							var canSxDownload = "false";
						}
						if ($("feature_wrap") && $("feature_wrap").style.width != "0px") { // when enlarge panel is shown
							viewSxDownload(imgCode, canSxDownload);
						}
					} else {
						// hide sx download panel
						if ($("sxDownload_panel")) {
							$("sxDownload_panel").style.display = "none";
							openSxDownloadContent.isOpen = false;
						}
					}
				}
			});

	return false;
}

function stream(feature_image) {

	if (userType != USER_GUEST && feature_image.getAttribute("streamClickComp") == "y") {
		feature_image.setAttribute("streamClickComp", "n");       // set thumb attribute so it doesn't get stream again.
		var params = {
			'act-as':'ClickComp',
			'query':DWRUtil.getValue("bigThumbKeyword"),
			'searchString':DWRUtil.getValue("bigRawSearchString"),
			'img':feature_image.getAttribute("imgcode"),
			'em':'y',
			'see':application.storageType
		};

		StreamAjax.execute(params, function(response) {
			if (! response.error) {
				// do nothing
			} else {
				// do nothing
			}
		});
	}
}

function imgZoom() {
	var collection = $("feature_collection").value;
	var imgcode = $("feature_imgcode").value;
	var zoompath = $("feature_zoompath").value;	// chris says we'll need this later on
}

function rand(n) {
	return ( Math.floor(Math.random() * n + 1) );
}

function requestHiRes(image) {
	var params = {};
	params["messageId"] = "HRESCOMPAUTH";
	params["method"] = "get";
	params["image"] = image;

	jQuery("#basic-modal-content").modal(
			{
				escClose: true,
				minHeight: 450,
				maxWidth: 600,
				onClose: function (dialog) {
					dialog.data.fadeOut('slow', function () {
						panel_slide_in("feature_options");
						closeFeatureImage();
						dialog.container.slideUp('slow', function () {
							dialog.overlay.fadeOut('slow', function () {
								jQuery.modal.close();
							});
						});
					});
				}});


	KeyBasedPassthrough.execute(params, function(response) {
		dwr.util.setValue("source", "source: " + response.source);

		if (! response.error) {
			jQuery("#basic-modal-content").html(response.data);

		} else {
			$("error_msg").innerHTML = response.error;
			$("error_msg").style.display = "block";
			EffectFade("error_msg");
		}
	});
}

function populateFeature(optAtt, rawResponse) {
	//debug("[FEATURE] Response received, processing data...");

	if (!optAtt) {
		optAtt = {};
	}

	var data = rawResponse.data;
	if (data.lbInfo) { //load lightbox info if available
		LB_INFO_MAP.update(new MfHashtable(data.lbInfo));
	}
	if (data.scInfo) { //load shopping cart info if available
		SC_INFO_MAP.update(new MfHashtable(data.scInfo));
	}

	var hiResCompsPendingAuth = data.hiResCompsPendingAuth;

	// this is a quick-but-messy implementation, will clean up later
	try {
		var imgcode = data["imgcode"];
	} catch(err) {
		var descr = i18n.not_available;
		debug("[FEATURE] imgcode error caught: " + err)
	}
	try {
		var wm_width = data["wm_width"];
	} catch(err) {
		var wm_width = 450;
	}
	try {
		var canComp = data["canComp"];
	} catch(err) {
		var canComp = i18n.releaseNo;
	}
	try {
		var canCompRM = data["canCompRM"];
	} catch(err) {
		var canCompRM = i18n.releaseNo;
	}
	try {
		var canCompRF = data["canCompRF"];
	} catch(err) {
		var canCompRF = i18n.releaseNo;
	}
	try {
		var canSxDownload = data["canSxDownload"];
	} catch(err) {
		var canSxDownload = "false";
	}
	try {
		var wm_height = data["wm_height"];
	} catch(err) {
		var wm_height = 450;
	}
	try {
		var descr = data["descr"];
	} catch(err) {
		var descr = i18n.not_available;
		debug("[FEATURE] descr error caught: " + err)
	}
	try {
		var artist = data["artist"];
	} catch(err) {
		var artist = i18n.not_available;
		debug("[FEATURE] artist error caught: " + err)
	}
	try {
		var caption = data["caption"];
	} catch(err) {
		var caption = i18n.not_available;
		debug("[FEATURE] caption error caught: " + err)
	}
	caption = caption.replace(/\|/g, " "); // clear out the "|"

	try {
		var propRelease = data["property_release"];
	} catch(err) {
		var propRelease = i18n.not_available;
		debug("[FEATURE] property release error caught: " + err)
	}
	try {
		var modelRelease = data["model_release"];
	} catch(err) {
		var modelRelease = i18n.not_available;
		debug("[FEATURE] model release error caught: " + err)
	}

	try {
		var licenseType = data["license_type"];
	} catch(err) {
		var licenseType = i18n.not_available;
		debug("[FEATURE] license type error caught: " + err)
	}

	switch ( licenseType  ) {
        case "RM":
            var license = i18n.rights_managed;
            break;
        case "RF":
            var license = i18n.royalty_free;
            break;
        case "MS":
            var license = i18n.em2_crestock_collection;
            break;
        default:
            var license = "";
    }

	try {
		var n_path = data["n_path"];
	} catch(err) {
		var n_path = i18n.not_available;
		debug("[FEATURE] n_path error caught: " + err)
	}
	try {
		var isRFEditorialPriceAvail = data["isRFEditorialPriceAvail"];
	} catch(err) {
		var isRFEditorialPriceAvail = "false";
	}

	try {
		var tags = data["tags"];
	} catch(err) {
		var tags = i18n.not_available;
		debug("[FEATURE] tags error caught: " + err)
	}

	// set up hidden input vars for imgZoom
	$("feature_imgcode").value = imgcode;

    if ( $("feature_license") ) {
	    $("feature_license").value = licenseType;
	}

	// display enlarged thumbnail
	$("feature_image").src = application.imageServerURL + n_path;

	$("feature_image").onmousedown = function() {
		stream(this);
	};

	$("inner_info_tags").innerHTML = tags;

	// display the image code
	$("feature_details_left").getElementsByTagName("p")[0].innerHTML = imgcode;
	// display the license type
	$("feature_details_left").getElementsByTagName("p")[1].innerHTML = license;
	// display the artist name
	if (artist) {  // EM-586 : Hide "Artist:" in feature panel caption area when no artist info
		$("feature_details_left").getElementsByTagName("p")[2].innerHTML = i18n.artist + ": " + artist;
	}
	// display the caption
	$("feature_details_left").getElementsByTagName("p")[3].innerHTML = caption;
	$("feature_details_left").getElementsByTagName("p")[3].title = caption;

	// display the model release
	var model_release = i18n.releaseNo;
	if (modelRelease == "yes") {
		var model_release = i18n.releaseYes;
	}
	release_info_model = "<a href='javascript:ShowPopUp(\"/terms.html#release\");' >" + i18n.releaseModel + "</a>" + ": " + model_release;
	$("feature_details_right").getElementsByTagName("p")[0].innerHTML = release_info_model;

	// display the property release
	var prop_release = i18n.releaseNo;
	if (propRelease == "yes") {
		var prop_release = i18n.releaseYes;
	}
	release_info_prop = "<a href='javascript:ShowPopUp(\"/terms.html#release\");' >" + i18n.releaseProperty + "</a>" + ": " + prop_release;
	$("feature_details_right").getElementsByTagName("p")[1].innerHTML = release_info_prop;

    $("zoom_toggle").style.display = "block";
    $("feature_options_icon").style.display = "block";
    if (licenseType == "MS") {
        $("zoom_toggle").style.display = "none";
        $("feature_options_icon").style.display = "none";
    }
	// display file sizes
	if (licenseType == "RM") {
		file_sizes_page = "enlarged_file_sizes.html";
		file_sizes_title = i18n.featureFileSizes;
	} else {
		file_sizes_page = "enlarged_pricing.html";
		file_sizes_title = i18n.enlarged_pricing_and_file_sizes;
	}
	file_sizes = "<a href='javascript:vElg(\"" + file_sizes_page + "\",\"" + imgcode + "\",\"search\",\"" + $("bigThumbKeyword").value + "\",\"" + licenseType + "\");' >" + file_sizes_title + "</a>";
	$("feature_details_right").getElementsByTagName("p")[3].innerHTML = file_sizes;
	if (areWeInRegularSearch()) {
		if ($("simsearch_container")) {
			$("simsearch_container").style.display = "block";
		}
		drawABSimSearchLinks("simsearch_links", imgcode);
	} else {
		if ($("simsearch_container")) {
			$("simsearch_container").style.display = "none";
		}
	}

	$("inner_info_keywords").innerHTML = i18n.related_keywords + ": ";

	var keywords = descr;
	for (i = 0; keywords != null && i < keywords.length; i++) {
		var lnk = document.createElement("a");
		if (areWeInRegularSearch()) {
			lnk.href = "?query=" + Url.encode(keywords[i]);
		} else {
			lnk.href = "/em/search/index.html?query=" + Url.encode(keywords[i]);
		}
		lnk.innerHTML = keywords[i];
		$("inner_info_keywords").appendChild(lnk);
		$("inner_info_keywords").innerHTML += ", ";
	}

	// Turn the keyword and tag links into Ajax searches.
	if (areWeInRegularSearch()) {
		var kLinks = $("inner_info_keywords").getElementsByTagName("a");
		var nKLinks = kLinks.length;
		for (i = 0; i < nKLinks; i++) {
			kLinks[i].onclick = createNewSearchFromLink;
		}

		var kTags = $("inner_info_tags").getElementsByTagName("a");
		var nKTags = kTags.length;
		for (i = 0; i < nKTags; i++) {
			kTags[i].onclick = createNewSearchFromLink;
		}
	}

	if (application.em_version == 1 || application.em_version == 2) {
		wm_width = Math.round(wm_width / 1.22222222222);        //reduce from 550 to 450
		wm_height = Math.round(wm_height / 1.22222222222);

		if (application.em_version == 2) {
			wm_width = Math.round(wm_width / 1.18421052632);    //reduce from 450 to 380
			wm_height = Math.round(wm_height / 1.18421052632);
		}
	} else {
		if (application.colSize == 2) {
			wm_width = Math.round(wm_width / 1.4473684);        //reduce from 550 to 380
			wm_height = Math.round(wm_height / 1.4473684);
		}
	}

	/* Draw lightbox icons */
	if (areWeInRegularSearch()) {
		drawLightboxAddRemoveIcons("bigThumbLbIcon", imgcode);
	} else {
		//lightbox
		drawLightboxAddRemoveIcons("bigThumbLbIcon", imgcode, $("lbid").value);
	}

	/* Draw View History icons */
	drawHistoryIcon("bigThumbHistoryIcon", imgcode);

	/* Draw Enlarge Pricing icons */
	drawPriceIcon("bigThumbPriceIcon", imgcode, DWRUtil.getValue("querybox"), licenseType, isRFEditorialPriceAvail);
	drawShoppingCartIcon("bigThumbSCIcon", imgcode);

	/* hookup link for Subscription Download from feature option panel */
	drawSxDownloadIcon("sxDownload_icon", imgcode, canSxDownload, null);

	/* hookup link for Download Hi-Res Comp from feature option panel */
	if (canComp) {
		if (licenseType == "RM") {
			linkDownloadHiResComp("bigThumbHiResCompDownload", imgcode, canCompRM);
		} else {
			linkDownloadHiResComp("bigThumbHiResCompDownload", imgcode, canCompRF);
		}
	} else if( application.hiResCompsAuthRequestEnabled && application.hiResCompsAuthRequestSupported){
		if (getCookie( getCookie("id")+"_"+"hiResCompsPendingAuth") == null ) {    //|| !hiResCompsPendingAuth
			$("bigThumbHiResCompDownload").innerHTML = "<a href='javascript:requestHiRes(\"" + imgcode + "\");'>" + i18n.sign_up_for_hirescomps + "</a>";
		} else {
			$("bigThumbHiResCompDownload").innerHTML = i18n.hirescomps_pending_approval;
		}
		$("bigThumbHiResCompDownload").style.display = "block";
	}

	/* hookup link for Copyright info from feature option panel below image enlargement, for EM-1450*/
	if (licenseType == "RM") {
		copyrightDownloadHRC("bigThumbCopyright", imgcode, canCompRM);
	} else if (licenseType == "RF") {
		copyrightDownloadHRC("bigThumbCopyright", imgcode, canCompRF);
	} else {
	    if ( $("bigThumbCopyright") ) {
	        $("bigThumbCopyright").style.display = "none";
	    }
	}

	/* hookup link for largerComping from feature option panel */
	linkLargerComping("largerComping", imgcode, $("bigThumbKeyword").value, licenseType);

	/* Add the Zoomify flash applet.
	 */
	var random_number = rand(10000);
	var so = new SWFObject("/flash/viewer_v13.swf?random_number=" + random_number, "theMovie", application.minWidthFeature, wm_height, "6", "#FFFFFF");

	var basePath = computeBasePath(imgcode);

	//	todo: make these PFF-specific vars read-in properties
	so.addVariable("zoomifyServerIP", "zoomify.masterfile.com");
	so.addVariable("zoomifyServerPort", "8080");
	//	end
	so.addVariable("zoomifyImagePath", "/flash/zimages" + basePath + ".pff");
	so.addVariable("zoomifyByteHandlerPath", "/servlet/zoomifyservlet.ZoomifyServlet");
	so.addVariable("zoomifyZoom", "-1");
	so.addVariable("zoomifyToolbar", "1");
	so.addVariable("zoomifyNavWindow", "1");
	so.addParam("wmode", "transparent");
	so.addParam("pluginspage", "http://www.macromedia.com/shockwave/download/index.cgi?P1_Prod_Version=ShockwaveFlash");
	so.write("feature_zoom");

	if (!(rawResponse.doNotAddToHistory)) { //if! -> unless

		// Add the small thumbnail to the user history display. This assumes a successful add.
		var keywordToUse = $("bigThumbKeyword").value;
		if (lastSearchWasSimSearch()) {
			keywordToUse = getLastKeywordQuery();
		}
		addToTodaysHistory({"image_code":imgcode,"wm_width":wm_width,
					"wm_height":wm_height,"wmark":n_path,
					"thumb":basePath,"keywords":keywordToUse,"result_position":rawResponse.resultPosition});
	}

    var newWidth = application.minWidthFeature;
	$("feature_image").style.display = "block";
	$("info_panel").style.left = newWidth + "px";
	$("sxDownload_panel").style.left = newWidth + "px";
	$("feature_metadata").style.width = newWidth + "px";
	featureOpen.set(newWidth);
	if (optAtt.showSxDownload) {
		//no reason to mark this open unless we are actually opening something see NETS-819
		openToolbarContent.isOpen = true;
	}
	if (optAtt.doSimSearchAfter) {
		//EM-1499
		//this should only ever happen when we use pseudo object to display image enlargement
		//also add padding again if we started with pseudo image
		resetFeatureImagePadding(wm_height);
		fetchSimSearchResults({image:imgcode, offset: Math.ceilThumb(wm_width)}); //and the auto-pair tab
	}

	$("feature_wrap").style.overflow = "visible";

    jQuery("#feature_wrap").height ( jQuery("#simsearch_wrapper").height() + jQuery("#search_results_wrapper").height() );

	stopWait();
	DISPATCHER.fire("IMAGE_ENLARGED"); //fire event that an image has been enlarged
}

function deleteDomImageDetails() {
	$("feature_imgcode").value = "";
	if ( $("feature_license") ) {
	    $("feature_license").value = "";
	}
	$("inner_info_tags").innerHTML = "";
	// display the image code
	$("feature_details_left").getElementsByTagName("p")[0].innerHTML = "";
	// display the license type
	$("feature_details_left").getElementsByTagName("p")[1].innerHTML = "";
	// display the artist name
	$("feature_details_left").getElementsByTagName("p")[2].innerHTML = "";
	// display the caption
	$("feature_details_left").getElementsByTagName("p")[3].innerHTML = "";
	// display the model release
	$("feature_details_right").getElementsByTagName("p")[0].innerHTML = "";
	// display the property release
	$("feature_details_right").getElementsByTagName("p")[1].innerHTML = "";
	// display more info on releases
	$("feature_details_right").getElementsByTagName("p")[2].innerHTML = "";
	// display file sizes
	$("feature_details_right").getElementsByTagName("p")[3].innerHTML = "";
	$("inner_info_keywords").innerHTML = "";
}

