function autoSave(mnt,srch,res){
	var r9http = new R9HTTPXml(); 
	var s = "/"+mnt+"/autosave.jsp?searchid="+srch+"&resultid="+res;
	r9http.init(s);
    r9http.asyncGET(null);
}
function r9escape(s){
var ns = s.replace("+", "%2b");
return escape(ns);
}
function openHelpWindow(subject, topic)
{
    var args = 'height=400,width=700,location=no,menubar=no,resizable=yes,toolbar=yes,status=no,scrollbars=yes';
    var url = "/help.html#" + topic;
    var newWin = window.open(url, "help", args);
    newWin.focus();
}

function openSmallerWindow(name, url, xOverride, yOverride)
{
    if (xOverride == null || xOverride < 0) {
        xOverride=600;
    }
    if (yOverride == null || yOverride < 0) {
        yOverride=600;
    }
    var args = 'height=' + yOverride + ',width=' + xOverride + ',location=no,menubar=no,resizable=yes,toolbar=no,status=no,scrollbars=yes';
    var newWin = window.open(url, name, args);
    newWin.focus();
    return(false);
}

/*
*  We are now using jquery.cookie.js for cookie stuff so please use directly for new calls, this is for backward
*  compatibility only.
 */
function ReadCookie(cookieName) {
    jQuery.cookie(cookieName);
}

function DeleteCookie(name)
{
  jQuery.cookie(name, null);
}

function SetCookie(cookieName,cookieValue,nDays,domain) {
     var options = {path: '/', secure: false};
     if (nDays!=null) {
         options.expires = nDays;
     }
     if (domain != null) {
         options.domain = domain;
     }

     jQuery.cookie(cookieName, cookieValue, options);
}


function showdiv3(obref) {
  showhidediv(obrev, 'visible');
}

function hidediv3(obref) {
  showhidediv(obrev, 'hidden');
}

function showhidediv3(obref, state) {
  if (document.all) { //IS IE 4 or 5 (or 6 beta)
     eval( "document.all." + obref + ".style.visibility = state");
  }
  if (document.layers) { //IS NETSCAPE 4 or below
     document.layers[obref].visibility = state;
  }
  if (document.getElementById &&!document.all) {
     obj = document.getElementById(obref);
     obj.style.visibility = state;
  }
}

function showhidediv(obref, state) {
  if (document.getElementById) { // DOM3 = IE5, NS6
  document.getElementById(obref).style.visibility = state;
  }
}


function hidediv(obref) {
  showhidediv(obref, 'hidden');
}

function showdiv(obref) {
  showhidediv(obref, 'visible');
}

function r9_addbm(url, name) {
    if (window.external) {
        window.external.AddFavorite(url,name)
    } else {
        alert("Sorry, your browser will not do this automatically.  Try hitting Ctrl+D after you click 'OK'");
    }
}

// Escape is not quite good enough, add extra characters here.
function escapeForXML(str)
{
   var retString = escape(str);
   return retString.replace(/\+/g, '%2b');
}

function kmail(addr)
{
  document.write('<a class="mlink" href=\"mai'+'lto:' +addr+ '&#64;kayak&#46;com\">'
    +addr+ '&#64;kayak&#46;com</a>'); 
}

function kmail2(addr, domain)
{
  document.write('<a class="mlink" href=\"mai'+'lto:' +addr+ '&#64;' +domain+ '\">'
    +addr+ '&#64;' + domain+ '</a>'); 
}

function validateEmail(email)
{
    if(email.length <= 0)
    {
      return false;
    }
    var splitted = email.match("^(.+)@(.+)$");
    if(splitted == null) return false;
    if(splitted[1] != null )
    {
      var regexp_user=/^\"?[\'\w-_\.\+]*\"?$/;
      if(splitted[1].match(regexp_user) == null) return false;
    }
    if(splitted[2] != null)
    {
      var regexp_domain=/^[\w-\.]*\.[A-Za-z]{2,4}$/;
      if(splitted[2].match(regexp_domain) == null)
      {
        var regexp_ip =/^\[\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\]$/;
        if(splitted[2].match(regexp_ip) == null) return false;
      }// if
      return true;
    }
    return false;
}

// Round a number up/down to nearest increment
function roundTo(num, nearest, up)
{
    if (up == null) up = true;

    var base = Math.floor(num / nearest);

    if ((num % nearest) > 0) {
        if (up) {
            return ((base + 1) * nearest);
        } else {
            return (base * nearest);
        }
    } else {
        return num;
    }
}

// Is browser ie5.X
function isIE5dotX()
{
    var version=0;
    if (navigator.appVersion.indexOf("MSIE")!=-1){
        temp=navigator.appVersion.split("MSIE")
        version=parseFloat(temp[1]);
        if (version >= 5 && version < 6) {
            return true;
        }
    }
    return false;
}

// Use to limit textarea text length
function taLimit(taObj, maxlength) {
    if (taObj.value.length==maxlength*1) {
        if (event.returnValue) {
                event.returnValue = false;
            } else if (event.preventDefault) {
                event.preventDefault();
            } else {
                return false;
            }
    }
}
function taCount(taObj, visText, visCnt, maxlength) {
    if (taObj.value.length>maxlength*1) taObj.value=taObj.value.substring(0,maxlength*1);
    if (visText) visText.style.visibility = 'visible';
    if (visCnt) visCnt.innerHTML=maxlength-taObj.value.length;
}

function sStat(text)
{
    try {
        window.status = text;
    } catch (ignored) {}
    return true;
}
function cStat(text)
{
    window.status = '';
}
function findPosX(obj)
{
    var curleft = 0;
    if (obj.offsetParent)
    {
        while (obj.offsetParent)
        {
            curleft += obj.offsetLeft
            obj = obj.offsetParent;
        }
    }
    else if (obj.x)
        curleft += obj.x;
    return curleft;
}

function findPosY(obj)
{
    var curtop = 0;
    if (obj.offsetParent)
    {
        while (obj.offsetParent)
        {
            curtop += obj.offsetTop
            obj = obj.offsetParent;
        }
    }
    else if (obj.y)
        curtop += obj.y;
    return curtop;
}

function selectByValue(what,value)
{
    if (what == null || typeof what.length == "undefined") return;

    for (var i = 0; i < what.length; i++) {
        if (what[i].value == value) { what.selectedIndex = i; break;} }
}

function selectByStartsWith(what,value)
{
    if (what == null || typeof what.length == "undefined") return;

    for (var i = 0; i < what.length; i++) {
        if ((what[i].value).indexOf(value) == 0) { what.selectedIndex = i; break;} }
}

// same as above but returns index instead of selecting
// used for profile defaulting
function getSelectByValue(what,value)
{
    for (var i = 0; i < what.length; i++) {
        if (what[i].value == value) {
            return i;
        }
    }
    return -1;
}

// get value of radio button group
function getRadioValue(what)
{
    for (var i = 0; i < what.length; i++) {
        if (what[i].checked) {
            return what[i].value;
        }
    }
    return null;
}

// get value of radio button group
function setRadioValue(what, value)
{
    for (var i = 0; i < what.length; i++) {
        if (what[i].value == value) {
            what[i].checked;
            return true;
        }
    }
    return false;
}

function getScrollAmount()
{
    var scrollAmount = document.body.scrollTop;
    if (typeof window.innerWidth != 'undefined')
    {
        if (scrollAmount == 0 && document.documentElement.scrollTop != 'undefined' && document.documentElement.scrollTop != 0) {
            scrollAmount = document.documentElement.scrollTop;
        }
    } else if (typeof document.documentElement != 'undefined'
         && typeof document.documentElement.scrollTop !=
         'undefined' && document.documentElement.scrollTop != 0) {
           if (scrollAmount == 0) {
            scrollAmount = document.documentElement.scrollTop;
           }
     }
    return scrollAmount;
}

function setScrollAmount(top, left)
{
    if( typeof( window.pageYOffset ) == 'number' ) {
    //Netscape compliant
    window.pageYOffset = top;
    window.pageXOffset = left;
  } else if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) ) {
    document.body.scrollTop = top;
    document.body.scrollLeft = left;
  } else if( document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) ) {
    //IE6 standards compliant mode
    document.documentElement.scrollTop = top;
    document.documentElement.scrollLeft = left;
  }

}

function showmessage(text)
{
    var msgbox = document.getElementById('messagebox');
    if (msgbox != null) {
        msgbox.innerHTML = text;
        msgbox.style.left  = Math.round((document.body.clientWidth - msgbox.offsetWidth) / 2) + "px" ;
        var top = 200;
        try {
            var browserWindowHeight;
            var scrollAmount = document.body.scrollTop;
            if (typeof window.innerWidth != 'undefined')
             {
                  browserWindowHeight = window.innerHeight;
                  if (scrollAmount == 0 && document.documentElement.scrollTop != 'undefined' && document.documentElement.scrollTop != 0) {
                    scrollAmount = document.documentElement.scrollTop;
                  }
             } else if (typeof document.documentElement != 'undefined'
                 && typeof document.documentElement.clientHeight !=
                 'undefined' && document.documentElement.clientHeight != 0) {
                   browserWindowHeight = document.documentElement.clientHeight;
                   if (scrollAmount == 0) {
                    scrollAmount = document.documentElement.scrollTop;
                   }
             } else {
                   browserWindowHeight = document.getElementsByTagName('body')[0].clientHeight;
             }

            top = Math.round(((browserWindowHeight - msgbox.offsetHeight) / 3) + scrollAmount - 0);
        } catch (ignored) {
        }
        msgbox.style.top   = top + "px";
        msgbox.style.visibility = 'visible';
    }
}

function hidemessage()
{
    var msgbox = document.getElementById('messagebox');
    if (msgbox != null) {
        msgbox.innerHTML = "";
        msgbox.style.visibility = 'hidden';
    }
}
function toggleFaderPane(show, clickevent)
{
    var theBody = jQuery("body");
    var faderPane = document.getElementById('faderPane');

    if (faderPane == null) {
        theBody.append("<div id='faderPane'></div>");
        if (jQuery.browser.msie && jQuery.browser.version.indexOf("6") == 0) {
            jQuery("#faderPane").append('<img height="2048" width="2048" src="/images/fake-alpha-999.gif"/>');
        }
        faderPane = document.getElementById('faderPane');
    }

    var height = theBody.height();
    var width  = theBody.width();

    faderPane.style.height  = height + "px";
    faderPane.style.width   = width  + "px";
    faderPane.style.display = (show) ? 'block' : 'none';

    if (typeof clickevent == "function" && show) {
        document.getElementById('faderPane').onclick = clickevent;
    } else {
        document.getElementById('faderPane').onclick = null;
    }
}
function htmlSafe(aString)
{
    aString = aString.replace(/\&/g, "&amp;");
    aString = aString.replace(/>/g, "&gt;");
    aString = aString.replace(/</g, "&lt;");
    aString = aString.replace(/\"/g, "&quot;");
    aString = aString.replace(/\'/g, "&#39;");

    return aString;
}

function stripSpaces(aString)
{
    aString = aString.replace(/\s/g, "");
    return aString;
}

function resizeIframeToContents(iframe)
{
    try {
        var frbody = jQuery(iframe).contents().find("body");
        var linkID = jQuery(iframe).attr("id");
        linkID = linkID.replace("displayAd", "displayAdHide");
        if (frbody) {
            // Set iframe size to the size of the body element
            iframe.height = frbody.height();
            iframe.width = frbody.width();
        }

        //8/13/09: We will only hide if it has a single image with the name: "/kayakadpixel.gif"
        //         So we don't run afoul in IE where other folks 1x1 tracking pixels can wreck havoc. 

        var alwaysHide = false;
        var frimg = jQuery(iframe).contents().find("body img");
        if (frimg && frimg.length == 1 && frimg.attr("src") != null && frimg.attr("src").indexOf("/kayakadpixel.gif") > 0) {
            //For various reasons we do not want to look for "1x1" in the name AND we don't want to assume that we only
            //have to detect an single image with a width/height of 1 -- becuase of IE bugs.
            alwaysHide = true;
        }
        if (alwaysHide) {
            iframe.height = 0;
            iframe.width = 0;
            try {
                jQuery(iframe).css("margin","0px");
            } catch (ignored) {
            }

            try {
                var id = linkID;
                id = id.replace("displayAdHide", "");
                jQuery("#bannerad" + id).hide();
                jQuery("#" + linkID).hide(); // link is in seperate div.
            } catch (ignored) {
            }
        } else {
            // Try to show link too
            //jQuery("#" + linkID).show();
            jQuery("#" + linkID).css("visibility", "visible");
        }

    } catch (ignored) {
    }
}

function reloadBannerAds() {
    function setSrc (frmName, rank) {
        var frm = document.getElementById(frmName);
        if (frm != null) {
            //need to improve, just add a timestamp and keep on replaing it with a time stamp.
            var ts = (new Date()).getTime();
            var newsrc = "";
            var oldsrc = "";

            if (navigator.appVersion.indexOf("MSIE")!=-1) {
               oldsrc = frm.contentWindow.location.href;
            } else {
               oldsrc = frm.src;
            }

            if (frm.src.indexOf("&ad_ts=") < 0) {
                newsrc =  oldsrc + "&ad_ts=" + ts; //force unique URL
            } else {
                newsrc = oldsrc.substring(0, oldsrc.indexOf("&ad_ts"))  + "&ad_ts=" + ts;
            }

            if (navigator.appVersion.indexOf("MSIE")!=-1) {
                //This is here to get the history correct in IE.
                var theHTML = document.getElementById("displayAdSpanFrame"+rank).innerHTML;
                var newHTML = theHTML.replace(/src="[^"]*"/, 'src="'+newsrc+'"');
                document.getElementById("displayAdSpanFrame"+rank).innerHTML = newHTML;
           } else {
               frm.src = newsrc;
           }

        }
    }

    function adShowing(theDiv) {
        if (theDiv == null) return false;
        if (document.getElementById(theDiv) == null) return false; 
        if (document.getElementById(theDiv).style.display == "none") return false;
        return true;
    }

    //if already hidden then don't reload. Prevents jumping of ads when paging
    if (adShowing("bannerad1")) setSrc ("displayAd1", "1")
    if (adShowing("bannerad2")) setSrc ("displayAd2", "2")
    if (adShowing("bannerad3")) setSrc ("displayAd3", "3")
    if (adShowing("bannerad4")) setSrc ("displayAd4", "4")
}

function showTT(parent,text,type,offsetOverride,doNotHide)
{
    if (doNotHide == null || ! doNotHide) {
        hideAllTT(false);
    }

    // new: hide any select boxes with class=hideOnTT - prevents bleed through in IE6
    if (navigator.appVersion.indexOf("MSIE")!=-1) {
    	jQuery("select.hideOnTT").css("visibility", "hidden");
    }
    
    obj = document.getElementById('ttip' + type);
    if (text != "") {
        document.getElementById('ttipText' + type).innerHTML = text;
    }
    obj.style.visibility = 'hidden';
    obj.style.display ='block';
    var offset = jQuery(parent).offset();
    var newY = offset.top;
    var newX = offset.left;
    if (offsetOverride != null) {
        newY += offsetOverride.y;
        newX += offsetOverride.x;
    }
    obj.style.zIndex='99';
    if (type == 'BL') {
        newY = newY - obj.offsetHeight + 5;
        newX = newX + parent.offsetWidth - 50;
    } else if (type == 'TL') {
        newY = newY + parent.offsetHeight - 5;
        newX = newX + parent.offsetWidth - 50;
    } else if (type == 'CL' || type == 'CR' || type == 'FL') {
        newY = newY - (obj.offsetHeight/2) + (parent.offsetHeight/2);
        if (type == 'CL' || type == 'FL') {
            newX = newX + parent.offsetWidth;
        } else {
            newX = newX - obj.offsetWidth;
        }
    } else if (type == 'DL') {
        newX = newX + jQuery(parent).outerWidth();
        newY = newY + (jQuery(parent).outerHeight() / 2) - 50;
        obj.style.zIndex='45';  // JR changed from 95 to have smartbox at 50, 51 above
    } else if (type == 'DR') {
    	var oldX = newX;
    	var oldY = newY;
        newY = newY + (jQuery(parent).outerHeight() / 2) - 50;
        newX = newX - (jQuery(obj).outerWidth() + 3);
    	//alert("paroutwidth is " + jQuery(parent).outerWidth() + ", objwidth is " + jQuery(obj).outerWidth() + ", oldtop: " + oldY + ", oldleft: " + oldX + ", top: " + newY + ", left: " + newX);
        obj.style.zIndex='45';  // CA changed from 95 to have smartbox at 50, 51 above
    } else if (type == 'CT' || type == 'CB') {
        newY = newY - 0 + parent.offsetHeight;
        if ((jQuery.browser.mozilla || jQuery.browser.safari) && (type == 'CL' || type == 'FL')) {
            newY += 8;
        } else if (jQuery.browser.msie && parseInt(jQuery.browser.version) == 6) {

        }
        newX = newX - (obj.offsetWidth / 2);
    }
    obj.style.top = newY + 'px';
    obj.style.left = newX + 'px';

    obj.style.visibility = 'visible';
}
function hideAllTT(calllocal)
{
	// new: for IE, select boxes are hidden during tooltip because of bleed-through. now we unhide them...
    if (navigator.appVersion.indexOf("MSIE")!=-1) {
    	jQuery("select.hideOnTT").css("visibility", "visible");
    }
	
    if (calllocal == null) calllocal = true;
    stoptime();
    var types = new Array("BL", "TL", "CL", "CR", "CB", "CT", "DL", "DR", "FL");
    for (var i=0; i < types.length; i++) {
        hideTTType(types[i]);
    }
    if (typeof localTTHidden == "function" && calllocal) {
        localTTHidden();
    }
}
function hideTTType(type)
{
    var o=document.getElementById('ttip' + type);
    if (o!=null) { o.style.display='none'; }
}
var ttipTimerID = null;
function starttime(x)
{
    if (ttipTimerID == null) {
        var t=10000;
        if(x!=null) { t=t*x; }
        ttipTimerID=setTimeout( "hideAllTT()" , t);
    }
}
function stoptime()
{
    if (ttipTimerID != null) {
        clearTimeout(ttipTimerID);
        ttipTimerID = null;
    }
}

function simpleurl(fullurl)
{
    if (fullurl == null) {
        return fullurl;
    }
    var startsWithHttp = (fullurl.indexOf("http://")==0);
    var nextSlash = fullurl.indexOf("/", startsWithHttp ? 7 : 0);
    var host = null;
    if (nextSlash > 0) {
        host = fullurl.substring(startsWithHttp ? 7 : 0, nextSlash);
    } else {
        host = fullurl.substring(startsWithHttp ? 7 : 0);
    }
    if (host.indexOf("www.") ==0) {
        return host.substring(4);
    }
    
    return host;
}
function hideTableRow(id)
{
    var theRow = document.getElementById(id);
    if (theRow == null) return;
    theRow.style.display="none";
}
function showTableRow(id)
{
    var theRow = document.getElementById(id);
    if (theRow == null) return;
    var _isIE = (((navigator.appName).indexOf('Microsoft') > -1) ? true : false);
    if (_isIE) {
        theRow.style.display="block";
    } else {
        theRow.style.display="table-row";
    }
}

function hideTbody(id)
{
    var theRows = document.getElementById(id);
    if (theRows == null) return;
    theRows.style.display="none";
}
function showTbody(id)
{
    var theRows = document.getElementById(id);
    if (theRows == null) return;
    var _isIE = (((navigator.appName).indexOf('Microsoft') > -1) ? true : false);
    if (_isIE) {
        theRows.style.display="block";
    } else {
        theRows.style.display="table-row-group";
    }
}

function cleanUrl(url)
{
    if (url != "" && url.indexOf('http') != 0) {
        // make sure we don't exceed max length
        if (url.length <= 1017) {
            url = "http://" + url;
        } else {
            url = "http://" + url.substring(0, 1017);
        }
    }
    return url;
}

function isBadUrl(url)
{
    url = cleanUrl(url);
    if (url.match(/^https?\:\/\/([A-Za-z0-9\-]*\.){1,}[A-Za-z0-9]{1,3}(\:[0-9]*)?[\/\?][^\s]*$/) ||
        url.match(/^https?\:\/\/([A-Za-z0-9\-]*\.){1,}[A-Za-z0-9]{1,3}(\:[0-9]*)?$/) ||
        url.match(/^https?\:\/\/([A-Za-z0-9\-]*\.){1,}(name|travel|museum|aero|mobi|info|jobs)(\:[0-9]*)?[\/\?][^\s]*$/) ||
        url.match(/^https?\:\/\/([A-Za-z0-9\-]*\.){1,}(name|travel|museum|aero|mobi|info|jobs)(\:[0-9]*)?$/)
        ) {
        return false;
    } else {
        return true;
    }
}
// Animation functions -- Adapted from http://www.hesido.com/web.php?page=javascriptanimation
function animateHeight(elem,startHeight,endHeight,steps,intervals,powr) {
    if (elem.heightChangeMemInt)
	window.clearInterval(elem.heightChangeMemInt);
    var actStep = 0;
    elem.heightChangeMemInt = window.setInterval(
	function() {
	  elem.currentHeight = easeInOut(startHeight,endHeight,steps,actStep,powr);
	  elem.style.height = elem.currentHeight + "px";
	  actStep++;
	  if (actStep > steps) window.clearInterval(elem.heightChangeMemInt);
	}
	,intervals)
}
function easeInOut(minValue,maxValue,totalSteps,actualStep,powr) {
    //Generic Animation Step Value Generator By www.hesido.com
    var delta = maxValue - minValue;
    var stepp = minValue+(Math.pow(((1 / totalSteps) * actualStep), powr) * delta);
    return Math.ceil(stepp)
}
function clearAnimation(elem)
{
    if (elem.heightChangeMemInt) {
	    window.clearInterval(elem.heightChangeMemInt);
    }
}
function replaceArgs()
{
  str = arguments[0];
  for (var i=1; i <= arguments.length; i++) {
    str = str.replace ("{" + (i-1).toString() + "}", arguments[i]);
  }
  return str;
}
function correctPNG() // correctly handle PNG transparency in Win IE 5.5 & 6.
{
   var arVersion = navigator.appVersion.split("MSIE")
   var version = parseFloat(arVersion[1])
   if ((version >= 5.5 && version < 7) && (document.body.filters))
   {
      for(var i=0; i<document.images.length; i++)
      {
         var img = document.images[i]
         var imgName = img.src.toUpperCase()
         if (imgName.substring(imgName.length-3, imgName.length) == "PNG")
         {
            var imgID = (img.id) ? "id='" + img.id + "' " : ""
            var imgClass = (img.className) ? "class='" + img.className + "' " : ""
            var imgTitle = (img.title) ? "title='" + img.title + "' " : "title='" + img.alt + "' "
            var imgStyle = "display:inline-block;" + img.style.cssText
            if (img.align == "left") imgStyle = "float:left;" + imgStyle
            if (img.align == "right") imgStyle = "float:right;" + imgStyle
            if (img.parentElement.href) imgStyle = "cursor:hand;" + imgStyle
            var strNewHTML = "<span " + imgID + imgClass + imgTitle
            + " style=\"" + "width:" + img.width + "px; height:" + img.height + "px;" + imgStyle + ";"
            + "filter:progid:DXImageTransform.Microsoft.AlphaImageLoader"
            + "(src=\'" + img.src + "\', sizingMethod='scale');\"></span>"
            img.outerHTML = strNewHTML
            i = i-1
         }
      }
   }
}
// this function determines whether the event is the equivalent of the microsoft mouseleave or mouseenter events.
// Thanks:  http://dynamic-tools.net/toolbox/isMouseLeaveOrEnter/
function isMLorE(e, handler)
{
    try {
    var reltg = e.relatedTarget ? e.relatedTarget : e.type == 'mouseout' ? e.toElement : e.fromElement;
    while (reltg && reltg != handler) reltg = reltg.parentNode;
    return (reltg != handler);
    } catch (ignored) {
    }
    return false;
}
function trim(str, len, ellip)
{
    if (str == null || str.length <= len) return str;
    if (len) {
        if (ellip) {
            return str.substr(0, len-1) + "&hellip;";
        }
        return str.substr(0, len);
    } else {
        return str.replace(/^\s*/,"").replace(/\s*$/,"");
    }
}
function trimSafe(str, len, ellip)
{
   if ( str == null ){
      return str;
   }

   if ( str.length <= len ){
      return htmlSafe(str);
   }

   var tmp;
   var addEll = false;

   if ( ellip ){
      tmp = trim(str, len - 1, false);
      if ( tmp.length < str.length ){
         addEll = true;
      }
   }else{
      tmp = trim(str, len, false);
   }
   var tmp2 = htmlSafe(tmp);

   if ( addEll ){
      return tmp2 + "&hellip;";
   }

   return tmp2;
}


var r9EventList = null;

function pushRecordedEvents() {
  if (r9EventList.length > 0) {
    var data = { }
    var i = 0;
    jQuery.each(r9EventList, function() {
      var value = (typeof this.value != "undefined") ? this.value : "";
      var units = (typeof this.units != "undefined") ? this.units : "";
      data["event_" + i] = this.category + ":" + this.subCategory + ":" + this.name + ":" + value + ":" + units;
      ++i;
    });
    jQuery.post("/s/sparkle?action=clientevents", data);
    r9EventList = new Array();
  }
}

function recordEvent(cat, subcat, name, units, value) {
  if (r9EventList == null) {
    // first time init
    r9EventList = new Array();
    jQuery(window).unload(pushRecordedEvents);
  }
  jQuery.get("/vs/" + cat + "/" + subcat + "/" + name + "/" + units + "/" + value + "?action=vs");
  //r9EventList.push({ category : cat, subCategory : subcat, name : name, value : value, units : units });
}

function chkCompareToGroups(codeArray)
{
    var finalList = new Array();
    var groupsSeen = new Object();
    for (var i = 0; i < codeArray.length; i++) {
        if (codeArray[i].group == null || codeArray[i].group.length == 0) {
            codeArray[i].groupOK = true;
        } else {
            var groupname = codeArray[i].group.substr(0, codeArray[i].group.indexOf("-"));
            var bestValue = parseInt(codeArray[i].group.slice(codeArray[i].group.indexOf("-") + 1));
            var bestIndex = i;
            if (groupsSeen[groupname] == null) {
                for (var j = i + 1; j < codeArray.length; j++) {
                    var currentgroupname = codeArray[j].group.substr(0, codeArray[j].group.indexOf("-"));
                    if (currentgroupname == groupname) {
                        var currentValue = parseInt(codeArray[j].group.slice(codeArray[j].group.indexOf("-") + 1));
                        if (currentValue < bestValue) {
                            codeArray[bestIndex].groupOK = false;
                            if (codeArray[bestIndex].input != null) {
                               codeArray[bestIndex].input.checked =false;
                            }
                            bestIndex = j;
                            bestValue = currentValue;
                        } else {
                            codeArray[j].groupOK = false;
                            if (codeArray[j].input != null) {
                               codeArray[j].input.checked =false;
                            }
                        }
                    }
                }
             }
        }
    }

    for (var i = 0; i < codeArray.length; i++) {
        if (codeArray[i].groupOK = true) {
            finalList.push(codeArray[i]);
        }
    }
    return finalList;
}
// Safari sort issues
if (typeof String.prototype.localeCompare == "undefined") {
String.prototype.localeCompare = function (sOther) {
    if (this < sOther) return -1;
    else if (this > sOther) return 1;
    else return 0;
}
}

var R9_DisplayEds_JustHidden = false;
function hideDisplayAds(isAnon)
{
    R9_DisplayEds_JustHidden = true;     // prevent them from coming back in this page view for ajax calls
    GetAjaxReg().disableDisplayAds();
    if (isAnon == null || isAnon) {
        var ajaxReg = GetAjaxReg();
        ajaxReg.regtype = "displayad";
        ajaxReg.showRegister();
    }
}

function hlitepagenum(tdref, hlite)
{
    tdref.style.backgroundColor = (hlite) ? '#ffffcc' : 'white';
    tdref.style.cursor = (hlite) ? 'pointer' : 'default';
}


// Initializes a new instance of the StringBuilder class

// and appends the given value if supplied
function StringBuilder(value)
    {
        this.strings = new Array("");
        if (value != null) {
           this.append(value);
        }
    }

// Appends the given value to the end of this instance.
StringBuilder.prototype.append = function (value)
    {
        if (value)
            {
                this.strings.push(value);
            }

        return this; //so I can do: string.append("foo").append("bar");
    }

// Clears the string buffer
StringBuilder.prototype.clear = function ()
    {
        this.strings.length = 1;
    }

    // Converts this instance to a String.
StringBuilder.prototype.toString = function ()
    {
        return this.strings.join("");
    }


function kykButtonClicked(btn, overridehtml) {
    jQuery(btn).children("table").children("tbody").children("tr").children("td.sideimg").each (function (i) {
                    var newPos = this.style.backgroundPosition.replace(/^0px/, "-90px").replace(/-60px/, "-90px").replace(/-30px/, "-90px");
                    this.style.backgroundPosition = newPos;
    });
    jQuery(btn).children("table").children("tbody").children("tr").children("td.text").each (function (i) {
        this.style.backgroundPosition = "0px -185px";
    });
    jQuery(btn).children("table").children("tbody").children("tr").children("td").children("div.up").hide();
    if (overridehtml != null) {
        jQuery(btn).children("table").children("tbody").children("tr").children("td").children("div.down").html(overridehtml);
    }
    jQuery(btn).children("table").children("tbody").children("tr").children("td").children("div.down").show();
    jQuery(btn).attr("disabled", true);
    jQuery(btn).children("table").children("tbody").children("tr").children("td").children("div").attr("disabled", false);
    
    jQuery(btn).unbind('hover').unbind('mouseenter').unbind('mouseleave').unbind('click').unbind('mousedown').unbind('mouseup');

    jQuery(btn).each(
        function (i) {
            this.blur();
        }
    );
}
function bindKykButton(buttonid)
{
    var elementid = "";
    if (buttonid == null) {
        elementid = "button.kykbtn";
    } else {
        elementid = buttonid;
    }
    jQuery(elementid).hover(
        function () {
        	jQuery(this).children("table").children("tbody").children("tr").each(function (i) {
                var oldPos = this.style.backgroundPosition;
                var newPos = this.style.backgroundPosition.replace(/^0px/, "-30px").replace(/^-60px/,"-30px")
                this.style.backgroundPosition = newPos;
            });
            jQuery(this).children("table").children("tbody").children("tr").children("td.text").each(function (i) {
                //alert('hover out');
                this.style.backgroundPosition = "0px -111px"
            });
        },
        function () {
        	jQuery(this).children("table").children("tbody").children("tr").children("td.sideimg").each(function (i) {
                var newPos = this.style.backgroundPosition.replace(/-30px/, "0px").replace(/-60px/, "0px");
                this.style.backgroundPosition = newPos;
            });
            jQuery(this).children("table").children("tbody").children("tr").children("td.text").each(function (i) {
                this.style.backgroundPosition = "0px -74px"
            });
        }
    );
    jQuery(elementid).bind("mousedown",
        function (e) {
    		jQuery(this).children("table").children("tbody").children("tr").children("td.sideimg").each(function (i) {
                var newPos = this.style.backgroundPosition.replace(/-30px/, "-60px")
                this.style.backgroundPosition = newPos;
            });
            jQuery(this).children("table").children("tbody").children("tr").children("td.text").each(function (i) {
                this.style.backgroundPosition = "0px -148px";
            });
    });

    if (buttonid == null) {
        jQuery("button.kykbtnsingleclick").bind("click",
            function (e) {
                jQuery(this).addClass("disabledKayakBtn");
                kykButtonClicked(this);
            }
        );
    }


    // try to fix width
    jQuery(elementid).children("table").each(function(i) {
        try {
            //ONLY NEEDED FOR IE (EXCEPT IE 8.0 STANDARDS MODE)
            if (navigator.appVersion.indexOf("MSIE")!=-1) {
                //Should be the BUTTON object
                this.parentElement.style.width = this.offsetWidth + "px";
                this.parentElement.style.hight = this.offsetHeight + "px";
            }
        } catch (ignored) {
        }

    });

}
function showCountryList(showCurrency)
{
   var popup = (document.getElementById("currentCountry") == null)? true : false;
   if(popup){
	   var mydata = "action=countrylist&showCurr="+showCurrency;
	   jQuery.ajax({
	        type: "POST",
	        url: "/s/toolbox",
	        data: mydata,
	        dataType: "html",
	        success: function(html) {
		   		try {
		   			
		   			jQuery("#countryList").html(html);
		   			loadCCCpicker();
		   		}catch (ignored) {}
	   		},
	   		error: function(request, textStatus, error) {
	   			alert(textStatus);
	   		},
	   		cache: false
	   		});
   }
}

// attach to the onmousedown event of links if you want to obscure the redirect page
function rewriteRedirect(e, hash)
{
	if (hash) {
		suffix = "&h=" + hash;
	} else {
		suffix = "";
	}
	
    e = jQuery(e);
    e.attr("href", "/out?url=" + encodeURI(e.attr("href")) + suffix);
    return true;
}

if (typeof(jQuery) != typeof(undefined)) {
    jQuery(function() { bindKykButton(); });
}
