var sTypeFolder = null;


function unquoteXml (xmlStr) {
    var result = xmlStr;

    var reg = new RegExp('&lt;', 'g');
    result = result.replace(reg, "<");
    reg = new RegExp('&gt;', 'g');
    result = result.replace(reg, ">");
    reg = new RegExp('&quot;', 'g');
    result = result.replace(reg, "\"");
    reg = new RegExp('&apos;', 'g');
    result = result.replace(reg, "'");
    reg = new RegExp('&amp;', 'g');
    result = result.replace(reg, "&");

    return result;
}

function i18nX() {
    var translated = "";    
    for (var i=0; i<arguments.length; i++) {
        var value = arguments[i];
        if ( i == 0 ) {
            translated = arguments[0];
        } else {
            var reg = new RegExp('\\\{' + (i-1) + '\\\}', 'g');
            translated = translated.replace(reg, value);
        }
    }
    return translated; 
}

function ww() {
	if (document.body.clientWidth){
		return document.body.clientWidth;
    } else {
		return document.body.offsetWidth;
    }
}

/* Put this somewhere better.
 */
function getElementsByClassName(strClass, strTag, objContElm) {
  strTag = strTag || "*";
  objContElm = objContElm || document;    
  var objColl = objContElm.getElementsByTagName(strTag);
  if (!objColl.length &&  strTag == "*" &&  objContElm.all) objColl = objContElm.all;
  var arr = new Array();                              
  var delim = strClass.indexOf('|') != -1  ? '|' : ' ';   
  var arrClass = strClass.split(delim);    
  for (var i = 0, j = objColl.length; i < j; i++) {                         
    var arrObjClass = objColl[i].className.split(' ');   
    if (delim == ' ' && arrClass.length > arrObjClass.length) continue;
    var c = 0;
    comparisonLoop:
    for (var k = 0, l = arrObjClass.length; k < l; k++) {
      for (var m = 0, n = arrClass.length; m < n; m++) {
        if (arrClass[m] == arrObjClass[k]) c++;
        if ((delim == '|' && c == 1) || (delim == ' ' && c == arrClass.length)) {
          arr.push(objColl[i]); 
          break comparisonLoop;
        }
      }
    }
  }
  return arr; 
}

// To cover IE 5 Mac lack of the push method
if(! Array.prototype.push){
    Array.prototype.push = function(value) {this[this.length] = value; };
}

Array.prototype.has = function(value) {
    var i;
    for (var i = 0, loopCnt = this.length; i < loopCnt; i++) {
        if (this[i] === value) {
            return true;
        }
    }
    return false;
};

String.prototype.getQueryValue = function(name) {
	//return this.match(new RegExp("[&amp;|&|?]" + name + "\=([^&|^&amp;]*)", "i"))[1];
	//return this.match(new RegExp("[&amp;|&|?]" + name + "\=([a-zA-Z0-9/\-_]+)", "i"))[1];

	var result = this.match(new RegExp("[&amp;|&|?|#]" + name + "\=([^&]*)", "i"));
	
	if (result == null)
		return false;
		
	return result[1];
}

String.prototype.containImageCode = function () {
    var objRegExp = /^(simSearch:)?\d+\-\d+$/;
    return objRegExp.test( this );    
}

Math.floorThumb = function(num) {
	return application.squareSize * Math.floor(num / application.squareSize);
}

Math.ceilThumb = function(num) {
	return application.squareSize * Math.ceil(num / application.squareSize);
}

Math.simfloorThumb = function(num) {
	return application.simSquareSize * Math.floor(num / application.simSquareSize);
}

Math.simceilThumb = function(num) {
	return application.simSquareSize * Math.ceil(num / application.simSquareSize);
}

// check min width for feature image panel.
Math.minThumbWidth = function(num) {
    var width = num;
    if ( width < application.minWidthFeature ) {
            width = application.minWidthFeature;
    }
    return width;
}

function sliderSettings(x) {
	if (document.body.offsetWidth)
		window_x = document.body.offsetWidth;
	else
		window_x = window.innerWidth;
	
	if (x <= window_x / 2) {
		document.getElementById("direction").value = "1";
		delta = x;
	} else {
		document.getElementById("direction").value = "-1";
		delta = window_x - x;
	}
	document.getElementById("coords").value = "Delta: " + delta;
	if (delta < 40) {	// fast!
//		document.getElementById("speed").value = "5";
//		document.getElementById("distance").value = "20";
		document.getElementById("traffic_light").value = "go";
	} else if (delta < 120) {
//		document.getElementById("speed").value = "20";
//		document.getElementById("distance").value = "10";
		document.getElementById("traffic_light").value = "go";
	} else if (delta < 250) {
//		document.getElementById("speed").value = "40";
//		document.getElementById("distance").value = "5";
		document.getElementById("traffic_light").value = "go";
	} else {
		document.getElementById("traffic_light").value = "stop";
	}
}


function historyAddDone(resObj) {
	if (resObj.success < 0) {
		alert("Something went wrong: " + resObj.error);
		return;
	}
	debug("[FEATURE] Feature image fetch complete.");
	
}

function textToXML(text) {
	if (window.ActiveXObject) {
		var xmldoc=new ActiveXObject("Microsoft.XMLDOM");
		xmldoc.async="false";
		xmldoc.loadXML(text);
	} else {
		var parser=new DOMParser();
		var xmldoc=parser.parseFromString(text,"text/xml");
	}
	return xmldoc;
}

function XMLtoObject(xmldoc) {
	resultObject = new Array();
	
	if (xmldoc.documentElement)
		rawResults = xmldoc.documentElement.getElementsByTagName("resultData");
	else
		rawResults = xmldoc.getElementsByTagName("resultData");
	
	
	for (i=0; i < rawResults.length; i++) {
		resultItem = new Object;

		for (i=0; i < rawResults[i].length; i++) {
			if (rawResults[i][i].nodeType == 1) // 1 == Node.ELEMENT_NODE, but the contant def. isn't supported in IE
				resultItem.resultData[rawResults[i][i].nodeName] = rawResults[i][i].firstChild.data;
		}

		resultObject.push(resultItem);
	}
	
	return resultObject;
}


function max(a, b) {
	if (a > b)
		return a;
	return b;
}

Date.prototype.oneMonthAgo = function() {
	if (this.getMonth() == 0)
		return new Date(this.getFullYear() - 1, 12, this.getDate(), this.getHours(), this.getMinutes(), this.getSeconds());
	else
		return new Date(this.getFullYear(), this.getMonth() - 1, this.getDate(), this.getHours(), this.getMinutes(), this.getSeconds());
};

Date.prototype.yesterday = function() {
	return new Date(this.getTime() - 86400000);
}

Date.prototype.isToday = function() {
	var today = new Date();
	return (today.getFullYear() == this.getFullYear() && today.getMonth() == this.getMonth() && today.getDate() == this.getDate());
}

Date.prototype.format = function() {
	var str = "";
	
	str += this.getFullYear() + "-";
    if ((this.getMonth()+1) < 10){
        str += "0";
    }
    str += (this.getMonth() + 1) + "-";
    if(this.getDate() < 10){
        str += "0";
    }
    str += this.getDate() + " ";
	str += this.getHours() + ":";
	str += this.getMinutes() + ":";
	str += this.getSeconds();
	
	//2008-04-22 22:13:12.787-0400
	
	return str;
}

function wait(msg) {
	var swn;
	if (swn = $("server_wait_notify")) {
		swn.innerHTML = "&nbsp;"; // msg;
		swn.style.display = "block";
	}
}

function stopWait() {
	var swn;
	if (swn = $("server_wait_notify")) {
		swn.innerHTML = "";
		swn.style.display = "none";
		
		swn.style.color = "#AAAAAA";
		swn.style.backgroundColor = "transparent";
	}
}

function highlightWait() {
	var swn;
	if (swn = $("server_wait_notify")) {
		swn.style.color = "#FFFFFF";
		swn.style.backgroundColor = "#FF0000";

		var highlight = new Fx.Styles('server_wait_notify', {duration:1000, transition: Fx.Transitions.linear});
			
		highlight.addEvent('onComplete', function() {
				$("server_wait_notify").style.backgroundColor = "transparent";
			});
		
		highlight.start({
				'color': 'AAAAAA',
				'backgroundColor': 'FFFFFF'
			});
	}
}

function addLoadEvent(func) {
	var oldonload = window.onload;
	if (typeof window.onload != 'function') {
		window.onload = func;
	} else {
		window.onload = function() {
			if (oldonload) {
				oldonload();
			}
			func();
		}
	}
}

function setCookie(name,value,days) {
    if (days) {
        var date = new Date();
        date.setTime(date.getTime()+(days*24*60*60*1000));
        var expires = "; expires="+date.toGMTString();
    }
    else var expires = "";
    document.cookie = name+"="+value+expires+"; path=/; domain=.masterfile.com";
}

function getCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1,c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
    }
    return null;
}

function delCookie(name) {
    setCookie(name,"",-1);
}

/*function setCookie(NameOfCookie, value, expiredays) {

    // Three variables are used to set the new cookie.
    // The name of the cookie, the value to be stored,
    // and finally the number of days until the cookie expires.
    // The first lines in the function convert
    // the number of days to a valid date.

    var ExpireDate = new Date ();
    ExpireDate.setTime(ExpireDate.getTime() + (expiredays * 24 * 3600 * 1000));

    // The next line stores the cookie, simply by assigning
    // the values to the "document.cookie" object.
    // Note the date is converted to Greenwich Mean time using
    // the "toGMTstring()" function.

    document.cookie = NameOfCookie + "=" + value + "; path=/ " +
    ((expiredays == null) ? "" : "; expires=" + ExpireDate.toGMTString()) + ";domain=.masterfile.com";    
}

function getCookie(NameOfCookie) {
    // First we check to see if there is a cookie stored.
    // Otherwise the length of document.cookie would be zero.
    if (document.cookie.length > 0)
    {
        // Second we check to see if the cookie's name is stored in the
        // "document.cookie" object for the page.

        // Since more than one cookie can be set on a
        // single page it is possible that our cookie
        // is not present, even though the "document.cookie" object
        // is not just an empty text.
        // If our cookie name is not present the value -1 is stored
        // in the variable called "begin".
        begin = document.cookie.lastIndexOf(NameOfCookie+"=");    //use lastIndexOf rather than indexOf
        if (begin != -1) // Note: != means "is not equal to"
        {
            // Our cookie was set.
            // The value stored in the cookie is returned from the function.

            begin += NameOfCookie.length+1;
            end = document.cookie.indexOf(";", begin);
            if (end == -1) {
                end = document.cookie.length;
            }
            return document.cookie.substring(begin, end);
        }
    }

    // Our cookie was not set.
    // The value "null" is returned from the function.
    return null;
}

function delCookie (NameOfCookie) {
    if(getCookie(NameOfCookie)){
        setCookie(NameOfCookie, '', -30);
    }
}*/

function setActiveLightboxes(lightboxes) {
    debug("[setActiveLightboxes] Someone calling setActiveLightboxes with: "+lightboxes);
    var lbs = mfMap(function(x){return new String(x);},lightboxes);
    var h = new MfOrderedHash();
    for (var i = 0; i < lbs.length; i++){
        h.set(lbs[i],1);
    }
    var uniq_lbs = h.getKeys();
    var cookie = uniq_lbs.slice(0,4).join(",");
    debug("[setActiveLightboxes] Saving activeLightboxes as "+cookie);
    setCookie ( "activeLightboxes", cookie, 365 );
}

function getActiveLightboxes() {
    var activeLb = getCookie("activeLightboxes");
    var activeLbAry = [];
    if ( activeLb != null ) {
        activeLbAry = activeLb.split(",");
    }
    return mfFilter(function(x){return x > 0;},mfMap(function(x){return Number(x)},activeLbAry)); //make sure we return Numbers and filter out zero and negatives
}

function restoreImageFormatCheckboxes() {
/* EM-1019: disabled on TRUNK
    var elms = ["so_horizontal", "so_vertical", "so_square", "so_panoramic", "so_qspace"];
*/
    var elms = ["so_horizontal", "so_vertical", "so_square", "so_panoramic"];
    for (i=0; i < elms.length; i++) {
		var elm = $(elms[i]);
		if (elm) {
			if (getCookie(elms[i]) != "off") {
				elm.checked = true;
			} else {
				elm.checked = false;
			}
		}
	}
}

function storeImageFormatCheckboxes() {
/* EM-1019: disabled on TRUNK
    var elms = ["so_horizontal", "so_vertical", "so_square", "so_panoramic", "so_qspace"];
*/
    var elms = ["so_horizontal", "so_vertical", "so_square", "so_panoramic"];
    for (i=0; i < elms.length; i++) {
		var elm = $(elms[i]);
		if (elm) {
			if (elm.checked)
				setCookie(elms[i], "on", 30);
			else
				setCookie(elms[i], "off", 30);			
		}
	}
}

function initImageFormatCheckboxes() {
	if (window.application && application.pageName == "search_results") {
		/* We need to permit the GET arguments to override the cookies. This is tricky, so what we do is check
		 * to see if all the boxes are unchecked. This implies that there were no GET arguments, so in that case
		 * we restore the checkbox values from the cookies.
		 *
		 * If there are any checked values, that means there were GET arguments which set them at the Velocity level,
		 * so we store those values in the cookies instead.
		 */

/* EM-1019: disabled on TRUNK
		    if (!$("so_horizontal").checked && !$("so_vertical").checked && !$("so_square").checked && !$("so_panoramic").checked && !$("so_qspace").checked) {
*/
        if (!$("so_horizontal").checked && !$("so_vertical").checked && !$("so_square").checked && !$("so_panoramic").checked ) {
            restoreImageFormatCheckboxes();
		} else {
			storeImageFormatCheckboxes();
		}
	} else {
		restoreImageFormatCheckboxes();
	}
}

var Console = {
	timers: {}
}

Console.log = function(arg) {
	// For Firefox browsers with Firebug installed.
	if (typeof(console) == "object" && console.time)
		console.log(arg);

	// For all browsers.
	this.timers[arg] = (new Date()).getTime();
};
Console.time = function(arg) {
	// For Firefox browsers with Firebug installed.
	if (typeof(console) == "object" && console.time)
		console.time(arg);
	
	// For all browsers.
	this.timers[arg] = (new Date()).getTime();
};
Console.timeEnd = function(arg) {
	// For Firefox browsers with Firebug installed.
	if (typeof(console) == "object" && console.timeEnd)
		console.timeEnd(arg);
	
	// For all browsers.
	var now = (new Date()).getTime();
	debug("[PROFILER] '" + arg + "' took " + (now - this.timers[arg]) + "ms")
	this.timers[arg] = null;
};


var LOGGER;
function createDebugConsole() {
    LOGGER = new Logger();
    LOGGER.setLevel(Logger.debugL);
    LOGGER.debug("Debug console enabled.");
}

function padLeft(ostr, len, chr) {
	str = ostr;
	while (str.length < len)
		str = chr + str;
	
	return str;
}
function clearDebug() {
/*	if (db = $("debug"))
		db.value = "";
		*/
}
function debug(msg){
    if(LOGGER) {
        LOGGER.debug(msg);
    }
}

function handleErrorsFromDWR(errorString, exception) {
	debug("== DWR Error ===========================");
	debug("Error type:    " + exception.name);
	debug("Line number:   " + exception.lineNumber);
	debug("Filename:      " + exception.fileName);
	debug("Error message: " + exception.message);
	debug("======================================");
}

function closeInfoDivs() {
	divs = $("info_panel").getElementsByTagName("div");
	nd = divs.length;
	for (i=0; i < nd; i++)
		if (divs[i].id.slice(0,5) == "info_")
			divs[i].style.display = "none";
			
	var p;
	while (p = application.openPanels.pop()) {
		var q = $(p);
		if (q) panel_slide_in(q);
	}
}

function closeSxDownloadDivs() {
	divs = $("sxDownload_panel").getElementsByTagName("div");
	nd = divs.length;
	for (i=0; i < nd; i++)
		if (divs[i].id.slice(0,10) == "sxDownload")
			divs[i].style.display = "none";

	var p;
	while (p = application.openPanels.pop()) {
		var q = $(p);
		if (q) panel_slide_in(q);
	}
}

function mfElemIndex(ary,elem){
    var r = -1;
    for(var i = 0; i < ary.length; i++){
        if (elem == ary[i]){
            r = i;
            break;
        }
    }
    return r;
}

function isInLightbox(lightboxID,imageCode) {
    var r = false;
    if (LB_INFO_MAP.hasKey(imageCode)) {
        var lbInfo = LB_INFO_MAP.get(imageCode);
        for (var j = 0; j < lbInfo.length; j++) {
            if (lbInfo[j] == lightboxID) {
                r = true;
                break;
            }
        }
    }
    return r;
}

function drawLightboxAddRemoveIcons(iconDivPrefix,imageCode,optCurrentLightboxID){
    var currentLightboxID = -1; //default is error id -1 means no active lightbox specified
    if(arguments.length > 2){
        currentLightboxID = optCurrentLightboxID;
    }
    //first paint only as many lightbox icons as we have
    var lbList = getActiveLightboxes();
    //first case where the lightbox is one of the active ones and if we are in a lightbox in the first place

    debug ( "drawLightboxAddRemoveIcons icondivid = " + iconDivPrefix + " imageCode = " + imageCode );
    if ( lbList && (currentLightboxID == -1 || mfElemIndex(lbList,currentLightboxID) > -1) ) {
        for (var i = 0; i < 4; i++) { //4 lightbox icons
            var iconDivId = iconDivPrefix + (1 + i);
            var div = $(iconDivId);

            removeChildSafe ( div );
            if (lbList.length > i) {
                //show
                var lightboxID = lbList[i];
                var htmlToPutIntoDiv = '';
                //var altText = "";
                var alt= "";
                var titleText = "";
                if (ALL_LB_MAP.hasKey(lightboxID)) {
					//altText = " alt='" + ALL_LB_MAP.get(lightboxID) + "' ";
                    alt = ALL_LB_MAP.get(lightboxID);
                } else {
                    //here we guess that ALL_LB_MAP has not been populated yet so we schedule ourselves to be called when it will
                    EXECUTE_AFTER_LIGHTBOX_VERIFY.push(drawLightboxAddRemoveIcons.curryAlt(iconDivPrefix, imageCode, currentLightboxID));
                }
                var onImage = "/images/ei/lightbox_on.gif";
                var offImage = "/images/ei/lightbox_off.gif";
                if (currentLightboxID == lightboxID) {
                    onImage = "/images/ei/lightbox_on_active.gif";
                    offImage = "/images/ei/lightbox_off_active.gif";
                }
                if (isInLightbox(lightboxID,imageCode)) {
                    titleText = i18n.lightbox_remove + " - " + "<strong>" + ALL_LB_MAP.get(lightboxID) + "</strong>";
                    div.setAttribute("title", titleText.replace(/ /g,"&nbsp;") );

                    htmlToPutIntoDiv = "<a href='javascript:iconRemoveFromLB(" + lightboxID + ",\"" + imageCode + "\",\"" + iconDivPrefix + "\"," + currentLightboxID + ");'><img src='" + STATIC_REPOSITORY + onImage + "' alt='" + alt + "'/></a>";

                    var a_element  = A_Q.pop();
                    a_element.id =  iconDivPrefix + "_a";
                    a_element.href = "javascript:iconRemoveFromLB(" + lightboxID + ",\"" + imageCode + "\",\"" + iconDivPrefix + "\"," + currentLightboxID + ");";

                    var img_element  = IMG_Q.pop();
                    img_element.id =  iconDivPrefix + "_img";
                    img_element.src = STATIC_REPOSITORY + onImage;
                    img_element.alt = alt;

                    a_element.appendChild( img_element );

                } else {
                    titleText = i18n.lightbox_add + " - " + "<strong>" + ALL_LB_MAP.get(lightboxID) + "</strong>";
                    div.setAttribute("title", titleText.replace(/ /g,"&nbsp;") );
                    htmlToPutIntoDiv = "<a href='javascript:iconAddToLB(" + lightboxID + ",\"" + imageCode + "\",\"" + iconDivPrefix + "\"," + currentLightboxID + ");'><img src='" + STATIC_REPOSITORY + offImage + "' alt='" + alt + "'/></a>";

                    var a_element  = A_Q.pop();
                    a_element.id =  iconDivPrefix + "_a";
                    a_element.href = "javascript:iconAddToLB(" + lightboxID + ",\"" + imageCode + "\",\"" + iconDivPrefix + "\"," + currentLightboxID + ");";

                    var img_element  = IMG_Q.pop();
                    img_element.id =  iconDivPrefix + "_img";
                    img_element.src = STATIC_REPOSITORY + offImage;
                    img_element.alt = alt;

                    a_element.appendChild( img_element );
                }

                //if ( areWeInRegularSearch() ) {
                //    div.innerHTML = htmlToPutIntoDiv;
                //} else {
                    div.appendChild( a_element );
                //}

                div.style.display = "block";
                debug ( "drawLightboxAddRemoveIcons displaying 1 = " + iconDivId );
            } else {
                //hide
                div.style.display = "none";
            }
        }
    } else {
        //second case where the lightbox is not one of the active ones and we are required to draw only one icon
        var iconDivId = iconDivPrefix + "1";
        var div = $(iconDivId);

        removeChildSafe ( div );
        var lightboxID = currentLightboxID;
        var htmlToPutIntoDiv = '';
        //var altText = "";
        var alt = "";
        var titleText = "";
        if (ALL_LB_MAP.hasKey(lightboxID)) {
            //altText = " alt='" + ALL_LB_MAP.get(lightboxID) + "' ";
            alt = ALL_LB_MAP.get(lightboxID);
        } else {
            //here we guess that ALL_LB_MAP has not been populated yet so we schedule ourselves to be called when it will
            EXECUTE_AFTER_LIGHTBOX_VERIFY.push(drawLightboxAddRemoveIcons.curryAlt(iconDivPrefix, imageCode, currentLightboxID));
        }
        var onImage = "/images/ei/lightbox_on_active.gif";
        var offImage = "/images/ei/lightbox_off_active.gif";
        if (isInLightbox(lightboxID,imageCode)) {
            titleText = i18n.lightbox_remove + " <strong>" + ALL_LB_MAP.get(lightboxID) + "</strong>";
            div.setAttribute("title", titleText.replace(/ /g,"&nbsp;") );
            htmlToPutIntoDiv = "<a href='javascript:iconRemoveFromLB(" + lightboxID + ",\"" + imageCode + "\",\"" + iconDivPrefix + "\"," + currentLightboxID + ");'><img src='" + STATIC_REPOSITORY + onImage + "' alt='" + alt + "'/></a>";

            var a_element  = A_Q.pop();
            a_element.id =  iconDivPrefix + "_a";
            a_element.href = "javascript:iconRemoveFromLB(" + lightboxID + ",\"" + imageCode + "\",\"" + iconDivPrefix + "\"," + currentLightboxID + ");";

            var img_element  = IMG_Q.pop();
            img_element.id =  iconDivPrefix + "_img";
            img_element.src = STATIC_REPOSITORY + onImage;
            img_element.alt = alt;

            a_element.appendChild( img_element );
            debug ( "drawLightboxAddRemoveIcons displaying 2 = " + iconDivId );

        } else {
            titleText = i18n.lightbox_add + " <strong>" + ALL_LB_MAP.get(lightboxID) + "</strong>";
            div.setAttribute("title", titleText.replace(/ /g,"&nbsp;") );            
            htmlToPutIntoDiv = "<a href='javascript:iconAddToLB(" + lightboxID + ",\"" + imageCode + "\",\"" + iconDivPrefix + "\"," + currentLightboxID + ");'><img src='" + STATIC_REPOSITORY + offImage + "' alt='" + alt + "'/></a>";

            var a_element  = A_Q.pop();
            a_element.id =  iconDivPrefix + "_a";
            a_element.href = "javascript:iconAddToLB(" + lightboxID + ",\"" + imageCode + "\",\"" + iconDivPrefix + "\"," + currentLightboxID + ");";

            var img_element  = IMG_Q.pop();
            img_element.id =  iconDivPrefix + "_img";
            img_element.src = STATIC_REPOSITORY + offImage;
            img_element.alt = alt;

            a_element.appendChild( img_element );
            debug ( "drawLightboxAddRemoveIcons displaying 3 = " + iconDivId );
        }

        //if(areWeInRegularSearch()){
        //    div.innerHTML = htmlToPutIntoDiv;
        //} else{
            div.appendChild( a_element );
        //}

        div.style.display = "block";
        for (var i = 1; i < 4; i++){//4 lightboxes
            iconDivId = iconDivPrefix + (1 + i);
            div = $(iconDivId);
            div.style.display = "none";
        }
    }
}

function linkDownloadHiResComp(iconDiv,imageCode,canComp){
    var div = $(iconDiv);
    var htmlToPutIntoDiv = '';

    if ( canComp ) {
        htmlToPutIntoDiv = "<a href='javascript:vComp(\""+ imageCode+ "\");'>"+ i18n.download_hires_comp + "</a>";

        div.innerHTML = htmlToPutIntoDiv;
        div.style.display = "block";
    } else {
        div.style.display = "none";
    }
}

function copyrightDownloadHRC(iconDiv,imageCode,canComp){
    var div = $(iconDiv);
    var htmlToPutIntoDiv = '';

    if ( canComp ) {
        htmlToPutIntoDiv = "<a href='javascript:vComp(\""+ imageCode+ "\");'>"+ i18n.download_hires_comp + "</a>";

        div.innerHTML = htmlToPutIntoDiv;
        div.style.display = "block";
    }
}

function linkLargerComping(iconDiv,imageCode,query,licenseType){
    var div = $(iconDiv);
    var htmlToPutIntoDiv = '';
    //EM-1022 : query is encoded in vElg function
    htmlToPutIntoDiv = "<a href='javascript:vElg(\"enlarged.html\",\"" + imageCode + "\",\"search\",\"" + query + "\",\"" + licenseType + "\");' >"+ i18n.largerComping + "</a>";

    div.innerHTML = htmlToPutIntoDiv;
}

function drawHistoryIcon(iconDiv,imageCode){
    var div = $(iconDiv);
    if ( div && areWeInRegularSearch() ) { // EM-479 : remove icon "View history" from lightbox featurebox
        var htmlToPutIntoDiv = '';

		var altText = " alt='"+i18n.viewHistory+"' ";
		div.setAttribute("title", i18n.viewHistory);
        htmlToPutIntoDiv = "<a href='#1'><img src='"+STATIC_REPOSITORY+"/images/ei/history_thumb2.gif"+"' "+ altText+ "  onClick='return viewUserHistory()' /></a>";

        div.innerHTML = htmlToPutIntoDiv;
        div.style.display = "block";
    }
}


function drawSxDownloadIcon(iconDiv,imageCode,canSxDownload,elementID){

    var div = $(iconDiv);

    if ( div ) {

        if ( canSxDownload && canSxDownload != "false" ) {
            var htmlToPutIntoDiv = '';

    		var altText = " alt="+i18n.download_sx+" ";
	    	div.setAttribute("title", i18n.download_sx);
             
            var onClickAction = "";
            if ( elementID == null ) {
                onClickAction = " onClick='return viewSxDownload(\""+imageCode+"\",\""+canSxDownload+"\")' ";
	    	} else {
	    	    onClickAction = " onClick='return clickthumb(\""+ elementID +"\")' ";
	    	}
	    	htmlToPutIntoDiv = "<a href='#1'><img src='"+STATIC_REPOSITORY+"/images/ei/sx_icon.gif"+"' "+ altText + onClickAction + "  /></a>";
            
            div.innerHTML = htmlToPutIntoDiv;
            div.style.display = "block";
        } else {
            div.style.display = "none";
        }
    }
}

function clickthumb( elementID ) {
        popupClick ( $(elementID),{"showSxDownload":true} );
        return false;
}

function drawSimSearchIcon(iconDiv,imageCode, thumb){
    var div = $(iconDiv);
    if ( div ) {
        removeChildSafe ( div );

        var htmlToPutIntoDiv = '';


        var alt = i18n.title_simsearch;

        div.setAttribute("title", i18n.title_simsearch);

        htmlToPutIntoDiv = "<a href='#1'><img src='"+STATIC_REPOSITORY+"/images/ei/simsearch-13x13.gif"+"' alt='" + alt + "' onClick='return popupClick($(\"" + thumb.id + "\"));' /></a>";

        var a_element  = A_Q.pop();
        a_element.id =  iconDiv + "_a";

        var img_element  = IMG_Q.pop();
        img_element.id =  iconDiv + "_img";
        img_element.src = STATIC_REPOSITORY+"/images/ei/simsearch-13x13.gif";
        img_element.alt = alt;        
        img_element.onclick = function() {
           return popupClick ($(thumb.id ) );
        }

        if(areWeInRegularSearch()){
            div.innerHTML = htmlToPutIntoDiv;
        }else{
            a_element.appendChild( img_element );
        }

        div.appendChild( a_element );
        div.style.display = "block";
    }
}

function runABSimSearch(imgCode,optSimType){
    var query;
    var simType = optSimType || ABSIM ;
    if(simType != SIMSEARCH_TYPE_EM && simType != SIMSEARCH_TYPE_K2 ){
        alert("Unable to execute simsearch due to unknown simsearch type: "+simType); //TODO conside making this warning somewhat softer once testing is over
        return;
    }
    ABSIM = simType; //save it back in our global variable
    if(simType == SIMSEARCH_TYPE_K2){
        query = "simSearch:"+imgCode;
    } else if (simType == SIMSEARCH_TYPE_EM){
        if (imgCode != getLastKeywordQuery().trim()){
            query = "simSearch:"+imgCode+",e "+getLastKeywordQuery();
        } else {
            //this is for the edge case to prevent e.g. simSearch:625-00902329,l 625-00902329 which returns 0
            query = "simSearch:"+imgCode+",e ";
        }
    } else {
        debug("Unknown simsearch type: "+simType);
    }
    if(query){
        dwr.util.setValue("smarties", "");
        createNewSearch({'query':query});
    }
    return true;
}

function drawABSimSearchIcon(iconDiv,imageCode, thumb){
    var div = $(iconDiv);
    if ( div ) {
        removeChildSafe ( div );
        var htmlToPutIntoDiv = '';
        var alt = i18n.title_simsearch;
        div.setAttribute("title", i18n.title_simsearch);
        htmlToPutIntoDiv = "<a href='#1'><img src='"+STATIC_REPOSITORY+"/images/ei/simsearch-13x13.gif"+"' alt='" + alt + "' onClick='return runABSimSearch(\"" + imageCode + "\");' /></a>";
        div.innerHTML = htmlToPutIntoDiv;
        div.style.display = "block";
    }
}

function drawABSimSearchLinks(elementID,imageCode){
    var element = $(elementID);
    if(element){
        var htmlToPutIntoDiv = '<a href="#" onClick="return runABSimSearch(\''+imageCode+'\','+SIMSEARCH_TYPE_EM+');">';
        if(ABSIM == SIMSEARCH_TYPE_EM ){
            htmlToPutIntoDiv = '<span id="ss_select"><a href="#" onClick="return runABSimSearch(\''+imageCode+'\','+SIMSEARCH_TYPE_EM+');" alt="' +i18n.simsearch_type_em_alt+ '" title="' +i18n.simsearch_type_em_alt+ '"><strong>' +i18n.simsearch_type_em+ '</strong></a></span>';
        } else {
            htmlToPutIntoDiv = '<a href="#" onClick="return runABSimSearch(\''+imageCode+'\','+SIMSEARCH_TYPE_EM+');">' +i18n.simsearch_type_em+ '</a>';
        }
        htmlToPutIntoDiv += '&nbsp;';
        if(ABSIM == SIMSEARCH_TYPE_K2 ){
            htmlToPutIntoDiv += '<span id="ss_select"><a href="#" onClick="return runABSimSearch(\''+imageCode+'\','+SIMSEARCH_TYPE_K2+');"><strong>' +i18n.simsearch_type_k2+ '</strong></a></span>';
        } else {
            htmlToPutIntoDiv += '<a href="#" onClick="return runABSimSearch(\''+imageCode+'\','+SIMSEARCH_TYPE_K2+');" alt="' +i18n.simsearch_type_k2_alt+ '" title="' +i18n.simsearch_type_k2_alt+ '">' +i18n.simsearch_type_k2+ '</a>';
        }
        htmlToPutIntoDiv += '<a href="#" id="simsearch_help" onClick="return showModalInfomercial(\'SIMSEARCH_FEATURE\',true);"><img src=\"'+STATIC_REPOSITORY+'/images/ei/help_icon.png\" /></a>';
        element.innerHTML=htmlToPutIntoDiv;
    }
}

var _LAST_KEYWORD_QUERY = "";
var _LAST_QUERY = "";
function setLastQuery(q){
    //sets 3 things: the last query, last keyword query, and simsearch flag
    _LAST_QUERY = q;
    if (q.indexOf("simSearch:") < 0){
        setLastKeywordQuery(q);
        setLastSearchWasSimSearch(false);
    } else {
        setLastSearchWasSimSearch(true);
    }
}

//returns the last keyword query
function getLastKeywordQuery(){
    return _LAST_KEYWORD_QUERY;
}

function setLastKeywordQuery(q){
    _LAST_KEYWORD_QUERY = q;
}

function getLastQuery(){
    return _LAST_QUERY;
}

var _WAS_SIMSEARCH = false;
function lastSearchWasSimSearch(){
    return _WAS_SIMSEARCH;
}

function setLastSearchWasSimSearch(truthValue){
    _WAS_SIMSEARCH = truthValue;
}

var _LAST_POS_IN_KEYWORD_SEARCH;
function setLastPositionInKS(position){
    _LAST_POS_IN_KEYWORD_SEARCH = position;
}

function getLastPositionInKS(){
    return _LAST_POS_IN_KEYWORD_SEARCH;
}

var _LAST_LICENCE_IN_KEYWORD_SEARCH;
function getLastLicenceInKS(){
    return _LAST_LICENCE_IN_KEYWORD_SEARCH;
}

function setLastLicenceInKS(licType){
    _LAST_LICENCE_IN_KEYWORD_SEARCH = licType;
}

function showKeywordSearchBackLink(numResults,originalQuery,originalPosition,origLicence){
    $("simsearch_results_span").innerHTML = new String(numResults);
    $("back_to_keyword_search_div").style.display = "block";
    $("back_to_keyword_search_link").onclick = function(oq,opos,olic) {
		    createNewSearch({'query':oq,'sp':opos,'licType':olic});
		    return false;
    }.curryAlt(originalQuery,originalPosition,origLicence);
}

function hideKeywordSearchBackLink(){
    $("back_to_keyword_search_div").style.display = "none";
}

function showModalInfomercial(contentName,alwaysShow){
    if(ELOCKS.get("MODAL_INFO_LOCK")){
        //loop via setTimeout until lock is freed
        setTimeout('showModalInfomercial("'+contentName+'",'+alwaysShow+')',100);
        return;
    }
    ELOCKS.set("MODAL_INFO_LOCK");
    //EM-1485 and EM-1499
    alwaysShow = alwaysShow | false;
    var SF_SEEN_BEFORE_KEY = "SEEN_BEFORE_"+contentName;
    //show only once
    if(USER_PREF_MAP.get(SF_SEEN_BEFORE_KEY) && alwaysShow == false){
        //they have seen this exit
        ELOCKS.unset("MODAL_INFO_LOCK");
        return;
    }
    var params = {};
    params["messageId"] =  contentName;
    KeyBasedPassthrough.execute( params, function(response){
        if (! response.error) {
            jQuery("#basic-modal-content").html(response.data);
            jQuery("#basic-modal-content").modal({onClose: function (dialog) {
                USER_PREF_MAP.set(SF_SEEN_BEFORE_KEY,"1");
                GetSetUserAppPrefs.execute({action:"set",userPrefs:JSON.stringify(USER_PREF_MAP.storage)},function(){});
                jQuery.modal.close(); //close the modal
                ELOCKS.unset("MODAL_INFO_LOCK");
            }});
        } else {
            ELOCKS.unset("MODAL_INFO_LOCK");
            debug("[showModalInfomercial] error: "+response.error);
        }
      });

}

function drawPriceIcon(iconDiv,imageCode,query,licenseType,isRFEditorialPriceAvail){
    var div = $(iconDiv);
    if ( div ) {
        removeChildSafe ( div );
        var htmlToPutIntoDiv = '';
        var curr = "";
        if ( currency[application.locale] ) {
            curr = "_" + currency[application.locale];
        }

        if ( isRFEditorialPriceAvail && isRFEditorialPriceAvail == "true" ) {
            var alt = i18n.seeRFPrice;

	        div.setAttribute("title", i18n.seeRFPrice);
            htmlToPutIntoDiv = "<a href='javascript:vElg(\"enlarged_pricing.html\",\"" + imageCode + "\",\"search\",\"" +  Url.encode(query) + "\",\"" + licenseType + "\");' ><img src='"+STATIC_REPOSITORY+"/images/ei/rf_prices"+curr+".gif"+"' alt='"+ alt+"'/></a>";

            var a_element  = A_Q.pop();
            a_element.href = "javascript:vElg(\"enlarged_pricing.html\",\"" + imageCode + "\",\"search\",\"" +  Url.encode(query) + "\",\"" + licenseType + "\");";
            a_element.id =  iconDiv + "_a";

            var img_element  = IMG_Q.pop();
            img_element.id =  iconDiv + "_img";
            img_element.src = STATIC_REPOSITORY+"/images/ei/rf_prices"+curr+".gif";
            img_element.alt = alt;


            a_element.appendChild( img_element );
        } else {
            var alt = i18n.seePrice;

            div.setAttribute("title", i18n.seePrice);
            htmlToPutIntoDiv = "<a href='javascript:vElg(\"enlarged_pricing.html\",\"" + imageCode + "\",\"search\",\"" +  Url.encode(query) + "\",\"" + licenseType + "\");' ><img src='"+STATIC_REPOSITORY+"/images/ei/price"+curr+".gif"+"' alt='"+ alt+"'/></a>";



            var a_element  = A_Q.pop();
            a_element.href = "javascript:vElg(\"enlarged_pricing.html\",\"" + imageCode + "\",\"search\",\"" +  Url.encode(query) + "\",\"" + licenseType + "\");";
            a_element.id =  iconDiv + "_a";

            var img_element  = IMG_Q.pop();
            img_element.id =  iconDiv + "_img";
            img_element.src = STATIC_REPOSITORY+"/images/ei/price"+curr+".gif";
            img_element.alt = alt;

            a_element.appendChild( img_element );
        }
        if ( areWeInRegularSearch()){
            div.innerHTML = htmlToPutIntoDiv;
        } else {
            div.appendChild( a_element );
        }

        div.style.display = "block";
    }
}

var SC_INFO_MAP = new MfHashtable(); //global cache for storing shopping cast information
//draws shopping cart icon
function drawShoppingCartIcon(divIDName,imageCode){
    var isInShoppingCart = false;
    var numOfUsages = 0;
    var div = $(divIDName);
    if ( div ) {
        removeChildSafe ( div );

        if (SC_INFO_MAP.hasKey(imageCode)){
            isInShoppingCart = true;
            numOfUsages = SC_INFO_MAP.get(imageCode);
        }
        var htmlToPutIntoDiv = '';

        if(isInShoppingCart){
            var alt = i18n.shopping_cart_remove;
            div.setAttribute("title", i18n.shopping_cart_remove);

            if(numOfUsages > 0){
                div.setAttribute("title", "<img src='/images/icon_warning.gif' />&nbsp;&nbsp;" + i18n.enlarged_hasUsage );
                htmlToPutIntoDiv = "<a href='/shoppingcart/'><img src='"+STATIC_REPOSITORY+"/images/ei/cart_icon_on.gif"+"' alt='"+ alt+"'/></a>";

                var a_element  = A_Q.pop();
                a_element.href = "/shoppingcart/";
                a_element.id =  divIDName + "_a";

                var img_element  = IMG_Q.pop();
                img_element.id =  divIDName + "_img";
                img_element.src = STATIC_REPOSITORY+"/images/ei/cart_icon_on.gif";
                img_element.alt = alt;

                a_element.appendChild( img_element );

            } else {
                htmlToPutIntoDiv = "<a href='javascript:iconRemoveFromSC(\""+ divIDName+ "\",\""+imageCode+"\");'><img src='"+STATIC_REPOSITORY+"/images/ei/cart_on.gif"+"' alt='"+ alt+"'/></a>";
                var a_element  = A_Q.pop();
                a_element.href = "javascript:iconRemoveFromSC(\""+ divIDName+ "\",\""+imageCode+"\");";
                a_element.id =  divIDName + "_a";

                var img_element  = IMG_Q.pop();
                img_element.id =  divIDName + "_img";
                img_element.src = STATIC_REPOSITORY+"/images/ei/cart_on.gif";
                img_element.alt = alt;

                a_element.appendChild( img_element );
            }
        } else {
            //var altText = " alt='"+i18n.shopping_cart_add+"' ";
            var alt = i18n.shopping_cart_add;
            div.setAttribute("title", i18n.shopping_cart_add);

            htmlToPutIntoDiv = "<a href='javascript:iconAddToSC(\""+ divIDName+ "\",\""+imageCode+"\");'><img src='"+STATIC_REPOSITORY+"/images/ei/cart_off.gif"+"' alt='"+ alt+"'/></a>";
            var a_element  = A_Q.pop();
            a_element.href = "javascript:iconAddToSC(\""+ divIDName+ "\",\""+imageCode+"\");";
            a_element.id =  divIDName + "_a";

            var img_element  = IMG_Q.pop();
            img_element.id =  divIDName + "_img";
            img_element.src = STATIC_REPOSITORY+"/images/ei/cart_off.gif";
            img_element.alt = alt;

            a_element.appendChild( img_element );
        }
        if ( areWeInRegularSearch() ){
            div.innerHTML = htmlToPutIntoDiv;
        } else {
            div.appendChild( a_element );
        }
    }
}

function iconAddToSC(divIDName,imagecode) {

    //scPopIcon : search
    //bigThumbSCIcon : feature image
    //ssSCIcon : SimSearch
    //lbCartxxx-xxxxxxxxx : lighbox
    var rawSearchString;
    if ( divIDName == "bigThumbSCIcon" ) {
        rawSearchString = DWRUtil.getValue("bigRawSearchString");
    } else if ( divIDName == "ssSCIcon" ) {
        rawSearchString = DWRUtil.getValue("ssRawSearchString");
    } else if ( divIDName == "scPopIcon" ) {
        rawSearchString = DWRUtil.getValue("rawSearchString");
    } else if ( divIDName.slice(0,6) == "lbCart" ) { // from lb
        rawSearchString = DWRUtil.getValue("lbIcon"+imagecode+"rawSearchString");
    }

    if(ELOCKS.get("CART_BUSY")) return;
    ELOCKS.set("CART_BUSY");
    ShoppingCartAddAction.execute({'imagecode':imagecode,'rawSearchString':rawSearchString}, {callback:postIconAddToSC.curryAlt(imagecode, divIDName),errorHandler:errorHandlerWithLockRelease.curryAlt("CART_BUSY")});
}

function postIconAddToSC(imagecode, divIDName, response) {
    if(response.numberOfUsages > -1){    //-1 means no image in SC
        SC_INFO_MAP.set(imagecode, response.numberOfUsages);
    }
    drawShoppingCartIcon(divIDName,imagecode);

    if ( divIDName != ("lbCart"+imagecode) ){
        if ( $("lbCart"+imagecode) ) {
            drawShoppingCartIcon("lbCart"+imagecode, imagecode);
        }
    }

    if ( divIDName != "bigThumbSCIcon" ){
        if ( $("bigThumbSCIcon") && imagecode == $("feature_image").getAttribute("imgCode") ) {
            drawShoppingCartIcon("bigThumbSCIcon", imagecode);
        }
    }

    recalculateSCInfoInHeader(1);
    ELOCKS.unset("CART_BUSY");
}

function iconRemoveFromSC(divIDName,imagecode) {
    if(ELOCKS.get("CART_BUSY")) return;
    ELOCKS.set("CART_BUSY");
    ShoppingCartRemoveAction.execute({'imagecode':imagecode}, {callback:postIconRemoveFromSC.curryAlt(imagecode,divIDName),errorHandler:errorHandlerWithLockRelease.curryAlt("CART_BUSY")});
}

function postIconRemoveFromSC(imagecode, divIDName, response) {
    if(response.numberOfUsages > -1){  //-1 means no image in SC
        SC_INFO_MAP.set(imagecode, response.numberOfUsages);
    } else {
        SC_INFO_MAP.remove(imagecode);
    }
    drawShoppingCartIcon(divIDName,imagecode);

    if ( divIDName != ("lbCart"+imagecode) ){
        if ( $("lbCart"+imagecode) ) {
            drawShoppingCartIcon("lbCart"+imagecode, imagecode);
        }
    }

    if ( divIDName != "bigThumbSCIcon" ){
        if ( $("bigThumbSCIcon") && imagecode == $("feature_image").getAttribute("imgCode") ) {
            drawShoppingCartIcon("bigThumbSCIcon", imagecode);
        }
    }

    recalculateSCInfoInHeader(-1);
    ELOCKS.unset("CART_BUSY");
}

function recalculateSCInfoInHeader(number){
    var elm = document.getElementById("sc_total_count");
    var n = parseInt(elm.innerHTML);
    if (isNaN(n)){
        return;
    }
    var res = n + number;
    if (res < 0){
        res = 0; //prevent shopping cart from being negative number
    }
    elm.innerHTML = new String(res);
}

//error handler with lock realease
//this is dwr error handler that releases the named lock when operation changed
function errorHandlerWithLockRelease(lockName,errmsg){
    ELOCKS.unset(lockName);
    //alert("Releasing "+lockName+" "+errmsg);
}

var IMAGE_CODE_RE = /\D*(\d+\-\d+)\D*/;
//this is the function that displays tooltip underneath the thumb on mouse over
function displayToolTip(popup) {

    //EM-226
    if (getCookie("activeLightboxes") == null){
        verifyActiveLightboxes();
    }
    //var elementID = popup.id;
    var imageCode = popup.getAttribute("alt");
    imageCode = IMAGE_CODE_RE.exec(imageCode)[1]; //first parentheses at 1 at 0 is the orig string
    if (popup.id == "ss_popup") {
		tt = $("ss_thumbnail_tooltip");
		$("ss_thumb_code").innerHTML = popup.getAttribute("alt");
	} else {
     	tt = $("thumbnail_tooltip");
		$("thumb_code").innerHTML = popup.getAttribute("alt");
    }
	tt.style.width = parseInt(popup.style.width) + (2 * parseInt(popup.style.paddingLeft)) - 11 + "px";	// the 11 compensates for the tooltip's padding

	tt.style.left = popup.style.left;
	// The 14 compensates for the popupg's border and padding. Might need to be tweaked.
	tt.style.top = 14 + parseInt(popup.style.top) + parseInt(popup.style.height) + "px";

    tt.className = "tooltip_for_" + popup.id;

    if (popup.id == "ss_popup") {
        if(areWeInRegularSearch()){
           drawLightboxAddRemoveIcons("ssLbIcon", imageCode);
        } else {
            drawLightboxAddRemoveIcons("ssLbIcon", imageCode, $("lbid").value );
        }
    } else {
        if(areWeInRegularSearch()){
            drawLightboxAddRemoveIcons("lbIcon",imageCode);
        } else {
            drawLightboxAddRemoveIcons("lbIcon",imageCode, $("lbid").value );
        }
    }    

    drawABSimSearchIcon("SimSearchIcon",imageCode, $(popup.className) ); // EM-638
    if (popup.id == "ss_popup") {
        drawShoppingCartIcon("ssSCIcon", imageCode);
        drawPriceIcon("ssPriceIcon", imageCode,DWRUtil.getValue("querybox"),popup.getAttribute("license"),popup.getAttribute("isRFEditorialPriceAvail"));
    } else {
        drawPriceIcon("PriceIcon",imageCode,DWRUtil.getValue("querybox"),popup.getAttribute("license"),popup.getAttribute("isRFEditorialPriceAvail"));
        drawShoppingCartIcon("scPopIcon",imageCode);
    }            

    var ss_popup = (popup.id == "ss_popup");
    var scIcon = ss_popup ? "ssSCIcon" : "scPopIcon";
    var pIcon = ss_popup ? "ssPriceIcon" : "PriceIcon";
    var sxIcon = ss_popup ? "ssSxIcon" : "SxIcon";

    drawShoppingCartIcon(scIcon, imageCode);
    drawPriceIcon(pIcon, imageCode,DWRUtil.getValue("querybox"),popup.getAttribute("license"),popup.getAttribute("isRFEditorialPriceAvail"));

    drawSxDownloadIcon( sxIcon,imageCode,popup.getAttribute("canSxDownload"),popup.elementID);
    tt.style.display = "block";
    return tt;
}

function hideToolTip(popup) {
	if (popup.id == "ss_popup")
		tt = $("ss_thumbnail_tooltip");
	else
		tt = $("thumbnail_tooltip");

	if (tt)
		tt.style.display = "none";
}

//turn collection into a proper javascript array
function collectionToArray(x){
    var r = new Array();
    for(var i = 0; i < x.length;i++){
        r.push(x[i]);
    }
    return r;
}

//	 resolve by type
//	type=eh, basePath=/12/34/56/700-12345678, returns: /t/12/34/56/700-12345678eh.jpg
function getResolvedPath(type, basePath)
{
	if ( sTypeFolder == null )
		initTypeFolder();

	return sTypeFolder[type] + basePath + type + ".jpg";
}

//	compute basePath and resolve by type
//	type=eh, imageCode=700-12345678, returns: /t/12/34/56/700-12345678eh.jpg
function getPath(type, imageCode)
{
	if ( sTypeFolder == null )
		initTypeFolder();

	return sTypeFolder[type] + computeBasePath(imageCode) + type + ".jpg";
}

//	compute basePath
//	imageCode=700-12345678, returns: /12/34/56/700-12345678
function computeBasePath(imageCode)
{
	var pp = imageCode.substring(imageCode.indexOf("-") + 1);

	return "/"+ pp.substring(0,2) + "/" + pp.substring(2,4) + "/" + pp.substring(4,6) + "/" + imageCode;
}

function initTypeFolder()
{
	if ( sTypeFolder == null ) {

		//  placeholder for new EM tree maps
		//  values should be loaded from client call for soft references
		sTypeFolder = new Object();
		sTypeFolder['eh'] =
		sTypeFolder['ft'] =
		sTypeFolder['et'] =
		sTypeFolder['er'] =
		sTypeFolder['t'] = "em_t";

		sTypeFolder['fw'] =
		sTypeFolder['ew'] =
		sTypeFolder['w'] = "em_w";

		sTypeFolder['fn'] =
		sTypeFolder['en'] =
		sTypeFolder['n'] = "em_n";
	}
}


/**
 * Display a popup div panel
 *
 * @param panel div's ID name
 * @param height the height of the popup panel
 */
function panel_slide_out (panel,height) {
    var params = {};

    params['div'] = panel
    params['to'] = height;

	closeAllPanels();
	addOpenPanel(panel);

    DISPATCHER.fire("PANEL_SLIDE_OUT", params);
    return false;
}

/**
 * Hide a popup div panel
 *
 * @param panel div's ID name
 */
function panel_slide_in (panel) {
    var params = {};


    params['div'] = panel;
    if ( $(params.div) ) {
        params['oncomplete'] = function() { $(params.div).style.display = "none"; };

        DISPATCHER.fire("PANEL_SLIDE_IN", params);
    }
    return false;
}

DISPATCHER.subscribe("PANEL_SLIDE_OUT",panelSlideOut);
function panelSlideOut(param){

    if ( $(param.div).style.display == "" || $(param.div).style.display == "none") {
       $(param.div).style.display = "block";
       var opener = new Fx.Style(param.div, 'height', {duration:400, transition: Fx.Transitions.linear});
       if ( param.oncomplete ) {
         opener.addEvent('onComplete', param.oncomplete );
       }
       opener.start(param.to);
    }
}

DISPATCHER.subscribe("PANEL_SLIDE_IN",panelSlideIn);
function panelSlideIn(param) {
    //alert (param.div);
    if ( $(param.div).style.display == "block" ) {
        var closer = new Fx.Style(param.div, 'height', {duration:400, transition: Fx.Transitions.linear});
	    if ( param.oncomplete ) {
             closer.addEvent('onComplete', param.oncomplete );
        }
        if ( param.to ) {
            closer.start(param.to);
        } else {
            closer.start(0);
        }
    }
}

/* Accepts a nodelist of radio button inputs.  Returns the selected value, NULL if no value is selected.
 */
function getRadioValue(nodeList) {
	var nl = nodeList.length;
	for (i=0; i < nl; i++)
		if (nodeList[i].checked) {
			return nodeList[i].value;
		}
	return null;
}

function setRadioValue(nodeList, newValue) {
	var nl = nodeList.length;
	for (i=0; i < nl; i++) {
		if (nodeList[i].value == newValue)
			nodeList[i].checked = true;
		else
			nodeList[i].checked = false;
	}
}


//Masterfile's very own hashtable class
function MfHashtable(data) { //be extremely careful with the data you pass to the constructor!!! Once you pass the data here DO NOT USE THEM ANYWHERE ELSE AND DESTROY ANY REFERENCES TO IT!
    var undef;
    this.storage = new Object();
    if(undef!=data){
        this.storage = data;
    }
    return this;
}
MfHashtable.prototype.hasKey = function(key) {
    var undef;
    var item = this.get(key);
    var r = (item == undef) ? false : true;
    return r;
};
MfHashtable.prototype.set = function(key, val) {
    this.storage[key]=val;
    //eval("this.storage." + key + " = val");
};
MfHashtable.prototype.get = function(key) {
    //var r = eval("this.storage." + key);
    var r = this.storage[key];
    return r;
}
MfHashtable.prototype.remove = function(key) {
    var val;
    if(this.hasKey(key)){
        val = this.storage[key];
        delete this.storage[key];
    }
    return val;
}
MfHashtable.prototype.getKeys = function(key) {
    var ret = [];
    for (var k in this.storage){
        ret.push(k);
    }
    return ret;
}
MfHashtable.prototype.update = function(otherTable) {
    //inplace update operation
    var oKeys = otherTable.getKeys();
    for(var i = 0; oKeys.length > i; i++){
        this.set(oKeys[i],otherTable.get(oKeys[i]));
    }
};
MfHashtable.prototype.copy = function() {
    //inplace update operation
    var newT = new MfHashtable();
    var ourKeys = this.getKeys();
    for(var i = 0; ourKeys.length > i; i++){
        newT.set(ourKeys[i],this.get(ourKeys[i]));
    }
    return newT;
};
//hashtable test
function _x1_testHashtable() {
    var t = new MfHashtable();
    t.set("car1", "honda");
    t.set("car2", "toyota");
    t.set("car3", "dacia");
    t.set(6,12);
    if (t.hasKey("car3") == true && t.hasKey("car4") == false && t.hasKey(6) == true) {
        alert("hasKey OK");
    } else {
        alert("hasKey FAILED!!!");
    }
    if (t.get("car3") == "dacia" && t.get(6) == 12) {
        alert("get/set OK");
    } else {
        alert("get/set FAILED!!!");
    }
    t.remove("car1");
    if(t.hasKey("car1")) { alert("remove failed"); } else { alert("remove OK") }
    var keys = t.getKeys();
    if (keys[0] == "car2" && keys[1] == "car3" && keys[2] == 6 && keys.length == 3){
        alert("getKeys OK");
    } else {
        alert("getKeys FAILED!!!");
    }
    var t1 = new MfHashtable();
    t1.set("weapon","Cookie's Tenderizer");
    t1.set("car2","chevrolet");
    t.update(t1);
    if(t.get("car2")=="chevrolet" && t.get("weapon") == "Cookie's Tenderizer"){
        alert("update OK");
    } else {
        alert("update FAILED!!!");
    }
    var initData = {"k1":"hello","k2":"world"};
    var t2  = new MfHashtable(initData);
    if(t2.get("k2") == "world"){alert("Constructor with initData OK");}else{alert("Constructor with initData FAILED!!!");}
    var t3 = t2.copy();
    t2.set("k2","azeroth");
    if(t3.get("k2") == "world"){alert("copy OK");}else{alert("copy FAILED!!!");}
}
//_x1_testHashtable();

/* Updates the "xx images for yyyyy" statement that's currently below the search box.
 * Does so without planting ID hooks in the universal foundresults template.
 */
function updatePublicHitCount(hitcount, keyword, spellchecked, enResolution, simsearchFlag ) {
	if (!hitcount) {
		hitcount = $("totalNumResults").value;
    }

    if (!keyword) {
        if ( $("raw_query") ) {
            keyword = $("raw_query").value;
        } else {
            keyword = "";
        }
    }

    keyword = dwr.util.escapeHtml(keyword);

    if (  $("foundresults") ) {
        var message = "";
        if ( spellchecked && spellchecked != "" && simsearchFlag == false) {
           message = "<small>"+i18nX(i18n.foundresults_noneBut , "<strong>"+keyword+"</strong> " )+"</small> ";
           if (  enResolution != "" ) {
               message = message + "<small>"+i18nX(i18n.foundresults_noneButInEnglish , "<strong> "+keyword+"</strong>" )+"</small>";
           } else if ( hitcount == 1 ) {
               message = message +  "<small>"+i18nX(i18n.foundresults_singular , "<strong> "+hitcount+"</strong>",  "<strong>"+$("querybox").value+"</strong>"  )+"</small>";
           } else {
               message = message +  "<small>"+i18nX(i18n.foundresults_plural , "<strong> "+hitcount+"</strong>",  "<strong>"+$("querybox").value+"</strong>"  )+"</small>";
           }
        }
        else if ( enResolution && enResolution != "" && hitcount > 0) {
           message = message + "<small>"+i18nX(i18n.foundresults_noneButInEnglish , "<strong> "+keyword+"</strong>" )+"</small>";
           if ( hitcount == 1 ) {
               message = message +  "<small>"+i18nX(i18n.foundresults_singular , "<strong> "+hitcount+"</strong>",  "<strong>"+$("querybox").value+"</strong>"  )+"</small>";
           } else {
               message = message +  "<small>"+i18nX(i18n.foundresults_plural , "<strong> "+hitcount+"</strong>",  "<strong>"+$("querybox").value+"</strong>"  )+"</small>";
           }
        }
        
        if ( message != "" ) {
            $("Tip").innerHTML = message;
        } else {
       		 $("Tip").innerHTML = ""
            /*$("Tip").innerHTML = "<p><strong>" + i18n.searchWithinResultsTip + "</strong> " + i18n.em_searchWithinResultsTipAddWords+ "</p>"*/
        }
        //EM-674
			$("search_params").style.top = parseInt($("querybox").offsetTop) + parseInt($("querybox").offsetHeight) + "px";
    }

}


function tooltipsEnabled() {
	var frm = $("frmuserprefs");
	if (frm && frm.show_tooltips) {
		var val = getRadioValue(frm.show_tooltips);
		if (val == 0)
			return false;
		else
			return true;
	}
	return true;
}

function globalTooltipShow() {
	if (tooltipsEnabled()) {
		var elm = this;
        if ( elm.getAttribute("title") ) {
            var title = elm.getAttribute("title").toString();
		    $("titleCache").value = title;
		    elm.setAttribute("title", "");

		    return Tip(title);
        }
    }
}

function globalTooltipHide() {
	if (tooltipsEnabled()) {
		var elm = this;
		var tc = $("titleCache");
		elm.setAttribute("title", tc.value);
		tc.value = "";

		return UnTip();
	}
}

function staticTooltipShow() {
	var ash = this;
	var stitle = ash.getAttribute("title").toString();
	$("titleCache2").value = stitle;
	ash.setAttribute("title", "");

	return Tip(stitle);
}

function staticTooltipHide() {
	var ash = this;
	var stc = $("titleCache2");
	ash.setAttribute("title", stc.value);
	stc.value = "";

	return UnTip();
}

//returns the current selected indes of a <SELECT> object
//or returns -1 if none selected
function selIndex(selObj){
    var idx = -1;
    for (var i = 0 ; i < selSize(selObj); i++){
        if (selObj.options[i].selected == true){
          idx = i;
          break;
        }
    }
    return idx;
}

function selOption(selObj){
    var idx = selIndex(selObj);
    return (idx > -1) ? selObj.options[idx]: null;
}

//sets the selected option by the provided index
function selSetIndex(selObj,idx){
    //first clear old selected index
    if (selIndex(selObj)>-1){
        selObj.options[selIndex(selObj)].selected = false;
    }
    if(selObj.options[idx]){
        selObj.options[idx].selected = true;
    }
    //legacy for price calculator
    selObj.selectedIndex = idx;
}

function selValue(selObj)
{
	var option = selOption(selObj);
    return (option == null) ? null: option.value;
}

//changes the selected index of in <select> field to the option whose value equals provided value
//leaves the select untouched if the value is not found
function selSetIndexByValue(selObj,value){
    for (var i = 0; i < selSize(selObj); i++){
        if (selObj.options[i].value == value){
            selSetIndex(selObj,i);
            break;
        }
    }
}

// select manipulation functions - start
//returns the size of a <SELECT> object
function selSize(selObj){
     var i = 0;
     while (selObj.options[i]){
       i++;
     }
     return i;
}

//add ordered hashtable/set
//ordered in the ascending order oldest first
function MfOrderedHash(sortOrder){
    this.storage = new MfHashtable();
    this.keySet = new Array();
    this.sortOrder = "asc";
    if(sortOrder=="desc"){
        this.sortOrder = sortOrder;
    }
    return this;
}
MfOrderedHash.prototype  = {
    getOrder:function(){return this.sortOrder;},
    hasKey:function(key){
        return this.storage.hasKey(key);
    },
    set:function(key, val) {
        if(this.hasKey(key)){
            this.remove(key);
        }
        this.storage.set(key,val);
        if(this.getOrder() == "asc"){
            this.keySet.push(key);
        } else {
            this.keySet.unshift(key);
        }
    },
    get:function(key) {
        return this.storage.get(key);
    },
    remove:function(key) {
        var val;
        if(this.hasKey(key)){
            val = this.storage.get(key);
            this.storage.remove(key);
            //now remove from keyset
            var idxOfKey = -1;
            for (var i = 0; i < this.keySet.length;i++){
                var nth = this.keySet[i];
                if(nth == key){
                    idxOfKey = i;
                    break;
                }
            }
            var a1 = this.keySet.slice(0,idxOfKey);
            //alert(a1);
            var a2 = this.keySet.slice(idxOfKey+1);
            //alert(a2);
            this.keySet = a1.concat(a2);
        }
        return val;
    },
    getKeys:function(key) {
        return this.keySet;
    },
    length:function(){return this.keySet.length;},
    getIdx:function(idx){
        var r;
        if(idx<this.keySet.length){
            r = this.storage.get(this.keySet[idx]);
        }
        return r;
    },
    getIdxKey:function(idx){
        var r;
        if(idx<this.keySet.length){
            r = this.keySet[idx];
        }
        return r;
    }
};

//test
function __xtestMfOrderedHash(){
    var myUndefined;
    var t = new MfOrderedHash();
    if(t.getOrder() == "asc"){
        alert("Order OK");
    } else {
        alert("Order FAILED!!!");
    }
    t.set("car1", "honda");
    t.set("car2", "toyota");
    t.set("car3", "dacia");
    t.set(6,12);
    if (t.hasKey("car3") == true && t.hasKey("car4") == false && t.hasKey(6) == true) {
        alert("hasKey OK");
    } else {
        alert("hasKey FAILED!!!");
    }
    if (t.get("car3") == "dacia" && t.get(6) == 12) {
        alert("get/set OK");
    } else {
        alert("get/set FAILED!!!");
    }
    t.remove("car1");
    if(t.hasKey("car1")) { alert("remove failed"); } else { alert("remove OK") }
    var keys = t.getKeys();
    if (keys[0] == "car2" && keys[1] == "car3" && keys[2] == 6 && keys.length == 3){
        alert("getKeys OK");
    } else {
        alert("getKeys FAILED!!!");
    }
    t.remove(6);
    keys = t.getKeys();
    if (keys[0] == "car2" && keys[1] == "car3" && keys.length == 2){
        alert("2nd getKeys OK");
    } else {
        alert("2nd getKeys FAILED!!!");
    }
    t.set("car2", "mazda");
    keys = t.getKeys();
    if (keys[1] == "car2" && keys[0] == "car3" && keys.length == 2){
        alert("ordered getKeys OK");
    } else {
        alert("ordered getKeys FAILED!!!");
    }
    var t1 = new MfOrderedHash("desc");
    if(t1.getOrder() == "desc"){
        alert("DESC Order OK");
    } else {
        alert("DESC Order FAILED!!!");
    }
    t1.set("car1", "honda");
    t1.set("car2", "toyota");
    t1.set("car3", "dacia");
    keys = t1.getKeys();
    if (keys[0] == "car3" && keys[1] == "car2" && keys[2] == "car1" && keys.length == 3){
        alert("3rd getKeys OK");
    } else {
        alert("3rd getKeys FAILED!!!");
    }
    if(t1.length()==3 && t.length() == 2){
        alert("length OK");
    } else {
        alert("length FAILED!!!");
    }
    if(t1.getIdx(1) == "toyota" ){
        alert("getIdx OK");
    } else {
        alert("getIdx FALIED!!!");
    }
    if(t1.getIdx(-1) == myUndefined && t1.getIdx(10) == myUndefined){
        alert("getIdx null OK");
    } else {
        alert("getIdx null FAILED!!!");
    }
    if(t1.getIdxKey(1) == "car2" ){
        alert("getIdxKey OK");
    } else {
        alert("getIdxKey FALIED!!!");
    }
}
//__xtestMfOrderedHash();

//param is an array of strings
//returns true if url contains any of the strings
function url_contains(exp_ary){
    var url = ""+top.document.location;
    if ( url.indexOf('?') > 0 ) {
        url = url.substring(0,url.indexOf('?'))    // EM-639 : just take URL path without parameter.
    }
    var r = false;
    for(var i = 0; i < exp_ary.length; i++){
        if (url.indexOf(exp_ary[i]) > -1){
            r = true;
            break;
        }
    }
    return r;
}
function _fdsjhs7_testurl_contains(){
    alert("Does url contains /search: "+url_contains(["/search"]));
    alert("Does url contain /lightbox or my /viewlightbox: "+url_contains(["/lightbox","/viewlightbox"]));
}
//_fdsjhs7_testurl_contains();

function MfThumbQueue(elm){
    this.storage = [];
    this.elm = elm;
    return this;
}
MfThumbQueue.prototype  = {
    pop:function(){
        var r;
        if(this.storage.length>0){
            r = this.storage.pop();
            r.style.cssText = null;
            r.className = null;
            r.onclick = null;
            r.onmousedown =null;
            r.onmouseup =null;
            r.onmouseover = null;
        } else {
            r = document.createElement(this.elm);
        }
        return r;
    },
    push:function(o){
        return this.storage.push(o);
    },
    size:function(){return this.storage.length;}
}
var THUMBQ = new MfThumbQueue("a");  //queue for searchresults/lightboxresults
var SSTHUMBQ = new MfThumbQueue("a"); //sim search thumb results queue

var A_Q = new MfThumbQueue("a");
var IMG_Q = new MfThumbQueue("img");
var DIV_Q = new MfThumbQueue("div");
var SPAN_Q = new MfThumbQueue("span");
var INPUT_Q = new MfThumbQueue("input");

function _fadada_testMfThumbQueue(){
    var a = THUMBQ.pop();
    var b = THUMBQ.pop();
    alert(THUMBQ.size());
    THUMBQ.push(a);
    THUMBQ.push(b);
    alert(THUMBQ.size());
}
//_fadada_testMfThumbQueue();
function MfPoint(x,y){
    this.x = x;
    this.y = y;
}
MfPoint.prototype = {
    toString:function(){return "x:"+this.x+", y:"+this.y}
}
function MfRectangle(NW,SE){
    this.NW = NW;
    this.SE = SE;
}
MfRectangle.prototype = {
    contains:function(p){
        var r = false;
        if(p.x >= this.NW.x && p.x <= this.SE.x){
            if(p.y >= this.NW.y && p.y <= this.SE.y){
                r = true;
            }
        }
        return r;
    },
    toString:function(){
        return "NW "+this.NW+" SE "+this.SE;
    }
};
function _fsaagrtqmqr_rectangleTest(){
    var NW = new MfPoint(10,10);
    var SE = new MfPoint(30,20);
    var box = new MfRectangle(NW,SE);
    alert("In "+(box.contains(new MfPoint(28,20)) ? "OK" : "ERROR"));
    alert("Out 1 "+(box.contains(new MfPoint(28,21)) ? "ERROR" : "OK"));
    alert("Out 2 "+(box.contains(new MfPoint(8,20)) ? "ERROR" : "OK"));
    alert("Out 3 "+(box.contains(new MfPoint(88,20)) ? "ERROR" : "OK"));
    alert("Out 4 "+(box.contains(new MfPoint(28,2)) ? "ERROR" : "OK"));
    alert("Out 5 "+(box.contains(new MfPoint(2,2)) ? "ERROR" : "OK"));
}
//_fsaagrtqmqr_rectangleTest();


//function to help us determine whether we are in regular search - using wrapper in case conditions change later on
function areWeInRegularSearch(){
    var ret = url_contains(["em/search/"]);
    if ( !ret && typeof application != "undefined"  ) {
        ret = (application.pageName == "search_results");
    }
    return ret;
}

//function to help us determine whether we are in lightboxes - using wrapper in case conditions change later on
function areWeInLightbox(){

    var ret = url_contains(["em/lightbox/","em/viewlightbox/"]);
    if ( !ret && typeof application != "undefined" ) {
       ret = (application.pageName == "lightbox") || (application.pageName == "viewlightbox");
    }
    return ret;
}

