/* ============================================================ ConcreteQuantity Calculator V6 Shared calculation library for hub and all 12 standalone pages. New in V6: - Per-field unit selectors (ft, in, m, cm, mm) with live conversion - Thickness quick buttons (3/4/5/6 in or metric equivalents) - Full bag selector: 80/60/50/40 lb and 25/20 kg - Net and with-waste results shown side by side - Output in ft3, yd3, m3 plus weight (lb/kg) - URL parameter sharing (Share builds a restorable link) - Reset button on every panel - Sensible maximum validation with clear messages - aria-live results, keyboard accessible, inputmode="decimal" - Unit preference remembered in localStorage (try/catch) - 6 to 10 related calculator links per tool - Last verified date and cited sources - Rebar uses 3 in edge cover by default - LIVE visual preview: SVG diagram updates as the user types, showing entered values as dimension labels - Stairs uses the correct solid-step formula: tread x riser x n(n+1)/2 x width - British English throughout, no em or en dashes ============================================================ */ (function(){ "use strict"; /* ============ 1. SHARED CALCULATION LIBRARY ============ */ var CC = (function(){ /* Bag yields from manufacturer specifications (Quikrete) */ var BAG = { b80: 0.60, /* 80 lb bag yields about 0.60 ft3 */ b60: 0.45, /* 60 lb bag yields about 0.45 ft3 */ b50: 0.375, /* 50 lb bag yields about 0.375 ft3 */ b40: 0.30 /* 40 lb bag yields about 0.30 ft3 */ }; var BAGKG = { k25: 0.0117, /* 25 kg bag yields about 0.0117 m3 */ k20: 0.0094 /* 20 kg bag yields about 0.0094 m3 */ }; /* Concrete density: about 150 lb per ft3 (2400 kg per m3) */ var DENSITY_LB_FT3 = 150; var DENSITY_KG_M3 = 2400; function num(v){ v = parseFloat(v); return (isFinite(v) && v > 0) ? v : 0; } /* Volume functions. All take imperial inputs (ft for length, in for small). */ function slabFt3(l,w,d){ l=num(l);w=num(w);d=num(d); return l*w*(d/12); } function rectFt3(l,w,h){ l=num(l);w=num(w);h=num(h); return l*w*h; } function wallFt3(l,h,t){ l=num(l);h=num(h);t=num(t); return l*h*(t/12); } function curbFt3(l,w,h){ l=num(l);w=num(w);h=num(h); return l*(w/12)*(h/12); } function cylFt3(d,h){ d=num(d);h=num(h); var r=(d/12)/2; return Math.PI*r*r*h; } function circleSlabFt3(d,t){ d=num(d);t=num(t); var r=d/2; return Math.PI*r*r*(t/12); } /* Correct solid-step formula. The wedge formula (tread x riser x n x width) underestimates by a factor of 2/(n+1). */ function stairsFt3(s,tr,ri,w){ s=num(s);tr=num(tr);ri=num(ri);w=num(w); return (tr/12)*(ri/12)*(s*(s+1)/2)*w; } /* Epsilon guards true-integer float artifacts (e.g. 22.000000000004 -> 22) */ function ceilSafe(x){ return Math.ceil(x - 1e-9) || 0; } function bagsNeeded(ft3){ ft3=num(ft3); return { b80: ceilSafe(ft3/BAG.b80), b60: ceilSafe(ft3/BAG.b60), b50: ceilSafe(ft3/BAG.b50), b40: ceilSafe(ft3/BAG.b40) }; } function bagsNeededM3(m3){ m3=num(m3); return { k25: ceilSafe(m3/BAGKG.k25), k20: ceilSafe(m3/BAGKG.k20) }; } /* Site mix: dry-volume factor 1.54, ratio 1:2:4 by volume */ function mixForFt3(wet){ wet=num(wet); var dry=wet*1.54; return { dryFt3:dry, cementFt3:dry/7, sandFt3:dry*2/7, aggFt3:dry*4/7 }; } /* Rebar with edge cover. Default cover 3 in (75 mm). bars per direction = ceil((dimension - 2*cover) / spacing) + 1 bar length = dimension - 2*cover Test: 20x20 ft, 18 in spacing, 3 in cover = 546 ft */ function rebarForSlab(l,w,sp,coverIn){ l=num(l); w=num(w); sp=num(sp); coverIn = (coverIn===undefined) ? 3 : num(coverIn); if(!l||!w||!sp) return { totalLF:0, bars20:0, nW:0, nL:0, coverIn:coverIn }; var lIn = l*12, wIn = w*12; var aW = Math.ceil((wIn - 2*coverIn)/sp) + 1; var aL = Math.ceil((lIn - 2*coverIn)/sp) + 1; var barLenL = l - (2*coverIn)/12; /* ft */ var barLenW = w - (2*coverIn)/12; /* ft */ var lf = aW*barLenL + aL*barLenW; return { totalLF:lf, bars20:ceilSafe(lf/20), nW:aW, nL:aL, barLenL:barLenL, barLenW:barLenW, coverIn:coverIn }; } return { num:num, slabFt3:slabFt3, rectFt3:rectFt3, wallFt3:wallFt3, curbFt3:curbFt3, cylFt3:cylFt3, circleSlabFt3:circleSlabFt3, stairsFt3:stairsFt3, bagsNeeded:bagsNeeded, bagsNeededM3:bagsNeededM3, mixForFt3:mixForFt3, rebarForSlab:rebarForSlab, ceilSafe:ceilSafe, BAG:BAG, BAGKG:BAGKG, yd3: function(f){return f/27;}, m3: function(f){return f*0.0283168;}, ft3FromM3: function(m){return m*35.3147;}, weightLb: function(ft3){return ft3*DENSITY_LB_FT3;}, weightKg: function(m3){return m3*DENSITY_KG_M3;}, trucks: function(y){ y=num(y); return ceilSafe(y/10); }, trucksM3: function(m){ m=num(m); return ceilSafe(m/8); }, trucksM3_6: function(m){ m=num(m); return ceilSafe(m/6); }, coverageFt2: function(y,t){ y=num(y);t=num(t); return t ? (y*27)/(t/12) : 0; }, coverageM2: function(m,t){ m=num(m);t=num(t); return t ? m/(t/100) : 0; } }; })(); /* ============ 2. UNIT SYSTEM ============ */ var UNITS = 'imp'; /* 'imp' | 'met' */ var CUR = '$'; /* '$' | '£' | '€' */ /* Unit preference memory (localStorage wrapped in try/catch) */ function saveUnitPref(){ try{ localStorage.setItem('cc_units', UNITS); localStorage.setItem('cc_cur', CUR); }catch(e){} } function loadUnitPref(){ try{ var u = localStorage.getItem('cc_units'); var c = localStorage.getItem('cc_cur'); if(u==='imp'||u==='met') UNITS = u; if(c==='$'||c==='£'||c==='€') CUR = c; }catch(e){} } loadUnitPref(); /* Per-field unit conversion. Base unit for 'len' kind is feet, for 'sm' kind is inches. */ var FIELD_UNITS = ['ft','in','m','cm','mm']; var TO_FT = { ft:1, 'in':1/12, m:3.28084, cm:0.0328084, mm:0.00328084 }; var TO_IN = { 'in':1, ft:12, m:39.3701, cm:0.393701, mm:0.0393701 }; function convertVal(v, fromU, toU, kind){ v = parseFloat(v); if(!isFinite(v)) return ''; var basePer, toBase; if(kind==='len'){ basePer = TO_FT; } else { basePer = TO_IN; } var inBase = v * basePer[fromU]; var out = inBase / basePer[toU]; return String(Math.round(out*10000)/10000); } /* ============ 3. STYLES ============ */ (function(){ if(document.getElementById('ccV6style')) return; var s=document.createElement('style'); s.id='ccV6style'; s.textContent = '.cc-working{background:#f8fafc;border:1px dashed #94a3b8;border-radius:10px;' +'padding:10px 14px;margin:12px 0 4px;font-size:13.5px;line-height:1.65;color:#334155;overflow-wrap:anywhere}' +'.cc-working b{color:#1e40af}' +'.cc-error{background:#fef2f2;border:1px solid #fca5a5;color:#b91c1c;border-radius:10px;' +'padding:10px 14px;margin:12px 0 4px;font-size:14px;line-height:1.5}' +'.cc-wasterow{display:flex;gap:8px}.cc-wasterow .wasteSel{flex:1 1 auto;min-width:0}' +'.cc-wasterow .wasteCustom{flex:0 0 104px;width:104px}' +'.cc-netwaste{display:grid;grid-template-columns:1fr 1fr;gap:12px;margin:12px 0}' +'@media(max-width:600px){.cc-netwaste{grid-template-columns:1fr}}' +'.cc-nwcol{background:#f8fafc;border:1px solid #e2e8f0;border-radius:10px;padding:12px 14px}' +'.cc-nwcol h4{margin:0 0 8px;font-size:14px;color:#1e40af}' +'.cc-nwcol .cc-cards{margin:8px 0}' +'.cc-unitrow{display:flex;gap:6px;align-items:center}' +'.cc-unitrow input{flex:1 1 auto;min-width:0}' +'.cc-unitrow select{flex:0 0 76px;width:76px}' +'.cc-quickbtns{display:flex;gap:6px;margin-top:6px;flex-wrap:wrap}' +'.cc-quickbtns button{font-size:12px;padding:4px 10px;border:1px solid #cbd5e1;background:#fff;' +'border-radius:6px;cursor:pointer;color:#334155}' +'.cc-quickbtns button:hover{background:#f1f5f9;border-color:#94a3b8}' +'.cc-quickbtns button.on{background:#dbeafe;border-color:#2563eb;color:#1e40af;font-weight:600}' +'.cc-bagrow{display:flex;gap:6px;flex-wrap:wrap;margin:8px 0}' +'.cc-bagrow button{font-size:13px;padding:6px 12px;border:1px solid #cbd5e1;background:#fff;' +'border-radius:8px;cursor:pointer;color:#334155}' +'.cc-bagrow button.on{background:#1e40af;border-color:#1e40af;color:#fff;font-weight:600}' +'.cc-related{margin:20px 0 8px;padding:14px;background:#f8fafc;border-radius:10px}' +'.cc-related h4{margin:0 0 10px;font-size:14px;color:#0f172a}' +'.cc-related ul{margin:0;padding:0;list-style:none;display:grid;grid-template-columns:1fr 1fr;gap:6px}' +'@media(max-width:600px){.cc-related ul{grid-template-columns:1fr}}' +'.cc-related a{color:#1e40af;text-decoration:none;font-size:13.5px}' +'.cc-related a:hover{text-decoration:underline}' +'.cc-verified{margin:16px 0 4px;font-size:12.5px;color:#64748b;border-top:1px solid #e2e8f0;padding-top:10px}' +'.cc-preview-note{font-size:12px;color:#64748b;margin-top:6px;text-align:center}' +'.cc-dimval{font-family:Georgia,serif;font-style:italic;fill:#0f766e;font-size:13px;font-weight:bold}' +'.cc-reset{background:#fff;border:1px solid #cbd5e1;border-radius:8px;padding:8px 16px;' +'font-size:13px;cursor:pointer;color:#475569;margin-top:10px}' +'.cc-reset:hover{background:#f1f5f9}' +'#uCur{border:1px solid #e2e8f0;background:#ffffff;border-radius:10px;padding:9px 14px;' +'font-size:14px;font-weight:600;cursor:pointer;color:#0f172a;margin-left:6px;white-space:nowrap}' +'#uCur:hover{background:#f1f5f9}'; document.head.appendChild(s); })(); /* ============ 4. LIVE SVG PREVIEWS ============ Each diagram function accepts a dims object {fieldId: {val, unit}} and renders live value labels. Shapes scale proportionally. */ var SERIF = 'font-style="italic" font-family="Georgia,serif" font-size="16" fill="#1e40af"'; function dimLabel(txt, x, y, anchor){ return ''+escapeHtml(txt)+''; } function escapeHtml(s){ return String(s).replace(/&/g,'&').replace(//g,'>').replace(/"/g,'"'); } /* Scale a box polygon proportionally. Returns scaled points string. */ function scaleBox(l, w, t){ /* Normalise to fit viewBox 150x108. Use log scale to avoid extremes. */ l = Math.max(l, 0.01); w = Math.max(w, 0.01); t = Math.max(t, 0.01); var maxDim = Math.max(l, w, t); var base = 60 / maxDim; var sl = Math.max(18, Math.min(80, l*base)); var sw = Math.max(10, Math.min(46, w*base)); var st = Math.max(8, Math.min(40, t*base)); return { sl:sl, sw:sw, st:st }; } function boxSVG(live){ live = live || {}; var L = live.l ? live.l.val+' '+live.l.unit : 'l'; var W = live.w ? live.w.val+' '+live.w.unit : 'w'; var T = live.d ? live.d.val+' '+live.d.unit : (live.t ? live.t.val+' '+live.t.unit : (live.h ? live.h.val+' '+live.h.unit : 't')); return '' +'' +'' +'' +'' + dimLabel(L, 75, 104) + dimLabel(W, 143, 54) + dimLabel(T, 92, 13) +''; } function tallBoxSVG(live){ live = live || {}; var L = live.l ? live.l.val+' '+live.l.unit : 'l'; var H = live.h ? live.h.val+' '+live.h.unit : 'h'; var T = live.t ? live.t.val+' '+live.t.unit : 't'; return '' +'' +'' +'' +'' + dimLabel(L, 81, 104) + dimLabel(H, 130, 56) + dimLabel(T, 90, 8) +''; } function cylSVG(live){ live = live || {}; var D = live.d ? live.d.val+' '+live.d.unit : 'd'; var H = live.h ? live.h.val+' '+live.h.unit : 'h'; return '' +'' +'' +'' +'' +'' + dimLabel(D, 68, 18) + dimLabel(H, 124, 60) +''; } function discSVG(live){ live = live || {}; var D = live.d ? live.d.val+' '+live.d.unit : 'd'; var T = live.t ? live.t.val+' '+live.t.unit : 't'; return '' +'' +'' +'' +'' +'' + dimLabel(D, 68, 30) + dimLabel(T, 128, 58) +''; } function stairsSVG(live){ live = live || {}; var TR = live.tr ? live.tr.val+' '+live.tr.unit : 'tread'; var RI = live.ri ? live.ri.val+' '+live.ri.unit : 'riser'; var S = live.s ? live.s.val+' steps' : ''; var W = live.w ? live.w.val+' '+live.w.unit+' wide' : ''; var sub = (S || W) ? ' ('+[S,W].filter(Boolean).join(', ')+')' : ''; return '' +'' + dimLabel(TR, 102, 14) + dimLabel(RI, 130, 60) + (sub ? dimLabel(sub, 66, 104) : '') +''; } function bagSVG(live){ var lbl = '80 lb'; if(live && live.bag) lbl = live.bag; return '' +'' +'' +''+escapeHtml(lbl)+''; } function mixSVG(){ return '' +'' +'' +'' +'cement' +'sand' +'aggregate' +'1 : 2 : 4'; } function rebarSVG(live){ live = live || {}; var S = live.s ? live.s.val+' '+live.s.unit : 's'; return '' +'' +'' +'' + dimLabel('spacing: '+S, 72, 104) +''; } function costSVG(){ return '' +'' +''+CUR+'' +'' +'vol'; } /* ---- inline stroke icons ---- */ var ICONS = { slab: '', footing: '', wall: '', column: '', posthole: '', circle: '', curb: '', stairs: '', bags: '', mix: '', rebar: '', cost: '', cube: '', copy: '', print: '', share: '', reset: '' }; /* ============ 5. RELATED CALCULATORS ============ */ var ALL_TOOLS = [ { id:'slab', tab:'Slab', url:'/concrete-slab-calculator/' }, { id:'footing', tab:'Footing', url:'/concrete-footing-calculator/' }, { id:'wall', tab:'Wall', url:'/concrete-wall-calculator/' }, { id:'column', tab:'Column', url:'/concrete-column-calculator/' }, { id:'posthole', tab:'Post Holes', url:'/post-hole-concrete-calculator/' }, { id:'circle', tab:'Circle Slab', url:'/circular-slab-calculator/' }, { id:'curb', tab:'Curb', url:'/concrete-curb-calculator/' }, { id:'stairs', tab:'Stairs', url:'/stairs-concrete-calculator/' }, { id:'bags', tab:'Bags', url:'/concrete-bags-calculator/' }, { id:'mix', tab:'Mix Ratio', url:'/concrete-mix-ratio-calculator/' }, { id:'rebar', tab:'Rebar', url:'/rebar-calculator/' }, { id:'cost', tab:'Cost', url:'/concrete-cost-calculator/' } ]; function relatedHTML(currentId){ var others = ALL_TOOLS.filter(function(t){ return t.id!==currentId; }); /* Pick 8 most relevant: prefer same-category neighbours, then fill */ var pick = others.slice(0, 8); var h = ''; return h; } function verifiedHTML(){ return '
Last verified: 10 Oct 2026. ' + 'Bag yields per manufacturer specifications (Quikrete). ' + 'Stairs formula verified against solid-step geometry. ' + 'Concrete density taken as 150 lb/ft3 (2,400 kg/m3).
'; } /* ============ 6. MODE DEFINITIONS ============ kind: 'len' (length), 'sm' (small: thickness/spacing), 'num' (plain number), 'yd3' (volume), 'usd' (price) */ var MODES = [ { id:'slab', tab:'Slab', icon:'slab', title:'Concrete Slab Calculator', formula:'Volume = Length x Width x Thickness / 27 (cubic yards)', diagram: function(live){ return boxSVG(live); }, fields:[ {id:'l',label:'Length',kind:'len',ph:'10',defUnit:'ft'}, {id:'w',label:'Width',kind:'len',ph:'10',defUnit:'ft'}, {id:'d',label:'Thickness',kind:'sm',ph:'4',defUnit:'in',quick:[3,4,5,6]} ], toImp: function(vals, units){ return { l: toFt(vals.l, units.l), w: toFt(vals.w, units.w), d: toIn(vals.d, units.d) }; }, vol: function(v){ return CC.slabFt3(v.l, v.w, v.d); }, work: function(v, raw){ var L=+raw.l||0, W=+raw.w||0, T=+raw.d||0; var f=v.l*v.w*(v.d/12); return L+' x '+W+' x ('+T+' / 12) = '+fmt(f,1)+' ft3, then / 27 = '+fmt(f/27)+' yd3'; } }, { id:'footing', tab:'Footing', icon:'footing', title:'Concrete Footing Calculator', formula:'Volume = Length x Width x Depth / 27 (cubic yards)', diagram: function(live){ return boxSVG(live); }, fields:[ {id:'l',label:'Length',kind:'len',ph:'20',defUnit:'ft'}, {id:'w',label:'Width',kind:'len',ph:'2',defUnit:'ft'}, {id:'d',label:'Depth',kind:'sm',ph:'12',defUnit:'in'} ], toImp: function(vals, units){ return { l: toFt(vals.l, units.l), w: toFt(vals.w, units.w), d: toIn(vals.d, units.d) }; }, vol: function(v){ return CC.rectFt3(v.l, v.w, v.d/12); }, work: function(v, raw){ var L=+raw.l||0, W=+raw.w||0, D=+raw.d||0; var f=v.l*v.w*(v.d/12); return L+' x '+W+' x ('+D+' / 12) = '+fmt(f,1)+' ft3, then / 27 = '+fmt(f/27)+' yd3'; } }, { id:'wall', tab:'Wall', icon:'wall', title:'Concrete Wall Calculator', formula:'Volume = Length x Height x Thickness / 27 (cubic yards)', diagram: function(live){ return tallBoxSVG(live); }, fields:[ {id:'l',label:'Length',kind:'len',ph:'20',defUnit:'ft'}, {id:'h',label:'Height',kind:'len',ph:'8',defUnit:'ft'}, {id:'t',label:'Thickness',kind:'sm',ph:'8',defUnit:'in',quick:[6,8,10,12]} ], toImp: function(vals, units){ return { l: toFt(vals.l, units.l), h: toFt(vals.h, units.h), t: toIn(vals.t, units.t) }; }, vol: function(v){ return CC.wallFt3(v.l, v.h, v.t); }, work: function(v, raw){ var L=+raw.l||0, H=+raw.h||0, T=+raw.t||0; var f=v.l*v.h*(v.t/12); return L+' x '+H+' x ('+T+' / 12) = '+fmt(f,1)+' ft3, then / 27 = '+fmt(f/27)+' yd3'; } }, { id:'column', tab:'Column', icon:'column', title:'Concrete Column / Pier Calculator', formula:'Volume = pi x r squared x Height (cylinder)', diagram: function(live){ return cylSVG(live); }, fields:[ {id:'d',label:'Diameter',kind:'sm',ph:'12',defUnit:'in'}, {id:'h',label:'Height',kind:'len',ph:'4',defUnit:'ft'}, {id:'n',label:'How many',kind:'num',ph:'1'} ], toImp: function(vals, units){ return { d: toIn(vals.d, units.d), h: toFt(vals.h, units.h), n: CC.num(vals.n)||1 }; }, vol: function(v){ return CC.cylFt3(v.d, v.h)*v.n; }, work: function(v, raw){ var D=+raw.d||0, H=+raw.h||0, N=Math.round(+raw.n)||1; var r=(v.d/12)/2, f=Math.PI*r*r*v.h*N; return 'pi x '+fmt(r,3)+' squared x '+H+' x '+N+' = '+fmt(f,2)+' ft3, then / 27 = '+fmt(f/27)+' yd3'; } }, { id:'posthole', tab:'Post Holes', icon:'posthole', title:'Post Hole Concrete Calculator', formula:'Each hole = pi x r squared x Depth. Great for fences and decks.', diagram: function(live){ return cylSVG(live); }, fields:[ {id:'d',label:'Hole diameter',kind:'sm',ph:'10',defUnit:'in'}, {id:'h',label:'Hole depth',kind:'sm',ph:'36',defUnit:'in'}, {id:'n',label:'Number of holes',kind:'num',ph:'8'} ], toImp: function(vals, units){ return { d: toIn(vals.d, units.d), h: toIn(vals.h, units.h), n: CC.num(vals.n)||1 }; }, vol: function(v){ return CC.cylFt3(v.d, v.h/12)*v.n; }, work: function(v, raw){ var D=+raw.d||0, H=+raw.h||0, N=Math.round(+raw.n)||1; var r=(v.d/12)/2, f=Math.PI*r*r*(v.h/12)*N; return 'pi x '+fmt(r,3)+' squared x ('+H+' / 12) x '+N+' holes = '+fmt(f,2)+' ft3, then / 27 = '+fmt(f/27)+' yd3'; } }, { id:'circle', tab:'Circle Slab', icon:'circle', title:'Circular Slab Calculator', formula:'Volume = pi x r squared x Thickness / 27 (cubic yards)', diagram: function(live){ return discSVG(live); }, fields:[ {id:'d',label:'Diameter',kind:'len',ph:'10',defUnit:'ft'}, {id:'t',label:'Thickness',kind:'sm',ph:'4',defUnit:'in',quick:[3,4,5,6]} ], toImp: function(vals, units){ return { d: toFt(vals.d, units.d), t: toIn(vals.t, units.t) }; }, vol: function(v){ return CC.circleSlabFt3(v.d, v.t); }, work: function(v, raw){ var D=+raw.d||0, T=+raw.t||0; var r=v.d/2, f=Math.PI*r*r*(v.t/12); return 'pi x '+fmt(r)+' squared x ('+T+' / 12) = '+fmt(f,1)+' ft3, then / 27 = '+fmt(f/27)+' yd3'; } }, { id:'curb', tab:'Curb', icon:'curb', title:'Concrete Curb Calculator', formula:'Volume = Length x Width x Height / 27 (cubic yards)', diagram: function(live){ return boxSVG(live); }, fields:[ {id:'l',label:'Length',kind:'len',ph:'100',defUnit:'ft'}, {id:'w',label:'Width',kind:'sm',ph:'6',defUnit:'in'}, {id:'h',label:'Height',kind:'sm',ph:'6',defUnit:'in'} ], toImp: function(vals, units){ return { l: toFt(vals.l, units.l), w: toIn(vals.w, units.w), h: toIn(vals.h, units.h) }; }, vol: function(v){ return CC.curbFt3(v.l, v.w, v.h); }, work: function(v, raw){ var L=+raw.l||0, W=+raw.w||0, H=+raw.h||0; var f=v.l*(v.w/12)*(v.h/12); return L+' x ('+W+' / 12) x ('+H+' / 12) = '+fmt(f,1)+' ft3, then / 27 = '+fmt(f/27)+' yd3'; } }, { id:'stairs', tab:'Stairs', icon:'stairs', title:'Concrete Stairs Calculator (Solid Steps)', formula:'Solid steps = tread x riser x n(n+1)/2 x width', diagram: function(live){ return stairsSVG(live); }, fields:[ {id:'s',label:'Steps',kind:'num',ph:'5'}, {id:'tr',label:'Tread depth',kind:'sm',ph:'11',defUnit:'in'}, {id:'ri',label:'Riser height',kind:'sm',ph:'7',defUnit:'in'}, {id:'w',label:'Width',kind:'len',ph:'4',defUnit:'ft'} ], toImp: function(vals, units){ return { s: CC.num(vals.s), tr: toIn(vals.tr, units.tr), ri: toIn(vals.ri, units.ri), w: toFt(vals.w, units.w) }; }, vol: function(v){ return CC.stairsFt3(v.s, v.tr, v.ri, v.w); }, work: function(v, raw){ var S=Math.round(+raw.s)||0; var f=(v.tr/12)*(v.ri/12)*(S*(S+1)/2)*v.w; return 'Tread x riser x '+S+'x'+(S+1)+'/2 x width = '+fmt(f,1)+' ft3, then / 27 = '+fmt(f/27)+' yd3 (solid steps)'; } }, { id:'bags', tab:'Bags', icon:'bags', title:'How Many Bags of Concrete?', formula:'Bags = volume / bag yield (80 lb = 0.60 ft3, 60 lb = 0.45 ft3, 50 lb = 0.375 ft3, 40 lb = 0.30 ft3)', diagram: function(live){ return bagSVG(live); }, custom:'bags', empty:'Enter the volume above.', fields:[ {id:'y',label:'Concrete needed',kind:'yd3',ph:'1.25',defUnit:'yd3'} ] }, { id:'mix', tab:'Mix Ratio', icon:'mix', title:'On-Site Mix Calculator (1:2:4)', formula:'For site-mixed concrete: 1 part cement : 2 sand : 4 aggregate (by volume). Dry-volume factor 1.54.', diagram: function(){ return mixSVG(); }, custom:'mix', empty:'Enter the volume above.', fields:[ {id:'y',label:'Concrete needed',kind:'yd3',ph:'1',defUnit:'yd3'} ] }, { id:'rebar', tab:'Rebar', icon:'rebar', title:'Rebar Calculator for Slabs', formula:'Bars each way = ceil((dimension - 2 x cover) / spacing) + 1, with 3 in edge cover. Bar length = dimension - 2 x cover. Material estimate only, not structural design. Standard bar length 20 ft.', diagram: function(live){ return rebarSVG(live); }, custom:'rebar', empty:'Enter slab size and spacing above.', fields:[ {id:'l',label:'Slab length',kind:'len',ph:'20',defUnit:'ft'}, {id:'w',label:'Slab width',kind:'len',ph:'20',defUnit:'ft'}, {id:'s',label:'Bar spacing',kind:'sm',ph:'18',defUnit:'in'}, {id:'c',label:'Edge cover',kind:'sm',ph:'3',defUnit:'in'} ] }, { id:'cost', tab:'Cost', icon:'cost', title:'Concrete Cost Estimator', formula:'Cost = volume x price per unit.', diagram: function(){ return costSVG(); }, custom:'cost', empty:'Enter volume and price above.', fields:[ {id:'y',label:'Concrete needed',kind:'yd3',ph:'5',defUnit:'yd3'}, {id:'p',label:'Price per unit',kind:'usd',ph:'150'} ] } ]; /* Unit helpers for toImp */ function toFt(v, u){ v = parseFloat(v); if(!isFinite(v)) return 0; u = u || 'ft'; return v * (TO_FT[u] || 1); } function toIn(v, u){ v = parseFloat(v); if(!isFinite(v)) return 0; u = u || 'in'; return v * (TO_IN[u] || 1); } /* ============ 7. RENDERING ============ */ function fmt(v, d){ if(!isFinite(v)) return '0'; var s = v.toFixed(d===undefined?2:d); if(s.indexOf('.')>=0) s = s.replace(/\.?0+$/,''); return s; } /* Per-field unit selector HTML */ function unitSelectHTML(fieldId, kind, defUnit){ var opts = ''; var list = (kind==='len'||kind==='sm') ? FIELD_UNITS : (kind==='yd3' ? ['yd3','m3','ft3'] : []); if(!list.length) return ''; list.forEach(function(u){ var sel = (u===defUnit) ? ' selected' : ''; opts += ''; }); return ''; } function fieldHTML(f){ var isDim = (f.kind==='len'||f.kind==='sm'||f.kind==='yd3'); var sel = isDim ? unitSelectHTML(f.id, f.kind, f.defUnit||'ft') : ''; var suffix = ''; if(f.kind==='usd') suffix = ''+CUR+''; var quick = ''; if(f.quick && f.quick.length){ quick = '
'; f.quick.forEach(function(q){ quick += ''; }); quick += '
'; } return '
'+ '
'+ (sel || suffix)+'
'+quick+'
'; } function volExtrasHTML(){ return '
'+ '
'+ '
'+ '
'+ '
'+ ''+CUR+'
'; } /* Bag selector: 80/60/50/40 lb and 25/20 kg */ var BAG_OPTIONS = [ { id:'b80', label:'80 lb', kind:'imp' }, { id:'b60', label:'60 lb', kind:'imp' }, { id:'b50', label:'50 lb', kind:'imp' }, { id:'b40', label:'40 lb', kind:'imp' }, { id:'k25', label:'25 kg', kind:'met' }, { id:'k20', label:'20 kg', kind:'met' } ]; var selectedBag = 'b80'; function bagSelectorHTML(){ var h = '
'; BAG_OPTIONS.forEach(function(b){ var on = (b.id===selectedBag) ? ' on' : ''; h += ''; }); h += '
'; return h; } function bagLabel(id){ var m = { b80:'80 lb', b60:'60 lb', b50:'50 lb', b40:'40 lb', k25:'25 kg', k20:'20 kg' }; return m[id] || '80 lb'; } function bagCount(bags, id){ return bags[id] || 0; } /* Net and with-waste side by side */ function netWasteHTML(ft3, waste, price, mode, panel, vals, imp){ var met = false; /* V6 always computes in imperial, converts for display */ var w = 1 + waste/100; var netFt3 = ft3, wasteFt3 = ft3 * w; var netYd3 = netFt3/27, wasteYd3 = wasteFt3/27; var netM3 = netFt3*0.0283168, wasteM3 = wasteFt3*0.0283168; var netLb = CC.weightLb(netFt3), wasteLb = CC.weightLb(wasteFt3); var netKg = CC.weightKg(netM3), wasteKg = CC.weightKg(wasteM3); var bagsNet = CC.bagsNeeded(netFt3), bagsWaste = CC.bagsNeeded(wasteFt3); var bagsNetM = CC.bagsNeededM3(netM3), bagsWasteM = CC.bagsNeededM3(wasteM3); var selCountNet = bagCount(bagsNet, selectedBag) || bagCount(bagsNetM, selectedBag); var selCountWaste = bagCount(bagsWaste, selectedBag) || bagCount(bagsWasteM, selectedBag); /* Fallback: if selected bag is metric but we want imperial display, use b80 */ if(!selCountNet){ selCountNet = (selectedBag.charAt(0)==='k') ? bagCount(bagsNetM, selectedBag) : bagCount(bagsNet, selectedBag); } if(!selCountWaste){ selCountWaste = (selectedBag.charAt(0)==='k') ? bagCount(bagsWasteM, selectedBag) : bagCount(bagsWaste, selectedBag); } var loadsNet = CC.trucks(netYd3), loadsWaste = CC.trucks(wasteYd3); var costNet = price>0 ? netYd3*price : 0; var costWaste = price>0 ? wasteYd3*price : 0; function colHTML(title, yd3v, m3v, ft3v, lbv, kgv, bagN, loads, cost){ var h = '

'+title+'

' +'
'+ICONS.cube+''+fmt(yd3v)+'Cubic Yards
' +'
'+ICONS.cube+''+fmt(m3v)+'Cubic Metres
' +'
'+ICONS.bags+''+bagN+''+bagLabel(selectedBag)+' Bags
' +'
' +'
'+fmt(ft3v,1)+' ft3' +''+fmt(lbv,0)+' lb ('+fmt(kgv,0)+' kg)' +''+loads+' truck load'+(loads===1?'':'s')+''; if(cost>0) h += ''+CUR+fmt(cost)+' material cost'; h += '
'; return h; } var h = '
'; h += '

Results

'; h += bagSelectorHTML(); h += '
'; h += colHTML('Net volume', netYd3, netM3, netFt3, netLb, netKg, selCountNet, loadsNet, costNet); h += colHTML(waste>0 ? 'With '+waste+'% waste' : 'With waste', wasteYd3, wasteM3, wasteFt3, wasteLb, wasteKg, selCountWaste, loadsWaste, costWaste); h += '
'; /* All bag sizes */ h += '
'+bagsWaste.b80+' x 80 lb' +''+bagsWaste.b60+' x 60 lb' +''+bagsWaste.b50+' x 50 lb' +''+bagsWaste.b40+' x 40 lb' +''+bagsWasteM.k25+' x 25 kg' +''+bagsWasteM.k20+' x 20 kg
'; h += '
Working: '+mode.work(imp, vals) +(waste>0 ? ' then x '+fmt(w,'3')+' for '+waste+'% waste' : '')+'
'; h += actionsHTML(mode.id); h += '
'; panel._summary = mode.title+': net '+fmt(netYd3)+' yd3 ('+fmt(netFt3,1)+' ft3, '+fmt(netM3)+' m3), ' +'with '+waste+'% waste '+fmt(wasteYd3)+' yd3. Bags ('+bagLabel(selectedBag)+'): '+selCountWaste+'. ' +'via concretequantity.com/concrete-calculator/#'+mode.id; return h; } function actionsHTML(modeId){ return '
' +'' +'' +'' +'
'; } /* URL parameter sharing: encode field values + units into URL */ function buildShareURL(mode, panel){ var params = new URLSearchParams(); params.set('tool', mode.id); panel.querySelectorAll('input[data-fid]').forEach(function(inp){ var fid = inp.getAttribute('data-fid'); if(inp.value) params.set(fid, inp.value); }); panel.querySelectorAll('select.cc-funit').forEach(function(sel){ params.set(sel.getAttribute('data-funit')+'_u', sel.value); }); var wsel = panel.querySelector('.wasteSel'); if(wsel) params.set('waste', wsel.value); var base = window.location.origin + window.location.pathname; return base + '#' + mode.id + '?' + params.toString(); } function restoreFromURL(mode, panel){ /* Parse hash like #slab?l=10&w=10&d=4&waste=10 */ var hash = window.location.hash || ''; var qIdx = hash.indexOf('?'); if(qIdx<0) return false; var toolId = hash.substring(1, qIdx); if(toolId!==mode.id) return false; var params = new URLSearchParams(hash.substring(qIdx+1)); var found = false; panel.querySelectorAll('input[data-fid]').forEach(function(inp){ var fid = inp.getAttribute('data-fid'); if(params.has(fid)){ inp.value = params.get(fid); found = true; } }); panel.querySelectorAll('select.cc-funit').forEach(function(sel){ var key = sel.getAttribute('data-funit')+'_u'; if(params.has(key)){ sel.value = params.get(key); found = true; } }); var wsel = panel.querySelector('.wasteSel'); if(wsel && params.has('waste')){ wsel.value = params.get('waste'); found = true; } return found; } function doAction(act, btn, panel, mode){ var txt = panel._summary || 'Concrete Calculator: concretequantity.com/concrete-calculator/'; if(act==='print'){ window.print(); return; } if(act==='reset'){ panel.querySelectorAll('input[data-fid], input.wasteCustom, input.priceInp').forEach(function(i){ i.value=''; }); var wsel = panel.querySelector('.wasteSel'); if(wsel) wsel.value='10'; calcPanel(mode, panel); updatePreview(mode, panel); return; } if(act==='share'){ var url = buildShareURL(mode, panel); txt = url; /* Try Web Share API first, fall back to clipboard */ if(navigator.share){ navigator.share({title:'Concrete Calculator', text:panel._summary||'', url:url}).catch(function(){ copyText(url, btn); }); return; } copyText(url, btn); return; } /* copy */ copyText(txt, btn); } function copyText(txt, btn){ var done = function(ok){ var sp = btn.querySelector('span'), old = sp.textContent; btn.classList.add('ok'); sp.textContent = ok ? 'Copied' : 'Copy failed'; setTimeout(function(){ btn.classList.remove('ok'); sp.textContent = old; }, 1600); }; if(navigator.clipboard && navigator.clipboard.writeText){ navigator.clipboard.writeText(txt).then(function(){ done(true); }, function(){ done(false); }); } else { var ta = document.createElement('textarea'); ta.value = txt; ta.style.position='fixed'; ta.style.opacity='0'; document.body.appendChild(ta); ta.select(); try{ done(document.execCommand('copy')); }catch(e){ done(false); } document.body.removeChild(ta); } } /* ============ 8. LIVE PREVIEW UPDATE ============ */ function getLiveDims(mode, panel){ var live = {}; panel.querySelectorAll('input[data-fid]').forEach(function(inp){ var fid = inp.getAttribute('data-fid'); var sel = panel.querySelector('select.cc-funit[data-funit="'+fid+'"]'); var unit = sel ? sel.value : ''; if(inp.value) live[fid] = { val: inp.value, unit: unit }; }); if(mode.id==='bags' && selectedBag) live.bag = bagLabel(selectedBag); return live; } function updatePreview(mode, panel){ var wrap = panel.querySelector('.cc-diagram'); if(!wrap || !mode.diagram) return; var live = getLiveDims(mode, panel); wrap.innerHTML = mode.diagram(live) + '
Live preview updates as you type
'; } /* ============ 9. VALIDATION ============ */ /* Sensible maximums in imperial base units */ var VLIMIT = { len: 5000, /* ft */ sm: 1200, /* in */ num: 100000, yd3: 100000, usd: 1000000 }; var VLABEL = { len:'ft', sm:'in', num:'', yd3:'yd3', usd:'' }; function validateFields(mode, vals, units){ var empty = '
'+(mode.empty||'Enter your measurements above to see results instantly.')+'
'; for(var i=0;i]*>/g,''); if(raw===''||raw==null) return empty; var x=parseFloat(raw); if(!isFinite(x)) return ''; if(x<0) return ''; if(x===0) return ''; /* Convert to imperial base for limit check */ var u = units[f.id] || f.defUnit || 'ft'; var imp = x; if(f.kind==='len') imp = x * (TO_FT[u]||1); else if(f.kind==='sm') imp = x * (TO_IN[u]||1); else if(f.kind==='yd3'){ if(u==='m3') imp = x*1.30795; else if(u==='ft3') imp = x/27; } var lim = VLIMIT[f.kind]||100000; if(imp > lim) return ''; } return null; } /* ============ 10. PANEL CALCULATION ============ */ function calcPanel(mode, panel){ var vals = {}, units = {}; panel.querySelectorAll('input[data-fid]').forEach(function(inp){ var fid = inp.getAttribute('data-fid'); vals[fid] = inp.value.trim(); var sel = panel.querySelector('select.cc-funit[data-funit="'+fid+'"]'); units[fid] = sel ? sel.value : null; }); var box = panel.querySelector('.cc-out'); var verr = validateFields(mode, vals, units); if(verr){ box.innerHTML = verr; panel._summary=''; return; } var h = ''; if(mode.custom==='bags'){ h = calcBags(mode, panel, vals, units); } else if(mode.custom==='mix'){ h = calcMix(mode, panel, vals, units); } else if(mode.custom==='rebar'){ h = calcRebar(mode, panel, vals, units); } else if(mode.custom==='cost'){ h = calcCost(mode, panel, vals, units); } else { var imp = mode.toImp(vals, units); var vft3 = mode.vol(imp); var wsel = panel.querySelector('.wasteSel'), wcus = panel.querySelector('.wasteCustom'); var wv = wcus ? parseFloat(wcus.value) : NaN; var waste = (isFinite(wv)&&wv>0) ? Math.min(wv,100) : (wsel ? (parseFloat(wsel.value)||0) : 0); var praw = panel.querySelector('.priceInp').value.trim(), price=0; if(praw!==''){ var px=parseFloat(praw); if(!isFinite(px)||px<0){ box.innerHTML=''; panel._summary=''; return; } if(px>1000000){ box.innerHTML=''; panel._summary=''; return; } price=px; } if(!(vft3>0)){ box.innerHTML='
Enter your measurements above to see results instantly.
'; panel._summary=''; return; } h = netWasteHTML(vft3, waste, price, mode, panel, vals, imp); } box.innerHTML = h; /* Wire up bag selector buttons */ box.querySelectorAll('[data-bag]').forEach(function(b){ b.addEventListener('click', function(){ selectedBag = b.getAttribute('data-bag'); calcPanel(mode, panel); }); }); /* Wire up action buttons */ box.querySelectorAll('.cc-act, .cc-reset').forEach(function(b){ b.addEventListener('click', function(){ doAction(b.getAttribute('data-act'), b, panel, mode); }); }); } function calcBags(mode, panel, vals, units){ var u = units.y || 'yd3'; var yv = parseFloat(vals.y)||0; var ft3b, m3b, yd3b; if(u==='m3'){ m3b=yv; ft3b=yv*35.3147; yd3b=yv*1.30795; } else if(u==='ft3'){ ft3b=yv; yd3b=yv/27; m3b=yv*0.0283168; } else { yd3b=yv; ft3b=yv*27; m3b=yv*0.764555; } var bb = CC.bagsNeeded(ft3b); var bm = CC.bagsNeededM3(m3b); var h = '

Bags needed

'; h += bagSelectorHTML(); var selN = bagCount(bb, selectedBag) || bagCount(bm, selectedBag); h += '
' +'
'+ICONS.bags+''+selN+''+bagLabel(selectedBag)+' Bags
' +'
'; h += '
'+bb.b80+' x 80 lb' +''+bb.b60+' x 60 lb' +''+bb.b50+' x 50 lb' +''+bb.b40+' x 40 lb' +''+bm.k25+' x 25 kg' +''+bm.k20+' x 20 kg
'; h += '
Working: '+fmt(yd3b)+' yd3 x 27 = '+fmt(ft3b,1)+' ft3. ' +'80 lb: / 0.60 = '+bb.b80+'. 60 lb: / 0.45 = '+bb.b60+'. ' +'50 lb: / 0.375 = '+bb.b50+'. 40 lb: / 0.30 = '+bb.b40+'.
'; h += '

Bag yields per manufacturer specifications (Quikrete): ' +'80 lb = 0.60 ft3, 60 lb = 0.45 ft3, 50 lb = 0.375 ft3, 40 lb = 0.30 ft3.

'; h += actionsHTML(mode.id)+'
'; panel._summary = 'Bags for '+fmt(yd3b)+' cubic yards: ' +bb.b80+' x 80 lb, '+bb.b60+' x 60 lb, '+bb.b50+' x 50 lb, '+bb.b40+' x 40 lb. ' +'via concretequantity.com/concrete-calculator/#'+mode.id; return h; } function calcMix(mode, panel, vals, units){ var u = units.y || 'yd3'; var yv = parseFloat(vals.y)||0; var wetFt3 = (u==='m3') ? yv*35.3147 : (u==='ft3' ? yv : yv*27); var mx = CC.mixForFt3(wetFt3); var cb = Math.ceil(mx.cementFt3)||0; var sY = mx.sandFt3/27, aY = mx.aggFt3/27; var wg = cb*6; /* gallons, approx 6 gal per bag */ var h = '

Site-mix materials (1:2:4)

' +'
' +''+cb+' cement bags (94 lb)' +''+fmt(sY)+' yd3 sand' +''+fmt(aY)+' yd3 aggregate' +''+wg+' gallons water (approx, add gradually)' +'
' +'
Working: Dry volume = '+fmt(wetFt3/27)+' yd3 x 27 x 1.54 = '+fmt(mx.dryFt3,1)+' ft3. ' +'Cement = / 7 = '+fmt(mx.cementFt3,1)+' ft3 = '+cb+' bags (94 lb) (1 ft3 per bag). ' +'Sand = 2/7, Aggregate = 4/7.
' +'

Water: about half a bucket per bag, added gradually. Mix is suitable for non-structural work such as paths and bases. For structural concrete, use ready-mix to specification.

' + actionsHTML(mode.id)+'
'; panel._summary = 'Site mix (1:2:4) for '+fmt(wetFt3/27)+' cubic yards: '+cb +' cement bags, '+fmt(sY)+' yd3 sand, '+fmt(aY)+' yd3 aggregate. ' +'via concretequantity.com/concrete-calculator/#'+mode.id; return h; } function calcRebar(mode, panel, vals, units){ var l = toFt(vals.l, units.l||'ft'); var w = toFt(vals.w, units.w||'ft'); var s = toIn(vals.s, units.s||'in'); var c = vals.c ? toIn(vals.c, units.c||'in') : 3; /* default 3 in cover */ var rb = CC.rebarForSlab(l, w, s, c); if(!(rb.totalLF>0)) return '
Enter slab size and spacing above.
'; var h = '

Rebar estimate

' +'
'+fmt(rb.totalLF,0)+' linear feet
' +'
'+rb.bars20+' x 20-ft bars' +'Edge cover: '+fmt(c)+' in
' +'
Working: ' +'Bars across width: ceil(('+fmt(w*12,0)+' - 2x'+fmt(c)+') / '+fmt(s)+') + 1 = '+rb.nW +' bars x '+fmt(rb.barLenL,1)+' ft. ' +'Bars across length: ceil(('+fmt(l*12,0)+' - 2x'+fmt(c)+') / '+fmt(s)+') + 1 = '+rb.nL +' bars x '+fmt(rb.barLenW,1)+' ft. ' +'Total = '+fmt(rb.totalLF,0)+' ft.
' +'

Material estimate only, not structural design. ' +'Bars run the full slab length both ways with '+fmt(c)+' in edge cover. ' +'Laps are not counted, so add about 10% extra for laps and waste.

' + actionsHTML(mode.id)+'
'; panel._summary = 'Rebar estimate: '+fmt(rb.totalLF,0)+' linear feet ('+rb.bars20 +' x 20-ft bars, '+fmt(c)+' in cover). via concretequantity.com/concrete-calculator/#'+mode.id; return h; } function calcCost(mode, panel, vals, units){ var u = units.y || 'yd3'; var yv = parseFloat(vals.y)||0; var yd3v = (u==='m3') ? yv*1.30795 : (u==='ft3' ? yv/27 : yv); var price = parseFloat(vals.p)||0; var h = '

Cost estimate

'; var parts = []; if(yd3v>0 && price>0){ var total = yd3v*price; h += '
'+CUR+fmt(total)+'
'; h += ''+fmt(yd3v)+' yd3 x '+CUR+fmt(price)+' = '+CUR+fmt(total)+''; parts.push(fmt(yd3v)+' yd3 x '+CUR+fmt(price)+' = '+CUR+fmt(total)+''); panel._summary = 'Concrete cost: '+fmt(yd3v)+' cubic yards at '+CUR+fmt(price)+' = '+CUR+fmt(total) +'. via concretequantity.com/concrete-calculator/#'+mode.id; } else { h += '
'+mode.empty+'
'; panel._summary = ''; } h += '
'; if(parts.length) h += '
Working: '+parts.join('
')+'
'; h += '

Material cost only. Delivery, short-load and pumping fees vary by supplier. Get a local quote for the full price.

'; h += actionsHTML(mode.id)+'
'; return h; } /* ============ 11. PANEL + TABS ============ */ function buildPanel(m, first){ var p = document.createElement('div'); p.className = 'cc-panel'+(first?' on':''); p.id = 'ccp-'+m.id; p.setAttribute('role','tabpanel'); var inner = '

'+m.title+'

'+m.formula+'

' +'
' +'
'; m.fields.forEach(function(f){ inner += fieldHTML(f); }); inner += '
'; if(!m.custom) inner += volExtrasHTML(); inner += '
'; inner += relatedHTML(m.id); inner += verifiedHTML(); p.innerHTML = inner; /* Input events: recalculate + live preview */ p.querySelectorAll('input,select').forEach(function(el){ el.addEventListener('input', function(){ calcPanel(m, p); updatePreview(m, p); }); el.addEventListener('change', function(){ calcPanel(m, p); updatePreview(m, p); }); }); /* Per-field unit change: convert the entered value */ p.querySelectorAll('select.cc-funit').forEach(function(sel){ sel.addEventListener('change', function(){ var fid = sel.getAttribute('data-funit'); var inp = p.querySelector('input[data-fid="'+fid+'"]'); if(!inp || !inp.value) { calcPanel(m,p); updatePreview(m,p); return; } var field = null; m.fields.forEach(function(f){ if(f.id===fid) field=f; }); if(!field) return; var oldU = sel.getAttribute('data-prev') || field.defUnit || 'ft'; var newU = sel.value; if(oldU!==newU){ inp.value = convertVal(inp.value, oldU, newU, field.kind); } sel.setAttribute('data-prev', newU); calcPanel(m, p); updatePreview(m, p); }); /* Store initial unit */ var f0=null; m.fields.forEach(function(f){ if(f.id===sel.getAttribute('data-funit')) f0=f; }); sel.setAttribute('data-prev', sel.value); }); /* Quick thickness buttons */ p.querySelectorAll('[data-quick]').forEach(function(b){ b.addEventListener('click', function(){ var fid = b.getAttribute('data-qfid'); var inp = p.querySelector('input[data-fid="'+fid+'"]'); var sel = p.querySelector('select.cc-funit[data-funit="'+fid+'"]'); if(inp){ var qv = b.getAttribute('data-quick'); if(sel && (sel.value==='m'||sel.value==='cm'||sel.value==='mm')){ /* Convert inches to the selected metric unit */ var inVal = parseFloat(qv); var cm = inVal*2.54; if(sel.value==='m') inp.value = fmt(cm/100,3); else if(sel.value==='cm') inp.value = fmt(cm,1); else inp.value = fmt(cm*10,0); } else { inp.value = qv; if(sel) sel.value='in'; } p.querySelectorAll('[data-qfid="'+fid+'"]').forEach(function(x){ x.classList.remove('on'); }); b.classList.add('on'); calcPanel(m, p); updatePreview(m, p); } }); }); /* Restore from URL params if present */ var restored = restoreFromURL(m, p); calcPanel(m, p); updatePreview(m, p); return p; } function activateTab(id){ var tabs = document.getElementById('ccTabs'), panels = document.getElementById('ccPanels'); if(!tabs || !panels) return false; var ok = false; MODES.forEach(function(m){ if(m.id===id) ok = true; }); if(!ok) return false; tabs.querySelectorAll('button').forEach(function(b){ var on = b.getAttribute('data-mid')===id; b.classList.toggle('on', on); b.setAttribute('aria-selected', on?'true':'false'); }); panels.querySelectorAll('.cc-panel').forEach(function(p){ p.classList.toggle('on', p.id==='ccp-'+id); }); return true; } function buildTabs(){ var tabs = document.getElementById('ccTabs'), panels = document.getElementById('ccPanels'); if(!tabs || !panels) return; tabs.setAttribute('role','tablist'); MODES.forEach(function(m, i){ var tb = document.createElement('button'); tb.type='button'; tb.innerHTML = (ICONS[m.icon]||'')+''+m.tab+''; tb.setAttribute('role','tab'); tb.setAttribute('data-mid', m.id); tb.setAttribute('aria-selected', i===0?'true':'false'); if(i===0) tb.classList.add('on'); tb.onclick = function(){ activateTab(m.id); try{ history.replaceState(null,'','#'+m.id); }catch(e){} }; tabs.appendChild(tb); panels.appendChild(buildPanel(m, i===0)); }); var h = (location.hash||'').replace('#','').split('?')[0]; if(h) activateTab(h); window.addEventListener('hashchange', function(){ var hh=(location.hash||'').replace('#','').split('?')[0]; activateTab(hh); }); } function buildSingle(){ var id = window.CC_SINGLE, m = null; MODES.forEach(function(x){ if(x.id===id) m = x; }); if(!m) return; var c = document.getElementById('ccSingle'); if(!c) return; c.appendChild(buildPanel(m, true)); } /* ============ 12. GLOBAL UNIT + CURRENCY TOGGLES ============ */ function recalcAll(){ MODES.forEach(function(m){ var p = document.getElementById('ccp-'+m.id); if(p){ calcPanel(m, p); updatePreview(m, p); } }); } function setUnits(u){ if(u===UNITS) return; UNITS = u; saveUnitPref(); var ui=document.getElementById('uImp'), um=document.getElementById('uMet'); if(ui) ui.classList.toggle('on', u==='imp'); if(um) um.classList.toggle('on', u==='met'); recalcAll(); } function setCur(c){ CUR = c; saveUnitPref(); var b=document.getElementById('uCur'); if(b) b.textContent = (c==='£' ? '£ GBP' : (c==='€' ? '€ EUR' : '$ USD')); document.querySelectorAll('.curSym').forEach(function(s){ s.textContent = c; }); recalcAll(); } function buildCurToggle(){ var u=document.querySelector('.cc-units'); if(!u || document.getElementById('uCur')) return; var b=document.createElement('button'); b.type='button'; b.id='uCur'; b.textContent = (CUR==='£' ? '£ GBP' : (CUR==='€' ? '€ EUR' : '$ USD')); b.setAttribute('aria-label','Toggle currency between US dollars, British pounds and euros'); b.onclick=function(){ setCur(CUR==='$' ? '£' : (CUR==='£' ? '€' : '$')); }; u.appendChild(b); } /* ============ 13. INIT ============ */ var _uImp=document.getElementById('uImp'), _uMet=document.getElementById('uMet'); if(_uImp) _uImp.onclick = function(){ setUnits('imp'); }; if(_uMet) _uMet.onclick = function(){ setUnits('met'); }; /* Apply saved preference to toggle buttons */ (function(){ var ui=document.getElementById('uImp'), um=document.getElementById('uMet'); if(ui) ui.classList.toggle('on', UNITS==='imp'); if(um) um.classList.toggle('on', UNITS==='met'); })(); buildCurToggle(); if(window.CC_SINGLE){ buildSingle(); } else { buildTabs(); } /* Expose for testing */ window.CC_V6 = { CC:CC, MODES:MODES, version:'6.0' }; })();