Replace PR_MIN/PR_MAX with NS_MIN/NS_MAX. b=512106 r=roc
authorMats Palmgren <matspal@gmail.com>
Wed, 16 Sep 2009 17:01:36 +0200
changeset 32531 1348d3ce063d1e3567360d34551cd11e92dd73d0
parent 32530 3c3e2b3d879a945c311ecd124bddecdc9115cd83
child 32532 bb40c09d164a95f17df1fb23abb9f5859e374fda
push idunknown
push userunknown
push dateunknown
reviewersroc
bugs512106
milestone1.9.3a1pre
Replace PR_MIN/PR_MAX with NS_MIN/NS_MAX. b=512106 r=roc
layout/base/nsBidiPresUtils.cpp
layout/base/nsCSSRendering.cpp
layout/base/nsCSSRenderingBorders.cpp
layout/base/nsCaret.cpp
layout/base/nsDisplayList.cpp
layout/base/nsDocumentViewer.cpp
layout/base/nsLayoutUtils.cpp
layout/base/nsPresShell.cpp
layout/forms/nsComboboxControlFrame.cpp
layout/forms/nsFieldSetFrame.cpp
layout/forms/nsGfxCheckboxControlFrame.cpp
layout/forms/nsHTMLButtonControlFrame.cpp
layout/forms/nsListControlFrame.cpp
layout/forms/nsTextControlFrame.cpp
layout/generic/nsAbsoluteContainingBlock.cpp
layout/generic/nsBlockFrame.cpp
layout/generic/nsBlockReflowState.cpp
layout/generic/nsBulletFrame.cpp
layout/generic/nsColumnSetFrame.cpp
layout/generic/nsFloatManager.cpp
layout/generic/nsFrame.cpp
layout/generic/nsFrameFrame.cpp
layout/generic/nsGfxScrollFrame.cpp
layout/generic/nsHTMLCanvasFrame.cpp
layout/generic/nsHTMLContainerFrame.cpp
layout/generic/nsHTMLReflowState.cpp
layout/generic/nsIFrame.h
layout/generic/nsImageFrame.cpp
layout/generic/nsIntervalSet.cpp
layout/generic/nsObjectFrame.cpp
layout/generic/nsSelection.cpp
layout/generic/nsSimplePageSequence.cpp
layout/generic/nsTextFrameThebes.cpp
layout/generic/nsTextFrameUtils.cpp
layout/generic/nsVideoFrame.cpp
layout/mathml/nsMathMLChar.cpp
layout/mathml/nsMathMLTokenFrame.cpp
layout/mathml/nsMathMLmencloseFrame.cpp
layout/mathml/nsMathMLmfencedFrame.cpp
layout/mathml/nsMathMLmfracFrame.cpp
layout/mathml/nsMathMLmmultiscriptsFrame.cpp
layout/mathml/nsMathMLmoFrame.cpp
layout/mathml/nsMathMLmoverFrame.cpp
layout/mathml/nsMathMLmpaddedFrame.cpp
layout/mathml/nsMathMLmrootFrame.cpp
layout/mathml/nsMathMLmsubFrame.cpp
layout/mathml/nsMathMLmsubsupFrame.cpp
layout/mathml/nsMathMLmsupFrame.cpp
layout/mathml/nsMathMLmtableFrame.cpp
layout/mathml/nsMathMLmunderFrame.cpp
layout/mathml/nsMathMLmunderoverFrame.cpp
layout/printing/nsPrintEngine.cpp
layout/style/nsCSSRuleProcessor.cpp
layout/style/nsComputedDOMStyle.cpp
layout/style/nsComputedDOMStyle.h
layout/style/nsRuleNode.cpp
layout/style/nsStyleAnimation.cpp
layout/style/nsStyleStruct.cpp
layout/style/nsStyleStruct.h
layout/style/nsStyleUtil.cpp
layout/svg/base/src/nsSVGGlyphFrame.cpp
layout/svg/base/src/nsSVGTextContainerFrame.cpp
layout/svg/base/src/nsSVGUtils.cpp
layout/tables/BasicTableLayoutStrategy.cpp
layout/tables/FixedTableLayoutStrategy.cpp
layout/tables/nsCellMap.cpp
layout/tables/nsCellMap.h
layout/tables/nsTableCellFrame.cpp
layout/tables/nsTableFrame.cpp
layout/tables/nsTableOuterFrame.cpp
layout/tables/nsTableRowFrame.cpp
layout/tables/nsTableRowGroupFrame.cpp
layout/xul/base/src/grid/nsGridRowLeafLayout.cpp
layout/xul/base/src/nsBox.cpp
layout/xul/base/src/nsBoxFrame.cpp
layout/xul/base/src/nsListItemFrame.cpp
layout/xul/base/src/nsSliderFrame.cpp
layout/xul/base/src/nsSprocketLayout.cpp
layout/xul/base/src/nsStackLayout.cpp
layout/xul/base/src/nsTextBoxFrame.cpp
layout/xul/base/src/tree/src/nsTreeBodyFrame.cpp
--- a/layout/base/nsBidiPresUtils.cpp
+++ b/layout/base/nsBidiPresUtils.cpp
@@ -454,17 +454,17 @@ nsBidiPresUtils::Resolve(nsBlockFrame*  
       ++lineOffset;
     }
     else {
       propTable->SetProperty(frame, nsGkAtoms::embeddingLevel,
                              NS_INT32_TO_PTR(embeddingLevel), nsnull, nsnull);
       propTable->SetProperty(frame, nsGkAtoms::baseLevel,
                              NS_INT32_TO_PTR(paraLevel), nsnull, nsnull);
       if (isTextFrame) {
-        PRInt32 typeLimit = PR_MIN(logicalLimit, lineOffset + fragmentLength);
+        PRInt32 typeLimit = NS_MIN(logicalLimit, lineOffset + fragmentLength);
         CalculateCharType(lineOffset, typeLimit, logicalLimit, runLength,
                            runCount, charType, prevType);
         // IBMBIDI - Egypt - Start
         propTable->SetProperty(frame, nsGkAtoms::charType,
                                NS_INT32_TO_PTR(charType), nsnull, nsnull);
         // IBMBIDI - Egypt - End
 
         if ( (runLength > 0) && (runLength < fragmentLength) ) {
@@ -1416,17 +1416,17 @@ nsresult nsBidiPresUtils::ProcessText(co
       return rv;
 
     rv = mBidiEngine->GetLogicalRun(start, &limit, &level);
     if (NS_FAILED(rv))
       return rv;
 
     PRInt32 subRunLength = limit - start;
     PRInt32 lineOffset = start;
-    PRInt32 typeLimit = PR_MIN(limit, aLength);
+    PRInt32 typeLimit = NS_MIN(limit, aLength);
     PRInt32 subRunCount = 1;
     PRInt32 subRunLimit = typeLimit;
 
     /*
      * If |level| is even, i.e. the direction of the run is left-to-right, we
      * render the subruns from left to right and increment the x-coordinate
      * |xOffset| by the width of each subrun after rendering.
      *
--- a/layout/base/nsCSSRendering.cpp
+++ b/layout/base/nsCSSRendering.cpp
@@ -516,17 +516,17 @@ ComputePixelRadii(const nscoord *aTwipsR
   gfxFloat f = 1.0f;
   NS_FOR_CSS_SIDES(side) {
     PRUint32 hc1 = NS_SIDE_TO_HALF_CORNER(side, PR_FALSE, PR_TRUE);
     PRUint32 hc2 = NS_SIDE_TO_HALF_CORNER(side, PR_TRUE, PR_TRUE);
     gfxFloat length = NS_SIDE_IS_VERTICAL(side) ? maxHeight : maxWidth;
     gfxFloat sum = radii[hc1] + radii[hc2];
     // avoid floating point division in the normal case
     if (length < sum)
-      f = PR_MIN(f, length/sum);
+      f = NS_MIN(f, length/sum);
   }
   if (f < 1.0) {
     NS_FOR_CSS_HALF_CORNERS(corner) {
       radii[corner] *= f;
     }
   }
 
   (*oBorderRadii)[C_TL] = gfxSize(radii[NS_CORNER_TOP_LEFT_X],
@@ -2021,19 +2021,19 @@ PaintBackgroundLayer(nsPresContext* aPre
   // percentages.
   float scaleX, scaleY;
   switch (aLayer.mSize.mWidthType) {
     case nsStyleBackground::Size::eContain:
     case nsStyleBackground::Size::eCover: {
       float scaleFitX = double(bgPositioningArea.width) / imageSize.width;
       float scaleFitY = double(bgPositioningArea.height) / imageSize.height;
       if (aLayer.mSize.mWidthType == nsStyleBackground::Size::eCover) {
-        scaleX = scaleY = PR_MAX(scaleFitX, scaleFitY);
+        scaleX = scaleY = NS_MAX(scaleFitX, scaleFitY);
       } else {
-        scaleX = scaleY = PR_MIN(scaleFitX, scaleFitY);
+        scaleX = scaleY = NS_MIN(scaleFitX, scaleFitY);
       }
       break;
     }
     default: {
       if (aLayer.mSize.mWidthType == nsStyleBackground::Size::eAuto) {
         if (aLayer.mSize.mHeightType == nsStyleBackground::Size::eAuto) {
           scaleX = scaleY = 1.0f;
         } else {
@@ -2546,17 +2546,17 @@ nsCSSRendering::DrawTableBorderSegment(n
   case NS_STYLE_BORDER_STYLE_DASHED: 
     {
       nscoord dashLength = (NS_STYLE_BORDER_STYLE_DASHED == aBorderStyle) ? DASH_LENGTH : DOT_LENGTH;
       // make the dash length proportional to the border thickness
       dashLength *= (horizontal) ? aBorder.height : aBorder.width;
       // make the min dash length for the ends 1/2 the dash length
       nscoord minDashLength = (NS_STYLE_BORDER_STYLE_DASHED == aBorderStyle) 
                               ? RoundFloatToPixel(((float)dashLength) / 2.0f, twipsPerPixel) : dashLength;
-      minDashLength = PR_MAX(minDashLength, twipsPerPixel);
+      minDashLength = NS_MAX(minDashLength, twipsPerPixel);
       nscoord numDashSpaces = 0;
       nscoord startDashLength = minDashLength;
       nscoord endDashLength   = minDashLength;
       if (horizontal) {
         GetDashInfo(aBorder.width, dashLength, twipsPerPixel, numDashSpaces, startDashLength, endDashLength);
         nsRect rect(aBorder.x, aBorder.y, startDashLength, aBorder.height);
         DrawSolidBorderSegment(aContext, rect, twipsPerPixel);
         for (PRInt32 spaceX = 0; spaceX < numDashSpaces; spaceX++) {
@@ -2758,17 +2758,17 @@ nsCSSRendering::PaintDecorationLine(gfxC
   if (aDecoration != NS_STYLE_TEXT_DECORATION_UNDERLINE &&
       aDecoration != NS_STYLE_TEXT_DECORATION_OVERLINE &&
       aDecoration != NS_STYLE_TEXT_DECORATION_LINE_THROUGH)
   {
     NS_ERROR("Invalid decoration value!");
     return;
   }
 
-  gfxFloat lineHeight = PR_MAX(NS_round(aLineSize.height), 1.0);
+  gfxFloat lineHeight = NS_MAX(NS_round(aLineSize.height), 1.0);
   PRBool contextIsSaved = PR_FALSE;
 
   gfxFloat oldLineWidth;
   nsRefPtr<gfxPattern> oldPattern;
 
   switch (aStyle) {
     case DECORATION_STYLE_SOLID:
     case DECORATION_STYLE_DOUBLE:
@@ -2897,17 +2897,17 @@ nsCSSRendering::PaintDecorationLine(gfxC
        */
 
       rect.pos.x += lineHeight / 2.0;
       aGfxContext->NewPath();
 
       gfxPoint pt(rect.pos);
       gfxFloat rightMost = pt.x + rect.Width() + lineHeight;
       gfxFloat adv = rect.Height() - lineHeight;
-      gfxFloat flatLengthAtVertex = PR_MAX((lineHeight - 1.0) * 2.0, 1.0);
+      gfxFloat flatLengthAtVertex = NS_MAX((lineHeight - 1.0) * 2.0, 1.0);
 
       pt.x -= lineHeight;
       aGfxContext->MoveTo(pt); // 1
 
       pt.x = rect.pos.x;
       aGfxContext->LineTo(pt); // 2
 
       PRBool goDown = PR_TRUE;
@@ -2978,22 +2978,22 @@ nsCSSRendering::GetTextDecorationRectInt
 
   PRBool canLiftUnderline = aDescentLimit >= 0.0;
 
   gfxRect r;
   r.pos.x = NS_floor(aPt.x + 0.5);
   r.size.width = NS_round(aLineSize.width);
 
   gfxFloat lineHeight = NS_round(aLineSize.height);
-  lineHeight = PR_MAX(lineHeight, 1.0);
+  lineHeight = NS_MAX(lineHeight, 1.0);
 
   gfxFloat ascent = NS_round(aAscent);
   gfxFloat descentLimit = NS_floor(aDescentLimit);
 
-  gfxFloat suggestedMaxRectHeight = PR_MAX(PR_MIN(ascent, descentLimit), 1.0);
+  gfxFloat suggestedMaxRectHeight = NS_MAX(NS_MIN(ascent, descentLimit), 1.0);
   r.size.height = lineHeight;
   if (aStyle == DECORATION_STYLE_DOUBLE) {
     /**
      *  We will draw double line as:
      *
      * +-------------------------------------------+
      * |XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX| ^
      * |XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX| | lineHeight
@@ -3002,23 +3002,23 @@ nsCSSRendering::GetTextDecorationRectInt
      * |                                           | | gap
      * |                                           | v
      * |XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX| ^
      * |XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX| | lineHeight
      * |XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX| v
      * +-------------------------------------------+
      */
     gfxFloat gap = NS_round(lineHeight / 2.0);
-    gap = PR_MAX(gap, 1.0);
+    gap = NS_MAX(gap, 1.0);
     r.size.height = lineHeight * 2.0 + gap;
     if (canLiftUnderline) {
       if (r.Height() > suggestedMaxRectHeight) {
         // Don't shrink the line height, because the thickness has some meaning.
         // We can just shrink the gap at this time.
-        r.size.height = PR_MAX(suggestedMaxRectHeight, lineHeight * 2.0 + 1.0);
+        r.size.height = NS_MAX(suggestedMaxRectHeight, lineHeight * 2.0 + 1.0);
       }
     }
   } else if (aStyle == DECORATION_STYLE_WAVY) {
     /**
      *  We will draw wavy line as:
      *
      * +-------------------------------------------+
      * |XXXXX            XXXXXX            XXXXXX  | ^
@@ -3032,17 +3032,17 @@ nsCSSRendering::GetTextDecorationRectInt
      */
     r.size.height = lineHeight > 2.0 ? lineHeight * 4.0 : lineHeight * 3.0;
     if (canLiftUnderline) {
       if (r.Height() > suggestedMaxRectHeight) {
         // Don't shrink the line height even if there is not enough space,
         // because the thickness has some meaning.  E.g., the 1px wavy line and
         // 2px wavy line can be used for different meaning in IME selections
         // at same time.
-        r.size.height = PR_MAX(suggestedMaxRectHeight, lineHeight * 2.0);
+        r.size.height = NS_MAX(suggestedMaxRectHeight, lineHeight * 2.0);
       }
     }
   }
 
   gfxFloat baseline = NS_floor(aPt.y + aAscent + 0.5);
   gfxFloat offset = 0.0;
   switch (aDecoration) {
     case NS_STYLE_TEXT_DECORATION_UNDERLINE:
@@ -3050,26 +3050,26 @@ nsCSSRendering::GetTextDecorationRectInt
       if (canLiftUnderline) {
         if (descentLimit < -offset + r.Height()) {
           // If we can ignore the offset and the decoration line is overflowing,
           // we should align the bottom edge of the decoration line rect if it's
           // possible.  Otherwise, we should lift up the top edge of the rect as
           // far as possible.
           gfxFloat offsetBottomAligned = -descentLimit + r.Height();
           gfxFloat offsetTopAligned = 0.0;
-          offset = PR_MIN(offsetBottomAligned, offsetTopAligned);
+          offset = NS_MIN(offsetBottomAligned, offsetTopAligned);
         }
       }
       break;
     case NS_STYLE_TEXT_DECORATION_OVERLINE:
       offset = aOffset - lineHeight + r.Height();
       break;
     case NS_STYLE_TEXT_DECORATION_LINE_THROUGH: {
       gfxFloat extra = NS_floor(r.Height() / 2.0 + 0.5);
-      extra = PR_MAX(extra, lineHeight);
+      extra = NS_MAX(extra, lineHeight);
       offset = aOffset - lineHeight + extra;
       break;
     }
     default:
       NS_ERROR("Invalid decoration value!");
   }
   r.pos.y = baseline - NS_floor(offset + 0.5);
   return r;
--- a/layout/base/nsCSSRenderingBorders.cpp
+++ b/layout/base/nsCSSRenderingBorders.cpp
@@ -197,27 +197,27 @@ nsCSSBorderRenderer::nsCSSBorderRenderer
 
 /* static */ void
 nsCSSBorderRenderer::ComputeInnerRadii(const gfxCornerSizes& aRadii,
                                        const gfxFloat *aBorderSizes,
                                        gfxCornerSizes *aInnerRadiiRet)
 {
   gfxCornerSizes& iRadii = *aInnerRadiiRet;
 
-  iRadii[C_TL].width = PR_MAX(0.0, aRadii[C_TL].width - aBorderSizes[NS_SIDE_LEFT]);
-  iRadii[C_TL].height = PR_MAX(0.0, aRadii[C_TL].height - aBorderSizes[NS_SIDE_TOP]);
+  iRadii[C_TL].width = NS_MAX(0.0, aRadii[C_TL].width - aBorderSizes[NS_SIDE_LEFT]);
+  iRadii[C_TL].height = NS_MAX(0.0, aRadii[C_TL].height - aBorderSizes[NS_SIDE_TOP]);
 
-  iRadii[C_TR].width = PR_MAX(0.0, aRadii[C_TR].width - aBorderSizes[NS_SIDE_RIGHT]);
-  iRadii[C_TR].height = PR_MAX(0.0, aRadii[C_TR].height - aBorderSizes[NS_SIDE_TOP]);
+  iRadii[C_TR].width = NS_MAX(0.0, aRadii[C_TR].width - aBorderSizes[NS_SIDE_RIGHT]);
+  iRadii[C_TR].height = NS_MAX(0.0, aRadii[C_TR].height - aBorderSizes[NS_SIDE_TOP]);
 
-  iRadii[C_BR].width = PR_MAX(0.0, aRadii[C_BR].width - aBorderSizes[NS_SIDE_RIGHT]);
-  iRadii[C_BR].height = PR_MAX(0.0, aRadii[C_BR].height - aBorderSizes[NS_SIDE_BOTTOM]);
+  iRadii[C_BR].width = NS_MAX(0.0, aRadii[C_BR].width - aBorderSizes[NS_SIDE_RIGHT]);
+  iRadii[C_BR].height = NS_MAX(0.0, aRadii[C_BR].height - aBorderSizes[NS_SIDE_BOTTOM]);
 
-  iRadii[C_BL].width = PR_MAX(0.0, aRadii[C_BL].width - aBorderSizes[NS_SIDE_LEFT]);
-  iRadii[C_BL].height = PR_MAX(0.0, aRadii[C_BL].height - aBorderSizes[NS_SIDE_BOTTOM]);
+  iRadii[C_BL].width = NS_MAX(0.0, aRadii[C_BL].width - aBorderSizes[NS_SIDE_LEFT]);
+  iRadii[C_BL].height = NS_MAX(0.0, aRadii[C_BL].height - aBorderSizes[NS_SIDE_BOTTOM]);
 }
 
 /*static*/ void
 ComputeBorderCornerDimensions(const gfxRect& aOuterRect,
                               const gfxRect& aInnerRect,
                               const gfxCornerSizes& aRadii,
                               gfxCornerSizes *aDimsRet)
 {
@@ -231,24 +231,24 @@ ComputeBorderCornerDimensions(const gfxR
     (*aDimsRet)[C_TL] = gfxSize(leftWidth, topWidth);
     (*aDimsRet)[C_TR] = gfxSize(rightWidth, topWidth);
     (*aDimsRet)[C_BR] = gfxSize(rightWidth, bottomWidth);
     (*aDimsRet)[C_BL] = gfxSize(leftWidth, bottomWidth);
   } else {
     // Always round up to whole pixels for the corners; it's safe to
     // make the corners bigger than necessary, and this way we ensure
     // that we avoid seams.
-    (*aDimsRet)[C_TL] = gfxSize(ceil(PR_MAX(leftWidth, aRadii[C_TL].width)),
-                                ceil(PR_MAX(topWidth, aRadii[C_TL].height)));
-    (*aDimsRet)[C_TR] = gfxSize(ceil(PR_MAX(rightWidth, aRadii[C_TR].width)),
-                                ceil(PR_MAX(topWidth, aRadii[C_TR].height)));
-    (*aDimsRet)[C_BR] = gfxSize(ceil(PR_MAX(rightWidth, aRadii[C_BR].width)),
-                                ceil(PR_MAX(bottomWidth, aRadii[C_BR].height)));
-    (*aDimsRet)[C_BL] = gfxSize(ceil(PR_MAX(leftWidth, aRadii[C_BL].width)),
-                                ceil(PR_MAX(bottomWidth, aRadii[C_BL].height)));
+    (*aDimsRet)[C_TL] = gfxSize(ceil(NS_MAX(leftWidth, aRadii[C_TL].width)),
+                                ceil(NS_MAX(topWidth, aRadii[C_TL].height)));
+    (*aDimsRet)[C_TR] = gfxSize(ceil(NS_MAX(rightWidth, aRadii[C_TR].width)),
+                                ceil(NS_MAX(topWidth, aRadii[C_TR].height)));
+    (*aDimsRet)[C_BR] = gfxSize(ceil(NS_MAX(rightWidth, aRadii[C_BR].width)),
+                                ceil(NS_MAX(bottomWidth, aRadii[C_BR].height)));
+    (*aDimsRet)[C_BL] = gfxSize(ceil(NS_MAX(leftWidth, aRadii[C_BL].width)),
+                                ceil(NS_MAX(bottomWidth, aRadii[C_BL].height)));
   }
 }
 
 PRBool
 nsCSSBorderRenderer::AreBorderSideFinalStylesSame(PRUint8 aSides)
 {
   NS_ASSERTION(aSides != 0 && (aSides & ~SIDE_BITS_ALL) == 0,
                "AreBorderSidesSame: invalid whichSides!");
@@ -425,17 +425,17 @@ typedef enum {
 // a horizontal or vertical line move p1 to the point nearest the
 // midpoint, while maintaing the slope of the line.
 static void
 MaybeMoveToMidPoint(gfxPoint& aP0, gfxPoint& aP1, const gfxPoint& aMidPoint)
 {
   gfxPoint ps = aP1 - aP0;
 
   if (ps.x != 0.0 && ps.y != 0.0) {
-    gfxFloat k = PR_MIN((aMidPoint.x - aP0.x) / ps.x,
+    gfxFloat k = NS_MIN((aMidPoint.x - aP0.x) / ps.x,
                         (aMidPoint.y - aP1.y) / ps.y);
     aP1 = aP0 + ps * k;
   }
 }
 
 void
 nsCSSBorderRenderer::DoSideClipSubPath(PRUint8 aSide)
 {
@@ -674,17 +674,17 @@ nsCSSBorderRenderer::DrawBorderSidesComp
 {
   gfxCornerSizes radii = mBorderRadii;
 
   // the generic composite colors path; each border is 1px in size
   gfxRect soRect = mOuterRect;
   gfxRect siRect;
   gfxFloat maxBorderWidth = 0;
   NS_FOR_CSS_SIDES (i) {
-    maxBorderWidth = PR_MAX(maxBorderWidth, mBorderWidths[i]);
+    maxBorderWidth = NS_MAX(maxBorderWidth, mBorderWidths[i]);
   }
 
   gfxFloat fakeBorderSizes[4];
 
   gfxRGBA lineColor;
   gfxPoint tl, br;
 
   gfxPoint itl = mInnerRect.TopLeft();
@@ -695,21 +695,21 @@ nsCSSBorderRenderer::DrawBorderSidesComp
 
     siRect = soRect;
     siRect.Inset(1.0, 1.0, 1.0, 1.0);
 
     // now cap the rects to the real mInnerRect
     tl = siRect.TopLeft();
     br = siRect.BottomRight();
 
-    tl.x = PR_MIN(tl.x, itl.x);
-    tl.y = PR_MIN(tl.y, itl.y);
+    tl.x = NS_MIN(tl.x, itl.x);
+    tl.y = NS_MIN(tl.y, itl.y);
 
-    br.x = PR_MAX(br.x, ibr.x);
-    br.y = PR_MAX(br.y, ibr.y);
+    br.x = NS_MAX(br.x, ibr.x);
+    br.y = NS_MAX(br.y, ibr.y);
 
     siRect.pos = tl;
     siRect.size.width = br.x - tl.x;
     siRect.size.height = br.y - tl.y;
 
     fakeBorderSizes[NS_SIDE_TOP] = siRect.TopLeft().y - soRect.TopLeft().y;
     fakeBorderSizes[NS_SIDE_RIGHT] = soRect.TopRight().x - siRect.TopRight().x;
     fakeBorderSizes[NS_SIDE_BOTTOM] = soRect.BottomRight().y - siRect.BottomRight().y;
--- a/layout/base/nsCaret.cpp
+++ b/layout/base/nsCaret.cpp
@@ -188,17 +188,17 @@ nsCaret::Metrics nsCaret::ComputeMetrics
   // Compute nominal sizes in appunits
   nscoord caretWidth = (aCaretHeight * mCaretAspectRatio) +
                        nsPresContext::CSSPixelsToAppUnits(mCaretWidthCSSPx);
 
   if (DrawCJKCaret(aFrame, aOffset)) {
     caretWidth += nsPresContext::CSSPixelsToAppUnits(1);
   }
   nscoord bidiIndicatorSize = nsPresContext::CSSPixelsToAppUnits(kMinBidiIndicatorPixels);
-  bidiIndicatorSize = PR_MAX(caretWidth, bidiIndicatorSize);
+  bidiIndicatorSize = NS_MAX(caretWidth, bidiIndicatorSize);
 
   // Round them to device pixels. Always round down, except that anything
   // between 0 and 1 goes up to 1 so we don't let the caret disappear.
   PRUint32 tpp = aFrame->PresContext()->AppUnitsPerDevPixel();
   Metrics result;
   result.mCaretWidth = NS_ROUND_BORDER_TO_PIXELS(caretWidth, tpp);
   result.mBidiIndicatorSize = NS_ROUND_BORDER_TO_PIXELS(bidiIndicatorSize, tpp);
   return result;
@@ -784,18 +784,18 @@ nsCaret::GetCaretFrameForNodeOffset(nsIC
       {
         frameBefore = levels.mFrameBefore;
         frameAfter = levels.mFrameAfter;
         levelBefore = levels.mLevelBefore;
         levelAfter = levels.mLevelAfter;
 
         if ((levelBefore != levelAfter) || (aBidiLevel != levelBefore))
         {
-          aBidiLevel = PR_MAX(aBidiLevel, PR_MIN(levelBefore, levelAfter));                                  // rule c3
-          aBidiLevel = PR_MIN(aBidiLevel, PR_MAX(levelBefore, levelAfter));                                  // rule c4
+          aBidiLevel = NS_MAX(aBidiLevel, NS_MIN(levelBefore, levelAfter));                                  // rule c3
+          aBidiLevel = NS_MIN(aBidiLevel, NS_MAX(levelBefore, levelAfter));                                  // rule c4
           if (aBidiLevel == levelBefore                                                                      // rule c1
               || (aBidiLevel > levelBefore && aBidiLevel < levelAfter && !((aBidiLevel ^ levelBefore) & 1))    // rule c5
               || (aBidiLevel < levelBefore && aBidiLevel > levelAfter && !((aBidiLevel ^ levelBefore) & 1)))  // rule c9
           {
             if (theFrame != frameBefore)
             {
               if (frameBefore) // if there is a frameBefore, move into it
               {
--- a/layout/base/nsDisplayList.cpp
+++ b/layout/base/nsDisplayList.cpp
@@ -573,27 +573,27 @@ void nsDisplaySolidColor::Paint(nsDispla
 // handled conservatively by returning FALSE in some situations where
 // a more thorough analysis could return TRUE.
 static PRBool RoundedRectContainsRect(const nsRect& aRoundedRect,
                                       const nscoord aRadii[8],
                                       const nsRect& aContainedRect) {
   // rectFullHeight and rectFullWidth together will approximately contain
   // the total area of the frame minus the rounded corners.
   nsRect rectFullHeight = aRoundedRect;
-  nscoord xDiff = PR_MAX(aRadii[NS_CORNER_TOP_LEFT_X], aRadii[NS_CORNER_BOTTOM_LEFT_X]);
+  nscoord xDiff = NS_MAX(aRadii[NS_CORNER_TOP_LEFT_X], aRadii[NS_CORNER_BOTTOM_LEFT_X]);
   rectFullHeight.x += xDiff;
-  rectFullHeight.width -= PR_MAX(aRadii[NS_CORNER_TOP_RIGHT_X],
+  rectFullHeight.width -= NS_MAX(aRadii[NS_CORNER_TOP_RIGHT_X],
                                  aRadii[NS_CORNER_BOTTOM_RIGHT_X]) + xDiff;
   if (rectFullHeight.Contains(aContainedRect))
     return PR_TRUE;
 
   nsRect rectFullWidth = aRoundedRect;
-  nscoord yDiff = PR_MAX(aRadii[NS_CORNER_TOP_LEFT_Y], aRadii[NS_CORNER_TOP_RIGHT_Y]);
+  nscoord yDiff = NS_MAX(aRadii[NS_CORNER_TOP_LEFT_Y], aRadii[NS_CORNER_TOP_RIGHT_Y]);
   rectFullWidth.y += yDiff;
-  rectFullWidth.height -= PR_MAX(aRadii[NS_CORNER_BOTTOM_LEFT_Y],
+  rectFullWidth.height -= NS_MAX(aRadii[NS_CORNER_BOTTOM_LEFT_Y],
                                  aRadii[NS_CORNER_BOTTOM_RIGHT_Y]) + yDiff;
   if (rectFullWidth.Contains(aContainedRect))
     return PR_TRUE;
 
   return PR_FALSE;
 }
 
 PRBool
--- a/layout/base/nsDocumentViewer.cpp
+++ b/layout/base/nsDocumentViewer.cpp
@@ -1156,17 +1156,17 @@ DocumentViewerImpl::PermitUnload(PRBool 
       // GetStringFromName can succeed, yet give NULL strings back.
       if (NS_FAILED(rv) || preMsg.IsEmpty() || postMsg.IsEmpty()) {
         NS_ERROR("Failed to get strings from dom.properties!");
         return NS_OK;
       }
 
       // Limit the length of the text the page can inject into this
       // dialogue to 1024 characters.
-      PRInt32 len = PR_MIN(text.Length(), 1024);
+      PRInt32 len = NS_MIN(text.Length(), 1024U);
 
       nsAutoString msg;
       if (len == 0) {
         msg = preMsg + NS_LITERAL_STRING("\n\n") + postMsg;
       } else {
         msg = preMsg + NS_LITERAL_STRING("\n\n") +
               StringHead(text, len) +
               NS_LITERAL_STRING("\n\n") + postMsg;
--- a/layout/base/nsLayoutUtils.cpp
+++ b/layout/base/nsLayoutUtils.cpp
@@ -2103,17 +2103,17 @@ nsLayoutUtils::ComputeWidthValue(
         NS_ASSERTION(result >= 0, "width less than zero");
         break;
       case NS_STYLE_WIDTH_FIT_CONTENT:
         {
           nscoord pref = aFrame->GetPrefWidth(aRenderingContext),
                    min = aFrame->GetMinWidth(aRenderingContext),
                   fill = aContainingBlockWidth -
                          (aBoxSizingToMarginEdge + aContentEdgeToBoxSizing);
-          result = PR_MAX(min, PR_MIN(pref, fill));
+          result = NS_MAX(min, NS_MIN(pref, fill));
           NS_ASSERTION(result >= 0, "width less than zero");
         }
         break;
       case NS_STYLE_WIDTH_AVAILABLE:
         result = aContainingBlockWidth -
                  (aBoxSizingToMarginEdge + aContentEdgeToBoxSizing);
     }
   } else {
@@ -3126,20 +3126,20 @@ nsLayoutUtils::GetTextRunFlagsForStyle(n
   return result;
 }
 
 /* static */ void
 nsLayoutUtils::GetRectDifferenceStrips(const nsRect& aR1, const nsRect& aR2,
                                        nsRect* aHStrip, nsRect* aVStrip) {
   NS_ASSERTION(aR1.TopLeft() == aR2.TopLeft(),
                "expected rects at the same position");
-  nsRect unionRect(aR1.x, aR1.y, PR_MAX(aR1.width, aR2.width),
-                   PR_MAX(aR1.height, aR2.height));
-  nscoord VStripStart = PR_MIN(aR1.width, aR2.width);
-  nscoord HStripStart = PR_MIN(aR1.height, aR2.height);
+  nsRect unionRect(aR1.x, aR1.y, NS_MAX(aR1.width, aR2.width),
+                   NS_MAX(aR1.height, aR2.height));
+  nscoord VStripStart = NS_MIN(aR1.width, aR2.width);
+  nscoord HStripStart = NS_MIN(aR1.height, aR2.height);
   *aVStrip = unionRect;
   aVStrip->x += VStripStart;
   aVStrip->width -= VStripStart;
   *aHStrip = unionRect;
   aHStrip->y += HStripStart;
   aHStrip->height -= HStripStart;
 }
 
--- a/layout/base/nsPresShell.cpp
+++ b/layout/base/nsPresShell.cpp
@@ -5329,33 +5329,33 @@ PresShell::ClipListToRange(nsDisplayList
       if (content) {
         PRBool atStart = (content == aRange->GetStartParent());
         PRBool atEnd = (content == aRange->GetEndParent());
         if ((atStart || atEnd) && frame->GetType() == nsGkAtoms::textFrame) {
           PRInt32 frameStartOffset, frameEndOffset;
           frame->GetOffsets(frameStartOffset, frameEndOffset);
 
           PRInt32 hilightStart =
-            atStart ? PR_MAX(aRange->StartOffset(), frameStartOffset) : frameStartOffset;
+            atStart ? NS_MAX(aRange->StartOffset(), frameStartOffset) : frameStartOffset;
           PRInt32 hilightEnd =
-            atEnd ? PR_MIN(aRange->EndOffset(), frameEndOffset) : frameEndOffset;
+            atEnd ? NS_MIN(aRange->EndOffset(), frameEndOffset) : frameEndOffset;
           if (hilightStart < hilightEnd) {
             // determine the location of the start and end edges of the range.
             nsPoint startPoint, endPoint;
             frame->GetPointFromOffset(hilightStart, &startPoint);
             frame->GetPointFromOffset(hilightEnd, &endPoint);
 
             // the clip rectangle is determined by taking the the start and
             // end points of the range, offset from the reference frame.
             // Because of rtl, the end point may be to the left of the
             // start point, so x is set to the lowest value
             nsRect textRect(aBuilder->ToReferenceFrame(frame), frame->GetSize());
-            nscoord x = PR_MIN(startPoint.x, endPoint.x);
+            nscoord x = NS_MIN(startPoint.x, endPoint.x);
             textRect.x += x;
-            textRect.width = PR_MAX(startPoint.x, endPoint.x) - x;
+            textRect.width = NS_MAX(startPoint.x, endPoint.x) - x;
             surfaceRect.UnionRect(surfaceRect, textRect);
 
             // wrap the item in an nsDisplayClip so that it can be clipped to
             // the selection. If the allocation fails, fall through and delete
             // the item below.
             itemToInsert = new (aBuilder)nsDisplayClip(frame, frame, i, textRect);
           }
         }
@@ -5489,19 +5489,19 @@ PresShell::PaintRangePaintInfo(nsTArray<
   nscoord maxHeight = pc->AppUnitsToDevPixels(maxSize.height >> 1);
   PRBool resize = (pixelArea.width > maxWidth || pixelArea.height > maxHeight);
   if (resize) {
     scale = 1.0;
     // divide the maximum size by the image size in both directions. Whichever
     // direction produces the smallest result determines how much should be
     // scaled.
     if (pixelArea.width > maxWidth)
-      scale = PR_MIN(scale, float(maxWidth) / pixelArea.width);
+      scale = NS_MIN(scale, float(maxWidth) / pixelArea.width);
     if (pixelArea.height > maxHeight)
-      scale = PR_MIN(scale, float(maxHeight) / pixelArea.height);
+      scale = NS_MIN(scale, float(maxHeight) / pixelArea.height);
 
     pixelArea.width = NSToIntFloor(float(pixelArea.width) * scale);
     pixelArea.height = NSToIntFloor(float(pixelArea.height) * scale);
 
     // adjust the screen position based on the rescaled size
     nscoord left = rootScreenRect.x + pixelArea.x;
     nscoord top = rootScreenRect.y + pixelArea.y;
     aScreenRect->x = NSToIntFloor(aPoint.x - float(aPoint.x - left) * scale);
@@ -7193,17 +7193,17 @@ PresShell::DoReflow(nsIFrame* target, PR
   nsHTMLReflowState reflowState(mPresContext, target, rcx, reflowSize);
 
   // fix the computed height
   NS_ASSERTION(reflowState.mComputedMargin == nsMargin(0, 0, 0, 0),
                "reflow state should not set margin for reflow roots");
   if (size.height != NS_UNCONSTRAINEDSIZE) {
     nscoord computedHeight =
       size.height - reflowState.mComputedBorderPadding.TopBottom();
-    computedHeight = PR_MAX(computedHeight, 0);
+    computedHeight = NS_MAX(computedHeight, 0);
     reflowState.SetComputedHeight(computedHeight);
   }
   NS_ASSERTION(reflowState.ComputedWidth() ==
                  size.width -
                    reflowState.mComputedBorderPadding.LeftRight(),
                "reflow state computed incorrect width");
 
   mPresContext->ReflowStarted(aInterruptible);
--- a/layout/forms/nsComboboxControlFrame.cpp
+++ b/layout/forms/nsComboboxControlFrame.cpp
@@ -453,17 +453,17 @@ nsComboboxControlFrame::ReflowDropdown(n
                                    availSize);
 
   // If the dropdown's intrinsic width is narrower than our specified width,
   // then expand it out.  We want our border-box width to end up the same as
   // the dropdown's so account for both sets of mComputedBorderPadding.
   nscoord forcedWidth = aReflowState.ComputedWidth() +
     aReflowState.mComputedBorderPadding.LeftRight() -
     kidReflowState.mComputedBorderPadding.LeftRight();
-  kidReflowState.SetComputedWidth(PR_MAX(kidReflowState.ComputedWidth(),
+  kidReflowState.SetComputedWidth(NS_MAX(kidReflowState.ComputedWidth(),
                                          forcedWidth));
 
   // ensure we start off hidden
   if (GetStateBits() & NS_FRAME_FIRST_REFLOW) {
     nsIView* view = mDropdownFrame->GetView();
     nsIViewManager* viewManager = view->GetViewManager();
     viewManager->SetViewVisibility(view, nsViewVisibility_kHide);
     nsRect emptyRect(0, 0, 0, 0);
@@ -578,17 +578,17 @@ nsComboboxControlFrame::GetIntrinsicWidt
     } else {
       NS_ASSERTION(aType == nsLayoutUtils::PREF_WIDTH, "Unexpected type");
       dropdownContentWidth = mDropdownFrame->GetPrefWidth(aRenderingContext);
     }
     dropdownContentWidth = NSCoordSaturatingSubtract(dropdownContentWidth, 
                                                      scrollbarWidth,
                                                      nscoord_MAX);
   
-    displayWidth = PR_MAX(dropdownContentWidth, displayWidth);
+    displayWidth = NS_MAX(dropdownContentWidth, displayWidth);
   }
 
   // add room for the dropmarker button if there is one
   if (!IsThemed() || presContext->GetTheme()->ThemeNeedsComboboxDropmarker())
     displayWidth += scrollbarWidth;
 
   return displayWidth;
 
--- a/layout/forms/nsFieldSetFrame.cpp
+++ b/layout/forms/nsFieldSetFrame.cpp
@@ -361,17 +361,17 @@ nsFieldSetFrame::GetIntrinsicWidth(nsIRe
   }
 
   if (mContentFrame) {
     contentWidth =
       nsLayoutUtils::IntrinsicForContainer(aRenderingContext, mContentFrame,
                                            aType);
   }
       
-  return PR_MAX(legendWidth, contentWidth);
+  return NS_MAX(legendWidth, contentWidth);
 }
 
 
 nscoord
 nsFieldSetFrame::GetMinWidth(nsIRenderingContext* aRenderingContext)
 {
   nscoord result = 0;
   DISPLAY_MIN_WIDTH(this, result);
@@ -507,25 +507,25 @@ nsFieldSetFrame::Reflow(nsPresContext*  
   // reflow the content frame only if needed
   if (reflowContent) {
     nsHTMLReflowState kidReflowState(aPresContext, aReflowState, mContentFrame,
                                      availSize);
     // Our child is "height:100%" but we actually want its height to be reduced
     // by the amount of content-height the legend is eating up, unless our
     // height is unconstrained (in which case the child's will be too).
     if (aReflowState.ComputedHeight() != NS_UNCONSTRAINEDSIZE) {
-      kidReflowState.SetComputedHeight(PR_MAX(0, aReflowState.ComputedHeight() - mLegendSpace));
+      kidReflowState.SetComputedHeight(NS_MAX(0, aReflowState.ComputedHeight() - mLegendSpace));
     }
 
     kidReflowState.mComputedMinHeight =
-      PR_MAX(0, aReflowState.mComputedMinHeight - mLegendSpace);
+      NS_MAX(0, aReflowState.mComputedMinHeight - mLegendSpace);
 
     if (aReflowState.mComputedMaxHeight != NS_UNCONSTRAINEDSIZE) {
       kidReflowState.mComputedMaxHeight =
-        PR_MAX(0, aReflowState.mComputedMaxHeight - mLegendSpace);
+        NS_MAX(0, aReflowState.mComputedMaxHeight - mLegendSpace);
     }
 
     nsHTMLReflowMetrics kidDesiredSize(aDesiredSize.mFlags);
     // Reflow the frame
     NS_ASSERTION(kidReflowState.mComputedMargin == nsMargin(0,0,0,0),
                  "Margins on anonymous fieldset child not supported!");
     nsPoint pt(borderPadding.left, borderPadding.top + mLegendSpace);
     ReflowChild(mContentFrame, aPresContext, kidDesiredSize, kidReflowState,
--- a/layout/forms/nsGfxCheckboxControlFrame.cpp
+++ b/layout/forms/nsGfxCheckboxControlFrame.cpp
@@ -60,17 +60,17 @@ PaintCheckMark(nsIFrame* aFrame,
   // Points come from the coordinates on a 7X7 unit box centered at 0,0
   const PRInt32 checkPolygonX[] = { -3, -1,  3,  3, -1, -3 };
   const PRInt32 checkPolygonY[] = { -1,  1, -3, -1,  3,  1 };
   const PRInt32 checkNumPoints = sizeof(checkPolygonX) / sizeof(PRInt32);
   const PRInt32 checkSize      = 9; // 2 units of padding on either side
                                     // of the 7x7 unit checkmark
 
   // Scale the checkmark based on the smallest dimension
-  nscoord paintScale = PR_MIN(rect.width, rect.height) / checkSize;
+  nscoord paintScale = NS_MIN(rect.width, rect.height) / checkSize;
   nsPoint paintCenter(rect.x + rect.width  / 2,
                       rect.y + rect.height / 2);
 
   nsPoint paintPolygon[checkNumPoints];
   // Convert checkmark for screen rendering
   for (PRInt32 polyIndex = 0; polyIndex < checkNumPoints; polyIndex++) {
     paintPolygon[polyIndex] = paintCenter +
                               nsPoint(checkPolygonX[polyIndex] * paintScale,
--- a/layout/forms/nsHTMLButtonControlFrame.cpp
+++ b/layout/forms/nsHTMLButtonControlFrame.cpp
@@ -314,36 +314,36 @@ nsHTMLButtonControlFrame::ReflowButtonCo
   nscoord extrawidth = GetMinWidth(aReflowState.rendContext) -
     aReflowState.ComputedWidth();
   if (extrawidth > 0) {
     nscoord extraleft = extrawidth / 2;
     nscoord extraright = extrawidth - extraleft;
     NS_ASSERTION(extraright >=0, "How'd that happen?");
     
     // Do not allow the extras to be bigger than the relevant padding
-    extraleft = PR_MIN(extraleft, aReflowState.mComputedPadding.left);
-    extraright = PR_MIN(extraright, aReflowState.mComputedPadding.right);
+    extraleft = NS_MIN(extraleft, aReflowState.mComputedPadding.left);
+    extraright = NS_MIN(extraright, aReflowState.mComputedPadding.right);
     xoffset -= extraleft;
     availSize.width += extraleft + extraright;
   }
-  availSize.width = PR_MAX(availSize.width,0);
+  availSize.width = NS_MAX(availSize.width,0);
   
   nsHTMLReflowState reflowState(aPresContext, aReflowState, aFirstKid,
                                 availSize);
 
   ReflowChild(aFirstKid, aPresContext, aDesiredSize, reflowState,
               xoffset,
               aFocusPadding.top + aReflowState.mComputedBorderPadding.top,
               0, aStatus);
   
   // calculate the min internal height so the contents gets centered correctly.
   // XXXbz this assumes border-box sizing.
   nscoord minInternalHeight = aReflowState.mComputedMinHeight -
     aReflowState.mComputedBorderPadding.TopBottom();
-  minInternalHeight = PR_MAX(minInternalHeight, 0);
+  minInternalHeight = NS_MAX(minInternalHeight, 0);
 
   // center child vertically
   nscoord yoff = 0;
   if (aReflowState.ComputedHeight() != NS_INTRINSICSIZE) {
     yoff = (aReflowState.ComputedHeight() - aDesiredSize.height)/2;
     if (yoff < 0) {
       yoff = 0;
     }
--- a/layout/forms/nsListControlFrame.cpp
+++ b/layout/forms/nsListControlFrame.cpp
@@ -484,17 +484,17 @@ GetOptGroupLabelsHeight(nsPresContext* a
   const PRUint32 childCount = aContent ? aContent->GetChildCount() : 0;
   for (PRUint32 index = 0; index < childCount; ++index) {
     nsIContent* child = aContent->GetChildAt(index);
     if (::IsOptGroup(child)) {
       PRUint32 numOptions = ::GetNumberOfOptionsRecursive(child);
       nscoord optionsHeight = aRowHeight * numOptions;
       nsIFrame* frame = aPresContext->GetPresShell()->GetPrimaryFrameFor(child);
       nscoord totalHeight = frame ? frame->GetSize().height : 0;
-      height += PR_MAX(0, totalHeight - optionsHeight);
+      height += NS_MAX(0, totalHeight - optionsHeight);
     }
   }
   return height;
 }
 
 //-----------------------------------------------------------------
 // Main Reflow for ListBox/Dropdown
 //-----------------------------------------------------------------
@@ -1935,17 +1935,17 @@ nsListControlFrame::CalcIntrinsicHeight(
     // (within the constraint above), bug 300474.
     nscoord labelHeight =
       ::GetOptGroupLabelsHeight(PresContext(), mContent, aHeightOfARow);
 
     if (GetMultiple()) {
       if (aNumberOfOptions < 2) {
         // Add in 1 aHeightOfARow also when aNumberOfOptions == 0
         mNumDisplayRows = 1;
-        extraHeight = PR_MAX(aHeightOfARow, labelHeight);
+        extraHeight = NS_MAX(aHeightOfARow, labelHeight);
       }
       else if (aNumberOfOptions * aHeightOfARow + labelHeight >
                kMaxDropDownRows * aHeightOfARow) {
         mNumDisplayRows = kMaxDropDownRows;
       } else {
         mNumDisplayRows = aNumberOfOptions;
         extraHeight = labelHeight;
       }
--- a/layout/forms/nsTextControlFrame.cpp
+++ b/layout/forms/nsTextControlFrame.cpp
@@ -650,17 +650,17 @@ nsTextInputSelectionImpl::ScrollSelectio
     nsIView* view = nsnull;
     scrollableView->GetScrolledView(view);
     if (!view) {
       return rv;
     }
     const nsRect portRect = scrollableView->View()->GetBounds();
     const nsRect viewRect = view->GetBounds();
     if (viewRect.XMost() < portRect.width) {
-      return scrollableView->ScrollTo(PR_MAX(viewRect.width - portRect.width, 0), -viewRect.y, 0);
+      return scrollableView->ScrollTo(NS_MAX(viewRect.width - portRect.width, 0), -viewRect.y, 0);
     }
 
     return rv;
   }
   return NS_ERROR_NULL_POINTER;
 }
 
 NS_IMETHODIMP
@@ -1260,17 +1260,17 @@ nsTextControlFrame::CalcIntrinsicSize(ns
   PRInt32 cols = GetCols();
   aIntrinsicSize.width = cols * charWidth;
 
   // To better match IE, take the maximum character width(in twips) and remove
   // 4 pixels add this on as additional padding(internalPadding). But only do
   // this if charMaxAdvance != charWidth; if they are equal, this is almost
   // certainly a fixed-width font.
   if (charWidth != charMaxAdvance) {
-    nscoord internalPadding = PR_MAX(0, charMaxAdvance -
+    nscoord internalPadding = NS_MAX(0, charMaxAdvance -
                                         nsPresContext::CSSPixelsToAppUnits(4));
     nscoord t = nsPresContext::CSSPixelsToAppUnits(1); 
    // Round to a multiple of t
     nscoord rest = internalPadding % t; 
     if (rest < t - rest) {
       internalPadding -= rest;
     } else {
       internalPadding += t - rest;
--- a/layout/generic/nsAbsoluteContainingBlock.cpp
+++ b/layout/generic/nsAbsoluteContainingBlock.cpp
@@ -523,20 +523,20 @@ nsAbsoluteContainingBlock::ReflowAbsolut
     // We also have to invalidate when we have overflow and the overflow
     // changes because the change might be caused by clipping
     // XXX This could be optimized in some cases, especially clipping changes
     aKidFrame->GetParent()->Invalidate(oldOverflowRect);
     aKidFrame->GetParent()->Invalidate(kidDesiredSize.mOverflowArea +
                                        rect.TopLeft());
   } else if (oldRect.Size() != rect.Size()) {
     // Invalidate the area where the frame changed size.
-    nscoord innerWidth = PR_MIN(oldRect.width, rect.width);
-    nscoord innerHeight = PR_MIN(oldRect.height, rect.height);
-    nscoord outerWidth = PR_MAX(oldRect.width, rect.width);
-    nscoord outerHeight = PR_MAX(oldRect.height, rect.height);
+    nscoord innerWidth = NS_MIN(oldRect.width, rect.width);
+    nscoord innerHeight = NS_MIN(oldRect.height, rect.height);
+    nscoord outerWidth = NS_MAX(oldRect.width, rect.width);
+    nscoord outerHeight = NS_MAX(oldRect.height, rect.height);
     aKidFrame->GetParent()->Invalidate(
         nsRect(rect.x + innerWidth, rect.y, outerWidth - innerWidth, outerHeight));
     // Invalidate the horizontal strip
     aKidFrame->GetParent()->Invalidate(
         nsRect(rect.x, rect.y + innerHeight, outerWidth, outerHeight - innerHeight));
   }
   aKidFrame->DidReflow(aPresContext, &kidReflowState, NS_FRAME_REFLOW_FINISHED);
 
--- a/layout/generic/nsBlockFrame.cpp
+++ b/layout/generic/nsBlockFrame.cpp
@@ -858,21 +858,21 @@ CalculateContainingBlockSizeForAbsolutes
         }
         if (!lastButOneRS->mFlags.mAssumingVScrollbar) {
           scrollbars.left = scrollbars.right = 0;
         }
       }
       // We found a reflow state for the outermost wrapping frame, so use
       // its computed metrics if available
       if (aLastRS->ComputedWidth() != NS_UNCONSTRAINEDSIZE) {
-        cbSize.width = PR_MAX(0,
+        cbSize.width = NS_MAX(0,
           aLastRS->ComputedWidth() + aLastRS->mComputedPadding.LeftRight() - scrollbars.LeftRight());
       }
       if (aLastRS->ComputedHeight() != NS_UNCONSTRAINEDSIZE) {
-        cbSize.height = PR_MAX(0,
+        cbSize.height = NS_MAX(0,
           aLastRS->ComputedHeight() + aLastRS->mComputedPadding.TopBottom() - scrollbars.TopBottom());
       }
     }
   }
 
   return cbSize;
 }
 
@@ -1262,43 +1262,43 @@ nsBlockFrame::ComputeFinalSize(const nsH
     // we have a computed height, since in that case the carried out
     // margin is not going to be applied anywhere, so we should note it
     // here to be included in the overflow area.
     // Apply the margin only if there's space for it.
     if (bottomEdgeOfChildren < aState.mReflowState.availableHeight)
     {
       // Truncate bottom margin if it doesn't fit to our available height.
       bottomEdgeOfChildren =
-        PR_MIN(bottomEdgeOfChildren + aState.mPrevBottomMargin.get(),
+        NS_MIN(bottomEdgeOfChildren + aState.mPrevBottomMargin.get(),
                aState.mReflowState.availableHeight);
     }
   }
   if (aState.GetFlag(BRS_FLOAT_MGR)) {
     // Include the float manager's state to properly account for the
     // bottom margin of any floated elements; e.g., inside a table cell.
     nscoord floatHeight =
       aState.ClearFloats(bottomEdgeOfChildren, NS_STYLE_CLEAR_LEFT_AND_RIGHT);
-    bottomEdgeOfChildren = PR_MAX(bottomEdgeOfChildren, floatHeight);
+    bottomEdgeOfChildren = NS_MAX(bottomEdgeOfChildren, floatHeight);
   }
 
   // Compute final height
   if (NS_UNCONSTRAINEDSIZE != aReflowState.ComputedHeight()) {
     // Figure out how much of the computed height should be
     // applied to this frame.
     nscoord computedHeightLeftOver = aReflowState.ComputedHeight();
     if (GetPrevInFlow()) {
       // Reduce the height by the computed height of prev-in-flows.
       for (nsIFrame* prev = GetPrevInFlow(); prev; prev = prev->GetPrevInFlow()) {
         computedHeightLeftOver -= prev->GetRect().height;
       }
       // We just subtracted our top-border padding, since it was included in the
       // first frame's height. Add it back to get the content height.
       computedHeightLeftOver += aReflowState.mComputedBorderPadding.top;
       // We may have stretched the frame beyond its computed height. Oh well.
-      computedHeightLeftOver = PR_MAX(0, computedHeightLeftOver);
+      computedHeightLeftOver = NS_MAX(0, computedHeightLeftOver);
     }
     NS_ASSERTION(!( IS_TRUE_OVERFLOW_CONTAINER(this)
                     && computedHeightLeftOver ),
                  "overflow container must not have computedHeightLeftOver");
 
     aMetrics.height = borderPadding.top + computedHeightLeftOver + borderPadding.bottom;
     if (NS_FRAME_IS_NOT_COMPLETE(aState.mReflowStatus)
         && aMetrics.height < aReflowState.availableHeight) {
@@ -1311,32 +1311,32 @@ nsBlockFrame::ComputeFinalSize(const nsH
       if (computedHeightLeftOver > 0 &&
           NS_UNCONSTRAINEDSIZE != aReflowState.availableHeight &&
           aMetrics.height > aReflowState.availableHeight) {
         // We don't fit and we consumed some of the computed height,
         // so we should consume all the available height and then
         // break.  If our bottom border/padding straddles the break
         // point, then this will increase our height and push the
         // border/padding to the next page/column.
-        aMetrics.height = PR_MAX(aReflowState.availableHeight,
+        aMetrics.height = NS_MAX(aReflowState.availableHeight,
                                  aState.mY + nonCarriedOutVerticalMargin);
         NS_FRAME_SET_INCOMPLETE(aState.mReflowStatus);
         if (!GetNextInFlow())
           aState.mReflowStatus |= NS_FRAME_REFLOW_NEXTINFLOW;
       }
     }
     else {
       // Use the current height; continuations will take up the rest.
       // Do extend the height to at least consume the available
       // height, otherwise our left/right borders (for example) won't
       // extend all the way to the break.
-      aMetrics.height = PR_MAX(aReflowState.availableHeight,
+      aMetrics.height = NS_MAX(aReflowState.availableHeight,
                                aState.mY + nonCarriedOutVerticalMargin);
       // ... but don't take up more height than is available
-      aMetrics.height = PR_MIN(aMetrics.height,
+      aMetrics.height = NS_MIN(aMetrics.height,
                                borderPadding.top + computedHeightLeftOver);
       // XXX It's pretty wrong that our bottom border still gets drawn on
       // on its own on the last-in-flow, even if we ran out of height
       // here. We need GetSkipSides to check whether we ran out of content
       // height in the current frame, not whether it's last-in-flow.
     }
 
     // Don't carry out a bottom margin when our height is fixed.
@@ -1353,32 +1353,32 @@ nsBlockFrame::ComputeFinalSize(const nsH
       aMetrics.mCarriedOutBottomMargin.Zero();
     }
     autoHeight += borderPadding.top + borderPadding.bottom;
     aMetrics.height = autoHeight;
   }
   else {
     NS_ASSERTION(aReflowState.availableHeight != NS_UNCONSTRAINEDSIZE,
       "Shouldn't be incomplete if availableHeight is UNCONSTRAINED.");
-    aMetrics.height = PR_MAX(aState.mY, aReflowState.availableHeight);
+    aMetrics.height = NS_MAX(aState.mY, aReflowState.availableHeight);
     if (aReflowState.availableHeight == NS_UNCONSTRAINEDSIZE)
       // This should never happen, but it does. See bug 414255
       aMetrics.height = aState.mY;
   }
 
   if (IS_TRUE_OVERFLOW_CONTAINER(this) &&
       NS_FRAME_IS_NOT_COMPLETE(aState.mReflowStatus)) {
     // Overflow containers can only be overflow complete.
     // Note that auto height overflow containers have no normal children
     NS_ASSERTION(aMetrics.height == 0, "overflow containers must be zero-height");
     NS_FRAME_SET_OVERFLOW_INCOMPLETE(aState.mReflowStatus);
   }
 
   // Screen out negative heights --- can happen due to integer overflows :-(
-  aMetrics.height = PR_MAX(0, aMetrics.height);
+  aMetrics.height = NS_MAX(0, aMetrics.height);
   *aBottomEdgeOfChildren = bottomEdgeOfChildren;
 
 #ifdef DEBUG_blocks
   if (CRAZY_WIDTH(aMetrics.width) || CRAZY_HEIGHT(aMetrics.height)) {
     ListTag(stdout);
     printf(": WARNING: desired:%d,%d\n", aMetrics.width, aMetrics.height);
   }
 #endif
@@ -1426,17 +1426,17 @@ nsBlockFrame::ComputeCombinedArea(const 
     // for the scrollframe's padding, which is logically below the
     // bottom margins of the children.
     nscoord bottomEdgeOfContents = aBottomEdgeOfChildren;
     if (GetStyleContext()->GetPseudoType() == nsCSSAnonBoxes::scrolledContent) {
       // We're a scrolled frame; the scrollframe's padding should be added
       // to the bottom edge of the children
       bottomEdgeOfContents += aReflowState.mComputedPadding.bottom;
     }
-    area.height = PR_MAX(area.YMost(), bottomEdgeOfContents) - area.y;
+    area.height = NS_MAX(area.YMost(), bottomEdgeOfContents) - area.y;
   }
 #ifdef NOISY_COMBINED_AREA
   ListTag(stdout);
   printf(": ca=%d,%d,%d,%d\n", area.x, area.y, area.width, area.height);
 #endif
 
   aMetrics.mOverflowArea = area;
 }
@@ -2227,18 +2227,18 @@ nsBlockFrame::ReflowDirtyLines(nsBlockRe
       nsLayoutUtils::SetFontFromStyle(rc, GetStyleContext());
       nsCOMPtr<nsIFontMetrics> fm;
       rc->GetFontMetrics(*getter_AddRefs(fm));
 
       nscoord minAscent =
         nsLayoutUtils::GetCenteredFontBaseline(fm, aState.mMinLineHeight);
       nscoord minDescent = aState.mMinLineHeight - minAscent;
 
-      aState.mY += PR_MAX(minAscent, metrics.ascent) +
-                   PR_MAX(minDescent, metrics.height - metrics.ascent);
+      aState.mY += NS_MAX(minAscent, metrics.ascent) +
+                   NS_MAX(minDescent, metrics.height - metrics.ascent);
 
       nscoord offset = minAscent - metrics.ascent;
       if (offset > 0) {
         mBullet->SetRect(mBullet->GetRect() + nsPoint(0, offset));
       }
     }
   }
 
@@ -4073,17 +4073,17 @@ nsBlockFrame::PlaceLine(nsBlockReflowSta
   // We want to compare to the available space that we would have had in
   // the line's height *before* we placed any floats in the line itself.
   // Floats that are in the line are handled during line reflow (and may
   // result in floats being pushed to below the line or (I HOPE???) in a
   // reflow with a forced break position).
   nsRect oldFloatAvailableSpace(aFloatAvailableSpace);
   // As we redo for floats, we can't reduce the amount of height we're
   // checking.
-  aAvailableSpaceHeight = PR_MAX(aAvailableSpaceHeight, aLine->mBounds.height);
+  aAvailableSpaceHeight = NS_MAX(aAvailableSpaceHeight, aLine->mBounds.height);
   aFloatAvailableSpace = 
     aState.GetFloatAvailableSpaceForHeight(aLine->mBounds.y,
                                            aAvailableSpaceHeight,
                                            aFloatStateBeforeLine).mRect;
   NS_ASSERTION(aFloatAvailableSpace.y == oldFloatAvailableSpace.y, "yikes");
   // Restore the height to the position of the next band.
   aFloatAvailableSpace.height = oldFloatAvailableSpace.height;
   // If the available space between the floats is smaller now that we
@@ -5533,17 +5533,17 @@ nsBlockFrame::AdjustFloatAvailableSpace(
     nscoord twp = nsPresContext::CSSPixelsToAppUnits(1);
     availWidth -=  availWidth % twp;
   }
 
   // aState.mY is relative to the border-top, make it relative to the content-top
   nscoord contentYOffset = aState.mY - aState.BorderPadding().top;
   nscoord availHeight = NS_UNCONSTRAINEDSIZE == aState.mContentArea.height
                         ? NS_UNCONSTRAINEDSIZE
-                        : PR_MAX(0, aState.mContentArea.height - contentYOffset);
+                        : NS_MAX(0, aState.mContentArea.height - contentYOffset);
 
 #ifdef DISABLE_FLOAT_BREAKING_IN_COLUMNS
   if (availHeight != NS_UNCONSTRAINEDSIZE &&
       nsLayoutUtils::GetClosestFrameOfType(this, nsGkAtoms::columnSetFrame)) {
     // Tell the float it has unrestricted height, so it won't break.
     // If the float doesn't actually fit in the column it will fail to be
     // placed, and either move to the top of the next column or just
     // overflow.
@@ -6572,26 +6572,26 @@ nsBlockFrame::ReflowBullet(nsBlockReflow
   // want to displace it by the same amount.  That is, we act as though
   // the edge of the floats is the content-edge of the block, and place
   // the bullet at a position offset from there by the block's padding,
   // the block's border, and the bullet frame's margin.
   nscoord x;
   if (rs.mStyleVisibility->mDirection == NS_STYLE_DIRECTION_LTR) {
     // Note: floatAvailSpace.x is relative to the content box and never
     // less than zero.  Converting to frame coordinates and subtracting
-    // the padding and border cancel each other out, and the PR_MAX()
+    // the padding and border cancel each other out, and the NS_MAX()
     // with 0 (or with the left border+padding) is even implied in the
     // right place.
     x = floatAvailSpace.x - reflowState.mComputedMargin.right - aMetrics.width;
   } else {
     // The XMost() of the available space and the computed width both
     // give us offsets from the left content edge.  Then we add the left
     // border/padding to get into frame coordinates, and the right
     // border/padding and the bullet's margin to offset the position.
-    x = PR_MIN(rs.ComputedWidth(), floatAvailSpace.XMost())
+    x = NS_MIN(rs.ComputedWidth(), floatAvailSpace.XMost())
         + rs.mComputedBorderPadding.LeftRight()
         + reflowState.mComputedMargin.left;
   }
 
   // Approximate the bullets position; vertical alignment will provide
   // the final vertical location.
   const nsMargin& bp = aState.BorderPadding();
   nscoord y = bp.top;
@@ -6783,18 +6783,18 @@ nsBlockFrame::WidthToClearPastFloats(nsB
          captionSide == NS_STYLE_CAPTION_SIDE_BOTTOM)) {
       result.marginLeft = tableMargin.left;
       result.marginRight = tableMargin.right;
     } else if (captionSide == NS_STYLE_CAPTION_SIDE_TOP_OUTSIDE ||
                captionSide == NS_STYLE_CAPTION_SIDE_BOTTOM_OUTSIDE) {
       // FIXME:  This doesn't treat the caption and table independently,
       // since we adjust by only the smaller margin, and the table outer
       // frame doesn't know about it.
-      result.marginLeft  = PR_MIN(tableMargin.left,  captionMargin.left);
-      result.marginRight = PR_MIN(tableMargin.right, captionMargin.right);
+      result.marginLeft  = NS_MIN(tableMargin.left,  captionMargin.left);
+      result.marginRight = NS_MIN(tableMargin.right, captionMargin.right);
     } else {
       NS_ASSERTION(captionSide == NS_STYLE_CAPTION_SIDE_LEFT ||
                    captionSide == NS_STYLE_CAPTION_SIDE_RIGHT,
                    "unexpected caption-side");
       if (captionSide == NS_STYLE_CAPTION_SIDE_LEFT) {
         result.marginLeft = captionMargin.left;
         result.marginRight = tableMargin.right;
       } else {
--- a/layout/generic/nsBlockReflowState.cpp
+++ b/layout/generic/nsBlockReflowState.cpp
@@ -120,17 +120,17 @@ nsBlockReflowState::nsBlockReflowState(c
   // specified style height then we may end up limiting our height if
   // the availableHeight is constrained (this situation occurs when we
   // are paginated).
   if (NS_UNCONSTRAINEDSIZE != aReflowState.availableHeight) {
     // We are in a paginated situation. The bottom edge is just inside
     // the bottom border and padding. The content area height doesn't
     // include either border or padding edge.
     mBottomEdge = aReflowState.availableHeight - borderPadding.bottom;
-    mContentArea.height = PR_MAX(0, mBottomEdge - borderPadding.top);
+    mContentArea.height = NS_MAX(0, mBottomEdge - borderPadding.top);
   }
   else {
     // When we are not in a paginated situation then we always use
     // an constrained height.
     SetFlag(BRS_UNCONSTRAINEDHEIGHT, PR_TRUE);
     mContentArea.height = mBottomEdge = NS_UNCONSTRAINEDSIZE;
   }
 
@@ -207,26 +207,26 @@ nsBlockReflowState::ComputeReplacedBlock
     nsCSSOffsetState os(aFrame, mReflowState.rendContext, mContentArea.width);
     NS_ASSERTION(!aReplacedWidth ||
                  aFrame->GetType() == nsGkAtoms::tableOuterFrame ||
                  (aReplacedWidth->marginLeft  == os.mComputedMargin.left &&
                   aReplacedWidth->marginRight == os.mComputedMargin.right),
                  "unexpected aReplacedWidth");
 
     nscoord leftFloatXOffset = aFloatAvailableSpace.x;
-    leftOffset = PR_MAX(leftFloatXOffset, os.mComputedMargin.left) -
+    leftOffset = NS_MAX(leftFloatXOffset, os.mComputedMargin.left) -
                  (aReplacedWidth ? aReplacedWidth->marginLeft
                                  : os.mComputedMargin.left);
-    leftOffset = PR_MAX(leftOffset, 0); // in case of negative margin
+    leftOffset = NS_MAX(leftOffset, 0); // in case of negative margin
     nscoord rightFloatXOffset =
       mContentArea.width - aFloatAvailableSpace.XMost();
-    rightOffset = PR_MAX(rightFloatXOffset, os.mComputedMargin.right) -
+    rightOffset = NS_MAX(rightFloatXOffset, os.mComputedMargin.right) -
                   (aReplacedWidth ? aReplacedWidth->marginRight
                                   : os.mComputedMargin.right);
-    rightOffset = PR_MAX(rightOffset, 0); // in case of negative margin
+    rightOffset = NS_MAX(rightOffset, 0); // in case of negative margin
   }
   aLeftResult = leftOffset;
   aRightResult = rightOffset;
 }
 
 // Compute the amount of available space for reflowing a block frame
 // at the current Y coordinate. This method assumes that
 // GetAvailableSpace has already been called.
@@ -239,17 +239,17 @@ nsBlockReflowState::ComputeBlockAvailSpa
 {
 #ifdef REALLY_NOISY_REFLOW
   printf("CBAS frame=%p has floats %d\n",
          aFrame, aFloatAvailableSpace.mHasFloats);
 #endif
   aResult.y = mY;
   aResult.height = GetFlag(BRS_UNCONSTRAINEDHEIGHT)
     ? NS_UNCONSTRAINEDSIZE
-    : PR_MAX(0, mReflowState.availableHeight - mY);
+    : NS_MAX(0, mReflowState.availableHeight - mY);
   // mY might be greater than mBottomEdge if the block's top margin pushes
   // it off the page/column. Negative available height can confuse other code
   // and is nonsense in principle.
 
   const nsMargin& borderPadding = BorderPadding();
 
   // XXX Do we really want this condition to be this restrictive (i.e.,
   // more restrictive than it used to be)?  The |else| here is allowed
@@ -915,17 +915,17 @@ nsBlockReflowState::FlowAndPlaceFloat(ns
   mFloatCombinedArea.UnionRect(combinedArea, mFloatCombinedArea);
 
   // Place the float in the float manager
   // calculate region
   nsRect region = nsFloatManager::CalculateRegionFor(aFloat, floatMargin);
   // if the float split, then take up all of the vertical height
   if (NS_FRAME_IS_NOT_COMPLETE(aReflowStatus) &&
       (NS_UNCONSTRAINEDSIZE != mContentArea.height)) {
-    region.height = PR_MAX(region.height, mContentArea.height - floatY);
+    region.height = NS_MAX(region.height, mContentArea.height - floatY);
   }
   nsresult rv =
   // spacemanager translation is inset by the border+padding.
   mFloatManager->AddFloat(aFloat,
                           region - nsPoint(borderPadding.left, borderPadding.top));
   NS_ABORT_IF_FALSE(NS_SUCCEEDED(rv), "bad float placement");
   // store region
   rv = nsFloatManager::StoreRegionFor(aFloat, region);
@@ -1041,20 +1041,20 @@ nsBlockReflowState::ClearFloats(nscoord 
   if (aReplacedBlock) {
     for (;;) {
       nsFlowAreaRect floatAvailableSpace = 
         GetFloatAvailableSpace(newY, PR_FALSE);
       nsBlockFrame::ReplacedElementWidthToClear replacedWidth =
         nsBlockFrame::WidthToClearPastFloats(*this, floatAvailableSpace.mRect,
                                              aReplacedBlock);
       if (!floatAvailableSpace.mHasFloats ||
-          PR_MAX(floatAvailableSpace.mRect.x, replacedWidth.marginLeft) +
+          NS_MAX(floatAvailableSpace.mRect.x, replacedWidth.marginLeft) +
             replacedWidth.borderBoxWidth +
-            PR_MAX(mContentArea.width -
-                     PR_MIN(mContentArea.width,
+            NS_MAX(mContentArea.width -
+                     NS_MIN(mContentArea.width,
                             floatAvailableSpace.mRect.XMost()),
                    replacedWidth.marginRight) <=
           mContentArea.width) {
         break;
       }
       // See the analogous code for inlines in nsBlockFrame::DoReflowInlineFrames
       if (floatAvailableSpace.mRect.height > 0) {
         // See if there's room in the next band.
--- a/layout/generic/nsBulletFrame.cpp
+++ b/layout/generic/nsBulletFrame.cpp
@@ -1292,17 +1292,17 @@ nsBulletFrame::GetDesiredSize(nsPresCont
       aMetrics.width = 0;
       aMetrics.ascent = aMetrics.height = 0;
       break;
 
     case NS_STYLE_LIST_STYLE_DISC:
     case NS_STYLE_LIST_STYLE_CIRCLE:
     case NS_STYLE_LIST_STYLE_SQUARE:
       fm->GetMaxAscent(ascent);
-      bulletSize = PR_MAX(nsPresContext::CSSPixelsToAppUnits(MIN_BULLET_SIZE),
+      bulletSize = NS_MAX(nsPresContext::CSSPixelsToAppUnits(MIN_BULLET_SIZE),
                           NSToCoordRound(0.8f * (float(ascent) / 2.0f)));
       mPadding.bottom = NSToCoordRound(float(ascent) / 8.0f);
       aMetrics.width = mPadding.right + bulletSize;
       aMetrics.ascent = aMetrics.height = mPadding.bottom + bulletSize;
       break;
 
     default:
     case NS_STYLE_LIST_STYLE_DECIMAL_LEADING_ZERO:
--- a/layout/generic/nsColumnSetFrame.cpp
+++ b/layout/generic/nsColumnSetFrame.cpp
@@ -304,29 +304,29 @@ static nscoord
 GetAvailableContentWidth(const nsHTMLReflowState& aReflowState)
 {
   if (aReflowState.availableWidth == NS_INTRINSICSIZE) {
     return NS_INTRINSICSIZE;
   }
   nscoord borderPaddingWidth =
     aReflowState.mComputedBorderPadding.left +
     aReflowState.mComputedBorderPadding.right;
-  return PR_MAX(0, aReflowState.availableWidth - borderPaddingWidth);
+  return NS_MAX(0, aReflowState.availableWidth - borderPaddingWidth);
 }
 
 static nscoord
 GetAvailableContentHeight(const nsHTMLReflowState& aReflowState)
 {
   if (aReflowState.availableHeight == NS_INTRINSICSIZE) {
     return NS_INTRINSICSIZE;
   }
   nscoord borderPaddingHeight =
     aReflowState.mComputedBorderPadding.top +
     aReflowState.mComputedBorderPadding.bottom;
-  return PR_MAX(0, aReflowState.availableHeight - borderPaddingHeight);
+  return NS_MAX(0, aReflowState.availableHeight - borderPaddingHeight);
 }
 
 static nscoord
 GetColumnGap(nsColumnSetFrame*    aFrame,
              const nsStyleColumn* aColStyle)
 {
   if (eStyleUnit_Normal == aColStyle->mColumnGap.GetUnit())
     return aFrame->GetStyleFont()->mFont.size;
@@ -364,27 +364,27 @@ nsColumnSetFrame::ChooseColumnStrategy(c
     // available width. Compute max number of columns that fit in
     // availContentWidth, satisfying colGap*(maxColumns - 1) +
     // colWidth*maxColumns <= availContentWidth
     if (availContentWidth != NS_INTRINSICSIZE && colGap + colWidth > 0
         && numColumns > 0) {
       // This expression uses truncated rounding, which is what we
       // want
       PRInt32 maxColumns = (availContentWidth + colGap)/(colGap + colWidth);
-      numColumns = PR_MAX(1, PR_MIN(numColumns, maxColumns));
+      numColumns = NS_MAX(1, NS_MIN(numColumns, maxColumns));
     }
   } else if (numColumns > 0 && availContentWidth != NS_INTRINSICSIZE) {
     nscoord widthMinusGaps = availContentWidth - colGap*(numColumns - 1);
     colWidth = widthMinusGaps/numColumns;
   } else {
     colWidth = NS_INTRINSICSIZE;
   }
   // Take care of the situation where there's only one column but it's
   // still too wide
-  colWidth = PR_MAX(1, PR_MIN(colWidth, availContentWidth));
+  colWidth = NS_MAX(1, NS_MIN(colWidth, availContentWidth));
 
   nscoord expectedWidthLeftOver = 0;
 
   if (colWidth != NS_INTRINSICSIZE && availContentWidth != NS_INTRINSICSIZE) {
     // distribute leftover space
 
     // First, determine how many columns will be showing if the column
     // count is auto
@@ -397,32 +397,32 @@ nsColumnSetFrame::ChooseColumnStrategy(c
       }
       if (numColumns <= 0) {
         numColumns = 1;
       }
     }
 
     // Compute extra space and divide it among the columns
     nscoord extraSpace =
-      PR_MAX(0, availContentWidth - (colWidth*numColumns + colGap*(numColumns - 1)));
+      NS_MAX(0, availContentWidth - (colWidth*numColumns + colGap*(numColumns - 1)));
     nscoord extraToColumns = extraSpace/numColumns;
     colWidth += extraToColumns;
     expectedWidthLeftOver = extraSpace - (extraToColumns*numColumns);
   }
 
   // NOTE that the non-balancing behavior for non-auto computed height
   // is not in the CSS3 columns draft as of 18 January 2001
   if (aReflowState.ComputedHeight() == NS_INTRINSICSIZE) {
     // Balancing!
     if (numColumns <= 0) {
       // Hmm, auto column count, column width or available width is unknown,
       // and balancing is required. Let's just use one column then.
       numColumns = 1;
     }
-    colHeight = PR_MIN(mLastBalanceHeight, GetAvailableContentHeight(aReflowState));
+    colHeight = NS_MIN(mLastBalanceHeight, GetAvailableContentHeight(aReflowState));
   } else {
     // No balancing, so don't limit the column count
     numColumns = PR_INT32_MAX;
   }
 
 #ifdef DEBUG_roc
   printf("*** nsColumnSetFrame::ChooseColumnStrategy: numColumns=%d, colWidth=%d, expectedWidthLeftOver=%d, colHeight=%d, colGap=%d\n",
          numColumns, colWidth, expectedWidthLeftOver, colHeight, colGap);
@@ -465,27 +465,27 @@ nsColumnSetFrame::GetMinWidth(nsIRenderi
   }
   const nsStyleColumn* colStyle = GetStyleColumn();
   nscoord colWidth;
   if (colStyle->mColumnWidth.GetUnit() == eStyleUnit_Coord) {
     colWidth = colStyle->mColumnWidth.GetCoordValue();
     // As available width reduces to zero, we reduce our number of columns
     // to one, and don't enforce the column width, so just return the min
     // of the child's min-width with any specified column width.
-    width = PR_MIN(width, colWidth);
+    width = NS_MIN(width, colWidth);
   } else {
     NS_ASSERTION(colStyle->mColumnCount > 0,
                  "column-count and column-width can't both be auto");
     // As available width reduces to zero, we still have mColumnCount columns,
     // so multiply the child's min-width by the number of columns.
     colWidth = width;
     width *= colStyle->mColumnCount;
     // The multiplication above can make 'width' negative (integer overflow),
-    // so use PR_MAX to protect against that.
-    width = PR_MAX(width, colWidth);
+    // so use NS_MAX to protect against that.
+    width = NS_MAX(width, colWidth);
   }
   // XXX count forced column breaks here? Maybe we should return the child's
   // min-width times the minimum number of columns.
   return width;
 }
 
 nscoord
 nsColumnSetFrame::GetPrefWidth(nsIRenderingContext *aRenderingContext) {
@@ -510,18 +510,18 @@ nsColumnSetFrame::GetPrefWidth(nsIRender
   PRInt32 numColumns = colStyle->mColumnCount;
   if (numColumns <= 0) {
     // if column-count is auto, assume one column
     numColumns = 1;
   }
   
   nscoord width = colWidth*numColumns + colGap*(numColumns - 1);
   // The multiplication above can make 'width' negative (integer overflow),
-  // so use PR_MAX to protect against that.
-  result = PR_MAX(width, colWidth);
+  // so use NS_MAX to protect against that.
+  result = NS_MAX(width, colWidth);
   return result;
 }
 
 PRBool
 nsColumnSetFrame::ReflowChildren(nsHTMLReflowMetrics&     aDesiredSize,
                                  const nsHTMLReflowState& aReflowState,
                                  nsReflowStatus&          aStatus,
                                  const ReflowConfig&      aConfig,
@@ -686,25 +686,25 @@ nsColumnSetFrame::ReflowChildren(nsHTMLR
       FinishReflowChild(child, PresContext(), &kidReflowState, 
                         kidDesiredSize, childOrigin.x, childOrigin.y, 0);
 
       childContentBottom = nsLayoutUtils::CalculateContentBottom(child);
       if (childContentBottom > aConfig.mColMaxHeight) {
         allFit = PR_FALSE;
       }
       if (childContentBottom > availSize.height) {
-        aColData.mMaxOverflowingHeight = PR_MAX(childContentBottom,
+        aColData.mMaxOverflowingHeight = NS_MAX(childContentBottom,
             aColData.mMaxOverflowingHeight);
       }
     }
 
     contentRect.UnionRect(contentRect, child->GetRect());
 
     ConsiderChildOverflow(overflowRect, child);
-    contentBottom = PR_MAX(contentBottom, childContentBottom);
+    contentBottom = NS_MAX(contentBottom, childContentBottom);
     aColData.mLastHeight = childContentBottom;
     aColData.mSumHeight += childContentBottom;
 
     // Build a continuation column if necessary
     nsIFrame* kidNextInFlow = child->GetNextInFlow();
 
     if (NS_FRAME_IS_FULLY_COMPLETE(aStatus) && !NS_FRAME_IS_TRUNCATED(aStatus)) {
       NS_ASSERTION(!kidNextInFlow, "next in flow should have been deleted");
@@ -813,43 +813,43 @@ nsColumnSetFrame::ReflowChildren(nsHTMLR
 #endif
     for (child = mFrames.FirstChild(); child; child = child->GetNextSibling()) {
       MoveChildTo(this, child, child->GetPosition() + nsPoint(deltaX, 0));
       ConsiderChildOverflow(overflowRect, child);
       contentRect.UnionRect(contentRect, child->GetRect());
     }
   }
   aColData.mMaxHeight = contentBottom;
-  contentRect.height = PR_MAX(contentRect.height, contentBottom);
+  contentRect.height = NS_MAX(contentRect.height, contentBottom);
   mLastFrameStatus = aStatus;
   
   // contentRect included the borderPadding.left,borderPadding.top of the child rects
   contentRect -= nsPoint(borderPadding.left, borderPadding.top);
   
   nsSize contentSize = nsSize(contentRect.XMost(), contentRect.YMost());
 
   // Apply computed and min/max values
   if (aReflowState.ComputedHeight() != NS_INTRINSICSIZE) {
     contentSize.height = aReflowState.ComputedHeight();
   } else {
     if (NS_UNCONSTRAINEDSIZE != aReflowState.mComputedMaxHeight) {
-      contentSize.height = PR_MIN(aReflowState.mComputedMaxHeight, contentSize.height);
+      contentSize.height = NS_MIN(aReflowState.mComputedMaxHeight, contentSize.height);
     }
     if (NS_UNCONSTRAINEDSIZE != aReflowState.mComputedMinHeight) {
-      contentSize.height = PR_MAX(aReflowState.mComputedMinHeight, contentSize.height);
+      contentSize.height = NS_MAX(aReflowState.mComputedMinHeight, contentSize.height);
     }
   }
   if (aReflowState.ComputedWidth() != NS_INTRINSICSIZE) {
     contentSize.width = aReflowState.ComputedWidth();
   } else {
     if (NS_UNCONSTRAINEDSIZE != aReflowState.mComputedMaxWidth) {
-      contentSize.width = PR_MIN(aReflowState.mComputedMaxWidth, contentSize.width);
+      contentSize.width = NS_MIN(aReflowState.mComputedMaxWidth, contentSize.width);
     }
     if (NS_UNCONSTRAINEDSIZE != aReflowState.mComputedMinWidth) {
-      contentSize.width = PR_MAX(aReflowState.mComputedMinWidth, contentSize.width);
+      contentSize.width = NS_MAX(aReflowState.mComputedMinWidth, contentSize.width);
     }
   }
     
   aDesiredSize.height = borderPadding.top + contentSize.height +
     borderPadding.bottom;
   aDesiredSize.width = contentSize.width + borderPadding.left + borderPadding.right;
   overflowRect.UnionRect(overflowRect, nsRect(0, 0, aDesiredSize.width, aDesiredSize.height));
   aDesiredSize.mOverflowArea = overflowRect;
@@ -945,39 +945,39 @@ nsColumnSetFrame::Reflow(nsPresContext* 
     PRBool maybeContinuousBreakingDetected = PR_FALSE;
 
     while (!aPresContext->HasPendingInterrupt()) {
       nscoord lastKnownFeasibleHeight = knownFeasibleHeight;
 
       // Record what we learned from the last reflow
       if (feasible) {
         // maxHeight is feasible. Also, mLastBalanceHeight is feasible.
-        knownFeasibleHeight = PR_MIN(knownFeasibleHeight, colData.mMaxHeight);
-        knownFeasibleHeight = PR_MIN(knownFeasibleHeight, mLastBalanceHeight);
+        knownFeasibleHeight = NS_MIN(knownFeasibleHeight, colData.mMaxHeight);
+        knownFeasibleHeight = NS_MIN(knownFeasibleHeight, mLastBalanceHeight);
 
         // Furthermore, no height less than the height of the last
         // column can ever be feasible. (We might be able to reduce the
         // height of a non-last column by moving content to a later column,
         // but we can't do that with the last column.)
         if (mFrames.GetLength() == config.mBalanceColCount) {
-          knownInfeasibleHeight = PR_MAX(knownInfeasibleHeight,
+          knownInfeasibleHeight = NS_MAX(knownInfeasibleHeight,
                                          colData.mLastHeight - 1);
         }
       } else {
-        knownInfeasibleHeight = PR_MAX(knownInfeasibleHeight, mLastBalanceHeight);
+        knownInfeasibleHeight = NS_MAX(knownInfeasibleHeight, mLastBalanceHeight);
         // If a column didn't fit in its available height, then its current
         // height must be the minimum height for unbreakable content in
         // the column, and therefore no smaller height can be feasible.
-        knownInfeasibleHeight = PR_MAX(knownInfeasibleHeight,
+        knownInfeasibleHeight = NS_MAX(knownInfeasibleHeight,
                                        colData.mMaxOverflowingHeight - 1);
 
         if (unboundedLastColumn) {
           // The last column is unbounded, so all content got reflowed, so the
           // mColMaxHeight is feasible.
-          knownFeasibleHeight = PR_MIN(knownFeasibleHeight,
+          knownFeasibleHeight = NS_MIN(knownFeasibleHeight,
                                        colData.mMaxHeight);
         }
       }
 
 #ifdef DEBUG_roc
       printf("*** nsColumnSetFrame::Reflow balancing knownInfeasible=%d knownFeasible=%d\n",
              knownInfeasibleHeight, knownFeasibleHeight);
 #endif
@@ -1007,26 +1007,26 @@ nsColumnSetFrame::Reflow(nsPresContext* 
         // differently.
         nextGuess = knownFeasibleHeight - 1;
       } else if (unboundedLastColumn) {
         // Make a guess by dividing that into N columns. Add some slop
         // to try to make it on the feasible side.  The constant of
         // 600 twips is arbitrary. It's about two line-heights.
         nextGuess = colData.mSumHeight/config.mBalanceColCount + 600;
         // Sanitize it
-        nextGuess = PR_MIN(PR_MAX(nextGuess, knownInfeasibleHeight + 1),
+        nextGuess = NS_MIN(NS_MAX(nextGuess, knownInfeasibleHeight + 1),
                            knownFeasibleHeight - 1);
       } else if (knownFeasibleHeight == NS_INTRINSICSIZE) {
         // This can happen when we had a next-in-flow so we didn't
         // want to do an unbounded height measuring step. Let's just increase
         // from the infeasible height by some reasonable amount.
         nextGuess = knownInfeasibleHeight*2 + 600;
       }
       // Don't bother guessing more than our height constraint.
-      nextGuess = PR_MIN(availableContentHeight, nextGuess);
+      nextGuess = NS_MIN(availableContentHeight, nextGuess);
 
 #ifdef DEBUG_roc
       printf("*** nsColumnSetFrame::Reflow balancing choosing next guess=%d\n", nextGuess);
 #endif
 
       config.mColMaxHeight = nextGuess;
       
       unboundedLastColumn = PR_FALSE;
--- a/layout/generic/nsFloatManager.cpp
+++ b/layout/generic/nsFloatManager.cpp
@@ -481,24 +481,24 @@ nsFloatManager::ClearFloats(nscoord aY, 
     return aY;
   }
 
   nscoord bottom = aY + mY;
 
   const FloatInfo &tail = mFloats[mFloats.Length() - 1];
   switch (aBreakType) {
     case NS_STYLE_CLEAR_LEFT_AND_RIGHT:
-      bottom = PR_MAX(bottom, tail.mLeftYMost);
-      bottom = PR_MAX(bottom, tail.mRightYMost);
+      bottom = NS_MAX(bottom, tail.mLeftYMost);
+      bottom = NS_MAX(bottom, tail.mRightYMost);
       break;
     case NS_STYLE_CLEAR_LEFT:
-      bottom = PR_MAX(bottom, tail.mLeftYMost);
+      bottom = NS_MAX(bottom, tail.mLeftYMost);
       break;
     case NS_STYLE_CLEAR_RIGHT:
-      bottom = PR_MAX(bottom, tail.mRightYMost);
+      bottom = NS_MAX(bottom, tail.mRightYMost);
       break;
     default:
       // Do nothing
       break;
   }
 
   bottom -= mY;
 
--- a/layout/generic/nsFrame.cpp
+++ b/layout/generic/nsFrame.cpp
@@ -2685,32 +2685,32 @@ static FrameTarget GetSelectionClosestFr
 
       nscoord fromLeft = aPoint.x - rect.x;
       nscoord fromRight = aPoint.x - rect.XMost();
 
       nscoord xDistance;
       if (fromLeft >= 0 && fromRight <= 0) {
         xDistance = 0;
       } else {
-        xDistance = PR_MIN(abs(fromLeft), abs(fromRight));
+        xDistance = NS_MIN(abs(fromLeft), abs(fromRight));
       }
 
       if (xDistance <= closestXDistance)
       {
         if (xDistance < closestXDistance)
           closestYDistance = HUGE_DISTANCE;
 
         nscoord fromTop = aPoint.y - rect.y;
         nscoord fromBottom = aPoint.y - rect.YMost();
 
         nscoord yDistance;
         if (fromTop >= 0 && fromBottom <= 0)
           yDistance = 0;
         else
-          yDistance = PR_MIN(abs(fromTop), abs(fromBottom));
+          yDistance = NS_MIN(abs(fromTop), abs(fromBottom));
 
         if (yDistance < closestYDistance)
         {
           closestXDistance = xDistance;
           closestYDistance = yDistance;
           closestFrame = kid;
         }
       }
@@ -2916,17 +2916,17 @@ nsFrame::AddInlinePrefWidth(nsIRendering
                        this, nsLayoutUtils::PREF_WIDTH);
   aData->currentLine = NSCoordSaturatingAdd(aData->currentLine, myPref);
 }
 
 void
 nsIFrame::InlineMinWidthData::ForceBreak(nsIRenderingContext *aRenderingContext)
 {
   currentLine -= trailingWhitespace;
-  prevLines = PR_MAX(prevLines, currentLine);
+  prevLines = NS_MAX(prevLines, currentLine);
   currentLine = trailingWhitespace = 0;
 
   for (PRUint32 i = 0, i_end = floats.Length(); i != i_end; ++i) {
     nsIFrame *floatFrame = floats[i];
     nscoord float_min =
       nsLayoutUtils::IntrinsicForContainer(aRenderingContext, floatFrame,
                                            nsLayoutUtils::MIN_WIDTH);
     if (float_min > prevLines)
@@ -2984,32 +2984,32 @@ nsIFrame::InlinePrefWidthData::ForceBrea
                               ? floats_cur_left : floats_cur_right;
       nscoord floatWidth =
           nsLayoutUtils::IntrinsicForContainer(aRenderingContext,
                                                floatFrame,
                                                nsLayoutUtils::PREF_WIDTH);
       // Negative-width floats don't change the available space so they
       // shouldn't change our intrinsic line width either.
       floats_cur =
-        NSCoordSaturatingAdd(floats_cur, PR_MAX(0, floatWidth));
+        NSCoordSaturatingAdd(floats_cur, NS_MAX(0, floatWidth));
     }
 
     nscoord floats_cur =
       NSCoordSaturatingAdd(floats_cur_left, floats_cur_right);
     if (floats_cur > floats_done)
       floats_done = floats_cur;
 
     currentLine = NSCoordSaturatingAdd(currentLine, floats_done);
 
     floats.Clear();
   }
 
   currentLine =
     NSCoordSaturatingSubtract(currentLine, trailingWhitespace, nscoord_MAX);
-  prevLines = PR_MAX(prevLines, currentLine);
+  prevLines = NS_MAX(prevLines, currentLine);
   currentLine = trailingWhitespace = 0;
   skipWhitespace = PR_TRUE;
 }
 
 static void
 AddCoord(const nsStyleCoord& aStyle,
          nsIRenderingContext* aRenderingContext,
          nsIFrame* aFrame,
@@ -3860,17 +3860,17 @@ ComputeOutlineAndEffectsRect(nsIFrame* a
       outline->GetOutlineWidth(width);
     NS_ASSERTION(result, "GetOutlineWidth had no cached outline width");
     if (width > 0) {
       if (aStoreRectProperties) {
         SetRectProperty(aFrame, nsGkAtoms::outlineInnerRectProperty, r);
       }
 
       nscoord offset = outline->mOutlineOffset;
-      nscoord inflateBy = PR_MAX(width + offset, 0);
+      nscoord inflateBy = NS_MAX(width + offset, 0);
       r.Inflate(inflateBy, inflateBy);
       *aAnyOutlineOrEffects = PR_TRUE;
     }
   }
   
   // Note that we don't remove the outlineInnerRect if a frame loses outline
   // style. That would require an extra property lookup for every frame,
   // or a new frame state bit to track whether a property had been stored,
@@ -6450,30 +6450,30 @@ nsFrame::BoxReflow(nsBoxLayoutState&    
     reflowState.mCBReflowState = &parentReflowState;
     reflowState.mReflowDepth = aState.GetReflowDepth();
 
     // mComputedWidth and mComputedHeight are content-box, not
     // border-box
     if (aWidth != NS_INTRINSICSIZE) {
       nscoord computedWidth =
         aWidth - reflowState.mComputedBorderPadding.LeftRight();
-      computedWidth = PR_MAX(computedWidth, 0);
+      computedWidth = NS_MAX(computedWidth, 0);
       reflowState.SetComputedWidth(computedWidth);
     }
 
     // Most child frames of box frames (e.g. subdocument or scroll frames)
     // need to be constrained to the provided size and overflow as necessary.
     // The one exception are block frames, because we need to know their
     // natural height excluding any overflow area which may be caused by
     // various CSS effects such as shadow or outline.
     if (!IsFrameOfType(eBlockFrame)) {
       if (aHeight != NS_INTRINSICSIZE) {
         nscoord computedHeight =
           aHeight - reflowState.mComputedBorderPadding.TopBottom();
-        computedHeight = PR_MAX(computedHeight, 0);
+        computedHeight = NS_MAX(computedHeight, 0);
         reflowState.SetComputedHeight(computedHeight);
       } else {
         reflowState.SetComputedHeight(
           ComputeSize(aRenderingContext, availSize, availSize.width,
                       nsSize(reflowState.mComputedMargin.LeftRight(),
                              reflowState.mComputedMargin.TopBottom()),
                       nsSize(reflowState.mComputedBorderPadding.LeftRight() -
                                reflowState.mComputedPadding.LeftRight(),
--- a/layout/generic/nsFrameFrame.cpp
+++ b/layout/generic/nsFrameFrame.cpp
@@ -633,20 +633,20 @@ nsSubDocumentFrame::ReflowFinished()
     nsSize innerSize(GetSize());
     if (IsInline()) {
       nsMargin usedBorderPadding = GetUsedBorderAndPadding();
 
       // Sadly, XUL smacks the frame size without changing the used
       // border and padding, so we can't trust those.  Subtracting
       // them might make things negative.
       innerSize.width  -= usedBorderPadding.LeftRight();
-      innerSize.width = PR_MAX(innerSize.width, 0);
+      innerSize.width = NS_MAX(innerSize.width, 0);
       
       innerSize.height -= usedBorderPadding.TopBottom();
-      innerSize.height = PR_MAX(innerSize.height, 0);
+      innerSize.height = NS_MAX(innerSize.height, 0);
     }  
 
     PRInt32 cx = presContext->AppUnitsToDevPixels(innerSize.width);
     PRInt32 cy = presContext->AppUnitsToDevPixels(innerSize.height);
     baseWindow->SetPositionAndSize(x, y, cx, cy, PR_FALSE);
   } else {
     // Make sure that we can post a reflow callback in the future.
     mPostedReflowCallback = PR_FALSE;
--- a/layout/generic/nsGfxScrollFrame.cpp
+++ b/layout/generic/nsGfxScrollFrame.cpp
@@ -413,23 +413,23 @@ nsHTMLScrollFrame::TryLayout(ScrollReflo
   }
   nscoord hScrollbarDesiredHeight = aAssumeHScroll ? hScrollbarPrefSize.height : 0;
   nscoord hScrollbarMinWidth = aAssumeHScroll ? hScrollbarMinSize.width : 0;
 
   // First, compute our inside-border size and scrollport size
   // XXXldb Can we depend more on ComputeSize here?
   nsSize desiredInsideBorderSize;
   desiredInsideBorderSize.width = vScrollbarDesiredWidth +
-    PR_MAX(aKidMetrics->width, hScrollbarMinWidth);
+    NS_MAX(aKidMetrics->width, hScrollbarMinWidth);
   desiredInsideBorderSize.height = hScrollbarDesiredHeight +
-    PR_MAX(aKidMetrics->height, vScrollbarMinHeight);
+    NS_MAX(aKidMetrics->height, vScrollbarMinHeight);
   aState->mInsideBorderSize =
     ComputeInsideBorderSize(aState, desiredInsideBorderSize);
-  nsSize scrollPortSize = nsSize(PR_MAX(0, aState->mInsideBorderSize.width - vScrollbarDesiredWidth),
-                                 PR_MAX(0, aState->mInsideBorderSize.height - hScrollbarDesiredHeight));
+  nsSize scrollPortSize = nsSize(NS_MAX(0, aState->mInsideBorderSize.width - vScrollbarDesiredWidth),
+                                 NS_MAX(0, aState->mInsideBorderSize.height - hScrollbarDesiredHeight));
                                                                                 
   if (!aForce) {
     nsRect scrolledRect = mInner.GetScrolledRect(scrollPortSize);
     nscoord oneDevPixel = aState->mBoxState.PresContext()->DevPixelsToAppUnits(1);
 
     // If the style is HIDDEN then we already know that aAssumeHScroll is PR_FALSE
     if (aState->mStyles.mHorizontal != NS_STYLE_OVERFLOW_HIDDEN) {
       PRBool wantHScrollbar =
@@ -483,17 +483,17 @@ nsHTMLScrollFrame::ScrolledContentDepend
 
 nsresult
 nsHTMLScrollFrame::ReflowScrolledFrame(ScrollReflowState* aState,
                                        PRBool aAssumeHScroll,
                                        PRBool aAssumeVScroll,
                                        nsHTMLReflowMetrics* aMetrics,
                                        PRBool aFirstPass)
 {
-  // these could be NS_UNCONSTRAINEDSIZE ... PR_MIN arithmetic should
+  // these could be NS_UNCONSTRAINEDSIZE ... NS_MIN arithmetic should
   // be OK
   nscoord paddingLR = aState->mReflowState.mComputedPadding.LeftRight();
 
   nscoord availWidth = aState->mReflowState.ComputedWidth() + paddingLR;
 
   nscoord computedHeight = aState->mReflowState.ComputedHeight();
   nscoord computedMinHeight = aState->mReflowState.mComputedMinHeight;
   nscoord computedMaxHeight = aState->mReflowState.mComputedMaxHeight;
@@ -501,26 +501,26 @@ nsHTMLScrollFrame::ReflowScrolledFrame(S
     computedHeight = NS_UNCONSTRAINEDSIZE;
     computedMinHeight = 0;
     computedMaxHeight = NS_UNCONSTRAINEDSIZE;
   }
   if (aAssumeHScroll) {
     nsSize hScrollbarPrefSize = 
       mInner.mHScrollbarBox->GetPrefSize(const_cast<nsBoxLayoutState&>(aState->mBoxState));
     if (computedHeight != NS_UNCONSTRAINEDSIZE)
-      computedHeight = PR_MAX(0, computedHeight - hScrollbarPrefSize.height);
-    computedMinHeight = PR_MAX(0, computedMinHeight - hScrollbarPrefSize.height);
+      computedHeight = NS_MAX(0, computedHeight - hScrollbarPrefSize.height);
+    computedMinHeight = NS_MAX(0, computedMinHeight - hScrollbarPrefSize.height);
     if (computedMaxHeight != NS_UNCONSTRAINEDSIZE)
-      computedMaxHeight = PR_MAX(0, computedMaxHeight - hScrollbarPrefSize.height);
+      computedMaxHeight = NS_MAX(0, computedMaxHeight - hScrollbarPrefSize.height);
   }
 
   if (aAssumeVScroll) {
     nsSize vScrollbarPrefSize = 
       mInner.mVScrollbarBox->GetPrefSize(const_cast<nsBoxLayoutState&>(aState->mBoxState));
-    availWidth = PR_MAX(0, availWidth - vScrollbarPrefSize.width);
+    availWidth = NS_MAX(0, availWidth - vScrollbarPrefSize.width);
   }
 
   // We're forcing the padding on our scrolled frame, so let it know what that
   // padding is.
   mInner.mScrolledFrame->
     SetProperty(nsGkAtoms::usedPaddingProperty,
                 new nsMargin(aState->mReflowState.mComputedPadding),
                 nsCSSOffsetState::DestroyMarginFunc);  
@@ -2056,18 +2056,18 @@ nsXULScrollFrame::LayoutScrollArea(nsBox
   aState.SetLayoutFlags(flags);
   mInner.mScrolledFrame->SetBounds(aState, childRect);
   mInner.mScrolledFrame->Layout(aState);
 
   childRect = mInner.mScrolledFrame->GetRect();
 
   if (childRect.width < aRect.width || childRect.height < aRect.height)
   {
-    childRect.width = PR_MAX(childRect.width, aRect.width);
-    childRect.height = PR_MAX(childRect.height, aRect.height);
+    childRect.width = NS_MAX(childRect.width, aRect.width);
+    childRect.height = NS_MAX(childRect.height, aRect.height);
 
     // remove overflow area when we update the bounds,
     // because we've already accounted for it
     mInner.mScrolledFrame->SetBounds(aState, childRect);
     mInner.mScrolledFrame->ClearOverflowRect();
   }
 
   aState.SetLayoutFlags(oldflags);
@@ -2419,17 +2419,17 @@ nsGfxScrollFrameInner::ReflowFinished()
       // of page scrolling.  However, it is too small when
       // fontHeight is very large. (If fontHeight is larger than
       // scrollArea.height, direction of scrolling will be opposite).
       // To avoid it, we use (float(scrollArea.height) * 0.8) as
       // lower bound value of height of page scrolling. (bug 383267)
       nscoord pageincrement = nscoord(scrollArea.height - fontHeight);
       nscoord pageincrementMin = nscoord(float(scrollArea.height) * 0.8);
       FinishReflowForScrollbar(vScroll, minY, maxY, curPosY,
-                               PR_MAX(pageincrement,pageincrementMin),
+                               NS_MAX(pageincrement,pageincrementMin),
                                fontHeight);
     }
     if (hScroll) {
       FinishReflowForScrollbar(hScroll, minX, maxX, curPosX,
                                nscoord(float(scrollArea.width) * 0.8),
                                nsPresContext::CSSPixelsToAppUnits(10));
     }
     NS_ENSURE_TRUE(weakFrame.IsAlive(), PR_FALSE);
@@ -2492,19 +2492,19 @@ static void AdjustScrollbarRect(nsIView*
              aPresContext->DevPixelsToAppUnits(widgetRect.y) - offset.y,
              aPresContext->DevPixelsToAppUnits(widgetRect.width),
              aPresContext->DevPixelsToAppUnits(widgetRect.height));
 
   if (!aRect.Intersects(resizerRect))
     return;
 
   if (aVertical)
-    aRect.height = PR_MAX(0, resizerRect.y - aRect.y);
+    aRect.height = NS_MAX(0, resizerRect.y - aRect.y);
   else
-    aRect.width = PR_MAX(0, resizerRect.x - aRect.x);
+    aRect.width = NS_MAX(0, resizerRect.x - aRect.x);
 }
 
 void
 nsGfxScrollFrameInner::LayoutScrollbars(nsBoxLayoutState& aState,
                                         const nsRect& aContentArea,
                                         const nsRect& aOldScrollArea,
                                         const nsRect& aScrollArea)
 {
@@ -2636,17 +2636,17 @@ nsGfxScrollFrameInner::GetScrolledRect(c
     if (x2 > aScrollPortSize.width)
       x2 = aScrollPortSize.width;
     // When the scrolled frame chooses a size larger than its available width (because
     // its padding alone is larger than the available width), we need to keep the
     // start-edge of the scroll frame anchored to the start-edge of the scrollport. 
     // When the scrolled frame is RTL, this means moving it in our left-based
     // coordinate system, so we need to compensate for its extra width here by
     // effectively repositioning the frame.
-    nscoord extraWidth = PR_MAX(0, mScrolledFrame->GetSize().width - aScrollPortSize.width);
+    nscoord extraWidth = NS_MAX(0, mScrolledFrame->GetSize().width - aScrollPortSize.width);
     x2 += extraWidth;
   }
 
   return nsRect(x1, y1, x2 - x1, y2 - y1);
 }
 
 nsMargin
 nsGfxScrollFrameInner::GetActualScrollbarSizes() const {
--- a/layout/generic/nsHTMLCanvasFrame.cpp
+++ b/layout/generic/nsHTMLCanvasFrame.cpp
@@ -189,17 +189,17 @@ nsHTMLCanvasFrame::Reflow(nsPresContext*
   mBorderPadding   = aReflowState.mComputedBorderPadding;
 
   aMetrics.width += mBorderPadding.left + mBorderPadding.right;
   aMetrics.height += mBorderPadding.top + mBorderPadding.bottom;
 
   if (GetPrevInFlow()) {
     nscoord y = GetContinuationOffset(&aMetrics.width);
     aMetrics.height -= y + mBorderPadding.top;
-    aMetrics.height = PR_MAX(0, aMetrics.height);
+    aMetrics.height = NS_MAX(0, aMetrics.height);
   }
 
   aMetrics.mOverflowArea.SetRect(0, 0, aMetrics.width, aMetrics.height);
   FinishAndStoreOverflow(&aMetrics);
 
   if (mRect.width != aMetrics.width || mRect.height != aMetrics.height) {
     Invalidate(nsRect(0, 0, mRect.width, mRect.height));
   }
@@ -296,17 +296,17 @@ nsHTMLCanvasFrame::GetContinuationOffset
     for (nsIFrame* prevInFlow = GetPrevInFlow() ; prevInFlow; prevInFlow = prevInFlow->GetPrevInFlow()) {
       nsRect rect = prevInFlow->GetRect();
       if (aWidth) {
         *aWidth = rect.width;
       }
       offset += rect.height;
     }
     offset -= mBorderPadding.top;
-    offset = PR_MAX(0, offset);
+    offset = NS_MAX(0, offset);
   }
   return offset;
 }
 
 #ifdef ACCESSIBILITY
 NS_IMETHODIMP
 nsHTMLCanvasFrame::GetAccessible(nsIAccessible** aAccessible)
 {
--- a/layout/generic/nsHTMLContainerFrame.cpp
+++ b/layout/generic/nsHTMLContainerFrame.cpp
@@ -177,17 +177,17 @@ private:
   gfxPoint      mOffset;     // App units
 };
 
 void
 nsDisplayTextShadow::Paint(nsDisplayListBuilder* aBuilder,
                            nsIRenderingContext* aCtx,
                            const nsRect& aDirtyRect)
 {
-  mBlurRadius = PR_MAX(mBlurRadius, 0);
+  mBlurRadius = NS_MAX(mBlurRadius, 0);
 
   nsCOMPtr<nsIFontMetrics> fm;
   nsLayoutUtils::GetFontMetricsForFrame(mFrame, getter_AddRefs(fm));
   nsIThebesFontMetrics* tfm = static_cast<nsIThebesFontMetrics*>(fm.get());
   gfxFontGroup* fontGroup = tfm->GetThebesFontGroup();
   gfxFont* firstFont = fontGroup->GetFontAt(0);
   if (!firstFont)
     return; // OOM
--- a/layout/generic/nsHTMLReflowState.cpp
+++ b/layout/generic/nsHTMLReflowState.cpp
@@ -1539,17 +1539,17 @@ CalcQuirkContainingBlockHeight(const nsH
                rs->parentReflowState->frame->GetType()) {
       // ... then subtract out margin/border/padding for the BODY element
       result -= GetVerticalMarginBorderPadding(secondAncestorRS);
     }
     break;
   }
 
   // Make sure not to return a negative height here!
-  return PR_MAX(result, 0);
+  return NS_MAX(result, 0);
 }
 // Called by InitConstraints() to compute the containing block rectangle for
 // the element. Handles the special logic for absolutely positioned elements
 void
 nsHTMLReflowState::ComputeContainingBlockRectangle(nsPresContext*          aPresContext,
                                                    const nsHTMLReflowState* aContainingBlockRS,
                                                    nscoord&                 aContainingBlockWidth,
                                                    nscoord&                 aContainingBlockHeight)
@@ -2244,26 +2244,26 @@ nsCSSOffsetState::ComputePadding(nscoord
 }
 
 void
 nsHTMLReflowState::ApplyMinMaxConstraints(nscoord* aFrameWidth,
                                           nscoord* aFrameHeight) const
 {
   if (aFrameWidth) {
     if (NS_UNCONSTRAINEDSIZE != mComputedMaxWidth) {
-      *aFrameWidth = PR_MIN(*aFrameWidth, mComputedMaxWidth);
+      *aFrameWidth = NS_MIN(*aFrameWidth, mComputedMaxWidth);
     }
-    *aFrameWidth = PR_MAX(*aFrameWidth, mComputedMinWidth);
+    *aFrameWidth = NS_MAX(*aFrameWidth, mComputedMinWidth);
   }
 
   if (aFrameHeight) {
     if (NS_UNCONSTRAINEDSIZE != mComputedMaxHeight) {
-      *aFrameHeight = PR_MIN(*aFrameHeight, mComputedMaxHeight);
+      *aFrameHeight = NS_MIN(*aFrameHeight, mComputedMaxHeight);
     }
-    *aFrameHeight = PR_MAX(*aFrameHeight, mComputedMinHeight);
+    *aFrameHeight = NS_MAX(*aFrameHeight, mComputedMinHeight);
   }
 }
 
 void
 nsHTMLReflowState::ComputeMinMaxValues(nscoord aContainingBlockWidth,
                                        nscoord aContainingBlockHeight,
                                        const nsHTMLReflowState* aContainingBlockRS)
 {
--- a/layout/generic/nsIFrame.h
+++ b/layout/generic/nsIFrame.h
@@ -50,16 +50,17 @@
 #include "nsQueryFrame.h"
 #include "nsEvent.h"
 #include "nsStyleStruct.h"
 #include "nsStyleContext.h"
 #include "nsIContent.h"
 #include "nsHTMLReflowMetrics.h"
 #include "gfxMatrix.h"
 #include "nsFrameList.h"
+#include "nsAlgorithm.h"
 
 /**
  * New rules of reflow:
  * 1. you get a WillReflow() followed by a Reflow() followed by a DidReflow() in order
  *    (no separate pass over the tree)
  * 2. it's the parent frame's responsibility to size/position the child's view (not
  *    the child frame's responsibility as it is today) during reflow (and before
  *    sending the DidReflow() notification)
@@ -1045,18 +1046,18 @@ public:
   // EndOffset helpers can be used.
   struct NS_STACK_CLASS ContentOffsets {
     nsCOMPtr<nsIContent> content;
     PRBool IsNull() { return !content; }
     PRInt32 offset;
     PRInt32 secondaryOffset;
     // Helpers for places that need the ends of the offsets and expect them in
     // numerical order, as opposed to wanting the primary and secondary offsets
-    PRInt32 StartOffset() { return PR_MIN(offset, secondaryOffset); }
-    PRInt32 EndOffset() { return PR_MAX(offset, secondaryOffset); }
+    PRInt32 StartOffset() { return NS_MIN(offset, secondaryOffset); }
+    PRInt32 EndOffset() { return NS_MAX(offset, secondaryOffset); }
     // This boolean indicates whether the associated content is before or after
     // the offset; the most visible use is to allow the caret to know which line
     // to display on.
     PRBool associateWithNext;
   };
   /**
    * This function calculates the content offsets for selection relative to
    * a point.  Note that this should generally only be callled on the event
--- a/layout/generic/nsImageFrame.cpp
+++ b/layout/generic/nsImageFrame.cpp
@@ -774,17 +774,17 @@ nsImageFrame::Reflow(nsPresContext*     
   // add borders and padding
   aMetrics.width  += aReflowState.mComputedBorderPadding.LeftRight();
   aMetrics.height += aReflowState.mComputedBorderPadding.TopBottom();
   
   if (GetPrevInFlow()) {
     aMetrics.width = GetPrevInFlow()->GetSize().width;
     nscoord y = GetContinuationOffset();
     aMetrics.height -= y + aReflowState.mComputedBorderPadding.top;
-    aMetrics.height = PR_MAX(0, aMetrics.height);
+    aMetrics.height = NS_MAX(0, aMetrics.height);
   }
 
 
   // we have to split images if we are:
   //  in Paginated mode, we need to have a constrained height, and have a height larger than our available height
   PRUint32 loadStatus = imgIRequest::STATUS_NONE;
   nsCOMPtr<nsIImageLoadingContent> imageLoader = do_QueryInterface(mContent);
   NS_ASSERTION(imageLoader, "No content node??");
@@ -797,17 +797,17 @@ nsImageFrame::Reflow(nsPresContext*     
     }
   }
   if (aPresContext->IsPaginated() &&
       ((loadStatus & imgIRequest::STATUS_SIZE_AVAILABLE) || (mState & IMAGE_SIZECONSTRAINED)) &&
       NS_UNCONSTRAINEDSIZE != aReflowState.availableHeight && 
       aMetrics.height > aReflowState.availableHeight) { 
     // our desired height was greater than 0, so to avoid infinite
     // splitting, use 1 pixel as the min
-    aMetrics.height = PR_MAX(nsPresContext::CSSPixelsToAppUnits(1), aReflowState.availableHeight);
+    aMetrics.height = NS_MAX(nsPresContext::CSSPixelsToAppUnits(1), aReflowState.availableHeight);
     aStatus = NS_FRAME_NOT_COMPLETE;
   }
 
   aMetrics.mOverflowArea.SetRect(0, 0, aMetrics.width, aMetrics.height);
   FinishAndStoreOverflow(&aMetrics);
 
   // Now that that's all done, check whether we're resizing... if we are,
   // invalidate our rect.
--- a/layout/generic/nsIntervalSet.cpp
+++ b/layout/generic/nsIntervalSet.cpp
@@ -34,16 +34,17 @@
  * the provisions above, a recipient may use your version of this file under
  * the terms of any one of the MPL, the GPL or the LGPL.
  *
  * ***** END LICENSE BLOCK ***** */
 
 /* a set of ranges on a number-line */
 
 #include "nsIntervalSet.h"
+#include "nsAlgorithm.h"
 #include NEW_H
 
 nsIntervalSet::nsIntervalSet(IntervalSetAlloc aAlloc, IntervalSetFree aFree,
                              void* aAllocatorClosure)
     : mList(nsnull),
       mAlloc(aAlloc),
       mFree(aFree),
       mAllocatorClosure(aAllocatorClosure)
@@ -83,18 +84,18 @@ void nsIntervalSet::IncludeInterval(coor
     while (*current && (*current)->mEnd < aBegin)
         current = &(*current)->mNext;
 
     newInterval->mNext = *current;
     *current = newInterval;
 
     Interval *subsumed = newInterval->mNext;
     while (subsumed && subsumed->mBegin <= aEnd) {
-        newInterval->mBegin = PR_MIN(newInterval->mBegin, subsumed->mBegin);
-        newInterval->mEnd = PR_MAX(newInterval->mEnd, subsumed->mEnd);
+        newInterval->mBegin = NS_MIN(newInterval->mBegin, subsumed->mBegin);
+        newInterval->mEnd = NS_MAX(newInterval->mEnd, subsumed->mEnd);
         newInterval->mNext = subsumed->mNext;
         FreeInterval(subsumed);
         subsumed = newInterval->mNext;
     }
 }
 
 PRBool nsIntervalSet::HasPoint(coord_type aPoint) const
 {
--- a/layout/generic/nsObjectFrame.cpp
+++ b/layout/generic/nsObjectFrame.cpp
@@ -785,33 +785,33 @@ nsObjectFrame::GetDesiredSize(nsPresCont
   
   aMetrics.width = aReflowState.ComputedWidth();
   aMetrics.height = aReflowState.ComputedHeight();
 
   // for EMBED and APPLET, default to 240x200 for compatibility
   nsIAtom *atom = mContent->Tag();
   if (atom == nsGkAtoms::applet || atom == nsGkAtoms::embed) {
     if (aMetrics.width == NS_UNCONSTRAINEDSIZE) {
-      aMetrics.width = PR_MIN(PR_MAX(nsPresContext::CSSPixelsToAppUnits(EMBED_DEF_WIDTH),
+      aMetrics.width = NS_MIN(NS_MAX(nsPresContext::CSSPixelsToAppUnits(EMBED_DEF_WIDTH),
                                      aReflowState.mComputedMinWidth),
                               aReflowState.mComputedMaxWidth);
     }
     if (aMetrics.height == NS_UNCONSTRAINEDSIZE) {
-      aMetrics.height = PR_MIN(PR_MAX(nsPresContext::CSSPixelsToAppUnits(EMBED_DEF_HEIGHT),
+      aMetrics.height = NS_MIN(NS_MAX(nsPresContext::CSSPixelsToAppUnits(EMBED_DEF_HEIGHT),
                                       aReflowState.mComputedMinHeight),
                                aReflowState.mComputedMaxHeight);
     }
 
 #if defined (MOZ_WIDGET_GTK2)
     // We need to make sure that the size of the object frame does not
     // exceed the maximum size of X coordinates.  See bug #225357 for
     // more information.  In theory Gtk2 can handle large coordinates,
     // but underlying plugins can't.
-    aMetrics.height = PR_MIN(aPresContext->DevPixelsToAppUnits(PR_INT16_MAX), aMetrics.height);
-    aMetrics.width = PR_MIN(aPresContext->DevPixelsToAppUnits(PR_INT16_MAX), aMetrics.width);
+    aMetrics.height = NS_MIN(aPresContext->DevPixelsToAppUnits(PR_INT16_MAX), aMetrics.height);
+    aMetrics.width = NS_MIN(aPresContext->DevPixelsToAppUnits(PR_INT16_MAX), aMetrics.width);
 #endif
   }
 
   // At this point, the width has an unconstrained value only if we have
   // nothing to go on (no width set, no information from the plugin, nothing).
   // Make up a number.
   if (aMetrics.width == NS_UNCONSTRAINEDSIZE) {
     aMetrics.width =
--- a/layout/generic/nsSelection.cpp
+++ b/layout/generic/nsSelection.cpp
@@ -1570,17 +1570,17 @@ void nsFrameSelection::BidiLevelFromMove
         SetCaretBidiLevel(levels.mLevelAfter);
       break;
     }
       /*
     // Up and Down: the new cursor Bidi level is the smaller of the two surrounding characters      
     case nsIDOMKeyEvent::DOM_VK_UP:
     case nsIDOMKeyEvent::DOM_VK_DOWN:
       GetPrevNextBidiLevels(aContext, aNode, aContentOffset, &firstFrame, &secondFrame, &firstLevel, &secondLevel);
-      aPresShell->SetCaretBidiLevel(PR_MIN(firstLevel, secondLevel));
+      aPresShell->SetCaretBidiLevel(NS_MIN(firstLevel, secondLevel));
       break;
       */
 
     default:
       UndefineCaretBidiLevel();
   }
 }
 
@@ -2730,20 +2730,20 @@ nsFrameSelection::UnselectCells(nsIConte
     GetIndexFromSelectionType(nsISelectionController::SELECTION_NORMAL);
   if (!mDomSelections[index])
     return NS_ERROR_NULL_POINTER;
 
   nsITableLayout *tableLayout = GetTableLayout(aTableContent);
   if (!tableLayout)
     return NS_ERROR_FAILURE;
 
-  PRInt32 minRowIndex = PR_MIN(aStartRowIndex, aEndRowIndex);
-  PRInt32 maxRowIndex = PR_MAX(aStartRowIndex, aEndRowIndex);
-  PRInt32 minColIndex = PR_MIN(aStartColumnIndex, aEndColumnIndex);
-  PRInt32 maxColIndex = PR_MAX(aStartColumnIndex, aEndColumnIndex);
+  PRInt32 minRowIndex = NS_MIN(aStartRowIndex, aEndRowIndex);
+  PRInt32 maxRowIndex = NS_MAX(aStartRowIndex, aEndRowIndex);
+  PRInt32 minColIndex = NS_MIN(aStartColumnIndex, aEndColumnIndex);
+  PRInt32 maxColIndex = NS_MAX(aStartColumnIndex, aEndColumnIndex);
 
   // Strong reference because we sometimes remove the range
   nsCOMPtr<nsIRange> range = GetFirstCellRange();
   nsIContent* cellNode = GetFirstSelectedContent(range);
   NS_PRECONDITION(!range || cellNode, "Must have cellNode if had a range");
 
   PRInt32 curRowIndex, curColIndex;
   while (cellNode)
@@ -4408,34 +4408,34 @@ nsTypedSelection::LookUpSelection(nsICon
     PRInt32 startOffset = range->StartOffset();
     PRInt32 endOffset = range->EndOffset();
 
     PRInt32 start = -1, end = -1;
     if (startNode == aContent && endNode == aContent) {
       if (startOffset < (aContentOffset + aContentLength)  &&
           endOffset > aContentOffset) {
         // this range is totally inside the requested content range
-        start = PR_MAX(0, startOffset - aContentOffset);
-        end = PR_MIN(aContentLength, endOffset - aContentOffset);
+        start = NS_MAX(0, startOffset - aContentOffset);
+        end = NS_MIN(aContentLength, endOffset - aContentOffset);
       }
       // otherwise, range is inside the requested node, but does not intersect
       // the requested content range, so ignore it
     } else if (startNode == aContent) {
       if (startOffset < (aContentOffset + aContentLength)) {
         // the beginning of the range is inside the requested node, but the
         // end is outside, select everything from there to the end
-        start = PR_MAX(0, startOffset - aContentOffset);
+        start = NS_MAX(0, startOffset - aContentOffset);
         end = aContentLength;
       }
     } else if (endNode == aContent) {
       if (endOffset > aContentOffset) {
         // the end of the range is inside the requested node, but the beginning
         // is outside, select everything from the beginning to there
         start = 0;
-        end = PR_MIN(aContentLength, endOffset - aContentOffset);
+        end = NS_MIN(aContentLength, endOffset - aContentOffset);
       }
     } else {
       // this range does not begin or end in the requested node, but since
       // GetRangesForInterval returned this range, we know it overlaps.
       // Therefore, this node is enclosed in the range, and we select all
       // of it.
       start = 0;
       end = aContentLength;
@@ -6345,17 +6345,17 @@ nsTypedSelection::SelectionLanguageChang
   }
 
   if ((levelBefore & 1) == (levelAfter & 1)) {
     // if cursor is between two characters with the same orientation, changing the keyboard language
     //  must toggle the cursor level between the level of the character with the lowest level
     //  (if the new language corresponds to the orientation of that character) and this level plus 1
     //  (if the new language corresponds to the opposite orientation)
     if ((level != levelBefore) && (level != levelAfter))
-      level = PR_MIN(levelBefore, levelAfter);
+      level = NS_MIN(levelBefore, levelAfter);
     if ((level & 1) == aLangRTL)
       mFrameSelection->SetCaretBidiLevel(level);
     else
       mFrameSelection->SetCaretBidiLevel(level + 1);
   }
   else {
     // if cursor is between characters with opposite orientations, changing the keyboard language must change
     //  the cursor level to that of the adjacent character with the orientation corresponding to the new language.
--- a/layout/generic/nsSimplePageSequence.cpp
+++ b/layout/generic/nsSimplePageSequence.cpp
@@ -207,20 +207,20 @@ nsSimplePageSequenceFrame::Reflow(nsPres
     mPageData->mPrintSettings->GetPrintRange(&printType);
     mPrintRangeType = printType;
 
     nsIntMargin edgeTwips;
     mPageData->mPrintSettings->GetEdgeInTwips(edgeTwips);
 
     // sanity check the values. three inches are sometimes needed
     PRInt32 inchInTwips = NS_INCHES_TO_TWIPS(3.0);
-    edgeTwips.top = PR_MIN(PR_MAX(edgeTwips.top, 0), inchInTwips);
-    edgeTwips.bottom = PR_MIN(PR_MAX(edgeTwips.bottom, 0), inchInTwips);
-    edgeTwips.left = PR_MIN(PR_MAX(edgeTwips.left, 0), inchInTwips);
-    edgeTwips.right = PR_MIN(PR_MAX(edgeTwips.right, 0), inchInTwips);
+    edgeTwips.top = NS_MIN(NS_MAX(edgeTwips.top, 0), inchInTwips);
+    edgeTwips.bottom = NS_MIN(NS_MAX(edgeTwips.bottom, 0), inchInTwips);
+    edgeTwips.left = NS_MIN(NS_MAX(edgeTwips.left, 0), inchInTwips);
+    edgeTwips.right = NS_MIN(NS_MAX(edgeTwips.right, 0), inchInTwips);
 
     mPageData->mEdgePaperMargin =
       aPresContext->TwipsToAppUnits(edgeTwips + unwriteableTwips);
   }
 
   // *** Special Override ***
   // If this is a sub-sdoc (meaning it doesn't take the whole page)
   // and if this Document is in the upper left hand corner
@@ -234,22 +234,22 @@ nsSimplePageSequenceFrame::Reflow(nsPres
   // even if it's beyond the first page of content.
   if (nsIPrintSettings::kRangeSelection == mPrintRangeType) {
     mPageData->mReflowSize.height = NS_UNCONSTRAINEDSIZE;
   }
   mPageData->mReflowMargin = mMargin;
 
   // Compute the size of each page and the x coordinate that each page will
   // be placed at
-  nscoord extraThreshold = PR_MAX(pageSize.width, pageSize.height)/10;
+  nscoord extraThreshold = NS_MAX(pageSize.width, pageSize.height)/10;
   PRInt32 gapInTwips = nsContentUtils::GetIntPref("print.print_extra_margin");
-  gapInTwips = PR_MAX(0, gapInTwips);
+  gapInTwips = NS_MAX(0, gapInTwips);
 
   nscoord extraGap = aPresContext->TwipsToAppUnits(gapInTwips);
-  extraGap = PR_MIN(extraGap, extraThreshold); // clamp to 1/10 of the largest dim of the page
+  extraGap = NS_MIN(extraGap, extraThreshold); // clamp to 1/10 of the largest dim of the page
 
   nscoord  deadSpaceGap = 0;
   if (isPrintPreview) {
     GetDeadSpaceValue(&gapInTwips);
     deadSpaceGap = aPresContext->TwipsToAppUnits(gapInTwips);
   }
 
   nsMargin extraMargin(0,0,0,0);
--- a/layout/generic/nsTextFrameThebes.cpp
+++ b/layout/generic/nsTextFrameThebes.cpp
@@ -3107,17 +3107,17 @@ nsTextPaintStyle::InitCommonColors()
   look->GetColor(nsILookAndFeel::eColor_TextSelectBackground,
                  selectionBGColor);
   look->GetColor(nsILookAndFeel::eColor_TextSelectForeground,
                  selectionTextColor);
   look->GetColor(nsILookAndFeel::eColor_WindowBackground,
                  defaultWindowBackgroundColor);
 
   mSufficientContrast =
-    PR_MIN(PR_MIN(NS_SUFFICIENT_LUMINOSITY_DIFFERENCE,
+    NS_MIN(NS_MIN(NS_SUFFICIENT_LUMINOSITY_DIFFERENCE,
                   NS_LUMINOSITY_DIFFERENCE(selectionTextColor,
                                            selectionBGColor)),
                   NS_LUMINOSITY_DIFFERENCE(defaultWindowBackgroundColor,
                                            selectionBGColor));
 
   mInitCommonColors = PR_TRUE;
 }
 
@@ -4149,19 +4149,19 @@ ComputeSelectionUnderlineHeight(nsPresCo
       // The thickness of the spellchecker underline shouldn't honor the font
       // metrics.  It should be constant pixels value which is decided from the
       // default font size.  Note that if the actual font size is smaller than
       // the default font size, we should use the actual font size because the
       // computed value from the default font size can be too thick for the
       // current font size.
       PRInt32 defaultFontSize =
         aPresContext->AppUnitsToDevPixels(nsStyleFont(aPresContext).mFont.size);
-      gfxFloat fontSize = PR_MIN(gfxFloat(defaultFontSize),
+      gfxFloat fontSize = NS_MIN(gfxFloat(defaultFontSize),
                                  aFontMetrics.emHeight);
-      fontSize = PR_MAX(fontSize, 1.0);
+      fontSize = NS_MAX(fontSize, 1.0);
       return NS_ceil(fontSize / 20);
     }
     default:
       NS_WARNING("Requested underline style is not valid");
       return aFontMetrics.underlineSize;
   }
 }
 
@@ -4428,17 +4428,17 @@ AddHyphenToMetrics(nsTextFrame* aTextFra
 void
 nsTextFrame::PaintOneShadow(PRUint32 aOffset, PRUint32 aLength,
                             nsCSSShadowItem* aShadowDetails,
                             PropertyProvider* aProvider, const gfxRect& aDirtyRect,
                             const gfxPoint& aFramePt, const gfxPoint& aTextBaselinePt,
                             gfxContext* aCtx, const nscolor& aForegroundColor)
 {
   gfxPoint shadowOffset(aShadowDetails->mXOffset, aShadowDetails->mYOffset);
-  nscoord blurRadius = PR_MAX(aShadowDetails->mRadius, 0);
+  nscoord blurRadius = NS_MAX(aShadowDetails->mRadius, 0);
 
   gfxTextRun::Metrics shadowMetrics =
     mTextRun->MeasureText(aOffset, aLength, gfxFont::LOOSE_INK_EXTENTS,
                           nsnull, aProvider);
   if (GetStateBits() & TEXT_HYPHEN_BREAK) {
     AddHyphenToMetrics(this, mTextRun, &shadowMetrics, gfxFont::LOOSE_INK_EXTENTS, aCtx);
   }
 
@@ -4508,18 +4508,18 @@ nsTextFrame::PaintTextWithSelectionColor
   SelectionType allTypes = 0;
   for (i = 0; i < contentLength; ++i) {
     prevailingSelections[i] = nsnull;
   }
 
   SelectionDetails *sdptr = aDetails;
   PRBool anyBackgrounds = PR_FALSE;
   while (sdptr) {
-    PRInt32 start = PR_MAX(0, sdptr->mStart - contentOffset);
-    PRInt32 end = PR_MIN(contentLength, sdptr->mEnd - contentOffset);
+    PRInt32 start = NS_MAX(0, sdptr->mStart - contentOffset);
+    PRInt32 end = NS_MIN(contentLength, sdptr->mEnd - contentOffset);
     SelectionType type = sdptr->mType;
     if (start < end) {
       allTypes |= type;
       // Ignore selections that don't set colors
       nscolor foreground, background;
       if (GetSelectionTextColors(type, aTextPaintStyle, sdptr->mTextRangeStyle,
                                  &foreground, &background)) {
         if (NS_GET_A(background) > 0) {
@@ -4604,18 +4604,18 @@ nsTextFrame::PaintTextSelectionDecoratio
   PRInt32 i;
   for (i = 0; i < contentLength; ++i) {
     selectedChars[i] = nsnull;
   }
 
   SelectionDetails *sdptr = aDetails;
   while (sdptr) {
     if (sdptr->mType == aSelectionType) {
-      PRInt32 start = PR_MAX(0, sdptr->mStart - contentOffset);
-      PRInt32 end = PR_MIN(contentLength, sdptr->mEnd - contentOffset);
+      PRInt32 start = NS_MAX(0, sdptr->mStart - contentOffset);
+      PRInt32 end = NS_MIN(contentLength, sdptr->mEnd - contentOffset);
       for (i = start; i < end; ++i) {
         selectedChars[i] = sdptr;
       }
     }
     sdptr = sdptr->mNext;
   }
 
   gfxFont* firstFont = aProvider.GetFontGroup()->GetFontAt(0);
@@ -4979,17 +4979,17 @@ nsTextFrame::CombineSelectionUnderlineRe
                                                           &style)) {
         continue;
       }
     }
     nsRect decorationArea;
     gfxSize size(aPresContext->AppUnitsToGfxUnits(aRect.width),
                  ComputeSelectionUnderlineHeight(aPresContext,
                                                  metrics, sd->mType));
-    relativeSize = PR_MAX(relativeSize, 1.0f);
+    relativeSize = NS_MAX(relativeSize, 1.0f);
     size.height *= relativeSize;
     decorationArea =
       nsCSSRendering::GetTextDecorationRect(aPresContext, size,
                                             ascent, underlineOffset,
                                             NS_STYLE_TEXT_DECORATION_UNDERLINE,
                                             style, descentLimit);
     aRect.UnionRect(aRect, decorationArea);
   }
@@ -5118,18 +5118,18 @@ nsTextFrame::GetPointFromOffset(PRInt32 
     NS_WARNING("offset before this frame's content");
     inOffset = GetContentOffset();
   } else if (inOffset > GetContentEnd()) {
     NS_WARNING("offset after this frame's content");
     inOffset = GetContentEnd();
   }
   PRInt32 trimmedOffset = properties.GetStart().GetOriginalOffset();
   PRInt32 trimmedEnd = trimmedOffset + properties.GetOriginalLength();
-  inOffset = PR_MAX(inOffset, trimmedOffset);
-  inOffset = PR_MIN(inOffset, trimmedEnd);
+  inOffset = NS_MAX(inOffset, trimmedOffset);
+  inOffset = NS_MIN(inOffset, trimmedEnd);
 
   iter.SetOriginalOffset(inOffset);
 
   if (inOffset < trimmedEnd &&
       !iter.IsOriginalCharSkipped() &&
       !mTextRun->IsClusterStart(iter.GetSkippedOffset())) {
     NS_WARNING("GetPointFromOffset called for non-cluster boundary");
     FindClusterStart(mTextRun, &iter);
@@ -5278,17 +5278,17 @@ nsTextFrame::PeekOffsetCharacter(PRBool 
 
   TrimmedOffsets trimmed = GetTrimmedOffsets(GetFragment(), PR_FALSE);
 
   // A negative offset means "end of frame".
   PRInt32 startOffset = GetContentOffset() + (*aOffset < 0 ? contentLength : *aOffset);
 
   if (!aForward) {
     PRInt32 i;
-    for (i = PR_MIN(trimmed.GetEnd(), startOffset) - 1;
+    for (i = NS_MIN(trimmed.GetEnd(), startOffset) - 1;
          i >= trimmed.mStart; --i) {
       iter.SetOriginalOffset(i);
       if (IsAcceptableCaretPosition(iter, mTextRun, this)) {
         *aOffset = i - mContentOffset;
         return PR_TRUE;
       }
     }
     *aOffset = 0;
@@ -6095,17 +6095,17 @@ nsTextFrame::Reflow(nsPresContext*      
 
       if (mTextRun) {
         PRInt32 firstLetterLength = length;
         if (lineLayout.GetFirstLetterStyleOK()) {
           completedFirstLetter =
             FindFirstLetterRange(frag, mTextRun, offset, iter, &firstLetterLength);
           if (newLineOffset >= 0) {
             // Don't allow a preformatted newline to be part of a first-letter.
-            firstLetterLength = PR_MIN(firstLetterLength, length - 1);
+            firstLetterLength = NS_MIN(firstLetterLength, length - 1);
             if (length == 1) {
               // There is no text to be consumed by the first-letter before the
               // preformatted newline. Note that the first letter is therefore
               // complete (FindFirstLetterRange will have returned false).
               completedFirstLetter = PR_TRUE;
             }
           }
         } else {
@@ -6301,41 +6301,41 @@ nsTextFrame::Reflow(nsPresContext*      
 
   /////////////////////////////////////////////////////////////////////
   // Compute output metrics
   /////////////////////////////////////////////////////////////////////
 
   // first-letter frames should use the tight bounding box metrics for ascent/descent
   // for good drop-cap effects
   if (GetStateBits() & TEXT_FIRST_LETTER) {
-    textMetrics.mAscent = PR_MAX(0, -textMetrics.mBoundingBox.Y());
-    textMetrics.mDescent = PR_MAX(0, textMetrics.mBoundingBox.YMost());
+    textMetrics.mAscent = NS_MAX(gfxFloat(0.0), -textMetrics.mBoundingBox.Y());
+    textMetrics.mDescent = NS_MAX(gfxFloat(0.0), textMetrics.mBoundingBox.YMost());
   }
 
   // Setup metrics for caller
   // Disallow negative widths
-  aMetrics.width = NSToCoordCeil(PR_MAX(0, textMetrics.mAdvanceWidth));
+  aMetrics.width = NSToCoordCeil(NS_MAX(gfxFloat(0.0), textMetrics.mAdvanceWidth));
 
   if (transformedCharsFit == 0 && !usedHyphenation) {
     aMetrics.ascent = 0;
     aMetrics.height = 0;
   } else if (boundingBoxType != gfxFont::LOOSE_INK_EXTENTS) {
     // Use actual text metrics for floating first letter frame.
     aMetrics.ascent = NSToCoordCeil(textMetrics.mAscent);
     aMetrics.height = aMetrics.ascent + NSToCoordCeil(textMetrics.mDescent);
   } else {
     // Otherwise, ascent should contain the overline drawable area.
     // And also descent should contain the underline drawable area.
     // nsIFontMetrics::GetMaxAscent/GetMaxDescent contains them.
     nscoord fontAscent, fontDescent;
     nsIFontMetrics* fm = provider.GetFontMetrics();
     fm->GetMaxAscent(fontAscent);
     fm->GetMaxDescent(fontDescent);
-    aMetrics.ascent = PR_MAX(NSToCoordCeil(textMetrics.mAscent), fontAscent);
-    nscoord descent = PR_MAX(NSToCoordCeil(textMetrics.mDescent), fontDescent);
+    aMetrics.ascent = NS_MAX(NSToCoordCeil(textMetrics.mAscent), fontAscent);
+    nscoord descent = NS_MAX(NSToCoordCeil(textMetrics.mDescent), fontDescent);
     aMetrics.height = aMetrics.ascent + descent;
   }
 
   NS_ASSERTION(aMetrics.ascent >= 0, "Negative ascent???");
   NS_ASSERTION(aMetrics.height - aMetrics.ascent >= 0, "Negative descent???");
 
   mAscent = aMetrics.ascent;
 
@@ -6844,18 +6844,18 @@ nsTextFrame::AdjustOffsetsForBidi(PRInt3
    */
   ClearTextRun();
 
   nsTextFrame* prev = static_cast<nsTextFrame*>(GetPrevContinuation());
   if (prev) {
     // the bidi resolver can be very evil when columns/pages are involved. Don't
     // let it violate our invariants.
     PRInt32 prevOffset = prev->GetContentOffset();
-    aStart = PR_MAX(aStart, prevOffset);
-    aEnd = PR_MAX(aEnd, prevOffset);
+    aStart = NS_MAX(aStart, prevOffset);
+    aEnd = NS_MAX(aEnd, prevOffset);
     prev->ClearTextRun();
   }
 
   mContentOffset = aStart;
   SetLength(aEnd - aStart);
 }
 
 /**
--- a/layout/generic/nsTextFrameUtils.cpp
+++ b/layout/generic/nsTextFrameUtils.cpp
@@ -256,13 +256,13 @@ PRBool nsSkipCharsRunIterator::NextRun()
       if (!mSkipped || mLengthIncludesSkipped) {
         mRemainingLength -= mRunLength;
       }
     }
     if (!mRemainingLength)
       return PR_FALSE;
     PRInt32 length;
     mSkipped = mIterator.IsOriginalCharSkipped(&length);
-    mRunLength = PR_MIN(length, mRemainingLength);
+    mRunLength = NS_MIN(length, mRemainingLength);
   } while (!mVisitSkipped && mSkipped);
 
   return PR_TRUE;
 }
--- a/layout/generic/nsVideoFrame.cpp
+++ b/layout/generic/nsVideoFrame.cpp
@@ -153,17 +153,17 @@ nsVideoFrame::IsLeaf() const
 // same aspect ratio as aRatio, centered at the center of aRect
 static gfxRect
 CorrectForAspectRatio(const gfxRect& aRect, const nsIntSize& aRatio)
 {
   NS_ASSERTION(aRatio.width > 0 && aRatio.height > 0 && !aRect.IsEmpty(),
                "Nothing to draw");
   // Choose scale factor that scales aRatio to just fit into aRect
   gfxFloat scale =
-    PR_MIN(aRect.Width()/aRatio.width, aRect.Height()/aRatio.height);
+    NS_MIN(aRect.Width()/aRatio.width, aRect.Height()/aRatio.height);
   gfxSize scaledRatio(scale*aRatio.width, scale*aRatio.height);
   gfxPoint topLeft((aRect.Width() - scaledRatio.width)/2,
                    (aRect.Height() - scaledRatio.height)/2);
   return gfxRect(aRect.TopLeft() + topLeft, scaledRatio);
 }
 
 void
 nsVideoFrame::PaintVideo(nsIRenderingContext& aRenderingContext,
--- a/layout/mathml/nsMathMLChar.cpp
+++ b/layout/mathml/nsMathMLChar.cpp
@@ -1001,17 +1001,17 @@ IsSizeOK(nsPresContext* aPresContext, ns
     (aHint & NS_STRETCH_NORMAL)
     && PRBool(float(PR_ABS(a - b))
               < (1.0f - NS_MATHML_DELIMITER_FACTOR) * float(b));
   // Nearer: True if 'a' is around max{ +/-10% of 'b' , 'b' - 5pt },
   // as documented in The TeXbook, Ch.17, p.152.
   // i.e. within 10% and within 5pt
   PRBool isNearer = PR_FALSE;
   if (aHint & (NS_STRETCH_NEARER | NS_STRETCH_LARGEOP)) {
-    float c = PR_MAX(float(b) * NS_MATHML_DELIMITER_FACTOR,
+    float c = NS_MAX(float(b) * NS_MATHML_DELIMITER_FACTOR,
                      float(b) - aPresContext->PointsToAppUnits(NS_MATHML_DELIMITER_SHORTFALL_POINTS));
     isNearer = PRBool(float(PR_ABS(b - a)) <= (float(b) - c));
   }
   // Smaller: Mainly for transitory use, to compare two candidate
   // choices
   PRBool isSmaller =
     (aHint & NS_STRETCH_SMALLER)
     && PRBool((float(a) >= (NS_MATHML_DELIMITER_FACTOR * float(b)))
@@ -1784,17 +1784,17 @@ nsMathMLChar::GetMaxWidth(nsPresContext*
 {
   nsBoundingMetrics bm;
   nsStretchDirection direction = NS_STRETCH_DIRECTION_VERTICAL;
   const nsBoundingMetrics container; // zero target size
 
   StretchInternal(aPresContext, aRenderingContext, direction, container,
                   bm, aStretchHint | NS_STRETCH_MAXWIDTH);
 
-  return PR_MAX(bm.width, bm.rightBearing) - PR_MIN(0, bm.leftBearing);
+  return NS_MAX(bm.width, bm.rightBearing) - NS_MIN(0, bm.leftBearing);
 }
 
 nsresult
 nsMathMLChar::ComposeChildren(nsPresContext*      aPresContext,
                               nsIRenderingContext& aRenderingContext,
                               nsGlyphTable*        aGlyphTable,
                               nscoord              aTargetSize,
                               nsBoundingMetrics&   aCompositeSize,
@@ -2356,29 +2356,29 @@ nsMathMLChar::PaintVertically(nsPresCont
     }
 
     SetFontFamily(aPresContext, aRenderingContext,
                   aFont, aGlyphTable, chGlue, mFamily);
     nsRect clipRect = unionRect;
 
     for (i = 0; i < bottom; ++i) {
       // Make sure not to draw outside the character
-      nscoord dy = PR_MAX(end[i], aRect.y);
-      nscoord fillEnd = PR_MIN(start[i+1], aRect.YMost());
+      nscoord dy = NS_MAX(end[i], aRect.y);
+      nscoord fillEnd = NS_MIN(start[i+1], aRect.YMost());
 #ifdef SHOW_BORDERS
       // exact area to fill
       aRenderingContext.SetColor(NS_RGB(255,0,0));
       clipRect.y = dy;
       clipRect.height = fillEnd - dy;
       aRenderingContext.DrawRect(clipRect);
       {
 #endif
       while (dy < fillEnd) {
         clipRect.y = dy;
-        clipRect.height = PR_MIN(bm.ascent + bm.descent, fillEnd - dy);
+        clipRect.height = NS_MIN(bm.ascent + bm.descent, fillEnd - dy);
         AutoPushClipRect clip(aRenderingContext, clipRect);
         dy += bm.ascent;
         aRenderingContext.DrawString(&chGlue.code, 1, dx, dy);
         dy += bm.descent;
       }
 #ifdef SHOW_BORDERS
       }
       // last glyph that may cross past its boundary and collide with the next
@@ -2583,29 +2583,29 @@ nsMathMLChar::PaintHorizontally(nsPresCo
     }
 
     SetFontFamily(aPresContext, aRenderingContext,
                   aFont, aGlyphTable, chGlue, mFamily);
     nsRect clipRect = unionRect;
 
     for (i = 0; i < right; ++i) {
       // Make sure not to draw outside the character
-      nscoord dx = PR_MAX(end[i], aRect.x);
-      nscoord fillEnd = PR_MIN(start[i+1], aRect.XMost());
+      nscoord dx = NS_MAX(end[i], aRect.x);
+      nscoord fillEnd = NS_MIN(start[i+1], aRect.XMost());
 #ifdef SHOW_BORDERS
       // rectangles in-between that are to be filled
       aRenderingContext.SetColor(NS_RGB(255,0,0));
       clipRect.x = dx;
       clipRect.width = fillEnd - dx;
       aRenderingContext.DrawRect(clipRect);
       {
 #endif
       while (dx < fillEnd) {
         clipRect.x = dx;
-        clipRect.width = PR_MIN(bm.rightBearing - bm.leftBearing, fillEnd - dx);
+        clipRect.width = NS_MIN(bm.rightBearing - bm.leftBearing, fillEnd - dx);
         AutoPushClipRect clip(aRenderingContext, clipRect);
         dx -= bm.leftBearing;
         aRenderingContext.DrawString(&chGlue.code, 1, dx, dy);
         dx += bm.rightBearing;
       }
 #ifdef SHOW_BORDERS
       }
       // last glyph that may cross past its boundary and collide with the next
--- a/layout/mathml/nsMathMLTokenFrame.cpp
+++ b/layout/mathml/nsMathMLTokenFrame.cpp
@@ -213,19 +213,19 @@ nsMathMLTokenFrame::Place(nsIRenderingCo
   nsCOMPtr<nsIFontMetrics> fm =
     PresContext()->GetMetricsFor(GetStyleFont()->mFont);
   nscoord ascent, descent;
   fm->GetMaxAscent(ascent);
   fm->GetMaxDescent(descent);
 
   aDesiredSize.mBoundingMetrics = mBoundingMetrics;
   aDesiredSize.width = mBoundingMetrics.width;
-  aDesiredSize.ascent = PR_MAX(mBoundingMetrics.ascent, ascent);
+  aDesiredSize.ascent = NS_MAX(mBoundingMetrics.ascent, ascent);
   aDesiredSize.height = aDesiredSize.ascent +
-                        PR_MAX(mBoundingMetrics.descent, descent);
+                        NS_MAX(mBoundingMetrics.descent, descent);
 
   if (aPlaceOrigin) {
     nscoord dy, dx = 0;
     for (nsIFrame* childFrame = GetFirstChild(nsnull); childFrame;
          childFrame = childFrame->GetNextSibling()) {
       nsHTMLReflowMetrics childSize;
       GetReflowAndBoundingMetricsFor(childFrame, childSize,
                                      childSize.mBoundingMetrics);
--- a/layout/mathml/nsMathMLmencloseFrame.cpp
+++ b/layout/mathml/nsMathMLmencloseFrame.cpp
@@ -432,18 +432,18 @@ nsMathMLmencloseFrame::PlaceInternal(nsI
       IsToDraw(NOTATION_UPDIAGONALSTRIKE) ||
       IsToDraw(NOTATION_DOWNDIAGONALSTRIKE) ||
       IsToDraw(NOTATION_VERTICALSTRIKE) ||
       IsToDraw(NOTATION_CIRCLE) ||
       IsToDraw(NOTATION_ROUNDEDBOX) ||
       IsToDraw(NOTATION_RADICAL) ||
       IsToDraw(NOTATION_LONGDIV)) {
       // set a minimal value for the base height
-      bmBase.ascent = PR_MAX(bmOne.ascent, bmBase.ascent);
-      bmBase.descent = PR_MAX(0, bmBase.descent);
+      bmBase.ascent = NS_MAX(bmOne.ascent, bmBase.ascent);
+      bmBase.descent = NS_MAX(0, bmBase.descent);
   }
 
   mBoundingMetrics.ascent = bmBase.ascent;
   mBoundingMetrics.descent = bmBase.descent;
     
   if (IsToDraw(NOTATION_ROUNDEDBOX) ||
       IsToDraw(NOTATION_TOP) ||
       IsToDraw(NOTATION_LEFT) ||
@@ -464,160 +464,160 @@ nsMathMLmencloseFrame::PlaceInternal(nsI
   // factor of at least sqrt(2).
   if (IsToDraw(NOTATION_CIRCLE)) {
     double ratio = (sqrt(2.0) - 1.0) / 2.0;
     nscoord padding2;
 
     // Update horizontal parameters
     padding2 = ratio * bmBase.width;
 
-    dx_left = PR_MAX(dx_left, padding2);
-    dx_right = PR_MAX(dx_right, padding2);
+    dx_left = NS_MAX(dx_left, padding2);
+    dx_right = NS_MAX(dx_right, padding2);
 
     // Update vertical parameters
     padding2 = ratio * (bmBase.ascent + bmBase.descent);
 
-    mBoundingMetrics.ascent = PR_MAX(mBoundingMetrics.ascent,
+    mBoundingMetrics.ascent = NS_MAX(mBoundingMetrics.ascent,
                                      bmBase.ascent + padding2);
-    mBoundingMetrics.descent = PR_MAX(mBoundingMetrics.descent,
+    mBoundingMetrics.descent = NS_MAX(mBoundingMetrics.descent,
                                       bmBase.descent + padding2);
   }
 
   ///////////////
   // longdiv notation:
   if (IsToDraw(NOTATION_LONGDIV)) {
     if (aWidthOnly) {
         nscoord longdiv_width = mMathMLChar[mLongDivCharIndex].
           GetMaxWidth(PresContext(), aRenderingContext);
 
         // Update horizontal parameters
-        dx_left = PR_MAX(dx_left, longdiv_width);
+        dx_left = NS_MAX(dx_left, longdiv_width);
     } else {
       // Stretch the parenthesis to the appropriate height if it is not
       // big enough.
       nsBoundingMetrics contSize = bmBase;
       contSize.ascent = mRuleThickness;
       contSize.descent = bmBase.ascent + bmBase.descent + psi;
 
       // height(longdiv) should be >= height(base) + psi + mRuleThickness
       mMathMLChar[mLongDivCharIndex].Stretch(PresContext(), aRenderingContext,
                                              NS_STRETCH_DIRECTION_VERTICAL,
                                              contSize, bmLongdivChar,
                                              NS_STRETCH_LARGER);
       mMathMLChar[mLongDivCharIndex].GetBoundingMetrics(bmLongdivChar);
 
       // Update horizontal parameters
-      dx_left = PR_MAX(dx_left, bmLongdivChar.width);
+      dx_left = NS_MAX(dx_left, bmLongdivChar.width);
 
       // Update vertical parameters
       longdivAscent = bmBase.ascent + psi + mRuleThickness;
-      longdivDescent = PR_MAX(bmBase.descent,
+      longdivDescent = NS_MAX(bmBase.descent,
                               (bmLongdivChar.ascent + bmLongdivChar.descent -
                                longdivAscent));
 
-      mBoundingMetrics.ascent = PR_MAX(mBoundingMetrics.ascent,
+      mBoundingMetrics.ascent = NS_MAX(mBoundingMetrics.ascent,
                                        longdivAscent);
-      mBoundingMetrics.descent = PR_MAX(mBoundingMetrics.descent,
+      mBoundingMetrics.descent = NS_MAX(mBoundingMetrics.descent,
                                         longdivDescent);
     }
   }
 
   ///////////////
   // radical notation:
   if (IsToDraw(NOTATION_RADICAL)) {
     if (aWidthOnly) {
       nscoord radical_width = mMathMLChar[mRadicalCharIndex].
         GetMaxWidth(PresContext(), aRenderingContext);
       
       // Update horizontal parameters
-      dx_left = PR_MAX(dx_left, radical_width);
+      dx_left = NS_MAX(dx_left, radical_width);
     } else {
       // Stretch the radical symbol to the appropriate height if it is not
       // big enough.
       nsBoundingMetrics contSize = bmBase;
       contSize.ascent = mRuleThickness;
       contSize.descent = bmBase.ascent + bmBase.descent + psi;
 
       // height(radical) should be >= height(base) + psi + mRuleThickness
       mMathMLChar[mRadicalCharIndex].Stretch(PresContext(), aRenderingContext,
                                              NS_STRETCH_DIRECTION_VERTICAL,
                                              contSize, bmRadicalChar,
                                              NS_STRETCH_LARGER);
       mMathMLChar[mRadicalCharIndex].GetBoundingMetrics(bmRadicalChar);
 
       // Update horizontal parameters
-      dx_left = PR_MAX(dx_left, bmRadicalChar.width);
+      dx_left = NS_MAX(dx_left, bmRadicalChar.width);
 
       // Update vertical parameters
       radicalAscent = bmBase.ascent + psi + mRuleThickness;
-      radicalDescent = PR_MAX(bmBase.descent,
+      radicalDescent = NS_MAX(bmBase.descent,
                               (bmRadicalChar.ascent + bmRadicalChar.descent -
                                radicalAscent));
 
-      mBoundingMetrics.ascent = PR_MAX(mBoundingMetrics.ascent,
+      mBoundingMetrics.ascent = NS_MAX(mBoundingMetrics.ascent,
                                        radicalAscent);
-      mBoundingMetrics.descent = PR_MAX(mBoundingMetrics.descent,
+      mBoundingMetrics.descent = NS_MAX(mBoundingMetrics.descent,
                                         radicalDescent);
     }
   }
 
   ///////////////
   //
   if (IsToDraw(NOTATION_CIRCLE) ||
       IsToDraw(NOTATION_ROUNDEDBOX) ||
       (IsToDraw(NOTATION_LEFT) && IsToDraw(NOTATION_RIGHT))) {
     // center the menclose around the content (horizontally)
-    dx_left = dx_right = PR_MAX(dx_left, dx_right);
+    dx_left = dx_right = NS_MAX(dx_left, dx_right);
   }
 
   ///////////////
   // The maximum size is now computed: set the remaining parameters
   mBoundingMetrics.width = dx_left + bmBase.width + dx_right;
 
-  mBoundingMetrics.leftBearing = PR_MIN(0, dx_left + bmBase.leftBearing);
+  mBoundingMetrics.leftBearing = NS_MIN(0, dx_left + bmBase.leftBearing);
   mBoundingMetrics.rightBearing =
-    PR_MAX(mBoundingMetrics.width, dx_left + bmBase.rightBearing);
+    NS_MAX(mBoundingMetrics.width, dx_left + bmBase.rightBearing);
   
   aDesiredSize.width = mBoundingMetrics.width;
 
-  aDesiredSize.ascent = PR_MAX(mBoundingMetrics.ascent, baseSize.ascent);
+  aDesiredSize.ascent = NS_MAX(mBoundingMetrics.ascent, baseSize.ascent);
   aDesiredSize.height = aDesiredSize.ascent +
-    PR_MAX(mBoundingMetrics.descent, baseSize.height - baseSize.ascent);
+    NS_MAX(mBoundingMetrics.descent, baseSize.height - baseSize.ascent);
 
   if (IsToDraw(NOTATION_LONGDIV) || IsToDraw(NOTATION_RADICAL)) {
     // get the leading to be left at the top of the resulting frame
     // this seems more reliable than using fm->GetLeading() on suspicious
     // fonts
     nscoord leading = nscoord(0.2f * mEmHeight);
     nscoord desiredSizeAscent = aDesiredSize.ascent;
     nscoord desiredSizeDescent = aDesiredSize.height - aDesiredSize.ascent;
     
     if (IsToDraw(NOTATION_LONGDIV)) {
-      desiredSizeAscent = PR_MAX(desiredSizeAscent,
+      desiredSizeAscent = NS_MAX(desiredSizeAscent,
                                  longdivAscent + leading);
-      desiredSizeDescent = PR_MAX(desiredSizeDescent,
+      desiredSizeDescent = NS_MAX(desiredSizeDescent,
                                   longdivDescent + mRuleThickness);
     }
     
     if (IsToDraw(NOTATION_RADICAL)) {
-      desiredSizeAscent = PR_MAX(desiredSizeAscent,
+      desiredSizeAscent = NS_MAX(desiredSizeAscent,
                                  radicalAscent + leading);
-      desiredSizeDescent = PR_MAX(desiredSizeDescent,
+      desiredSizeDescent = NS_MAX(desiredSizeDescent,
                                   radicalDescent + mRuleThickness);
     }
 
     aDesiredSize.ascent = desiredSizeAscent;
     aDesiredSize.height = desiredSizeAscent + desiredSizeDescent;
   }
     
   if (IsToDraw(NOTATION_CIRCLE) ||
       IsToDraw(NOTATION_ROUNDEDBOX) ||
       (IsToDraw(NOTATION_TOP) && IsToDraw(NOTATION_BOTTOM))) {
     // center the menclose around the content (vertically)
-    nscoord dy = PR_MAX(aDesiredSize.ascent - bmBase.ascent,
+    nscoord dy = NS_MAX(aDesiredSize.ascent - bmBase.ascent,
                         aDesiredSize.height - aDesiredSize.ascent -
                         bmBase.descent);
 
     aDesiredSize.ascent = bmBase.ascent + dy;
     aDesiredSize.height = aDesiredSize.ascent + bmBase.descent + dy;
   }
 
   // Update mBoundingMetrics ascent/descent
--- a/layout/mathml/nsMathMLmfencedFrame.cpp
+++ b/layout/mathml/nsMathMLmfencedFrame.cpp
@@ -381,17 +381,17 @@ nsMathMLmfencedFrame::doReflow(nsPresCon
   }
 
   //////////////////////////////////////////
   // Prepare the opening fence, separators, and closing fence, and
   // adjust the origin of children.
 
   // we need to center around the axis
   if (firstChild) { // do nothing for an empty <mfenced></mfenced>
-    nscoord delta = PR_MAX(containerSize.ascent - axisHeight, 
+    nscoord delta = NS_MAX(containerSize.ascent - axisHeight, 
                            containerSize.descent + axisHeight);
     containerSize.ascent = delta + axisHeight;
     containerSize.descent = delta - axisHeight;
   }
 
   /////////////////
   // opening fence ...
   ReflowChar(aPresContext, *aReflowState.rendContext, aOpenChar,
--- a/layout/mathml/nsMathMLmfracFrame.cpp
+++ b/layout/mathml/nsMathMLmfracFrame.cpp
@@ -318,18 +318,18 @@ nsMathMLmfracFrame::Place(nsIRenderingCo
 
   // by default, leave at least one-pixel padding at either end, or use
   // lspace & rspace that may come from <mo> if we are an embellished container
   // (we fetch values from the core since they may use units that depend
   // on style data, and style changes could have occurred in the core since
   // our last visit there)
   nsEmbellishData coreData;
   GetEmbellishDataFrom(mEmbellishData.coreFrame, coreData);
-  nscoord leftSpace = PR_MAX(onePixel, coreData.leftSpace);
-  nscoord rightSpace = PR_MAX(onePixel, coreData.rightSpace);
+  nscoord leftSpace = NS_MAX(onePixel, coreData.leftSpace);
+  nscoord rightSpace = NS_MAX(onePixel, coreData.rightSpace);
 
   // see if the linethickness attribute is there 
   nsAutoString value;
   GetAttribute(mContent, mPresentationData.mstyle, nsGkAtoms::linethickness_, value);
   mLineRect.height = CalcLineThickness(presContext, mStyleContext, value,
                                        onePixel, defaultRuleThickness);
   nscoord numShift = 0;
   nscoord denShift = 0;
@@ -401,17 +401,17 @@ nsMathMLmfracFrame::Place(nsIRenderingCo
     }
   }
 
   //////////////////
   // Place Children
 
   // XXX Need revisiting the width. TeX uses the exact width
   // e.g. in $$\huge\frac{\displaystyle\int}{i}$$
-  nscoord width = PR_MAX(bmNum.width, bmDen.width);
+  nscoord width = NS_MAX(bmNum.width, bmDen.width);
   nscoord dxNum = leftSpace + (width - sizeNum.width)/2;
   nscoord dxDen = leftSpace + (width - sizeDen.width)/2;
   width += leftSpace + rightSpace;
 
   // see if the numalign attribute is there 
   GetAttribute(mContent, mPresentationData.mstyle, nsGkAtoms::numalign_,
                value);
   if (value.EqualsLiteral("left"))
@@ -423,21 +423,21 @@ nsMathMLmfracFrame::Place(nsIRenderingCo
   GetAttribute(mContent, mPresentationData.mstyle, nsGkAtoms::denomalign_,
                value);
   if (value.EqualsLiteral("left"))
     dxDen = leftSpace;
   else if (value.EqualsLiteral("right"))
     dxDen = width - rightSpace - sizeDen.width;
 
   mBoundingMetrics.rightBearing =
-    PR_MAX(dxNum + bmNum.rightBearing, dxDen + bmDen.rightBearing);
+    NS_MAX(dxNum + bmNum.rightBearing, dxDen + bmDen.rightBearing);
   if (mBoundingMetrics.rightBearing < width - rightSpace)
     mBoundingMetrics.rightBearing = width - rightSpace;
   mBoundingMetrics.leftBearing =
-    PR_MIN(dxNum + bmNum.leftBearing, dxDen + bmDen.leftBearing);
+    NS_MIN(dxNum + bmNum.leftBearing, dxDen + bmDen.leftBearing);
   if (mBoundingMetrics.leftBearing > leftSpace)
     mBoundingMetrics.leftBearing = leftSpace;
   mBoundingMetrics.ascent = bmNum.ascent + numShift;
   mBoundingMetrics.descent = bmDen.descent + denShift;
   mBoundingMetrics.width = width;
 
   aDesiredSize.ascent = sizeNum.ascent + numShift;
   aDesiredSize.height = aDesiredSize.ascent +
--- a/layout/mathml/nsMathMLmmultiscriptsFrame.cpp
+++ b/layout/mathml/nsMathMLmmultiscriptsFrame.cpp
@@ -170,37 +170,37 @@ nsMathMLmmultiscriptsFrame::Place(nsIRen
   fm->GetXHeight (xHeight);
 
   nscoord ruleSize;
   GetRuleThickness (aRenderingContext, fm, ruleSize);
 
   // scriptspace from TeX for extra spacing after sup/subscript (0.5pt in plain TeX)
   // forced to be at least 1 pixel here
   nscoord onePixel = nsPresContext::CSSPixelsToAppUnits(1);
-  nscoord scriptSpace = PR_MAX(PresContext()->PointsToAppUnits(0.5f), onePixel);
+  nscoord scriptSpace = NS_MAX(PresContext()->PointsToAppUnits(0.5f), onePixel);
 
   /////////////////////////////////////
   // first the shift for the subscript
 
   // subScriptShift{1,2}
   // = minimum amount to shift the subscript down
   // = sub{1,2} in TeXbook
   // subScriptShift1 = subscriptshift attribute * x-height
   nscoord subScriptShift1, subScriptShift2;
 
   // Get subScriptShift{1,2} default from font
   GetSubScriptShifts (fm, subScriptShift1, subScriptShift2);
   if (0 < mSubScriptShift) {
     // the user has set the subscriptshift attribute
     float scaler = ((float) subScriptShift2) / subScriptShift1;
-    subScriptShift1 = PR_MAX(subScriptShift1, mSubScriptShift);
+    subScriptShift1 = NS_MAX(subScriptShift1, mSubScriptShift);
     subScriptShift2 = NSToCoordRound(scaler * subScriptShift1);
   }
   // the font dependent shift
-  nscoord subScriptShift = PR_MAX(subScriptShift1,subScriptShift2);
+  nscoord subScriptShift = NS_MAX(subScriptShift1,subScriptShift2);
 
   /////////////////////////////////////
   // next the shift for the superscript
 
   // supScriptShift{1,2,3}
   // = minimum amount to shift the supscript up
   // = sup{1,2,3} in TeX
   // supScriptShift1 = superscriptshift attribute * x-height
@@ -208,17 +208,17 @@ nsMathMLmmultiscriptsFrame::Place(nsIRen
   // on the current style
   nscoord supScriptShift1, supScriptShift2, supScriptShift3;
   // Set supScriptShift{1,2,3} default from font
   GetSupScriptShifts (fm, supScriptShift1, supScriptShift2, supScriptShift3);
   if (0 < mSupScriptShift) {
     // the user has set the superscriptshift attribute
     float scaler2 = ((float) supScriptShift2) / supScriptShift1;
     float scaler3 = ((float) supScriptShift3) / supScriptShift1;
-    supScriptShift1 = PR_MAX(supScriptShift1, mSupScriptShift);
+    supScriptShift1 = NS_MAX(supScriptShift1, mSupScriptShift);
     supScriptShift2 = NSToCoordRound(scaler2 * supScriptShift1);
     supScriptShift3 = NSToCoordRound(scaler3 * supScriptShift1);
   }
 
   // get sup script shift depending on current script level and display style
   // Rule 18c, App. G, TeXbook
   nscoord supScriptShift;
   if ( font->mScriptLevel == 0 &&
@@ -297,53 +297,53 @@ nsMathMLmmultiscriptsFrame::Place(nsIRen
         if (isSubScript) {
           // subscript
           subScriptFrame = childFrame;
           GetReflowAndBoundingMetricsFor(subScriptFrame, subScriptSize, bmSubScript);
           // get the subdrop from the subscript font
           GetSubDropFromChild (subScriptFrame, subDrop);
           // parameter v, Rule 18a, App. G, TeXbook
           minSubScriptShift = bmBase.descent + subDrop;
-          trySubScriptShift = PR_MAX(minSubScriptShift,subScriptShift);
+          trySubScriptShift = NS_MAX(minSubScriptShift,subScriptShift);
           mBoundingMetrics.descent =
-            PR_MAX(mBoundingMetrics.descent,bmSubScript.descent);
-          descent = PR_MAX(descent,subScriptSize.height - subScriptSize.ascent);
+            NS_MAX(mBoundingMetrics.descent,bmSubScript.descent);
+          descent = NS_MAX(descent,subScriptSize.height - subScriptSize.ascent);
           width = bmSubScript.width + scriptSpace;
           rightBearing = bmSubScript.rightBearing;
         }
         else {
           // supscript
           supScriptFrame = childFrame;
           GetReflowAndBoundingMetricsFor(supScriptFrame, supScriptSize, bmSupScript);
           // get the supdrop from the supscript font
           GetSupDropFromChild (supScriptFrame, supDrop);
           // parameter u, Rule 18a, App. G, TeXbook
           minSupScriptShift = bmBase.ascent - supDrop;
           // get min supscript shift limit from x-height
           // = d(x) + 1/4 * sigma_5, Rule 18c, App. G, TeXbook
           minShiftFromXHeight = NSToCoordRound
             ((bmSupScript.descent + (1.0f/4.0f) * xHeight));
           trySupScriptShift =
-            PR_MAX(minSupScriptShift,PR_MAX(minShiftFromXHeight,supScriptShift));
+            NS_MAX(minSupScriptShift,NS_MAX(minShiftFromXHeight,supScriptShift));
           mBoundingMetrics.ascent =
-            PR_MAX(mBoundingMetrics.ascent,bmSupScript.ascent);
-          ascent = PR_MAX(ascent,supScriptSize.ascent);
-          width = PR_MAX(width, bmSupScript.width + scriptSpace);
-          rightBearing = PR_MAX(rightBearing, bmSupScript.rightBearing);
+            NS_MAX(mBoundingMetrics.ascent,bmSupScript.ascent);
+          ascent = NS_MAX(ascent,supScriptSize.ascent);
+          width = NS_MAX(width, bmSupScript.width + scriptSpace);
+          rightBearing = NS_MAX(rightBearing, bmSupScript.rightBearing);
 
           if (!mprescriptsFrame) { // we are still looping over base & postscripts
             mBoundingMetrics.rightBearing = mBoundingMetrics.width + rightBearing;
             mBoundingMetrics.width += width;
           }
           else {
             prescriptsWidth += width;
             if (firstPrescriptsPair) {
               firstPrescriptsPair = PR_FALSE;
               mBoundingMetrics.leftBearing =
-                PR_MIN(bmSubScript.leftBearing, bmSupScript.leftBearing);
+                NS_MIN(bmSubScript.leftBearing, bmSupScript.leftBearing);
             }
           }
           width = rightBearing = 0;
 
           // negotiate between the various shifts so that
           // there is enough gap between the sup and subscripts
           // Rule 18e, App. G, TeXbook
           nscoord gap =
@@ -358,18 +358,18 @@ nsMathMLmmultiscriptsFrame::Place(nsIRen
           // will be > (4/5) * x-height above baseline
           gap = NSToCoordRound ((4.0f/5.0f) * xHeight -
                   (trySupScriptShift - bmSupScript.descent));
           if (gap > 0.0f) {
             trySupScriptShift += gap;
             trySubScriptShift -= gap;
           }
           
-          maxSubScriptShift = PR_MAX(maxSubScriptShift, trySubScriptShift);
-          maxSupScriptShift = PR_MAX(maxSupScriptShift, trySupScriptShift);
+          maxSubScriptShift = NS_MAX(maxSubScriptShift, trySubScriptShift);
+          maxSupScriptShift = NS_MAX(maxSupScriptShift, trySupScriptShift);
 
           trySubScriptShift = subScriptShift;
           trySupScriptShift = supScriptShift;
         }
       }
 
       isSubScript = !isSubScript;
     }
@@ -383,25 +383,25 @@ nsMathMLmmultiscriptsFrame::Place(nsIRen
   }
 
   // we left out the width of prescripts, so ...
   mBoundingMetrics.rightBearing += prescriptsWidth;
   mBoundingMetrics.width += prescriptsWidth;
 
   // we left out the base during our bounding box updates, so ...
   mBoundingMetrics.ascent =
-    PR_MAX(mBoundingMetrics.ascent+maxSupScriptShift,bmBase.ascent);
+    NS_MAX(mBoundingMetrics.ascent+maxSupScriptShift,bmBase.ascent);
   mBoundingMetrics.descent =
-    PR_MAX(mBoundingMetrics.descent+maxSubScriptShift,bmBase.descent);
+    NS_MAX(mBoundingMetrics.descent+maxSubScriptShift,bmBase.descent);
 
   // get the reflow metrics ...
   aDesiredSize.ascent =
-    PR_MAX(ascent+maxSupScriptShift,baseSize.ascent);
+    NS_MAX(ascent+maxSupScriptShift,baseSize.ascent);
   aDesiredSize.height = aDesiredSize.ascent +
-    PR_MAX(descent+maxSubScriptShift,baseSize.height - baseSize.ascent);
+    NS_MAX(descent+maxSubScriptShift,baseSize.height - baseSize.ascent);
   aDesiredSize.width = mBoundingMetrics.width;
   aDesiredSize.mBoundingMetrics = mBoundingMetrics;
 
   mReference.x = 0;
   mReference.y = aDesiredSize.ascent;
 
   //////////////////
   // Place Children
@@ -434,17 +434,17 @@ nsMathMLmmultiscriptsFrame::Place(nsIRen
           count = 0;
 
           // get the ascent/descent of sup/subscripts stored in their rects
           // rect.x = descent, rect.y = ascent
           GetReflowAndBoundingMetricsFor(subScriptFrame, subScriptSize, bmSubScript);
           GetReflowAndBoundingMetricsFor(supScriptFrame, supScriptSize, bmSupScript);
 
           // center w.r.t. largest width
-          width = PR_MAX(subScriptSize.width, supScriptSize.width);
+          width = NS_MAX(subScriptSize.width, supScriptSize.width);
 
           dy = aDesiredSize.ascent - subScriptSize.ascent +
             maxSubScriptShift;
           FinishReflowChild (subScriptFrame, PresContext(), nsnull, subScriptSize,
                              dx + (width-subScriptSize.width)/2, dy, 0);
 
           dy = aDesiredSize.ascent - supScriptSize.ascent -
             maxSupScriptShift;
--- a/layout/mathml/nsMathMLmoFrame.cpp
+++ b/layout/mathml/nsMathMLmoFrame.cpp
@@ -669,53 +669,53 @@ nsMathMLmoFrame::Stretch(nsIRenderingCon
     if (stretchHint != NS_STRETCH_NONE) {
 
       container = aContainerSize;
 
       // some adjustments if the operator is symmetric and vertical
 
       if (isVertical && NS_MATHML_OPERATOR_IS_SYMMETRIC(mFlags)) {
         // we need to center about the axis
-        nscoord delta = PR_MAX(container.ascent - axisHeight,
+        nscoord delta = NS_MAX(container.ascent - axisHeight,
                                container.descent + axisHeight);
         container.ascent = delta + axisHeight;
         container.descent = delta - axisHeight;
 
         // get ready in case we encounter user-desired min-max size
-        delta = PR_MAX(initialSize.ascent - axisHeight,
+        delta = NS_MAX(initialSize.ascent - axisHeight,
                        initialSize.descent + axisHeight);
         initialSize.ascent = delta + axisHeight;
         initialSize.descent = delta - axisHeight;
       }
 
       // check for user-desired min-max size
 
       if (mMaxSize != NS_MATHML_OPERATOR_SIZE_INFINITY && mMaxSize > 0.0f) {
         // if we are here, there is a user defined maxsize ...
         //XXX Set stretchHint = NS_STRETCH_NORMAL? to honor the maxsize as close as possible?
         if (NS_MATHML_OPERATOR_MAXSIZE_IS_ABSOLUTE(mFlags)) {
           // there is an explicit value like maxsize="20pt"
           // try to maintain the aspect ratio of the char
           float aspect = mMaxSize / float(initialSize.ascent + initialSize.descent);
           container.ascent =
-            PR_MIN(container.ascent, nscoord(initialSize.ascent * aspect));
+            NS_MIN(container.ascent, nscoord(initialSize.ascent * aspect));
           container.descent =
-            PR_MIN(container.descent, nscoord(initialSize.descent * aspect));
+            NS_MIN(container.descent, nscoord(initialSize.descent * aspect));
           // below we use a type cast instead of a conversion to avoid a VC++ bug
           // see http://support.microsoft.com/support/kb/articles/Q115/7/05.ASP
           container.width =
-            PR_MIN(container.width, (nscoord)mMaxSize);
+            NS_MIN(container.width, (nscoord)mMaxSize);
         }
         else { // multiplicative value
           container.ascent =
-            PR_MIN(container.ascent, nscoord(initialSize.ascent * mMaxSize));
+            NS_MIN(container.ascent, nscoord(initialSize.ascent * mMaxSize));
           container.descent =
-            PR_MIN(container.descent, nscoord(initialSize.descent * mMaxSize));
+            NS_MIN(container.descent, nscoord(initialSize.descent * mMaxSize));
           container.width =
-            PR_MIN(container.width, nscoord(initialSize.width * mMaxSize));
+            NS_MIN(container.width, nscoord(initialSize.width * mMaxSize));
         }
 
         if (isVertical && !NS_MATHML_OPERATOR_IS_SYMMETRIC(mFlags)) {
           // re-adjust to align the char with the bottom of the initial container
           height = container.ascent + container.descent;
           container.descent = aContainerSize.descent;
           container.ascent = height - container.descent;
         }
@@ -732,29 +732,29 @@ nsMathMLmoFrame::Stretch(nsIRenderingCon
           // we should not use the caller's container size either
           container = initialSize;
         }
         if (NS_MATHML_OPERATOR_MINSIZE_IS_ABSOLUTE(mFlags)) {
           // there is an explicit value like minsize="20pt"
           // try to maintain the aspect ratio of the char
           float aspect = mMinSize / float(initialSize.ascent + initialSize.descent);
           container.ascent =
-            PR_MAX(container.ascent, nscoord(initialSize.ascent * aspect));
+            NS_MAX(container.ascent, nscoord(initialSize.ascent * aspect));
           container.descent =
-            PR_MAX(container.descent, nscoord(initialSize.descent * aspect));
+            NS_MAX(container.descent, nscoord(initialSize.descent * aspect));
           container.width =
-            PR_MAX(container.width, (nscoord)mMinSize);
+            NS_MAX(container.width, (nscoord)mMinSize);
         }
         else { // multiplicative value
           container.ascent =
-            PR_MAX(container.ascent, nscoord(initialSize.ascent * mMinSize));
+            NS_MAX(container.ascent, nscoord(initialSize.ascent * mMinSize));
           container.descent =
-            PR_MAX(container.descent, nscoord(initialSize.descent * mMinSize));
+            NS_MAX(container.descent, nscoord(initialSize.descent * mMinSize));
           container.width =
-            PR_MAX(container.width, nscoord(initialSize.width * mMinSize));
+            NS_MAX(container.width, nscoord(initialSize.width * mMinSize));
         }
 
         if (isVertical && !NS_MATHML_OPERATOR_IS_SYMMETRIC(mFlags)) {
           // re-adjust to align the char with the bottom of the initial container
           height = container.ascent + container.descent;
           container.descent = aContainerSize.descent;
           container.ascent = height - container.descent;
         }
@@ -844,19 +844,19 @@ nsMathMLmoFrame::Stretch(nsIRenderingCon
     aDesiredStretchSize.height = aDesiredStretchSize.ascent + mBoundingMetrics.descent;
 
     firstChild->SetPosition(firstChild->GetPosition() - nsPoint(0, dy));
   }
   else if (useMathMLChar) {
     nscoord ascent, descent;
     fm->GetMaxAscent(ascent);
     fm->GetMaxDescent(descent);
-    aDesiredStretchSize.ascent = PR_MAX(mBoundingMetrics.ascent + leading, ascent);
+    aDesiredStretchSize.ascent = NS_MAX(mBoundingMetrics.ascent + leading, ascent);
     aDesiredStretchSize.height = aDesiredStretchSize.ascent +
-                                 PR_MAX(mBoundingMetrics.descent + leading, descent);
+                                 NS_MAX(mBoundingMetrics.descent + leading, descent);
   }
   aDesiredStretchSize.width = mBoundingMetrics.width;
   aDesiredStretchSize.mBoundingMetrics = mBoundingMetrics;
   mReference.x = 0;
   mReference.y = aDesiredStretchSize.ascent;
   // Place our mMathMLChar, its origin is in our coordinate system
   if (useMathMLChar) {
     nscoord dy = aDesiredStretchSize.ascent - mBoundingMetrics.ascent;
--- a/layout/mathml/nsMathMLmoverFrame.cpp
+++ b/layout/mathml/nsMathMLmoverFrame.cpp
@@ -303,24 +303,24 @@ nsMathMLmoverFrame::Place(nsIRenderingCo
   nscoord delta2 = 0; // extra space above overscript
   if (!NS_MATHML_EMBELLISH_IS_ACCENTOVER(mEmbellishData.flags)) {    
     // Rule 13a, App. G, TeXbook
     nscoord bigOpSpacing1, bigOpSpacing3, bigOpSpacing5, dummy; 
     GetBigOpSpacings (fm, 
                       bigOpSpacing1, dummy, 
                       bigOpSpacing3, dummy, 
                       bigOpSpacing5);
-    delta1 = PR_MAX(bigOpSpacing1, (bigOpSpacing3 - bmOver.descent));
+    delta1 = NS_MAX(bigOpSpacing1, (bigOpSpacing3 - bmOver.descent));
     delta2 = bigOpSpacing5;
 
     // XXX This is not a TeX rule... 
     // delta1 (as computed above) can become really big when bmOver.descent is
     // negative,  e.g., if the content is &OverBar. In such case, we use the height
     if (bmOver.descent < 0)    
-      delta1 = PR_MAX(bigOpSpacing1, (bigOpSpacing3 - (bmOver.ascent + bmOver.descent)));
+      delta1 = NS_MAX(bigOpSpacing1, (bigOpSpacing3 - (bmOver.ascent + bmOver.descent)));
   }
   else {
     // Rule 12, App. G, TeXbook
     // We are going to modify this rule to make it more general.
     // The idea behind Rule 12 in the TeXBook is to keep the accent
     // as close to the base as possible, while ensuring that the
     // distance between the *baseline* of the accent char and 
     // the *baseline* of the base is atleast x-height. 
@@ -368,31 +368,31 @@ nsMathMLmoverFrame::Place(nsIRenderingCo
     dxOver = -bmOver.leftBearing;
   }
 
   if (NS_MATHML_EMBELLISH_IS_ACCENTOVER(mEmbellishData.flags)) {
     mBoundingMetrics.width = bmBase.width; 
     dxOver += correction + (mBoundingMetrics.width - overWidth)/2;
   }
   else {
-    mBoundingMetrics.width = PR_MAX(bmBase.width, overWidth);
+    mBoundingMetrics.width = NS_MAX(bmBase.width, overWidth);
     dxOver += correction/2 + (mBoundingMetrics.width - overWidth)/2;
   }
   dxBase = (mBoundingMetrics.width - bmBase.width) / 2;
 
   mBoundingMetrics.ascent = 
     bmOver.ascent + bmOver.descent + delta1 + bmBase.ascent;
   mBoundingMetrics.descent = bmBase.descent;
   mBoundingMetrics.leftBearing = 
-    PR_MIN(dxBase + bmBase.leftBearing, dxOver + bmOver.leftBearing);
+    NS_MIN(dxBase + bmBase.leftBearing, dxOver + bmOver.leftBearing);
   mBoundingMetrics.rightBearing = 
-    PR_MAX(dxBase + bmBase.rightBearing, dxOver + bmOver.rightBearing);
+    NS_MAX(dxBase + bmBase.rightBearing, dxOver + bmOver.rightBearing);
 
   aDesiredSize.ascent = 
-    PR_MAX(mBoundingMetrics.ascent + delta2,
+    NS_MAX(mBoundingMetrics.ascent + delta2,
            overSize.ascent + bmOver.descent + delta1 + bmBase.ascent);
   aDesiredSize.height = aDesiredSize.ascent +
     baseSize.height - baseSize.ascent;
   aDesiredSize.width = mBoundingMetrics.width;
   aDesiredSize.mBoundingMetrics = mBoundingMetrics;
 
   mReference.x = 0;
   mReference.y = aDesiredSize.ascent;
--- a/layout/mathml/nsMathMLmpaddedFrame.cpp
+++ b/layout/mathml/nsMathMLmpaddedFrame.cpp
@@ -446,17 +446,17 @@ nsMathMLmpaddedFrame::Place(nsIRendering
   if (mLeftSpaceSign != NS_MATHML_SIGN_INVALID) { // there was padding on the left
     // dismiss the left italic correction now (so that our parent won't correct us)
     mBoundingMetrics.leftBearing = 0;
   }
 
   if (mLeftSpaceSign != NS_MATHML_SIGN_INVALID ||
       mWidthSign != NS_MATHML_SIGN_INVALID) { // there was padding on the right
     // dismiss the right italic correction now (so that our parent won't correct us)
-    mBoundingMetrics.width = PR_MAX(0, lspace + width);
+    mBoundingMetrics.width = NS_MAX(0, lspace + width);
     mBoundingMetrics.rightBearing = mBoundingMetrics.width;
   }
 
   nscoord dy = height - mBoundingMetrics.ascent;
   nscoord dx = lspace;
 
   mBoundingMetrics.ascent = height;
   mBoundingMetrics.descent = depth;
--- a/layout/mathml/nsMathMLmrootFrame.cpp
+++ b/layout/mathml/nsMathMLmrootFrame.cpp
@@ -318,26 +318,26 @@ nsMathMLmrootFrame::Reflow(nsPresContext
   // radicalSize have changed at this point, and should match with
   // the bounding metrics of the char
   mSqrChar.GetBoundingMetrics(bmSqr);
 
   // Update the desired size for the container (like msqrt, index is not yet included)
   // the baseline will be that of the base.
   mBoundingMetrics.ascent = bmBase.ascent + psi + ruleThickness;
   mBoundingMetrics.descent = 
-    PR_MAX(bmBase.descent,
+    NS_MAX(bmBase.descent,
            (bmSqr.ascent + bmSqr.descent - mBoundingMetrics.ascent));
   mBoundingMetrics.width = bmSqr.width + bmBase.width;
   mBoundingMetrics.leftBearing = bmSqr.leftBearing;
   mBoundingMetrics.rightBearing = bmSqr.width + 
-    PR_MAX(bmBase.width, bmBase.rightBearing); // take also care of the rule
+    NS_MAX(bmBase.width, bmBase.rightBearing); // take also care of the rule
 
   aDesiredSize.ascent = mBoundingMetrics.ascent + leading;
   aDesiredSize.height = aDesiredSize.ascent +
-    PR_MAX(baseSize.height - baseSize.ascent,
+    NS_MAX(baseSize.height - baseSize.ascent,
            mBoundingMetrics.descent + ruleThickness);
   aDesiredSize.width = mBoundingMetrics.width;
 
   /////////////
   // Re-adjust the desired size to include the index.
   
   // the index is raised by some fraction of the height
   // of the radical, see \mroot macro in App. B, TexBook
@@ -375,19 +375,19 @@ nsMathMLmrootFrame::Reflow(nsPresContext
   dy = aDesiredSize.ascent - baseSize.ascent;
   FinishReflowChild(baseFrame, aPresContext, nsnull, baseSize, dx, dy, 0);
 
   mReference.x = 0;
   mReference.y = aDesiredSize.ascent;
 
   mBoundingMetrics.width = dx + bmBase.width;
   mBoundingMetrics.leftBearing = 
-    PR_MIN(dxIndex + bmIndex.leftBearing, dxSqr + bmSqr.leftBearing);
+    NS_MIN(dxIndex + bmIndex.leftBearing, dxSqr + bmSqr.leftBearing);
   mBoundingMetrics.rightBearing = dx +
-    PR_MAX(bmBase.width, bmBase.rightBearing);
+    NS_MAX(bmBase.width, bmBase.rightBearing);
 
   aDesiredSize.width = mBoundingMetrics.width;
   aDesiredSize.mBoundingMetrics = mBoundingMetrics;
   GatherAndStoreOverflow(&aDesiredSize);
 
   aStatus = NS_FRAME_COMPLETE;
   NS_FRAME_SET_TRUNCATION(aStatus, aReflowState, aDesiredSize);
   return NS_OK;
--- a/layout/mathml/nsMathMLmsubFrame.cpp
+++ b/layout/mathml/nsMathMLmsubFrame.cpp
@@ -119,17 +119,17 @@ nsMathMLmsubFrame::PlaceSubScript (nsPre
                                    nsIRenderingContext& aRenderingContext,
                                    PRBool               aPlaceOrigin,
                                    nsHTMLReflowMetrics& aDesiredSize,
                                    nsMathMLContainerFrame* aFrame,
                                    nscoord              aUserSubScriptShift,
                                    nscoord              aScriptSpace)
 {
   // force the scriptSpace to be atleast 1 pixel 
-  aScriptSpace = PR_MAX(nsPresContext::CSSPixelsToAppUnits(1), aScriptSpace);
+  aScriptSpace = NS_MAX(nsPresContext::CSSPixelsToAppUnits(1), aScriptSpace);
 
   ////////////////////////////////////
   // Get the children's desired sizes
 
   nsBoundingMetrics bmBase, bmSubScript;
   nsHTMLReflowMetrics baseSize;
   nsHTMLReflowMetrics subScriptSize;
   nsIFrame* baseFrame = aFrame->GetFirstChild(nsnull);
@@ -166,41 +166,41 @@ nsMathMLmsubFrame::PlaceSubScript (nsPre
   // = minimum amount to shift the subscript down set by user or from the font
   // = sub1 in TeX
   // = subscriptshift attribute * x-height
   nscoord subScriptShift, dummy;
   // get subScriptShift default from font
   GetSubScriptShifts (fm, subScriptShift, dummy);
 
   subScriptShift = 
-    PR_MAX(subScriptShift, aUserSubScriptShift);
+    NS_MAX(subScriptShift, aUserSubScriptShift);
 
   // get actual subscriptshift to be used
   // Rule 18b, App. G, TeXbook
   nscoord actualSubScriptShift = 
-    PR_MAX(minSubScriptShift,PR_MAX(subScriptShift,minShiftFromXHeight));
+    NS_MAX(minSubScriptShift,NS_MAX(subScriptShift,minShiftFromXHeight));
   // get bounding box for base + subscript
   nsBoundingMetrics boundingMetrics;
   boundingMetrics.ascent = 
-    PR_MAX(bmBase.ascent, bmSubScript.ascent - actualSubScriptShift);
+    NS_MAX(bmBase.ascent, bmSubScript.ascent - actualSubScriptShift);
   boundingMetrics.descent = 
-    PR_MAX(bmBase.descent, bmSubScript.descent + actualSubScriptShift);
+    NS_MAX(bmBase.descent, bmSubScript.descent + actualSubScriptShift);
 
   // add aScriptSpace to the subscript's width
   boundingMetrics.width = bmBase.width + bmSubScript.width + aScriptSpace;
   boundingMetrics.leftBearing = bmBase.leftBearing;
-  boundingMetrics.rightBearing = PR_MAX(bmBase.rightBearing, bmBase.width +
-    PR_MAX(bmSubScript.width + aScriptSpace, bmSubScript.rightBearing));
+  boundingMetrics.rightBearing = NS_MAX(bmBase.rightBearing, bmBase.width +
+    NS_MAX(bmSubScript.width + aScriptSpace, bmSubScript.rightBearing));
   aFrame->SetBoundingMetrics (boundingMetrics);
 
   // reflow metrics
   aDesiredSize.ascent = 
-    PR_MAX(baseSize.ascent, subScriptSize.ascent - actualSubScriptShift);
+    NS_MAX(baseSize.ascent, subScriptSize.ascent - actualSubScriptShift);
   aDesiredSize.height = aDesiredSize.ascent +
-    PR_MAX(baseSize.height - baseSize.ascent,
+    NS_MAX(baseSize.height - baseSize.ascent,
            subScriptSize.height - subScriptSize.ascent + actualSubScriptShift);
   aDesiredSize.width = boundingMetrics.width;
   aDesiredSize.mBoundingMetrics = boundingMetrics;
 
   aFrame->SetReference(nsPoint(0, aDesiredSize.ascent));
 
   if (aPlaceOrigin) {
     nscoord dx, dy;
--- a/layout/mathml/nsMathMLmsubsupFrame.cpp
+++ b/layout/mathml/nsMathMLmsubsupFrame.cpp
@@ -137,17 +137,17 @@ nsMathMLmsubsupFrame::PlaceSubSupScript(
                                         nsHTMLReflowMetrics& aDesiredSize,
                                         nsMathMLContainerFrame* aFrame,
                                         nscoord              aUserSubScriptShift,
                                         nscoord              aUserSupScriptShift,
                                         nscoord              aScriptSpace)
 {
   // force the scriptSpace to be atleast 1 pixel
   nscoord onePixel = nsPresContext::CSSPixelsToAppUnits(1);
-  aScriptSpace = PR_MAX(onePixel, aScriptSpace);
+  aScriptSpace = NS_MAX(onePixel, aScriptSpace);
 
   ////////////////////////////////////
   // Get the children's desired sizes
 
   nsHTMLReflowMetrics baseSize;
   nsHTMLReflowMetrics subScriptSize;
   nsHTMLReflowMetrics supScriptSize;
   nsBoundingMetrics bmBase, bmSubScript, bmSupScript;
@@ -207,24 +207,24 @@ nsMathMLmsubsupFrame::PlaceSubSupScript(
   GetRuleThickness (aRenderingContext, fm, ruleSize);
 
   // Get subScriptShift{1,2} default from font
   GetSubScriptShifts (fm, subScriptShift1, subScriptShift2);
 
   if (0 < aUserSubScriptShift) {
     // the user has set the subscriptshift attribute
     float scaler = ((float) subScriptShift2) / subScriptShift1;
-    subScriptShift1 = PR_MAX(subScriptShift1, aUserSubScriptShift);
+    subScriptShift1 = NS_MAX(subScriptShift1, aUserSubScriptShift);
     subScriptShift2 = NSToCoordRound(scaler * subScriptShift1);
   }
 
   // get a tentative value for subscriptshift
   // Rule 18d, App. G, TeXbook
   nscoord subScriptShift =
-    PR_MAX(minSubScriptShift,PR_MAX(subScriptShift1,subScriptShift2));
+    NS_MAX(minSubScriptShift,NS_MAX(subScriptShift1,subScriptShift2));
 
   //////////////////////////////////////////////////
   // Get supscript shift
   // same code from nsMathMLmsupFrame.cpp
   //////////////////////////////////////////////////
 
   // get min supscript shift limit from x-height
   // = d(x) + 1/4 * sigma_5, Rule 18c, App. G, TeXbook
@@ -239,17 +239,17 @@ nsMathMLmsubsupFrame::PlaceSubSupScript(
   // on the current style
   nscoord supScriptShift1, supScriptShift2, supScriptShift3;
   // Set supScriptShift{1,2,3} default from font
   GetSupScriptShifts (fm, supScriptShift1, supScriptShift2, supScriptShift3);
   if (0 < aUserSupScriptShift) {
     // the user has set the superscriptshift attribute
     float scaler2 = ((float) supScriptShift2) / supScriptShift1;
     float scaler3 = ((float) supScriptShift3) / supScriptShift1;
-    supScriptShift1 = PR_MAX(supScriptShift1, aUserSupScriptShift);
+    supScriptShift1 = NS_MAX(supScriptShift1, aUserSupScriptShift);
     supScriptShift2 = NSToCoordRound(scaler2 * supScriptShift1);
     supScriptShift3 = NSToCoordRound(scaler3 * supScriptShift1);
   }
 
   // get sup script shift depending on current script level and display style
   // Rule 18c, App. G, TeXbook
   nscoord supScriptShift;
   nsPresentationData presentationData;
@@ -267,17 +267,17 @@ nsMathMLmsubsupFrame::PlaceSubSupScript(
   else {
     // everything else = T,S,SS
     supScriptShift = supScriptShift2;
   }
 
   // get tentative value for superscriptshift
   // Rule 18c, App. G, TeXbook
   supScriptShift =
-    PR_MAX(minSupScriptShift,PR_MAX(supScriptShift,minShiftFromXHeight));
+    NS_MAX(minSupScriptShift,NS_MAX(supScriptShift,minShiftFromXHeight));
 
   //////////////////////////////////////////////////
   // Negotiate between supScriptShift and subScriptShift
   // so that there will be enough gap between them
   // Rule 18e, App. G, TeXbook
   //////////////////////////////////////////////////
 
   nscoord gap =
@@ -299,42 +299,42 @@ nsMathMLmsubsupFrame::PlaceSubSupScript(
 
   //////////////////////////////////////////////////
   // Do the Placing
   //////////////////////////////////////////////////
 
   // get bounding box for base + subscript + superscript
   nsBoundingMetrics boundingMetrics;
   boundingMetrics.ascent =
-    PR_MAX(bmBase.ascent, (bmSupScript.ascent + supScriptShift));
+    NS_MAX(bmBase.ascent, (bmSupScript.ascent + supScriptShift));
   boundingMetrics.descent =
-   PR_MAX(bmBase.descent, (bmSubScript.descent + subScriptShift));
+   NS_MAX(bmBase.descent, (bmSubScript.descent + subScriptShift));
 
   // leave aScriptSpace after both super/subscript
   // add italicCorrection between base and superscript
   // add "a little to spare" as well (see TeXbook Ch.11, p.64), as we
   // estimate the italic creation ourselves and it isn't the same as TeX 
   nscoord italicCorrection;
   GetItalicCorrection(bmBase, italicCorrection);
   italicCorrection += onePixel;
   boundingMetrics.width = bmBase.width + aScriptSpace +
-    PR_MAX((italicCorrection + bmSupScript.width), bmSubScript.width);
+    NS_MAX((italicCorrection + bmSupScript.width), bmSubScript.width);
   boundingMetrics.leftBearing = bmBase.leftBearing;
   boundingMetrics.rightBearing = bmBase.width +
-    PR_MAX((italicCorrection + bmSupScript.rightBearing), bmSubScript.rightBearing);
+    NS_MAX((italicCorrection + bmSupScript.rightBearing), bmSubScript.rightBearing);
   aFrame->SetBoundingMetrics(boundingMetrics);
 
   // reflow metrics
   aDesiredSize.ascent =
-    PR_MAX(baseSize.ascent, 
-       PR_MAX(subScriptSize.ascent - subScriptShift,
+    NS_MAX(baseSize.ascent, 
+       NS_MAX(subScriptSize.ascent - subScriptShift,
               supScriptSize.ascent + supScriptShift));
   aDesiredSize.height = aDesiredSize.ascent +
-    PR_MAX(baseSize.height - baseSize.ascent,
-       PR_MAX(subScriptSize.height - subScriptSize.ascent + subScriptShift, 
+    NS_MAX(baseSize.height - baseSize.ascent,
+       NS_MAX(subScriptSize.height - subScriptSize.ascent + subScriptShift, 
               supScriptSize.height - subScriptSize.ascent - supScriptShift));
   aDesiredSize.width = boundingMetrics.width;
   aDesiredSize.mBoundingMetrics = boundingMetrics;
 
   aFrame->SetReference(nsPoint(0, aDesiredSize.ascent));
 
   if (aPlaceOrigin) {
     nscoord dx, dy;
--- a/layout/mathml/nsMathMLmsupFrame.cpp
+++ b/layout/mathml/nsMathMLmsupFrame.cpp
@@ -120,17 +120,17 @@ nsMathMLmsupFrame::PlaceSuperScript(nsPr
                                     PRBool               aPlaceOrigin,
                                     nsHTMLReflowMetrics& aDesiredSize,
                                     nsMathMLContainerFrame* aFrame,
                                     nscoord              aUserSupScriptShift,
                                     nscoord              aScriptSpace)
 {
   // force the scriptSpace to be at least 1 pixel 
   nscoord onePixel = nsPresContext::CSSPixelsToAppUnits(1);
-  aScriptSpace = PR_MAX(onePixel, aScriptSpace);
+  aScriptSpace = NS_MAX(onePixel, aScriptSpace);
 
   ////////////////////////////////////
   // Get the children's desired sizes
 
   nsHTMLReflowMetrics baseSize;
   nsHTMLReflowMetrics supScriptSize;
   nsBoundingMetrics bmBase, bmSupScript;
   nsIFrame* supScriptFrame = nsnull;
@@ -175,17 +175,17 @@ nsMathMLmsupFrame::PlaceSuperScript(nsPr
   // Set supScriptShift{1,2,3} default from font
   GetSupScriptShifts (fm, supScriptShift1, supScriptShift2, supScriptShift3);
 
   if (0 < aUserSupScriptShift) {
     // the user has set the superscriptshift attribute
     float scaler2 = ((float) supScriptShift2) / supScriptShift1;
     float scaler3 = ((float) supScriptShift3) / supScriptShift1;
     supScriptShift1 = 
-      PR_MAX(supScriptShift1, aUserSupScriptShift);
+      NS_MAX(supScriptShift1, aUserSupScriptShift);
     supScriptShift2 = NSToCoordRound(scaler2 * supScriptShift1);
     supScriptShift3 = NSToCoordRound(scaler3 * supScriptShift1);
   }
 
   // get sup script shift depending on current script level and display style
   // Rule 18c, App. G, TeXbook
   nscoord supScriptShift;
   nsPresentationData presentationData;
@@ -203,42 +203,42 @@ nsMathMLmsupFrame::PlaceSuperScript(nsPr
   else {
     // everything else = T,S,SS
     supScriptShift = supScriptShift2;
   }
 
   // get actual supscriptshift to be used
   // Rule 18c, App. G, TeXbook
   nscoord actualSupScriptShift = 
-    PR_MAX(minSupScriptShift,PR_MAX(supScriptShift,minShiftFromXHeight));
+    NS_MAX(minSupScriptShift,NS_MAX(supScriptShift,minShiftFromXHeight));
 
   // bounding box
   nsBoundingMetrics boundingMetrics;
   boundingMetrics.ascent =
-    PR_MAX(bmBase.ascent, (bmSupScript.ascent + actualSupScriptShift));
+    NS_MAX(bmBase.ascent, (bmSupScript.ascent + actualSupScriptShift));
   boundingMetrics.descent =
-    PR_MAX(bmBase.descent, (bmSupScript.descent - actualSupScriptShift));
+    NS_MAX(bmBase.descent, (bmSupScript.descent - actualSupScriptShift));
 
   // leave aScriptSpace after superscript
   // add italicCorrection between base and superscript
   // add "a little to spare" as well (see TeXbook Ch.11, p.64), as we
   // estimate the italic creation ourselves and it isn't the same as TeX 
   italicCorrection += onePixel;
   boundingMetrics.width = bmBase.width + italicCorrection +
                           bmSupScript.width + aScriptSpace;
   boundingMetrics.leftBearing = bmBase.leftBearing;
   boundingMetrics.rightBearing = bmBase.width + italicCorrection +
                                  bmSupScript.rightBearing;
   aFrame->SetBoundingMetrics(boundingMetrics);
 
   // reflow metrics
   aDesiredSize.ascent =
-    PR_MAX(baseSize.ascent, (supScriptSize.ascent + actualSupScriptShift));
+    NS_MAX(baseSize.ascent, (supScriptSize.ascent + actualSupScriptShift));
   aDesiredSize.height = aDesiredSize.ascent +
-    PR_MAX(baseSize.height - baseSize.ascent,
+    NS_MAX(baseSize.height - baseSize.ascent,
            (supScriptSize.height - supScriptSize.ascent - actualSupScriptShift));
   aDesiredSize.width = boundingMetrics.width;
   aDesiredSize.mBoundingMetrics = boundingMetrics;
 
   aFrame->SetReference(nsPoint(0, aDesiredSize.ascent));
 
   if (aPlaceOrigin) {
     nscoord dx, dy;
--- a/layout/mathml/nsMathMLmtableFrame.cpp
+++ b/layout/mathml/nsMathMLmtableFrame.cpp
@@ -763,17 +763,17 @@ nsMathMLmtdFrame::GetRowSpan()
   if ((mContent->Tag() == nsGkAtoms::mtd_) && !GetStyleContext()->GetPseudoType()) {
     nsAutoString value;
     mContent->GetAttr(kNameSpaceID_None, nsGkAtoms::rowspan, value);
     if (!value.IsEmpty()) {
       PRInt32 error;
       rowspan = value.ToInteger(&error);
       if (error || rowspan < 0)
         rowspan = 1;
-      rowspan = PR_MIN(rowspan, MAX_ROWSPAN);
+      rowspan = NS_MIN(rowspan, MAX_ROWSPAN);
     }
   }
   return rowspan;
 }
 
 PRInt32
 nsMathMLmtdFrame::GetColSpan()
 {
--- a/layout/mathml/nsMathMLmunderFrame.cpp
+++ b/layout/mathml/nsMathMLmunderFrame.cpp
@@ -300,17 +300,17 @@ nsMathMLmunderFrame::Place(nsIRenderingC
   nscoord delta2 = 0; // extra space beneath underscript
   if (!NS_MATHML_EMBELLISH_IS_ACCENTUNDER(mEmbellishData.flags)) {    
     // Rule 13a, App. G, TeXbook
     nscoord bigOpSpacing2, bigOpSpacing4, bigOpSpacing5, dummy; 
     GetBigOpSpacings (fm, 
                       dummy, bigOpSpacing2, 
                       dummy, bigOpSpacing4, 
                       bigOpSpacing5);
-    delta1 = PR_MAX(bigOpSpacing2, (bigOpSpacing4 - bmUnder.ascent));
+    delta1 = NS_MAX(bigOpSpacing2, (bigOpSpacing4 - bmUnder.ascent));
     delta2 = bigOpSpacing5;
   }
   else {
     // No corresponding rule in TeXbook - we are on our own here
     // XXX tune the gap delta between base and underscript 
 
     // Should we use Rule 10 like \underline does?
     delta1 = ruleThickness + onePixel/2;
@@ -323,38 +323,38 @@ nsMathMLmunderFrame::Place(nsIRenderingC
 
   // Width of non-spacing marks is zero so use left and right bearing.
   nscoord underWidth = bmUnder.width;
   if (!underWidth) {
     underWidth = bmUnder.rightBearing - bmUnder.leftBearing;
     dxUnder = -bmUnder.leftBearing;
   }
 
-  nscoord maxWidth = PR_MAX(bmBase.width, underWidth);
+  nscoord maxWidth = NS_MAX(bmBase.width, underWidth);
   if (NS_MATHML_EMBELLISH_IS_ACCENTUNDER(mEmbellishData.flags)) {    
     dxUnder += (maxWidth - underWidth)/2;
   }
   else {
     dxUnder += -correction/2 + (maxWidth - underWidth)/2;
   }
   dxBase = (maxWidth - bmBase.width)/2;
 
   mBoundingMetrics.width =
-    PR_MAX(dxBase + bmBase.width, dxUnder + bmUnder.width);
+    NS_MAX(dxBase + bmBase.width, dxUnder + bmUnder.width);
   mBoundingMetrics.ascent = bmBase.ascent;
   mBoundingMetrics.descent = 
     bmBase.descent + delta1 + bmUnder.ascent + bmUnder.descent;
   mBoundingMetrics.leftBearing = 
-    PR_MIN(dxBase + bmBase.leftBearing, dxUnder + bmUnder.leftBearing);
+    NS_MIN(dxBase + bmBase.leftBearing, dxUnder + bmUnder.leftBearing);
   mBoundingMetrics.rightBearing = 
-    PR_MAX(dxBase + bmBase.rightBearing, dxUnder + bmUnder.rightBearing);
+    NS_MAX(dxBase + bmBase.rightBearing, dxUnder + bmUnder.rightBearing);
 
   aDesiredSize.ascent = baseSize.ascent;
   aDesiredSize.height = aDesiredSize.ascent +
-    PR_MAX(mBoundingMetrics.descent + delta2,
+    NS_MAX(mBoundingMetrics.descent + delta2,
            bmBase.descent + delta1 + bmUnder.ascent +
              underSize.height - underSize.ascent);
   aDesiredSize.width = mBoundingMetrics.width;
   aDesiredSize.mBoundingMetrics = mBoundingMetrics;
 
   mReference.x = 0;
   mReference.y = aDesiredSize.ascent;
 
--- a/layout/mathml/nsMathMLmunderoverFrame.cpp
+++ b/layout/mathml/nsMathMLmunderoverFrame.cpp
@@ -342,17 +342,17 @@ nsMathMLmunderoverFrame::Place(nsIRender
 
   if (!NS_MATHML_EMBELLISH_IS_ACCENTUNDER(mEmbellishData.flags)) {
     // Rule 13a, App. G, TeXbook
     nscoord bigOpSpacing2, bigOpSpacing4, bigOpSpacing5, dummy; 
     GetBigOpSpacings (fm, 
                       dummy, bigOpSpacing2, 
                       dummy, bigOpSpacing4, 
                       bigOpSpacing5);
-    underDelta1 = PR_MAX(bigOpSpacing2, (bigOpSpacing4 - bmUnder.ascent));
+    underDelta1 = NS_MAX(bigOpSpacing2, (bigOpSpacing4 - bmUnder.ascent));
     underDelta2 = bigOpSpacing5;
   }
   else {
     // No corresponding rule in TeXbook - we are on our own here
     // XXX tune the gap delta between base and underscript 
 
     // Should we use Rule 10 like \underline does?
     underDelta1 = ruleThickness + onePixel/2;
@@ -366,24 +366,24 @@ nsMathMLmunderoverFrame::Place(nsIRender
 
   if (!NS_MATHML_EMBELLISH_IS_ACCENTOVER(mEmbellishData.flags)) {    
     // Rule 13a, App. G, TeXbook
     nscoord bigOpSpacing1, bigOpSpacing3, bigOpSpacing5, dummy; 
     GetBigOpSpacings (fm, 
                       bigOpSpacing1, dummy, 
                       bigOpSpacing3, dummy, 
                       bigOpSpacing5);
-    overDelta1 = PR_MAX(bigOpSpacing1, (bigOpSpacing3 - bmOver.descent));
+    overDelta1 = NS_MAX(bigOpSpacing1, (bigOpSpacing3 - bmOver.descent));
     overDelta2 = bigOpSpacing5;
 
     // XXX This is not a TeX rule... 
     // delta1 (as computed abvove) can become really big when bmOver.descent is
     // negative,  e.g., if the content is &OverBar. In such case, we use the height
     if (bmOver.descent < 0)    
-      overDelta1 = PR_MAX(bigOpSpacing1, (bigOpSpacing3 - (bmOver.ascent + bmOver.descent)));
+      overDelta1 = NS_MAX(bigOpSpacing1, (bigOpSpacing3 - (bmOver.ascent + bmOver.descent)));
   }
   else {
     // Rule 12, App. G, TeXbook
     overDelta1 = ruleThickness + onePixel/2;
     if (bmBase.ascent < xHeight) { 
       overDelta1 += xHeight - bmBase.ascent;
     }
     overDelta2 = ruleThickness;
@@ -405,75 +405,75 @@ nsMathMLmunderoverFrame::Place(nsIRender
     dxOver = -bmOver.leftBearing;
   }
 
   if (NS_MATHML_EMBELLISH_IS_ACCENTOVER(mEmbellishData.flags)) {
     mBoundingMetrics.width = bmBase.width; 
     dxOver += correction + (mBoundingMetrics.width - overWidth)/2;
   }
   else {
-    mBoundingMetrics.width = PR_MAX(bmBase.width, overWidth);
+    mBoundingMetrics.width = NS_MAX(bmBase.width, overWidth);
     dxOver += correction/2 + (mBoundingMetrics.width - overWidth)/2;
   }
   dxBase = (mBoundingMetrics.width - bmBase.width)/2;
 
   mBoundingMetrics.ascent = 
     bmBase.ascent + overDelta1 + bmOver.ascent + bmOver.descent;
   mBoundingMetrics.descent = 
     bmBase.descent + underDelta1 + bmUnder.ascent + bmUnder.descent;
   mBoundingMetrics.leftBearing = 
-    PR_MIN(dxBase + bmBase.leftBearing, dxOver + bmOver.leftBearing);
+    NS_MIN(dxBase + bmBase.leftBearing, dxOver + bmOver.leftBearing);
   mBoundingMetrics.rightBearing = 
-    PR_MAX(dxBase + bmBase.rightBearing, dxOver + bmOver.rightBearing);
+    NS_MAX(dxBase + bmBase.rightBearing, dxOver + bmOver.rightBearing);
 
   //////////
   // pass 2, do what <munder> does: attach the underscript on the previous
   // result. We conceptually view the previous result as an "anynomous base" 
   // from where to attach the underscript. Hence if the underscript is empty,
   // we should end up like <mover>. If the overscript is empty, we should
   // end up like <munder>.
 
   nsBoundingMetrics bmAnonymousBase = mBoundingMetrics;
   nscoord ascentAnonymousBase =
-    PR_MAX(mBoundingMetrics.ascent + overDelta2,
+    NS_MAX(mBoundingMetrics.ascent + overDelta2,
            overSize.ascent + bmOver.descent + overDelta1 + bmBase.ascent);
 
   GetItalicCorrection(bmAnonymousBase, correction);
 
   // Width of non-spacing marks is zero so use left and right bearing.
   nscoord underWidth = bmUnder.width;
   if (!underWidth) {
     underWidth = bmUnder.rightBearing - bmUnder.leftBearing;
     dxUnder = -bmUnder.leftBearing;
   }
 
-  nscoord maxWidth = PR_MAX(bmAnonymousBase.width, underWidth);
+  nscoord maxWidth = NS_MAX(bmAnonymousBase.width, underWidth);
   if (NS_MATHML_EMBELLISH_IS_ACCENTUNDER(mEmbellishData.flags)) {
     dxUnder += (maxWidth - underWidth)/2;;
   }
   else {
     dxUnder += -correction/2 + (maxWidth - underWidth)/2;
   }
   nscoord dxAnonymousBase = (maxWidth - bmAnonymousBase.width)/2;
 
   // adjust the offsets of the real base and overscript since their
   // final offsets should be relative to us...
   dxOver += dxAnonymousBase;
   dxBase += dxAnonymousBase;
 
   mBoundingMetrics.width =
-    PR_MAX(dxAnonymousBase + bmAnonymousBase.width, dxUnder + bmUnder.width);
+    NS_MAX(dxAnonymousBase + bmAnonymousBase.width, dxUnder + bmUnder.width);
   mBoundingMetrics.leftBearing =
-    PR_MIN(dxAnonymousBase + bmAnonymousBase.leftBearing, dxUnder + bmUnder.leftBearing);
+    NS_MIN(dxAnonymousBase + bmAnonymousBase.leftBearing, dxUnder + bmUnder.leftBearing);
   mBoundingMetrics.rightBearing = 
-    PR_MAX(dxAnonymousBase + bmAnonymousBase.rightBearing, dxUnder + bmUnder.rightBearing);
+    NS_MAX(dxAnonymousBase + bmAnonymousBase.rightBearing, dxUnder + bmUnder.rightBearing);
 
   aDesiredSize.ascent = ascentAnonymousBase;
   aDesiredSize.height = aDesiredSize.ascent +
-    PR_MAX(mBoundingMetrics.descent + underDelta2,
+    NS_MAX(mBoundingMetrics.descent + underDelta2,
            bmAnonymousBase.descent + underDelta1 + bmUnder.ascent +
              underSize.height - underSize.ascent);
   aDesiredSize.width = mBoundingMetrics.width;
   aDesiredSize.mBoundingMetrics = mBoundingMetrics;
 
   mReference.x = 0;
   mReference.y = aDesiredSize.ascent;
 
--- a/layout/printing/nsPrintEngine.cpp
+++ b/layout/printing/nsPrintEngine.cpp
@@ -1661,17 +1661,17 @@ nsPrintEngine::SetupToPrintContent()
     } else {
       // Single document so use the Shrink as calculated for the PO
       mPrt->mShrinkRatio = mPrt->mPrintObject->mShrinkRatio;
     }
 
     // Only Shrink if we are smaller
     if (mPrt->mShrinkRatio < 0.998f) {
       // Clamp Shrink to Fit to 60%
-      mPrt->mShrinkRatio = PR_MAX(mPrt->mShrinkRatio, 0.60f);
+      mPrt->mShrinkRatio = NS_MAX(mPrt->mShrinkRatio, 0.60f);
 
       for (PRUint32 i=0;i<mPrt->mPrintDocList.Length();i++) {
         nsPrintObject* po = mPrt->mPrintDocList.ElementAt(i);
         NS_ASSERTION(po, "nsPrintObject can't be null!");
         // Wipe out the presentation before we reflow
         po->DestroyPresentation();
       }
 
@@ -2229,23 +2229,23 @@ nsPrintEngine::DoPrint(nsPrintObject * a
               {
                 startRect.y -= totalMargin.top;
                 endRect.y   -= totalMargin.top;
 
                 // Clip out selection regions above the top of the first page
                 if (startRect.y < 0) {
                   // Reduce height to be the height of the positive-territory
                   // region of original rect
-                  startRect.height = PR_MAX(0, startRect.YMost());
+                  startRect.height = NS_MAX(0, startRect.YMost());
                   startRect.y = 0;
                 }
                 if (endRect.y < 0) {
                   // Reduce height to be the height of the positive-territory
                   // region of original rect
-                  endRect.height = PR_MAX(0, endRect.YMost());
+                  endRect.height = NS_MAX(0, endRect.YMost());
                   endRect.y = 0;
                 }
                 NS_ASSERTION(endRect.y >= startRect.y,
                              "Selection end point should be after start point");
                 NS_ASSERTION(startRect.height >= 0,
                              "rect should have non-negative height.");
                 NS_ASSERTION(endRect.height >= 0,
                              "rect should have non-negative height.");
--- a/layout/style/nsCSSRuleProcessor.cpp
+++ b/layout/style/nsCSSRuleProcessor.cpp
@@ -579,17 +579,17 @@ void RuleHash::EnumerateAllRules(PRInt32
   PRInt32 classCount = aClassList ? aClassList->GetAtomCount() : 0;
 
   // assume 1 universal, tag, id, and namespace, rather than wasting
   // time counting
   PRInt32 testCount = classCount + 4;
 
   if (mEnumListSize < testCount) {
     delete [] mEnumList;
-    mEnumListSize = PR_MAX(testCount, MIN_ENUM_LIST_SIZE);
+    mEnumListSize = NS_MAX(testCount, MIN_ENUM_LIST_SIZE);
     mEnumList = new RuleValue*[mEnumListSize];
   }
 
   PRInt32 valueCount = 0;
   RULE_HASH_STAT_INCREMENT(mElementsMatched);
 
   { // universal rules
     RuleValue* value = mUniversalRules;
--- a/layout/style/nsComputedDOMStyle.cpp
+++ b/layout/style/nsComputedDOMStyle.cpp
@@ -3768,31 +3768,31 @@ nsComputedDOMStyle::SetValueToCoord(nsRO
       break;
       
     case eStyleUnit_Percent:
       {
         nscoord percentageBase;
         if (aPercentageBaseGetter &&
             (this->*aPercentageBaseGetter)(percentageBase)) {
           nscoord val = nscoord(aCoord.GetPercentValue() * percentageBase);
-          aValue->SetAppUnits(PR_MAX(aMinAppUnits, PR_MIN(val, aMaxAppUnits)));
+          aValue->SetAppUnits(NS_MAX(aMinAppUnits, NS_MIN(val, aMaxAppUnits)));
         } else {
           aValue->SetPercent(aCoord.GetPercentValue());
         }
       }
       break;
       
     case eStyleUnit_Factor:
       aValue->SetNumber(aCoord.GetFactorValue());
       break;
       
     case eStyleUnit_Coord:
       {
         nscoord val = aCoord.GetCoordValue();
-        aValue->SetAppUnits(PR_MAX(aMinAppUnits, PR_MIN(val, aMaxAppUnits)));
+        aValue->SetAppUnits(NS_MAX(aMinAppUnits, NS_MIN(val, aMaxAppUnits)));
       }
       break;
       
     case eStyleUnit_Integer:
       aValue->SetNumber(aCoord.GetIntValue());
       break;
       
     case eStyleUnit_Enumerated:
--- a/layout/style/nsComputedDOMStyle.h
+++ b/layout/style/nsComputedDOMStyle.h
@@ -393,17 +393,17 @@ private:
   /**
    * Method to set aValue to aCoord.  If aCoord is a percentage value and
    * aPercentageBaseGetter is not null, aPercentageBaseGetter is called.  If it
    * returns PR_TRUE, the percentage base it outputs in its out param is used
    * to compute an nscoord value.  If the getter is null or returns PR_FALSE,
    * the percent value of aCoord is set as a percent value on aValue.  aTable,
    * if not null, is the keyword table to handle eStyleUnit_Enumerated.  When
    * calling SetAppUnits on aValue (for coord or percent values), the value
-   * passed in will be PR_MAX of the value in aMinAppUnits and the PR_MIN of
+   * passed in will be NS_MAX of the value in aMinAppUnits and the NS_MIN of
    * the actual value in aCoord and the value in aMaxAppUnits.
    *
    * XXXbz should caller pass in some sort of bitfield indicating which units
    * can be expected or something?
    */
   void SetValueToCoord(nsROCSSPrimitiveValue* aValue,
                        const nsStyleCoord& aCoord,
                        PercentageBaseGetter aPercentageBaseGetter = nsnull,
--- a/layout/style/nsRuleNode.cpp
+++ b/layout/style/nsRuleNode.cpp
@@ -2029,17 +2029,17 @@ nsRuleNode::SetDefaultOnRoot(const nsSty
     case eStyleStruct_Font: 
     {
       nsStyleFont* fontData = new (mPresContext) nsStyleFont(mPresContext);
       if (NS_LIKELY(fontData != nsnull)) {
         nscoord minimumFontSize =
           mPresContext->GetCachedIntPref(kPresContext_MinimumFontSize);
 
         if (minimumFontSize > 0 && !mPresContext->IsChrome()) {
-          fontData->mFont.size = PR_MAX(fontData->mSize, minimumFontSize);
+          fontData->mFont.size = NS_MAX(fontData->mSize, minimumFontSize);
         }
         else {
           fontData->mFont.size = fontData->mSize;
         }
         aContext->SetStyle(eStyleStruct_Font, fontData);
       }
       return fontData;
     }
@@ -2497,36 +2497,36 @@ ComputeScriptLevelSize(const nsStyleFont
   nscoord minScriptSize =
     nsStyleFont::ZoomText(aPresContext, aParentFont->mScriptMinSize);
 
   double scriptLevelScale =
     pow(aParentFont->mScriptSizeMultiplier, scriptLevelChange);
   // Compute the size we would have had if minscriptsize had never been
   // applied, also prevent overflow (bug 413274)
   *aUnconstrainedSize =
-    NSToCoordRound(PR_MIN(aParentFont->mScriptUnconstrainedSize*scriptLevelScale,
-                          nscoord_MAX));
+    NSToCoordRound(NS_MIN(aParentFont->mScriptUnconstrainedSize*scriptLevelScale,
+                          double(nscoord_MAX)));
   // Compute the size we could get via scriptlevel change
   nscoord scriptLevelSize =
-    NSToCoordRound(PR_MIN(aParentFont->mSize*scriptLevelScale,
-                          nscoord_MAX));
+    NSToCoordRound(NS_MIN(aParentFont->mSize*scriptLevelScale,
+                          double(nscoord_MAX)));
   if (scriptLevelScale <= 1.0) {
     if (aParentFont->mSize <= minScriptSize) {
       // We can't decrease the font size at all, so just stick to no change
       // (authors are allowed to explicitly set the font size smaller than
       // minscriptsize)
       return aParentFont->mSize;
     }
     // We can decrease, so apply constraint #1
-    return PR_MAX(minScriptSize, scriptLevelSize);
+    return NS_MAX(minScriptSize, scriptLevelSize);
   } else {
     // scriptminsize can only make sizes larger than the unconstrained size
     NS_ASSERTION(*aUnconstrainedSize <= scriptLevelSize, "How can this ever happen?");
     // Apply constraint #2
-    return PR_MIN(scriptLevelSize, PR_MAX(*aUnconstrainedSize, minScriptSize));
+    return NS_MIN(scriptLevelSize, NS_MAX(*aUnconstrainedSize, minScriptSize));
   }
 }
 #endif
 
 /* static */ void
 nsRuleNode::SetFontSize(nsPresContext* aPresContext,
                         const nsRuleDataFont& aFontData,
                         const nsStyleFont* aFont,
@@ -2719,17 +2719,17 @@ nsRuleNode::SetFont(nsPresContext* aPres
       //    (and the assumption is) it is always a proportional font. Then we
       //    always use 2 points smaller than what the browser has defined as
       //    the default proportional font.
       case eSystemFont_Field:
       case eSystemFont_Button:
       case eSystemFont_List:
         // Assumption: system defined font is proportional
         systemFont.size = 
-          PR_MAX(defaultVariableFont->size - aPresContext->PointsToAppUnits(2), 0);
+          NS_MAX(defaultVariableFont->size - aPresContext->PointsToAppUnits(2), 0);
         break;
     }
 #endif
   } else {
     // In case somebody explicitly used -moz-use-system-font.
     systemFont = *defaultVariableFont;
   }
 
@@ -5637,17 +5637,17 @@ nsRuleNode::ComputeColumnData(void* aSta
 
   // column-count: auto, integer, inherit
   if (eCSSUnit_Auto == columnData.mColumnCount.GetUnit() ||
       eCSSUnit_Initial == columnData.mColumnCount.GetUnit()) {
     column->mColumnCount = NS_STYLE_COLUMN_COUNT_AUTO;
   } else if (eCSSUnit_Integer == columnData.mColumnCount.GetUnit()) {
     column->mColumnCount = columnData.mColumnCount.GetIntValue();
     // Max 1000 columns - wallpaper for bug 345583.
-    column->mColumnCount = PR_MIN(column->mColumnCount, 1000);
+    column->mColumnCount = NS_MIN(column->mColumnCount, 1000U);
   } else if (eCSSUnit_Inherit == columnData.mColumnCount.GetUnit()) {
     canStoreInRuleTree = PR_FALSE;
     column->mColumnCount = parent->mColumnCount;
   }
 
   // column-rule-width: length, enum, inherit
   const nsCSSValue& widthValue = columnData.mColumnRuleWidth;
   if (eCSSUnit_Initial == widthValue.GetUnit()) {
--- a/layout/style/nsStyleAnimation.cpp
+++ b/layout/style/nsStyleAnimation.cpp
@@ -550,17 +550,17 @@ nsStyleAnimation::StoreComputedValue(nsC
     case eStyleAnimType_nscoord:
       *static_cast<nscoord*>(StyleDataAtOffset(aStyleStruct, ssOffset)) =
         aComputedValue.GetCoordValue();
       if (aProperty == eCSSProperty_font) {
         nsStyleFont *font = static_cast<nsStyleFont*>(aStyleStruct);
         if (!aPresContext->IsChrome()) {
           nscoord minimumFontSize =
             aPresContext->GetCachedIntPref(kPresContext_MinimumFontSize);
-          font->mFont.size = PR_MAX(font->mSize, minimumFontSize);
+          font->mFont.size = NS_MAX(font->mSize, minimumFontSize);
         } else {
           font->mFont.size = font->mSize;
         }
       }
       return PR_TRUE;
     case eStyleAnimType_Color:
       *static_cast<nscolor*>(StyleDataAtOffset(aStyleStruct, ssOffset)) =
         aComputedValue.GetColorValue();
--- a/layout/style/nsStyleStruct.cpp
+++ b/layout/style/nsStyleStruct.cpp
@@ -1430,17 +1430,17 @@ ConvertToPixelCoord(const nsStyleCoord& 
     case eStyleUnit_Factor:
       pixelValue = aCoord.GetFactorValue();
       break;
     default:
       NS_NOTREACHED("unexpected unit for image crop rect");
       return 0;
   }
   NS_ABORT_IF_FALSE(pixelValue >= 0, "we ensured non-negative while parsing");
-  pixelValue = PR_MIN(pixelValue, PR_INT32_MAX); // avoid overflow
+  pixelValue = NS_MIN(pixelValue, double(PR_INT32_MAX)); // avoid overflow
   return NS_lround(pixelValue);
 }
 
 PRBool
 nsStyleImage::ComputeActualCropRect(nsIntRect& aActualCropRect,
                                     PRBool* aIsEntireImage) const
 {
   if (mType != eStyleImageType_Image)
@@ -1594,23 +1594,23 @@ nsStyleBackground::nsStyleBackground(con
   , mBackgroundColor(aSource.mBackgroundColor)
   , mBackgroundInlinePolicy(aSource.mBackgroundInlinePolicy)
 {
   MOZ_COUNT_CTOR(nsStyleBackground);
   // If the deep copy of mLayers failed, truncate the counts.
   PRUint32 count = mLayers.Length();
   if (count != aSource.mLayers.Length()) {
     NS_WARNING("truncating counts due to out-of-memory");
-    mAttachmentCount = PR_MAX(mAttachmentCount, count);
-    mClipCount = PR_MAX(mClipCount, count);
-    mOriginCount = PR_MAX(mOriginCount, count);
-    mRepeatCount = PR_MAX(mRepeatCount, count);
-    mPositionCount = PR_MAX(mPositionCount, count);
-    mImageCount = PR_MAX(mImageCount, count);
-    mSizeCount = PR_MAX(mSizeCount, count);
+    mAttachmentCount = NS_MAX(mAttachmentCount, count);
+    mClipCount = NS_MAX(mClipCount, count);
+    mOriginCount = NS_MAX(mOriginCount, count);
+    mRepeatCount = NS_MAX(mRepeatCount, count);
+    mPositionCount = NS_MAX(mPositionCount, count);
+    mImageCount = NS_MAX(mImageCount, count);
+    mSizeCount = NS_MAX(mSizeCount, count);
   }
 }
 
 nsStyleBackground::~nsStyleBackground()
 {
   MOZ_COUNT_DTOR(nsStyleBackground);
 }
 
--- a/layout/style/nsStyleStruct.h
+++ b/layout/style/nsStyleStruct.h
@@ -60,16 +60,17 @@
 #include "nsIPresShell.h"
 #include "nsCOMPtr.h"
 #include "nsCOMArray.h"
 #include "nsTArray.h"
 #include "nsIAtom.h"
 #include "nsIURI.h"
 #include "nsCSSValue.h"
 #include "nsStyleTransformMatrix.h"
+#include "nsAlgorithm.h"
 
 class nsIFrame;
 class imgIRequest;
 
 // Includes nsStyleStructID.
 #include "nsStyleStructFwd.h"
 
 // Bits for each struct.
@@ -661,24 +662,24 @@ class nsCSSShadowArray {
     PRUint32 mRefCnt;
     nsCSSShadowItem mArray[1]; // This MUST be the last item
 };
 
 // Border widths are rounded to the nearest-below integer number of pixels,
 // but values between zero and one device pixels are always rounded up to
 // one device pixel.
 #define NS_ROUND_BORDER_TO_PIXELS(l,tpp) \
-  ((l) == 0) ? 0 : PR_MAX((tpp), (l) / (tpp) * (tpp))
+  ((l) == 0) ? 0 : NS_MAX((tpp), (l) / (tpp) * (tpp))
 // Outline offset is rounded to the nearest integer number of pixels, but values
 // between zero and one device pixels are always rounded up to one device pixel.
 // Note that the offset can be negative.
 #define NS_ROUND_OFFSET_TO_PIXELS(l,tpp) \
   (((l) == 0) ? 0 : \
-    ((l) > 0) ? PR_MAX( (tpp), ((l) + ((tpp) / 2)) / (tpp) * (tpp)) : \
-                PR_MIN(-(tpp), ((l) - ((tpp) / 2)) / (tpp) * (tpp)))
+    ((l) > 0) ? NS_MAX( (tpp), ((l) + ((tpp) / 2)) / (tpp) * (tpp)) : \
+                NS_MIN(-(tpp), ((l) - ((tpp) / 2)) / (tpp) * (tpp)))
 
 // Returns if the given border style type is visible or not
 static PRBool IsVisibleBorderStyle(PRUint8 aStyle)
 {
   return (aStyle != NS_STYLE_BORDER_STYLE_NONE &&
           aStyle != NS_STYLE_BORDER_STYLE_HIDDEN);
 }
 
--- a/layout/style/nsStyleUtil.cpp
+++ b/layout/style/nsStyleUtil.cpp
@@ -300,17 +300,17 @@ nscoord nsStyleUtil::FindNextSmallerFont
       // set the new size to have the same relative position between the next smallest two indexed sizes
       smallerSize = smallerIndexFontSize + NSToCoordRound(relativePosition * (indexFontSize - smallerIndexFontSize));      
     }
     else {  // larger than HTML table, drop by 33%
       smallerSize = NSToCoordRound(float(aFontSize) / 1.5);
     }
   }
   else { // smaller than HTML table, drop by 1px
-    smallerSize = PR_MAX(aFontSize - onePx, onePx);
+    smallerSize = NS_MAX(aFontSize - onePx, onePx);
   }
   return smallerSize;
 }
 
 //------------------------------------------------------------------------------
 //
 //------------------------------------------------------------------------------
 
--- a/layout/svg/base/src/nsSVGGlyphFrame.cpp
+++ b/layout/svg/base/src/nsSVGGlyphFrame.cpp
@@ -1348,18 +1348,18 @@ nsSVGGlyphFrame::EnsureTextRun(float *aD
       langGroup.Assign(lg);
     }
 
     if (GetStyleSVG()->mTextRendering ==
         NS_STYLE_TEXT_RENDERING_GEOMETRICPRECISION) {
       textRunSize = PRECISE_SIZE;
     } else {
       textRunSize = size*contextScale;
-      textRunSize = PR_MAX(textRunSize, CLAMP_MIN_SIZE);
-      textRunSize = PR_MIN(textRunSize, CLAMP_MAX_SIZE);
+      textRunSize = NS_MAX(textRunSize, double(CLAMP_MIN_SIZE));
+      textRunSize = NS_MIN(textRunSize, double(CLAMP_MAX_SIZE));
     }
 
     const nsFont& font = fontData->mFont;
     PRBool printerFont = (presContext->Type() == nsPresContext::eContext_PrintPreview ||
                           presContext->Type() == nsPresContext::eContext_Print);
     gfxFontStyle fontStyle(font.style, font.weight, font.stretch, textRunSize,
                            langGroup, font.sizeAdjust, font.systemFont,
                            font.familyNameQuirks,
--- a/layout/svg/base/src/nsSVGTextContainerFrame.cpp
+++ b/layout/svg/base/src/nsSVGTextContainerFrame.cpp
@@ -284,23 +284,23 @@ float
 nsSVGTextContainerFrame::GetSubStringLength(PRUint32 charnum, PRUint32 nchars)
 {
   float length = 0.0f;
   nsISVGGlyphFragmentNode *node = GetFirstGlyphFragmentChildNode();
 
   while (node) {
     PRUint32 count = node->GetNumberOfChars();
     if (count > charnum) {
-      PRUint32 fragmentChars = PR_MIN(nchars, count);
+      PRUint32 fragmentChars = NS_MIN(nchars, count);
       float fragmentLength = node->GetSubStringLength(charnum, fragmentChars);
       length += fragmentLength;
       nchars -= fragmentChars;
       if (nchars == 0) break;
     }
-    charnum -= PR_MIN(charnum, count);
+    charnum -= NS_MIN(charnum, count);
     node = GetNextGlyphFragmentChildNode(node);
   }
 
   return length;
 }
 
 PRInt32
 nsSVGTextContainerFrame::GetCharNumAtPosition(nsIDOMSVGPoint *point)
--- a/layout/svg/base/src/nsSVGUtils.cpp
+++ b/layout/svg/base/src/nsSVGUtils.cpp
@@ -1211,19 +1211,19 @@ nsSVGUtils::ConvertToSurfaceSize(const g
 
   *aResultOverflows = (aSize.width >= PR_INT32_MAX + 0.5 ||
                        aSize.height >= PR_INT32_MAX + 0.5 ||
                        aSize.width <= PR_INT32_MIN - 0.5 ||
                        aSize.height <= PR_INT32_MIN - 0.5);
 
   if (*aResultOverflows ||
       !gfxASurface::CheckSurfaceSize(surfaceSize)) {
-    surfaceSize.width = PR_MIN(NS_SVG_OFFSCREEN_MAX_DIMENSION,
+    surfaceSize.width = NS_MIN(NS_SVG_OFFSCREEN_MAX_DIMENSION,
                                surfaceSize.width);
-    surfaceSize.height = PR_MIN(NS_SVG_OFFSCREEN_MAX_DIMENSION,
+    surfaceSize.height = NS_MIN(NS_SVG_OFFSCREEN_MAX_DIMENSION,
                                 surfaceSize.height);
     *aResultOverflows = PR_TRUE;
   }
   return surfaceSize;
 }
 
 gfxASurface *
 nsSVGUtils::GetThebesComputationalSurface()
--- a/layout/tables/BasicTableLayoutStrategy.cpp
+++ b/layout/tables/BasicTableLayoutStrategy.cpp
@@ -132,17 +132,17 @@ GetWidthInfo(nsIRenderingContext *aRende
         // nsTableCellFrame::AttributeChanged
         if (aIsCell && w > minCoord &&
             aFrame->PresContext()->CompatibilityMode() ==
               eCompatibility_NavQuirks &&
             aFrame->GetContent()->HasAttr(kNameSpaceID_None,
                                           nsGkAtoms::nowrap)) {
             minCoord = w;
         }
-        prefCoord = PR_MAX(w, minCoord);
+        prefCoord = NS_MAX(w, minCoord);
     } else if (unit == eStyleUnit_Percent) {
         prefPercent = stylePos->mWidth.GetPercentValue();
     } else if (unit == eStyleUnit_Enumerated && aIsCell) {
         switch (stylePos->mWidth.GetIntValue()) {
             case NS_STYLE_WIDTH_MAX_CONTENT:
                 // 'width' only affects pref width, not min
                 // width, so don't change anything
                 break;
--- a/layout/tables/FixedTableLayoutStrategy.cpp
+++ b/layout/tables/FixedTableLayoutStrategy.cpp
@@ -318,17 +318,17 @@ FixedTableLayoutStrategy::ComputeColumnW
     }
 
     if (unassignedSpace < 0) {
         if (pctTotal > 0) {
             // If the columns took up too much space, reduce those that
             // had percentage widths.  The spec doesn't say to do this,
             // but we've always done it in the past, and so does WinIE6.
             nscoord pctUsed = NSToCoordFloor(pctTotal * float(tableWidth));
-            nscoord reduce = PR_MIN(pctUsed, -unassignedSpace);
+            nscoord reduce = NS_MIN(pctUsed, -unassignedSpace);
             float reduceRatio = float(reduce) / pctTotal;
             for (PRInt32 col = 0; col < colCount; ++col) {
                 nsTableColFrame *colFrame = mTableFrame->GetColFrame(col);
                 if (!colFrame) {
                     NS_ERROR("column frames out of sync with cell map");
                     continue;
                 }
                 nscoord colWidth = colFrame->GetFinalWidth();
--- a/layout/tables/nsCellMap.cpp
+++ b/layout/tables/nsCellMap.cpp
@@ -479,18 +479,18 @@ nsTableCellMap::InsertRows(nsTableRowGro
   if ((numNewRows <= 0) || (aFirstRowIndex < 0)) ABORT0(); 
 
   PRInt32 rowIndex = aFirstRowIndex;
   nsCellMap* cellMap = mFirstMap;
   while (cellMap) {
     nsTableRowGroupFrame* rg = cellMap->GetRowGroup();
     if (rg == &aParent) {
       cellMap->InsertRows(*this, aRows, rowIndex, aConsiderSpans, aDamageArea);
-      aDamageArea.y = PR_MIN(aFirstRowIndex, aDamageArea.y);
-      aDamageArea.height = PR_MAX(0, GetRowCount() - aDamageArea.y);
+      aDamageArea.y = NS_MIN(aFirstRowIndex, aDamageArea.y);
+      aDamageArea.height = NS_MAX(0, GetRowCount() - aDamageArea.y);
 #ifdef DEBUG_TABLE_CELLMAP 
       Dump("after InsertRows");
 #endif
       if (mBCInfo) {
         PRInt32 count = mBCInfo->mRightBorders.Length();
         if (aFirstRowIndex < count) {
           for (PRInt32 rowX = aFirstRowIndex; rowX < aFirstRowIndex + numNewRows; rowX++) {
             if (!mBCInfo->mRightBorders.InsertElementAt(rowX))
@@ -522,17 +522,17 @@ nsTableCellMap::RemoveRows(PRInt32      
 {
   PRInt32 rowIndex = aFirstRowIndex;
   nsCellMap* cellMap = mFirstMap;
   while (cellMap) {
     if (cellMap->GetRowCount() > rowIndex) {
       cellMap->RemoveRows(*this, rowIndex, aNumRowsToRemove, aConsiderSpans, aDamageArea);
       nsTableRowGroupFrame* rg = cellMap->GetRowGroup();
       aDamageArea.y += (rg) ? rg->GetStartRowIndex() : 0;
-      aDamageArea.height = PR_MAX(0, GetRowCount() - aFirstRowIndex);
+      aDamageArea.height = NS_MAX(0, GetRowCount() - aFirstRowIndex);
       if (mBCInfo) {
         for (PRInt32 rowX = aFirstRowIndex + aNumRowsToRemove - 1; rowX >= aFirstRowIndex; rowX--) {
           if (PRUint32(rowX) < mBCInfo->mRightBorders.Length()) {
             mBCInfo->mRightBorders.RemoveElementAt(rowX);
           }
         }
       }
       break;
@@ -587,17 +587,17 @@ nsTableCellMap::InsertCells(nsTArray<nsT
 {
   PRInt32 rowIndex = aRowIndex;
   nsCellMap* cellMap = mFirstMap;
   while (cellMap) {
     if (cellMap->GetRowCount() > rowIndex) {
       cellMap->InsertCells(*this, aCellFrames, rowIndex, aColIndexBefore, aDamageArea);
       nsTableRowGroupFrame* rg = cellMap->GetRowGroup();
       aDamageArea.y += (rg) ? rg->GetStartRowIndex() : 0;
-      aDamageArea.width = PR_MAX(0, GetColCount() - aColIndexBefore - 1);
+      aDamageArea.width = NS_MAX(0, GetColCount() - aColIndexBefore - 1);
       break;
     }
     rowIndex -= cellMap->GetRowCount();
     cellMap = cellMap->GetNextSibling();
   }
 #ifdef DEBUG_TABLE_CELLMAP
   Dump("after InsertCells");
 #endif
@@ -616,17 +616,17 @@ nsTableCellMap::RemoveCell(nsTableCellFr
   nsCellMap* cellMap = mFirstMap;
   while (cellMap) {
     if (cellMap->GetRowCount() > rowIndex) {
       cellMap->RemoveCell(*this, aCellFrame, rowIndex, aDamageArea);
       nsTableRowGroupFrame* rg = cellMap->GetRowGroup();
       aDamageArea.y += (rg) ? rg->GetStartRowIndex() : 0;
       PRInt32 colIndex;
       aCellFrame->GetColIndex(colIndex);
-      aDamageArea.width = PR_MAX(0, GetColCount() - colIndex - 1);
+      aDamageArea.width = NS_MAX(0, GetColCount() - colIndex - 1);
 #ifdef DEBUG_TABLE_CELLMAP
       Dump("after RemoveCell");
 #endif
       return;
     }
     rowIndex -= cellMap->GetRowCount();
     cellMap = cellMap->GetNextSibling();
   }
@@ -641,18 +641,18 @@ void
 SetDamageArea(PRInt32 aXOrigin,
               PRInt32 aYOrigin,
               PRInt32 aWidth,
               PRInt32 aHeight,
               nsRect& aDamageArea)
 {
   aDamageArea.x      = aXOrigin;
   aDamageArea.y      = aYOrigin;
-  aDamageArea.width  = PR_MAX(1, aWidth);
-  aDamageArea.height = PR_MAX(1, aHeight);
+  aDamageArea.width  = NS_MAX(1, aWidth);
+  aDamageArea.height = NS_MAX(1, aHeight);
 }
 
 void 
 nsTableCellMap::RebuildConsideringCells(nsCellMap*                   aCellMap,
                                         nsTArray<nsTableCellFrame*>* aCellFrames,
                                         PRInt32                      aRowIndex,
                                         PRInt32                      aColIndex,
                                         PRBool                       aInsert,
@@ -1371,27 +1371,27 @@ nsCellMap::InsertRows(nsTableCellMap&   
     PRInt32 numEmptyRows = aFirstRowIndex - mRows.Length();
     if (!Grow(aMap, numEmptyRows)) {
       return;
     }
   }
 
   if (!aConsiderSpans) {
     // update mContentRowCount, since non-empty rows will be added
-    mContentRowCount = PR_MAX(aFirstRowIndex, mContentRowCount);
+    mContentRowCount = NS_MAX(aFirstRowIndex, mContentRowCount);
     ExpandWithRows(aMap, aRows, aFirstRowIndex, aDamageArea);
     return;
   }
 
   // if any cells span into or out of the row being inserted, then rebuild
   PRBool spansCauseRebuild = CellsSpanInOrOut(aFirstRowIndex,
                                               aFirstRowIndex, 0, numCols - 1);
   
   // update mContentRowCount, since non-empty rows will be added
-  mContentRowCount = PR_MAX(aFirstRowIndex, mContentRowCount);
+  mContentRowCount = NS_MAX(aFirstRowIndex, mContentRowCount);
 
   // if any of the new cells span out of the new rows being added, then rebuild
   // XXX it would be better to only rebuild the portion of the map that follows the new rows
   if (!spansCauseRebuild && (PRUint32(aFirstRowIndex) < mRows.Length())) {
     spansCauseRebuild = CellsSpanOut(aRows);
   }
 
   if (spansCauseRebuild) {
@@ -1503,17 +1503,17 @@ nsCellMap::AppendCell(nsTableCellMap&   
   // if the new cell could potentially span into other rows and collide with 
   // originating cells there, we will play it safe and just rebuild the map
   if (aRebuildIfNecessary && (aRowIndex < mContentRowCount - 1) && (rowSpan > 1)) {
     nsAutoTArray<nsTableCellFrame*, 1> newCellArray;
     newCellArray.AppendElement(aCellFrame);
     aMap.RebuildConsideringCells(this, &newCellArray, aRowIndex, startColIndex, PR_TRUE, aDamageArea);
     return origData;
   }
-  mContentRowCount = PR_MAX(mContentRowCount, aRowIndex + 1);
+  mContentRowCount = NS_MAX(mContentRowCount, aRowIndex + 1);
 
   // add new cols to the table map if necessary
   PRInt32 endColIndex = startColIndex + colSpan - 1;
   if (endColIndex >= origNumCols) {
     NS_ASSERTION(aCellFrame, "dead cells should not require new columns");
     aMap.AddColsAtEnd(1 + endColIndex - origNumCols);
   }
 
@@ -1926,17 +1926,17 @@ void nsCellMap::ExpandWithCells(nsTableC
             }
           }
         }
         SetDataAt(aMap, *data, rowX, colX);
       }
     }
     cellFrame->SetColIndex(startColIndex);
   }
-  PRInt32 damageHeight = PR_MIN(GetRowGroup()->GetRowCount() - aRowIndex, aRowSpan);
+  PRInt32 damageHeight = NS_MIN(GetRowGroup()->GetRowCount() - aRowIndex, aRowSpan);
   SetDamageArea(aColIndex, aRowIndex, 1 + endColIndex - aColIndex, damageHeight, aDamageArea); 
 
   PRInt32 rowX;
 
   // update the row and col info due to shifting
   for (rowX = aRowIndex; rowX <= endRowIndex; rowX++) {
     CellDataArray& row = mRows[rowX];
     PRUint32 numCols = row.Length();
@@ -2051,17 +2051,17 @@ PRInt32 nsCellMap::GetEffectiveColSpan(c
       // use that as the max number of cols to iterate. Since this is rare, only 
       // pay the price of looking up the cell's colspan here.
       if (!hitOverlap && data->IsOverlap()) {
         CellData* origData = row.SafeElementAt(aColIndex);
         if (origData && origData->IsOrig()) {
           nsTableCellFrame* cellFrame = origData->GetCellFrame();
           if (cellFrame) {
             // possible change the number of colums to iterate
-            maxCols = PR_MIN(aColIndex + cellFrame->GetColSpan(), maxCols);
+            maxCols = NS_MIN(aColIndex + cellFrame->GetColSpan(), maxCols);
             if (colX >= maxCols) 
               break;
           }
         }
       }
       if (data->IsColSpan()) {
         colSpan++;
         if (data->IsZeroColSpan()) {
@@ -2082,17 +2082,17 @@ nsCellMap::GetRowSpanForNewCell(nsTableC
                                 PRInt32           aRowIndex,
                                 PRBool&           aIsZeroRowSpan) const
 {
   aIsZeroRowSpan = PR_FALSE;
   PRInt32 rowSpan = aCellFrameToAdd->GetRowSpan();
   if (0 == rowSpan) {
     // Use a min value of 2 for a zero rowspan to make computations easier
     // elsewhere. Zero rowspans are only content dependent!
-    rowSpan = PR_MAX(2, mContentRowCount - aRowIndex); 
+    rowSpan = NS_MAX(2, mContentRowCount - aRowIndex); 
     aIsZeroRowSpan = PR_TRUE;
   }
   return rowSpan;
 }
 
 PRBool nsCellMap::HasMoreThanOneCell(PRInt32 aRowIndex) const
 {
   const CellDataArray& row = mRows.SafeElementAt(aRowIndex, *sEmptyRow);
@@ -2182,17 +2182,17 @@ void nsCellMap::ShrinkWithoutCell(nsTabl
 
   // remove the deleted cell and cellData entries for it
   for (rowX = aRowIndex; rowX <= endRowIndex; rowX++) {
     CellDataArray& row = mRows[rowX];
 
     // endIndexForRow points at the first slot we don't want to clean up.  This
     // makes the aColIndex == 0 case work right with our unsigned int colX.
     NS_ASSERTION(endColIndex + 1 <= row.Length(), "span beyond the row size!");
-    PRUint32 endIndexForRow = PR_MIN(endColIndex + 1, row.Length());
+    PRUint32 endIndexForRow = NS_MIN(endColIndex + 1, row.Length());
 
     // Since endIndexForRow <= row.Length(), enough to compare aColIndex to it.
     if (PRUint32(aColIndex) < endIndexForRow) {
       for (colX = endIndexForRow; colX > PRUint32(aColIndex); colX--) {
         DestroyCellData(row[colX-1]);
       }
       row.RemoveElementsAt(aColIndex, endIndexForRow - aColIndex);
     }
@@ -2265,17 +2265,17 @@ nsCellMap::RebuildConsideringRows(nsTabl
     if (!Grow(aMap, mContentRowCount)) {
       // Bail, I guess...  Not sure what else we can do here.
       return;
     }
   }
 
   // aStartRowIndex might be after all existing rows so we should limit the
   // copy to the amount of exisiting rows
-  PRUint32 copyEndRowIndex = PR_MIN(numOrigRows, PRUint32(aStartRowIndex));
+  PRUint32 copyEndRowIndex = NS_MIN(numOrigRows, PRUint32(aStartRowIndex));
 
   // rowX keeps track of where we are in mRows while setting up the
   // new cellmap.
   PRUint32 rowX = 0;
   
   // put back the rows before the affected ones just as before.  Note that we
   // can't just copy the old rows in bit-for-bit, because they might be
   // spanning out into the rows we're adding/removing.
@@ -2358,17 +2358,17 @@ nsCellMap::RebuildConsideringCells(nsTab
   PRInt32 numOrigRows  = mRows.Length();
   nsTArray<CellDataArray> origRows;
   mRows.SwapElements(origRows);
 
   PRInt32 numNewCells = (aCellFrames) ? aCellFrames->Length() : 0;
   
   // the new cells might extend the previous column number
   NS_ASSERTION(aNumOrigCols >= aColIndex, "Appending cells far beyond cellmap data?!");
-  PRInt32 numCols = aInsert ? PR_MAX(aNumOrigCols, aColIndex + 1) : aNumOrigCols;  
+  PRInt32 numCols = aInsert ? NS_MAX(aNumOrigCols, aColIndex + 1) : aNumOrigCols;  
   
   // build the new cell map.  Hard to say what, if anything, we can preallocate
   // here...  Should come back to that sometime, perhaps.
   PRInt32 rowX;
   for (rowX = 0; rowX < numOrigRows; rowX++) {
     const CellDataArray& row = origRows[rowX];
     for (PRInt32 colX = 0; colX < numCols; colX++) {
       if ((rowX == aRowIndex) && (colX == aColIndex)) { 
@@ -2840,17 +2840,17 @@ nsCellMapColumnIterator::AdvanceRowGroup
       // if we got here.
       mCurMapContentRowCount = 0;
       mCurMapRelevantRowCount = 0;
       break;
     }
 
     mCurMapContentRowCount = mCurMap->GetRowCount();
     PRUint32 rowArrayLength = mCurMap->mRows.Length();
-    mCurMapRelevantRowCount = PR_MIN(mCurMapContentRowCount, rowArrayLength);
+    mCurMapRelevantRowCount = NS_MIN(mCurMapContentRowCount, rowArrayLength);
   } while (0 == mCurMapRelevantRowCount);
 
   NS_ASSERTION(mCurMapRelevantRowCount != 0 || !mCurMap,
                "How did that happen?");
 
   // Set mCurMapRow to 0, since cells can't span across table row groups.
   mCurMapRow = 0;
 }
--- a/layout/tables/nsCellMap.h
+++ b/layout/tables/nsCellMap.h
@@ -38,16 +38,17 @@
 #define nsCellMap_h__
 
 #include "nscore.h"
 #include "celldata.h"
 #include "nsTArray.h"
 #include "nsTPtrArray.h"
 #include "nsRect.h"
 #include "nsCOMPtr.h"
+#include "nsAlgorithm.h"
 
 #undef DEBUG_TABLE_CELLMAP
 
 class nsTableColFrame;
 class nsTableCellFrame;
 class nsTableRowFrame;
 class nsTableRowGroupFrame;
 class nsTableFrame;
@@ -624,17 +625,17 @@ public:
     mCurMapRow(0), mCol(aCol), mFoundCells(0)
   {
     NS_PRECONDITION(aMap, "Must have map");
     NS_PRECONDITION(mCol < aMap->GetColCount(), "Invalid column");
     mOrigCells = aMap->GetNumCellsOriginatingInCol(mCol);
     if (mCurMap) {
       mCurMapContentRowCount = mCurMap->GetRowCount();
       PRUint32 rowArrayLength = mCurMap->mRows.Length();
-      mCurMapRelevantRowCount = PR_MIN(mCurMapContentRowCount, rowArrayLength);
+      mCurMapRelevantRowCount = NS_MIN(mCurMapContentRowCount, rowArrayLength);
       if (mCurMapRelevantRowCount == 0 && mOrigCells > 0) {
         // This row group is useless; advance!
         AdvanceRowGroup();
       }
     }
 #ifdef DEBUG
     else {
       NS_ASSERTION(mOrigCells == 0, "Why no rowgroups?");
--- a/layout/tables/nsTableCellFrame.cpp
+++ b/layout/tables/nsTableCellFrame.cpp
@@ -586,17 +586,17 @@ void nsTableCellFrame::VerticallyAlignCh
     break;
 
     default:
     case NS_STYLE_VERTICAL_ALIGN_MIDDLE:
       // Align the middle of the child frame with the middle of the content area, 
       kidYTop = (height - childHeight - bottomInset + topInset) / 2;
   }
   // if the content is larger than the cell height align from top
-  kidYTop = PR_MAX(0, kidYTop);
+  kidYTop = NS_MAX(0, kidYTop);
 
   if (kidYTop != kidRect.y) {
     // Invalidate at the old position first
     firstKid->InvalidateOverflowRect();
   }
   
   firstKid->SetPosition(nsPoint(kidRect.x, kidYTop));
   nsHTMLReflowMetrics desiredSize;
--- a/layout/tables/nsTableFrame.cpp
+++ b/layout/tables/nsTableFrame.cpp
@@ -113,24 +113,24 @@ struct nsTableReflowState {
 
     x = borderPadding.left + cellSpacingX;
     y = borderPadding.top; //cellspacing added during reflow
 
     availSize.width  = aAvailWidth;
     if (NS_UNCONSTRAINEDSIZE != availSize.width) {
       availSize.width -= borderPadding.left + borderPadding.right
                          + (2 * cellSpacingX);
-      availSize.width = PR_MAX(0, availSize.width);
+      availSize.width = NS_MAX(0, availSize.width);
     }
 
     availSize.height = aAvailHeight;
     if (NS_UNCONSTRAINEDSIZE != availSize.height) {
       availSize.height -= borderPadding.top + borderPadding.bottom
                           + (2 * table->GetCellSpacingY());
-      availSize.height = PR_MAX(0, availSize.height);
+      availSize.height = NS_MAX(0, availSize.height);
     }
   }
 
   nsTableReflowState(nsPresContext&           aPresContext,
                      const nsHTMLReflowState& aReflowState,
                      nsTableFrame&            aTableFrame)
     : reflowState(aReflowState)
   {
@@ -629,17 +629,17 @@ void nsTableFrame::InsertCol(nsTableColF
       }
       if (!removedFromCache) {
         cellMap->AddColsAtEnd(1);
       }
     }
   }
   // for now, just bail and recalc all of the collapsing borders
   if (IsBorderCollapse()) {
-    nsRect damageArea(0, 0, PR_MAX(1, GetColCount()), PR_MAX(1, GetRowCount()));
+    nsRect damageArea(0, 0, NS_MAX(1, GetColCount()), NS_MAX(1, GetRowCount()));
     SetBCDamageArea(damageArea);
   }
 }
 
 void nsTableFrame::RemoveCol(nsTableColGroupFrame* aColGroupFrame,
                              PRInt32               aColIndex,
                              PRBool                aRemoveFromCache,
                              PRBool                aRemoveFromCellMap)
@@ -1424,17 +1424,17 @@ nsTableFrame::SetColumnDimensions(nscoor
   nscoord cellSpacingX = GetCellSpacingX();
   nscoord cellSpacingY = GetCellSpacingY();
   nscoord colHeight = aHeight -= aBorderPadding.top + aBorderPadding.bottom +
                                  2* cellSpacingY;
 
   nsTableIterator iter(mColGroups); 
   nsIFrame* colGroupFrame = iter.First();
   PRBool tableIsLTR = GetStyleVisibility()->mDirection == NS_STYLE_DIRECTION_LTR;
-  PRInt32 colX =tableIsLTR ? 0 : PR_MAX(0, GetColCount() - 1);
+  PRInt32 colX =tableIsLTR ? 0 : NS_MAX(0, GetColCount() - 1);
   PRInt32 tableColIncr = tableIsLTR ? 1 : -1; 
   nsPoint colGroupOrigin(aBorderPadding.left + cellSpacingX,
                          aBorderPadding.top + cellSpacingY);
   while (nsnull != colGroupFrame) {
     nscoord colGroupWidth = 0;
     nsTableIterator iterCol(*colGroupFrame);  
     nsIFrame* colFrame = iterCol.First();
     nsPoint colOrigin(0,0);
@@ -2343,17 +2343,17 @@ nsTableFrame::RemoveFrame(nsIAtom*      
     } else {
       // Just remove the frame
       mFrames.DestroyFrame(aOldFrame);
     }
   }
   // for now, just bail and recalc all of the collapsing borders
   // XXXldb [reflow branch merging 20060830] do we still need this?
   if (IsBorderCollapse()) {
-    nsRect damageArea(0, 0, PR_MAX(1, GetColCount()), PR_MAX(1, GetRowCount()));
+    nsRect damageArea(0, 0, NS_MAX(1, GetColCount()), NS_MAX(1, GetRowCount()));
     SetBCDamageArea(damageArea);
   }
   PresContext()->PresShell()->FrameNeedsReflow(this, nsIPresShell::eTreeChange,
                                                NS_FRAME_HAS_DIRTY_CHILDREN);
   SetGeometryDirty();
 #ifdef DEBUG_TABLE_CELLMAP
   printf("=== TableFrame::RemoveFrame\n");
   Dump(PR_TRUE, PR_TRUE, PR_TRUE);
@@ -3151,17 +3151,17 @@ nsTableFrame::DistributeHeightToRows(con
     nscoord yOriginRow = 0;
     nsRect rgRect = rgFrame->GetRect();
     if (!rgFrame->HasStyleHeight()) {
       nsTableRowFrame* rowFrame = rgFrame->GetFirstRow();
       while (rowFrame) {
         nsRect rowRect = rowFrame->GetRect();
         if ((amountUsed < aAmount) && rowFrame->HasPctHeight()) {
           nscoord pctHeight = rowFrame->GetHeight(pctBasis);
-          nscoord amountForRow = PR_MIN(aAmount - amountUsed, pctHeight - rowRect.height);
+          nscoord amountForRow = NS_MIN(aAmount - amountUsed, pctHeight - rowRect.height);
           if (amountForRow > 0) {
             nsRect oldRowRect = rowRect;
             rowRect.height += amountForRow;
             // XXXbz we don't need to change rowRect.y to be yOriginRow?
             rowFrame->SetRect(rowRect);
             yOriginRow += rowRect.height + cellSpacingY;
             yEndRG += rowRect.height + cellSpacingY;
             amountUsed += amountForRow;
@@ -3308,17 +3308,17 @@ nsTableFrame::DistributeHeightToRows(con
           else {
             // all rows get the same additional space
             ratio = 1.0f / float(divisor);
           }
           // give rows their additional space, except for the last row which
           // gets the remainder
           nscoord amountForRow = (rowFrame == lastEligibleRow) 
                                  ? aAmount - amountUsed : NSToCoordRound(((float)(heightToDistribute)) * ratio);
-          amountForRow = PR_MIN(amountForRow, aAmount - amountUsed);
+          amountForRow = NS_MIN(amountForRow, aAmount - amountUsed);
 
           if (yOriginRow != rowRect.y) {
             rowFrame->InvalidateOverflowRect();
           }
           
           // update the row height
           nsRect newRowRect(rowRect.x, yOriginRow, rowRect.width,
                             rowRect.height + amountForRow);
@@ -3532,17 +3532,17 @@ nsTableFrame::IsAutoHeight()
 nscoord 
 nsTableFrame::CalcBorderBoxHeight(const nsHTMLReflowState& aState)
 {
   nscoord height = aState.ComputedHeight();
   if (NS_AUTOHEIGHT != height) {
     nsMargin borderPadding = GetChildAreaOffset(&aState);
     height += borderPadding.top + borderPadding.bottom;
   }
-  height = PR_MAX(0, height);
+  height = NS_MAX(0, height);
 
   return height;
 }
 
 PRBool 
 nsTableFrame::IsAutoLayout()
 {
   if (GetStyleTable()->mLayoutStrategy == NS_STYLE_TABLE_LAYOUT_AUTO)
@@ -3933,18 +3933,18 @@ CheckFixDamageArea(PRInt32 aNumRows,
  *     cell, row, rowgroup, col, colgroup, table
  *  5) if all border styles are NONE, then that's the computed border style.
  *******************************************************************************/
 
 void 
 nsTableFrame::SetBCDamageArea(const nsRect& aValue)
 {
   nsRect newRect(aValue);
-  newRect.width  = PR_MAX(1, newRect.width);
-  newRect.height = PR_MAX(1, newRect.height);
+  newRect.width  = NS_MAX(1, newRect.width);
+  newRect.height = NS_MAX(1, newRect.height);
 
   if (!IsBorderCollapse()) {
     NS_ASSERTION(PR_FALSE, "invalid call - not border collapse model");
     return;
   }
   SetNeedToCalcBCBorders(PR_TRUE);
   // Get the property 
   BCPropertyData* value = (BCPropertyData*)nsTableFrame::GetProperty(this, nsGkAtoms::tableBCProperty, PR_TRUE);
@@ -4318,17 +4318,17 @@ BCMapCellInfo::SetInfo(nsTableRowFrame* 
                                                          mColSpan -1);
     if (!colFrame) ABORT0();
     mRightCol = colFrame;
   }
 
   // col group frame info
   mColGroup = static_cast<nsTableColGroupFrame*>(mLeftCol->GetParent());
   PRInt32 cgStart = mColGroup->GetStartColumnIndex();
-  PRInt32 cgEnd = PR_MAX(0, cgStart + mColGroup->GetColCount() - 1);
+  PRInt32 cgEnd = NS_MAX(0, cgStart + mColGroup->GetColCount() - 1);
   mCgAtLeft  = (cgStart == aColIndex);
   mCgAtRight = (cgEnd == aColIndex + mColSpan - 1);
 }
 
 PRBool
 BCMapCellIterator::SetNewRow(nsTableRowFrame* aRow)
 {
   mAtEnd   = PR_TRUE;
@@ -5016,17 +5016,17 @@ struct BCCorners
 {
   BCCorners(PRInt32 aNumCorners,
             PRInt32 aStartIndex);
 
   ~BCCorners() { delete [] corners; }
   
   BCCornerInfo& operator [](PRInt32 i) const
   { NS_ASSERTION((i >= startIndex) && (i <= endIndex), "program error");
-    return corners[PR_MAX(PR_MIN(i, endIndex), startIndex) - startIndex]; }
+    return corners[NS_MAX(NS_MIN(i, endIndex), startIndex) - startIndex]; }
 
   PRInt32       startIndex;
   PRInt32       endIndex;
   BCCornerInfo* corners;
 };
   
 BCCorners::BCCorners(PRInt32 aNumCorners,
                      PRInt32 aStartIndex)
@@ -5042,17 +5042,17 @@ struct BCCellBorders
 {
   BCCellBorders(PRInt32 aNumBorders,
                 PRInt32 aStartIndex);
 
   ~BCCellBorders() { delete [] borders; }
   
   BCCellBorder& operator [](PRInt32 i) const
   { NS_ASSERTION((i >= startIndex) && (i <= endIndex), "program error");
-    return borders[PR_MAX(PR_MIN(i, endIndex), startIndex) - startIndex]; }
+    return borders[NS_MAX(NS_MIN(i, endIndex), startIndex) - startIndex]; }
 
   PRInt32       startIndex;
   PRInt32       endIndex;
   BCCellBorder* borders;
 };
   
 BCCellBorders::BCCellBorders(PRInt32 aNumBorders,
                              PRInt32 aStartIndex)
@@ -5173,22 +5173,22 @@ nsTableFrame::ExpandBCDamageArea(nsRect&
         }
       }
       // check for spanners on the left and right
       PRInt32 iterStartY = -1;
       PRInt32 iterEndY   = -1;
       if ((dStartY >= rgStartY) && (dStartY <= rgEndY)) {
         // the damage area starts in the row group
         iterStartY = dStartY;
-        iterEndY   = PR_MIN(dEndY, rgEndY);
+        iterEndY   = NS_MIN(dEndY, rgEndY);
       }
       else if ((dEndY >= rgStartY) && (dEndY <= rgEndY)) {
         // the damage area ends in the row group
         iterStartY = rgStartY;
-        iterEndY   = PR_MIN(dEndY, rgStartY);
+        iterEndY   = NS_MIN(dEndY, rgStartY);
       }
       else if ((rgStartY >= dStartY) && (rgEndY <= dEndY)) {
         // the damage area contains the row group
         iterStartY = rgStartY;
         iterEndY   = rgEndY;
       }
       if ((iterStartY >= 0) && (iterEndY >= 0)) {
         for (PRInt32 y = iterStartY; y <= iterEndY; y++) {
@@ -5226,17 +5226,17 @@ nsTableFrame::ExpandBCDamageArea(nsRect&
     aRect.height = 1 + dEndY - dStartY;
   }
 }
 
 #define MAX_TABLE_BORDER_WIDTH 255
 static PRUint8
 LimitBorderWidth(PRUint16 aWidth)
 {
-  return PR_MIN(MAX_TABLE_BORDER_WIDTH, aWidth);
+  return NS_MIN(PRUint16(MAX_TABLE_BORDER_WIDTH), aWidth);
 }
 
 #define TABLE_EDGE  PR_TRUE
 #define ADJACENT    PR_TRUE
 #define HORIZONTAL  PR_TRUE
 
 void
 BCMapCellInfo::SetTableTopLeftContBCBorder()
@@ -5405,110 +5405,112 @@ BCMapCellInfo::SetRowRightContBCBorder()
     mCurrentRowFrame->SetContinuousBCBorderWidth(mEndSide,
                                                  currentBorder.width);
   }
 }
 void
 BCMapCellInfo::SetTableTopBorderWidth(BCPixelSize aWidth)
 {
   mTableBCData->mTopBorderWidth =
-     LimitBorderWidth(PR_MAX(mTableBCData->mTopBorderWidth, (PRUint8) aWidth));
+     LimitBorderWidth(NS_MAX(mTableBCData->mTopBorderWidth, aWidth));
 }
 
 void
 BCMapCellInfo::SetTableLeftBorderWidth(PRInt32 aRowY, BCPixelSize aWidth)
 {
   // update the left/right first cell border
   if (aRowY == 0) {
     if (mTableIsLTR) {
       mTableBCData->mLeftCellBorderWidth = aWidth;
     }
     else {
       mTableBCData->mRightCellBorderWidth = aWidth;
     }
   }
   mTableBCData->mLeftBorderWidth =
-               LimitBorderWidth(PR_MAX(mTableBCData->mLeftBorderWidth, aWidth));
+               LimitBorderWidth(NS_MAX(mTableBCData->mLeftBorderWidth, aWidth));
 }
 
 void
 BCMapCellInfo::SetTableRightBorderWidth(PRInt32 aRowY, BCPixelSize aWidth)
 {
   // update the left/right first cell border
   if (aRowY == 0) {
     if (mTableIsLTR) {
       mTableBCData->mRightCellBorderWidth = aWidth;
     }
     else {
       mTableBCData->mLeftCellBorderWidth = aWidth;
     }
   }
   mTableBCData->mRightBorderWidth =
-              LimitBorderWidth(PR_MAX(mTableBCData->mRightBorderWidth, aWidth));
+              LimitBorderWidth(NS_MAX(mTableBCData->mRightBorderWidth, aWidth));
 }
 
 void
 BCMapCellInfo::SetRightBorderWidths(BCPixelSize aWidth)
 {
    // update the borders of the cells and cols affected
   if (mCell) {
-    mCell->SetBorderWidth(mEndSide, PR_MAX(aWidth,
+    mCell->SetBorderWidth(mEndSide, NS_MAX(aWidth,
                           mCell->GetBorderWidth(mEndSide)));
   }
   if (mRightCol) {
     BCPixelSize half = BC_BORDER_LEFT_HALF(aWidth);
-    mRightCol->SetRightBorderWidth(PR_MAX(half,
+    mRightCol->SetRightBorderWidth(NS_MAX(nscoord(half),
                                    mRightCol->GetRightBorderWidth()));
   }
 }
 
 void
 BCMapCellInfo::SetBottomBorderWidths(BCPixelSize aWidth)
 {
   // update the borders of the affected cells and rows
   if (mCell) {
-    mCell->SetBorderWidth(NS_SIDE_BOTTOM, PR_MAX(aWidth,
+    mCell->SetBorderWidth(NS_SIDE_BOTTOM, NS_MAX(aWidth,
                           mCell->GetBorderWidth(NS_SIDE_BOTTOM)));
   }
   if (mBottomRow) {
     BCPixelSize half = BC_BORDER_TOP_HALF(aWidth);
-    mBottomRow->SetBottomBCBorderWidth(PR_MAX(half,
+    mBottomRow->SetBottomBCBorderWidth(NS_MAX(nscoord(half),
                                        mBottomRow->GetBottomBCBorderWidth()));
   }
 }
 void
 BCMapCellInfo::SetTopBorderWidths(BCPixelSize aWidth)
 {
  if (mCell) {
-     mCell->SetBorderWidth(NS_SIDE_TOP, PR_MAX(aWidth,
+     mCell->SetBorderWidth(NS_SIDE_TOP, NS_MAX(aWidth,
                            mCell->GetBorderWidth(NS_SIDE_TOP)));
   }
   if (mTopRow) {
     BCPixelSize half = BC_BORDER_BOTTOM_HALF(aWidth);
-    mTopRow->SetTopBCBorderWidth(PR_MAX(half, mTopRow->GetTopBCBorderWidth()));
+    mTopRow->SetTopBCBorderWidth(NS_MAX(nscoord(half),
+                                        mTopRow->GetTopBCBorderWidth()));
   }
 }
 void
 BCMapCellInfo::SetLeftBorderWidths(BCPixelSize aWidth)
 {
   if (mCell) {
-    mCell->SetBorderWidth(mStartSide, PR_MAX(aWidth,
+    mCell->SetBorderWidth(mStartSide, NS_MAX(aWidth,
                           mCell->GetBorderWidth(mStartSide)));
   }
   if (mLeftCol) {
     BCPixelSize half = BC_BORDER_RIGHT_HALF(aWidth);
-    mLeftCol->SetLeftBorderWidth(PR_MAX(half, mLeftCol->GetLeftBorderWidth()));
+    mLeftCol->SetLeftBorderWidth(NS_MAX(nscoord(half),
+                                        mLeftCol->GetLeftBorderWidth()));
   }
 }
 
 void
 BCMapCellInfo::SetTableBottomBorderWidth(BCPixelSize aWidth)
 {
   mTableBCData->mBottomBorderWidth =
-             LimitBorderWidth(PR_MAX(mTableBCData->mBottomBorderWidth, aWidth));
+             LimitBorderWidth(NS_MAX(mTableBCData->mBottomBorderWidth, aWidth));
 }
 
 void
 BCMapCellInfo::SetColumn(PRInt32 aColX)
 {
   mCurrentColFrame = mTableFrame->GetColFrame(aColX);
   if (!mCurrentColFrame) {
     NS_ERROR("null mCurrentColFrame");
@@ -5843,18 +5845,18 @@ nsTableFrame::CalcBCBorders()
       for (PRInt32 rowY = info.mRowIndex; rowY <= info.GetCellEndRowIndex();
            rowY += segLength) {
         iter.PeekRight(info, rowY, ajaInfo);
         currentBorder  = info.GetRightInternalBorder();
         adjacentBorder = ajaInfo.GetLeftInternalBorder();
         currentBorder = CompareBorders(!CELL_CORNER, currentBorder,
                                         adjacentBorder, !HORIZONTAL);
                           
-        segLength = PR_MAX(1, ajaInfo.mRowIndex + ajaInfo.mRowSpan - rowY);
-        segLength = PR_MIN(segLength, info.mRowIndex + info.mRowSpan - rowY);
+        segLength = NS_MAX(1, ajaInfo.mRowIndex + ajaInfo.mRowSpan - rowY);
+        segLength = NS_MIN(segLength, info.mRowIndex + info.mRowSpan - rowY);
 
         // update lastVerBorders and see if a new segment starts
         startSeg = SetBorder(currentBorder,
                              lastVerBorders[info.GetCellEndColIndex() + 1]);
         // store the border segment in the cell map and update cellBorders
         if (info.GetCellEndColIndex() < damageArea.XMost() &&
             rowY >= damageArea.y && rowY < damageArea.YMost()) {
           tableCellMap->SetBCBorderEdge(NS_SIDE_RIGHT, *iter.mCellMap,
@@ -5977,18 +5979,18 @@ nsTableFrame::CalcBCBorders()
       PRInt32 segLength = 0;
       for (PRInt32 colX = info.mColIndex; colX <= info.GetCellEndColIndex();
            colX += segLength) {
         iter.PeekBottom(info, colX, ajaInfo);
         currentBorder  = info.GetBottomInternalBorder();
         adjacentBorder = ajaInfo.GetTopInternalBorder();
         currentBorder = CompareBorders(!CELL_CORNER, currentBorder,
                                         adjacentBorder, HORIZONTAL);
-        segLength = PR_MAX(1, ajaInfo.mColIndex + ajaInfo.mColSpan - colX);
-        segLength = PR_MIN(segLength, info.mColIndex + info.mColSpan - colX);
+        segLength = NS_MAX(1, ajaInfo.mColIndex + ajaInfo.mColSpan - colX);
+        segLength = NS_MIN(segLength, info.mColIndex + info.mColSpan - colX);
 
         // update, store the bottom left corner
         BCCornerInfo& blCorner = bottomCorners[colX]; // bottom left
         PRBool hitsSpanBelow = (colX > ajaInfo.mColIndex) &&
                                (colX < ajaInfo.mColIndex + ajaInfo.mColSpan);
         PRBool update = PR_TRUE;
         if ((colX == info.mColIndex) && (colX > damageArea.x)) {
           PRInt32 prevRowIndex = lastBottomBorders[colX - 1].rowIndex;
@@ -6507,17 +6509,17 @@ BCVerticalSeg::Start(BCMapBorderIterator
                      BCVerticalSeg*       aVerInfoArray)
 {
   PRUint8      ownerSide = 0;
   PRPackedBool bevel     = PR_FALSE;
   PRInt32      xAdj      = aIter.x - aIter.startX;
 
   nscoord cornerSubWidth  = (aIter.bcData) ? aIter.bcData->GetCorner(ownerSide, bevel) : 0;
   PRBool  topBevel        = (aVerSegWidth > 0) ? bevel : PR_FALSE;
-  nscoord maxHorSegHeight = PR_MAX(aPrevHorSegHeight, aHorSegHeight);
+  nscoord maxHorSegHeight = NS_MAX(aPrevHorSegHeight, aHorSegHeight);
   nscoord offset          = CalcVerCornerOffset(ownerSide, cornerSubWidth, maxHorSegHeight, 
                                                 PR_TRUE, topBevel);
 
   bevelOffset   = (topBevel) ? maxHorSegHeight : 0;
   bevelSide     = (aHorSegHeight > 0) ? NS_SIDE_RIGHT : NS_SIDE_LEFT;
   segY         += offset;
   segHeight     = -offset;
   segWidth      = aVerSegWidth;
@@ -6585,17 +6587,17 @@ BCHorizontalSeg::Start(BCMapBorderIterat
                        nscoord              aTopVerSegWidth,
                        nscoord              aBottomVerSegWidth,
                        nscoord              aHorSegHeight,
                        nsTableCellFrame*    aLastCell,
                        PRBool               aTableIsLTR)
 {
   owner = aBorderOwner;
   leftBevel = (aHorSegHeight > 0) ? aBevel : PR_FALSE;
-  nscoord maxVerSegWidth = PR_MAX(aTopVerSegWidth, aBottomVerSegWidth);
+  nscoord maxVerSegWidth = NS_MAX(aTopVerSegWidth, aBottomVerSegWidth);
   nscoord offset = CalcHorCornerOffset(aCornerOwnerSide, aSubWidth, maxVerSegWidth, 
                                        PR_TRUE, leftBevel, aTableIsLTR);
   leftBevelOffset = (leftBevel && (aHorSegHeight > 0)) ? maxVerSegWidth : 0;
   leftBevelSide   = (aBottomVerSegWidth > 0) ? NS_SIDE_BOTTOM : NS_SIDE_TOP;
   if (aTableIsLTR) {
     x            += offset;
   }
   else {
@@ -6788,17 +6790,17 @@ nsTableFrame::PaintBCBorders(nsIRenderin
         if (iter.bcData) {
           cornerSubWidth = iter.bcData->GetCorner(ownerSide, bevel);
         } else {
           cornerSubWidth = 0;
           ownerSide = 0; // ???
           bevel = PR_FALSE; // ???
         }
         PRBool endBevel = (info.segWidth > 0) ? bevel : PR_FALSE; 
-        nscoord bottomHorSegHeight = PR_MAX(prevHorSegHeight, horSegHeight); 
+        nscoord bottomHorSegHeight = NS_MAX(prevHorSegHeight, horSegHeight); 
         nscoord endOffset = CalcVerCornerOffset(ownerSide, cornerSubWidth, bottomHorSegHeight, 
                                                 PR_FALSE, endBevel);
         info.segHeight += endOffset;
         if (info.segWidth > 0) {     
           // get the border style, color and paint the segment
           PRUint8 side = (iter.IsRightMost()) ? NS_SIDE_RIGHT : NS_SIDE_LEFT;
           nsTableRowFrame* row           = info.firstRow;
           nsTableRowGroupFrame* rowGroup = info.firstRowGroup;
@@ -6901,17 +6903,17 @@ nsTableFrame::PaintBCBorders(nsIRenderin
         verInfo[xAdj].colWidth = verInfo[xAdj - 1].colWidth;
       }
       else {
         nsTableColFrame* col = firstInFlow->GetColFrame(iter.x); if (!col) ABORT0();
         verInfo[xAdj].colWidth = col->GetSize().width;
       }
     }
     cornerSubWidth = (iter.bcData) ? iter.bcData->GetCorner(ownerSide, bevel) : 0;
-    nscoord verWidth = PR_MAX(verInfo[xAdj].segWidth, leftSegWidth);
+    nscoord verWidth = NS_MAX(nscoord(verInfo[xAdj].segWidth), leftSegWidth);
     if (iter.isNewRow || (iter.IsLeftMost() && iter.IsBottomMost())) {
       horSeg.y = nextY;
       nextY    = nextY + iter.row->GetSize().height;
       horSeg.x = startColX;
       horSeg.Start(iter, borderOwner, ownerSide, cornerSubWidth, bevel, verInfo[xAdj].segWidth, 
                    leftSegWidth, topSegHeight, verInfo[xAdj].lastCell, tableIsLTR);
     }
     PRBool verOwnsCorner = (NS_SIDE_TOP == ownerSide) || (NS_SIDE_BOTTOM == ownerSide);
--- a/layout/tables/nsTableOuterFrame.cpp
+++ b/layout/tables/nsTableOuterFrame.cpp
@@ -544,17 +544,17 @@ nsTableOuterFrame::GetPrefWidth(nsIRende
           NS_ASSERTION(captionSide == NS_STYLE_CAPTION_SIDE_TOP_OUTSIDE ||
                        captionSide == NS_STYLE_CAPTION_SIDE_BOTTOM_OUTSIDE,
                        "unexpected caption side");
           iwt = nsLayoutUtils::PREF_WIDTH;
         }
         nscoord capPref =
           nsLayoutUtils::IntrinsicForContainer(aRenderingContext, mCaptionFrame,
                                                iwt);
-        maxWidth = PR_MAX(maxWidth, capPref);
+        maxWidth = NS_MAX(maxWidth, capPref);
       }
       break;
     }
   }
   return maxWidth;
 }
 
 // Compute the margin-box width of aChildFrame given the inputs.  If
@@ -674,33 +674,33 @@ nsTableOuterFrame::SetDesiredSize(PRUint
   nsRect captionRect(0,0,0,0);
   nscoord captionWidth = 0;
   if (mCaptionFrame) {
     captionRect = mCaptionFrame->GetRect();
     captionWidth = captionRect.width;
   }
   switch(aCaptionSide) {
     case NS_STYLE_CAPTION_SIDE_LEFT:
-      aWidth = PR_MAX(aInnerMargin.left, aCaptionMargin.left + captionWidth + aCaptionMargin.right) +
+      aWidth = NS_MAX(aInnerMargin.left, aCaptionMargin.left + captionWidth + aCaptionMargin.right) +
                innerWidth + aInnerMargin.right;
       break;
     case NS_STYLE_CAPTION_SIDE_RIGHT:
-      aWidth = PR_MAX(aInnerMargin.right, aCaptionMargin.left + captionWidth + aCaptionMargin.right) +
+      aWidth = NS_MAX(aInnerMargin.right, aCaptionMargin.left + captionWidth + aCaptionMargin.right) +
                innerWidth + aInnerMargin.left;
       break;
     default:
       aWidth = aInnerMargin.left + innerWidth + aInnerMargin.right;
-      aWidth = PR_MAX(aWidth, captionRect.XMost() + aCaptionMargin.right);
+      aWidth = NS_MAX(aWidth, captionRect.XMost() + aCaptionMargin.right);
   }
   aHeight = innerRect.YMost() + aInnerMargin.bottom;
   if (NS_STYLE_CAPTION_SIDE_BOTTOM != aCaptionSide) {
-    aHeight = PR_MAX(aHeight, captionRect.YMost() + aCaptionMargin.bottom);
+    aHeight = NS_MAX(aHeight, captionRect.YMost() + aCaptionMargin.bottom);
   }
   else {
-    aHeight = PR_MAX(aHeight, captionRect.YMost() + aCaptionMargin.bottom +
+    aHeight = NS_MAX(aHeight, captionRect.YMost() + aCaptionMargin.bottom +
                               aInnerMargin.bottom);
   }
 
 }
 
 // XXX This is now unused, but it probably should be used!
 void
 nsTableOuterFrame::BalanceLeftRightCaption(PRUint8         aCaptionSide,
@@ -822,20 +822,20 @@ nsTableOuterFrame::GetCaptionOrigin(PRUi
   }
   // vertical computation
   switch (aCaptionSide) {
     case NS_STYLE_CAPTION_SIDE_RIGHT:
     case NS_STYLE_CAPTION_SIDE_LEFT:
       aOrigin.y = aInnerMargin.top;
       switch (GetCaptionVerticalAlign()) {
         case NS_STYLE_VERTICAL_ALIGN_MIDDLE:
-          aOrigin.y = PR_MAX(0, aInnerMargin.top + ((aInnerSize.height - aCaptionSize.height) / 2));
+          aOrigin.y = NS_MAX(0, aInnerMargin.top + ((aInnerSize.height - aCaptionSize.height) / 2));
           break;
         case NS_STYLE_VERTICAL_ALIGN_BOTTOM:
-          aOrigin.y = PR_MAX(0, aInnerMargin.top + aInnerSize.height - aCaptionSize.height);
+          aOrigin.y = NS_MAX(0, aInnerMargin.top + aInnerSize.height - aCaptionSize.height);
           break;
         default:
           break;
       }
       break;
     case NS_STYLE_CAPTION_SIDE_BOTTOM: {
       aOrigin.y = aInnerMargin.top + aInnerSize.height + aCaptionMargin.top;
     } break;
@@ -888,17 +888,17 @@ nsTableOuterFrame::GetInnerOrigin(PRUint
   minCapWidth += aCaptionMargin.right;
 
   // horizontal computation
   switch (aCaptionSide) {
   case NS_STYLE_CAPTION_SIDE_LEFT: {
     if (aInnerMargin.left < minCapWidth) {
       // shift the inner table to get some place for the caption
       aInnerMargin.right += aInnerMargin.left - minCapWidth;
-      aInnerMargin.right  = PR_MAX(0, aInnerMargin.right);
+      aInnerMargin.right  = NS_MAX(0, aInnerMargin.right);
       aInnerMargin.left   = minCapWidth;
     }
     aOrigin.x = aInnerMargin.left;
   } break;
   default: {
     NS_ASSERTION(aCaptionSide == NS_STYLE_CAPTION_SIDE_TOP ||
                  aCaptionSide == NS_STYLE_CAPTION_SIDE_TOP_OUTSIDE ||
                  aCaptionSide == NS_STYLE_CAPTION_SIDE_BOTTOM ||
@@ -916,20 +916,20 @@ nsTableOuterFrame::GetInnerOrigin(PRUint
     case NS_STYLE_CAPTION_SIDE_BOTTOM_OUTSIDE: {
       aOrigin.y = aInnerMargin.top;
     } break;
     case NS_STYLE_CAPTION_SIDE_LEFT:
     case NS_STYLE_CAPTION_SIDE_RIGHT: {
       aOrigin.y = aInnerMargin.top;
       switch (GetCaptionVerticalAlign()) {
         case NS_STYLE_VERTICAL_ALIGN_MIDDLE:
-          aOrigin.y = PR_MAX(aInnerMargin.top, (aCaptionSize.height - aInnerSize.height) / 2);
+          aOrigin.y = NS_MAX(aInnerMargin.top, (aCaptionSize.height - aInnerSize.height) / 2);
           break;
         case NS_STYLE_VERTICAL_ALIGN_BOTTOM:
-          aOrigin.y = PR_MAX(aInnerMargin.top, aCaptionSize.height - aInnerSize.height);
+          aOrigin.y = NS_MAX(aInnerMargin.top, aCaptionSize.height - aInnerSize.height);
           break;
         default:
           break;
       }
     } break;
     case NO_SIDE:
     case NS_STYLE_CAPTION_SIDE_TOP: {
       aOrigin.y = aInnerMargin.top + aCaptionMargin.top + aCaptionSize.height +
--- a/layout/tables/nsTableRowFrame.cpp
+++ b/layout/tables/nsTableRowFrame.cpp
@@ -70,24 +70,24 @@ struct nsTableCellReflowState : public n
 void nsTableCellReflowState::FixUp(const nsSize& aAvailSpace)
 {
   // fix the mComputed values during a pass 2 reflow since the cell can be a percentage base
   NS_ASSERTION(NS_UNCONSTRAINEDSIZE != aAvailSpace.width,
                "unconstrained available width in reflow");
   if (NS_UNCONSTRAINEDSIZE != ComputedWidth()) {
     nscoord computedWidth =
       aAvailSpace.width - mComputedBorderPadding.LeftRight();
-    computedWidth = PR_MAX(0, computedWidth);
+    computedWidth = NS_MAX(0, computedWidth);
     SetComputedWidth(computedWidth);
   }
   if (NS_UNCONSTRAINEDSIZE != ComputedHeight() &&
       NS_UNCONSTRAINEDSIZE != aAvailSpace.height) {
     nscoord computedHeight =
       aAvailSpace.height - mComputedBorderPadding.TopBottom();
-    computedHeight = PR_MAX(0, computedHeight);
+    computedHeight = NS_MAX(0, computedHeight);
     SetComputedHeight(computedHeight);
   }
 }
 
 void
 nsTableRowFrame::InitChildReflowState(nsPresContext&         aPresContext,
                                       const nsSize&           aAvailSize,
                                       PRBool                  aBorderCollapse,
@@ -104,17 +104,17 @@ nsTableRowFrame::InitChildReflowState(ns
   }
   aReflowState.Init(&aPresContext, -1, -1, pCollapseBorder);
   aReflowState.FixUp(aAvailSize);
 }
 
 void 
 nsTableRowFrame::SetFixedHeight(nscoord aValue)
 {
-  nscoord height = PR_MAX(0, aValue);
+  nscoord height = NS_MAX(0, aValue);
   if (HasFixedHeight()) {
     if (height > mStyleFixedHeight) {
       mStyleFixedHeight = height;
     }
   }
   else {
     mStyleFixedHeight = height;
     if (height > 0) {
@@ -122,17 +122,17 @@ nsTableRowFrame::SetFixedHeight(nscoord 
     }
   }
 }
 
 void 
 nsTableRowFrame::SetPctHeight(float  aPctValue,
                               PRBool aForce)
 {
-  nscoord height = PR_MAX(0, NSToCoordRound(aPctValue * 100.0f));
+  nscoord height = NS_MAX(0, NSToCoordRound(aPctValue * 100.0f));
   if (HasPctHeight()) {
     if ((height > mStylePctHeight) || aForce) {
       mStylePctHeight = height;
     }
   }
   else {
     mStylePctHeight = height;
     if (height > 0.0f) {
@@ -441,34 +441,34 @@ nscoord nsTableRowFrame::GetRowBaseline(
   // bbbbbbbbbbbbbbbbbb
 
   nsTableIterator iter(*this);
   nsIFrame* childFrame = iter.First();
   nscoord ascent = 0;
    while (childFrame) {
     if (IS_TABLE_CELL(childFrame->GetType())) {
       nsIFrame* firstKid = childFrame->GetFirstChild(nsnull);
-      ascent = PR_MAX(ascent, firstKid->GetRect().YMost());
+      ascent = NS_MAX(ascent, firstKid->GetRect().YMost());
     }
     // Get the next child
     childFrame = iter.Next();
   }
   return ascent;
 }
 nscoord
 nsTableRowFrame::GetHeight(nscoord aPctBasis) const
 {
   nscoord height = 0;
   if ((aPctBasis > 0) && HasPctHeight()) {
     height = NSToCoordRound(GetPctHeight() * (float)aPctBasis);
   }
   if (HasFixedHeight()) {
-    height = PR_MAX(height, GetFixedHeight());
+    height = NS_MAX(height, GetFixedHeight());
   }
-  return PR_MAX(height, GetContentHeight());
+  return NS_MAX(height, GetContentHeight());
 }
 
 void 
 nsTableRowFrame::ResetHeight(nscoord aFixedHeight)
 {
   SetHasFixedHeight(PR_FALSE);
   SetHasPctHeight(PR_FALSE);
   SetFixedHeight(0);
@@ -783,17 +783,17 @@ nscoord CalcHeightFromUnpaginatedHeight(
   if (!firstInFlow) ABORT1(0);
   if (firstInFlow->HasUnpaginatedHeight()) {
     height = firstInFlow->GetUnpaginatedHeight(aPresContext);
     for (nsIFrame* prevInFlow = aRow.GetPrevInFlow(); prevInFlow;
          prevInFlow = prevInFlow->GetPrevInFlow()) {
       height -= prevInFlow->GetSize().height;
     }
   }
-  return PR_MAX(height, 0);
+  return NS_MAX(height, 0);
 }
 
 NS_METHOD 
 nsTableRowFrame::ReflowChildren(nsPresContext*          aPresContext,
                                 nsHTMLReflowMetrics&     aDesiredSize,
                                 const nsHTMLReflowState& aReflowState,
                                 nsTableFrame&            aTableFrame,
                                 nsReflowStatus&          aStatus)
@@ -957,17 +957,17 @@ nsTableRowFrame::ReflowChildren(nsPresCo
         if (!kidFrame->GetFirstChild(nsnull)->GetFirstChild(nsnull))
           ascent = desiredSize.height;
         else
           ascent = ((nsTableCellFrame *)kidFrame)->GetCellBaseline();
         nscoord descent = desiredSize.height - ascent;
         UpdateHeight(desiredSize.height, ascent, descent, &aTableFrame, cellFrame);
       }
       else {
-        cellMaxHeight = PR_MAX(cellMaxHeight, desiredSize.height);
+        cellMaxHeight = NS_MAX(cellMaxHeight, desiredSize.height);
         PRInt32 rowSpan = aTableFrame.GetEffectiveRowSpan((nsTableCellFrame&)*kidFrame);
         if (1 == rowSpan) {
           SetContentHeight(cellMaxHeight);
         }
       }
 
       // Place the child
       desiredSize.width = availCellWidth;
@@ -1005,38 +1005,38 @@ nsTableRowFrame::ReflowChildren(nsPresCo
 
   if (aReflowState.mFlags.mSpecialHeightReflow) {
     aDesiredSize.height = mRect.height;
   }
   else if (NS_UNCONSTRAINEDSIZE == aReflowState.availableHeight) {
     aDesiredSize.height = CalcHeight(aReflowState);
     if (GetPrevInFlow()) {
       nscoord height = CalcHeightFromUnpaginatedHeight(aPresContext, *this);
-      aDesiredSize.height = PR_MAX(aDesiredSize.height, height);
+      aDesiredSize.height = NS_MAX(aDesiredSize.height, height);
     }
     else {
       if (isPaginated && HasStyleHeight()) {
         // set the unpaginated height so next in flows can try to honor it
         SetHasUnpaginatedHeight(PR_TRUE);
         SetUnpaginatedHeight(aPresContext, aDesiredSize.height);
       }
       if (isPaginated && HasUnpaginatedHeight()) {
-        aDesiredSize.height = PR_MAX(aDesiredSize.height, GetUnpaginatedHeight(aPresContext));
+        aDesiredSize.height = NS_MAX(aDesiredSize.height, GetUnpaginatedHeight(aPresContext));
       }
     }
   }
   else { // constrained height, paginated
     // Compute the height we should have from style (subtracting the
     // height from our prev-in-flows from the style height)
     nscoord styleHeight = CalcHeightFromUnpaginatedHeight(aPresContext, *this);
     if (styleHeight > aReflowState.availableHeight) {
       styleHeight = aReflowState.availableHeight;
       NS_FRAME_SET_INCOMPLETE(aStatus);
     }
-    aDesiredSize.height = PR_MAX(cellMaxHeight, styleHeight);
+    aDesiredSize.height = NS_MAX(cellMaxHeight, styleHeight);
   }
   nsRect rowRect(0, 0, aDesiredSize.width, aDesiredSize.height);
   aDesiredSize.mOverflowArea.UnionRect(aDesiredSize.mOverflowArea, rowRect);
   FinishAndStoreOverflow(&aDesiredSize);
   return rv;
 }
 
 /** Layout the entire row.
--- a/layout/tables/nsTableRowGroupFrame.cpp
+++ b/layout/tables/nsTableRowGroupFrame.cpp
@@ -606,25 +606,25 @@ nsTableRowGroupFrame::CalculateRowHeight
   // the largest desired height of each cell, the largest style height of each cell, 
   // the style height of the row.
   nscoord pctHeightBasis = GetHeightBasis(aReflowState);
   PRInt32 rowIndex; // the index in rowInfo, not among the rows in the row group
   nsTableRowFrame* rowFrame;
   for (rowFrame = startRowFrame, rowIndex = 0; rowFrame; rowFrame = rowFrame->GetNextRow(), rowIndex++) {
     nscoord nonPctHeight = rowFrame->GetContentHeight();
     if (isPaginated) {
-      nonPctHeight = PR_MAX(nonPctHeight, rowFrame->GetSize().height);
+      nonPctHeight = NS_MAX(nonPctHeight, rowFrame->GetSize().height);
     }
     if (!rowFrame->GetPrevInFlow()) {
       if (rowFrame->HasPctHeight()) {
         rowInfo[rowIndex].hasPctHeight = PR_TRUE;
         rowInfo[rowIndex].pctHeight = rowFrame->GetHeight(pctHeightBasis);
       }
       rowInfo[rowIndex].hasStyleHeight = rowFrame->HasStyleHeight();
-      nonPctHeight = PR_MAX(nonPctHeight, rowFrame->GetFixedHeight());
+      nonPctHeight = NS_MAX(nonPctHeight, rowFrame->GetFixedHeight());
     }
     UpdateHeights(rowInfo[rowIndex], nonPctHeight, heightOfRows, heightOfUnStyledRows);
 
     if (!rowInfo[rowIndex].hasStyleHeight) {
       if (isPaginated || tableFrame->HasMoreThanOneCell(rowIndex + startRowIndex)) {
         rowInfo[rowIndex].isSpecial = PR_TRUE;
         // iteratate the row's cell frames to see if any do not have rowspan > 1
         nsTableCellFrame* cellFrame = rowFrame->GetFirstCell();
@@ -709,17 +709,17 @@ nsTableRowGroupFrame::CalculateRowHeight
                   for (spanX = rowSpan - 1; spanX >= 0; spanX--) {
                     if (!haveUnStyledRowsSpanned || !rowInfo[rowIndex + spanX].hasStyleHeight) {
                       // The amount of additional space each row gets is proportional to its height
                       float percent = ((float)rowInfo[rowIndex + spanX].height) / ((float)divisor);
                     
                       // give rows their percentage, except for the first row which gets the remainder
                       nscoord extraForRow = (0 == spanX) ? extra - extraUsed  
                                                          : NSToCoordRound(((float)(extra)) * percent);
-                      extraForRow = PR_MIN(extraForRow, extra - extraUsed);
+                      extraForRow = NS_MIN(extraForRow, extra - extraUsed);
                       // update the row height
                       UpdateHeights(rowInfo[rowIndex + spanX], extraForRow, heightOfRows, heightOfUnStyledRows);
                       extraUsed += extraForRow;
                       if (extraUsed >= extra) {
                         NS_ASSERTION((extraUsed == extra), "invalid row height calculation");
                         break;
                       }
                     }
@@ -737,17 +737,17 @@ nsTableRowGroupFrame::CalculateRowHeight
                   if (rowInfo[rowIndex + spanX].isSpecial) {
                     // The amount of additional space each degenerate row gets is proportional to the number of them
                     float percent = 1.0f / ((float)numSpecialRowsSpanned);
                     
                     // give rows their percentage, except for the first row which gets the remainder
                     nscoord extraForRow = (numSpecialRowsSpanned - 1 == numSpecialRowsAllocated) 
                                           ? extra - extraUsed  
                                           : NSToCoordRound(((float)(extra)) * percent);
-                    extraForRow = PR_MIN(extraForRow, extra - extraUsed);
+                    extraForRow = NS_MIN(extraForRow, extra - extraUsed);
                     // update the row height
                     UpdateHeights(rowInfo[rowIndex + spanX], extraForRow, heightOfRows, heightOfUnStyledRows);
                     extraUsed += extraForRow;
                     if (extraUsed >= extra) {
                       NS_ASSERTION((extraUsed == extra), "invalid row height calculation");
                       break;
                     }
                   }
@@ -763,17 +763,17 @@ nsTableRowGroupFrame::CalculateRowHeight
 
   // pct height rows have already got their content heights. Give them their pct heights up to pctHeightBasis
   nscoord extra = pctHeightBasis - heightOfRows;
   for (rowFrame = startRowFrame, rowIndex = 0; rowFrame && (extra > 0); rowFrame = rowFrame->GetNextRow(), rowIndex++) {
     RowInfo& rInfo = rowInfo[rowIndex];
     if (rInfo.hasPctHeight) {
       nscoord rowExtra = (rInfo.pctHeight > rInfo.height)  
                          ? rInfo.pctHeight - rInfo.height: 0;
-      rowExtra = PR_MIN(rowExtra, extra);
+      rowExtra = NS_MIN(rowExtra, extra);
       UpdateHeights(rInfo, rowExtra, heightOfRows, heightOfUnStyledRows);
       extra -= rowExtra;
     }
   }
 
   PRBool styleHeightAllocation = PR_FALSE;
   nscoord rowGroupHeight = startRowGroupHeight + heightOfRows + ((numRows - 1) * cellSpacingY);
   // if we have a style height, allocate the extra height to unconstrained rows
@@ -790,17 +790,17 @@ nsTableRowGroupFrame::CalculateRowHeight
         if (!haveUnStyledRows || !rowInfo[rowIndex].hasStyleHeight) {
           // The amount of additional space each row gets is based on the
           // percentage of space it occupies
           float percent = ((float)rowInfo[rowIndex].height) / ((float)divisor);
           // give rows their percentage, except for the last row which gets the remainder
           nscoord extraForRow = (numRows - 1 == rowIndex) 
                                 ? extraComputedHeight - extraUsed  
                                 : NSToCoordRound(((float)extraComputedHeight) * percent);
-          extraForRow = PR_MIN(extraForRow, extraComputedHeight - extraUsed);
+          extraForRow = NS_MIN(extraForRow, extraComputedHeight - extraUsed);
           // update the row height
           UpdateHeights(rowInfo[rowIndex], extraForRow, heightOfRows, heightOfUnStyledRows);
           extraUsed += extraForRow;
           if (extraUsed >= extraComputedHeight) {
             NS_ASSERTION((extraUsed == extraComputedHeight), "invalid row height calculation");
             break;
           }
         }
@@ -981,17 +981,17 @@ nsTableRowGroupFrame::SplitSpanningCells
         // Ask the row to reflow the cell to the height of all the rows it spans up through aLastRow
         // aAvailHeight is the space between the row group start and the end of the page
         nscoord cellAvailHeight = aSpanningRowBottom - rowPos.y;
         NS_ASSERTION(cellAvailHeight >= 0, "No space for cell?");
         PRBool isTopOfPage = (row == &aFirstRow) && aFirstRowIsTopOfPage;
         nscoord cellHeight = row->ReflowCellFrame(&aPresContext, aReflowState,
                                                   isTopOfPage, cell,
                                                   cellAvailHeight, status);
-        aDesiredHeight = PR_MAX(aDesiredHeight, rowPos.y + cellHeight);
+        aDesiredHeight = NS_MAX(aDesiredHeight, rowPos.y + cellHeight);
         if (NS_FRAME_IS_COMPLETE(status)) {
           if (cellHeight > cellAvailHeight) {
             aFirstTruncatedRow = row;
             if ((row != &aFirstRow) || !aFirstRowIsTopOfPage) {
               // return now, since we will be getting another reflow after either (1) row is 
               // moved to the next page or (2) the row group is moved to the next page
               return;
             }
@@ -1098,19 +1098,19 @@ nsTableRowGroupFrame::SplitRowGroup(nsPr
     nsRect rowRect = rowFrame->GetRect();
     // See if the row fits on this page
     if (rowRect.YMost() > availHeight) {
       nsTableRowFrame* contRow = nsnull;
       // Reflow the row in the availabe space and have it split if it is the 1st
       // row (on the page) or there is at least 5% of the current page available 
       // XXX this 5% should be made a preference 
       if (!prevRowFrame || (availHeight - aDesiredSize.height > pageHeight / 20)) { 
-        nsSize availSize(availWidth, PR_MAX(availHeight - rowRect.y, 0));
+        nsSize availSize(availWidth, NS_MAX(availHeight - rowRect.y, 0));
         // don't let the available height exceed what CalculateRowHeights set for it
-        availSize.height = PR_MIN(availSize.height, rowRect.height);
+        availSize.height = NS_MIN(availSize.height, rowRect.height);
 
         nsHTMLReflowState rowReflowState(aPresContext, aReflowState,
                                          rowFrame, availSize,
                                          -1, -1, PR_FALSE);
                                          
         InitChildReflowState(*aPresContext, borderCollapse, rowReflowState);
         rowReflowState.mFlags.mIsTopOfPage = isTopOfPage; // set top of page
         nsHTMLReflowMetrics rowMetrics;
@@ -1255,17 +1255,17 @@ nsTableRowGroupFrame::SplitRowGroup(nsPr
               aStatus = NS_FRAME_COMPLETE;
               UndoContinuedRow(aPresContext, contRow);
               contRow = nsnull;
             }
           }
         } // if (firstTruncatedRow == firstRowThisPage)
       } // if (firstTruncatedRow)
       else {
-        aDesiredSize.height = PR_MAX(aDesiredSize.height, yMost);
+        aDesiredSize.height = NS_MAX(aDesiredSize.height, yMost);
         if (contRow) {
           aStatus = NS_FRAME_NOT_COMPLETE;
         }
       }
       if (NS_FRAME_IS_NOT_COMPLETE(aStatus) && !contRow) {
         nsTableRowFrame* nextRow = lastRowThisPage->GetNextRow();
         if (nextRow) {
           PushChildren(aPresContext, nextRow, lastRowThisPage);
@@ -1528,27 +1528,27 @@ nsTableRowGroupFrame::GetUsedPadding() c
 
 nscoord 
 nsTableRowGroupFrame::GetHeightBasis(const nsHTMLReflowState& aReflowState)
 {
   nscoord result = 0;
   nsTableFrame* tableFrame = nsTableFrame::GetTableFrame(this);
   if (tableFrame) {
     if ((aReflowState.ComputedHeight() > 0) && (aReflowState.ComputedHeight() < NS_UNCONSTRAINEDSIZE)) {
-      nscoord cellSpacing = PR_MAX(0, GetRowCount() - 1) * tableFrame->GetCellSpacingY();
+      nscoord cellSpacing = NS_MAX(0, GetRowCount() - 1) * tableFrame->GetCellSpacingY();
       result = aReflowState.ComputedHeight() - cellSpacing;
     }
     else {
       const nsHTMLReflowState* parentRS = aReflowState.parentReflowState;
       if (parentRS && (tableFrame != parentRS->frame)) {
         parentRS = parentRS->parentReflowState;
       }
       if (parentRS && (tableFrame == parentRS->frame) && 
           (parentRS->ComputedHeight() > 0) && (parentRS->ComputedHeight() < NS_UNCONSTRAINEDSIZE)) {
-        nscoord cellSpacing = PR_MAX(0, tableFrame->GetRowCount() + 1) * tableFrame->GetCellSpacingY();
+        nscoord cellSpacing = NS_MAX(0, tableFrame->GetRowCount() + 1) * tableFrame->GetCellSpacingY();
         result = parentRS->ComputedHeight() - cellSpacing;
       }
     }
   }
 
   return result;
 }
 
@@ -1910,12 +1910,12 @@ nsTableRowGroupFrame::GetFirstRowContain
 PRBool
 nsTableRowGroupFrame::FrameCursorData::AppendFrame(nsIFrame* aFrame)
 {
   nsRect overflowRect = aFrame->GetOverflowRect();
   if (overflowRect.IsEmpty())
     return PR_TRUE;
   nscoord overflowAbove = -overflowRect.y;
   nscoord overflowBelow = overflowRect.YMost() - aFrame->GetSize().height;
-  mOverflowAbove = PR_MAX(mOverflowAbove, overflowAbove);
-  mOverflowBelow = PR_MAX(mOverflowBelow, overflowBelow);
+  mOverflowAbove = NS_MAX(mOverflowAbove, overflowAbove);
+  mOverflowBelow = NS_MAX(mOverflowBelow, overflowBelow);
   return mFrames.AppendElement(aFrame) != nsnull;
 }
--- a/layout/xul/base/src/grid/nsGridRowLeafLayout.cpp
+++ b/layout/xul/base/src/grid/nsGridRowLeafLayout.cpp
@@ -211,17 +211,17 @@ nsGridRowLeafLayout::PopulateBoxSizes(ns
           if (isHorizontal)
            right -= offset.right;
           else
            right -= offset.bottom;
         }
       }
     
       // initialize the box size here 
-      max = PR_MAX(min, max);
+      max = NS_MAX(min, max);
       pref = nsBox::BoundsCheck(min, pref, max);
    
       current = new (aState) nsBoxSize();
       current->pref = pref;
       current->min = min;
       current->max = max;
       current->flex = flex;
       current->bogus = column->mIsBogus;
--- a/layout/xul/base/src/nsBox.cpp
+++ b/layout/xul/base/src/nsBox.cpp
@@ -972,18 +972,18 @@ nsBox::BoundsCheck(nscoord aMin, nscoord
        aPref = aMin;
 
    return aPref;
 }
 
 nsSize
 nsBox::BoundsCheckMinMax(const nsSize& aMinSize, const nsSize& aMaxSize)
 {
-  return nsSize(PR_MAX(aMaxSize.width, aMinSize.width),
-                PR_MAX(aMaxSize.height, aMinSize.height));
+  return nsSize(NS_MAX(aMaxSize.width, aMinSize.width),
+                NS_MAX(aMaxSize.height, aMinSize.height));
 }
 
 nsSize
 nsBox::BoundsCheck(const nsSize& aMinSize, const nsSize& aPrefSize, const nsSize& aMaxSize)
 {
   return nsSize(BoundsCheck(aMinSize.width, aPrefSize.width, aMaxSize.width),
                 BoundsCheck(aMinSize.height, aPrefSize.height, aMaxSize.height));
 }
--- a/layout/xul/base/src/nsBoxFrame.cpp
+++ b/layout/xul/base/src/nsBoxFrame.cpp
@@ -631,17 +631,17 @@ nsBoxFrame::GetMinWidth(nsIRenderingCont
   // GetMinSize returns border-box width, and we want to return content
   // width.  Since Reflow uses the reflow state's border and padding, we
   // actually just want to subtract what GetMinSize added, which is the
   // result of GetBorderAndPadding.
   nsMargin bp;
   GetBorderAndPadding(bp);
 
   result = minSize.width - bp.LeftRight();
-  result = PR_MAX(result, 0);
+  result = NS_MAX(result, 0);
 
   return result;
 }
 
 /* virtual */ nscoord
 nsBoxFrame::GetPrefWidth(nsIRenderingContext *aRenderingContext)
 {
   nscoord result;
@@ -653,17 +653,17 @@ nsBoxFrame::GetPrefWidth(nsIRenderingCon
   // GetPrefSize returns border-box width, and we want to return content
   // width.  Since Reflow uses the reflow state's border and padding, we
   // actually just want to subtract what GetPrefSize added, which is the
   // result of GetBorderAndPadding.
   nsMargin bp;
   GetBorderAndPadding(bp);
 
   result = prefSize.width - bp.LeftRight();
-  result = PR_MAX(result, 0);
+  result = NS_MAX(result, 0);
 
   return result;
 }
 
 NS_IMETHODIMP
 nsBoxFrame::Reflow(nsPresContext*          aPresContext,
                    nsHTMLReflowMetrics&     aDesiredSize,
                    const nsHTMLReflowState& aReflowState,
--- a/layout/xul/base/src/nsListItemFrame.cpp
+++ b/layout/xul/base/src/nsListItemFrame.cpp
@@ -60,17 +60,17 @@ nsListItemFrame::~nsListItemFrame()
 nsSize
 nsListItemFrame::GetPrefSize(nsBoxLayoutState& aState)
 {
   nsSize size = nsBoxFrame::GetPrefSize(aState);  
   DISPLAY_PREF_SIZE(this, size);
 
   // guarantee that our preferred height doesn't exceed the standard
   // listbox row height
-  size.height = PR_MAX(mRect.height, size.height);
+  size.height = NS_MAX(mRect.height, size.height);
   return size;
 }
 
 NS_IMETHODIMP
 nsListItemFrame::BuildDisplayListForChildren(nsDisplayListBuilder*   aBuilder,
                                              const nsRect&           aDirtyRect,
                                              const nsDisplayListSet& aLists)
 {
--- a/layout/xul/base/src/nsSliderFrame.cpp
+++ b/layout/xul/base/src/nsSliderFrame.cpp
@@ -400,25 +400,25 @@ nsSliderFrame::DoLayout(nsBoxLayoutState
   else
     thumbSize.width = clientRect.width;
 
   PRInt32 curPos = GetCurrentPosition(scrollbar);
   PRInt32 minPos = GetMinPosition(scrollbar);
   PRInt32 maxPos = GetMaxPosition(scrollbar);
   PRInt32 pageIncrement = GetPageIncrement(scrollbar);
 
-  maxPos = PR_MAX(minPos, maxPos);
-  curPos = PR_MAX(minPos, PR_MIN(curPos, maxPos));
+  maxPos = NS_MAX(minPos, maxPos);
+  curPos = NS_MAX(minPos, NS_MIN(curPos, maxPos));
 
   nscoord& availableLength = IsHorizontal() ? clientRect.width : clientRect.height;
   nscoord& thumbLength = IsHorizontal() ? thumbSize.width : thumbSize.height;
 
   if ((pageIncrement + maxPos - minPos) > 0 && thumbBox->GetFlex(aState) > 0) {
     float ratio = float(pageIncrement) / float(maxPos - minPos + pageIncrement);
-    thumbLength = PR_MAX(thumbLength, NSToCoordRound(availableLength * ratio));
+    thumbLength = NS_MAX(thumbLength, NSToCoordRound(availableLength * ratio));
   }
 
   // Round the thumb's length to device pixels.
   nsPresContext* presContext = PresContext();
   thumbLength = presContext->DevPixelsToAppUnits(
                   presContext->AppUnitsToDevPixels(thumbLength));
 
   // mRatio translates the thumb position in app units to the value.
@@ -682,18 +682,18 @@ nsSliderFrame::CurrentPositionChanged(ns
   // do nothing if the position did not change
   if (mCurPos == curPos)
       return NS_OK;
 
   // get our current min and max position from our content node
   PRInt32 minPos = GetMinPosition(scrollbar);
   PRInt32 maxPos = GetMaxPosition(scrollbar);
 
-  maxPos = PR_MAX(minPos, maxPos);
-  curPos = PR_MAX(minPos, PR_MIN(curPos, maxPos));
+  maxPos = NS_MAX(minPos, maxPos);
+  curPos = NS_MAX(minPos, NS_MIN(curPos, maxPos));
 
   // get the thumb's rect
   nsIFrame* thumbFrame = mFrames.FirstChild();
   if (!thumbFrame)
     return NS_OK; // The thumb may stream in asynchronously via XBL.
 
   nsRect thumbRect = thumbFrame->GetRect();
 
--- a/layout/xul/base/src/nsSprocketLayout.cpp
+++ b/layout/xul/base/src/nsSprocketLayout.cpp
@@ -358,18 +358,18 @@ nsSprocketLayout::Layout(nsIBox* aBox, n
         // opposite axis.
         if (!(frameState & NS_STATE_AUTO_STRETCH)) {
            nsSize prefSize = child->GetPrefSize(aState);
            nsSize minSize = child->GetMinSize(aState);
            nsSize maxSize = child->GetMaxSize(aState);
            prefSize = nsBox::BoundsCheck(minSize, prefSize, maxSize);
        
            AddMargin(child, prefSize);
-           width = PR_MIN(prefSize.width, originalClientRect.width);
-           height = PR_MIN(prefSize.height, originalClientRect.height);
+           width = NS_MIN(prefSize.width, originalClientRect.width);
+           height = NS_MIN(prefSize.height, originalClientRect.height);
         }
       }
 
       // Obtain the computed size along the axis of the box for this child from the computedBoxSize entry.  
       // We store the result in |width| for horizontal boxes and |height| for vertical boxes.
       if (frameState & NS_STATE_IS_HORIZONTAL)
         width = childComputedBoxSize->size;
       else
@@ -902,30 +902,30 @@ nsSprocketLayout::PopulateBoxSizes(nsIBo
 
   if (childCount > 0) {
     nscoord maxAllowedFlex = nscoord_MAX / childCount;
   
     if (NS_UNLIKELY(maxFlex > maxAllowedFlex)) {
       // clamp all the flexes
       currentBox = aBoxSizes;
       while (currentBox) {
-        currentBox->flex = PR_MIN(currentBox->flex, maxAllowedFlex);
+        currentBox->flex = NS_MIN(currentBox->flex, maxAllowedFlex);
         currentBox = currentBox->next;      
       }
     }
   }
 #ifdef DEBUG
   else {
     NS_ASSERTION(maxFlex == 0, "How did that happen?");
   }
 #endif
 
   // we specified all our children are equal size;
   if (frameState & NS_STATE_EQUAL_SIZE) {
-    smallestMaxWidth = PR_MAX(smallestMaxWidth, biggestMinWidth);
+    smallestMaxWidth = NS_MAX(smallestMaxWidth, biggestMinWidth);
     biggestPrefWidth = nsBox::BoundsCheck(biggestMinWidth, biggestPrefWidth, smallestMaxWidth);
 
     currentBox = aBoxSizes;
 
     while(currentBox)
     {
       if (!currentBox->collapsed) {
         currentBox->pref = biggestPrefWidth;
--- a/layout/xul/base/src/nsStackLayout.cpp
+++ b/layout/xul/base/src/nsStackLayout.cpp
@@ -301,34 +301,34 @@ nsStackLayout::Layout(nsIBox* aBox, nsBo
           // Margins on the child are also included in the edge offsets
           if (offsetSpecified) {
             if (offsetSpecified & SPECIFIED_LEFT) {
               childRect.x = clientRect.x + offset.left + margin.left;
               if (offsetSpecified & SPECIFIED_RIGHT) {
                 nsSize min = child->GetMinSize(aState);
                 nsSize max = child->GetMaxSize(aState);
                 nscoord width = clientRect.width - offset.LeftRight() - margin.LeftRight();
-                childRect.width = PR_MAX(min.width, PR_MIN(max.width, width));
+                childRect.width = NS_MAX(min.width, NS_MIN(max.width, width));
               }
               else {
                 childRect.width = child->GetPrefSize(aState).width;
               }
             }
             else if (offsetSpecified & SPECIFIED_RIGHT) {
               childRect.width = child->GetPrefSize(aState).width;
               childRect.x = clientRect.XMost() - offset.right - margin.right - childRect.width;
             }
 
             if (offsetSpecified & SPECIFIED_TOP) {
               childRect.y = clientRect.y + offset.top + margin.top;
               if (offsetSpecified & SPECIFIED_BOTTOM) {
                 nsSize min = child->GetMinSize(aState);
                 nsSize max = child->GetMaxSize(aState);
                 nscoord height = clientRect.height - offset.TopBottom() - margin.TopBottom();
-                childRect.height = PR_MAX(min.height, PR_MIN(max.height, height));
+                childRect.height = NS_MAX(min.height, NS_MIN(max.height, height));
               }
               else {
                 childRect.height = child->GetPrefSize(aState).height;
               }
             }
             else if (offsetSpecified & SPECIFIED_BOTTOM) {
               childRect.height = child->GetPrefSize(aState).height;
               childRect.y = clientRect.YMost() - offset.bottom - margin.bottom - childRect.height;
--- a/layout/xul/base/src/nsTextBoxFrame.cpp
+++ b/layout/xul/base/src/nsTextBoxFrame.cpp
@@ -566,17 +566,17 @@ nsTextBoxFrame::DrawText(nsIRenderingCon
 
 void nsTextBoxFrame::PaintOneShadow(gfxContext*      aCtx,
                                     const nsRect&    aTextRect,
                                     nsCSSShadowItem* aShadowDetails,
                                     const nscolor&   aForegroundColor,
                                     const nsRect&    aDirtyRect) {
   nsPoint shadowOffset(aShadowDetails->mXOffset,
                        aShadowDetails->mYOffset);
-  nscoord blurRadius = PR_MAX(aShadowDetails->mRadius, 0);
+  nscoord blurRadius = NS_MAX(aShadowDetails->mRadius, 0);
 
   nsRect shadowRect(aTextRect);
   shadowRect.MoveBy(shadowOffset);
 
   gfxRect shadowRectGFX(shadowRect.x, shadowRect.y, shadowRect.width, shadowRect.height);
   gfxRect dirtyRectGFX(aDirtyRect.x, aDirtyRect.y, aDirtyRect.width, aDirtyRect.height);
 
   nsContextBoxBlur contextBoxBlur;
--- a/layout/xul/base/src/tree/src/nsTreeBodyFrame.cpp
+++ b/layout/xul/base/src/tree/src/nsTreeBodyFrame.cpp
@@ -443,17 +443,17 @@ nsTreeBodyFrame::ReflowFinished()
   if (mView) {
     CalcInnerBox();
     ScrollParts parts = GetScrollParts();
     mHorzWidth = CalcHorzWidth(parts);
     if (!mHasFixedRowCount) {
       mPageLength = mInnerBox.height / mRowHeight;
     }
 
-    PRInt32 lastPageTopRow = PR_MAX(0, mRowCount - mPageLength);
+    PRInt32 lastPageTopRow = NS_MAX(0, mRowCount - mPageLength);
     if (mTopRowIndex > lastPageTopRow)
       ScrollToRowInternal(parts, lastPageTopRow);
 
     nsIContent *treeContent = GetBaseElement();
     if (treeContent->AttrValueIs(kNameSpaceID_None,
                                  nsGkAtoms::keepcurrentinview,
                                  nsGkAtoms::_true, eCaseMatters)) {
       // make sure that the current selected item is still
@@ -1916,17 +1916,17 @@ nsTreeBodyFrame::RowCountChanged(PRInt32
     if (mTopRowIndex > aIndex+count-1) {
       // No need to invalidate. The remove happened
       // completely above us (offscreen).
       mTopRowIndex -= count;
     }
     else if (mTopRowIndex >= aIndex) {
       // This is a full-blown invalidate.
       if (mTopRowIndex + mPageLength > mRowCount - 1) {
-        mTopRowIndex = PR_MAX(0, mRowCount - 1 - mPageLength);
+        mTopRowIndex = NS_MAX(0, mRowCount - 1 - mPageLength);
       }
       needsInvalidation = PR_TRUE;
     }
   }
 
   if (FullScrollbarsUpdate(needsInvalidation)) {
     MarkDirtyIfSelect();
   }
@@ -1948,17 +1948,17 @@ nsTreeBodyFrame::EndUpdateBatch()
 
   if (--mUpdateBatchNest == 0) {
     if (mView) {
       Invalidate();
       PRInt32 countBeforeUpdate = mRowCount;
       mView->GetRowCount(&mRowCount);
       if (countBeforeUpdate != mRowCount) {
         if (mTopRowIndex + mPageLength > mRowCount - 1) {
-          mTopRowIndex = PR_MAX(0, mRowCount - 1 - mPageLength);
+          mTopRowIndex = NS_MAX(0, mRowCount - 1 - mPageLength);
         }
         FullScrollbarsUpdate(PR_FALSE);
       }
     }
   }
 
   return NS_OK;
 }
@@ -4351,18 +4351,18 @@ nsTreeBodyFrame::OffsetForHorzScroll(nsR
   if (rect.XMost() <= mInnerBox.x)
     return PR_FALSE;
 
   // Scrolled out after
   if (rect.x > mInnerBox.XMost())
     return PR_FALSE;
 
   if (clip) {
-    nscoord leftEdge = PR_MAX(rect.x, mInnerBox.x);
-    nscoord rightEdge = PR_MIN(rect.XMost(), mInnerBox.XMost());
+    nscoord leftEdge = NS_MAX(rect.x, mInnerBox.x);
+    nscoord rightEdge = NS_MIN(rect.XMost(), mInnerBox.XMost());
     rect.x = leftEdge;
     rect.width = rightEdge - leftEdge;
 
     // Should have returned false above
     NS_ASSERTION(rect.width >= 0, "horz scroll code out of sync");
   }
 
   return PR_TRUE;