var moveResultsOverA;
var moveResultsOverB;
var moveSimsOver;
var movePopupOver;
var featureOpen;
var	openToolbarContent;
var oldWW;
var SIMSEARCH_TYPE_K2 = 1;
var SIMSEARCH_TYPE_EM = 2;
var ABSIM = 0; //the prefereed simsearch type 1 (broad/k2) 2 (narrow/em) - 0 default errorCode

var ajax_managedPlans;

/* Initialize all effects and events which are application-specific.  This can be stay
 * active across multiple searches.
 */
function initSearchMain() {
	oldWW = ww();
    if (application.debug) {
		createDebugConsole();
	}

	Console.time("EM Application Initialization");

	initHashHistory();

	// Override the GET values with any relevant values after the hash.
	// This allows for bookmarking after Ajax Search.
    var loc = ""+top.location;
    var idx = loc.indexOf("#");
    if ( idx > 0 ) {
        var left = loc.substr(0,idx);
        if (left.length > 0) {
		    debug("[SearchOverride] URL has detected, checking values...");

            if (newQuery = left.getQueryValue("query")) {
			    debug("[SearchOverride] Overwriting query with " + newQuery);
                $("rawQuery").value = Url.decode(newQuery).replace(/\+/g,' '); 

                $("querybox").value = Url.decode(newQuery).replace(/\+/g,' ');
            }

	    	var search_form = $("search_form");

    		if (newLicType = left.getQueryValue("licType")) {
	    		setRadioValue(search_form.licType, newLicType)
            }

            if (newSort = left.getQueryValue("sort")) {
    			setRadioValue(search_form.sort, newSort)
            }
        }
        var right = loc.substr(idx);
        if (right.length > 0) {
            if (newPos = right.getQueryValue("sp")) {
                var sp = document.createElement("input");
                sp.setAttribute("type", "hidden");
                sp.id = "startPosition";
                sp.value = newPos;
                document.body.appendChild(sp);
            }
        }
    } else {
        var query = loc.getQueryValue("query");
        if (query) {
            $("rawQuery").value = Url.decode(query).replace(/\+/g,' ');            
        }
    }

    // Reset all application variables.
	resetMain();

	if (window.initImageFormatCheckboxes) {
		initImageFormatCheckboxes();
	}

    var searchParams = {};

    var startPosition = $("startPosition");
    if (startPosition) searchParams.sp = startPosition.value;


    searchParams.query = DWRUtil.getValue("rawQuery"); 


    var licType = loc.getQueryValue("licType");
    if (licType) searchParams.licType = licType;

    var sort = loc.getQueryValue("sort");
    if (sort) searchParams.sort = sort;

    if (searchParams) {
        createNewSearch(searchParams);
    }

    if (application.gta) {
		gtaInit();
    }

    if ($("totalNumResults").value == "0") {
		debug("[INIT] No results.")

		var params = {};
		params["messageId"] = "NO_RESULTS";
		params["query"] = DWRUtil.getValue("rawQuery");

		KeyBasedPassthrough.execute(params, function(response){
			document.getElementById("noresults").innerHTML = response.data;
			noResultsOn();
		});
	}

	initFX();

	setThrottle();
	setSimsSearchThrottle();

    DISPATCHER.fire("START_SLIDER");
    //runSlider();

	var theResults = getElementsByClassName("result_image");
	numResults = theResults.length;
	for (i=0; i < numResults; i++) {
		theResults[i].onclick = function() {
			fetchFeatureImage(this);
			return false;
		}
		if (areWeInLightbox()) {
			//theResults[i].onmouseover = lbThumbnailPopup;
		} else {
			theResults[i].onmouseover = delayedThumbnailPopup;
        }
	}
	//$("popup").onclick = popupClick;

    //disabled onclick
    $("popup").onclick = function() {
        return false;
    }
    //disabled drag
    $("popup").onmousedown  = function(event){
        if(event && event.preventDefault) {
        event.preventDefault();
        }
    }
    //use mouseup instead on onclick
    $("popup").onmouseup = popupClick;
    //need to detect if user left search area with mouse
    if($("result_counts")){
        $("result_counts").onmouseover = function(){
            DISPATCHER.fire("CANCEL_NEXT_THUMBNAIL_POPUP");
        };
    }
    if($("feature_inner")){
        $("feature_inner").onmouseover = function(){
            DISPATCHER.fire("CANCEL_NEXT_THUMBNAIL_POPUP");
            DISPATCHER.fire("CLOSE_SEARCH_POPUP");
        };
    }
    document.onmouseover = function(e){
        if (!e) var e = window.event;
        var x;
        var y;
        if(e.pageX){
            x = e.pageX;
        } else if(e.clientX){
            x = e.clientX + (document.documentElement.scrollLeft ? document.documentElement.scrollLeft : document.body.scrollLeft);
        }
        if(e.pageY){
            y = e.pageY;
        } else if(e.clientY){
            y = e.clientY + (document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop);
        }

        //debug("[EVENT] mouse document event "+x+" "+y);
        var p = new MfPoint(x,y);
        if(POPUP_BOX){
            if( POPUP_BOX.contains(p) == false){
                //mouse movement outside of popup yet popup exists
                debug("[EVENT] " +POPUP_BOX+" does not contain "+p);
                DISPATCHER.fire("CLOSE_SEARCH_POPUP");
            }
        }
        if(SIM_POPUP_BOX){
            if( SIM_POPUP_BOX.contains(p) == false){
                //mouse movement outside of simpopup yet popup exists
                debug("[EVENT] " +SIM_POPUP_BOX+" does not contain "+p);
                DISPATCHER.fire("CLOSE_SIMSEARCH_POPUP");
            }
        }

		// This is an imaginary line at the bottom of the search_results div.  If the mouse cursor crosses that line,
		// we either enable Search Popups and disable SimSearch, or vice versa.  This is to prevent time-delayed popups
		// appearing when the mouse has left their parent region.  For more info please see EM-736.
		var imaginaryLineBetweenSearchAndSimSearch = application.headerHeight + application.squareSize * application.colSize + 14;
		var imaginaryLineBelowSimSearch = imaginaryLineBetweenSearchAndSimSearch + application.squareSize + 32;

		if (y < application.headerHeight) {							// Mouse pointer is above search results.
			application.preventSearchPopup = true;
			application.preventSimSearchPopup = true;
		} else if (y <= imaginaryLineBetweenSearchAndSimSearch) {	// Mouse pointer is above SimSearch.
			application.preventSearchPopup = false;
			application.preventSimSearchPopup = true;
		} else if (y <= imaginaryLineBelowSimSearch) { 				// Mouse pointer is above the bottom of SimSearch.
			application.preventSearchPopup = true;
			if (x <= application.minWidthFeature + application.simSquareSize) {	// Mouse pointer is over the feature box area.
				application.preventSimSearchPopup = true;
			} else {
				application.preventSimSearchPopup = false;
			}
		} else {													// Mouse pointer is below SimSearch.
			application.preventSearchPopup = true;
			application.preventSimSearchPopup = true;
		}
    };

    //$("popup").onmouseout = popupClear;

    $("header").onmouseover = closeAllPopups;
	$("feature_wrap").onmouseover = closeAllPopups;
	$("look_ahead").onmouseover = closeAllPopups;
	$("ss_action_bar").onmouseover = closeAllPopups;

	if ($("ss_popup_clear")) {
		$("ss_popup_clear").onmouseover = closeAllPopups;
	}
	if ($("feature_ss_action_bar")) {
		$("feature_ss_action_bar").onmouseover = closeAllPopups;
	}
	$("simsearch_wrapper").onmouseover = function() { closePopup("popup"); }

	if ($("debug_wrapper")) {
		$("debug_wrapper").onmouseover = closeAllPopups;
	}
	if ( $("footer") ) {
        $("footer").onmouseover = closeAllPopups;
    }
	$("search_results_wrapper").onmouseover = function() {
		closePopup("la_popup");
		closePopup("ss_popup");
	}

    //disabled onclick
    $("ss_popup").onclick = function() {return false;}
    //disabled drag
    $("ss_popup").onmousedown  = function(event){
        if(event && event.preventDefault) {
        event.preventDefault();
        }
    }
    //use mouseup instead on onclick
    $("ss_popup").onmouseup = popupClick;
    //$("ss_popup").onmouseout = popupClear;

    $("la_popup").onclick = popupClick;
	//$("la_popup").onmouseout = popupClear;

	$("tb_keytags_wrap").onclick = function() {

	    closeAllPanels(openToolbarContent);

		var root = this.id.slice(3);
		if (openToolbarContent.isOpen) {
			if ($("info_" + root).style.display == "block") {		 // clicking on the current button to close				
				openToolbarContent.isOpen = false;
				openToolbarContent.start(0);
			} else {
				closeInfoDivs();
				$("info_" + root).style.display = "block";			// clicking on another button to switch panels
			}
		} else {
			$("info_" + root).style.display = "block";
			openToolbarContent.isOpen = true;
			openToolbarContent.start(213);
		}
		return false;
	}

    /*************************************************************************/
	/** SimSearch auto-pairing.												**/

	$("auto_pair_form").onsubmit = function() {

        var kw = Url.encode( $("auto_pair_keyword").value );
        $("refine_search").value = $("auto_pair_keyword").value; //EM-1591 store it in refine_search so that it stays preserved for other enlargements 

        if ( ! kw ) {
            var keywordDivId = "bigThumbKeyword";
            if ( $(keywordDivId) ) {
                kw = Url.encode( $(keywordDivId).value );
            }

            if ( ! kw ) {
                kw = Url.encode( $("querybox").value );
            }
        }

        if (kw) {
            fetchSimSearchResults({image: $("feature_imgcode").value, keyword: kw, type: 1, offset: 1, streamThis: "yes", streamSource: "R", license: $("feature_license").value });
        }

        return false;
	}

    if($("zoom_toggle")){
	    $("zoom_toggle").onclick = function() {
            var params ={};
			params[ "actionName"] = "Zoomify";
            params[ "_cmd_streamThis"] = "y";
			params[ "_attr_em"] = "y";
			params[ "_attr_img"] = $("feature_imgcode").value;

			var zoom = $("feature_zoom");

			if (zoom.style.display == "block") {

				zoom.style.display = "none";
				$("feature_image").style.visibility = "visible";
				resetHistoryButtons();
				params[ "_attr_zoomCmd"] = "close";

			} else {

				zoom.style.display = "block";
				$("feature_image").style.visibility = "hidden";
                if ( $("feature_previous") ) {
                    $("feature_previous").style.display = "none";
                }
                if ( $("feature_next") )  {
                    $("feature_next").style.display = "none";
                }

				//streamerContextAttributes["_msg_"] = "open zoom " + $("feature_imgcode").value + " "+$("user_id").value;
				params[ "_attr_zoomCmd"] = "open";
			}

			StreamParameters.execute( params);
			return false;
		}
    }

    /* EM-1153 : IE7 runtime error when user goes to lightbox details page from my dowload page
    if (featureAutoOpen = $("featureOpen")) {
		debug("FeatureAutoOpen request detected (" + featureAutoOpen.value + "), looking for match in result set...");
		results = getElementsByClassName("result_image");
		nr = results.length;

		for (i=0; i < nr; i++) {
			if (results[i].getQueryValue("image") == featureAutoOpen.value) {
				debug("FeatureAutoOpen match found.");
				fetchFeatureImage(results[i]);
				break;
			}
		}
	}
	*/

    if ($("user_history")) {
        $("user_history").onclick = function() {
            viewUserHistory();
            return false;
        }
    }

    if ($("user_prefs")) {
        $("user_prefs").onclick = function() {
            setupUserPref ();
            panel_slide_out("user_prefs_form", 260);
            return false;
        }
    }

    if ($("options_off")) {
        $("options_off").onclick = function() {

            DWRUtil.setValue("show_search_panel", "0" );

            userPref = getUserPrefStatus();
            changedCount = 0;
            for (var i = 0; i < userPref.length; i++) {
                if ( $( "pref_" + userPref[i]['id']) ) {
                    if ( userPref[i]['isChange'] ) {
                        $( "pref_" + userPref[i]['id'] ).style.backgroundColor = "#ffc";
                        changedCount++;
                    } else {
                        $( "pref_" + userPref[i]['id'] ).style.backgroundColor =  $("user_prefs_form").style.backgroundColor;
                    }
                }
            }
            if ( changedCount > 0 ) {
                $( "pref_user_msg").style.display = "block";
            } else {
                $( "pref_user_msg").style.display = "none";
            }

            panel_slide_out ("user_prefs_form",260);

            return false;
        }
    }

    if ($("show_display_settings")) {
        $("show_display_settings").onclick = function() {
            if ( $("user_prefs_form").style.display != "block" ) {
                setupUserPref ();
                    EffectHighlight ( "pref_em_version" );
                panel_slide_out ("user_prefs_form",260);
            } else {
                if ( $( "pref_em_version" ) ) {
                    EffectHighlight ( "pref_em_version" );
                }
            }
            return false;
        }
    }

   if ($("thumb_pref_grid_sm")) {
        $("thumb_pref_grid_sm").onclick = function() {
            dwr.util.setValue("em_version", "2" );           
            return false;
        }
    }

   if ($("thumb_pref_grid_lg")) {
        $("thumb_pref_grid_lg").onclick = function() {
            dwr.util.setValue("em_version", "1" );
            return false;
        }
    }

   if ($("thumb_pref_far")) {
        $("thumb_pref_far").onclick = function() {
            dwr.util.setValue("em_version", "3" );
            return false;
        }
    }

    // feature options
    if ($("feature_options_toggle")) {
        $("feature_options_toggle").onclick = function() {

            if ( $("feature_options").style.display == "block" ) {
                panel_slide_in ( "feature_options" );
            } else {
                panel_slide_out ("feature_options",80);
            }

            return false;
        }
    }

	// auto pair help
    if ($("auto_pair_help_toggle")) {
        $("auto_pair_help_toggle").onclick = function() {

            if ( $("auto_pair_help").style.display == "block" ) {
                panel_slide_in ( "auto_pair_help" );
            } else {
                panel_slide_out ("auto_pair_help",115);
            }

            return false;
        }
    }
    
	// copyright message
    if ($("copyright_msg_toggle")) {
       $("copyright_msg_toggle").onclick = function() {
	
           if ( $("copyright_msg").style.display == "block" ) {
               panel_slide_in ( "copyright_msg" );
          } else {
               panel_slide_out ("copyright_msg",190);
           }

          return false;
      }
    }


    if ($("total-hit-count-link")) {
        $("total-hit-count-link").onclick = function() {
		    createNewSearch({licType:"ALL"});
		    return false;
	    }
    }
    if ($("sx-overtab-si")) {
        $("sx-overtab-si").onclick = function() {
		    createNewSearch({licType:"ALL"});
		    return false;
	    }
    }
    if ($("rm-hit-count-link")) {
        $("rm-hit-count-link").onclick = function() {
		    createNewSearch({licType:"RM"});
		    return false;
	    }
    }
    if ($("rf-hit-count-link")) {
        $("rf-hit-count-link").onclick = function() {
		    createNewSearch({licType:"RF"});
		    return false;
	    }
    }
    if ($("sx-hit-count-link")) {
        $("sx-hit-count-link").onclick = function() {
		    createNewSearch({licType:"SX"});
		    return false;
	    }
    }

    if ($("sx-overtab-su")) {
        $("sx-overtab-su").onclick = function() {
		    createNewSearch({licType:"SX"});
		    return false;
	    }
    }

    if (areWeInRegularSearch()) {
        var catArtLinks = getElementsByClassName("ca_link");
	    var nLinks = catArtLinks.length;

        for (i=0; i < nLinks; i++) {
    		catArtLinks[i].onclick = createNewSearchFromLink;
    	}
    }

	window.setTimeout("pollHistoryHash()", 600);

	if ($("feature_next")) {
		$("feature_next").onclick = function() {

		    closeAllPanels();

            var next = getNewerHistory();
			if (next) {
				fetchFeatureAndSims(next,{"doNotAddToHistory":true});
			}
			resetHistoryButtons();
			return false;
		}
	}

	if ($("feature_previous")) {
		$("feature_previous").onclick = function() {

		    closeAllPanels();
		    
            var prev = getOlderHistory();
			if (prev) {
				fetchFeatureAndSims(prev,{"doNotAddToHistory":true});
			}
			resetHistoryButtons();
			return false;
		}
	}

    if ( $("tipBar") ) {
        EffectHighlight ( "tipBar" );
    }

    //obtain preferred simsearch type
    GetSimsearchType.execute( {}, function(response) {
        ABSIM = parseInt(response.abSim);
	});

    debug("Client-side application initialized.");

    Console.timeEnd("EM Application Initialization");
}

function viewUserHistory() {
    //addTodayHistory(); not sure if this is useful at all
    if ( $("user_history_form").style.display == "block" ) {
        //closing panel here
        panel_slide_in ( "user_history_form" );
    } else {
        //here we want to open the panel
        var params = {};
         params['div_header'] = "last_searches_history_header";
         params['div_list'] = "last_searches_history_list";

        params['oncomplete'] = "panel_slide_out ('user_history_form',360);";
        DISPATCHER.fire("GET_USER_SEARCH_HISTORY", params);
    }
    return false;
}

/*
 * Subscriptions - SX
 */

function viewSxDownload(imageCode, aig) {

	$("assetInstName").value = imageCode;
	$("aig").value = aig;
	$("error_msg").innerHTML = "";

	closeAllPanels(openSxDownloadContent);

	if (openSxDownloadContent.isOpen) {
		closeSxDownload();

	}else{


		var params = {
				'assetInstName': $("assetInstName").value,
				'assetInstGroup': aig
		};

		FindSubscriberPlansAjax.execute(params, function(response){

			var error = false;
			var st, st2;
			st = st2 = '';

			if (!response.error) {

				ajax_managedPlans = response.responseJSON.plans;
				var allowedResolutions = response.allowedResolutions;

				if (ajax_managedPlans.length === 0){

					if (response.responseJSON.userHasValidPlans){
						st = "<div class='sxErrorMsg'>" + i18n.sx_image_not_supported + "</div>";
					}else{
						st = "<div class='sxErrorMsg'>" + i18nX(i18n.sx_no_subscriber_plans, i18n.contactPhone, 'javascript:sxAddToCart("' + $("assetInstName").value + '");') + "</div>";
					}

					error = true;

				}else{

					var totalQuota = 0;
					var warnings = response.responseJSON.warnings;
					var needToConfirmTandC = response.responseJSON.needToConfirmTandC;
					if(needToConfirmTandC == true){
						showModalInfomercial("CONFIRM_DOWNLOADTC",true,true);
						application.callAfterConfirmDownloadTC = 'viewSxDownload("'+imageCode+'",'+aig+');';
						return false; //exit right here
					}

					st = '<div class="sxCol1 sxHeader"><strong>' + i18n.sx_myaccount_mysxplans + '</strong></div>' +
						'<div class="sxCol2 sxHeader">' + i18n.sx_download_by + '</div>' +
						'<div class="sxCol3 sxHeader">' + i18n.sx_downloads_available + '</div>';

					for (var i = 0; i < ajax_managedPlans.length; i++) {
						var plan = ajax_managedPlans[i];

						totalQuota += plan.planQuota;

						if (plan.isExpired){
							var expiredPlans = true

							st += '<div class="sxCol1">' + plan.name + '</div>' + '<div class="sxCol2">' +
							      '<span class="sxExpiredPlan">' + i18n.sx_expired + '</span>' + '</div>' +
							      '<div class="sxCol3"></div>';
						}

						for(var j=0; j < plan.terms.length; j++){
							term = plan.terms[j];

							if (j === 0){
								st += '<div class="sxCol1">' + plan.name + '</div>' + '<div class="sxCol2">' +
								plan.rolloverDate + '</div>';

							}else{
								st += '<div class="sxCol1">&nbsp;</div>' + '<div class="sxCol2">&nbsp;</div>'
							}

							st += '<div class="sxCol3">' + term.quota + ' ' + i18n['sx_res_' + highestResolution(term.resolutions) + '_s'];

							if (j === 0 && plan.cappedMaxDownloads > 0){
								st += '<sup>' + plan.cappedMaxDownloads + '</sup>';
							}

							st += '</div>';
						}
					}

					if (warnings.length > 0){
						st += '<div class="sxSeparator">&nbsp;</div>';

						for (var j=0, s=warnings.length; j < s; j++){
							st += '<div class="sx_warning"><sup>' + (j+1) + '</sup> ' + i18nX(i18n.sx_max_downloads, warnings[j]) + '</div>';
						}
					}

					if (totalQuota <= 0){
						error = true;

						if (expiredPlans){
							st2 = i18nX(i18n.sx_plan_expired, i18n.contactPhone, 'javascript:sxAddToCart("' + $("assetInstName").value + '");');

						}else{
							if (plan.valid_thru === plan.rolloverDate){
								st2 = i18nX(i18n.sx_no_quota_left, 'javascript:sxAddToCart("' + $("assetInstName").value + '");', i18n.contactPhone);

							}else{
								st2 = i18nX(i18n.sx_no_quota_left_for_now, 'javascript:sxAddToCart("' + $("assetInstName").value + '");', plan.name, plan.rolloverDate);
							}
						}
					}
				}

			}else{

				error = true;
				var errorMessage = (typeof i18n[response.error] !== "undefined") ? i18n[response.error] : i18nX(i18n.sx_download_error, i18n.contactPhone);
				st = "<div class='sxErrorMsg'>" + i18nX(errorMessage, i18n.contactPhone, 'javascript:sxAddToCart("' + $("assetInstName").value + '");') + "</div>";
			}

			$("inner_plans").innerHTML = st;
			$("inner_resolutions").innerHTML = '<p>' + st2 + '</p>';
			$("inner_plan_selection").innerHTML = '';
			$("inner_download_confirmation").innerHTML = '';

			$("info_sxDownload_wrap").style.display = "block";

			openSxDownloadContent.isOpen = true;
			openSxDownloadContent.start(360);

			if (!error){
				viewImageResolutions(allowedResolutions);
			}
		});
    }

    return false;
}

function closeSxDownload(){
	if ($("info_sxDownload_wrap").style.display == "block") {		 // clicking on the current button to close
		closeInfoDivs();
		openSxDownloadContent.isOpen = false;
		openSxDownloadContent.start(0);
	}else{
		closeInfoDivs();
		$("info_sxDownload_wrap").style.display = "block";			// clicking on another button to switch panels
	}
}

function highestResolution(resolution){
	var cmp = {
		's': 5,
		'a': 4,
		'b': 3,
		'c': 2,
		'd': 1
	}

	var highest = resolution[0];

	for (var i=1; i < resolution.length; i++){
		var res = resolution[i];
		if (cmp[res] > cmp[highest]){
			highest = res;
		}
	}
	
	return highest;
}

function viewImageResolutions(resolutions){

    var st = '<div class="sxCol1"><strong>' + i18n.sx_select_res + '</strong></div>' +
		'<div class="sxCol2">' + i18n.sx_dimensions + '</div>' +
		'<div class="sxCol3">' + i18n.sx_file_size + '</div>';

    for (var r in resolutions){
    	var res = resolutions[r];

		st += '<div class="sxCol1">' +
			'<input type="radio" name="res" id="res' + res.resolution + '" ' +
			'onclick="selectPlan(\'' + res.resolution + '\');" value="' + res.resolution + '" />' +
			'<label for="res' + res.resolution + '">' + i18n["resolutionLabel_" + res.resolution] + '</label>' +
			'</div>' +
			'<div class="sxCol2">' + res.width + 'x' + res.height + ' ' + i18n.pixels + '</div>' +
			'<div class="sxCol3">' + res.compress_size + ' MB</div>';
    }

    $("inner_resolutions").innerHTML = st;
}

function selectPlan(resolution) {

	var plans = [];
	var st = '';

	$("inner_download_confirmation").innerHTML = '';
	$("error_msg").style.display = "none"; // EM-1561

	for (var i=0; i < ajax_managedPlans.length; i++){
		var plan = ajax_managedPlans[i];

		for (var j=0; j < plan.terms.length; j++){
			var term = plan.terms[j];

			if (term.quota > 0){

				for (var k=0; k < term.resolutions.length; k++){
					var res = term.resolutions[k];

					if (res === resolution){
						plans.push({
							'id': plan.id,
							'name': plan.name,
							'refresh': plan.timeToRefreshDailyLimit, 
							'termId': term.id
						});
					}
				}
			}
		}
	}

	switch (plans.length){
	case 0:
		st = '<p>' + i18nX(i18n.sx_resolution_not_available, 'javascript:sxAddToCart("' + $("assetInstName").value + '");') + '</p>';
		break;

	case 1:
		var p = plans[0];
		sxConfirmDownload(p.id, escape(p.name), p.termId, p.refresh, resolution);
		break;

	default:
		st = '<div class="sxCol1 sxCol1full"><strong>' + i18n.sx_select_plan + '</strong></div>';
		for (var i=0; i < plans.length; i++){
			var p = plans[i];
			st += '<div class="sxFullRow">' +
				'<input type="radio" name="plan" id="plan' + p.id + '" ' +
				'onclick="sxConfirmDownload(' + p.id + ',\'' + escape(p.name) + '\',' + p.termId + ',' + p.refresh + ',\'' + resolution + '\');" />' +
				'<label for="plan' + p.id + '">' + p.name + '</label>' +
				'</div>';
		}
		break;
	}

    $("inner_plan_selection").innerHTML = st;
}

function sxAddToCart(imageCode){
	if (! SC_INFO_MAP.hasKey(imageCode)){
		iconAddToSC("bigThumbSCIcon", imageCode);
	}

	closeSxDownload();
}

function sxConfirmDownload(planId, planName, termId, refresh, res){
	$("error_msg").style.display = "none"; // EM-1561

	var st = '<p>' + i18nX(i18n.sx_image_will_be_downloaded, i18n["resolutionLabel_" + res], unescape(planName)) + '</p>' +
		'<button id ="sxDownload" class="" onclick="sxDownload(' + planId + ',\'' + planName + '\',' + termId + ',' + refresh + ',\'' + res + '\');">' + i18n.sx_download_image+ '</button>';

    $("inner_download_confirmation").innerHTML = st;
}

function sxDownload(planId, planName, termId, refresh, res) {

	$("sxDownload").disabled = true;
	
	var params = {
			'assetInstName':$("assetInstName").value,
			'aig':$("aig").value,
			'res':res,
			'plan':planId,
			'term':termId
	};

	SxTermDownloadAjax.execute(params, function(response){

		if (!response.error){

			sxDisableButtons();

			var st = '<p>' + i18nX(i18n.sx_image_was_downloaded, i18n["resolutionLabel_" + res], unescape(planName), response.downloadurl) + '</p>';

			$("inner_download_confirmation").innerHTML = st;

			if (BrowserDetect.browser !== "Explorer"){ //Workaround for EM-1487 
				window.location.href = response.downloadurl;
			}

			if (isDefined(response.debugMsg)){
				Console.log(response.debugMsg);
			}

		}else{

			if ("daily_hard_limit_or_term_limit_reached" === response.error){
				$("error_msg").innerHTML = i18nX(i18n.sx_no_daily_quota_left, refresh, 'javascript:sxAddToCart("' + $("assetInstName").value + '");', i18n.contactPhone);

			}else{
				sxDisableButtons();
				$("error_msg").innerHTML = i18nX(i18n.sx_download_error, i18n.contactPhone);
			}

			$("error_msg").style.display = "block";
		}
	});
}

function sxDisableButtons(){

	var radioRes = document.getElementsByName("res");
	for (var i=0; i < radioRes.length; i++){
		radioRes[i].disabled = true;
	}

	var radioPlan = document.getElementsByName("plan");
	for (var i=0; i < radioPlan.length; i++){
		radioPlan[i].disabled = true;
	}

 	$("sxDownload").disabled = true;
}

/* To be used as an event handler on links.  Extracts all relevant search data from the
 * link's href attribute, and creates a new search with it.
 */
function createNewSearchFromLink() {
	var searchParams = {};
	var query = Url.decode(this.href.getQueryValue("query").replace(/\+/g,' '));
    if (query) searchParams.query = query;

	var licType = this.href.getQueryValue("licType");
	if (licType) searchParams.licType = licType;

	var sort = this.href.getQueryValue("sort");
	if (sort) searchParams.sort = sort;

	if (searchParams)
		createNewSearch(searchParams);

	return false;
}

/* Creates a new Ajax search.
 */
function createNewSearch(overrides) {

    if (!overrides) overrides = new Object();

    if ( ELOCKS.get("UI_IS_BUSY") ) {
        var searchParams = {};

        if (overrides.licType) {
            searchParams.licType = overrides.licType;
        }
        if (overrides.query) {
            searchParams.query = overrides.query;
        }
        if (overrides.sp) {
            searchParams.sp = overrides.sp;
        }
        if (overrides.sort) {
            searchParams.sort = overrides.sort;
        }

        // EM-850 : save last action to be perfomed after all current ajax fetching has finished.
        // triggered @images.js : processReadReqChange
        debug ( "*********** QUEUE NEW_SEARCH ");
        EBUFFER.set("NEW_SEARCH",searchParams);
        return;
    }


    debug("[SEARCH] Performing new search.");
	application.searchReloadInProgress = true;
	setLastAction(application.events.NEW_SEARCH);

    closeFeatureImage();

    panel_slide_in('search_params', 300); // EM-562


	blurOn();

	if (overrides.licType) {
		debug("[SEARCH] Changing license type to " + overrides.licType);
		var licTypeInput = $("search_form").licType;

		if (getRadioValue(licTypeInput) != overrides.licType) {
			setRadioValue(licTypeInput, overrides.licType)
		}
	}

	var oldQuery = $("rawQuery").value;
	var newQuery = "";

    if (overrides.query) {

        debug("[SEARCH] Changing search query to " + overrides.query);

		newQuery = overrides.query;

		$("rawQuery").value = overrides.query;
		$("querybox").value = overrides.query;
	} else {
		newQuery = $("querybox").value;
		if((newQuery == null || newQuery == "") && lastSearchWasSimSearch()){
		    newQuery = getLastQuery();
		}
		$("rawQuery").value = newQuery;
	}


    DWRUtil.setValue("refine_search", "");

    /* EM-318, EM-188, EM-176, EM-440 and probably a few more:
	 * We have safeguards in slideTo() and fetchMoreResults() that prevent fetching results
	 * beyond the current result set's boundaries. However, if we're loading a new result
	 * set from an Ajax search, we won't know the new set's boundaries. To work around the
	 * safeguards for this exception, we will manually set the total results to double the
	 * screen size.
	 *
	 * EM-459:  We need to reset the boundaries on every new search.  There are too many
	 * variables to track otherwise.
	 */
	var li = getLeftIndex();
	var ri = getRightIndex(li);

	if (overrides.sp && overrides.sp > 0) {
		debug("[SEARCH] Resetting boundaries with position override, changing totalNumResults to " + (overrides.sp + 3 * (ri - li)));
		$("totalNumResults").value = overrides.sp + 3 * (ri - li);
	} else {
		debug("[SEARCH] Resetting boundaries, changing totalNumResults to " + (3 * (ri - li)));
		$("totalNumResults").value = 3 * (ri - li);
	}

	if (overrides.sort) {
		debug("[SEARCH] Changing sort to " + overrides.sort);
		setRadioValue($("search_form").sort, overrides.sort);
	}

	debug("[SEARCH] Query is now '" + $("rawQuery").value+"'");
	setLastQuery($("rawQuery").value);

	//$("totalNumResults").value = "-1"; disabled by PRQ - EM-318.

	resetMain();
	resetPages();

    if (areWeInRegularSearch()) {
	    SearchAjax.newSearch = true;
    }

    ELOCKS.set("UI_IS_BUSY");

	if (overrides.sp && overrides.sp > 0) {
		debug("[SEARCH] createNewSearch override: sliding to " + overrides.sp);
		slideTo(overrides.sp);
	} else {
	    resetVisibility({newSearch:true});
	}

	if (!overrides.doNotSaveSearchState)
		saveCurrentSearchState();

    var params = { };
    params["query"] = dwr.util.getValue("querybox");

//    PrepareSmarties.execute(params, function(response) {
//        if (response.error) {
//            dwr.util.setValue("debug", "Cannot use the codes: " + response.error);
//        } else {
//            dwr.util.setValue("smarties", response.smarties, { escapeHtml:false });
//        }
//    });
    return false;

}

/* Reset all variables specific to the current search.  This needs to be called every time
 * we start a new search.
 */
function resetMain() {
	stopThrottle();

	$("direction").value = "-1";
	$("clicked").value = "false";
	$("search_results_a_offset").value = "0";
	$("search_results_b_offset").value = "300";

	if (application.garbageCollection) {
		$("gcLeftIndex").value = "";
		$("gcRightIndex").value = "";
	}

	application.headerHeight = parseInt($("header").offsetHeight); // cacheing this because we use it frequently and it doesn't change

	debug("Resetting variables: licType is " + getRadioValue($("search_form").licType) + ", sort is " + getRadioValue($("search_form").sort));

	debug("Application variables reset.");
}

/* Empty both swap pages and reset to initial positions.
 */
function resetPages() {
	pageA = $("search_results_a");
	pageB = $("search_results_b");

	// Remove all old results.
	while (pageA.firstChild)
		pageA.removeChild(pageA.firstChild);
	while (pageB.firstChild)
		pageB.removeChild(pageB.firstChild);

	pageA.style.left = "0px";
	pageB.style.left = (parseInt($("resultsPerSheet").value) * application.squareSize) / application.colSize + "px";
}

/*
 * Saving image position for 'Quick Return'
 *
 */
function saveImagePosition() {
    var params = {};
    //var currentPage = getCurrentPage();

    var topLeftIndex = getLeftIndex();

    params["startPosition"] = topLeftIndex + 1;

    if ( parseInt( $("feature_wrap").style.width ) > 0 ) {

        var feature_image = $("feature_image");
        //EM-681: commented out because it changes the the startPosition
        //topLeftIndex = parseInt($(currentPage.id + "_offset").value) + application.colSize * Math.floor(Math.abs(parseInt(currentPage.style.left)-(parseInt($("feature_wrap").style.width))) / application.squareSize);
        params["startPosition"] = topLeftIndex + 1;

        params["feature"] = feature_image.getAttribute("alt");

        topSimLeftIndex = Math.floor(Math.abs(parseInt($("simsearch").style.left)-parseInt($("feature_wrap").style.width)-application.squareSize) / application.squareSize);
        params["ss_searchPosition"] = topSimLeftIndex + 1;
    }

	if (window.SetUserSearchHistory)
    	SetUserSearchHistory.execute(params);
}



function snapToGrid(lockObj, edge, width) {
    debug("in snap to grid with edge:"+edge+" width: "+width);
    theLeftA = parseInt($("search_results_a").style.left);
	theLeftB = parseInt($("search_results_b").style.left);

	if (edge == "right") {
        if(lockObj.get("WAS_SNAP_RIGHT")){
            return;//exit we already snapped to right
        }
        lockObj.set("WAS_SNAP_RIGHT");
        lockObj.unset("WAS_SNAP_LEFT");
        offs = ww() % application.squareSize;

		leftOffs = theLeftA % application.squareSize;
		if (offs != 0) {
			diff = application.squareSize - offs + 2;  // that last value is a calibration key -- may have to be adjusted depending on scrollbar width.  in other words, it may have to be browser (os?) sensitive at some point in the future.
			theLeftA -= diff;
			theLeftB -= diff;

			if ($("popup").style.display == "block") {
				var popup = $("popup");
				popup.style.left = parseInt(popup.style.left) - diff + "px";
			}

			moveResultsOverA.start(theLeftA);
			moveResultsOverB.start(theLeftB);

			setProgressBar();
		}
	} else {
        if(lockObj.get("WAS_SNAP_LEFT")){
            return;//exit we already snapped to left
        }
        lockObj.set("WAS_SNAP_LEFT");
        lockObj.unset("WAS_SNAP_RIGHT");
        offs = theLeftA % application.squareSize;
		if (offs != 0) {

			moveResultsOverA.start(Math.ceilThumb(theLeftA));
			moveResultsOverB.start(Math.ceilThumb(theLeftB));

			if ($("popup").style.display == "block") {
				$("popup").style.left = "0px";
			}

			setProgressBar();
		}
	}
}

// remove all children of an element
function removeChildSafe(element) {
    if ( element ) {
        while (element.firstChild) {
            removeSafe (element.firstChild);
        }        
    }
}

// remove all children of an element and itself
//before deleting el, recursively delete all of its children then itself
function removeSafe(element) {
    if ( element ) {
        while(element.childNodes.length > 0) {
            removeSafe(element.childNodes[element.childNodes.length-1]);
        }
        element.parentNode.removeChild(element);

        if ( element.id ) element.id = null;
        if ( element.nodeName ) {
            if ( element.nodeName == "A" ) {
                A_Q.push(element);
            } else if ( element.nodeName == "DIV" ) {
                DIV_Q.push(element);
            } else if ( element.nodeName == "SPAN" ) {
                SPAN_Q.push(element);
            } else if ( element.nodeName == "INPUT" ) {
                INPUT_Q.push(element);
            } else if ( element.nodeName == "IMG" ) {
                IMG_Q.push(element);
            }
        }
    }
}

/* This is where things get exciting.
 *
 * On hideImage, we grab the image's style string and destroy the element.  Then we re-create the element,
 * and add the style data (with a display: none).  The idea here:  upon element destruction, the image
 * should be removed from memory by regular JS garbage collection.  But when the element is re-created, the
 * image shouldn't be loaded back into memory until showImage() is called to turn the display on.
 *
 * Right?
 *
 * Right?
 *
 * I hope so.
 */
function hideImage(index) {

    if (!$("img_" + index))
		return false;

    removeSafe ( $("img_" + index) );

    return true;
}

function blurOn() {
	$("blur").style.visibility = "visible";
}

function blurOff() {
	$("blur").style.visibility = "hidden";
}

function isBlurOn() {
	return ($("blur").style.visibility == "visible");
}

function noResultsOn() {
	if (areWeInRegularSearch()) {
		if (nr = $("nr_browse"))
			nr.style.display = "block";

		$("noresults").style.visibility = "visible";
		$("indicator").style.visibility = "hidden";
		$("gti_toggle_wrapper").style.visibility = "hidden";
	}
}

function noResultsOff(partial) {
	if (areWeInRegularSearch()) {
		$("noresults").style.visibility = "hidden";

		if (!partial) {		// clean display for EM-786
			$("indicator").style.visibility = "visible";
			$("gti_toggle_wrapper").style.visibility = "visible";
		}

		if (nr = $("nr_browse"))
			nr.style.display = "none";
	}
}

function showImage(index, numResults) {
    if ($("img_" + index)) {
        ELOCKS.unset("UI_IS_BUSY");  // EM-1564
		return true;
	} else  {

        if (!numResults)
			numResults = application.defaultFetchSize;

        debug("[showImage] No image at position " + index + ", grabbing " + numResults + " more");

		if ($("gtaFetch").value == "true") {
			debug("GTA slide requires a fetch. Turning blur image ON.");
			blurOn();
		}
		fetchResultsBlock(index, numResults);
	}
	return false;
}

function getCurrentPage() {
	aLeft = parseInt($("search_results_a").style.left);
	bLeft = parseInt($("search_results_b").style.left);

	product = aLeft * bLeft;

	if (product < 0) {				// signs are different
		if (aLeft < 0)
			currentPage = $("search_results_a");
		else
			currentPage = $("search_results_b");
	} else if (product > 0) {		// signs are the same
		if (Math.abs(aLeft) < Math.abs(bLeft))
			currentPage = $("search_results_a");
		else
			currentPage = $("search_results_b");
	} else {						// one of them is 0, use that one
		if (aLeft == 0)
			currentPage = $("search_results_a");
		else
			currentPage = $("search_results_b");
	}
	return currentPage;
}

function getOffScreenFactor() {
	 // the number of results' distance off the screen at which we perform the display toggle
	 return application.bufferSize * Math.round(ww() / application.squareSize * application.colSize);
}

function getLeftIndex() {
	var currentPage = getCurrentPage();
	return parseInt($(currentPage.id + "_offset").value) + application.colSize * Math.ceil(Math.abs(parseInt(currentPage.style.left)) / application.squareSize);
}

function getRightIndex(leftIndex) {
	return leftIndex + (Math.floor(ww() / application.squareSize) * application.colSize) - 1;
}

function resetVisibility(options) {
	windowWidth = ww();

	if (!options)
		options = new Object();

	updateHashSearchPosition();

	var ss = application.squareSize;
	var cs = application.colSize;

	var dxn = parseInt($("direction").value);
	var currentPage = getCurrentPage();
	var totalResults = parseInt($("totalNumResults").value);

	offScreenFactor = getOffScreenFactor();
	leftIndex = getLeftIndex();
	rightIndex = getRightIndex(leftIndex);

	leftIndex -= offScreenFactor;
	rightIndex += offScreenFactor;

	if (leftIndex < 0)
		leftIndex = 0;

	// We limit the reset call to the known result set boundaries,
	// but only if we know them.
	if (totalResults >= 0)
		if (rightIndex >= totalResults )
			rightIndex = totalResults - 1;	/* This is a necessary off-by-one.  The last image in the result set
			 								 * will be img_x, where x = totalResults - 1.  This is because we start
											 * counting images from 0.  We're fun like that.
											 */

	debug("ResetVisibility:  showing between " + leftIndex + " and " + (rightIndex + cs));

	if ($("gtaFetch").value == "true")
		$("gtaLeftIndex").value = leftIndex + (3 * offScreenFactor);

	if (dxn == -1) {	// images coming in right, exiting left
		for (i = leftIndex; i <= rightIndex && showImage(i, rightIndex - i + (application.colSize+1)); i++)
			;

		if (options.complete)
			if (!isBlurOn())
				garbageCollect();
		else
			for (i = leftIndex - 1; $("img_" + i); i--)
				hideImage(i);
	} else {							// images coming in left, exiting right
		for (i = rightIndex; i >= 0 && showImage(i, i - leftIndex + 1); i--)
			;
		if (options.complete)
			if (!isBlurOn())
				garbageCollect();
		else
			for (i = rightIndex + (application.colSize+1); $("img_" + i); i++)
				hideImage(i);
	}
}

function garbageCollect() {
	if (application.gcDebug) {
		var total = $("search_results_a").getElementsByTagName("a").length + $("search_results_b").getElementsByTagName("a").length;
		debug("[GC] Beginning garbage collection with " + total + " images");
	}

	Console.time("Garbage Collection");

	var ss = application.squareSize;
	var cs = application.colSize;

	var dxn = parseInt($("direction").value);
	var numTotal = parseInt($("totalNumResults").value);

	var currentPage = getCurrentPage();

	var offScreenFactor = getOffScreenFactor();
	var leftIndex = getLeftIndex();
	var rightIndex = getRightIndex(leftIndex);

	leftIndex -= offScreenFactor;
	rightIndex += offScreenFactor;

	var gcLeftIndex = parseInt($("gcLeftIndex").value);
	var gcRightIndex = parseInt($("gcRightIndex").value);

	debug("Garbage collection, full ranges: 0 to " + (leftIndex - 1) + ", " + (rightIndex + (application.colSize+1)) + " to " + numTotal);
	repStr = "Garbage collection [" + dxn + "]: Actual start was ";

	if (gcLeftIndex && gcRightIndex) {
		debug("Garbage collection, GTA limited ranges: " + gcLeftIndex + " to " + gcRightIndex);

		if (dxn == -1) {	// images coming in right, exiting left
			repStr += gcLeftIndex;
			for (i = gcLeftIndex; i < leftIndex && i <= gcRightIndex; i++)
				hideImage(i);
		} else {
			repStr += gcRightIndex;		// images coming in left, exiting right
			for (i = gcRightIndex; i > rightIndex + (application.colSize+1) && i >= gcLeftIndex; i--)
				hideImage(i);
		}
		$("gcLeftIndex").value = "";
		$("gcRightIndex").value = ""
	} else {
		if (dxn == -1) {	// images coming in right, exiting left
			repStr += leftIndex - 1;
			for (i = leftIndex - 1; hideImage(i); i--)
				;
		} else {
			repStr += rightIndex + (application.colSize+1);		// images coming in left, exiting right
			for (i = rightIndex + (application.colSize+1); hideImage(i); i++)
				;
		}
	}

	repStr += ", actual finish was " + i;
	debug(repStr);

	Console.timeEnd("Garbage Collection");

	if (application.gcDebug) {
		var total = $("search_results_a").getElementsByTagName("a").length + $("search_results_b").getElementsByTagName("a").length;
	}
}

function runSlider(loopStore,id) {
	if(!loopStore.exists(id)){ //are we active
        return false;
    }
    loopStore.remove(id);
    //debug("slider id:"+id+ " started!");
    if (application.gta)
		if ($("updateProgressBarNumbers").value == "true")
			updateProgressBarNumbers();

	if ($("traffic_light").value == "go") {
		if ($("feature_wrap").style.width != "0px") {
			featureOpen.set(0);
    		openToolbarContent.start(0);
	        openToolbarContent.isOpen = false;

	        openSxDownloadContent.start(0);
            openSxDownloadContent.isOpen = false;
	
			$("simsearch").style.display = "none";
			$("ss_action_bar").style.display = "none";
            if ( $("simsearch_wrapper") ) {
                $("simsearch_wrapper").style.display = "none";
            }
            $("look_ahead").style.display = "none";
			
			// 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);			
			}			
		}
				
		windowWidth = ww();
		
		thumbsPerScreen = Math.floor(windowWidth / application.squareSize);
		dxn = parseInt($("direction").value);
		
		currentPage = getCurrentPage();
		
		numResults = parseInt($("totalNumResults").value);
		
		leftIndex = getLeftIndex();
		rightIndex = getRightIndex(leftIndex);
				
		var stopping = false;
		
		if (dxn == 1 && leftIndex <= 0 && parseInt(currentPage.style.left) >= 0) {
			stopThrottle();
			stopping = true;
            //DISPATCHER.fire("SNAP_TO_GRID_LEFT");
		
			currentPage.style.left = "0px";	 // currentPage will be search_results_a
			$("search_results_b").style.left = currentPage.style.width;
			
			setProgressBar();
		} else if (dxn == -1 && rightIndex + 1 >= numResults) {
			
			var srcOffset = parseInt($(currentPage.id + "_offset").value);
			
			var ss = application.squareSize
			
			var finalStopPoint = -1 * (leftIndex - (2 * application.colSize) - srcOffset) * ss / application.colSize - (ss - windowWidth % ss);
			finalStopPoint -= application.squareSize;
			
			if (parseInt(currentPage.style.left) < finalStopPoint) {
				debug("Stopping throttle.  Left: " + leftIndex + ", Right: " + rightIndex);
				stopping = true;
				stopThrottle();
				setProgressBar();
			}
            //DISPATCHER.fire("SNAP_TO_GRID_RIGHT");			
		}
		
		if (!stopping) {
			// adjust the indices to move off the screen, so we can work this magic offscreen
			leftIndex = leftIndex - (thumbsPerScreen * 2);
			rightIndex = rightIndex + (thumbsPerScreen * 2);

            if (dxn == 1) {	// images coming in left, exiting right
				if (leftIndex < 0) leftIndex = 0;

                for (i = leftIndex+application.colSize; i >= leftIndex && showImage(i, i - leftIndex); i--)
			        ;

                for (i=rightIndex; i < rightIndex + application.colSize; i++) {
					if ($("img_" + i))
						hideImage(i);
				}
			} else {				// images coming in right, exiting left
				if (rightIndex >= numResults) rightIndex = numResults - 1;

                for (i=leftIndex; i < leftIndex + application.colSize; i++) {
					if ($("img_" + i))
						hideImage(i);
				}
                for (i = rightIndex - application.colSize; i <= rightIndex && showImage(i, rightIndex - i + (application.colSize+1)); i++)
			        ;
            }
			var distance = dxn * USER_PREF_MAP.get("scroll_speed");
			
			var search_results_a = $("search_results_a");
			var search_results_b = $("search_results_b");
			
			search_results_a.style.left = parseInt(search_results_a.style.left) + distance + "px";
			search_results_b.style.left = parseInt(search_results_b.style.left) + distance + "px";
			
			var popup = $("popup");
			if (popup.style.display == "block")
				popup.style.left = parseInt(popup.style.left) + distance + "px";
			
			var tt = $("thumbnail_tooltip");
			if (tt)
				tt.style.left = parseInt(tt.style.left) + distance + "px";
			
		}
		setProgressBar();
	} else if ($("pageLeftToggle").value == "false" && $("pageRightToggle").value == "false") {
	
		// Handling window resize on the fly.
		var currentWW = ww();
		
		if (oldWW != currentWW) {
			resetVisibility();
			oldWW = currentWW;
		}
	}

    var new_id = loopStore.getNew();

    window.setTimeout(curry(runSlider,window,loopStore,new_id), document.getElementById("speed").value);
}
