PIE_IE678_uncompressed.js 166 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451
  1. /*
  2. PIE: CSS3 rendering for IE
  3. Version 2.0beta1
  4. http://css3pie.com
  5. Dual-licensed for use under the Apache License Version 2.0 or the General Public License (GPL) Version 2.
  6. */
  7. (function( win, doc ) {
  8. var PIE = win[ 'PIE' ] || ( win[ 'PIE' ] = {} );
  9. /**
  10. * Simple utility for merging objects
  11. * @param {Object} obj1 The main object into which all others will be merged
  12. * @param {...Object} var_args Other objects which will be merged into the first, in order
  13. */
  14. PIE.merge = function( obj1 ) {
  15. var i, len, p, objN, args = arguments;
  16. for( i = 1, len = args.length; i < len; i++ ) {
  17. objN = args[i];
  18. for( p in objN ) {
  19. if( objN.hasOwnProperty( p ) ) {
  20. obj1[ p ] = objN[ p ];
  21. }
  22. }
  23. }
  24. return obj1;
  25. };
  26. PIE.merge(PIE, {
  27. // Constants
  28. CSS_PREFIX: '-pie-',
  29. STYLE_PREFIX: 'Pie',
  30. CLASS_PREFIX: 'pie_',
  31. tableCellTags: {
  32. 'TD': 1,
  33. 'TH': 1
  34. },
  35. /**
  36. * Lookup table of elements which cannot take custom children.
  37. */
  38. childlessElements: {
  39. 'TABLE':1,
  40. 'THEAD':1,
  41. 'TBODY':1,
  42. 'TFOOT':1,
  43. 'TR':1,
  44. 'INPUT':1,
  45. 'TEXTAREA':1,
  46. 'SELECT':1,
  47. 'OPTION':1,
  48. 'IMG':1,
  49. 'HR':1
  50. },
  51. /**
  52. * Elements that can receive user focus
  53. */
  54. focusableElements: {
  55. 'A':1,
  56. 'INPUT':1,
  57. 'TEXTAREA':1,
  58. 'SELECT':1,
  59. 'BUTTON':1
  60. },
  61. /**
  62. * Values of the type attribute for input elements displayed as buttons
  63. */
  64. inputButtonTypes: {
  65. 'submit':1,
  66. 'button':1,
  67. 'reset':1
  68. },
  69. emptyFn: function() {}
  70. });
  71. // Force the background cache to be used. No reason it shouldn't be.
  72. try {
  73. doc.execCommand( 'BackgroundImageCache', false, true );
  74. } catch(e) {}
  75. (function() {
  76. /*
  77. * IE version detection approach by James Padolsey, with modifications -- from
  78. * http://james.padolsey.com/javascript/detect-ie-in-js-using-conditional-comments/
  79. */
  80. var ieVersion = 4,
  81. div = doc.createElement('div'),
  82. all = div.getElementsByTagName('i'),
  83. shape;
  84. while (
  85. div.innerHTML = '<!--[if gt IE ' + (++ieVersion) + ']><i></i><![endif]-->',
  86. all[0]
  87. ) {}
  88. PIE.ieVersion = ieVersion;
  89. // Detect IE6
  90. if( ieVersion === 6 ) {
  91. // IE6 can't access properties with leading dash, but can without it.
  92. PIE.CSS_PREFIX = PIE.CSS_PREFIX.replace( /^-/, '' );
  93. }
  94. PIE.ieDocMode = doc.documentMode || PIE.ieVersion;
  95. // Detect VML support (a small number of IE installs don't have a working VML engine)
  96. div.innerHTML = '<v:shape adj="1"/>';
  97. shape = div.firstChild;
  98. shape.style['behavior'] = 'url(#default#VML)';
  99. PIE.supportsVML = (typeof shape['adj'] === "object");
  100. })();
  101. /**
  102. * Utility functions
  103. */
  104. (function() {
  105. var idNum = 0,
  106. imageSizes = {};
  107. PIE.Util = {
  108. /**
  109. * Generate and return a unique ID for a given object. The generated ID is stored
  110. * as a property of the object for future reuse. For DOM Elements, don't use this
  111. * but use the IE-native uniqueID property instead.
  112. * @param {Object} obj
  113. */
  114. getUID: function( obj ) {
  115. return obj && obj[ '_pieId' ] || ( obj[ '_pieId' ] = '_' + idNum++ );
  116. },
  117. /**
  118. * Execute a callback function, passing it the dimensions of a given image once
  119. * they are known.
  120. * @param {string} src The source URL of the image
  121. * @param {function({w:number, h:number})} func The callback function to be called once the image dimensions are known
  122. * @param {Object} ctx A context object which will be used as the 'this' value within the executed callback function
  123. */
  124. withImageSize: function( src, func, ctx ) {
  125. var size = imageSizes[ src ], img, queue;
  126. if( size ) {
  127. // If we have a queue, add to it
  128. if( Object.prototype.toString.call( size ) === '[object Array]' ) {
  129. size.push( [ func, ctx ] );
  130. }
  131. // Already have the size cached, call func right away
  132. else {
  133. func.call( ctx, size );
  134. }
  135. } else {
  136. queue = imageSizes[ src ] = [ [ func, ctx ] ]; //create queue
  137. img = new Image();
  138. img.onload = function() {
  139. size = imageSizes[ src ] = { w: img.width, h: img.height };
  140. for( var i = 0, len = queue.length; i < len; i++ ) {
  141. queue[ i ][ 0 ].call( queue[ i ][ 1 ], size );
  142. }
  143. img.onload = null;
  144. };
  145. img.src = src;
  146. }
  147. }
  148. };
  149. })();/**
  150. * Utility functions for handling gradients
  151. */
  152. PIE.GradientUtil = {
  153. toSideAngles: {
  154. 'top': 0,
  155. 'right': 90,
  156. 'bottom': 180,
  157. 'left': 270
  158. },
  159. getGradientMetrics: function( el, width, height, gradientInfo ) {
  160. var angle = gradientInfo.angle,
  161. toPos = gradientInfo.gradientTo,
  162. dX, dY,
  163. endPoint,
  164. startX, startY,
  165. endX, endY;
  166. // If an angle was specified, just use it
  167. if (angle) {
  168. angle = angle.degrees();
  169. }
  170. // If a to-position was specified, find the appropriate angle for it
  171. else if (toPos) {
  172. // To a corner; find the adjacent corners and use the angle perpendicular to them
  173. if (toPos[1]) {
  174. dX = ( toPos[0] == 'top' || toPos[1] == 'top' ) ? width : -width;
  175. dY = ( toPos[0] == 'left' || toPos[1] == 'left' ) ? -height : height;
  176. angle = Math.atan2(dY, dX) * 180 / Math.PI;
  177. }
  178. // To a side; map to a vertical/horizontal angle
  179. else {
  180. angle = this.toSideAngles[toPos[0]];
  181. }
  182. }
  183. // Neither specified; default is top to bottom
  184. else {
  185. angle = 180;
  186. }
  187. // Normalize the angle to a value between [0, 360)
  188. while( angle < 0 ) {
  189. angle += 360;
  190. }
  191. angle = angle % 360;
  192. // Find the end point of the gradient line, extending the angle from the center point
  193. // to where it intersects the perpendicular line passing through the nearest corner.
  194. endPoint = PIE.GradientUtil.perpendicularIntersect(width / 2, height / 2, angle,
  195. ( angle >= 180 ? 0 : width ), ( angle < 90 || angle > 270 ? 0 : height )
  196. );
  197. endX = endPoint[0];
  198. endY = endPoint[1];
  199. startX = width - endX;
  200. startY = height - endY;
  201. return {
  202. angle: angle,
  203. endX: endX,
  204. endY: endY,
  205. startX: startX,
  206. startY: startY,
  207. lineLength: PIE.GradientUtil.distance( startX, startY, endX, endY )
  208. };
  209. },
  210. /**
  211. * Find the point along a given line (defined by a starting point and an angle), at which
  212. * that line is intersected by a perpendicular line extending through another point.
  213. * @param x1 - x coord of the starting point
  214. * @param y1 - y coord of the starting point
  215. * @param angle - angle of the line extending from the starting point (in degrees)
  216. * @param x2 - x coord of point along the perpendicular line
  217. * @param y2 - y coord of point along the perpendicular line
  218. * @return [ x, y ]
  219. */
  220. perpendicularIntersect: function( x1, y1, angle, x2, y2 ) {
  221. // Handle straight vertical and horizontal angles, for performance and to avoid
  222. // divide-by-zero errors.
  223. if( angle === 0 || angle === 180 ) {
  224. return [ x1, y2 ];
  225. }
  226. else if( angle === 90 || angle === 270 ) {
  227. return [ x2, y1 ];
  228. }
  229. else {
  230. // General approach: determine the Ax+By=C formula for each line (the slope of the second
  231. // line is the negative inverse of the first) and then solve for where both formulas have
  232. // the same x/y values.
  233. var a1 = Math.tan( ( angle - 90 ) * Math.PI / 180 ),
  234. c1 = a1 * x1 - y1,
  235. a2 = -1 / a1,
  236. c2 = a2 * x2 - y2,
  237. d = a2 - a1,
  238. endX = ( c2 - c1 ) / d,
  239. endY = ( a1 * c2 - a2 * c1 ) / d;
  240. return [ endX, endY ];
  241. }
  242. },
  243. /**
  244. * Find the distance between two points
  245. * @param {Number} p1x
  246. * @param {Number} p1y
  247. * @param {Number} p2x
  248. * @param {Number} p2y
  249. * @return {Number} the distance
  250. */
  251. distance: function( p1x, p1y, p2x, p2y ) {
  252. var dx = p2x - p1x,
  253. dy = p2y - p1y;
  254. return Math.abs(
  255. dx === 0 ? dy :
  256. dy === 0 ? dx :
  257. Math.sqrt( dx * dx + dy * dy )
  258. );
  259. }
  260. };/**
  261. *
  262. */
  263. PIE.Observable = function() {
  264. /**
  265. * List of registered observer functions
  266. */
  267. this.observers = [];
  268. /**
  269. * Hash of function ids to their position in the observers list, for fast lookup
  270. */
  271. this.indexes = {};
  272. };
  273. PIE.Observable.prototype = {
  274. observe: function( fn ) {
  275. var id = PIE.Util.getUID( fn ),
  276. indexes = this.indexes,
  277. observers = this.observers;
  278. if( !( id in indexes ) ) {
  279. indexes[ id ] = observers.length;
  280. observers.push( fn );
  281. }
  282. },
  283. unobserve: function( fn ) {
  284. var id = PIE.Util.getUID( fn ),
  285. indexes = this.indexes;
  286. if( id && id in indexes ) {
  287. delete this.observers[ indexes[ id ] ];
  288. delete indexes[ id ];
  289. }
  290. },
  291. fire: function() {
  292. var o = this.observers,
  293. i = o.length;
  294. while( i-- ) {
  295. o[ i ] && o[ i ]();
  296. }
  297. }
  298. };/*
  299. * Simple heartbeat timer - this is a brute-force workaround for syncing issues caused by IE not
  300. * always firing the onmove and onresize events when elements are moved or resized. We check a few
  301. * times every second to make sure the elements have the correct position and size. See Element.js
  302. * which adds heartbeat listeners based on the custom -pie-poll flag, which defaults to true in IE8-9
  303. * and false elsewhere.
  304. */
  305. PIE.Heartbeat = new PIE.Observable();
  306. PIE.Heartbeat.run = function() {
  307. var me = this,
  308. interval;
  309. if( !me.running ) {
  310. interval = doc.documentElement.currentStyle.getAttribute( PIE.CSS_PREFIX + 'poll-interval' ) || 250;
  311. (function beat() {
  312. me.fire();
  313. setTimeout(beat, interval);
  314. })();
  315. me.running = 1;
  316. }
  317. };
  318. /**
  319. * Create an observable listener for the onunload event
  320. */
  321. (function() {
  322. PIE.OnUnload = new PIE.Observable();
  323. function handleUnload() {
  324. PIE.OnUnload.fire();
  325. win.detachEvent( 'onunload', handleUnload );
  326. win[ 'PIE' ] = null;
  327. }
  328. win.attachEvent( 'onunload', handleUnload );
  329. /**
  330. * Attach an event which automatically gets detached onunload
  331. */
  332. PIE.OnUnload.attachManagedEvent = function( target, name, handler ) {
  333. target.attachEvent( name, handler );
  334. this.observe( function() {
  335. target.detachEvent( name, handler );
  336. } );
  337. };
  338. })()/**
  339. * Create a single observable listener for window resize events.
  340. */
  341. PIE.OnResize = new PIE.Observable();
  342. PIE.OnUnload.attachManagedEvent( win, 'onresize', function() { PIE.OnResize.fire(); } );
  343. /**
  344. * Create a single observable listener for scroll events. Used for lazy loading based
  345. * on the viewport, and for fixed position backgrounds.
  346. */
  347. (function() {
  348. PIE.OnScroll = new PIE.Observable();
  349. function scrolled() {
  350. PIE.OnScroll.fire();
  351. }
  352. PIE.OnUnload.attachManagedEvent( win, 'onscroll', scrolled );
  353. PIE.OnResize.observe( scrolled );
  354. })();
  355. /**
  356. * Listen for printing events, destroy all active PIE instances when printing, and
  357. * restore them afterward.
  358. */
  359. (function() {
  360. var elements;
  361. function beforePrint() {
  362. elements = PIE.Element.destroyAll();
  363. }
  364. function afterPrint() {
  365. if( elements ) {
  366. for( var i = 0, len = elements.length; i < len; i++ ) {
  367. PIE[ 'attach' ]( elements[i] );
  368. }
  369. elements = 0;
  370. }
  371. }
  372. PIE.OnUnload.attachManagedEvent( win, 'onbeforeprint', beforePrint );
  373. PIE.OnUnload.attachManagedEvent( win, 'onafterprint', afterPrint );
  374. })();/**
  375. * Create a single observable listener for document mouseup events.
  376. */
  377. PIE.OnMouseup = new PIE.Observable();
  378. PIE.OnUnload.attachManagedEvent( doc, 'onmouseup', function() { PIE.OnMouseup.fire(); } );
  379. /**
  380. * Wrapper for length and percentage style values. The value is immutable. A singleton instance per unique
  381. * value is returned from PIE.getLength() - always use that instead of instantiating directly.
  382. * @constructor
  383. * @param {string} val The CSS string representing the length. It is assumed that this will already have
  384. * been validated as a valid length or percentage syntax.
  385. */
  386. PIE.Length = (function() {
  387. var lengthCalcEl = doc.createElement( 'length-calc' ),
  388. parent = doc.body || doc.documentElement,
  389. s = lengthCalcEl.style,
  390. conversions = {},
  391. units = [ 'mm', 'cm', 'in', 'pt', 'pc' ],
  392. i = units.length,
  393. instances = {};
  394. s.position = 'absolute';
  395. s.top = s.left = '-9999px';
  396. parent.appendChild( lengthCalcEl );
  397. while( i-- ) {
  398. s.width = '100' + units[i];
  399. conversions[ units[i] ] = lengthCalcEl.offsetWidth / 100;
  400. }
  401. parent.removeChild( lengthCalcEl );
  402. // All calcs from here on will use 1em
  403. s.width = '1em';
  404. function Length( val ) {
  405. this.val = val;
  406. }
  407. Length.prototype = {
  408. /**
  409. * Regular expression for matching the length unit
  410. * @private
  411. */
  412. unitRE: /(px|em|ex|mm|cm|in|pt|pc|%)$/,
  413. /**
  414. * Get the numeric value of the length
  415. * @return {number} The value
  416. */
  417. getNumber: function() {
  418. var num = this.num,
  419. UNDEF;
  420. if( num === UNDEF ) {
  421. num = this.num = parseFloat( this.val );
  422. }
  423. return num;
  424. },
  425. /**
  426. * Get the unit of the length
  427. * @return {string} The unit
  428. */
  429. getUnit: function() {
  430. var unit = this.unit,
  431. m;
  432. if( !unit ) {
  433. m = this.val.match( this.unitRE );
  434. unit = this.unit = ( m && m[0] ) || 'px';
  435. }
  436. return unit;
  437. },
  438. /**
  439. * Determine whether this is a percentage length value
  440. * @return {boolean}
  441. */
  442. isPercentage: function() {
  443. return this.getUnit() === '%';
  444. },
  445. /**
  446. * Resolve this length into a number of pixels.
  447. * @param {Element} el - the context element, used to resolve font-relative values
  448. * @param {(function():number|number)=} pct100 - the number of pixels that equal a 100% percentage. This can be either a number or a
  449. * function which will be called to return the number.
  450. */
  451. pixels: function( el, pct100 ) {
  452. var num = this.getNumber(),
  453. unit = this.getUnit();
  454. switch( unit ) {
  455. case "px":
  456. return num;
  457. case "%":
  458. return num * ( typeof pct100 === 'function' ? pct100() : pct100 ) / 100;
  459. case "em":
  460. return num * this.getEmPixels( el );
  461. case "ex":
  462. return num * this.getEmPixels( el ) / 2;
  463. default:
  464. return num * conversions[ unit ];
  465. }
  466. },
  467. /**
  468. * The em and ex units are relative to the font-size of the current element,
  469. * however if the font-size is set using non-pixel units then we get that value
  470. * rather than a pixel conversion. To get around this, we keep a floating element
  471. * with width:1em which we insert into the target element and then read its offsetWidth.
  472. * For elements that won't accept a child we insert into the parent node and perform
  473. * additional calculation. If the font-size *is* specified in pixels, then we use that
  474. * directly to avoid the expensive DOM manipulation.
  475. * @param {Element} el
  476. * @return {number}
  477. */
  478. getEmPixels: function( el ) {
  479. var fs = el.currentStyle.fontSize,
  480. px, parent, me;
  481. if( fs.indexOf( 'px' ) > 0 ) {
  482. return parseFloat( fs );
  483. }
  484. else if( el.tagName in PIE.childlessElements ) {
  485. me = this;
  486. parent = el.parentNode;
  487. return PIE.getLength( fs ).pixels( parent, function() {
  488. return me.getEmPixels( parent );
  489. } );
  490. }
  491. else {
  492. el.appendChild( lengthCalcEl );
  493. px = lengthCalcEl.offsetWidth;
  494. if( lengthCalcEl.parentNode === el ) { //not sure how this could be false but it sometimes is
  495. el.removeChild( lengthCalcEl );
  496. }
  497. return px;
  498. }
  499. }
  500. };
  501. /**
  502. * Convert a pixel length into a point length
  503. */
  504. Length.pxToPt = function( px ) {
  505. return px / conversions[ 'pt' ];
  506. };
  507. /**
  508. * Retrieve a PIE.Length instance for the given value. A shared singleton instance is returned for each unique value.
  509. * @param {string} val The CSS string representing the length. It is assumed that this will already have
  510. * been validated as a valid length or percentage syntax.
  511. */
  512. PIE.getLength = function( val ) {
  513. return instances[ val ] || ( instances[ val ] = new Length( val ) );
  514. };
  515. return Length;
  516. })();
  517. /**
  518. * Wrapper for a CSS3 bg-position value. Takes up to 2 position keywords and 2 lengths/percentages.
  519. * @constructor
  520. * @param {Array.<PIE.Tokenizer.Token>} tokens The tokens making up the background position value.
  521. */
  522. PIE.BgPosition = (function() {
  523. var length_fifty = PIE.getLength( '50%' ),
  524. vert_idents = { 'top': 1, 'center': 1, 'bottom': 1 },
  525. horiz_idents = { 'left': 1, 'center': 1, 'right': 1 };
  526. function BgPosition( tokens ) {
  527. this.tokens = tokens;
  528. }
  529. BgPosition.prototype = {
  530. /**
  531. * Normalize the values into the form:
  532. * [ xOffsetSide, xOffsetLength, yOffsetSide, yOffsetLength ]
  533. * where: xOffsetSide is either 'left' or 'right',
  534. * yOffsetSide is either 'top' or 'bottom',
  535. * and x/yOffsetLength are both PIE.Length objects.
  536. * @return {Array}
  537. */
  538. getValues: function() {
  539. if( !this._values ) {
  540. var tokens = this.tokens,
  541. len = tokens.length,
  542. Tokenizer = PIE.Tokenizer,
  543. identType = Tokenizer.Type,
  544. length_zero = PIE.getLength( '0' ),
  545. type_ident = identType.IDENT,
  546. type_length = identType.LENGTH,
  547. type_percent = identType.PERCENT,
  548. type, value,
  549. vals = [ 'left', length_zero, 'top', length_zero ];
  550. // If only one value, the second is assumed to be 'center'
  551. if( len === 1 ) {
  552. tokens.push( new Tokenizer.Token( type_ident, 'center' ) );
  553. len++;
  554. }
  555. // Two values - CSS2
  556. if( len === 2 ) {
  557. // If both idents, they can appear in either order, so switch them if needed
  558. if( type_ident & ( tokens[0].tokenType | tokens[1].tokenType ) &&
  559. tokens[0].tokenValue in vert_idents && tokens[1].tokenValue in horiz_idents ) {
  560. tokens.push( tokens.shift() );
  561. }
  562. if( tokens[0].tokenType & type_ident ) {
  563. if( tokens[0].tokenValue === 'center' ) {
  564. vals[1] = length_fifty;
  565. } else {
  566. vals[0] = tokens[0].tokenValue;
  567. }
  568. }
  569. else if( tokens[0].isLengthOrPercent() ) {
  570. vals[1] = PIE.getLength( tokens[0].tokenValue );
  571. }
  572. if( tokens[1].tokenType & type_ident ) {
  573. if( tokens[1].tokenValue === 'center' ) {
  574. vals[3] = length_fifty;
  575. } else {
  576. vals[2] = tokens[1].tokenValue;
  577. }
  578. }
  579. else if( tokens[1].isLengthOrPercent() ) {
  580. vals[3] = PIE.getLength( tokens[1].tokenValue );
  581. }
  582. }
  583. // Three or four values - CSS3
  584. else {
  585. // TODO
  586. }
  587. this._values = vals;
  588. }
  589. return this._values;
  590. },
  591. /**
  592. * Find the coordinates of the background image from the upper-left corner of the background area.
  593. * Note that these coordinate values are not rounded.
  594. * @param {Element} el
  595. * @param {number} width - the width for percentages (background area width minus image width)
  596. * @param {number} height - the height for percentages (background area height minus image height)
  597. * @return {Object} { x: Number, y: Number }
  598. */
  599. coords: function( el, width, height ) {
  600. var vals = this.getValues(),
  601. pxX = vals[1].pixels( el, width ),
  602. pxY = vals[3].pixels( el, height );
  603. return {
  604. x: vals[0] === 'right' ? width - pxX : pxX,
  605. y: vals[2] === 'bottom' ? height - pxY : pxY
  606. };
  607. }
  608. };
  609. return BgPosition;
  610. })();
  611. /**
  612. * Wrapper for a CSS3 background-size value.
  613. * @constructor
  614. * @param {String|PIE.Length} w The width parameter
  615. * @param {String|PIE.Length} h The height parameter, if any
  616. */
  617. PIE.BgSize = (function() {
  618. var CONTAIN = 'contain',
  619. COVER = 'cover',
  620. AUTO = 'auto';
  621. function BgSize( w, h ) {
  622. this.w = w;
  623. this.h = h;
  624. }
  625. BgSize.prototype = {
  626. pixels: function( el, areaW, areaH, imgW, imgH ) {
  627. var me = this,
  628. w = me.w,
  629. h = me.h,
  630. areaRatio = areaW / areaH,
  631. imgRatio = imgW / imgH;
  632. if ( w === CONTAIN ) {
  633. w = imgRatio > areaRatio ? areaW : areaH * imgRatio;
  634. h = imgRatio > areaRatio ? areaW / imgRatio : areaH;
  635. }
  636. else if ( w === COVER ) {
  637. w = imgRatio < areaRatio ? areaW : areaH * imgRatio;
  638. h = imgRatio < areaRatio ? areaW / imgRatio : areaH;
  639. }
  640. else if ( w === AUTO ) {
  641. h = ( h === AUTO ? imgH : h.pixels( el, areaH ) );
  642. w = h * imgRatio;
  643. }
  644. else {
  645. w = w.pixels( el, areaW );
  646. h = ( h === AUTO ? w / imgRatio : h.pixels( el, areaH ) );
  647. }
  648. return { w: w, h: h };
  649. }
  650. };
  651. BgSize.DEFAULT = new BgSize( AUTO, AUTO );
  652. return BgSize;
  653. })();
  654. /**
  655. * Wrapper for angle values; handles conversion to degrees from all allowed angle units
  656. * @constructor
  657. * @param {string} val The raw CSS value for the angle. It is assumed it has been pre-validated.
  658. */
  659. PIE.Angle = (function() {
  660. function Angle( val ) {
  661. this.val = val;
  662. }
  663. Angle.prototype = {
  664. unitRE: /[a-z]+$/i,
  665. /**
  666. * @return {string} The unit of the angle value
  667. */
  668. getUnit: function() {
  669. return this._unit || ( this._unit = this.val.match( this.unitRE )[0].toLowerCase() );
  670. },
  671. /**
  672. * Get the numeric value of the angle in degrees.
  673. * @return {number} The degrees value
  674. */
  675. degrees: function() {
  676. var deg = this._deg, u, n;
  677. if( deg === undefined ) {
  678. u = this.getUnit();
  679. n = parseFloat( this.val, 10 );
  680. deg = this._deg = ( u === 'deg' ? n : u === 'rad' ? n / Math.PI * 180 : u === 'grad' ? n / 400 * 360 : u === 'turn' ? n * 360 : 0 );
  681. }
  682. return deg;
  683. }
  684. };
  685. return Angle;
  686. })();/**
  687. * Abstraction for colors values. Allows detection of rgba values. A singleton instance per unique
  688. * value is returned from PIE.getColor() - always use that instead of instantiating directly.
  689. * @constructor
  690. * @param {string} val The raw CSS string value for the color
  691. */
  692. PIE.Color = (function() {
  693. /*
  694. * hsl2rgb from http://codingforums.com/showthread.php?t=11156
  695. * code by Jason Karl Davis (http://www.jasonkarldavis.com)
  696. * swiped from cssSandpaper by Zoltan Hawryluk (http://www.useragentman.com/blog/csssandpaper-a-css3-javascript-library/)
  697. * modified for formatting and size optimizations
  698. */
  699. function hsl2rgb( h, s, l ) {
  700. var m1, m2, r, g, b,
  701. round = Math.round;
  702. s /= 100;
  703. l /= 100;
  704. if ( !s ) { r = g = b = l * 255; }
  705. else {
  706. if ( l <= 0.5 ) { m2 = l * ( s + 1 ); }
  707. else { m2 = l + s - l * s; }
  708. m1 = l * 2 - m2;
  709. h = ( h % 360 ) / 360;
  710. r = hueToRgb( m1, m2, h + 1/3 );
  711. g = hueToRgb( m1, m2, h );
  712. b = hueToRgb( m1, m2, h - 1/3 );
  713. }
  714. return { r: round( r ), g: round( g ), b: round( b ) };
  715. }
  716. function hueToRgb( m1, m2, hue ) {
  717. var v;
  718. if ( hue < 0 ) { hue += 1; }
  719. else if ( hue > 1 ) { hue -= 1; }
  720. if ( 6 * hue < 1 ) { v = m1 + ( m2 - m1 ) * hue * 6; }
  721. else if ( 2 * hue < 1 ) { v = m2; }
  722. else if ( 3 * hue < 2 ) { v = m1 + ( m2 - m1 ) * ( 2/3 - hue ) * 6; }
  723. else { v = m1; }
  724. return 255 * v;
  725. }
  726. var instances = {};
  727. function Color( val ) {
  728. this.val = val;
  729. }
  730. /**
  731. * Regular expression for matching rgba colors and extracting their components
  732. * @type {RegExp}
  733. */
  734. Color.rgbOrRgbaRE = /\s*rgba?\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*(,\s*(\d+|\d*\.\d+))?\s*\)\s*/;
  735. Color.hslOrHslaRE = /\s*hsla?\(\s*(\d*\.?\d+)\s*,\s*(\d{1,3})%\s*,\s*(\d{1,3})%\s*(,\s*(\d+|\d*\.\d+))?\s*\)\s*/;
  736. /**
  737. * Hash of color keyword names to their corresponding hex values. Encoded for
  738. * small size and expanded into a hash on startup.
  739. */
  740. Color.names = {};
  741. var names = 'black|0|navy|3k|darkblue|b|mediumblue|1u|blue|1e|darkgreen|jk1|green|5j4|teal|3k|darkcyan|26j|deepskyblue|ad0|darkturquoise|2xe|mediumspringgreen|8nd|lime|va|springgreen|3j|aqua|3k|cyan|0|midnightblue|xunl|dodgerblue|7ogf|lightseagreen|2zsb|forestgreen|2lbs|seagreen|guut|darkslategray|12pk|limegreen|4wkj|mediumseagreen|dwlb|turquoise|5v8f|royalblue|r2p|steelblue|75qr|darkslateblue|2fh3|mediumturquoise|ta9|indigo|32d2|darkolivegreen|emr1|cadetblue|ebu9|cornflowerblue|6z4d|mediumaquamarine|3459|dimgray|3nwf|slateblue|1bok|olivedrab|1opi|slategray|6y5p|lightslategray|9vk9|mediumslateblue|5g0l|lawngreen|27ma|chartreuse|48ao|aquamarine|5w|maroon|18|purple|3k|olive|p6o|gray|3k|lightslateblue|5j7j|skyblue|4q98|lightskyblue|f|blueviolet|3bhk|darkred|15we|darkmagenta|3v|saddlebrown|djc|darkseagreen|69vg|lightgreen|1og1|mediumpurple|3ivc|darkviolet|sfv|palegreen|6zt1|darkorchid|awk|yellowgreen|292e|sienna|7r3v|brown|6sxp|darkgray|6bgf|lightblue|5vlp|greenyellow|7k9|paleturquoise|2pxb|lightsteelblue|169c|powderblue|5jc|firebrick|1rgc|darkgoldenrod|8z55|mediumorchid|2jm0|rosybrown|34jg|darkkhaki|1mfw|silver|49jp|mediumvioletred|8w5h|indianred|8tef|peru|82r|violetred|3ntd|feldspar|212d|chocolate|16eh|tan|ewe|lightgrey|1kqv|palevioletred|6h8g|metle|fnp|orchid|2dj2|goldenrod|abu|crimson|20ik|gainsboro|13mo|plum|12pt|burlywood|1j8q|lightcyan|3794|lavender|8agr|darksalmon|3rsw|violet|6wz8|palegoldenrod|k3g|lightcoral|28k6|khaki|k5o|aliceblue|3n7|honeydew|1dd|azure|f|sandybrown|5469|wheat|1q37|beige|4kp|whitesmoke|p|mintcream|1z9|ghostwhite|46bp|salmon|25bn|antiquewhite|l7p|linen|zz|lightgoldenrodyellow|1yk|oldlace|46qc|red|1gka|magenta|73|fuchsia|0|deeppink|3v8|orangered|9kd|tomato|5zb|hotpink|19p|coral|49o|darkorange|2i8|lightsalmon|41m|orange|w6|lightpink|3i9|pink|1ze|gold|4dx|peachpuff|qh|navajowhite|s4|moccasin|16w|bisque|f|mistyrose|t|blanchedalmond|1d8|papayawhip|so|lavenderblush|80|seashell|zd|cornsilk|ku|lemonchiffon|dt|floralwhite|z|snow|a|yellow|sm|lightyellow|68|ivory|g|white|f'.split('|'),
  742. i = 0, len = names.length, color = 0, hexColor;
  743. for(; i < len; i += 2) {
  744. color += parseInt(names[i + 1], 36);
  745. hexColor = color.toString(16);
  746. Color.names[names[i]] = '#000000'.slice(0, -hexColor.length) + hexColor;
  747. }
  748. Color.prototype = {
  749. /**
  750. * @private
  751. */
  752. parse: function() {
  753. if( !this._color ) {
  754. var me = this,
  755. color = me.val,
  756. alpha, vLower, m, rgb;
  757. // RGB or RGBA colors
  758. if( m = color.match( Color.rgbOrRgbaRE ) ) {
  759. color = me.rgbToHex( +m[1], +m[2], +m[3] );
  760. alpha = m[5] ? +m[5] : 1;
  761. }
  762. // HSL or HSLA colors
  763. else if( m = color.match( Color.hslOrHslaRE ) ) {
  764. rgb = hsl2rgb( m[1], m[2], m[3] );
  765. color = me.rgbToHex( rgb.r, rgb.g, rgb.b );
  766. alpha = m[5] ? +m[5] : 1;
  767. }
  768. else {
  769. if( Color.names.hasOwnProperty( vLower = color.toLowerCase() ) ) {
  770. color = Color.names[vLower];
  771. }
  772. alpha = ( color === 'transparent' ? 0 : 1 );
  773. }
  774. me._color = color;
  775. me._alpha = alpha;
  776. }
  777. },
  778. /**
  779. * Converts RGB color channels to a hex value string
  780. */
  781. rgbToHex: function( r, g, b ) {
  782. return '#' + ( r < 16 ? '0' : '' ) + r.toString( 16 ) +
  783. ( g < 16 ? '0' : '' ) + g.toString( 16 ) +
  784. ( b < 16 ? '0' : '' ) + b.toString( 16 );
  785. },
  786. /**
  787. * Retrieve the value of the color in a format usable by IE natively. This will be the same as
  788. * the raw input value, except for rgb(a) and hsl(a) values which will be converted to a hex value.
  789. * @param {Element} el The context element, used to get 'currentColor' keyword value.
  790. * @return {string} Color value
  791. */
  792. colorValue: function( el ) {
  793. this.parse();
  794. return this._color === 'currentColor' ? PIE.getColor( el.currentStyle.color ).colorValue( el ) : this._color;
  795. },
  796. /**
  797. * Retrieve the value of the color in a normalized six-digit hex format.
  798. * @param el
  799. */
  800. hexValue: function( el ) {
  801. var color = this.colorValue( el );
  802. // At this point the color should be either a 3- or 6-digit hex value, or the string "transparent".
  803. function ch( i ) {
  804. return color.charAt( i );
  805. }
  806. // Fudge transparent to black - should be ignored anyway since its alpha will be 0
  807. if( color === 'transparent' ) {
  808. color = '#000';
  809. }
  810. // Expand 3-digit to 6-digit hex
  811. if( ch(0) === '#' && color.length === 4 ) {
  812. color = '#' + ch(1) + ch(1) + ch(2) + ch(2) + ch(3) + ch(3);
  813. }
  814. return color;
  815. },
  816. /**
  817. * Retrieve the alpha value of the color. Will be 1 for all values except for rgba values
  818. * with an alpha component.
  819. * @return {number} The alpha value, from 0 to 1.
  820. */
  821. alpha: function() {
  822. this.parse();
  823. return this._alpha;
  824. }
  825. };
  826. /**
  827. * Retrieve a PIE.Color instance for the given value. A shared singleton instance is returned for each unique value.
  828. * @param {string} val The CSS string representing the color. It is assumed that this will already have
  829. * been validated as a valid color syntax.
  830. */
  831. PIE.getColor = function(val) {
  832. return instances[ val ] || ( instances[ val ] = new Color( val ) );
  833. };
  834. return Color;
  835. })();/**
  836. * A tokenizer for CSS value strings.
  837. * @constructor
  838. * @param {string} css The CSS value string
  839. */
  840. PIE.Tokenizer = (function() {
  841. function Tokenizer( css ) {
  842. this.css = css;
  843. this.ch = 0;
  844. this.tokens = [];
  845. this.tokenIndex = 0;
  846. }
  847. /**
  848. * Enumeration of token type constants.
  849. * @enum {number}
  850. */
  851. var Type = Tokenizer.Type = {
  852. ANGLE: 1,
  853. CHARACTER: 2,
  854. COLOR: 4,
  855. DIMEN: 8,
  856. FUNCTION: 16,
  857. IDENT: 32,
  858. LENGTH: 64,
  859. NUMBER: 128,
  860. OPERATOR: 256,
  861. PERCENT: 512,
  862. STRING: 1024,
  863. URL: 2048
  864. };
  865. /**
  866. * A single token
  867. * @constructor
  868. * @param {number} type The type of the token - see PIE.Tokenizer.Type
  869. * @param {string} value The value of the token
  870. */
  871. Tokenizer.Token = function( type, value ) {
  872. this.tokenType = type;
  873. this.tokenValue = value;
  874. };
  875. Tokenizer.Token.prototype = {
  876. isLength: function() {
  877. return this.tokenType & Type.LENGTH || ( this.tokenType & Type.NUMBER && this.tokenValue === '0' );
  878. },
  879. isLengthOrPercent: function() {
  880. return this.isLength() || this.tokenType & Type.PERCENT;
  881. }
  882. };
  883. Tokenizer.prototype = {
  884. whitespace: /\s/,
  885. number: /^[\+\-]?(\d*\.)?\d+/,
  886. url: /^url\(\s*("([^"]*)"|'([^']*)'|([!#$%&*-~]*))\s*\)/i,
  887. ident: /^\-?[_a-z][\w-]*/i,
  888. string: /^("([^"]*)"|'([^']*)')/,
  889. operator: /^[\/,]/,
  890. hash: /^#[\w]+/,
  891. hashColor: /^#([\da-f]{6}|[\da-f]{3})/i,
  892. unitTypes: {
  893. 'px': Type.LENGTH, 'em': Type.LENGTH, 'ex': Type.LENGTH,
  894. 'mm': Type.LENGTH, 'cm': Type.LENGTH, 'in': Type.LENGTH,
  895. 'pt': Type.LENGTH, 'pc': Type.LENGTH,
  896. 'deg': Type.ANGLE, 'rad': Type.ANGLE, 'grad': Type.ANGLE
  897. },
  898. colorFunctions: {
  899. 'rgb': 1, 'rgba': 1, 'hsl': 1, 'hsla': 1
  900. },
  901. /**
  902. * Advance to and return the next token in the CSS string. If the end of the CSS string has
  903. * been reached, null will be returned.
  904. * @param {boolean} forget - if true, the token will not be stored for the purposes of backtracking with prev().
  905. * @return {PIE.Tokenizer.Token}
  906. */
  907. next: function( forget ) {
  908. var css, ch, firstChar, match, val,
  909. me = this;
  910. function newToken( type, value ) {
  911. var tok = new Tokenizer.Token( type, value );
  912. if( !forget ) {
  913. me.tokens.push( tok );
  914. me.tokenIndex++;
  915. }
  916. return tok;
  917. }
  918. function failure() {
  919. me.tokenIndex++;
  920. return null;
  921. }
  922. // In case we previously backed up, return the stored token in the next slot
  923. if( this.tokenIndex < this.tokens.length ) {
  924. return this.tokens[ this.tokenIndex++ ];
  925. }
  926. // Move past leading whitespace characters
  927. while( this.whitespace.test( this.css.charAt( this.ch ) ) ) {
  928. this.ch++;
  929. }
  930. if( this.ch >= this.css.length ) {
  931. return failure();
  932. }
  933. ch = this.ch;
  934. css = this.css.substring( this.ch );
  935. firstChar = css.charAt( 0 );
  936. switch( firstChar ) {
  937. case '#':
  938. if( match = css.match( this.hashColor ) ) {
  939. this.ch += match[0].length;
  940. return newToken( Type.COLOR, match[0] );
  941. }
  942. break;
  943. case '"':
  944. case "'":
  945. if( match = css.match( this.string ) ) {
  946. this.ch += match[0].length;
  947. return newToken( Type.STRING, match[2] || match[3] || '' );
  948. }
  949. break;
  950. case "/":
  951. case ",":
  952. this.ch++;
  953. return newToken( Type.OPERATOR, firstChar );
  954. case 'u':
  955. if( match = css.match( this.url ) ) {
  956. this.ch += match[0].length;
  957. return newToken( Type.URL, match[2] || match[3] || match[4] || '' );
  958. }
  959. }
  960. // Numbers and values starting with numbers
  961. if( match = css.match( this.number ) ) {
  962. val = match[0];
  963. this.ch += val.length;
  964. // Check if it is followed by a unit
  965. if( css.charAt( val.length ) === '%' ) {
  966. this.ch++;
  967. return newToken( Type.PERCENT, val + '%' );
  968. }
  969. if( match = css.substring( val.length ).match( this.ident ) ) {
  970. val += match[0];
  971. this.ch += match[0].length;
  972. return newToken( this.unitTypes[ match[0].toLowerCase() ] || Type.DIMEN, val );
  973. }
  974. // Plain ol' number
  975. return newToken( Type.NUMBER, val );
  976. }
  977. // Identifiers
  978. if( match = css.match( this.ident ) ) {
  979. val = match[0];
  980. this.ch += val.length;
  981. // Named colors
  982. if( val.toLowerCase() in PIE.Color.names || val === 'currentColor' || val === 'transparent' ) {
  983. return newToken( Type.COLOR, val );
  984. }
  985. // Functions
  986. if( css.charAt( val.length ) === '(' ) {
  987. this.ch++;
  988. // Color values in function format: rgb, rgba, hsl, hsla
  989. if( val.toLowerCase() in this.colorFunctions ) {
  990. function isNum( tok ) {
  991. return tok && tok.tokenType & Type.NUMBER;
  992. }
  993. function isNumOrPct( tok ) {
  994. return tok && ( tok.tokenType & ( Type.NUMBER | Type.PERCENT ) );
  995. }
  996. function isValue( tok, val ) {
  997. return tok && tok.tokenValue === val;
  998. }
  999. function next() {
  1000. return me.next( 1 );
  1001. }
  1002. if( ( val.charAt(0) === 'r' ? isNumOrPct( next() ) : isNum( next() ) ) &&
  1003. isValue( next(), ',' ) &&
  1004. isNumOrPct( next() ) &&
  1005. isValue( next(), ',' ) &&
  1006. isNumOrPct( next() ) &&
  1007. ( val === 'rgb' || val === 'hsa' || (
  1008. isValue( next(), ',' ) &&
  1009. isNum( next() )
  1010. ) ) &&
  1011. isValue( next(), ')' ) ) {
  1012. return newToken( Type.COLOR, this.css.substring( ch, this.ch ) );
  1013. }
  1014. return failure();
  1015. }
  1016. return newToken( Type.FUNCTION, val );
  1017. }
  1018. // Other identifier
  1019. return newToken( Type.IDENT, val );
  1020. }
  1021. // Standalone character
  1022. this.ch++;
  1023. return newToken( Type.CHARACTER, firstChar );
  1024. },
  1025. /**
  1026. * Determine whether there is another token
  1027. * @return {boolean}
  1028. */
  1029. hasNext: function() {
  1030. var next = this.next();
  1031. this.prev();
  1032. return !!next;
  1033. },
  1034. /**
  1035. * Back up and return the previous token
  1036. * @return {PIE.Tokenizer.Token}
  1037. */
  1038. prev: function() {
  1039. return this.tokens[ this.tokenIndex-- - 2 ];
  1040. },
  1041. /**
  1042. * Retrieve all the tokens in the CSS string
  1043. * @return {Array.<PIE.Tokenizer.Token>}
  1044. */
  1045. all: function() {
  1046. while( this.next() ) {}
  1047. return this.tokens;
  1048. },
  1049. /**
  1050. * Return a list of tokens from the current position until the given function returns
  1051. * true. The final token will not be included in the list.
  1052. * @param {function():boolean} func - test function
  1053. * @param {boolean} require - if true, then if the end of the CSS string is reached
  1054. * before the test function returns true, null will be returned instead of the
  1055. * tokens that have been found so far.
  1056. * @return {Array.<PIE.Tokenizer.Token>}
  1057. */
  1058. until: function( func, require ) {
  1059. var list = [], t, hit;
  1060. while( t = this.next() ) {
  1061. if( func( t ) ) {
  1062. hit = true;
  1063. this.prev();
  1064. break;
  1065. }
  1066. list.push( t );
  1067. }
  1068. return require && !hit ? null : list;
  1069. }
  1070. };
  1071. return Tokenizer;
  1072. })();/**
  1073. * Handles calculating, caching, and detecting changes to size and position of the element.
  1074. * @constructor
  1075. * @param {Element} el the target element
  1076. */
  1077. PIE.BoundsInfo = function( el ) {
  1078. this.targetElement = el;
  1079. };
  1080. PIE.BoundsInfo.prototype = {
  1081. _locked: 0,
  1082. /**
  1083. * Determines if the element's position has changed since the last update.
  1084. * TODO this does a simple getBoundingClientRect comparison for detecting the
  1085. * changes in position, which may not always be accurate; it's possible that
  1086. * an element will actually move relative to its positioning parent, but its position
  1087. * relative to the viewport will stay the same. Need to come up with a better way to
  1088. * track movement. The most accurate would be the same logic used in RootRenderer.updatePos()
  1089. * but that is a more expensive operation since it performs DOM walking, and we want this
  1090. * check to be as fast as possible. Perhaps introduce a -pie-* flag to trigger the slower
  1091. * but more accurate method?
  1092. */
  1093. positionChanged: function() {
  1094. var last = this._lastBounds,
  1095. bounds;
  1096. return !last || ( ( bounds = this.getBounds() ) && ( last.x !== bounds.x || last.y !== bounds.y ) );
  1097. },
  1098. sizeChanged: function() {
  1099. var last = this._lastBounds,
  1100. bounds;
  1101. return !last || ( ( bounds = this.getBounds() ) && ( last.w !== bounds.w || last.h !== bounds.h ) );
  1102. },
  1103. getLiveBounds: function() {
  1104. var el = this.targetElement,
  1105. rect = el.getBoundingClientRect(),
  1106. isIE9 = PIE.ieDocMode === 9,
  1107. isIE7 = PIE.ieVersion === 7,
  1108. width = rect.right - rect.left;
  1109. return {
  1110. x: rect.left,
  1111. y: rect.top,
  1112. // In some cases scrolling the page will cause IE9 to report incorrect dimensions
  1113. // in the rect returned by getBoundingClientRect, so we must query offsetWidth/Height
  1114. // instead. Also IE7 is inconsistent in using logical vs. device pixels in measurements
  1115. // so we must calculate the ratio and use it in certain places as a position adjustment.
  1116. w: isIE9 || isIE7 ? el.offsetWidth : width,
  1117. h: isIE9 || isIE7 ? el.offsetHeight : rect.bottom - rect.top,
  1118. logicalZoomRatio: ( isIE7 && width ) ? el.offsetWidth / width : 1
  1119. };
  1120. },
  1121. getBounds: function() {
  1122. return this._locked ?
  1123. ( this._lockedBounds || ( this._lockedBounds = this.getLiveBounds() ) ) :
  1124. this.getLiveBounds();
  1125. },
  1126. hasBeenQueried: function() {
  1127. return !!this._lastBounds;
  1128. },
  1129. lock: function() {
  1130. ++this._locked;
  1131. },
  1132. unlock: function() {
  1133. if( !--this._locked ) {
  1134. if( this._lockedBounds ) this._lastBounds = this._lockedBounds;
  1135. this._lockedBounds = null;
  1136. }
  1137. }
  1138. };
  1139. (function() {
  1140. function cacheWhenLocked( fn ) {
  1141. var uid = PIE.Util.getUID( fn );
  1142. return function() {
  1143. if( this._locked ) {
  1144. var cache = this._lockedValues || ( this._lockedValues = {} );
  1145. return ( uid in cache ) ? cache[ uid ] : ( cache[ uid ] = fn.call( this ) );
  1146. } else {
  1147. return fn.call( this );
  1148. }
  1149. }
  1150. }
  1151. PIE.StyleInfoBase = {
  1152. _locked: 0,
  1153. /**
  1154. * Create a new StyleInfo class, with the standard constructor, and augmented by
  1155. * the StyleInfoBase's members.
  1156. * @param proto
  1157. */
  1158. newStyleInfo: function( proto ) {
  1159. function StyleInfo( el ) {
  1160. this.targetElement = el;
  1161. this._lastCss = this.getCss();
  1162. }
  1163. PIE.merge( StyleInfo.prototype, PIE.StyleInfoBase, proto );
  1164. StyleInfo._propsCache = {};
  1165. return StyleInfo;
  1166. },
  1167. /**
  1168. * Get an object representation of the target CSS style, caching it for each unique
  1169. * CSS value string.
  1170. * @return {Object}
  1171. */
  1172. getProps: function() {
  1173. var css = this.getCss(),
  1174. cache = this.constructor._propsCache;
  1175. return css ? ( css in cache ? cache[ css ] : ( cache[ css ] = this.parseCss( css ) ) ) : null;
  1176. },
  1177. /**
  1178. * Get the raw CSS value for the target style
  1179. * @return {string}
  1180. */
  1181. getCss: cacheWhenLocked( function() {
  1182. var el = this.targetElement,
  1183. ctor = this.constructor,
  1184. s = el.style,
  1185. cs = el.currentStyle,
  1186. cssProp = this.cssProperty,
  1187. styleProp = this.styleProperty,
  1188. prefixedCssProp = ctor._prefixedCssProp || ( ctor._prefixedCssProp = PIE.CSS_PREFIX + cssProp ),
  1189. prefixedStyleProp = ctor._prefixedStyleProp || ( ctor._prefixedStyleProp = PIE.STYLE_PREFIX + styleProp.charAt(0).toUpperCase() + styleProp.substring(1) );
  1190. return s[ prefixedStyleProp ] || cs.getAttribute( prefixedCssProp ) || s[ styleProp ] || cs.getAttribute( cssProp );
  1191. } ),
  1192. /**
  1193. * Determine whether the target CSS style is active.
  1194. * @return {boolean}
  1195. */
  1196. isActive: cacheWhenLocked( function() {
  1197. return !!this.getProps();
  1198. } ),
  1199. /**
  1200. * Determine whether the target CSS style has changed since the last time it was used.
  1201. * @return {boolean}
  1202. */
  1203. changed: cacheWhenLocked( function() {
  1204. var currentCss = this.getCss(),
  1205. changed = currentCss !== this._lastCss;
  1206. this._lastCss = currentCss;
  1207. return changed;
  1208. } ),
  1209. cacheWhenLocked: cacheWhenLocked,
  1210. lock: function() {
  1211. ++this._locked;
  1212. },
  1213. unlock: function() {
  1214. if( !--this._locked ) {
  1215. delete this._lockedValues;
  1216. }
  1217. }
  1218. };
  1219. })();/**
  1220. * Handles parsing, caching, and detecting changes to background (and -pie-background) CSS
  1221. * @constructor
  1222. * @param {Element} el the target element
  1223. */
  1224. PIE.BackgroundStyleInfo = PIE.StyleInfoBase.newStyleInfo( {
  1225. cssProperty: PIE.CSS_PREFIX + 'background',
  1226. styleProperty: PIE.STYLE_PREFIX + 'Background',
  1227. attachIdents: { 'scroll':1, 'fixed':1, 'local':1 },
  1228. repeatIdents: { 'repeat-x':1, 'repeat-y':1, 'repeat':1, 'no-repeat':1 },
  1229. originAndClipIdents: { 'padding-box':1, 'border-box':1, 'content-box':1 },
  1230. positionIdents: { 'top':1, 'right':1, 'bottom':1, 'left':1, 'center':1 },
  1231. sizeIdents: { 'contain':1, 'cover':1 },
  1232. tbIdents: { 'top': 1, 'bottom': 1 },
  1233. lrIdents: { 'left': 1, 'right': 1 },
  1234. propertyNames: {
  1235. CLIP: 'backgroundClip',
  1236. COLOR: 'backgroundColor',
  1237. IMAGE: 'backgroundImage',
  1238. ORIGIN: 'backgroundOrigin',
  1239. POSITION: 'backgroundPosition',
  1240. REPEAT: 'backgroundRepeat',
  1241. SIZE: 'backgroundSize'
  1242. },
  1243. /**
  1244. * For background styles, we support the -pie-background property but fall back to the standard
  1245. * backround* properties. The reason we have to use the prefixed version is that IE natively
  1246. * parses the standard properties and if it sees something it doesn't know how to parse, for example
  1247. * multiple values or gradient definitions, it will throw that away and not make it available through
  1248. * currentStyle.
  1249. *
  1250. * Format of return object:
  1251. * {
  1252. * color: <PIE.Color>,
  1253. * colorClip: <'border-box' | 'padding-box'>,
  1254. * bgImages: [
  1255. * {
  1256. * imgType: 'image',
  1257. * imgUrl: 'image.png',
  1258. * imgRepeat: <'no-repeat' | 'repeat-x' | 'repeat-y' | 'repeat'>,
  1259. * bgPosition: <PIE.BgPosition>,
  1260. * bgAttachment: <'scroll' | 'fixed' | 'local'>,
  1261. * bgOrigin: <'border-box' | 'padding-box' | 'content-box'>,
  1262. * bgClip: <'border-box' | 'padding-box'>,
  1263. * bgSize: <PIE.BgSize>,
  1264. * origString: 'url(img.png) no-repeat top left'
  1265. * },
  1266. * {
  1267. * imgType: 'linear-gradient',
  1268. * gradientTo: [<'top' | 'bottom'>, <'left' | 'right'>?],
  1269. * angle: <PIE.Angle>,
  1270. * stops: [
  1271. * { color: <PIE.Color>, offset: <PIE.Length> },
  1272. * { color: <PIE.Color>, offset: <PIE.Length> }, ...
  1273. * ]
  1274. * }
  1275. * ]
  1276. * }
  1277. * @param {String} css
  1278. * @override
  1279. */
  1280. parseCss: function( css ) {
  1281. var el = this.targetElement,
  1282. cs = el.currentStyle,
  1283. tokenizer, token, image,
  1284. tok_type = PIE.Tokenizer.Type,
  1285. type_operator = tok_type.OPERATOR,
  1286. type_ident = tok_type.IDENT,
  1287. type_color = tok_type.COLOR,
  1288. tokType, tokVal,
  1289. beginCharIndex = 0,
  1290. positionIdents = this.positionIdents,
  1291. gradient, stop, width, height, gradientTo, len, tbIdents, lrIdents,
  1292. props = { bgImages: [] };
  1293. function isBgPosToken( token ) {
  1294. return token && token.isLengthOrPercent() || ( token.tokenType & type_ident && token.tokenValue in positionIdents );
  1295. }
  1296. function sizeToken( token ) {
  1297. return token && ( ( token.isLengthOrPercent() && PIE.getLength( token.tokenValue ) ) || ( token.tokenValue === 'auto' && 'auto' ) );
  1298. }
  1299. // If the CSS3-specific -pie-background property is present, parse it
  1300. if( this.getCss3() ) {
  1301. tokenizer = new PIE.Tokenizer( css );
  1302. image = {};
  1303. while( token = tokenizer.next() ) {
  1304. tokType = token.tokenType;
  1305. tokVal = token.tokenValue;
  1306. if( !image.imgType && tokType & tok_type.FUNCTION && tokVal === 'linear-gradient' ) {
  1307. gradient = { stops: [], imgType: tokVal };
  1308. stop = {};
  1309. while( token = tokenizer.next() ) {
  1310. tokType = token.tokenType;
  1311. tokVal = token.tokenValue;
  1312. // If we reached the end of the function and had at least 2 stops, flush the info
  1313. if( tokType & tok_type.CHARACTER && tokVal === ')' ) {
  1314. if( stop.color ) {
  1315. gradient.stops.push( stop );
  1316. }
  1317. if( gradient.stops.length > 1 ) {
  1318. PIE.merge( image, gradient );
  1319. }
  1320. break;
  1321. }
  1322. // Color stop - must start with color
  1323. if( tokType & type_color ) {
  1324. // if we already have an angle/position, make sure that the previous token was a comma
  1325. if( gradient.angle || gradient.gradientTo ) {
  1326. token = tokenizer.prev();
  1327. if( token.tokenType !== type_operator ) {
  1328. break; //fail
  1329. }
  1330. tokenizer.next();
  1331. }
  1332. stop = {
  1333. color: PIE.getColor( tokVal )
  1334. };
  1335. // check for offset following color
  1336. token = tokenizer.next();
  1337. if( token.isLengthOrPercent() ) {
  1338. stop.offset = PIE.getLength( token.tokenValue );
  1339. } else {
  1340. tokenizer.prev();
  1341. }
  1342. }
  1343. // Angle - can only appear in first spot
  1344. else if( tokType & tok_type.ANGLE && !gradient.angle && !gradient.gradientTo && !stop.color && !gradient.stops.length ) {
  1345. gradient.angle = new PIE.Angle( token.tokenValue );
  1346. }
  1347. // "to <side-or-corner>" - can only appear in first spot
  1348. else if( tokType & tok_type.IDENT && tokVal === 'to' && !gradient.gradientTo && !gradient.angle && !stop.color && !gradient.stops.length ) {
  1349. tbIdents = this.tbIdents;
  1350. lrIdents = this.lrIdents;
  1351. gradientTo = tokenizer.until( function( t ) {
  1352. return !(t && t.tokenType & tok_type.IDENT && ( t.tokenValue in tbIdents || t.tokenValue in lrIdents ));
  1353. } );
  1354. len = gradientTo.length;
  1355. gradientTo = [ gradientTo[0] && gradientTo[0].tokenValue, gradientTo[1] && gradientTo[1].tokenValue ];
  1356. // bail unless there are 1 or 2 values, or if the 2 values are from the same pair of sides
  1357. if ( len < 1 || len > 2 || ( len > 1 && (
  1358. ( gradientTo[0] in tbIdents && gradientTo[1] in tbIdents ) ||
  1359. ( gradientTo[0] in lrIdents && gradientTo[1] in lrIdents )
  1360. ) ) ) {
  1361. break;
  1362. }
  1363. gradient.gradientTo = gradientTo;
  1364. }
  1365. else if( tokType & type_operator && tokVal === ',' ) {
  1366. if( stop.color ) {
  1367. gradient.stops.push( stop );
  1368. stop = {};
  1369. }
  1370. }
  1371. else {
  1372. // Found something we didn't recognize; fail without adding image
  1373. break;
  1374. }
  1375. }
  1376. }
  1377. else if( !image.imgType && tokType & tok_type.URL ) {
  1378. image.imgUrl = tokVal;
  1379. image.imgType = 'image';
  1380. }
  1381. else if( isBgPosToken( token ) && !image.bgPosition ) {
  1382. tokenizer.prev();
  1383. image.bgPosition = new PIE.BgPosition(
  1384. tokenizer.until( function( t ) {
  1385. return !isBgPosToken( t );
  1386. }, false )
  1387. );
  1388. }
  1389. else if( tokType & type_ident ) {
  1390. if( tokVal in this.repeatIdents && !image.imgRepeat ) {
  1391. image.imgRepeat = tokVal;
  1392. }
  1393. else if( tokVal in this.originAndClipIdents && !image.bgOrigin ) {
  1394. image.bgOrigin = tokVal;
  1395. if( ( token = tokenizer.next() ) && ( token.tokenType & type_ident ) &&
  1396. token.tokenValue in this.originAndClipIdents ) {
  1397. image.bgClip = token.tokenValue;
  1398. } else {
  1399. image.bgClip = tokVal;
  1400. tokenizer.prev();
  1401. }
  1402. }
  1403. else if( tokVal in this.attachIdents && !image.bgAttachment ) {
  1404. image.bgAttachment = tokVal;
  1405. }
  1406. else {
  1407. return null;
  1408. }
  1409. }
  1410. else if( tokType & type_color && !props.color ) {
  1411. props.color = PIE.getColor( tokVal );
  1412. }
  1413. else if( tokType & type_operator && tokVal === '/' && !image.bgSize && image.bgPosition ) {
  1414. // background size
  1415. token = tokenizer.next();
  1416. if( token.tokenType & type_ident && token.tokenValue in this.sizeIdents ) {
  1417. image.bgSize = new PIE.BgSize( token.tokenValue );
  1418. }
  1419. else if( width = sizeToken( token ) ) {
  1420. height = sizeToken( tokenizer.next() );
  1421. if ( !height ) {
  1422. height = width;
  1423. tokenizer.prev();
  1424. }
  1425. image.bgSize = new PIE.BgSize( width, height );
  1426. }
  1427. else {
  1428. return null;
  1429. }
  1430. }
  1431. // new layer
  1432. else if( tokType & type_operator && tokVal === ',' && image.imgType ) {
  1433. image.origString = css.substring( beginCharIndex, tokenizer.ch - 1 );
  1434. beginCharIndex = tokenizer.ch;
  1435. props.bgImages.push( image );
  1436. image = {};
  1437. }
  1438. else {
  1439. // Found something unrecognized; chuck everything
  1440. return null;
  1441. }
  1442. }
  1443. // leftovers
  1444. if( image.imgType ) {
  1445. image.origString = css.substring( beginCharIndex );
  1446. props.bgImages.push( image );
  1447. }
  1448. props.colorClip = image.bgClip;
  1449. }
  1450. // Otherwise, use the standard background properties; let IE give us the values rather than parsing them
  1451. else {
  1452. this.withActualBg( PIE.ieDocMode < 9 ?
  1453. function() {
  1454. var propNames = this.propertyNames,
  1455. posX = cs[propNames.POSITION + 'X'],
  1456. posY = cs[propNames.POSITION + 'Y'],
  1457. img = cs[propNames.IMAGE],
  1458. color = cs[propNames.COLOR];
  1459. if( color !== 'transparent' ) {
  1460. props.color = PIE.getColor( color )
  1461. }
  1462. if( img !== 'none' ) {
  1463. props.bgImages = [ {
  1464. imgType: 'image',
  1465. imgUrl: new PIE.Tokenizer( img ).next().tokenValue,
  1466. imgRepeat: cs[propNames.REPEAT],
  1467. bgPosition: new PIE.BgPosition( new PIE.Tokenizer( posX + ' ' + posY ).all() )
  1468. } ];
  1469. }
  1470. } :
  1471. function() {
  1472. var propNames = this.propertyNames,
  1473. splitter = /\s*,\s*/,
  1474. images = cs[propNames.IMAGE].split( splitter ),
  1475. color = cs[propNames.COLOR],
  1476. repeats, positions, origins, clips, sizes, i, len, image, sizeParts;
  1477. if( color !== 'transparent' ) {
  1478. props.color = PIE.getColor( color )
  1479. }
  1480. len = images.length;
  1481. if( len && images[0] !== 'none' ) {
  1482. repeats = cs[propNames.REPEAT].split( splitter );
  1483. positions = cs[propNames.POSITION].split( splitter );
  1484. origins = cs[propNames.ORIGIN].split( splitter );
  1485. clips = cs[propNames.CLIP].split( splitter );
  1486. sizes = cs[propNames.SIZE].split( splitter );
  1487. props.bgImages = [];
  1488. for( i = 0; i < len; i++ ) {
  1489. image = images[ i ];
  1490. if( image && image !== 'none' ) {
  1491. sizeParts = sizes[i].split( ' ' );
  1492. props.bgImages.push( {
  1493. origString: image + ' ' + repeats[ i ] + ' ' + positions[ i ] + ' / ' + sizes[ i ] + ' ' +
  1494. origins[ i ] + ' ' + clips[ i ],
  1495. imgType: 'image',
  1496. imgUrl: new PIE.Tokenizer( image ).next().tokenValue,
  1497. imgRepeat: repeats[ i ],
  1498. bgPosition: new PIE.BgPosition( new PIE.Tokenizer( positions[ i ] ).all() ),
  1499. bgOrigin: origins[ i ],
  1500. bgClip: clips[ i ],
  1501. bgSize: new PIE.BgSize( sizeParts[ 0 ], sizeParts[ 1 ] )
  1502. } );
  1503. }
  1504. }
  1505. }
  1506. }
  1507. );
  1508. }
  1509. return ( props.color || props.bgImages[0] ) ? props : null;
  1510. },
  1511. /**
  1512. * Execute a function with the actual background styles (not overridden with runtimeStyle
  1513. * properties set by the renderers) available via currentStyle.
  1514. * @param fn
  1515. */
  1516. withActualBg: function( fn ) {
  1517. var isIE9 = PIE.ieDocMode > 8,
  1518. propNames = this.propertyNames,
  1519. rs = this.targetElement.runtimeStyle,
  1520. rsImage = rs[propNames.IMAGE],
  1521. rsColor = rs[propNames.COLOR],
  1522. rsRepeat = rs[propNames.REPEAT],
  1523. rsClip, rsOrigin, rsSize, rsPosition, ret;
  1524. if( rsImage ) rs[propNames.IMAGE] = '';
  1525. if( rsColor ) rs[propNames.COLOR] = '';
  1526. if( rsRepeat ) rs[propNames.REPEAT] = '';
  1527. if( isIE9 ) {
  1528. rsClip = rs[propNames.CLIP];
  1529. rsOrigin = rs[propNames.ORIGIN];
  1530. rsPosition = rs[propNames.POSITION];
  1531. rsSize = rs[propNames.SIZE];
  1532. if( rsClip ) rs[propNames.CLIP] = '';
  1533. if( rsOrigin ) rs[propNames.ORIGIN] = '';
  1534. if( rsPosition ) rs[propNames.POSITION] = '';
  1535. if( rsSize ) rs[propNames.SIZE] = '';
  1536. }
  1537. ret = fn.call( this );
  1538. if( rsImage ) rs[propNames.IMAGE] = rsImage;
  1539. if( rsColor ) rs[propNames.COLOR] = rsColor;
  1540. if( rsRepeat ) rs[propNames.REPEAT] = rsRepeat;
  1541. if( isIE9 ) {
  1542. if( rsClip ) rs[propNames.CLIP] = rsClip;
  1543. if( rsOrigin ) rs[propNames.ORIGIN] = rsOrigin;
  1544. if( rsPosition ) rs[propNames.POSITION] = rsPosition;
  1545. if( rsSize ) rs[propNames.SIZE] = rsSize;
  1546. }
  1547. return ret;
  1548. },
  1549. getCss: PIE.StyleInfoBase.cacheWhenLocked( function() {
  1550. return this.getCss3() ||
  1551. this.withActualBg( function() {
  1552. var cs = this.targetElement.currentStyle,
  1553. propNames = this.propertyNames;
  1554. return cs[propNames.COLOR] + ' ' + cs[propNames.IMAGE] + ' ' + cs[propNames.REPEAT] + ' ' +
  1555. cs[propNames.POSITION + 'X'] + ' ' + cs[propNames.POSITION + 'Y'];
  1556. } );
  1557. } ),
  1558. getCss3: PIE.StyleInfoBase.cacheWhenLocked( function() {
  1559. var el = this.targetElement;
  1560. return el.style[ this.styleProperty ] || el.currentStyle.getAttribute( this.cssProperty );
  1561. } ),
  1562. /**
  1563. * For a given background-origin value, return the dimensions of the background area.
  1564. * @param {String} bgOrigin
  1565. * @param {PIE.BoundsInfo} boundsInfo
  1566. * @param {PIE.BorderStyleInfo} borderInfo
  1567. */
  1568. getBgAreaSize: function( bgOrigin, boundsInfo, borderInfo, paddingInfo ) {
  1569. var el = this.targetElement,
  1570. bounds = boundsInfo.getBounds(),
  1571. w = bounds.w,
  1572. h = bounds.h,
  1573. borders, paddings;
  1574. if( bgOrigin !== 'border-box' ) {
  1575. borders = borderInfo.getProps();
  1576. if( borders && ( borders = borders.widths ) ) {
  1577. w -= borders[ 'l' ].pixels( el ) + borders[ 'l' ].pixels( el );
  1578. h -= borders[ 't' ].pixels( el ) + borders[ 'b' ].pixels( el );
  1579. }
  1580. }
  1581. if ( bgOrigin === 'content-box' ) {
  1582. paddings = paddingInfo.getProps();
  1583. if ( paddings ) {
  1584. w -= paddings[ 'l' ].pixels( el ) + paddings[ 'l' ].pixels( el );
  1585. h -= paddings[ 't' ].pixels( el ) + paddings[ 'b' ].pixels( el );
  1586. }
  1587. }
  1588. return { w: w, h: h };
  1589. },
  1590. /**
  1591. * Tests if style.PiePngFix or the -pie-png-fix property is set to true in IE6.
  1592. */
  1593. isPngFix: function() {
  1594. var val = 0, el;
  1595. if( PIE.ieVersion < 7 ) {
  1596. el = this.targetElement;
  1597. val = ( '' + ( el.style[ PIE.STYLE_PREFIX + 'PngFix' ] || el.currentStyle.getAttribute( PIE.CSS_PREFIX + 'png-fix' ) ) === 'true' );
  1598. }
  1599. return val;
  1600. },
  1601. /**
  1602. * The isActive logic is slightly different, because getProps() always returns an object
  1603. * even if it is just falling back to the native background properties. But we only want
  1604. * to report is as being "active" if either the -pie-background override property is present
  1605. * and parses successfully or '-pie-png-fix' is set to true in IE6.
  1606. */
  1607. isActive: PIE.StyleInfoBase.cacheWhenLocked( function() {
  1608. return (this.getCss3() || this.isPngFix()) && !!this.getProps();
  1609. } )
  1610. } );/**
  1611. * Handles parsing, caching, and detecting changes to border CSS
  1612. * @constructor
  1613. * @param {Element} el the target element
  1614. */
  1615. PIE.BorderStyleInfo = PIE.StyleInfoBase.newStyleInfo( {
  1616. sides: [ 'Top', 'Right', 'Bottom', 'Left' ],
  1617. namedWidths: {
  1618. 'thin': '1px',
  1619. 'medium': '3px',
  1620. 'thick': '5px'
  1621. },
  1622. parseCss: function( css ) {
  1623. var w = {},
  1624. s = {},
  1625. c = {},
  1626. active = false,
  1627. colorsSame = true,
  1628. stylesSame = true,
  1629. widthsSame = true;
  1630. this.withActualBorder( function() {
  1631. var el = this.targetElement,
  1632. cs = el.currentStyle,
  1633. i = 0,
  1634. style, color, width, lastStyle, lastColor, lastWidth, side, ltr;
  1635. for( ; i < 4; i++ ) {
  1636. side = this.sides[ i ];
  1637. ltr = side.charAt(0).toLowerCase();
  1638. style = s[ ltr ] = cs[ 'border' + side + 'Style' ];
  1639. color = cs[ 'border' + side + 'Color' ];
  1640. width = cs[ 'border' + side + 'Width' ];
  1641. if( i > 0 ) {
  1642. if( style !== lastStyle ) { stylesSame = false; }
  1643. if( color !== lastColor ) { colorsSame = false; }
  1644. if( width !== lastWidth ) { widthsSame = false; }
  1645. }
  1646. lastStyle = style;
  1647. lastColor = color;
  1648. lastWidth = width;
  1649. c[ ltr ] = PIE.getColor( color );
  1650. width = w[ ltr ] = PIE.getLength( s[ ltr ] === 'none' ? '0' : ( this.namedWidths[ width ] || width ) );
  1651. if( width.pixels( this.targetElement ) > 0 ) {
  1652. active = true;
  1653. }
  1654. }
  1655. } );
  1656. return active ? {
  1657. widths: w,
  1658. styles: s,
  1659. colors: c,
  1660. widthsSame: widthsSame,
  1661. colorsSame: colorsSame,
  1662. stylesSame: stylesSame
  1663. } : null;
  1664. },
  1665. getCss: PIE.StyleInfoBase.cacheWhenLocked( function() {
  1666. var el = this.targetElement,
  1667. cs = el.currentStyle,
  1668. css;
  1669. // Don't redraw or hide borders for cells in border-collapse:collapse tables
  1670. if( !( el.tagName in PIE.tableCellTags && el.offsetParent.currentStyle.borderCollapse === 'collapse' ) ) {
  1671. this.withActualBorder( function() {
  1672. css = cs.borderWidth + '|' + cs.borderStyle + '|' + cs.borderColor;
  1673. } );
  1674. }
  1675. return css;
  1676. } ),
  1677. /**
  1678. * Execute a function with the actual border styles (not overridden with runtimeStyle
  1679. * properties set by the renderers) available via currentStyle.
  1680. * @param fn
  1681. */
  1682. withActualBorder: function( fn ) {
  1683. var rs = this.targetElement.runtimeStyle,
  1684. rsWidth = rs.borderWidth,
  1685. rsColor = rs.borderColor,
  1686. ret;
  1687. if( rsWidth ) rs.borderWidth = '';
  1688. if( rsColor ) rs.borderColor = '';
  1689. ret = fn.call( this );
  1690. if( rsWidth ) rs.borderWidth = rsWidth;
  1691. if( rsColor ) rs.borderColor = rsColor;
  1692. return ret;
  1693. }
  1694. } );
  1695. /**
  1696. * Handles parsing, caching, and detecting changes to border-radius CSS
  1697. * @constructor
  1698. * @param {Element} el the target element
  1699. */
  1700. (function() {
  1701. PIE.BorderRadiusStyleInfo = PIE.StyleInfoBase.newStyleInfo( {
  1702. cssProperty: 'border-radius',
  1703. styleProperty: 'borderRadius',
  1704. parseCss: function( css ) {
  1705. var p = null, x, y,
  1706. tokenizer, token, length,
  1707. hasNonZero = false;
  1708. if( css ) {
  1709. tokenizer = new PIE.Tokenizer( css );
  1710. function collectLengths() {
  1711. var arr = [], num;
  1712. while( ( token = tokenizer.next() ) && token.isLengthOrPercent() ) {
  1713. length = PIE.getLength( token.tokenValue );
  1714. num = length.getNumber();
  1715. if( num < 0 ) {
  1716. return null;
  1717. }
  1718. if( num > 0 ) {
  1719. hasNonZero = true;
  1720. }
  1721. arr.push( length );
  1722. }
  1723. return arr.length > 0 && arr.length < 5 ? {
  1724. 'tl': arr[0],
  1725. 'tr': arr[1] || arr[0],
  1726. 'br': arr[2] || arr[0],
  1727. 'bl': arr[3] || arr[1] || arr[0]
  1728. } : null;
  1729. }
  1730. // Grab the initial sequence of lengths
  1731. if( x = collectLengths() ) {
  1732. // See if there is a slash followed by more lengths, for the y-axis radii
  1733. if( token ) {
  1734. if( token.tokenType & PIE.Tokenizer.Type.OPERATOR && token.tokenValue === '/' ) {
  1735. y = collectLengths();
  1736. }
  1737. } else {
  1738. y = x;
  1739. }
  1740. // Treat all-zero values the same as no value
  1741. if( hasNonZero && x && y ) {
  1742. p = { x: x, y : y };
  1743. }
  1744. }
  1745. }
  1746. return p;
  1747. }
  1748. } );
  1749. var zero = PIE.getLength( '0' ),
  1750. zeros = { 'tl': zero, 'tr': zero, 'br': zero, 'bl': zero };
  1751. PIE.BorderRadiusStyleInfo.ALL_ZERO = { x: zeros, y: zeros };
  1752. })();/**
  1753. * Handles parsing, caching, and detecting changes to border-image CSS
  1754. * @constructor
  1755. * @param {Element} el the target element
  1756. */
  1757. PIE.BorderImageStyleInfo = PIE.StyleInfoBase.newStyleInfo( {
  1758. cssProperty: 'border-image',
  1759. styleProperty: 'borderImage',
  1760. repeatIdents: { 'stretch':1, 'round':1, 'repeat':1, 'space':1 },
  1761. parseCss: function( css ) {
  1762. var p = null, tokenizer, token, type, value,
  1763. slices, widths, outsets,
  1764. slashCount = 0,
  1765. Type = PIE.Tokenizer.Type,
  1766. IDENT = Type.IDENT,
  1767. NUMBER = Type.NUMBER,
  1768. PERCENT = Type.PERCENT;
  1769. if( css ) {
  1770. tokenizer = new PIE.Tokenizer( css );
  1771. p = {};
  1772. function isSlash( token ) {
  1773. return token && ( token.tokenType & Type.OPERATOR ) && ( token.tokenValue === '/' );
  1774. }
  1775. function isFillIdent( token ) {
  1776. return token && ( token.tokenType & IDENT ) && ( token.tokenValue === 'fill' );
  1777. }
  1778. function collectSlicesEtc() {
  1779. slices = tokenizer.until( function( tok ) {
  1780. return !( tok.tokenType & ( NUMBER | PERCENT ) );
  1781. } );
  1782. if( isFillIdent( tokenizer.next() ) && !p.fill ) {
  1783. p.fill = true;
  1784. } else {
  1785. tokenizer.prev();
  1786. }
  1787. if( isSlash( tokenizer.next() ) ) {
  1788. slashCount++;
  1789. widths = tokenizer.until( function( token ) {
  1790. return !token.isLengthOrPercent() && !( ( token.tokenType & IDENT ) && token.tokenValue === 'auto' );
  1791. } );
  1792. if( isSlash( tokenizer.next() ) ) {
  1793. slashCount++;
  1794. outsets = tokenizer.until( function( token ) {
  1795. return !token.isLength();
  1796. } );
  1797. }
  1798. } else {
  1799. tokenizer.prev();
  1800. }
  1801. }
  1802. while( token = tokenizer.next() ) {
  1803. type = token.tokenType;
  1804. value = token.tokenValue;
  1805. // Numbers and/or 'fill' keyword: slice values. May be followed optionally by width values, followed optionally by outset values
  1806. if( type & ( NUMBER | PERCENT ) && !slices ) {
  1807. tokenizer.prev();
  1808. collectSlicesEtc();
  1809. }
  1810. else if( isFillIdent( token ) && !p.fill ) {
  1811. p.fill = true;
  1812. collectSlicesEtc();
  1813. }
  1814. // Idents: one or values for 'repeat'
  1815. else if( ( type & IDENT ) && this.repeatIdents[value] && !p.repeat ) {
  1816. p.repeat = { h: value };
  1817. if( token = tokenizer.next() ) {
  1818. if( ( token.tokenType & IDENT ) && this.repeatIdents[token.tokenValue] ) {
  1819. p.repeat.v = token.tokenValue;
  1820. } else {
  1821. tokenizer.prev();
  1822. }
  1823. }
  1824. }
  1825. // URL of the image
  1826. else if( ( type & Type.URL ) && !p.src ) {
  1827. p.src = value;
  1828. }
  1829. // Found something unrecognized; exit.
  1830. else {
  1831. return null;
  1832. }
  1833. }
  1834. // Validate what we collected
  1835. if( !p.src || !slices || slices.length < 1 || slices.length > 4 ||
  1836. ( widths && widths.length > 4 ) || ( slashCount === 1 && widths.length < 1 ) ||
  1837. ( outsets && outsets.length > 4 ) || ( slashCount === 2 && outsets.length < 1 ) ) {
  1838. return null;
  1839. }
  1840. // Fill in missing values
  1841. if( !p.repeat ) {
  1842. p.repeat = { h: 'stretch' };
  1843. }
  1844. if( !p.repeat.v ) {
  1845. p.repeat.v = p.repeat.h;
  1846. }
  1847. function distributeSides( tokens, convertFn ) {
  1848. return {
  1849. 't': convertFn( tokens[0] ),
  1850. 'r': convertFn( tokens[1] || tokens[0] ),
  1851. 'b': convertFn( tokens[2] || tokens[0] ),
  1852. 'l': convertFn( tokens[3] || tokens[1] || tokens[0] )
  1853. };
  1854. }
  1855. p.slice = distributeSides( slices, function( tok ) {
  1856. return PIE.getLength( ( tok.tokenType & NUMBER ) ? tok.tokenValue + 'px' : tok.tokenValue );
  1857. } );
  1858. if( widths && widths[0] ) {
  1859. p.widths = distributeSides( widths, function( tok ) {
  1860. return tok.isLengthOrPercent() ? PIE.getLength( tok.tokenValue ) : tok.tokenValue;
  1861. } );
  1862. }
  1863. if( outsets && outsets[0] ) {
  1864. p.outset = distributeSides( outsets, function( tok ) {
  1865. return tok.isLength() ? PIE.getLength( tok.tokenValue ) : tok.tokenValue;
  1866. } );
  1867. }
  1868. }
  1869. return p;
  1870. }
  1871. } );/**
  1872. * Handles parsing, caching, and detecting changes to box-shadow CSS
  1873. * @constructor
  1874. * @param {Element} el the target element
  1875. */
  1876. PIE.BoxShadowStyleInfo = PIE.StyleInfoBase.newStyleInfo( {
  1877. cssProperty: 'box-shadow',
  1878. styleProperty: 'boxShadow',
  1879. parseCss: function( css ) {
  1880. var props,
  1881. getLength = PIE.getLength,
  1882. Type = PIE.Tokenizer.Type,
  1883. tokenizer;
  1884. if( css ) {
  1885. tokenizer = new PIE.Tokenizer( css );
  1886. props = { outset: [], inset: [] };
  1887. function parseItem() {
  1888. var token, type, value, color, lengths, inset, len;
  1889. while( token = tokenizer.next() ) {
  1890. value = token.tokenValue;
  1891. type = token.tokenType;
  1892. if( type & Type.OPERATOR && value === ',' ) {
  1893. break;
  1894. }
  1895. else if( token.isLength() && !lengths ) {
  1896. tokenizer.prev();
  1897. lengths = tokenizer.until( function( token ) {
  1898. return !token.isLength();
  1899. } );
  1900. }
  1901. else if( type & Type.COLOR && !color ) {
  1902. color = value;
  1903. }
  1904. else if( type & Type.IDENT && value === 'inset' && !inset ) {
  1905. inset = true;
  1906. }
  1907. else { //encountered an unrecognized token; fail.
  1908. return false;
  1909. }
  1910. }
  1911. len = lengths && lengths.length;
  1912. if( len > 1 && len < 5 ) {
  1913. ( inset ? props.inset : props.outset ).push( {
  1914. xOffset: getLength( lengths[0].tokenValue ),
  1915. yOffset: getLength( lengths[1].tokenValue ),
  1916. blur: getLength( lengths[2] ? lengths[2].tokenValue : '0' ),
  1917. spread: getLength( lengths[3] ? lengths[3].tokenValue : '0' ),
  1918. color: PIE.getColor( color || 'currentColor' )
  1919. } );
  1920. return true;
  1921. }
  1922. return false;
  1923. }
  1924. while( parseItem() ) {}
  1925. }
  1926. return props && ( props.inset.length || props.outset.length ) ? props : null;
  1927. }
  1928. } );
  1929. /**
  1930. * Handles parsing, caching, and detecting changes to padding CSS
  1931. * @constructor
  1932. * @param {Element} el the target element
  1933. */
  1934. PIE.PaddingStyleInfo = PIE.StyleInfoBase.newStyleInfo( {
  1935. parseCss: function( css ) {
  1936. var tokenizer = new PIE.Tokenizer( css ),
  1937. arr = [],
  1938. token;
  1939. while( ( token = tokenizer.next() ) && token.isLengthOrPercent() ) {
  1940. arr.push( PIE.getLength( token.tokenValue ) );
  1941. }
  1942. return arr.length > 0 && arr.length < 5 ? {
  1943. 't': arr[0],
  1944. 'r': arr[1] || arr[0],
  1945. 'b': arr[2] || arr[0],
  1946. 'l': arr[3] || arr[1] || arr[0]
  1947. } : null;
  1948. },
  1949. getCss: PIE.StyleInfoBase.cacheWhenLocked( function() {
  1950. var el = this.targetElement,
  1951. rs = el.runtimeStyle,
  1952. rsPadding = rs.padding,
  1953. padding;
  1954. if( rsPadding ) rs.padding = '';
  1955. padding = el.currentStyle.padding;
  1956. if( rsPadding ) rs.padding = rsPadding;
  1957. return padding;
  1958. } )
  1959. } );
  1960. /**
  1961. * Retrieves the state of the element's visibility and display
  1962. * @constructor
  1963. * @param {Element} el the target element
  1964. */
  1965. PIE.VisibilityStyleInfo = PIE.StyleInfoBase.newStyleInfo( {
  1966. getCss: PIE.StyleInfoBase.cacheWhenLocked( function() {
  1967. var el = this.targetElement,
  1968. rs = el.runtimeStyle,
  1969. cs = el.currentStyle,
  1970. rsVis = rs.visibility,
  1971. ret;
  1972. rs.visibility = '';
  1973. ret = cs.visibility + '|' + cs.display;
  1974. rs.visibility = rsVis;
  1975. return ret;
  1976. } ),
  1977. parseCss: function() {
  1978. var info = this.getCss().split('|');
  1979. return {
  1980. visible: info[0] !== 'hidden',
  1981. displayed: info[1] !== 'none'
  1982. };
  1983. },
  1984. /**
  1985. * Always return false for isActive, since this property alone will not trigger
  1986. * a renderer to do anything.
  1987. */
  1988. isActive: function() {
  1989. return false;
  1990. }
  1991. } );
  1992. /**
  1993. * Abstraction for a VML shape element. Allows assembling a VML shape's properties in
  1994. * a non-DOM structure, which can then both generate itself as a single HTML string, and/or
  1995. * update itself incrementally if its DOM element already exists.
  1996. */
  1997. PIE.VmlShape = (function() {
  1998. var nsPrefix = 'pievml',
  1999. attrsPrefix = '_attrs_',
  2000. objectSetters = {
  2001. 'colors': function( fill, name, value ) {
  2002. if( fill[ name ] ) { //sometimes the colors object isn't initialized so we have to assign it directly (?)
  2003. fill[ name ].value = value;
  2004. } else {
  2005. fill[ name ] = value;
  2006. }
  2007. },
  2008. 'size': function( fill, name, value ) {
  2009. if ( !value ) {
  2010. delete fill[ name ];
  2011. } else {
  2012. fill[ name ][ 'x' ] = 1; //Can be any value, just has to be set to "prime" it so the next line works. Weird!
  2013. fill[ name ] = value;
  2014. }
  2015. },
  2016. 'o:opacity2': function( fill, name, value ) {
  2017. // The VML DOM does not allow dynamic setting of o:opacity2, so we must regenerate
  2018. // the entire shape from markup instead.
  2019. var me = this;
  2020. if( value !== me.lastOpacity2 ) {
  2021. me.getShape().insertAdjacentHTML( 'afterEnd', me.getMarkup() );
  2022. me.destroy();
  2023. me.lastOpacity2 = value;
  2024. }
  2025. }
  2026. };
  2027. function createSetter( objName ) {
  2028. return function() {
  2029. var args = arguments,
  2030. i, len = args.length,
  2031. obj, name, setter;
  2032. // Store the property locally
  2033. obj = this[ attrsPrefix + objName ] || ( this[ attrsPrefix + objName ] = {} );
  2034. for( i = 0; i < len; i += 2 ) {
  2035. obj[ args[ i ] ] = args[ i + 1 ];
  2036. }
  2037. // If there is a rendered VML shape already, set the property directly via the VML DOM
  2038. obj = this.getShape();
  2039. if( obj ) {
  2040. if( objName ) {
  2041. obj = obj[ objName ];
  2042. }
  2043. for( i = 0; i < len; i += 2 ) {
  2044. name = args[ i ];
  2045. setter = objectSetters[ name ]; //if there is a custom setter for this property, use it
  2046. if ( setter ) {
  2047. setter.call( this, obj, name, args[ i + 1 ]);
  2048. } else {
  2049. obj[ name ] = args[ i + 1 ];
  2050. }
  2051. }
  2052. }
  2053. }
  2054. }
  2055. /**
  2056. * The VML namespace has to be registered with the document, or the shapes will be invisible
  2057. * on initial render sometimes. This results in the infamous "Unspecified error" if called
  2058. * at certain times, so catch that and retry after a delay.
  2059. */
  2060. (function addVmlNamespace() {
  2061. try {
  2062. doc.namespaces.add(nsPrefix, 'urn:schemas-microsoft-com:vml', '#default#VML');
  2063. }
  2064. catch (e) {
  2065. setTimeout(addVmlNamespace, 1);
  2066. }
  2067. })();
  2068. function VmlShape( idSeed, ordinalGroup ) {
  2069. this.elId = '_pie_' + ( idSeed || 'shape' ) + PIE.Util.getUID(this);
  2070. this.ordinalGroup = ordinalGroup || 0;
  2071. }
  2072. VmlShape.prototype = {
  2073. behaviorStyle: 'behavior:url(#default#VML);',
  2074. defaultStyles: 'position:absolute;top:0px;left:0px;',
  2075. defaultAttrs: 'coordorigin="1,1" stroked="false" ',
  2076. tagName: 'shape',
  2077. mightBeRendered: 0,
  2078. getShape: function() {
  2079. return this.mightBeRendered ?
  2080. ( this._shape || ( this._shape = doc.getElementById( this.elId ) ) ) : null;
  2081. },
  2082. setAttrs: createSetter( '' ),
  2083. setStyles: createSetter( 'style' ),
  2084. setFillAttrs: createSetter( 'fill' ),
  2085. setSize: function( w, h ) {
  2086. this.setStyles(
  2087. 'width', w + 'px',
  2088. 'height', h + 'px'
  2089. );
  2090. this.setAttrs(
  2091. 'coordsize', w * 2 + ',' + h * 2
  2092. );
  2093. },
  2094. getStyleCssText: function() {
  2095. var styles = this[ attrsPrefix + 'style' ] || {},
  2096. cssText = [], p;
  2097. for( p in styles ) {
  2098. if( styles.hasOwnProperty( p ) ) {
  2099. cssText.push( p + ':' + styles[p] );
  2100. }
  2101. }
  2102. return this.behaviorStyle + this.defaultStyles + cssText.join( ';' );
  2103. },
  2104. getMarkup: function() {
  2105. var m,
  2106. me = this,
  2107. tag = me.tagName,
  2108. tagStart = '<' + nsPrefix + ':',
  2109. subElEnd = ' style="' + me.behaviorStyle + '" />';
  2110. me.mightBeRendered = 1;
  2111. function pushAttrs( keyVals ) {
  2112. if( keyVals ) {
  2113. for( var key in keyVals ) {
  2114. if( keyVals.hasOwnProperty( key ) ) {
  2115. m.push( ' ' + key + '="' + keyVals[key] + '"' );
  2116. }
  2117. }
  2118. }
  2119. }
  2120. function pushElement( name ) {
  2121. var attrs = me[ attrsPrefix + name ];
  2122. if( attrs ) {
  2123. m.push( tagStart + name );
  2124. pushAttrs( attrs );
  2125. m.push( subElEnd );
  2126. }
  2127. }
  2128. m = [ tagStart, tag, ' id="', me.elId, '" style="', me.getStyleCssText(), '" ', me.defaultAttrs ];
  2129. pushAttrs( me[ attrsPrefix ] );
  2130. m.push( '>' );
  2131. pushElement( 'fill' );
  2132. m.push( '</' + nsPrefix + ':' + tag + '>' );
  2133. return m.join( '' );
  2134. },
  2135. destroy: function() {
  2136. var shape = this.getShape(),
  2137. par = shape && shape.parentNode;
  2138. if( par ) {
  2139. par.removeChild(shape);
  2140. delete this._shape;
  2141. }
  2142. }
  2143. };
  2144. return VmlShape;
  2145. })();PIE.RendererBase = {
  2146. /**
  2147. * Create a new Renderer class, with the standard constructor, and augmented by
  2148. * the RendererBase's members.
  2149. * @param proto
  2150. */
  2151. newRenderer: function( proto ) {
  2152. function Renderer( el, boundsInfo, styleInfos, parent ) {
  2153. this.targetElement = el;
  2154. this.boundsInfo = boundsInfo;
  2155. this.styleInfos = styleInfos;
  2156. this.parent = parent;
  2157. }
  2158. PIE.merge( Renderer.prototype, PIE.RendererBase, proto );
  2159. return Renderer;
  2160. },
  2161. /**
  2162. * Determine if the renderer needs to be updated
  2163. * @return {boolean}
  2164. */
  2165. needsUpdate: function() {
  2166. return false;
  2167. },
  2168. /**
  2169. * Run any preparation logic that would affect the main update logic of this
  2170. * renderer or any of the other renderers, e.g. things that might affect the
  2171. * element's size or style properties.
  2172. */
  2173. prepareUpdate: PIE.emptyFn,
  2174. /**
  2175. * Tell the renderer to update based on modified properties or element dimensions
  2176. */
  2177. updateRendering: function() {
  2178. if( this.isActive() ) {
  2179. this.draw();
  2180. } else {
  2181. this.destroy();
  2182. }
  2183. },
  2184. /**
  2185. * Hide the target element's border
  2186. */
  2187. hideBorder: function() {
  2188. this.targetElement.runtimeStyle.borderColor = 'transparent';
  2189. },
  2190. /**
  2191. * Destroy the rendered objects. This is a base implementation which handles common renderer
  2192. * structures, but individual renderers may override as necessary.
  2193. */
  2194. destroy: function() {
  2195. }
  2196. };
  2197. PIE.merge(PIE.RendererBase, {
  2198. /**
  2199. * Get a VmlShape by name, creating it if necessary.
  2200. * @param {string} name A name identifying the element
  2201. * @param {number} zIndex Specifies the target z-index of the shape. This will be used when rendering
  2202. * the shape to ensure it is inserted in the correct order with other shapes to give
  2203. * correct stacking order without using actual CSS z-index.
  2204. * @return {PIE.VmlShape}
  2205. */
  2206. getShape: function( name, zIndex ) {
  2207. var shapes = this._shapes || ( this._shapes = {} ),
  2208. shape = shapes[ name ];
  2209. if( !shape ) {
  2210. shape = shapes[ name ] = new PIE.VmlShape( name, zIndex );
  2211. this.parent.enqueueShapeForRender( shape );
  2212. }
  2213. return shape;
  2214. },
  2215. /**
  2216. * Delete a named shape which was created by getShape(). Returns true if a shape with the
  2217. * given name was found and deleted, or false if there was no shape of that name.
  2218. * @param {string} name
  2219. * @return {boolean}
  2220. */
  2221. deleteShape: function( name ) {
  2222. var shapes = this._shapes,
  2223. shape = shapes && shapes[ name ];
  2224. if( shape ) {
  2225. shape.destroy();
  2226. this.parent.removeShape( shape );
  2227. delete shapes[ name ];
  2228. }
  2229. return !!shape;
  2230. },
  2231. /**
  2232. * For a given set of border radius length/percentage values, convert them to concrete pixel
  2233. * values based on the current size of the target element.
  2234. * @param {Object} radii
  2235. * @return {Object}
  2236. */
  2237. getRadiiPixels: function( radii ) {
  2238. var el = this.targetElement,
  2239. bounds = this.boundsInfo.getBounds(),
  2240. w = bounds.w,
  2241. h = bounds.h,
  2242. tlX, tlY, trX, trY, brX, brY, blX, blY, f;
  2243. tlX = radii.x['tl'].pixels( el, w );
  2244. tlY = radii.y['tl'].pixels( el, h );
  2245. trX = radii.x['tr'].pixels( el, w );
  2246. trY = radii.y['tr'].pixels( el, h );
  2247. brX = radii.x['br'].pixels( el, w );
  2248. brY = radii.y['br'].pixels( el, h );
  2249. blX = radii.x['bl'].pixels( el, w );
  2250. blY = radii.y['bl'].pixels( el, h );
  2251. // If any corner ellipses overlap, reduce them all by the appropriate factor. This formula
  2252. // is taken straight from the CSS3 Backgrounds and Borders spec.
  2253. f = Math.min(
  2254. w / ( tlX + trX ),
  2255. h / ( trY + brY ),
  2256. w / ( blX + brX ),
  2257. h / ( tlY + blY )
  2258. );
  2259. if( f < 1 ) {
  2260. tlX *= f;
  2261. tlY *= f;
  2262. trX *= f;
  2263. trY *= f;
  2264. brX *= f;
  2265. brY *= f;
  2266. blX *= f;
  2267. blY *= f;
  2268. }
  2269. return {
  2270. x: {
  2271. 'tl': tlX,
  2272. 'tr': trX,
  2273. 'br': brX,
  2274. 'bl': blX
  2275. },
  2276. y: {
  2277. 'tl': tlY,
  2278. 'tr': trY,
  2279. 'br': brY,
  2280. 'bl': blY
  2281. }
  2282. }
  2283. },
  2284. /**
  2285. * Return the VML path string for the element's background box, with corners rounded.
  2286. * @param {number} shrinkT - number of pixels to shrink the box path inward from the element's top side.
  2287. * @param {number} shrinkR - number of pixels to shrink the box path inward from the element's right side.
  2288. * @param {number} shrinkB - number of pixels to shrink the box path inward from the element's bottom side.
  2289. * @param {number} shrinkL - number of pixels to shrink the box path inward from the element's left side.
  2290. * @param {number} mult All coordinates will be multiplied by this number
  2291. * @param {Object=} radii If specified, this will be used for the corner radii instead of the properties
  2292. * from this renderer's borderRadiusInfo object.
  2293. * @return {string} the VML path
  2294. */
  2295. getBoxPath: function( shrinkT, shrinkR, shrinkB, shrinkL, mult, radii ) {
  2296. var coords = this.getBoxPathCoords( shrinkT, shrinkR, shrinkB, shrinkL, mult, radii );
  2297. return 'm' + coords[ 0 ] + ',' + coords[ 1 ] +
  2298. 'qy' + coords[ 2 ] + ',' + coords[ 3 ] +
  2299. 'l' + coords[ 4 ] + ',' + coords[ 5 ] +
  2300. 'qx' + coords[ 6 ] + ',' + coords[ 7 ] +
  2301. 'l' + coords[ 8 ] + ',' + coords[ 9 ] +
  2302. 'qy' + coords[ 10 ] + ',' + coords[ 11 ] +
  2303. 'l' + coords[ 12 ] + ',' + coords[ 13 ] +
  2304. 'qx' + coords[ 14 ] + ',' + coords[ 15 ] +
  2305. 'x';
  2306. },
  2307. /**
  2308. * Return the VML coordinates for all the vertices in the rounded box path.
  2309. * @param {number} shrinkT - number of pixels to shrink the box path inward from the element's top side.
  2310. * @param {number} shrinkR - number of pixels to shrink the box path inward from the element's right side.
  2311. * @param {number} shrinkB - number of pixels to shrink the box path inward from the element's bottom side.
  2312. * @param {number} shrinkL - number of pixels to shrink the box path inward from the element's left side.
  2313. * @param {number=} mult If specified, all coordinates will be multiplied by this number
  2314. * @param {Object=} radii If specified, this will be used for the corner radii instead of the properties
  2315. * from this renderer's borderRadiusInfo object.
  2316. * @return {Array.<number>} all the coordinates going clockwise, starting with the top-left corner's lower vertex
  2317. */
  2318. getBoxPathCoords: function( shrinkT, shrinkR, shrinkB, shrinkL, mult, radii ) {
  2319. var bounds = this.boundsInfo.getBounds(),
  2320. w = bounds.w * mult,
  2321. h = bounds.h * mult,
  2322. M = Math,
  2323. floor = M.floor, ceil = M.ceil,
  2324. max = M.max, min = M.min,
  2325. coords;
  2326. shrinkT *= mult;
  2327. shrinkR *= mult;
  2328. shrinkB *= mult;
  2329. shrinkL *= mult;
  2330. if ( !radii ) {
  2331. radii = this.styleInfos.borderRadiusInfo.getProps();
  2332. }
  2333. if ( radii ) {
  2334. radii = this.getRadiiPixels( radii );
  2335. var tlRadiusX = radii.x['tl'] * mult,
  2336. tlRadiusY = radii.y['tl'] * mult,
  2337. trRadiusX = radii.x['tr'] * mult,
  2338. trRadiusY = radii.y['tr'] * mult,
  2339. brRadiusX = radii.x['br'] * mult,
  2340. brRadiusY = radii.y['br'] * mult,
  2341. blRadiusX = radii.x['bl'] * mult,
  2342. blRadiusY = radii.y['bl'] * mult;
  2343. coords = [
  2344. floor( shrinkL ), // top-left lower x
  2345. floor( min( max( tlRadiusY, shrinkT ), h - shrinkB ) ), // top-left lower y
  2346. floor( min( max( tlRadiusX, shrinkL ), w - shrinkR ) ), // top-left upper x
  2347. floor( shrinkT ), // top-left upper y
  2348. ceil( max( shrinkL, w - max( trRadiusX, shrinkR ) ) ), // top-right upper x
  2349. floor( shrinkT ), // top-right upper y
  2350. ceil( w - shrinkR ), // top-right lower x
  2351. floor( min( max( trRadiusY, shrinkT ), h - shrinkB ) ), // top-right lower y
  2352. ceil( w - shrinkR ), // bottom-right upper x
  2353. ceil( max( shrinkT, h - max( brRadiusY, shrinkB ) ) ), // bottom-right upper y
  2354. ceil( max( shrinkL, w - max( brRadiusX, shrinkR ) ) ), // bottom-right lower x
  2355. ceil( h - shrinkB ), // bottom-right lower y
  2356. floor( min( max( blRadiusX, shrinkL ), w - shrinkR ) ), // bottom-left lower x
  2357. ceil( h - shrinkB ), // bottom-left lower y
  2358. floor( shrinkL ), // bottom-left upper x
  2359. ceil( max( shrinkT, h - max( blRadiusY, shrinkB ) ) ) // bottom-left upper y
  2360. ];
  2361. } else {
  2362. // Skip most of the heavy math for a simple non-rounded box
  2363. var t = floor( shrinkT ),
  2364. r = ceil( w - shrinkR ),
  2365. b = ceil( h - shrinkB ),
  2366. l = floor( shrinkL );
  2367. coords = [ l, t, l, t, r, t, r, t, r, b, r, b, l, b, l, b ];
  2368. }
  2369. return coords;
  2370. },
  2371. /**
  2372. * Hide the actual border of the element. In IE7 and up we can just set its color to transparent;
  2373. * however IE6 does not support transparent borders so we have to get tricky with it. Also, some elements
  2374. * like form buttons require removing the border width altogether, so for those we increase the padding
  2375. * by the border size.
  2376. */
  2377. hideBorder: function() {
  2378. var el = this.targetElement,
  2379. cs = el.currentStyle,
  2380. rs = el.runtimeStyle,
  2381. tag = el.tagName,
  2382. isIE6 = PIE.ieVersion === 6,
  2383. sides, side, i;
  2384. if( ( isIE6 && ( tag in PIE.childlessElements || tag === 'FIELDSET' ) ) ||
  2385. tag === 'BUTTON' || ( tag === 'INPUT' && el.type in PIE.inputButtonTypes ) ) {
  2386. rs.borderWidth = '';
  2387. sides = this.styleInfos.borderInfo.sides;
  2388. for( i = sides.length; i--; ) {
  2389. side = sides[ i ];
  2390. rs[ 'padding' + side ] = '';
  2391. rs[ 'padding' + side ] = ( PIE.getLength( cs[ 'padding' + side ] ) ).pixels( el ) +
  2392. ( PIE.getLength( cs[ 'border' + side + 'Width' ] ) ).pixels( el ) +
  2393. ( PIE.ieVersion !== 8 && i % 2 ? 1 : 0 ); //needs an extra horizontal pixel to counteract the extra "inner border" going away
  2394. }
  2395. rs.borderWidth = 0;
  2396. }
  2397. else if( isIE6 ) {
  2398. // Wrap all the element's children in a custom element, set the element to visiblity:hidden,
  2399. // and set the wrapper element to visiblity:visible. This hides the outer element's decorations
  2400. // (background and border) but displays all the contents.
  2401. // TODO find a better way to do this that doesn't mess up the DOM parent-child relationship,
  2402. // as this can interfere with other author scripts which add/modify/delete children. Also, this
  2403. // won't work for elements which cannot take children, e.g. input/button/textarea/img/etc. Look into
  2404. // using a compositor filter or some other filter which masks the border.
  2405. if( el.childNodes.length !== 1 || el.firstChild.tagName !== 'ie6-mask' ) {
  2406. var cont = doc.createElement( 'ie6-mask' ),
  2407. s = cont.style, child;
  2408. s.visibility = 'visible';
  2409. s.zoom = 1;
  2410. while( child = el.firstChild ) {
  2411. cont.appendChild( child );
  2412. }
  2413. el.appendChild( cont );
  2414. rs.visibility = 'hidden';
  2415. }
  2416. }
  2417. else {
  2418. rs.borderColor = 'transparent';
  2419. }
  2420. },
  2421. unhideBorder: function() {
  2422. },
  2423. /**
  2424. * Destroy the rendered objects. This is a base implementation which handles common renderer
  2425. * structures, but individual renderers may override as necessary.
  2426. */
  2427. destroy: function() {
  2428. var shapes = this._shapes, s;
  2429. if ( shapes ) {
  2430. for( s in shapes ) {
  2431. if( shapes.hasOwnProperty( s ) ) {
  2432. this.deleteShape( s );
  2433. }
  2434. }
  2435. }
  2436. }
  2437. });
  2438. /**
  2439. * Root renderer; creates the outermost container element and handles keeping it aligned
  2440. * with the target element's size and position.
  2441. * @param {Element} el The target element
  2442. * @param {Object} styleInfos The StyleInfo objects
  2443. */
  2444. PIE.RootRenderer = PIE.RendererBase.newRenderer( {
  2445. isActive: function() {
  2446. var children = this.childRenderers;
  2447. for( var i in children ) {
  2448. if( children.hasOwnProperty( i ) && children[ i ].isActive() ) {
  2449. return true;
  2450. }
  2451. }
  2452. return false;
  2453. },
  2454. getBoxCssText: function() {
  2455. var el = this.getPositioningElement(),
  2456. par = el,
  2457. docEl,
  2458. parRect,
  2459. tgtCS = el.currentStyle,
  2460. tgtPos = tgtCS.position,
  2461. boxPos,
  2462. cs,
  2463. x = 0, y = 0,
  2464. elBounds = this.boundsInfo.getBounds(),
  2465. vis = this.styleInfos.visibilityInfo.getProps(),
  2466. logicalZoomRatio = elBounds.logicalZoomRatio;
  2467. if( tgtPos === 'fixed' && PIE.ieVersion > 6 ) {
  2468. x = elBounds.x * logicalZoomRatio;
  2469. y = elBounds.y * logicalZoomRatio;
  2470. boxPos = tgtPos;
  2471. } else {
  2472. // Get the element's offsets from its nearest positioned ancestor. Uses
  2473. // getBoundingClientRect for accuracy and speed.
  2474. do {
  2475. par = par.offsetParent;
  2476. } while( par && ( par.currentStyle.position === 'static' ) );
  2477. if( par ) {
  2478. parRect = par.getBoundingClientRect();
  2479. cs = par.currentStyle;
  2480. x = ( elBounds.x - parRect.left ) * logicalZoomRatio - ( parseFloat(cs.borderLeftWidth) || 0 );
  2481. y = ( elBounds.y - parRect.top ) * logicalZoomRatio - ( parseFloat(cs.borderTopWidth) || 0 );
  2482. } else {
  2483. docEl = doc.documentElement;
  2484. x = ( elBounds.x + docEl.scrollLeft - docEl.clientLeft ) * logicalZoomRatio;
  2485. y = ( elBounds.y + docEl.scrollTop - docEl.clientTop ) * logicalZoomRatio;
  2486. }
  2487. boxPos = 'absolute';
  2488. }
  2489. return 'direction:ltr;' +
  2490. 'position:absolute;' +
  2491. 'behavior:none !important;' +
  2492. 'position:' + boxPos + ';' +
  2493. 'left:' + x + 'px;' +
  2494. 'top:' + y + 'px;' +
  2495. 'z-index:' + ( tgtPos === 'static' ? -1 : tgtCS.zIndex ) + ';' +
  2496. 'display:' + ( vis.visible && vis.displayed ? 'block' : 'none' );
  2497. },
  2498. updateBoxStyles: function() {
  2499. var me = this,
  2500. boxEl = me.getBoxEl();
  2501. if( boxEl && ( me.boundsInfo.positionChanged() || me.styleInfos.visibilityInfo.changed() ) ) {
  2502. boxEl.style.cssText = me.getBoxCssText();
  2503. }
  2504. },
  2505. getPositioningElement: function() {
  2506. var el = this.targetElement;
  2507. return el.tagName in PIE.tableCellTags ? el.offsetParent : el;
  2508. },
  2509. /**
  2510. * Get a reference to the css3pie container element that contains the VML shapes,
  2511. * if it has been inserted.
  2512. */
  2513. getBoxEl: function() {
  2514. var box = this._box;
  2515. if( !box ) {
  2516. box = this._box = doc.getElementById( '_pie' + PIE.Util.getUID( this ) );
  2517. }
  2518. return box;
  2519. },
  2520. /**
  2521. * Render any child rendrerer shapes which have not already been rendered into the DOM.
  2522. */
  2523. updateRendering: function() {
  2524. var me = this,
  2525. queue = me._shapeRenderQueue,
  2526. renderedShapes, markup, i, len, j,
  2527. ref, pos, vis;
  2528. if (me.isActive()) {
  2529. if( queue ) {
  2530. // We've already rendered something once, so do incremental insertion of new shapes
  2531. renderedShapes = me._renderedShapes;
  2532. if( renderedShapes ) {
  2533. for( i = 0, len = queue.length; i < len; i++ ) {
  2534. for( j = renderedShapes.length; j--; ) {
  2535. if( renderedShapes[ j ].ordinalGroup < queue[ i ].ordinalGroup ) {
  2536. break;
  2537. }
  2538. }
  2539. if ( j < 0 ) {
  2540. ref = me.getBoxEl();
  2541. pos = 'afterBegin';
  2542. } else {
  2543. ref = renderedShapes[ j ].getShape();
  2544. pos = 'afterEnd';
  2545. }
  2546. ref.insertAdjacentHTML( pos, queue[ i ].getMarkup() );
  2547. renderedShapes.splice( j < 0 ? 0 : j, 0, queue[ i ] );
  2548. }
  2549. me._shapeRenderQueue = 0;
  2550. me.updateBoxStyles();
  2551. }
  2552. // This is the first render, so build up a single markup string and insert it all at once
  2553. else {
  2554. vis = me.styleInfos.visibilityInfo.getProps();
  2555. if( vis.visible && vis.displayed ) {
  2556. queue.sort( me.shapeSorter );
  2557. markup = [ '<css3pie id="_pie' + PIE.Util.getUID( me ) + '" style="' + me.getBoxCssText() + '">' ];
  2558. for( i = 0, len = queue.length; i < len; i++ ) {
  2559. markup.push( queue[ i ].getMarkup() );
  2560. }
  2561. markup.push( '</css3pie>' );
  2562. me.getPositioningElement().insertAdjacentHTML( 'beforeBegin', markup.join( '' ) );
  2563. me._renderedShapes = queue;
  2564. me._shapeRenderQueue = 0;
  2565. }
  2566. }
  2567. } else {
  2568. me.updateBoxStyles();
  2569. }
  2570. } else {
  2571. me.destroy();
  2572. }
  2573. },
  2574. shapeSorter: function( shape1, shape2 ) {
  2575. return shape1.ordinalGroup - shape2.ordinalGroup;
  2576. },
  2577. /**
  2578. * Add a VmlShape into the queue to get rendered in finishUpdate
  2579. */
  2580. enqueueShapeForRender: function( shape ) {
  2581. var me = this,
  2582. queue = me._shapeRenderQueue || ( me._shapeRenderQueue = [] );
  2583. queue.push( shape );
  2584. },
  2585. /**
  2586. * Remove a VmlShape from the DOM and also from the internal list of rendered shapes.
  2587. */
  2588. removeShape: function( shape ) {
  2589. var shapes = this._renderedShapes, i;
  2590. if ( shapes ) {
  2591. for( i = shapes.length; i--; ) {
  2592. if( shapes[ i ] === shape ) {
  2593. shapes.splice( i, 1 );
  2594. break;
  2595. }
  2596. }
  2597. }
  2598. },
  2599. destroy: function() {
  2600. var box = this._box, par;
  2601. if( box && ( par = box.parentNode ) ) {
  2602. par.removeChild( box );
  2603. }
  2604. delete this._box;
  2605. delete this._renderedShapes;
  2606. }
  2607. } );
  2608. // Prime IE for recognizing the custom <css3pie> element
  2609. doc.createElement( 'css3pie' );
  2610. /**
  2611. * Renderer for element backgrounds.
  2612. * @constructor
  2613. * @param {Element} el The target element
  2614. * @param {Object} styleInfos The StyleInfo objects
  2615. * @param {PIE.RootRenderer} parent
  2616. */
  2617. PIE.BackgroundRenderer = PIE.RendererBase.newRenderer( {
  2618. shapeZIndex: 2,
  2619. needsUpdate: function() {
  2620. var si = this.styleInfos;
  2621. return si.backgroundInfo.changed() || si.borderRadiusInfo.changed();
  2622. },
  2623. isActive: function() {
  2624. var si = this.styleInfos;
  2625. return si.borderImageInfo.isActive() ||
  2626. si.borderRadiusInfo.isActive() ||
  2627. si.backgroundInfo.isActive() ||
  2628. ( si.boxShadowInfo.isActive() && si.boxShadowInfo.getProps().inset );
  2629. },
  2630. /**
  2631. * Draw the shapes
  2632. */
  2633. draw: function() {
  2634. var bounds = this.boundsInfo.getBounds();
  2635. if( bounds.w && bounds.h ) {
  2636. this.drawBgColor();
  2637. this.drawBgImages();
  2638. }
  2639. },
  2640. /**
  2641. * Draw the background color shape
  2642. */
  2643. drawBgColor: function() {
  2644. var props = this.styleInfos.backgroundInfo.getProps(),
  2645. bounds = this.boundsInfo.getBounds(),
  2646. el = this.targetElement,
  2647. color = props && props.color,
  2648. shape, alpha;
  2649. if( color && color.alpha() > 0 ) {
  2650. this.hideBackground();
  2651. shape = this.getShape( 'bgColor', this.shapeZIndex );
  2652. shape.setSize( bounds.w, bounds.h );
  2653. shape.setAttrs(
  2654. 'path', this.getBgClipPath( bounds, props.colorClip )
  2655. );
  2656. shape.setFillAttrs( 'color', color.colorValue( el ) );
  2657. alpha = color.alpha();
  2658. if( alpha < 1 ) {
  2659. shape.setFillAttrs( 'opacity', alpha );
  2660. }
  2661. } else {
  2662. this.deleteShape( 'bgColor' );
  2663. }
  2664. },
  2665. /**
  2666. * Draw all the background image layers
  2667. */
  2668. drawBgImages: function() {
  2669. var props = this.styleInfos.backgroundInfo.getProps(),
  2670. bounds = this.boundsInfo.getBounds(),
  2671. images = props && props.bgImages,
  2672. img, shape, w, h, i;
  2673. if( images ) {
  2674. this.hideBackground();
  2675. w = bounds.w;
  2676. h = bounds.h;
  2677. i = images.length;
  2678. while( i-- ) {
  2679. img = images[i];
  2680. shape = this.getShape( 'bgImage' + i, this.shapeZIndex + ( .5 - i / 1000 ) );
  2681. shape.setAttrs(
  2682. 'path', this.getBgClipPath( bounds, img.bgClip )
  2683. );
  2684. shape.setSize( w, h );
  2685. if( img.imgType === 'linear-gradient' ) {
  2686. this.addLinearGradient( shape, img );
  2687. }
  2688. else {
  2689. shape.setFillAttrs(
  2690. 'type', 'tile',
  2691. 'color', 'none'
  2692. );
  2693. this.positionBgImage( shape, img.imgUrl, i );
  2694. }
  2695. }
  2696. }
  2697. // Delete any bgImage shapes previously created which weren't used above
  2698. i = images ? images.length : 0;
  2699. while( this.deleteShape( 'bgImage' + i++ ) ) {}
  2700. },
  2701. /**
  2702. * Set the position and clipping of the background image for a layer
  2703. * @param {Element} shape
  2704. * @param {String} src
  2705. * @param {number} index
  2706. */
  2707. positionBgImage: function( shape, src, index ) {
  2708. PIE.Util.withImageSize( src, function( imgSize ) {
  2709. var me = this,
  2710. el = me.targetElement,
  2711. bounds = me.boundsInfo.getBounds(),
  2712. elW = bounds.w,
  2713. elH = bounds.h;
  2714. // It's possible that the element dimensions are zero now but weren't when the original
  2715. // update executed, make sure that's not the case to avoid divide-by-zero error
  2716. if( elW && elH ) {
  2717. var styleInfos = me.styleInfos,
  2718. bgInfo = styleInfos.backgroundInfo,
  2719. bg = bgInfo.getProps().bgImages[ index ],
  2720. bgAreaSize = bgInfo.getBgAreaSize( bg.bgOrigin, me.boundsInfo, styleInfos.borderInfo, styleInfos.paddingInfo ),
  2721. adjustedImgSize = ( bg.bgSize || PIE.BgSize.DEFAULT ).pixels(
  2722. me.targetElement, bgAreaSize.w, bgAreaSize.h, imgSize.w, imgSize.h
  2723. ),
  2724. bgOriginXY = me.getBgOriginXY( bg.bgOrigin ),
  2725. bgPos = bg.bgPosition ? bg.bgPosition.coords( el, bgAreaSize.w - adjustedImgSize.w, bgAreaSize.h - adjustedImgSize.h ) : { x:0, y:0 },
  2726. repeat = bg.imgRepeat,
  2727. pxX, pxY,
  2728. clipT = 0, clipL = 0,
  2729. clipR = elW + 1, clipB = elH + 1, //make sure the default clip region is not inside the box (by a subpixel)
  2730. clipAdjust = PIE.ieVersion === 8 ? 0 : 1; //prior to IE8 requires 1 extra pixel in the image clip region
  2731. // Positioning - find the pixel offset from the top/left and convert to a ratio
  2732. // The position is shifted by half a pixel, to adjust for the half-pixel coordorigin shift which is
  2733. // needed to fix antialiasing but makes the bg image fuzzy.
  2734. pxX = Math.round( bgOriginXY.x + bgPos.x ) + 0.5;
  2735. pxY = Math.round( bgOriginXY.y + bgPos.y ) + 0.5;
  2736. shape.setFillAttrs(
  2737. 'src', src,
  2738. 'position', ( pxX / elW ) + ',' + ( pxY / elH ),
  2739. // Set the size of the image. We only set it if the image is scaled via background-size or by
  2740. // the user changing the browser zoom level, to avoid fuzzy images at normal size. For some reason
  2741. // using px units doesn't work in VML markup so we must convert to pt.
  2742. 'size', ( adjustedImgSize.w !== imgSize.w || adjustedImgSize.h !== imgSize.h ||
  2743. bounds.logicalZoomRatio !== 1 || screen['logicalXDPI'] / screen['deviceXDPI'] !== 1 ) ?
  2744. PIE.Length.pxToPt( adjustedImgSize.w ) + 'pt,' + PIE.Length.pxToPt( adjustedImgSize.h ) + 'pt' : ''
  2745. );
  2746. // Repeating - clip the image shape
  2747. if( repeat && repeat !== 'repeat' ) {
  2748. if( repeat === 'repeat-x' || repeat === 'no-repeat' ) {
  2749. clipT = pxY + 1;
  2750. clipB = pxY + adjustedImgSize.h + clipAdjust;
  2751. }
  2752. if( repeat === 'repeat-y' || repeat === 'no-repeat' ) {
  2753. clipL = pxX + 1;
  2754. clipR = pxX + adjustedImgSize.w + clipAdjust;
  2755. }
  2756. shape.setStyles( 'clip', 'rect(' + clipT + 'px,' + clipR + 'px,' + clipB + 'px,' + clipL + 'px)' );
  2757. }
  2758. }
  2759. }, this );
  2760. },
  2761. /**
  2762. * For a given background-clip value, return the VML path for that clip area.
  2763. * @param {Object} bounds
  2764. * @param {String} bgClip
  2765. */
  2766. getBgClipPath: function( bounds, bgClip ) {
  2767. var me = this,
  2768. shrinkT = 0,
  2769. shrinkR = 0,
  2770. shrinkB = 0,
  2771. shrinkL = 0,
  2772. el = me.targetElement,
  2773. styleInfos = me.styleInfos,
  2774. borders, paddings;
  2775. if ( bgClip && bgClip !== 'border-box' ) {
  2776. borders = styleInfos.borderInfo.getProps();
  2777. if ( borders && ( borders = borders.widths ) ) {
  2778. shrinkT += borders[ 't' ].pixels( el );
  2779. shrinkR += borders[ 'r' ].pixels( el );
  2780. shrinkB += borders[ 'b' ].pixels( el );
  2781. shrinkL += borders[ 'l' ].pixels( el );
  2782. }
  2783. }
  2784. if ( bgClip === 'content-box' ) {
  2785. paddings = styleInfos.paddingInfo.getProps();
  2786. if( paddings ) {
  2787. shrinkT += paddings[ 't' ].pixels( el );
  2788. shrinkR += paddings[ 'r' ].pixels( el );
  2789. shrinkB += paddings[ 'b' ].pixels( el );
  2790. shrinkL += paddings[ 'l' ].pixels( el );
  2791. }
  2792. }
  2793. // Add points at 0,0 and w,h so that the image size/position will still be
  2794. // based on the full element area.
  2795. return 'm0,0r0,0m' + bounds.w * 2 + ',' + bounds.h * 2 + 'r0,0' +
  2796. me.getBoxPath( shrinkT, shrinkR, shrinkB, shrinkL, 2 );
  2797. },
  2798. /**
  2799. * For a given background-origin value, return the x/y position of the origin
  2800. * from the top-left of the element bounds.
  2801. * @param {String} bgOrigin
  2802. */
  2803. getBgOriginXY: function( bgOrigin ) {
  2804. var me = this,
  2805. el = me.targetElement,
  2806. styleInfos = me.styleInfos,
  2807. x = 0,
  2808. y = 0,
  2809. borders, paddings;
  2810. if( bgOrigin !== 'border-box' ) {
  2811. borders = styleInfos.borderInfo.getProps();
  2812. if( borders && ( borders = borders.widths ) ) {
  2813. x += borders[ 'l' ].pixels( el );
  2814. y += borders[ 't' ].pixels( el );
  2815. }
  2816. }
  2817. if ( bgOrigin === 'content-box' ) {
  2818. paddings = styleInfos.paddingInfo.getProps();
  2819. if( paddings ) {
  2820. x += paddings[ 'l' ].pixels( el );
  2821. y += paddings[ 't' ].pixels( el );
  2822. }
  2823. }
  2824. return { x: x, y: y };
  2825. },
  2826. /**
  2827. * Draw the linear gradient for a gradient layer
  2828. * @param {Element} shape
  2829. * @param {Object} info The object holding the information about the gradient
  2830. */
  2831. addLinearGradient: function( shape, info ) {
  2832. var el = this.targetElement,
  2833. bounds = this.boundsInfo.getBounds(),
  2834. w = bounds.w,
  2835. h = bounds.h,
  2836. stops = info.stops,
  2837. stopCount = stops.length,
  2838. PI = Math.PI,
  2839. metrics = PIE.GradientUtil.getGradientMetrics( el, w, h, info ),
  2840. angle = metrics.angle,
  2841. lineLength = metrics.lineLength,
  2842. vmlAngle, vmlColors,
  2843. stopPx, i, j, before, after;
  2844. // In VML land, the angle of the rendered gradient depends on the aspect ratio of the shape's
  2845. // bounding box; for example specifying a 45 deg angle actually results in a gradient
  2846. // drawn diagonally from one corner to its opposite corner, which will only appear to the
  2847. // viewer as 45 degrees if the shape is equilateral. We adjust for this by taking the x/y deltas
  2848. // between the start and end points, multiply one of them by the shape's aspect ratio,
  2849. // and get their arctangent, resulting in an appropriate VML angle. If the angle is perfectly
  2850. // horizontal or vertical then we don't need to do this conversion.
  2851. // VML angles go in the opposite direction from CSS angles.
  2852. vmlAngle = ( angle % 90 ) ?
  2853. Math.atan2( metrics.startY - metrics.endY, ( metrics.endX - metrics.startX ) * w / h ) / PI * 180 - 90 :
  2854. -angle;
  2855. while( vmlAngle < 0 ) {
  2856. vmlAngle += 360;
  2857. }
  2858. vmlAngle = vmlAngle % 360;
  2859. // Add all the stops to the VML 'colors' list, including the first and last stops.
  2860. // For each, we find its pixel offset along the gradient-line; if the offset of a stop is less
  2861. // than that of its predecessor we increase it to be equal.
  2862. vmlColors = [];
  2863. // Find the pixel offsets along the CSS3 gradient-line for each stop.
  2864. stopPx = [];
  2865. for( i = 0; i < stopCount; i++ ) {
  2866. stopPx.push( stops[i].offset ? stops[i].offset.pixels( el, lineLength ) :
  2867. i === 0 ? 0 : i === stopCount - 1 ? lineLength : null );
  2868. }
  2869. // Fill in gaps with evenly-spaced offsets
  2870. for( i = 1; i < stopCount; i++ ) {
  2871. if( stopPx[ i ] === null ) {
  2872. before = stopPx[ i - 1 ];
  2873. j = i;
  2874. do {
  2875. after = stopPx[ ++j ];
  2876. } while( after === null );
  2877. stopPx[ i ] = before + ( after - before ) / ( j - i + 1 );
  2878. }
  2879. // Make sure each stop's offset is no less than the one before it
  2880. stopPx[ i ] = Math.max( stopPx[ i ], stopPx[ i - 1 ] );
  2881. }
  2882. // Convert to percentage along the gradient line and add to the VML 'colors' value
  2883. for( i = 0; i < stopCount; i++ ) {
  2884. vmlColors.push(
  2885. ( stopPx[ i ] / lineLength * 100 ) + '% ' + stops[i].color.colorValue( el )
  2886. );
  2887. }
  2888. // Now, finally, we're ready to render the gradient fill. Set the start and end colors to
  2889. // the first and last stop colors; this just sets outer bounds for the gradient.
  2890. shape.setFillAttrs(
  2891. 'angle', vmlAngle,
  2892. 'type', 'gradient',
  2893. 'method', 'sigma',
  2894. 'color', stops[0].color.colorValue( el ),
  2895. 'color2', stops[stopCount - 1].color.colorValue( el ),
  2896. 'colors', vmlColors.join( ',' )
  2897. );
  2898. // Set opacity; right now we only support this for two-stop gradients, multi-stop
  2899. // opacity will require chopping up each segment into its own shape.
  2900. // Note these seem backwards but they must be that way since VML strangely reverses
  2901. // them when the 'colors' property is present.
  2902. if ( stopCount === 2 ) {
  2903. shape.setFillAttrs(
  2904. 'opacity', stops[1].color.alpha(),
  2905. 'o:opacity2', stops[0].color.alpha()
  2906. );
  2907. }
  2908. },
  2909. /**
  2910. * Hide the actual background image and color of the element.
  2911. */
  2912. hideBackground: function() {
  2913. var rs = this.targetElement.runtimeStyle;
  2914. rs.backgroundImage = 'url(about:blank)'; //ensures the background area reacts to mouse events
  2915. rs.backgroundColor = 'transparent';
  2916. },
  2917. destroy: function() {
  2918. PIE.RendererBase.destroy.call( this );
  2919. var rs = this.targetElement.runtimeStyle;
  2920. rs.backgroundImage = rs.backgroundColor = '';
  2921. }
  2922. } );
  2923. /**
  2924. * Renderer for element borders.
  2925. * @constructor
  2926. * @param {Element} el The target element
  2927. * @param {Object} styleInfos The StyleInfo objects
  2928. * @param {PIE.RootRenderer} parent
  2929. */
  2930. PIE.BorderRenderer = PIE.RendererBase.newRenderer( {
  2931. shapeZIndex: 4,
  2932. /**
  2933. * Single definition of arguments for use by the per-side creation loop in
  2934. * getBorderSegmentsInfo. Arguments are, in order:
  2935. * centerX1, centerY1, outerX1, outerY1, centerX2, centerY2, outerX2, outerY2, baseAngle
  2936. */
  2937. sideArgs: {
  2938. 't': [ 2, 1, 0, 3, 4, 7, 6, 5, 90 ],
  2939. 'r': [ 4, 7, 6, 5, 10, 9, 8, 11, 0 ],
  2940. 'b': [ 10, 9, 8, 11, 12, 15, 14, 13, 270 ],
  2941. 'l': [ 12, 15, 14, 13, 2, 1, 0, 3, 180 ]
  2942. },
  2943. dashedStyles: {
  2944. 'dotted': 1,
  2945. 'dashed': 1
  2946. },
  2947. colorManipStyles: {
  2948. 'groove': 1,
  2949. 'ridge': 1,
  2950. 'inset': 1,
  2951. 'outset': 1
  2952. },
  2953. doubleStyles: {
  2954. 'groove': 1,
  2955. 'ridge': 1,
  2956. 'double': 1
  2957. },
  2958. needsUpdate: function() {
  2959. var si = this.styleInfos;
  2960. return si.borderInfo.changed() || si.borderRadiusInfo.changed();
  2961. },
  2962. isActive: function() {
  2963. var si = this.styleInfos;
  2964. return si.borderRadiusInfo.isActive() &&
  2965. !si.borderImageInfo.isActive() &&
  2966. si.borderInfo.isActive(); //check BorderStyleInfo last because it's the most expensive
  2967. },
  2968. /**
  2969. * Draw the border shape(s)
  2970. */
  2971. draw: function() {
  2972. var me = this,
  2973. props = me.styleInfos.borderInfo.getProps(),
  2974. bounds = me.boundsInfo.getBounds(),
  2975. shape, segmentsInfo, i, j, len;
  2976. if( props ) {
  2977. me.hideBorder();
  2978. segmentsInfo = me.getBorderSegmentsInfo();
  2979. for( i = j = 0, len = segmentsInfo.length; i < len; i += 2) {
  2980. shape = me.getShape( 'border' + j++, me.shapeZIndex );
  2981. shape.setSize( bounds.w, bounds.h );
  2982. shape.setAttrs(
  2983. 'path', segmentsInfo[ i ]
  2984. );
  2985. shape.setFillAttrs(
  2986. 'color', segmentsInfo[ i + 1 ]
  2987. );
  2988. }
  2989. // remove any previously-created border shapes which didn't get used above
  2990. while( me.deleteShape( 'border' + j++ ) ) {}
  2991. }
  2992. },
  2993. /**
  2994. * Adds rectangular sub-paths at intervals along a given side which serve to "cut out"
  2995. * those areas, forming the spaces in a dashed or dotted border.
  2996. * @param {Array.<string>} path The path string array to which the extra sub-paths will be added
  2997. * @param {number} startCoord The x or y coordinate at which the dashing starts
  2998. * @param {number} endCoord The x or y coordinate at which the dashing ends
  2999. * @param {number} sideWidth The width of the border on the target side
  3000. * @param {number} shift A shift of the perpendicular coordinate
  3001. * @param {boolean} isVertical True if this is a vertical border (left or right)
  3002. * @param {string} style The border style, either 'dotted' or 'dashed'
  3003. */
  3004. dashify: function( path, startCoord, endCoord, sideWidth, shift, isVertical, style ) {
  3005. var dashLength = sideWidth * ( style === 'dashed' ? 3 : 1 ),
  3006. shift2 = shift + sideWidth,
  3007. dashEndCoord;
  3008. // If dash is longer than the box edge, don't make any cutouts
  3009. if( dashLength < endCoord - startCoord ) {
  3010. // adjust the start to keep the dash pattern centered on the box edge, favoring full
  3011. // spaces over full dashes, like WebKit does.
  3012. startCoord += ( endCoord - startCoord - dashLength ) / 2 % dashLength;
  3013. // add rectangular sub-paths to cut out each dash's space
  3014. while( startCoord < endCoord ) {
  3015. dashEndCoord = Math.min( startCoord + dashLength, endCoord );
  3016. path.push(
  3017. isVertical ? (
  3018. 'm' + shift + ',' + startCoord +
  3019. 'l' + shift + ',' + dashEndCoord +
  3020. 'l' + shift2 + ',' + dashEndCoord +
  3021. 'l' + shift2 + ',' + startCoord + 'x'
  3022. ) : (
  3023. 'm' + startCoord + ',' + shift +
  3024. 'l' + dashEndCoord + ',' + shift +
  3025. 'l' + dashEndCoord + ',' + shift2 +
  3026. 'l' + startCoord + ',' + shift2 + 'x'
  3027. )
  3028. );
  3029. startCoord += dashLength * 2;
  3030. }
  3031. }
  3032. },
  3033. /**
  3034. * Get the VML path definitions for the border segment(s).
  3035. * @return {Array.<string>} Pairs of segment info: 1st item in each pair is the path string, 2nd is the fill color
  3036. */
  3037. getBorderSegmentsInfo: function() {
  3038. var me = this,
  3039. borderInfo = me.styleInfos.borderInfo,
  3040. segmentsInfo = [];
  3041. if( borderInfo.isActive() ) {
  3042. var mult = 2,
  3043. el = me.targetElement,
  3044. bounds = me.boundsInfo.getBounds(),
  3045. borderProps = borderInfo.getProps(),
  3046. widths = borderProps.widths,
  3047. styles = borderProps.styles,
  3048. colors = borderProps.colors,
  3049. M = Math,
  3050. abs = M.abs,
  3051. round = M.round,
  3052. wT = round( widths['t'].pixels( el ) ),
  3053. wR = round( widths['r'].pixels( el ) ),
  3054. wB = round( widths['b'].pixels( el ) ),
  3055. wL = round( widths['l'].pixels( el ) ),
  3056. path = [],
  3057. innerCoords, outerCoords, doubleOuterCoords, doubleInnerCoords,
  3058. sideArgs = me.sideArgs,
  3059. side,
  3060. deg = 65535,
  3061. dashedStyles = me.dashedStyles,
  3062. style, color;
  3063. // When the border has uniform color and style all the way around, we can get
  3064. // away with a single VML path shape, otherwise we need four separate shapes.
  3065. if ( borderProps.stylesSame && borderProps.colorsSame && !( styles[ 't' ] in me.colorManipStyles ) ) {
  3066. if( colors['t'].alpha() > 0 ) {
  3067. // Outer path
  3068. path[ 0 ] = me.getBoxPath( 0, 0, 0, 0, mult );
  3069. // If double style, add the middle cutout sub-paths
  3070. style = styles[ 't' ];
  3071. if( style === 'double' ) {
  3072. path.push(
  3073. me.getBoxPath( wT / 3, wR / 3, wB / 3, wL / 3, mult ) +
  3074. me.getBoxPath( wT * 2 / 3, wR * 2 / 3, wB * 2 / 3, wL * 2 / 3, mult )
  3075. );
  3076. }
  3077. // If dashed, add the dash cutout sub-paths
  3078. else if( style in dashedStyles ) {
  3079. innerCoords = me.getBoxPathCoords( wT, wR, wB, wL, mult );
  3080. me.dashify( path, innerCoords[ 2 ], innerCoords[ 4 ], wT * mult, 0, 0, styles[ 't' ] );
  3081. me.dashify( path, innerCoords[ 7 ], innerCoords[ 9 ], wR * mult, ( bounds.w - wR ) * mult, 1, styles[ 'r' ] );
  3082. me.dashify( path, innerCoords[ 12 ], innerCoords[ 10 ], wB * mult, ( bounds.h - wB ) * mult, 0, styles[ 'b' ] );
  3083. me.dashify( path, innerCoords[ 1 ], innerCoords[ 15 ], wL * mult, 0, 1, styles[ 'l' ] );
  3084. }
  3085. // Inner path
  3086. path.push( me.getBoxPath( wT, wR, wB, wL, mult ) );
  3087. segmentsInfo.push( path.join( '' ), colors['t'].colorValue( el ) );
  3088. }
  3089. }
  3090. else {
  3091. outerCoords = me.getBoxPathCoords( 0, 0, 0, 0, mult );
  3092. innerCoords = me.getBoxPathCoords( wT, wR, wB, wL, mult );
  3093. // Build the segment for each side
  3094. for( side in sideArgs ) {
  3095. if ( sideArgs.hasOwnProperty( side ) && colors[ side ].alpha() > 0 ) {
  3096. var args = sideArgs[ side ],
  3097. centerX1 = args[ 0 ],
  3098. centerY1 = args[ 1 ],
  3099. outerX1 = args[ 2 ],
  3100. outerY1 = args[ 3 ],
  3101. centerX2 = args[ 4 ],
  3102. centerY2 = args[ 5 ],
  3103. outerX2 = args[ 6 ],
  3104. outerY2 = args[ 7 ],
  3105. baseAngle = args[ 8 ],
  3106. isTopLeft = side === 't' || side === 'l';
  3107. style = styles[ side ];
  3108. // Outer edge
  3109. path[ 0 ] = 'al' + outerCoords[ centerX1 ] + ',' + outerCoords[ centerY1 ] + ',' +
  3110. abs( outerCoords[ outerX1 ] - outerCoords[ centerX1 ] ) + ',' +
  3111. abs( outerCoords[ outerY1 ] - outerCoords[ centerY1 ] ) + ',' +
  3112. ( baseAngle + 45 ) * deg + ',' + -45 * deg +
  3113. 'ae' + outerCoords[ centerX2 ] + ',' + outerCoords[ centerY2 ] + ',' +
  3114. abs( outerCoords[ outerX2 ] - outerCoords[ centerX2 ] ) + ',' +
  3115. abs( outerCoords[ outerY2 ] - outerCoords[ centerY2 ] ) + ',' +
  3116. baseAngle * deg + ',' + -45 * deg;
  3117. // If double style, add the middle sub-paths
  3118. if( style in me.doubleStyles ) {
  3119. if( !doubleOuterCoords ) {
  3120. if ( style === 'double' ) {
  3121. doubleOuterCoords = me.getBoxPathCoords( wT / 3, wR / 3, wB / 3, wL / 3, mult );
  3122. doubleInnerCoords = me.getBoxPathCoords( wT * 2 / 3, wR * 2 / 3, wB * 2 / 3, wL * 2 / 3, mult );
  3123. } else {
  3124. doubleOuterCoords = doubleInnerCoords = me.getBoxPathCoords( wT / 2, wR / 2, wB / 2, wL / 2, mult );
  3125. }
  3126. }
  3127. path.push(
  3128. 'ae' + doubleOuterCoords[ centerX2 ] + ',' + doubleOuterCoords[ centerY2 ] + ',' +
  3129. abs( doubleOuterCoords[ outerX2 ] - doubleOuterCoords[ centerX2 ] ) + ',' +
  3130. abs( doubleOuterCoords[ outerY2 ] - doubleOuterCoords[ centerY2 ] ) + ',' +
  3131. ( baseAngle - 45 ) * deg + ',' + 45 * deg +
  3132. 'ae' + doubleOuterCoords[ centerX1 ] + ',' + doubleOuterCoords[ centerY1 ] + ',' +
  3133. abs( doubleOuterCoords[ outerX1 ] - doubleOuterCoords[ centerX1 ] ) + ',' +
  3134. abs( doubleOuterCoords[ outerY1 ] - doubleOuterCoords[ centerY1 ] ) + ',' +
  3135. baseAngle * deg + ',' + 45 * deg +
  3136. 'x'
  3137. );
  3138. // Actual 'double' style with have both paths as a single shape, but 'ridge' and
  3139. // 'groove' need separate shapes for the different colors
  3140. if( style !== 'double' ) {
  3141. color = colors[ side ].colorValue( el ) + (
  3142. ( style === 'groove' ? isTopLeft : !isTopLeft ) ? ' darken(128)' : ' lighten(128)'
  3143. );
  3144. segmentsInfo.push( path.join( '' ), color );
  3145. path.length = 0; //reuse same array for next loop
  3146. }
  3147. path.push(
  3148. 'al' + doubleInnerCoords[ centerX1 ] + ',' + doubleInnerCoords[ centerY1 ] + ',' +
  3149. abs( doubleInnerCoords[ outerX1 ] - doubleInnerCoords[ centerX1 ] ) + ',' +
  3150. abs( doubleInnerCoords[ outerY1 ] - doubleInnerCoords[ centerY1 ] ) + ',' +
  3151. ( baseAngle + 45 ) * deg + ',' + -45 * deg +
  3152. 'ae' + doubleInnerCoords[ centerX2 ] + ',' + doubleInnerCoords[ centerY2 ] + ',' +
  3153. abs( doubleInnerCoords[ outerX2 ] - doubleInnerCoords[ centerX2 ] ) + ',' +
  3154. abs( doubleInnerCoords[ outerY2 ] - doubleInnerCoords[ centerY2 ] ) + ',' +
  3155. baseAngle * deg + ',' + -45 * deg
  3156. );
  3157. }
  3158. // Inner edge
  3159. path.push(
  3160. 'ae' + innerCoords[ centerX2 ] + ',' + innerCoords[ centerY2 ] + ',' +
  3161. abs( innerCoords[ outerX2 ] - innerCoords[ centerX2 ] ) + ',' +
  3162. abs( innerCoords[ outerY2 ] - innerCoords[ centerY2 ] ) + ',' +
  3163. ( baseAngle - 45 ) * deg + ',' + 45 * deg +
  3164. 'ae' + innerCoords[ centerX1 ] + ',' + innerCoords[ centerY1 ] + ',' +
  3165. abs( innerCoords[ outerX1 ] - innerCoords[ centerX1 ] ) + ',' +
  3166. abs( innerCoords[ outerY1 ] - innerCoords[ centerY1 ] ) + ',' +
  3167. baseAngle * deg + ',' + 45 * deg +
  3168. 'x'
  3169. );
  3170. // For dashed/dotted styles, add the dash cutout sub-paths
  3171. if ( style in dashedStyles ) {
  3172. side === 't' ?
  3173. me.dashify( path, innerCoords[ 2 ], innerCoords[ 4 ], wT * mult, 0, 0, style ) :
  3174. side === 'r' ?
  3175. me.dashify( path, innerCoords[ 7 ], innerCoords[ 9 ], wR * mult, ( bounds.w - wR ) * mult, 1, style ) :
  3176. side === 'b' ?
  3177. me.dashify( path, innerCoords[ 12 ], innerCoords[ 10 ], wB * mult, ( bounds.h - wB ) * mult, 0, style ) :
  3178. //side === 'l' ?
  3179. me.dashify( path, innerCoords[ 1 ], innerCoords[ 15 ], wL * mult, 0, 1, style );
  3180. }
  3181. color = colors[ side ].colorValue( el );
  3182. if ( style in me.colorManipStyles ) {
  3183. // lighten or darken as appropriate
  3184. color += (
  3185. ( ( style === 'groove' || style === 'outset' ) ? isTopLeft : !isTopLeft ) ?
  3186. ' lighten(128)' : ' darken(128)'
  3187. );
  3188. }
  3189. segmentsInfo.push( path.join( '' ), color );
  3190. path.length = 0; //reuse same array for next loop
  3191. }
  3192. }
  3193. }
  3194. }
  3195. return segmentsInfo;
  3196. },
  3197. destroy: function() {
  3198. var me = this;
  3199. if (me.finalized || !me.styleInfos.borderImageInfo.isActive()) {
  3200. me.targetElement.runtimeStyle.borderColor = '';
  3201. }
  3202. PIE.RendererBase.destroy.call( me );
  3203. }
  3204. } );
  3205. /**
  3206. * Renderer for border-image
  3207. * @constructor
  3208. * @param {Element} el The target element
  3209. * @param {Object} styleInfos The StyleInfo objects
  3210. * @param {PIE.RootRenderer} parent
  3211. */
  3212. PIE.BorderImageRenderer = PIE.RendererBase.newRenderer( {
  3213. shapeZIndex: 5,
  3214. needsUpdate: function() {
  3215. return this.styleInfos.borderImageInfo.changed();
  3216. },
  3217. isActive: function() {
  3218. return this.styleInfos.borderImageInfo.isActive();
  3219. },
  3220. draw: function() {
  3221. var me = this,
  3222. props = me.styleInfos.borderImageInfo.getProps(),
  3223. borderProps = me.styleInfos.borderInfo.getProps(),
  3224. bounds = me.boundsInfo.getBounds(),
  3225. el = me.targetElement;
  3226. PIE.Util.withImageSize( props.src, function( imgSize ) {
  3227. var me = this,
  3228. elW = bounds.w,
  3229. elH = bounds.h,
  3230. zero = PIE.getLength( '0' ),
  3231. widths = props.widths || ( borderProps ? borderProps.widths : { 't': zero, 'r': zero, 'b': zero, 'l': zero } ),
  3232. widthT = widths['t'].pixels( el ),
  3233. widthR = widths['r'].pixels( el ),
  3234. widthB = widths['b'].pixels( el ),
  3235. widthL = widths['l'].pixels( el ),
  3236. slices = props.slice,
  3237. sliceT = slices['t'].pixels( el ),
  3238. sliceR = slices['r'].pixels( el ),
  3239. sliceB = slices['b'].pixels( el ),
  3240. sliceL = slices['l'].pixels( el ),
  3241. src = props.src,
  3242. imgW = imgSize.w,
  3243. imgH = imgSize.h;
  3244. function setSizeAndPos( rect, rectX, rectY, rectW, rectH, sliceX, sliceY, sliceW, sliceH ) {
  3245. // Hide the piece entirely if we have zero dimensions for the image, the rect, or the slice
  3246. var max = Math.max;
  3247. if ( !imgW || !imgH || !rectW || !rectH || !sliceW || !sliceH ) {
  3248. rect.setStyles( 'display', 'none' );
  3249. } else {
  3250. rectW = max( rectW, 0 );
  3251. rectH = max( rectH, 0 );
  3252. rect.setAttrs(
  3253. 'path', 'm0,0l' + rectW * 2 + ',0l' + rectW * 2 + ',' + rectH * 2 + 'l0,' + rectH * 2 + 'x'
  3254. );
  3255. rect.setFillAttrs(
  3256. 'src', src,
  3257. 'type', 'tile',
  3258. 'position', '0,0',
  3259. 'origin', ( ( sliceX - 0.5 ) / imgW ) + ',' + ( ( sliceY - 0.5 ) / imgH ),
  3260. // For some reason using px units doesn't work in VML markup so we must convert to pt.
  3261. 'size', PIE.Length.pxToPt( rectW * imgW / sliceW ) + 'pt,' + PIE.Length.pxToPt( rectH * imgH / sliceH ) + 'pt'
  3262. );
  3263. rect.setSize( rectW, rectH );
  3264. rect.setStyles(
  3265. 'left', rectX + 'px',
  3266. 'top', rectY + 'px',
  3267. 'display', ''
  3268. );
  3269. }
  3270. }
  3271. // Piece positions and sizes
  3272. // TODO right now this treats everything like 'stretch', need to support other schemes
  3273. setSizeAndPos( me.getRect( 'tl' ), 0, 0, widthL, widthT, 0, 0, sliceL, sliceT );
  3274. setSizeAndPos( me.getRect( 't' ), widthL, 0, elW - widthL - widthR, widthT, sliceL, 0, imgW - sliceL - sliceR, sliceT );
  3275. setSizeAndPos( me.getRect( 'tr' ), elW - widthR, 0, widthR, widthT, imgW - sliceR, 0, sliceR, sliceT );
  3276. setSizeAndPos( me.getRect( 'r' ), elW - widthR, widthT, widthR, elH - widthT - widthB, imgW - sliceR, sliceT, sliceR, imgH - sliceT - sliceB );
  3277. setSizeAndPos( me.getRect( 'br' ), elW - widthR, elH - widthB, widthR, widthB, imgW - sliceR, imgH - sliceB, sliceR, sliceB );
  3278. setSizeAndPos( me.getRect( 'b' ), widthL, elH - widthB, elW - widthL - widthR, widthB, sliceL, imgH - sliceB, imgW - sliceL - sliceR, sliceB );
  3279. setSizeAndPos( me.getRect( 'bl' ), 0, elH - widthB, widthL, widthB, 0, imgH - sliceB, sliceL, sliceB );
  3280. setSizeAndPos( me.getRect( 'l' ), 0, widthT, widthL, elH - widthT - widthB, 0, sliceT, sliceL, imgH - sliceT - sliceB );
  3281. setSizeAndPos( me.getRect( 'c' ), widthL, widthT, elW - widthL - widthR, elH - widthT - widthB, sliceL, sliceT, props.fill ? imgW - sliceL - sliceR : 0, imgH - sliceT - sliceB );
  3282. }, me );
  3283. },
  3284. getRect: function( name ) {
  3285. return this.getShape( 'borderImage_' + name, this.shapeZIndex );
  3286. },
  3287. prepareUpdate: function() {
  3288. if (this.isActive()) {
  3289. var me = this,
  3290. el = me.targetElement,
  3291. rs = el.runtimeStyle,
  3292. widths = me.styleInfos.borderImageInfo.getProps().widths;
  3293. // Force border-style to solid so it doesn't collapse
  3294. rs.borderStyle = 'solid';
  3295. // If widths specified in border-image shorthand, override border-width
  3296. if ( widths ) {
  3297. rs.borderTopWidth = widths['t'].pixels( el );
  3298. rs.borderRightWidth = widths['r'].pixels( el );
  3299. rs.borderBottomWidth = widths['b'].pixels( el );
  3300. rs.borderLeftWidth = widths['l'].pixels( el );
  3301. }
  3302. // Make the border transparent
  3303. me.hideBorder();
  3304. }
  3305. },
  3306. destroy: function() {
  3307. var me = this,
  3308. rs = me.targetElement.runtimeStyle;
  3309. rs.borderStyle = '';
  3310. if (me.finalized || !me.styleInfos.borderInfo.isActive()) {
  3311. rs.borderColor = rs.borderWidth = '';
  3312. }
  3313. PIE.RendererBase.destroy.call( me );
  3314. }
  3315. } );
  3316. /**
  3317. * Renderer for outset box-shadows
  3318. * @constructor
  3319. * @param {Element} el The target element
  3320. * @param {Object} styleInfos The StyleInfo objects
  3321. * @param {PIE.RootRenderer} parent
  3322. */
  3323. PIE.BoxShadowOutsetRenderer = PIE.RendererBase.newRenderer( {
  3324. shapeZIndex: 1,
  3325. needsUpdate: function() {
  3326. var si = this.styleInfos;
  3327. return si.boxShadowInfo.changed() || si.borderRadiusInfo.changed();
  3328. },
  3329. isActive: function() {
  3330. var boxShadowInfo = this.styleInfos.boxShadowInfo;
  3331. return boxShadowInfo.isActive() && boxShadowInfo.getProps().outset[0];
  3332. },
  3333. draw: function() {
  3334. var me = this,
  3335. el = me.targetElement,
  3336. styleInfos = me.styleInfos,
  3337. shadowInfos = styleInfos.boxShadowInfo.getProps().outset,
  3338. radii = styleInfos.borderRadiusInfo.getProps(),
  3339. len = shadowInfos.length,
  3340. i = len,
  3341. bounds = me.boundsInfo.getBounds(),
  3342. w = bounds.w,
  3343. h = bounds.h,
  3344. shadowInfo, shape, xOff, yOff, spread, blur, shrink, color, alpha, path,
  3345. totalW, totalH, focusX, focusY, focusAdjustRatio;
  3346. while( i-- ) {
  3347. shadowInfo = shadowInfos[ i ];
  3348. xOff = shadowInfo.xOffset.pixels( el );
  3349. yOff = shadowInfo.yOffset.pixels( el );
  3350. spread = shadowInfo.spread.pixels( el );
  3351. blur = shadowInfo.blur.pixels( el );
  3352. color = shadowInfo.color;
  3353. alpha = color.alpha();
  3354. color = color.colorValue( el );
  3355. // Shape path
  3356. shrink = -spread - blur;
  3357. if( !radii && blur ) {
  3358. // If blurring, use a non-null border radius info object so that getBoxPath will
  3359. // round the corners of the expanded shadow shape rather than squaring them off.
  3360. radii = PIE.BorderRadiusStyleInfo.ALL_ZERO;
  3361. }
  3362. path = me.getBoxPath( shrink, shrink, shrink, shrink, 2, radii );
  3363. // Create the shape object
  3364. shape = me.getShape( 'shadow' + i, me.shapeZIndex + ( .5 - i / 1000 ) );
  3365. if( blur ) {
  3366. totalW = ( spread + blur ) * 2 + w;
  3367. totalH = ( spread + blur ) * 2 + h;
  3368. focusX = totalW ? blur * 2 / totalW : 0;
  3369. focusY = totalH ? blur * 2 / totalH : 0;
  3370. // If the blur is larger than half the element's narrowest dimension, then its focussize
  3371. // will to be less than zero which results in ugly artifacts. To get around this, we adjust
  3372. // the focus to keep it centered and then bump the center opacity down to match.
  3373. if (focusX > 0.5 || focusY > 0.5) {
  3374. focusAdjustRatio = 0.5 / Math.max(focusX, focusY);
  3375. focusX *= focusAdjustRatio;
  3376. focusY *= focusAdjustRatio;
  3377. alpha *= focusAdjustRatio * focusAdjustRatio; //this is a rough eyeball-adjustment, could be refined
  3378. }
  3379. shape.setFillAttrs(
  3380. 'type', 'gradienttitle', //makes the VML gradient follow the shape's outline - hooray for undocumented features?!?!
  3381. 'color2', color,
  3382. 'focusposition', focusX + ',' + focusY,
  3383. 'focussize', ( 1 - focusX * 2 ) + ',' + ( 1 - focusY * 2 ),
  3384. 'opacity', 0,
  3385. 'o:opacity2', alpha
  3386. );
  3387. } else {
  3388. shape.setFillAttrs(
  3389. 'type', 'solid',
  3390. 'opacity', alpha
  3391. );
  3392. }
  3393. shape.setAttrs(
  3394. 'path', path
  3395. );
  3396. shape.setFillAttrs( 'color', color );
  3397. shape.setStyles(
  3398. 'left', xOff + 'px',
  3399. 'top', yOff + 'px'
  3400. );
  3401. shape.setSize( w, h );
  3402. }
  3403. // Delete any shadow shapes previously created which weren't reused above
  3404. while( me.deleteShape( 'shadow' + len++ ) ) {}
  3405. }
  3406. } );
  3407. /**
  3408. * Renderer for re-rendering img elements using VML. Kicks in if the img has
  3409. * a border-radius applied, or if the -pie-png-fix flag is set.
  3410. * @constructor
  3411. * @param {Element} el The target element
  3412. * @param {Object} styleInfos The StyleInfo objects
  3413. * @param {PIE.RootRenderer} parent
  3414. */
  3415. PIE.ImgRenderer = PIE.RendererBase.newRenderer( {
  3416. shapeZIndex: 6,
  3417. needsUpdate: function() {
  3418. var si = this.styleInfos;
  3419. return this.targetElement.src !== this._lastSrc || si.borderRadiusInfo.changed();
  3420. },
  3421. isActive: function() {
  3422. var si = this.styleInfos;
  3423. return si.borderRadiusInfo.isActive() || si.backgroundInfo.isPngFix();
  3424. },
  3425. draw: function() {
  3426. this._lastSrc = src;
  3427. this.hideActualImg();
  3428. var shape = this.getShape( 'img', this.shapeZIndex ),
  3429. bounds = this.boundsInfo.getBounds(),
  3430. w = bounds.w,
  3431. h = bounds.h,
  3432. borderProps = this.styleInfos.borderInfo.getProps(),
  3433. borderWidths = borderProps && borderProps.widths,
  3434. el = this.targetElement,
  3435. src = el.src,
  3436. round = Math.round,
  3437. paddings = this.styleInfos.paddingInfo.getProps(),
  3438. zero;
  3439. // In IE6, the BorderRenderer will have hidden the border by moving the border-width to
  3440. // the padding; therefore we want to pretend the borders have no width so they aren't doubled
  3441. // when adding in the current padding value below.
  3442. if( !borderWidths || PIE.ieVersion < 7 ) {
  3443. zero = PIE.getLength( '0' );
  3444. borderWidths = { 't': zero, 'r': zero, 'b': zero, 'l': zero };
  3445. }
  3446. shape.setAttrs(
  3447. 'path', this.getBoxPath(
  3448. round( borderWidths['t'].pixels( el ) + paddings[ 't' ].pixels( el ) ),
  3449. round( borderWidths['r'].pixels( el ) + paddings[ 'r' ].pixels( el ) ),
  3450. round( borderWidths['b'].pixels( el ) + paddings[ 'b' ].pixels( el ) ),
  3451. round( borderWidths['l'].pixels( el ) + paddings[ 'l' ].pixels( el ) ),
  3452. 2
  3453. )
  3454. );
  3455. shape.setFillAttrs(
  3456. 'type', 'frame',
  3457. 'src', src,
  3458. 'position', (w ? 0.5 / w : 0) + ',' + (h ? 0.5 / h : 0)
  3459. );
  3460. shape.setSize( w, h );
  3461. },
  3462. hideActualImg: function() {
  3463. this.targetElement.runtimeStyle.filter = 'alpha(opacity=0)';
  3464. },
  3465. destroy: function() {
  3466. PIE.RendererBase.destroy.call( this );
  3467. this.targetElement.runtimeStyle.filter = '';
  3468. }
  3469. } );
  3470. PIE.Element = (function() {
  3471. var wrappers = {},
  3472. lazyInitCssProp = PIE.CSS_PREFIX + 'lazy-init',
  3473. pollCssProp = PIE.CSS_PREFIX + 'poll',
  3474. trackActiveCssProp = PIE.CSS_PREFIX + 'track-active',
  3475. trackHoverCssProp = PIE.CSS_PREFIX + 'track-hover',
  3476. hoverClass = PIE.CLASS_PREFIX + 'hover',
  3477. activeClass = PIE.CLASS_PREFIX + 'active',
  3478. focusClass = PIE.CLASS_PREFIX + 'focus',
  3479. firstChildClass = PIE.CLASS_PREFIX + 'first-child',
  3480. ignorePropertyNames = { 'background':1, 'bgColor':1, 'display': 1 },
  3481. classNameRegExes = {},
  3482. dummyArray = [];
  3483. function addClass( el, className ) {
  3484. el.className += ' ' + className;
  3485. }
  3486. function removeClass( el, className ) {
  3487. var re = classNameRegExes[ className ] ||
  3488. ( classNameRegExes[ className ] = new RegExp( '\\b' + className + '\\b', 'g' ) );
  3489. el.className = el.className.replace( re, '' );
  3490. }
  3491. function delayAddClass( el, className /*, className2*/ ) {
  3492. var classes = dummyArray.slice.call( arguments, 1 ),
  3493. i = classes.length;
  3494. setTimeout( function() {
  3495. if( el ) {
  3496. while( i-- ) {
  3497. addClass( el, classes[ i ] );
  3498. }
  3499. }
  3500. }, 0 );
  3501. }
  3502. function delayRemoveClass( el, className /*, className2*/ ) {
  3503. var classes = dummyArray.slice.call( arguments, 1 ),
  3504. i = classes.length;
  3505. setTimeout( function() {
  3506. if( el ) {
  3507. while( i-- ) {
  3508. removeClass( el, classes[ i ] );
  3509. }
  3510. }
  3511. }, 0 );
  3512. }
  3513. function Element( el ) {
  3514. var me = this,
  3515. childRenderers,
  3516. rootRenderer,
  3517. boundsInfo = new PIE.BoundsInfo( el ),
  3518. styleInfos,
  3519. styleInfosArr,
  3520. initializing,
  3521. initialized,
  3522. eventsAttached,
  3523. eventListeners = [],
  3524. delayed,
  3525. destroyed,
  3526. poll;
  3527. me.el = el;
  3528. /**
  3529. * Initialize PIE for this element.
  3530. */
  3531. function init() {
  3532. if( !initialized ) {
  3533. var docEl,
  3534. bounds,
  3535. ieDocMode = PIE.ieDocMode,
  3536. cs = el.currentStyle,
  3537. lazy = cs.getAttribute( lazyInitCssProp ) === 'true',
  3538. trackActive = cs.getAttribute( trackActiveCssProp ) !== 'false',
  3539. trackHover = cs.getAttribute( trackHoverCssProp ) !== 'false';
  3540. // Polling for size/position changes: default to on in IE8, off otherwise, overridable by -pie-poll
  3541. poll = cs.getAttribute( pollCssProp );
  3542. poll = ieDocMode > 7 ? poll !== 'false' : poll === 'true';
  3543. // Force layout so move/resize events will fire. Set this as soon as possible to avoid layout changes
  3544. // after load, but make sure it only gets called the first time through to avoid recursive calls to init().
  3545. if( !initializing ) {
  3546. initializing = 1;
  3547. el.runtimeStyle.zoom = 1;
  3548. initFirstChildPseudoClass();
  3549. }
  3550. boundsInfo.lock();
  3551. // If the -pie-lazy-init:true flag is set, check if the element is outside the viewport and if so, delay initialization
  3552. if( lazy && ( bounds = boundsInfo.getBounds() ) && ( docEl = doc.documentElement || doc.body ) &&
  3553. ( bounds.y > docEl.clientHeight || bounds.x > docEl.clientWidth || bounds.y + bounds.h < 0 || bounds.x + bounds.w < 0 ) ) {
  3554. if( !delayed ) {
  3555. delayed = 1;
  3556. PIE.OnScroll.observe( init );
  3557. }
  3558. } else {
  3559. initialized = 1;
  3560. delayed = initializing = 0;
  3561. PIE.OnScroll.unobserve( init );
  3562. // Create the style infos and renderers
  3563. if ( ieDocMode === 9 ) {
  3564. styleInfos = {
  3565. backgroundInfo: new PIE.BackgroundStyleInfo( el ),
  3566. borderImageInfo: new PIE.BorderImageStyleInfo( el ),
  3567. borderInfo: new PIE.BorderStyleInfo( el ),
  3568. paddingInfo: new PIE.PaddingStyleInfo( el )
  3569. };
  3570. styleInfosArr = [
  3571. styleInfos.backgroundInfo,
  3572. styleInfos.borderInfo,
  3573. styleInfos.borderImageInfo,
  3574. styleInfos.paddingInfo
  3575. ];
  3576. rootRenderer = new PIE.IE9RootRenderer( el, boundsInfo, styleInfos );
  3577. childRenderers = [
  3578. new PIE.IE9BackgroundRenderer( el, boundsInfo, styleInfos, rootRenderer ),
  3579. new PIE.IE9BorderImageRenderer( el, boundsInfo, styleInfos, rootRenderer )
  3580. ];
  3581. } else {
  3582. styleInfos = {
  3583. backgroundInfo: new PIE.BackgroundStyleInfo( el ),
  3584. borderInfo: new PIE.BorderStyleInfo( el ),
  3585. borderImageInfo: new PIE.BorderImageStyleInfo( el ),
  3586. borderRadiusInfo: new PIE.BorderRadiusStyleInfo( el ),
  3587. boxShadowInfo: new PIE.BoxShadowStyleInfo( el ),
  3588. paddingInfo: new PIE.PaddingStyleInfo( el ),
  3589. visibilityInfo: new PIE.VisibilityStyleInfo( el )
  3590. };
  3591. styleInfosArr = [
  3592. styleInfos.backgroundInfo,
  3593. styleInfos.borderInfo,
  3594. styleInfos.borderImageInfo,
  3595. styleInfos.borderRadiusInfo,
  3596. styleInfos.boxShadowInfo,
  3597. styleInfos.paddingInfo,
  3598. styleInfos.visibilityInfo
  3599. ];
  3600. rootRenderer = new PIE.RootRenderer( el, boundsInfo, styleInfos );
  3601. childRenderers = [
  3602. new PIE.BoxShadowOutsetRenderer( el, boundsInfo, styleInfos, rootRenderer ),
  3603. new PIE.BackgroundRenderer( el, boundsInfo, styleInfos, rootRenderer ),
  3604. //new PIE.BoxShadowInsetRenderer( el, boundsInfo, styleInfos, rootRenderer ),
  3605. new PIE.BorderRenderer( el, boundsInfo, styleInfos, rootRenderer ),
  3606. new PIE.BorderImageRenderer( el, boundsInfo, styleInfos, rootRenderer )
  3607. ];
  3608. if( el.tagName === 'IMG' ) {
  3609. childRenderers.push( new PIE.ImgRenderer( el, boundsInfo, styleInfos, rootRenderer ) );
  3610. }
  3611. rootRenderer.childRenderers = childRenderers; // circular reference, can't pass in constructor; TODO is there a cleaner way?
  3612. }
  3613. // Add property change listeners to ancestors if requested
  3614. initAncestorEventListeners();
  3615. // Add to list of polled elements when -pie-poll:true
  3616. if( poll ) {
  3617. PIE.Heartbeat.observe( update );
  3618. PIE.Heartbeat.run();
  3619. }
  3620. // Trigger rendering
  3621. update( 0, 1 );
  3622. }
  3623. if( !eventsAttached ) {
  3624. eventsAttached = 1;
  3625. if( ieDocMode < 9 ) {
  3626. addListener( el, 'onmove', handleMoveOrResize );
  3627. }
  3628. addListener( el, 'onresize', handleMoveOrResize );
  3629. addListener( el, 'onpropertychange', propChanged );
  3630. if( trackHover ) {
  3631. addListener( el, 'onmouseenter', mouseEntered );
  3632. }
  3633. if( trackHover || trackActive ) {
  3634. addListener( el, 'onmouseleave', mouseLeft );
  3635. }
  3636. if( trackActive ) {
  3637. addListener( el, 'onmousedown', mousePressed );
  3638. }
  3639. if( el.tagName in PIE.focusableElements ) {
  3640. addListener( el, 'onfocus', focused );
  3641. addListener( el, 'onblur', blurred );
  3642. }
  3643. PIE.OnResize.observe( handleMoveOrResize );
  3644. PIE.OnUnload.observe( removeEventListeners );
  3645. }
  3646. boundsInfo.unlock();
  3647. }
  3648. }
  3649. /**
  3650. * Event handler for onmove and onresize events. Invokes update() only if the element's
  3651. * bounds have previously been calculated, to prevent multiple runs during page load when
  3652. * the element has no initial CSS3 properties.
  3653. */
  3654. function handleMoveOrResize() {
  3655. if( boundsInfo && boundsInfo.hasBeenQueried() ) {
  3656. update();
  3657. }
  3658. }
  3659. /**
  3660. * Update position and/or size as necessary. Both move and resize events call
  3661. * this rather than the updatePos/Size functions because sometimes, particularly
  3662. * during page load, one will fire but the other won't.
  3663. */
  3664. function update( isPropChange, force ) {
  3665. if( !destroyed ) {
  3666. if( initialized ) {
  3667. lockAll();
  3668. var i = 0, len = childRenderers.length,
  3669. sizeChanged = boundsInfo.sizeChanged();
  3670. for( ; i < len; i++ ) {
  3671. childRenderers[i].prepareUpdate();
  3672. }
  3673. for( i = 0; i < len; i++ ) {
  3674. if( force || sizeChanged || ( isPropChange && childRenderers[i].needsUpdate() ) ) {
  3675. childRenderers[i].updateRendering();
  3676. }
  3677. }
  3678. if( force || sizeChanged || isPropChange || boundsInfo.positionChanged() ) {
  3679. rootRenderer.updateRendering();
  3680. }
  3681. unlockAll();
  3682. }
  3683. else if( !initializing ) {
  3684. init();
  3685. }
  3686. }
  3687. }
  3688. /**
  3689. * Handle property changes to trigger update when appropriate.
  3690. */
  3691. function propChanged() {
  3692. // Some elements like <table> fire onpropertychange events for old-school background properties
  3693. // ('background', 'bgColor') when runtimeStyle background properties are changed, which
  3694. // results in an infinite loop; therefore we filter out those property names. Also, 'display'
  3695. // is ignored because size calculations don't work correctly immediately when its onpropertychange
  3696. // event fires, and because it will trigger an onresize event anyway.
  3697. if( initialized && !( event && event.propertyName in ignorePropertyNames ) ) {
  3698. update( 1 );
  3699. }
  3700. }
  3701. /**
  3702. * Handle mouseenter events. Adds a custom class to the element to allow IE6 to add
  3703. * hover styles to non-link elements, and to trigger a propertychange update.
  3704. */
  3705. function mouseEntered() {
  3706. //must delay this because the mouseenter event fires before the :hover styles are added.
  3707. delayAddClass( el, hoverClass );
  3708. }
  3709. /**
  3710. * Handle mouseleave events
  3711. */
  3712. function mouseLeft() {
  3713. //must delay this because the mouseleave event fires before the :hover styles are removed.
  3714. delayRemoveClass( el, hoverClass, activeClass );
  3715. }
  3716. /**
  3717. * Handle mousedown events. Adds a custom class to the element to allow IE6 to add
  3718. * active styles to non-link elements, and to trigger a propertychange update.
  3719. */
  3720. function mousePressed() {
  3721. //must delay this because the mousedown event fires before the :active styles are added.
  3722. delayAddClass( el, activeClass );
  3723. // listen for mouseups on the document; can't just be on the element because the user might
  3724. // have dragged out of the element while the mouse button was held down
  3725. PIE.OnMouseup.observe( mouseReleased );
  3726. }
  3727. /**
  3728. * Handle mouseup events
  3729. */
  3730. function mouseReleased() {
  3731. //must delay this because the mouseup event fires before the :active styles are removed.
  3732. delayRemoveClass( el, activeClass );
  3733. PIE.OnMouseup.unobserve( mouseReleased );
  3734. }
  3735. /**
  3736. * Handle focus events. Adds a custom class to the element to trigger a propertychange update.
  3737. */
  3738. function focused() {
  3739. //must delay this because the focus event fires before the :focus styles are added.
  3740. delayAddClass( el, focusClass );
  3741. }
  3742. /**
  3743. * Handle blur events
  3744. */
  3745. function blurred() {
  3746. //must delay this because the blur event fires before the :focus styles are removed.
  3747. delayRemoveClass( el, focusClass );
  3748. }
  3749. /**
  3750. * Handle property changes on ancestors of the element; see initAncestorEventListeners()
  3751. * which adds these listeners as requested with the -pie-watch-ancestors CSS property.
  3752. */
  3753. function ancestorPropChanged() {
  3754. var name = event.propertyName;
  3755. if( name === 'className' || name === 'id' || name.indexOf( 'style.' ) === 0 ) {
  3756. propChanged();
  3757. }
  3758. }
  3759. function lockAll() {
  3760. boundsInfo.lock();
  3761. for( var i = styleInfosArr.length; i--; ) {
  3762. styleInfosArr[i].lock();
  3763. }
  3764. }
  3765. function unlockAll() {
  3766. for( var i = styleInfosArr.length; i--; ) {
  3767. styleInfosArr[i].unlock();
  3768. }
  3769. boundsInfo.unlock();
  3770. }
  3771. function addListener( targetEl, type, handler ) {
  3772. targetEl.attachEvent( type, handler );
  3773. eventListeners.push( [ targetEl, type, handler ] );
  3774. }
  3775. /**
  3776. * Remove all event listeners from the element and any monitored ancestors.
  3777. */
  3778. function removeEventListeners() {
  3779. if (eventsAttached) {
  3780. var i = eventListeners.length,
  3781. listener;
  3782. while( i-- ) {
  3783. listener = eventListeners[ i ];
  3784. listener[ 0 ].detachEvent( listener[ 1 ], listener[ 2 ] );
  3785. }
  3786. PIE.OnUnload.unobserve( removeEventListeners );
  3787. eventsAttached = 0;
  3788. eventListeners = [];
  3789. }
  3790. }
  3791. /**
  3792. * Clean everything up when the behavior is removed from the element, or the element
  3793. * is manually destroyed.
  3794. */
  3795. function destroy() {
  3796. if( !destroyed ) {
  3797. var i, len;
  3798. removeEventListeners();
  3799. destroyed = 1;
  3800. // destroy any active renderers
  3801. if( childRenderers ) {
  3802. for( i = 0, len = childRenderers.length; i < len; i++ ) {
  3803. childRenderers[i].finalized = 1;
  3804. childRenderers[i].destroy();
  3805. }
  3806. }
  3807. rootRenderer.destroy();
  3808. // Remove from list of polled elements in IE8
  3809. if( poll ) {
  3810. PIE.Heartbeat.unobserve( update );
  3811. }
  3812. // Stop onresize listening
  3813. PIE.OnResize.unobserve( update );
  3814. // Kill references
  3815. childRenderers = rootRenderer = boundsInfo = styleInfos = styleInfosArr = el = null;
  3816. me.el = me = 0;
  3817. }
  3818. }
  3819. /**
  3820. * If requested via the custom -pie-watch-ancestors CSS property, add onpropertychange and
  3821. * other event listeners to ancestor(s) of the element so we can pick up style changes
  3822. * based on CSS rules using descendant selectors.
  3823. */
  3824. function initAncestorEventListeners() {
  3825. var watch = el.currentStyle.getAttribute( PIE.CSS_PREFIX + 'watch-ancestors' ),
  3826. i, a;
  3827. if( watch ) {
  3828. watch = parseInt( watch, 10 );
  3829. i = 0;
  3830. a = el.parentNode;
  3831. while( a && ( watch === 'NaN' || i++ < watch ) ) {
  3832. addListener( a, 'onpropertychange', ancestorPropChanged );
  3833. addListener( a, 'onmouseenter', mouseEntered );
  3834. addListener( a, 'onmouseleave', mouseLeft );
  3835. addListener( a, 'onmousedown', mousePressed );
  3836. if( a.tagName in PIE.focusableElements ) {
  3837. addListener( a, 'onfocus', focused );
  3838. addListener( a, 'onblur', blurred );
  3839. }
  3840. a = a.parentNode;
  3841. }
  3842. }
  3843. }
  3844. /**
  3845. * If the target element is a first child, add a pie_first-child class to it. This allows using
  3846. * the added class as a workaround for the fact that PIE's rendering element breaks the :first-child
  3847. * pseudo-class selector.
  3848. */
  3849. function initFirstChildPseudoClass() {
  3850. var tmpEl = el,
  3851. isFirst = 1;
  3852. while( tmpEl = tmpEl.previousSibling ) {
  3853. if( tmpEl.nodeType === 1 ) {
  3854. isFirst = 0;
  3855. break;
  3856. }
  3857. }
  3858. if( isFirst ) {
  3859. addClass( el, firstChildClass );
  3860. }
  3861. }
  3862. // These methods are all already bound to this instance so there's no need to wrap them
  3863. // in a closure to maintain the 'this' scope object when calling them.
  3864. me.init = init;
  3865. me.destroy = destroy;
  3866. }
  3867. Element.getInstance = function( el ) {
  3868. var id = el[ 'uniqueID' ];
  3869. return wrappers[ id ] || ( wrappers[ id ] = new Element( el ) );
  3870. };
  3871. Element.destroy = function( el ) {
  3872. var id = el[ 'uniqueID' ],
  3873. wrapper = wrappers[ id ];
  3874. if( wrapper ) {
  3875. wrapper.destroy();
  3876. delete wrappers[ id ];
  3877. }
  3878. };
  3879. Element.destroyAll = function() {
  3880. var els = [], wrapper;
  3881. if( wrappers ) {
  3882. for( var w in wrappers ) {
  3883. if( wrappers.hasOwnProperty( w ) ) {
  3884. wrapper = wrappers[ w ];
  3885. els.push( wrapper.el );
  3886. wrapper.destroy();
  3887. }
  3888. }
  3889. wrappers = {};
  3890. }
  3891. return els;
  3892. };
  3893. return Element;
  3894. })();
  3895. /*
  3896. * This file exposes the public API for invoking PIE.
  3897. */
  3898. /**
  3899. * The version number of this PIE build.
  3900. */
  3901. PIE[ 'version' ] = '2.0beta1';
  3902. /**
  3903. * @property supportsVML
  3904. * True if the current IE browser environment has a functioning VML engine. Should be true
  3905. * in most IEs, but in rare cases may be false. If false, PIE will exit immediately when
  3906. * attached to an element (for IE<9) to prevent errors; this property may also be used for
  3907. * debugging or by external scripts to perform some special action when VML support is absent.
  3908. * @type {boolean}
  3909. */
  3910. PIE[ 'supportsVML' ] = PIE.supportsVML;
  3911. /**
  3912. * Programatically attach PIE to a single element.
  3913. * @param {Element} el
  3914. */
  3915. PIE[ 'attach' ] = function( el ) {
  3916. if ( PIE.ieDocMode === 9 || ( PIE.ieDocMode < 9 && PIE.supportsVML ) ) {
  3917. PIE.Element.getInstance( el ).init();
  3918. }
  3919. };
  3920. /**
  3921. * Programatically detach PIE from a single element.
  3922. * @param {Element} el
  3923. */
  3924. PIE[ 'detach' ] = function( el ) {
  3925. PIE.Element.destroy( el );
  3926. };
  3927. })( window, document );