
function error(msg) {
	alert(msg);
}

function log(msg) {
	//document.getElementById("log").value = msg + "\n" + document.getElementById("log").value;
}

/* Our XMLHTTPRequest object.  Needs to be global.
 */
var readReq;
var simReadReq;

/*
 *  fetchResultsBlock(index, numResults);
 *
 *  	index - the position at which we start fetching
 *		numResults - the number of results to fetch
 */
function fetchResultsBlock(index, numResults) {
	var targetAction,targetActionName;
    var params = {};
    params["lbInfo"] = String(getActiveLightboxes());
    params["scInfo"] = "yes";

	var lastAction = "";

    closeFeatureImage();

    if (areWeInRegularSearch()){
		targetAction = SearchAjax;
		
		if ( $("search_ready") ) { //MAR-33 : Rethink need to know the moment when the server returns the search result
	        $("search_ready").value = "0";
        }

        targetActionName = "SearchAjax";

        if ($("direction").value == "-1")		// coming in right, exiting left, so get NEXT images
            start = index;
        else
            start = index - numResults + 1;

		if (start < 3) start = 0;	// rounding down to avoid an extra tiny fetch

		lastAction = getLastAction();
        if(lastSearchWasSimSearch()){
            params["simSearchType"] = ABSIM;  //stream if we are doing main area simsearch
        }
    } else if (areWeInLightbox()) {
		targetAction = LightboxViewAction;
        targetActionName = "LightboxViewAction";
       
        if ($("direction").value == "-1")		// coming in right, exiting left, so get NEXT images
            start = index;
        else
            start = index - numResults;

		if (start < 2) start = 0;	// rounding down to avoid an extra tiny fetch

		if (start == 0)
			numResults--;	// fix for EM-711
    }

	var dstr = "Original index is " + index;
    dstr += ", refined index is " + start;
    debug(dstr);

    var total = parseInt($("totalNumResults").value);
	if (total >= 0)
		if (start + numResults > total)
			numResults = total - start;

	if (numResults < 1) {
		debug("[RESULTS] - ABORT - Zero results were requested. Probably harmless, but investigate when you have a moment.");
		return;
	}

	if (targetAction.inProgress)
		return;

    targetAction.inProgress = true;

	debug("[RESULTS] Fetching more results, getting " + numResults + " results starting from " + start + ":  sending fetch request...");

	noResultsOff();

	var search_form = $("search_form");
	var licType = getRadioValue(search_form.licType);

	if (!licType)
		licType = "ALL";

	setLicenseTypeDisplay(licType);

	params["query"] = DWRUtil.getValue("rawQuery");
    params["lictype"] = licType;
	params["sortOrder"] = getRadioValue(search_form.sort);
	params["start"] = start;
	params["perPage"] = numResults;
	params["outputFormat"] = "json";
	params["scriptSessionId"] = dwr.engine._origScriptSessionId;
	params["eventName"] = lastAction;
	params["enlargedType"] = application.featurePrefix;
    params["emVersion"] = application.em_version;

    if (areWeInLightbox()) {
        params["id"] =  DWRUtil.getValue("lbid");
    } else {
        if($("so_horizontal").checked){
          params["so_horizontal"] = true;
        }
        if($("so_vertical").checked){
          params["so_vertical"] = true;
        }
        if($("so_square").checked){
          params["so_square"] = true;
        }
        if($("so_panoramic").checked){
          params["so_panoramic"] = true;
        }
/* EM-1019: disabled on TRUNK
        if($("so_qspace").checked){
          params["so_qspace"] = true;
        }
*/
        debug("[IF] Storing image format checkboxes from image fetch.");
		storeImageFormatCheckboxes();
	}

    wait("Fetching more search results...");

    // a trigger to call SetUserSearchHistory.bsh
    if (window.SetUserSearchHistory) {
        params["SetUserSearchHistory"] = true;
        params["startPosition"] = getLeftIndex() + 1;
    }
    //save our position for keyword queries
    if(lastSearchWasSimSearch() == false && areWeInRegularSearch()){
       setLastPositionInKS(getLeftIndex()+1);
       setLastLicenceInKS(licType);
    }

    targetAction.execute(params, {
			callback:processReadReqChangeWrapper.curryAlt(targetActionName,new Date())
		});


    debug("[RESULTS] Fetch request sent off.");
}

function setLicenseTypeDisplay(licType) {
    if ($("total-hit-count-link")) {
        $("total-hit-count-link").className = "tooltippable";
    }
    if ($("rm-hit-count-link")) {
        $("rm-hit-count-link").className = "tooltippable";
    }
    if ($("rf-hit-count-link")) {
        $("rf-hit-count-link").className = "tooltippable";
    }
    if ($("sx-hit-count-link")) {
        $("sx-hit-count-link").className = "tooltippable";
    }

    if (!licType) licType = "";

	var tgt;

	if (tgt = $(licType.toLowerCase() + "-hit-count-link"))
		tgt.className = "selected tooltippable";
	else {
        if ($("total-hit-count-link")) {
            $("total-hit-count-link").className = "selected tooltippable"
        }
    }
}

function processReadReqChangeWrapper(targetActionName,startDate,rawResponse){
    var d2 = new Date();
    debug("[PROFILER] ["+targetActionName+"] The time difference between DWR request and DWR response was: "+(d2.getTime() - startDate.getTime())+"ms. Calling processReadReqChange.\nScript session id is: "+dwr.engine._origScriptSessionId);
    return processReadReqChange(rawResponse);
}

/* Receive the response for the XML document.
 */
function processReadReqChange(rawResponse) {
	Console.time("SearchAjax request response, initial parsing")


	if (areWeInRegularSearch() && SearchAjax.inProgress) {

	    if ( $("search_ready") ) { //MAR-33 : Rethink need to know the moment when the server returns the search result
	        $("search_ready").value = "1";
        }

		// Stop debugging timers.
		debug("[RESULTS] Response received, processing data...");
		stopWait();
		Console.time("Search Results Fetch: Response Processing");

		// Flag to prevent duplicate searches -- we're done, so we can search again.
		SearchAjax.inProgress = false;

		// Initial post-processing.
		var resultObject = new Array();
		var resultJSON = rawResponse.data;
        if(resultJSON != null && resultJSON.response["storageType"] != null ){
            application.setStorageType(resultJSON.response["storageType"]);
        }

        Console.timeEnd("SearchAjax request response, initial parsing")

		if (SearchAjax.newSearch) {
		    
            if (resultJSON.response['license'] == "RM"){
                $("totalNumResults").value = resultJSON.response["rm-hit-count"];
            } else if (resultJSON.response['license'] == "RF") {
                $("totalNumResults").value = resultJSON.response["rf-hit-count"];
            } else if (resultJSON.response['license'] == "SX") {
                $("totalNumResults").value = resultJSON.response["sx-hit-count"];
            } else if (resultJSON.response['license'] == "MS") {
                $("totalNumResults").value = resultJSON.response["cs-hit-count"];
            } else {
				$("totalNumResults").value = resultJSON.response["hit-count"];
			}

            $("total-hit-count").innerHTML = resultJSON.response["hit-count"];
			debug("[RESULTS] " + resultJSON.response["hit-count"] + " total results")
			$("rm-hit-count").innerHTML = resultJSON.response["rm-hit-count"];
			debug("[RESULTS] " + resultJSON.response["rm-hit-count"] + " RM results")
			$("rf-hit-count").innerHTML = resultJSON.response["rf-hit-count"];
			debug("[RESULTS] " + resultJSON.response["rf-hit-count"] + " RF results")

            var rawSearchString = resultJSON.response["rawSearchString"];
            if ( $("rawSearchString") ) {
                DWRUtil.setValue("rawSearchString", rawSearchString );
            }
            
            if ( $("sx-hit-count") ) {
                $("sx-hit-count").innerHTML = resultJSON.response["sx-hit-count"];    
            }
			
            var querybox = resultJSON.response["query"];
            if (querybox != "") {
                if ( querybox && querybox.search(/^simSearch:/) == -1 ){
                    DWRUtil.setValue("querybox", querybox );
                } else {
                    DWRUtil.setValue("querybox", "");
                }
            }
            var spellChecked = resultJSON.response["spellchecked"];
            if (spellChecked && spellChecked != "" && lastSearchWasSimSearch() == false) {
				$("querybox").value = spellChecked;
            }

			if( $("querybox").value.search(/^simSearch:/) == -1){
            	$("auto_pair_keyword").value = $("querybox").value; // EM-556 : Inject primary search query into Secondary search field.
            	if(DWRUtil.getValue("auto_pair_keyword").trim() == ""){
            	    //it's empty because we are most likely in simsearch whichever the case nothing to lose try using last keyword query
            	    $("auto_pair_keyword").value = getLastKeywordQuery();
            	}
            	debug("injecting primary search query to auto_pair_keyword: "+$("auto_pair_keyword").value);
			}
            updatePublicHitCount(resultJSON.response["hit-count"], resultJSON.response["query"], resultJSON.response["spellchecked"], resultJSON.response["enResolution"],lastSearchWasSimSearch());
            if( resultJSON.response["spellchecked"] && resultJSON.response["spellchecked"] != "" && lastSearchWasSimSearch() == false ){
                setLastKeywordQuery(resultJSON.response["spellchecked"]); //EM-1508
            }
			setProgressBar();
			SearchAjax.newSearch = false;
		}

		if (resultJSON.response["license"] != rawResponse.licType) {
			setRadioValue($("search_form").licType, resultJSON.response["license"]);
			setLicenseTypeDisplay(resultJSON.response["license"]);
		}

		if (resultJSON.response["hit-count"] == 0) {
			displayNoResults();
		}

		if(lastSearchWasSimSearch()){
            showKeywordSearchBackLink(resultJSON.response["hit-count"],getLastKeywordQuery(),getLastPositionInKS(),getLastLicenceInKS());
		} else {
            hideKeywordSearchBackLink();
		}

		var resultObject = resultJSON.response.images;

        if ( resultObject && resultObject.length > 0) {
            if(resultJSON.response.lbInfo){ //load lightbox info if available
                LB_INFO_MAP.update(new MfHashtable(resultJSON.response.lbInfo));
            }
            if(resultJSON.response.scInfo){ //load shopping cart info if available
                SC_INFO_MAP.update(new MfHashtable(resultJSON.response.scInfo));
            }

            numResults = resultObject.length;

	    	boundaries = {
		    	start: parseInt(resultObject[0].result_position),
			    end: parseInt(resultObject[numResults - 1].result_position)
		    }

		    var gtaLeftIndex = parseInt($("gtaLeftIndex").value);

    		leftIndex = resultObject[0].result_position;

	    	if (gtaLeftIndex >= 0) {
		    	var diff = gtaLeftIndex - leftIndex;
    			$("gtaLeftIndex").value = "-1";

		    	// Take the results which are off-screen to the left, and move them to the end of the array.
			    var fragment = resultObject.splice(0, diff);

    			resultObject = resultObject.concat(fragment);
	    	}

            if ( resultJSON.response['license'] == "SX" ) {
		        resultObject.canSxDownload = "SX";          // even if you are in SX tab, show indicator (js work)
            }

		    resultObject.push(boundaries);
        }
    } else if (areWeInLightbox() && LightboxViewAction.inProgress) {
		LightboxViewAction.inProgress = false;

		resultJSON = rawResponse.resultJSON;
		resultObject = resultJSON.resultData;

        if(resultJSON != null && resultJSON["storageType"] != null ){
            application.setStorageType(resultJSON["storageType"]);
        }

        if(resultJSON.lbInfo){ //load lightbox info if available
            LB_INFO_MAP.update(new MfHashtable(resultJSON.lbInfo));
        }
        if(resultJSON.scInfo){ //load shopping cart info if available
            SC_INFO_MAP.update(new MfHashtable(resultJSON.scInfo));
        }

        var nr = resultObject.length;

        $("totalNumResults").value = resultJSON.hit_count;
		if (nr == 0) {
			debug("[RESULTS] No results were returned. Nothing to process.");
			return;
		}

		boundaries = new Object;
		boundaries.start = resultObject[0].result_position;
		boundaries.end = resultObject[nr - 1].result_position;

		resultObject.push(boundaries);
	}
    addNewImages(resultObject, "search_results");

    // EM-558 : Immediately open the preview pane when only *one* image is found
    if (areWeInRegularSearch() && resultJSON.response["hit-count"] == 1 ) {
        if ( $("img_0") ) {
            fetchFeatureAndSims($("img_0"));
        }
    }

    ELOCKS.unset("UI_IS_BUSY");
    debug ("------------------- processReadReqChange unset UI_IS_BUSY 1");
    if ( EBUFFER.get() ) {
        debug ("-------------- executing buffered action = " +  EBUFFER.get()  )
        stopAutoBrowseTimeout();
        DISPATCHER.fire( EBUFFER.get() );
        EBUFFER.unset();
    }
    DISPATCHER.fire("SEARCH_RESULTS_PROCESSED");
}

function displayNoResults() {
	debug("[RESULTS] No results.")
	Console.timeEnd("Search Results Fetch: Response Processing");

	var params = {};
	params["messageId"] = "NO_RESULTS";
	params["query"] = DWRUtil.getValue("rawQuery");

	KeyBasedPassthrough.execute(params, function(response){
		document.getElementById("noresults").innerHTML = response.data;
	});

	noResultsOn();

	return;
}

/*
 * The page swapping function.
 *
 * 		originPageID 	- The ID of the page which remains stationary.  The other page may swap around it.
 *		gta				- A boolean which indicates whether or not this swap is being requested as part of a GTA
 *						movement:
 *							- If true, we ignore the direction variable, and simply force-swap the alternate
 *							page to move to the other side of the origin page.
 *							- If false, we check to see if the alternate page is "behind" the origin page (as per
 *							the current direction), and swap if it isn't.
 */
function swap(originPageID, gta) {

    // Albert Sep 1, 2011 : EMTWO-676
    // I don't know this code nor why we need to swap pages.
    // Apparently this function break lightbox results when swapping.
    // Added logic to ignore this code on LB seems fix the issue
    if (!areWeInRegularSearch()) {
        return;
    }

	var dxn = parseInt($("direction").value);
	var rps = parseInt($("resultsPerSheet").value);

	if (originPageID == "search_results_a") {
		var originPage = $("search_results_a");
		var alternatePage = $("search_results_b");

		var originOffset = $("search_results_a_offset");
		alternateOffset = $("search_results_b_offset");
	} else {
		var originPage = $("search_results_b");
		var alternatePage = $("search_results_a");

		var originOffset = $("search_results_b_offset");
		var alternateOffset = $("search_results_a_offset");
	}

	if (gta) {
		if (parseInt(originOffset.value) < parseInt(alternateOffset.value) ) {
			// alternate is to the right of origin, so we move it to the left
			debug("Swapping pages, GTA: moving " + alternatePage.id + " to the left of " + originPage.id);

			alternateOffset.value = parseInt(originOffset.value) - rps;
			alternatePage.style.left = parseInt(originPage.style.left) - parseInt(alternatePage.style.width) + "px";
		} else {
			// alternate is to the left of origin, so we move it to the right
			debug("Swapping pages, GTA: moving " + alternatePage.id + " to the right of " + originPage.id);

			alternateOffset.value = parseInt(originOffset.value) + rps;
			alternatePage.style.left = parseInt(originPage.style.left) + parseInt(alternatePage.style.width) + "px";
		}
		debug("Swapping sanity check [GTA]:  a_left is " + $("search_results_a").style.left + ", b_left is " + $("search_results_b").style.left);
		return;
	}

	if (dxn == -1) {
		// ensure alternatePage is AFTER originPage.  If not, swap.
		if (parseInt(alternatePage.style.left) <= parseInt(originPage.style.left) || parseInt(alternateOffset.value) <= parseInt(originOffset.value)) {
			// swap!
			alternateOffset.value = parseInt(originOffset.value) + rps;
			debug("Swapping pages [-1]:  adding originPage left [" + originPage.style.left + "] to alternatePage width [" + alternatePage.style.width + "]");
			alternatePage.style.left = (parseInt(originPage.style.left) + parseInt(alternatePage.style.width)).toString() + "px";
			debug("Swapping [-1]:  alternate [" + alternatePage.id + "] left is now " + alternatePage.style.left);
			debug("Swapping sanity check [-1]:  a_left is " + $("search_results_a").style.left + ", b_left is " + $("search_results_b").style.left);
		}
	} else {
		// ensure alternatePage is BEFORE originPage.  If not, swap.
		if (parseInt(alternatePage.style.left) >= parseInt(originPage.style.left) || parseInt(alternateOffset.value) >= parseInt(originOffset.value)) {
			// swap!
			debug("Swapping pages [+1]:  haven't really debugged this yet.");

			alternateOffset.value = parseInt(originOffset.value) - rps;
			alternatePage.style.left = (parseInt(originPage.style.left) - parseInt(alternatePage.style.width)) + "px";

			debug("Swapping [+1]:  alternate [" + alternatePage.id + "] left is now " + alternatePage.style.left);
			debug("Swapping sanity check [+1]:  a_left is " + $("search_results_a").style.left + ", b_left is " + $("search_results_b").style.left);
		}
	}
}


//the below is now used by simsearch only
function thumbClick() {
	//if (this.parentNode.id == "look_ahead")
	//	fetchFeatureImage(this);
    DISPATCHER.fire("CANCEL_NEXT_THUMBNAIL_POPUP");
    fetchFeatureAndSims(this);
	return false;
}

function addNewImages(resObj, parent) {
    if ( ! resObj || resObj.length == 0) {
		return;
    }
    if (resObj.success == -1) {
		log("Error reading messages: " + resObj.error)
		return;
	}

	/* Figure out what the current "page" is, so we know where to start adding images.
	 */
	if (parent == "search_results") {
		Console.time("Search Results Fetch: Swap checking.");
		boundaries = resObj.pop();

		numItems = resObj.length;

		originPageID = "";

		debug("[RESULTS] Adding results " + boundaries.start + " - " + boundaries.end);

		startOffsetOne = boundaries.start - 1;
		endOffsetOne = boundaries.end + 1;

		rps = parseInt($("resultsPerSheet").value);

		if ($("img_" + startOffsetOne)) {
			// direction is -1
			originPageID = $("img_" + startOffsetOne).parentNode.id;
			originOffset = parseInt($(originPageID + "_offset").value);

			debug("Glue detection: img_" + startOffsetOne + " exists at beginning of fetched set.");

			if (endOffsetOne - 1 > originOffset + rps) {
				debug("Result #" + (endOffsetOne - 1) + " is at the end of this set and on the next page: swapping pages.")
				// perform the swap
				swap(originPageID);
			}
		} else if ($("img_" + endOffsetOne)) {
			// direction is 1
			originPageID = $("img_" + endOffsetOne).parentNode.id;
			originOffset = parseInt($(originPageID + "_offset").value);

			debug("Glue detection: img_" + endOffsetOne + " exists at end of fetched set.");

			if (startOffsetOne + 1 < originOffset) {
				debug("Result #" + (startOffsetOne + 1) + " is at the beginning of this set and on the previous page: swapping pages.");
				// perform the swap
				swap(originPageID);
			}
		} else {
			/* If we're here, there's no image set on either side of this result set which we can hook onto.
			 * That means that this result set was called as a result of go-to-anywhere.
			 */

			// figure out which page we're moving to
			startPageNum = Math.floor(boundaries.start / rps)
			endPageNum = Math.floor(boundaries.end / rps)

			// Calculate page of starting position, and page of ending position.  Conditions:
			// 	1. Page of starting position must be positionally BEFORE page of ending position.
			//  2. ... is that it?
			//
			// If any of those conditions fail, SWAP.

			if (startPageNum % 2 == 0) { // even
				startPageID = "search_results_a";
			} else {
				startPageID = "search_results_b";
			}

			if (endPageNum % 2 == 0) { // even
				endPageID = "search_results_a";
			} else {
				endPageID = "search_results_b";
			}

			originOffset = parseInt($(startPageID + "_offset").value);
			endOffset = parseInt($(endPageID + "_offset").value);
			originPageID = startPageID; // need this later on

			if (startPageNum != endPageNum) {
				if (endOffset < originOffset) {
					debug("GTA swap, because originOffset [" + originOffset + "] is not smaller than endOffset [" + endOffset + "]");
					swap(startPageID, true);
				} else {
					debug("GTA call, but originOffset [" + originOffset + "] is already smaller than endOffset [" + endOffset + "]");
				}
			}
		}
		Console.timeEnd("Search Results Fetch: Swap checking.");
	} else { // simsearch!
		numItems = resObj.length;

    }

	/* Note for my own reference (move to another comment later):
	 *
	 * origin page's image run FROM originPage.resultOffset TO originPage.resultOffset + resultsPerSheet
	 *
	 * so, if an incoming image's pos is in between those values, add to origin page.
	 * otherwise, add to alternate page.  (and calibrate? when do we calibrate, anyway?)
	 *
	 */
	Console.time("Search Results Fetch: Adding images.");

    for (i=0; i < numItems; i++) {		// think about doing this backwards, later?   that would be fun! /////////////////////////////////

		if (parent == "search_results") {
			newIndex = resObj[i].result_position;	// don't need newIndex, it's in the element
			rps = parseInt($("resultsPerSheet").value);
			if (originOffset <= newIndex + 1 && newIndex + 1 <= originOffset + rps) {
				// we're on this page!
				parentElement = originPageID;
			} else {
				// we're not on this page!  What the heck do we do?
				if (originPageID == "search_results_a")
					parentElement = "search_results_b";
				else
					parentElement = "search_results_a";
			}
		} else {
			parentElement = parent;
			newIndex = resObj[i].result_position;	// don't need newIndex, it's in the element

			//if (parent == "look_ahead") {
			//	newIndex = i;
			//	type = "eh";
			//}
		}

		var basePath = computeBasePath(resObj[i].imgcode);
        var thumb;
        /*
        if (parent == "simsearch") {
            thumb = SSTHUMBQ.pop();
        } else {
            thumb = THUMBQ.pop();
        } */
         thumb = A_Q.pop();
         thumb.removeAttribute( "style" );

        if ( application.em_version == 1 ) {
            new_width = Math.floor(parseInt(resObj[i].wm_width) / 1.22222222222);       //from 550 to 450
			new_height = Math.floor(parseInt(resObj[i].wm_height) / 1.22222222222);     //from 550 to 450
        } else if ( application.em_version == 2 ) {
            new_width = Math.floor(parseInt(resObj[i].wm_width) / 1.44736842105);       //from 550 to 380
			new_height = Math.floor(parseInt(resObj[i].wm_height) / 1.44736842105);     //from 550 to 380
        } else {
            new_width = resObj[i].wm_width;
			new_height = resObj[i].wm_height;
            if ( screen.width <= 1024 ) {
                new_width = Math.floor(parseInt(resObj[i].wm_width) / 1.44736842105);       //from 550 to 380
			    new_height = Math.floor(parseInt(resObj[i].wm_height) / 1.44736842105);     //from 550 to 380
            }
        }
        thumb.href = "?width=" + new_width + "&height=" + new_height;

        thumb.href += "&image=" + resObj[i].imgcode;
        if ( resObj[i].keyword ) {
            thumb.href += "&keyword=" + Url.encode(resObj[i].keyword);
        }
        thumb.href += "&tw=" + resObj[i].tw;
		thumb.href += "&th=" + resObj[i].th;
        thumb.href += "&erw=" + resObj[i].erw;
		thumb.href += "&erh=" + resObj[i].erh;
		thumb.href += "&thumb=" + basePath;
		thumb.href += "&wmark=" + resObj[i].n_path;
        thumb.href += "&license=" + resObj[i].license;
        if ( resObj[i].isRFEditorialPriceAvail ) {
            thumb.href += "&isRFEditorialPriceAvail=" + resObj[i].isRFEditorialPriceAvail;
        }

        if ( isDefined ( resObj.canSxDownload ) || resObj[i].canSxDownload ) {
            thumb.href += "&canSxDownload=" + resObj[i].canSxDownload;
        }

        //thumb.setAttribute("title", i18nX(i18n.click_to_enlarge, newIndex) );
        thumb.className = "result_image";
        thumb.style.display = "block";

        if (parent == "search_results") {

            thumb.style.backgroundImage = "url("+application.imageServerURL + getResolvedPath(application.thumbPrefix, basePath) + ")";
            thumb.style.width  = application.squareSize + "px";
            thumb.style.height = application.squareSize + "px";

            offsetX = application.squareSize * (Math.floor(newIndex / application.colSize) - Math.floor(parseInt($(parentElement + "_offset").value / application.colSize)));
            offsetY = application.squareSize * ((newIndex) % application.colSize);

            offsetX = application.squareSize * (Math.floor(newIndex / application.colSize) - Math.floor(parseInt($(parentElement + "_offset").value / application.colSize)));
            offsetY = application.squareSize * ((newIndex) % application.colSize);

            if (areWeInRegularSearch()) {
               	thumb.id = "img_" + newIndex;

                thumb.style.left = offsetX + "px";
                thumb.style.top = offsetY + "px";

                //disabled onclick
                thumb.onclick = function() {
                    return false;
                }
                //disabled drag
                thumb.onmousedown  = function(event){
                    if(event && event.preventDefault) {
                        event.preventDefault();
                    }
                }
                //use mouseup instead on onclick
                thumb.onmouseup = function() {
                    closeAllPanels();
                    DISPATCHER.fire("CANCEL_NEXT_THUMBNAIL_POPUP");
                    fetchFeatureAndSims ($(this) );
                    return false;
                }

                thumb.onmouseover = delayedThumbnailPopup;

                $(parentElement).appendChild(thumb);

            } else { // lightbox

                thumb.id = "img_lb_" + newIndex;

                thumb.style.width  = application.squareSize + "px";
                thumb.style.height = (application.squareSize-40) + "px";        // 40px is the placeholder for the mini icons

                //thumb_div = document.createElement("div");
                thumb_div = DIV_Q.pop();

                thumb_div.id = "img_" + newIndex;

                thumb_div.className = "img_lb";

                thumb_div.style.left = offsetX + "px";
                thumb_div.style.top = offsetY + "px";

                //var element  = document.createElement("div");
                var element  = DIV_Q.pop();
                element.id = "lb_thumb_icon_"+newIndex;
                element.className = "lb_thumb_icon";

                while (element.firstChild) {
                    element.removeChild(element.firstChild);
                }

                //var thumb_code  = document.createElement("span");
                var thumb_code  = SPAN_Q.pop();
                thumb_code.id = "thumb_code_"+newIndex;
                thumb_code.className = "thumb_code";

                switch ( resObj[i].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 = "";
                }

                thumb_code.innerHTML = resObj[i].imgcode + " " + licTypeLabel;

                element.appendChild( thumb_code );

                //var lb_thumb_left  = document.createElement("div");
                var lb_thumb_left  = DIV_Q.pop();
                lb_thumb_left.id = "feature_buttons_" + newIndex;
                lb_thumb_left.className = "lb_feature_buttons";

                //var element_input  = document.createElement("input");
                var element_input  = INPUT_Q.pop();
                element_input.id = "lbIcon"+resObj[i].imgcode+"Keyword";
                if ( element_input.getAttribute('type') !== 'hidden' ) {
                    element_input.setAttribute('type', 'hidden');
                }
                element_input.setAttribute('value', resObj[i].keyword);
                lb_thumb_left.appendChild( element_input );

                var element_rawSearchString = INPUT_Q.pop();
                element_rawSearchString.id = "lbIcon"+resObj[i].imgcode+"rawSearchString";
                if ( element_rawSearchString.getAttribute('type') !== 'hidden' ) {
                    element_rawSearchString.setAttribute('type', 'hidden');
                }
                element_rawSearchString.setAttribute('value', resObj[i].rawSearchString);
                lb_thumb_left.appendChild( element_rawSearchString );                

                //var element_lb1  = document.createElement("div");
                var element_lb1  =  DIV_Q.pop();
                element_lb1.id = "lbIcon" + resObj[i].imgcode + "1";
                element_lb1.className = "feature_icon tooltippable";
                element_lb1.onmouseover = globalTooltipShow;
		        element_lb1.onmouseout = globalTooltipHide;
                lb_thumb_left.appendChild( element_lb1 );


                //var element_lb2  = document.createElement("div");
                var element_lb2  =  DIV_Q.pop();
                element_lb2.id = "lbIcon" + resObj[i].imgcode + "2";
                element_lb2.className = "feature_icon tooltippable";
                element_lb2.onmouseover = globalTooltipShow;
		        element_lb2.onmouseout = globalTooltipHide;
                lb_thumb_left.appendChild( element_lb2 );

                //var element_lb3  = document.createElement("div");
                var element_lb3  =  DIV_Q.pop();
                element_lb3.id = "lbIcon" + resObj[i].imgcode + "3";
                element_lb3.className = "feature_icon tooltippable";
                element_lb3.onmouseover = globalTooltipShow;
		        element_lb3.onmouseout = globalTooltipHide;
                lb_thumb_left.appendChild( element_lb3 );

                //var element_lb4  = document.createElement("div");
                var element_lb4  = DIV_Q.pop();
                element_lb4.id = "lbIcon" + resObj[i].imgcode + "4";
                element_lb4.className = "feature_icon tooltippable";
                element_lb4.onmouseover = globalTooltipShow;
		        element_lb4.onmouseout = globalTooltipHide;
                lb_thumb_left.appendChild( element_lb4 );

                //var element_ss  = document.createElement("div");
                var element_ss  = DIV_Q.pop();
                element_ss.id = "lbSimSearch" + newIndex;
                element_ss.className = "feature_icon tooltippable";
                element_ss.onmouseover = globalTooltipShow;
		        element_ss.onmouseout = globalTooltipHide;
                lb_thumb_left.appendChild( element_ss );

                //var element_prices  = document.createElement("div");
                var element_prices  = DIV_Q.pop();
                element_prices.id = "lbPrice" + newIndex;
                element_prices.className = "feature_icon tooltippable";
                element_prices.onmouseover = globalTooltipShow;
		        element_prices.onmouseout = globalTooltipHide;
                lb_thumb_left.appendChild( element_prices );

                //var element_cart  = document.createElement("div");
                var element_cart  = DIV_Q.pop();
                element_cart.id = "lbCart" + resObj[i].imgcode;
                element_cart.className = "feature_icon tooltippable";
                jQuery(element_cart).attr("imgcode",resObj[i].imgcode);
                element_cart.onmouseover = globalTooltipShow;
		        element_cart.onmouseout = globalTooltipHide;
                lb_thumb_left.appendChild( element_cart );

                if ( resObj[i].canSxDownload ) {
                    var element_sx  = DIV_Q.pop();
                    element_sx.id = "sxDownload" + resObj[i].imgcode;
                    element_sx.className = "feature_icon tooltippable";
                    element_sx.onmouseover = globalTooltipShow;
		            element_sx.onmouseout = globalTooltipHide;
                    lb_thumb_left.appendChild( element_sx );
                }

                element.appendChild( lb_thumb_left );

                thumb_div.appendChild(thumb);
                thumb_div.appendChild(element);

                //disabled onclick
                thumb.onclick = function() {
                    return false;
                }
                //disabled drag
                thumb.onmousedown  = function(event){
                    if(event && event.preventDefault) {
                        event.preventDefault();
                    }
                }
                //use mouseup instead on onclick
                thumb.onmouseup = function() {
                    closeAllPanels();
                    fetchFeatureAndSims ($(this) );
                    return false;
                }
                               
                thumb.onmouseover  = function(event){
                    if(event && event.preventDefault) {
                        event.preventDefault();
                    }
                }

                $(parentElement).appendChild(thumb_div);

                drawLightboxAddRemoveIcons("lbIcon"+resObj[i].imgcode, resObj[i].imgcode, $("lbid").value );

                drawSimSearchIcon("lbSimSearch"+newIndex,resObj[i].imgcode,thumb);
                drawPriceIcon("lbPrice"+newIndex,resObj[i].imgcode,DWRUtil.getValue("querybox"), resObj[i].license, resObj[i].isRFEditorialPriceAvail);
                drawShoppingCartIcon("lbCart"+resObj[i].imgcode, resObj[i].imgcode);
                                      
                drawSxDownloadIcon("sxDownload"+resObj[i].imgcode, resObj[i].imgcode, resObj[i].canSxDownload, thumb.id );

                //thumb_div.appendChild(thumb);
                //$(parentElement).appendChild(thumb_div);
            }



        } else if (parent == "simsearch") {

            thumb.style.backgroundImage = "url("+application.imageServerURL + getResolvedPath(application.simThumbPrefix, basePath) + ")";
            thumb.className = "sim_result_image";
            if ( newIndex == 0 ) { // AlbertW 09.02.2008: EM-384
                /*    AW Feb 26, 2009: Since we don't show it on the screen. I removed it.
                while ($("ss_thumb").firstChild) {
                   $("ss_thumb").removeChild($("ss_thumb").firstChild);
                }

                var mini_thumb = document.createElement("a");
                mini_thumb.id = "sim_mini_thumb";
                mini_thumb.className = "result_image";
                mini_thumb.style.backgroundImage = "url("+application.imageServerURL + getResolvedPath("eh", basePath) + ")";

                $("ss_thumb").appendChild(mini_thumb);
                */
            } else {
                newSimIndex = newIndex-1; // newIndex minus 1 because index 0 is used for mini thumb

                offsetY = 0;
                offsetX = application.simSquareSize * newSimIndex;

                thumb.id = "sim_img_" + newSimIndex;

                //disabled onclick
                thumb.onclick = function() {
                    return false;
                }
                //disabled drag
                thumb.onmousedown  = function(event){
                    if(event && event.preventDefault) {
                        event.preventDefault();
                    }
                }

                thumb.onmouseover = delayed_ssThumbnailPopup;

                thumb.onmouseup = thumbClick;


                thumb.style.left = offsetX + "px";
                thumb.style.top = offsetY + "px";

                $(parentElement).appendChild(thumb);
            }

        } else {
			// LookAhead
			offsetY = 0;
			offsetX = application.squareSize * newIndex;
			thumb.id = "tiny_sim_img_" + newIndex;
			if (newIndex == 0)
				thumb.style.backgroundPosition  = "0px 0px";
			else
				thumb.style.backgroundPosition  = "50% 0px";

			thumb.onmouseover = la_thumbnailPopup;
            thumb.onclick = thumbClick;

            thumb.style.left = offsetX + "px";
            thumb.style.top = offsetY + "px";

            $(parentElement).appendChild(thumb);
        }


    } // end of for loop
	//debug("[RESULTS] Finished adding images.");
	if (isBlurOn()) {
		debug("Finished image fetch for GTA/refresh. Turning blur image OFF.");
		blurOff();
	}
	Console.timeEnd("Search Results Fetch: Adding images.");
	if (parent == "simsearch") {
		//debug("[SIMSEARCH] Finished fetching simsearch results.");
		//Console.timeEnd("SimSearch/LookAhead Fetch and Display");
		Console.timeEnd("SimSearch/LookAhead Fetch: Response Processing");
	} else if (parent == "look_ahead") {
		$("look_ahead_headsup").style.display = "none";
		debug("[SIMSEARCH] Finished fetching LookAhead results.");
		Console.timeEnd("SimSearch/LookAhead Fetch and Display");
		Console.timeEnd("SimSearch/LookAhead Fetch: Response Processing");
	} else {
		Console.timeEnd("Search Results Fetch: Response Processing");
		debug("[RESULTS] Finished fetching more results.");
		garbageCollect();
	}
}

function fetchSimSearchResults(options) {
	var image = options.image;
	var stream = options.stream;
	var keyword = options.keyword;

    var offset = options.offset;

    var startPos = options.startPos;

//	if (SimSearchAjax.inProgress)
//		return;

//	SimSearchAjax.inProgress = true;

	if (image)
		$("current_ss_image").value = image;
	else
		image = $("current_ss_image").value;

    var target;
	if (stream == "look_ahead") {
		if ($("ss_popup").alt != image)
			return;
		target = $("look_ahead");
	} else
		target = $("simsearch");

	var streamTracker = $("stream_" + target.id);
	if (stream == "look_ahead" && streamTracker.value == image)
		return;

	streamTracker.value = image;

	// Definitely going ahead with the SimSearch.  Perform display adjustments.
	if (offset) {
        offset = Math.minThumbWidth(offset);   // check min width for feature image panel.

        $("feature_ss_action_bar").style.left = offset - 1 + "px";
        $("feature_ss_action_message").style.left = offset + "px";
        $("simsearch").style.left = offset + application.simSquareSize + "px";
		$("ss_action_bar").style.left = offset + "px";
		$("look_ahead").style.left = offset + 297 + "px";
	}

    stopSimsThrottle();
	stopThrottle();

	//	Console.time("SimSearch/LookAhead Fetch and Display");

/* AlbertW 07.16.08:
   The reason is :  EM-189 part 2. clearing the results caused the parent id to be null.
   Resolution: delay the clean up until the new results are ready to be displayed.
    // Remove old SimSearch/LookAhead results.
    while (target.firstChild) {
		if (target.firstChild.id == "look_ahead_headsup")
			var la_headsup = target.removeChild(target.firstChild);
		else
			target.removeChild(target.firstChild);
	}
	target.style.display = "block";

	// Put back the LookAhead notification.
	if (la_headsup) {
		la_headsup.style.display = "block";
		target.appendChild(la_headsup);
		target.style.display = "block";
	}
*/
	$("totalSimResults").value = 0;

    if (options.type != -1 && !options.type) {
		options.type = 1;
	}

    var auto_pair = false;
    var keywordQuery = null;


    if ( options.type == 2 ) {
        var apk = DWRUtil.getValue("auto_pair_keyword").trim();
        if ( apk == "" && apk.search(/^simSearch/) == -1 ) {
            if ( DWRUtil.getValue("querybox").trim().containImageCode() == false ) {
                keywordQuery =  DWRUtil.getValue("querybox");
            } else {
                keywordQuery =  image;
            }
        } else {
            // EM-867 : update refine search field for single image search
            var objRegExp = /^\d+\-\d+$/;
            if( objRegExp.test(DWRUtil.getValue("ssKeyword")) ) {
                DWRUtil.setValue("ssKeyword", image );
            }
            keywordQuery = DWRUtil.getValue("ssKeyword");
        }

        auto_pair = false;
    }

    if ( !keywordQuery ) {
        if ( keyword ) {
            keywordQuery = Url.decode(keyword);
            if ( keywordQuery == "" ) {
                if ( DWRUtil.getValue("querybox").trim().containImageCode() == false ) {
                    if ( DWRUtil.getValue("querybox").trim() == "" ) {
                        keywordQuery = image;
                    } else {
                        keywordQuery = DWRUtil.getValue("querybox");
                    }
                }
            }
            auto_pair = false;
        } else {
            if ( DWRUtil.getValue("refine_search") != "" ) {
                if ( DWRUtil.getValue("auto_pair_keyword").trim() == "" ) {
	     			if( DWRUtil.getValue("querybox") && DWRUtil.getValue("querybox").search(/^simSearch/) == -1){
                        keywordQuery = DWRUtil.getValue("querybox");
                    }
                    DWRUtil.setValue("refine_search", "" );
                } else {
					if( DWRUtil.getValue("refine_search").search(/^simSearch/) == -1){
                        keywordQuery = DWRUtil.getValue("refine_search");
                    }
                }
            }
            else {
                if (lastSearchWasSimSearch()){
                    keywordQuery = getLastKeywordQuery();
                }else if( DWRUtil.getValue("querybox").trim().containImageCode() || DWRUtil.getValue("querybox").trim() == "" ) {
                    keywordQuery = image;
                } else{
                    keywordQuery = DWRUtil.getValue("auto_pair_keyword");
                }
            }

            auto_pair = true;
        }

        if (!keywordQuery && DWRUtil.getValue("querybox").search(/^simSearch/) == -1) {
    	    keywordQuery = DWRUtil.getValue("querybox");
            auto_pair = false;
        }
    }

    if (options.type > 0 && auto_pair) {
		options.type += 2;
	}

	if (!startPos) {
		startPos = 0;
    }

    if ( image == keywordQuery ) {  // SimSearch by image code
        options.type = 5;
    }

    debug("[SIMSEARCH] Fetching SimSearch results for " + image + " " + keywordQuery + ", target is " + target.id);

    var params = {};
    params["lbInfo"] = String(getActiveLightboxes());
    params["scInfo"] = "yes";
    params["imgcode"] = image;
    if ( keywordQuery != null ) {
        keywordQuery = keywordQuery.trim();
    }
    params["keyword"] = keywordQuery;
    params["lictype"] = options.license || getRadioValue($("search_form").licType);
    params["start"] = startPos;
    params["perPage"] = target.id == "look_ahead" ? 32 : 32;	// this will be fleshed out later on
	params["ssType"] = options.type;
	if( options.streamThis != null){
	  params["streamThis"] = options.streamThis;
    }
    if( options.streamSource != null){
	  params["streamSource"] = options.streamSource;
    }
    params["stream"] = target.id;
	params["outputFormat"] = "json";
    params["scriptSessionId"] = dwr.engine._origScriptSessionId;
    params["enlargedType"] = application.featurePrefix;
    params["sortOrder"] = getRadioValue($("search_form").sort);
    params["emVersion"] = application.em_version;

    // AlbertW Oct 31, 08
    // EM-658 : as per John, legal search only happen on primary search. (i.e: primary keyword == secondary keyword )
    // else perform keyword search by default.
    if ( keywordQuery ==  DWRUtil.getValue("querybox") || keywordQuery.trim() == "") {
        params["kOrLegals"] = "l";
    }
    //EM-1535
    if(USER_PREF_MAP.get("em_version")==application.smallThumbEMVersion){
        $("ss_arrow").style.display="none";
    } else {
        $("ss_arrow").style.display="block";
    }
    stopWait();	// stop "feature image" message
	wait("Fetching SimSearch results...");

    debug("[PROFILER] [SimSearchAjax] Sending Fetch Request");
    SimSearchAjax.execute(params, {
			callback:processSimReadReqChangeWrapper.curryAlt(new Date())
		});
}



function processSimReadReqChangeWrapper(startDate,rawResponse){
    var d2 = new Date();
    debug("[PROFILER] [SimSearchAjax] The time difference between DWR request and DWR response was: "+(d2.getTime() - startDate.getTime())+"ms. Calling processSimReadReqChange.\nScript session id is: "+dwr.engine._origScriptSessionId);
    return processSimReadReqChange(rawResponse);
}

/* Receive the response for the XML document.
 */
function processSimReadReqChange(rawResponse) {
//	debug("[SIMSEARCH] Response received, processing data.");

	stopWait();
//	SimSearchAjax.inProgress = false;

	var imgcode = $("feature_image").getAttribute("imgcode");
	if (imgcode != rawResponse.imgcode) {
		if (!imgcode || imgcode.length == 0) {
			debug("[SIMSEARCH] Feature image is turned off.  Re-positioning.");
            $("feature_ss_action_bar").style.left =  "0px";
            $("feature_ss_action_message").style.left =  "0px";

            $("simsearch").style.left =  parseInt($("feature_ss_action_bar").style.width) +  "px";
			$("ss_action_bar").style.left =  "0px";
			$("look_ahead").style.left = "297px";
		} else {
			debug("[SIMSEARCH] Sim response source image does not match feature image. Abandoning SimSearch display.");
			rawResponse = null;
			return;
		}
	}

	Console.time("SimSearch/LookAhead Fetch: Response Processing");

	// Initial post-processing.
	var resultObject = new Array();
	var resultJSON = rawResponse.data;

	resultObject = resultJSON.response.images;
    if(resultJSON.response.lbInfo){ //load lightbox info if available
        LB_INFO_MAP.update(new MfHashtable(resultJSON.response.lbInfo));
    }
    if(resultJSON.response.scInfo){ //load shopping cart info if available
        SC_INFO_MAP.update(new MfHashtable(resultJSON.response.scInfo));
    }

    if ( resultJSON.response["license"] == "RF" ) {
        numResults = resultJSON.response["rf-hit-count"];
    } else if (resultJSON.response["license"] == "RM") {
        numResults = resultJSON.response["rm-hit-count"];
    } else if (resultJSON.response["license"] == "SX") {
        numResults = resultJSON.response["sx-hit-count"];
    } else if (resultJSON.response["license"] == "MS") {
        numResults = resultJSON.response["cs-hit-count"];
    } else {
        numResults = resultJSON.response["hit-count"];
    }

    if (numResults > 300) {
		numResults = 300;
    }

    var target;
    if (rawResponse.stream == "look_ahead") {
	    target = $("look_ahead");
    } else {
	    target = $("simsearch");
    }

    var type = parseInt(rawResponse.ssType);

/*
    simsearch_message_1={0} images of &quot;{1}&quot; similar to this enlargement
"NUMBER" images of " SEARCH TERM " similar to this enlargement

    simsearch_message_2=Searching within similars: {0} images of &quot;{1}&quot; similar to this enlargement
Searching within similars: "NUMBER" images of " SEARCH TERM " similar to this one

    simsearch_message_3=Auto-Pairing ON: {0} images of &quot;{2}&quot; similar to this enlargement of &quot;{1}&quot;
Auto -Pairing ON : "NUMBER" images of " AUTO-PAIRING SEARCH TERM " similar to this enlargement of "SEARCH TERM"

    simsearch_message_4=Searching withing Auto-pairing results: {0} images of &quot;{1}&quot; similar to this one
Searching within Auto-Pairing results "NUMBER" images of " AUTO PAIRING SEARCH TERM " similar to this one

  */

    if (type > 0) {
        if (type >= 3)
            $("sstab").innerHTML = i18nX(i18n["simsearch_message_" + type], numResults, resultJSON.response.keyword, Url.decode($("bigThumbKeyword").value) );
        else
            $("sstab").innerHTML = i18nX(i18n["simsearch_message_" + type], numResults, resultJSON.response.keyword );
    }


    var rawSearchString = resultJSON.response["rawSearchString"];
    if ( $("ssRawSearchString") ) {
        DWRUtil.setValue("ssRawSearchString", rawSearchString );
    }

    var keywordQuery = resultJSON.response["keyword"];
    if ( $("ssKeyword") ) {
        DWRUtil.setValue("ssKeyword", keywordQuery );
    }
    if ( $("auto_pair_keyword") ) {
        DWRUtil.setValue("auto_pair_keyword", keywordQuery );
    }

    if (numResults <= 1) {
		debug("[SIMSEARCH] No results.");
        $("feature_ss_action_bar").style.display = "none";
        DWRUtil.setValue("ss_no_results", i18n.em_ss_no_image_found);
        $("feature_ss_action_message").style.display = "block";

        if (rawResponse.stream == "look_ahead") {
			$("look_ahead_headsup").style.display = "none";
        }

        $("ss_action_bar").style.display = "block";
        if ( $("simsearch_wrapper") ) {
            $("simsearch_wrapper").style.display="block";
        }
        $("feature_ss_action_bar").style.display = "none";
        
        $("numSimsResults").innerHTML = "0";
        
        $("simsearch").style.display = "none";
        return;
	}

    // Remove old SimSearch/LookAhead results, but only if it's a fresh request.
    var numResultsInResponse = resultObject.length;
    if ( numResultsInResponse > 0 && resultObject[0].result_position == 0) {
	    while (target.firstChild) {
		    if (target.firstChild.id == "look_ahead_headsup"){
			    var la_headsup = target.removeChild(target.firstChild);
            } else {
                //clean the sim search thumb
                var tmp = target.removeChild(target.firstChild);
                if (tmp) {
                    if (tmp.id) { //make sure this is anything
                        SSTHUMBQ.push(tmp);
                        tmp.id = null;
                    }
                }
            }
        }
	}
	// Put back the LookAhead notification.
	if (la_headsup) {
	    la_headsup.style.display = "block";
		target.appendChild(la_headsup);
		target.style.display = "block";
    }

    $("feature_ss_action_bar").style.display = "block";
    $("feature_ss_action_message").style.display = "none";
    $("numSimsResults").innerHTML = numResults;         // being used in ss_throtle.js ss_pageRight()

    if ( resultJSON.response['license'] == "SX" ) {
        resultObject.canSxDownload = "SX";          // even if you are in SX tab, show indicator (js work)
    }

    addNewImages(resultObject, rawResponse.stream);
	closePopup("ss_popup");
	//closePopup("la_popup");

    $("simsearch").style.display = "block";
    $("ss_action_bar").style.display = "block";
    if ( $("simsearch_wrapper") ) {
        $("simsearch_wrapper").style.display="block";
    }
    $("feature_ss_action_bar").style.display = "block";
    $("feature_ss_action_message").style.display = "none";

}

function preloader() {
	// counter
	var i = 0;

	// create object
	imageObj = new Image();

	// set image list
	// these are to load the icons for the lightbox and cart
	pl = new Array();
	pl[0]="/images/ei/lightbox_on.gif";
	pl[1]="/images/ei/cart_on.gif"
	var items = pl.length;

	// start preloading
	for (i=0; i < items; i++)
	{
		imageObj.src=pl[i];
	}
}
