//
// file: tripadvisor.js.m4
//   common functions

var ie = (navigator.appName.indexOf("Microsoft Internet Explorer")!=-1);

// func: OnSelectDestination
function OnSelectDestination ( newURL )
{
    if ( newURL != "" )
    if ( newURL != "none")
    location.href = newURL;
}

// func: submitForm
function submitForm(name)
{
    eval("document." + name + ".submit()"); return;
}

// func: showHideButton
function showHideButton(offlayer, onlayer) {
  //alert('on = ' + onlayer + ' off = ' + offlayer);
  document.getElementById(offlayer).style.display = "none";
  document.getElementById(onlayer).style.display = "block";
}

// func: submitNewsletter
function submitNewsletter()
{
    document.newsletter.submit();
    self.close();
}

// func: escramble_affiliates
function escramble_affiliates()
{
    var a,b,c;
    a='<a href="ma';
    b='trip';
    a+='ilto:affi';
    b+='advisor.com">Become an affiliate</a>';
    c=unescape('%40');
    d='liates';
    document.write(a+d+c+b);
}

// func: showYesNoButton
function showYesNoButton(rUrl, uId, yesno, yesnoImage, value)
{
    // value is either 1 for 'Yes' or 0 for 'No';
    var buttonPath = yesnoImage;
    var rateURL;
    rateURL = rUrl + '&rateValue=' + value;
    var imgTag = "<img src='" + buttonPath + "' hspace='2' vspace='2' " +
    "alt='" + yesno + "' style='cursor:pointer;'  align='absmiddle' " +
    "onclick='sendUserRating(\"" + rateURL + "\",\"" + uId + "\")'>";
    document.write(imgTag);
}

// func: showYesNoLink
function showYesNoLink(rUrl, uId, yesno, value)
{
    // value is either 1 for 'Yes' or 0 for 'No';
    var rateURL;
    rateURL = rUrl + '&rateValue=' + value;
    var yesnoLink = "<span style='color:blue; text-decoration:underline; cursor:pointer;' " +
    "onclick='sendUserRating(\"" + rateURL + "\",\"" + uId + "\")'>" + yesno + "</span>";
    document.write(yesnoLink);
}

// func: sendUserRating
function sendUserRating(rateUrl, id)
{
    var idName = 'RatingFrame' + id;
    // treat an iframe as frame instead of the DOM element.
    var iframe = frames[idName];
    if (!iframe && document.layers && document.layers[idName])
    {
        iframe = document.layers[idName];
    }
    else if (!iframe && document.all && document.all[idName])
    {
        iframe = document.all[idName];
    }
    if (!iframe)
    {   // Bug 4148: the following works on most browsers except NS on Mac and AOL on Mac.
        // So we don't use it unless the frame model does not work.
        iframe = document.getElementById(idName);
        if (iframe)
        iframe.src = rateUrl;
    }
    else // this fixes the bug 4148. Treat an iframe as frame instead of the DOM element.
    {
        iframe.location.href = rateUrl;
    }
}
// criteria hotel class and price

// func: goToHoelPage
function goToHotelPage(url, prefix)
{
    var tgtUrl = prefix + url;
    top.location.href = tgtUrl;
}

// func: setVendorStatus
function setVendorStatus(sVendor)
{
    if(sVendor == null || sVendor == "")
    {
        return ss("Click for details");
    }
    else
    {
        return ss(sVendor);
    }
}

// func: ss
function ss(w)
{
    window.status=w; return true;
}

// func: cs
function cs()
{
    window.status='';
}

// func: ga
function ga(o,e)
{
    if (document.getElementById)
    {
        a=o.id.substring(1);
        p = "";
        r = "";
        g = e.target;
        if (g)
        {
            t = g.id;
            f = g.parentNode;
            if (f)
            {
                p = f.id;
                h = f.parentNode;
                if (h) r = h.id;
            }
        }
        else
        {
            h = e.srcElement;
            f = h.parentNode;
            if (f) p = f.id;
            t = h.id;
        }
        if (t==a || p==a || r==a)
        return true;
        window.open(document.getElementById(a).href)
    }
}

// func: showObsoleteWarning
function showObsoleteWarning(mode)
{
    cookie = getCookie('OBW');
    if (cookie == null)
    {
        setCookie('OBW', '1', '1');
        document.write('<br />');
        if (mode == 'ob'){
          document.write('<table border="0" width="98%" cellspacing="0" cellpadding="10" bgcolor="#FFCC33" align="center">');
        }
        else{
          document.write('<table border="0" width="98%" cellspacing="0" cellpadding="10" bgcolor="#EEEEEE" align="center">');
        }
        document.write('<tr>');
        document.write('<td class="dt1"> ');
        document.write('<b>');
        if (mode == 'ob'){
          document.write(sObsoleteBrowser);
        }
        else{
          document.write(sUnsupportedBrowser);
        }

        document.write(" Windows: ");

        document.write('<a rel="nofollow" target="_blank" href="');
        document.write(sIeURL);
        document.write('">Internet Explorer</a>, ');

        document.write('<a rel="nofollow" target="_blank" href="');
        document.write(sFirefoxURL);
        document.write('">Mozilla Firefox</a>. ');

        document.write("Mac: ");

        document.write('<a rel="nofollow" target="_blank" href="');
        document.write(sSafariURL);
        document.write('">Safari</a>');

        document.write('</td>');
        document.write('</tr>');
        document.write('</table>');
        document.write('<br />');
    }
}

// func: padMonth
function padMonth(m)
{
    var s=""+m;
    if (s.length==1) return "0"+s;
    return s;
}

// func: setInDate
function setInDate(d)
{
    setInDateN(d,0);
}

// func: setInDate1
function setInDate1(d)
{
    setInDateN(d,1);
}

// check for hac and vacation advisor forms
// func: setInDateN
function setInDateN(d,n)
{
    var f;
    if (n == 0)
    {
        f = document.HotelAvailabilityComparisonForm;
    } else
    {
        f = document.HacCheckForm;
    }
    if (f) _setInDate(f, d , n);

}

// func: _setInDate
function _setInDate(f, d,n)
{
    f.inDay.selectedIndex=d.getDate()-1;
    for (var i=0; i<f.inMonth.length;i++)
    {
        if (f.inMonth[i].value == padMonth(d.getMonth()+1)+"/"+d.getFullYear())
        {
            f.inMonth.selectedIndex=i;
        }
    }
    if (cal_dcomp(getOutDateN(n), d)<=0)
    {
        var dout=new Date(d);
        dout.setMilliseconds(86400000);
        setOutDateN(dout,n);
    }
}

// func: setOutDate
function setOutDate(d)
{
    setOutDateN(d,0);
}

// func: setOutDate1
function setOutDate1(d)
{
    setOutDateN(d,1);
}

// cehck for hac and vacation advisor forms
// func: setOutDateN
function setOutDateN(d,n)
{
    var f;
    if (n == 0)
    {
        f = document.HotelAvailabilityComparisonForm;
    } else
    {
        f = document.HacCheckForm;
    }
	   if (f) _setOutDate(f, d , n);

}

// func: _setOutDate
function _setOutDate(f, d,n)
{

    f.outDay.selectedIndex=d.getDate()-1;
    for (var i=0; i<f.outMonth.length;i++)
    {
        if (f.outMonth[i].value == padMonth(d.getMonth()+1)+"/"+d.getFullYear())
        {
            f.outMonth.selectedIndex=i;
        }
    }
}

// func: getLastDate
function getLastDate()
{
    var d = new Date();
    d.setFullYear(d.getFullYear()+1);
    d.setDate(1);
    d.setMilliseconds(-86400000);
    return d;
}

// func: getInDate
function getInDate()
{
    return getInDateN(0);
}

// gunc: getInDate1
function getInDate1()
{
    return getInDateN(1);
}

// func: getOutDate
function getOutDate()
{
    return getOutDateN(0);
}

// func: getOutDate1
function getOutDate1()
{
    return getOutDateN(1);
}

// func: getInDateN
function getInDateN(n)
{
    var f;

    if (n == 0)
    {
        f = document.HotelAvailabilityComparisonForm;
    } else
    {
        f = document.HacCheckForm;
    }

    var monY = f.inMonth[f.inMonth.selectedIndex].value.split(/\//);
    return new Date(monY[1],monY[0]-1,f.inDay.selectedIndex+1);
}

// func: getOutDateN
function getOutDateN(n)
{
    var f;
    if (n == 0)
    {
        f = document.HotelAvailabilityComparisonForm;
    } else
    {
        f = document.HacCheckForm;
    }
    var monY = f.outMonth[f.outMonth.selectedIndex].value.split(/\//);
    return new Date(monY[1],monY[0]-1,f.outDay.selectedIndex+1);
}

// func: showHideCurrency
function showHideCurrency()
{
	document.getElementById('ExpandCurrency').style.display = "none";
    document.getElementById('CurrencyBox').style.display = "block";
}

// func: fillRates
function fillRates(currency)
{
   try
   {
      currency = (currency == null) ? "USD" : currency;
      var currencySelect = document.getElementById("currency");
      if (currencySelect)
      {
        currencySelect.value = currency;
      }
      var rateSelect = document.getElementById("minmaxrate").options;
      rateSelect.length = 0;
      var levels = currencyLevel[currency];
      for (var i = 0 ; i < levels.length ; i += 2)
      {
         rateSelect[i/2] = new Option(levels[i], levels[i+1]);
         // if the current max rate is in the minmax value string, select it
         if ( levels[i+1].indexOf(maxRate) > 0)
         {
            rateSelect.selectedIndex = i/2;
         }
      }
   }
   catch(e)
   {
   // form not generated for this page
   }
}

// func: fillRatesAndClear
function fillRatesAndClear(currency)
{
	maxRate = '9999999';
	fillRates(currency);
}

// func: escramble
function escramble(a) {
document.write('<a href="mailto:' + a + unescape('%40') + 'tripadvisor.com">' + a + unescape('%40') + 'tripadvisor.com</a>');
}

// func: escramble for i18n (no hard-coded tripadvisor.com)    
function escrambleI18N(sName, sDomain) {
    document.write('<a href="mailto:' + sName + unescape('%40') + 'tripadvisor' + sDomain + '">' + sName + unescape('%40') + 'tripadvisor' + sDomain + '</a>');
}
    
// func: escramblejobs
function escramblejobs(a,b) {
var a,b;
document.write('<a href="mailto:' + a + unescape('%40') + 'tripadvisor.com' + unescape('?subject=') + b + '">' + a + unescape('%40') + 'tripadvisor.com</a>');
}

// func: checkPopupValue
function checkPopupValue(form, elt, invalid, msg)
{
    try
    {
       var popup = form[elt];
       if (popup.selectedIndex >= 0 &&
           popup.options[popup.selectedIndex].value != invalid)
       {
           return true;
       }
    }
    catch(e)
    {
       // do nothing ;
    }
    alert(msg);
    return false;
}

  // DHTML popup using visibility: visible style.
// func: togglePopup
	function togglePopup(objectID, condition)
	{
	   if(objectID)
	   {

  	   // get a reference to the cross-browser object
	     var myObject = getObject(objectID);

  	   if(myObject)  // make sure the object exists
	     {
         myObject.style.visibility = condition;
         return true;
       }
       else
       {
         // we couldn't find the object, so we can't change its visibility
         return false;
       }
	   }

	} //togglePopup()

// func: getObject
	function getObject(objectID)
	{
	   // cross-browser function to get an object given its id
	   if(document.getElementById && document.getElementById(objectID))
   {
      // W3C DOM
      return document.getElementById(objectID);
   }
   else if(document.all && document.all(objectID))
   {
      // MSIE 4 DOM
      return document.all(objectID);
   }
   else if(document.layers && document.layers[objectID])
   {
      // NN 4 DOM.. note: this won't find nested layers
      return document.layers[objectID];
   }
   else
   {
      return false;
   }
} // getObject()

// func: removePid
//   Remove the PID from a URL Reference - Used in GatedOffer forms to not get the PID
//   to be sent twice
function removePID(sRef)
{
  var iStart;
  var iEnd;
  var sNewRef = sRef;
  try
  {
	  if (sRef.indexOf('pid=') > 0)
	  {
	    iStart = sRef.indexOf('pid=');
	    sNewRef = sRef.substring(0, iStart);
	    iEnd = sRef.indexOf('&', iStart);
	    if (iEnd > 0)
	      sNewRef += sRef.substring(iEnd);
	  }
	  else if (sRef.indexOf('-p') > 0)
	  {
	    iStart = sRef.indexOf('-p')
	    sNewRef = sRef.substring(0, iStart);
	    iEnd = sRef.indexOf('-', iStart + 1);
	    if (iEnd < 0)
	      iEnd = sRef.indexOf('?', iStart + 1);
	    if (iEnd > 0)
	    {
	      sNewRef += sRef.substring(iEnd);
	    }
	  }
	}
	catch(e)
	{
	  sNewRef = sRef;
	}
	return sNewRef;
}

// func: sendPasswordEmail
function sendPasswordEmail(fName, eName)
{
  var form = document.getElementById(fName);
  var elt = document.getElementById(eName);
  if ((form != null) && (elt != null))
  {
    elt.value = 'true';
    form.submit();
  }
  return false;
}

// func: clrSet
    // used for RateThis on HotelReview, AttractionReview, and RestaurantReview
    function clrSet(rating)
    {
        for(var i=1; i<=rating; i++) {
            document.getElementById('ccl_' + i + '_w').style.display = 'none';
            document.getElementById('ccl_' + i + '_y').style.display = 'inline';
        }
        for(var i=5; i>=1 && i>rating; i--) {
            document.getElementById('ccl_' + i + '_w').style.display = 'inline';
            document.getElementById('ccl_' + i + '_y').style.display = 'none';
        }

        for(var i=1; i<6; i++) {
            document.getElementById('ccl_t' + i).style.display = 'none';
        }
        document.getElementById('ccl_t' + rating).style.display = 'inline';

    }

// func: clrSetQR
    // used in same places as clrSet but for the Quick Review dialog
    function clrSetQR(rating)
    {
        for(var i=1; i<=rating; i++) {
            document.getElementById('ccl_' + i + 'qr_w').style.display = 'none';
            document.getElementById('ccl_' + i + 'qr_y').style.display = 'inline';
        }
        for(var i=5; i>=1 && i>rating; i--) {
            document.getElementById('ccl_' + i + 'qr_w').style.display = 'inline';
            document.getElementById('ccl_' + i + 'qr_y').style.display = 'none';
        }
    }

// func: clrOut
    // used for RateThis on HotelReview, AttractionReview, and RestaurantReview
    function clrOut(rating)
    {
        for(var i=1; i<6; i++) {
        document.getElementById('ccl_' + i + '_w').style.display = 'inline';
        document.getElementById('ccl_' + i + '_y').style.display = 'none';
        }
        document.getElementById('ccl_t' + rating).style.display = 'none';
    }

// func: clrOutQR
    // used in same places as clrOut but for the Quick Review dialog
    function clrOutQR(rating)
    {
	rating = document.getElementById('qr_rating').value;
	clrOut(rating);
	clrSetQR(rating);
    }

// func: wrtTRvw
    // used for RateThis on HotelReview, AttractionReview, and RestaurantReview
    function wrtTRvw(rating)
    {
        if (rating > 0 && rating < 6)
        {
            unobf(rateUrl[rating - 1]);
        }

    }

// func: wrtTRvw2
    // used for RateThis on HotelReview, AttractionReview, and RestaurantReview
    // in-page review creation seen on .de
    function wrtTRvw2(rating)
    {
        if (rating > 0 && rating < 6)
        {
            var popup = document.getElementById('QRFPOPUP');
            var qrForm = document.getElementById('qrFormContent');
            setPID(186);
            if(qrForm.innerHTML == '')
            {
               qrPingController("qrForm");
                var req = new HttpRpc("/UserReviewController", 
                        function (req) { alert('error: ' + req.responseText); },
                        function(reply) {
                            qrForm.innerHTML = reply.responseText;
                            qrFillYear();
                            wrtTRvwQR(rating);
                            popup.style.display = 'block';
                            qrCenterDiv(popup);
                            document.getElementById('qrfieframe').style.display='block';
                        }, null, "POST", false);
                var svFrom = document.getElementById('qr_svFrom').value;
                req.sendRequest('a=qrForm&svFrom='+svFrom);
            } else {
                wrtTRvwQR(rating);
                popup.style.display = 'block';
                qrCenterDiv(popup);
                document.getElementById('qrfieframe').style.display='block';
            }
        }
    }

// func: wrtTRvwQR
    // Same as wrtTRvw but used in the Quick Review dialog
    function wrtTRvwQR(rating)
    {
        if (rating > 0 && rating < 6)
        {
		document.getElementById('qr_rating').value = rating;
        }
	clrOutQR(rating);
    }

// func: qrClose
    // Closes the Quick Review DHTML pop-up
    function qrClose()
    {
	document.getElementById('QRFPOPUP').style.display = 'none';
        document.getElementById('qrfieframe').style.display='none';
    }

// func: unobf
    function unobf(sUrl)
    {
        // can have NOFOLLOW (absolute reference) otherwise it is a relative url
        if (sUrl.substr(0,8) == "NOFOLLOW")
        {
            window.parent.location.href = "http://" + sUrl.substr(8) + ".html";
        }
        else
        {
            window.parent.location.href = "/" + sUrl + ".html";
        }
    }

// func: findPos
function findPos(obj)
{
	var curleft = curtop = 0;
	if (obj.offsetParent)
	{
		curleft = obj.offsetLeft
		curtop = obj.offsetTop
		while (obj = obj.offsetParent)
		{
			curleft += obj.offsetLeft
			curtop += obj.offsetTop
		}
	}

	return [curleft,curtop];
}

// func: getSize
//   Cross-browser function to get the size of an element.
function getSize(obj)
{
  obj = $(obj);
  var w = obj.clientWidth ? obj.clientWidth : obj.offsetWidth;
  var h = obj.clientHeight ? obj.clientHeight : obj.offsetHeight;
  return [w,h];
}

// func: slideDown
//   Animate an element to 'slide' down.
//
// Parameters:
//   elem - container div
//   contents - div with the contents to appear
//   duration - duration of animation in ms
//   callback - function to call when animation completes
//   fps - tweak animation smoothness
function slideDown(elem, contents, duration, callback, fps)
{
  // parameter defaults
  if (!fps) fps = 20;

  // make sure we have the actual objects
  elem = $(elem);
  contents = $(contents);

  // make the necessary calculations
  var distance = getSize(contents)[1];
  var steps = Math.round(fps * (duration / 1000));
  var x = Math.round(distance / steps);

  // increase the view window
  var height = parseInt(elem.style.height.replace(/px/,''));
  elem.style.height = (height + x) + 'px';

  // call self in a bit to make the next step
  if (height + x < distance)
    setTimeout(function(){slideDown(elem, contents, duration, callback, fps);}, Math.round(1000 / fps));
  else if (callback)
    callback();

}

// func: slideLeft
//   Animate an element to 'slide' left.
//
// Parameters:
//   elem - container div
//   contents - div with the contents to appear
//   duration - duration of animation in ms
//   callback - function to call when animation completes
//   fps - tweak animation smoothness
function slideLeft(elem, contents, duration, callback, fps)
{
  // parameter defaults
  if (!fps) fps = 20;

  // make sure we have the actual objects
  elem = $(elem);
  var distance;
  if (typeof(contents) == "object") {
    distance = getSize(contents[0])[0];
    distance += contents[1];
  } else {
    distance = getSize(contents)[0];
  }

  // make the necessary calculations
  var steps = Math.round(fps * (duration / 1000));
  var x = Math.round(distance / steps);

  // increase the view window
  var width = parseInt(elem.style.width.replace(/px/,''));
  var left = parseInt(elem.style.left.replace(/px/,''));
  elem.style.width = (width + x) + 'px';
  elem.style.left = (left - x) + 'px';

  // call self in a bit to make the next step
  if (width + x < distance) {
    setTimeout(function(){slideLeft(elem, contents, duration, callback, fps);}, Math.round(1000 / fps));
  } else if (callback) {
    callback();
  }
}

// func: getScrollOffset
function getScrollOffset()
{
  var scrOfX = 0, scrOfY = 0;
  if( typeof( window.pageYOffset ) == 'number' ) {
    //Netscape compliant
    scrOfY = window.pageYOffset;
    scrOfX = window.pageXOffset;
  } else if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) ) {
    //DOM compliant
    scrOfY = document.body.scrollTop;
    scrOfX = document.body.scrollLeft;
  } else if( document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) ) {
    //IE6 standards compliant mode
    scrOfY = document.documentElement.scrollTop;
    scrOfX = document.documentElement.scrollLeft;
  }
  return [ scrOfX, scrOfY ];
}

// func: getEventPosition
function getEventPosition(event)
{
  if (!event && window.event)
    event = window.event;
  var x = y = 0;
  if (event.clientX) {
    x = event.clientX;
    y = event.clientY;
  } else if (event.pageX) {
    x = event.pageX;
    y = event.pageY;
  }
  return [x,y];
}

// func: getEventRelativePosition
function getEventRelativePosition(event)
{
  var x = y = 0;
  if (event.offsetX) {
    x = event.offsetX;
    y = event.offsetY;
  } else if (event.layerX) {
    x = event.layerX;
    y = event.layerY;
  }
  return [x,y];
}

// func: $
// convenience method from prototype
function $() {
  var elements = new Array();

  for (var i = 0; i < arguments.length; i++) {
    var element = arguments[i];
    if (typeof element == 'string')
      element = document.getElementById(element);

    if (arguments.length == 1)
      return element;

    elements.push(element);
  }

  return elements;
}

// func: display
function display(val,list)
{
  for (var i = 0; i < list.length; i++) {
    var ele = $(list[i]);
    if (ele && ele.style) ele.style.display = val;
  }
}

// func: show
function show() {display('block',arguments);}

// func: hide
function hide() {display('none',arguments);}

// func: inline
function inline() {display('inline',arguments);}

// func: expandChangeClass
function expandChangeClass(target, source, shownClass, hiddenClass)
{
  target = $(target);
  source = $(source);
  if (target.style.display == 'block') {
    source.className = hiddenClass;
    target.style.display = 'none';
  }
  else {
    source.className = shownClass;
    target.style.display = 'block';
  }
}

// func: withinBounds
//   test if the mouse is inside the given bounds
function withinBounds(e, bounds)
{
  var eventPos = getEventPosition(e);// x, y
  return (eventPos[0] >= bounds[3] && eventPos[0] <= bounds[1] && eventPos[1] >= bounds[0] && eventPos[1] <= bounds[2]);
}

// func: isIn
//   test if the mouse is inside the bounds of the given element
function isIn(eventPos, ele, bounds)
{
  var off = getScrollOffset();

  ele = $(ele);
  var pos = findPos(ele);
  // calculate element bounts
  var l = pos[0] - off[0];
  var t = pos[1] - off[1];
  var r = l + ele.clientWidth;
  var b = t + ele.clientHeight;

  if (bounds) {
    if (typeof(bounds) == "number") {
      l = l - bounds;
      t = t - bounds;
      r = r + bounds;
      b = b + bounds;
    }
    else if (bounds instanceof Array && (bounds.length == 2 || bounds.length == 4)) {
      t = t - bounds[0];
      r = r + bounds[1];
      l = l - (bounds.length == 4 ? bounds[3] : bounds[1]);
      b = b + (bounds.length == 4 ? bounds[2] : bounds[0]);
    }
  }

  //alert("x="+eventPos[0]+", y="+eventPos[1]+", "+elem+" l="+l+", r="+r+", t="+t+", b="+b);
  return (eventPos[0] >= l && eventPos[0] <= r && eventPos[1] >= t && eventPos[1] <= b);
}

// func: hideIfNotIn
//   hide target element if the mouse in not within the bounds of target
//   or any other element given
function hideIfNotIn(e, tgt)
{
  var pos = getEventPosition(e);
  var inside = false;
  for (var i = 1; !inside && i < arguments.length; i++) {
    if (i + 1 < arguments.length && (typeof(arguments[i+1]) == "number" || arguments[i+1] instanceof Array)) {
      inside = isIn(pos, arguments[i], arguments[i+1]);
      i++;
    }
    else {
      inside = isIn(pos, arguments[i]);
    }
  }
  if (!inside) {hide(tgt);}
}

// func: addMargins
//   adds margins to the given bounds, just like CSS.
//   if margins is a number, the bounding box is increased on all sides by number.
//   if margins is an array of 2 numbers, the first increases the top and bottom bounds,
//     the second increases the left and right bounds
//   if margins is an array of 4 numbers, the bounds are increased by [top, right, bottom, left]
function addMargins(bounds, margins)
{
  if (bounds.length != 4) {return bounds;}
  if (typeof(margins) == "number") {
    bounds[0] -= margins;
    bounds[1] += margins;
    bounds[2] += margins;
    bounds[3] -= margins;
  }
  else if (margins instanceof Array && (margins.length == 2 || margins.length == 4)) {
    bounds[0] -= margins[0];
    bounds[1] += margins[1];
    bounds[2] += margins.length == 4 ? margins[2] : margins[0];
    bounds[3] -= margins.length == 4 ? margins[3] : margins[1];
  }
  return bounds;
}

// func: findBounds
//   finds the bounds of a given element, increasing the box by margins if specified
function findBounds(elem, margins)
{
  elem = $(elem);
  var bounds = new Array(4);
  var pos = findPos(elem); // left, top
  var off = getScrollOffset();
  var size = getSize(elem);
  bounds[0] = pos[1] - off[1];
  bounds[3] = pos[0] - off[0];
  bounds[1] = bounds[3] + size[0];
  bounds[2] = bounds[0] + size[1];

  if (margins) {
    bounds = addMargins(bounds, margins);
  }

  return bounds;
}

var bubbleBounds; // top, right, bottom, left
var bubbleElem;
var bubbleOrigMM;
var bubbleTimeout;
var bubbleAnimating = false; // animation flag

// func: showBubble
//   shows the given bubble after 200ms (delegates to _showBubble)
function showBubble()
{
  if (bubbleAnimating) {return;}
  var args = arguments;
  bubbleTimeout = setTimeout(function(){_showBubble(args);},200);
}

// func: cacnelBubble
//   cancels the timeout on showing a bubble in case the user just runs the mouse over
//    the trigger element quickly
function cancelBubble()
{
  clearTimeout(bubbleTimeout);
}

// func: _showBubble
//   first param should be the bubble to show, second can optionally be a margins
//   additional parameters increase the size of the bounding box to include to element
//   and (optionally) following margins.
//   This method uses a mouse listener for more precise sampling. hideBubble() set as
//   the mousemove listener to hide the bubble when the mouse moves outside the bounds.
function _showBubble()
{
  myargs = arguments[0];
  bubbleElem = $(myargs[0]);
  show(bubbleElem);
  bubbleBounds = findBounds(bubbleElem, myargs.length > 1 ? myargs[1] : null);
  for (var i = 1; i < myargs.length; i++) {
    if (typeof(myargs[i]) == "string" || typeof(myargs[i]) == "object") {
      bounds = findBounds(myargs[i], myargs.length > i ? myargs[i+1] : null);
      bubbleBounds[0] = Math.min(bubbleBounds[0], bounds[0]);
      bubbleBounds[1] = Math.max(bubbleBounds[1], bounds[1]);
      bubbleBounds[2] = Math.max(bubbleBounds[2], bounds[2]);
      bubbleBounds[3] = Math.min(bubbleBounds[3], bounds[3]);
    }
  }

  bubbleOrigMM = document.body.onmousemove;
  document.body.onmousemove = hideBubble;
}

// func: hideBubble
//   hides the bubble if the mouse moves outside the bounding box
function hideBubble(e)
{
  if (!e && window.event) {
    var e = window.event;
  }

  if (bubbleBounds != null && !withinBounds(e, bubbleBounds)) {
    document.body.onmousemove = bubbleOrigMM;
    hide(bubbleElem);
    bubbleBounds = null;
    bubbleElem = null;
    bubbleOrigMM = null;
  }
}

// func: getElementsByClassName
//   Written by Jonathan Snook, http://www.snook.ca/jonathan
//   Add-ons by Robert Nyman, http://www.robertnyman.com
function getElementsByClassName(oElm, strTagName, strClassName)
{
	var arrElements = (strTagName == "*" && oElm.all)? oElm.all : oElm.getElementsByTagName(strTagName);
	var arrReturnElements = new Array();
	strClassName = strClassName.replace(/-/g, "\-");
	var oRegExp = new RegExp("(^|\\s)" + strClassName + "(\\s|$)");
	var oElement;
	for(var i=0; i<arrElements.length; i++){
		oElement = arrElements[i];
		if(oRegExp.test(oElement.className)){
			arrReturnElements.push(oElement);
		}
	}
	return arrReturnElements;
}

//
// section: Window functions
//

// func: getWindowSize
//   Cross-browser function to get the size of the browser window
//
function getWindowSize()
{
  var w = 0, h = 0;
  if (typeof(window.innerWidth) == 'number') {
    // Non-IE
    w = window.innerWidth;
    h = window.innerHeight;
  }
  else if (document.documentElement &&
    (document.documentElement.clientWidth || document.documentElement.clientHeight)) {
    // IE 6+ in 'standards compliant mode'
    w = document.documentElement.clientWidth;
    h = document.documentElement.clientHeight;
  }
  else if (document.body && (document.body.clientWidth || document.body.clientHeight)) {
    // IE 4 compatible
    w = document.body.clientWidth;
    h = document.body.clientHeight;
  }
  return {width: w, height: h};
}

function centerMe(element)
{
  var dlg = $(element);
  var wSize = getWindowSize();
  var scrOff = getScrollOffset();
  var dlgSize = getSize(dlg);
  var l = (Math.round((wSize.width  - dlgSize[0]) / 2) + scrOff[0]);
  var r = (Math.round((wSize.height - dlgSize[1]) / 2) + scrOff[1]);
  dlg.style.left = l + "px";
  dlg.style.top = r + "px";
  return [l,r,dlgSize[0],dlgSize[1]];
}

//
// section: Drag 'n Drop functions
//

var dragObj = {el: null, elX: -1, elY: -1, mouseX: -1, mouseY: -1, zIndex: 5120};

function handleDrag(event)
{
  var pos = getEventPosition(event);
  dragObj.el.style.left = dragObj.elX + pos[0] - dragObj.mouseX + "px";
  dragObj.el.style.top  = dragObj.elY + pos[1] - dragObj.mouseY + "px";
  if (dragObj.el.style.left.replace(/px/,'') < 0) dragObj.el.style.left = '0px';
  if (dragObj.el.style.top.replace(/px/,'')  < 0) dragObj.el.style.top  = '0px';
  if(ie)
  {
	  var dragId = dragObj.el.id;
	  if(typeof dragId != 'undefined')
	  {
	  	var dragIframeId = dragId + "Iframe";
	  	if(typeof $(dragIframeId) != 'undefined')
	  	{
	  		$(dragIframeId).style.left = dragObj.elX + pos[0] - dragObj.mouseX + "px";
	  		$(dragIframeId).style.top  = dragObj.elY + pos[1] - dragObj.mouseY + "px";
		    if ($(dragIframeId).style.left.replace(/px/,'') < 0) $(dragIframeId).style.left = '0px';
		    if ($(dragIframeId).style.top.replace(/px/,'')  < 0) $(dragIframeId).style.top  = '0px';
	  	}
	  }
  }
  
  hide('confirmBubble');

  if (window.event) {
    window.event.cancelBubble = true;
    window.event.returnValue = false;
  }
  else
    event.preventDefault();
}

function startDrag(event, container)
{
  if (container)
    dragObj.el = $(container);
  else if (window.event)
    dragObj.el = window.event.srcElement;
  else if (event.target)
    dragObj.el = event.target
  if (dragObj.el.nodeType == 3)
    dragObj.el = dragObj.el.parentNode;  

  var ePos = getEventPosition(event);
  dragObj.mouseX = ePos[0];
  dragObj.mouseY = ePos[1];
  var pos = findPos(dragObj.el);
  dragObj.elX = pos[0];
  dragObj.elY = pos[1];
  dragObj.el.style.zIndex = dragObj.zIndex++;

  if (document.attachEvent) {
    document.attachEvent("onmousemove", handleDrag);
    document.attachEvent("onmouseup",   stopDrag);
    window.event.cancelBubble = true;
    window.event.returnValue  = false;
  }
  else {
    document.addEventListener("mousemove", handleDrag, true);
    document.addEventListener("mouseup",   stopDrag,   true);
    event.preventDefault();
  }
}

function stopDrag()
{
  if (document.detachEvent) {
    document.detachEvent("onmousemove", handleDrag);
    document.detachEvent("onmouseup",   stopDrag);
  }
  else {
    document.removeEventListener("mousemove", handleDrag, true);
    document.removeEventListener("mouseup",   stopDrag,   true);
  }
}

//
// section: Dialog functions
//

var floater;

// func: FloatingDialog
//   Shows a styled DHTML floating dialog.
//
// Paramters:
//   content - content of the dialog, should be a string.
//
function FloatingDialog(content)
{
  var dlg = floater;
  if (dlg == null) {
    var dlg = document.createElement('div');
    floater = dlg;
  }
  dlg.id = 'floater';
  dlg.style.width = '400px';
  dlg.style.position = 'absolute';
  dlg.style.zIndex = dragObj.zIndex;
  // position it offscreen to get the size so we can center properly
  // also make sure to position at the current scroll offset, otherwise
  // it causes the browser to scroll to the top, throwing off the centering
  dlg.style.left =' -5000px';
  var scrOff = getScrollOffset();
  dlg.style.top = scrOff[1] + 'px';
  dlg.style.display = 'block';
  dlg.innerHTML = content;
  document.body.appendChild(dlg);
  var offsets = centerMe(dlg);

  if(ie) {
	  var iFr=document.createElement("IFRAME");
	  iFr.id="floaterIframe";
	  iFr.style.zIndex = dragObj.zIndex-1;
	  iFr.style.borderWidth = 0;
	  iFr.style.position="absolute";
	  iFr.style.display="block";
	  iFr.style.left=offsets[0] + 'px';
	  iFr.style.top=offsets[1] + 'px';
	  iFr.style.width = offsets[2] + "px";
	  iFr.style.height = offsets[3] + "px";
	  document.body.appendChild(iFr);
  }
  var draggable = getElementsByClassName(dlg, '*', 'draggable');
  for (var i in draggable) {
    draggable[i].onmousedown = function(event) {startDrag(event, dlg);}
  }
}

function closeFloater()
{
  if (floater) hide(floater);
  if($('floaterIframe'))
  {
  	document.body.removeChild($('floaterIframe'));
  }
  return false;
}

//
// section: Community functions
//

function enableCommunity(callback, noHandle)
{
  var res;
  if (!noHandle)
    res = function(r) {enableCommunityResponse(r, callback);}
  else res = callback;
  AjaxRequest('/CommunityAjax', 'err:', ['action', 'CommunitySet', 'set', 'on'], res);
}

function enableCommunityResponse(res, callback) {
  in_data = eval("(" + res.responseText + ")");
  if (in_data.error) {
    document.getElementById('inviteStatusField').innerHTML = in_data.error;
    document.getElementById('inviteStatusField').style.display='block';
  } else if (in_data.response) {
    document.getElementById('inviteStatusField').innerHTML = in_data.response;
    document.getElementById('inviteStatusField').style.display='block';
    setTimeout(function() {hide('confirmBubble'); callback();}, 1000);
  }
}

//
// section: AJAX functions
//

// var: AjaxResponseDialog
//   Use as responseFunc for HttpRpc call. Returned text is shown in the dialog.
//
var AjaxResponseDialog = function(req) { FloatingDialog(req.responseText); evalScripts(req.responseText); }

var sendMessageAjaxResponseDialog = function(req) {
    AjaxResponseDialog(req);
    if (typeof window['callback_ShowRecaptcha'] != 'undefined')
    {
        var cbfn = window['callback_ShowRecaptcha'];
        cbfn();
    }
}

function AjaxResponseBubble(elmt)
{
  return function(req) {
    dialogBubble(elmt, 0, 2, req.responseText);
    evalScripts(req.responseText);
  }
}

// func: AjaxUpdateLogin
//   Makes a call to login and AjaxUpdate.
//   Note that this does *not* wait until the login processess finishes
//   to call AjaxUpdate.
function AjaxUpdateLogin(target, url, errMsg, parameters, responseFunc)
{
    var relUrl = url.substring(url.indexOf('/',7)); 
    var errFunc = function(req) { /* alert(errMsg+"\n"+req.responseText); */ }
    var resFunc = function(req) {
        txt = req.responseText;
        //evalScripts(req.responseText);
        var bWasLoggedIn = (txt.indexOf('<!--nologin-->')<0);
        if(!bWasLoggedIn)
        {
            login(['tt','ajax','returnTo', escape(relUrl), 'greeting', 'showuserreviews_vote_25ed']);
        }
        else
        {
            $(target).innerHTML = txt;
        }
        if (responseFunc) {responseFunc();}
    }

    var req = new HttpRpc(url, errFunc, resFunc);
    if (parameters) {
        params = new UrlParams();
        for (var i = 0; i < parameters.length; i += 2) {
          params.add(parameters[i], parameters[i+1]);
        }
        req.sendRequest(params.toString());
    }
    else req.sendRequest();
    return false;
}

// func: AjaxUpdate
//   Replaces the contents of an element with the result of the AJAX call, if it succeeds. Shows an alert if it fails.
//   responseFunc is called on success AFTER the target is updated.
//
// Parameters:
//   target - element to update
//   url - url to retrieve
//   errMsg - prepended to alert on failure
//   parameters - built with UrlParams and passed to sendRequest
//   responseFunc - function to call on success
//
function AjaxUpdate(target, url, errMsg, parameters, responseFunc, errFunc)
{
  if (!errFunc) errFunc = function(req) {alert(errMsg+"\n"+req.responseText);}
  var resFunc = function(req) {
    $(target).innerHTML = req.responseText;
    evalScripts(req.responseText);
    if (responseFunc) {responseFunc();}
  }

  var req = new HttpRpc(url, errFunc, resFunc);
  if (parameters) {
    params = new UrlParams();
    for (var i = 0; i < parameters.length; i += 2) {
      params.add(parameters[i], parameters[i+1]);
    }
    req.sendRequest(params.toString());
  }
  else req.sendRequest();
  return false;
}

// func: AjaxRequest
//   Makes an request to the given url. responseFunc will be called with the request if the
//   call was successful, errMsg will be shown with an alert if not.
//
// Parameters:
//   url - url to retrieve
//   errMsg - prepended to alert on failure
//   parameters - built with UrlParams and passed to sendRequest
//   responseFunc - function to call on success
//
function AjaxRequest(url, errMsg, parameters, responseFunc)
{
  var errFunc = function(req) {alert(errMsg+"\n"+req.responseText);}
  var req = new HttpRpc(url, errFunc, responseFunc);
  if (parameters) {
    params = new UrlParams();
    for (var i = 0; i < parameters.length; i += 2) {
      params.add(parameters[i], parameters[i+1]);
    }
    req.sendRequest(params.toString());
  }
  else req.sendRequest();
  return false;
}

// func: serializeForm
//   Creates an array of all the form fields and their values suitable for passing into the
// AjaxRequest or AjaxUpdate functions.
function serializeForm(id)
{
  var f = $(id);
  params = new Array;
  for (var i = 0; i < f.elements.length; i++) {
    var elem = f.elements[i];
    if (elem.type == "radio") { // only include radio buttons if they're checked
      if (elem.checked) {
        params.push(elem.name);
        params.push(elem.value);
      }
    }
    else if (elem.type == "checkbox") { // only include checkboxes if they're checked
      if (elem.checked) {
        params.push(elem.name);
        params.push(elem.value);
      }
    }
    else {
      params.push(elem.name);
      params.push(elem.value);
    }
  }
  return params;
}

// func: evalScripts
//   Looks for all script tags the given elements contains and evals their contents.
var ScriptFragment = '(?:<script.*?>)((\n|\r|.)*?)(?:<\/script>)';
function evalScripts(code)
{
  var matchAll = new RegExp(ScriptFragment, 'img');
  var matchOne = new RegExp(ScriptFragment, 'im');
  var matches = code.match(matchAll);
  if (matches) {
    for (var i=0; i<matches.length; i++) {
      var m = matches[i].match(matchOne);
      if (m) eval(m[1]);
    }
  }
}

//
// section: Cookie functions
//

// func: getCookie
//   Gets the value of a cookie.
//
// Parameters:
//   name - name of the cookie
//
// Returns:
//   The value of the cookie or null if the cookie could not be found.
//
function getCookie(name)
{
    var sCookies = document.cookie;
    var sPrefix = name + '=';
    if(sCookies == null)
    {
        return null;
    }
    var nBegin = sCookies.indexOf('; ' + sPrefix);
    if(nBegin == -1)
    {
        nBegin = sCookies.indexOf(sPrefix);
        if(nBegin == -1)
        {
            return null;
        }
    }
    else
    {
        nBegin += 2;
    }
    var nEnd = sCookies.indexOf(';', nBegin);
    if(nEnd == -1)
    {
        nEnd = sCookies.length;
    }
    return unescape(sCookies.substring(nBegin + sPrefix.length, nEnd));
}

// func: setPID
//   Sets the NPID cookie value
//
// Parameters:
//   sValue - new cookie value
//
function setPID(sValue)
{
    setCookie('NPID', sValue, -1);
}

function setPMCookies(sGuid, sMsgType)
{
  setCookie('sendPM', sGuid);
  setCookie('messagetype', sMsgType);
}

// func: setCookie
//   Sets a cookie.
//
// Parameters:
//   sName - name of the cookie to set
//   sValue - value of the cookie
//   nDays - expiration time (in days)
//
function setCookie(sName, sValue, nDays, domain)
{
    var dExpires = null;
    if ((nDays > 0) || (nDays < -1))
    {
        dExpires = new Date();
        dExpires.setTime(dExpires.getTime() + (nDays * 24 * 3600 * 1000));
    }
    else if (nDays == -1)
    {
        dExpires = new Date();
        dExpires.setTime(dExpires.getTime() + (5 * 1000));
    }

    var sCookie = sName + "=" + escape(sValue) +
    ((dExpires == null) ? "" : "; expires="
    + dExpires.toGMTString())
    + "; path=/";
    if (typeof domain != 'undefined') {
        sCookie += "; domain=" + domain;
    }
    document.cookie = sCookie;
}

// func: setBlackout
//   Sets the NLPB cookie to 1.
//
function setBlackout()
{
    document.cookie = 'NLPB=true';
    setCookie('NLPB', 'true', 1);
}

// func: doCookieCheck
//   Checks that none of the newsletter cookies are set.
//
// Returns:
//   true if none of the cookies are set, false otherwise
//
function doCookieCheck()
{
    var sCookie = getCookie('NLPB');
    if(sCookie != null)
    {
        return false;
    }
    sCookie = getCookie('NLPS');
    if(sCookie != null)
    {
        return false;
    }
    sCookie = getCookie('NLPP');
    if(sCookie != null)
    {
        return false;
    }
    // Session cookies not accepted
    setCookie('NLPS', 'true', 0);
    sCookie = getCookie('NLPS');
    if(sCookie == null)
    {
        return false;
    }
    setCookie('NLPP', 'true', 1/2);
    return true;
}

//
// section: Event functions
//

// func: getMouseY
//   Cross-browser function to get the position of the mouse in the document when the event ocurred.
//
// Params:
//   e - the event
//
// Returns:
//   20 + the Y position
//
function getMouseY(e)
{
    if (!e && window.event) var e = window.event;
    if (e && e.pageY) return e.pageY+20;
    if (e && e.clientY) return e.clientY + document.body.scrollTop+20;
    return 50;
}

// func: getMouseX
//   Cross-browser function to get the position of the mouse in the document when the event ocurred.
//
// Params:
//   e - the event
//
// Returns:
//   The X position
//
function getMouseX(e)
{
    if (!e && window.event) var e = window.event;
    if (e && e.pageX) return e.pageX;
    if (e && e.clientX) return e.clientX + document.body.scrollLeft;
    return 50;
}

// func: getTarget
//   Cross-browser function to get the target of the event.
//
// Parameters:
//   e - the event
//
// Returns:
//   The Element that fired the event
//
function getTarget(e)
{
  var targ;
  if (e.target) {targ = e.target;}
  else if (e.srcElement) {targ = e.srcElement;}
  if (targ.nodeType == 3) {targ = targ.parentNode;} // defeat Safari bug
  return targ;
}

//
// section: Popup functions
//

// var: nCurrentWindowOffset
//   Offset for the previous popup window.
var nCurrentWindowOffset = 0;

// var: popopsNone
//   window.open() options with everything disabled.
var popopsNone = "location=0,menubar=0,resizable=0,scrollbars=0,status=0,toolbar=0";

// var: popopsResize
//   window.open() options with only resizable enabled.
var popopsResize = "location=0,menubar=0,resizable=1,scrollbars=0,status=0,toolbar=0";

// var: popopsResizeScroll
//   window.open() options with only resizable and scrollbars enabled.
var popopsResizeScroll = "location=0,menubar=0,resizable=1,scrollbars=1,status=0,toolbar=0";

// func: openInParentOrNew
//   Changes the location of the parent window if possible, opens a new window if not
//
// Parameters:
//   url - url to open
//
function openInParentOrNew(url)
{
  if (window.opener) {
    window.opener.location=url;
  } else {
    window.open(url);
  }
  window.close();
}

// func: openInParent
//   Changes the location of the parent window if possible
//
// Parameters:
//   url - url to open
// Return true if successful, false if not
//
function openInParent(url)
{
  if (window.opener) {
    window.opener.location=url;
    window.close();
    return true;
  }
  return false;
}

var menuNode = null;
var menuNodeP = null;
var menuDelay;
var menuOrigMouseMove = null;

function showMenu(id)
{
  menuNode = $(id);
  menuNodeP = $(id+'p');
  show(menuNode, menuNodeP);
  menuOrigMouseMove = document.body.onmousemove;
  if (!menuOrigMouseMove) {
    menuOrigMouseMove = null;
  }

  document.body.onmousemove = menuMouseMove;
}

function showPopupMenu(id)
{
  closeMenu();
  menuNode = $(id);
  menuNodeP = $(id+'p');
  show(menuNode, menuNodeP);
  menuOrigMouseClick = document.body.onclick;
  if (!menuOrigMouseClick) {
    menuOrigMouseClick = null;
  }

  document.body.onclick = menuMouseMove;
}

function menuMouseMove(e)
{
    if (!e && window.event) {
        var e = window.event;
    }

    hideMenu(e);
}

function rollOverMenu(id) {
  if ($(id) != menuNode) {
    hide(menuNode, menuNodeP);
	menuNode = menuNodeP = null;
  }
}

function closeMenu(id) {
  hide(menuNode, menuNodeP);
  menuNode = menuNodeP = null;
}

function hideMenu(e)
{
  if (menuNode == null) {
    return;
  }

  var pos = findPos(menuNode);
  var off = getScrollOffset();
  l = pos[0] - off[0];
  t = pos[1] - off[1];
  var r = l + menuNode.clientWidth;
  var b = t + menuNode.clientHeight;
  pos = getEventPosition(e);
  x = pos[0];
  y = pos[1];

  if (x <= l || x >= r || y <= t || y >= b) {
    hide(menuNode, menuNodeP);
    menuNode = menuNodeP = null;
    if(typeof(menuOrigMouseMove)!="undefined") {
      document.body.onmousemove = menuOrigMouseMove;
    }
    if(typeof(menuOrigMouseClick)!="undefined") {
      document.body.onclick = menuOrigMouseClick;
    }
  }
}

function cancelMenuDelay()
{
  clearTimeout(menuDelay);
}

function showNavMenu(arg)
{
  if (menuNode != $(arg)) {
    hide(menuNode, menuNodeP);
    menuDelay  = setTimeout(function(){showMenu(arg);},250);
  }
}

// func: benumberone
//   makes the current window the top one
//
function benumberone()
{
    
    if (top.location != location)
    {
        // top.location.href = document.location.href ;
    }
    
}

// func: focusOpener
//   Focuses the window that opened this one. Useful for pop-unders.
//
function focusOpener()
{
    if(self.opener != null)
    {
        self.opener.focus();
    }
}

// func: makeOptions
//   Create standard options string for window.open(). This will use an 800x600 window if the resolution is larger
//   than 1024, otherwise it will use a 620x500 window. Each window will be offset by 24,24.
//
// Returns:
//   options string for window.open()
//
function makeOptions()
{
    var nW = 475;
    var nH = 390;
    var nXI = 24;
    var nYI = 24;
    var nX = 210;
    var nY = 5;
    if(screen.width > 1024)
    {
        nW = 800;
        nH = 600;
        nX = 240;
    }
    else if(screen.width > 800)
    {
        nW = 620;
        nH = 500;
        nX = 240;
    }
    nCurrentWindowOffset ++;
    return 'toolbar=1,scrollbars=1,location=1,status=1,menubar=1,resizable=1,left=' + (nX + (nCurrentWindowOffset * nXI)) + ',top='+ (nY + (nCurrentWindowOffset * nYI)) + ',width=' + nW + ',height=' + nH;
}

// func: showFaq
function showFAQ()
{
    window.open( "pages/reviewfaq.html", "ReviewFAQ", popopsResizeScroll + ",width=800,height=470,screenX=30,screenY=25,left=30,top=25" );
}

// func: showVideoPopup
function showVideoPopup(url)
{
  var w = window.open( url, "VideoGallery", popopsResize + ",width=780,height=640" );
  if (w != null) w.focus();
  return false;
}

// func: showProfileGalleryPopup
function showProfileGalleryPopup(url)
{
  var w = window.open( url, "VideoGallery", popopsNone + ",width=780,height=380" );
  if (w != null)	w.focus();
  return false;
}

// func: showPhotoPopup
function showPhotoPopup(sUrl)
{

  var child = window.open(sUrl,'taphotobrowser', popopsResizeScroll+',width=780,height=660');
  if (child != null) child.focus();
  return false;
}

// func: showDmoVideoPopup
function showDmoVideoPopup(url)
{

   // Get the photo id for the cookie
   var id = url.match(/#([0-9]+)/)[1];
   if (!id) {
     id = "1";
   }

   // Set a temp cookie to indicate a popup
   setCookie("PhotoPop", id, -1);

   var w = window.open( url, "DmoVideo", popopsResize + ",width=400,height=400" );
   if (w != null) {
     w.focus();
   }

   // If we have a window then try to display the right photo (if the window was already open it may be wrong)
   if (w && w.showImage) {
     w.showImage(id);
   }

   return false;
}

// func: showPricingTerms
function showPricingTerms()
{
    window.open( "/pages/pricing_terms.html", "PricingTermsAndConditions", popopsResizeScroll+",width=300,height=300,screenX=30,screenY=25,left=30,top=25");
}

// func: showTermsOfUse
function showTermsOfUse()
{
    window.open( "/pages/terms.html", "TermsOfUse", "toolbar=0,resizable=1,menubar=0,location=0,status=0,scrollbars=3,width=800,height=600,screenX=30,screenY=25,left=30,top=25");
}

// func: PopupOnSelectDestination
function PopupOnSelectDestination ( newURL )
{
    PopupOnSelectDestinationNoClose( newURL );
    self.close();
}

// func: PopupOnSelectDestinationNoClose
function PopupOnSelectDestinationNoClose ( newURL )
{
    if ( newURL != "" )
    if ( newURL != "none")
    if(opener == null || opener.closed == true)
    {
        window.open(newURL, 'TripAdvisor');
    }
    else
    {
        opener.location.href = newURL;
    }
}

// func: openWindowQuickCheck
function openWindowQuickCheck()
{
    window.open('/pages/quickcheck_popup.html','quickcheck_popup','toolbar=0,resizable=1,menubar=0,location=0,status=0,scrollbars=3,width=550,height=395,screenX=30,screenY=25,left=30,top=25');
}

// func: showuserrev_rules
function showuserrev_rules()
{
    var tgtUrl = "/pages/userrev_rules.html";
    window.open ( tgtUrl, "userrev_rules", "toolbar=0,resizable=1,menubar=0,location=0,status=0,scrollbars=3,width=500,height=400,screenX=30,screenY=25,left=30,top=25");
}

// func: showfraud_rules
function showfraud_rules()
{
    var tgtUrl = "/pages/fraud.html";
    window.open ( tgtUrl, "fraud", "toolbar=0,resizable=1,menubar=0,location=0,status=0,scrollbars=3,width=800,height=470,screenX=30,screenY=25,left=30,top=25");
}

// func: showmgmt_rules
function showmgmt_rules()
{
    var tgtUrl = "/pages/userrev_mgmt_rsp_rules.html";
    window.open ( tgtUrl, "userrev_rules", "toolbar=0,resizable=1,menubar=0,location=0,status=0,scrollbars=3,width=500,height=400,screenX=30,screenY=25,left=30,top=25");
}

// func: showuserrev_photoguide
function showuserrev_photoguide()
{
    var tgtUrl = "/pages/photo_submission_guidelines.html";
    window.open ( tgtUrl, "userrev_rules", "toolbar=0,resizable=1,menubar=0,location=0,status=0,scrollbars=3,width=500,height=400,screenX=30,screenY=25,left=30,top=25");
}

// func: showuserrev_photobox
// For Photobox Promotion
// areed - 6/27/08
function showuserrev_photobox()
{
    var tgtUrl = "/PhotoBox";
    window.open ( tgtUrl, "userrev_rules", "toolbar=0,resizable=1,menubar=0,location=0,status=0,scrollbars=3,width=600,height=700,screenX=30,screenY=25,left=30,top=25");
}

// func: promoPopup
// Initially for FIG iPod Promotion official rules popup - hope to reuse
function promoPopup(url)
{
    window.open ( url, "promo_popup", "toolbar=0,resizable=1,menubar=0,location=0,status=0,scrollbars=3,width=600,height=700,screenX=30,screenY=25,left=30,top=25");
}

// func: popularityIndex
function popularityIndex()
{
    var tgtUrl = "/pages/hotel_popularity_popup.html";
    window.open ( tgtUrl, "hotel_popularity_popup", "toolbar=0,resizable=1,menubar=0,location=0,status=0,scrollbars=3,width=500,height=500,screenX=30,screenY=25,left=30,top=25");
}

// func: popOpen
function popOpen(Url)
{
    window.open (Url, "nexus_web_survey", "toolbar=0,resizable=1,menubar=0,location=0,status=0,scrollbars=3,width=700,height=500,screenX=30,screenY=25,left=30,top=25");
}

// func: userreviewName
function userreviewName()
{
    var tgtUrl = "/pages/write_a_review_name_popup.html";
    window.open ( tgtUrl, "write_a_review_name_popup", "toolbar=0,resizable=1,menubar=0,location=0,status=0,scrollbars=3,width=550,height=175,screenX=30,screenY=25,left=30,top=25");
}

// func: userreviewLocation
function userreviewLocation()
{
    var tgtUrl = "/pages/write_a_review_location_popup.html";
    window.open ( tgtUrl, "write_a_review_location_popup", "toolbar=0,resizable=1,menubar=0,location=0,status=0,scrollbars=3,width=550,height=175,screenX=30,screenY=25,left=30,top=25");
}

// func: userreviewSample
function userreviewSample()
{
    var tgtUrl = "/pages/write_a_review_sample_popup.html";
    window.open ( tgtUrl, "write_a_review_sample_popup", "toolbar=0,resizable=1,menubar=0,location=0,status=0,scrollbars=3,width=685,height=484,screenX=25,screenY=25,left=25,top=25");
}

// func: cityPopularityIndex
function cityPopularityIndex()
{
    var tgtUrl = "/pages/city_popularity_popup.html";
    window.open ( tgtUrl, "city_popularity_popup", "toolbar=0,resizable=1,menubar=0,location=0,status=0,scrollbars=3,width=500,height=400,screenX=30,screenY=25,left=30,top=25");
}

// func: destinationGuidePopup
function destinationGuidePopup(url)
{
	var winl = (screen.width - 600) / 2;
    var wint = (screen.height - 620 - 50) / 2;
	window.open(url, "destination_guide_popup", "toolbar=0,resizable=1,scrollbars=1,menubar=0,width=545,height=680,left=" + winl + ",wint" + wint);
}

// func: smartyDeals
//   added by jay 4/16/04 to support popup privacy link
function smartDeals()
{
    var tgtUrl = "/pages/smart_deals_popup.html";
    window.open ( tgtUrl, "smart_deals_popup", "toolbar=0,resizable=1,menubar=0,location=0,status=0,scrollbars=3,width=350,height=350,screenX=30,screenY=25,left=30,top=25");
}

// func: showPrivacyPolicy
//   added by sugata 5/20/04 to support popup stay-logged-in help
function showPrivacyPolicy()
{
    var tgtUrl = "/pages/privacy.html";
    window.open ( tgtUrl, "PrivacyPolicy", "toolbar=0,resizable=1,menubar=0,location=0,status=0,scrollbars=3,width=800,height=600,screenX=30,screenY=25,left=30,top=25");
}

// func: showStayLoggedinHelp
function showStayLoggedinHelp()
{
    var tgtUrl = "/pages/stay_logged_help.html";
    window.open ( tgtUrl, "StayLoggedIn", "toolbar=0,resizable=1,menubar=0,location=0,status=0,scrollbars=3,width=500,height=300,screenX=30,screenY=25,left=30,top=25");
}

// func: mappopup
function mappopup(nLocationID, nWidth, nHeight)
{
    // pad map size
    nHeight += 34;
    nWidth += 4;
    var tgtUrl = "/MapPopup?geo=" + nLocationID;
    var sOpts = "toolbar=0,resizable=1,menubar=0,location=0,status=0,scrollbars=0,width=" + nWidth + ",height=" + nHeight + ",screenX=5,screenY=5,left=5,top=5";
    var w = window.open ( tgtUrl, "MapPopup", sOpts);
    if (w != null)
    {
        w.opener = self;
        w.focus();
    }
}

// func: popDYKWindow
function popDYKWindow(sUrl)
{
    setBlackout();
    var w = window.open(sUrl, 'TripAdvisor', 'toolbar=1,location=1,status=1,menubar=1,resizable=1,copyhistory=1,scrollbars=1');
    self.close();
}

// func: openSurveyWindow
//
// Params:
//   sURL - URL to open
//
function openSurveyWindow(sURL)
{
   try
   {
      window.open(sURL, "tawebsurveyor", "toolbar=0,resizable=1,menubar=0,location=0,status=0,scrollbars=3,width=480,height=640,screenX=30,screenY=25,left=30,top=25");
   }
   catch(e)
   {
      // popup blocker?
   }
}

// func: openWindowUserReview
function openWindowUserReview(myUrl)
{
    window.open(myUrl,'userreview_popup','toolbar=0,resizable=1,menubar=0,location=0,status=0,scrollbars=3,width=550,height=395,screenX=30,screenY=25,left=30,top=25');
}

// Generic function to popup a window with the TA default popup settings
function jsPopup (url, label, width, height)
{
  var opt =
  "menubar=0,status=0,location=0,toolbar=0,menubar=0,directories=0,resizable=1";
  if (width) opt += ",width=" + width;
  if (height) opt += ",height=" + height;
  window.open (url, label, opt);
  return false;
}

function jsPopupScrollXY (url, label, width, height)
{
  var opt =
  "menubar=0,status=0,location=0,toolbar=0,menubar=0,directories=0,resizable=1,scrollbars=1,screenX=30,screenY=25,left=30,top=25";
  if (width) opt += ",width=" + width;
  if (height) opt += ",height=" + height;
  window.open (url, label, opt);
  return false;
}

function setSelRange(input, start, end)
{
 if (!end) end=start;
 input.focus();
 if (input.setSelectionRange)
 {
  input.setSelectionRange(start, end);
 }
 else if (input.createTextRange)
 {
  var range = input.createTextRange();
  range.collapse(true);
  range.moveEnd('character', end);
  range.moveStart('character', start);
  range.select();
 }
}

// Sets all checkable elements in a form to be checked or unchecked
function selectAll (formId, value)
{
  var elements = document.getElementById(formId).elements;
  for (var i = 0; i < elements.length; i++)
  {
      elements[i].checked = value;
  }
  return false;
}

// Determines if all checkboxes in a form are checked
function allSelected (formId)
{
  var elements = document.getElementById(formId).elements;
  for (var i = 0; i < elements.length; i++)
  {
    var e = elements[i];
    if (e.type == 'checkbox' && e.checked == false)
    {
      return false;
    }
  }
  return true;
}

// func: submitSignIn
function submitSignIn(fName)
{
  var form = document.getElementById(fName);
  if (form != null)
  {
      form.submit();
  }
  return false;
}

// func: trim
function trim(stringToTrim) {
  return stringToTrim.replace(/^\s+|\s+$/g,"");
}

// Fancy "are you sure?" confirmation box
// swap lets you switch if yes or no is gold... 1 makes no gold
function confirmBubble(ele, swap, offX, offY, msg, func)
{
  var bubble = $('confirmBubble');
  if(bubble) {
    bubble.parentNode.removeChild(bubble);
  }

  var args = confirmBubble.arguments;
  var params = new Array();

  if(msg=="") {
    msg = JS_js_common__207f;
  }
  if(func) {
    confirmBubbleFunc = func;
    for(i=6; i<args.length; i++){
      params[i-6] = args[i];
    }
  } else {
    confirmBubbleFunc = function() {};
  }

  var pos = findPos($(ele));
  var l = pos[0];
  var t = pos[1];
  if(l!=0 && t!=0) {
    var x=document.createElement("DIV");
    x.style.left = l + offX - 14;
    x.style.top = t + offY + 19;
    x.id="confirmBubble";
    x.style.position="absolute";
    x.className="navigationPopBox";
    x.style.display="block";
    var sb = new StringBuffer();
    sb.append('<div class="saveShadow"><div class="saveShell">');
    sb.append('<div class="navigationPopPoint" style=" top: -5px; left: 20px;">');
    sb.append('<img src="http://cdn.tripadvisor.com/img/m2m/arrowPointUpEdit.gif" width="13" height="7" border="0"/>');
    sb.append('</div>');
    sb.append('<div class="saveBodyFluid">');
    sb.append(msg+'<br /><br />');
    if (swap==1) {
      sb.append('<div class="m2m_link_gold" style="margin-right: 20px;"><div style="cursor: pointer;" onclick="$(\'confirmBubble\').parentNode.removeChild($(\'confirmBubble\'));"><div class="m2m_copy"><img src="http://cdn.tripadvisor.com/img/m2m/m2m_leftBG_Gold.gif" alt="' + JS_common_No + '" align="absmiddle" border="0" height="20" width="5" /><strong>' + JS_common_No + '</strong></div></div></div>');
      sb.append('<div class="m2m_link"><div style="cursor: pointer;" onclick="confirmBubbleFunc(' + params + ');$(\'confirmBubble\').parentNode.removeChild($(\'confirmBubble\'));"><div class="m2m_copy"><img src="http://cdn.tripadvisor.com/img/m2m/m2m_leftBG.gif" alt="' + JS_common_Yes + '" align="absmiddle" border="0" height="20" width="5" />' + JS_common_Yes + '</div></div></div>');
    } else {
    sb.append('<div class="m2m_link" style="margin-right: 20px;"><div style="cursor: pointer;" onclick="$(\'confirmBubble\').parentNode.removeChild($(\'confirmBubble\'));"><div class="m2m_copy"><img src="http://cdn.tripadvisor.com/img/m2m/m2m_leftBG.gif" alt="' + JS_common_No + '" align="absmiddle" border="0" height="20" width="5" />' + JS_common_No + '</div></div></div>');
    sb.append('<div class="m2m_link_gold"><div style="cursor: pointer;" onclick="confirmBubbleFunc(' + params + ');$(\'confirmBubble\').parentNode.removeChild($(\'confirmBubble\'));"><div class="m2m_copy"><img src="http://cdn.tripadvisor.com/img/m2m/m2m_leftBG_Gold.gif" alt="' + JS_common_Yes + '" align="absmiddle" border="0" height="20" width="5" /><strong>' + JS_common_Yes + '</strong></div></div></div>');
    }
    sb.append('<br /><br />');
    sb.append('</div>');
    sb.append('</div></div>');
    x.innerHTML=sb;
    document.body.appendChild(x);
  }
}

// Fancy dialog confirmation box
//
// optional arguments:
// shiftX will move the placement of the pointer
// width will fix the width of the bubble
//
function dialogBubble(ele, offX, offY, msg, shiftX, width)
{
  closeDialogBubble();

  if(msg==null) {
    msg = "";
  }

  if(shiftX==null || shiftX=="") {
    shiftX = 0;
  }

  shiftX = shiftX + 20;

  var pos = findPos($(ele));
  var l = pos[0];
  var t = pos[1];
  if(l!=0 && t!=0) {
    var x=document.createElement("DIV");
    x.style.left = l + offX + 6 - shiftX;
    x.style.top = t + offY + 19;
    x.style.zIndex = dragObj.zIndex;
    x.id="confirmBubble";
    x.style.position="absolute";
    x.className="navigationPopBox";
    x.style.display="block";
    if(width!="" && width!=null) {
      x.style.width = width;
    }
    var sb = new StringBuffer();
    sb.append('<div class="saveShadow"><div class="saveShell">');
    sb.append('<div class="navigationPopPoint" style="top: -5px; left: '+shiftX+'px;">');
    sb.append('<img src="http://cdn.tripadvisor.com/img/m2m/arrowPointUpEdit.gif" width="13" height="7" border="0"/>');
    sb.append('</div>');
    sb.append('<div class="saveBodyFluid">');
    sb.append(msg);
    sb.append('<div style="text-align: right;"><a href="javascript:void(0)" onclick="closeDialogBubble();">' + JS_common_close + '</a></div>');
    sb.append('</div>');
    sb.append('</div></div>');
    x.innerHTML=sb;
    document.body.appendChild(x);
  }
}

// function closeDialogBubble
// helper function for dialogBubble
function closeDialogBubble() {
  var bubble = $('confirmBubble');
  if(bubble) {
    bubble.parentNode.removeChild(bubble);
  }
}

// function showPopupMenuRelative
//  special popup menu show function to fix IE bug
//
function showPopupMenuRelative(ele, id, offX, offY)
{
  closeMenu();
  var pos = findPos(ele);
// calculate element bounts
  var l = pos[0];
  var t = pos[1];
  if(l!=0 && t!=0) {
    menuNode = $(id);
    menuNodeP = $(id+'p');

    menuNode.style.left = l + offX;
    menuNode.style.top = t + offY;

    show(menuNode, menuNodeP);
    menuOrigMouseClick = document.body.onclick;
    if (!menuOrigMouseClick) {
      menuOrigMouseClick = null;
    }

    document.body.onclick = menuMouseMove;
  }
}

// fancy CSS button to match the velocity macro
function cssButton(text, image) {
  button = '<div class="m2m_link"><div style="cursor: pointer;"><div class="m2m_copy"><img src="http://cdn.tripadvisor.com/img/m2m/m2m_leftBG.gif" alt="';
  button += text;
  button += '" align="absmiddle" border="0" height="20" width="5" />';
  if(image!="") {
    button += '<img src="'+image+'" alt="" align="absmiddle" style="padding-right:3px;" />';
  }
  button += text;
  button += '</div></div></div>';
  return button;
}

// fancy CSS button to match the velocity macro
function cssButtonG(text, image) {
  button = '<div class="m2m_link_gold"><div style="cursor: pointer;"><div class="m2m_copy"><img src="http://cdn.tripadvisor.com/img/m2m/m2m_leftBG_Gold.gif" alt="';
  button += text;
  button += '" align="absmiddle" border="0" height="20" width="5" />';
  if(image!="") {
    button += '<img src="'+image+'" alt="" align="absmiddle" style="padding-right:3px;" />';
  }
  button += '<strong>'+text+'</strong>';
  button += '</div></div></div>';
  return button;
}

// fancy small CSS button to match the velocity macro
function cssButtonSmall(text) {
  button = '<div class="m2m_link" style="background: transparent url(http://cdn.tripadvisor.com/img/community/travelmap/buttonSmRight.gif) no-repeat scroll right center;"><div style="cursor: pointer;"><div class="m2m_copy"><img src="http://cdn.tripadvisor.com/img/community/travelmap/addButtonSmLeft.gif" alt="';
  button += text;
  button += '" align="absmiddle" border="0" height="17" width="18" />';
  button += text;
  button += '</div></div></div>';
  return button;
}

function setFocus(elemName)
{
    if (elemName)
    {
      var myElem = document.getElementById(elemName);
      if (myElem)
      {
          myElem.focus();
      }
    }
}

//allows a "maxlength" attribute for a text area
//to use: onkeypress="return isNotMax(this)" in any textarea tag
function isNotMax(textArea)
{
  var max = textArea.getAttribute("maxlength");
  var b = textArea.value.length <= max;
  if (!b) {
    textArea.value = textArea.value.slice(0, max);
  }
  return b;
}

//assures that there are no words larger than 24 characters in the textarea
//to use: onblur="return truncateLargeWords(this)" in any textarea tag
function truncateLargeWords(textArea)
{
  var newValue = ""
  var wordSize = 0;
  for (var i = 0; i < textArea.value.length; i++) {
    var tChar = textArea.value.charAt(i);
    if (tChar == ' ' || tChar == '\n' || tChar == '\t') wordSize = 0; else wordSize++;
    newValue += (wordSize > 24) ? ' ' : tChar;
  }
  textArea.value = newValue;
  return false;
}

// scaleImage(imageID, maxSize) with helper function scaleImageDims(...)
// to use: pass in a document id as the imageID and a maxSize that the image
// should be scaled to preserving aspect ratio
function scaleImage(imageID, maxSize) {
  $(imageID).style.visibility = "hidden";
  var tempImage = new Image();
  tempImage.onload = function() { scaleImageDims(tempImage, imageID, maxSize); }
  tempImage.src = $(imageID).src;
}
function scaleImageDims(tempImage, imageID, maxSize) {
  if(tempImage.width > tempImage.height) {
    var width = maxSize;
    var height = width * tempImage.height / tempImage.width;
  } else {
    var height = maxSize;
    var width  = height * tempImage.width / tempImage.height;
  }
  $(imageID).style.height = height;
  $(imageID).style.width = width;
  $(imageID).style.visibility = "visible";
}

var bRecaptchaSetup = false;
function AjaxSendMessage(params)
{
    var showSendMessage = function() {
        AjaxRequest('/SendMessage','oops!',params,sendMessageAjaxResponseDialog);
    }
    if (!bRecaptchaSetup)
    {
        var headID = document.getElementsByTagName("head")[0];         
        var rcScript = document.createElement('script')
        rcScript.type = 'text/javascript';
        rcScript.onload=showSendMessage;
        rcScript.onreadystatechange= function () {
            if (this.readyState == 'loaded' || this.readyState == 'complete' ) showSendMessage();
        }
        rcScript.src = 'http://api.recaptcha.net/js/recaptcha_ajax.js';
        headID.appendChild(rcScript);
        bRecaptchaSetup = true;
    }
    else
    {
        AjaxRequest('/SendMessage','oops!',params,sendMessageAjaxResponseDialog);
    }
}

// sendPM(src, PM_compliment, fid, communityEnabled, PM_pid, PM_src, PM_t, PM_d, PM_lang, PM_summary)
// used by the privateMessage, privateMessageText and privateMessageReview velocity macro
// to use: use one of the velocity macros, don't call this function directly
// note: make sure that js_strings.vm is parsed to get the localized strings
var msgCallbackPM;
function sendPM(src, PM_compliment, fid, communityEnabled, PM_pid, PM_src, PM_t, PM_d, PM_lang, PM_summary)
{
  if (communityEnabled) {
    if (PM_compliment == 1) {
      var messageType = 1;
    } else {
      var messageType = 2;
    }
    if (PM_src!='' && PM_t!='' && PM_summary!='') {
      var params = ['t',PM_t,'src',PM_src,'to',fid,'d',PM_d,'lang',PM_lang,'pid',PM_pid,'summary',PM_summary,'messagetype',messageType];
      if (messageType == 2) {
        AjaxSendMessage(params);
      } else {
        AjaxRequest('/SendMessage','oops!',params,AjaxResponseDialog);
      }
    } else {
      AjaxSendMessage(['messagetype',2,'to',fid,'pid',PM_pid]);
    }
  }
  else {
    msgCallbackPM = function()
    {
      communityEnabled = true;
      closeDialogBubble();
      sendPM(src, PM_compliment, fid, communityEnabled, PM_pid, PM_src, PM_t, PM_d, PM_lang, PM_summary);
    }
    var aSMC = new StringBuffer();
    aSMC.append('<p id="inviteStatusField" style="display: none; color: red;"></p>');
    aSMC.append('<p>'+JS_mem_travelnet_friends_disabledM2M+'.</p>'); // You have disabled member-to-member communications
    aSMC.append('<p><a href="javascript:void(0)" onclick="enableCommunity(msgCallbackPM, true); return false;">'+JS_common_Clickhere+'</a> '+JS_mem_travelnet_friends_turnOn+'.</p>'); // Click here</a> to turn the feature back on and send your message
    dialogBubble(src, -5, -4, aSMC);
  }
  return false;
}

function showMyTA()
{
  if (menuNode != $('myta_div')) {
    hide(menuNode, menuNodeP);
    menuDelay  = setTimeout(function(){showMenu('myta_div');},250);
  }
}

function showRegisterMenu()
{
  if (menuNode != $('register_div')) {
    hide(menuNode, menuNodeP);
    menuDelay  = setTimeout(function(){showMenu('register_div');},250);
  }
}

function showFloatingDialog(html, posFunc, suppressIFrame)
{
  var x = document.createElement("DIV");
  x.id = "floating_dialog";
  x.style.position = "absolute";
  x.style.zIndex = 9999;
  x.style.display = "block";
  x.style.left = "-999em";
  x.style.top = "-999em";
  x.innerHTML = html;
  document.body.appendChild(x);
    var fcSize = getSize(x);
  if (posFunc) {
    var pos = posFunc(x);
    x.style.left = pos[0] + "px";
    x.style.top = pos[1] + "px";
  }
  else {
    var width = window.innerWidth ? window.innerWidth : (document.documentElement.clientWidth ? document.documentElement.clientWidth : document.body.offsetWidth);
    var height = window.innerHeight ? window.innerHeight : (document.documentElement.clientHeight ? document.documentElement.clientHeight : document.body.offsetHeight);
    var scOff = getScrollOffset();
    var fcSize = getSize(x);
    x.style.left = ((width - fcSize[0]) / 2 + scOff[0]) + "px";
    x.style.top = ((height - fcSize[1]) / 2 + scOff[1]) + "px";
  }
  if(ie && !(suppressIFrame || false)) {
    var i = document.createElement("IFRAME");
    i.id = "floating_dialog_iframe";
    i.style.zIndex = 9998;
    i.style.borderWidth = 0;
    i.style.position = "absolute";
    i.style.display = "block";
    i.style.top = x.style.top;
    i.style.left = x.style.left;
    i.style.width = fcSize[0] + "px";
    i.style.height = fcSize[1] + "px";
    document.body.appendChild(i);
  }
}

function closeFloatingDialog() {
  if($('floating_dialog')) {
    document.body.removeChild($('floating_dialog'));
  }
  if($('floating_dialog_iframe')) {
    document.body.removeChild($('floating_dialog_iframe'));
  }
}

function showDhtmlPopup(promo, locationId, styleLeft, callBack, popId)
{
	  var x=document.createElement("DIV");
	  x.id="dhtmlPopup";
	  x.style.position="absolute";
	  x.style.zIndex="9999";
	  x.style.display="block";
	  var width = window.innerWidth ? window.innerWidth : (document.documentElement.clientWidth ? document.documentElement.clientWidth : document.body.offsetWidth);
	  x.style.left=(width-777)/2;
	  if(styleLeft)
	  {
	  	x.style.left = styleLeft;
	  }
	  x.style.top="0";
	  if($('toptabs')) {
	    var pos = findPos($('toptabs'));
	    var l = pos[0];
	    var t = pos[1];
	    x.style.left = l-100;
	    x.style.top = t;
	  }
	  
	  var callBackFunc = function(res) {
	  	if(res.responseText) {
	      x.innerHTML = res.responseText;
	      evalScripts(x.innerHTML);
	
	      document.body.appendChild(x);
	      
	      var popupId = popId;
	      if(!popupId)
	      {
	      	popupId = 'POPUP';
	      }
	        
	      if(ie && $(popupId)) {
	        var i=document.createElement("IFRAME");
	        i.id="dhtmlPopupIframe";
	        i.style.zIndex = 9998;
	        i.style.borderWidth = 0;
	        i.style.position="absolute";
	        i.style.display="block";
	        var pos = findPos($(popupId));
	        i.style.top=pos[1];
	        i.style.left=pos[0];
	        var fcSize = getSize(x.firstChild);
	        i.style.width = fcSize[0] + "px";
	        i.style.height = fcSize[1] + "px";
	        document.body.appendChild(i);
	      }
	      
	      if(callBack)
	      {
	      	callBack(res.responseText);
	      }
	    }
	  }
	  
	  var errFunc = function(req) {alert(errMsg+"\n"+req.responseText);}
	  var req = new HttpRpc('/DhtmlPopup', function(res) {}, callBackFunc);
	  
	  var params = new UrlParams();
	  
	  params.add('promo', promo);
	  if(locationId!="") {
	    params.add('location', locationId);
	  }
	  req.sendRequest(params.toString());
}

function closeDhtmlPopup() {
  if($('dhtmlPopup')) {
    document.body.removeChild($('dhtmlPopup'));
  }
  if($('dhtmlPopupIframe')) {
    document.body.removeChild($('dhtmlPopupIframe'));
  }
}

function takeFigsSurvey(surveyURL, cookieName)
{
		updateFigsSurveyCookie(true, cookieName);
		window.open(surveyURL,'remote','width=875,height=770,top=100,left=100,toolbar=1,resizable=1,menubar=1,location=1,status=1,scrollbars=1');
		closeDhtmlPopup();
}

function updateFigsSurveyCookie(hidePop, cookieName)
{
  var newCookieVal = getCookie(cookieName);
  if(newCookieVal == null)
  {
    newCookieVal = '0';
  }
  var val = parseInt(newCookieVal) + 1;
  newCookieVal = val + "";
  
  var domain = document.domain;
  if (/(\.|^)(tripadvisor\..+)/.test(document.location.host)) {
	domain = '.'+RegExp.$2;
  }
  
  if(hidePop)
  {
  		setCookie(cookieName, '3', 365, domain);
  }
  else
  {
    setCookie(cookieName, newCookieVal, 365, domain);
  }
}

function nextElement(nref) {
  var n = nref.nextSibling;
  while (n != null && n.nodeType != 1) {
    n = n.nextSibling;
  }
  return n;
}

function previousElement(nref) {
  var n = nref.previousSibling;
  while (n != null && n.nodeType != 1) {
    n = n.previousSibling;
  }
  return n;
}

function callBackFigsSurvey()
{
	updateFigsSurveyCookie(false, 'TAPanelSurveyPopup');
}

function callBackFigsReviewSurvey()
{
	updateFigsSurveyCookie(false, 'TAPanelReviewSurveyPopup');
}

function injectAds()
{
  var ads = getElementsByClassName(document, 'div', 'adServer');
  for(i=0; i<ads.length; i++)
  {
    var detailsA = getElementsByClassName(ads[i], 'div', 'details');
    if (detailsA == null)  continue;
    var details = detailsA[0];
    if (details == null) continue;
    var el = document.createElement("iframe");
    var id = details.id + '_iframe';
    el.setAttribute('id', id);
    el.setAttribute('name', id);
    el.setAttribute('height', 0); 
    el.setAttribute('width', 0) ; 
    el.setAttribute('scrolling', 'no');
    el.setAttribute('border', '0');
    el.setAttribute('bordercolor', '#000000');
    el.setAttribute('marginheight', '0');
    el.setAttribute('marginwidth', '0');
    el.setAttribute('frameborder', '0');
    var srcParams = eval(details.id);
    var src = 'http://' + document.domain + "/adp/adp.html#" + srcParams;
    el.setAttribute('src', src);
    ads[i].appendChild(el);
  }
}
