code_text
stringlengths
604
999k
repo_name
stringlengths
4
100
file_path
stringlengths
4
873
language
stringclasses
23 values
license
stringclasses
15 values
size
int32
1.02k
999k
// (c) ammap.com | SVG (in JSON format) map of Taiwan // areas: {id:"TW-TP"},{id:"TW-TW"},{id:"TW-KH"},{id:"TW-FK"} AmCharts.maps.taiwanLow={ "svg": { "defs": { "amcharts:ammap": { "projection":"mercator", "leftLongitude":"118.151413", "topLatitude":"26.384406", "rightLongitude":"122.006208", "bottomLatitude":"21.896077" } }, "g":{ "path":[ { "id":"TW-TP", "title":"Taipei", "d":"M545.85,156.9L550.68,158.75L553.79,164.47L555.11,169.47L551.75,173.97L545.95,179.15L538.38,181.78L533.98,180.66L533.98,180.66L533.79,174.64L536.83,169.64L536.83,169.64L539.05,164.65L540.69,163.15L539.7,159.88z" }, { "id":"TW-TW", "title":"Taiwan", "d":"M551.92,532.15l0.13,0.13l0.35,-0.07v0.24l-0.47,0.03l-0.13,-0.13L551.92,532.15zM550.81,531.44l0.35,0.67l-0.16,0.68l-0.19,0.1l0.09,1.05l0.6,0.41l0.19,0.44l-0.13,0.1l-0.06,-0.2H551l-0.03,0.24l-0.22,-0.03l-0.44,0.47v0.51l0.47,1.15l1.29,1.01l2.01,0.91l0.47,0.51l0.03,0.34l-0.54,0.57l-0.38,1.18l-0.44,0.34l-0.5,0.03l-0.5,-0.37l-1.26,0.17l-0.16,-0.91l-0.31,-0.2l-0.13,-0.37l-0.72,-0.78l-1.04,-0.57l-1.26,0.3l-1.13,-1.01l-0.41,-0.81l-0.5,-0.13l-0.5,-0.61v-0.27h-0.54l-0.19,0.17l-0.13,-0.34l0.25,-0.24v-0.24l-0.47,-0.64l0.31,-0.34l-0.03,-0.47l0.22,-0.24l-0.28,-0.71l-1.04,-1.15l0.13,-0.34l0.47,-0.24h0.22l0.63,0.51h0.91l0.76,-0.2l0.31,0.1l0.19,0.27l0.13,-0.17l1.04,-0.17l1.79,-0.13l0.38,0.34L550.81,531.44zM416.07,498.63l0.38,0.41l0.57,0.24l0.09,0.47l-0.16,0.58l-1.26,0.81v0.2l-0.54,0.3l-0.72,0.95l-0.72,0.3l-0.69,-0.27l-0.09,-0.3l0.19,-0.54l0.63,-0.44l0.13,-0.51l0.25,-0.17l-0.25,-0.85l0.91,-0.75L416.07,498.63zM403.06,467.02l1.04,0.27l0.5,0.58l-0.06,0.64l0.25,-0.1l0.19,0.2l0.09,0.24l-0.16,0.41l0.28,0.41l0,0.27l0.6,0.27l1.32,1.7l0.09,0.44l-0.19,0.2l0.19,0.1l0.28,-0.3l0.5,0.85l1.07,1.05l-0.32,0.34l-0.28,-0.13l-0.38,-0.58l-0.35,0.14l-0.25,-0.27l-0.41,-1.02l-2.58,-3.15l-1.07,-1.7l-0.41,-0.44l-0.13,0.14l-0.16,-0.07v-0.27L403.06,467.02zM542.09,459.08l0.16,0.44l0.53,0.03l1.29,-0.41l0.22,0.44l-0.03,0.98l0.44,0.17l-0.6,0.47l0.06,0.2l-0.25,0.44l0.06,0.2l0.35,-0.1v0.3l-0.94,0.34l-0.28,0.61l0.57,0.64l0.06,0.37l0.38,0.48l-0.06,0.2l-1.01,-0.1l-0.13,0.17l-0.38,-0.03l-0.38,-0.85l-0.5,-0.41l-1.35,-0.37l-0.19,0.1l-0.22,-0.17l0.19,-0.68v-0.81l-0.41,-0.81l-0.75,-0.68v-0.82l0.16,-0.2h0.31l1.26,0.44l0.63,-0.54l0.63,0.07L542.09,459.08zM544.36,458.77l0.22,0.14l-0.16,0.27l-0.28,-0.24L544.36,458.77zM533.75,404.28l0.09,0.2l0.57,-0.14l0.09,0.17l-0.63,0.41h-0.69v-0.17L533.75,404.28zM309.68,392.77l0.76,0.2l-0.22,0.51l-0.35,0.24l-0.09,1.06l0.19,0.44l-0.22,0.27l-0.69,-0.24l-0.41,0.58l-0.32,0.1l0.25,0.98l-0.28,0.29l-0.16,-0.41l-0.41,-0.2l-0.35,0.1l0,-0.27l-0.41,-0.04l0.03,-0.13l0.41,-0.1l-0.03,-0.13l-0.44,0.07l0.32,-0.41l-0.01,-0.65l-1.17,-1.09l-0.03,-0.34l0.22,-0.06l0.13,0.2l-0.03,-0.27l0.22,0.03l0.13,-0.17l0.47,0.03l0.25,-0.2l0.5,0.03L309.68,392.77zM329.5,388.87l0.57,0.09l-0.16,0.61l0.25,0.51l-0.25,-0.14l-0.38,0.24l-0.54,-0.24l-0.44,-0.44l0.19,-0.44L329.5,388.87zM336.4,387.62l0.29,0.11l0.09,0.41l-0.22,-0.03l-0.13,0.72l-0.35,0.2v0.17l-0.16,-0.03l0.19,0.57l-0.38,0.41l-0.72,-0.88l0.13,-0.34l0.18,-0.03l-0.31,-0.68l0.38,-0.42l0.66,0.01L336.4,387.62zM334.58,387.52l0.09,0.24l-0.22,0.35l-0.44,0l0.03,-0.38L334.58,387.52zM318.51,387.44l0.38,0.25l-0.03,0.24l-0.35,0.13l-0.41,0.68l-0.32,-0.1l-0.13,0.34l-0.35,-0.13l-0.03,-0.31l0.38,-0.14l0.25,-0.31l0,-0.38L318.51,387.44zM317.41,386.49l0.18,0.32l-0.02,0.55l-0.57,-0.1l-0.35,-0.24l-0.03,-0.48L317.41,386.49zM316.46,384.18l0.22,0.26l-0.38,0.46v-0.65L316.46,384.18zM297.76,380.34l0.25,0.54l-0.19,0.31l-0.22,-0.1l-0.09,-0.27l0.03,-0.31L297.76,380.34zM295.96,379.79l0.19,0.37l0.41,0.07l-0.03,0.17l-0.47,0.03l-0.41,-0.17l0.19,-0.2l-0.03,-0.25L295.96,379.79zM320.65,376.95l0.19,0.04l-0.13,0.27l-0.22,-0.14L320.65,376.95zM320.49,375.39l0.13,0.54l-0.32,-0.1v-0.31L320.49,375.39zM390.02,375.32l0.35,0.1l0.09,0.34l-0.13,0.14l0.19,0.38l-0.28,-0.31l-0.28,0.03l-0.19,-0.31v-0.34L390.02,375.32zM318.97,373.92l0.3,0.03l0.12,0.28l-0.5,-0.07L318.97,373.92zM320.49,373.75l0.5,0.58l0.13,0.31l-0.09,0.31l0.31,0.3l-0.37,0.07l-0.1,-0.17l-0.35,0.1l-0.54,-0.2l-0.03,0.17l-0.69,0.37l0.09,0.38l-0.16,0.23l-0.25,0.04l0.13,-0.41l-0.25,-0.07l-0.25,0.14l0.06,-0.34l-0.31,-0.17l0.03,-0.27l0.16,-0.17l0.57,0.14l0.25,-0.31l-0.03,-0.48l0.23,-0.07l0.25,0.14l0.07,-0.2l0.34,0.03L320.49,373.75zM319.49,373.48l0.19,0.2l-0.06,0.2l-0.38,-0.34L319.49,373.48zM317.91,372.79l0.16,0.44l-0.34,0.11l-0.03,-0.55L317.91,372.79zM315.68,371.28l0.06,0.25l0.35,0.16v0.31l0.28,-0.07l0.16,0.17l0.25,-0.55l0.16,0l0.29,0.38l-0.13,1.12l0.18,-0.03l0.04,0.75l0.41,0.17l-0.38,0.48l0.44,0l0.16,-0.44l0.28,0.24l-0.19,0.27l0.03,0.55l-0.38,0.1l-0.03,0.14h-0.16l-0.04,-0.17l-0.28,0.14l0.25,0.38l-0.16,0.27l0.09,0.41l0.25,0.03l0.25,0.44l-0.47,-0.14l-0.41,0.14l-0.09,-0.34l-0.38,-0.07l-0.25,0.31l-0.41,-0.14l-0.66,0.34l-0.06,-0.38l-0.54,-0.17l0.85,-1.09l0.22,-0.01l-0.25,-0.61l0.25,-0.31l-0.22,0.03l-0.09,-0.38l0.2,-0.31l-0.26,-0.23l0.06,-0.31l0.38,-0.38v-0.27l-0.25,-0.17l-0.13,-0.51l-0.35,-0.07l0.25,-0.48L315.68,371.28zM295.9,369.35l0.22,0.27l0.35,0.07l0.09,0.31l0.44,-0.03l0.19,0.44l-0.35,0.24l0,0.38l-0.82,0.13l-0.13,0.17h-0.5l-0.22,-0.78l0.44,-0.38l0.03,-0.65L295.9,369.35zM390.31,366.1l0.03,0.21l0.28,0.07l-0.13,0.38l-0.35,-0.24l-0.03,-0.34L390.31,366.1zM543.22,362.79v0.44l-0.31,-0.03l0.06,-0.34L543.22,362.79zM320.56,358.8l0.83,0.48l-0.04,0.21l-0.66,0.07l-1.01,0.79l-1.52,0.16l-0.25,0.28h-0.38l-0.25,-0.21l0.07,-0.92l0.44,0.03l0.19,0.58l0.13,-0.24l0.19,0.14l0.22,-0.2l0.11,-0.44l0.65,-0.03l0.28,-0.38h0.72L320.56,358.8zM318.76,356.81l0.06,0.7l-0.38,0.14l-0.57,-0.17l0.19,-0.65l0.25,0l0.13,0.34l0.06,-0.31L318.76,356.81zM320.08,353.47v0.48l-0.28,-0.31h-0.31l0.06,-0.14L320.08,353.47zM321.03,351.77l0.25,0.3l-0.32,0.14l-0.06,-0.38L321.03,351.77zM336.4,345.67l0.03,0.18l-0.38,0.27l-0.32,-0.21l0.03,-0.14L336.4,345.67zM333.46,345.06l0.45,0.14l0.28,0.31l0,0.48l-0.22,0.27l0.06,0.27l0.25,0.14l0.35,-0.07l0.13,0.17l-0.35,0.38l0.06,0.34l0.22,0.07l0.13,-0.21l0.22,0.1l0.28,-0.2l0.04,-0.28l-0.48,0.11l-0.25,-0.1l0.66,-0.17v-0.55l0.16,-0.17l0.41,0.17l0.16,0.69l0.41,-0.14l0.03,0.82l0.28,0.14v0.31l0.32,0.24l-0.16,0.41l0.13,0.51l-0.25,0.38l0.25,0.1l-0.09,0.31l0.13,0.07l0.03,0.55l0.09,0.17l0.6,0.2l0.19,-0.1l0.12,0.24l0.28,0l-0.03,0.68l0.16,0.21l-0.79,0.07l-0.09,-0.17l-0.03,0.24l-0.35,0.17l-0.35,-0.2l-0.22,0.38l-0.44,-0.17l-0.25,-0.34l0.09,-0.27l0.28,-0.03l-0.25,-0.41l-0.29,0.1l-0.38,-0.34l-0.35,0.03l-0.16,0.24l-1.67,-0.07l-0.44,-0.21l-0.88,0.92l0.03,0.21l0.28,-0.03l0.03,0.17l-0.6,-0.07l-0.09,0.72l-0.44,0.1l-0.16,-0.28l-0.13,0.32l-0.35,0.03l-0.47,0.38l0.13,0.27l-0.13,0.41l-0.19,0.07l-0.25,-0.31l-0.41,0.07l-0.16,0.27l0.06,0.31l-0.28,0.03l-0.19,0.41l-0.28,0.07l-0.09,0.65l0.76,0.14l-0.13,0.48l-0.57,0.27l0.25,0.31l0.1,0.72l-0.44,0.06l-0.09,-0.17l-0.41,-0.03l-0.19,-0.33l-0.34,0.16l-0.06,-0.31l-0.31,0.07l-0.28,-0.17l-0.19,0.1l0.03,0.27l-0.35,0.21l-0.82,0.03l-0.31,0.24l-0.5,-0.14l-0.16,-0.68l0.38,-0.44l-0.13,-0.61l-0.72,-0.52l-0.28,0.07l-0.16,0.27l-0.66,0.03l-0.35,-0.61l0.03,-0.38l-0.22,-0.17l-0.38,0l-0.06,-0.34l0.25,-0.21l-0.12,-0.24l-0.57,0.24l-0.41,-0.1l-0.03,-0.51h0.16l0.06,-0.75l0.19,-0.07l0.06,0.21l0.28,-0.14l0.03,-0.68l0.31,-0.1l-0.13,0.44l0.5,0.3l-0.19,0.18l0.1,0.75l0.63,0.38l0.06,0.61l-0.28,0.24l-0.03,0.27l0.63,0.24l-0.13,-0.41l0.57,-0.17l-0.06,-0.34l0.13,-0.14l0.19,0.1l0.09,0.41l0.47,-0.28v0.24l0.38,0.41l-0.38,0.41l0.38,0.55l0.09,-0.21h0.19l0.31,-0.58l-0.12,-0.72l0.28,-0.2l0.44,0.24l0.03,0.31l0.38,-0.34l0.35,0.13l0.09,0.41l0.28,-0.1l-0.06,-0.31l0.25,-0.07l-0.31,-0.17v-0.24l-0.38,-0.34l-0.06,-0.34l0.35,0.14l0.44,-0.07l0.19,-0.82l0.38,-0.1l0.13,-0.41l-1.01,0.41l-0.47,-0.31h-0.47l-0.25,0.34l-0.41,-0.14l-0.82,0.31l-0.19,-0.24l-0.35,-0.03l-0.16,-0.27l-0.25,0.07l-0.09,0.34l-0.06,-0.17l-0.22,0.06l0.06,-0.38l0.16,-0.07l-0.25,-0.03l0.03,-0.44l0.31,-0.14l0.79,0.21l0.22,-0.17l-0.06,-0.31l0.38,0.2l0.06,-0.14l-0.19,-0.17l0.41,-0.48l-0.5,-0.45l-0.38,0.41l-0.35,0.04l-0.22,0.34l-0.1,-0.17l-0.28,0.14l-0.16,-0.1l-0.35,0.24l-0.35,-0.31l0.03,-0.17l0.47,-0.03l0.03,-0.38l0.29,-0.21l-0.07,-0.27l0.54,-0.44l-0.03,-0.38l-0.67,-0.96l0.76,0.03l0.22,-0.2l0.54,0.1l0.35,-0.55l0.38,0.03l0.1,-0.44l0.31,-0.14l0.06,0.34l0.25,0.17l0.03,0.44l-0.38,0.55l0.28,0.21v0.27l0.35,-0.07l-0.19,0.61l0.31,0.07l0.16,-0.24l0.31,0.03l0.22,0.51l0.19,-0.48l-0.16,-0.21l0.16,-0.44l-0.16,-0.58l-0.19,-0.1l0.06,-0.27h0.28l0.22,0.24l0.72,-0.07l-0.13,-0.92l-0.47,-0.44l0.16,-0.41l0.25,-0.21l0.09,-0.34l0.66,0.07l-0.06,0.31l0.32,0l0.44,-0.27l-0.06,0.27l0.13,0.03l0.25,-0.17l-0.16,-0.21l0.25,-0.21L330,345.2l0.19,-0.03l0.72,0.34l0.22,-0.1v0.27l0.22,0.07l-0.19,0.27l-0.35,-0.07l-0.19,0.24v0.34l0.16,0.03l0.15,0.41l-0.22,0.07l0.04,0.54l-0.19,0.28l0.16,0.58l-0.41,0.51l0.03,0.23l-0.22,0.25l0.13,0.03l0.32,-0.27l-0.03,-0.24l0.25,-0.41l0.44,-0.41l0.19,-0.92h-0.19l-0.03,-0.17l0.54,-0.41l0.06,-0.24l0.57,0.07l0.06,0.38l-0.25,0.38l0.03,0.21l0.28,-0.24l0.03,0.31l0.82,0v-0.55l-0.22,-0.27l-0.22,0.03l-0.06,0.34h-0.25l-0.06,-0.17l0.72,-1.09l-0.03,-0.21l-0.38,-0.07l0.38,-0.14l0.03,-0.24L333.46,345.06zM339.1,343.93l-0.15,0.53l-0.23,0l0.1,-0.51L339.1,343.93zM324.18,343.51l0.26,0.54l-0.07,0.17l-0.32,0.03l-0.41,-0.21l0.28,-0.21l0.03,-0.31L324.18,343.51zM328.49,343.46l0.22,0.24l0.19,-0.1l0.38,0.27l-0.06,1.03l-0.2,0.1l-0.16,0.47l-0.28,-0.27h-0.6l-0.76,-0.75v-0.31h0.6l0.31,-0.58L328.49,343.46zM332.49,343.46l-0.16,0.34l-0.44,0.07L332.49,343.46zM337.41,342.94l0.12,0.21l-0.32,0.21l-0.19,-0.27L337.41,342.94zM321.4,340.04l0.13,0.25l-0.22,0.14L321.4,340.04zM331.58,339.94l0.28,0.1l-0.09,0.48l-0.57,0.34l-0.13,0.38l0.19,0.1l-0.22,0.14l-0.09,-0.34l0.19,-0.51l-0.16,0.03l-0.03,-0.14l0.23,-0.1l0.12,-0.48H331.58zM333.22,338.71l0.09,0.31l-0.37,-0.14l-0.77,0.1l-0.25,0.21l0.25,-0.38l0.66,0.07l0.06,-0.17L333.22,338.71zM334.76,338.26l0.45,0.41l0,0.27l-0.69,0.17l-0.22,-0.17l-0.47,0.07l0.31,-0.58l0.38,0.14L334.76,338.26zM335.04,337.72l0.1,0.41l-0.28,0.1v-0.44L335.04,337.72zM325.78,336.79l0.41,0.28l0.13,0.38l0.38,0.1l0.25,0l0.03,-0.31l0.44,-0.34l0.37,0.16v0.59l0.48,0.21l-0.09,0.55l0.23,-0.04l0.06,0.14h0.19l0.06,-0.17h0.47l0.35,-0.48l0.06,-0.65l0.25,-0.03l-0.54,1.3l-0.44,-0.01l-0.41,0.52l0.31,0.72l0.44,0.1l-0.25,0.72l-0.79,-0.17l-0.38,0.38l0.13,0.51h0.16l0.25,0.38l-0.54,-0.41l-0.47,0.17l0.32,0.27v0.24l0.25,-0.27l0.13,0.48l0.47,-0.44l0.38,0.24l-0.03,0.48l-0.7,0.3l0.16,0.61l-0.38,0.17l-0.25,0.41l-0.25,-0.03v-0.38l-0.51,-0.11l-0.37,-0.03l-0.06,0.38l-0.25,-0.03l0.03,-0.65l0.19,-0.07l0.22,-0.55l0.23,0.03l0.18,-0.21l-0.21,-0.37l0.09,-0.44l-1.07,-0.96l-0.47,-0.03l0.03,-0.14l0.25,0.1l0.19,-0.24l-0.32,-0.14l-0.06,-0.38l0.15,-0.16l-0.31,-0.14l0.02,-0.24l-0.24,-0.3l-0.32,0.1l-0.06,-0.2l-0.35,0.03l-0.6,0.89l-0.06,0.44l-0.22,0.14l-0.13,-0.34h-0.19l-0.28,-0.31l-0.25,0.14l-0.19,-0.34l-1.48,1.98l0.31,-0.03l0.04,0.27l-0.13,0.24l-0.22,0l0.04,0.31l-0.25,0.34L320,342.3l-0.35,0.41l-0.54,-0.03l-0.19,0.14v-0.21l-0.22,-0.03l-0.38,0.34l0.44,0.82l-0.25,0.31l0.32,0.51l-0.22,0.58l0.28,0.27l0.13,0.41l-0.38,1.16l-0.66,0.1l-0.16,0.17l0.16,0.62l0.28,0.24l-0.09,0.37l-0.41,0.38v0.41l0.34,0.14l-0.18,0.72l0.5,0.17l-0.25,0.48l-0.67,0.06l-0.6,-0.31l-0.54,0.1l-0.09,-0.28l-0.41,-0.06l-0.31,0.1l-0.32,0.58l-0.75,-0.14l-0.63,0.27l-0.19,0.31l-1.01,-0.17l0,-0.55l1.14,-0.58l0.39,-0.82l0.34,0.06l0.54,0.62l0.37,0.04l1.17,-1.06l0.16,-1.2l-0.63,-0.51l-0.66,-0.17l-0.35,0.07l-0.03,-0.24l0.29,-0.07l-0.07,-0.44l0.22,-0.27l0.16,0.14l0.25,-0.14l0.22,0.17l-0.03,0.72l0.44,-0.51l-0.09,-0.51l0.38,-0.85l0.44,-0.21l-0.18,-0.45l-0.6,-0.14l-0.35,-0.48l0.6,-0.48l-0.28,-0.85l0.25,-0.65l0.44,-0.08l0.47,-1.46l0.31,0.03l0.19,-0.24l0.09,0.27l0.22,-0.03l-0.19,-0.41l-0.28,0.07l-0.13,-0.14v-0.31l1.17,-0.07l0.1,0.58l-0.54,0.41v0.31l0.22,0.21l0.41,-0.14l0.13,0.38l0.98,0.34l0.28,-0.31l0.32,-0.07l0.79,-1.06l-0.06,-0.48h0.41l0.34,-0.38l-0.03,-0.17l-0.41,0.14l0.13,-0.34l-0.09,-0.31l0.19,-0.11l0.28,-0.75l0.57,-0.1l0.06,-0.52l0.09,0.38l0.31,0.1l0.82,-0.27l0.13,-0.21l0.56,0.03l0.2,-0.37L325.78,336.79zM335.33,336.15l-0.03,0.45l0.21,0.17l-0.12,0.21l-0.47,-0.14l0.13,-0.1l-0.09,-0.41L335.33,336.15zM335.86,335.26l-0.13,0.99l-0.19,-0.17l-0.03,-0.55L335.86,335.26zM333.53,334.79l0.16,0.16l-0.06,0.27l-0.41,-0.27l0.09,-0.17L333.53,334.79zM323.15,334.5l0.12,0.14l-0.22,0.34l-0.06,-0.31L323.15,334.5zM326.92,334.4l-0.01,0.27l0.47,0.52l-0.25,0.21l-0.38,-0.75L326.92,334.4zM323.3,334.08l-0.22,0.39v-0.27L323.3,334.08zM328.87,332.31l-0.06,0.34l0.31,-0.1l0.03,0.1l-0.54,0.31l-0.13,-0.51L328.87,332.31zM391.22,331.5l0.03,0.31l0.16,0.03l0.06,-0.24h0.16l0.16,0.24l-0.85,0.1l0.03,-0.27L391.22,331.5zM322.76,331.44l0.09,0.22h0.19l-0.31,0.65l0.21,0.44l-0.4,0.25l-0.25,-0.41l0.25,-0.21l-0.09,-0.41l0.16,-0.07l-0.35,-0.38L322.76,331.44zM327.48,327.16l0.16,0.44l-0.35,-0.27l0.03,-0.17L327.48,327.16zM328.96,326.79l0.25,0.26l-0.16,0.48l0.28,0.14l0.07,-0.28l0.41,0.01l-0.09,0.38l0.44,0.17l0.13,0.7l-0.28,0.19l-0.09,0.31l-0.44,-0.17l0.03,0.55l-0.91,-0.17l-0.38,0.68l-0.28,0.21l-0.31,-0.58l-0.57,-0.2l0.22,-0.31l-0.1,-0.35l0.29,0.07l0.5,-0.27l0.54,-0.75l-0.28,-0.38l0.28,-0.1l0.16,-0.28l0.28,-0.03l-0.13,-0.21L328.96,326.79zM328.24,324.82l0.28,0.38l-0.25,0.31l-0.44,0.1l-0.06,-0.24l0.19,-0.03L328.24,324.82zM327.8,323.19l0.06,0.19l-0.25,0.27l-0.09,-0.24l0.13,-0.24L327.8,323.19zM557.99,300.2l-0.47,0.69l0.03,-0.31l0.63,-0.93l0.16,-0.51v0.51L557.99,300.2zM420.32,286.39l0.16,0.14l-0.03,0.27l-0.44,1.03l-0.6,0.34l-0.35,1.03l-0.6,0.65l-1.26,0.03l-0.35,0.17l-0.5,-0.14l-1.7,0.1l-0.25,-0.17v-0.45l1.26,-2.88L420.32,286.39zM476.65,199.05l-0.06,-0.21l0.16,-0.1L476.65,199.05zM594.27,191.7l0.82,0.41l0.22,0.79l0.38,0.21l-0.19,0.45l-0.31,0.1l-0.35,-0.28l-1.01,0.14l-0.03,-0.14l-0.25,0.07l-0.13,-0.17l-0.35,0.07l-0.38,-0.69l-0.41,-0.35l1.01,0.31l0.44,-0.86L594.27,191.7zM547.29,135.79l0.31,0.31l-0.06,0.59l1.17,0.35l0.35,-0.35l0.66,0.14l0.76,-0.07l0.03,-0.38l0.28,-0.31l0.98,-0.14l0.54,0.45l0.28,-0.14l-0.03,0.24l0.5,0.42l1.13,-0.07l-0.06,0.35l0.91,0.55l0.16,0.42l1.13,0.35l1.17,1.14l0.76,1.28l-0.06,0.42l0.19,0.87l-0.19,1.35l0.38,0.1l0.38,0.59l0.32,-0.1l-0.06,0.52h0.31l0.06,-0.21l0.35,0.1l-0.06,-0.24l0.32,-0.14l-0.03,0.28l0.25,0.28l-0.13,0.38l-0.38,0.35l0.28,0.59l1.04,1.21l0.25,-0.07l0.95,0.83h0.44l0.1,-0.31l0.44,0.28l0.79,-0.83l0.16,0.45l0.13,-0.28h0.22l0.38,-0.31l0.22,-0.52l0.6,-0.35l0.09,0.21l-0.16,0.21l-0.82,0.66l-0.13,0.42l0.31,0.28l-0.25,0.24l0.03,0.21l-0.35,0.17l-0.06,0.31l-0.38,0.24l-0.13,0.52l0.13,0.31l0.66,0.86l0.32,-0.14l0.16,0.14l0.1,-0.24l0.6,0.28l0.22,0.45l0.57,0.1v0.66l-0.28,0.48l0.09,0.17l0.88,-0.17l0.31,0.14l0.79,-0.07l0.19,0.21h0.41l0.47,0.45l0.44,-0.1v0.21l0.32,0.28l1.01,0.03l0.25,0.17l-0.03,0.14l-0.41,0.03l-0.25,0.42l0.25,0.1l0.06,-0.38l0.22,-0.07l0.13,0.28l-0.25,0.03l0.03,0.14l0.16,-0.03l-0.19,0.35l0.41,-0.1l0.06,0.14l-0.25,0.21l0.03,0.24l-0.98,0.55l-0.25,1l0.57,-0.83l0.66,-0.17l0.19,-0.31l0.44,-0.24l0.19,-0.48l0.79,-0.62l-0.06,-0.21h-0.19l-0.13,0.28l-0.22,0.07l-0.22,-0.31l0.06,-0.38l-0.22,-0.07l-0.13,0.21l-0.03,-0.11l0.19,-0.55l0.38,-0.03l0.06,-0.28l0.28,-0.03l0.54,0.21l0.13,0.24l0.69,0.03l0.03,0.21l-0.28,0.21l-0.32,-0.03l-0.09,0.17h0.35l0.16,0.31l0.28,0.14l0.6,-0.03l0.35,0.31l-0.16,0.35l0.35,0.07l0.03,0.24l0.41,-0.07l0.19,0.35l0.16,0.03l0.03,-0.21l-0.22,-0.52l0.35,-0.07l0.47,0.17l0.06,-0.14l0.5,0.03l0.19,-0.14l0.13,0.24l-0.41,0.28l-0.22,0.55l0.13,0.52l0.6,0.38l1.1,-0.07l0.35,-0.31l0.44,0.07l-0.22,0.31l-0.22,0.03l0.1,0.24l-0.35,0.35l0.09,0.62l0.25,0.17l0.41,-0.1l0.35,-0.69l0.13,0.1l1.39,-0.21l0.13,0.17l0.75,0.03l0.69,0.35l0.63,-0.21l0.25,0.42h0.25l0.38,-0.31h0.6l0.25,0.31l0.06,-0.14l0.72,-0.03l0.22,0.14l0.44,-0.03l0.03,0.38l0.57,-0.14l0.44,0.14l0.57,-0.46l0.28,0.18l0.28,-0.03l0.41,-0.24l0.22,0.03l0.19,-0.38l0.98,-0.21l-0.57,1.28l-0.79,0.62l0.57,0.21l0.5,-0.24l0.19,0.83l-0.06,0.45l-0.25,0.03l-0.28,0.31l0.13,0.55l-0.63,0.83l-0.03,0.66l0.06,0.24l0.25,0.14l-0.13,0.48l0.09,0.31l0.25,-0.1l0.35,0.52l0.31,0.03l0.06,0.48l0.85,0.45l-0.09,0.48l-0.63,0.1v0.17l0.16,-0.07l0.06,0.24l0.41,0.07v0.38l-0.25,0.14l-0.03,0.28l-0.19,-0.03l0.28,0.17l0.03,0.45l-0.25,0.24l-0.03,0.28l0.6,1.21l0.82,0.79l-0.09,0.17l-0.38,-0.03l-0.03,0.21l1.51,0.31l0.1,-0.38l1.13,0.1l0.6,-0.1l0.69,-0.38l0.57,-0.03l0.38,0.25l0.38,-0.04l0.76,0.45l0.03,0.97l0.63,-0.45l0.09,-0.41l0.28,0.38l0.28,0.03l0.47,0.41l-0.06,1.21l-0.91,0.17l-0.19,0.31l-0.72,0.1l-0.69,0.73l-0.63,0.07l-0.6,0.73l-0.94,0.41h-0.72l-1.86,1.11l-1.51,0.52l-0.5,0.55l-0.03,0.45l-0.5,0.41l-0.16,0.66l-0.82,0.31l-0.19,0.35l-0.44,0.24l-0.03,0.76l-0.95,-0.1l-0.63,0.45l-0.5,0.59l0.19,0.86l-0.32,0.28l0.09,0.69l-0.63,0.48l-1.04,1.31l-0.57,0.1l-0.31,0.69l-0.57,0.55l-0.72,0.17l-0.35,0.83l-0.82,0.97l-1.61,4.38l-0.41,1.76l-0.6,4.14l0.06,4.76l0.44,1.93l1.61,4l-0.09,1.96l0.22,2.62l0.57,2.72l0.66,1.76l1.07,2.28l0.76,0.75l0.44,0.17l0.47,-0.03l0.28,0.41h0.57l0.19,0.24h0.41l-0.13,0.21l0.09,0.38l-0.94,0.1l-0.32,0.21l-0.06,-0.1l0.66,-0.38l-0.09,-0.24l-0.88,0.31l-0.13,-0.31l-0.6,-0.34l-0.6,0.17l-0.16,0.21l0.06,0.62l0.32,-0.1l0.13,0.48l0.44,-0.41l0.25,0.07l-0.03,0.45l-0.22,0.17l0.09,0.24l-0.22,0.14l0.06,0.28l0.57,-0.24l0.13,0.28h0.35l0.5,-0.76l0.25,-0.14l-0.85,1.21l0.57,0.58l-0.54,0.24l-0.31,-0.1l-0.22,0.48l0.16,2.48l0.13,0.65l0.28,0.31l-0.25,0.86l0.09,0.34l0.41,0.34l-0.41,0.07l-0.44,0.65l-0.57,-0.03l-1.35,0.69l-1.01,0.17l-0.25,0.24l-0.32,1.07l0.06,1.34l0.16,0.21l0.44,-0.03l0.79,0.38l-0.03,1.27l0.16,0.17l0.91,-0.04l0.25,0.48l-0.25,0.14h-0.35l-0.13,-0.17l-0.85,0.14l-0.22,0.24l-0.6,0.21l-0.38,0.62l-0.35,0.03l-0.28,0.34l-0.98,0.41l-0.28,0.28l0.06,0.28l-0.16,0.24l0.19,0.48l-0.6,0.55l-0.44,0.72l-0.91,0.65l-0.6,0.76l-0.88,2.24l-0.35,1.65l-0.19,3.51l-0.28,0.27l-0.25,0.96l-0.44,0.65l-0.91,2.58l0.38,2.2l-0.13,1.37l-1.01,1.34l-0.82,0.58l-0.54,0.62l-0.63,1.48l-0.25,1.75l-0.95,0.89l-0.25,0.45l-1.04,0.79l-0.6,-0.07l-0.54,0.38l-0.66,1.06l-0.09,0.65l-0.25,0.34l-1.8,0.96l-0.63,0.65l-1.01,0.34l-0.44,0.38l-0.31,0.82l-0.63,0.86l-0.6,1.89l0.19,1.72l0.5,0.86l0.13,0.62v1.17l-0.28,0.93l-1.23,1.89l-1.64,1.06l-1.13,0.99l-1.1,2.09l-0.22,1.1l0.03,1.75l0.53,1.89l1.39,2.54l1.26,0.99l0.41,1.41l-0.54,0.99l-0.44,0.45l-0.19,0.93l-0.35,0.48l0.57,-2.4l-0.22,-0.14v0.48l-0.22,-0.21l0.19,0.75l-0.19,0.75l-0.57,0.75l-0.6,0.45l0.32,0.55l-0.06,0.34l-0.47,-0.48h-0.35l-0.41,0.24l-0.32,0.55v0.38l-0.69,0.69l0.03,0.45l-0.19,0.24v0.51l0.41,1.03l0.22,1.44l-0.25,0.45v0.51l-0.54,1.68l-0.09,0.75l0.19,0.69l-0.44,3.12l-1.1,4.14l-0.25,0.21l-0.38,1.13l-0.16,0.03v0.58l-0.25,0.79l-0.91,1.06l0.03,0.31l-0.25,0.55l-0.16,1.99l-0.19,0.58v2.19l0.31,0.14l0.09,0.31l-0.25,0.65l0.09,0.14l-0.54,0.99v0.41l-0.44,0.55l0.03,0.27l-0.28,0.24l-0.32,0.99l-0.16,0.17l-0.41,0.03l-0.41,0.82l-0.13,0.99l0.09,0.92l0.16,0.31l0.31,-0.17l0.13,0.1l-0.22,0.68l-0.25,0.17v0.48l-0.22,0.24l0.13,0.1l-0.09,0.48l-0.35,0.68l-0.03,0.21l0.19,0.21l-0.35,0.58l0.16,0.41l-0.22,0.17l-0.19,0.62l0.19,0.58l-0.19,0.27l-0.41,0.1l-0.35,0.55l-0.19,1.23l-0.35,0.79l-0.03,3.83l-0.28,1.78l-0.22,0.24l0.09,0.72l-0.47,0.65l-0.03,0.58l-0.25,0.07l-0.35,0.55l0.03,0.21l-0.25,0.14l-0.19,0.65l-0.19,0.1l0.06,0.24l-0.47,1.54l0.13,0.14l-0.13,0.79l-0.28,0.2v0.55l-0.22,0.58l0.22,1.06l-0.16,0.51l0.06,0.34l0.22,0.03l-0.13,0.68l0.25,0.31l0.06,0.44l0.66,-0.03l-0.06,0.41l0.13,0.24l-0.16,0.51l0.03,0.1l0.35,-0.1v0.2l-0.69,0.24l-0.22,0.85l0.09,0.21l-0.41,0.1l-0.31,0.51l-0.47,-0.14l-0.16,0.17l-0.54,0.03l-0.54,-0.17l0.98,0.61l0.38,0.07l0.13,0.24l-0.35,1.16l-0.25,2.32l-0.22,0.03v0.27l-0.54,0.75l-0.13,0.68l-0.47,0.82l-0.03,0.82l-0.25,0.34l0.03,0.55l-0.41,0.07l-0.16,0.96l-0.25,0.17l0.06,0.61l-0.38,1.36l0.25,1.02l-0.35,0.65l0.09,0.65l-0.28,0.2l-0.22,0.65l0.09,1.77l-0.25,0.24l0.06,0.65l-0.5,0.85v0.51l-0.74,-0.17l-1,0.61l-1.48,2.22l-0.03,0.41l-0.41,0.31l-0.38,1.19l0.16,0.31l-0.09,0.92l-0.44,0.17l-0.16,0.34l-0.25,0.82l-0.22,1.91l-0.38,0.92l0.13,0.4l0.32,-0.14l0.25,0.2v0.27l-0.6,0.54l-0.5,0.85l-0.28,0.17l-0.57,-0.03l-0.13,0.37l-0.44,0.24l-0.16,0.34l-0.13,0.99l0.28,1.5l0.38,0.65l0.25,0.1l0.19,-0.17l-0.35,0.85l0.54,0.48l0.09,0.34l-0.32,1.5l-0.63,0.58l-0.16,1.46l0.38,0.95l0.31,0.34l0.85,0.34v0.31l-0.98,0.95l-0.31,0.03l-0.47,-0.34l-0.28,0.75l-0.82,0.95l0.06,0.24l-0.38,0.85l-0.22,-0.24h-0.25l0.03,-0.21h-0.25l-0.09,0.21l-1.17,-0.1l-0.91,1.12l-0.19,0.31l0.19,0.34l-0.38,0.31l0.25,0.75l-0.85,0.44l-0.22,0.51l-0.19,0.92l0.03,0.82l-0.25,0.27l0.06,0.51l-0.41,0.51l0.06,0.34l-0.19,0.07l-0.19,0.71l-0.03,0.34l0.16,0.03v0.17l-0.57,0.61l0.28,0.34l-0.98,0.48l0.03,0.65l-0.28,0.1l0.09,0.34l-0.44,0.2l-0.25,0.88l0.19,0.65l-0.5,0.82l-0.16,0.65l-0.31,0.31v0.34l-1.45,1.46l-0.13,0.48l-0.38,0.14l-0.47,0.51l-0.44,0.03l-0.25,0.24l-0.03,0.27l-0.32,0.07l-0.5,1.22l-0.06,1.09l-0.47,0.37l-0.25,1.16l-0.35,0.41l-0.06,0.34l-0.76,0.61l-0.25,1.02l-0.31,0.1l-0.31,1.02l-0.63,0.95l-0.72,0.07l-0.25,0.2l-0.44,0.78l0.1,0.54l-0.19,0.34l-0.41,0.14l-0.72,-0.41l-0.41,0.1l-0.09,0.27l-0.66,-0.03l-0.28,0.17l-0.57,-0.14l-0.09,0.41l-0.66,0.3l-0.22,0.41l-0.5,0.31l-0.5,0.65l-0.06,1.19l-0.35,0.41l-0.03,0.48l0.09,0.2l0.54,0.27l0.03,0.44l0.25,0.2l-0.1,0.31l0.66,1.6l0.19,1.36l-0.85,0.65l-0.38,-0.27l-0.25,0.07l-0.69,0.75l-0.41,1.9l-0.22,0.34l-0.41,0.1l0.22,0.68l0.44,-0.65l-0.54,1.19l-1.07,0.71l-0.63,0.14l-4.03,4.07l-0.82,0.27l-1.54,1.05h-0.63l-0.66,0.24l-1.92,1.29l-0.28,0.03l-1.83,1.87l-1.73,0.68l-0.54,0.37l-1.01,1.22l-1.1,2.61l-0.54,2.07l-0.32,3.76l-0.98,1.08l-0.31,0.1l-1.48,1.36l-0.76,1.42l-1.23,4.03l-0.88,2.17l-1.57,6.27l-0.19,0.07l0.06,0.27l-1.35,3.66l-0.88,1.63l-0.35,1.42l-0.79,1.39l-0.6,2.34l-0.06,0.88l-0.69,0.64l-0.57,1.69l-0.38,0.64l-0.35,2.94l-0.03,3.66l0.47,4.43l0.38,0.85l0.03,0.68l-0.32,0.3l-0.28,1.15l0.31,1.93l-0.16,0.44l-0.54,0.51l-0.03,0.61l0.13,1.15l0.25,0.68v0.64l-0.25,0.88l0.25,0.47l0.06,0.64l-0.28,0.74l0.6,0.71l-0.25,0.44l-1.1,0.84v0.24l0.54,2.13l0.32,0.41l1.2,0.44l-0.03,0.17l-0.44,0.2l-0.06,0.98l-0.76,0.95l-0.06,1.01l0.25,0.74l0.03,2.87l0.69,1.32l0.06,0.44l-1.26,0.95l-0.13,1.11l-0.6,0.44l-0.6,0.17v1.01l-0.16,0.47l-2.39,1.32l-1.32,0.07l0.19,0.2l-0.09,0.88l0.19,0.03l0.06,0.64l-0.57,1.82l0.16,1.38l0.66,1.38l-0.03,0.34l0.6,0.44l0.91,1.55l0.09,1.38l0.57,0.57l-0.22,0.27l-0.44,0.24h-0.95l-0.32,-0.2l-0.28,-0.4l-0.13,-0.57l0.06,-0.88l-1.2,-0.3l-0.5,-0.95l-0.88,-0.81l-0.35,-0.61l-1.1,0.24l-0.47,-0.24l-0.28,-0.67l-0.44,0.51l-0.28,-0.07l-0.19,-0.74l-0.88,-0.17l-0.69,0.13l-0.57,-0.64l-0.79,-0.3l-0.41,-0.74l-0.35,-0.2l-0.41,0.03l-0.13,0.24l-0.31,0.07l-0.13,0.37l-0.66,0.24l-0.19,0.27l-0.28,0.98l0.16,1.21h-0.25l-0.22,0.44l-0.32,0.14l-0.09,0.91l-1.39,0.13l-0.47,-0.37l-0.44,-0.78l-0.06,-0.84l-0.82,0.07l-0.13,-1.18l0.19,-0.78l0.03,-1.89l0.35,-0.61l0.03,-0.81l-0.28,-0.78l-0.54,-0.41l-0.25,-0.95l-0.76,-0.34l-0.63,-0.95l-0.19,-0.81l-0.66,-1.32l-0.09,-0.68l0.5,-1.05l0.85,-0.54l0.06,-0.2l-0.25,-0.07l-0.16,-0.57l0.31,-0.81l0.19,-0.13l0.66,0.07l0.31,-0.88l0.41,-0.3l-0.13,-0.1l-0.31,0.24l-0.03,-0.64l-0.38,-1.22l-0.35,-0.44l0.35,-0.41l0.54,-0.03l0.44,-0.27l0.22,-0.41l0.06,0.17l0.22,-0.07l0.09,-0.3l-0.22,-0.47l0.03,-0.95l-0.32,-0.41l-0.09,-0.74l-0.31,-0.54l0.06,-0.57l-0.88,-0.91l0.1,-0.71l-0.44,-0.14l-0.13,-0.2l-0.03,-0.51l0.31,-0.61l-0.44,-0.61l0.06,-0.91l-0.38,-1.05l-0.09,-1.05l-1.04,-2.27l0.28,-1.22l-0.57,-1.05l-0.41,-0.37l-0.28,-1.18l-0.47,-0.81l-1.32,-1.39l-1.1,-0.88l0.28,-1.73l-0.54,-1.69l-0.35,-0.51l-0.22,-2.1l-0.69,-1.18l-1.92,-2l-1.32,-1.08l-0.54,-0.95l-0.25,-0.88l-0.57,-0.85l-0.16,0.07l-0.28,-0.2l0.13,-0.3l-0.6,-0.68l-4.38,-3.22l-3.59,-1.83l0.06,-0.58l0.63,-1.22l-0.03,-0.58l-0.98,1.59l-0.5,0.34l-1.23,-0.85l-2.55,-1.29l-2.55,-1.76l-0.03,-0.17l0.66,-0.14l0.16,0.27l0.54,0.27l0.06,0.27l0.6,0.2l0.16,0.41l1.23,0.54l0.35,-0.34l0.25,-0.85l-0.41,-0.1l-0.13,-0.61l-0.54,0.03l-0.03,-0.61l-0.16,-0.17l-1.04,-0.13l0.03,0.24h-0.13l-0.31,-0.14v-0.34l-0.28,-0.07l-0.13,0.3l-0.35,0.24v0.47l-0.32,-0.03l-0.41,0.31l-1.57,-1.86l0.06,-0.2l-0.22,-0.03l0.13,-0.3l0.79,-0.17l-0.28,-0.34h-0.28l-0.6,0.44l-0.16,-0.71l-0.85,-0.41l-0.19,-0.24l-0.79,0.14l-0.22,0.27l-0.41,0.03l-1.57,-0.68l-2.83,-2l-1.26,-1.15l-0.47,0.07l-0.13,-0.51l-0.63,-0.68l-0.32,-0.14l0.03,-0.34l-0.41,-0.24l-0.19,-0.44l-0.22,0.03l-0.6,-0.85l-0.47,-0.03l-0.54,-0.64l-1.48,-1.09l0.38,-0.47l0.6,0.03l1.04,1.36H411l0.47,-0.24l0.88,0.58l0.22,-0.07l-1.45,-1.29l-0.06,-0.27l0.54,-0.41l0.06,-0.24l-1.1,0.71l-0.25,-0.24l1.01,-0.68l-0.03,-0.27l-1.16,0.71l-0.25,-0.37l0.57,-0.37l-0.16,-0.27l-0.88,0.54l-0.57,-0.64l-0.5,-0.81l0.31,0.24l0.44,-0.24l-0.41,-0.44l-0.44,0.3l-0.25,-0.17l-1.04,-1.53l-0.22,-0.07l-0.47,-0.61l-1.29,-2.44l0.03,-0.14l0.16,0.03l1.04,0.58l0.35,0.85l0.31,0.24l0.28,0.61l-0.31,-1.12l2.07,-1.15l-0.22,-4.82l0,0l-1.73,-7.26l0,0l-3.34,-3.93l-3.59,-1.27l-2.8,-6.77l-1.7,0.17l-0.19,-0.27l-0.06,-0.37l0.22,0.17l0.06,0.34l0.47,-0.07l-0.09,-0.68l0.54,-0.07l0.28,-0.34l-1.83,-5.44l0.38,-0.14l0.72,0.31l0.32,-0.31l0.16,-0.24l0.06,-0.88l0.41,-0.44l-0.35,-0.03l-0.03,-0.17l0.35,-0.03l0.06,-0.24l-0.63,-0.03l-0.38,0.31l0.25,0.65l-0.16,-0.2l-0.22,0.07l0.09,0.75l-0.66,0.17l0.13,-0.2l-0.16,-0.58l-0.28,0.03l0.19,0.85l-0.28,0.07l-1.95,-5.68l0.13,-0.41l1.07,-0.82l-1.17,0.78l-0.22,-0.14l0.22,-2.96l-0.38,-1.5l-1.13,-2.14l0.31,-0.34l0.63,0.44l-0.03,-0.37l0.47,-0.71l-0.03,-0.34l-0.31,-0.1l0.28,-0.44l-1.42,-0.1l-0.66,-0.44v-0.75l0.57,-0.14l0.25,-0.38l-0.85,0.41l-0.13,-0.17l0.35,-0.17l-0.38,0.07l-0.35,0.71l-0.31,-0.24l-0.22,0.17l1.61,1.36l0.5,0.99l-0.06,0.2l-0.35,0.07l-0.69,-1.26l-1.61,-1.63v-0.41l1.07,-0.82l-0.06,-0.14l-0.38,0.24l-0.54,-0.07l0.22,-0.82l0.47,-0.31l2.11,-0.48l0.66,-0.71l-0.22,-0.07l0.06,-0.31l-0.25,-0.1l-0.22,0.68l-0.25,-0.31l-0.16,0.03l0.22,0.75l-0.79,0.07l-0.69,0.27h-0.13l0.13,-0.2l-0.38,-0.85l-0.09,0.61l0.16,0.03l-0.41,0.07l-0.09,0.24l0.25,0.27l-0.28,0.17l0.03,-0.24l-0.22,-0.03l0.06,0.37l-0.44,0.34l0.1,0.27l-0.19,0.92l-0.22,0.03l-3.15,-2.76l0.28,-0.61l-0.35,0.37l-0.28,0.07l-2.61,-1.74l-1.83,-0.68l0.38,-1.09l-0.41,-0.31l-0.54,0.48l-0.57,0.24l-0.79,-1.26l0.13,-0.24l0.47,0.03l0.38,-0.17v-0.41l-0.35,-0.85l0.39,-0.17l-0.04,-0.27l-0.44,0.17l-0.22,-0.68l-1.73,0.03l-0.09,0.48l-0.6,-0.2l0.44,-2.35l-0.03,-0.92l1.83,-1.36l2.39,-1.19l0.91,-0.1l0.63,0.14l0.85,0.88l0.82,0.17l0.03,-0.2l-0.94,-0.2l-0.09,-0.58H383l-0.38,-0.65l0.13,-1.02l-0.28,-0.89l0.6,-0.99l-0.06,-2.21l-0.25,-0.31h-1.23l-0.35,-0.21l-0.28,-0.48l0.13,-0.65l-0.16,-0.07l1.32,-2.86l-0.5,-0.17l-0.35,-0.44l0.32,0.31l0.54,0.17l0.16,-0.27l0.03,-0.55l-0.85,0.03l0.63,-0.07l0.28,-0.2l0.13,-2.15l0.25,0.03l-0.13,1.09l0.63,0.14l0.16,0.68l0.35,-0.1l0.09,-0.65l0.38,0.34l0.91,-0.37l0.54,0.07l0.35,-0.24l1.54,0.14l0.41,-0.24l-4.22,-0.2l-0.09,-0.92l-0.41,-0.31l0.03,-0.14l0.22,0.1l0.5,-0.1l0.25,-0.34v-0.44l0.57,-0.44l0.06,-0.34h0.28l0.35,-0.31l-0.03,-0.58l-0.22,0.31h-0.19v-1.02l0.35,-0.41l0.47,-0.07l0.54,-0.44v-0.17l-0.32,-0.03l-1.1,0.78h-0.5l-0.41,-0.27l-0.38,-0.75l0.28,-2.11l0.19,-0.07l0.22,0.17l0.25,-0.2l0.98,0.07l0.06,-0.61l-0.66,0.03l-0.03,-0.44l0.66,-1.02l0.41,-1.88l0.25,-0.03l0.66,0.55l0.66,0.1l1.26,-0.41l0.79,0.61l0.5,0.83l1.04,1.05l-1.54,-2.08l-0.79,-0.48l-1.23,0.1l-0.66,-0.31l-0.22,-0.44h0.35l-0.13,-0.65l-0.25,0.38h-0.19l0.38,-0.55l0.69,-0.03l-0.13,-0.48l-0.35,0.17l-0.03,-0.38l-0.28,-0.14l1.04,-1.84l-0.25,-0.07l-0.28,0.24l-0.91,1.64l-0.06,-0.14l1.1,-1.88l0.19,-0.75l0.85,-0.58l-0.79,-0.17l1.17,-0.07l-0.09,0.27l-0.22,0.03l0.09,0.24l-0.16,0.34l-0.82,0.72l0.57,0.2l0.38,-0.58l-0.03,0.24l0.19,0.17h0.38v0.85l0.19,-0.14l0.06,-0.31l-0.13,-0.14l0.16,-0.2l0.54,0.44l0.22,0.58l1.1,0.48l0.19,0.48l0.69,-0.07l0.5,0.14l0.38,-0.61l0.38,-0.2l0.09,0.31l-0.25,-0.07l0.03,0.2l-0.66,0.65l0.22,0.38l0.38,0.14l-0.28,-0.38l0.19,-0.2l0.22,0.68h0.13v-0.24l0.19,0.1l0.03,0.2l-0.32,0.1l-0.13,0.24l0.28,0.89l0.63,-0.24l0.19,-0.24l-0.6,-1.09l0.28,-0.24h-0.19l0.03,-0.14l0.38,-0.24l0.06,-0.78l-0.31,-0.58h-0.19l-0.19,0.34l-0.38,0.03l-0.16,-0.14v-0.65l0.19,-0.24l-0.19,-0.55l0.22,-0.2l-0.38,-0.96l-1.13,-0.41l-0.57,0.17l-1.45,-0.17l-0.03,-0.17l-0.38,-0.14l-0.6,0.03l-0.25,0.51l-0.85,0.03l0.03,-1.19h-0.47l-0.13,0.17l-0.13,-0.1l0.22,-0.2l0.59,-0.03l2.71,0.07l0.54,-0.51l0.32,-0.68l-0.35,-1.23l-0.09,-0.1l-0.54,0.1l-0.13,0.48l-0.25,0.14l-0.22,-0.72l0.06,-2.32l0.5,-0.27l0.09,-1.06l0.28,-0.1l0.09,-0.31v-0.31l-0.16,0.1l0.06,-0.27l-0.22,-0.24l0.16,0.03l0.09,-0.17h-0.25v-0.24h-0.25l0.28,-0.24l0.54,0.58l0.28,-0.24l0.35,0.38l0.47,0.03l0.85,-0.44l0.19,-0.55l0.03,-1.67l-0.13,-0.03l-0.25,0.27l0.03,0.68l-0.38,1.09l-0.79,0.1l-0.47,-0.41l-0.35,-0.58l-0.57,-0.17l-1.7,0.89l-0.03,-0.27l-0.16,-0.03v0.17l-0.19,0.03l0.19,0.24l-0.31,0.1l-0.19,-0.41l0.06,-0.31l0.57,-0.58l0.5,-0.17l0.44,0.07l0.22,-0.58l0.25,-0.14l0.06,-0.41l-0.28,0.24l0.22,-0.51l-0.47,0.68l-0.35,-0.24l-0.03,-0.41l0.16,-0.44l1.13,-1.3l0.09,-0.48l-0.19,-0.1v-0.21l1.67,-0.1l-1.92,-0.24l-2.11,0.72l-0.88,0.03l-0.63,-0.55l-0.22,-1.13l0.03,-1.78l0.31,-0.55l0.72,-0.07l1.2,0.31l0.88,-0.14l-0.06,-0.85l0.35,0.03l0.22,-0.48l-0.16,-0.55l0.25,-0.1l-0.98,-0.75l-0.44,-1.13l0.13,-0.75l-0.09,-0.65l0.31,-0.34l0.13,-0.48v-0.44l-0.32,-0.17l-0.03,-0.34l0.1,-1.81l0.09,-0.31l0.85,-0.55l-0.25,-0.03l0.19,-0.58h-0.22l-0.22,0.58h-0.47l0.06,-2.8l-0.16,-0.44l0.28,-2.02l0.16,-0.03l0.72,-1.3l0.57,-1.98l0.35,-0.48l0.57,-1.47l1.76,-2.12l0.31,-0.03l0.41,0.41l0.32,-0.14v-0.41l-1.32,-0.27l-0.38,0.14l-0.41,-0.31l0.19,-1.92l-0.47,-0.07l-0.09,0.31l-0.09,-0.27h-0.25l0.25,-0.1l-0.06,-0.24l-0.19,-0.07v-0.51l0.44,-0.68l0.22,0.03l-0.03,0.17l-0.19,-0.07l-0.35,0.72l0.38,0.14v0.41l0.47,0.14l0.19,-1.54l0.09,-0.38l0.22,-0.1l-0.13,-0.44l0.28,-0.75l0.72,0.03v-0.82h-0.44l-0.22,-0.44l-0.91,0.03l-0.63,-1.3l-0.19,-0.79l0.13,-0.41v0.65l0.66,1.68l0.6,0.07l-0.09,-0.1l0.5,-0.92l-0.32,-0.27l0.06,-0.48l0.28,-0.17l0.28,-0.82l0.41,-0.1l0.57,-1.23l-0.22,-0.17l-0.5,0.65l-0.38,-0.17l0.35,-0.65l0.31,0.21l0.16,-0.41l-0.35,-0.51l-0.5,0.38l-0.54,-0.31l0.03,0.17l-0.63,0.61l-0.25,0.07l0.1,-0.21l-0.16,-0.03l-0.72,1.16l-0.03,-0.24l0.63,-1.03l1.07,-0.86l-0.09,-0.17l-0.5,-0.1l0.06,-0.21l1.01,0.27l0.57,-0.62l1.64,-0.99l0.75,-0.79l0.28,0.03l0.13,0.62l0.54,0.24l0.09,-0.17l0.22,0.07l0.28,0.27l-0.16,0.27l0.47,0.24l0.38,-0.79l0.6,0.17l0.69,-0.21l-0.03,-0.17l-0.95,-0.27l0.06,-0.21l2.39,0.31l0.35,-0.82l0.09,-0.82l1.1,0.14l-0.41,0.07l-0.06,0.27l0.6,0.38l1.07,-0.34l0.03,-0.75l-0.35,-0.55l-1.26,-0.72l0.31,-0.38v-0.34l-1.35,-0.58l0.13,-0.45l0.31,-0.1l0.47,0.24l0.35,-1.16l0.31,0.41l0.41,-0.38l0.47,0.03l0.41,0.24l1.2,-0.99l0.22,-0.79l0.69,-0.92l0.28,-1.06l0.95,-1.34l0.98,-2.53l0.5,-0.86l-1.39,-0.31l-0.25,-0.31l1.73,-2.91l0.32,-0.38h0.22l-0.13,-0.48l0.79,-2.19l0.28,-0.21l1.48,-0.03l0.13,0.14l0.22,-0.14l-0.09,-0.41l0.22,-1.23l0.47,-0.69l0.6,-1.44l1.1,-1.44l0.25,-0.89l0.31,-0.03l2.83,-1.71l0.44,0.17l-0.09,0.48l0.09,0.62l0.13,0.03l-0.03,-1.37l0.38,-0.24l-0.06,-0.69l0.22,-0.58l0.35,-0.69l0.44,-0.03l0.44,-1.2l0.22,-0.17l-0.03,-0.27l-0.41,-0.24l-0.13,-0.41l0.76,-0.38l0.22,-0.34l-0.54,0.45l-0.69,-0.1l-0.35,0.51l-0.79,-0.14l-0.09,-0.24l0.13,-0.55l0.57,0.03l0.66,-0.82l0.06,-0.24l-0.13,-0.1l-0.09,0.41l-0.41,0.45l-1.01,0.1l-0.16,0.17l-0.09,0.31l0.22,0.07l-0.06,0.24l-1.98,0.14l-0.38,-0.21l0.03,-0.38l2.68,-3.67l1.07,0.1l0.06,-0.24l0.19,0.17l0.16,-0.07l0.19,-1.06l0.66,-0.86l-0.54,-0.51l1.26,-1.65l0.57,-0.1l1.57,0.17l0.57,-0.21l0.25,0.14l-0.03,0.38l-2.08,2.71l-0.13,0.96l0.22,0.03l0.06,-0.96l2.27,-2.85v-0.27l0.22,-0.27l0.41,-0.03l-0.06,-0.31l0.25,-0.14l-0.47,-0.21l-0.03,-0.24l0.82,-1.06h0.19l0.41,-0.69l0.54,-0.45l0.44,-1.13l0.98,0.52l0.32,-0.31l-0.03,-0.69l-0.25,-0.03l-0.91,-0.86l-0.19,0.1l-0.19,-0.27l-0.66,-0.17v-0.14l-0.35,0.03l-0.09,-0.17l-0.25,0.03l-0.88,-0.55l0.91,0.24l1.07,-3.02l0.54,0.07l0.6,-1.44l0.13,-0.55l-0.32,-0.34h0.22l0.13,-0.21l0.5,-1.37l0.72,0.17l0.85,-1.92h0.13l0.1,0.17l0.19,-0.03l0.09,0.38l-0.35,0.34l-0.16,1.34l-0.38,0.86l-0.63,1.24l-0.47,-0.1l-0.13,-0.17h-0.38l-1.23,3.54l0.35,0.17l0.25,-0.1v-0.45l0.25,-0.14l0.57,-1.55l0.54,0.17l0.25,0.69l0.44,0.35l0.22,-0.69l-0.25,-0.21l-0.16,-0.62l1.13,-2.71l-0.03,-0.24l0.13,-0.03l0.44,-1.44l0.6,0.21l0.19,0.34l-0.54,0.69l0.09,0.52l-0.22,0.31l0.25,0.14l0.57,-0.72l-0.09,-0.41l0.25,-0.51l-0.03,-0.45l-0.35,-0.45l0.66,-0.52h0.25l0.09,0.24l0.5,-0.1l0.16,-0.34v-0.27l-0.38,0.21l-0.63,0.14l-0.28,-0.1l-0.25,0.17l-0.72,-0.1l-0.22,-0.17l0.03,-0.38l0.95,-0.1l-0.79,-0.28l0.82,-1.72l0.25,-0.45l0.57,0.45l0.25,-0.07l0.13,-0.24l1.17,0.58l0.13,0.58l0.06,-0.72l0.32,-0.21l0.09,-0.34l-0.06,-0.52l0.22,-0.58l-0.13,-0.48l0.16,-0.31l-0.31,-0.41l0.19,-0.69l0.25,-0.31l0.13,0.21l0.25,-0.14l0.25,-0.48l0.19,-0.07l0.06,-0.55l1.58,-1.51l0.57,-1l-0.19,-0.76l0.25,-0.07l0.28,-0.48l0.19,-0.93l0.54,-0.76l-0.03,-0.48l0.25,-0.48l-0.09,-0.41l0.41,-0.03l-0.03,-0.27h-0.22l0.06,-0.21l0.44,-0.55l0.35,-0.07l0.13,-0.38l0.38,-0.38l0.47,-0.31l0.54,-1h0.41l0.63,-1.65l0.72,-0.55l0.57,-0.1l0.13,-0.34h0.28l0.32,-0.45l0.38,-0.17l0.38,-0.55l0.06,-0.52l0.47,-0.21l-0.03,0.34l0.38,-0.03l0.25,-0.76l-0.22,-0.1l-0.31,0.38l0.13,-0.55l0.32,-0.03l0.72,-0.72l0.31,-0.55l-0.03,-0.52l0.44,-0.14l-0.25,-0.55l0.54,-0.58l0.13,0.03v-0.69l0.25,-0.14l0.69,-1.51l0.69,-0.9l0.69,-1.93l-0.09,-0.24l0.19,-0.17l0.35,-1.17l0.6,-1.38l0.19,-0.1l0.69,-1.86l0.09,-0.96l0.66,-1.58l0.85,-1.27l0.35,-0.31l0.69,-0.03l0.35,-0.34h0.25l0.88,0.55l0.28,-0.38l0.85,-0.38l0.82,0.28l0.75,0.58l1.26,-0.24l0.09,-0.14l-0.82,0.03l-1.48,-1.52l-0.28,0.03l-0.13,-0.14l-0.38,0.31l0.16,-0.59l0.6,-0.9l0.03,-0.9l1.13,-1.17l-0.16,-0.34h0.31l0.32,-0.24l0.72,-1.1l1.61,-0.14l1.42,-0.41l0.44,0.07l0.25,-0.21l1.89,-0.03v-1.03l2.52,-2.21l0.22,-0.24l0.09,-0.59l0.44,0.1l-0.06,-0.41l0.28,-0.48l0.06,-0.9l0.47,-1.24l2.24,-1.83l0.32,0.03l0.75,-0.31l0.88,-0.69l0.28,-0.76l-0.03,-1.35l0.69,-0.03l0.25,-0.55l0.06,-1.1l0.13,-0.1l-0.19,-0.62l0.32,-1.07l-0.22,-1.72l0.28,-0.03l-0.2,-0.52l-0.72,0.17l-0.44,-0.86l0.91,-2.04l0.63,-0.72l0.03,-0.72l-0.13,-0.21l0.19,-0.14l0.38,0.31l0.13,-0.35l-0.1,-0.17l0.16,0.03l0.03,-0.17h-0.38v-0.17l0.16,-0.17l0.5,0.07l0.22,0.14l0.31,0.83l0.32,-0.03l-0.09,-0.52l0.19,-0.07l0.22,0.76l1.29,0.59l-1.17,-0.9l0.09,-0.48l-0.28,-0.17l-0.09,-0.28l0.06,-0.14l0.54,0.14l0.06,-0.38l0.28,-0.17l1.07,-0.07l-0.76,-0.21l-1.01,0.24l0.06,-0.14l-0.19,-0.1l1.1,-1.66l0.85,-2.31l0.47,-0.41l0.82,-1.28l0.19,-0.04l-0.28,-0.55l0.28,-1.1l1.57,-2.14l0.54,-0.21v-0.86l0.25,-0.38l0.91,-0.48l0.94,-1.49l0.98,-0.96l0.28,-0.97l0.03,-0.9l-0.16,-0.41l0.5,-0.52l0.41,-1.31l1.42,-1.59l-0.16,-0.03l-0.38,0.41l0.44,-0.86l0.66,-0.52v-0.21l0.47,-0.38l0.57,-0.83l1.35,-0.73l0.82,-0.07l0.57,-0.24l3.31,-2.59l0.72,-0.1l0.73,-0.45l0.35,0.07l0.19,-0.21l1.64,-0.31l0.91,-0.41l0.91,0.03l1.7,-0.87l0.72,-0.1l0.69,-0.79l0.72,-0.35l0.38,0.03l0.85,-0.73l1.89,-1.14l1.1,-0.31l0.95,-0.07l0.32,-0.42l0.6,0.28l0.28,-0.03l0.25,-0.35v-0.14l-0.41,-0.03l0.16,-0.31l0.94,0.14l0.03,-0.28l0.35,0.07l0.73,-0.24l0.69,0.17l0.09,0.38l0.28,0.07l2.3,-0.03l0.85,-0.48l0.22,-0.31l0.63,0.24l0.03,-0.48l0.63,-0.03l0.13,0.52l0.98,0.1l0.44,-0.31l0.88,-0.07l2.08,-0.69l0.19,-0.24l0.38,0.04l0.28,-0.35l0.13,0.14l1.32,-0.59l0.25,-0.42l1.95,-0.66l-0.16,-0.69l-0.44,-0.45l0.57,0.42l0.6,-0.48l0.06,-0.42l0.28,-0.35l-0.76,-0.83l1.29,1.21l0.44,-0.24l0.91,-0.94l0.22,-0.1l0.44,0.1l0.09,-0.9l-0.35,-0.55l-1.35,-0.24l-0.09,-0.14l0.35,-0.45l0.91,-0.14l0.35,-0.38v-0.17l-0.41,-0.24l0.41,-0.86l0.47,-0.1l1.2,-1.66l0.41,-0.07l0.32,-0.38v-0.97l0.63,-0.45l-0.16,-0.59l0.5,-0.73l0.16,-0.83l0.28,-0.38l0.44,-0.14l0.35,0.45l0.57,-0.03l0.44,-0.24l0.57,-0.45l0.25,-0.76l0.28,-0.21l-0.03,-0.55l0.57,-0.52h0.35l1.54,-0.9l0.35,0.07l0.22,-0.28l0.6,-0.28l-0.19,-0.9l0.09,-0.21l0.25,-0.07l0.22,0.69l0.47,0.28l0.38,-0.1l0.1,-0.31l0.35,0.03l0.25,0.24l0.47,-0.48h0.25l0.22,-0.48l-0.19,-0.07l-0.06,-0.35l0.38,-0.55H547.29zM536.83,169.64L536.83,169.64l-3.04,4.99l0.19,6.03l0,0l4.4,1.12l7.56,-2.63l5.8,-5.18l3.36,-4.5l-1.32,-5.01l-3.1,-5.71l-4.83,-1.85l-6.15,2.98l0.99,3.28l-1.64,1.5L536.83,169.64z" }, { "id":"TW-KH", "title":"Kaohsiung", "d":"M403.59,451.63l-3.52,-1.25l0.72,1.43l0.03,0.41l0.57,1.29l0.13,0.17l0.19,-0.07l0.03,-0.2l0.19,0.13l-0.28,0.37l1.04,2.68l0.03,0.41l-0.31,0.24l0.66,-0.14l-0.25,-0.48l0.19,-0.54l0.28,-0.2l-0.06,-0.17l-0.22,0.03l0.09,-0.13l0.44,-0.07l0.57,0.34v0.58l-0.38,0.14v0.41l0.38,0.04l-0.41,0.1l0.19,0.24l0.06,0.51l-0.16,0.2l0.09,0.44l-0.19,0.14v0.24h-0.35l-0.19,-1.05l-0.47,0.03v0.17l0.22,0.03l0.19,1.05l-0.13,0.1v0.64l-0.6,0.54l-0.31,0.03l-0.66,0.78l-0.13,1.46l0.69,1.8l0.6,0.54l0.32,0.71l-0.22,0.41l0.38,0.13l0.16,0.54l1.13,-0.2l1.35,0.61l0.06,-0.41l0.22,-0.14l0.09,0.27l-0.22,0.37l0.5,0.17l0.47,1.26l2.07,-1.15l-0.22,-4.82l0,0l-1.73,-7.26L403.59,451.63z" }, { "id":"TW-FK", "title":"Fukien", "d":"M163.89,249.71l0.28,0.34l0.5,-0.03l-0.66,0.28l-0.19,-0.21l-0.19,0.03l-0.03,-0.21l-0.19,0.03L163.89,249.71zM164.52,248.09l0.44,0.14v0.17l-0.25,0.14l0.16,0.34l0.28,0.17h0.69l-0.06,0.34l-0.66,0.17l-0.31,-0.34l-0.35,0.03l0.22,-0.21l-0.03,-0.28l-0.5,-0.41L164.52,248.09zM168.27,247.85l0.06,0.34l-0.38,-0.1l0.13,-0.24H168.27zM174.38,240.94l0.57,0.17l1.04,0.96l0.69,0.14l-0.19,0.96l-0.41,0.34l0.22,0.1v0.48l-0.25,0.27l0.28,0.03l-0.28,0.31l0.03,0.24l-0.32,-0.07l-0.09,-0.28l-0.88,-0.07l-0.66,0.69v0.35l0.28,-0.07l-0.19,0.38l-0.63,0.38v-0.38l-0.53,-0.1l-0.57,0.34l-0.57,0.86h-0.25l-0.35,-0.55l-0.79,0.03l-0.35,-0.38l0.31,0.1l0.38,-0.45l0.19,0.07l0.13,-0.41l-0.38,-1.03l0.91,-0.07l0.19,-0.2l0.41,-2.41l0.44,-0.27l0.73,0.03l0.13,-0.24L174.38,240.94zM192.67,231.58l-0.13,0.31l0.31,-0.03l0.16,0.38l0.35,0l-0.1,-0.21l0.31,-0.24l0.76,0.31l0.35,-0.03l-0.16,0.37l0.22,0.15l0.03,0.62l0.47,0.9l0.32,-0.07l0.22,0.17l0.76,-0.21l0.76,0.38l-0.03,0.21l-0.22,-0.03l-0.13,0.69l0.28,0.58l0.47,0.07l-0.09,0.52l0.19,0.72l0.66,0.86l0.31,-0.41l0.28,0.21l-0.06,0.34l-0.16,0.21l-0.22,-0.1l-0.09,0.31l0.13,2.06l0.63,0.76l0.6,-0.28l0.13,0.65l-0.5,0.38l0.13,0.34l-0.16,0.14l-0.16,0.03v-0.24l-0.38,0.07l-0.57,0.62l0.41,0.83l0.03,0.38l-0.16,0.28l-0.28,0.07l-0.28,-0.21l-0.28,0.21l-0.09,0.45l0.28,0.28l-0.44,0.41l-0.6,0.1l-1.32,0.82l-0.94,0.1l-0.06,-0.28l0.69,-0.03l-0.03,-0.45l0.28,-0.27l-0.66,-1.03l-1.29,-0.55l-0.47,0.1l-1.54,-1.07l-1.67,0.1l-1.76,0.52l-1.61,0.72l-0.72,0.58l-1.54,2.03l-0.5,1.48l0.03,0.48l-0.38,0.14l-0.41,-0.14l-0.13,0.28l-0.41,0l-0.09,-0.28l-0.22,0.03l-0.16,-0.21l-0.79,-0.03l-0.38,-0.82l-1.1,0.03l0.12,-0.28h-0.12l-0.03,-0.27l-0.25,-0.03l-0.28,-0.48l-0.69,-0.38l0.06,-0.21l-0.5,-0.1v-0.24l-0.41,-0.24l0.47,-0.34h0.35l0.19,0.24l0.57,-0.21l0.06,0.24l0.41,0.17l0.6,-0.31l-0.03,-0.31l0.19,-0.28l-0.13,-0.58l0.47,-0.21l0.57,0.1l-0.06,-1.89l-0.28,-0.93l-0.47,-0.69l-0.13,-0.62l0.28,-0.79l0.72,-0.14v-0.48l-0.32,-0.24l-0.22,0.27l-0.95,0.04v0.31l0.28,0.31l-0.38,0.03l-0.47,-0.38l-0.03,-0.38l-0.28,-0.17l0.35,-0.83l0.31,-0.24l0.5,0l0.32,-0.65l0.41,-0.21h0.44v-0.24l0.22,-0.1l0.88,0.48l2.08,1.89l1.1,0.48l0.35,0.34l0.38,-0.07l1.51,0.55l1.39,-0.17l-0.03,-0.17l0.54,-0.58l0.16,-1.14l-0.72,-0.79l0.76,0.1l0.28,-0.14l-0.13,-0.17l0.28,-0.34l0.41,-0.14l-0.06,-0.21l0.28,-0.24l-0.19,-0.52l-0.25,-0.14l0.28,-0.21v-0.79l-0.22,-0.48l1.26,-0.21l0.28,-0.45l0.63,-0.14l-0.03,-0.52l-0.19,-0.17l0.06,-0.34l-0.38,-0.34l0.22,-0.24L192.67,231.58zM313.31,174.95l0.5,0.41l-0.03,0.21l-0.38,0.07l0.03,0.28l-0.32,-0.1l0.06,-0.38l-0.32,0.14l-0.13,-0.14v0.17l-0.44,-0.14l0.16,-0.21l0.19,0.07l0.09,-0.21L313.31,174.95zM310.54,173.47l0.13,0.28l0.66,0.17l0.06,0.76l0.19,0.03v0.14l-0.32,0.07l-0.38,-0.17l-0.03,-0.17l-0.54,-0.31l-0.19,-0.62L310.54,173.47zM370.25,51.17l0.19,0.35l-0.25,0.52l0.57,0.14l0.06,0.17l0.22,-0.11l0.09,-0.35h0.57l0.13,0.17l-0.54,0.66l-0.06,0.38l-0.6,0.17l-0.09,0.59l-0.22,-0.04l-0.34,0.28l-0.19,-0.31l-0.98,0.94l-0.25,-0.35l0.5,-0.77l-0.19,-0.21l0.28,0.07l0.5,-0.59l0.03,-0.49L370.25,51.17zM364.17,50.92l0.03,0.28l-0.22,0.04l-0.16,0.24L364.17,50.92zM366.78,50.36l0.03,0.21l0.47,0.17l-0.06,0.21l-0.63,0.69l-0.54,-0.03l-0.31,0.66l-0.22,0.07l-0.16,-0.07l-0.06,-0.35l-0.47,-0.03v-0.24l-0.25,-0.17l-0.32,-0.66l0.32,-0.28l0.88,0.11L366.78,50.36zM363.67,26.27l0.22,0.04l0.32,0.42l0.69,-0.04l-0.03,0.28l-0.25,-0.04l0.03,0.28l-0.25,0.35l-0.1,0.52h0.66l0.19,-0.17l-0.09,0.42l0.19,0.1l0.32,-0.18l-0.03,0.42l0.19,0.35l0.19,0v-0.28l0.25,-0.31l0.41,0.04v-0.38l-0.38,-0.24h0.47l0.5,-0.59l0.38,-0.11l0.25,0.42l0.38,-0.42l0.32,-0.07l0.25,0.21l0.63,-0.14l-0.38,0.17l-0.22,0.38l-0.06,0.66l-0.35,0.1l-0.16,0.59l-0.25,0.28l-0.16,0l-0.31,-0.59l-0.35,0.42l0.03,0.38l-0.25,0.03l-0.38,0.63l-0.6,0.11l-0.06,-0.38h-0.16l-0.82,0.56l0.16,0.25l-0.28,-0.04l-0.38,0.28l-0.13,-0.1l0.03,-0.42l-0.75,0.11l-0.44,-0.18v-0.35l-0.25,0.1l-0.19,-0.1l0.16,-0.52l0.47,-0.42l0.31,-0.59l-0.13,-0.31l-0.38,-0.04l0.22,-0.24l0.22,0l0.22,-0.46v-0.24L363.42,27v-0.49l0.09,-0.24H363.67zM370.03,23.79l0.22,0.07l-0.13,0.28l-0.22,-0.07L370.03,23.79zM373.02,18.31l0.22,0.45l0.47,0.1l-0.06,0.38l0.16,0.38l0.35,-0.1l0.57,0.1l-0.09,0.7l-0.41,0.31l0.25,0.24l0.03,0.42l0.35,0.03l-0.28,0.28l0.09,0.24l-0.32,0.17l-0.16,-0.07l0.06,-0.56L374,21.28l-0.06,-0.42l-0.32,-0.17l-0.06,-0.59l-0.44,0.56v-0.38h-0.28l-0.19,0.63l-0.44,-0.07l-0.31,0.52l-0.16,-0.07l0.03,-0.42l-0.6,-0.07l-0.72,0.49l-0.28,-0.11l-0.25,0.24l-0.09,0.91l0.13,0.63l-0.13,0.35l0.19,0.14v0.25l-0.13,0.17l-0.66,0.07l-0.09,-1.15l0.22,-0.28l-0.19,-0.28l0.19,0l0.35,-0.52l-0.41,-1.19l0.5,0.07l0.38,-0.45l0.47,-0.24l0.38,0.17l1.04,-1.01l0.13,-0.45l0.25,-0.24L373.02,18.31zM374.12,16.11l0.09,0.17h0.41l-0.06,0.28l-0.75,0.14l-0.19,0.56l-0.25,0.07l-0.06,0.25h-0.25l-0.5,0.35l-0.1,-0.25l0.35,-0.77l0.28,0.1l0.19,-0.35l0.28,0.14l0.35,-0.35l0.03,-0.28L374.12,16.11zM371.92,12.55l0.19,0.18l-0.41,0.56l0.38,-0.11l-0.13,0.28l0.19,0.24l-0.41,0.31l0.16,0.45l-0.5,0.35h-0.6l-0.22,-0.84l0.57,-0.14v-0.35l-0.22,-0.03l-0.03,-0.21l0.25,-0.25l0.25,0.07l0.06,-0.42L371.92,12.55zM399,4.54l0.06,0.35l-0.63,0.8l-0.32,0.1l-0.28,0.39l-0.69,0.04l0.09,-0.18l0.38,-0.07l0.28,-0.7h0.25l0.22,-0.35L399,4.54zM427.44,0l0.06,0.45l0.22,-0.04l0.03,0.25h0.13v0.28l-0.28,0.31l0.06,0.31l0.31,0.14l0.25,-0.03V1.5l0.5,0.14l-0.03,-0.45l0.22,-0.35l0.32,-0.17l0.41,0.04v0.59l0.31,0.21l0.44,-0.18l0.47,0.73l0.06,0.42l-0.25,0.04l-0.22,-0.21l-0.31,0.07l-0.13,-0.35h-0.19l-0.06,0.56l-0.47,0.31l-0.19,0.52l-0.25,0.07V3.25l-0.47,0.14l-0.31,-0.21l0.16,0.24l-0.06,0.21h-0.32l-0.35,-0.42l0.25,-0.31l-0.16,-0.52l0.28,0.07l0.19,-0.21l-0.19,-0.46h-0.38l-0.28,0.32l-0.16,-0.04V0.77l-0.38,0.28l-0.34,0.66l-0.25,-0.17l0.16,-0.32l-0.16,-0.38l0.6,-0.28L426.65,0l0.35,0.07v0.14L427.44,0z" } ] } } };
aferlazzo/cdnjs
ajax/libs/ammaps/3.10.0/maps/js/taiwanLow.js
JavaScript
mit
41,263
<?php /* * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * This software consists of voluntary contributions made by many individuals * and is licensed under the MIT license. For more information, see * <http://www.doctrine-project.org>. */ namespace Doctrine\ORM\Query\AST; /** * Description of HavingClause * * * @link www.doctrine-project.org * @since 2.0 * @author Guilherme Blanco <guilhermeblanco@hotmail.com> * @author Jonathan Wage <jonwage@gmail.com> * @author Roman Borschel <roman@code-factory.org> */ class HavingClause extends Node { public $conditionalExpression; public function __construct($conditionalExpression) { $this->conditionalExpression = $conditionalExpression; } public function dispatch($sqlWalker) { return $sqlWalker->walkHavingClause($this); } }
cardellcr/postres_oliver
vendor/doctrine/orm/lib/Doctrine/ORM/Query/AST/HavingClause.php
PHP
mit
1,589
'use strict'; angular.module("ngLocale", [], ["$provide", function($provide) { var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"}; function getDecimals(n) { n = n + ''; var i = n.indexOf('.'); return (i == -1) ? 0 : n.length - i - 1; } function getVF(n, opt_precision) { var v = opt_precision; if (undefined === v) { v = Math.min(getDecimals(n), 3); } var base = Math.pow(10, v); var f = ((n * base) | 0) % base; return {v: v, f: f}; } $provide.value("$locale", { "DATETIME_FORMATS": { "AMPMS": [ "am", "pm" ], "DAY": [ "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" ], "ERANAMES": [ "Before Christ", "Anno Domini" ], "ERAS": [ "BC", "AD" ], "MONTH": [ "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" ], "SHORTDAY": [ "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" ], "SHORTMONTH": [ "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" ], "fullDate": "EEEE, d MMMM y", "longDate": "d MMMM y", "medium": "d MMM y HH:mm:ss", "mediumDate": "d MMM y", "mediumTime": "HH:mm:ss", "short": "dd/MM/y HH:mm", "shortDate": "dd/MM/y", "shortTime": "HH:mm" }, "NUMBER_FORMATS": { "CURRENCY_SYM": "\u00a3", "DECIMAL_SEP": ".", "GROUP_SEP": ",", "PATTERNS": [ { "gSize": 3, "lgSize": 3, "maxFrac": 3, "minFrac": 0, "minInt": 1, "negPre": "-", "negSuf": "", "posPre": "", "posSuf": "" }, { "gSize": 3, "lgSize": 3, "maxFrac": 2, "minFrac": 2, "minInt": 1, "negPre": "\u00a4-", "negSuf": "", "posPre": "\u00a4", "posSuf": "" } ] }, "id": "en-gb", "pluralCat": function(n, opt_precision) { var i = n | 0; var vf = getVF(n, opt_precision); if (i == 1 && vf.v == 0) { return PLURAL_CATEGORY.ONE; } return PLURAL_CATEGORY.OTHER;} }); }]);
viral810/ngSimpleCMS
web/bundles/sunraangular/js/angular/angular-1.3.16/i18n/angular-locale_en-gb.js
JavaScript
mit
2,392
//! moment.js locale configuration //! locale : Morocco Central Atlas Tamaziɣt in Latin (tzm-latn) //! author : Abdel Said : https://github.com/abdelsaid import moment from '../moment'; export default moment.defineLocale('tzm-latn', { months : 'innayr_brˤayrˤ_marˤsˤ_ibrir_mayyw_ywnyw_ywlywz_ɣwšt_šwtanbir_ktˤwbrˤ_nwwanbir_dwjnbir'.split('_'), monthsShort : 'innayr_brˤayrˤ_marˤsˤ_ibrir_mayyw_ywnyw_ywlywz_ɣwšt_šwtanbir_ktˤwbrˤ_nwwanbir_dwjnbir'.split('_'), weekdays : 'asamas_aynas_asinas_akras_akwas_asimwas_asiḍyas'.split('_'), weekdaysShort : 'asamas_aynas_asinas_akras_akwas_asimwas_asiḍyas'.split('_'), weekdaysMin : 'asamas_aynas_asinas_akras_akwas_asimwas_asiḍyas'.split('_'), longDateFormat : { LT : 'HH:mm', LTS : 'HH:mm:ss', L : 'DD/MM/YYYY', LL : 'D MMMM YYYY', LLL : 'D MMMM YYYY HH:mm', LLLL : 'dddd D MMMM YYYY HH:mm' }, calendar : { sameDay: '[asdkh g] LT', nextDay: '[aska g] LT', nextWeek: 'dddd [g] LT', lastDay: '[assant g] LT', lastWeek: 'dddd [g] LT', sameElse: 'L' }, relativeTime : { future : 'dadkh s yan %s', past : 'yan %s', s : 'imik', m : 'minuḍ', mm : '%d minuḍ', h : 'saɛa', hh : '%d tassaɛin', d : 'ass', dd : '%d ossan', M : 'ayowr', MM : '%d iyyirn', y : 'asgas', yy : '%d isgasn' }, week : { dow : 6, // Saturday is the first day of the week. doy : 12 // The week that contains Jan 1st is the first week of the year. } });
galileo81580/petition-pro
client/bower_components/moment/src/locale/tzm-latn.js
JavaScript
mit
1,661
YUI.add('axis-category', function (Y, NAME) { /** * Provides functionality for drawing a category axis for use with a chart. * * @module charts * @submodule axis-category */ /** * CategoryAxis draws a category axis for a chart. * * @class CategoryAxis * @constructor * @extends Axis * @uses CategoryImpl * @param {Object} config (optional) Configuration parameters. * @submodule axis-category */ Y.CategoryAxis = Y.Base.create("categoryAxis", Y.Axis, [Y.CategoryImpl], { /** * Returns a string corresponding to the first label on an * axis. * * @method getMinimumValue * @return String */ getMinimumValue: function() { var data = this.get("data"), label = data[0]; return label; }, /** * Returns a string corresponding to the last label on an * axis. * * @method getMaximumValue * @return String */ getMaximumValue: function() { var data = this.get("data"), len = data.length - 1, label = data[len]; return label; }, /** * Calculates and returns a value based on the number of labels and the index of * the current label. * * @method _getLabelByIndex * @param {Number} i Index of the label. * @return String * @private */ _getLabelByIndex: function(i) { var label, data = this.get("data"); label = data[i]; return label; }, /** * Calculates the position of ticks and labels based on an array of specified label values. Returns * an object containing an array of values to be used for labels and an array of objects containing * x and y coordinates for each label. * * @method _getDataFromLabelValues * @param {Object} startPoint An object containing the x and y coordinates for the start of the axis. * @param {Array} labelValues An array containing values to be used for determining the number and * position of labels and ticks on the axis. * @param {Number} edgeOffset The distance, in pixels, on either edge of the axis. * @param {Number} layoutLength The length, in pixels, of the axis. If the axis is vertical, the length * is equal to the height. If the axis is horizontal, the length is equal to the width. * @return Object * @private */ _getDataFromLabelValues: function(startPoint, labelValues, edgeOffset, layoutLength, direction) { var points = [], values = [], labelValue, multiplier = (layoutLength - (edgeOffset * 2))/(this.getTotalMajorUnits() - 1), data = this.get("data"), labelIndex, i, len = labelValues.length, staticCoord, dynamicCoord, constantVal, newPoint, rawVal; if(direction === "vertical") { staticCoord = "x"; dynamicCoord = "y"; } else { staticCoord = "y"; dynamicCoord = "x"; } constantVal = startPoint[staticCoord]; for(i = 0; i < len; i = i + 1) { labelValue = labelValues[i]; labelIndex = Y.Array.indexOf(data, labelValue); if(Y.Lang.isNumber(labelIndex) && labelIndex > -1) { rawVal = labelIndex ? (labelIndex * multiplier) : 0; newPoint = {}; newPoint[staticCoord] = constantVal; newPoint[dynamicCoord] = rawVal + edgeOffset; points.push(newPoint); values.push(labelValue); } } return { points: points, values: values }; } }); }, '@VERSION@', {"requires": ["axis", "axis-category-base"]});
drewbaumann/cdnjs
ajax/libs/yui/3.10.0/axis-category/axis-category.js
JavaScript
mit
3,862
/* Name: Base16 Default Light Author: Chris Kempson (http://chriskempson.com) CodeMirror template by Jan T. Sott (https://github.com/idleberg/base16-chrome-devtools) Original Base16 color scheme by Chris Kempson (https://github.com/chriskempson/base16) */ .cm-s-base16-light.CodeMirror {background: #f5f5f5; color: #202020;} .cm-s-base16-light div.CodeMirror-selected {background: #e0e0e0 !important;} .cm-s-base16-light .CodeMirror-gutters {background: #f5f5f5; border-right: 0px;} .cm-s-base16-light .CodeMirror-linenumber {color: #b0b0b0;} .cm-s-base16-light .CodeMirror-cursor {border-left: 1px solid #505050 !important;} .cm-s-base16-light span.cm-comment {color: #8f5536;} .cm-s-base16-light span.cm-atom {color: #aa759f;} .cm-s-base16-light span.cm-number {color: #aa759f;} .cm-s-base16-light span.cm-property, .cm-s-base16-light span.cm-attribute {color: #90a959;} .cm-s-base16-light span.cm-keyword {color: #ac4142;} .cm-s-base16-light span.cm-string {color: #f4bf75;} .cm-s-base16-light span.cm-variable {color: #90a959;} .cm-s-base16-light span.cm-variable-2 {color: #6a9fb5;} .cm-s-base16-light span.cm-def {color: #d28445;} .cm-s-base16-light span.cm-bracket {color: #202020;} .cm-s-base16-light span.cm-tag {color: #ac4142;} .cm-s-base16-light span.cm-link {color: #aa759f;} .cm-s-base16-light span.cm-error {background: #ac4142; color: #505050;} .cm-s-base16-light .CodeMirror-activeline-background {background: #DDDCDC !important;} .cm-s-base16-light .CodeMirror-matchingbracket { text-decoration: underline; color: white !important;}
js-data/cdnjs
ajax/libs/codemirror/3.22.0/theme/base16-light.css
CSS
mit
1,585
/* Name: Paraíso (Light) Author: Jan T. Sott Color scheme by Jan T. Sott (https://github.com/idleberg/Paraiso-CodeMirror) Inspired by the art of Rubens LP (http://www.rubenslp.com.br) */ .cm-s-paraiso-light.CodeMirror {background: #e7e9db; color: #41323f;} .cm-s-paraiso-light div.CodeMirror-selected {background: #b9b6b0 !important;} .cm-s-paraiso-light .CodeMirror-gutters {background: #e7e9db; border-right: 0px;} .cm-s-paraiso-light .CodeMirror-linenumber {color: #8d8687;} .cm-s-paraiso-light .CodeMirror-cursor {border-left: 1px solid #776e71 !important;} .cm-s-paraiso-light span.cm-comment {color: #e96ba8;} .cm-s-paraiso-light span.cm-atom {color: #815ba4;} .cm-s-paraiso-light span.cm-number {color: #815ba4;} .cm-s-paraiso-light span.cm-property, .cm-s-paraiso-light span.cm-attribute {color: #48b685;} .cm-s-paraiso-light span.cm-keyword {color: #ef6155;} .cm-s-paraiso-light span.cm-string {color: #fec418;} .cm-s-paraiso-light span.cm-variable {color: #48b685;} .cm-s-paraiso-light span.cm-variable-2 {color: #06b6ef;} .cm-s-paraiso-light span.cm-def {color: #f99b15;} .cm-s-paraiso-light span.cm-bracket {color: #41323f;} .cm-s-paraiso-light span.cm-tag {color: #ef6155;} .cm-s-paraiso-light span.cm-link {color: #815ba4;} .cm-s-paraiso-light span.cm-error {background: #ef6155; color: #776e71;} .cm-s-paraiso-light .CodeMirror-activeline-background {background: #CFD1C4 !important;} .cm-s-paraiso-light .CodeMirror-matchingbracket { text-decoration: underline; color: white !important;}
evilangelmd/jsdelivr
files/codemirror/4.2.0/theme/paraiso-light.css
CSS
mit
1,538
/** * Galleria v 1.3.5 2014-01-25 * http://galleria.io * * Licensed under the MIT license * https://raw.github.com/aino/galleria/master/LICENSE * */ (function( $, window, Galleria, undef ) { /*global jQuery, navigator, Image, module, define */ // some references var doc = window.document, $doc = $( doc ), $win = $( window ), // native prototypes protoArray = Array.prototype, // internal constants VERSION = 1.35, DEBUG = true, TIMEOUT = 30000, DUMMY = false, NAV = navigator.userAgent.toLowerCase(), HASH = window.location.hash.replace(/#\//, ''), PROT = window.location.protocol, M = Math, F = function(){}, FALSE = function() { return false; }, IE = (function() { var v = 3, div = doc.createElement( 'div' ), all = div.getElementsByTagName( 'i' ); do { div.innerHTML = '<!--[if gt IE ' + (++v) + ']><i></i><![endif]-->'; } while ( all[0] ); return v > 4 ? v : doc.documentMode || undef; }() ), DOM = function() { return { html: doc.documentElement, body: doc.body, head: doc.getElementsByTagName('head')[0], title: doc.title }; }, IFRAME = window.parent !== window.self, // list of Galleria events _eventlist = 'data ready thumbnail loadstart loadfinish image play pause progress ' + 'fullscreen_enter fullscreen_exit idle_enter idle_exit rescale ' + 'lightbox_open lightbox_close lightbox_image', _events = (function() { var evs = []; $.each( _eventlist.split(' '), function( i, ev ) { evs.push( ev ); // legacy events if ( /_/.test( ev ) ) { evs.push( ev.replace( /_/g, '' ) ); } }); return evs; }()), // legacy options // allows the old my_setting syntax and converts it to camel case _legacyOptions = function( options ) { var n; if ( typeof options !== 'object' ) { // return whatever it was... return options; } $.each( options, function( key, value ) { if ( /^[a-z]+_/.test( key ) ) { n = ''; $.each( key.split('_'), function( i, k ) { n += i > 0 ? k.substr( 0, 1 ).toUpperCase() + k.substr( 1 ) : k; }); options[ n ] = value; delete options[ key ]; } }); return options; }, _patchEvent = function( type ) { // allow 'image' instead of Galleria.IMAGE if ( $.inArray( type, _events ) > -1 ) { return Galleria[ type.toUpperCase() ]; } return type; }, // video providers _video = { youtube: { reg: /https?:\/\/(?:[a-zA_Z]{2,3}.)?(?:youtube\.com\/watch\?)((?:[\w\d\-\_\=]+&amp;(?:amp;)?)*v(?:&lt;[A-Z]+&gt;)?=([0-9a-zA-Z\-\_]+))/i, embed: function() { return 'http://www.youtube.com/embed/' + this.id; }, getUrl: function() { return PROT + '//gdata.youtube.com/feeds/api/videos/' + this.id + '?v=2&alt=json-in-script&callback=?'; }, get_thumb: function(data) { return data.entry.media$group.media$thumbnail[2].url; }, get_image: function(data) { if ( data.entry.yt$hd ) { return PROT + '//img.youtube.com/vi/'+this.id+'/maxresdefault.jpg'; } return data.entry.media$group.media$thumbnail[3].url; } }, vimeo: { reg: /https?:\/\/(?:www\.)?(vimeo\.com)\/(?:hd#)?([0-9]+)/i, embed: function() { return 'http://player.vimeo.com/video/' + this.id; }, getUrl: function() { return PROT + '//vimeo.com/api/v2/video/' + this.id + '.json?callback=?'; }, get_thumb: function( data ) { return data[0].thumbnail_medium; }, get_image: function( data ) { return data[0].thumbnail_large; } }, dailymotion: { reg: /https?:\/\/(?:www\.)?(dailymotion\.com)\/video\/([^_]+)/, embed: function() { return PROT + '//www.dailymotion.com/embed/video/' + this.id; }, getUrl: function() { return 'https://api.dailymotion.com/video/' + this.id + '?fields=thumbnail_240_url,thumbnail_720_url&callback=?'; }, get_thumb: function( data ) { return data.thumbnail_240_url; }, get_image: function( data ) { return data.thumbnail_720_url; } }, _inst: [] }, Video = function( type, id ) { for( var i=0; i<_video._inst.length; i++ ) { if ( _video._inst[i].id === id && _video._inst[i].type == type ) { return _video._inst[i]; } } this.type = type; this.id = id; this.readys = []; _video._inst.push(this); var self = this; $.extend( this, _video[type] ); $.getJSON( this.getUrl(), function(data) { self.data = data; $.each( self.readys, function( i, fn ) { fn( self.data ); }); self.readys = []; }); this.getMedia = function( type, callback, fail ) { fail = fail || F; var self = this; var success = function( data ) { callback( self['get_'+type]( data ) ); }; try { if ( self.data ) { success( self.data ); } else { self.readys.push( success ); } } catch(e) { fail(); } }; }, // utility for testing the video URL and getting the video ID _videoTest = function( url ) { var match; for ( var v in _video ) { match = url && _video[v].reg && url.match( _video[v].reg ); if( match && match.length ) { return { id: match[2], provider: v }; } } return false; }, // native fullscreen handler _nativeFullscreen = { support: (function() { var html = DOM().html; return !IFRAME && ( html.requestFullscreen || html.mozRequestFullScreen || html.webkitRequestFullScreen ); }()), callback: F, enter: function( instance, callback, elem ) { this.instance = instance; this.callback = callback || F; elem = elem || DOM().html; if ( elem.requestFullscreen ) { elem.requestFullscreen(); } else if ( elem.mozRequestFullScreen ) { elem.mozRequestFullScreen(); } else if ( elem.webkitRequestFullScreen ) { elem.webkitRequestFullScreen(); } }, exit: function( callback ) { this.callback = callback || F; if ( doc.exitFullscreen ) { doc.exitFullscreen(); } else if ( doc.mozCancelFullScreen ) { doc.mozCancelFullScreen(); } else if ( doc.webkitCancelFullScreen ) { doc.webkitCancelFullScreen(); } }, instance: null, listen: function() { if ( !this.support ) { return; } var handler = function() { if ( !_nativeFullscreen.instance ) { return; } var fs = _nativeFullscreen.instance._fullscreen; if ( doc.fullscreen || doc.mozFullScreen || doc.webkitIsFullScreen ) { fs._enter( _nativeFullscreen.callback ); } else { fs._exit( _nativeFullscreen.callback ); } }; doc.addEventListener( 'fullscreenchange', handler, false ); doc.addEventListener( 'mozfullscreenchange', handler, false ); doc.addEventListener( 'webkitfullscreenchange', handler, false ); } }, // the internal gallery holder _galleries = [], // the internal instance holder _instances = [], // flag for errors _hasError = false, // canvas holder _canvas = false, // instance pool, holds the galleries until themeLoad is triggered _pool = [], // themeLoad trigger _themeLoad = function( theme ) { Galleria.theme = theme; // run the instances we have in the pool $.each( _pool, function( i, instance ) { if ( !instance._initialized ) { instance._init.call( instance ); } }); _pool = []; }, // the Utils singleton Utils = (function() { return { // legacy support for clearTimer clearTimer: function( id ) { $.each( Galleria.get(), function() { this.clearTimer( id ); }); }, // legacy support for addTimer addTimer: function( id ) { $.each( Galleria.get(), function() { this.addTimer( id ); }); }, array : function( obj ) { return protoArray.slice.call(obj, 0); }, create : function( className, nodeName ) { nodeName = nodeName || 'div'; var elem = doc.createElement( nodeName ); elem.className = className; return elem; }, removeFromArray : function( arr, elem ) { $.each(arr, function(i, el) { if ( el == elem ) { arr.splice(i, 1); return false; } }); return arr; }, getScriptPath : function( src ) { // the currently executing script is always the last src = src || $('script:last').attr('src'); var slices = src.split('/'); if (slices.length == 1) { return ''; } slices.pop(); return slices.join('/') + '/'; }, // CSS3 transitions, added in 1.2.4 animate : (function() { // detect transition var transition = (function( style ) { var props = 'transition WebkitTransition MozTransition OTransition'.split(' '), i; // disable css3 animations in opera until stable if ( window.opera ) { return false; } for ( i = 0; props[i]; i++ ) { if ( typeof style[ props[ i ] ] !== 'undefined' ) { return props[ i ]; } } return false; }(( doc.body || doc.documentElement).style )); // map transitionend event var endEvent = { MozTransition: 'transitionend', OTransition: 'oTransitionEnd', WebkitTransition: 'webkitTransitionEnd', transition: 'transitionend' }[ transition ]; // map bezier easing conversions var easings = { _default: [0.25, 0.1, 0.25, 1], galleria: [0.645, 0.045, 0.355, 1], galleriaIn: [0.55, 0.085, 0.68, 0.53], galleriaOut: [0.25, 0.46, 0.45, 0.94], ease: [0.25, 0, 0.25, 1], linear: [0.25, 0.25, 0.75, 0.75], 'ease-in': [0.42, 0, 1, 1], 'ease-out': [0, 0, 0.58, 1], 'ease-in-out': [0.42, 0, 0.58, 1] }; // function for setting transition css for all browsers var setStyle = function( elem, value, suffix ) { var css = {}; suffix = suffix || 'transition'; $.each( 'webkit moz ms o'.split(' '), function() { css[ '-' + this + '-' + suffix ] = value; }); elem.css( css ); }; // clear styles var clearStyle = function( elem ) { setStyle( elem, 'none', 'transition' ); if ( Galleria.WEBKIT && Galleria.TOUCH ) { setStyle( elem, 'translate3d(0,0,0)', 'transform' ); if ( elem.data('revert') ) { elem.css( elem.data('revert') ); elem.data('revert', null); } } }; // various variables var change, strings, easing, syntax, revert, form, css; // the actual animation method return function( elem, to, options ) { // extend defaults options = $.extend({ duration: 400, complete: F, stop: false }, options); // cache jQuery instance elem = $( elem ); if ( !options.duration ) { elem.css( to ); options.complete.call( elem[0] ); return; } // fallback to jQuery's animate if transition is not supported if ( !transition ) { elem.animate(to, options); return; } // stop if ( options.stop ) { // clear the animation elem.off( endEvent ); clearStyle( elem ); } // see if there is a change change = false; $.each( to, function( key, val ) { css = elem.css( key ); if ( Utils.parseValue( css ) != Utils.parseValue( val ) ) { change = true; } // also add computed styles for FF elem.css( key, css ); }); if ( !change ) { window.setTimeout( function() { options.complete.call( elem[0] ); }, options.duration ); return; } // the css strings to be applied strings = []; // the easing bezier easing = options.easing in easings ? easings[ options.easing ] : easings._default; // the syntax syntax = ' ' + options.duration + 'ms' + ' cubic-bezier(' + easing.join(',') + ')'; // add a tiny timeout so that the browsers catches any css changes before animating window.setTimeout( (function(elem, endEvent, to, syntax) { return function() { // attach the end event elem.one(endEvent, (function( elem ) { return function() { // clear the animation clearStyle(elem); // run the complete method options.complete.call(elem[0]); }; }( elem ))); // do the webkit translate3d for better performance on iOS if( Galleria.WEBKIT && Galleria.TOUCH ) { revert = {}; form = [0,0,0]; $.each( ['left', 'top'], function(i, m) { if ( m in to ) { form[ i ] = ( Utils.parseValue( to[ m ] ) - Utils.parseValue(elem.css( m )) ) + 'px'; revert[ m ] = to[ m ]; delete to[ m ]; } }); if ( form[0] || form[1]) { elem.data('revert', revert); strings.push('-webkit-transform' + syntax); // 3d animate setStyle( elem, 'translate3d(' + form.join(',') + ')', 'transform'); } } // push the animation props $.each(to, function( p, val ) { strings.push(p + syntax); }); // set the animation styles setStyle( elem, strings.join(',') ); // animate elem.css( to ); }; }(elem, endEvent, to, syntax)), 2); }; }()), removeAlpha : function( elem ) { if ( elem instanceof jQuery ) { elem = elem[0]; } if ( IE < 9 && elem ) { var style = elem.style, currentStyle = elem.currentStyle, filter = currentStyle && currentStyle.filter || style.filter || ""; if ( /alpha/.test( filter ) ) { style.filter = filter.replace( /alpha\([^)]*\)/i, '' ); } } }, forceStyles : function( elem, styles ) { elem = $(elem); if ( elem.attr( 'style' ) ) { elem.data( 'styles', elem.attr( 'style' ) ).removeAttr( 'style' ); } elem.css( styles ); }, revertStyles : function() { $.each( Utils.array( arguments ), function( i, elem ) { elem = $( elem ); elem.removeAttr( 'style' ); elem.attr('style',''); // "fixes" webkit bug if ( elem.data( 'styles' ) ) { elem.attr( 'style', elem.data('styles') ).data( 'styles', null ); } }); }, moveOut : function( elem ) { Utils.forceStyles( elem, { position: 'absolute', left: -10000 }); }, moveIn : function() { Utils.revertStyles.apply( Utils, Utils.array( arguments ) ); }, hide : function( elem, speed, callback ) { callback = callback || F; var $elem = $(elem); elem = $elem[0]; // save the value if not exist if (! $elem.data('opacity') ) { $elem.data('opacity', $elem.css('opacity') ); } // always hide var style = { opacity: 0 }; if (speed) { var complete = IE < 9 && elem ? function() { Utils.removeAlpha( elem ); elem.style.visibility = 'hidden'; callback.call( elem ); } : callback; Utils.animate( elem, style, { duration: speed, complete: complete, stop: true }); } else { if ( IE < 9 && elem ) { Utils.removeAlpha( elem ); elem.style.visibility = 'hidden'; } else { $elem.css( style ); } } }, show : function( elem, speed, callback ) { callback = callback || F; var $elem = $(elem); elem = $elem[0]; // bring back saved opacity var saved = parseFloat( $elem.data('opacity') ) || 1, style = { opacity: saved }; // animate or toggle if (speed) { if ( IE < 9 ) { $elem.css('opacity', 0); elem.style.visibility = 'visible'; } var complete = IE < 9 && elem ? function() { if ( style.opacity == 1 ) { Utils.removeAlpha( elem ); } callback.call( elem ); } : callback; Utils.animate( elem, style, { duration: speed, complete: complete, stop: true }); } else { if ( IE < 9 && style.opacity == 1 && elem ) { Utils.removeAlpha( elem ); elem.style.visibility = 'visible'; } else { $elem.css( style ); } } }, wait : function(options) { Galleria._waiters = Galleria._waiters || []; options = $.extend({ until : FALSE, success : F, error : function() { Galleria.raise('Could not complete wait function.'); }, timeout: 3000 }, options); var start = Utils.timestamp(), elapsed, now, tid, fn = function() { now = Utils.timestamp(); elapsed = now - start; Utils.removeFromArray( Galleria._waiters, tid ); if ( options.until( elapsed ) ) { options.success(); return false; } if (typeof options.timeout == 'number' && now >= start + options.timeout) { options.error(); return false; } Galleria._waiters.push( tid = window.setTimeout(fn, 10) ); }; Galleria._waiters.push( tid = window.setTimeout(fn, 10) ); }, toggleQuality : function( img, force ) { if ( ( IE !== 7 && IE !== 8 ) || !img || img.nodeName.toUpperCase() != 'IMG' ) { return; } if ( typeof force === 'undefined' ) { force = img.style.msInterpolationMode === 'nearest-neighbor'; } img.style.msInterpolationMode = force ? 'bicubic' : 'nearest-neighbor'; }, insertStyleTag : function( styles, id ) { if ( id && $( '#'+id ).length ) { return; } var style = doc.createElement( 'style' ); if ( id ) { style.id = id; } DOM().head.appendChild( style ); if ( style.styleSheet ) { // IE style.styleSheet.cssText = styles; } else { var cssText = doc.createTextNode( styles ); style.appendChild( cssText ); } }, // a loadscript method that works for local scripts loadScript: function( url, callback ) { var done = false, script = $('<scr'+'ipt>').attr({ src: url, async: true }).get(0); // Attach handlers for all browsers script.onload = script.onreadystatechange = function() { if ( !done && (!this.readyState || this.readyState === 'loaded' || this.readyState === 'complete') ) { done = true; // Handle memory leak in IE script.onload = script.onreadystatechange = null; if (typeof callback === 'function') { callback.call( this, this ); } } }; DOM().head.appendChild( script ); }, // parse anything into a number parseValue: function( val ) { if (typeof val === 'number') { return val; } else if (typeof val === 'string') { var arr = val.match(/\-?\d|\./g); return arr && arr.constructor === Array ? arr.join('')*1 : 0; } else { return 0; } }, // timestamp abstraction timestamp: function() { return new Date().getTime(); }, loadCSS : function( href, id, callback ) { var link, length; // look for manual css $('link[rel=stylesheet]').each(function() { if ( new RegExp( href ).test( this.href ) ) { link = this; return false; } }); if ( typeof id === 'function' ) { callback = id; id = undef; } callback = callback || F; // dirty // if already present, return if ( link ) { callback.call( link, link ); return link; } // save the length of stylesheets to check against length = doc.styleSheets.length; // check for existing id if( $( '#' + id ).length ) { $( '#' + id ).attr( 'href', href ); length--; } else { link = $( '<link>' ).attr({ rel: 'stylesheet', href: href, id: id }).get(0); var styles = $('link[rel="stylesheet"], style'); if ( styles.length ) { styles.get(0).parentNode.insertBefore( link, styles[0] ); } else { DOM().head.appendChild( link ); } if ( IE && length >= 31 ) { Galleria.raise( 'You have reached the browser stylesheet limit (31)', true ); return; } } if ( typeof callback === 'function' ) { // First check for dummy element (new in 1.2.8) var $loader = $('<s>').attr( 'id', 'galleria-loader' ).hide().appendTo( DOM().body ); Utils.wait({ until: function() { return $loader.height() == 1; }, success: function() { $loader.remove(); callback.call( link, link ); }, error: function() { $loader.remove(); // If failed, tell the dev to download the latest theme Galleria.raise( 'Theme CSS could not load after 20 sec. ' + ( Galleria.QUIRK ? 'Your browser is in Quirks Mode, please add a correct doctype.' : 'Please download the latest theme at http://galleria.io/customer/.' ), true ); }, timeout: 5000 }); } return link; } }; }()), // play icon _playIcon = function( container ) { var css = '.galleria-videoicon{width:60px;height:60px;position:absolute;top:50%;left:50%;z-index:1;' + 'margin:-30px 0 0 -30px;cursor:pointer;background:#000;background:rgba(0,0,0,.8);border-radius:3px;-webkit-transition:all 150ms}' + '.galleria-videoicon i{width:0px;height:0px;border-style:solid;border-width:10px 0 10px 16px;display:block;' + 'border-color:transparent transparent transparent #ffffff;margin:20px 0 0 22px}.galleria-image:hover .galleria-videoicon{background:#000}'; Utils.insertStyleTag( css, 'galleria-videoicon' ); return $( Utils.create( 'galleria-videoicon' ) ).html( '<i></i>' ).appendTo( container ) .click( function() { $( this ).siblings( 'img' ).mouseup(); }); }, // the transitions holder _transitions = (function() { var _slide = function(params, complete, fade, door) { var easing = this.getOptions('easing'), distance = this.getStageWidth(), from = { left: distance * ( params.rewind ? -1 : 1 ) }, to = { left: 0 }; if ( fade ) { from.opacity = 0; to.opacity = 1; } else { from.opacity = 1; } $(params.next).css(from); Utils.animate(params.next, to, { duration: params.speed, complete: (function( elems ) { return function() { complete(); elems.css({ left: 0 }); }; }( $( params.next ).add( params.prev ) )), queue: false, easing: easing }); if (door) { params.rewind = !params.rewind; } if (params.prev) { from = { left: 0 }; to = { left: distance * ( params.rewind ? 1 : -1 ) }; if ( fade ) { from.opacity = 1; to.opacity = 0; } $(params.prev).css(from); Utils.animate(params.prev, to, { duration: params.speed, queue: false, easing: easing, complete: function() { $(this).css('opacity', 0); } }); } }; return { active: false, init: function( effect, params, complete ) { if ( _transitions.effects.hasOwnProperty( effect ) ) { _transitions.effects[ effect ].call( this, params, complete ); } }, effects: { fade: function(params, complete) { $(params.next).css({ opacity: 0, left: 0 }); Utils.animate(params.next, { opacity: 1 },{ duration: params.speed, complete: complete }); if (params.prev) { $(params.prev).css('opacity',1).show(); Utils.animate(params.prev, { opacity: 0 },{ duration: params.speed }); } }, flash: function(params, complete) { $(params.next).css({ opacity: 0, left: 0 }); if (params.prev) { Utils.animate( params.prev, { opacity: 0 },{ duration: params.speed/2, complete: function() { Utils.animate( params.next, { opacity:1 },{ duration: params.speed, complete: complete }); } }); } else { Utils.animate( params.next, { opacity: 1 },{ duration: params.speed, complete: complete }); } }, pulse: function(params, complete) { if (params.prev) { $(params.prev).hide(); } $(params.next).css({ opacity: 0, left: 0 }).show(); Utils.animate(params.next, { opacity:1 },{ duration: params.speed, complete: complete }); }, slide: function(params, complete) { _slide.apply( this, Utils.array( arguments ) ); }, fadeslide: function(params, complete) { _slide.apply( this, Utils.array( arguments ).concat( [true] ) ); }, doorslide: function(params, complete) { _slide.apply( this, Utils.array( arguments ).concat( [false, true] ) ); } } }; }()); // listen to fullscreen _nativeFullscreen.listen(); // create special click:fast event for fast touch interaction $.event.special['click:fast'] = { propagate: true, add: function(handleObj) { var prop = this.propagate; if ( Galleria.TOUCH ) { $(this).on('touchstart.fast', function start(e) { var ev = e.originalEvent, x, y, dist = 0; if ( ev.touches.length == 1 ) { x = ev.touches[0].pageX; y = ev.touches[0].pageY; $(this).on('touchmove.fast', function(f) { var ft = f.originalEvent.touches; if ( ft.length == 1 ) { dist = M.max( M.abs( x - ft[0].pageX ), M.abs( y - ft[0].pageY ) ); } }); $(this).on('touchend.fast', function() { if( dist > 4 ) { return $(this).off('touchend.fast touchmove.fast'); } handleObj.handler.call(this, e); $(this).off('touchend.fast touchmove.fast'); }); } }); } else { $(this).on('click.fast', handleObj.handler); } }, remove: function(handleObj) { if ( Galleria.TOUCH ) { $(this).off('touchstart.fast touchmove.fast touchend.fast'); } else { $(this).off('click.fast', handleObj.handler); } } }; // trigger resize on orientationchange (IOS7) $win.on( 'orientationchange', function() { $(this).resize(); }); /** The main Galleria class @class @constructor @example var gallery = new Galleria(); @author http://aino.se @requires jQuery */ Galleria = function() { var self = this; // internal options this._options = {}; // flag for controlling play/pause this._playing = false; // internal interval for slideshow this._playtime = 5000; // internal variable for the currently active image this._active = null; // the internal queue, arrayified this._queue = { length: 0 }; // the internal data array this._data = []; // the internal dom collection this._dom = {}; // the internal thumbnails array this._thumbnails = []; // the internal layers array this._layers = []; // internal init flag this._initialized = false; // internal firstrun flag this._firstrun = false; // global stagewidth/height this._stageWidth = 0; this._stageHeight = 0; // target holder this._target = undef; // bind hashes this._binds = []; // instance id this._id = parseInt(M.random()*10000, 10); // add some elements var divs = 'container stage images image-nav image-nav-left image-nav-right ' + 'info info-text info-title info-description ' + 'thumbnails thumbnails-list thumbnails-container thumb-nav-left thumb-nav-right ' + 'loader counter tooltip', spans = 'current total'; $.each( divs.split(' '), function( i, elemId ) { self._dom[ elemId ] = Utils.create( 'galleria-' + elemId ); }); $.each( spans.split(' '), function( i, elemId ) { self._dom[ elemId ] = Utils.create( 'galleria-' + elemId, 'span' ); }); // the internal keyboard object // keeps reference of the keybinds and provides helper methods for binding keys var keyboard = this._keyboard = { keys : { 'UP': 38, 'DOWN': 40, 'LEFT': 37, 'RIGHT': 39, 'RETURN': 13, 'ESCAPE': 27, 'BACKSPACE': 8, 'SPACE': 32 }, map : {}, bound: false, press: function(e) { var key = e.keyCode || e.which; if ( key in keyboard.map && typeof keyboard.map[key] === 'function' ) { keyboard.map[key].call(self, e); } }, attach: function(map) { var key, up; for( key in map ) { if ( map.hasOwnProperty( key ) ) { up = key.toUpperCase(); if ( up in keyboard.keys ) { keyboard.map[ keyboard.keys[up] ] = map[key]; } else { keyboard.map[ up ] = map[key]; } } } if ( !keyboard.bound ) { keyboard.bound = true; $doc.on('keydown', keyboard.press); } }, detach: function() { keyboard.bound = false; keyboard.map = {}; $doc.off('keydown', keyboard.press); } }; // internal controls for keeping track of active / inactive images var controls = this._controls = { 0: undef, 1: undef, active : 0, swap : function() { controls.active = controls.active ? 0 : 1; }, getActive : function() { return self._options.swipe ? controls.slides[ self._active ] : controls[ controls.active ]; }, getNext : function() { return self._options.swipe ? controls.slides[ self.getNext( self._active ) ] : controls[ 1 - controls.active ]; }, slides : [], frames: [], layers: [] }; // internal carousel object var carousel = this._carousel = { // shortcuts next: self.$('thumb-nav-right'), prev: self.$('thumb-nav-left'), // cache the width width: 0, // track the current position current: 0, // cache max value max: 0, // save all hooks for each width in an array hooks: [], // update the carousel // you can run this method anytime, f.ex on window.resize update: function() { var w = 0, h = 0, hooks = [0]; $.each( self._thumbnails, function( i, thumb ) { if ( thumb.ready ) { w += thumb.outerWidth || $( thumb.container ).outerWidth( true ); // Due to a bug in jquery, outerwidth() returns the floor of the actual outerwidth, // if the browser is zoom to a value other than 100%. height() returns the floating point value. var containerWidth = $( thumb.container).width(); w += containerWidth - M.floor(containerWidth); hooks[ i+1 ] = w; h = M.max( h, thumb.outerHeight || $( thumb.container).outerHeight( true ) ); } }); self.$( 'thumbnails' ).css({ width: w, height: h }); carousel.max = w; carousel.hooks = hooks; carousel.width = self.$( 'thumbnails-list' ).width(); carousel.setClasses(); self.$( 'thumbnails-container' ).toggleClass( 'galleria-carousel', w > carousel.width ); // one extra calculation carousel.width = self.$( 'thumbnails-list' ).width(); // todo: fix so the carousel moves to the left }, bindControls: function() { var i; carousel.next.on( 'click:fast', function(e) { e.preventDefault(); if ( self._options.carouselSteps === 'auto' ) { for ( i = carousel.current; i < carousel.hooks.length; i++ ) { if ( carousel.hooks[i] - carousel.hooks[ carousel.current ] > carousel.width ) { carousel.set(i - 2); break; } } } else { carousel.set( carousel.current + self._options.carouselSteps); } }); carousel.prev.on( 'click:fast', function(e) { e.preventDefault(); if ( self._options.carouselSteps === 'auto' ) { for ( i = carousel.current; i >= 0; i-- ) { if ( carousel.hooks[ carousel.current ] - carousel.hooks[i] > carousel.width ) { carousel.set( i + 2 ); break; } else if ( i === 0 ) { carousel.set( 0 ); break; } } } else { carousel.set( carousel.current - self._options.carouselSteps ); } }); }, // calculate and set positions set: function( i ) { i = M.max( i, 0 ); while ( carousel.hooks[i - 1] + carousel.width >= carousel.max && i >= 0 ) { i--; } carousel.current = i; carousel.animate(); }, // get the last position getLast: function(i) { return ( i || carousel.current ) - 1; }, // follow the active image follow: function(i) { //don't follow if position fits if ( i === 0 || i === carousel.hooks.length - 2 ) { carousel.set( i ); return; } // calculate last position var last = carousel.current; while( carousel.hooks[last] - carousel.hooks[ carousel.current ] < carousel.width && last <= carousel.hooks.length ) { last ++; } // set position if ( i - 1 < carousel.current ) { carousel.set( i - 1 ); } else if ( i + 2 > last) { carousel.set( i - last + carousel.current + 2 ); } }, // helper for setting disabled classes setClasses: function() { carousel.prev.toggleClass( 'disabled', !carousel.current ); carousel.next.toggleClass( 'disabled', carousel.hooks[ carousel.current ] + carousel.width >= carousel.max ); }, // the animation method animate: function(to) { carousel.setClasses(); var num = carousel.hooks[ carousel.current ] * -1; if ( isNaN( num ) ) { return; } // FF 24 bug self.$( 'thumbnails' ).css('left', function() { return $(this).css('left'); }); Utils.animate(self.get( 'thumbnails' ), { left: num },{ duration: self._options.carouselSpeed, easing: self._options.easing, queue: false }); } }; // tooltip control // added in 1.2 var tooltip = this._tooltip = { initialized : false, open: false, timer: 'tooltip' + self._id, swapTimer: 'swap' + self._id, init: function() { tooltip.initialized = true; var css = '.galleria-tooltip{padding:3px 8px;max-width:50%;background:#ffe;color:#000;z-index:3;position:absolute;font-size:11px;line-height:1.3;' + 'opacity:0;box-shadow:0 0 2px rgba(0,0,0,.4);-moz-box-shadow:0 0 2px rgba(0,0,0,.4);-webkit-box-shadow:0 0 2px rgba(0,0,0,.4);}'; Utils.insertStyleTag( css, 'galleria-tooltip' ); self.$( 'tooltip' ).css({ opacity: 0.8, visibility: 'visible', display: 'none' }); }, // move handler move: function( e ) { var mouseX = self.getMousePosition(e).x, mouseY = self.getMousePosition(e).y, $elem = self.$( 'tooltip' ), x = mouseX, y = mouseY, height = $elem.outerHeight( true ) + 1, width = $elem.outerWidth( true ), limitY = height + 15; var maxX = self.$( 'container' ).width() - width - 2, maxY = self.$( 'container' ).height() - height - 2; if ( !isNaN(x) && !isNaN(y) ) { x += 10; y -= ( height+8 ); x = M.max( 0, M.min( maxX, x ) ); y = M.max( 0, M.min( maxY, y ) ); if( mouseY < limitY ) { y = limitY; } $elem.css({ left: x, top: y }); } }, // bind elements to the tooltip // you can bind multiple elementIDs using { elemID : function } or { elemID : string } // you can also bind single DOM elements using bind(elem, string) bind: function( elem, value ) { // todo: revise if alternative tooltip is needed for mobile devices if (Galleria.TOUCH) { return; } if (! tooltip.initialized ) { tooltip.init(); } var mouseout = function() { self.$( 'container' ).off( 'mousemove', tooltip.move ); self.clearTimer( tooltip.timer ); self.$( 'tooltip' ).stop().animate({ opacity: 0 }, 200, function() { self.$( 'tooltip' ).hide(); self.addTimer( tooltip.swapTimer, function() { tooltip.open = false; }, 1000); }); }; var hover = function( elem, value) { tooltip.define( elem, value ); $( elem ).hover(function() { self.clearTimer( tooltip.swapTimer ); self.$('container').off( 'mousemove', tooltip.move ).on( 'mousemove', tooltip.move ).trigger( 'mousemove' ); tooltip.show( elem ); self.addTimer( tooltip.timer, function() { self.$( 'tooltip' ).stop().show().animate({ opacity: 1 }); tooltip.open = true; }, tooltip.open ? 0 : 500); }, mouseout).click(mouseout); }; if ( typeof value === 'string' ) { hover( ( elem in self._dom ? self.get( elem ) : elem ), value ); } else { // asume elemID here $.each( elem, function( elemID, val ) { hover( self.get(elemID), val ); }); } }, show: function( elem ) { elem = $( elem in self._dom ? self.get(elem) : elem ); var text = elem.data( 'tt' ), mouseup = function( e ) { // attach a tiny settimeout to make sure the new tooltip is filled window.setTimeout( (function( ev ) { return function() { tooltip.move( ev ); }; }( e )), 10); elem.off( 'mouseup', mouseup ); }; text = typeof text === 'function' ? text() : text; if ( ! text ) { return; } self.$( 'tooltip' ).html( text.replace(/\s/, '&#160;') ); // trigger mousemove on mouseup in case of click elem.on( 'mouseup', mouseup ); }, define: function( elem, value ) { // we store functions, not strings if (typeof value !== 'function') { var s = value; value = function() { return s; }; } elem = $( elem in self._dom ? self.get(elem) : elem ).data('tt', value); tooltip.show( elem ); } }; // internal fullscreen control var fullscreen = this._fullscreen = { scrolled: 0, crop: undef, active: false, prev: $(), beforeEnter: function(fn){ fn(); }, beforeExit: function(fn){ fn(); }, keymap: self._keyboard.map, parseCallback: function( callback, enter ) { return _transitions.active ? function() { if ( typeof callback == 'function' ) { callback.call(self); } var active = self._controls.getActive(), next = self._controls.getNext(); self._scaleImage( next ); self._scaleImage( active ); if ( enter && self._options.trueFullscreen ) { // Firefox bug, revise later $( active.container ).add( next.container ).trigger( 'transitionend' ); } } : callback; }, enter: function( callback ) { fullscreen.beforeEnter(function() { callback = fullscreen.parseCallback( callback, true ); if ( self._options.trueFullscreen && _nativeFullscreen.support ) { // do some stuff prior animation for wmoother transitions fullscreen.active = true; Utils.forceStyles( self.get('container'), { width: '100%', height: '100%' }); self.rescale(); if ( Galleria.MAC ) { if ( !( Galleria.SAFARI && /version\/[1-5]/.test(NAV)) ) { self.$('container').css('opacity', 0).addClass('fullscreen'); window.setTimeout(function() { fullscreen.scale(); self.$('container').css('opacity', 1); }, 50); } else { self.$('stage').css('opacity', 0); window.setTimeout(function() { fullscreen.scale(); self.$('stage').css('opacity', 1); },4); } } else { self.$('container').addClass('fullscreen'); } $win.resize( fullscreen.scale ); _nativeFullscreen.enter( self, callback, self.get('container') ); } else { fullscreen.scrolled = $win.scrollTop(); if( !Galleria.TOUCH ) { window.scrollTo(0, 0); } fullscreen._enter( callback ); } }); }, _enter: function( callback ) { fullscreen.active = true; if ( IFRAME ) { fullscreen.iframe = (function() { var elem, refer = doc.referrer, test = doc.createElement('a'), loc = window.location; test.href = refer; if( test.protocol != loc.protocol || test.hostname != loc.hostname || test.port != loc.port ) { Galleria.raise('Parent fullscreen not available. Iframe protocol, domains and ports must match.'); return false; } fullscreen.pd = window.parent.document; $( fullscreen.pd ).find('iframe').each(function() { var idoc = this.contentDocument || this.contentWindow.document; if ( idoc === doc ) { elem = this; return false; } }); return elem; }()); } // hide the image until rescale is complete Utils.hide( self.getActiveImage() ); if ( IFRAME && fullscreen.iframe ) { fullscreen.iframe.scrolled = $( window.parent ).scrollTop(); window.parent.scrollTo(0, 0); } var data = self.getData(), options = self._options, inBrowser = !self._options.trueFullscreen || !_nativeFullscreen.support, htmlbody = { height: '100%', overflow: 'hidden', margin:0, padding:0 }; if (inBrowser) { self.$('container').addClass('fullscreen'); fullscreen.prev = self.$('container').prev(); if ( !fullscreen.prev.length ) { fullscreen.parent = self.$( 'container' ).parent(); } // move self.$( 'container' ).appendTo( 'body' ); // begin styleforce Utils.forceStyles(self.get('container'), { position: Galleria.TOUCH ? 'absolute' : 'fixed', top: 0, left: 0, width: '100%', height: '100%', zIndex: 10000 }); Utils.forceStyles( DOM().html, htmlbody ); Utils.forceStyles( DOM().body, htmlbody ); } if ( IFRAME && fullscreen.iframe ) { Utils.forceStyles( fullscreen.pd.documentElement, htmlbody ); Utils.forceStyles( fullscreen.pd.body, htmlbody ); Utils.forceStyles( fullscreen.iframe, $.extend( htmlbody, { width: '100%', height: '100%', top: 0, left: 0, position: 'fixed', zIndex: 10000, border: 'none' })); } // temporarily attach some keys // save the old ones first in a cloned object fullscreen.keymap = $.extend({}, self._keyboard.map); self.attachKeyboard({ escape: self.exitFullscreen, right: self.next, left: self.prev }); // temporarily save the crop fullscreen.crop = options.imageCrop; // set fullscreen options if ( options.fullscreenCrop != undef ) { options.imageCrop = options.fullscreenCrop; } // swap to big image if it's different from the display image if ( data && data.big && data.image !== data.big ) { var big = new Galleria.Picture(), cached = big.isCached( data.big ), index = self.getIndex(), thumb = self._thumbnails[ index ]; self.trigger( { type: Galleria.LOADSTART, cached: cached, rewind: false, index: index, imageTarget: self.getActiveImage(), thumbTarget: thumb, galleriaData: data }); big.load( data.big, function( big ) { self._scaleImage( big, { complete: function( big ) { self.trigger({ type: Galleria.LOADFINISH, cached: cached, index: index, rewind: false, imageTarget: big.image, thumbTarget: thumb }); var image = self._controls.getActive().image; if ( image ) { $( image ).width( big.image.width ).height( big.image.height ) .attr( 'style', $( big.image ).attr('style') ) .attr( 'src', big.image.src ); } } }); }); var n = self.getNext(index), p = new Galleria.Picture(), ndata = self.getData( n ); p.preload( self.isFullscreen() && ndata.big ? ndata.big : ndata.image ); } // init the first rescale and attach callbacks self.rescale(function() { self.addTimer(false, function() { // show the image after 50 ms if ( inBrowser ) { Utils.show( self.getActiveImage() ); } if (typeof callback === 'function') { callback.call( self ); } self.rescale(); }, 100); self.trigger( Galleria.FULLSCREEN_ENTER ); }); if ( !inBrowser ) { Utils.show( self.getActiveImage() ); } else { $win.resize( fullscreen.scale ); } }, scale : function() { self.rescale(); }, exit: function( callback ) { fullscreen.beforeExit(function() { callback = fullscreen.parseCallback( callback ); if ( self._options.trueFullscreen && _nativeFullscreen.support ) { _nativeFullscreen.exit( callback ); } else { fullscreen._exit( callback ); } }); }, _exit: function( callback ) { fullscreen.active = false; var inBrowser = !self._options.trueFullscreen || !_nativeFullscreen.support, $container = self.$( 'container' ).removeClass( 'fullscreen' ); // move back if ( fullscreen.parent ) { fullscreen.parent.prepend( $container ); } else { $container.insertAfter( fullscreen.prev ); } if ( inBrowser ) { Utils.hide( self.getActiveImage() ); // revert all styles Utils.revertStyles( self.get('container'), DOM().html, DOM().body ); // scroll back if( !Galleria.TOUCH ) { window.scrollTo(0, fullscreen.scrolled); } // reload iframe src manually var frame = self._controls.frames[ self._controls.active ]; if ( frame && frame.image ) { frame.image.src = frame.image.src; } } if ( IFRAME && fullscreen.iframe ) { Utils.revertStyles( fullscreen.pd.documentElement, fullscreen.pd.body, fullscreen.iframe ); if ( fullscreen.iframe.scrolled ) { window.parent.scrollTo(0, fullscreen.iframe.scrolled ); } } // detach all keyboard events and apply the old keymap self.detachKeyboard(); self.attachKeyboard( fullscreen.keymap ); // bring back cached options self._options.imageCrop = fullscreen.crop; // return to original image var big = self.getData().big, image = self._controls.getActive().image; if ( !self.getData().iframe && image && big && big == image.src ) { window.setTimeout(function(src) { return function() { image.src = src; }; }( self.getData().image ), 1 ); } self.rescale(function() { self.addTimer(false, function() { // show the image after 50 ms if ( inBrowser ) { Utils.show( self.getActiveImage() ); } if ( typeof callback === 'function' ) { callback.call( self ); } $win.trigger( 'resize' ); }, 50); self.trigger( Galleria.FULLSCREEN_EXIT ); }); $win.off('resize', fullscreen.scale); } }; // the internal idle object for controlling idle states var idle = this._idle = { trunk: [], bound: false, active: false, add: function(elem, to, from, hide) { if ( !elem || Galleria.TOUCH ) { return; } if (!idle.bound) { idle.addEvent(); } elem = $(elem); if ( typeof from == 'boolean' ) { hide = from; from = {}; } from = from || {}; var extract = {}, style; for ( style in to ) { if ( to.hasOwnProperty( style ) ) { extract[ style ] = elem.css( style ); } } elem.data('idle', { from: $.extend( extract, from ), to: to, complete: true, busy: false }); if ( !hide ) { idle.addTimer(); } else { elem.css( to ); } idle.trunk.push(elem); }, remove: function(elem) { elem = $(elem); $.each(idle.trunk, function(i, el) { if ( el && el.length && !el.not(elem).length ) { elem.css( elem.data( 'idle' ).from ); idle.trunk.splice(i, 1); } }); if (!idle.trunk.length) { idle.removeEvent(); self.clearTimer( idle.timer ); } }, addEvent : function() { idle.bound = true; self.$('container').on( 'mousemove click', idle.showAll ); if ( self._options.idleMode == 'hover' ) { self.$('container').on( 'mouseleave', idle.hide ); } }, removeEvent : function() { idle.bound = false; self.$('container').on( 'mousemove click', idle.showAll ); if ( self._options.idleMode == 'hover' ) { self.$('container').off( 'mouseleave', idle.hide ); } }, addTimer : function() { if( self._options.idleMode == 'hover' ) { return; } self.addTimer( 'idle', function() { idle.hide(); }, self._options.idleTime ); }, hide : function() { if ( !self._options.idleMode || self.getIndex() === false ) { return; } self.trigger( Galleria.IDLE_ENTER ); var len = idle.trunk.length; $.each( idle.trunk, function(i, elem) { var data = elem.data('idle'); if (! data) { return; } elem.data('idle').complete = false; Utils.animate( elem, data.to, { duration: self._options.idleSpeed, complete: function() { if ( i == len-1 ) { idle.active = false; } } }); }); }, showAll : function() { self.clearTimer( 'idle' ); $.each( idle.trunk, function( i, elem ) { idle.show( elem ); }); }, show: function(elem) { var data = elem.data('idle'); if ( !idle.active || ( !data.busy && !data.complete ) ) { data.busy = true; self.trigger( Galleria.IDLE_EXIT ); self.clearTimer( 'idle' ); Utils.animate( elem, data.from, { duration: self._options.idleSpeed/2, complete: function() { idle.active = true; $(elem).data('idle').busy = false; $(elem).data('idle').complete = true; } }); } idle.addTimer(); } }; // internal lightbox object // creates a predesigned lightbox for simple popups of images in galleria var lightbox = this._lightbox = { width : 0, height : 0, initialized : false, active : null, image : null, elems : {}, keymap: false, init : function() { if ( lightbox.initialized ) { return; } lightbox.initialized = true; // create some elements to work with var elems = 'overlay box content shadow title info close prevholder prev nextholder next counter image', el = {}, op = self._options, css = '', abs = 'position:absolute;', prefix = 'lightbox-', cssMap = { overlay: 'position:fixed;display:none;opacity:'+op.overlayOpacity+';filter:alpha(opacity='+(op.overlayOpacity*100)+ ');top:0;left:0;width:100%;height:100%;background:'+op.overlayBackground+';z-index:99990', box: 'position:fixed;display:none;width:400px;height:400px;top:50%;left:50%;margin-top:-200px;margin-left:-200px;z-index:99991', shadow: abs+'background:#000;width:100%;height:100%;', content: abs+'background-color:#fff;top:10px;left:10px;right:10px;bottom:10px;overflow:hidden', info: abs+'bottom:10px;left:10px;right:10px;color:#444;font:11px/13px arial,sans-serif;height:13px', close: abs+'top:10px;right:10px;height:20px;width:20px;background:#fff;text-align:center;cursor:pointer;color:#444;font:16px/22px arial,sans-serif;z-index:99999', image: abs+'top:10px;left:10px;right:10px;bottom:30px;overflow:hidden;display:block;', prevholder: abs+'width:50%;top:0;bottom:40px;cursor:pointer;', nextholder: abs+'width:50%;top:0;bottom:40px;right:-1px;cursor:pointer;', prev: abs+'top:50%;margin-top:-20px;height:40px;width:30px;background:#fff;left:20px;display:none;text-align:center;color:#000;font:bold 16px/36px arial,sans-serif', next: abs+'top:50%;margin-top:-20px;height:40px;width:30px;background:#fff;right:20px;left:auto;display:none;font:bold 16px/36px arial,sans-serif;text-align:center;color:#000', title: 'float:left', counter: 'float:right;margin-left:8px;' }, hover = function(elem) { return elem.hover( function() { $(this).css( 'color', '#bbb' ); }, function() { $(this).css( 'color', '#444' ); } ); }, appends = {}; // fix for navigation hovers transparent background event "feature" var exs = ''; if ( IE > 7 ) { exs = IE < 9 ? 'background:#000;filter:alpha(opacity=0);' : 'background:rgba(0,0,0,0);'; } else { exs = 'z-index:99999'; } cssMap.nextholder += exs; cssMap.prevholder += exs; // create and insert CSS $.each(cssMap, function( key, value ) { css += '.galleria-'+prefix+key+'{'+value+'}'; }); css += '.galleria-'+prefix+'box.iframe .galleria-'+prefix+'prevholder,'+ '.galleria-'+prefix+'box.iframe .galleria-'+prefix+'nextholder{'+ 'width:100px;height:100px;top:50%;margin-top:-70px}'; Utils.insertStyleTag( css, 'galleria-lightbox' ); // create the elements $.each(elems.split(' '), function( i, elemId ) { self.addElement( 'lightbox-' + elemId ); el[ elemId ] = lightbox.elems[ elemId ] = self.get( 'lightbox-' + elemId ); }); // initiate the image lightbox.image = new Galleria.Picture(); // append the elements $.each({ box: 'shadow content close prevholder nextholder', info: 'title counter', content: 'info image', prevholder: 'prev', nextholder: 'next' }, function( key, val ) { var arr = []; $.each( val.split(' '), function( i, prop ) { arr.push( prefix + prop ); }); appends[ prefix+key ] = arr; }); self.append( appends ); $( el.image ).append( lightbox.image.container ); $( DOM().body ).append( el.overlay, el.box ); // add the prev/next nav and bind some controls hover( $( el.close ).on( 'click:fast', lightbox.hide ).html('&#215;') ); $.each( ['Prev','Next'], function(i, dir) { var $d = $( el[ dir.toLowerCase() ] ).html( /v/.test( dir ) ? '&#8249;&#160;' : '&#160;&#8250;' ), $e = $( el[ dir.toLowerCase()+'holder'] ); $e.on( 'click:fast', function() { lightbox[ 'show' + dir ](); }); // IE7 and touch devices will simply show the nav if ( IE < 8 || Galleria.TOUCH ) { $d.show(); return; } $e.hover( function() { $d.show(); }, function(e) { $d.stop().fadeOut( 200 ); }); }); $( el.overlay ).on( 'click:fast', lightbox.hide ); // the lightbox animation is slow on ipad if ( Galleria.IPAD ) { self._options.lightboxTransitionSpeed = 0; } }, rescale: function(event) { // calculate var width = M.min( $win.width()-40, lightbox.width ), height = M.min( $win.height()-60, lightbox.height ), ratio = M.min( width / lightbox.width, height / lightbox.height ), destWidth = M.round( lightbox.width * ratio ) + 40, destHeight = M.round( lightbox.height * ratio ) + 60, to = { width: destWidth, height: destHeight, 'margin-top': M.ceil( destHeight / 2 ) *- 1, 'margin-left': M.ceil( destWidth / 2 ) *- 1 }; // if rescale event, don't animate if ( event ) { $( lightbox.elems.box ).css( to ); } else { $( lightbox.elems.box ).animate( to, { duration: self._options.lightboxTransitionSpeed, easing: self._options.easing, complete: function() { var image = lightbox.image, speed = self._options.lightboxFadeSpeed; self.trigger({ type: Galleria.LIGHTBOX_IMAGE, imageTarget: image.image }); $( image.container ).show(); $( image.image ).animate({ opacity: 1 }, speed); Utils.show( lightbox.elems.info, speed ); } }); } }, hide: function() { // remove the image lightbox.image.image = null; $win.off('resize', lightbox.rescale); $( lightbox.elems.box ).hide().find( 'iframe' ).remove(); Utils.hide( lightbox.elems.info ); self.detachKeyboard(); self.attachKeyboard( lightbox.keymap ); lightbox.keymap = false; Utils.hide( lightbox.elems.overlay, 200, function() { $( this ).hide().css( 'opacity', self._options.overlayOpacity ); self.trigger( Galleria.LIGHTBOX_CLOSE ); }); }, showNext: function() { lightbox.show( self.getNext( lightbox.active ) ); }, showPrev: function() { lightbox.show( self.getPrev( lightbox.active ) ); }, show: function(index) { lightbox.active = index = typeof index === 'number' ? index : self.getIndex() || 0; if ( !lightbox.initialized ) { lightbox.init(); } // trigger the event self.trigger( Galleria.LIGHTBOX_OPEN ); // temporarily attach some keys // save the old ones first in a cloned object if ( !lightbox.keymap ) { lightbox.keymap = $.extend({}, self._keyboard.map); self.attachKeyboard({ escape: lightbox.hide, right: lightbox.showNext, left: lightbox.showPrev }); } $win.off('resize', lightbox.rescale ); var data = self.getData(index), total = self.getDataLength(), n = self.getNext( index ), ndata, p, i; Utils.hide( lightbox.elems.info ); try { for ( i = self._options.preload; i > 0; i-- ) { p = new Galleria.Picture(); ndata = self.getData( n ); p.preload( ndata.big ? ndata.big : ndata.image ); n = self.getNext( n ); } } catch(e) {} lightbox.image.isIframe = ( data.iframe && !data.image ); $( lightbox.elems.box ).toggleClass( 'iframe', lightbox.image.isIframe ); $( lightbox.image.container ).find( '.galleria-videoicon' ).remove(); lightbox.image.load( data.big || data.image || data.iframe, function( image ) { if ( image.isIframe ) { var cw = $(window).width(), ch = $(window).height(); if ( image.video && self._options.maxVideoSize ) { var r = M.min( self._options.maxVideoSize/cw, self._options.maxVideoSize/ch ); if ( r < 1 ) { cw *= r; ch *= r; } } lightbox.width = cw; lightbox.height = ch; } else { lightbox.width = image.original.width; lightbox.height = image.original.height; } $( image.image ).css({ width: image.isIframe ? '100%' : '100.1%', height: image.isIframe ? '100%' : '100.1%', top: 0, bottom: 0, zIndex: 99998, opacity: 0, visibility: 'visible' }).parent().height('100%'); lightbox.elems.title.innerHTML = data.title || ''; lightbox.elems.counter.innerHTML = (index + 1) + ' / ' + total; $win.resize( lightbox.rescale ); lightbox.rescale(); if( data.image && data.iframe ) { $( lightbox.elems.box ).addClass('iframe'); if ( data.video ) { var $icon = _playIcon( image.container ).hide(); window.setTimeout(function() { $icon.fadeIn(200); }, 200); } $( image.image ).css( 'cursor', 'pointer' ).mouseup((function(data, image) { return function(e) { $( lightbox.image.container ).find( '.galleria-videoicon' ).remove(); e.preventDefault(); image.isIframe = true; image.load( data.iframe + ( data.video ? '&autoplay=1' : '' ), { width: '100%', height: IE < 8 ? $( lightbox.image.container ).height() : '100%' }); }; }(data, image))); } }); $( lightbox.elems.overlay ).show().css( 'visibility', 'visible' ); $( lightbox.elems.box ).show(); } }; // the internal timeouts object // provides helper methods for controlling timeouts var _timer = this._timer = { trunk: {}, add: function( id, fn, delay, loop ) { id = id || new Date().getTime(); loop = loop || false; this.clear( id ); if ( loop ) { var old = fn; fn = function() { old(); _timer.add( id, fn, delay ); }; } this.trunk[ id ] = window.setTimeout( fn, delay ); }, clear: function( id ) { var del = function( i ) { window.clearTimeout( this.trunk[ i ] ); delete this.trunk[ i ]; }, i; if ( !!id && id in this.trunk ) { del.call( this, id ); } else if ( typeof id === 'undefined' ) { for ( i in this.trunk ) { if ( this.trunk.hasOwnProperty( i ) ) { del.call( this, i ); } } } } }; return this; }; // end Galleria constructor Galleria.prototype = { // bring back the constructor reference constructor: Galleria, /** Use this function to initialize the gallery and start loading. Should only be called once per instance. @param {HTMLElement} target The target element @param {Object} options The gallery options @returns Instance */ init: function( target, options ) { options = _legacyOptions( options ); // save the original ingredients this._original = { target: target, options: options, data: null }; // save the target here this._target = this._dom.target = target.nodeName ? target : $( target ).get(0); // save the original content for destruction this._original.html = this._target.innerHTML; // push the instance _instances.push( this ); // raise error if no target is detected if ( !this._target ) { Galleria.raise('Target not found', true); return; } // apply options this._options = { autoplay: false, carousel: true, carouselFollow: true, // legacy, deprecate at 1.3 carouselSpeed: 400, carouselSteps: 'auto', clicknext: false, dailymotion: { foreground: '%23EEEEEE', highlight: '%235BCEC5', background: '%23222222', logo: 0, hideInfos: 1 }, dataConfig : function( elem ) { return {}; }, dataSelector: 'img', dataSort: false, dataSource: this._target, debug: undef, dummy: undef, // 1.2.5 easing: 'galleria', extend: function(options) {}, fullscreenCrop: undef, // 1.2.5 fullscreenDoubleTap: true, // 1.2.4 toggles fullscreen on double-tap for touch devices fullscreenTransition: undef, // 1.2.6 height: 0, idleMode: true, // 1.2.4 toggles idleMode idleTime: 3000, idleSpeed: 200, imageCrop: false, imageMargin: 0, imagePan: false, imagePanSmoothness: 12, imagePosition: '50%', imageTimeout: undef, // 1.2.5 initialTransition: undef, // 1.2.4, replaces transitionInitial keepSource: false, layerFollow: true, // 1.2.5 lightbox: false, // 1.2.3 lightboxFadeSpeed: 200, lightboxTransitionSpeed: 200, linkSourceImages: true, maxScaleRatio: undef, maxVideoSize: undef, // 1.2.9 minScaleRatio: undef, // deprecated in 1.2.9 overlayOpacity: 0.85, overlayBackground: '#0b0b0b', pauseOnInteraction: true, popupLinks: false, preload: 2, queue: true, responsive: true, show: 0, showInfo: true, showCounter: true, showImagenav: true, swipe: 'auto', // 1.2.4 -> revised in 1.3 -> changed type in 1.3.5 thumbCrop: true, thumbEventType: 'click:fast', thumbMargin: 0, thumbQuality: 'auto', thumbDisplayOrder: true, // 1.2.8 thumbPosition: '50%', // 1.3 thumbnails: true, touchTransition: undef, // 1.2.6 transition: 'fade', transitionInitial: undef, // legacy, deprecate in 1.3. Use initialTransition instead. transitionSpeed: 400, trueFullscreen: true, // 1.2.7 useCanvas: false, // 1.2.4 variation: '', // 1.3.2 videoPoster: true, // 1.3 vimeo: { title: 0, byline: 0, portrait: 0, color: 'aaaaaa' }, wait: 5000, // 1.2.7 width: 'auto', youtube: { modestbranding: 1, autohide: 1, color: 'white', hd: 1, rel: 0, showinfo: 0 } }; // legacy support for transitionInitial this._options.initialTransition = this._options.initialTransition || this._options.transitionInitial; // turn off debug if ( options && options.debug === false ) { DEBUG = false; } // set timeout if ( options && typeof options.imageTimeout === 'number' ) { TIMEOUT = options.imageTimeout; } // set dummy if ( options && typeof options.dummy === 'string' ) { DUMMY = options.dummy; } // hide all content $( this._target ).children().hide(); // Warn for quirks mode if ( Galleria.QUIRK ) { Galleria.raise('Your page is in Quirks mode, Galleria may not render correctly. Please validate your HTML and add a correct doctype.'); } // now we just have to wait for the theme... if ( typeof Galleria.theme === 'object' ) { this._init(); } else { // push the instance into the pool and run it when the theme is ready _pool.push( this ); } return this; }, // this method should only be called once per instance // for manipulation of data, use the .load method _init: function() { var self = this, options = this._options; if ( this._initialized ) { Galleria.raise( 'Init failed: Gallery instance already initialized.' ); return this; } this._initialized = true; if ( !Galleria.theme ) { Galleria.raise( 'Init failed: No theme found.', true ); return this; } // merge the theme & caller options $.extend( true, options, Galleria.theme.defaults, this._original.options, Galleria.configure.options ); // internally we use boolean for swipe options.swipe = (function(s) { if ( s == 'enforced' ) { return true; } // legacy patch if( s === false || s == 'disabled' ) { return false; } return !!Galleria.TOUCH; }( options.swipe )); // disable options that arent compatible with swipe if ( options.swipe ) { options.clicknext = false; options.imagePan = false; } // check for canvas support (function( can ) { if ( !( 'getContext' in can ) ) { can = null; return; } _canvas = _canvas || { elem: can, context: can.getContext( '2d' ), cache: {}, length: 0 }; }( doc.createElement( 'canvas' ) ) ); // bind the gallery to run when data is ready this.bind( Galleria.DATA, function() { // remove big if total pixels are less than 1024 (most phones) if ( window.screen && window.screen.width && Array.prototype.forEach ) { this._data.forEach(function(data) { var density = 'devicePixelRatio' in window ? window.devicePixelRatio : 1, m = M.max( window.screen.width, window.screen.height ); if ( m*density < 1024 ) { data.big = data.image; } }); } // save the new data this._original.data = this._data; // lets show the counter here this.get('total').innerHTML = this.getDataLength(); // cache the container var $container = this.$( 'container' ); // set ratio if height is < 2 if ( self._options.height < 2 ) { self._userRatio = self._ratio = self._options.height; } // the gallery is ready, let's just wait for the css var num = { width: 0, height: 0 }; var testHeight = function() { return self.$( 'stage' ).height(); }; // check container and thumbnail height Utils.wait({ until: function() { // keep trying to get the value num = self._getWH(); $container.width( num.width ).height( num.height ); return testHeight() && num.width && num.height > 50; }, success: function() { self._width = num.width; self._height = num.height; self._ratio = self._ratio || num.height/num.width; // for some strange reason, webkit needs a single setTimeout to play ball if ( Galleria.WEBKIT ) { window.setTimeout( function() { self._run(); }, 1); } else { self._run(); } }, error: function() { // Height was probably not set, raise hard errors if ( testHeight() ) { Galleria.raise('Could not extract sufficient width/height of the gallery container. Traced measures: width:' + num.width + 'px, height: ' + num.height + 'px.', true); } else { Galleria.raise('Could not extract a stage height from the CSS. Traced height: ' + testHeight() + 'px.', true); } }, timeout: typeof this._options.wait == 'number' ? this._options.wait : false }); }); // build the gallery frame this.append({ 'info-text' : ['info-title', 'info-description'], 'info' : ['info-text'], 'image-nav' : ['image-nav-right', 'image-nav-left'], 'stage' : ['images', 'loader', 'counter', 'image-nav'], 'thumbnails-list' : ['thumbnails'], 'thumbnails-container' : ['thumb-nav-left', 'thumbnails-list', 'thumb-nav-right'], 'container' : ['stage', 'thumbnails-container', 'info', 'tooltip'] }); Utils.hide( this.$( 'counter' ).append( this.get( 'current' ), doc.createTextNode(' / '), this.get( 'total' ) ) ); this.setCounter('&#8211;'); Utils.hide( self.get('tooltip') ); // add a notouch class on the container to prevent unwanted :hovers on touch devices this.$( 'container' ).addClass( ( Galleria.TOUCH ? 'touch' : 'notouch' ) + ' ' + this._options.variation ); // add images to the controls if ( !this._options.swipe ) { $.each( new Array(2), function( i ) { // create a new Picture instance var image = new Galleria.Picture(); // apply some styles, create & prepend overlay $( image.container ).css({ position: 'absolute', top: 0, left: 0 }).prepend( self._layers[i] = $( Utils.create('galleria-layer') ).css({ position: 'absolute', top:0, left:0, right:0, bottom:0, zIndex:2 })[0] ); // append the image self.$( 'images' ).append( image.container ); // reload the controls self._controls[i] = image; // build a frame var frame = new Galleria.Picture(); frame.isIframe = true; $( frame.container ).attr('class', 'galleria-frame').css({ position: 'absolute', top: 0, left: 0, zIndex: 4, background: '#000', display: 'none' }).appendTo( image.container ); self._controls.frames[i] = frame; }); } // some forced generic styling this.$( 'images' ).css({ position: 'relative', top: 0, left: 0, width: '100%', height: '100%' }); if ( options.swipe ) { this.$( 'images' ).css({ position: 'absolute', top: 0, left: 0, width: 0, height: '100%' }); this.finger = new Galleria.Finger(this.get('stage'), { onchange: function(page) { self.pause().show(page); }, oncomplete: function(page) { var index = M.max( 0, M.min( parseInt( page, 10 ), self.getDataLength() - 1 ) ), data = self.getData(index); $( self._thumbnails[ index ].container ) .addClass( 'active' ) .siblings( '.active' ) .removeClass( 'active' ); if ( !data ) { return; } self.$( 'images' ).find( 'iframe' ).remove(); self.$( 'images' ).find( '.galleria-frame' ).css('opacity', 0).hide(); if ( self._options.carousel && self._options.carouselFollow ) { self._carousel.follow( index ); } } }); this.bind( Galleria.RESCALE, function() { this.finger.setup(); }); this.$('stage').on('click', function(e) { var data = self.getData(); if ( !data ) { return; } if ( data.iframe ) { if ( self.isPlaying() ) { self.pause(); } var frame = self._controls.frames[ self._active ], w = self._stageWidth, h = self._stageHeight; if ( $( frame.container ).find( 'iframe' ).length ) { return; } $( frame.container ).css({ width: w, height: h, opacity: 0 }).show().animate({ opacity: 1 }, 200); window.setTimeout(function() { frame.load( data.iframe + ( data.video ? '&autoplay=1' : '' ), { width: w, height: h }, function( frame ) { self.$( 'container' ).addClass( 'videoplay' ); frame.scale({ width: self._stageWidth, height: self._stageHeight, iframelimit: data.video ? self._options.maxVideoSize : undef }); }); }, 100); return; } if ( data.link ) { if ( self._options.popupLinks ) { var win = window.open( data.link, '_blank' ); } else { window.location.href = data.link; } return; } }); this.bind( Galleria.IMAGE, function(e) { self.setCounter( e.index ); self.setInfo( e.index ); var next = this.getNext(), prev = this.getPrev(); var preloads = [prev,next]; preloads.push(this.getNext(next), this.getPrev(prev), self._controls.slides.length-1); var filtered = []; $.each(preloads, function(i, val) { if ( $.inArray(val, filtered) == -1 ) { filtered.push(val); } }); $.each(filtered, function(i, loadme) { var d = self.getData(loadme), img = self._controls.slides[loadme], src = self.isFullscreen() && d.big ? d.big : ( d.image || d.iframe ); if ( d.iframe && !d.image ) { img.isIframe = true; } if ( !img.ready ) { self._controls.slides[loadme].load(src, function(img) { if ( !img.isIframe ) { $(img.image).css('visibility', 'hidden'); } self._scaleImage(img, { complete: function(img) { if ( !img.isIframe ) { $(img.image).css({ opacity: 0, visibility: 'visible' }).animate({ opacity: 1 }, 200); } } }); }); } }); }); } this.$( 'thumbnails, thumbnails-list' ).css({ overflow: 'hidden', position: 'relative' }); // bind image navigation arrows this.$( 'image-nav-right, image-nav-left' ).on( 'click:fast', function(e) { // pause if options is set if ( options.pauseOnInteraction ) { self.pause(); } // navigate var fn = /right/.test( this.className ) ? 'next' : 'prev'; self[ fn ](); }).on('click', function(e) { e.preventDefault(); // tune the clicknext option if ( options.clicknext || options.swipe ) { e.stopPropagation(); } }); // hide controls if chosen to $.each( ['info','counter','image-nav'], function( i, el ) { if ( options[ 'show' + el.substr(0,1).toUpperCase() + el.substr(1).replace(/-/,'') ] === false ) { Utils.moveOut( self.get( el.toLowerCase() ) ); } }); // load up target content this.load(); // now it's usually safe to remove the content // IE will never stop loading if we remove it, so let's keep it hidden for IE (it's usually fast enough anyway) if ( !options.keepSource && !IE ) { this._target.innerHTML = ''; } // re-append the errors, if they happened before clearing if ( this.get( 'errors' ) ) { this.appendChild( 'target', 'errors' ); } // append the gallery frame this.appendChild( 'target', 'container' ); // parse the carousel on each thumb load if ( options.carousel ) { var count = 0, show = options.show; this.bind( Galleria.THUMBNAIL, function() { this.updateCarousel(); if ( ++count == this.getDataLength() && typeof show == 'number' && show > 0 ) { this._carousel.follow( show ); } }); } // bind window resize for responsiveness if ( options.responsive ) { $win.on( 'resize', function() { if ( !self.isFullscreen() ) { self.resize(); } }); } // double-tap/click fullscreen toggle if ( options.fullscreenDoubleTap ) { this.$( 'stage' ).on( 'touchstart', (function() { var last, cx, cy, lx, ly, now, getData = function(e) { return e.originalEvent.touches ? e.originalEvent.touches[0] : e; }; self.$( 'stage' ).on('touchmove', function() { last = 0; }); return function(e) { if( /(-left|-right)/.test(e.target.className) ) { return; } now = Utils.timestamp(); cx = getData(e).pageX; cy = getData(e).pageY; if ( e.originalEvent.touches.length < 2 && ( now - last < 300 ) && ( cx - lx < 20) && ( cy - ly < 20) ) { self.toggleFullscreen(); e.preventDefault(); return; } last = now; lx = cx; ly = cy; }; }())); } // bind the ons $.each( Galleria.on.binds, function(i, bind) { // check if already bound if ( $.inArray( bind.hash, self._binds ) == -1 ) { self.bind( bind.type, bind.callback ); } }); return this; }, addTimer : function() { this._timer.add.apply( this._timer, Utils.array( arguments ) ); return this; }, clearTimer : function() { this._timer.clear.apply( this._timer, Utils.array( arguments ) ); return this; }, // parse width & height from CSS or options _getWH : function() { var $container = this.$( 'container' ), $target = this.$( 'target' ), self = this, num = {}, arr; $.each(['width', 'height'], function( i, m ) { // first check if options is set if ( self._options[ m ] && typeof self._options[ m ] === 'number') { num[ m ] = self._options[ m ]; } else { arr = [ Utils.parseValue( $container.css( m ) ), // the container css height Utils.parseValue( $target.css( m ) ), // the target css height $container[ m ](), // the container jQuery method $target[ m ]() // the target jQuery method ]; // if first time, include the min-width & min-height if ( !self[ '_'+m ] ) { arr.splice(arr.length, Utils.parseValue( $container.css( 'min-'+m ) ), Utils.parseValue( $target.css( 'min-'+m ) ) ); } // else extract the measures from different sources and grab the highest value num[ m ] = M.max.apply( M, arr ); } }); // allow setting a height ratio instead of exact value // useful when doing responsive galleries if ( self._userRatio ) { num.height = num.width * self._userRatio; } return num; }, // Creates the thumbnails and carousel // can be used at any time, f.ex when the data object is manipulated // push is an optional argument with pushed images _createThumbnails : function( push ) { this.get( 'total' ).innerHTML = this.getDataLength(); var src, thumb, data, $container, self = this, o = this._options, i = push ? this._data.length - push.length : 0, chunk = i, thumbchunk = [], loadindex = 0, gif = IE < 8 ? 'http://upload.wikimedia.org/wikipedia/commons/c/c0/Blank.gif' : 'data:image/gif;base64,R0lGODlhAQABAPABAP///wAAACH5BAEKAAAALAAAAAABAAEAAAICRAEAOw%3D%3D', // get previously active thumbnail, if exists active = (function() { var a = self.$('thumbnails').find('.active'); if ( !a.length ) { return false; } return a.find('img').attr('src'); }()), // cache the thumbnail option optval = typeof o.thumbnails === 'string' ? o.thumbnails.toLowerCase() : null, // move some data into the instance // for some reason, jQuery cant handle css(property) when zooming in FF, breaking the gallery // so we resort to getComputedStyle for browsers who support it getStyle = function( prop ) { return doc.defaultView && doc.defaultView.getComputedStyle ? doc.defaultView.getComputedStyle( thumb.container, null )[ prop ] : $container.css( prop ); }, fake = function(image, index, container) { return function() { $( container ).append( image ); self.trigger({ type: Galleria.THUMBNAIL, thumbTarget: image, index: index, galleriaData: self.getData( index ) }); }; }, onThumbEvent = function( e ) { // pause if option is set if ( o.pauseOnInteraction ) { self.pause(); } // extract the index from the data var index = $( e.currentTarget ).data( 'index' ); if ( self.getIndex() !== index ) { self.show( index ); } e.preventDefault(); }, thumbComplete = function( thumb, callback ) { $( thumb.container ).css( 'visibility', 'visible' ); self.trigger({ type: Galleria.THUMBNAIL, thumbTarget: thumb.image, index: thumb.data.order, galleriaData: self.getData( thumb.data.order ) }); if ( typeof callback == 'function' ) { callback.call( self, thumb ); } }, onThumbLoad = function( thumb, callback ) { // scale when ready thumb.scale({ width: thumb.data.width, height: thumb.data.height, crop: o.thumbCrop, margin: o.thumbMargin, canvas: o.useCanvas, position: o.thumbPosition, complete: function( thumb ) { // shrink thumbnails to fit var top = ['left', 'top'], arr = ['Width', 'Height'], m, css, data = self.getData( thumb.index ); // calculate shrinked positions $.each(arr, function( i, measure ) { m = measure.toLowerCase(); if ( (o.thumbCrop !== true || o.thumbCrop === m ) ) { css = {}; css[ m ] = thumb[ m ]; $( thumb.container ).css( css ); css = {}; css[ top[ i ] ] = 0; $( thumb.image ).css( css ); } // cache outer measures thumb[ 'outer' + measure ] = $( thumb.container )[ 'outer' + measure ]( true ); }); // set high quality if downscale is moderate Utils.toggleQuality( thumb.image, o.thumbQuality === true || ( o.thumbQuality === 'auto' && thumb.original.width < thumb.width * 3 ) ); if ( o.thumbDisplayOrder && !thumb.lazy ) { $.each( thumbchunk, function( i, th ) { if ( i === loadindex && th.ready && !th.displayed ) { loadindex++; th.displayed = true; thumbComplete( th, callback ); return; } }); } else { thumbComplete( thumb, callback ); } } }); }; if ( !push ) { this._thumbnails = []; this.$( 'thumbnails' ).empty(); } // loop through data and create thumbnails for( ; this._data[ i ]; i++ ) { data = this._data[ i ]; // get source from thumb or image src = data.thumb || data.image; if ( ( o.thumbnails === true || optval == 'lazy' ) && ( data.thumb || data.image ) ) { // add a new Picture instance thumb = new Galleria.Picture(i); // save the index thumb.index = i; // flag displayed thumb.displayed = false; // flag lazy thumb.lazy = false; // flag video thumb.video = false; // append the thumbnail this.$( 'thumbnails' ).append( thumb.container ); // cache the container $container = $( thumb.container ); // hide it $container.css( 'visibility', 'hidden' ); thumb.data = { width : Utils.parseValue( getStyle( 'width' ) ), height : Utils.parseValue( getStyle( 'height' ) ), order : i, src : src }; // grab & reset size for smoother thumbnail loads if ( o.thumbCrop !== true ) { $container.css( { width: 'auto', height: 'auto' } ); } else { $container.css( { width: thumb.data.width, height: thumb.data.height } ); } // load the thumbnail if ( optval == 'lazy' ) { $container.addClass( 'lazy' ); thumb.lazy = true; thumb.load( gif, { height: thumb.data.height, width: thumb.data.width }); } else { thumb.load( src, onThumbLoad ); } // preload all images here if ( o.preload === 'all' ) { thumb.preload( data.image ); } // create empty spans if thumbnails is set to 'empty' } else if ( data.iframe || optval === 'empty' || optval === 'numbers' ) { thumb = { container: Utils.create( 'galleria-image' ), image: Utils.create( 'img', 'span' ), ready: true, data: { order: i } }; // create numbered thumbnails if ( optval === 'numbers' ) { $( thumb.image ).text( i + 1 ); } if ( data.iframe ) { $( thumb.image ).addClass( 'iframe' ); } this.$( 'thumbnails' ).append( thumb.container ); // we need to "fake" a loading delay before we append and trigger // 50+ should be enough window.setTimeout( ( fake )( thumb.image, i, thumb.container ), 50 + ( i*20 ) ); // create null object to silent errors } else { thumb = { container: null, image: null }; } // add events for thumbnails // you can control the event type using thumb_event_type // we'll add the same event to the source if it's kept $( thumb.container ).add( o.keepSource && o.linkSourceImages ? data.original : null ) .data('index', i).on( o.thumbEventType, onThumbEvent ) .data('thumbload', onThumbLoad); if (active === src) { $( thumb.container ).addClass( 'active' ); } this._thumbnails.push( thumb ); } thumbchunk = this._thumbnails.slice( chunk ); return this; }, /** Lazy-loads thumbnails. You can call this method to load lazy thumbnails at run time @param {Array|Number} index Index or array of indexes of thumbnails to be loaded @param {Function} complete Callback that is called when all lazy thumbnails have been loaded @returns Instance */ lazyLoad: function( index, complete ) { var arr = index.constructor == Array ? index : [ index ], self = this, loaded = 0; $.each( arr, function(i, ind) { if ( ind > self._thumbnails.length - 1 ) { return; } var thumb = self._thumbnails[ ind ], data = thumb.data, callback = function() { if ( ++loaded == arr.length && typeof complete == 'function' ) { complete.call( self ); } }, thumbload = $( thumb.container ).data( 'thumbload' ); if ( thumb.video ) { thumbload.call( self, thumb, callback ); } else { thumb.load( data.src , function( thumb ) { thumbload.call( self, thumb, callback ); }); } }); return this; }, /** Lazy-loads thumbnails in chunks. This method automatcally chops up the loading process of many thumbnails into chunks @param {Number} size Size of each chunk to be loaded @param {Number} [delay] Delay between each loads @returns Instance */ lazyLoadChunks: function( size, delay ) { var len = this.getDataLength(), i = 0, n = 0, arr = [], temp = [], self = this; delay = delay || 0; for( ; i<len; i++ ) { temp.push(i); if ( ++n == size || i == len-1 ) { arr.push( temp ); n = 0; temp = []; } } var init = function( wait ) { var a = arr.shift(); if ( a ) { window.setTimeout(function() { self.lazyLoad(a, function() { init( true ); }); }, ( delay && wait ) ? delay : 0 ); } }; init( false ); return this; }, // the internal _run method should be called after loading data into galleria // makes sure the gallery has proper measurements before postrun & ready _run : function() { var self = this; self._createThumbnails(); // make sure we have a stageHeight && stageWidth Utils.wait({ timeout: 10000, until: function() { // Opera crap if ( Galleria.OPERA ) { self.$( 'stage' ).css( 'display', 'inline-block' ); } self._stageWidth = self.$( 'stage' ).width(); self._stageHeight = self.$( 'stage' ).height(); return( self._stageWidth && self._stageHeight > 50 ); // what is an acceptable height? }, success: function() { // save the instance _galleries.push( self ); // postrun some stuff after the gallery is ready // create the touch slider if ( self._options.swipe ) { var $images = self.$( 'images' ).width( self.getDataLength() * self._stageWidth ); $.each( new Array( self.getDataLength() ), function(i) { var image = new Galleria.Picture(), data = self.getData(i); $( image.container ).css({ position: 'absolute', top: 0, left: self._stageWidth*i }).prepend( self._layers[i] = $( Utils.create('galleria-layer') ).css({ position: 'absolute', top:0, left:0, right:0, bottom:0, zIndex:2 })[0] ).appendTo( $images ); if( data.video ) { _playIcon( image.container ); } self._controls.slides.push(image); var frame = new Galleria.Picture(); frame.isIframe = true; $( frame.container ).attr('class', 'galleria-frame').css({ position: 'absolute', top: 0, left: 0, zIndex: 4, background: '#000', display: 'none' }).appendTo( image.container ); self._controls.frames.push(frame); }); self.finger.setup(); } // show counter Utils.show( self.get('counter') ); // bind carousel nav if ( self._options.carousel ) { self._carousel.bindControls(); } // start autoplay if ( self._options.autoplay ) { self.pause(); if ( typeof self._options.autoplay === 'number' ) { self._playtime = self._options.autoplay; } self._playing = true; } // if second load, just do the show and return if ( self._firstrun ) { if ( self._options.autoplay ) { self.trigger( Galleria.PLAY ); } if ( typeof self._options.show === 'number' ) { self.show( self._options.show ); } return; } self._firstrun = true; // initialize the History plugin if ( Galleria.History ) { // bind the show method Galleria.History.change(function( value ) { // if ID is NaN, the user pressed back from the first image // return to previous address if ( isNaN( value ) ) { window.history.go(-1); // else show the image } else { self.show( value, undef, true ); } }); } self.trigger( Galleria.READY ); // call the theme init method Galleria.theme.init.call( self, self._options ); // Trigger Galleria.ready $.each( Galleria.ready.callbacks, function(i ,fn) { if ( typeof fn == 'function' ) { fn.call( self, self._options ); } }); // call the extend option self._options.extend.call( self, self._options ); // show the initial image // first test for permalinks in history if ( /^[0-9]{1,4}$/.test( HASH ) && Galleria.History ) { self.show( HASH, undef, true ); } else if( self._data[ self._options.show ] ) { self.show( self._options.show ); } // play trigger if ( self._options.autoplay ) { self.trigger( Galleria.PLAY ); } }, error: function() { Galleria.raise('Stage width or height is too small to show the gallery. Traced measures: width:' + self._stageWidth + 'px, height: ' + self._stageHeight + 'px.', true); } }); }, /** Loads data into the gallery. You can call this method on an existing gallery to reload the gallery with new data. @param {Array|string} [source] Optional JSON array of data or selector of where to find data in the document. Defaults to the Galleria target or dataSource option. @param {string} [selector] Optional element selector of what elements to parse. Defaults to 'img'. @param {Function} [config] Optional function to modify the data extraction proceedure from the selector. See the dataConfig option for more information. @returns Instance */ load : function( source, selector, config ) { var self = this, o = this._options; // empty the data array this._data = []; // empty the thumbnails this._thumbnails = []; this.$('thumbnails').empty(); // shorten the arguments if ( typeof selector === 'function' ) { config = selector; selector = null; } // use the source set by target source = source || o.dataSource; // use selector set by option selector = selector || o.dataSelector; // use the dataConfig set by option config = config || o.dataConfig; // if source is a true object, make it into an array if( $.isPlainObject( source ) ) { source = [source]; } // check if the data is an array already if ( $.isArray( source ) ) { if ( this.validate( source ) ) { this._data = source; } else { Galleria.raise( 'Load failed: JSON Array not valid.' ); } } else { // add .video and .iframe to the selector (1.2.7) selector += ',.video,.iframe'; // loop through images and set data $( source ).find( selector ).each( function( i, elem ) { elem = $( elem ); var data = {}, parent = elem.parent(), href = parent.attr( 'href' ), rel = parent.attr( 'rel' ); if( href && ( elem[0].nodeName == 'IMG' || elem.hasClass('video') ) && _videoTest( href ) ) { data.video = href; } else if( href && elem.hasClass('iframe') ) { data.iframe = href; } else { data.image = data.big = href; } if ( rel ) { data.big = rel; } // alternative extraction from HTML5 data attribute, added in 1.2.7 $.each( 'big title description link layer image'.split(' '), function( i, val ) { if ( elem.data(val) ) { data[ val ] = elem.data(val).toString(); } }); if ( !data.big ) { data.big = data.image; } // mix default extractions with the hrefs and config // and push it into the data array self._data.push( $.extend({ title: elem.attr('title') || '', thumb: elem.attr('src'), image: elem.attr('src'), big: elem.attr('src'), description: elem.attr('alt') || '', link: elem.attr('longdesc'), original: elem.get(0) // saved as a reference }, data, config( elem ) ) ); }); } if ( typeof o.dataSort == 'function' ) { protoArray.sort.call( this._data, o.dataSort ); } else if ( o.dataSort == 'random' ) { this._data.sort( function() { return M.round(M.random())-0.5; }); } // trigger the DATA event and return if ( this.getDataLength() ) { this._parseData( function() { this.trigger( Galleria.DATA ); } ); } return this; }, // make sure the data works properly _parseData : function( callback ) { var self = this, current, ready = false, onload = function() { var complete = true; $.each( self._data, function( i, data ) { if ( data.loading ) { complete = false; return false; } }); if ( complete && !ready ) { ready = true; callback.call( self ); } }; $.each( this._data, function( i, data ) { current = self._data[ i ]; // copy image as thumb if no thumb exists if ( 'thumb' in data === false ) { current.thumb = data.image; } // copy image as big image if no biggie exists if ( !data.big ) { current.big = data.image; } // parse video if ( 'video' in data ) { var result = _videoTest( data.video ); if ( result ) { current.iframe = new Video(result.provider, result.id ).embed() + (function() { // add options if ( typeof self._options[ result.provider ] == 'object' ) { var str = '?', arr = []; $.each( self._options[ result.provider ], function( key, val ) { arr.push( key + '=' + val ); }); // small youtube specifics, perhaps move to _video later if ( result.provider == 'youtube' ) { arr = ['wmode=opaque'].concat(arr); } return str + arr.join('&'); } return ''; }()); // pre-fetch video providers media if( !current.thumb || !current.image ) { $.each( ['thumb', 'image'], function( i, type ) { if ( type == 'image' && !self._options.videoPoster ) { current.image = undef; return; } var video = new Video( result.provider, result.id ); if ( !current[ type ] ) { current.loading = true; video.getMedia( type, (function(current, type) { return function(src) { current[ type ] = src; if ( type == 'image' && !current.big ) { current.big = current.image; } delete current.loading; onload(); }; }( current, type ))); } }); } } } }); onload(); return this; }, /** Destroy the Galleria instance and recover the original content @example this.destroy(); @returns Instance */ destroy : function() { this.$( 'target' ).data( 'galleria', null ); this.$( 'container' ).off( 'galleria' ); this.get( 'target' ).innerHTML = this._original.html; this.clearTimer(); Utils.removeFromArray( _instances, this ); Utils.removeFromArray( _galleries, this ); if ( Galleria._waiters.length ) { $.each( Galleria._waiters, function( i, w ) { if ( w ) window.clearTimeout( w ); }); } return this; }, /** Adds and/or removes images from the gallery Works just like Array.splice https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/splice @example this.splice( 2, 4 ); // removes 4 images after the second image @returns Instance */ splice : function() { var self = this, args = Utils.array( arguments ); window.setTimeout(function() { protoArray.splice.apply( self._data, args ); self._parseData( function() { self._createThumbnails(); }); },2); return self; }, /** Append images to the gallery Works just like Array.push https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/push @example this.push({ image: 'image1.jpg' }); // appends the image to the gallery @returns Instance */ push : function() { var self = this, args = Utils.array( arguments ); if ( args.length == 1 && args[0].constructor == Array ) { args = args[0]; } window.setTimeout(function() { protoArray.push.apply( self._data, args ); self._parseData( function() { self._createThumbnails( args ); }); }, 2); return self; }, _getActive : function() { return this._controls.getActive(); }, validate : function( data ) { // todo: validate a custom data array return true; }, /** Bind any event to Galleria @param {string} type The Event type to listen for @param {Function} fn The function to execute when the event is triggered @example this.bind( 'image', function() { Galleria.log('image shown') }); @returns Instance */ bind : function(type, fn) { // allow 'image' instead of Galleria.IMAGE type = _patchEvent( type ); this.$( 'container' ).on( type, this.proxy(fn) ); return this; }, /** Unbind any event to Galleria @param {string} type The Event type to forget @returns Instance */ unbind : function(type) { type = _patchEvent( type ); this.$( 'container' ).off( type ); return this; }, /** Manually trigger a Galleria event @param {string} type The Event to trigger @returns Instance */ trigger : function( type ) { type = typeof type === 'object' ? $.extend( type, { scope: this } ) : { type: _patchEvent( type ), scope: this }; this.$( 'container' ).trigger( type ); return this; }, /** Assign an "idle state" to any element. The idle state will be applied after a certain amount of idle time Useful to hide f.ex navigation when the gallery is inactive @param {HTMLElement|string} elem The Dom node or selector to apply the idle state to @param {Object} styles the CSS styles to apply when in idle mode @param {Object} [from] the CSS styles to apply when in normal @param {Boolean} [hide] set to true if you want to hide it first @example addIdleState( this.get('image-nav'), { opacity: 0 }); @example addIdleState( '.galleria-image-nav', { top: -200 }, true); @returns Instance */ addIdleState: function( elem, styles, from, hide ) { this._idle.add.apply( this._idle, Utils.array( arguments ) ); return this; }, /** Removes any idle state previously set using addIdleState() @param {HTMLElement|string} elem The Dom node or selector to remove the idle state from. @returns Instance */ removeIdleState: function( elem ) { this._idle.remove.apply( this._idle, Utils.array( arguments ) ); return this; }, /** Force Galleria to enter idle mode. @returns Instance */ enterIdleMode: function() { this._idle.hide(); return this; }, /** Force Galleria to exit idle mode. @returns Instance */ exitIdleMode: function() { this._idle.showAll(); return this; }, /** Enter FullScreen mode @param {Function} callback the function to be executed when the fullscreen mode is fully applied. @returns Instance */ enterFullscreen: function( callback ) { this._fullscreen.enter.apply( this, Utils.array( arguments ) ); return this; }, /** Exits FullScreen mode @param {Function} callback the function to be executed when the fullscreen mode is fully applied. @returns Instance */ exitFullscreen: function( callback ) { this._fullscreen.exit.apply( this, Utils.array( arguments ) ); return this; }, /** Toggle FullScreen mode @param {Function} callback the function to be executed when the fullscreen mode is fully applied or removed. @returns Instance */ toggleFullscreen: function( callback ) { this._fullscreen[ this.isFullscreen() ? 'exit' : 'enter'].apply( this, Utils.array( arguments ) ); return this; }, /** Adds a tooltip to any element. You can also call this method with an object as argument with elemID:value pairs to apply tooltips to (see examples) @param {HTMLElement} elem The DOM Node to attach the event to @param {string|Function} value The tooltip message. Can also be a function that returns a string. @example this.bindTooltip( this.get('thumbnails'), 'My thumbnails'); @example this.bindTooltip( this.get('thumbnails'), function() { return 'My thumbs' }); @example this.bindTooltip( { image_nav: 'Navigation' }); @returns Instance */ bindTooltip: function( elem, value ) { this._tooltip.bind.apply( this._tooltip, Utils.array(arguments) ); return this; }, /** Note: this method is deprecated. Use refreshTooltip() instead. Redefine a tooltip. Use this if you want to re-apply a tooltip value to an already bound tooltip element. @param {HTMLElement} elem The DOM Node to attach the event to @param {string|Function} value The tooltip message. Can also be a function that returns a string. @returns Instance */ defineTooltip: function( elem, value ) { this._tooltip.define.apply( this._tooltip, Utils.array(arguments) ); return this; }, /** Refresh a tooltip value. Use this if you want to change the tooltip value at runtime, f.ex if you have a play/pause toggle. @param {HTMLElement} elem The DOM Node that has a tooltip that should be refreshed @returns Instance */ refreshTooltip: function( elem ) { this._tooltip.show.apply( this._tooltip, Utils.array(arguments) ); return this; }, /** Open a pre-designed lightbox with the currently active image. You can control some visuals using gallery options. @returns Instance */ openLightbox: function() { this._lightbox.show.apply( this._lightbox, Utils.array( arguments ) ); return this; }, /** Close the lightbox. @returns Instance */ closeLightbox: function() { this._lightbox.hide.apply( this._lightbox, Utils.array( arguments ) ); return this; }, /** Check if a variation exists @returns {Boolean} If the variation has been applied */ hasVariation: function( variation ) { return $.inArray( variation, this._options.variation.split(/\s+/) ) > -1; }, /** Get the currently active image element. @returns {HTMLElement} The image element */ getActiveImage: function() { var active = this._getActive(); return active ? active.image : undef; }, /** Get the currently active thumbnail element. @returns {HTMLElement} The thumbnail element */ getActiveThumb: function() { return this._thumbnails[ this._active ].image || undef; }, /** Get the mouse position relative to the gallery container @param e The mouse event @example var gallery = this; $(document).mousemove(function(e) { console.log( gallery.getMousePosition(e).x ); }); @returns {Object} Object with x & y of the relative mouse postion */ getMousePosition : function(e) { return { x: e.pageX - this.$( 'container' ).offset().left, y: e.pageY - this.$( 'container' ).offset().top }; }, /** Adds a panning effect to the image @param [img] The optional image element. If not specified it takes the currently active image @returns Instance */ addPan : function( img ) { if ( this._options.imageCrop === false ) { return; } img = $( img || this.getActiveImage() ); // define some variables and methods var self = this, x = img.width() / 2, y = img.height() / 2, destX = parseInt( img.css( 'left' ), 10 ), destY = parseInt( img.css( 'top' ), 10 ), curX = destX || 0, curY = destY || 0, distX = 0, distY = 0, active = false, ts = Utils.timestamp(), cache = 0, move = 0, // positions the image position = function( dist, cur, pos ) { if ( dist > 0 ) { move = M.round( M.max( dist * -1, M.min( 0, cur ) ) ); if ( cache !== move ) { cache = move; if ( IE === 8 ) { // scroll is faster for IE img.parent()[ 'scroll' + pos ]( move * -1 ); } else { var css = {}; css[ pos.toLowerCase() ] = move; img.css(css); } } } }, // calculates mouse position after 50ms calculate = function(e) { if (Utils.timestamp() - ts < 50) { return; } active = true; x = self.getMousePosition(e).x; y = self.getMousePosition(e).y; }, // the main loop to check loop = function(e) { if (!active) { return; } distX = img.width() - self._stageWidth; distY = img.height() - self._stageHeight; destX = x / self._stageWidth * distX * -1; destY = y / self._stageHeight * distY * -1; curX += ( destX - curX ) / self._options.imagePanSmoothness; curY += ( destY - curY ) / self._options.imagePanSmoothness; position( distY, curY, 'Top' ); position( distX, curX, 'Left' ); }; // we need to use scroll in IE8 to speed things up if ( IE === 8 ) { img.parent().scrollTop( curY * -1 ).scrollLeft( curX * -1 ); img.css({ top: 0, left: 0 }); } // unbind and bind event this.$( 'stage' ).off( 'mousemove', calculate ).on( 'mousemove', calculate ); // loop the loop this.addTimer( 'pan' + self._id, loop, 50, true); return this; }, /** Brings the scope into any callback @param fn The callback to bring the scope into @param [scope] Optional scope to bring @example $('#fullscreen').click( this.proxy(function() { this.enterFullscreen(); }) ) @returns {Function} Return the callback with the gallery scope */ proxy : function( fn, scope ) { if ( typeof fn !== 'function' ) { return F; } scope = scope || this; return function() { return fn.apply( scope, Utils.array( arguments ) ); }; }, /** Removes the panning effect set by addPan() @returns Instance */ removePan: function() { // todo: doublecheck IE8 this.$( 'stage' ).off( 'mousemove' ); this.clearTimer( 'pan' + this._id ); return this; }, /** Adds an element to the Galleria DOM array. When you add an element here, you can access it using element ID in many API calls @param {string} id The element ID you wish to use. You can add many elements by adding more arguments. @example addElement('mybutton'); @example addElement('mybutton','mylink'); @returns Instance */ addElement : function( id ) { var dom = this._dom; $.each( Utils.array(arguments), function( i, blueprint ) { dom[ blueprint ] = Utils.create( 'galleria-' + blueprint ); }); return this; }, /** Attach keyboard events to Galleria @param {Object} map The map object of events. Possible keys are 'UP', 'DOWN', 'LEFT', 'RIGHT', 'RETURN', 'ESCAPE', 'BACKSPACE', and 'SPACE'. @example this.attachKeyboard({ right: this.next, left: this.prev, up: function() { console.log( 'up key pressed' ) } }); @returns Instance */ attachKeyboard : function( map ) { this._keyboard.attach.apply( this._keyboard, Utils.array( arguments ) ); return this; }, /** Detach all keyboard events to Galleria @returns Instance */ detachKeyboard : function() { this._keyboard.detach.apply( this._keyboard, Utils.array( arguments ) ); return this; }, /** Fast helper for appending galleria elements that you added using addElement() @param {string} parentID The parent element ID where the element will be appended @param {string} childID the element ID that should be appended @example this.addElement('myElement'); this.appendChild( 'info', 'myElement' ); @returns Instance */ appendChild : function( parentID, childID ) { this.$( parentID ).append( this.get( childID ) || childID ); return this; }, /** Fast helper for prepending galleria elements that you added using addElement() @param {string} parentID The parent element ID where the element will be prepended @param {string} childID the element ID that should be prepended @example this.addElement('myElement'); this.prependChild( 'info', 'myElement' ); @returns Instance */ prependChild : function( parentID, childID ) { this.$( parentID ).prepend( this.get( childID ) || childID ); return this; }, /** Remove an element by blueprint @param {string} elemID The element to be removed. You can remove multiple elements by adding arguments. @returns Instance */ remove : function( elemID ) { this.$( Utils.array( arguments ).join(',') ).remove(); return this; }, // a fast helper for building dom structures // leave this out of the API for now append : function( data ) { var i, j; for( i in data ) { if ( data.hasOwnProperty( i ) ) { if ( data[i].constructor === Array ) { for( j = 0; data[i][j]; j++ ) { this.appendChild( i, data[i][j] ); } } else { this.appendChild( i, data[i] ); } } } return this; }, // an internal helper for scaling according to options _scaleImage : function( image, options ) { image = image || this._controls.getActive(); // janpub (JH) fix: // image might be unselected yet // e.g. when external logics rescales the gallery on window resize events if( !image ) { return; } var complete, scaleLayer = function( img ) { $( img.container ).children(':first').css({ top: M.max(0, Utils.parseValue( img.image.style.top )), left: M.max(0, Utils.parseValue( img.image.style.left )), width: Utils.parseValue( img.image.width ), height: Utils.parseValue( img.image.height ) }); }; options = $.extend({ width: this._stageWidth, height: this._stageHeight, crop: this._options.imageCrop, max: this._options.maxScaleRatio, min: this._options.minScaleRatio, margin: this._options.imageMargin, position: this._options.imagePosition, iframelimit: this._options.maxVideoSize }, options ); if ( this._options.layerFollow && this._options.imageCrop !== true ) { if ( typeof options.complete == 'function' ) { complete = options.complete; options.complete = function() { complete.call( image, image ); scaleLayer( image ); }; } else { options.complete = scaleLayer; } } else { $( image.container ).children(':first').css({ top: 0, left: 0 }); } image.scale( options ); return this; }, /** Updates the carousel, useful if you resize the gallery and want to re-check if the carousel nav is needed. @returns Instance */ updateCarousel : function() { this._carousel.update(); return this; }, /** Resize the entire gallery container @param {Object} [measures] Optional object with width/height specified @param {Function} [complete] The callback to be called when the scaling is complete @returns Instance */ resize : function( measures, complete ) { if ( typeof measures == 'function' ) { complete = measures; measures = undef; } measures = $.extend( { width:0, height:0 }, measures ); var self = this, $container = this.$( 'container' ); $.each( measures, function( m, val ) { if ( !val ) { $container[ m ]( 'auto' ); measures[ m ] = self._getWH()[ m ]; } }); $.each( measures, function( m, val ) { $container[ m ]( val ); }); return this.rescale( complete ); }, /** Rescales the gallery @param {number} width The target width @param {number} height The target height @param {Function} complete The callback to be called when the scaling is complete @returns Instance */ rescale : function( width, height, complete ) { var self = this; // allow rescale(fn) if ( typeof width === 'function' ) { complete = width; width = undef; } var scale = function() { // set stagewidth self._stageWidth = width || self.$( 'stage' ).width(); self._stageHeight = height || self.$( 'stage' ).height(); if ( self._options.swipe ) { $.each( self._controls.slides, function(i, img) { self._scaleImage( img ); $( img.container ).css('left', self._stageWidth * i); }); self.$('images').css('width', self._stageWidth * self.getDataLength()); } else { // scale the active image self._scaleImage(); } if ( self._options.carousel ) { self.updateCarousel(); } var frame = self._controls.frames[ self._controls.active ]; if (frame) { self._controls.frames[ self._controls.active ].scale({ width: self._stageWidth, height: self._stageHeight, iframelimit: self._options.maxVideoSize }); } self.trigger( Galleria.RESCALE ); if ( typeof complete === 'function' ) { complete.call( self ); } }; scale.call( self ); return this; }, /** Refreshes the gallery. Useful if you change image options at runtime and want to apply the changes to the active image. @returns Instance */ refreshImage : function() { this._scaleImage(); if ( this._options.imagePan ) { this.addPan(); } return this; }, _preload: function() { if ( this._options.preload ) { var p, i, n = this.getNext(), ndata; try { for ( i = this._options.preload; i > 0; i-- ) { p = new Galleria.Picture(); ndata = this.getData( n ); p.preload( this.isFullscreen() && ndata.big ? ndata.big : ndata.image ); n = this.getNext( n ); } } catch(e) {} } }, /** Shows an image by index @param {number|boolean} index The index to show @param {Boolean} rewind A boolean that should be true if you want the transition to go back @returns Instance */ show : function( index, rewind, _history ) { var swipe = this._options.swipe; // do nothing queue is long || index is false || queue is false and transition is in progress if ( !swipe && ( this._queue.length > 3 || index === false || ( !this._options.queue && this._queue.stalled ) ) ) { return; } index = M.max( 0, M.min( parseInt( index, 10 ), this.getDataLength() - 1 ) ); rewind = typeof rewind !== 'undefined' ? !!rewind : index < this.getIndex(); _history = _history || false; // do the history thing and return if ( !_history && Galleria.History ) { Galleria.History.set( index.toString() ); return; } if ( this.finger && index !== this._active ) { this.finger.to = -( index*this.finger.width ); this.finger.index = index; } this._active = index; // we do things a bit simpler in swipe: if ( swipe ) { var data = this.getData(index), self = this; if ( !data ) { return; } var src = this.isFullscreen() && data.big ? data.big : ( data.image || data.iframe ), image = this._controls.slides[index], cached = image.isCached( src ), thumb = this._thumbnails[ index ]; var evObj = { cached: cached, index: index, rewind: rewind, imageTarget: image.image, thumbTarget: thumb.image, galleriaData: data }; this.trigger($.extend(evObj, { type: Galleria.LOADSTART })); self.$('container').removeClass( 'videoplay' ); var complete = function() { self._layers[index].innerHTML = self.getData().layer || ''; self.trigger($.extend(evObj, { type: Galleria.LOADFINISH })); self._playCheck(); }; self._preload(); window.setTimeout(function() { // load if not ready if ( !image.ready || $(image.image).attr('src') != src ) { if ( data.iframe && !data.image ) { image.isIframe = true; } image.load(src, function(image) { self._scaleImage(image, complete).trigger($.extend(evObj, { type: Galleria.IMAGE })); complete(); }); } else { self.trigger($.extend(evObj, { type: Galleria.IMAGE })); complete(); } }, 100); } else { protoArray.push.call( this._queue, { index : index, rewind : rewind }); if ( !this._queue.stalled ) { this._show(); } } return this; }, // the internal _show method does the actual showing _show : function() { // shortcuts var self = this, queue = this._queue[ 0 ], data = this.getData( queue.index ); if ( !data ) { return; } var src = this.isFullscreen() && data.big ? data.big : ( data.image || data.iframe ), active = this._controls.getActive(), next = this._controls.getNext(), cached = next.isCached( src ), thumb = this._thumbnails[ queue.index ], mousetrigger = function() { $( next.image ).trigger( 'mouseup' ); }; self.$('container').toggleClass('iframe', !!data.isIframe).removeClass( 'videoplay' ); // to be fired when loading & transition is complete: var complete = (function( data, next, active, queue, thumb ) { return function() { var win; _transitions.active = false; // optimize quality Utils.toggleQuality( next.image, self._options.imageQuality ); // remove old layer self._layers[ self._controls.active ].innerHTML = ''; // swap $( active.container ).css({ zIndex: 0, opacity: 0 }).show(); $( active.container ).find( 'iframe, .galleria-videoicon' ).remove(); $( self._controls.frames[ self._controls.active ].container ).hide(); $( next.container ).css({ zIndex: 1, left: 0, top: 0 }).show(); self._controls.swap(); // add pan according to option if ( self._options.imagePan ) { self.addPan( next.image ); } // make the image clickable // order of precedence: iframe, link, lightbox, clicknext if ( ( data.iframe && data.image ) || data.link || self._options.lightbox || self._options.clicknext ) { $( next.image ).css({ cursor: 'pointer' }).on( 'mouseup', function( e ) { // non-left click if ( typeof e.which == 'number' && e.which > 1 ) { return; } // iframe / video if ( data.iframe ) { if ( self.isPlaying() ) { self.pause(); } var frame = self._controls.frames[ self._controls.active ], w = self._stageWidth, h = self._stageHeight; $( frame.container ).css({ width: w, height: h, opacity: 0 }).show().animate({ opacity: 1 }, 200); window.setTimeout(function() { frame.load( data.iframe + ( data.video ? '&autoplay=1' : '' ), { width: w, height: h }, function( frame ) { self.$( 'container' ).addClass( 'videoplay' ); frame.scale({ width: self._stageWidth, height: self._stageHeight, iframelimit: data.video ? self._options.maxVideoSize : undef }); }); }, 100); return; } // clicknext if ( self._options.clicknext && !Galleria.TOUCH ) { if ( self._options.pauseOnInteraction ) { self.pause(); } self.next(); return; } // popup link if ( data.link ) { if ( self._options.popupLinks ) { win = window.open( data.link, '_blank' ); } else { window.location.href = data.link; } return; } if ( self._options.lightbox ) { self.openLightbox(); } }); } // check if we are playing self._playCheck(); // trigger IMAGE event self.trigger({ type: Galleria.IMAGE, index: queue.index, imageTarget: next.image, thumbTarget: thumb.image, galleriaData: data }); // remove the queued image protoArray.shift.call( self._queue ); // remove stalled self._queue.stalled = false; // if we still have images in the queue, show it if ( self._queue.length ) { self._show(); } }; }( data, next, active, queue, thumb )); // let the carousel follow if ( this._options.carousel && this._options.carouselFollow ) { this._carousel.follow( queue.index ); } // preload images self._preload(); // show the next image, just in case Utils.show( next.container ); next.isIframe = data.iframe && !data.image; // add active classes $( self._thumbnails[ queue.index ].container ) .addClass( 'active' ) .siblings( '.active' ) .removeClass( 'active' ); // trigger the LOADSTART event self.trigger( { type: Galleria.LOADSTART, cached: cached, index: queue.index, rewind: queue.rewind, imageTarget: next.image, thumbTarget: thumb.image, galleriaData: data }); // stall the queue self._queue.stalled = true; // begin loading the next image next.load( src, function( next ) { // add layer HTML var layer = $( self._layers[ 1-self._controls.active ] ).html( data.layer || '' ).hide(); self._scaleImage( next, { complete: function( next ) { // toggle low quality for IE if ( 'image' in active ) { Utils.toggleQuality( active.image, false ); } Utils.toggleQuality( next.image, false ); // remove the image panning, if applied // TODO: rethink if this is necessary self.removePan(); // set the captions and counter self.setInfo( queue.index ); self.setCounter( queue.index ); // show the layer now if ( data.layer ) { layer.show(); // inherit click events set on image if ( ( data.iframe && data.image ) || data.link || self._options.lightbox || self._options.clicknext ) { layer.css( 'cursor', 'pointer' ).off( 'mouseup' ).mouseup( mousetrigger ); } } // add play icon if( data.video && data.image ) { _playIcon( next.container ); } var transition = self._options.transition; // can JavaScript loop through objects in order? yes. $.each({ initial: active.image === null, touch: Galleria.TOUCH, fullscreen: self.isFullscreen() }, function( type, arg ) { if ( arg && self._options[ type + 'Transition' ] !== undef ) { transition = self._options[ type + 'Transition' ]; return false; } }); // validate the transition if ( transition in _transitions.effects === false ) { complete(); } else { var params = { prev: active.container, next: next.container, rewind: queue.rewind, speed: self._options.transitionSpeed || 400 }; _transitions.active = true; // call the transition function and send some stuff _transitions.init.call( self, transition, params, complete ); } // trigger the LOADFINISH event self.trigger({ type: Galleria.LOADFINISH, cached: cached, index: queue.index, rewind: queue.rewind, imageTarget: next.image, thumbTarget: self._thumbnails[ queue.index ].image, galleriaData: self.getData( queue.index ) }); } }); }); }, /** Gets the next index @param {number} [base] Optional starting point @returns {number} the next index, or the first if you are at the first (looping) */ getNext : function( base ) { base = typeof base === 'number' ? base : this.getIndex(); return base === this.getDataLength() - 1 ? 0 : base + 1; }, /** Gets the previous index @param {number} [base] Optional starting point @returns {number} the previous index, or the last if you are at the first (looping) */ getPrev : function( base ) { base = typeof base === 'number' ? base : this.getIndex(); return base === 0 ? this.getDataLength() - 1 : base - 1; }, /** Shows the next image in line @returns Instance */ next : function() { if ( this.getDataLength() > 1 ) { this.show( this.getNext(), false ); } return this; }, /** Shows the previous image in line @returns Instance */ prev : function() { if ( this.getDataLength() > 1 ) { this.show( this.getPrev(), true ); } return this; }, /** Retrieve a DOM element by element ID @param {string} elemId The delement ID to fetch @returns {HTMLElement} The elements DOM node or null if not found. */ get : function( elemId ) { return elemId in this._dom ? this._dom[ elemId ] : null; }, /** Retrieve a data object @param {number} index The data index to retrieve. If no index specified it will take the currently active image @returns {Object} The data object */ getData : function( index ) { return index in this._data ? this._data[ index ] : this._data[ this._active ]; }, /** Retrieve the number of data items @returns {number} The data length */ getDataLength : function() { return this._data.length; }, /** Retrieve the currently active index @returns {number|boolean} The active index or false if none found */ getIndex : function() { return typeof this._active === 'number' ? this._active : false; }, /** Retrieve the stage height @returns {number} The stage height */ getStageHeight : function() { return this._stageHeight; }, /** Retrieve the stage width @returns {number} The stage width */ getStageWidth : function() { return this._stageWidth; }, /** Retrieve the option @param {string} key The option key to retrieve. If no key specified it will return all options in an object. @returns option or options */ getOptions : function( key ) { return typeof key === 'undefined' ? this._options : this._options[ key ]; }, /** Set options to the instance. You can set options using a key & value argument or a single object argument (see examples) @param {string} key The option key @param {string} value the the options value @example setOptions( 'autoplay', true ) @example setOptions({ autoplay: true }); @returns Instance */ setOptions : function( key, value ) { if ( typeof key === 'object' ) { $.extend( this._options, key ); } else { this._options[ key ] = value; } return this; }, /** Starts playing the slideshow @param {number} delay Sets the slideshow interval in milliseconds. If you set it once, you can just call play() and get the same interval the next time. @returns Instance */ play : function( delay ) { this._playing = true; this._playtime = delay || this._playtime; this._playCheck(); this.trigger( Galleria.PLAY ); return this; }, /** Stops the slideshow if currently playing @returns Instance */ pause : function() { this._playing = false; this.trigger( Galleria.PAUSE ); return this; }, /** Toggle between play and pause events. @param {number} delay Sets the slideshow interval in milliseconds. @returns Instance */ playToggle : function( delay ) { return ( this._playing ) ? this.pause() : this.play( delay ); }, /** Checks if the gallery is currently playing @returns {Boolean} */ isPlaying : function() { return this._playing; }, /** Checks if the gallery is currently in fullscreen mode @returns {Boolean} */ isFullscreen : function() { return this._fullscreen.active; }, _playCheck : function() { var self = this, played = 0, interval = 20, now = Utils.timestamp(), timer_id = 'play' + this._id; if ( this._playing ) { this.clearTimer( timer_id ); var fn = function() { played = Utils.timestamp() - now; if ( played >= self._playtime && self._playing ) { self.clearTimer( timer_id ); self.next(); return; } if ( self._playing ) { // trigger the PROGRESS event self.trigger({ type: Galleria.PROGRESS, percent: M.ceil( played / self._playtime * 100 ), seconds: M.floor( played / 1000 ), milliseconds: played }); self.addTimer( timer_id, fn, interval ); } }; self.addTimer( timer_id, fn, interval ); } }, /** Modify the slideshow delay @param {number} delay the number of milliseconds between slides, @returns Instance */ setPlaytime: function( delay ) { this._playtime = delay; return this; }, setIndex: function( val ) { this._active = val; return this; }, /** Manually modify the counter @param {number} [index] Optional data index to fectch, if no index found it assumes the currently active index @returns Instance */ setCounter: function( index ) { if ( typeof index === 'number' ) { index++; } else if ( typeof index === 'undefined' ) { index = this.getIndex()+1; } this.get( 'current' ).innerHTML = index; if ( IE ) { // weird IE bug var count = this.$( 'counter' ), opacity = count.css( 'opacity' ); if ( parseInt( opacity, 10 ) === 1) { Utils.removeAlpha( count[0] ); } else { this.$( 'counter' ).css( 'opacity', opacity ); } } return this; }, /** Manually set captions @param {number} [index] Optional data index to fectch and apply as caption, if no index found it assumes the currently active index @returns Instance */ setInfo : function( index ) { var self = this, data = this.getData( index ); $.each( ['title','description'], function( i, type ) { var elem = self.$( 'info-' + type ); if ( !!data[type] ) { elem[ data[ type ].length ? 'show' : 'hide' ]().html( data[ type ] ); } else { elem.empty().hide(); } }); return this; }, /** Checks if the data contains any captions @param {number} [index] Optional data index to fectch, if no index found it assumes the currently active index. @returns {boolean} */ hasInfo : function( index ) { var check = 'title description'.split(' '), i; for ( i = 0; check[i]; i++ ) { if ( !!this.getData( index )[ check[i] ] ) { return true; } } return false; }, jQuery : function( str ) { var self = this, ret = []; $.each( str.split(','), function( i, elemId ) { elemId = $.trim( elemId ); if ( self.get( elemId ) ) { ret.push( elemId ); } }); var jQ = $( self.get( ret.shift() ) ); $.each( ret, function( i, elemId ) { jQ = jQ.add( self.get( elemId ) ); }); return jQ; }, /** Converts element IDs into a jQuery collection You can call for multiple IDs separated with commas. @param {string} str One or more element IDs (comma-separated) @returns jQuery @example this.$('info,container').hide(); */ $ : function( str ) { return this.jQuery.apply( this, Utils.array( arguments ) ); } }; // End of Galleria prototype // Add events as static variables $.each( _events, function( i, ev ) { // legacy events var type = /_/.test( ev ) ? ev.replace( /_/g, '' ) : ev; Galleria[ ev.toUpperCase() ] = 'galleria.'+type; } ); $.extend( Galleria, { // Browser helpers IE9: IE === 9, IE8: IE === 8, IE7: IE === 7, IE6: IE === 6, IE: IE, WEBKIT: /webkit/.test( NAV ), CHROME: /chrome/.test( NAV ), SAFARI: /safari/.test( NAV ) && !(/chrome/.test( NAV )), QUIRK: ( IE && doc.compatMode && doc.compatMode === "BackCompat" ), MAC: /mac/.test( navigator.platform.toLowerCase() ), OPERA: !!window.opera, IPHONE: /iphone/.test( NAV ), IPAD: /ipad/.test( NAV ), ANDROID: /android/.test( NAV ), TOUCH: ('ontouchstart' in doc) }); // Galleria static methods /** Adds a theme that you can use for your Gallery @param {Object} theme Object that should contain all your theme settings. <ul> <li>name - name of the theme</li> <li>author - name of the author</li> <li>css - css file name (not path)</li> <li>defaults - default options to apply, including theme-specific options</li> <li>init - the init function</li> </ul> @returns {Object} theme */ Galleria.addTheme = function( theme ) { // make sure we have a name if ( !theme.name ) { Galleria.raise('No theme name specified'); } if ( typeof theme.defaults !== 'object' ) { theme.defaults = {}; } else { theme.defaults = _legacyOptions( theme.defaults ); } var css = false, reg; if ( typeof theme.css === 'string' ) { // look for manually added CSS $('link').each(function( i, link ) { reg = new RegExp( theme.css ); if ( reg.test( link.href ) ) { // we found the css css = true; // the themeload trigger _themeLoad( theme ); return false; } }); // else look for the absolute path and load the CSS dynamic if ( !css ) { $(function() { // Try to determine the css-path from the theme script. // In IE8/9, the script-dom-element seems to be not present // at once, if galleria itself is inserted into the dom // dynamically. We therefore try multiple times before raising // an error. var retryCount = 0; var tryLoadCss = function() { $('script').each(function (i, script) { // look for the theme script reg = new RegExp('galleria\\.' + theme.name.toLowerCase() + '\\.'); if (reg.test(script.src)) { // we have a match css = script.src.replace(/[^\/]*$/, '') + theme.css; window.setTimeout(function () { Utils.loadCSS(css, 'galleria-theme', function () { // the themeload trigger _themeLoad(theme); }); }, 1); } }); if (!css) { if (retryCount++ > 5) { Galleria.raise('No theme CSS loaded'); } else { window.setTimeout(tryLoadCss, 500); } } }; tryLoadCss(); }); } } else { // pass _themeLoad( theme ); } return theme; }; /** loadTheme loads a theme js file and attaches a load event to Galleria @param {string} src The relative path to the theme source file @param {Object} [options] Optional options you want to apply @returns Galleria */ Galleria.loadTheme = function( src, options ) { // Don't load if theme is already loaded if( $('script').filter(function() { return $(this).attr('src') == src; }).length ) { return; } var loaded = false, err; // start listening for the timeout onload $( window ).load( function() { if ( !loaded ) { // give it another 20 seconds err = window.setTimeout(function() { if ( !loaded && !Galleria.theme ) { Galleria.raise( "Galleria had problems loading theme at " + src + ". Please check theme path or load manually.", true ); } }, 20000); } }); // first clear the current theme, if exists Galleria.unloadTheme(); // load the theme Utils.loadScript( src, function() { loaded = true; window.clearTimeout( err ); }); return Galleria; }; /** unloadTheme unloads the Galleria theme and prepares for a new theme @returns Galleria */ Galleria.unloadTheme = function() { if ( typeof Galleria.theme == 'object' ) { $('script').each(function( i, script ) { if( new RegExp( 'galleria\\.' + Galleria.theme.name + '\\.' ).test( script.src ) ) { $( script ).remove(); } }); Galleria.theme = undef; } return Galleria; }; /** Retrieves a Galleria instance. @param {number} [index] Optional index to retrieve. If no index is supplied, the method will return all instances in an array. @returns Instance or Array of instances */ Galleria.get = function( index ) { if ( !!_instances[ index ] ) { return _instances[ index ]; } else if ( typeof index !== 'number' ) { return _instances; } else { Galleria.raise('Gallery index ' + index + ' not found'); } }; /** Configure Galleria options via a static function. The options will be applied to all instances @param {string|object} key The options to apply or a key @param [value] If key is a string, this is the value @returns Galleria */ Galleria.configure = function( key, value ) { var opts = {}; if( typeof key == 'string' && value ) { opts[key] = value; key = opts; } else { $.extend( opts, key ); } Galleria.configure.options = opts; $.each( Galleria.get(), function(i, instance) { instance.setOptions( opts ); }); return Galleria; }; Galleria.configure.options = {}; /** Bind a Galleria event to the gallery @param {string} type A string representing the galleria event @param {function} callback The function that should run when the event is triggered @returns Galleria */ Galleria.on = function( type, callback ) { if ( !type ) { return; } callback = callback || F; // hash the bind var hash = type + callback.toString().replace(/\s/g,'') + Utils.timestamp(); // for existing instances $.each( Galleria.get(), function(i, instance) { instance._binds.push( hash ); instance.bind( type, callback ); }); // for future instances Galleria.on.binds.push({ type: type, callback: callback, hash: hash }); return Galleria; }; Galleria.on.binds = []; /** Run Galleria Alias for $(selector).galleria(options) @param {string} selector A selector of element(s) to intialize galleria to @param {object} options The options to apply @returns Galleria */ Galleria.run = function( selector, options ) { if ( $.isFunction( options ) ) { options = { extend: options }; } $( selector || '#galleria' ).galleria( options ); return Galleria; }; /** Creates a transition to be used in your gallery @param {string} name The name of the transition that you will use as an option @param {Function} fn The function to be executed in the transition. The function contains two arguments, params and complete. Use the params Object to integrate the transition, and then call complete when you are done. @returns Galleria */ Galleria.addTransition = function( name, fn ) { _transitions.effects[name] = fn; return Galleria; }; /** The Galleria utilites */ Galleria.utils = Utils; /** A helper metod for cross-browser logging. It uses the console log if available otherwise it falls back to alert @example Galleria.log("hello", document.body, [1,2,3]); */ Galleria.log = function() { var args = Utils.array( arguments ); if( 'console' in window && 'log' in window.console ) { try { return window.console.log.apply( window.console, args ); } catch( e ) { $.each( args, function() { window.console.log(this); }); } } else { return window.alert( args.join('<br>') ); } }; /** A ready method for adding callbacks when a gallery is ready Each method is call before the extend option for every instance @param {function} callback The function to call @returns Galleria */ Galleria.ready = function( fn ) { if ( typeof fn != 'function' ) { return Galleria; } $.each( _galleries, function( i, gallery ) { fn.call( gallery, gallery._options ); }); Galleria.ready.callbacks.push( fn ); return Galleria; }; Galleria.ready.callbacks = []; /** Method for raising errors @param {string} msg The message to throw @param {boolean} [fatal] Set this to true to override debug settings and display a fatal error */ Galleria.raise = function( msg, fatal ) { var type = fatal ? 'Fatal error' : 'Error', css = { color: '#fff', position: 'absolute', top: 0, left: 0, zIndex: 100000 }, echo = function( msg ) { var html = '<div style="padding:4px;margin:0 0 2px;background:#' + ( fatal ? '811' : '222' ) + ';">' + ( fatal ? '<strong>' + type + ': </strong>' : '' ) + msg + '</div>'; $.each( _instances, function() { var cont = this.$( 'errors' ), target = this.$( 'target' ); if ( !cont.length ) { target.css( 'position', 'relative' ); cont = this.addElement( 'errors' ).appendChild( 'target', 'errors' ).$( 'errors' ).css(css); } cont.append( html ); }); if ( !_instances.length ) { $('<div>').css( $.extend( css, { position: 'fixed' } ) ).append( html ).appendTo( DOM().body ); } }; // if debug is on, display errors and throw exception if fatal if ( DEBUG ) { echo( msg ); if ( fatal ) { throw new Error(type + ': ' + msg); } // else just echo a silent generic error if fatal } else if ( fatal ) { if ( _hasError ) { return; } _hasError = true; fatal = false; echo( 'Gallery could not load.' ); } }; // Add the version Galleria.version = VERSION; /** A method for checking what version of Galleria the user has installed and throws a readable error if the user needs to upgrade. Useful when building plugins that requires a certain version to function. @param {number} version The minimum version required @param {string} [msg] Optional message to display. If not specified, Galleria will throw a generic error. @returns Galleria */ Galleria.requires = function( version, msg ) { msg = msg || 'You need to upgrade Galleria to version ' + version + ' to use one or more components.'; if ( Galleria.version < version ) { Galleria.raise(msg, true); } return Galleria; }; /** Adds preload, cache, scale and crop functionality @constructor @requires jQuery @param {number} [id] Optional id to keep track of instances */ Galleria.Picture = function( id ) { // save the id this.id = id || null; // the image should be null until loaded this.image = null; // Create a new container this.container = Utils.create('galleria-image'); // add container styles $( this.container ).css({ overflow: 'hidden', position: 'relative' // for IE Standards mode }); // saves the original measurements this.original = { width: 0, height: 0 }; // flag when the image is ready this.ready = false; // flag for iframe Picture this.isIframe = false; }; Galleria.Picture.prototype = { // the inherited cache object cache: {}, // show the image on stage show: function() { Utils.show( this.image ); }, // hide the image hide: function() { Utils.moveOut( this.image ); }, clear: function() { this.image = null; }, /** Checks if an image is in cache @param {string} src The image source path, ex '/path/to/img.jpg' @returns {boolean} */ isCached: function( src ) { return !!this.cache[src]; }, /** Preloads an image into the cache @param {string} src The image source path, ex '/path/to/img.jpg' @returns Galleria.Picture */ preload: function( src ) { $( new Image() ).load((function(src, cache) { return function() { cache[ src ] = src; }; }( src, this.cache ))).attr( 'src', src ); }, /** Loads an image and call the callback when ready. Will also add the image to cache. @param {string} src The image source path, ex '/path/to/img.jpg' @param {Object} [size] The forced size of the image, defined as an object { width: xx, height:xx } @param {Function} callback The function to be executed when the image is loaded & scaled @returns The image container (jQuery object) */ load: function(src, size, callback) { if ( typeof size == 'function' ) { callback = size; size = null; } if( this.isIframe ) { var id = 'if'+new Date().getTime(); var iframe = this.image = $('<iframe>', { src: src, frameborder: 0, id: id, allowfullscreen: true, css: { visibility: 'hidden' } })[0]; if ( size ) { $( iframe ).css( size ); } $( this.container ).find( 'iframe,img' ).remove(); this.container.appendChild( this.image ); $('#'+id).load( (function( self, callback ) { return function() { window.setTimeout(function() { $( self.image ).css( 'visibility', 'visible' ); if( typeof callback == 'function' ) { callback.call( self, self ); } }, 10); }; }( this, callback ))); return this.container; } this.image = new Image(); // IE8 opacity inherit bug if ( Galleria.IE8 ) { $( this.image ).css( 'filter', 'inherit' ); } var reload = false, resort = false, // some jquery cache $container = $( this.container ), $image = $( this.image ), onerror = function() { if ( !reload ) { reload = true; // reload the image with a timestamp window.setTimeout((function(image, src) { return function() { image.attr('src', src + (src.indexOf('?') > -1 ? '&' : '?') + Utils.timestamp() ); }; }( $(this), src )), 50); } else { // apply the dummy image if it exists if ( DUMMY ) { $( this ).attr( 'src', DUMMY ); } else { Galleria.raise('Image not found: ' + src); } } }, // the onload method onload = (function( self, callback, src ) { return function() { var complete = function() { $( this ).off( 'load' ); // save the original size self.original = size || { height: this.height, width: this.width }; // translate3d if needed if ( Galleria.HAS3D ) { this.style.MozTransform = this.style.webkitTransform = 'translate3d(0,0,0)'; } $container.append( this ); self.cache[ src ] = src; // will override old cache if (typeof callback == 'function' ) { window.setTimeout(function() { callback.call( self, self ); },1); } }; // Delay the callback to "fix" the Adblock Bug // http://code.google.com/p/adblockforchrome/issues/detail?id=3701 if ( ( !this.width || !this.height ) ) { (function( img ) { Utils.wait({ until: function() { return img.width && img.height; }, success: function() { complete.call( img ); }, error: function() { if ( !resort ) { $(new Image()).load( onload ).attr( 'src', img.src ); resort = true; } else { Galleria.raise('Could not extract width/height from image: ' + img.src + '. Traced measures: width:' + img.width + 'px, height: ' + img.height + 'px.'); } }, timeout: 100 }); }( this )); } else { complete.call( this ); } }; }( this, callback, src )); // remove any previous images $container.find( 'iframe,img' ).remove(); // append the image $image.css( 'display', 'block'); // hide it for now Utils.hide( this.image ); // remove any max/min scaling $.each('minWidth minHeight maxWidth maxHeight'.split(' '), function(i, prop) { $image.css(prop, (/min/.test(prop) ? '0' : 'none')); }); // begin load and insert in cache when done $image.load( onload ).on( 'error', onerror ).attr( 'src', src ); // return the container return this.container; }, /** Scales and crops the image @param {Object} options The method takes an object with a number of options: <ul> <li>width - width of the container</li> <li>height - height of the container</li> <li>min - minimum scale ratio</li> <li>max - maximum scale ratio</li> <li>margin - distance in pixels from the image border to the container</li> <li>complete - a callback that fires when scaling is complete</li> <li>position - positions the image, works like the css background-image property.</li> <li>crop - defines how to crop. Can be true, false, 'width' or 'height'</li> <li>canvas - set to true to try a canvas-based rescale</li> </ul> @returns The image container object (jQuery) */ scale: function( options ) { var self = this; // extend some defaults options = $.extend({ width: 0, height: 0, min: undef, max: undef, margin: 0, complete: F, position: 'center', crop: false, canvas: false, iframelimit: undef }, options); if( this.isIframe ) { var cw = options.width, ch = options.height, nw, nh; if ( options.iframelimit ) { var r = M.min( options.iframelimit/cw, options.iframelimit/ch ); if ( r < 1 ) { nw = cw * r; nh = ch * r; $( this.image ).css({ top: ch/2-nh/2, left: cw/2-nw/2, position: 'absolute' }); } else { $( this.image ).css({ top: 0, left: 0 }); } } $( this.image ).width( nw || cw ).height( nh || ch ).removeAttr( 'width' ).removeAttr( 'height' ); $( this.container ).width( cw ).height( ch ); options.complete.call(self, self); try { if( this.image.contentWindow ) { $( this.image.contentWindow ).trigger('resize'); } } catch(e) {} return this.container; } // return the element if no image found if (!this.image) { return this.container; } // store locale variables var width, height, $container = $( self.container ), data; // wait for the width/height Utils.wait({ until: function() { width = options.width || $container.width() || Utils.parseValue( $container.css('width') ); height = options.height || $container.height() || Utils.parseValue( $container.css('height') ); return width && height; }, success: function() { // calculate some cropping var newWidth = ( width - options.margin * 2 ) / self.original.width, newHeight = ( height - options.margin * 2 ) / self.original.height, min = M.min( newWidth, newHeight ), max = M.max( newWidth, newHeight ), cropMap = { 'true' : max, 'width' : newWidth, 'height': newHeight, 'false' : min, 'landscape': self.original.width > self.original.height ? max : min, 'portrait': self.original.width < self.original.height ? max : min }, ratio = cropMap[ options.crop.toString() ], canvasKey = ''; // allow maxScaleRatio if ( options.max ) { ratio = M.min( options.max, ratio ); } // allow minScaleRatio if ( options.min ) { ratio = M.max( options.min, ratio ); } $.each( ['width','height'], function( i, m ) { $( self.image )[ m ]( self[ m ] = self.image[ m ] = M.round( self.original[ m ] * ratio ) ); }); $( self.container ).width( width ).height( height ); if ( options.canvas && _canvas ) { _canvas.elem.width = self.width; _canvas.elem.height = self.height; canvasKey = self.image.src + ':' + self.width + 'x' + self.height; self.image.src = _canvas.cache[ canvasKey ] || (function( key ) { _canvas.context.drawImage(self.image, 0, 0, self.original.width*ratio, self.original.height*ratio); try { data = _canvas.elem.toDataURL(); _canvas.length += data.length; _canvas.cache[ key ] = data; return data; } catch( e ) { return self.image.src; } }( canvasKey ) ); } // calculate image_position var pos = {}, mix = {}, getPosition = function(value, measure, margin) { var result = 0; if (/\%/.test(value)) { var flt = parseInt( value, 10 ) / 100, m = self.image[ measure ] || $( self.image )[ measure ](); result = M.ceil( m * -1 * flt + margin * flt ); } else { result = Utils.parseValue( value ); } return result; }, positionMap = { 'top': { top: 0 }, 'left': { left: 0 }, 'right': { left: '100%' }, 'bottom': { top: '100%' } }; $.each( options.position.toLowerCase().split(' '), function( i, value ) { if ( value === 'center' ) { value = '50%'; } pos[i ? 'top' : 'left'] = value; }); $.each( pos, function( i, value ) { if ( positionMap.hasOwnProperty( value ) ) { $.extend( mix, positionMap[ value ] ); } }); pos = pos.top ? $.extend( pos, mix ) : mix; pos = $.extend({ top: '50%', left: '50%' }, pos); // apply position $( self.image ).css({ position : 'absolute', top : getPosition(pos.top, 'height', height), left : getPosition(pos.left, 'width', width) }); // show the image self.show(); // flag ready and call the callback self.ready = true; options.complete.call( self, self ); }, error: function() { Galleria.raise('Could not scale image: '+self.image.src); }, timeout: 1000 }); return this; } }; // our own easings $.extend( $.easing, { galleria: function (_, t, b, c, d) { if ((t/=d/2) < 1) { return c/2*t*t*t + b; } return c/2*((t-=2)*t*t + 2) + b; }, galleriaIn: function (_, t, b, c, d) { return c*(t/=d)*t + b; }, galleriaOut: function (_, t, b, c, d) { return -c *(t/=d)*(t-2) + b; } }); // Forked version of Ainos Finger.js for native-style touch Galleria.Finger = (function() { var abs = M.abs; // test for translate3d support var has3d = Galleria.HAS3D = (function() { var el = doc.createElement('p'), has3d, t = ['webkit','O','ms','Moz',''], s, i=0, a = 'transform'; DOM().html.insertBefore(el, null); for (; t[i]; i++) { s = t[i] ? t[i]+'Transform' : a; if (el.style[s] !== undefined) { el.style[s] = "translate3d(1px,1px,1px)"; has3d = $(el).css(t[i] ? '-'+t[i].toLowerCase()+'-'+a : a); } } DOM().html.removeChild(el); return (has3d !== undefined && has3d.length > 0 && has3d !== "none"); }()); // request animation shim var requestFrame = (function(){ var r = 'RequestAnimationFrame'; return window.requestAnimationFrame || window['webkit'+r] || window['moz'+r] || window['o'+r] || window['ms'+r] || function( callback ) { window.setTimeout(callback, 1000 / 60); }; }()); var Finger = function(elem, options) { // default options this.config = { start: 0, duration: 500, onchange: function() {}, oncomplete: function() {}, easing: function(x,t,b,c,d) { return -c * ((t=t/d-1)*t*t*t - 1) + b; // easeOutQuart } }; this.easeout = function (x, t, b, c, d) { return c*((t=t/d-1)*t*t*t*t + 1) + b; }; if ( !elem.children.length ) { return; } var self = this; // extend options $.extend(this.config, options); this.elem = elem; this.child = elem.children[0]; this.to = this.pos = 0; this.touching = false; this.start = {}; this.index = this.config.start; this.anim = 0; this.easing = this.config.easing; if ( !has3d ) { this.child.style.position = 'absolute'; this.elem.style.position = 'relative'; } // Bind event handlers to context $.each(['ontouchstart','ontouchmove','ontouchend','setup'], function(i, fn) { self[fn] = (function(caller) { return function() { caller.apply( self, arguments ); }; }(self[fn])); }); // the physical animator this.setX = function() { var style = self.child.style; if (!has3d) { // this is actually faster than CSS3 translate style.left = self.pos+'px'; return; } style.MozTransform = style.webkitTransform = 'translate3d(' + self.pos + 'px,0,0)'; return; }; // bind events $(elem).on('touchstart', this.ontouchstart); $(window).on('resize', this.setup); $(window).on('orientationchange', this.setup); // set up width this.setup(); // start the animations (function animloop(){ requestFrame(animloop); self.loop.call( self ); }()); }; Finger.prototype = { constructor: Finger, setup: function() { this.width = $( this.elem ).width(); this.length = M.ceil( $(this.child).width() / this.width ); if ( this.index !== 0 ) { this.index = M.max(0, M.min( this.index, this.length-1 ) ); this.pos = this.to = -this.width*this.index; } }, setPosition: function(pos) { this.pos = pos; this.to = pos; }, ontouchstart: function(e) { var touch = e.originalEvent.touches; this.start = { pageX: touch[0].pageX, pageY: touch[0].pageY, time: +new Date() }; this.isScrolling = null; this.touching = true; this.deltaX = 0; $doc.on('touchmove', this.ontouchmove); $doc.on('touchend', this.ontouchend); }, ontouchmove: function(e) { var touch = e.originalEvent.touches; // ensure swiping with one touch and not pinching if( touch && touch.length > 1 || e.scale && e.scale !== 1 ) { return; } this.deltaX = touch[0].pageX - this.start.pageX; // determine if scrolling test has run - one time test if ( this.isScrolling === null ) { this.isScrolling = !!( this.isScrolling || M.abs(this.deltaX) < M.abs(touch[0].pageY - this.start.pageY) ); } // if user is not trying to scroll vertically if (!this.isScrolling) { // prevent native scrolling e.preventDefault(); // increase resistance if first or last slide this.deltaX /= ( (!this.index && this.deltaX > 0 || this.index == this.length - 1 && this.deltaX < 0 ) ? ( M.abs(this.deltaX) / this.width + 1.8 ) : 1 ); this.to = this.deltaX - this.index * this.width; } e.stopPropagation(); }, ontouchend: function(e) { this.touching = false; // determine if slide attempt triggers next/prev slide var isValidSlide = +new Date() - this.start.time < 250 && M.abs(this.deltaX) > 40 || M.abs(this.deltaX) > this.width/2, isPastBounds = !this.index && this.deltaX > 0 || this.index == this.length - 1 && this.deltaX < 0; // if not scrolling vertically if ( !this.isScrolling ) { this.show( this.index + ( isValidSlide && !isPastBounds ? (this.deltaX < 0 ? 1 : -1) : 0 ) ); } $doc.off('touchmove', this.ontouchmove); $doc.off('touchend', this.ontouchend); }, show: function( index ) { if ( index != this.index ) { this.config.onchange.call(this, index); } else { this.to = -( index*this.width ); } }, moveTo: function( index ) { if ( index != this.index ) { this.pos = this.to = -( index*this.width ); this.index = index; } }, loop: function() { var distance = this.to - this.pos, factor = 1; if ( this.width && distance ) { factor = M.max(0.5, M.min(1.5, M.abs(distance / this.width) ) ); } // if distance is short or the user is touching, do a 1-1 animation if ( this.touching || M.abs(distance) <= 1 ) { this.pos = this.to; distance = 0; if ( this.anim && !this.touching ) { this.config.oncomplete( this.index ); } this.anim = 0; this.easing = this.config.easing; } else { if ( !this.anim ) { // save animation parameters this.anim = { start: this.pos, time: +new Date(), distance: distance, factor: factor, destination: this.to }; } // check if to has changed or time has run out var elapsed = +new Date() - this.anim.time; var duration = this.config.duration*this.anim.factor; if ( elapsed > duration || this.anim.destination != this.to ) { this.anim = 0; this.easing = this.easeout; return; } // apply easing this.pos = this.easing( null, elapsed, this.anim.start, this.anim.distance, duration ); } this.setX(); } }; return Finger; }()); // the plugin initializer $.fn.galleria = function( options ) { var selector = this.selector; // try domReady if element not found if ( !$(this).length ) { $(function() { if ( $( selector ).length ) { // if found on domReady, go ahead $( selector ).galleria( options ); } else { // if not, try fetching the element for 5 secs, then raise a warning. Galleria.utils.wait({ until: function() { return $( selector ).length; }, success: function() { $( selector ).galleria( options ); }, error: function() { Galleria.raise('Init failed: Galleria could not find the element "'+selector+'".'); }, timeout: 5000 }); } }); return this; } return this.each(function() { // destroy previous instance and prepare for new load if ( $.data(this, 'galleria') ) { $.data( this, 'galleria' ).destroy(); $( this ).find( '*' ).hide(); } // load the new gallery $.data( this, 'galleria', new Galleria().init( this, options ) ); }); }; // export as AMD or CommonJS if ( typeof module === "object" && module && typeof module.exports === "object" ) { module.exports = Galleria; } else { window.Galleria = Galleria; if ( typeof define === "function" && define.amd ) { define( "galleria", ['jquery'], function() { return Galleria; } ); } } // phew }( jQuery, this ) );
alexmojaki/jsdelivr
files/galleria/1.3.5/galleria.js
JavaScript
mit
213,535
/* * /MathJax/jax/output/HTML-CSS/fonts/STIX/General/Bold/NumberForms.js * * Copyright (c) 2009-2017 The MathJax Consortium * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ MathJax.Hub.Insert(MathJax.OutputJax["HTML-CSS"].FONTDATA.FONTS["STIXGeneral-bold"],{8531:[688,12,750,-7,763],8532:[688,12,750,28,763],8533:[688,12,750,-7,775],8534:[688,12,750,28,775],8535:[688,12,750,23,775],8536:[688,12,750,22,775],8537:[688,12,750,-7,758],8538:[688,12,750,49,758],8539:[688,12,750,-7,775],8540:[688,12,750,23,775],8541:[688,12,750,49,775],8542:[688,12,750,30,775]});MathJax.Ajax.loadComplete(MathJax.OutputJax["HTML-CSS"].fontDir+"/General/Bold/NumberForms.js");
ahocevar/cdnjs
ajax/libs/mathjax/2.7.2-beta.1/jax/output/HTML-CSS/fonts/STIX/General/Bold/NumberForms.js
JavaScript
mit
1,185
/* * /MathJax/jax/output/HTML-CSS/fonts/STIX-Web/Operators/Regular/Main.js * * Copyright (c) 2009-2017 The MathJax Consortium * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ MathJax.OutputJax["HTML-CSS"].FONTDATA.FONTS.STIXMathJax_Operators={directory:"Operators/Regular",family:"STIXMathJax_Operators",testString:"\u00A0\u2206\u220A\u220C\u220E\u220F\u2210\u2211\u221B\u221C\u221F\u222C\u222D\u222E\u222F",32:[0,0,250,0,0],160:[0,0,250,0,0],8710:[674,0,731,63,665],8714:[459,-45,486,64,422],8716:[662,157,685,60,625],8718:[640,0,545,60,485],8719:[763,259,1000,52,948],8720:[763,259,1000,52,948],8721:[763,259,914,58,856],8731:[973,259,928,112,963],8732:[973,259,928,112,963],8735:[584,0,685,50,634],8748:[824,320,701,32,881],8749:[824,320,943,32,1123],8750:[824,320,499,32,639],8751:[824,320,741,32,881],8752:[824,320,982,32,1122],8753:[824,320,499,32,639],8754:[824,320,499,32,639],8755:[824,320,499,32,639],8758:[521,13,511,192,319],8759:[521,13,685,82,602],8760:[511,-220,685,48,637],8761:[511,5,685,48,637],8762:[511,5,685,48,637],8763:[521,13,685,48,637],8766:[413,-90,685,48,637],8767:[467,-39,685,49,637],8772:[519,35,685,48,637],8775:[647,202,685,48,637],8777:[549,49,685,48,637],8779:[532,26,685,48,638],8780:[532,27,685,48,637],8788:[417,-89,824,48,776],8789:[417,-89,824,48,776],8792:[729,-120,685,48,637],8793:[853,-120,685,48,637],8794:[853,-120,685,48,637],8795:[756,-120,685,48,637],8797:[823,-120,685,7,678],8798:[703,-120,685,48,637],8799:[863,-120,685,48,637],8802:[662,156,685,48,637],8803:[544,38,685,48,637],8813:[572,66,685,48,637],8820:[731,228,685,48,637],8821:[730,229,685,48,637],8824:[750,250,685,48,637],8825:[750,250,685,48,637],8836:[662,156,685,65,623],8837:[662,156,685,65,623],8844:[536,31,620,48,572],8845:[536,31,620,48,572],8860:[623,119,842,50,792],8870:[662,0,497,64,433],8871:[662,0,498,64,434],8875:[662,0,860,57,814],8880:[551,45,685,64,621],8881:[551,45,685,64,621],8886:[403,-103,1145,50,1095],8887:[403,-103,1145,50,1095],8889:[547,41,685,48,636],8893:[646,29,620,32,590],8894:[584,0,685,50,634],8895:[662,158,911,45,865],8896:[763,259,924,54,870],8897:[763,259,924,54,870],8898:[778,254,924,94,830],8899:[768,264,924,94,830],8903:[545,38,685,51,634],8917:[690,189,685,48,637],8924:[607,103,685,64,621],8925:[607,103,685,64,621],8930:[730,229,685,65,622],8931:[730,229,685,65,622],8932:[627,216,685,64,621],8933:[627,216,685,64,621],8944:[520,18,926,194,732],8946:[531,27,823,55,763],8947:[531,27,685,60,625],8948:[459,-45,486,62,420],8949:[716,27,685,60,625],8950:[685,27,685,60,625],8951:[613,-45,486,62,420],8952:[532,180,685,60,625],8953:[531,27,685,61,625],8954:[531,27,823,55,763],8955:[531,27,685,59,624],8956:[459,-45,486,62,420],8957:[685,27,685,61,626],8958:[613,-45,486,67,425],8959:[662,158,910,45,865],10752:[763,259,1126,53,1073],10753:[763,259,1126,53,1073],10754:[763,259,1126,53,1073],10755:[768,264,924,94,830],10756:[768,264,924,94,830],10757:[763,259,924,94,830],10758:[763,259,924,94,830],10759:[763,259,1180,83,1097],10760:[763,259,1180,83,1097],10761:[763,259,1021,50,971],10762:[763,259,914,58,856],10763:[824,320,690,33,659],10764:[824,320,1184,32,1364],10765:[824,320,499,32,639],10766:[824,320,499,32,639],10767:[824,320,499,32,639],10768:[824,320,499,32,639],10769:[824,320,499,32,639],10770:[824,320,519,32,639],10771:[824,320,499,32,639],10772:[824,320,628,32,688],10773:[824,320,499,32,639],10774:[824,320,529,32,639],10775:[824,320,738,32,818],10776:[824,320,539,32,639],10777:[824,320,559,32,639],10778:[824,320,559,32,639],10779:[947,320,459,32,639],10780:[824,443,459,32,639],10781:[770,252,1270,93,1177],10782:[764,258,1018,45,924],10783:[566,291,503,110,410],10784:[633,127,1177,98,1079],10785:[805,300,547,215,472],10786:[819,41,685,48,636],10787:[707,41,685,48,636],10788:[704,41,685,48,636],10789:[547,235,685,48,636],10790:[547,198,685,48,636],10791:[547,210,685,41,673],10792:[547,41,685,48,636],10793:[556,-220,685,48,637],10794:[286,5,685,48,637],10795:[511,5,685,48,637],10796:[511,5,685,48,637],10797:[623,119,724,50,674],10798:[623,119,724,50,674],10799:[447,-59,490,50,439],10800:[686,25,640,43,597],10801:[529,130,640,43,597],10802:[529,45,640,43,597],10803:[538,32,685,57,627],10804:[623,119,674,50,624],10805:[623,119,674,50,624],10806:[810,119,842,50,792],10807:[752,248,1100,50,1050],10808:[623,119,842,50,792],10809:[811,127,1145,35,1110],10810:[811,127,1145,35,1110],10811:[811,127,1145,35,1110],10812:[393,-115,600,48,552],10813:[393,-115,600,48,552],10814:[488,170,300,60,230],10816:[536,31,620,48,572],10817:[536,31,620,48,572],10818:[668,31,620,48,572],10819:[668,31,620,48,572],10820:[536,31,620,48,572],10821:[536,31,620,48,572],10822:[914,406,620,48,572],10823:[914,406,620,48,572],10824:[914,406,620,48,572],10825:[914,406,620,48,572],10826:[528,39,1078,48,1030],10827:[527,40,1078,48,1030],10828:[602,31,620,10,610],10829:[536,97,620,10,610],10830:[536,31,620,48,572],10831:[536,31,620,48,572],10832:[602,31,620,10,610],10833:[710,29,620,31,589],10834:[710,29,620,31,589],10835:[536,29,620,31,589],10836:[536,29,620,31,589],10837:[536,29,780,32,748],10838:[536,29,780,32,748],10839:[536,29,706,106,683],10840:[536,29,706,23,600],10841:[585,77,620,31,589],10842:[536,29,620,31,589],10843:[536,29,620,31,589],10844:[536,29,620,31,589],10845:[536,29,620,31,589],10847:[536,139,620,30,590],10848:[536,289,620,30,590],10849:[479,0,620,45,575],10850:[806,29,620,30,590],10851:[536,289,620,30,590],10852:[791,284,1043,70,1008],10853:[791,284,1043,70,1008],10854:[386,105,685,48,637],10855:[703,-28,685,48,637],10856:[695,189,685,48,637],10857:[662,156,685,48,637],10858:[521,-148,685,48,637],10859:[521,13,685,48,637],10860:[543,38,685,48,637],10861:[703,27,685,48,637],10862:[847,-120,685,48,637],10863:[707,-25,685,48,637],10864:[650,146,685,48,637],10865:[648,141,685,48,637],10866:[648,141,685,48,637],10867:[532,27,685,48,637],10868:[417,-89,1015,48,967],10869:[386,-120,997,48,949],10870:[386,-120,1436,48,1388],10871:[611,106,685,48,637],10872:[703,-28,685,38,647],10873:[532,26,685,44,609],10874:[532,26,685,76,641],10875:[806,26,685,44,609],10876:[806,26,685,76,641],10879:[625,137,685,60,625],10880:[625,137,685,60,625],10881:[625,137,685,60,625],10882:[625,137,685,60,625],10883:[777,137,685,60,625],10884:[777,137,685,60,625],10893:[746,176,685,48,637],10894:[746,176,685,48,637],10895:[867,361,685,60,649],10896:[867,361,685,60,649],10897:[844,338,685,55,630],10898:[844,338,685,55,630],10899:[866,361,685,60,625],10900:[866,361,685,60,625],10903:[640,122,685,56,621],10904:[640,122,685,56,621],10905:[718,211,685,60,625],10906:[718,211,685,60,625],10907:[726,220,685,60,625],10908:[726,220,685,60,625],10909:[664,164,685,53,642],10910:[664,164,685,43,632],10911:[774,267,685,48,637],10912:[774,267,685,48,637],10913:[532,26,685,44,609],10914:[532,26,685,76,641],10915:[609,103,933,25,908],10916:[532,26,782,60,722],10917:[532,26,855,60,795],10918:[532,26,685,35,625],10919:[532,26,685,60,650],10920:[625,137,685,50,640],10921:[626,137,685,45,635],10922:[537,31,685,45,609],10923:[537,31,685,76,640],10924:[613,103,685,60,625],10925:[613,103,685,60,625],10926:[563,-28,685,48,637],10929:[628,216,685,60,625],10930:[628,216,685,60,625],10931:[717,211,685,60,625],10932:[717,211,685,60,625],10939:[532,26,933,25,908],10940:[532,26,933,25,908],10941:[532,26,685,60,625],10942:[532,26,685,60,625],10943:[607,103,685,60,625],10944:[607,103,685,60,625],10945:[607,103,685,60,625],10946:[607,103,685,60,625],10947:[709,103,685,60,625],10948:[709,103,685,60,625],10951:[665,164,685,60,625],10952:[665,164,685,60,625],10953:[746,274,685,60,625],10954:[746,274,685,60,625],10957:[558,53,1352,64,1288],10958:[558,53,1352,64,1288],10959:[532,26,685,50,615],10960:[532,26,685,70,635],10961:[609,103,685,60,626],10962:[609,103,685,60,625],10963:[715,209,685,60,625],10964:[715,209,685,60,625],10965:[715,209,685,60,625],10966:[715,209,685,60,625],10967:[532,26,1250,60,1190],10968:[532,26,1250,60,1190],10969:[536,31,620,48,572],10970:[697,128,620,48,572],10971:[695,97,620,48,572],10972:[557,10,620,11,572],10973:[557,10,620,48,572],10974:[662,0,497,64,433],10975:[371,0,685,48,637],10976:[371,0,685,48,637],10977:[662,0,685,48,637],10978:[662,0,685,60,625],10979:[662,0,860,46,803],10980:[662,0,685,60,625],10981:[662,0,860,46,803],10982:[662,0,685,57,626],10983:[571,0,685,48,637],10984:[571,0,685,48,637],10985:[691,185,685,48,637],10986:[662,0,685,48,637],10987:[662,0,685,48,637],10988:[489,-18,600,48,552],10989:[489,-18,600,48,552],10990:[690,189,404,23,381],10991:[660,154,502,101,401],10992:[660,154,502,101,401],10993:[693,187,502,101,401],10994:[695,189,523,10,513],10995:[695,189,685,48,637],10996:[695,189,685,131,555],10997:[695,189,685,12,674],10998:[608,102,685,279,406],10999:[661,155,1170,58,1080],11000:[661,155,1170,90,1112],11001:[726,220,685,60,625],11002:[726,220,685,60,625],11003:[710,222,894,46,848],11004:[763,259,654,94,560],11005:[710,222,709,46,663],11006:[690,189,410,100,310],11007:[763,259,478,94,384],57348:[450,-59,926,55,871],57349:[530,-57,926,55,871],57354:[538,-55,685,48,637],57355:[543,37,685,48,637],57358:[846,340,685,60,626],57359:[730,229,685,56,621],57360:[730,229,685,56,621],57361:[846,340,685,61,626],57366:[818,311,685,53,618],57368:[818,311,685,67,632],57374:[607,110,685,48,638],57379:[695,189,685,48,637],57381:[724,236,685,48,637],57382:[662,156,685,47,612],57383:[662,156,685,73,638],57384:[663,155,933,25,908],57385:[662,156,933,25,908],57386:[662,156,1240,43,1184],57387:[662,156,1240,56,1197],57397:[602,98,486,64,422],57399:[662,156,685,48,637],57400:[690,189,732,50,682],57401:[662,156,685,47,636],57402:[811,156,471,40,525],57403:[736,156,685,60,625],57404:[662,156,685,60,625],57405:[602,98,486,64,422],57408:[415,-92,685,48,637],57411:[818,311,685,60,625],57412:[818,311,685,60,625],57413:[818,311,685,60,625],57414:[818,311,685,60,625],57419:[745,242,685,60,625],57420:[845,341,685,60,625],57421:[534,19,685,48,637],57422:[845,341,685,60,625],57423:[745,242,685,60,625],57424:[662,156,685,65,620],57425:[662,156,685,65,620],57426:[561,55,685,48,637],57433:[730,224,685,48,637],57434:[730,224,685,48,637],57435:[561,-30,685,48,637],57436:[534,19,685,48,637],57451:[602,98,486,64,422],57452:[602,98,486,64,422],57453:[785,157,685,60,625],57454:[785,157,685,60,625],57455:[785,129,685,60,625],57456:[785,129,685,60,625],57461:[626,119,685,48,637],57462:[626,119,685,48,637],57463:[725,236,685,48,637],57468:[758,252,685,48,637],57469:[758,252,685,48,637],57470:[732,227,685,56,621],57471:[732,227,685,56,621],57472:[818,311,685,57,622],57473:[818,311,685,57,622],57474:[730,229,685,56,621],57475:[730,229,685,56,621],57476:[709,201,685,56,621],57477:[709,201,685,56,621],57478:[818,311,685,56,621],57479:[818,311,685,55,621],57480:[818,311,685,56,621],57481:[818,311,685,55,620],57490:[719,296,685,62,627],57491:[719,296,685,61,626],57492:[719,240,685,62,627],57493:[719,240,685,61,626],57494:[818,311,685,55,620],57495:[818,311,685,65,630],57496:[690,189,685,23,662],57531:[622,101,685,48,637],57580:[862,-120,685,48,637],57609:[781,279,327,10,286],57610:[781,279,250,41,178],57676:[660,158,857,48,777],57677:[660,158,857,80,809],57678:[661,157,685,44,609],57679:[661,157,685,76,641],57998:[622,101,685,48,637],58002:[662,0,1388,38,1350],58003:[763,260,1797,58,1739],58306:[662,156,685,48,637],58307:[627,135,685,48,637],58308:[627,135,685,48,637]};MathJax.Callback.Queue(["initFont",MathJax.OutputJax["HTML-CSS"],"STIXMathJax_Operators"],["loadComplete",MathJax.Ajax,MathJax.OutputJax["HTML-CSS"].fontDir+"/Operators/Regular/Main.js"]);
froala/cdnjs
ajax/libs/mathjax/2.7.2-beta.0/jax/output/HTML-CSS/fonts/STIX-Web/Operators/Regular/Main.js
JavaScript
mit
12,031
<?php /* * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * This software consists of voluntary contributions made by many individuals * and is licensed under the MIT license. For more information, see * <http://www.doctrine-project.org>. */ namespace Doctrine\ORM\Query\AST; /** * Join ::= ["LEFT" ["OUTER"] | "INNER"] "JOIN" JoinAssociationPathExpression * ["AS"] AliasIdentificationVariable [("ON" | "WITH") ConditionalExpression] * * @link www.doctrine-project.org * @since 2.0 * @author Guilherme Blanco <guilhermeblanco@hotmail.com> * @author Jonathan Wage <jonwage@gmail.com> * @author Roman Borschel <roman@code-factory.org> */ class Join extends Node { const JOIN_TYPE_LEFT = 1; const JOIN_TYPE_LEFTOUTER = 2; const JOIN_TYPE_INNER = 3; public $joinType = self::JOIN_TYPE_INNER; public $joinAssociationDeclaration = null; public $conditionalExpression = null; public function __construct($joinType, $joinAssociationDeclaration) { $this->joinType = $joinType; $this->joinAssociationDeclaration = $joinAssociationDeclaration; } public function dispatch($sqlWalker) { return $sqlWalker->walkJoin($this); } }
GeromePaquant/ingesupecom
vendor/doctrine/orm/lib/Doctrine/ORM/Query/AST/Join.php
PHP
mit
1,972
<?php /* * This file is part of the Symfony package. * * (c) Fabien Potencier <fabien@symfony.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\Validator\Constraints; use Symfony\Component\Validator\Constraint; /** * @Annotation * @Target({"PROPERTY", "METHOD", "ANNOTATION"}) * * @author Antonio J. García Lagar <aj@garcialagar.es> * @author Bernhard Schussek <bschussek@gmail.com> */ class Issn extends Constraint { const TOO_SHORT_ERROR = 1; const TOO_LONG_ERROR = 2; const MISSING_HYPHEN_ERROR = 3; const INVALID_CHARACTERS_ERROR = 4; const INVALID_CASE_ERROR = 5; const CHECKSUM_FAILED_ERROR = 6; protected static $errorNames = array( self::TOO_SHORT_ERROR => 'TOO_SHORT_ERROR', self::TOO_LONG_ERROR => 'TOO_LONG_ERROR', self::MISSING_HYPHEN_ERROR => 'MISSING_HYPHEN_ERROR', self::INVALID_CHARACTERS_ERROR => 'INVALID_CHARACTERS_ERROR', self::INVALID_CASE_ERROR => 'INVALID_CASE_ERROR', self::CHECKSUM_FAILED_ERROR => 'CHECKSUM_FAILED_ERROR', ); public $message = 'This value is not a valid ISSN.'; public $caseSensitive = false; public $requireHyphen = false; }
aschempp/symfony
src/Symfony/Component/Validator/Constraints/Issn.php
PHP
mit
1,293
/** * @license * Lo-Dash 2.4.1 (Custom Build) <http://lodash.com/> * Build: `lodash underscore exports="amd,commonjs,global,node" -o ./dist/lodash.underscore.js` * Copyright 2012-2013 The Dojo Foundation <http://dojofoundation.org/> * Based on Underscore.js 1.5.2 <http://underscorejs.org/LICENSE> * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors * Available under MIT license <http://lodash.com/license> */ ;(function() { /** Used as a safe reference for `undefined` in pre ES5 environments */ var undefined; /** Used to generate unique IDs */ var idCounter = 0; /** Used internally to indicate various things */ var indicatorObject = {}; /** Used to prefix keys to avoid issues with `__proto__` and properties on `Object.prototype` */ var keyPrefix = +new Date + ''; /** Used to match "interpolate" template delimiters */ var reInterpolate = /<%=([\s\S]+?)%>/g; /** Used to ensure capturing order of template delimiters */ var reNoMatch = /($^)/; /** Used to match unescaped characters in compiled string literals */ var reUnescapedString = /['\n\r\t\u2028\u2029\\]/g; /** `Object#toString` result shortcuts */ var argsClass = '[object Arguments]', arrayClass = '[object Array]', boolClass = '[object Boolean]', dateClass = '[object Date]', funcClass = '[object Function]', numberClass = '[object Number]', objectClass = '[object Object]', regexpClass = '[object RegExp]', stringClass = '[object String]'; /** Used to determine if values are of the language type Object */ var objectTypes = { 'boolean': false, 'function': true, 'object': true, 'number': false, 'string': false, 'undefined': false }; /** Used to escape characters for inclusion in compiled string literals */ var stringEscapes = { '\\': '\\', "'": "'", '\n': 'n', '\r': 'r', '\t': 't', '\u2028': 'u2028', '\u2029': 'u2029' }; /** Used as a reference to the global object */ var root = (objectTypes[typeof window] && window) || this; /** Detect free variable `exports` */ var freeExports = objectTypes[typeof exports] && exports && !exports.nodeType && exports; /** Detect free variable `module` */ var freeModule = objectTypes[typeof module] && module && !module.nodeType && module; /** Detect the popular CommonJS extension `module.exports` */ var moduleExports = freeModule && freeModule.exports === freeExports && freeExports; /** Detect free variable `global` from Node.js or Browserified code and use it as `root` */ var freeGlobal = objectTypes[typeof global] && global; if (freeGlobal && (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal)) { root = freeGlobal; } /*--------------------------------------------------------------------------*/ /** * The base implementation of `_.indexOf` without support for binary searches * or `fromIndex` constraints. * * @private * @param {Array} array The array to search. * @param {*} value The value to search for. * @param {number} [fromIndex=0] The index to search from. * @returns {number} Returns the index of the matched value or `-1`. */ function baseIndexOf(array, value, fromIndex) { var index = (fromIndex || 0) - 1, length = array ? array.length : 0; while (++index < length) { if (array[index] === value) { return index; } } return -1; } /** * Used by `sortBy` to compare transformed `collection` elements, stable sorting * them in ascending order. * * @private * @param {Object} a The object to compare to `b`. * @param {Object} b The object to compare to `a`. * @returns {number} Returns the sort order indicator of `1` or `-1`. */ function compareAscending(a, b) { var ac = a.criteria, bc = b.criteria, index = -1, length = ac.length; while (++index < length) { var value = ac[index], other = bc[index]; if (value !== other) { if (value > other || typeof value == 'undefined') { return 1; } if (value < other || typeof other == 'undefined') { return -1; } } } // Fixes an `Array#sort` bug in the JS engine embedded in Adobe applications // that causes it, under certain circumstances, to return the same value for // `a` and `b`. See https://github.com/jashkenas/underscore/pull/1247 // // This also ensures a stable sort in V8 and other engines. // See http://code.google.com/p/v8/issues/detail?id=90 return a.index - b.index; } /** * Used by `template` to escape characters for inclusion in compiled * string literals. * * @private * @param {string} match The matched character to escape. * @returns {string} Returns the escaped character. */ function escapeStringChar(match) { return '\\' + stringEscapes[match]; } /** * Slices the `collection` from the `start` index up to, but not including, * the `end` index. * * Note: This function is used instead of `Array#slice` to support node lists * in IE < 9 and to ensure dense arrays are returned. * * @private * @param {Array|Object|string} collection The collection to slice. * @param {number} start The start index. * @param {number} end The end index. * @returns {Array} Returns the new array. */ function slice(array, start, end) { start || (start = 0); if (typeof end == 'undefined') { end = array ? array.length : 0; } var index = -1, length = end - start || 0, result = Array(length < 0 ? 0 : length); while (++index < length) { result[index] = array[start + index]; } return result; } /*--------------------------------------------------------------------------*/ /** * Used for `Array` method references. * * Normally `Array.prototype` would suffice, however, using an array literal * avoids issues in Narwhal. */ var arrayRef = []; /** Used for native method references */ var objectProto = Object.prototype; /** Used to restore the original `_` reference in `noConflict` */ var oldDash = root._; /** Used to resolve the internal [[Class]] of values */ var toString = objectProto.toString; /** Used to detect if a method is native */ var reNative = RegExp('^' + String(toString) .replace(/[.*+?^${}()|[\]\\]/g, '\\$&') .replace(/toString| for [^\]]+/g, '.*?') + '$' ); /** Native method shortcuts */ var ceil = Math.ceil, floor = Math.floor, hasOwnProperty = objectProto.hasOwnProperty, push = arrayRef.push, propertyIsEnumerable = objectProto.propertyIsEnumerable; /* Native method shortcuts for methods with the same name as other `lodash` methods */ var nativeCreate = isNative(nativeCreate = Object.create) && nativeCreate, nativeIsArray = isNative(nativeIsArray = Array.isArray) && nativeIsArray, nativeIsFinite = root.isFinite, nativeIsNaN = root.isNaN, nativeKeys = isNative(nativeKeys = Object.keys) && nativeKeys, nativeMax = Math.max, nativeMin = Math.min, nativeRandom = Math.random; /*--------------------------------------------------------------------------*/ /** * Creates a `lodash` object which wraps the given value to enable intuitive * method chaining. * * In addition to Lo-Dash methods, wrappers also have the following `Array` methods: * `concat`, `join`, `pop`, `push`, `reverse`, `shift`, `slice`, `sort`, `splice`, * and `unshift` * * Chaining is supported in custom builds as long as the `value` method is * implicitly or explicitly included in the build. * * The chainable wrapper functions are: * `after`, `assign`, `bind`, `bindAll`, `bindKey`, `chain`, `compact`, * `compose`, `concat`, `countBy`, `create`, `createCallback`, `curry`, * `debounce`, `defaults`, `defer`, `delay`, `difference`, `filter`, `flatten`, * `forEach`, `forEachRight`, `forIn`, `forInRight`, `forOwn`, `forOwnRight`, * `functions`, `groupBy`, `indexBy`, `initial`, `intersection`, `invert`, * `invoke`, `keys`, `map`, `max`, `memoize`, `merge`, `min`, `object`, `omit`, * `once`, `pairs`, `partial`, `partialRight`, `pick`, `pluck`, `pull`, `push`, * `range`, `reject`, `remove`, `rest`, `reverse`, `shuffle`, `slice`, `sort`, * `sortBy`, `splice`, `tap`, `throttle`, `times`, `toArray`, `transform`, * `union`, `uniq`, `unshift`, `unzip`, `values`, `where`, `without`, `wrap`, * and `zip` * * The non-chainable wrapper functions are: * `clone`, `cloneDeep`, `contains`, `escape`, `every`, `find`, `findIndex`, * `findKey`, `findLast`, `findLastIndex`, `findLastKey`, `has`, `identity`, * `indexOf`, `isArguments`, `isArray`, `isBoolean`, `isDate`, `isElement`, * `isEmpty`, `isEqual`, `isFinite`, `isFunction`, `isNaN`, `isNull`, `isNumber`, * `isObject`, `isPlainObject`, `isRegExp`, `isString`, `isUndefined`, `join`, * `lastIndexOf`, `mixin`, `noConflict`, `parseInt`, `pop`, `random`, `reduce`, * `reduceRight`, `result`, `shift`, `size`, `some`, `sortedIndex`, `runInContext`, * `template`, `unescape`, `uniqueId`, and `value` * * The wrapper functions `first` and `last` return wrapped values when `n` is * provided, otherwise they return unwrapped values. * * Explicit chaining can be enabled by using the `_.chain` method. * * @name _ * @constructor * @category Chaining * @param {*} value The value to wrap in a `lodash` instance. * @returns {Object} Returns a `lodash` instance. * @example * * var wrapped = _([1, 2, 3]); * * // returns an unwrapped value * wrapped.reduce(function(sum, num) { * return sum + num; * }); * // => 6 * * // returns a wrapped value * var squares = wrapped.map(function(num) { * return num * num; * }); * * _.isArray(squares); * // => false * * _.isArray(squares.value()); * // => true */ function lodash(value) { return (value instanceof lodash) ? value : new lodashWrapper(value); } /** * A fast path for creating `lodash` wrapper objects. * * @private * @param {*} value The value to wrap in a `lodash` instance. * @param {boolean} chainAll A flag to enable chaining for all methods * @returns {Object} Returns a `lodash` instance. */ function lodashWrapper(value, chainAll) { this.__chain__ = !!chainAll; this.__wrapped__ = value; } // ensure `new lodashWrapper` is an instance of `lodash` lodashWrapper.prototype = lodash.prototype; /** * An object used to flag environments features. * * @static * @memberOf _ * @type Object */ var support = {}; (function() { var object = { '0': 1, 'length': 1 }; /** * Detect if `Array#shift` and `Array#splice` augment array-like objects correctly. * * Firefox < 10, IE compatibility mode, and IE < 9 have buggy Array `shift()` * and `splice()` functions that fail to remove the last element, `value[0]`, * of array-like objects even though the `length` property is set to `0`. * The `shift()` method is buggy in IE 8 compatibility mode, while `splice()` * is buggy regardless of mode in IE < 9 and buggy in compatibility mode in IE 9. * * @memberOf _.support * @type boolean */ support.spliceObjects = (arrayRef.splice.call(object, 0, 1), !object[0]); }(1)); /** * By default, the template delimiters used by Lo-Dash are similar to those in * embedded Ruby (ERB). Change the following template settings to use alternative * delimiters. * * @static * @memberOf _ * @type Object */ lodash.templateSettings = { /** * Used to detect `data` property values to be HTML-escaped. * * @memberOf _.templateSettings * @type RegExp */ 'escape': /<%-([\s\S]+?)%>/g, /** * Used to detect code to be evaluated. * * @memberOf _.templateSettings * @type RegExp */ 'evaluate': /<%([\s\S]+?)%>/g, /** * Used to detect `data` property values to inject. * * @memberOf _.templateSettings * @type RegExp */ 'interpolate': reInterpolate, /** * Used to reference the data object in the template text. * * @memberOf _.templateSettings * @type string */ 'variable': '' }; /*--------------------------------------------------------------------------*/ /** * The base implementation of `_.bind` that creates the bound function and * sets its meta data. * * @private * @param {Array} bindData The bind data array. * @returns {Function} Returns the new bound function. */ function baseBind(bindData) { var func = bindData[0], partialArgs = bindData[2], thisArg = bindData[4]; function bound() { // `Function#bind` spec // http://es5.github.io/#x15.3.4.5 if (partialArgs) { // avoid `arguments` object deoptimizations by using `slice` instead // of `Array.prototype.slice.call` and not assigning `arguments` to a // variable as a ternary expression var args = slice(partialArgs); push.apply(args, arguments); } // mimic the constructor's `return` behavior // http://es5.github.io/#x13.2.2 if (this instanceof bound) { // ensure `new bound` is an instance of `func` var thisBinding = baseCreate(func.prototype), result = func.apply(thisBinding, args || arguments); return isObject(result) ? result : thisBinding; } return func.apply(thisArg, args || arguments); } return bound; } /** * The base implementation of `_.create` without support for assigning * properties to the created object. * * @private * @param {Object} prototype The object to inherit from. * @returns {Object} Returns the new object. */ function baseCreate(prototype, properties) { return isObject(prototype) ? nativeCreate(prototype) : {}; } // fallback for browsers without `Object.create` if (!nativeCreate) { baseCreate = (function() { function Object() {} return function(prototype) { if (isObject(prototype)) { Object.prototype = prototype; var result = new Object; Object.prototype = null; } return result || root.Object(); }; }()); } /** * The base implementation of `_.createCallback` without support for creating * "_.pluck" or "_.where" style callbacks. * * @private * @param {*} [func=identity] The value to convert to a callback. * @param {*} [thisArg] The `this` binding of the created callback. * @param {number} [argCount] The number of arguments the callback accepts. * @returns {Function} Returns a callback function. */ function baseCreateCallback(func, thisArg, argCount) { if (typeof func != 'function') { return identity; } // exit early for no `thisArg` or already bound by `Function#bind` if (typeof thisArg == 'undefined' || !('prototype' in func)) { return func; } switch (argCount) { case 1: return function(value) { return func.call(thisArg, value); }; case 2: return function(a, b) { return func.call(thisArg, a, b); }; case 3: return function(value, index, collection) { return func.call(thisArg, value, index, collection); }; case 4: return function(accumulator, value, index, collection) { return func.call(thisArg, accumulator, value, index, collection); }; } return bind(func, thisArg); } /** * The base implementation of `createWrapper` that creates the wrapper and * sets its meta data. * * @private * @param {Array} bindData The bind data array. * @returns {Function} Returns the new function. */ function baseCreateWrapper(bindData) { var func = bindData[0], bitmask = bindData[1], partialArgs = bindData[2], partialRightArgs = bindData[3], thisArg = bindData[4], arity = bindData[5]; var isBind = bitmask & 1, isBindKey = bitmask & 2, isCurry = bitmask & 4, isCurryBound = bitmask & 8, key = func; function bound() { var thisBinding = isBind ? thisArg : this; if (partialArgs) { var args = slice(partialArgs); push.apply(args, arguments); } if (partialRightArgs || isCurry) { args || (args = slice(arguments)); if (partialRightArgs) { push.apply(args, partialRightArgs); } if (isCurry && args.length < arity) { bitmask |= 16 & ~32; return baseCreateWrapper([func, (isCurryBound ? bitmask : bitmask & ~3), args, null, thisArg, arity]); } } args || (args = arguments); if (isBindKey) { func = thisBinding[key]; } if (this instanceof bound) { thisBinding = baseCreate(func.prototype); var result = func.apply(thisBinding, args); return isObject(result) ? result : thisBinding; } return func.apply(thisBinding, args); } return bound; } /** * The base implementation of `_.difference` that accepts a single array * of values to exclude. * * @private * @param {Array} array The array to process. * @param {Array} [values] The array of values to exclude. * @returns {Array} Returns a new array of filtered values. */ function baseDifference(array, values) { var index = -1, indexOf = getIndexOf(), length = array ? array.length : 0, result = []; while (++index < length) { var value = array[index]; if (indexOf(values, value) < 0) { result.push(value); } } return result; } /** * The base implementation of `_.flatten` without support for callback * shorthands or `thisArg` binding. * * @private * @param {Array} array The array to flatten. * @param {boolean} [isShallow=false] A flag to restrict flattening to a single level. * @param {boolean} [isStrict=false] A flag to restrict flattening to arrays and `arguments` objects. * @param {number} [fromIndex=0] The index to start from. * @returns {Array} Returns a new flattened array. */ function baseFlatten(array, isShallow, isStrict, fromIndex) { var index = (fromIndex || 0) - 1, length = array ? array.length : 0, result = []; while (++index < length) { var value = array[index]; if (value && typeof value == 'object' && typeof value.length == 'number' && (isArray(value) || isArguments(value))) { // recursively flatten arrays (susceptible to call stack limits) if (!isShallow) { value = baseFlatten(value, isShallow, isStrict); } var valIndex = -1, valLength = value.length, resIndex = result.length; result.length += valLength; while (++valIndex < valLength) { result[resIndex++] = value[valIndex]; } } else if (!isStrict) { result.push(value); } } return result; } /** * The base implementation of `_.isEqual`, without support for `thisArg` binding, * that allows partial "_.where" style comparisons. * * @private * @param {*} a The value to compare. * @param {*} b The other value to compare. * @param {Function} [callback] The function to customize comparing values. * @param {Function} [isWhere=false] A flag to indicate performing partial comparisons. * @param {Array} [stackA=[]] Tracks traversed `a` objects. * @param {Array} [stackB=[]] Tracks traversed `b` objects. * @returns {boolean} Returns `true` if the values are equivalent, else `false`. */ function baseIsEqual(a, b, stackA, stackB) { if (a === b) { return a !== 0 || (1 / a == 1 / b); } var type = typeof a, otherType = typeof b; if (a === a && !(a && objectTypes[type]) && !(b && objectTypes[otherType])) { return false; } if (a == null || b == null) { return a === b; } var className = toString.call(a), otherClass = toString.call(b); if (className != otherClass) { return false; } switch (className) { case boolClass: case dateClass: return +a == +b; case numberClass: return a != +a ? b != +b : (a == 0 ? (1 / a == 1 / b) : a == +b); case regexpClass: case stringClass: return a == String(b); } var isArr = className == arrayClass; if (!isArr) { var aWrapped = a instanceof lodash, bWrapped = b instanceof lodash; if (aWrapped || bWrapped) { return baseIsEqual(aWrapped ? a.__wrapped__ : a, bWrapped ? b.__wrapped__ : b, stackA, stackB); } if (className != objectClass) { return false; } var ctorA = a.constructor, ctorB = b.constructor; if (ctorA != ctorB && !(isFunction(ctorA) && ctorA instanceof ctorA && isFunction(ctorB) && ctorB instanceof ctorB) && ('constructor' in a && 'constructor' in b) ) { return false; } } stackA || (stackA = []); stackB || (stackB = []); var length = stackA.length; while (length--) { if (stackA[length] == a) { return stackB[length] == b; } } var result = true, size = 0; stackA.push(a); stackB.push(b); if (isArr) { size = b.length; result = size == a.length; if (result) { while (size--) { if (!(result = baseIsEqual(a[size], b[size], stackA, stackB))) { break; } } } } else { forIn(b, function(value, key, b) { if (hasOwnProperty.call(b, key)) { size++; return !(result = hasOwnProperty.call(a, key) && baseIsEqual(a[key], value, stackA, stackB)) && indicatorObject; } }); if (result) { forIn(a, function(value, key, a) { if (hasOwnProperty.call(a, key)) { return !(result = --size > -1) && indicatorObject; } }); } } stackA.pop(); stackB.pop(); return result; } /** * The base implementation of `_.random` without argument juggling or support * for returning floating-point numbers. * * @private * @param {number} min The minimum possible value. * @param {number} max The maximum possible value. * @returns {number} Returns a random number. */ function baseRandom(min, max) { return min + floor(nativeRandom() * (max - min + 1)); } /** * The base implementation of `_.uniq` without support for callback shorthands * or `thisArg` binding. * * @private * @param {Array} array The array to process. * @param {boolean} [isSorted=false] A flag to indicate that `array` is sorted. * @param {Function} [callback] The function called per iteration. * @returns {Array} Returns a duplicate-value-free array. */ function baseUniq(array, isSorted, callback) { var index = -1, indexOf = getIndexOf(), length = array ? array.length : 0, result = [], seen = callback ? [] : result; while (++index < length) { var value = array[index], computed = callback ? callback(value, index, array) : value; if (isSorted ? !index || seen[seen.length - 1] !== computed : indexOf(seen, computed) < 0 ) { if (callback) { seen.push(computed); } result.push(value); } } return result; } /** * Creates a function that aggregates a collection, creating an object composed * of keys generated from the results of running each element of the collection * through a callback. The given `setter` function sets the keys and values * of the composed object. * * @private * @param {Function} setter The setter function. * @returns {Function} Returns the new aggregator function. */ function createAggregator(setter) { return function(collection, callback, thisArg) { var result = {}; callback = createCallback(callback, thisArg, 3); var index = -1, length = collection ? collection.length : 0; if (typeof length == 'number') { while (++index < length) { var value = collection[index]; setter(result, value, callback(value, index, collection), collection); } } else { forOwn(collection, function(value, key, collection) { setter(result, value, callback(value, key, collection), collection); }); } return result; }; } /** * Creates a function that, when called, either curries or invokes `func` * with an optional `this` binding and partially applied arguments. * * @private * @param {Function|string} func The function or method name to reference. * @param {number} bitmask The bitmask of method flags to compose. * The bitmask may be composed of the following flags: * 1 - `_.bind` * 2 - `_.bindKey` * 4 - `_.curry` * 8 - `_.curry` (bound) * 16 - `_.partial` * 32 - `_.partialRight` * @param {Array} [partialArgs] An array of arguments to prepend to those * provided to the new function. * @param {Array} [partialRightArgs] An array of arguments to append to those * provided to the new function. * @param {*} [thisArg] The `this` binding of `func`. * @param {number} [arity] The arity of `func`. * @returns {Function} Returns the new function. */ function createWrapper(func, bitmask, partialArgs, partialRightArgs, thisArg, arity) { var isBind = bitmask & 1, isBindKey = bitmask & 2, isCurry = bitmask & 4, isCurryBound = bitmask & 8, isPartial = bitmask & 16, isPartialRight = bitmask & 32; if (!isBindKey && !isFunction(func)) { throw new TypeError; } if (isPartial && !partialArgs.length) { bitmask &= ~16; isPartial = partialArgs = false; } if (isPartialRight && !partialRightArgs.length) { bitmask &= ~32; isPartialRight = partialRightArgs = false; } // fast path for `_.bind` var creater = (bitmask == 1 || bitmask === 17) ? baseBind : baseCreateWrapper; return creater([func, bitmask, partialArgs, partialRightArgs, thisArg, arity]); } /** * Used by `escape` to convert characters to HTML entities. * * @private * @param {string} match The matched character to escape. * @returns {string} Returns the escaped character. */ function escapeHtmlChar(match) { return htmlEscapes[match]; } /** * Gets the appropriate "indexOf" function. If the `_.indexOf` method is * customized, this method returns the custom method, otherwise it returns * the `baseIndexOf` function. * * @private * @returns {Function} Returns the "indexOf" function. */ function getIndexOf() { var result = (result = lodash.indexOf) === indexOf ? baseIndexOf : result; return result; } /** * Checks if `value` is a native function. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if the `value` is a native function, else `false`. */ function isNative(value) { return typeof value == 'function' && reNative.test(value); } /** * Used by `unescape` to convert HTML entities to characters. * * @private * @param {string} match The matched character to unescape. * @returns {string} Returns the unescaped character. */ function unescapeHtmlChar(match) { return htmlUnescapes[match]; } /*--------------------------------------------------------------------------*/ /** * Checks if `value` is an `arguments` object. * * @static * @memberOf _ * @category Objects * @param {*} value The value to check. * @returns {boolean} Returns `true` if the `value` is an `arguments` object, else `false`. * @example * * (function() { return _.isArguments(arguments); })(1, 2, 3); * // => true * * _.isArguments([1, 2, 3]); * // => false */ function isArguments(value) { return value && typeof value == 'object' && typeof value.length == 'number' && toString.call(value) == argsClass || false; } // fallback for browsers that can't detect `arguments` objects by [[Class]] if (!isArguments(arguments)) { isArguments = function(value) { return value && typeof value == 'object' && typeof value.length == 'number' && hasOwnProperty.call(value, 'callee') && !propertyIsEnumerable.call(value, 'callee') || false; }; } /** * Checks if `value` is an array. * * @static * @memberOf _ * @type Function * @category Objects * @param {*} value The value to check. * @returns {boolean} Returns `true` if the `value` is an array, else `false`. * @example * * (function() { return _.isArray(arguments); })(); * // => false * * _.isArray([1, 2, 3]); * // => true */ var isArray = nativeIsArray || function(value) { return value && typeof value == 'object' && typeof value.length == 'number' && toString.call(value) == arrayClass || false; }; /** * A fallback implementation of `Object.keys` which produces an array of the * given object's own enumerable property names. * * @private * @type Function * @param {Object} object The object to inspect. * @returns {Array} Returns an array of property names. */ var shimKeys = function(object) { var index, iterable = object, result = []; if (!iterable) return result; if (!(objectTypes[typeof object])) return result; for (index in iterable) { if (hasOwnProperty.call(iterable, index)) { result.push(index); } } return result }; /** * Creates an array composed of the own enumerable property names of an object. * * @static * @memberOf _ * @category Objects * @param {Object} object The object to inspect. * @returns {Array} Returns an array of property names. * @example * * _.keys({ 'one': 1, 'two': 2, 'three': 3 }); * // => ['one', 'two', 'three'] (property order is not guaranteed across environments) */ var keys = !nativeKeys ? shimKeys : function(object) { if (!isObject(object)) { return []; } return nativeKeys(object); }; /** * Used to convert characters to HTML entities: * * Though the `>` character is escaped for symmetry, characters like `>` and `/` * don't require escaping in HTML and have no special meaning unless they're part * of a tag or an unquoted attribute value. * http://mathiasbynens.be/notes/ambiguous-ampersands (under "semi-related fun fact") */ var htmlEscapes = { '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#x27;' }; /** Used to convert HTML entities to characters */ var htmlUnescapes = invert(htmlEscapes); /** Used to match HTML entities and HTML characters */ var reEscapedHtml = RegExp('(' + keys(htmlUnescapes).join('|') + ')', 'g'), reUnescapedHtml = RegExp('[' + keys(htmlEscapes).join('') + ']', 'g'); /*--------------------------------------------------------------------------*/ /** * Assigns own enumerable properties of source object(s) to the destination * object. Subsequent sources will overwrite property assignments of previous * sources. If a callback is provided it will be executed to produce the * assigned values. The callback is bound to `thisArg` and invoked with two * arguments; (objectValue, sourceValue). * * @static * @memberOf _ * @type Function * @alias extend * @category Objects * @param {Object} object The destination object. * @param {...Object} [source] The source objects. * @param {Function} [callback] The function to customize assigning values. * @param {*} [thisArg] The `this` binding of `callback`. * @returns {Object} Returns the destination object. * @example * * _.assign({ 'name': 'fred' }, { 'employer': 'slate' }); * // => { 'name': 'fred', 'employer': 'slate' } * * var defaults = _.partialRight(_.assign, function(a, b) { * return typeof a == 'undefined' ? b : a; * }); * * var object = { 'name': 'barney' }; * defaults(object, { 'name': 'fred', 'employer': 'slate' }); * // => { 'name': 'barney', 'employer': 'slate' } */ function assign(object) { if (!object) { return object; } for (var argsIndex = 1, argsLength = arguments.length; argsIndex < argsLength; argsIndex++) { var iterable = arguments[argsIndex]; if (iterable) { for (var key in iterable) { object[key] = iterable[key]; } } } return object; } /** * Creates a clone of `value`. If `isDeep` is `true` nested objects will also * be cloned, otherwise they will be assigned by reference. If a callback * is provided it will be executed to produce the cloned values. If the * callback returns `undefined` cloning will be handled by the method instead. * The callback is bound to `thisArg` and invoked with one argument; (value). * * @static * @memberOf _ * @category Objects * @param {*} value The value to clone. * @param {boolean} [isDeep=false] Specify a deep clone. * @param {Function} [callback] The function to customize cloning values. * @param {*} [thisArg] The `this` binding of `callback`. * @returns {*} Returns the cloned value. * @example * * var characters = [ * { 'name': 'barney', 'age': 36 }, * { 'name': 'fred', 'age': 40 } * ]; * * var shallow = _.clone(characters); * shallow[0] === characters[0]; * // => true * * var deep = _.clone(characters, true); * deep[0] === characters[0]; * // => false * * _.mixin({ * 'clone': _.partialRight(_.clone, function(value) { * return _.isElement(value) ? value.cloneNode(false) : undefined; * }) * }); * * var clone = _.clone(document.body); * clone.childNodes.length; * // => 0 */ function clone(value) { return isObject(value) ? (isArray(value) ? slice(value) : assign({}, value)) : value; } /** * Assigns own enumerable properties of source object(s) to the destination * object for all destination properties that resolve to `undefined`. Once a * property is set, additional defaults of the same property will be ignored. * * @static * @memberOf _ * @type Function * @category Objects * @param {Object} object The destination object. * @param {...Object} [source] The source objects. * @param- {Object} [guard] Allows working with `_.reduce` without using its * `key` and `object` arguments as sources. * @returns {Object} Returns the destination object. * @example * * var object = { 'name': 'barney' }; * _.defaults(object, { 'name': 'fred', 'employer': 'slate' }); * // => { 'name': 'barney', 'employer': 'slate' } */ function defaults(object) { if (!object) { return object; } for (var argsIndex = 1, argsLength = arguments.length; argsIndex < argsLength; argsIndex++) { var iterable = arguments[argsIndex]; if (iterable) { for (var key in iterable) { if (typeof object[key] == 'undefined') { object[key] = iterable[key]; } } } } return object; } /** * Iterates over own and inherited enumerable properties of an object, * executing the callback for each property. The callback is bound to `thisArg` * and invoked with three arguments; (value, key, object). Callbacks may exit * iteration early by explicitly returning `false`. * * @static * @memberOf _ * @type Function * @category Objects * @param {Object} object The object to iterate over. * @param {Function} [callback=identity] The function called per iteration. * @param {*} [thisArg] The `this` binding of `callback`. * @returns {Object} Returns `object`. * @example * * function Shape() { * this.x = 0; * this.y = 0; * } * * Shape.prototype.move = function(x, y) { * this.x += x; * this.y += y; * }; * * _.forIn(new Shape, function(value, key) { * console.log(key); * }); * // => logs 'x', 'y', and 'move' (property order is not guaranteed across environments) */ var forIn = function(collection, callback) { var index, iterable = collection, result = iterable; if (!iterable) return result; if (!objectTypes[typeof iterable]) return result; for (index in iterable) { if (callback(iterable[index], index, collection) === indicatorObject) return result; } return result }; /** * Iterates over own enumerable properties of an object, executing the callback * for each property. The callback is bound to `thisArg` and invoked with three * arguments; (value, key, object). Callbacks may exit iteration early by * explicitly returning `false`. * * @static * @memberOf _ * @type Function * @category Objects * @param {Object} object The object to iterate over. * @param {Function} [callback=identity] The function called per iteration. * @param {*} [thisArg] The `this` binding of `callback`. * @returns {Object} Returns `object`. * @example * * _.forOwn({ '0': 'zero', '1': 'one', 'length': 2 }, function(num, key) { * console.log(key); * }); * // => logs '0', '1', and 'length' (property order is not guaranteed across environments) */ var forOwn = function(collection, callback) { var index, iterable = collection, result = iterable; if (!iterable) return result; if (!objectTypes[typeof iterable]) return result; for (index in iterable) { if (hasOwnProperty.call(iterable, index)) { if (callback(iterable[index], index, collection) === indicatorObject) return result; } } return result }; /** * Creates a sorted array of property names of all enumerable properties, * own and inherited, of `object` that have function values. * * @static * @memberOf _ * @alias methods * @category Objects * @param {Object} object The object to inspect. * @returns {Array} Returns an array of property names that have function values. * @example * * _.functions(_); * // => ['all', 'any', 'bind', 'bindAll', 'clone', 'compact', 'compose', ...] */ function functions(object) { var result = []; forIn(object, function(value, key) { if (isFunction(value)) { result.push(key); } }); return result.sort(); } /** * Checks if the specified property name exists as a direct property of `object`, * instead of an inherited property. * * @static * @memberOf _ * @category Objects * @param {Object} object The object to inspect. * @param {string} key The name of the property to check. * @returns {boolean} Returns `true` if key is a direct property, else `false`. * @example * * _.has({ 'a': 1, 'b': 2, 'c': 3 }, 'b'); * // => true */ function has(object, key) { return object ? hasOwnProperty.call(object, key) : false; } /** * Creates an object composed of the inverted keys and values of the given object. * * @static * @memberOf _ * @category Objects * @param {Object} object The object to invert. * @returns {Object} Returns the created inverted object. * @example * * _.invert({ 'first': 'fred', 'second': 'barney' }); * // => { 'fred': 'first', 'barney': 'second' } */ function invert(object) { var index = -1, props = keys(object), length = props.length, result = {}; while (++index < length) { var key = props[index]; result[object[key]] = key; } return result; } /** * Checks if `value` is a boolean value. * * @static * @memberOf _ * @category Objects * @param {*} value The value to check. * @returns {boolean} Returns `true` if the `value` is a boolean value, else `false`. * @example * * _.isBoolean(null); * // => false */ function isBoolean(value) { return value === true || value === false || value && typeof value == 'object' && toString.call(value) == boolClass || false; } /** * Checks if `value` is a date. * * @static * @memberOf _ * @category Objects * @param {*} value The value to check. * @returns {boolean} Returns `true` if the `value` is a date, else `false`. * @example * * _.isDate(new Date); * // => true */ function isDate(value) { return value && typeof value == 'object' && toString.call(value) == dateClass || false; } /** * Checks if `value` is a DOM element. * * @static * @memberOf _ * @category Objects * @param {*} value The value to check. * @returns {boolean} Returns `true` if the `value` is a DOM element, else `false`. * @example * * _.isElement(document.body); * // => true */ function isElement(value) { return value && value.nodeType === 1 || false; } /** * Checks if `value` is empty. Arrays, strings, or `arguments` objects with a * length of `0` and objects with no own enumerable properties are considered * "empty". * * @static * @memberOf _ * @category Objects * @param {Array|Object|string} value The value to inspect. * @returns {boolean} Returns `true` if the `value` is empty, else `false`. * @example * * _.isEmpty([1, 2, 3]); * // => false * * _.isEmpty({}); * // => true * * _.isEmpty(''); * // => true */ function isEmpty(value) { if (!value) { return true; } if (isArray(value) || isString(value)) { return !value.length; } for (var key in value) { if (hasOwnProperty.call(value, key)) { return false; } } return true; } /** * Performs a deep comparison between two values to determine if they are * equivalent to each other. If a callback is provided it will be executed * to compare values. If the callback returns `undefined` comparisons will * be handled by the method instead. The callback is bound to `thisArg` and * invoked with two arguments; (a, b). * * @static * @memberOf _ * @category Objects * @param {*} a The value to compare. * @param {*} b The other value to compare. * @param {Function} [callback] The function to customize comparing values. * @param {*} [thisArg] The `this` binding of `callback`. * @returns {boolean} Returns `true` if the values are equivalent, else `false`. * @example * * var object = { 'name': 'fred' }; * var copy = { 'name': 'fred' }; * * object == copy; * // => false * * _.isEqual(object, copy); * // => true * * var words = ['hello', 'goodbye']; * var otherWords = ['hi', 'goodbye']; * * _.isEqual(words, otherWords, function(a, b) { * var reGreet = /^(?:hello|hi)$/i, * aGreet = _.isString(a) && reGreet.test(a), * bGreet = _.isString(b) && reGreet.test(b); * * return (aGreet || bGreet) ? (aGreet == bGreet) : undefined; * }); * // => true */ function isEqual(a, b) { return baseIsEqual(a, b); } /** * Checks if `value` is, or can be coerced to, a finite number. * * Note: This is not the same as native `isFinite` which will return true for * booleans and empty strings. See http://es5.github.io/#x15.1.2.5. * * @static * @memberOf _ * @category Objects * @param {*} value The value to check. * @returns {boolean} Returns `true` if the `value` is finite, else `false`. * @example * * _.isFinite(-101); * // => true * * _.isFinite('10'); * // => true * * _.isFinite(true); * // => false * * _.isFinite(''); * // => false * * _.isFinite(Infinity); * // => false */ function isFinite(value) { return nativeIsFinite(value) && !nativeIsNaN(parseFloat(value)); } /** * Checks if `value` is a function. * * @static * @memberOf _ * @category Objects * @param {*} value The value to check. * @returns {boolean} Returns `true` if the `value` is a function, else `false`. * @example * * _.isFunction(_); * // => true */ function isFunction(value) { return typeof value == 'function'; } // fallback for older versions of Chrome and Safari if (isFunction(/x/)) { isFunction = function(value) { return typeof value == 'function' && toString.call(value) == funcClass; }; } /** * Checks if `value` is the language type of Object. * (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) * * @static * @memberOf _ * @category Objects * @param {*} value The value to check. * @returns {boolean} Returns `true` if the `value` is an object, else `false`. * @example * * _.isObject({}); * // => true * * _.isObject([1, 2, 3]); * // => true * * _.isObject(1); * // => false */ function isObject(value) { // check if the value is the ECMAScript language type of Object // http://es5.github.io/#x8 // and avoid a V8 bug // http://code.google.com/p/v8/issues/detail?id=2291 return !!(value && objectTypes[typeof value]); } /** * Checks if `value` is `NaN`. * * Note: This is not the same as native `isNaN` which will return `true` for * `undefined` and other non-numeric values. See http://es5.github.io/#x15.1.2.4. * * @static * @memberOf _ * @category Objects * @param {*} value The value to check. * @returns {boolean} Returns `true` if the `value` is `NaN`, else `false`. * @example * * _.isNaN(NaN); * // => true * * _.isNaN(new Number(NaN)); * // => true * * isNaN(undefined); * // => true * * _.isNaN(undefined); * // => false */ function isNaN(value) { // `NaN` as a primitive is the only value that is not equal to itself // (perform the [[Class]] check first to avoid errors with some host objects in IE) return isNumber(value) && value != +value; } /** * Checks if `value` is `null`. * * @static * @memberOf _ * @category Objects * @param {*} value The value to check. * @returns {boolean} Returns `true` if the `value` is `null`, else `false`. * @example * * _.isNull(null); * // => true * * _.isNull(undefined); * // => false */ function isNull(value) { return value === null; } /** * Checks if `value` is a number. * * Note: `NaN` is considered a number. See http://es5.github.io/#x8.5. * * @static * @memberOf _ * @category Objects * @param {*} value The value to check. * @returns {boolean} Returns `true` if the `value` is a number, else `false`. * @example * * _.isNumber(8.4 * 5); * // => true */ function isNumber(value) { return typeof value == 'number' || value && typeof value == 'object' && toString.call(value) == numberClass || false; } /** * Checks if `value` is a regular expression. * * @static * @memberOf _ * @category Objects * @param {*} value The value to check. * @returns {boolean} Returns `true` if the `value` is a regular expression, else `false`. * @example * * _.isRegExp(/fred/); * // => true */ function isRegExp(value) { return value && objectTypes[typeof value] && toString.call(value) == regexpClass || false; } /** * Checks if `value` is a string. * * @static * @memberOf _ * @category Objects * @param {*} value The value to check. * @returns {boolean} Returns `true` if the `value` is a string, else `false`. * @example * * _.isString('fred'); * // => true */ function isString(value) { return typeof value == 'string' || value && typeof value == 'object' && toString.call(value) == stringClass || false; } /** * Checks if `value` is `undefined`. * * @static * @memberOf _ * @category Objects * @param {*} value The value to check. * @returns {boolean} Returns `true` if the `value` is `undefined`, else `false`. * @example * * _.isUndefined(void 0); * // => true */ function isUndefined(value) { return typeof value == 'undefined'; } /** * Creates a shallow clone of `object` excluding the specified properties. * Property names may be specified as individual arguments or as arrays of * property names. If a callback is provided it will be executed for each * property of `object` omitting the properties the callback returns truey * for. The callback is bound to `thisArg` and invoked with three arguments; * (value, key, object). * * @static * @memberOf _ * @category Objects * @param {Object} object The source object. * @param {Function|...string|string[]} [callback] The properties to omit or the * function called per iteration. * @param {*} [thisArg] The `this` binding of `callback`. * @returns {Object} Returns an object without the omitted properties. * @example * * _.omit({ 'name': 'fred', 'age': 40 }, 'age'); * // => { 'name': 'fred' } * * _.omit({ 'name': 'fred', 'age': 40 }, function(value) { * return typeof value == 'number'; * }); * // => { 'name': 'fred' } */ function omit(object) { var props = []; forIn(object, function(value, key) { props.push(key); }); props = baseDifference(props, baseFlatten(arguments, true, false, 1)); var index = -1, length = props.length, result = {}; while (++index < length) { var key = props[index]; result[key] = object[key]; } return result; } /** * Creates a two dimensional array of an object's key-value pairs, * i.e. `[[key1, value1], [key2, value2]]`. * * @static * @memberOf _ * @category Objects * @param {Object} object The object to inspect. * @returns {Array} Returns new array of key-value pairs. * @example * * _.pairs({ 'barney': 36, 'fred': 40 }); * // => [['barney', 36], ['fred', 40]] (property order is not guaranteed across environments) */ function pairs(object) { var index = -1, props = keys(object), length = props.length, result = Array(length); while (++index < length) { var key = props[index]; result[index] = [key, object[key]]; } return result; } /** * Creates a shallow clone of `object` composed of the specified properties. * Property names may be specified as individual arguments or as arrays of * property names. If a callback is provided it will be executed for each * property of `object` picking the properties the callback returns truey * for. The callback is bound to `thisArg` and invoked with three arguments; * (value, key, object). * * @static * @memberOf _ * @category Objects * @param {Object} object The source object. * @param {Function|...string|string[]} [callback] The function called per * iteration or property names to pick, specified as individual property * names or arrays of property names. * @param {*} [thisArg] The `this` binding of `callback`. * @returns {Object} Returns an object composed of the picked properties. * @example * * _.pick({ 'name': 'fred', '_userid': 'fred1' }, 'name'); * // => { 'name': 'fred' } * * _.pick({ 'name': 'fred', '_userid': 'fred1' }, function(value, key) { * return key.charAt(0) != '_'; * }); * // => { 'name': 'fred' } */ function pick(object) { var index = -1, props = baseFlatten(arguments, true, false, 1), length = props.length, result = {}; while (++index < length) { var key = props[index]; if (key in object) { result[key] = object[key]; } } return result; } /** * Creates an array composed of the own enumerable property values of `object`. * * @static * @memberOf _ * @category Objects * @param {Object} object The object to inspect. * @returns {Array} Returns an array of property values. * @example * * _.values({ 'one': 1, 'two': 2, 'three': 3 }); * // => [1, 2, 3] (property order is not guaranteed across environments) */ function values(object) { var index = -1, props = keys(object), length = props.length, result = Array(length); while (++index < length) { result[index] = object[props[index]]; } return result; } /*--------------------------------------------------------------------------*/ /** * Checks if a given value is present in a collection using strict equality * for comparisons, i.e. `===`. If `fromIndex` is negative, it is used as the * offset from the end of the collection. * * @static * @memberOf _ * @alias include * @category Collections * @param {Array|Object|string} collection The collection to iterate over. * @param {*} target The value to check for. * @param {number} [fromIndex=0] The index to search from. * @returns {boolean} Returns `true` if the `target` element is found, else `false`. * @example * * _.contains([1, 2, 3], 1); * // => true * * _.contains([1, 2, 3], 1, 2); * // => false * * _.contains({ 'name': 'fred', 'age': 40 }, 'fred'); * // => true * * _.contains('pebbles', 'eb'); * // => true */ function contains(collection, target) { var indexOf = getIndexOf(), length = collection ? collection.length : 0, result = false; if (length && typeof length == 'number') { result = indexOf(collection, target) > -1; } else { forOwn(collection, function(value) { return (result = value === target) && indicatorObject; }); } return result; } /** * Creates an object composed of keys generated from the results of running * each element of `collection` through the callback. The corresponding value * of each key is the number of times the key was returned by the callback. * The callback is bound to `thisArg` and invoked with three arguments; * (value, index|key, collection). * * If a property name is provided for `callback` the created "_.pluck" style * callback will return the property value of the given element. * * If an object is provided for `callback` the created "_.where" style callback * will return `true` for elements that have the properties of the given object, * else `false`. * * @static * @memberOf _ * @category Collections * @param {Array|Object|string} collection The collection to iterate over. * @param {Function|Object|string} [callback=identity] The function called * per iteration. If a property name or object is provided it will be used * to create a "_.pluck" or "_.where" style callback, respectively. * @param {*} [thisArg] The `this` binding of `callback`. * @returns {Object} Returns the composed aggregate object. * @example * * _.countBy([4.3, 6.1, 6.4], function(num) { return Math.floor(num); }); * // => { '4': 1, '6': 2 } * * _.countBy([4.3, 6.1, 6.4], function(num) { return this.floor(num); }, Math); * // => { '4': 1, '6': 2 } * * _.countBy(['one', 'two', 'three'], 'length'); * // => { '3': 2, '5': 1 } */ var countBy = createAggregator(function(result, value, key) { (hasOwnProperty.call(result, key) ? result[key]++ : result[key] = 1); }); /** * Checks if the given callback returns truey value for **all** elements of * a collection. The callback is bound to `thisArg` and invoked with three * arguments; (value, index|key, collection). * * If a property name is provided for `callback` the created "_.pluck" style * callback will return the property value of the given element. * * If an object is provided for `callback` the created "_.where" style callback * will return `true` for elements that have the properties of the given object, * else `false`. * * @static * @memberOf _ * @alias all * @category Collections * @param {Array|Object|string} collection The collection to iterate over. * @param {Function|Object|string} [callback=identity] The function called * per iteration. If a property name or object is provided it will be used * to create a "_.pluck" or "_.where" style callback, respectively. * @param {*} [thisArg] The `this` binding of `callback`. * @returns {boolean} Returns `true` if all elements passed the callback check, * else `false`. * @example * * _.every([true, 1, null, 'yes']); * // => false * * var characters = [ * { 'name': 'barney', 'age': 36 }, * { 'name': 'fred', 'age': 40 } * ]; * * // using "_.pluck" callback shorthand * _.every(characters, 'age'); * // => true * * // using "_.where" callback shorthand * _.every(characters, { 'age': 36 }); * // => false */ function every(collection, callback, thisArg) { var result = true; callback = createCallback(callback, thisArg, 3); var index = -1, length = collection ? collection.length : 0; if (typeof length == 'number') { while (++index < length) { if (!(result = !!callback(collection[index], index, collection))) { break; } } } else { forOwn(collection, function(value, index, collection) { return !(result = !!callback(value, index, collection)) && indicatorObject; }); } return result; } /** * Iterates over elements of a collection, returning an array of all elements * the callback returns truey for. The callback is bound to `thisArg` and * invoked with three arguments; (value, index|key, collection). * * If a property name is provided for `callback` the created "_.pluck" style * callback will return the property value of the given element. * * If an object is provided for `callback` the created "_.where" style callback * will return `true` for elements that have the properties of the given object, * else `false`. * * @static * @memberOf _ * @alias select * @category Collections * @param {Array|Object|string} collection The collection to iterate over. * @param {Function|Object|string} [callback=identity] The function called * per iteration. If a property name or object is provided it will be used * to create a "_.pluck" or "_.where" style callback, respectively. * @param {*} [thisArg] The `this` binding of `callback`. * @returns {Array} Returns a new array of elements that passed the callback check. * @example * * var evens = _.filter([1, 2, 3, 4, 5, 6], function(num) { return num % 2 == 0; }); * // => [2, 4, 6] * * var characters = [ * { 'name': 'barney', 'age': 36, 'blocked': false }, * { 'name': 'fred', 'age': 40, 'blocked': true } * ]; * * // using "_.pluck" callback shorthand * _.filter(characters, 'blocked'); * // => [{ 'name': 'fred', 'age': 40, 'blocked': true }] * * // using "_.where" callback shorthand * _.filter(characters, { 'age': 36 }); * // => [{ 'name': 'barney', 'age': 36, 'blocked': false }] */ function filter(collection, callback, thisArg) { var result = []; callback = createCallback(callback, thisArg, 3); var index = -1, length = collection ? collection.length : 0; if (typeof length == 'number') { while (++index < length) { var value = collection[index]; if (callback(value, index, collection)) { result.push(value); } } } else { forOwn(collection, function(value, index, collection) { if (callback(value, index, collection)) { result.push(value); } }); } return result; } /** * Iterates over elements of a collection, returning the first element that * the callback returns truey for. The callback is bound to `thisArg` and * invoked with three arguments; (value, index|key, collection). * * If a property name is provided for `callback` the created "_.pluck" style * callback will return the property value of the given element. * * If an object is provided for `callback` the created "_.where" style callback * will return `true` for elements that have the properties of the given object, * else `false`. * * @static * @memberOf _ * @alias detect, findWhere * @category Collections * @param {Array|Object|string} collection The collection to iterate over. * @param {Function|Object|string} [callback=identity] The function called * per iteration. If a property name or object is provided it will be used * to create a "_.pluck" or "_.where" style callback, respectively. * @param {*} [thisArg] The `this` binding of `callback`. * @returns {*} Returns the found element, else `undefined`. * @example * * var characters = [ * { 'name': 'barney', 'age': 36, 'blocked': false }, * { 'name': 'fred', 'age': 40, 'blocked': true }, * { 'name': 'pebbles', 'age': 1, 'blocked': false } * ]; * * _.find(characters, function(chr) { * return chr.age < 40; * }); * // => { 'name': 'barney', 'age': 36, 'blocked': false } * * // using "_.where" callback shorthand * _.find(characters, { 'age': 1 }); * // => { 'name': 'pebbles', 'age': 1, 'blocked': false } * * // using "_.pluck" callback shorthand * _.find(characters, 'blocked'); * // => { 'name': 'fred', 'age': 40, 'blocked': true } */ function find(collection, callback, thisArg) { callback = createCallback(callback, thisArg, 3); var index = -1, length = collection ? collection.length : 0; if (typeof length == 'number') { while (++index < length) { var value = collection[index]; if (callback(value, index, collection)) { return value; } } } else { var result; forOwn(collection, function(value, index, collection) { if (callback(value, index, collection)) { result = value; return indicatorObject; } }); return result; } } /** * Examines each element in a `collection`, returning the first that * has the given properties. When checking `properties`, this method * performs a deep comparison between values to determine if they are * equivalent to each other. * * @static * @memberOf _ * @category Collections * @param {Array|Object|string} collection The collection to iterate over. * @param {Object} properties The object of property values to filter by. * @returns {*} Returns the found element, else `undefined`. * @example * * var food = [ * { 'name': 'apple', 'organic': false, 'type': 'fruit' }, * { 'name': 'banana', 'organic': true, 'type': 'fruit' }, * { 'name': 'beet', 'organic': false, 'type': 'vegetable' } * ]; * * _.findWhere(food, { 'type': 'vegetable' }); * // => { 'name': 'beet', 'organic': false, 'type': 'vegetable' } */ function findWhere(object, properties) { return where(object, properties, true); } /** * Iterates over elements of a collection, executing the callback for each * element. The callback is bound to `thisArg` and invoked with three arguments; * (value, index|key, collection). Callbacks may exit iteration early by * explicitly returning `false`. * * Note: As with other "Collections" methods, objects with a `length` property * are iterated like arrays. To avoid this behavior `_.forIn` or `_.forOwn` * may be used for object iteration. * * @static * @memberOf _ * @alias each * @category Collections * @param {Array|Object|string} collection The collection to iterate over. * @param {Function} [callback=identity] The function called per iteration. * @param {*} [thisArg] The `this` binding of `callback`. * @returns {Array|Object|string} Returns `collection`. * @example * * _([1, 2, 3]).forEach(function(num) { console.log(num); }).join(','); * // => logs each number and returns '1,2,3' * * _.forEach({ 'one': 1, 'two': 2, 'three': 3 }, function(num) { console.log(num); }); * // => logs each number and returns the object (property order is not guaranteed across environments) */ function forEach(collection, callback, thisArg) { var index = -1, length = collection ? collection.length : 0; callback = callback && typeof thisArg == 'undefined' ? callback : baseCreateCallback(callback, thisArg, 3); if (typeof length == 'number') { while (++index < length) { if (callback(collection[index], index, collection) === indicatorObject) { break; } } } else { forOwn(collection, callback); } } /** * This method is like `_.forEach` except that it iterates over elements * of a `collection` from right to left. * * @static * @memberOf _ * @alias eachRight * @category Collections * @param {Array|Object|string} collection The collection to iterate over. * @param {Function} [callback=identity] The function called per iteration. * @param {*} [thisArg] The `this` binding of `callback`. * @returns {Array|Object|string} Returns `collection`. * @example * * _([1, 2, 3]).forEachRight(function(num) { console.log(num); }).join(','); * // => logs each number from right to left and returns '3,2,1' */ function forEachRight(collection, callback) { var length = collection ? collection.length : 0; if (typeof length == 'number') { while (length--) { if (callback(collection[length], length, collection) === false) { break; } } } else { var props = keys(collection); length = props.length; forOwn(collection, function(value, key, collection) { key = props ? props[--length] : --length; return callback(collection[key], key, collection) === false && indicatorObject; }); } } /** * Creates an object composed of keys generated from the results of running * each element of a collection through the callback. The corresponding value * of each key is an array of the elements responsible for generating the key. * The callback is bound to `thisArg` and invoked with three arguments; * (value, index|key, collection). * * If a property name is provided for `callback` the created "_.pluck" style * callback will return the property value of the given element. * * If an object is provided for `callback` the created "_.where" style callback * will return `true` for elements that have the properties of the given object, * else `false` * * @static * @memberOf _ * @category Collections * @param {Array|Object|string} collection The collection to iterate over. * @param {Function|Object|string} [callback=identity] The function called * per iteration. If a property name or object is provided it will be used * to create a "_.pluck" or "_.where" style callback, respectively. * @param {*} [thisArg] The `this` binding of `callback`. * @returns {Object} Returns the composed aggregate object. * @example * * _.groupBy([4.2, 6.1, 6.4], function(num) { return Math.floor(num); }); * // => { '4': [4.2], '6': [6.1, 6.4] } * * _.groupBy([4.2, 6.1, 6.4], function(num) { return this.floor(num); }, Math); * // => { '4': [4.2], '6': [6.1, 6.4] } * * // using "_.pluck" callback shorthand * _.groupBy(['one', 'two', 'three'], 'length'); * // => { '3': ['one', 'two'], '5': ['three'] } */ var groupBy = createAggregator(function(result, value, key) { (hasOwnProperty.call(result, key) ? result[key] : result[key] = []).push(value); }); /** * Creates an object composed of keys generated from the results of running * each element of the collection through the given callback. The corresponding * value of each key is the last element responsible for generating the key. * The callback is bound to `thisArg` and invoked with three arguments; * (value, index|key, collection). * * If a property name is provided for `callback` the created "_.pluck" style * callback will return the property value of the given element. * * If an object is provided for `callback` the created "_.where" style callback * will return `true` for elements that have the properties of the given object, * else `false`. * * @static * @memberOf _ * @category Collections * @param {Array|Object|string} collection The collection to iterate over. * @param {Function|Object|string} [callback=identity] The function called * per iteration. If a property name or object is provided it will be used * to create a "_.pluck" or "_.where" style callback, respectively. * @param {*} [thisArg] The `this` binding of `callback`. * @returns {Object} Returns the composed aggregate object. * @example * * var keys = [ * { 'dir': 'left', 'code': 97 }, * { 'dir': 'right', 'code': 100 } * ]; * * _.indexBy(keys, 'dir'); * // => { 'left': { 'dir': 'left', 'code': 97 }, 'right': { 'dir': 'right', 'code': 100 } } * * _.indexBy(keys, function(key) { return String.fromCharCode(key.code); }); * // => { 'a': { 'dir': 'left', 'code': 97 }, 'd': { 'dir': 'right', 'code': 100 } } * * _.indexBy(characters, function(key) { this.fromCharCode(key.code); }, String); * // => { 'a': { 'dir': 'left', 'code': 97 }, 'd': { 'dir': 'right', 'code': 100 } } */ var indexBy = createAggregator(function(result, value, key) { result[key] = value; }); /** * Invokes the method named by `methodName` on each element in the `collection` * returning an array of the results of each invoked method. Additional arguments * will be provided to each invoked method. If `methodName` is a function it * will be invoked for, and `this` bound to, each element in the `collection`. * * @static * @memberOf _ * @category Collections * @param {Array|Object|string} collection The collection to iterate over. * @param {Function|string} methodName The name of the method to invoke or * the function invoked per iteration. * @param {...*} [arg] Arguments to invoke the method with. * @returns {Array} Returns a new array of the results of each invoked method. * @example * * _.invoke([[5, 1, 7], [3, 2, 1]], 'sort'); * // => [[1, 5, 7], [1, 2, 3]] * * _.invoke([123, 456], String.prototype.split, ''); * // => [['1', '2', '3'], ['4', '5', '6']] */ function invoke(collection, methodName) { var args = slice(arguments, 2), index = -1, isFunc = typeof methodName == 'function', length = collection ? collection.length : 0, result = Array(typeof length == 'number' ? length : 0); forEach(collection, function(value) { result[++index] = (isFunc ? methodName : value[methodName]).apply(value, args); }); return result; } /** * Creates an array of values by running each element in the collection * through the callback. The callback is bound to `thisArg` and invoked with * three arguments; (value, index|key, collection). * * If a property name is provided for `callback` the created "_.pluck" style * callback will return the property value of the given element. * * If an object is provided for `callback` the created "_.where" style callback * will return `true` for elements that have the properties of the given object, * else `false`. * * @static * @memberOf _ * @alias collect * @category Collections * @param {Array|Object|string} collection The collection to iterate over. * @param {Function|Object|string} [callback=identity] The function called * per iteration. If a property name or object is provided it will be used * to create a "_.pluck" or "_.where" style callback, respectively. * @param {*} [thisArg] The `this` binding of `callback`. * @returns {Array} Returns a new array of the results of each `callback` execution. * @example * * _.map([1, 2, 3], function(num) { return num * 3; }); * // => [3, 6, 9] * * _.map({ 'one': 1, 'two': 2, 'three': 3 }, function(num) { return num * 3; }); * // => [3, 6, 9] (property order is not guaranteed across environments) * * var characters = [ * { 'name': 'barney', 'age': 36 }, * { 'name': 'fred', 'age': 40 } * ]; * * // using "_.pluck" callback shorthand * _.map(characters, 'name'); * // => ['barney', 'fred'] */ function map(collection, callback, thisArg) { var index = -1, length = collection ? collection.length : 0; callback = createCallback(callback, thisArg, 3); if (typeof length == 'number') { var result = Array(length); while (++index < length) { result[index] = callback(collection[index], index, collection); } } else { result = []; forOwn(collection, function(value, key, collection) { result[++index] = callback(value, key, collection); }); } return result; } /** * Retrieves the maximum value of a collection. If the collection is empty or * falsey `-Infinity` is returned. If a callback is provided it will be executed * for each value in the collection to generate the criterion by which the value * is ranked. The callback is bound to `thisArg` and invoked with three * arguments; (value, index, collection). * * If a property name is provided for `callback` the created "_.pluck" style * callback will return the property value of the given element. * * If an object is provided for `callback` the created "_.where" style callback * will return `true` for elements that have the properties of the given object, * else `false`. * * @static * @memberOf _ * @category Collections * @param {Array|Object|string} collection The collection to iterate over. * @param {Function|Object|string} [callback=identity] The function called * per iteration. If a property name or object is provided it will be used * to create a "_.pluck" or "_.where" style callback, respectively. * @param {*} [thisArg] The `this` binding of `callback`. * @returns {*} Returns the maximum value. * @example * * _.max([4, 2, 8, 6]); * // => 8 * * var characters = [ * { 'name': 'barney', 'age': 36 }, * { 'name': 'fred', 'age': 40 } * ]; * * _.max(characters, function(chr) { return chr.age; }); * // => { 'name': 'fred', 'age': 40 }; * * // using "_.pluck" callback shorthand * _.max(characters, 'age'); * // => { 'name': 'fred', 'age': 40 }; */ function max(collection, callback, thisArg) { var computed = -Infinity, result = computed; // allows working with functions like `_.map` without using // their `index` argument as a callback if (typeof callback != 'function' && thisArg && thisArg[callback] === collection) { callback = null; } var index = -1, length = collection ? collection.length : 0; if (callback == null && typeof length == 'number') { while (++index < length) { var value = collection[index]; if (value > result) { result = value; } } } else { callback = createCallback(callback, thisArg, 3); forEach(collection, function(value, index, collection) { var current = callback(value, index, collection); if (current > computed) { computed = current; result = value; } }); } return result; } /** * Retrieves the minimum value of a collection. If the collection is empty or * falsey `Infinity` is returned. If a callback is provided it will be executed * for each value in the collection to generate the criterion by which the value * is ranked. The callback is bound to `thisArg` and invoked with three * arguments; (value, index, collection). * * If a property name is provided for `callback` the created "_.pluck" style * callback will return the property value of the given element. * * If an object is provided for `callback` the created "_.where" style callback * will return `true` for elements that have the properties of the given object, * else `false`. * * @static * @memberOf _ * @category Collections * @param {Array|Object|string} collection The collection to iterate over. * @param {Function|Object|string} [callback=identity] The function called * per iteration. If a property name or object is provided it will be used * to create a "_.pluck" or "_.where" style callback, respectively. * @param {*} [thisArg] The `this` binding of `callback`. * @returns {*} Returns the minimum value. * @example * * _.min([4, 2, 8, 6]); * // => 2 * * var characters = [ * { 'name': 'barney', 'age': 36 }, * { 'name': 'fred', 'age': 40 } * ]; * * _.min(characters, function(chr) { return chr.age; }); * // => { 'name': 'barney', 'age': 36 }; * * // using "_.pluck" callback shorthand * _.min(characters, 'age'); * // => { 'name': 'barney', 'age': 36 }; */ function min(collection, callback, thisArg) { var computed = Infinity, result = computed; // allows working with functions like `_.map` without using // their `index` argument as a callback if (typeof callback != 'function' && thisArg && thisArg[callback] === collection) { callback = null; } var index = -1, length = collection ? collection.length : 0; if (callback == null && typeof length == 'number') { while (++index < length) { var value = collection[index]; if (value < result) { result = value; } } } else { callback = createCallback(callback, thisArg, 3); forEach(collection, function(value, index, collection) { var current = callback(value, index, collection); if (current < computed) { computed = current; result = value; } }); } return result; } /** * Retrieves the value of a specified property from all elements in the collection. * * @static * @memberOf _ * @type Function * @category Collections * @param {Array|Object|string} collection The collection to iterate over. * @param {string} property The name of the property to pluck. * @returns {Array} Returns a new array of property values. * @example * * var characters = [ * { 'name': 'barney', 'age': 36 }, * { 'name': 'fred', 'age': 40 } * ]; * * _.pluck(characters, 'name'); * // => ['barney', 'fred'] */ var pluck = map; /** * Reduces a collection to a value which is the accumulated result of running * each element in the collection through the callback, where each successive * callback execution consumes the return value of the previous execution. If * `accumulator` is not provided the first element of the collection will be * used as the initial `accumulator` value. The callback is bound to `thisArg` * and invoked with four arguments; (accumulator, value, index|key, collection). * * @static * @memberOf _ * @alias foldl, inject * @category Collections * @param {Array|Object|string} collection The collection to iterate over. * @param {Function} [callback=identity] The function called per iteration. * @param {*} [accumulator] Initial value of the accumulator. * @param {*} [thisArg] The `this` binding of `callback`. * @returns {*} Returns the accumulated value. * @example * * var sum = _.reduce([1, 2, 3], function(sum, num) { * return sum + num; * }); * // => 6 * * var mapped = _.reduce({ 'a': 1, 'b': 2, 'c': 3 }, function(result, num, key) { * result[key] = num * 3; * return result; * }, {}); * // => { 'a': 3, 'b': 6, 'c': 9 } */ function reduce(collection, callback, accumulator, thisArg) { if (!collection) return accumulator; var noaccum = arguments.length < 3; callback = createCallback(callback, thisArg, 4); var index = -1, length = collection.length; if (typeof length == 'number') { if (noaccum) { accumulator = collection[++index]; } while (++index < length) { accumulator = callback(accumulator, collection[index], index, collection); } } else { forOwn(collection, function(value, index, collection) { accumulator = noaccum ? (noaccum = false, value) : callback(accumulator, value, index, collection) }); } return accumulator; } /** * This method is like `_.reduce` except that it iterates over elements * of a `collection` from right to left. * * @static * @memberOf _ * @alias foldr * @category Collections * @param {Array|Object|string} collection The collection to iterate over. * @param {Function} [callback=identity] The function called per iteration. * @param {*} [accumulator] Initial value of the accumulator. * @param {*} [thisArg] The `this` binding of `callback`. * @returns {*} Returns the accumulated value. * @example * * var list = [[0, 1], [2, 3], [4, 5]]; * var flat = _.reduceRight(list, function(a, b) { return a.concat(b); }, []); * // => [4, 5, 2, 3, 0, 1] */ function reduceRight(collection, callback, accumulator, thisArg) { var noaccum = arguments.length < 3; callback = createCallback(callback, thisArg, 4); forEachRight(collection, function(value, index, collection) { accumulator = noaccum ? (noaccum = false, value) : callback(accumulator, value, index, collection); }); return accumulator; } /** * The opposite of `_.filter` this method returns the elements of a * collection that the callback does **not** return truey for. * * If a property name is provided for `callback` the created "_.pluck" style * callback will return the property value of the given element. * * If an object is provided for `callback` the created "_.where" style callback * will return `true` for elements that have the properties of the given object, * else `false`. * * @static * @memberOf _ * @category Collections * @param {Array|Object|string} collection The collection to iterate over. * @param {Function|Object|string} [callback=identity] The function called * per iteration. If a property name or object is provided it will be used * to create a "_.pluck" or "_.where" style callback, respectively. * @param {*} [thisArg] The `this` binding of `callback`. * @returns {Array} Returns a new array of elements that failed the callback check. * @example * * var odds = _.reject([1, 2, 3, 4, 5, 6], function(num) { return num % 2 == 0; }); * // => [1, 3, 5] * * var characters = [ * { 'name': 'barney', 'age': 36, 'blocked': false }, * { 'name': 'fred', 'age': 40, 'blocked': true } * ]; * * // using "_.pluck" callback shorthand * _.reject(characters, 'blocked'); * // => [{ 'name': 'barney', 'age': 36, 'blocked': false }] * * // using "_.where" callback shorthand * _.reject(characters, { 'age': 36 }); * // => [{ 'name': 'fred', 'age': 40, 'blocked': true }] */ function reject(collection, callback, thisArg) { callback = createCallback(callback, thisArg, 3); return filter(collection, function(value, index, collection) { return !callback(value, index, collection); }); } /** * Retrieves a random element or `n` random elements from a collection. * * @static * @memberOf _ * @category Collections * @param {Array|Object|string} collection The collection to sample. * @param {number} [n] The number of elements to sample. * @param- {Object} [guard] Allows working with functions like `_.map` * without using their `index` arguments as `n`. * @returns {Array} Returns the random sample(s) of `collection`. * @example * * _.sample([1, 2, 3, 4]); * // => 2 * * _.sample([1, 2, 3, 4], 2); * // => [3, 1] */ function sample(collection, n, guard) { if (collection && typeof collection.length != 'number') { collection = values(collection); } if (n == null || guard) { return collection ? collection[baseRandom(0, collection.length - 1)] : undefined; } var result = shuffle(collection); result.length = nativeMin(nativeMax(0, n), result.length); return result; } /** * Creates an array of shuffled values, using a version of the Fisher-Yates * shuffle. See http://en.wikipedia.org/wiki/Fisher-Yates_shuffle. * * @static * @memberOf _ * @category Collections * @param {Array|Object|string} collection The collection to shuffle. * @returns {Array} Returns a new shuffled collection. * @example * * _.shuffle([1, 2, 3, 4, 5, 6]); * // => [4, 1, 6, 3, 5, 2] */ function shuffle(collection) { var index = -1, length = collection ? collection.length : 0, result = Array(typeof length == 'number' ? length : 0); forEach(collection, function(value) { var rand = baseRandom(0, ++index); result[index] = result[rand]; result[rand] = value; }); return result; } /** * Gets the size of the `collection` by returning `collection.length` for arrays * and array-like objects or the number of own enumerable properties for objects. * * @static * @memberOf _ * @category Collections * @param {Array|Object|string} collection The collection to inspect. * @returns {number} Returns `collection.length` or number of own enumerable properties. * @example * * _.size([1, 2]); * // => 2 * * _.size({ 'one': 1, 'two': 2, 'three': 3 }); * // => 3 * * _.size('pebbles'); * // => 7 */ function size(collection) { var length = collection ? collection.length : 0; return typeof length == 'number' ? length : keys(collection).length; } /** * Checks if the callback returns a truey value for **any** element of a * collection. The function returns as soon as it finds a passing value and * does not iterate over the entire collection. The callback is bound to * `thisArg` and invoked with three arguments; (value, index|key, collection). * * If a property name is provided for `callback` the created "_.pluck" style * callback will return the property value of the given element. * * If an object is provided for `callback` the created "_.where" style callback * will return `true` for elements that have the properties of the given object, * else `false`. * * @static * @memberOf _ * @alias any * @category Collections * @param {Array|Object|string} collection The collection to iterate over. * @param {Function|Object|string} [callback=identity] The function called * per iteration. If a property name or object is provided it will be used * to create a "_.pluck" or "_.where" style callback, respectively. * @param {*} [thisArg] The `this` binding of `callback`. * @returns {boolean} Returns `true` if any element passed the callback check, * else `false`. * @example * * _.some([null, 0, 'yes', false], Boolean); * // => true * * var characters = [ * { 'name': 'barney', 'age': 36, 'blocked': false }, * { 'name': 'fred', 'age': 40, 'blocked': true } * ]; * * // using "_.pluck" callback shorthand * _.some(characters, 'blocked'); * // => true * * // using "_.where" callback shorthand * _.some(characters, { 'age': 1 }); * // => false */ function some(collection, callback, thisArg) { var result; callback = createCallback(callback, thisArg, 3); var index = -1, length = collection ? collection.length : 0; if (typeof length == 'number') { while (++index < length) { if ((result = callback(collection[index], index, collection))) { break; } } } else { forOwn(collection, function(value, index, collection) { return (result = callback(value, index, collection)) && indicatorObject; }); } return !!result; } /** * Creates an array of elements, sorted in ascending order by the results of * running each element in a collection through the callback. This method * performs a stable sort, that is, it will preserve the original sort order * of equal elements. The callback is bound to `thisArg` and invoked with * three arguments; (value, index|key, collection). * * If a property name is provided for `callback` the created "_.pluck" style * callback will return the property value of the given element. * * If an array of property names is provided for `callback` the collection * will be sorted by each property value. * * If an object is provided for `callback` the created "_.where" style callback * will return `true` for elements that have the properties of the given object, * else `false`. * * @static * @memberOf _ * @category Collections * @param {Array|Object|string} collection The collection to iterate over. * @param {Array|Function|Object|string} [callback=identity] The function called * per iteration. If a property name or object is provided it will be used * to create a "_.pluck" or "_.where" style callback, respectively. * @param {*} [thisArg] The `this` binding of `callback`. * @returns {Array} Returns a new array of sorted elements. * @example * * _.sortBy([1, 2, 3], function(num) { return Math.sin(num); }); * // => [3, 1, 2] * * _.sortBy([1, 2, 3], function(num) { return this.sin(num); }, Math); * // => [3, 1, 2] * * var characters = [ * { 'name': 'barney', 'age': 36 }, * { 'name': 'fred', 'age': 40 }, * { 'name': 'barney', 'age': 26 }, * { 'name': 'fred', 'age': 30 } * ]; * * // using "_.pluck" callback shorthand * _.map(_.sortBy(characters, 'age'), _.values); * // => [['barney', 26], ['fred', 30], ['barney', 36], ['fred', 40]] * * // sorting by multiple properties * _.map(_.sortBy(characters, ['name', 'age']), _.values); * // = > [['barney', 26], ['barney', 36], ['fred', 30], ['fred', 40]] */ function sortBy(collection, callback, thisArg) { var index = -1, length = collection ? collection.length : 0, result = Array(typeof length == 'number' ? length : 0); callback = createCallback(callback, thisArg, 3); forEach(collection, function(value, key, collection) { result[++index] = { 'criteria': [callback(value, key, collection)], 'index': index, 'value': value }; }); length = result.length; result.sort(compareAscending); while (length--) { result[length] = result[length].value; } return result; } /** * Converts the `collection` to an array. * * @static * @memberOf _ * @category Collections * @param {Array|Object|string} collection The collection to convert. * @returns {Array} Returns the new converted array. * @example * * (function() { return _.toArray(arguments).slice(1); })(1, 2, 3, 4); * // => [2, 3, 4] */ function toArray(collection) { if (isArray(collection)) { return slice(collection); } if (collection && typeof collection.length == 'number') { return map(collection); } return values(collection); } /** * Performs a deep comparison of each element in a `collection` to the given * `properties` object, returning an array of all elements that have equivalent * property values. * * @static * @memberOf _ * @type Function * @category Collections * @param {Array|Object|string} collection The collection to iterate over. * @param {Object} props The object of property values to filter by. * @returns {Array} Returns a new array of elements that have the given properties. * @example * * var characters = [ * { 'name': 'barney', 'age': 36, 'pets': ['hoppy'] }, * { 'name': 'fred', 'age': 40, 'pets': ['baby puss', 'dino'] } * ]; * * _.where(characters, { 'age': 36 }); * // => [{ 'name': 'barney', 'age': 36, 'pets': ['hoppy'] }] * * _.where(characters, { 'pets': ['dino'] }); * // => [{ 'name': 'fred', 'age': 40, 'pets': ['baby puss', 'dino'] }] */ function where(collection, properties, first) { return (first && isEmpty(properties)) ? undefined : (first ? find : filter)(collection, properties); } /*--------------------------------------------------------------------------*/ /** * Creates an array with all falsey values removed. The values `false`, `null`, * `0`, `""`, `undefined`, and `NaN` are all falsey. * * @static * @memberOf _ * @category Arrays * @param {Array} array The array to compact. * @returns {Array} Returns a new array of filtered values. * @example * * _.compact([0, 1, false, 2, '', 3]); * // => [1, 2, 3] */ function compact(array) { var index = -1, length = array ? array.length : 0, result = []; while (++index < length) { var value = array[index]; if (value) { result.push(value); } } return result; } /** * Creates an array excluding all values of the provided arrays using strict * equality for comparisons, i.e. `===`. * * @static * @memberOf _ * @category Arrays * @param {Array} array The array to process. * @param {...Array} [values] The arrays of values to exclude. * @returns {Array} Returns a new array of filtered values. * @example * * _.difference([1, 2, 3, 4, 5], [5, 2, 10]); * // => [1, 3, 4] */ function difference(array) { return baseDifference(array, baseFlatten(arguments, true, true, 1)); } /** * Gets the first element or first `n` elements of an array. If a callback * is provided elements at the beginning of the array are returned as long * as the callback returns truey. The callback is bound to `thisArg` and * invoked with three arguments; (value, index, array). * * If a property name is provided for `callback` the created "_.pluck" style * callback will return the property value of the given element. * * If an object is provided for `callback` the created "_.where" style callback * will return `true` for elements that have the properties of the given object, * else `false`. * * @static * @memberOf _ * @alias head, take * @category Arrays * @param {Array} array The array to query. * @param {Function|Object|number|string} [callback] The function called * per element or the number of elements to return. If a property name or * object is provided it will be used to create a "_.pluck" or "_.where" * style callback, respectively. * @param {*} [thisArg] The `this` binding of `callback`. * @returns {*} Returns the first element(s) of `array`. * @example * * _.first([1, 2, 3]); * // => 1 * * _.first([1, 2, 3], 2); * // => [1, 2] * * _.first([1, 2, 3], function(num) { * return num < 3; * }); * // => [1, 2] * * var characters = [ * { 'name': 'barney', 'blocked': true, 'employer': 'slate' }, * { 'name': 'fred', 'blocked': false, 'employer': 'slate' }, * { 'name': 'pebbles', 'blocked': true, 'employer': 'na' } * ]; * * // using "_.pluck" callback shorthand * _.first(characters, 'blocked'); * // => [{ 'name': 'barney', 'blocked': true, 'employer': 'slate' }] * * // using "_.where" callback shorthand * _.pluck(_.first(characters, { 'employer': 'slate' }), 'name'); * // => ['barney', 'fred'] */ function first(array, callback, thisArg) { var n = 0, length = array ? array.length : 0; if (typeof callback != 'number' && callback != null) { var index = -1; callback = createCallback(callback, thisArg, 3); while (++index < length && callback(array[index], index, array)) { n++; } } else { n = callback; if (n == null || thisArg) { return array ? array[0] : undefined; } } return slice(array, 0, nativeMin(nativeMax(0, n), length)); } /** * Flattens a nested array (the nesting can be to any depth). If `isShallow` * is truey, the array will only be flattened a single level. If a callback * is provided each element of the array is passed through the callback before * flattening. The callback is bound to `thisArg` and invoked with three * arguments; (value, index, array). * * If a property name is provided for `callback` the created "_.pluck" style * callback will return the property value of the given element. * * If an object is provided for `callback` the created "_.where" style callback * will return `true` for elements that have the properties of the given object, * else `false`. * * @static * @memberOf _ * @category Arrays * @param {Array} array The array to flatten. * @param {boolean} [isShallow=false] A flag to restrict flattening to a single level. * @param {Function|Object|string} [callback=identity] The function called * per iteration. If a property name or object is provided it will be used * to create a "_.pluck" or "_.where" style callback, respectively. * @param {*} [thisArg] The `this` binding of `callback`. * @returns {Array} Returns a new flattened array. * @example * * _.flatten([1, [2], [3, [[4]]]]); * // => [1, 2, 3, 4]; * * _.flatten([1, [2], [3, [[4]]]], true); * // => [1, 2, 3, [[4]]]; * * var characters = [ * { 'name': 'barney', 'age': 30, 'pets': ['hoppy'] }, * { 'name': 'fred', 'age': 40, 'pets': ['baby puss', 'dino'] } * ]; * * // using "_.pluck" callback shorthand * _.flatten(characters, 'pets'); * // => ['hoppy', 'baby puss', 'dino'] */ function flatten(array, isShallow) { return baseFlatten(array, isShallow); } /** * Gets the index at which the first occurrence of `value` is found using * strict equality for comparisons, i.e. `===`. If the array is already sorted * providing `true` for `fromIndex` will run a faster binary search. * * @static * @memberOf _ * @category Arrays * @param {Array} array The array to search. * @param {*} value The value to search for. * @param {boolean|number} [fromIndex=0] The index to search from or `true` * to perform a binary search on a sorted array. * @returns {number} Returns the index of the matched value or `-1`. * @example * * _.indexOf([1, 2, 3, 1, 2, 3], 2); * // => 1 * * _.indexOf([1, 2, 3, 1, 2, 3], 2, 3); * // => 4 * * _.indexOf([1, 1, 2, 2, 3, 3], 2, true); * // => 2 */ function indexOf(array, value, fromIndex) { if (typeof fromIndex == 'number') { var length = array ? array.length : 0; fromIndex = (fromIndex < 0 ? nativeMax(0, length + fromIndex) : fromIndex || 0); } else if (fromIndex) { var index = sortedIndex(array, value); return array[index] === value ? index : -1; } return baseIndexOf(array, value, fromIndex); } /** * Gets all but the last element or last `n` elements of an array. If a * callback is provided elements at the end of the array are excluded from * the result as long as the callback returns truey. The callback is bound * to `thisArg` and invoked with three arguments; (value, index, array). * * If a property name is provided for `callback` the created "_.pluck" style * callback will return the property value of the given element. * * If an object is provided for `callback` the created "_.where" style callback * will return `true` for elements that have the properties of the given object, * else `false`. * * @static * @memberOf _ * @category Arrays * @param {Array} array The array to query. * @param {Function|Object|number|string} [callback=1] The function called * per element or the number of elements to exclude. If a property name or * object is provided it will be used to create a "_.pluck" or "_.where" * style callback, respectively. * @param {*} [thisArg] The `this` binding of `callback`. * @returns {Array} Returns a slice of `array`. * @example * * _.initial([1, 2, 3]); * // => [1, 2] * * _.initial([1, 2, 3], 2); * // => [1] * * _.initial([1, 2, 3], function(num) { * return num > 1; * }); * // => [1] * * var characters = [ * { 'name': 'barney', 'blocked': false, 'employer': 'slate' }, * { 'name': 'fred', 'blocked': true, 'employer': 'slate' }, * { 'name': 'pebbles', 'blocked': true, 'employer': 'na' } * ]; * * // using "_.pluck" callback shorthand * _.initial(characters, 'blocked'); * // => [{ 'name': 'barney', 'blocked': false, 'employer': 'slate' }] * * // using "_.where" callback shorthand * _.pluck(_.initial(characters, { 'employer': 'na' }), 'name'); * // => ['barney', 'fred'] */ function initial(array, callback, thisArg) { var n = 0, length = array ? array.length : 0; if (typeof callback != 'number' && callback != null) { var index = length; callback = createCallback(callback, thisArg, 3); while (index-- && callback(array[index], index, array)) { n++; } } else { n = (callback == null || thisArg) ? 1 : callback || n; } return slice(array, 0, nativeMin(nativeMax(0, length - n), length)); } /** * Creates an array of unique values present in all provided arrays using * strict equality for comparisons, i.e. `===`. * * @static * @memberOf _ * @category Arrays * @param {...Array} [array] The arrays to inspect. * @returns {Array} Returns an array of shared values. * @example * * _.intersection([1, 2, 3], [5, 2, 1, 4], [2, 1]); * // => [1, 2] */ function intersection() { var args = [], argsIndex = -1, argsLength = arguments.length; while (++argsIndex < argsLength) { var value = arguments[argsIndex]; if (isArray(value) || isArguments(value)) { args.push(value); } } var array = args[0], index = -1, indexOf = getIndexOf(), length = array ? array.length : 0, result = []; outer: while (++index < length) { value = array[index]; if (indexOf(result, value) < 0) { var argsIndex = argsLength; while (--argsIndex) { if (indexOf(args[argsIndex], value) < 0) { continue outer; } } result.push(value); } } return result; } /** * Gets the last element or last `n` elements of an array. If a callback is * provided elements at the end of the array are returned as long as the * callback returns truey. The callback is bound to `thisArg` and invoked * with three arguments; (value, index, array). * * If a property name is provided for `callback` the created "_.pluck" style * callback will return the property value of the given element. * * If an object is provided for `callback` the created "_.where" style callback * will return `true` for elements that have the properties of the given object, * else `false`. * * @static * @memberOf _ * @category Arrays * @param {Array} array The array to query. * @param {Function|Object|number|string} [callback] The function called * per element or the number of elements to return. If a property name or * object is provided it will be used to create a "_.pluck" or "_.where" * style callback, respectively. * @param {*} [thisArg] The `this` binding of `callback`. * @returns {*} Returns the last element(s) of `array`. * @example * * _.last([1, 2, 3]); * // => 3 * * _.last([1, 2, 3], 2); * // => [2, 3] * * _.last([1, 2, 3], function(num) { * return num > 1; * }); * // => [2, 3] * * var characters = [ * { 'name': 'barney', 'blocked': false, 'employer': 'slate' }, * { 'name': 'fred', 'blocked': true, 'employer': 'slate' }, * { 'name': 'pebbles', 'blocked': true, 'employer': 'na' } * ]; * * // using "_.pluck" callback shorthand * _.pluck(_.last(characters, 'blocked'), 'name'); * // => ['fred', 'pebbles'] * * // using "_.where" callback shorthand * _.last(characters, { 'employer': 'na' }); * // => [{ 'name': 'pebbles', 'blocked': true, 'employer': 'na' }] */ function last(array, callback, thisArg) { var n = 0, length = array ? array.length : 0; if (typeof callback != 'number' && callback != null) { var index = length; callback = createCallback(callback, thisArg, 3); while (index-- && callback(array[index], index, array)) { n++; } } else { n = callback; if (n == null || thisArg) { return array ? array[length - 1] : undefined; } } return slice(array, nativeMax(0, length - n)); } /** * Gets the index at which the last occurrence of `value` is found using strict * equality for comparisons, i.e. `===`. If `fromIndex` is negative, it is used * as the offset from the end of the collection. * * If a property name is provided for `callback` the created "_.pluck" style * callback will return the property value of the given element. * * If an object is provided for `callback` the created "_.where" style callback * will return `true` for elements that have the properties of the given object, * else `false`. * * @static * @memberOf _ * @category Arrays * @param {Array} array The array to search. * @param {*} value The value to search for. * @param {number} [fromIndex=array.length-1] The index to search from. * @returns {number} Returns the index of the matched value or `-1`. * @example * * _.lastIndexOf([1, 2, 3, 1, 2, 3], 2); * // => 4 * * _.lastIndexOf([1, 2, 3, 1, 2, 3], 2, 3); * // => 1 */ function lastIndexOf(array, value, fromIndex) { var index = array ? array.length : 0; if (typeof fromIndex == 'number') { index = (fromIndex < 0 ? nativeMax(0, index + fromIndex) : nativeMin(fromIndex, index - 1)) + 1; } while (index--) { if (array[index] === value) { return index; } } return -1; } /** * Creates an array of numbers (positive and/or negative) progressing from * `start` up to but not including `end`. If `start` is less than `stop` a * zero-length range is created unless a negative `step` is specified. * * @static * @memberOf _ * @category Arrays * @param {number} [start=0] The start of the range. * @param {number} end The end of the range. * @param {number} [step=1] The value to increment or decrement by. * @returns {Array} Returns a new range array. * @example * * _.range(4); * // => [0, 1, 2, 3] * * _.range(1, 5); * // => [1, 2, 3, 4] * * _.range(0, 20, 5); * // => [0, 5, 10, 15] * * _.range(0, -4, -1); * // => [0, -1, -2, -3] * * _.range(1, 4, 0); * // => [1, 1, 1] * * _.range(0); * // => [] */ function range(start, end, step) { start = +start || 0; step = (+step || 1); if (end == null) { end = start; start = 0; } // use `Array(length)` so engines like Chakra and V8 avoid slower modes // http://youtu.be/XAqIpGU8ZZk#t=17m25s var index = -1, length = nativeMax(0, ceil((end - start) / step)), result = Array(length); while (++index < length) { result[index] = start; start += step; } return result; } /** * The opposite of `_.initial` this method gets all but the first element or * first `n` elements of an array. If a callback function is provided elements * at the beginning of the array are excluded from the result as long as the * callback returns truey. The callback is bound to `thisArg` and invoked * with three arguments; (value, index, array). * * If a property name is provided for `callback` the created "_.pluck" style * callback will return the property value of the given element. * * If an object is provided for `callback` the created "_.where" style callback * will return `true` for elements that have the properties of the given object, * else `false`. * * @static * @memberOf _ * @alias drop, tail * @category Arrays * @param {Array} array The array to query. * @param {Function|Object|number|string} [callback=1] The function called * per element or the number of elements to exclude. If a property name or * object is provided it will be used to create a "_.pluck" or "_.where" * style callback, respectively. * @param {*} [thisArg] The `this` binding of `callback`. * @returns {Array} Returns a slice of `array`. * @example * * _.rest([1, 2, 3]); * // => [2, 3] * * _.rest([1, 2, 3], 2); * // => [3] * * _.rest([1, 2, 3], function(num) { * return num < 3; * }); * // => [3] * * var characters = [ * { 'name': 'barney', 'blocked': true, 'employer': 'slate' }, * { 'name': 'fred', 'blocked': false, 'employer': 'slate' }, * { 'name': 'pebbles', 'blocked': true, 'employer': 'na' } * ]; * * // using "_.pluck" callback shorthand * _.pluck(_.rest(characters, 'blocked'), 'name'); * // => ['fred', 'pebbles'] * * // using "_.where" callback shorthand * _.rest(characters, { 'employer': 'slate' }); * // => [{ 'name': 'pebbles', 'blocked': true, 'employer': 'na' }] */ function rest(array, callback, thisArg) { if (typeof callback != 'number' && callback != null) { var n = 0, index = -1, length = array ? array.length : 0; callback = createCallback(callback, thisArg, 3); while (++index < length && callback(array[index], index, array)) { n++; } } else { n = (callback == null || thisArg) ? 1 : nativeMax(0, callback); } return slice(array, n); } /** * Uses a binary search to determine the smallest index at which a value * should be inserted into a given sorted array in order to maintain the sort * order of the array. If a callback is provided it will be executed for * `value` and each element of `array` to compute their sort ranking. The * callback is bound to `thisArg` and invoked with one argument; (value). * * If a property name is provided for `callback` the created "_.pluck" style * callback will return the property value of the given element. * * If an object is provided for `callback` the created "_.where" style callback * will return `true` for elements that have the properties of the given object, * else `false`. * * @static * @memberOf _ * @category Arrays * @param {Array} array The array to inspect. * @param {*} value The value to evaluate. * @param {Function|Object|string} [callback=identity] The function called * per iteration. If a property name or object is provided it will be used * to create a "_.pluck" or "_.where" style callback, respectively. * @param {*} [thisArg] The `this` binding of `callback`. * @returns {number} Returns the index at which `value` should be inserted * into `array`. * @example * * _.sortedIndex([20, 30, 50], 40); * // => 2 * * // using "_.pluck" callback shorthand * _.sortedIndex([{ 'x': 20 }, { 'x': 30 }, { 'x': 50 }], { 'x': 40 }, 'x'); * // => 2 * * var dict = { * 'wordToNumber': { 'twenty': 20, 'thirty': 30, 'fourty': 40, 'fifty': 50 } * }; * * _.sortedIndex(['twenty', 'thirty', 'fifty'], 'fourty', function(word) { * return dict.wordToNumber[word]; * }); * // => 2 * * _.sortedIndex(['twenty', 'thirty', 'fifty'], 'fourty', function(word) { * return this.wordToNumber[word]; * }, dict); * // => 2 */ function sortedIndex(array, value, callback, thisArg) { var low = 0, high = array ? array.length : low; // explicitly reference `identity` for better inlining in Firefox callback = callback ? createCallback(callback, thisArg, 1) : identity; value = callback(value); while (low < high) { var mid = (low + high) >>> 1; (callback(array[mid]) < value) ? low = mid + 1 : high = mid; } return low; } /** * Creates an array of unique values, in order, of the provided arrays using * strict equality for comparisons, i.e. `===`. * * @static * @memberOf _ * @category Arrays * @param {...Array} [array] The arrays to inspect. * @returns {Array} Returns an array of combined values. * @example * * _.union([1, 2, 3], [5, 2, 1, 4], [2, 1]); * // => [1, 2, 3, 5, 4] */ function union() { return baseUniq(baseFlatten(arguments, true, true)); } /** * Creates a duplicate-value-free version of an array using strict equality * for comparisons, i.e. `===`. If the array is sorted, providing * `true` for `isSorted` will use a faster algorithm. If a callback is provided * each element of `array` is passed through the callback before uniqueness * is computed. The callback is bound to `thisArg` and invoked with three * arguments; (value, index, array). * * If a property name is provided for `callback` the created "_.pluck" style * callback will return the property value of the given element. * * If an object is provided for `callback` the created "_.where" style callback * will return `true` for elements that have the properties of the given object, * else `false`. * * @static * @memberOf _ * @alias unique * @category Arrays * @param {Array} array The array to process. * @param {boolean} [isSorted=false] A flag to indicate that `array` is sorted. * @param {Function|Object|string} [callback=identity] The function called * per iteration. If a property name or object is provided it will be used * to create a "_.pluck" or "_.where" style callback, respectively. * @param {*} [thisArg] The `this` binding of `callback`. * @returns {Array} Returns a duplicate-value-free array. * @example * * _.uniq([1, 2, 1, 3, 1]); * // => [1, 2, 3] * * _.uniq([1, 1, 2, 2, 3], true); * // => [1, 2, 3] * * _.uniq(['A', 'b', 'C', 'a', 'B', 'c'], function(letter) { return letter.toLowerCase(); }); * // => ['A', 'b', 'C'] * * _.uniq([1, 2.5, 3, 1.5, 2, 3.5], function(num) { return this.floor(num); }, Math); * // => [1, 2.5, 3] * * // using "_.pluck" callback shorthand * _.uniq([{ 'x': 1 }, { 'x': 2 }, { 'x': 1 }], 'x'); * // => [{ 'x': 1 }, { 'x': 2 }] */ function uniq(array, isSorted, callback, thisArg) { // juggle arguments if (typeof isSorted != 'boolean' && isSorted != null) { thisArg = callback; callback = (typeof isSorted != 'function' && thisArg && thisArg[isSorted] === array) ? null : isSorted; isSorted = false; } if (callback != null) { callback = createCallback(callback, thisArg, 3); } return baseUniq(array, isSorted, callback); } /** * Creates an array excluding all provided values using strict equality for * comparisons, i.e. `===`. * * @static * @memberOf _ * @category Arrays * @param {Array} array The array to filter. * @param {...*} [value] The values to exclude. * @returns {Array} Returns a new array of filtered values. * @example * * _.without([1, 2, 1, 0, 3, 1, 4], 0, 1); * // => [2, 3, 4] */ function without(array) { return baseDifference(array, slice(arguments, 1)); } /** * Creates an array of grouped elements, the first of which contains the first * elements of the given arrays, the second of which contains the second * elements of the given arrays, and so on. * * @static * @memberOf _ * @alias unzip * @category Arrays * @param {...Array} [array] Arrays to process. * @returns {Array} Returns a new array of grouped elements. * @example * * _.zip(['fred', 'barney'], [30, 40], [true, false]); * // => [['fred', 30, true], ['barney', 40, false]] */ function zip() { var index = -1, length = max(pluck(arguments, 'length')), result = Array(length < 0 ? 0 : length); while (++index < length) { result[index] = pluck(arguments, index); } return result; } /** * Creates an object composed from arrays of `keys` and `values`. Provide * either a single two dimensional array, i.e. `[[key1, value1], [key2, value2]]` * or two arrays, one of `keys` and one of corresponding `values`. * * @static * @memberOf _ * @alias object * @category Arrays * @param {Array} keys The array of keys. * @param {Array} [values=[]] The array of values. * @returns {Object} Returns an object composed of the given keys and * corresponding values. * @example * * _.zipObject(['fred', 'barney'], [30, 40]); * // => { 'fred': 30, 'barney': 40 } */ function zipObject(keys, values) { var index = -1, length = keys ? keys.length : 0, result = {}; if (!values && length && !isArray(keys[0])) { values = []; } while (++index < length) { var key = keys[index]; if (values) { result[key] = values[index]; } else if (key) { result[key[0]] = key[1]; } } return result; } /*--------------------------------------------------------------------------*/ /** * Creates a function that executes `func`, with the `this` binding and * arguments of the created function, only after being called `n` times. * * @static * @memberOf _ * @category Functions * @param {number} n The number of times the function must be called before * `func` is executed. * @param {Function} func The function to restrict. * @returns {Function} Returns the new restricted function. * @example * * var saves = ['profile', 'settings']; * * var done = _.after(saves.length, function() { * console.log('Done saving!'); * }); * * _.forEach(saves, function(type) { * asyncSave({ 'type': type, 'complete': done }); * }); * // => logs 'Done saving!', after all saves have completed */ function after(n, func) { if (!isFunction(func)) { throw new TypeError; } return function() { if (--n < 1) { return func.apply(this, arguments); } }; } /** * Creates a function that, when called, invokes `func` with the `this` * binding of `thisArg` and prepends any additional `bind` arguments to those * provided to the bound function. * * @static * @memberOf _ * @category Functions * @param {Function} func The function to bind. * @param {*} [thisArg] The `this` binding of `func`. * @param {...*} [arg] Arguments to be partially applied. * @returns {Function} Returns the new bound function. * @example * * var func = function(greeting) { * return greeting + ' ' + this.name; * }; * * func = _.bind(func, { 'name': 'fred' }, 'hi'); * func(); * // => 'hi fred' */ function bind(func, thisArg) { return arguments.length > 2 ? createWrapper(func, 17, slice(arguments, 2), null, thisArg) : createWrapper(func, 1, null, null, thisArg); } /** * Binds methods of an object to the object itself, overwriting the existing * method. Method names may be specified as individual arguments or as arrays * of method names. If no method names are provided all the function properties * of `object` will be bound. * * @static * @memberOf _ * @category Functions * @param {Object} object The object to bind and assign the bound methods to. * @param {...string} [methodName] The object method names to * bind, specified as individual method names or arrays of method names. * @returns {Object} Returns `object`. * @example * * var view = { * 'label': 'docs', * 'onClick': function() { console.log('clicked ' + this.label); } * }; * * _.bindAll(view); * jQuery('#docs').on('click', view.onClick); * // => logs 'clicked docs', when the button is clicked */ function bindAll(object) { var funcs = arguments.length > 1 ? baseFlatten(arguments, true, false, 1) : functions(object), index = -1, length = funcs.length; while (++index < length) { var key = funcs[index]; object[key] = createWrapper(object[key], 1, null, null, object); } return object; } /** * Creates a function that is the composition of the provided functions, * where each function consumes the return value of the function that follows. * For example, composing the functions `f()`, `g()`, and `h()` produces `f(g(h()))`. * Each function is executed with the `this` binding of the composed function. * * @static * @memberOf _ * @category Functions * @param {...Function} [func] Functions to compose. * @returns {Function} Returns the new composed function. * @example * * var realNameMap = { * 'pebbles': 'penelope' * }; * * var format = function(name) { * name = realNameMap[name.toLowerCase()] || name; * return name.charAt(0).toUpperCase() + name.slice(1).toLowerCase(); * }; * * var greet = function(formatted) { * return 'Hiya ' + formatted + '!'; * }; * * var welcome = _.compose(greet, format); * welcome('pebbles'); * // => 'Hiya Penelope!' */ function compose() { var funcs = arguments, length = funcs.length; while (length--) { if (!isFunction(funcs[length])) { throw new TypeError; } } return function() { var args = arguments, length = funcs.length; while (length--) { args = [funcs[length].apply(this, args)]; } return args[0]; }; } /** * Creates a function that will delay the execution of `func` until after * `wait` milliseconds have elapsed since the last time it was invoked. * Provide an options object to indicate that `func` should be invoked on * the leading and/or trailing edge of the `wait` timeout. Subsequent calls * to the debounced function will return the result of the last `func` call. * * Note: If `leading` and `trailing` options are `true` `func` will be called * on the trailing edge of the timeout only if the the debounced function is * invoked more than once during the `wait` timeout. * * @static * @memberOf _ * @category Functions * @param {Function} func The function to debounce. * @param {number} wait The number of milliseconds to delay. * @param {Object} [options] The options object. * @param {boolean} [options.leading=false] Specify execution on the leading edge of the timeout. * @param {number} [options.maxWait] The maximum time `func` is allowed to be delayed before it's called. * @param {boolean} [options.trailing=true] Specify execution on the trailing edge of the timeout. * @returns {Function} Returns the new debounced function. * @example * * // avoid costly calculations while the window size is in flux * var lazyLayout = _.debounce(calculateLayout, 150); * jQuery(window).on('resize', lazyLayout); * * // execute `sendMail` when the click event is fired, debouncing subsequent calls * jQuery('#postbox').on('click', _.debounce(sendMail, 300, { * 'leading': true, * 'trailing': false * }); * * // ensure `batchLog` is executed once after 1 second of debounced calls * var source = new EventSource('/stream'); * source.addEventListener('message', _.debounce(batchLog, 250, { * 'maxWait': 1000 * }, false); */ function debounce(func, wait, options) { var args, maxTimeoutId, result, stamp, thisArg, timeoutId, trailingCall, lastCalled = 0, maxWait = false, trailing = true; if (!isFunction(func)) { throw new TypeError; } wait = nativeMax(0, wait) || 0; if (options === true) { var leading = true; trailing = false; } else if (isObject(options)) { leading = options.leading; maxWait = 'maxWait' in options && (nativeMax(wait, options.maxWait) || 0); trailing = 'trailing' in options ? options.trailing : trailing; } var delayed = function() { var remaining = wait - (now() - stamp); if (remaining <= 0) { if (maxTimeoutId) { clearTimeout(maxTimeoutId); } var isCalled = trailingCall; maxTimeoutId = timeoutId = trailingCall = undefined; if (isCalled) { lastCalled = now(); result = func.apply(thisArg, args); if (!timeoutId && !maxTimeoutId) { args = thisArg = null; } } } else { timeoutId = setTimeout(delayed, remaining); } }; var maxDelayed = function() { if (timeoutId) { clearTimeout(timeoutId); } maxTimeoutId = timeoutId = trailingCall = undefined; if (trailing || (maxWait !== wait)) { lastCalled = now(); result = func.apply(thisArg, args); if (!timeoutId && !maxTimeoutId) { args = thisArg = null; } } }; return function() { args = arguments; stamp = now(); thisArg = this; trailingCall = trailing && (timeoutId || !leading); if (maxWait === false) { var leadingCall = leading && !timeoutId; } else { if (!maxTimeoutId && !leading) { lastCalled = stamp; } var remaining = maxWait - (stamp - lastCalled), isCalled = remaining <= 0; if (isCalled) { if (maxTimeoutId) { maxTimeoutId = clearTimeout(maxTimeoutId); } lastCalled = stamp; result = func.apply(thisArg, args); } else if (!maxTimeoutId) { maxTimeoutId = setTimeout(maxDelayed, remaining); } } if (isCalled && timeoutId) { timeoutId = clearTimeout(timeoutId); } else if (!timeoutId && wait !== maxWait) { timeoutId = setTimeout(delayed, wait); } if (leadingCall) { isCalled = true; result = func.apply(thisArg, args); } if (isCalled && !timeoutId && !maxTimeoutId) { args = thisArg = null; } return result; }; } /** * Defers executing the `func` function until the current call stack has cleared. * Additional arguments will be provided to `func` when it is invoked. * * @static * @memberOf _ * @category Functions * @param {Function} func The function to defer. * @param {...*} [arg] Arguments to invoke the function with. * @returns {number} Returns the timer id. * @example * * _.defer(function(text) { console.log(text); }, 'deferred'); * // logs 'deferred' after one or more milliseconds */ function defer(func) { if (!isFunction(func)) { throw new TypeError; } var args = slice(arguments, 1); return setTimeout(function() { func.apply(undefined, args); }, 1); } /** * Executes the `func` function after `wait` milliseconds. Additional arguments * will be provided to `func` when it is invoked. * * @static * @memberOf _ * @category Functions * @param {Function} func The function to delay. * @param {number} wait The number of milliseconds to delay execution. * @param {...*} [arg] Arguments to invoke the function with. * @returns {number} Returns the timer id. * @example * * _.delay(function(text) { console.log(text); }, 1000, 'later'); * // => logs 'later' after one second */ function delay(func, wait) { if (!isFunction(func)) { throw new TypeError; } var args = slice(arguments, 2); return setTimeout(function() { func.apply(undefined, args); }, wait); } /** * Creates a function that memoizes the result of `func`. If `resolver` is * provided it will be used to determine the cache key for storing the result * based on the arguments provided to the memoized function. By default, the * first argument provided to the memoized function is used as the cache key. * The `func` is executed with the `this` binding of the memoized function. * The result cache is exposed as the `cache` property on the memoized function. * * @static * @memberOf _ * @category Functions * @param {Function} func The function to have its output memoized. * @param {Function} [resolver] A function used to resolve the cache key. * @returns {Function} Returns the new memoizing function. * @example * * var fibonacci = _.memoize(function(n) { * return n < 2 ? n : fibonacci(n - 1) + fibonacci(n - 2); * }); * * fibonacci(9) * // => 34 * * var data = { * 'fred': { 'name': 'fred', 'age': 40 }, * 'pebbles': { 'name': 'pebbles', 'age': 1 } * }; * * // modifying the result cache * var get = _.memoize(function(name) { return data[name]; }, _.identity); * get('pebbles'); * // => { 'name': 'pebbles', 'age': 1 } * * get.cache.pebbles.name = 'penelope'; * get('pebbles'); * // => { 'name': 'penelope', 'age': 1 } */ function memoize(func, resolver) { var cache = {}; return function() { var key = resolver ? resolver.apply(this, arguments) : keyPrefix + arguments[0]; return hasOwnProperty.call(cache, key) ? cache[key] : (cache[key] = func.apply(this, arguments)); }; } /** * Creates a function that is restricted to execute `func` once. Repeat calls to * the function will return the value of the first call. The `func` is executed * with the `this` binding of the created function. * * @static * @memberOf _ * @category Functions * @param {Function} func The function to restrict. * @returns {Function} Returns the new restricted function. * @example * * var initialize = _.once(createApplication); * initialize(); * initialize(); * // `initialize` executes `createApplication` once */ function once(func) { var ran, result; if (!isFunction(func)) { throw new TypeError; } return function() { if (ran) { return result; } ran = true; result = func.apply(this, arguments); // clear the `func` variable so the function may be garbage collected func = null; return result; }; } /** * Creates a function that, when called, invokes `func` with any additional * `partial` arguments prepended to those provided to the new function. This * method is similar to `_.bind` except it does **not** alter the `this` binding. * * @static * @memberOf _ * @category Functions * @param {Function} func The function to partially apply arguments to. * @param {...*} [arg] Arguments to be partially applied. * @returns {Function} Returns the new partially applied function. * @example * * var greet = function(greeting, name) { return greeting + ' ' + name; }; * var hi = _.partial(greet, 'hi'); * hi('fred'); * // => 'hi fred' */ function partial(func) { return createWrapper(func, 16, slice(arguments, 1)); } /** * Creates a function that, when executed, will only call the `func` function * at most once per every `wait` milliseconds. Provide an options object to * indicate that `func` should be invoked on the leading and/or trailing edge * of the `wait` timeout. Subsequent calls to the throttled function will * return the result of the last `func` call. * * Note: If `leading` and `trailing` options are `true` `func` will be called * on the trailing edge of the timeout only if the the throttled function is * invoked more than once during the `wait` timeout. * * @static * @memberOf _ * @category Functions * @param {Function} func The function to throttle. * @param {number} wait The number of milliseconds to throttle executions to. * @param {Object} [options] The options object. * @param {boolean} [options.leading=true] Specify execution on the leading edge of the timeout. * @param {boolean} [options.trailing=true] Specify execution on the trailing edge of the timeout. * @returns {Function} Returns the new throttled function. * @example * * // avoid excessively updating the position while scrolling * var throttled = _.throttle(updatePosition, 100); * jQuery(window).on('scroll', throttled); * * // execute `renewToken` when the click event is fired, but not more than once every 5 minutes * jQuery('.interactive').on('click', _.throttle(renewToken, 300000, { * 'trailing': false * })); */ function throttle(func, wait, options) { var leading = true, trailing = true; if (!isFunction(func)) { throw new TypeError; } if (options === false) { leading = false; } else if (isObject(options)) { leading = 'leading' in options ? options.leading : leading; trailing = 'trailing' in options ? options.trailing : trailing; } options = {}; options.leading = leading; options.maxWait = wait; options.trailing = trailing; return debounce(func, wait, options); } /** * Creates a function that provides `value` to the wrapper function as its * first argument. Additional arguments provided to the function are appended * to those provided to the wrapper function. The wrapper is executed with * the `this` binding of the created function. * * @static * @memberOf _ * @category Functions * @param {*} value The value to wrap. * @param {Function} wrapper The wrapper function. * @returns {Function} Returns the new function. * @example * * var p = _.wrap(_.escape, function(func, text) { * return '<p>' + func(text) + '</p>'; * }); * * p('Fred, Wilma, & Pebbles'); * // => '<p>Fred, Wilma, &amp; Pebbles</p>' */ function wrap(value, wrapper) { return createWrapper(wrapper, 16, [value]); } /*--------------------------------------------------------------------------*/ /** * Produces a callback bound to an optional `thisArg`. If `func` is a property * name the created callback will return the property value for a given element. * If `func` is an object the created callback will return `true` for elements * that contain the equivalent object properties, otherwise it will return `false`. * * @static * @memberOf _ * @category Utilities * @param {*} [func=identity] The value to convert to a callback. * @param {*} [thisArg] The `this` binding of the created callback. * @param {number} [argCount] The number of arguments the callback accepts. * @returns {Function} Returns a callback function. * @example * * var characters = [ * { 'name': 'barney', 'age': 36 }, * { 'name': 'fred', 'age': 40 } * ]; * * // wrap to create custom callback shorthands * _.createCallback = _.wrap(_.createCallback, function(func, callback, thisArg) { * var match = /^(.+?)__([gl]t)(.+)$/.exec(callback); * return !match ? func(callback, thisArg) : function(object) { * return match[2] == 'gt' ? object[match[1]] > match[3] : object[match[1]] < match[3]; * }; * }); * * _.filter(characters, 'age__gt38'); * // => [{ 'name': 'fred', 'age': 40 }] */ function createCallback(func, thisArg, argCount) { var type = typeof func; if (func == null || type == 'function') { return baseCreateCallback(func, thisArg, argCount); } // handle "_.pluck" style callback shorthands if (type != 'object') { return property(func); } var props = keys(func); return function(object) { var length = props.length, result = false; while (length--) { if (!(result = object[props[length]] === func[props[length]])) { break; } } return result; }; } /** * Converts the characters `&`, `<`, `>`, `"`, and `'` in `string` to their * corresponding HTML entities. * * @static * @memberOf _ * @category Utilities * @param {string} string The string to escape. * @returns {string} Returns the escaped string. * @example * * _.escape('Fred, Wilma, & Pebbles'); * // => 'Fred, Wilma, &amp; Pebbles' */ function escape(string) { return string == null ? '' : String(string).replace(reUnescapedHtml, escapeHtmlChar); } /** * This method returns the first argument provided to it. * * @static * @memberOf _ * @category Utilities * @param {*} value Any value. * @returns {*} Returns `value`. * @example * * var object = { 'name': 'fred' }; * _.identity(object) === object; * // => true */ function identity(value) { return value; } /** * Adds function properties of a source object to the destination object. * If `object` is a function methods will be added to its prototype as well. * * @static * @memberOf _ * @category Utilities * @param {Function|Object} [object=lodash] object The destination object. * @param {Object} source The object of functions to add. * @param {Object} [options] The options object. * @param {boolean} [options.chain=true] Specify whether the functions added are chainable. * @example * * function capitalize(string) { * return string.charAt(0).toUpperCase() + string.slice(1).toLowerCase(); * } * * _.mixin({ 'capitalize': capitalize }); * _.capitalize('fred'); * // => 'Fred' * * _('fred').capitalize().value(); * // => 'Fred' * * _.mixin({ 'capitalize': capitalize }, { 'chain': false }); * _('fred').capitalize(); * // => 'Fred' */ function mixin(object) { forEach(functions(object), function(methodName) { var func = lodash[methodName] = object[methodName]; lodash.prototype[methodName] = function() { var args = [this.__wrapped__]; push.apply(args, arguments); var result = func.apply(lodash, args); return this.__chain__ ? new lodashWrapper(result, true) : result; }; }); } /** * Reverts the '_' variable to its previous value and returns a reference to * the `lodash` function. * * @static * @memberOf _ * @category Utilities * @returns {Function} Returns the `lodash` function. * @example * * var lodash = _.noConflict(); */ function noConflict() { root._ = oldDash; return this; } /** * A no-operation function. * * @static * @memberOf _ * @category Utilities * @example * * var object = { 'name': 'fred' }; * _.noop(object) === undefined; * // => true */ function noop() { // no operation performed } /** * Gets the number of milliseconds that have elapsed since the Unix epoch * (1 January 1970 00:00:00 UTC). * * @static * @memberOf _ * @category Utilities * @example * * var stamp = _.now(); * _.defer(function() { console.log(_.now() - stamp); }); * // => logs the number of milliseconds it took for the deferred function to be called */ var now = isNative(now = Date.now) && now || function() { return new Date().getTime(); }; /** * Creates a "_.pluck" style function, which returns the `key` value of a * given object. * * @static * @memberOf _ * @category Utilities * @param {string} key The name of the property to retrieve. * @returns {Function} Returns the new function. * @example * * var characters = [ * { 'name': 'fred', 'age': 40 }, * { 'name': 'barney', 'age': 36 } * ]; * * var getName = _.property('name'); * * _.map(characters, getName); * // => ['barney', 'fred'] * * _.sortBy(characters, getName); * // => [{ 'name': 'barney', 'age': 36 }, { 'name': 'fred', 'age': 40 }] */ function property(key) { return function(object) { return object[key]; }; } /** * Produces a random number between `min` and `max` (inclusive). If only one * argument is provided a number between `0` and the given number will be * returned. If `floating` is truey or either `min` or `max` are floats a * floating-point number will be returned instead of an integer. * * @static * @memberOf _ * @category Utilities * @param {number} [min=0] The minimum possible value. * @param {number} [max=1] The maximum possible value. * @param {boolean} [floating=false] Specify returning a floating-point number. * @returns {number} Returns a random number. * @example * * _.random(0, 5); * // => an integer between 0 and 5 * * _.random(5); * // => also an integer between 0 and 5 * * _.random(5, true); * // => a floating-point number between 0 and 5 * * _.random(1.2, 5.2); * // => a floating-point number between 1.2 and 5.2 */ function random(min, max) { if (min == null && max == null) { max = 1; } min = +min || 0; if (max == null) { max = min; min = 0; } else { max = +max || 0; } return min + floor(nativeRandom() * (max - min + 1)); } /** * Resolves the value of property `key` on `object`. If `key` is a function * it will be invoked with the `this` binding of `object` and its result returned, * else the property value is returned. If `object` is falsey then `undefined` * is returned. * * @static * @memberOf _ * @category Utilities * @param {Object} object The object to inspect. * @param {string} key The name of the property to resolve. * @returns {*} Returns the resolved value. * @example * * var object = { * 'cheese': 'crumpets', * 'stuff': function() { * return 'nonsense'; * } * }; * * _.result(object, 'cheese'); * // => 'crumpets' * * _.result(object, 'stuff'); * // => 'nonsense' */ function result(object, key) { if (object) { var value = object[key]; return isFunction(value) ? object[key]() : value; } } /** * A micro-templating method that handles arbitrary delimiters, preserves * whitespace, and correctly escapes quotes within interpolated code. * * Note: In the development build, `_.template` utilizes sourceURLs for easier * debugging. See http://www.html5rocks.com/en/tutorials/developertools/sourcemaps/#toc-sourceurl * * For more information on precompiling templates see: * http://lodash.com/custom-builds * * For more information on Chrome extension sandboxes see: * http://developer.chrome.com/stable/extensions/sandboxingEval.html * * @static * @memberOf _ * @category Utilities * @param {string} text The template text. * @param {Object} data The data object used to populate the text. * @param {Object} [options] The options object. * @param {RegExp} [options.escape] The "escape" delimiter. * @param {RegExp} [options.evaluate] The "evaluate" delimiter. * @param {Object} [options.imports] An object to import into the template as local variables. * @param {RegExp} [options.interpolate] The "interpolate" delimiter. * @param {string} [sourceURL] The sourceURL of the template's compiled source. * @param {string} [variable] The data object variable name. * @returns {Function|string} Returns a compiled function when no `data` object * is given, else it returns the interpolated text. * @example * * // using the "interpolate" delimiter to create a compiled template * var compiled = _.template('hello <%= name %>'); * compiled({ 'name': 'fred' }); * // => 'hello fred' * * // using the "escape" delimiter to escape HTML in data property values * _.template('<b><%- value %></b>', { 'value': '<script>' }); * // => '<b>&lt;script&gt;</b>' * * // using the "evaluate" delimiter to generate HTML * var list = '<% _.forEach(people, function(name) { %><li><%- name %></li><% }); %>'; * _.template(list, { 'people': ['fred', 'barney'] }); * // => '<li>fred</li><li>barney</li>' * * // using the ES6 delimiter as an alternative to the default "interpolate" delimiter * _.template('hello ${ name }', { 'name': 'pebbles' }); * // => 'hello pebbles' * * // using the internal `print` function in "evaluate" delimiters * _.template('<% print("hello " + name); %>!', { 'name': 'barney' }); * // => 'hello barney!' * * // using a custom template delimiters * _.templateSettings = { * 'interpolate': /{{([\s\S]+?)}}/g * }; * * _.template('hello {{ name }}!', { 'name': 'mustache' }); * // => 'hello mustache!' * * // using the `imports` option to import jQuery * var list = '<% jq.each(people, function(name) { %><li><%- name %></li><% }); %>'; * _.template(list, { 'people': ['fred', 'barney'] }, { 'imports': { 'jq': jQuery } }); * // => '<li>fred</li><li>barney</li>' * * // using the `sourceURL` option to specify a custom sourceURL for the template * var compiled = _.template('hello <%= name %>', null, { 'sourceURL': '/basic/greeting.jst' }); * compiled(data); * // => find the source of "greeting.jst" under the Sources tab or Resources panel of the web inspector * * // using the `variable` option to ensure a with-statement isn't used in the compiled template * var compiled = _.template('hi <%= data.name %>!', null, { 'variable': 'data' }); * compiled.source; * // => function(data) { * var __t, __p = '', __e = _.escape; * __p += 'hi ' + ((__t = ( data.name )) == null ? '' : __t) + '!'; * return __p; * } * * // using the `source` property to inline compiled templates for meaningful * // line numbers in error messages and a stack trace * fs.writeFileSync(path.join(cwd, 'jst.js'), '\ * var JST = {\ * "main": ' + _.template(mainText).source + '\ * };\ * '); */ function template(text, data, options) { var _ = lodash, settings = _.templateSettings; text = String(text || ''); options = defaults({}, options, settings); var index = 0, source = "__p += '", variable = options.variable; var reDelimiters = RegExp( (options.escape || reNoMatch).source + '|' + (options.interpolate || reNoMatch).source + '|' + (options.evaluate || reNoMatch).source + '|$' , 'g'); text.replace(reDelimiters, function(match, escapeValue, interpolateValue, evaluateValue, offset) { source += text.slice(index, offset).replace(reUnescapedString, escapeStringChar); if (escapeValue) { source += "' +\n_.escape(" + escapeValue + ") +\n'"; } if (evaluateValue) { source += "';\n" + evaluateValue + ";\n__p += '"; } if (interpolateValue) { source += "' +\n((__t = (" + interpolateValue + ")) == null ? '' : __t) +\n'"; } index = offset + match.length; return match; }); source += "';\n"; if (!variable) { variable = 'obj'; source = 'with (' + variable + ' || {}) {\n' + source + '\n}\n'; } source = 'function(' + variable + ') {\n' + "var __t, __p = '', __j = Array.prototype.join;\n" + "function print() { __p += __j.call(arguments, '') }\n" + source + 'return __p\n}'; try { var result = Function('_', 'return ' + source)(_); } catch(e) { e.source = source; throw e; } if (data) { return result(data); } result.source = source; return result; } /** * Executes the callback `n` times, returning an array of the results * of each callback execution. The callback is bound to `thisArg` and invoked * with one argument; (index). * * @static * @memberOf _ * @category Utilities * @param {number} n The number of times to execute the callback. * @param {Function} callback The function called per iteration. * @param {*} [thisArg] The `this` binding of `callback`. * @returns {Array} Returns an array of the results of each `callback` execution. * @example * * var diceRolls = _.times(3, _.partial(_.random, 1, 6)); * // => [3, 6, 4] * * _.times(3, function(n) { mage.castSpell(n); }); * // => calls `mage.castSpell(n)` three times, passing `n` of `0`, `1`, and `2` respectively * * _.times(3, function(n) { this.cast(n); }, mage); * // => also calls `mage.castSpell(n)` three times */ function times(n, callback, thisArg) { n = (n = +n) > -1 ? n : 0; var index = -1, result = Array(n); callback = baseCreateCallback(callback, thisArg, 1); while (++index < n) { result[index] = callback(index); } return result; } /** * The inverse of `_.escape` this method converts the HTML entities * `&amp;`, `&lt;`, `&gt;`, `&quot;`, and `&#39;` in `string` to their * corresponding characters. * * @static * @memberOf _ * @category Utilities * @param {string} string The string to unescape. * @returns {string} Returns the unescaped string. * @example * * _.unescape('Fred, Barney &amp; Pebbles'); * // => 'Fred, Barney & Pebbles' */ function unescape(string) { return string == null ? '' : String(string).replace(reEscapedHtml, unescapeHtmlChar); } /** * Generates a unique ID. If `prefix` is provided the ID will be appended to it. * * @static * @memberOf _ * @category Utilities * @param {string} [prefix] The value to prefix the ID with. * @returns {string} Returns the unique ID. * @example * * _.uniqueId('contact_'); * // => 'contact_104' * * _.uniqueId(); * // => '105' */ function uniqueId(prefix) { var id = ++idCounter + ''; return prefix ? prefix + id : id; } /*--------------------------------------------------------------------------*/ /** * Creates a `lodash` object that wraps the given value with explicit * method chaining enabled. * * @static * @memberOf _ * @category Chaining * @param {*} value The value to wrap. * @returns {Object} Returns the wrapper object. * @example * * var characters = [ * { 'name': 'barney', 'age': 36 }, * { 'name': 'fred', 'age': 40 }, * { 'name': 'pebbles', 'age': 1 } * ]; * * var youngest = _.chain(characters) * .sortBy('age') * .map(function(chr) { return chr.name + ' is ' + chr.age; }) * .first() * .value(); * // => 'pebbles is 1' */ function chain(value) { value = new lodashWrapper(value); value.__chain__ = true; return value; } /** * Invokes `interceptor` with the `value` as the first argument and then * returns `value`. The purpose of this method is to "tap into" a method * chain in order to perform operations on intermediate results within * the chain. * * @static * @memberOf _ * @category Chaining * @param {*} value The value to provide to `interceptor`. * @param {Function} interceptor The function to invoke. * @returns {*} Returns `value`. * @example * * _([1, 2, 3, 4]) * .tap(function(array) { array.pop(); }) * .reverse() * .value(); * // => [3, 2, 1] */ function tap(value, interceptor) { interceptor(value); return value; } /** * Enables explicit method chaining on the wrapper object. * * @name chain * @memberOf _ * @category Chaining * @returns {*} Returns the wrapper object. * @example * * var characters = [ * { 'name': 'barney', 'age': 36 }, * { 'name': 'fred', 'age': 40 } * ]; * * // without explicit chaining * _(characters).first(); * // => { 'name': 'barney', 'age': 36 } * * // with explicit chaining * _(characters).chain() * .first() * .pick('age') * .value(); * // => { 'age': 36 } */ function wrapperChain() { this.__chain__ = true; return this; } /** * Extracts the wrapped value. * * @name valueOf * @memberOf _ * @alias value * @category Chaining * @returns {*} Returns the wrapped value. * @example * * _([1, 2, 3]).valueOf(); * // => [1, 2, 3] */ function wrapperValueOf() { return this.__wrapped__; } /*--------------------------------------------------------------------------*/ // add functions that return wrapped values when chaining lodash.after = after; lodash.bind = bind; lodash.bindAll = bindAll; lodash.chain = chain; lodash.compact = compact; lodash.compose = compose; lodash.countBy = countBy; lodash.debounce = debounce; lodash.defaults = defaults; lodash.defer = defer; lodash.delay = delay; lodash.difference = difference; lodash.filter = filter; lodash.flatten = flatten; lodash.forEach = forEach; lodash.functions = functions; lodash.groupBy = groupBy; lodash.indexBy = indexBy; lodash.initial = initial; lodash.intersection = intersection; lodash.invert = invert; lodash.invoke = invoke; lodash.keys = keys; lodash.map = map; lodash.max = max; lodash.memoize = memoize; lodash.min = min; lodash.omit = omit; lodash.once = once; lodash.pairs = pairs; lodash.partial = partial; lodash.pick = pick; lodash.pluck = pluck; lodash.range = range; lodash.reject = reject; lodash.rest = rest; lodash.shuffle = shuffle; lodash.sortBy = sortBy; lodash.tap = tap; lodash.throttle = throttle; lodash.times = times; lodash.toArray = toArray; lodash.union = union; lodash.uniq = uniq; lodash.values = values; lodash.where = where; lodash.without = without; lodash.wrap = wrap; lodash.zip = zip; // add aliases lodash.collect = map; lodash.drop = rest; lodash.each = forEach; lodash.extend = assign; lodash.methods = functions; lodash.object = zipObject; lodash.select = filter; lodash.tail = rest; lodash.unique = uniq; /*--------------------------------------------------------------------------*/ // add functions that return unwrapped values when chaining lodash.clone = clone; lodash.contains = contains; lodash.escape = escape; lodash.every = every; lodash.find = find; lodash.has = has; lodash.identity = identity; lodash.indexOf = indexOf; lodash.isArguments = isArguments; lodash.isArray = isArray; lodash.isBoolean = isBoolean; lodash.isDate = isDate; lodash.isElement = isElement; lodash.isEmpty = isEmpty; lodash.isEqual = isEqual; lodash.isFinite = isFinite; lodash.isFunction = isFunction; lodash.isNaN = isNaN; lodash.isNull = isNull; lodash.isNumber = isNumber; lodash.isObject = isObject; lodash.isRegExp = isRegExp; lodash.isString = isString; lodash.isUndefined = isUndefined; lodash.lastIndexOf = lastIndexOf; lodash.mixin = mixin; lodash.noConflict = noConflict; lodash.random = random; lodash.reduce = reduce; lodash.reduceRight = reduceRight; lodash.result = result; lodash.size = size; lodash.some = some; lodash.sortedIndex = sortedIndex; lodash.template = template; lodash.unescape = unescape; lodash.uniqueId = uniqueId; // add aliases lodash.all = every; lodash.any = some; lodash.detect = find; lodash.findWhere = findWhere; lodash.foldl = reduce; lodash.foldr = reduceRight; lodash.include = contains; lodash.inject = reduce; /*--------------------------------------------------------------------------*/ // add functions capable of returning wrapped and unwrapped values when chaining lodash.first = first; lodash.last = last; lodash.sample = sample; // add aliases lodash.take = first; lodash.head = first; /*--------------------------------------------------------------------------*/ // add functions to `lodash.prototype` mixin(lodash); /** * The semantic version number. * * @static * @memberOf _ * @type string */ lodash.VERSION = '2.4.1'; // add "Chaining" functions to the wrapper lodash.prototype.chain = wrapperChain; lodash.prototype.value = wrapperValueOf; // add `Array` mutator functions to the wrapper forEach(['pop', 'push', 'reverse', 'shift', 'sort', 'splice', 'unshift'], function(methodName) { var func = arrayRef[methodName]; lodash.prototype[methodName] = function() { var value = this.__wrapped__; func.apply(value, arguments); // avoid array-like object bugs with `Array#shift` and `Array#splice` // in Firefox < 10 and IE < 9 if (!support.spliceObjects && value.length === 0) { delete value[0]; } return this; }; }); // add `Array` accessor functions to the wrapper forEach(['concat', 'join', 'slice'], function(methodName) { var func = arrayRef[methodName]; lodash.prototype[methodName] = function() { var value = this.__wrapped__, result = func.apply(value, arguments); if (this.__chain__) { result = new lodashWrapper(result); result.__chain__ = true; } return result; }; }); /*--------------------------------------------------------------------------*/ // some AMD build optimizers like r.js check for condition patterns like the following: if (typeof define == 'function' && typeof define.amd == 'object' && define.amd) { // Expose Lo-Dash to the global object even when an AMD loader is present in // case Lo-Dash is loaded with a RequireJS shim config. // See http://requirejs.org/docs/api.html#config-shim root._ = lodash; // define as an anonymous module so, through path mapping, it can be // referenced as the "underscore" module define(function() { return lodash; }); } // check for `exports` after `define` in case a build optimizer adds an `exports` object else if (freeExports && freeModule) { // in Node.js or RingoJS if (moduleExports) { (freeModule.exports = lodash)._ = lodash; } // in Narwhal or Rhino -require else { freeExports._ = lodash; } } else { // in a browser or Rhino root._ = lodash; } }.call(this));
kellyselden/cdnjs
ajax/libs/lodash.js/2.4.1/lodash.underscore.js
JavaScript
mit
159,528
webshims.register("form-fixrangechange",function(a){"use strict";var b={trigger:function(){b.blockElement&&(b.blockElement=!1,setTimeout(function(){b.requestedChange&&b.value!=b.requestedChange.value&&a(b.requestedChange).trigger("change"),b.value=!1},9))},lastValue:!1,updateInputValue:function(a){b.lastValue=a.target.value},triggerInput:function(c){b.lastValue!==!1&&b.lastValue!=c.target.value&&a(c.target).trigger("input")},inputTeardown:function(c){a(c.target).off("input",b.updateInputValue).off("blur",b.inputTeardown),b.lastValue=!1},inputSetup:function(c){"range"==c.target.type&&(b.inputTeardown(c),b.lastValue=c.target.value,a(c.target).on("input",b.updateInputValue).on("blur",b.inputTeardown))}};a.each([{name:"key",evt:"keyup"},{name:"mouse",evt:"mouseup"},{name:"touch",evt:"touchend"}],function(c,d){var e=(d.name+"Setup",d.name+"Commit");b[d.name+"Block"]=function(c){b.blockElement||"range"!=c.target.type||(b.blockElement=c.target,b.value=c.target.value,a(b.blockElement).off("blur",b.trigger).on("blur",b.trigger),a(document.body).off(d.evt,b[e]).on(d.evt,b[e]))},b[e]=function(){a(document.body).off(d.evt,b[e]),b.trigger()}}),a(document.body||"html").on({mousedown:b.mouseBlock,"keydown kepress":function(a){a.keyCode<45&&a.keyCode>30&&b.keyBlock(a)},touchstart:b.touchBlock,focusin:b.inputSetup}),a.extend(!0,a.event.special,{change:{handle:function(a){return a.isTrigger||b.blockElement!=a.target?(b.requestedChange==a.target&&(b.requestedChange=!1),void a.handleObj.handler.apply(this,arguments)):(b.requestedChange=a.target,b.triggerInput(a),!1)}},input:{handle:function(){var b,c,d=function(){c&&a(c).off("change",d),b=!1,c=!1},e=function(e){d(e),c=e.target,b=e.target.value,a(e.target).on("change",d)};return function(a){var d;if(!a.isTrigger&&"range"==a.target.type)if(c!=a.target)e(a);else if(c==a.target){if(b==(d=a.target.value))return!1;b=a.target.value}a.handleObj.handler.apply(this,arguments)}}()}})});
hasantayyar/cdnjs
ajax/libs/webshim/1.15.5/minified/shims/form-fixrangechange.js
JavaScript
mit
1,939
<?php namespace Intervention\Image; class Constraint { /** * Bit value of aspect ratio constraint */ const ASPECTRATIO = 1; /** * Bit value of upsize constraint */ const UPSIZE = 2; /** * Constraint size * * @var \Intervention\Image\Size */ private $size; /** * Integer value of fixed parameters * * @var integer */ private $fixed = 0; /** * Create a new constraint based on size * * @param Size $size */ public function __construct(Size $size) { $this->size = $size; } /** * Returns current size of constraint * * @return \Intervention\Image\Size */ public function getSize() { return $this->size; } /** * Fix the given argument in current constraint * @param integer $type * @return void */ public function fix($type) { $this->fixed = ($this->fixed & ~(1 << $type)) | (1 << $type); } /** * Checks if given argument is fixed in current constraint * * @param integer $type * @return boolean */ public function isFixed($type) { return (bool) ($this->fixed & (1 << $type)); } /** * Fixes aspect ratio in current constraint * * @return void */ public function aspectRatio() { $this->fix(self::ASPECTRATIO); } /** * Fixes possibility to size up in current constraint * * @return void */ public function upsize() { $this->fix(self::UPSIZE); } }
nhahv/image
src/Intervention/Image/Constraint.php
PHP
mit
1,615
/** * Locate the best instance of 'pattern' in 'text' using the Bitap algorithm. * * This method is a based on: Diff Match and Patch * http://code.google.com/p/google-diff-match-patch/ * Author: fraser@google.com (Neil Fraser) * Modifications by: l.vanegeraat@gmail.com (Luuk van Egeraat) * Plugin by: jonny.stromberg@gmail.com (Jonny Strömberg / @javve) * * Licensed under the Apache License * http://www.apache.org/licenses/LICENSE-2.0 * */ List.prototype.plugins.fuzzySearch = function(locals, options) { var self = this; var searchFunction = function(text, pattern, options) { // Aproximately where in the text is the pattern expected to be found? var Match_Location = options.location || 0; //Determines how close the match must be to the fuzzy location (specified above). An exact letter match which is 'distance' characters away from the fuzzy location would score as a complete mismatch. A distance of '0' requires the match be at the exact location specified, a threshold of '1000' would require a perfect match to be within 800 characters of the fuzzy location to be found using a 0.8 threshold. var Match_Distance = options.distance || 100; // At what point does the match algorithm give up. A threshold of '0.0' requires a perfect match (of both letters and location), a threshold of '1.0' would match anything. var Match_Threshold = options.threshold || 0.4; if (pattern === text) return true; // Exact match if (pattern.length > 32) return false; // This algorithm cannot be used // Set starting location at beginning text and initialise the alphabet. var loc = Match_Location, s = (function() { var q = {}; for (var i = 0; i < pattern.length; i++) { q[pattern.charAt(i)] = 0; } for (var i = 0; i < pattern.length; i++) { q[pattern.charAt(i)] |= 1 << (pattern.length - i - 1); } return q; }()); // Compute and return the score for a match with e errors and x location. // Accesses loc and pattern through being a closure. function match_bitapScore_(e, x) { var accuracy = e / pattern.length, proximity = Math.abs(loc - x); if (!Match_Distance) { // Dodge divide by zero error. return proximity ? 1.0 : accuracy; } return accuracy + (proximity / Match_Distance); } var score_threshold = Match_Threshold, // Highest score beyond which we give up. best_loc = text.indexOf(pattern, loc); // Is there a nearby exact match? (speedup) if (best_loc != -1) { score_threshold = Math.min(match_bitapScore_(0, best_loc), score_threshold); // What about in the other direction? (speedup) best_loc = text.lastIndexOf(pattern, loc + pattern.length); if (best_loc != -1) { score_threshold = Math.min(match_bitapScore_(0, best_loc), score_threshold); } } // Initialise the bit arrays. var matchmask = 1 << (pattern.length - 1); best_loc = -1; var bin_min, bin_mid; var bin_max = pattern.length + text.length; var last_rd; for (var d = 0; d < pattern.length; d++) { // Scan for the best match; each iteration allows for one more error. // Run a binary search to determine how far from 'loc' we can stray at this // error level. bin_min = 0; bin_mid = bin_max; while (bin_min < bin_mid) { if (match_bitapScore_(d, loc + bin_mid) <= score_threshold) { bin_min = bin_mid; } else { bin_max = bin_mid; } bin_mid = Math.floor((bin_max - bin_min) / 2 + bin_min); } // Use the result from this iteration as the maximum for the next. bin_max = bin_mid; var start = Math.max(1, loc - bin_mid + 1); var finish = Math.min(loc + bin_mid, text.length) + pattern.length; var rd = Array(finish + 2); rd[finish + 1] = (1 << d) - 1; for (var j = finish; j >= start; j--) { // The alphabet (s) is a sparse hash, so the following line generates // warnings. var charMatch = s[text.charAt(j - 1)]; if (d === 0) { // First pass: exact match. rd[j] = ((rd[j + 1] << 1) | 1) & charMatch; } else { // Subsequent passes: fuzzy match. rd[j] = (((rd[j + 1] << 1) | 1) & charMatch) | (((last_rd[j + 1] | last_rd[j]) << 1) | 1) | last_rd[j + 1]; } if (rd[j] & matchmask) { var score = match_bitapScore_(d, j - 1); // This match will almost certainly be better than any existing match. // But check anyway. if (score <= score_threshold) { // Told you so. score_threshold = score; best_loc = j - 1; if (best_loc > loc) { // When passing loc, don't exceed our current distance from loc. start = Math.max(1, 2 * loc - best_loc); } else { // Already passed loc, downhill from here on in. break; } } } } // No hope for a (better) match at greater error levels. if (match_bitapScore_(d + 1, loc) > score_threshold) { break; } last_rd = rd; } return (best_loc < 0) ? false : true; }; return (function() { var func = function(searchString, columns) { self.i = 1; // Reset paging var searchArguments, foundArgument, matching = [], found, item, text, values, is, multiSearch = (typeof options.multiSearch !== 'boolean') ? true : options.multiSearch, columns = (columns === undefined) ? self.items[0].values() : columns, searchString = (searchString === undefined) ? "" : searchString, target = searchString.target || searchString.srcElement; /* IE have srcElement */ searchString = (target === undefined) ? (""+searchString).toLowerCase() : ""+target.value.toLowerCase(); is = self.items; // Substract arguments from the searchString or put searchString as only argument searchArguments = multiSearch ? searchString.replace(/ +$/, '').split(/ +/) : [searchString]; locals.templater.clear(); if (searchString === "") { locals.reset.search(); self.searched = false; self.update(); } else { self.searched = true; for (var k = 0, kl = is.length; k < kl; k++) { found = true; item = is[k]; values = item.values(); for(var i = 0; i < searchArguments.length; i++) { foundArgument = false; for(var j in columns) { if(values.hasOwnProperty(j) && columns[j] !== null) { text = (values[j] != null) ? values[j].toString().toLowerCase() : ""; if (searchFunction(text, searchArguments[i], options)) { foundArgument = true; } } } if(!foundArgument) found = false; } if (found) { item.found = true; matching.push(item); } else { item.found = false; } } self.update(); } return self.visibleItems; }, timeout; return function() { var context = this, args = arguments; var later = function() { timeout = null; func.apply(context, args); }; clearTimeout(timeout); timeout = setTimeout(later, 100); }; }()); };
Craga89/jsdelivr
files/list.js/0.2.1/plugins/fuzzy/list.fuzzySearch.js
JavaScript
mit
8,873
<?php namespace Doctrine\Tests\DBAL\Functional; use Doctrine\DBAL\Types\Type; use Doctrine\DBAL\Cache\QueryCacheProfile; use PDO; require_once __DIR__ . '/../../TestInit.php'; /** * @group DDC-217 */ class ResultCacheTest extends \Doctrine\Tests\DbalFunctionalTestCase { private $expectedResult = array(array('test_int' => 100, 'test_string' => 'foo'), array('test_int' => 200, 'test_string' => 'bar'), array('test_int' => 300, 'test_string' => 'baz')); private $sqlLogger; public function setUp() { parent::setUp(); try { /* @var $sm \Doctrine\DBAL\Schema\AbstractSchemaManager */ $table = new \Doctrine\DBAL\Schema\Table("caching"); $table->addColumn('test_int', 'integer'); $table->addColumn('test_string', 'string', array('notnull' => false)); $table->setPrimaryKey(array('test_int')); $sm = $this->_conn->getSchemaManager(); $sm->createTable($table); } catch(\Exception $e) { } $this->_conn->executeUpdate('DELETE FROM caching'); foreach ($this->expectedResult AS $row) { $this->_conn->insert('caching', $row); } $config = $this->_conn->getConfiguration(); $config->setSQLLogger($this->sqlLogger = new \Doctrine\DBAL\Logging\DebugStack); $cache = new \Doctrine\Common\Cache\ArrayCache; $config->setResultCacheImpl($cache); } public function testCacheFetchAssoc() { $this->assertCacheNonCacheSelectSameFetchModeAreEqual($this->expectedResult, \PDO::FETCH_ASSOC); } public function testFetchNum() { $expectedResult = array(); foreach ($this->expectedResult AS $v) { $expectedResult[] = array_values($v); } $this->assertCacheNonCacheSelectSameFetchModeAreEqual($expectedResult, \PDO::FETCH_NUM); } public function testFetchBoth() { $expectedResult = array(); foreach ($this->expectedResult AS $v) { $expectedResult[] = array_merge($v, array_values($v)); } $this->assertCacheNonCacheSelectSameFetchModeAreEqual($expectedResult, \PDO::FETCH_BOTH); } public function testFetchColumn() { $expectedResult = array(); foreach ($this->expectedResult AS $v) { $expectedResult[] = array_shift($v); } $this->assertCacheNonCacheSelectSameFetchModeAreEqual($expectedResult, \PDO::FETCH_COLUMN); } public function testMixingFetch() { $numExpectedResult = array(); foreach ($this->expectedResult AS $v) { $numExpectedResult[] = array_values($v); } $stmt = $this->_conn->executeQuery("SELECT * FROM caching ORDER BY test_int ASC", array(), array(), new QueryCacheProfile(10, "testcachekey")); $data = $this->hydrateStmt($stmt, \PDO::FETCH_ASSOC); $this->assertEquals($this->expectedResult, $data); $stmt = $this->_conn->executeQuery("SELECT * FROM caching ORDER BY test_int ASC", array(), array(), new QueryCacheProfile(10, "testcachekey")); $data = $this->hydrateStmt($stmt, \PDO::FETCH_NUM); $this->assertEquals($numExpectedResult, $data); } public function testIteratorFetch() { $this->assertStandardAndIteratorFetchAreEqual(\PDO::FETCH_BOTH); $this->assertStandardAndIteratorFetchAreEqual(\PDO::FETCH_ASSOC); $this->assertStandardAndIteratorFetchAreEqual(\PDO::FETCH_NUM); } public function assertStandardAndIteratorFetchAreEqual($fetchMode) { $stmt = $this->_conn->executeQuery("SELECT * FROM caching ORDER BY test_int ASC", array(), array(), new QueryCacheProfile(10, "testcachekey")); $data = $this->hydrateStmt($stmt, $fetchMode); $stmt = $this->_conn->executeQuery("SELECT * FROM caching ORDER BY test_int ASC", array(), array(), new QueryCacheProfile(10, "testcachekey")); $data_iterator = $this->hydrateStmtIterator($stmt, $fetchMode); $this->assertEquals($data, $data_iterator); } public function testDontCloseNoCache() { $stmt = $this->_conn->executeQuery("SELECT * FROM caching ORDER BY test_int ASC", array(), array(), new QueryCacheProfile(10, "testcachekey")); $data = array(); while ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) { $data[] = $row; } $stmt = $this->_conn->executeQuery("SELECT * FROM caching ORDER BY test_int ASC", array(), array(), new QueryCacheProfile(10, "testcachekey")); $data = array(); while ($row = $stmt->fetch(\PDO::FETCH_NUM)) { $data[] = $row; } $this->assertEquals(2, count($this->sqlLogger->queries)); } public function testDontFinishNoCache() { $stmt = $this->_conn->executeQuery("SELECT * FROM caching ORDER BY test_int ASC", array(), array(), new QueryCacheProfile(10, "testcachekey")); $row = $stmt->fetch(\PDO::FETCH_ASSOC); $stmt->closeCursor(); $stmt = $this->_conn->executeQuery("SELECT * FROM caching ORDER BY test_int ASC", array(), array(), new QueryCacheProfile(10, "testcachekey")); $data = $this->hydrateStmt($stmt, \PDO::FETCH_NUM); $this->assertEquals(2, count($this->sqlLogger->queries)); } public function assertCacheNonCacheSelectSameFetchModeAreEqual($expectedResult, $fetchMode) { $stmt = $this->_conn->executeQuery("SELECT * FROM caching ORDER BY test_int ASC", array(), array(), new QueryCacheProfile(10, "testcachekey")); $this->assertEquals(2, $stmt->columnCount()); $data = $this->hydrateStmt($stmt, $fetchMode); $this->assertEquals($expectedResult, $data); $stmt = $this->_conn->executeQuery("SELECT * FROM caching ORDER BY test_int ASC", array(), array(), new QueryCacheProfile(10, "testcachekey")); $this->assertEquals(2, $stmt->columnCount()); $data = $this->hydrateStmt($stmt, $fetchMode); $this->assertEquals($expectedResult, $data); $this->assertEquals(1, count($this->sqlLogger->queries), "just one dbal hit"); } public function testEmptyResultCache() { $stmt = $this->_conn->executeQuery("SELECT * FROM caching WHERE test_int > 500", array(), array(), new QueryCacheProfile(10, "emptycachekey")); $data = $this->hydrateStmt($stmt); $stmt = $this->_conn->executeQuery("SELECT * FROM caching WHERE test_int > 500", array(), array(), new QueryCacheProfile(10, "emptycachekey")); $data = $this->hydrateStmt($stmt); $this->assertEquals(1, count($this->sqlLogger->queries), "just one dbal hit"); } public function testChangeCacheImpl() { $stmt = $this->_conn->executeQuery("SELECT * FROM caching WHERE test_int > 500", array(), array(), new QueryCacheProfile(10, "emptycachekey")); $data = $this->hydrateStmt($stmt); $secondCache = new \Doctrine\Common\Cache\ArrayCache; $stmt = $this->_conn->executeQuery("SELECT * FROM caching WHERE test_int > 500", array(), array(), new QueryCacheProfile(10, "emptycachekey", $secondCache)); $data = $this->hydrateStmt($stmt); $this->assertEquals(2, count($this->sqlLogger->queries), "two hits"); $this->assertEquals(1, count($secondCache->fetch("emptycachekey"))); } private function hydrateStmt($stmt, $fetchMode = \PDO::FETCH_ASSOC) { $data = array(); while ($row = $stmt->fetch($fetchMode)) { $data[] = is_array($row) ? array_change_key_case($row, CASE_LOWER) : $row; } $stmt->closeCursor(); return $data; } private function hydrateStmtIterator($stmt, $fetchMode = \PDO::FETCH_ASSOC) { $data = array(); $stmt->setFetchMode($fetchMode); foreach ($stmt as $row) { $data[] = is_array($row) ? array_change_key_case($row, CASE_LOWER) : $row; } $stmt->closeCursor(); return $data; } }
mixxx73/calculator
vendor/doctrine/dbal/tests/Doctrine/Tests/DBAL/Functional/ResultCacheTest.php
PHP
mit
8,011
var isFunction = require('./isFunction'), isObject = require('./isObject'), isSymbol = require('./isSymbol'); /** Used as references for various `Number` constants. */ var NAN = 0 / 0; /** Used to match leading and trailing whitespace. */ var reTrim = /^\s+|\s+$/g; /** Used to detect bad signed hexadecimal string values. */ var reIsBadHex = /^[-+]0x[0-9a-f]+$/i; /** Used to detect binary string values. */ var reIsBinary = /^0b[01]+$/i; /** Used to detect octal string values. */ var reIsOctal = /^0o[0-7]+$/i; /** Built-in method references without a dependency on `root`. */ var freeParseInt = parseInt; /** * Converts `value` to a number. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to process. * @returns {number} Returns the number. * @example * * _.toNumber(3); * // => 3 * * _.toNumber(Number.MIN_VALUE); * // => 5e-324 * * _.toNumber(Infinity); * // => Infinity * * _.toNumber('3'); * // => 3 */ function toNumber(value) { if (typeof value == 'number') { return value; } if (isSymbol(value)) { return NAN; } if (isObject(value)) { var other = isFunction(value.valueOf) ? value.valueOf() : value; value = isObject(other) ? (other + '') : other; } if (typeof value != 'string') { return value === 0 ? value : +value; } value = value.replace(reTrim, ''); var isBinary = reIsBinary.test(value); return (isBinary || reIsOctal.test(value)) ? freeParseInt(value.slice(2), isBinary ? 2 : 8) : (reIsBadHex.test(value) ? NAN : +value); } module.exports = toNumber;
jibadano/71mb4
node_modules/gulp-less/node_modules/accord/node_modules/lodash/package/toNumber.js
JavaScript
mit
1,597
.mm-fixed-bottom,.mm-fixed-top,.mm-page{-webkit-transition:none .4s ease;-moz-transition:none .4s ease;-ms-transition:none .4s ease;-o-transition:none .4s ease;transition:none .4s ease;-webkit-transition-property:top,right,bottom,left,border;-moz-transition-property:top,right,bottom,left,border;-ms-transition-property:top,right,bottom,left,border;-o-transition-property:top,right,bottom,left,border;transition-property:top,right,bottom,left,border}html.mm-opened #mm-blocker,html.mm-opened .mm-page{margin:0;top:0;right:0;bottom:0;left:0;border:0 solid transparent}html.mm-opening .mm-page{border:0 solid #010101}.mm-fixed-bottom,.mm-fixed-top{position:fixed;left:0}.mm-fixed-top{top:0}.mm-fixed-bottom{bottom:0}html.mm-opened{overflow-x:hidden;position:relative}html.mm-opened .mm-page{-webkit-box-sizing:border-box;-moz-box-sizing:border-box;-ms-box-sizing:border-box;-o-box-sizing:border-box;box-sizing:border-box;position:relative}html.mm-background .mm-page{background:inherit}#mm-blocker{background:url(data:image/gif;base64,R0lGODlhAQABAIAAAP///wAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw==);display:none;width:100%;height:100%;position:fixed;z-index:999999}html.mm-blocking #mm-blocker,html.mm-opened #mm-blocker{display:block}.mm-menu.mm-offcanvas{display:none;position:fixed}.mm-menu.mm-current{display:block}html.mm-opening #mm-blocker,html.mm-opening .mm-fixed-bottom,html.mm-opening .mm-fixed-top,html.mm-opening .mm-page{left:80%}.mm-menu{width:80%}@media all and (max-width:175px){.mm-menu{width:140px}html.mm-opening #mm-blocker,html.mm-opening .mm-fixed-bottom,html.mm-opening .mm-fixed-top,html.mm-opening .mm-page{left:140px}}@media all and (min-width:550px){.mm-menu{width:440px}html.mm-opening #mm-blocker,html.mm-opening .mm-fixed-bottom,html.mm-opening .mm-fixed-top,html.mm-opening .mm-page{left:440px}}
matteofigus/cdnjs
ajax/libs/jQuery.mmenu/4.3.1/css/addons/jquery.mmenu.offcanvas.min.css
CSS
mit
1,823
(function(g){var b="//code.jquery.com/jquery-1.11.0.min.js",k="//www.jplayer.org/2.6.0/js/jquery.jplayer.min.js",e="//www.jplayer.org/2.6.0/js/Jplayer.swf",a="html,flash",i=false,d=false,h=false,j={mp3:{codec:'audio/mpeg; codecs="mp3"',flashCanPlay:true,media:"audio"},m4a:{codec:'audio/mp4; codecs="mp4a.40.2"',flashCanPlay:true,media:"audio"},m3u8a:{codec:'application/vnd.apple.mpegurl; codecs="mp4a.40.2"',flashCanPlay:false,media:"audio"},m3ua:{codec:"audio/mpegurl",flashCanPlay:false,media:"audio"},oga:{codec:'audio/ogg; codecs="vorbis, opus"',flashCanPlay:false,media:"audio"},flac:{codec:"audio/x-flac",flashCanPlay:false,media:"audio"},wav:{codec:'audio/wav; codecs="1"',flashCanPlay:false,media:"audio"},webma:{codec:'audio/webm; codecs="vorbis"',flashCanPlay:false,media:"audio"},fla:{codec:"audio/x-flv",flashCanPlay:true,media:"audio"},rtmpa:{codec:'audio/rtmp; codecs="rtmp"',flashCanPlay:true,media:"audio"},m4v:{codec:'video/mp4; codecs="avc1.42E01E, mp4a.40.2"',flashCanPlay:true,media:"video"},m3u8v:{codec:'application/vnd.apple.mpegurl; codecs="avc1.42E01E, mp4a.40.2"',flashCanPlay:false,media:"video"},m3uv:{codec:"audio/mpegurl",flashCanPlay:false,media:"video"},ogv:{codec:'video/ogg; codecs="theora, vorbis"',flashCanPlay:false,media:"video"},webmv:{codec:'video/webm; codecs="vorbis, vp8"',flashCanPlay:false,media:"video"},flv:{codec:"video/x-flv",flashCanPlay:true,media:"video"},rtmpv:{codec:'video/rtmp; codecs="rtmp"',flashCanPlay:true,media:"video"}},l=function(m){if(m&&typeof m==="object"&&m.hasOwnProperty){return true}else{return false}},f=function(n){var m=false;if(/\.mp3$/i.test(n)){m="mp3"}else{if(/\.mp4$/i.test(n)||/\.m4v$/i.test(n)){m="m4v"}else{if(/\.m4a$/i.test(n)){m="m4a"}else{if(/\.ogg$/i.test(n)||/\.oga$/i.test(n)){m="oga"}else{if(/\.ogv$/i.test(n)){m="ogv"}else{if(/\.webm$/i.test(n)){m="webmv"}}}}}}return m},c=function(m){var o="",n="";if(l(m)){for(var p in m){if(m.hasOwnProperty(p)){o+=n+p;n=","}}}if(i){console.log('getSupplied(): Generated: supplied = "'+o+'"')}return o};g.player("jplayer",{_canPlayType:function(z,m){var t=z.toLowerCase(),C={media:{},options:{}},v=false,B;if(t!=="video"&&t!=="audio"){if(typeof m==="string"){if(/^http.*/i.test(m)){B=f(m);if(B){C.media[B]=m;C.options.solution=a;C.options.supplied=B}}}else{C=m}if(l(C)&&l(C.media)){if(!l(C.options)){C.options={}}if(!C.options.solution){C.options.solution=a}if(!C.options.supplied){C.options.supplied=c(C.media)}var w=C.options.solution.toLowerCase().split(","),y=C.options.supplied.toLowerCase().split(",");for(var x=0;x<w.length;x++){var r=w[x].replace(/^\s+|\s+$/g,""),q=r==="html",p=r==="flash",u;for(var o=0;o<y.length;o++){B=y[o].replace(/^\s+|\s+$/g,"");if(j[B]){if(!u&&q){u=document.createElement(j[B].media)}var s=!!(u&&u.canPlayType&&u.canPlayType(j[B].codec)),A=s&&q,n=j[B].flashCanPlay&&p;if(A||n){v={html:A,type:B};x=w.length;o=y.length}}}}}}return v},_setup:function(){var o=this,n,u,A="unknown",z={},q={},y=false,r=0,s=null,m=false,v=null,x=function(){if(y){if(i){console.log("Dispatched event : durationchange : "+r)}o.dispatchEvent("durationchange")}else{if(i){console.log("DELAYED EVENT (!ready) : durationchange : "+r)}clearTimeout(s);s=setTimeout(x,250)}},w=function(){var D=function(E){if(E.jPlayer.status.duration!==r){r=E.jPlayer.status.duration;x()}},C=function(E){if(!m&&E.jPlayer.status.seekPercent===100){m=true;setTimeout(function(){if(i){console.log("Trigger : canplaythrough")}u._trigger($.jPlayer.event.canplaythrough)},0)}};n.bind($.jPlayer.event.loadstart,function(){setTimeout(function(){if(i){console.log("Trigger : loadeddata")}u._trigger($.jPlayer.event.loadeddata)},0)}).bind($.jPlayer.event.progress,function(E){D(E);C(E)}).bind($.jPlayer.event.timeupdate,function(E){D(E);C(E)}).bind($.jPlayer.event.play,function(){setTimeout(function(){if(i){console.log("Trigger : playing")}u._trigger($.jPlayer.event.playing)},0)});if(i){console.log("Created CUSTOM event handlers for FLASH")}},t=function(){(function(G){n=G("#"+o.id);if(typeof o.src==="string"){A=f(o.src);z[A]=o.src;q.supplied=A;q.solution=a}else{if(l(o.src)){z=l(o.src.media)?o.src.media:{};q=l(o.src.options)?o.src.options:{};q.solution=q.solution||a;q.supplied=q.supplied||c(o.src.media)}}q.swfPath=q.swfPath||e;n.bind(G.jPlayer.event.ready,function(J){if(J.jPlayer.flash.used){w()}G(this).jPlayer("setMedia",z).jPlayer("load")});var D=G.jPlayer.reservedEvent+" loadeddata durationchange",I=D.split(/\s+/g);var H=function(J){n.bind(G.jPlayer.event[J],function(K){if(i){console.log("Dispatched event: "+J+(K&&K.jPlayer?" ("+K.jPlayer.status.currentTime+"s)":""))}o.dispatchEvent(J)});if(i){console.log("Created event handler for: "+J)}};for(var E in G.jPlayer.event){if(G.jPlayer.event.hasOwnProperty(E)){var C=true;for(var F in I){if(I.hasOwnProperty(F)){if(I[F]===E){C=false;break}}}if(C){H(E)}else{if(i){console.log("Skipped auto event handler creation for: "+E)}}}}n.bind(G.jPlayer.event.loadeddata,function(J){if(i){console.log("Dispatched event: loadeddata"+(J&&J.jPlayer?" ("+J.jPlayer.status.currentTime+"s)":""))}o.dispatchEvent("loadeddata");y=true});if(i){console.log("Created CUSTOM event handler for: loadeddata")}n.bind(G.jPlayer.event.durationchange,function(J){r=J.jPlayer.status.duration;x()});if(i){console.log("Created CUSTOM event handler for: durationchange")}n.bind(G.jPlayer.event.error,function(J){v=J.jPlayer.error;if(v.type===G.jPlayer.error.URL){v.code=4}else{v.code=0}if(i){console.log("Dispatched event: error")}if(i){console.dir(v)}o.dispatchEvent("error")});if(i){console.log("Created CUSTOM event handler for: error")}g.player.defineProperty(o,"error",{set:function(){return v},get:function(){return v}});g.player.defineProperty(o,"currentTime",{set:function(J){if(u.status.paused){n.jPlayer("pause",J)}else{n.jPlayer("play",J)}return J},get:function(){return u.status.currentTime}});g.player.defineProperty(o,"duration",{set:function(){if(y){return r}else{return NaN}},get:function(){if(y){return r}else{return NaN}}});g.player.defineProperty(o,"muted",{set:function(J){n.jPlayer("mute",J);return u.options.muted},get:function(){return u.options.muted}});g.player.defineProperty(o,"volume",{set:function(J){n.jPlayer("volume",J);return u.options.volume},get:function(){return u.options.volume}});g.player.defineProperty(o,"paused",{set:function(){return u.status.paused},get:function(){return u.status.paused}});o.play=function(){n.jPlayer("play")};o.pause=function(){n.jPlayer("pause")};n.jPlayer(q);u=n.data("jPlayer")}(jQuery))},p=function(){if(!jQuery.jPlayer){if(!h){h=true;g.getScript(k,function(){h=false;t()})}else{setTimeout(p,250)}}else{t()}},B=function(){if(!window.jQuery){if(!d){d=true;g.getScript(b,function(){d=false;p()})}else{setTimeout(B,250)}}else{p()}};B()},_teardown:function(){jQuery("#"+this.id).jPlayer("destroy")}})}(Popcorn));
jemmy655/cdnjs
ajax/libs/jplayer/2.6.1/popcorn/player/popcorn.jplayer.min.js
JavaScript
mit
6,811
<?php /** * CodeIgniter * * An open source application development framework for PHP * * This content is released under the MIT License (MIT) * * Copyright (c) 2014 - 2015, British Columbia Institute of Technology * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * * @package CodeIgniter * @author EllisLab Dev Team * @copyright Copyright (c) 2008 - 2014, EllisLab, Inc. (http://ellislab.com/) * @copyright Copyright (c) 2014 - 2015, British Columbia Institute of Technology (http://bcit.ca/) * @license http://opensource.org/licenses/MIT MIT License * @link http://codeigniter.com * @since Version 1.0.0 * @filesource */ defined('BASEPATH') OR exit('No direct script access allowed'); $lang['upload_userfile_not_set'] = 'Unable to find a post variable called userfile.'; $lang['upload_file_exceeds_limit'] = 'The uploaded file exceeds the maximum allowed size in your PHP configuration file.'; $lang['upload_file_exceeds_form_limit'] = 'The uploaded file exceeds the maximum size allowed by the submission form.'; $lang['upload_file_partial'] = 'The file was only partially uploaded.'; $lang['upload_no_temp_directory'] = 'The temporary folder is missing.'; $lang['upload_unable_to_write_file'] = 'The file could not be written to disk.'; $lang['upload_stopped_by_extension'] = 'The file upload was stopped by extension.'; $lang['upload_no_file_selected'] = 'You did not select a file to upload.'; $lang['upload_invalid_filetype'] = 'The filetype you are attempting to upload is not allowed.'; $lang['upload_invalid_filesize'] = 'The file you are attempting to upload is larger than the permitted size.'; $lang['upload_invalid_dimensions'] = 'The image you are attempting to upload doesn\'t fit into the allowed dimensions.'; $lang['upload_destination_error'] = 'A problem was encountered while attempting to move the uploaded file to the final destination.'; $lang['upload_no_filepath'] = 'The upload path does not appear to be valid.'; $lang['upload_no_file_types'] = 'You have not specified any allowed file types.'; $lang['upload_bad_filename'] = 'The file name you submitted already exists on the server.'; $lang['upload_not_writable'] = 'The upload destination folder does not appear to be writable.';
MingoDev/code-igniter-tutorial
system/language/english/upload_lang.php
PHP
mit
3,253
<?php namespace Illuminate\Queue; use Aws\Sqs\SqsClient; use Illuminate\Queue\Jobs\SqsJob; use Illuminate\Contracts\Queue\Queue as QueueContract; class SqsQueue extends Queue implements QueueContract { /** * The Amazon SQS instance. * * @var \Aws\Sqs\SqsClient */ protected $sqs; /** * The name of the default tube. * * @var string */ protected $default; /** * The sqs prefix url. * * @var string */ protected $prefix; /** * The job creator callback. * * @var callable|null */ protected $jobCreator; /** * Create a new Amazon SQS queue instance. * * @param \Aws\Sqs\SqsClient $sqs * @param string $default * @param string $prefix * @return void */ public function __construct(SqsClient $sqs, $default, $prefix = '') { $this->sqs = $sqs; $this->prefix = $prefix; $this->default = $default; } /** * Push a new job onto the queue. * * @param string $job * @param mixed $data * @param string $queue * @return mixed */ public function push($job, $data = '', $queue = null) { return $this->pushRaw($this->createPayload($job, $data), $queue); } /** * Push a raw payload onto the queue. * * @param string $payload * @param string $queue * @param array $options * @return mixed */ public function pushRaw($payload, $queue = null, array $options = []) { $response = $this->sqs->sendMessage(['QueueUrl' => $this->getQueue($queue), 'MessageBody' => $payload]); return $response->get('MessageId'); } /** * Push a new job onto the queue after a delay. * * @param \DateTime|int $delay * @param string $job * @param mixed $data * @param string $queue * @return mixed */ public function later($delay, $job, $data = '', $queue = null) { $payload = $this->createPayload($job, $data); $delay = $this->getSeconds($delay); return $this->sqs->sendMessage([ 'QueueUrl' => $this->getQueue($queue), 'MessageBody' => $payload, 'DelaySeconds' => $delay, ])->get('MessageId'); } /** * Pop the next job off of the queue. * * @param string $queue * @return \Illuminate\Contracts\Queue\Job|null */ public function pop($queue = null) { $queue = $this->getQueue($queue); $response = $this->sqs->receiveMessage( ['QueueUrl' => $queue, 'AttributeNames' => ['ApproximateReceiveCount']] ); if (count($response['Messages']) > 0) { if ($this->jobCreator) { return call_user_func($this->jobCreator, $this->container, $this->sqs, $queue, $response); } else { return new SqsJob($this->container, $this->sqs, $queue, $response['Messages'][0]); } } } /** * Define the job creator callback for the connection. * * @param callable $callback * @return $this */ public function createJobsUsing(callable $callback) { $this->jobCreator = $callback; return $this; } /** * Get the queue or return the default. * * @param string|null $queue * @return string */ public function getQueue($queue) { $queue = $queue ?: $this->default; if (filter_var($queue, FILTER_VALIDATE_URL) !== false) { return $queue; } return rtrim($this->prefix, '/').'/'.($queue); } /** * Get the underlying SQS instance. * * @return \Aws\Sqs\SqsClient */ public function getSqs() { return $this->sqs; } }
noikiy/framework-1
src/Illuminate/Queue/SqsQueue.php
PHP
mit
3,842
<?php /* * This file is part of the Symfony package. * * (c) Fabien Potencier <fabien@symfony.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\HttpFoundation\Tests\Session\Storage\Handler; use Symfony\Component\HttpFoundation\Session\Storage\Handler\MongoDbSessionHandler; /** * @author Markus Bachmann <markus.bachmann@bachi.biz> */ class MongoDbSessionHandlerTest extends \PHPUnit_Framework_TestCase { /** * @var \PHPUnit_Framework_MockObject_MockObject */ private $mongo; private $storage; public $options; protected function setUp() { if (!extension_loaded('mongo')) { $this->markTestSkipped('MongoDbSessionHandler requires the PHP "mongo" extension.'); } $mongoClass = version_compare(phpversion('mongo'), '1.3.0', '<') ? 'Mongo' : 'MongoClient'; $this->mongo = $this->getMockBuilder($mongoClass) ->getMock(); $this->options = array( 'id_field' => '_id', 'data_field' => 'data', 'time_field' => 'time', 'expiry_field' => 'expires_at', 'database' => 'sf2-test', 'collection' => 'session-test', ); $this->storage = new MongoDbSessionHandler($this->mongo, $this->options); } /** * @expectedException \InvalidArgumentException */ public function testConstructorShouldThrowExceptionForInvalidMongo() { new MongoDbSessionHandler(new \stdClass(), $this->options); } /** * @expectedException \InvalidArgumentException */ public function testConstructorShouldThrowExceptionForMissingOptions() { new MongoDbSessionHandler($this->mongo, array()); } public function testOpenMethodAlwaysReturnTrue() { $this->assertTrue($this->storage->open('test', 'test'), 'The "open" method should always return true'); } public function testCloseMethodAlwaysReturnTrue() { $this->assertTrue($this->storage->close(), 'The "close" method should always return true'); } public function testRead() { $collection = $this->createMongoCollectionMock(); $this->mongo->expects($this->once()) ->method('selectCollection') ->with($this->options['database'], $this->options['collection']) ->will($this->returnValue($collection)); $that = $this; // defining the timeout before the actual method call // allows to test for "greater than" values in the $criteria $testTimeout = time() + 1; $collection->expects($this->once()) ->method('findOne') ->will($this->returnCallback(function ($criteria) use ($that, $testTimeout) { $that->assertArrayHasKey($that->options['id_field'], $criteria); $that->assertEquals($criteria[$that->options['id_field']], 'foo'); $that->assertArrayHasKey($that->options['expiry_field'], $criteria); $that->assertArrayHasKey('$gte', $criteria[$that->options['expiry_field']]); $that->assertInstanceOf('MongoDate', $criteria[$that->options['expiry_field']]['$gte']); $that->assertGreaterThanOrEqual($criteria[$that->options['expiry_field']]['$gte']->sec, $testTimeout); return array( $that->options['id_field'] => 'foo', $that->options['data_field'] => new \MongoBinData('bar', \MongoBinData::BYTE_ARRAY), $that->options['id_field'] => new \MongoDate(), ); })); $this->assertEquals('bar', $this->storage->read('foo')); } public function testWrite() { $collection = $this->createMongoCollectionMock(); $this->mongo->expects($this->once()) ->method('selectCollection') ->with($this->options['database'], $this->options['collection']) ->will($this->returnValue($collection)); $that = $this; $data = array(); $collection->expects($this->once()) ->method('update') ->will($this->returnCallback(function ($criteria, $updateData, $options) use ($that, &$data) { $that->assertEquals(array($that->options['id_field'] => 'foo'), $criteria); $that->assertEquals(array('upsert' => true, 'multiple' => false), $options); $data = $updateData['$set']; })); $expectedExpiry = time() + (int) ini_get('session.gc_maxlifetime'); $this->assertTrue($this->storage->write('foo', 'bar')); $this->assertEquals('bar', $data[$this->options['data_field']]->bin); $that->assertInstanceOf('MongoDate', $data[$this->options['time_field']]); $this->assertInstanceOf('MongoDate', $data[$this->options['expiry_field']]); $this->assertGreaterThanOrEqual($expectedExpiry, $data[$this->options['expiry_field']]->sec); } public function testWriteWhenUsingExpiresField() { $this->options = array( 'id_field' => '_id', 'data_field' => 'data', 'time_field' => 'time', 'database' => 'sf2-test', 'collection' => 'session-test', 'expiry_field' => 'expiresAt', ); $this->storage = new MongoDbSessionHandler($this->mongo, $this->options); $collection = $this->createMongoCollectionMock(); $this->mongo->expects($this->once()) ->method('selectCollection') ->with($this->options['database'], $this->options['collection']) ->will($this->returnValue($collection)); $that = $this; $data = array(); $collection->expects($this->once()) ->method('update') ->will($this->returnCallback(function ($criteria, $updateData, $options) use ($that, &$data) { $that->assertEquals(array($that->options['id_field'] => 'foo'), $criteria); $that->assertEquals(array('upsert' => true, 'multiple' => false), $options); $data = $updateData['$set']; })); $this->assertTrue($this->storage->write('foo', 'bar')); $this->assertEquals('bar', $data[$this->options['data_field']]->bin); $that->assertInstanceOf('MongoDate', $data[$this->options['time_field']]); $that->assertInstanceOf('MongoDate', $data[$this->options['expiry_field']]); } public function testReplaceSessionData() { $collection = $this->createMongoCollectionMock(); $this->mongo->expects($this->once()) ->method('selectCollection') ->with($this->options['database'], $this->options['collection']) ->will($this->returnValue($collection)); $data = array(); $collection->expects($this->exactly(2)) ->method('update') ->will($this->returnCallback(function ($criteria, $updateData, $options) use (&$data) { $data = $updateData; })); $this->storage->write('foo', 'bar'); $this->storage->write('foo', 'foobar'); $this->assertEquals('foobar', $data['$set'][$this->options['data_field']]->bin); } public function testDestroy() { $collection = $this->createMongoCollectionMock(); $this->mongo->expects($this->once()) ->method('selectCollection') ->with($this->options['database'], $this->options['collection']) ->will($this->returnValue($collection)); $collection->expects($this->once()) ->method('remove') ->with(array($this->options['id_field'] => 'foo')); $this->assertTrue($this->storage->destroy('foo')); } public function testGc() { $collection = $this->createMongoCollectionMock(); $this->mongo->expects($this->once()) ->method('selectCollection') ->with($this->options['database'], $this->options['collection']) ->will($this->returnValue($collection)); $that = $this; $collection->expects($this->once()) ->method('remove') ->will($this->returnCallback(function ($criteria) use ($that) { $that->assertInstanceOf('MongoDate', $criteria[$that->options['expiry_field']]['$lt']); $that->assertGreaterThanOrEqual(time() - 1, $criteria[$that->options['expiry_field']]['$lt']->sec); })); $this->assertTrue($this->storage->gc(1)); } private function createMongoCollectionMock() { $mongoClient = $this->getMockBuilder('MongoClient') ->getMock(); $mongoDb = $this->getMockBuilder('MongoDB') ->setConstructorArgs(array($mongoClient, 'database-name')) ->getMock(); $collection = $this->getMockBuilder('MongoCollection') ->setConstructorArgs(array($mongoDb, 'collection-name')) ->getMock(); return $collection; } }
khalilbenihoud/lightbloog
vendor/symfony/http-foundation/Tests/Session/Storage/Handler/MongoDbSessionHandlerTest.php
PHP
mit
9,130
/* qTip2 v2.2.0 None | qtip2.com | Licensed MIT, GPL | Thu Nov 21 2013 20:36:59 */ (function(t,e,i){(function(t){"use strict";"function"==typeof define&&define.amd?define(["jquery"],t):jQuery&&!jQuery.fn.qtip&&t(jQuery)})(function(s){"use strict";function n(t,e,i,n){this.id=i,this.target=t,this.tooltip=q,this.elements={target:t},this._id=O+"-"+i,this.timers={img:{}},this.options=e,this.plugins={},this.cache={event:{},target:s(),disabled:j,attr:n,onTooltip:j,lastClass:""},this.rendered=this.destroyed=this.disabled=this.waiting=this.hiddenDuringWait=this.positioning=this.triggering=j}function o(t){return t===q||"object"!==s.type(t)}function r(t){return!(s.isFunction(t)||t&&t.attr||t.length||"object"===s.type(t)&&(t.jquery||t.then))}function a(t){var e,i,n,a;return o(t)?j:(o(t.metadata)&&(t.metadata={type:t.metadata}),"content"in t&&(e=t.content,o(e)||e.jquery||e.done?e=t.content={text:i=r(e)?j:e}:i=e.text,"ajax"in e&&(n=e.ajax,a=n&&n.once!==j,delete e.ajax,e.text=function(t,e){var o=i||s(this).attr(e.options.content.attr)||"Loading...",r=s.ajax(s.extend({},n,{context:e})).then(n.success,q,n.error).then(function(t){return t&&a&&e.set("content.text",t),t},function(t,i,s){e.destroyed||0===t.status||e.set("content.text",i+": "+s)});return a?o:(e.set("content.text",o),r)}),"title"in e&&(o(e.title)||(e.button=e.title.button,e.title=e.title.text),r(e.title||j)&&(e.title=j))),"position"in t&&o(t.position)&&(t.position={my:t.position,at:t.position}),"show"in t&&o(t.show)&&(t.show=t.show.jquery?{target:t.show}:t.show===C?{ready:C}:{event:t.show}),"hide"in t&&o(t.hide)&&(t.hide=t.hide.jquery?{target:t.hide}:{event:t.hide}),"style"in t&&o(t.style)&&(t.style={classes:t.style}),s.each(S,function(){this.sanitize&&this.sanitize(t)}),t)}function h(t,e){for(var i,s=0,n=t,o=e.split(".");n=n[o[s++]];)o.length>s&&(i=n);return[i||t,o.pop()]}function l(t,e){var i,s,n;for(i in this.checks)for(s in this.checks[i])(n=RegExp(s,"i").exec(t))&&(e.push(n),("builtin"===i||this.plugins[i])&&this.checks[i][s].apply(this.plugins[i]||this,e))}function d(t){return I.concat("").join(t?"-"+t+" ":" ")}function c(i){return i&&{type:i.type,pageX:i.pageX,pageY:i.pageY,target:i.target,relatedTarget:i.relatedTarget,scrollX:i.scrollX||t.pageXOffset||e.body.scrollLeft||e.documentElement.scrollLeft,scrollY:i.scrollY||t.pageYOffset||e.body.scrollTop||e.documentElement.scrollTop}||{}}function u(t,e){return e>0?setTimeout(s.proxy(t,this),e):(t.call(this),i)}function p(t){return this.tooltip.hasClass(H)?j:(clearTimeout(this.timers.show),clearTimeout(this.timers.hide),this.timers.show=u.call(this,function(){this.toggle(C,t)},this.options.show.delay),i)}function f(t){if(this.tooltip.hasClass(H))return j;var e=s(t.relatedTarget),i=e.closest(Y)[0]===this.tooltip[0],n=e[0]===this.options.show.target[0];if(clearTimeout(this.timers.show),clearTimeout(this.timers.hide),this!==e[0]&&"mouse"===this.options.position.target&&i||this.options.hide.fixed&&/mouse(out|leave|move)/.test(t.type)&&(i||n))try{t.preventDefault(),t.stopImmediatePropagation()}catch(o){}else this.timers.hide=u.call(this,function(){this.toggle(j,t)},this.options.hide.delay,this)}function g(t){return this.tooltip.hasClass(H)||!this.options.hide.inactive?j:(clearTimeout(this.timers.inactive),this.timers.inactive=u.call(this,function(){this.hide(t)},this.options.hide.inactive),i)}function m(t){this.rendered&&this.tooltip[0].offsetWidth>0&&this.reposition(t)}function v(t,i,n){s(e.body).delegate(t,(i.split?i:i.join(K+" "))+K,function(){var t=b.api[s.attr(this,X)];t&&!t.disabled&&n.apply(t,arguments)})}function y(t,i,o){var r,h,l,d,c,u=s(e.body),p=t[0]===e?u:t,f=t.metadata?t.metadata(o.metadata):q,g="html5"===o.metadata.type&&f?f[o.metadata.name]:q,m=t.data(o.metadata.name||"qtipopts");try{m="string"==typeof m?s.parseJSON(m):m}catch(v){}if(d=s.extend(C,{},b.defaults,o,"object"==typeof m?a(m):q,a(g||f)),h=d.position,d.id=i,"boolean"==typeof d.content.text){if(l=t.attr(d.content.attr),d.content.attr===j||!l)return j;d.content.text=l}if(h.container.length||(h.container=u),h.target===j&&(h.target=p),d.show.target===j&&(d.show.target=p),d.show.solo===C&&(d.show.solo=h.container.closest("body")),d.hide.target===j&&(d.hide.target=p),d.position.viewport===C&&(d.position.viewport=h.container),h.container=h.container.eq(0),h.at=new _(h.at,C),h.my=new _(h.my),t.data(O))if(d.overwrite)t.qtip("destroy",!0);else if(d.overwrite===j)return j;return t.attr(D,i),d.suppress&&(c=t.attr("title"))&&t.removeAttr("title").attr(R,c).attr("title",""),r=new n(t,d,i,!!l),t.data(O,r),t.one("remove.qtip-"+i+" removeqtip.qtip-"+i,function(){var t;(t=s(this).data(O))&&t.destroy(!0)}),r}var b,w,_,x,T,C=!0,j=!1,q=null,E="x",W="y",z="top",A="left",F="bottom",L="right",k="center",S={},O="qtip",D="data-hasqtip",X="data-qtip-id",I=["ui-widget","ui-tooltip"],Y="."+O,$="click dblclick mousedown mouseup mousemove mouseleave mouseenter".split(" "),B=O+"-fixed",M=O+"-default",N=O+"-focus",P=O+"-hover",H=O+"-disabled",Q="_replacedByqTip",R="oldtitle",U={ie:function(){for(var t=3,i=e.createElement("div");(i.innerHTML="<!--[if gt IE "+ ++t+"]><i></i><![endif]-->")&&i.getElementsByTagName("i")[0];);return t>4?t:0/0}(),iOS:parseFloat((""+(/CPU.*OS ([0-9_]{1,5})|(CPU like).*AppleWebKit.*Mobile/i.exec(navigator.userAgent)||[0,""])[1]).replace("undefined","3_2").replace("_",".").replace("_",""))||j};w=n.prototype,w._when=function(t){return s.when.apply(s,t)},w.render=function(t){if(this.rendered||this.destroyed)return this;var e,i=this,n=this.options,o=this.cache,r=this.elements,a=n.content.text,h=n.content.title,l=n.content.button,d=n.position,c=("."+this._id+" ",[]);return s.attr(this.target[0],"aria-describedby",this._id),this.tooltip=r.tooltip=e=s("<div/>",{id:this._id,"class":[O,M,n.style.classes,O+"-pos-"+n.position.my.abbrev()].join(" "),width:n.style.width||"",height:n.style.height||"",tracking:"mouse"===d.target&&d.adjust.mouse,role:"alert","aria-live":"polite","aria-atomic":j,"aria-describedby":this._id+"-content","aria-hidden":C}).toggleClass(H,this.disabled).attr(X,this.id).data(O,this).appendTo(d.container).append(r.content=s("<div />",{"class":O+"-content",id:this._id+"-content","aria-atomic":C})),this.rendered=-1,this.positioning=C,h&&(this._createTitle(),s.isFunction(h)||c.push(this._updateTitle(h,j))),l&&this._createButton(),s.isFunction(a)||c.push(this._updateContent(a,j)),this.rendered=C,this._setWidget(),s.each(S,function(t){var e;"render"===this.initialize&&(e=this(i))&&(i.plugins[t]=e)}),this._unassignEvents(),this._assignEvents(),this._when(c).then(function(){i._trigger("render"),i.positioning=j,i.hiddenDuringWait||!n.show.ready&&!t||i.toggle(C,o.event,j),i.hiddenDuringWait=j}),b.api[this.id]=this,this},w.destroy=function(t){function e(){if(!this.destroyed){this.destroyed=C;var t=this.target,e=t.attr(R);this.rendered&&this.tooltip.stop(1,0).find("*").remove().end().remove(),s.each(this.plugins,function(){this.destroy&&this.destroy()}),clearTimeout(this.timers.show),clearTimeout(this.timers.hide),this._unassignEvents(),t.removeData(O).removeAttr(X).removeAttr(D).removeAttr("aria-describedby"),this.options.suppress&&e&&t.attr("title",e).removeAttr(R),this._unbind(t),this.options=this.elements=this.cache=this.timers=this.plugins=this.mouse=q,delete b.api[this.id]}}return this.destroyed?this.target:(t===C&&"hide"!==this.triggering||!this.rendered?e.call(this):(this.tooltip.one("tooltiphidden",s.proxy(e,this)),!this.triggering&&this.hide()),this.target)},x=w.checks={builtin:{"^id$":function(t,e,i,n){var o=i===C?b.nextid:i,r=O+"-"+o;o!==j&&o.length>0&&!s("#"+r).length?(this._id=r,this.rendered&&(this.tooltip[0].id=this._id,this.elements.content[0].id=this._id+"-content",this.elements.title[0].id=this._id+"-title")):t[e]=n},"^prerender":function(t,e,i){i&&!this.rendered&&this.render(this.options.show.ready)},"^content.text$":function(t,e,i){this._updateContent(i)},"^content.attr$":function(t,e,i,s){this.options.content.text===this.target.attr(s)&&this._updateContent(this.target.attr(i))},"^content.title$":function(t,e,s){return s?(s&&!this.elements.title&&this._createTitle(),this._updateTitle(s),i):this._removeTitle()},"^content.button$":function(t,e,i){this._updateButton(i)},"^content.title.(text|button)$":function(t,e,i){this.set("content."+e,i)},"^position.(my|at)$":function(t,e,i){"string"==typeof i&&(t[e]=new _(i,"at"===e))},"^position.container$":function(t,e,i){this.rendered&&this.tooltip.appendTo(i)},"^show.ready$":function(t,e,i){i&&(!this.rendered&&this.render(C)||this.toggle(C))},"^style.classes$":function(t,e,i,s){this.rendered&&this.tooltip.removeClass(s).addClass(i)},"^style.(width|height)":function(t,e,i){this.rendered&&this.tooltip.css(e,i)},"^style.widget|content.title":function(){this.rendered&&this._setWidget()},"^style.def":function(t,e,i){this.rendered&&this.tooltip.toggleClass(M,!!i)},"^events.(render|show|move|hide|focus|blur)$":function(t,e,i){this.rendered&&this.tooltip[(s.isFunction(i)?"":"un")+"bind"]("tooltip"+e,i)},"^(show|hide|position).(event|target|fixed|inactive|leave|distance|viewport|adjust)":function(){if(this.rendered){var t=this.options.position;this.tooltip.attr("tracking","mouse"===t.target&&t.adjust.mouse),this._unassignEvents(),this._assignEvents()}}}},w.get=function(t){if(this.destroyed)return this;var e=h(this.options,t.toLowerCase()),i=e[0][e[1]];return i.precedance?i.string():i};var V=/^position\.(my|at|adjust|target|container|viewport)|style|content|show\.ready/i,G=/^prerender|show\.ready/i;w.set=function(t,e){if(this.destroyed)return this;var n,o=this.rendered,r=j,d=this.options;return this.checks,"string"==typeof t?(n=t,t={},t[n]=e):t=s.extend({},t),s.each(t,function(e,n){if(o&&G.test(e))return delete t[e],i;var a,l=h(d,e.toLowerCase());a=l[0][l[1]],l[0][l[1]]=n&&n.nodeType?s(n):n,r=V.test(e)||r,t[e]=[l[0],l[1],n,a]}),a(d),this.positioning=C,s.each(t,s.proxy(l,this)),this.positioning=j,this.rendered&&this.tooltip[0].offsetWidth>0&&r&&this.reposition("mouse"===d.position.target?q:this.cache.event),this},w._update=function(t,e){var i=this,n=this.cache;return this.rendered&&t?(s.isFunction(t)&&(t=t.call(this.elements.target,n.event,this)||""),s.isFunction(t.then)?(n.waiting=C,t.then(function(t){return n.waiting=j,i._update(t,e)},q,function(t){return i._update(t,e)})):t===j||!t&&""!==t?j:(t.jquery&&t.length>0?e.empty().append(t.css({display:"block",visibility:"visible"})):e.html(t),this._waitForContent(e).then(function(t){t.images&&t.images.length&&i.rendered&&i.tooltip[0].offsetWidth>0&&i.reposition(n.event,!t.length)}))):j},w._waitForContent=function(t){var e=this.cache;return e.waiting=C,(s.fn.imagesLoaded?t.imagesLoaded():s.Deferred().resolve([])).done(function(){e.waiting=j}).promise()},w._updateContent=function(t,e){this._update(t,this.elements.content,e)},w._updateTitle=function(t,e){this._update(t,this.elements.title,e)===j&&this._removeTitle(j)},w._createTitle=function(){var t=this.elements,e=this._id+"-title";t.titlebar&&this._removeTitle(),t.titlebar=s("<div />",{"class":O+"-titlebar "+(this.options.style.widget?d("header"):"")}).append(t.title=s("<div />",{id:e,"class":O+"-title","aria-atomic":C})).insertBefore(t.content).delegate(".qtip-close","mousedown keydown mouseup keyup mouseout",function(t){s(this).toggleClass("ui-state-active ui-state-focus","down"===t.type.substr(-4))}).delegate(".qtip-close","mouseover mouseout",function(t){s(this).toggleClass("ui-state-hover","mouseover"===t.type)}),this.options.content.button&&this._createButton()},w._removeTitle=function(t){var e=this.elements;e.title&&(e.titlebar.remove(),e.titlebar=e.title=e.button=q,t!==j&&this.reposition())},w.reposition=function(i,n){if(!this.rendered||this.positioning||this.destroyed)return this;this.positioning=C;var o,r,a=this.cache,h=this.tooltip,l=this.options.position,d=l.target,c=l.my,u=l.at,p=l.viewport,f=l.container,g=l.adjust,m=g.method.split(" "),v=h.outerWidth(j),y=h.outerHeight(j),b=0,w=0,_=h.css("position"),x={left:0,top:0},T=h[0].offsetWidth>0,q=i&&"scroll"===i.type,E=s(t),W=f[0].ownerDocument,O=this.mouse;if(s.isArray(d)&&2===d.length)u={x:A,y:z},x={left:d[0],top:d[1]};else if("mouse"===d)u={x:A,y:z},!O||!O.pageX||!g.mouse&&i&&i.pageX?i&&i.pageX||((!g.mouse||this.options.show.distance)&&a.origin&&a.origin.pageX?i=a.origin:(!i||i&&("resize"===i.type||"scroll"===i.type))&&(i=a.event)):i=O,"static"!==_&&(x=f.offset()),W.body.offsetWidth!==(t.innerWidth||W.documentElement.clientWidth)&&(r=s(e.body).offset()),x={left:i.pageX-x.left+(r&&r.left||0),top:i.pageY-x.top+(r&&r.top||0)},g.mouse&&q&&O&&(x.left-=(O.scrollX||0)-E.scrollLeft(),x.top-=(O.scrollY||0)-E.scrollTop());else{if("event"===d?i&&i.target&&"scroll"!==i.type&&"resize"!==i.type?a.target=s(i.target):i.target||(a.target=this.elements.target):"event"!==d&&(a.target=s(d.jquery?d:this.elements.target)),d=a.target,d=s(d).eq(0),0===d.length)return this;d[0]===e||d[0]===t?(b=U.iOS?t.innerWidth:d.width(),w=U.iOS?t.innerHeight:d.height(),d[0]===t&&(x={top:(p||d).scrollTop(),left:(p||d).scrollLeft()})):S.imagemap&&d.is("area")?o=S.imagemap(this,d,u,S.viewport?m:j):S.svg&&d&&d[0].ownerSVGElement?o=S.svg(this,d,u,S.viewport?m:j):(b=d.outerWidth(j),w=d.outerHeight(j),x=d.offset()),o&&(b=o.width,w=o.height,r=o.offset,x=o.position),x=this.reposition.offset(d,x,f),(U.iOS>3.1&&4.1>U.iOS||U.iOS>=4.3&&4.33>U.iOS||!U.iOS&&"fixed"===_)&&(x.left-=E.scrollLeft(),x.top-=E.scrollTop()),(!o||o&&o.adjustable!==j)&&(x.left+=u.x===L?b:u.x===k?b/2:0,x.top+=u.y===F?w:u.y===k?w/2:0)}return x.left+=g.x+(c.x===L?-v:c.x===k?-v/2:0),x.top+=g.y+(c.y===F?-y:c.y===k?-y/2:0),S.viewport?(x.adjusted=S.viewport(this,x,l,b,w,v,y),r&&x.adjusted.left&&(x.left+=r.left),r&&x.adjusted.top&&(x.top+=r.top)):x.adjusted={left:0,top:0},this._trigger("move",[x,p.elem||p],i)?(delete x.adjusted,n===j||!T||isNaN(x.left)||isNaN(x.top)||"mouse"===d||!s.isFunction(l.effect)?h.css(x):s.isFunction(l.effect)&&(l.effect.call(h,this,s.extend({},x)),h.queue(function(t){s(this).css({opacity:"",height:""}),U.ie&&this.style.removeAttribute("filter"),t()})),this.positioning=j,this):this},w.reposition.offset=function(t,i,n){function o(t,e){i.left+=e*t.scrollLeft(),i.top+=e*t.scrollTop()}if(!n[0])return i;var r,a,h,l,d=s(t[0].ownerDocument),c=!!U.ie&&"CSS1Compat"!==e.compatMode,u=n[0];do"static"!==(a=s.css(u,"position"))&&("fixed"===a?(h=u.getBoundingClientRect(),o(d,-1)):(h=s(u).position(),h.left+=parseFloat(s.css(u,"borderLeftWidth"))||0,h.top+=parseFloat(s.css(u,"borderTopWidth"))||0),i.left-=h.left+(parseFloat(s.css(u,"marginLeft"))||0),i.top-=h.top+(parseFloat(s.css(u,"marginTop"))||0),r||"hidden"===(l=s.css(u,"overflow"))||"visible"===l||(r=s(u)));while(u=u.offsetParent);return r&&(r[0]!==d[0]||c)&&o(r,1),i};var J=(_=w.reposition.Corner=function(t,e){t=(""+t).replace(/([A-Z])/," $1").replace(/middle/gi,k).toLowerCase(),this.x=(t.match(/left|right/i)||t.match(/center/)||["inherit"])[0].toLowerCase(),this.y=(t.match(/top|bottom|center/i)||["inherit"])[0].toLowerCase(),this.forceY=!!e;var i=t.charAt(0);this.precedance="t"===i||"b"===i?W:E}).prototype;J.invert=function(t,e){this[t]=this[t]===A?L:this[t]===L?A:e||this[t]},J.string=function(){var t=this.x,e=this.y;return t===e?t:this.precedance===W||this.forceY&&"center"!==e?e+" "+t:t+" "+e},J.abbrev=function(){var t=this.string().split(" ");return t[0].charAt(0)+(t[1]&&t[1].charAt(0)||"")},J.clone=function(){return new _(this.string(),this.forceY)},w.toggle=function(t,i){var n=this.cache,o=this.options,r=this.tooltip;if(i){if(/over|enter/.test(i.type)&&/out|leave/.test(n.event.type)&&o.show.target.add(i.target).length===o.show.target.length&&r.has(i.relatedTarget).length)return this;n.event=c(i)}if(this.waiting&&!t&&(this.hiddenDuringWait=C),!this.rendered)return t?this.render(1):this;if(this.destroyed||this.disabled)return this;var a,h,l,d=t?"show":"hide",u=this.options[d],p=(this.options[t?"hide":"show"],this.options.position),f=this.options.content,g=this.tooltip.css("width"),m=this.tooltip.is(":visible"),v=t||1===u.target.length,y=!i||2>u.target.length||n.target[0]===i.target;return(typeof t).search("boolean|number")&&(t=!m),a=!r.is(":animated")&&m===t&&y,h=a?q:!!this._trigger(d,[90]),this.destroyed?this:(h!==j&&t&&this.focus(i),!h||a?this:(s.attr(r[0],"aria-hidden",!t),t?(n.origin=c(this.mouse),s.isFunction(f.text)&&this._updateContent(f.text,j),s.isFunction(f.title)&&this._updateTitle(f.title,j),!T&&"mouse"===p.target&&p.adjust.mouse&&(s(e).bind("mousemove."+O,this._storeMouse),T=C),g||r.css("width",r.outerWidth(j)),this.reposition(i,arguments[2]),g||r.css("width",""),u.solo&&("string"==typeof u.solo?s(u.solo):s(Y,u.solo)).not(r).not(u.target).qtip("hide",s.Event("tooltipsolo"))):(clearTimeout(this.timers.show),delete n.origin,T&&!s(Y+'[tracking="true"]:visible',u.solo).not(r).length&&(s(e).unbind("mousemove."+O),T=j),this.blur(i)),l=s.proxy(function(){t?(U.ie&&r[0].style.removeAttribute("filter"),r.css("overflow",""),"string"==typeof u.autofocus&&s(this.options.show.autofocus,r).focus(),this.options.show.target.trigger("qtip-"+this.id+"-inactive")):r.css({display:"",visibility:"",opacity:"",left:"",top:""}),this._trigger(t?"visible":"hidden")},this),u.effect===j||v===j?(r[d](),l()):s.isFunction(u.effect)?(r.stop(1,1),u.effect.call(r,this),r.queue("fx",function(t){l(),t()})):r.fadeTo(90,t?1:0,l),t&&u.target.trigger("qtip-"+this.id+"-inactive"),this))},w.show=function(t){return this.toggle(C,t)},w.hide=function(t){return this.toggle(j,t)},w.focus=function(t){if(!this.rendered||this.destroyed)return this;var e=s(Y),i=this.tooltip,n=parseInt(i[0].style.zIndex,10),o=b.zindex+e.length;return i.hasClass(N)||this._trigger("focus",[o],t)&&(n!==o&&(e.each(function(){this.style.zIndex>n&&(this.style.zIndex=this.style.zIndex-1)}),e.filter("."+N).qtip("blur",t)),i.addClass(N)[0].style.zIndex=o),this},w.blur=function(t){return!this.rendered||this.destroyed?this:(this.tooltip.removeClass(N),this._trigger("blur",[this.tooltip.css("zIndex")],t),this)},w.disable=function(t){return this.destroyed?this:("toggle"===t?t=!(this.rendered?this.tooltip.hasClass(H):this.disabled):"boolean"!=typeof t&&(t=C),this.rendered&&this.tooltip.toggleClass(H,t).attr("aria-disabled",t),this.disabled=!!t,this)},w.enable=function(){return this.disable(j)},w._createButton=function(){var t=this,e=this.elements,i=e.tooltip,n=this.options.content.button,o="string"==typeof n,r=o?n:"Close tooltip";e.button&&e.button.remove(),e.button=n.jquery?n:s("<a />",{"class":"qtip-close "+(this.options.style.widget?"":O+"-icon"),title:r,"aria-label":r}).prepend(s("<span />",{"class":"ui-icon ui-icon-close",html:"&times;"})),e.button.appendTo(e.titlebar||i).attr("role","button").click(function(e){return i.hasClass(H)||t.hide(e),j})},w._updateButton=function(t){if(!this.rendered)return j;var e=this.elements.button;t?this._createButton():e.remove()},w._setWidget=function(){var t=this.options.style.widget,e=this.elements,i=e.tooltip,s=i.hasClass(H);i.removeClass(H),H=t?"ui-state-disabled":"qtip-disabled",i.toggleClass(H,s),i.toggleClass("ui-helper-reset "+d(),t).toggleClass(M,this.options.style.def&&!t),e.content&&e.content.toggleClass(d("content"),t),e.titlebar&&e.titlebar.toggleClass(d("header"),t),e.button&&e.button.toggleClass(O+"-icon",!t)},w._storeMouse=function(t){(this.mouse=c(t)).type="mousemove"},w._bind=function(t,e,i,n,o){var r="."+this._id+(n?"-"+n:"");e.length&&s(t).bind((e.split?e:e.join(r+" "))+r,s.proxy(i,o||this))},w._unbind=function(t,e){s(t).unbind("."+this._id+(e?"-"+e:""))};var K="."+O;s(function(){v(Y,["mouseenter","mouseleave"],function(t){var e="mouseenter"===t.type,i=s(t.currentTarget),n=s(t.relatedTarget||t.target),o=this.options;e?(this.focus(t),i.hasClass(B)&&!i.hasClass(H)&&clearTimeout(this.timers.hide)):"mouse"===o.position.target&&o.hide.event&&o.show.target&&!n.closest(o.show.target[0]).length&&this.hide(t),i.toggleClass(P,e)}),v("["+X+"]",$,g)}),w._trigger=function(t,e,i){var n=s.Event("tooltip"+t);return n.originalEvent=i&&s.extend({},i)||this.cache.event||q,this.triggering=t,this.tooltip.trigger(n,[this].concat(e||[])),this.triggering=j,!n.isDefaultPrevented()},w._bindEvents=function(t,e,n,o,r,a){if(o.add(n).length===o.length){var h=[];e=s.map(e,function(e){var n=s.inArray(e,t);return n>-1?(h.push(t.splice(n,1)[0]),i):e}),h.length&&this._bind(n,h,function(t){var e=this.rendered?this.tooltip[0].offsetWidth>0:!1;(e?a:r).call(this,t)})}this._bind(n,t,r),this._bind(o,e,a)},w._assignInitialEvents=function(t){function e(t){return this.disabled||this.destroyed?j:(this.cache.event=c(t),this.cache.target=t?s(t.target):[i],clearTimeout(this.timers.show),this.timers.show=u.call(this,function(){this.render("object"==typeof t||n.show.ready)},n.show.delay),i)}var n=this.options,o=n.show.target,r=n.hide.target,a=n.show.event?s.trim(""+n.show.event).split(" "):[],h=n.hide.event?s.trim(""+n.hide.event).split(" "):[];/mouse(over|enter)/i.test(n.show.event)&&!/mouse(out|leave)/i.test(n.hide.event)&&h.push("mouseleave"),this._bind(o,"mousemove",function(t){this._storeMouse(t),this.cache.onTarget=C}),this._bindEvents(a,h,o,r,e,function(){clearTimeout(this.timers.show)}),(n.show.ready||n.prerender)&&e.call(this,t)},w._assignEvents=function(){var i=this,n=this.options,o=n.position,r=this.tooltip,a=n.show.target,h=n.hide.target,l=o.container,d=o.viewport,c=s(e),u=(s(e.body),s(t)),v=n.show.event?s.trim(""+n.show.event).split(" "):[],y=n.hide.event?s.trim(""+n.hide.event).split(" "):[];s.each(n.events,function(t,e){i._bind(r,"toggle"===t?["tooltipshow","tooltiphide"]:["tooltip"+t],e,null,r)}),/mouse(out|leave)/i.test(n.hide.event)&&"window"===n.hide.leave&&this._bind(c,["mouseout","blur"],function(t){/select|option/.test(t.target.nodeName)||t.relatedTarget||this.hide(t)}),n.hide.fixed?h=h.add(r.addClass(B)):/mouse(over|enter)/i.test(n.show.event)&&this._bind(h,"mouseleave",function(){clearTimeout(this.timers.show)}),(""+n.hide.event).indexOf("unfocus")>-1&&this._bind(l.closest("html"),["mousedown","touchstart"],function(t){var e=s(t.target),i=this.rendered&&!this.tooltip.hasClass(H)&&this.tooltip[0].offsetWidth>0,n=e.parents(Y).filter(this.tooltip[0]).length>0;e[0]===this.target[0]||e[0]===this.tooltip[0]||n||this.target.has(e[0]).length||!i||this.hide(t)}),"number"==typeof n.hide.inactive&&(this._bind(a,"qtip-"+this.id+"-inactive",g),this._bind(h.add(r),b.inactiveEvents,g,"-inactive")),this._bindEvents(v,y,a,h,p,f),this._bind(a.add(r),"mousemove",function(t){if("number"==typeof n.hide.distance){var e=this.cache.origin||{},i=this.options.hide.distance,s=Math.abs;(s(t.pageX-e.pageX)>=i||s(t.pageY-e.pageY)>=i)&&this.hide(t)}this._storeMouse(t)}),"mouse"===o.target&&o.adjust.mouse&&(n.hide.event&&this._bind(a,["mouseenter","mouseleave"],function(t){this.cache.onTarget="mouseenter"===t.type}),this._bind(c,"mousemove",function(t){this.rendered&&this.cache.onTarget&&!this.tooltip.hasClass(H)&&this.tooltip[0].offsetWidth>0&&this.reposition(t)})),(o.adjust.resize||d.length)&&this._bind(s.event.special.resize?d:u,"resize",m),o.adjust.scroll&&this._bind(u.add(o.container),"scroll",m)},w._unassignEvents=function(){var i=[this.options.show.target[0],this.options.hide.target[0],this.rendered&&this.tooltip[0],this.options.position.container[0],this.options.position.viewport[0],this.options.position.container.closest("html")[0],t,e];this._unbind(s([]).pushStack(s.grep(i,function(t){return"object"==typeof t})))},b=s.fn.qtip=function(t,e,n){var o=(""+t).toLowerCase(),r=q,h=s.makeArray(arguments).slice(1),l=h[h.length-1],d=this[0]?s.data(this[0],O):q;return!arguments.length&&d||"api"===o?d:"string"==typeof t?(this.each(function(){var t=s.data(this,O);if(!t)return C;if(l&&l.timeStamp&&(t.cache.event=l),!e||"option"!==o&&"options"!==o)t[o]&&t[o].apply(t,h);else{if(n===i&&!s.isPlainObject(e))return r=t.get(e),j;t.set(e,n)}}),r!==q?r:this):"object"!=typeof t&&arguments.length?i:(d=a(s.extend(C,{},t)),this.each(function(t){var e,n;return n=s.isArray(d.id)?d.id[t]:d.id,n=!n||n===j||1>n.length||b.api[n]?b.nextid++:n,e=y(s(this),n,d),e===j?C:(b.api[n]=e,s.each(S,function(){"initialize"===this.initialize&&this(e)}),e._assignInitialEvents(l),i)}))},s.qtip=n,b.api={},s.each({attr:function(t,e){if(this.length){var i=this[0],n="title",o=s.data(i,"qtip");if(t===n&&o&&"object"==typeof o&&o.options.suppress)return 2>arguments.length?s.attr(i,R):(o&&o.options.content.attr===n&&o.cache.attr&&o.set("content.text",e),this.attr(R,e))}return s.fn["attr"+Q].apply(this,arguments)},clone:function(t){var e=(s([]),s.fn["clone"+Q].apply(this,arguments));return t||e.filter("["+R+"]").attr("title",function(){return s.attr(this,R)}).removeAttr(R),e}},function(t,e){if(!e||s.fn[t+Q])return C;var i=s.fn[t+Q]=s.fn[t];s.fn[t]=function(){return e.apply(this,arguments)||i.apply(this,arguments)}}),s.ui||(s["cleanData"+Q]=s.cleanData,s.cleanData=function(t){for(var e,i=0;(e=s(t[i])).length;i++)if(e.attr(D))try{e.triggerHandler("removeqtip")}catch(n){}s["cleanData"+Q].apply(this,arguments)}),b.version="2.2.0",b.nextid=0,b.inactiveEvents=$,b.zindex=15e3,b.defaults={prerender:j,id:j,overwrite:C,suppress:C,content:{text:C,attr:"title",title:j,button:j},position:{my:"top left",at:"bottom right",target:j,container:j,viewport:j,adjust:{x:0,y:0,mouse:C,scroll:C,resize:C,method:"flipinvert flipinvert"},effect:function(t,e){s(this).animate(e,{duration:200,queue:j})}},show:{target:j,event:"mouseenter",effect:C,delay:90,solo:j,ready:j,autofocus:j},hide:{target:j,event:"mouseleave",effect:C,delay:0,fixed:j,inactive:j,leave:"window",distance:j},style:{classes:"",widget:j,width:j,height:j,def:C},events:{render:q,move:q,show:q,hide:q,toggle:q,visible:q,hidden:q,focus:q,blur:q}}})})(window,document); //@ sourceMappingURL=http://cdnjs.cloudflare.com/ajax/libs/qtip2/2.2.0/jquery.qtip.min.map
vuonghuuphuc/cdnjs
ajax/libs/qtip2/2.2.0/basic/jquery.qtip.min.js
JavaScript
mit
25,709
<?php defined('BASEPATH') OR exit('No direct script access allowed'); ?><!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>Database Error</title> <style type="text/css"> ::selection { background-color: #E13300; color: white; } ::-moz-selection { background-color: #E13300; color: white; } body { background-color: #fff; margin: 40px; font: 13px/20px normal Helvetica, Arial, sans-serif; color: #4F5155; } a { color: #003399; background-color: transparent; font-weight: normal; } h1 { color: #444; background-color: transparent; border-bottom: 1px solid #D0D0D0; font-size: 19px; font-weight: normal; margin: 0 0 14px 0; padding: 14px 15px 10px 15px; } code { font-family: Consolas, Monaco, Courier New, Courier, monospace; font-size: 12px; background-color: #f9f9f9; border: 1px solid #D0D0D0; color: #002166; display: block; margin: 14px 0 14px 0; padding: 12px 10px 12px 10px; } #container { margin: 10px; border: 1px solid #D0D0D0; box-shadow: 0 0 8px #D0D0D0; } p { margin: 12px 15px 12px 15px; } </style> </head> <body> <div id="container"> <h1><?php echo $heading; ?></h1> <?php echo $message; ?> </div> </body> </html>
atleaststartsomewhere/smmwcrd
application/views/errors/html/error_db.php
PHP
mit
1,183
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="robots" content="index, follow, all" /> <title>Imagine\Gd\Font | Imagine API</title> <link rel="stylesheet" type="text/css" href="../../stylesheet.css"> </head> <body id="class"> <div class="header"> <ul> <li><a href="../../classes.html">Classes</a></li> <li><a href="../../namespaces.html">Namespaces</a></li> <li><a href="../../interfaces.html">Interfaces</a></li> <li><a href="../../doc-index.html">Index</a></li> </ul> <div id="title">Imagine API</div> <div class="type">Class</div> <h1><a href="../../Imagine/Gd.html">Imagine\Gd</a>\Font</h1> </div> <div class="content"> <p>class <strong>Font</strong> extends <a href="../../Imagine/Image/AbstractFont.html"><abbr title="Imagine\Image\AbstractFont">AbstractFont</abbr></a></p> <div class="description"> <p>Font implementation using the GD library</p> <p> </p> </div> <h2>Methods</h2> <table> <tr> <td class="type"> </td> <td class="last"> <a href="#method___construct">__construct</a>(string $file, integer $size, <a href="../../Imagine/Image/Color.html"><abbr title="Imagine\Image\Color">Color</abbr></a> $color) <p>Constructs a font with specified $file, $size and $color</p> </td> <td><small>from&nbsp;<a href="../../Imagine/Image/AbstractFont.html#method___construct"><abbr title="Imagine\Image\AbstractFont">AbstractFont</abbr></a></small></td> </tr> <tr> <td class="type"> string </td> <td class="last"> <a href="#method_getFile">getFile</a>() <p>Gets the fontfile for current font</p> </td> <td><small>from&nbsp;<a href="../../Imagine/Image/AbstractFont.html#method_getFile"><abbr title="Imagine\Image\AbstractFont">AbstractFont</abbr></a></small></td> </tr> <tr> <td class="type"> integer </td> <td class="last"> <a href="#method_getSize">getSize</a>() <p>Gets font's integer point size</p> </td> <td><small>from&nbsp;<a href="../../Imagine/Image/AbstractFont.html#method_getSize"><abbr title="Imagine\Image\AbstractFont">AbstractFont</abbr></a></small></td> </tr> <tr> <td class="type"> <a href="../../Imagine/Image/Color.html"><abbr title="Imagine\Image\Color">Color</abbr></a> </td> <td class="last"> <a href="#method_getColor">getColor</a>() <p>Gets font's color</p> </td> <td><small>from&nbsp;<a href="../../Imagine/Image/AbstractFont.html#method_getColor"><abbr title="Imagine\Image\AbstractFont">AbstractFont</abbr></a></small></td> </tr> <tr> <td class="type"> <a href="../../Imagine/Image/BoxInterface.html"><abbr title="Imagine\Image\BoxInterface">BoxInterface</abbr></a> </td> <td class="last"> <a href="#method_box">box</a>(string $string, integer $angle) <p>Gets BoxInterface of font size on the image based on string and angle</p> </td> <td></td> </tr> </table> <h2>Details</h2> <h3 id="method___construct"> <div class="location">in <a href="../../Imagine/Image/AbstractFont.html#method___construct"><abbr title="Imagine\Image\AbstractFont">AbstractFont</abbr></a> at line 45</div> <code> public <strong>__construct</strong>(string $file, integer $size, <a href="../../Imagine/Image/Color.html"><abbr title="Imagine\Image\Color">Color</abbr></a> $color)</code> </h3> <div class="details"> <p>Constructs a font with specified $file, $size and $color</p> <p>The font size is to be specified in points (e.g. 10pt means 10)</p> <div class="tags"> <h4>Parameters</h4> <table> <tr> <td>string</td> <td>$file</td> <td> </td> </tr> <tr> <td>integer</td> <td>$size</td> <td> </td> </tr> <tr> <td><a href="../../Imagine/Image/Color.html"><abbr title="Imagine\Image\Color">Color</abbr></a></td> <td>$color</td> <td> </td> </tr> </table> </div> </div> <h3 id="method_getFile"> <div class="location">in <a href="../../Imagine/Image/AbstractFont.html#method_getFile"><abbr title="Imagine\Image\AbstractFont">AbstractFont</abbr></a> at line 55</div> <code>final public string <strong>getFile</strong>()</code> </h3> <div class="details"> <p>Gets the fontfile for current font</p> <p> </p> <div class="tags"> <h4>Return Value</h4> <table> <tr> <td>string</td> <td> </td> </tr> </table> </div> </div> <h3 id="method_getSize"> <div class="location">in <a href="../../Imagine/Image/AbstractFont.html#method_getSize"><abbr title="Imagine\Image\AbstractFont">AbstractFont</abbr></a> at line 63</div> <code>final public integer <strong>getSize</strong>()</code> </h3> <div class="details"> <p>Gets font's integer point size</p> <p> </p> <div class="tags"> <h4>Return Value</h4> <table> <tr> <td>integer</td> <td> </td> </tr> </table> </div> </div> <h3 id="method_getColor"> <div class="location">in <a href="../../Imagine/Image/AbstractFont.html#method_getColor"><abbr title="Imagine\Image\AbstractFont">AbstractFont</abbr></a> at line 71</div> <code>final public <a href="../../Imagine/Image/Color.html"><abbr title="Imagine\Image\Color">Color</abbr></a> <strong>getColor</strong>()</code> </h3> <div class="details"> <p>Gets font's color</p> <p> </p> <div class="tags"> <h4>Return Value</h4> <table> <tr> <td><a href="../../Imagine/Image/Color.html"><abbr title="Imagine\Image\Color">Color</abbr></a></td> <td> </td> </tr> </table> </div> </div> <h3 id="method_box"> <div class="location">at line 25</div> <code> public <a href="../../Imagine/Image/BoxInterface.html"><abbr title="Imagine\Image\BoxInterface">BoxInterface</abbr></a> <strong>box</strong>(string $string, integer $angle)</code> </h3> <div class="details"> <p>Gets BoxInterface of font size on the image based on string and angle</p> <p> </p> <div class="tags"> <h4>Parameters</h4> <table> <tr> <td>string</td> <td>$string</td> <td> </td> </tr> <tr> <td>integer</td> <td>$angle</td> <td> </td> </tr> </table> <h4>Return Value</h4> <table> <tr> <td><a href="../../Imagine/Image/BoxInterface.html"><abbr title="Imagine\Image\BoxInterface">BoxInterface</abbr></a></td> <td> </td> </tr> </table> </div> </div> </div> <div id="footer"> Generated by <a href="http://sami.sensiolabs.org/" target="_top">Sami, the API Documentation Generator</a>. </div> </body> </html>
nkhanhquoc/waterfactory
source/vendor/imagine/imagine/docs/API/API/Imagine/Gd/Font.html
HTML
mit
8,919
/* * Copyright © 2012-2014 Intel Corporation * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice (including the next * paragraph) shall be included in all copies or substantial portions of the * Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS * IN THE SOFTWARE. * * Authors: * Eugeni Dodonov <eugeni.dodonov@intel.com> * Daniel Vetter <daniel.vetter@ffwll.ch> * */ #include <linux/pm_runtime.h> #include <linux/vgaarb.h> #include "i915_drv.h" #include "intel_drv.h" /** * DOC: runtime pm * * The i915 driver supports dynamic enabling and disabling of entire hardware * blocks at runtime. This is especially important on the display side where * software is supposed to control many power gates manually on recent hardware, * since on the GT side a lot of the power management is done by the hardware. * But even there some manual control at the device level is required. * * Since i915 supports a diverse set of platforms with a unified codebase and * hardware engineers just love to shuffle functionality around between power * domains there's a sizeable amount of indirection required. This file provides * generic functions to the driver for grabbing and releasing references for * abstract power domains. It then maps those to the actual power wells * present for a given platform. */ #define GEN9_ENABLE_DC5(dev) 0 #define SKL_ENABLE_DC6(dev) IS_SKYLAKE(dev) #define for_each_power_well(i, power_well, domain_mask, power_domains) \ for (i = 0; \ i < (power_domains)->power_well_count && \ ((power_well) = &(power_domains)->power_wells[i]); \ i++) \ if ((power_well)->domains & (domain_mask)) #define for_each_power_well_rev(i, power_well, domain_mask, power_domains) \ for (i = (power_domains)->power_well_count - 1; \ i >= 0 && ((power_well) = &(power_domains)->power_wells[i]);\ i--) \ if ((power_well)->domains & (domain_mask)) bool intel_display_power_well_is_enabled(struct drm_i915_private *dev_priv, int power_well_id); static void intel_power_well_enable(struct drm_i915_private *dev_priv, struct i915_power_well *power_well) { DRM_DEBUG_KMS("enabling %s\n", power_well->name); power_well->ops->enable(dev_priv, power_well); power_well->hw_enabled = true; } static void intel_power_well_disable(struct drm_i915_private *dev_priv, struct i915_power_well *power_well) { DRM_DEBUG_KMS("disabling %s\n", power_well->name); power_well->hw_enabled = false; power_well->ops->disable(dev_priv, power_well); } /* * We should only use the power well if we explicitly asked the hardware to * enable it, so check if it's enabled and also check if we've requested it to * be enabled. */ static bool hsw_power_well_enabled(struct drm_i915_private *dev_priv, struct i915_power_well *power_well) { return I915_READ(HSW_PWR_WELL_DRIVER) == (HSW_PWR_WELL_ENABLE_REQUEST | HSW_PWR_WELL_STATE_ENABLED); } /** * __intel_display_power_is_enabled - unlocked check for a power domain * @dev_priv: i915 device instance * @domain: power domain to check * * This is the unlocked version of intel_display_power_is_enabled() and should * only be used from error capture and recovery code where deadlocks are * possible. * * Returns: * True when the power domain is enabled, false otherwise. */ bool __intel_display_power_is_enabled(struct drm_i915_private *dev_priv, enum intel_display_power_domain domain) { struct i915_power_domains *power_domains; struct i915_power_well *power_well; bool is_enabled; int i; if (dev_priv->pm.suspended) return false; power_domains = &dev_priv->power_domains; is_enabled = true; for_each_power_well_rev(i, power_well, BIT(domain), power_domains) { if (power_well->always_on) continue; if (!power_well->hw_enabled) { is_enabled = false; break; } } return is_enabled; } /** * intel_display_power_is_enabled - check for a power domain * @dev_priv: i915 device instance * @domain: power domain to check * * This function can be used to check the hw power domain state. It is mostly * used in hardware state readout functions. Everywhere else code should rely * upon explicit power domain reference counting to ensure that the hardware * block is powered up before accessing it. * * Callers must hold the relevant modesetting locks to ensure that concurrent * threads can't disable the power well while the caller tries to read a few * registers. * * Returns: * True when the power domain is enabled, false otherwise. */ bool intel_display_power_is_enabled(struct drm_i915_private *dev_priv, enum intel_display_power_domain domain) { struct i915_power_domains *power_domains; bool ret; power_domains = &dev_priv->power_domains; mutex_lock(&power_domains->lock); ret = __intel_display_power_is_enabled(dev_priv, domain); mutex_unlock(&power_domains->lock); return ret; } /** * intel_display_set_init_power - set the initial power domain state * @dev_priv: i915 device instance * @enable: whether to enable or disable the initial power domain state * * For simplicity our driver load/unload and system suspend/resume code assumes * that all power domains are always enabled. This functions controls the state * of this little hack. While the initial power domain state is enabled runtime * pm is effectively disabled. */ void intel_display_set_init_power(struct drm_i915_private *dev_priv, bool enable) { if (dev_priv->power_domains.init_power_on == enable) return; if (enable) intel_display_power_get(dev_priv, POWER_DOMAIN_INIT); else intel_display_power_put(dev_priv, POWER_DOMAIN_INIT); dev_priv->power_domains.init_power_on = enable; } /* * Starting with Haswell, we have a "Power Down Well" that can be turned off * when not needed anymore. We have 4 registers that can request the power well * to be enabled, and it will only be disabled if none of the registers is * requesting it to be enabled. */ static void hsw_power_well_post_enable(struct drm_i915_private *dev_priv) { struct drm_device *dev = dev_priv->dev; /* * After we re-enable the power well, if we touch VGA register 0x3d5 * we'll get unclaimed register interrupts. This stops after we write * anything to the VGA MSR register. The vgacon module uses this * register all the time, so if we unbind our driver and, as a * consequence, bind vgacon, we'll get stuck in an infinite loop at * console_unlock(). So make here we touch the VGA MSR register, making * sure vgacon can keep working normally without triggering interrupts * and error messages. */ vga_get_uninterruptible(dev->pdev, VGA_RSRC_LEGACY_IO); outb(inb(VGA_MSR_READ), VGA_MSR_WRITE); vga_put(dev->pdev, VGA_RSRC_LEGACY_IO); if (IS_BROADWELL(dev)) gen8_irq_power_well_post_enable(dev_priv, 1 << PIPE_C | 1 << PIPE_B); } static void skl_power_well_post_enable(struct drm_i915_private *dev_priv, struct i915_power_well *power_well) { struct drm_device *dev = dev_priv->dev; /* * After we re-enable the power well, if we touch VGA register 0x3d5 * we'll get unclaimed register interrupts. This stops after we write * anything to the VGA MSR register. The vgacon module uses this * register all the time, so if we unbind our driver and, as a * consequence, bind vgacon, we'll get stuck in an infinite loop at * console_unlock(). So make here we touch the VGA MSR register, making * sure vgacon can keep working normally without triggering interrupts * and error messages. */ if (power_well->data == SKL_DISP_PW_2) { vga_get_uninterruptible(dev->pdev, VGA_RSRC_LEGACY_IO); outb(inb(VGA_MSR_READ), VGA_MSR_WRITE); vga_put(dev->pdev, VGA_RSRC_LEGACY_IO); gen8_irq_power_well_post_enable(dev_priv, 1 << PIPE_C | 1 << PIPE_B); } if (power_well->data == SKL_DISP_PW_1) { if (!dev_priv->power_domains.initializing) intel_prepare_ddi(dev); gen8_irq_power_well_post_enable(dev_priv, 1 << PIPE_A); } } static void hsw_set_power_well(struct drm_i915_private *dev_priv, struct i915_power_well *power_well, bool enable) { bool is_enabled, enable_requested; uint32_t tmp; tmp = I915_READ(HSW_PWR_WELL_DRIVER); is_enabled = tmp & HSW_PWR_WELL_STATE_ENABLED; enable_requested = tmp & HSW_PWR_WELL_ENABLE_REQUEST; if (enable) { if (!enable_requested) I915_WRITE(HSW_PWR_WELL_DRIVER, HSW_PWR_WELL_ENABLE_REQUEST); if (!is_enabled) { DRM_DEBUG_KMS("Enabling power well\n"); if (wait_for((I915_READ(HSW_PWR_WELL_DRIVER) & HSW_PWR_WELL_STATE_ENABLED), 20)) DRM_ERROR("Timeout enabling power well\n"); hsw_power_well_post_enable(dev_priv); } } else { if (enable_requested) { I915_WRITE(HSW_PWR_WELL_DRIVER, 0); POSTING_READ(HSW_PWR_WELL_DRIVER); DRM_DEBUG_KMS("Requesting to disable the power well\n"); } } } #define SKL_DISPLAY_POWERWELL_2_POWER_DOMAINS ( \ BIT(POWER_DOMAIN_TRANSCODER_A) | \ BIT(POWER_DOMAIN_PIPE_B) | \ BIT(POWER_DOMAIN_TRANSCODER_B) | \ BIT(POWER_DOMAIN_PIPE_C) | \ BIT(POWER_DOMAIN_TRANSCODER_C) | \ BIT(POWER_DOMAIN_PIPE_B_PANEL_FITTER) | \ BIT(POWER_DOMAIN_PIPE_C_PANEL_FITTER) | \ BIT(POWER_DOMAIN_PORT_DDI_B_2_LANES) | \ BIT(POWER_DOMAIN_PORT_DDI_B_4_LANES) | \ BIT(POWER_DOMAIN_PORT_DDI_C_2_LANES) | \ BIT(POWER_DOMAIN_PORT_DDI_C_4_LANES) | \ BIT(POWER_DOMAIN_PORT_DDI_D_2_LANES) | \ BIT(POWER_DOMAIN_PORT_DDI_D_4_LANES) | \ BIT(POWER_DOMAIN_PORT_DDI_E_2_LANES) | \ BIT(POWER_DOMAIN_AUX_B) | \ BIT(POWER_DOMAIN_AUX_C) | \ BIT(POWER_DOMAIN_AUX_D) | \ BIT(POWER_DOMAIN_AUDIO) | \ BIT(POWER_DOMAIN_VGA) | \ BIT(POWER_DOMAIN_INIT)) #define SKL_DISPLAY_POWERWELL_1_POWER_DOMAINS ( \ SKL_DISPLAY_POWERWELL_2_POWER_DOMAINS | \ BIT(POWER_DOMAIN_PLLS) | \ BIT(POWER_DOMAIN_PIPE_A) | \ BIT(POWER_DOMAIN_TRANSCODER_EDP) | \ BIT(POWER_DOMAIN_PIPE_A_PANEL_FITTER) | \ BIT(POWER_DOMAIN_PORT_DDI_A_2_LANES) | \ BIT(POWER_DOMAIN_PORT_DDI_A_4_LANES) | \ BIT(POWER_DOMAIN_AUX_A) | \ BIT(POWER_DOMAIN_INIT)) #define SKL_DISPLAY_DDI_A_E_POWER_DOMAINS ( \ BIT(POWER_DOMAIN_PORT_DDI_A_2_LANES) | \ BIT(POWER_DOMAIN_PORT_DDI_A_4_LANES) | \ BIT(POWER_DOMAIN_PORT_DDI_E_2_LANES) | \ BIT(POWER_DOMAIN_INIT)) #define SKL_DISPLAY_DDI_B_POWER_DOMAINS ( \ BIT(POWER_DOMAIN_PORT_DDI_B_2_LANES) | \ BIT(POWER_DOMAIN_PORT_DDI_B_4_LANES) | \ BIT(POWER_DOMAIN_INIT)) #define SKL_DISPLAY_DDI_C_POWER_DOMAINS ( \ BIT(POWER_DOMAIN_PORT_DDI_C_2_LANES) | \ BIT(POWER_DOMAIN_PORT_DDI_C_4_LANES) | \ BIT(POWER_DOMAIN_INIT)) #define SKL_DISPLAY_DDI_D_POWER_DOMAINS ( \ BIT(POWER_DOMAIN_PORT_DDI_D_2_LANES) | \ BIT(POWER_DOMAIN_PORT_DDI_D_4_LANES) | \ BIT(POWER_DOMAIN_INIT)) #define SKL_DISPLAY_MISC_IO_POWER_DOMAINS ( \ SKL_DISPLAY_POWERWELL_1_POWER_DOMAINS | \ BIT(POWER_DOMAIN_PLLS) | \ BIT(POWER_DOMAIN_INIT)) #define SKL_DISPLAY_ALWAYS_ON_POWER_DOMAINS ( \ (POWER_DOMAIN_MASK & ~(SKL_DISPLAY_POWERWELL_1_POWER_DOMAINS | \ SKL_DISPLAY_POWERWELL_2_POWER_DOMAINS | \ SKL_DISPLAY_DDI_A_E_POWER_DOMAINS | \ SKL_DISPLAY_DDI_B_POWER_DOMAINS | \ SKL_DISPLAY_DDI_C_POWER_DOMAINS | \ SKL_DISPLAY_DDI_D_POWER_DOMAINS | \ SKL_DISPLAY_MISC_IO_POWER_DOMAINS)) | \ BIT(POWER_DOMAIN_INIT)) #define BXT_DISPLAY_POWERWELL_2_POWER_DOMAINS ( \ BIT(POWER_DOMAIN_TRANSCODER_A) | \ BIT(POWER_DOMAIN_PIPE_B) | \ BIT(POWER_DOMAIN_TRANSCODER_B) | \ BIT(POWER_DOMAIN_PIPE_C) | \ BIT(POWER_DOMAIN_TRANSCODER_C) | \ BIT(POWER_DOMAIN_PIPE_B_PANEL_FITTER) | \ BIT(POWER_DOMAIN_PIPE_C_PANEL_FITTER) | \ BIT(POWER_DOMAIN_PORT_DDI_B_2_LANES) | \ BIT(POWER_DOMAIN_PORT_DDI_B_4_LANES) | \ BIT(POWER_DOMAIN_PORT_DDI_C_2_LANES) | \ BIT(POWER_DOMAIN_PORT_DDI_C_4_LANES) | \ BIT(POWER_DOMAIN_AUX_B) | \ BIT(POWER_DOMAIN_AUX_C) | \ BIT(POWER_DOMAIN_AUDIO) | \ BIT(POWER_DOMAIN_VGA) | \ BIT(POWER_DOMAIN_GMBUS) | \ BIT(POWER_DOMAIN_INIT)) #define BXT_DISPLAY_POWERWELL_1_POWER_DOMAINS ( \ BXT_DISPLAY_POWERWELL_2_POWER_DOMAINS | \ BIT(POWER_DOMAIN_PIPE_A) | \ BIT(POWER_DOMAIN_TRANSCODER_EDP) | \ BIT(POWER_DOMAIN_PIPE_A_PANEL_FITTER) | \ BIT(POWER_DOMAIN_PORT_DDI_A_2_LANES) | \ BIT(POWER_DOMAIN_PORT_DDI_A_4_LANES) | \ BIT(POWER_DOMAIN_AUX_A) | \ BIT(POWER_DOMAIN_PLLS) | \ BIT(POWER_DOMAIN_INIT)) #define BXT_DISPLAY_ALWAYS_ON_POWER_DOMAINS ( \ (POWER_DOMAIN_MASK & ~(BXT_DISPLAY_POWERWELL_1_POWER_DOMAINS | \ BXT_DISPLAY_POWERWELL_2_POWER_DOMAINS)) | \ BIT(POWER_DOMAIN_INIT)) static void assert_can_enable_dc9(struct drm_i915_private *dev_priv) { struct drm_device *dev = dev_priv->dev; WARN(!IS_BROXTON(dev), "Platform doesn't support DC9.\n"); WARN((I915_READ(DC_STATE_EN) & DC_STATE_EN_DC9), "DC9 already programmed to be enabled.\n"); WARN(I915_READ(DC_STATE_EN) & DC_STATE_EN_UPTO_DC5, "DC5 still not disabled to enable DC9.\n"); WARN(I915_READ(HSW_PWR_WELL_DRIVER), "Power well on.\n"); WARN(intel_irqs_enabled(dev_priv), "Interrupts not disabled yet.\n"); /* * TODO: check for the following to verify the conditions to enter DC9 * state are satisfied: * 1] Check relevant display engine registers to verify if mode set * disable sequence was followed. * 2] Check if display uninitialize sequence is initialized. */ } static void assert_can_disable_dc9(struct drm_i915_private *dev_priv) { WARN(intel_irqs_enabled(dev_priv), "Interrupts not disabled yet.\n"); WARN(!(I915_READ(DC_STATE_EN) & DC_STATE_EN_DC9), "DC9 already programmed to be disabled.\n"); WARN(I915_READ(DC_STATE_EN) & DC_STATE_EN_UPTO_DC5, "DC5 still not disabled.\n"); /* * TODO: check for the following to verify DC9 state was indeed * entered before programming to disable it: * 1] Check relevant display engine registers to verify if mode * set disable sequence was followed. * 2] Check if display uninitialize sequence is initialized. */ } void bxt_enable_dc9(struct drm_i915_private *dev_priv) { uint32_t val; assert_can_enable_dc9(dev_priv); DRM_DEBUG_KMS("Enabling DC9\n"); val = I915_READ(DC_STATE_EN); val |= DC_STATE_EN_DC9; I915_WRITE(DC_STATE_EN, val); POSTING_READ(DC_STATE_EN); } void bxt_disable_dc9(struct drm_i915_private *dev_priv) { uint32_t val; assert_can_disable_dc9(dev_priv); DRM_DEBUG_KMS("Disabling DC9\n"); val = I915_READ(DC_STATE_EN); val &= ~DC_STATE_EN_DC9; I915_WRITE(DC_STATE_EN, val); POSTING_READ(DC_STATE_EN); } static void gen9_set_dc_state_debugmask_memory_up( struct drm_i915_private *dev_priv) { uint32_t val; /* The below bit doesn't need to be cleared ever afterwards */ val = I915_READ(DC_STATE_DEBUG); if (!(val & DC_STATE_DEBUG_MASK_MEMORY_UP)) { val |= DC_STATE_DEBUG_MASK_MEMORY_UP; I915_WRITE(DC_STATE_DEBUG, val); POSTING_READ(DC_STATE_DEBUG); } } static void assert_can_enable_dc5(struct drm_i915_private *dev_priv) { struct drm_device *dev = dev_priv->dev; bool pg2_enabled = intel_display_power_well_is_enabled(dev_priv, SKL_DISP_PW_2); WARN_ONCE(!IS_SKYLAKE(dev), "Platform doesn't support DC5.\n"); WARN_ONCE(!HAS_RUNTIME_PM(dev), "Runtime PM not enabled.\n"); WARN_ONCE(pg2_enabled, "PG2 not disabled to enable DC5.\n"); WARN_ONCE((I915_READ(DC_STATE_EN) & DC_STATE_EN_UPTO_DC5), "DC5 already programmed to be enabled.\n"); WARN_ONCE(dev_priv->pm.suspended, "DC5 cannot be enabled, if platform is runtime-suspended.\n"); assert_csr_loaded(dev_priv); } static void assert_can_disable_dc5(struct drm_i915_private *dev_priv) { bool pg2_enabled = intel_display_power_well_is_enabled(dev_priv, SKL_DISP_PW_2); /* * During initialization, the firmware may not be loaded yet. * We still want to make sure that the DC enabling flag is cleared. */ if (dev_priv->power_domains.initializing) return; WARN_ONCE(!pg2_enabled, "PG2 not enabled to disable DC5.\n"); WARN_ONCE(dev_priv->pm.suspended, "Disabling of DC5 while platform is runtime-suspended should never happen.\n"); } static void gen9_enable_dc5(struct drm_i915_private *dev_priv) { uint32_t val; assert_can_enable_dc5(dev_priv); DRM_DEBUG_KMS("Enabling DC5\n"); gen9_set_dc_state_debugmask_memory_up(dev_priv); val = I915_READ(DC_STATE_EN); val &= ~DC_STATE_EN_UPTO_DC5_DC6_MASK; val |= DC_STATE_EN_UPTO_DC5; I915_WRITE(DC_STATE_EN, val); POSTING_READ(DC_STATE_EN); } static void gen9_disable_dc5(struct drm_i915_private *dev_priv) { uint32_t val; assert_can_disable_dc5(dev_priv); DRM_DEBUG_KMS("Disabling DC5\n"); val = I915_READ(DC_STATE_EN); val &= ~DC_STATE_EN_UPTO_DC5; I915_WRITE(DC_STATE_EN, val); POSTING_READ(DC_STATE_EN); } static void assert_can_enable_dc6(struct drm_i915_private *dev_priv) { struct drm_device *dev = dev_priv->dev; WARN_ONCE(!IS_SKYLAKE(dev), "Platform doesn't support DC6.\n"); WARN_ONCE(!HAS_RUNTIME_PM(dev), "Runtime PM not enabled.\n"); WARN_ONCE(I915_READ(UTIL_PIN_CTL) & UTIL_PIN_ENABLE, "Backlight is not disabled.\n"); WARN_ONCE((I915_READ(DC_STATE_EN) & DC_STATE_EN_UPTO_DC6), "DC6 already programmed to be enabled.\n"); assert_csr_loaded(dev_priv); } static void assert_can_disable_dc6(struct drm_i915_private *dev_priv) { /* * During initialization, the firmware may not be loaded yet. * We still want to make sure that the DC enabling flag is cleared. */ if (dev_priv->power_domains.initializing) return; assert_csr_loaded(dev_priv); WARN_ONCE(!(I915_READ(DC_STATE_EN) & DC_STATE_EN_UPTO_DC6), "DC6 already programmed to be disabled.\n"); } static void skl_enable_dc6(struct drm_i915_private *dev_priv) { uint32_t val; assert_can_enable_dc6(dev_priv); DRM_DEBUG_KMS("Enabling DC6\n"); gen9_set_dc_state_debugmask_memory_up(dev_priv); val = I915_READ(DC_STATE_EN); val &= ~DC_STATE_EN_UPTO_DC5_DC6_MASK; val |= DC_STATE_EN_UPTO_DC6; I915_WRITE(DC_STATE_EN, val); POSTING_READ(DC_STATE_EN); } static void skl_disable_dc6(struct drm_i915_private *dev_priv) { uint32_t val; assert_can_disable_dc6(dev_priv); DRM_DEBUG_KMS("Disabling DC6\n"); val = I915_READ(DC_STATE_EN); val &= ~DC_STATE_EN_UPTO_DC6; I915_WRITE(DC_STATE_EN, val); POSTING_READ(DC_STATE_EN); } static void skl_set_power_well(struct drm_i915_private *dev_priv, struct i915_power_well *power_well, bool enable) { struct drm_device *dev = dev_priv->dev; uint32_t tmp, fuse_status; uint32_t req_mask, state_mask; bool is_enabled, enable_requested, check_fuse_status = false; tmp = I915_READ(HSW_PWR_WELL_DRIVER); fuse_status = I915_READ(SKL_FUSE_STATUS); switch (power_well->data) { case SKL_DISP_PW_1: if (wait_for((I915_READ(SKL_FUSE_STATUS) & SKL_FUSE_PG0_DIST_STATUS), 1)) { DRM_ERROR("PG0 not enabled\n"); return; } break; case SKL_DISP_PW_2: if (!(fuse_status & SKL_FUSE_PG1_DIST_STATUS)) { DRM_ERROR("PG1 in disabled state\n"); return; } break; case SKL_DISP_PW_DDI_A_E: case SKL_DISP_PW_DDI_B: case SKL_DISP_PW_DDI_C: case SKL_DISP_PW_DDI_D: case SKL_DISP_PW_MISC_IO: break; default: WARN(1, "Unknown power well %lu\n", power_well->data); return; } req_mask = SKL_POWER_WELL_REQ(power_well->data); enable_requested = tmp & req_mask; state_mask = SKL_POWER_WELL_STATE(power_well->data); is_enabled = tmp & state_mask; if (enable) { if (!enable_requested) { WARN((tmp & state_mask) && !I915_READ(HSW_PWR_WELL_BIOS), "Invalid for power well status to be enabled, unless done by the BIOS, \ when request is to disable!\n"); if ((GEN9_ENABLE_DC5(dev) || SKL_ENABLE_DC6(dev)) && power_well->data == SKL_DISP_PW_2) { if (SKL_ENABLE_DC6(dev)) { skl_disable_dc6(dev_priv); /* * DDI buffer programming unnecessary during driver-load/resume * as it's already done during modeset initialization then. * It's also invalid here as encoder list is still uninitialized. */ if (!dev_priv->power_domains.initializing) intel_prepare_ddi(dev); } else { gen9_disable_dc5(dev_priv); } } I915_WRITE(HSW_PWR_WELL_DRIVER, tmp | req_mask); } if (!is_enabled) { DRM_DEBUG_KMS("Enabling %s\n", power_well->name); if (wait_for((I915_READ(HSW_PWR_WELL_DRIVER) & state_mask), 1)) DRM_ERROR("%s enable timeout\n", power_well->name); check_fuse_status = true; } } else { if (enable_requested) { if (IS_SKYLAKE(dev) && (power_well->data == SKL_DISP_PW_1) && (intel_csr_load_status_get(dev_priv) == FW_LOADED)) DRM_DEBUG_KMS("Not Disabling PW1, dmc will handle\n"); else { I915_WRITE(HSW_PWR_WELL_DRIVER, tmp & ~req_mask); POSTING_READ(HSW_PWR_WELL_DRIVER); DRM_DEBUG_KMS("Disabling %s\n", power_well->name); } if ((GEN9_ENABLE_DC5(dev) || SKL_ENABLE_DC6(dev)) && power_well->data == SKL_DISP_PW_2) { enum csr_state state; /* TODO: wait for a completion event or * similar here instead of busy * waiting using wait_for function. */ wait_for((state = intel_csr_load_status_get(dev_priv)) != FW_UNINITIALIZED, 1000); if (state != FW_LOADED) DRM_DEBUG("CSR firmware not ready (%d)\n", state); else if (SKL_ENABLE_DC6(dev)) skl_enable_dc6(dev_priv); else gen9_enable_dc5(dev_priv); } } } if (check_fuse_status) { if (power_well->data == SKL_DISP_PW_1) { if (wait_for((I915_READ(SKL_FUSE_STATUS) & SKL_FUSE_PG1_DIST_STATUS), 1)) DRM_ERROR("PG1 distributing status timeout\n"); } else if (power_well->data == SKL_DISP_PW_2) { if (wait_for((I915_READ(SKL_FUSE_STATUS) & SKL_FUSE_PG2_DIST_STATUS), 1)) DRM_ERROR("PG2 distributing status timeout\n"); } } if (enable && !is_enabled) skl_power_well_post_enable(dev_priv, power_well); } static void hsw_power_well_sync_hw(struct drm_i915_private *dev_priv, struct i915_power_well *power_well) { hsw_set_power_well(dev_priv, power_well, power_well->count > 0); /* * We're taking over the BIOS, so clear any requests made by it since * the driver is in charge now. */ if (I915_READ(HSW_PWR_WELL_BIOS) & HSW_PWR_WELL_ENABLE_REQUEST) I915_WRITE(HSW_PWR_WELL_BIOS, 0); } static void hsw_power_well_enable(struct drm_i915_private *dev_priv, struct i915_power_well *power_well) { hsw_set_power_well(dev_priv, power_well, true); } static void hsw_power_well_disable(struct drm_i915_private *dev_priv, struct i915_power_well *power_well) { hsw_set_power_well(dev_priv, power_well, false); } static bool skl_power_well_enabled(struct drm_i915_private *dev_priv, struct i915_power_well *power_well) { uint32_t mask = SKL_POWER_WELL_REQ(power_well->data) | SKL_POWER_WELL_STATE(power_well->data); return (I915_READ(HSW_PWR_WELL_DRIVER) & mask) == mask; } static void skl_power_well_sync_hw(struct drm_i915_private *dev_priv, struct i915_power_well *power_well) { skl_set_power_well(dev_priv, power_well, power_well->count > 0); /* Clear any request made by BIOS as driver is taking over */ I915_WRITE(HSW_PWR_WELL_BIOS, 0); } static void skl_power_well_enable(struct drm_i915_private *dev_priv, struct i915_power_well *power_well) { skl_set_power_well(dev_priv, power_well, true); } static void skl_power_well_disable(struct drm_i915_private *dev_priv, struct i915_power_well *power_well) { skl_set_power_well(dev_priv, power_well, false); } static void i9xx_always_on_power_well_noop(struct drm_i915_private *dev_priv, struct i915_power_well *power_well) { } static bool i9xx_always_on_power_well_enabled(struct drm_i915_private *dev_priv, struct i915_power_well *power_well) { return true; } static void vlv_set_power_well(struct drm_i915_private *dev_priv, struct i915_power_well *power_well, bool enable) { enum punit_power_well power_well_id = power_well->data; u32 mask; u32 state; u32 ctrl; mask = PUNIT_PWRGT_MASK(power_well_id); state = enable ? PUNIT_PWRGT_PWR_ON(power_well_id) : PUNIT_PWRGT_PWR_GATE(power_well_id); mutex_lock(&dev_priv->rps.hw_lock); #define COND \ ((vlv_punit_read(dev_priv, PUNIT_REG_PWRGT_STATUS) & mask) == state) if (COND) goto out; ctrl = vlv_punit_read(dev_priv, PUNIT_REG_PWRGT_CTRL); ctrl &= ~mask; ctrl |= state; vlv_punit_write(dev_priv, PUNIT_REG_PWRGT_CTRL, ctrl); if (wait_for(COND, 100)) DRM_ERROR("timeout setting power well state %08x (%08x)\n", state, vlv_punit_read(dev_priv, PUNIT_REG_PWRGT_CTRL)); #undef COND out: mutex_unlock(&dev_priv->rps.hw_lock); } static void vlv_power_well_sync_hw(struct drm_i915_private *dev_priv, struct i915_power_well *power_well) { vlv_set_power_well(dev_priv, power_well, power_well->count > 0); } static void vlv_power_well_enable(struct drm_i915_private *dev_priv, struct i915_power_well *power_well) { vlv_set_power_well(dev_priv, power_well, true); } static void vlv_power_well_disable(struct drm_i915_private *dev_priv, struct i915_power_well *power_well) { vlv_set_power_well(dev_priv, power_well, false); } static bool vlv_power_well_enabled(struct drm_i915_private *dev_priv, struct i915_power_well *power_well) { int power_well_id = power_well->data; bool enabled = false; u32 mask; u32 state; u32 ctrl; mask = PUNIT_PWRGT_MASK(power_well_id); ctrl = PUNIT_PWRGT_PWR_ON(power_well_id); mutex_lock(&dev_priv->rps.hw_lock); state = vlv_punit_read(dev_priv, PUNIT_REG_PWRGT_STATUS) & mask; /* * We only ever set the power-on and power-gate states, anything * else is unexpected. */ WARN_ON(state != PUNIT_PWRGT_PWR_ON(power_well_id) && state != PUNIT_PWRGT_PWR_GATE(power_well_id)); if (state == ctrl) enabled = true; /* * A transient state at this point would mean some unexpected party * is poking at the power controls too. */ ctrl = vlv_punit_read(dev_priv, PUNIT_REG_PWRGT_CTRL) & mask; WARN_ON(ctrl != state); mutex_unlock(&dev_priv->rps.hw_lock); return enabled; } static void vlv_display_power_well_init(struct drm_i915_private *dev_priv) { enum pipe pipe; /* * Enable the CRI clock source so we can get at the * display and the reference clock for VGA * hotplug / manual detection. Supposedly DSI also * needs the ref clock up and running. * * CHV DPLL B/C have some issues if VGA mode is enabled. */ for_each_pipe(dev_priv->dev, pipe) { u32 val = I915_READ(DPLL(pipe)); val |= DPLL_REF_CLK_ENABLE_VLV | DPLL_VGA_MODE_DIS; if (pipe != PIPE_A) val |= DPLL_INTEGRATED_CRI_CLK_VLV; I915_WRITE(DPLL(pipe), val); } spin_lock_irq(&dev_priv->irq_lock); valleyview_enable_display_irqs(dev_priv); spin_unlock_irq(&dev_priv->irq_lock); /* * During driver initialization/resume we can avoid restoring the * part of the HW/SW state that will be inited anyway explicitly. */ if (dev_priv->power_domains.initializing) return; intel_hpd_init(dev_priv); i915_redisable_vga_power_on(dev_priv->dev); } static void vlv_display_power_well_deinit(struct drm_i915_private *dev_priv) { spin_lock_irq(&dev_priv->irq_lock); valleyview_disable_display_irqs(dev_priv); spin_unlock_irq(&dev_priv->irq_lock); vlv_power_sequencer_reset(dev_priv); } static void vlv_display_power_well_enable(struct drm_i915_private *dev_priv, struct i915_power_well *power_well) { WARN_ON_ONCE(power_well->data != PUNIT_POWER_WELL_DISP2D); vlv_set_power_well(dev_priv, power_well, true); vlv_display_power_well_init(dev_priv); } static void vlv_display_power_well_disable(struct drm_i915_private *dev_priv, struct i915_power_well *power_well) { WARN_ON_ONCE(power_well->data != PUNIT_POWER_WELL_DISP2D); vlv_display_power_well_deinit(dev_priv); vlv_set_power_well(dev_priv, power_well, false); } static void vlv_dpio_cmn_power_well_enable(struct drm_i915_private *dev_priv, struct i915_power_well *power_well) { WARN_ON_ONCE(power_well->data != PUNIT_POWER_WELL_DPIO_CMN_BC); /* since ref/cri clock was enabled */ udelay(1); /* >10ns for cmnreset, >0ns for sidereset */ vlv_set_power_well(dev_priv, power_well, true); /* * From VLV2A0_DP_eDP_DPIO_driver_vbios_notes_10.docx - * 6. De-assert cmn_reset/side_reset. Same as VLV X0. * a. GUnit 0x2110 bit[0] set to 1 (def 0) * b. The other bits such as sfr settings / modesel may all * be set to 0. * * This should only be done on init and resume from S3 with * both PLLs disabled, or we risk losing DPIO and PLL * synchronization. */ I915_WRITE(DPIO_CTL, I915_READ(DPIO_CTL) | DPIO_CMNRST); } static void vlv_dpio_cmn_power_well_disable(struct drm_i915_private *dev_priv, struct i915_power_well *power_well) { enum pipe pipe; WARN_ON_ONCE(power_well->data != PUNIT_POWER_WELL_DPIO_CMN_BC); for_each_pipe(dev_priv, pipe) assert_pll_disabled(dev_priv, pipe); /* Assert common reset */ I915_WRITE(DPIO_CTL, I915_READ(DPIO_CTL) & ~DPIO_CMNRST); vlv_set_power_well(dev_priv, power_well, false); } #define POWER_DOMAIN_MASK (BIT(POWER_DOMAIN_NUM) - 1) static struct i915_power_well *lookup_power_well(struct drm_i915_private *dev_priv, int power_well_id) { struct i915_power_domains *power_domains = &dev_priv->power_domains; struct i915_power_well *power_well; int i; for_each_power_well(i, power_well, POWER_DOMAIN_MASK, power_domains) { if (power_well->data == power_well_id) return power_well; } return NULL; } #define BITS_SET(val, bits) (((val) & (bits)) == (bits)) static void assert_chv_phy_status(struct drm_i915_private *dev_priv) { struct i915_power_well *cmn_bc = lookup_power_well(dev_priv, PUNIT_POWER_WELL_DPIO_CMN_BC); struct i915_power_well *cmn_d = lookup_power_well(dev_priv, PUNIT_POWER_WELL_DPIO_CMN_D); u32 phy_control = dev_priv->chv_phy_control; u32 phy_status = 0; u32 phy_status_mask = 0xffffffff; u32 tmp; /* * The BIOS can leave the PHY is some weird state * where it doesn't fully power down some parts. * Disable the asserts until the PHY has been fully * reset (ie. the power well has been disabled at * least once). */ if (!dev_priv->chv_phy_assert[DPIO_PHY0]) phy_status_mask &= ~(PHY_STATUS_CMN_LDO(DPIO_PHY0, DPIO_CH0) | PHY_STATUS_SPLINE_LDO(DPIO_PHY0, DPIO_CH0, 0) | PHY_STATUS_SPLINE_LDO(DPIO_PHY0, DPIO_CH0, 1) | PHY_STATUS_CMN_LDO(DPIO_PHY0, DPIO_CH1) | PHY_STATUS_SPLINE_LDO(DPIO_PHY0, DPIO_CH1, 0) | PHY_STATUS_SPLINE_LDO(DPIO_PHY0, DPIO_CH1, 1)); if (!dev_priv->chv_phy_assert[DPIO_PHY1]) phy_status_mask &= ~(PHY_STATUS_CMN_LDO(DPIO_PHY1, DPIO_CH0) | PHY_STATUS_SPLINE_LDO(DPIO_PHY1, DPIO_CH0, 0) | PHY_STATUS_SPLINE_LDO(DPIO_PHY1, DPIO_CH0, 1)); if (cmn_bc->ops->is_enabled(dev_priv, cmn_bc)) { phy_status |= PHY_POWERGOOD(DPIO_PHY0); /* this assumes override is only used to enable lanes */ if ((phy_control & PHY_CH_POWER_DOWN_OVRD_EN(DPIO_PHY0, DPIO_CH0)) == 0) phy_control |= PHY_CH_POWER_DOWN_OVRD(0xf, DPIO_PHY0, DPIO_CH0); if ((phy_control & PHY_CH_POWER_DOWN_OVRD_EN(DPIO_PHY0, DPIO_CH1)) == 0) phy_control |= PHY_CH_POWER_DOWN_OVRD(0xf, DPIO_PHY0, DPIO_CH1); /* CL1 is on whenever anything is on in either channel */ if (BITS_SET(phy_control, PHY_CH_POWER_DOWN_OVRD(0xf, DPIO_PHY0, DPIO_CH0) | PHY_CH_POWER_DOWN_OVRD(0xf, DPIO_PHY0, DPIO_CH1))) phy_status |= PHY_STATUS_CMN_LDO(DPIO_PHY0, DPIO_CH0); /* * The DPLLB check accounts for the pipe B + port A usage * with CL2 powered up but all the lanes in the second channel * powered down. */ if (BITS_SET(phy_control, PHY_CH_POWER_DOWN_OVRD(0xf, DPIO_PHY0, DPIO_CH1)) && (I915_READ(DPLL(PIPE_B)) & DPLL_VCO_ENABLE) == 0) phy_status |= PHY_STATUS_CMN_LDO(DPIO_PHY0, DPIO_CH1); if (BITS_SET(phy_control, PHY_CH_POWER_DOWN_OVRD(0x3, DPIO_PHY0, DPIO_CH0))) phy_status |= PHY_STATUS_SPLINE_LDO(DPIO_PHY0, DPIO_CH0, 0); if (BITS_SET(phy_control, PHY_CH_POWER_DOWN_OVRD(0xc, DPIO_PHY0, DPIO_CH0))) phy_status |= PHY_STATUS_SPLINE_LDO(DPIO_PHY0, DPIO_CH0, 1); if (BITS_SET(phy_control, PHY_CH_POWER_DOWN_OVRD(0x3, DPIO_PHY0, DPIO_CH1))) phy_status |= PHY_STATUS_SPLINE_LDO(DPIO_PHY0, DPIO_CH1, 0); if (BITS_SET(phy_control, PHY_CH_POWER_DOWN_OVRD(0xc, DPIO_PHY0, DPIO_CH1))) phy_status |= PHY_STATUS_SPLINE_LDO(DPIO_PHY0, DPIO_CH1, 1); } if (cmn_d->ops->is_enabled(dev_priv, cmn_d)) { phy_status |= PHY_POWERGOOD(DPIO_PHY1); /* this assumes override is only used to enable lanes */ if ((phy_control & PHY_CH_POWER_DOWN_OVRD_EN(DPIO_PHY1, DPIO_CH0)) == 0) phy_control |= PHY_CH_POWER_DOWN_OVRD(0xf, DPIO_PHY1, DPIO_CH0); if (BITS_SET(phy_control, PHY_CH_POWER_DOWN_OVRD(0xf, DPIO_PHY1, DPIO_CH0))) phy_status |= PHY_STATUS_CMN_LDO(DPIO_PHY1, DPIO_CH0); if (BITS_SET(phy_control, PHY_CH_POWER_DOWN_OVRD(0x3, DPIO_PHY1, DPIO_CH0))) phy_status |= PHY_STATUS_SPLINE_LDO(DPIO_PHY1, DPIO_CH0, 0); if (BITS_SET(phy_control, PHY_CH_POWER_DOWN_OVRD(0xc, DPIO_PHY1, DPIO_CH0))) phy_status |= PHY_STATUS_SPLINE_LDO(DPIO_PHY1, DPIO_CH0, 1); } phy_status &= phy_status_mask; /* * The PHY may be busy with some initial calibration and whatnot, * so the power state can take a while to actually change. */ if (wait_for((tmp = I915_READ(DISPLAY_PHY_STATUS) & phy_status_mask) == phy_status, 10)) WARN(phy_status != tmp, "Unexpected PHY_STATUS 0x%08x, expected 0x%08x (PHY_CONTROL=0x%08x)\n", tmp, phy_status, dev_priv->chv_phy_control); } #undef BITS_SET static void chv_dpio_cmn_power_well_enable(struct drm_i915_private *dev_priv, struct i915_power_well *power_well) { enum dpio_phy phy; enum pipe pipe; uint32_t tmp; WARN_ON_ONCE(power_well->data != PUNIT_POWER_WELL_DPIO_CMN_BC && power_well->data != PUNIT_POWER_WELL_DPIO_CMN_D); if (power_well->data == PUNIT_POWER_WELL_DPIO_CMN_BC) { pipe = PIPE_A; phy = DPIO_PHY0; } else { pipe = PIPE_C; phy = DPIO_PHY1; } /* since ref/cri clock was enabled */ udelay(1); /* >10ns for cmnreset, >0ns for sidereset */ vlv_set_power_well(dev_priv, power_well, true); /* Poll for phypwrgood signal */ if (wait_for(I915_READ(DISPLAY_PHY_STATUS) & PHY_POWERGOOD(phy), 1)) DRM_ERROR("Display PHY %d is not power up\n", phy); mutex_lock(&dev_priv->sb_lock); /* Enable dynamic power down */ tmp = vlv_dpio_read(dev_priv, pipe, CHV_CMN_DW28); tmp |= DPIO_DYNPWRDOWNEN_CH0 | DPIO_CL1POWERDOWNEN | DPIO_SUS_CLK_CONFIG_GATE_CLKREQ; vlv_dpio_write(dev_priv, pipe, CHV_CMN_DW28, tmp); if (power_well->data == PUNIT_POWER_WELL_DPIO_CMN_BC) { tmp = vlv_dpio_read(dev_priv, pipe, _CHV_CMN_DW6_CH1); tmp |= DPIO_DYNPWRDOWNEN_CH1; vlv_dpio_write(dev_priv, pipe, _CHV_CMN_DW6_CH1, tmp); } else { /* * Force the non-existing CL2 off. BXT does this * too, so maybe it saves some power even though * CL2 doesn't exist? */ tmp = vlv_dpio_read(dev_priv, pipe, CHV_CMN_DW30); tmp |= DPIO_CL2_LDOFUSE_PWRENB; vlv_dpio_write(dev_priv, pipe, CHV_CMN_DW30, tmp); } mutex_unlock(&dev_priv->sb_lock); dev_priv->chv_phy_control |= PHY_COM_LANE_RESET_DEASSERT(phy); I915_WRITE(DISPLAY_PHY_CONTROL, dev_priv->chv_phy_control); DRM_DEBUG_KMS("Enabled DPIO PHY%d (PHY_CONTROL=0x%08x)\n", phy, dev_priv->chv_phy_control); assert_chv_phy_status(dev_priv); } static void chv_dpio_cmn_power_well_disable(struct drm_i915_private *dev_priv, struct i915_power_well *power_well) { enum dpio_phy phy; WARN_ON_ONCE(power_well->data != PUNIT_POWER_WELL_DPIO_CMN_BC && power_well->data != PUNIT_POWER_WELL_DPIO_CMN_D); if (power_well->data == PUNIT_POWER_WELL_DPIO_CMN_BC) { phy = DPIO_PHY0; assert_pll_disabled(dev_priv, PIPE_A); assert_pll_disabled(dev_priv, PIPE_B); } else { phy = DPIO_PHY1; assert_pll_disabled(dev_priv, PIPE_C); } dev_priv->chv_phy_control &= ~PHY_COM_LANE_RESET_DEASSERT(phy); I915_WRITE(DISPLAY_PHY_CONTROL, dev_priv->chv_phy_control); vlv_set_power_well(dev_priv, power_well, false); DRM_DEBUG_KMS("Disabled DPIO PHY%d (PHY_CONTROL=0x%08x)\n", phy, dev_priv->chv_phy_control); /* PHY is fully reset now, so we can enable the PHY state asserts */ dev_priv->chv_phy_assert[phy] = true; assert_chv_phy_status(dev_priv); } static void assert_chv_phy_powergate(struct drm_i915_private *dev_priv, enum dpio_phy phy, enum dpio_channel ch, bool override, unsigned int mask) { enum pipe pipe = phy == DPIO_PHY0 ? PIPE_A : PIPE_C; u32 reg, val, expected, actual; /* * The BIOS can leave the PHY is some weird state * where it doesn't fully power down some parts. * Disable the asserts until the PHY has been fully * reset (ie. the power well has been disabled at * least once). */ if (!dev_priv->chv_phy_assert[phy]) return; if (ch == DPIO_CH0) reg = _CHV_CMN_DW0_CH0; else reg = _CHV_CMN_DW6_CH1; mutex_lock(&dev_priv->sb_lock); val = vlv_dpio_read(dev_priv, pipe, reg); mutex_unlock(&dev_priv->sb_lock); /* * This assumes !override is only used when the port is disabled. * All lanes should power down even without the override when * the port is disabled. */ if (!override || mask == 0xf) { expected = DPIO_ALLDL_POWERDOWN | DPIO_ANYDL_POWERDOWN; /* * If CH1 common lane is not active anymore * (eg. for pipe B DPLL) the entire channel will * shut down, which causes the common lane registers * to read as 0. That means we can't actually check * the lane power down status bits, but as the entire * register reads as 0 it's a good indication that the * channel is indeed entirely powered down. */ if (ch == DPIO_CH1 && val == 0) expected = 0; } else if (mask != 0x0) { expected = DPIO_ANYDL_POWERDOWN; } else { expected = 0; } if (ch == DPIO_CH0) actual = val >> DPIO_ANYDL_POWERDOWN_SHIFT_CH0; else actual = val >> DPIO_ANYDL_POWERDOWN_SHIFT_CH1; actual &= DPIO_ALLDL_POWERDOWN | DPIO_ANYDL_POWERDOWN; WARN(actual != expected, "Unexpected DPIO lane power down: all %d, any %d. Expected: all %d, any %d. (0x%x = 0x%08x)\n", !!(actual & DPIO_ALLDL_POWERDOWN), !!(actual & DPIO_ANYDL_POWERDOWN), !!(expected & DPIO_ALLDL_POWERDOWN), !!(expected & DPIO_ANYDL_POWERDOWN), reg, val); } bool chv_phy_powergate_ch(struct drm_i915_private *dev_priv, enum dpio_phy phy, enum dpio_channel ch, bool override) { struct i915_power_domains *power_domains = &dev_priv->power_domains; bool was_override; mutex_lock(&power_domains->lock); was_override = dev_priv->chv_phy_control & PHY_CH_POWER_DOWN_OVRD_EN(phy, ch); if (override == was_override) goto out; if (override) dev_priv->chv_phy_control |= PHY_CH_POWER_DOWN_OVRD_EN(phy, ch); else dev_priv->chv_phy_control &= ~PHY_CH_POWER_DOWN_OVRD_EN(phy, ch); I915_WRITE(DISPLAY_PHY_CONTROL, dev_priv->chv_phy_control); DRM_DEBUG_KMS("Power gating DPIO PHY%d CH%d (DPIO_PHY_CONTROL=0x%08x)\n", phy, ch, dev_priv->chv_phy_control); assert_chv_phy_status(dev_priv); out: mutex_unlock(&power_domains->lock); return was_override; } void chv_phy_powergate_lanes(struct intel_encoder *encoder, bool override, unsigned int mask) { struct drm_i915_private *dev_priv = to_i915(encoder->base.dev); struct i915_power_domains *power_domains = &dev_priv->power_domains; enum dpio_phy phy = vlv_dport_to_phy(enc_to_dig_port(&encoder->base)); enum dpio_channel ch = vlv_dport_to_channel(enc_to_dig_port(&encoder->base)); mutex_lock(&power_domains->lock); dev_priv->chv_phy_control &= ~PHY_CH_POWER_DOWN_OVRD(0xf, phy, ch); dev_priv->chv_phy_control |= PHY_CH_POWER_DOWN_OVRD(mask, phy, ch); if (override) dev_priv->chv_phy_control |= PHY_CH_POWER_DOWN_OVRD_EN(phy, ch); else dev_priv->chv_phy_control &= ~PHY_CH_POWER_DOWN_OVRD_EN(phy, ch); I915_WRITE(DISPLAY_PHY_CONTROL, dev_priv->chv_phy_control); DRM_DEBUG_KMS("Power gating DPIO PHY%d CH%d lanes 0x%x (PHY_CONTROL=0x%08x)\n", phy, ch, mask, dev_priv->chv_phy_control); assert_chv_phy_status(dev_priv); assert_chv_phy_powergate(dev_priv, phy, ch, override, mask); mutex_unlock(&power_domains->lock); } static bool chv_pipe_power_well_enabled(struct drm_i915_private *dev_priv, struct i915_power_well *power_well) { enum pipe pipe = power_well->data; bool enabled; u32 state, ctrl; mutex_lock(&dev_priv->rps.hw_lock); state = vlv_punit_read(dev_priv, PUNIT_REG_DSPFREQ) & DP_SSS_MASK(pipe); /* * We only ever set the power-on and power-gate states, anything * else is unexpected. */ WARN_ON(state != DP_SSS_PWR_ON(pipe) && state != DP_SSS_PWR_GATE(pipe)); enabled = state == DP_SSS_PWR_ON(pipe); /* * A transient state at this point would mean some unexpected party * is poking at the power controls too. */ ctrl = vlv_punit_read(dev_priv, PUNIT_REG_DSPFREQ) & DP_SSC_MASK(pipe); WARN_ON(ctrl << 16 != state); mutex_unlock(&dev_priv->rps.hw_lock); return enabled; } static void chv_set_pipe_power_well(struct drm_i915_private *dev_priv, struct i915_power_well *power_well, bool enable) { enum pipe pipe = power_well->data; u32 state; u32 ctrl; state = enable ? DP_SSS_PWR_ON(pipe) : DP_SSS_PWR_GATE(pipe); mutex_lock(&dev_priv->rps.hw_lock); #define COND \ ((vlv_punit_read(dev_priv, PUNIT_REG_DSPFREQ) & DP_SSS_MASK(pipe)) == state) if (COND) goto out; ctrl = vlv_punit_read(dev_priv, PUNIT_REG_DSPFREQ); ctrl &= ~DP_SSC_MASK(pipe); ctrl |= enable ? DP_SSC_PWR_ON(pipe) : DP_SSC_PWR_GATE(pipe); vlv_punit_write(dev_priv, PUNIT_REG_DSPFREQ, ctrl); if (wait_for(COND, 100)) DRM_ERROR("timeout setting power well state %08x (%08x)\n", state, vlv_punit_read(dev_priv, PUNIT_REG_DSPFREQ)); #undef COND out: mutex_unlock(&dev_priv->rps.hw_lock); } static void chv_pipe_power_well_sync_hw(struct drm_i915_private *dev_priv, struct i915_power_well *power_well) { WARN_ON_ONCE(power_well->data != PIPE_A); chv_set_pipe_power_well(dev_priv, power_well, power_well->count > 0); } static void chv_pipe_power_well_enable(struct drm_i915_private *dev_priv, struct i915_power_well *power_well) { WARN_ON_ONCE(power_well->data != PIPE_A); chv_set_pipe_power_well(dev_priv, power_well, true); vlv_display_power_well_init(dev_priv); } static void chv_pipe_power_well_disable(struct drm_i915_private *dev_priv, struct i915_power_well *power_well) { WARN_ON_ONCE(power_well->data != PIPE_A); vlv_display_power_well_deinit(dev_priv); chv_set_pipe_power_well(dev_priv, power_well, false); } /** * intel_display_power_get - grab a power domain reference * @dev_priv: i915 device instance * @domain: power domain to reference * * This function grabs a power domain reference for @domain and ensures that the * power domain and all its parents are powered up. Therefore users should only * grab a reference to the innermost power domain they need. * * Any power domain reference obtained by this function must have a symmetric * call to intel_display_power_put() to release the reference again. */ void intel_display_power_get(struct drm_i915_private *dev_priv, enum intel_display_power_domain domain) { struct i915_power_domains *power_domains; struct i915_power_well *power_well; int i; intel_runtime_pm_get(dev_priv); power_domains = &dev_priv->power_domains; mutex_lock(&power_domains->lock); for_each_power_well(i, power_well, BIT(domain), power_domains) { if (!power_well->count++) intel_power_well_enable(dev_priv, power_well); } power_domains->domain_use_count[domain]++; mutex_unlock(&power_domains->lock); } /** * intel_display_power_put - release a power domain reference * @dev_priv: i915 device instance * @domain: power domain to reference * * This function drops the power domain reference obtained by * intel_display_power_get() and might power down the corresponding hardware * block right away if this is the last reference. */ void intel_display_power_put(struct drm_i915_private *dev_priv, enum intel_display_power_domain domain) { struct i915_power_domains *power_domains; struct i915_power_well *power_well; int i; power_domains = &dev_priv->power_domains; mutex_lock(&power_domains->lock); WARN_ON(!power_domains->domain_use_count[domain]); power_domains->domain_use_count[domain]--; for_each_power_well_rev(i, power_well, BIT(domain), power_domains) { WARN_ON(!power_well->count); if (!--power_well->count && i915.disable_power_well) intel_power_well_disable(dev_priv, power_well); } mutex_unlock(&power_domains->lock); intel_runtime_pm_put(dev_priv); } #define HSW_ALWAYS_ON_POWER_DOMAINS ( \ BIT(POWER_DOMAIN_PIPE_A) | \ BIT(POWER_DOMAIN_TRANSCODER_EDP) | \ BIT(POWER_DOMAIN_PORT_DDI_A_2_LANES) | \ BIT(POWER_DOMAIN_PORT_DDI_A_4_LANES) | \ BIT(POWER_DOMAIN_PORT_DDI_B_2_LANES) | \ BIT(POWER_DOMAIN_PORT_DDI_B_4_LANES) | \ BIT(POWER_DOMAIN_PORT_DDI_C_2_LANES) | \ BIT(POWER_DOMAIN_PORT_DDI_C_4_LANES) | \ BIT(POWER_DOMAIN_PORT_DDI_D_2_LANES) | \ BIT(POWER_DOMAIN_PORT_DDI_D_4_LANES) | \ BIT(POWER_DOMAIN_PORT_CRT) | \ BIT(POWER_DOMAIN_PLLS) | \ BIT(POWER_DOMAIN_AUX_A) | \ BIT(POWER_DOMAIN_AUX_B) | \ BIT(POWER_DOMAIN_AUX_C) | \ BIT(POWER_DOMAIN_AUX_D) | \ BIT(POWER_DOMAIN_GMBUS) | \ BIT(POWER_DOMAIN_INIT)) #define HSW_DISPLAY_POWER_DOMAINS ( \ (POWER_DOMAIN_MASK & ~HSW_ALWAYS_ON_POWER_DOMAINS) | \ BIT(POWER_DOMAIN_INIT)) #define BDW_ALWAYS_ON_POWER_DOMAINS ( \ HSW_ALWAYS_ON_POWER_DOMAINS | \ BIT(POWER_DOMAIN_PIPE_A_PANEL_FITTER)) #define BDW_DISPLAY_POWER_DOMAINS ( \ (POWER_DOMAIN_MASK & ~BDW_ALWAYS_ON_POWER_DOMAINS) | \ BIT(POWER_DOMAIN_INIT)) #define VLV_ALWAYS_ON_POWER_DOMAINS BIT(POWER_DOMAIN_INIT) #define VLV_DISPLAY_POWER_DOMAINS POWER_DOMAIN_MASK #define VLV_DPIO_CMN_BC_POWER_DOMAINS ( \ BIT(POWER_DOMAIN_PORT_DDI_B_2_LANES) | \ BIT(POWER_DOMAIN_PORT_DDI_B_4_LANES) | \ BIT(POWER_DOMAIN_PORT_DDI_C_2_LANES) | \ BIT(POWER_DOMAIN_PORT_DDI_C_4_LANES) | \ BIT(POWER_DOMAIN_PORT_CRT) | \ BIT(POWER_DOMAIN_AUX_B) | \ BIT(POWER_DOMAIN_AUX_C) | \ BIT(POWER_DOMAIN_INIT)) #define VLV_DPIO_TX_B_LANES_01_POWER_DOMAINS ( \ BIT(POWER_DOMAIN_PORT_DDI_B_2_LANES) | \ BIT(POWER_DOMAIN_PORT_DDI_B_4_LANES) | \ BIT(POWER_DOMAIN_AUX_B) | \ BIT(POWER_DOMAIN_INIT)) #define VLV_DPIO_TX_B_LANES_23_POWER_DOMAINS ( \ BIT(POWER_DOMAIN_PORT_DDI_B_4_LANES) | \ BIT(POWER_DOMAIN_AUX_B) | \ BIT(POWER_DOMAIN_INIT)) #define VLV_DPIO_TX_C_LANES_01_POWER_DOMAINS ( \ BIT(POWER_DOMAIN_PORT_DDI_C_2_LANES) | \ BIT(POWER_DOMAIN_PORT_DDI_C_4_LANES) | \ BIT(POWER_DOMAIN_AUX_C) | \ BIT(POWER_DOMAIN_INIT)) #define VLV_DPIO_TX_C_LANES_23_POWER_DOMAINS ( \ BIT(POWER_DOMAIN_PORT_DDI_C_4_LANES) | \ BIT(POWER_DOMAIN_AUX_C) | \ BIT(POWER_DOMAIN_INIT)) #define CHV_DPIO_CMN_BC_POWER_DOMAINS ( \ BIT(POWER_DOMAIN_PORT_DDI_B_2_LANES) | \ BIT(POWER_DOMAIN_PORT_DDI_B_4_LANES) | \ BIT(POWER_DOMAIN_PORT_DDI_C_2_LANES) | \ BIT(POWER_DOMAIN_PORT_DDI_C_4_LANES) | \ BIT(POWER_DOMAIN_AUX_B) | \ BIT(POWER_DOMAIN_AUX_C) | \ BIT(POWER_DOMAIN_INIT)) #define CHV_DPIO_CMN_D_POWER_DOMAINS ( \ BIT(POWER_DOMAIN_PORT_DDI_D_2_LANES) | \ BIT(POWER_DOMAIN_PORT_DDI_D_4_LANES) | \ BIT(POWER_DOMAIN_AUX_D) | \ BIT(POWER_DOMAIN_INIT)) static const struct i915_power_well_ops i9xx_always_on_power_well_ops = { .sync_hw = i9xx_always_on_power_well_noop, .enable = i9xx_always_on_power_well_noop, .disable = i9xx_always_on_power_well_noop, .is_enabled = i9xx_always_on_power_well_enabled, }; static const struct i915_power_well_ops chv_pipe_power_well_ops = { .sync_hw = chv_pipe_power_well_sync_hw, .enable = chv_pipe_power_well_enable, .disable = chv_pipe_power_well_disable, .is_enabled = chv_pipe_power_well_enabled, }; static const struct i915_power_well_ops chv_dpio_cmn_power_well_ops = { .sync_hw = vlv_power_well_sync_hw, .enable = chv_dpio_cmn_power_well_enable, .disable = chv_dpio_cmn_power_well_disable, .is_enabled = vlv_power_well_enabled, }; static struct i915_power_well i9xx_always_on_power_well[] = { { .name = "always-on", .always_on = 1, .domains = POWER_DOMAIN_MASK, .ops = &i9xx_always_on_power_well_ops, }, }; static const struct i915_power_well_ops hsw_power_well_ops = { .sync_hw = hsw_power_well_sync_hw, .enable = hsw_power_well_enable, .disable = hsw_power_well_disable, .is_enabled = hsw_power_well_enabled, }; static const struct i915_power_well_ops skl_power_well_ops = { .sync_hw = skl_power_well_sync_hw, .enable = skl_power_well_enable, .disable = skl_power_well_disable, .is_enabled = skl_power_well_enabled, }; static struct i915_power_well hsw_power_wells[] = { { .name = "always-on", .always_on = 1, .domains = HSW_ALWAYS_ON_POWER_DOMAINS, .ops = &i9xx_always_on_power_well_ops, }, { .name = "display", .domains = HSW_DISPLAY_POWER_DOMAINS, .ops = &hsw_power_well_ops, }, }; static struct i915_power_well bdw_power_wells[] = { { .name = "always-on", .always_on = 1, .domains = BDW_ALWAYS_ON_POWER_DOMAINS, .ops = &i9xx_always_on_power_well_ops, }, { .name = "display", .domains = BDW_DISPLAY_POWER_DOMAINS, .ops = &hsw_power_well_ops, }, }; static const struct i915_power_well_ops vlv_display_power_well_ops = { .sync_hw = vlv_power_well_sync_hw, .enable = vlv_display_power_well_enable, .disable = vlv_display_power_well_disable, .is_enabled = vlv_power_well_enabled, }; static const struct i915_power_well_ops vlv_dpio_cmn_power_well_ops = { .sync_hw = vlv_power_well_sync_hw, .enable = vlv_dpio_cmn_power_well_enable, .disable = vlv_dpio_cmn_power_well_disable, .is_enabled = vlv_power_well_enabled, }; static const struct i915_power_well_ops vlv_dpio_power_well_ops = { .sync_hw = vlv_power_well_sync_hw, .enable = vlv_power_well_enable, .disable = vlv_power_well_disable, .is_enabled = vlv_power_well_enabled, }; static struct i915_power_well vlv_power_wells[] = { { .name = "always-on", .always_on = 1, .domains = VLV_ALWAYS_ON_POWER_DOMAINS, .ops = &i9xx_always_on_power_well_ops, }, { .name = "display", .domains = VLV_DISPLAY_POWER_DOMAINS, .data = PUNIT_POWER_WELL_DISP2D, .ops = &vlv_display_power_well_ops, }, { .name = "dpio-tx-b-01", .domains = VLV_DPIO_TX_B_LANES_01_POWER_DOMAINS | VLV_DPIO_TX_B_LANES_23_POWER_DOMAINS | VLV_DPIO_TX_C_LANES_01_POWER_DOMAINS | VLV_DPIO_TX_C_LANES_23_POWER_DOMAINS, .ops = &vlv_dpio_power_well_ops, .data = PUNIT_POWER_WELL_DPIO_TX_B_LANES_01, }, { .name = "dpio-tx-b-23", .domains = VLV_DPIO_TX_B_LANES_01_POWER_DOMAINS | VLV_DPIO_TX_B_LANES_23_POWER_DOMAINS | VLV_DPIO_TX_C_LANES_01_POWER_DOMAINS | VLV_DPIO_TX_C_LANES_23_POWER_DOMAINS, .ops = &vlv_dpio_power_well_ops, .data = PUNIT_POWER_WELL_DPIO_TX_B_LANES_23, }, { .name = "dpio-tx-c-01", .domains = VLV_DPIO_TX_B_LANES_01_POWER_DOMAINS | VLV_DPIO_TX_B_LANES_23_POWER_DOMAINS | VLV_DPIO_TX_C_LANES_01_POWER_DOMAINS | VLV_DPIO_TX_C_LANES_23_POWER_DOMAINS, .ops = &vlv_dpio_power_well_ops, .data = PUNIT_POWER_WELL_DPIO_TX_C_LANES_01, }, { .name = "dpio-tx-c-23", .domains = VLV_DPIO_TX_B_LANES_01_POWER_DOMAINS | VLV_DPIO_TX_B_LANES_23_POWER_DOMAINS | VLV_DPIO_TX_C_LANES_01_POWER_DOMAINS | VLV_DPIO_TX_C_LANES_23_POWER_DOMAINS, .ops = &vlv_dpio_power_well_ops, .data = PUNIT_POWER_WELL_DPIO_TX_C_LANES_23, }, { .name = "dpio-common", .domains = VLV_DPIO_CMN_BC_POWER_DOMAINS, .data = PUNIT_POWER_WELL_DPIO_CMN_BC, .ops = &vlv_dpio_cmn_power_well_ops, }, }; static struct i915_power_well chv_power_wells[] = { { .name = "always-on", .always_on = 1, .domains = VLV_ALWAYS_ON_POWER_DOMAINS, .ops = &i9xx_always_on_power_well_ops, }, { .name = "display", /* * Pipe A power well is the new disp2d well. Pipe B and C * power wells don't actually exist. Pipe A power well is * required for any pipe to work. */ .domains = VLV_DISPLAY_POWER_DOMAINS, .data = PIPE_A, .ops = &chv_pipe_power_well_ops, }, { .name = "dpio-common-bc", .domains = CHV_DPIO_CMN_BC_POWER_DOMAINS, .data = PUNIT_POWER_WELL_DPIO_CMN_BC, .ops = &chv_dpio_cmn_power_well_ops, }, { .name = "dpio-common-d", .domains = CHV_DPIO_CMN_D_POWER_DOMAINS, .data = PUNIT_POWER_WELL_DPIO_CMN_D, .ops = &chv_dpio_cmn_power_well_ops, }, }; bool intel_display_power_well_is_enabled(struct drm_i915_private *dev_priv, int power_well_id) { struct i915_power_well *power_well; bool ret; power_well = lookup_power_well(dev_priv, power_well_id); ret = power_well->ops->is_enabled(dev_priv, power_well); return ret; } static struct i915_power_well skl_power_wells[] = { { .name = "always-on", .always_on = 1, .domains = SKL_DISPLAY_ALWAYS_ON_POWER_DOMAINS, .ops = &i9xx_always_on_power_well_ops, }, { .name = "power well 1", .domains = SKL_DISPLAY_POWERWELL_1_POWER_DOMAINS, .ops = &skl_power_well_ops, .data = SKL_DISP_PW_1, }, { .name = "MISC IO power well", .domains = SKL_DISPLAY_MISC_IO_POWER_DOMAINS, .ops = &skl_power_well_ops, .data = SKL_DISP_PW_MISC_IO, }, { .name = "power well 2", .domains = SKL_DISPLAY_POWERWELL_2_POWER_DOMAINS, .ops = &skl_power_well_ops, .data = SKL_DISP_PW_2, }, { .name = "DDI A/E power well", .domains = SKL_DISPLAY_DDI_A_E_POWER_DOMAINS, .ops = &skl_power_well_ops, .data = SKL_DISP_PW_DDI_A_E, }, { .name = "DDI B power well", .domains = SKL_DISPLAY_DDI_B_POWER_DOMAINS, .ops = &skl_power_well_ops, .data = SKL_DISP_PW_DDI_B, }, { .name = "DDI C power well", .domains = SKL_DISPLAY_DDI_C_POWER_DOMAINS, .ops = &skl_power_well_ops, .data = SKL_DISP_PW_DDI_C, }, { .name = "DDI D power well", .domains = SKL_DISPLAY_DDI_D_POWER_DOMAINS, .ops = &skl_power_well_ops, .data = SKL_DISP_PW_DDI_D, }, }; static struct i915_power_well bxt_power_wells[] = { { .name = "always-on", .always_on = 1, .domains = BXT_DISPLAY_ALWAYS_ON_POWER_DOMAINS, .ops = &i9xx_always_on_power_well_ops, }, { .name = "power well 1", .domains = BXT_DISPLAY_POWERWELL_1_POWER_DOMAINS, .ops = &skl_power_well_ops, .data = SKL_DISP_PW_1, }, { .name = "power well 2", .domains = BXT_DISPLAY_POWERWELL_2_POWER_DOMAINS, .ops = &skl_power_well_ops, .data = SKL_DISP_PW_2, } }; static int sanitize_disable_power_well_option(const struct drm_i915_private *dev_priv, int disable_power_well) { if (disable_power_well >= 0) return !!disable_power_well; if (IS_SKYLAKE(dev_priv)) { DRM_DEBUG_KMS("Disabling display power well support\n"); return 0; } return 1; } #define set_power_wells(power_domains, __power_wells) ({ \ (power_domains)->power_wells = (__power_wells); \ (power_domains)->power_well_count = ARRAY_SIZE(__power_wells); \ }) /** * intel_power_domains_init - initializes the power domain structures * @dev_priv: i915 device instance * * Initializes the power domain structures for @dev_priv depending upon the * supported platform. */ int intel_power_domains_init(struct drm_i915_private *dev_priv) { struct i915_power_domains *power_domains = &dev_priv->power_domains; i915.disable_power_well = sanitize_disable_power_well_option(dev_priv, i915.disable_power_well); BUILD_BUG_ON(POWER_DOMAIN_NUM > 31); mutex_init(&power_domains->lock); /* * The enabling order will be from lower to higher indexed wells, * the disabling order is reversed. */ if (IS_HASWELL(dev_priv->dev)) { set_power_wells(power_domains, hsw_power_wells); } else if (IS_BROADWELL(dev_priv->dev)) { set_power_wells(power_domains, bdw_power_wells); } else if (IS_SKYLAKE(dev_priv->dev)) { set_power_wells(power_domains, skl_power_wells); } else if (IS_BROXTON(dev_priv->dev)) { set_power_wells(power_domains, bxt_power_wells); } else if (IS_CHERRYVIEW(dev_priv->dev)) { set_power_wells(power_domains, chv_power_wells); } else if (IS_VALLEYVIEW(dev_priv->dev)) { set_power_wells(power_domains, vlv_power_wells); } else { set_power_wells(power_domains, i9xx_always_on_power_well); } return 0; } static void intel_runtime_pm_disable(struct drm_i915_private *dev_priv) { struct drm_device *dev = dev_priv->dev; struct device *device = &dev->pdev->dev; if (!HAS_RUNTIME_PM(dev)) return; if (!intel_enable_rc6(dev)) return; /* Make sure we're not suspended first. */ pm_runtime_get_sync(device); } /** * intel_power_domains_fini - finalizes the power domain structures * @dev_priv: i915 device instance * * Finalizes the power domain structures for @dev_priv depending upon the * supported platform. This function also disables runtime pm and ensures that * the device stays powered up so that the driver can be reloaded. */ void intel_power_domains_fini(struct drm_i915_private *dev_priv) { intel_runtime_pm_disable(dev_priv); /* The i915.ko module is still not prepared to be loaded when * the power well is not enabled, so just enable it in case * we're going to unload/reload. */ intel_display_set_init_power(dev_priv, true); } static void intel_power_domains_resume(struct drm_i915_private *dev_priv) { struct i915_power_domains *power_domains = &dev_priv->power_domains; struct i915_power_well *power_well; int i; mutex_lock(&power_domains->lock); for_each_power_well(i, power_well, POWER_DOMAIN_MASK, power_domains) { power_well->ops->sync_hw(dev_priv, power_well); power_well->hw_enabled = power_well->ops->is_enabled(dev_priv, power_well); } mutex_unlock(&power_domains->lock); } static void chv_phy_control_init(struct drm_i915_private *dev_priv) { struct i915_power_well *cmn_bc = lookup_power_well(dev_priv, PUNIT_POWER_WELL_DPIO_CMN_BC); struct i915_power_well *cmn_d = lookup_power_well(dev_priv, PUNIT_POWER_WELL_DPIO_CMN_D); /* * DISPLAY_PHY_CONTROL can get corrupted if read. As a * workaround never ever read DISPLAY_PHY_CONTROL, and * instead maintain a shadow copy ourselves. Use the actual * power well state and lane status to reconstruct the * expected initial value. */ dev_priv->chv_phy_control = PHY_LDO_SEQ_DELAY(PHY_LDO_DELAY_600NS, DPIO_PHY0) | PHY_LDO_SEQ_DELAY(PHY_LDO_DELAY_600NS, DPIO_PHY1) | PHY_CH_POWER_MODE(PHY_CH_DEEP_PSR, DPIO_PHY0, DPIO_CH0) | PHY_CH_POWER_MODE(PHY_CH_DEEP_PSR, DPIO_PHY0, DPIO_CH1) | PHY_CH_POWER_MODE(PHY_CH_DEEP_PSR, DPIO_PHY1, DPIO_CH0); /* * If all lanes are disabled we leave the override disabled * with all power down bits cleared to match the state we * would use after disabling the port. Otherwise enable the * override and set the lane powerdown bits accding to the * current lane status. */ if (cmn_bc->ops->is_enabled(dev_priv, cmn_bc)) { uint32_t status = I915_READ(DPLL(PIPE_A)); unsigned int mask; mask = status & DPLL_PORTB_READY_MASK; if (mask == 0xf) mask = 0x0; else dev_priv->chv_phy_control |= PHY_CH_POWER_DOWN_OVRD_EN(DPIO_PHY0, DPIO_CH0); dev_priv->chv_phy_control |= PHY_CH_POWER_DOWN_OVRD(mask, DPIO_PHY0, DPIO_CH0); mask = (status & DPLL_PORTC_READY_MASK) >> 4; if (mask == 0xf) mask = 0x0; else dev_priv->chv_phy_control |= PHY_CH_POWER_DOWN_OVRD_EN(DPIO_PHY0, DPIO_CH1); dev_priv->chv_phy_control |= PHY_CH_POWER_DOWN_OVRD(mask, DPIO_PHY0, DPIO_CH1); dev_priv->chv_phy_control |= PHY_COM_LANE_RESET_DEASSERT(DPIO_PHY0); dev_priv->chv_phy_assert[DPIO_PHY0] = false; } else { dev_priv->chv_phy_assert[DPIO_PHY0] = true; } if (cmn_d->ops->is_enabled(dev_priv, cmn_d)) { uint32_t status = I915_READ(DPIO_PHY_STATUS); unsigned int mask; mask = status & DPLL_PORTD_READY_MASK; if (mask == 0xf) mask = 0x0; else dev_priv->chv_phy_control |= PHY_CH_POWER_DOWN_OVRD_EN(DPIO_PHY1, DPIO_CH0); dev_priv->chv_phy_control |= PHY_CH_POWER_DOWN_OVRD(mask, DPIO_PHY1, DPIO_CH0); dev_priv->chv_phy_control |= PHY_COM_LANE_RESET_DEASSERT(DPIO_PHY1); dev_priv->chv_phy_assert[DPIO_PHY1] = false; } else { dev_priv->chv_phy_assert[DPIO_PHY1] = true; } I915_WRITE(DISPLAY_PHY_CONTROL, dev_priv->chv_phy_control); DRM_DEBUG_KMS("Initial PHY_CONTROL=0x%08x\n", dev_priv->chv_phy_control); } static void vlv_cmnlane_wa(struct drm_i915_private *dev_priv) { struct i915_power_well *cmn = lookup_power_well(dev_priv, PUNIT_POWER_WELL_DPIO_CMN_BC); struct i915_power_well *disp2d = lookup_power_well(dev_priv, PUNIT_POWER_WELL_DISP2D); /* If the display might be already active skip this */ if (cmn->ops->is_enabled(dev_priv, cmn) && disp2d->ops->is_enabled(dev_priv, disp2d) && I915_READ(DPIO_CTL) & DPIO_CMNRST) return; DRM_DEBUG_KMS("toggling display PHY side reset\n"); /* cmnlane needs DPLL registers */ disp2d->ops->enable(dev_priv, disp2d); /* * From VLV2A0_DP_eDP_HDMI_DPIO_driver_vbios_notes_11.docx: * Need to assert and de-assert PHY SB reset by gating the * common lane power, then un-gating it. * Simply ungating isn't enough to reset the PHY enough to get * ports and lanes running. */ cmn->ops->disable(dev_priv, cmn); } /** * intel_power_domains_init_hw - initialize hardware power domain state * @dev_priv: i915 device instance * * This function initializes the hardware power domain state and enables all * power domains using intel_display_set_init_power(). */ void intel_power_domains_init_hw(struct drm_i915_private *dev_priv) { struct drm_device *dev = dev_priv->dev; struct i915_power_domains *power_domains = &dev_priv->power_domains; power_domains->initializing = true; if (IS_CHERRYVIEW(dev)) { mutex_lock(&power_domains->lock); chv_phy_control_init(dev_priv); mutex_unlock(&power_domains->lock); } else if (IS_VALLEYVIEW(dev)) { mutex_lock(&power_domains->lock); vlv_cmnlane_wa(dev_priv); mutex_unlock(&power_domains->lock); } /* For now, we need the power well to be always enabled. */ intel_display_set_init_power(dev_priv, true); intel_power_domains_resume(dev_priv); power_domains->initializing = false; } /** * intel_runtime_pm_get - grab a runtime pm reference * @dev_priv: i915 device instance * * This function grabs a device-level runtime pm reference (mostly used for GEM * code to ensure the GTT or GT is on) and ensures that it is powered up. * * Any runtime pm reference obtained by this function must have a symmetric * call to intel_runtime_pm_put() to release the reference again. */ void intel_runtime_pm_get(struct drm_i915_private *dev_priv) { struct drm_device *dev = dev_priv->dev; struct device *device = &dev->pdev->dev; if (!HAS_RUNTIME_PM(dev)) return; pm_runtime_get_sync(device); WARN(dev_priv->pm.suspended, "Device still suspended.\n"); } /** * intel_runtime_pm_get_noresume - grab a runtime pm reference * @dev_priv: i915 device instance * * This function grabs a device-level runtime pm reference (mostly used for GEM * code to ensure the GTT or GT is on). * * It will _not_ power up the device but instead only check that it's powered * on. Therefore it is only valid to call this functions from contexts where * the device is known to be powered up and where trying to power it up would * result in hilarity and deadlocks. That pretty much means only the system * suspend/resume code where this is used to grab runtime pm references for * delayed setup down in work items. * * Any runtime pm reference obtained by this function must have a symmetric * call to intel_runtime_pm_put() to release the reference again. */ void intel_runtime_pm_get_noresume(struct drm_i915_private *dev_priv) { struct drm_device *dev = dev_priv->dev; struct device *device = &dev->pdev->dev; if (!HAS_RUNTIME_PM(dev)) return; WARN(dev_priv->pm.suspended, "Getting nosync-ref while suspended.\n"); pm_runtime_get_noresume(device); } /** * intel_runtime_pm_put - release a runtime pm reference * @dev_priv: i915 device instance * * This function drops the device-level runtime pm reference obtained by * intel_runtime_pm_get() and might power down the corresponding * hardware block right away if this is the last reference. */ void intel_runtime_pm_put(struct drm_i915_private *dev_priv) { struct drm_device *dev = dev_priv->dev; struct device *device = &dev->pdev->dev; if (!HAS_RUNTIME_PM(dev)) return; pm_runtime_mark_last_busy(device); pm_runtime_put_autosuspend(device); } /** * intel_runtime_pm_enable - enable runtime pm * @dev_priv: i915 device instance * * This function enables runtime pm at the end of the driver load sequence. * * Note that this function does currently not enable runtime pm for the * subordinate display power domains. That is only done on the first modeset * using intel_display_set_init_power(). */ void intel_runtime_pm_enable(struct drm_i915_private *dev_priv) { struct drm_device *dev = dev_priv->dev; struct device *device = &dev->pdev->dev; if (!HAS_RUNTIME_PM(dev)) return; /* * RPM depends on RC6 to save restore the GT HW context, so make RC6 a * requirement. */ if (!intel_enable_rc6(dev)) { DRM_INFO("RC6 disabled, disabling runtime PM support\n"); return; } pm_runtime_set_autosuspend_delay(device, 10000); /* 10s */ pm_runtime_mark_last_busy(device); pm_runtime_use_autosuspend(device); pm_runtime_put_autosuspend(device); }
KristFoundation/Programs
luaide/drivers/gpu/drm/i915/intel_runtime_pm.c
C
mit
65,965
/* e_chil_err.c */ /* ==================================================================== * Copyright (c) 1999-2005 The OpenSSL Project. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. All advertising materials mentioning features or use of this * software must display the following acknowledgment: * "This product includes software developed by the OpenSSL Project * for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)" * * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to * endorse or promote products derived from this software without * prior written permission. For written permission, please contact * openssl-core@OpenSSL.org. * * 5. Products derived from this software may not be called "OpenSSL" * nor may "OpenSSL" appear in their names without prior written * permission of the OpenSSL Project. * * 6. Redistributions of any form whatsoever must retain the following * acknowledgment: * "This product includes software developed by the OpenSSL Project * for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)" * * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. * ==================================================================== * * This product includes cryptographic software written by Eric Young * (eay@cryptsoft.com). This product includes software written by Tim * Hudson (tjh@cryptsoft.com). * */ /* * NOTE: this file was auto generated by the mkerr.pl script: any changes * made to it will be overwritten when the script next updates this file, * only reason strings will be preserved. */ #include <stdio.h> #include <openssl/err.h> #include "e_chil_err.h" /* BEGIN ERROR CODES */ #ifndef OPENSSL_NO_ERR # define ERR_FUNC(func) ERR_PACK(0,func,0) # define ERR_REASON(reason) ERR_PACK(0,0,reason) static ERR_STRING_DATA HWCRHK_str_functs[] = { {ERR_FUNC(HWCRHK_F_HWCRHK_CTRL), "HWCRHK_CTRL"}, {ERR_FUNC(HWCRHK_F_HWCRHK_FINISH), "HWCRHK_FINISH"}, {ERR_FUNC(HWCRHK_F_HWCRHK_GET_PASS), "HWCRHK_GET_PASS"}, {ERR_FUNC(HWCRHK_F_HWCRHK_INIT), "HWCRHK_INIT"}, {ERR_FUNC(HWCRHK_F_HWCRHK_INSERT_CARD), "HWCRHK_INSERT_CARD"}, {ERR_FUNC(HWCRHK_F_HWCRHK_LOAD_PRIVKEY), "HWCRHK_LOAD_PRIVKEY"}, {ERR_FUNC(HWCRHK_F_HWCRHK_LOAD_PUBKEY), "HWCRHK_LOAD_PUBKEY"}, {ERR_FUNC(HWCRHK_F_HWCRHK_MOD_EXP), "HWCRHK_MOD_EXP"}, {ERR_FUNC(HWCRHK_F_HWCRHK_RAND_BYTES), "HWCRHK_RAND_BYTES"}, {ERR_FUNC(HWCRHK_F_HWCRHK_RSA_MOD_EXP), "HWCRHK_RSA_MOD_EXP"}, {0, NULL} }; static ERR_STRING_DATA HWCRHK_str_reasons[] = { {ERR_REASON(HWCRHK_R_ALREADY_LOADED), "already loaded"}, {ERR_REASON(HWCRHK_R_BIO_WAS_FREED), "bio was freed"}, {ERR_REASON(HWCRHK_R_CHIL_ERROR), "chil error"}, {ERR_REASON(HWCRHK_R_CTRL_COMMAND_NOT_IMPLEMENTED), "ctrl command not implemented"}, {ERR_REASON(HWCRHK_R_DSO_FAILURE), "dso failure"}, {ERR_REASON(HWCRHK_R_MISSING_KEY_COMPONENTS), "missing key components"}, {ERR_REASON(HWCRHK_R_NOT_INITIALISED), "not initialised"}, {ERR_REASON(HWCRHK_R_NOT_LOADED), "not loaded"}, {ERR_REASON(HWCRHK_R_NO_CALLBACK), "no callback"}, {ERR_REASON(HWCRHK_R_NO_KEY), "no key"}, {ERR_REASON(HWCRHK_R_PRIVATE_KEY_ALGORITHMS_DISABLED), "private key algorithms disabled"}, {ERR_REASON(HWCRHK_R_REQUEST_FAILED), "request failed"}, {ERR_REASON(HWCRHK_R_REQUEST_FALLBACK), "request fallback"}, {ERR_REASON(HWCRHK_R_UNIT_FAILURE), "unit failure"}, {0, NULL} }; #endif #ifdef HWCRHK_LIB_NAME static ERR_STRING_DATA HWCRHK_lib_name[] = { {0, HWCRHK_LIB_NAME}, {0, NULL} }; #endif static int HWCRHK_lib_error_code = 0; static int HWCRHK_error_init = 1; static void ERR_load_HWCRHK_strings(void) { if (HWCRHK_lib_error_code == 0) HWCRHK_lib_error_code = ERR_get_next_error_library(); if (HWCRHK_error_init) { HWCRHK_error_init = 0; #ifndef OPENSSL_NO_ERR ERR_load_strings(HWCRHK_lib_error_code, HWCRHK_str_functs); ERR_load_strings(HWCRHK_lib_error_code, HWCRHK_str_reasons); #endif #ifdef HWCRHK_LIB_NAME HWCRHK_lib_name->error = ERR_PACK(HWCRHK_lib_error_code, 0, 0); ERR_load_strings(0, HWCRHK_lib_name); #endif } } static void ERR_unload_HWCRHK_strings(void) { if (HWCRHK_error_init == 0) { #ifndef OPENSSL_NO_ERR ERR_unload_strings(HWCRHK_lib_error_code, HWCRHK_str_functs); ERR_unload_strings(HWCRHK_lib_error_code, HWCRHK_str_reasons); #endif #ifdef HWCRHK_LIB_NAME ERR_unload_strings(0, HWCRHK_lib_name); #endif HWCRHK_error_init = 1; } } static void ERR_HWCRHK_error(int function, int reason, char *file, int line) { if (HWCRHK_lib_error_code == 0) HWCRHK_lib_error_code = ERR_get_next_error_library(); ERR_PUT_error(HWCRHK_lib_error_code, function, reason, file, line); }
nodenative/nodenative
deps/openssl/openssl/engines/e_chil_err.c
C
mit
6,057
PR.registerLangHandler(PR.createSimpleLexer([["pln",/^[\t\n\r \xa0\u2028\u2029]+/,null,"\t\n\r Â\xa0

"],["str",/^(?:["\u201c\u201d](?:[^"\u201c\u201d]|["\u201c\u201d]{2})(?:["\u201c\u201d]c|$)|["\u201c\u201d](?:[^"\u201c\u201d]|["\u201c\u201d]{2})*(?:["\u201c\u201d]|$))/i,null,'"“”'],["com",/^['\u2018\u2019].*/,null,"'‘’"]],[["kwd",/^(?:addhandler|addressof|alias|and|andalso|ansi|as|assembly|auto|boolean|byref|byte|byval|call|case|catch|cbool|cbyte|cchar|cdate|cdbl|cdec|char|cint|class|clng|cobj|const|cshort|csng|cstr|ctype|date|decimal|declare|default|delegate|dim|directcast|do|double|each|else|elseif|end|endif|enum|erase|error|event|exit|finally|for|friend|function|get|gettype|gosub|goto|handles|if|implements|imports|in|inherits|integer|interface|is|let|lib|like|long|loop|me|mod|module|mustinherit|mustoverride|mybase|myclass|namespace|new|next|not|notinheritable|notoverridable|object|on|option|optional|or|orelse|overloads|overridable|overrides|paramarray|preserve|private|property|protected|public|raiseevent|readonly|redim|removehandler|resume|return|select|set|shadows|shared|short|single|static|step|stop|string|structure|sub|synclock|then|throw|to|try|typeof|unicode|until|variant|wend|when|while|with|withevents|writeonly|xor|endif|gosub|let|variant|wend)\b/i, null],["com",/^rem.*/i],["lit",/^(?:true\b|false\b|nothing\b|\d+(?:e[+-]?\d+[dfr]?|[dfilrs])?|(?:&h[\da-f]+|&o[0-7]+)[ils]?|\d*\.\d+(?:e[+-]?\d+)?[dfr]?|#\s+(?:\d+[/-]\d+[/-]\d+(?:\s+\d+:\d+(?::\d+)?(\s*(?:am|pm))?)?|\d+:\d+(?::\d+)?(\s*(?:am|pm))?)\s+#)/i],["pln",/^(?:(?:[a-z]|_\w)\w*|\[(?:[a-z]|_\w)\w*])/i],["pun",/^[^\w\t\n\r "'[\]\xa0\u2018\u2019\u201c\u201d\u2028\u2029]+/],["pun",/^(?:\[|])/]]),["vb","vbs"]);
MaxMillion/jsdelivr
files/prettify/0.1/lang-vb.js
JavaScript
mit
1,715
ul.tree { margin-left: 12px; } ul.tree, ul.tree ul { list-style: none outside; margin-bottom: 0; } ul.tree ul { display: block; margin-left: 12px; margin-right: 0; } ul.tree li.closed > ul { display: none; } ul.tree li { clear: both; } ul.tree .toggler { background: url(treeDownTriangleBlack.png) no-repeat 0 50%; width: 12px; display: block; position: absolute; left: -12px; text-indent: -9999px; border-bottom: none; } ul.tree div { cursor: pointer; } ul.tree .title { color: #1C4257; vertical-align: middle; } ul.tree li.folder { margin-bottom: 4px; } ul.tree li.folder.closed { margin-bottom: 1px; } ul.tree li.folder .title { margin-left: 0; } ul.tree .toggler.closed { background-image: url(treeRightTriangleBlack.png); } span.tree-dragging { color: #fff; background: #000; opacity: 0.6; cursor: pointer; padding: 2px 8px; } ul.tree li.ghost { position: relative; z-index: 10; margin-right: 10px; } ul.tree li.ghost span { display: block; } ul.tree li.ghost span.circle { background: url(circle.png) no-repeat; height: 8px; width: 8px; position: absolute; top: -4px; left: 2px; } ul.tree li.ghost span.line { background-color: #0000ff; height: 2px; padding: 0; position: absolute; top: -1px; left: 10px; width: 100%; } ul.tree li.ghost.inside { margin-left: 48px; } ul.tree span.tree-hit { position: absolute; display: block; } ul.tree span.border { position: absolute; display: block; left: -2px; top: 0; border: solid 2px #0000ff; -webkit-border-radius: 6px; -moz-border-radius: 6px; border-radius: 6px; margin: 0; } ul.tree div { width: 100%; position: relative; } ul.tree li.selected > div, ul.tree li.selected > div:hover { background-color: #97BDD6; background: -webkit-gradient(linear, left top, left bottom, from(#BEE0F5), to(#89AFCA)); background: -moz-linear-gradient(top, #BEE0F5, #89AFCA); text-shadow: 0 1px 0 rgba(255, 255, 255, 0.7); } ul.tree .moving > div .title { outline: dashed 1px #0000ff; }
nolsherry/cdnjs
ajax/libs/jqtree/0.6/jqtree.css
CSS
mit
2,005
/* ******************************************************************************* * * Copyright (C) 2003-2006, International Business Machines * Corporation and others. All Rights Reserved. * ******************************************************************************* * file name: uit_len8.c * encoding: US-ASCII * tab size: 8 (not used) * indentation:4 * * created on: 2003feb10 * created by: Markus W. Scherer * * This file contains the implementation of the "lenient UTF-8" UCharIterator * as used in the uciter8 sample code. * UTF-8-style macros are defined as well as the UCharIterator. * The macros are incomplete (do not assemble code points from pairs of * surrogates, see comment below) * but sufficient for the iterator. */ #include <string.h> #include "unicode/utypes.h" #include "unicode/uiter.h" /* lenient UTF-8/CESU-8 macros ---------------------------------------------- */ /* * This code leniently reads 8-bit Unicode strings, * which could contain a mix of UTF-8 and CESU-8. * More precisely: * - supplementary code points may be encoded with dedicated 4-byte sequences * (UTF-8 style) * - supplementary code points may be encoded with * pairs of 3-byte sequences, one for each surrogate of the UTF-16 form * (CESU-8 style) * - single surrogates are allowed, encoded with their "natural" 3-byte sequences * * Limitation: * Right now, the macros do not attempt to assemble code points from pairs of * separately encoded surrogates. * This would not be sufficient for processing based on these macros, * but it is sufficient for a UCharIterator that returns only UChars anyway. * * The code is copied and modified from utf_impl.c and utf8.h. * * Change 2006feb08: Much of the implementation code is replaced by calling * the utf_impl.c functions which accept a new "strict" parameter value * of -2 implementing exactly this leniency. */ #define L8_NEXT(s, i, length, c) { \ (c)=(uint8_t)(s)[(i)++]; \ if((c)>=0x80) { \ if(U8_IS_LEAD(c)) { \ (c)=utf8_nextCharSafeBody((const uint8_t *)s, &(i), (int32_t)(length), c, -2); \ } else { \ (c)=U_SENTINEL; \ } \ } \ } #define L8_PREV(s, start, i, c) { \ (c)=(uint8_t)(s)[--(i)]; \ if((c)>=0x80) { \ if((c)<=0xbf) { \ (c)=utf8_prevCharSafeBody((const uint8_t *)s, start, &(i), c, -2); \ } else { \ (c)=U_SENTINEL; \ } \ } \ } /* lenient-8 UCharIterator -------------------------------------------------- */ /* * This is a copy of the UTF-8 UCharIterator in uiter.cpp, * except that it uses the lenient-8-bit-Unicode macros above. */ /* * Minimal implementation: * Maintain a single-UChar buffer for an additional surrogate. * The caller must not modify start and limit because they are used internally. * * Use UCharIterator fields as follows: * context pointer to UTF-8 string * length UTF-16 length of the string; -1 until lazy evaluation * start current UTF-8 index * index current UTF-16 index; may be -1="unknown" after setState() * limit UTF-8 length of the string * reservedField supplementary code point * * Since UCharIterator delivers 16-bit code units, the iteration can be * currently in the middle of the byte sequence for a supplementary code point. * In this case, reservedField will contain that code point and start will * point to after the corresponding byte sequence. The UTF-16 index will be * one less than what it would otherwise be corresponding to the UTF-8 index. * Otherwise, reservedField will be 0. */ /* * Possible optimization for NUL-terminated UTF-8 and UTF-16 strings: * Add implementations that do not call strlen() for iteration but check for NUL. */ static int32_t U_CALLCONV lenient8IteratorGetIndex(UCharIterator *iter, UCharIteratorOrigin origin) { switch(origin) { case UITER_ZERO: case UITER_START: return 0; case UITER_CURRENT: if(iter->index<0) { /* the current UTF-16 index is unknown after setState(), count from the beginning */ const uint8_t *s; UChar32 c; int32_t i, limit, index; s=(const uint8_t *)iter->context; i=index=0; limit=iter->start; /* count up to the UTF-8 index */ while(i<limit) { L8_NEXT(s, i, limit, c); if(c<=0xffff) { ++index; } else { index+=2; } } iter->start=i; /* just in case setState() did not get us to a code point boundary */ if(i==iter->limit) { iter->length=index; /* in case it was <0 or wrong */ } if(iter->reservedField!=0) { --index; /* we are in the middle of a supplementary code point */ } iter->index=index; } return iter->index; case UITER_LIMIT: case UITER_LENGTH: if(iter->length<0) { const uint8_t *s; UChar32 c; int32_t i, limit, length; s=(const uint8_t *)iter->context; if(iter->index<0) { /* * the current UTF-16 index is unknown after setState(), * we must first count from the beginning to here */ i=length=0; limit=iter->start; /* count from the beginning to the current index */ while(i<limit) { L8_NEXT(s, i, limit, c); if(c<=0xffff) { ++length; } else { length+=2; } } /* assume i==limit==iter->start, set the UTF-16 index */ iter->start=i; /* just in case setState() did not get us to a code point boundary */ iter->index= iter->reservedField!=0 ? length-1 : length; } else { i=iter->start; length=iter->index; if(iter->reservedField!=0) { ++length; } } /* count from the current index to the end */ limit=iter->limit; while(i<limit) { L8_NEXT(s, i, limit, c); if(c<=0xffff) { ++length; } else { length+=2; } } iter->length=length; } return iter->length; default: /* not a valid origin */ /* Should never get here! */ return -1; } } static int32_t U_CALLCONV lenient8IteratorMove(UCharIterator *iter, int32_t delta, UCharIteratorOrigin origin) { const uint8_t *s; UChar32 c; int32_t pos; /* requested UTF-16 index */ int32_t i; /* UTF-8 index */ UBool havePos; /* calculate the requested UTF-16 index */ switch(origin) { case UITER_ZERO: case UITER_START: pos=delta; havePos=TRUE; /* iter->index<0 (unknown) is possible */ break; case UITER_CURRENT: if(iter->index>=0) { pos=iter->index+delta; havePos=TRUE; } else { /* the current UTF-16 index is unknown after setState(), use only delta */ pos=0; havePos=FALSE; } break; case UITER_LIMIT: case UITER_LENGTH: if(iter->length>=0) { pos=iter->length+delta; havePos=TRUE; } else { /* pin to the end, avoid counting the length */ iter->index=-1; iter->start=iter->limit; iter->reservedField=0; if(delta>=0) { return UITER_UNKNOWN_INDEX; } else { /* the current UTF-16 index is unknown, use only delta */ pos=0; havePos=FALSE; } } break; default: return -1; /* Error */ } if(havePos) { /* shortcuts: pinning to the edges of the string */ if(pos<=0) { iter->index=iter->start=iter->reservedField=0; return 0; } else if(iter->length>=0 && pos>=iter->length) { iter->index=iter->length; iter->start=iter->limit; iter->reservedField=0; return iter->index; } /* minimize the number of L8_NEXT/PREV operations */ if(iter->index<0 || pos<iter->index/2) { /* go forward from the start instead of backward from the current index */ iter->index=iter->start=iter->reservedField=0; } else if(iter->length>=0 && (iter->length-pos)<(pos-iter->index)) { /* * if we have the UTF-16 index and length and the new position is * closer to the end than the current index, * then go backward from the end instead of forward from the current index */ iter->index=iter->length; iter->start=iter->limit; iter->reservedField=0; } delta=pos-iter->index; if(delta==0) { return iter->index; /* nothing to do */ } } else { /* move relative to unknown UTF-16 index */ if(delta==0) { return UITER_UNKNOWN_INDEX; /* nothing to do */ } else if(-delta>=iter->start) { /* moving backwards by more UChars than there are UTF-8 bytes, pin to 0 */ iter->index=iter->start=iter->reservedField=0; return 0; } else if(delta>=(iter->limit-iter->start)) { /* moving forward by more UChars than the remaining UTF-8 bytes, pin to the end */ iter->index=iter->length; /* may or may not be <0 (unknown) */ iter->start=iter->limit; iter->reservedField=0; return iter->index>=0 ? iter->index : UITER_UNKNOWN_INDEX; } } /* delta!=0 */ /* move towards the requested position, pin to the edges of the string */ s=(const uint8_t *)iter->context; pos=iter->index; /* could be <0 (unknown) */ i=iter->start; if(delta>0) { /* go forward */ int32_t limit=iter->limit; if(iter->reservedField!=0) { iter->reservedField=0; ++pos; --delta; } while(delta>0 && i<limit) { L8_NEXT(s, i, limit, c); if(c<0xffff) { ++pos; --delta; } else if(delta>=2) { pos+=2; delta-=2; } else /* delta==1 */ { /* stop in the middle of a supplementary code point */ iter->reservedField=c; ++pos; break; /* delta=0; */ } } if(i==limit) { if(iter->length<0 && iter->index>=0) { iter->length= iter->reservedField==0 ? pos : pos+1; } else if(iter->index<0 && iter->length>=0) { iter->index= iter->reservedField==0 ? iter->length : iter->length-1; } } } else /* delta<0 */ { /* go backward */ if(iter->reservedField!=0) { iter->reservedField=0; i-=4; /* we stayed behind the supplementary code point; go before it now */ --pos; ++delta; } while(delta<0 && i>0) { L8_PREV(s, 0, i, c); if(c<0xffff) { --pos; ++delta; } else if(delta<=-2) { pos-=2; delta+=2; } else /* delta==-1 */ { /* stop in the middle of a supplementary code point */ i+=4; /* back to behind this supplementary code point for consistent state */ iter->reservedField=c; --pos; break; /* delta=0; */ } } } iter->start=i; if(iter->index>=0) { return iter->index=pos; } else { /* we started with index<0 (unknown) so pos is bogus */ if(i<=1) { return iter->index=i; /* reached the beginning */ } else { /* we still don't know the UTF-16 index */ return UITER_UNKNOWN_INDEX; } } } static UBool U_CALLCONV lenient8IteratorHasNext(UCharIterator *iter) { return iter->reservedField!=0 || iter->start<iter->limit; } static UBool U_CALLCONV lenient8IteratorHasPrevious(UCharIterator *iter) { return iter->start>0; } static UChar32 U_CALLCONV lenient8IteratorCurrent(UCharIterator *iter) { if(iter->reservedField!=0) { return U16_TRAIL(iter->reservedField); } else if(iter->start<iter->limit) { const uint8_t *s=(const uint8_t *)iter->context; UChar32 c; int32_t i=iter->start; L8_NEXT(s, i, iter->limit, c); if(c<0) { return 0xfffd; } else if(c<=0xffff) { return c; } else { return U16_LEAD(c); } } else { return U_SENTINEL; } } static UChar32 U_CALLCONV lenient8IteratorNext(UCharIterator *iter) { int32_t index; if(iter->reservedField!=0) { UChar trail=U16_TRAIL(iter->reservedField); iter->reservedField=0; if((index=iter->index)>=0) { iter->index=index+1; } return trail; } else if(iter->start<iter->limit) { const uint8_t *s=(const uint8_t *)iter->context; UChar32 c; L8_NEXT(s, iter->start, iter->limit, c); if((index=iter->index)>=0) { iter->index=++index; if(iter->length<0 && iter->start==iter->limit) { iter->length= c<=0xffff ? index : index+1; } } else if(iter->start==iter->limit && iter->length>=0) { iter->index= c<=0xffff ? iter->length : iter->length-1; } if(c<0) { return 0xfffd; } else if(c<=0xffff) { return c; } else { iter->reservedField=c; return U16_LEAD(c); } } else { return U_SENTINEL; } } static UChar32 U_CALLCONV lenient8IteratorPrevious(UCharIterator *iter) { int32_t index; if(iter->reservedField!=0) { UChar lead=U16_LEAD(iter->reservedField); iter->reservedField=0; iter->start-=4; /* we stayed behind the supplementary code point; go before it now */ if((index=iter->index)>0) { iter->index=index-1; } return lead; } else if(iter->start>0) { const uint8_t *s=(const uint8_t *)iter->context; UChar32 c; L8_PREV(s, 0, iter->start, c); if((index=iter->index)>0) { iter->index=index-1; } else if(iter->start<=1) { iter->index= c<=0xffff ? iter->start : iter->start+1; } if(c<0) { return 0xfffd; } else if(c<=0xffff) { return c; } else { iter->start+=4; /* back to behind this supplementary code point for consistent state */ iter->reservedField=c; return U16_TRAIL(c); } } else { return U_SENTINEL; } } static uint32_t U_CALLCONV lenient8IteratorGetState(const UCharIterator *iter) { uint32_t state=(uint32_t)(iter->start<<1); if(iter->reservedField!=0) { state|=1; } return state; } static void U_CALLCONV lenient8IteratorSetState(UCharIterator *iter, uint32_t state, UErrorCode *pErrorCode) { if(pErrorCode==NULL || U_FAILURE(*pErrorCode)) { /* do nothing */ } else if(iter==NULL) { *pErrorCode=U_ILLEGAL_ARGUMENT_ERROR; } else if(state==lenient8IteratorGetState(iter)) { /* setting to the current state: no-op */ } else { int32_t index=(int32_t)(state>>1); /* UTF-8 index */ state&=1; /* 1 if in surrogate pair, must be index>=4 */ if((state==0 ? index<0 : index<4) || iter->limit<index) { *pErrorCode=U_INDEX_OUTOFBOUNDS_ERROR; } else { iter->start=index; /* restore UTF-8 byte index */ if(index<=1) { iter->index=index; } else { iter->index=-1; /* unknown UTF-16 index */ } if(state==0) { iter->reservedField=0; } else { /* verified index>=4 above */ UChar32 c; L8_PREV((const uint8_t *)iter->context, 0, index, c); if(c<=0xffff) { *pErrorCode=U_INDEX_OUTOFBOUNDS_ERROR; } else { iter->reservedField=c; } } } } } static const UCharIterator lenient8Iterator={ 0, 0, 0, 0, 0, 0, lenient8IteratorGetIndex, lenient8IteratorMove, lenient8IteratorHasNext, lenient8IteratorHasPrevious, lenient8IteratorCurrent, lenient8IteratorNext, lenient8IteratorPrevious, NULL, lenient8IteratorGetState, lenient8IteratorSetState }; U_CAPI void U_EXPORT2 uiter_setLenient8(UCharIterator *iter, const char *s, int32_t length) { if(iter!=0) { if(s!=0 && length>=-1) { *iter=lenient8Iterator; iter->context=s; if(length>=0) { iter->limit=length; } else { iter->limit=strlen(s); } iter->length= iter->limit<=1 ? iter->limit : -1; } else { /* set no-op iterator */ uiter_setString(iter, NULL, 0); } } }
babycaseny/poedit
deps/icu4c/source/samples/uciter8/uit_len8.c
C
mit
17,754
/** * Bunch of useful filters for angularJS(with no external dependencies!) * @version v0.4.8 - 2014-10-13 * @link https://github.com/a8m/angular-filter * @author Ariel Mashraki <ariel@mashraki.co.il> * @license MIT License, http://www.opensource.org/licenses/MIT */ (function ( window, angular, undefined ) { /*jshint globalstrict:true*/ 'use strict'; var isDefined = angular.isDefined, isUndefined = angular.isUndefined, isFunction = angular.isFunction, isString = angular.isString, isNumber = angular.isNumber, isObject = angular.isObject, isArray = angular.isArray, forEach = angular.forEach, extend = angular.extend, copy = angular.copy, equals = angular.equals; /** * @description * get an object and return array of values * @param object * @returns {Array} */ function toArray(object) { return isArray(object) ? object : Object.keys(object).map(function(key) { return object[key]; }); } /** * @param value * @returns {boolean} */ function isNull(value) { return value === null; } /** * @description * return if object contains partial object * @param partial{object} * @param object{object} * @returns {boolean} */ function objectContains(partial, object) { var keys = Object.keys(partial); return keys.map(function(el) { return !(!object[el] || (object[el] != partial[el])); }).indexOf(false) == -1; } /** * @description * search for approximate pattern in string * @param word * @param pattern * @returns {*} */ function hasApproxPattern(word, pattern) { if(pattern === '') return word; var index = word.indexOf(pattern.charAt(0)); if(index === -1) return false; return hasApproxPattern(word.substr(index+1), pattern.substr(1)) } /** * @description * return the first n element of an array, * if expression provided, is returns as long the expression return truthy * @param array * @param n {number} * @param expression {$parse} * @return array or single object */ function getFirstMatches(array, n, expression) { var count = 0; return array.filter(function(elm) { var rest = isDefined(expression) ? (count < n && expression(elm)) : count < n; count = rest ? count+1 : count; return rest; }); } /** * Polyfill to ECMA6 String.prototype.contains */ if (!String.prototype.contains) { String.prototype.contains = function() { return String.prototype.indexOf.apply(this, arguments) !== -1; }; } /** * @param num {Number} * @param decimal {Number} * @param $math * @returns {Number} */ function convertToDecimal(num, decimal, $math){ return $math.round(num * $math.pow(10,decimal)) / ($math.pow(10,decimal)); } /** * @description * Get an object, and return an array composed of it's properties names(nested too). * @param obj {Object} * @param stack {Array} * @param parent {String} * @returns {Array} * @example * parseKeys({ a:1, b: { c:2, d: { e: 3 } } }) ==> ["a", "b.c", "b.d.e"] */ function deepKeys(obj, stack, parent) { stack = stack || []; var keys = Object.keys(obj); keys.forEach(function(el) { //if it's a nested object if(isObject(obj[el]) && !isArray(obj[el])) { //concatenate the new parent if exist var p = parent ? parent + '.' + el : parent; deepKeys(obj[el], stack, p || el); } else { //create and save the key var key = parent ? parent + '.' + el : el; stack.push(key) } }); return stack } /** * @ngdoc filter * @name a8m.angular * @kind function * * @description * reference to angular function */ angular.module('a8m.angular', []) .filter('isUndefined', function () { return function (input) { return angular.isUndefined(input); } }) .filter('isDefined', function() { return function (input) { return angular.isDefined(input); } }) .filter('isFunction', function() { return function (input) { return angular.isFunction(input); } }) .filter('isString', function() { return function (input) { return angular.isString(input) } }) .filter('isNumber', function() { return function (input) { return angular.isNumber(input); } }) .filter('isArray', function() { return function (input) { return angular.isArray(input); } }) .filter('isObject', function() { return function (input) { return angular.isObject(input); } }) .filter('isEqual', function() { return function (o1, o2) { return angular.equals(o1, o2); } }); /** * @ngdoc filter * @name a8m.conditions * @kind function * * @description * reference to math conditions */ angular.module('a8m.conditions', []) .filter({ isGreaterThan : isGreaterThanFilter, '>' : isGreaterThanFilter, isGreaterThanOrEqualTo : isGreaterThanOrEqualToFilter, '>=' : isGreaterThanOrEqualToFilter, isLessThan : isLessThanFilter, '<' : isLessThanFilter, isLessThanOrEqualTo : isLessThanOrEqualToFilter, '<=' : isLessThanOrEqualToFilter, isEqualTo : isEqualToFilter, '==' : isEqualToFilter, isNotEqualTo : isNotEqualToFilter, '!=' : isNotEqualToFilter, isIdenticalTo : isIdenticalToFilter, '===' : isIdenticalToFilter, isNotIdenticalTo : isNotIdenticalToFilter, '!==' : isNotIdenticalToFilter }); function isGreaterThanFilter() { return function (input, check) { return input > check; }; } function isGreaterThanOrEqualToFilter() { return function (input, check) { return input >= check; }; } function isLessThanFilter() { return function (input, check) { return input < check; }; } function isLessThanOrEqualToFilter() { return function (input, check) { return input <= check; }; } function isEqualToFilter() { return function (input, check) { return input == check; }; } function isNotEqualToFilter() { return function (input, check) { return input != check; }; } function isIdenticalToFilter() { return function (input, check) { return input === check; }; } function isNotIdenticalToFilter() { return function (input, check) { return input !== check; }; } /** * @ngdoc filter * @name isNull * @kind function * * @description * checks if value is null or not * @return Boolean */ angular.module('a8m.is-null', []) .filter('isNull', function () { return function(input) { return isNull(input); } }); /** * @ngdoc filter * @name after-where * @kind function * * @description * get a collection and properties object, and returns all of the items * in the collection after the first that found with the given properties. * */ angular.module('a8m.after-where', []) .filter('afterWhere', function() { return function (collection, object) { collection = (isObject(collection)) ? toArray(collection) : collection; if(!isArray(collection) || isUndefined(object)) return collection; var index = collection.map( function( elm ) { return objectContains(object, elm); }).indexOf( true ); return collection.slice((index === -1) ? 0 : index); } }); /** * @ngdoc filter * @name after * @kind function * * @description * get a collection and specified count, and returns all of the items * in the collection after the specified count. * */ angular.module('a8m.after', []) .filter('after', function() { return function (collection, count) { collection = (isObject(collection)) ? toArray(collection) : collection; return (isArray(collection)) ? collection.slice(count) : collection; } }); /** * @ngdoc filter * @name before-where * @kind function * * @description * get a collection and properties object, and returns all of the items * in the collection before the first that found with the given properties. * */ angular.module('a8m.before-where', []) .filter('beforeWhere', function() { return function (collection, object) { collection = (isObject(collection)) ? toArray(collection) : collection; if(!isArray(collection) || isUndefined(object)) return collection; var index = collection.map( function( elm ) { return objectContains(object, elm); }).indexOf( true ); return collection.slice(0, (index === -1) ? collection.length : ++index); } }); /** * @ngdoc filter * @name before * @kind function * * @description * get a collection and specified count, and returns all of the items * in the collection before the specified count. * */ angular.module('a8m.before', []) .filter('before', function() { return function (collection, count) { collection = (isObject(collection)) ? toArray(collection) : collection; return (isArray(collection)) ? collection.slice(0, (!count) ? count : --count) : collection; } }); /** * @ngdoc filter * @name concat * @kind function * * @description * get (array/object, object/array) and return merged collection * */ angular.module('a8m.concat', []) //TODO:unique option ? or use unique filter to filter result .filter('concat', [function () { return function (collection, joined) { if (isUndefined(joined)) { return collection; } if (isArray(collection)) { return (isObject(joined)) ? collection.concat(toArray(joined)) : collection.concat(joined); } if (isObject(collection)) { var array = toArray(collection); return (isObject(joined)) ? array.concat(toArray(joined)) : array.concat(joined); } return collection; }; } ]); /** * @ngdoc filter * @name contains * @kind function * * @description * Checks if given expression is present in one or more object in the collection */ angular.module('a8m.contains', []) .filter({ contains: ['$parse', containsFilter], some: ['$parse', containsFilter] }); function containsFilter( $parse ) { return function (collection, expression) { collection = (isObject(collection)) ? toArray(collection) : collection; if(!isArray(collection) || isUndefined(expression)) { return true; } return collection.some( function(elm) { return (isObject(elm) || isFunction(expression)) ? $parse(expression)(elm) : elm === expression; }); } } /** * @ngdoc filter * @name countBy * @kind function * * @description * Sorts a list into groups and returns a count for the number of objects in each group. */ angular.module('a8m.count-by', []) .filter('countBy', [ '$parse', function ( $parse ) { return function (collection, property) { var result = {}, get = $parse(property), prop; collection = (isObject(collection)) ? toArray(collection) : collection; if(!isArray(collection) || isUndefined(property)) { return collection; } collection.forEach( function( elm ) { prop = get(elm); if(!result[prop]) { result[prop] = 0; } result[prop]++; }); return result; } }]); /** * @ngdoc filter * @name defaults * @kind function * * @description * defaultsFilter allows to specify a default fallback value for properties that resolve to undefined. */ angular.module('a8m.defaults', []) .filter('defaults', ['$parse', function( $parse ) { return function(collection, defaults) { collection = (isObject(collection)) ? toArray(collection) : collection; if(!isArray(collection) || !isObject(defaults)) { return collection; } var keys = deepKeys(defaults); collection.forEach(function(elm) { //loop through all the keys keys.forEach(function(key) { var getter = $parse(key); var setter = getter.assign; //if it's not exist if(isUndefined(getter(elm))) { //get from defaults, and set to the returned object setter(elm, getter(defaults)) } }); }); return collection; } }]); /** * @ngdoc filter * @name every * @kind function * * @description * Checks if given expression is present in all members in the collection * */ angular.module('a8m.every', []) .filter('every', ['$parse', function($parse) { return function (collection, expression) { collection = (isObject(collection)) ? toArray(collection) : collection; if(!isArray(collection) || isUndefined(expression)) { return true; } return collection.every( function(elm) { return (isObject(elm) || isFunction(expression)) ? $parse(expression)(elm) : elm === expression; }); } }]); /** * @ngdoc filter * @name filterBy * @kind function * * @description * filter by specific properties, avoid the rest */ angular.module('a8m.filter-by', []) .filter('filterBy', ['$parse', function( $parse ) { return function(collection, properties, search) { var comparator; search = (isString(search) || isNumber(search)) ? String(search).toLowerCase() : undefined; collection = (isObject(collection)) ? toArray(collection) : collection; if(!isArray(collection) || isUndefined(search)) { return collection; } return collection.filter(function(elm) { return properties.some(function(prop) { /** * check if there is concatenate properties * example: * object: { first: 'foo', last:'bar' } * filterBy: ['first + last'] => search by full name(i.e 'foo bar') */ if(!~prop.indexOf('+')) { comparator = $parse(prop)(elm) } else { var propList = prop.replace(new RegExp('\\s', 'g'), '').split('+'); comparator = propList.reduce(function(prev, cur, index) { return (index === 1) ? $parse(prev)(elm) + ' ' + $parse(cur)(elm) : prev + ' ' + $parse(cur)(elm); }); } return (isString(comparator) || isNumber(comparator)) ? String(comparator).toLowerCase().contains(search) : false; }) }); } }]); /** * @ngdoc filter * @name first * @kind function * * @description * Gets the first element or first n elements of an array * if callback is provided, is returns as long the callback return truthy */ angular.module('a8m.first', []) .filter('first', ['$parse', function( $parse ) { return function(collection) { var n, getter, args; collection = (isObject(collection)) ? toArray(collection) : collection; if(!isArray(collection)) { return collection; } args = Array.prototype.slice.call(arguments, 1); n = (isNumber(args[0])) ? args[0] : 1; getter = (!isNumber(args[0])) ? args[0] : (!isNumber(args[1])) ? args[1] : undefined; return (args.length) ? getFirstMatches(collection, n,(getter) ? $parse(getter) : getter) : collection[0]; } }]); /** * @ngdoc filter * @name flatten * @kind function * * @description * Flattens a nested array (the nesting can be to any depth). * If you pass shallow, the array will only be flattened a single level */ angular.module('a8m.flatten', []) .filter('flatten', function () { return function(collection, shallow) { shallow = shallow || false; collection = (isObject(collection)) ? toArray(collection) : collection; if(!isArray(collection)) { return collection; } return (!shallow) ? flatten(collection, 0) : [].concat.apply([], collection); } }); /** * flatten nested array (the nesting can be to any depth). * @param array {Array} * @param i {int} * @returns {Array} * @private */ function flatten(array, i) { i = i || 0; if(i >= array.length) return array; if(isArray(array[i])) { return flatten(array.slice(0,i) .concat(array[i], array.slice(i+1)), i); } return flatten(array, i+1); } /** * @ngdoc filter * @name fuzzyByKey * @kind function * * @description * fuzzy string searching by key */ angular.module('a8m.fuzzy-by', []) .filter('fuzzyBy', ['$parse', function ( $parse ) { return function (collection, property, search, csensitive) { var sensitive = csensitive || false, prop, getter; collection = (isObject(collection)) ? toArray(collection) : collection; if(!isArray(collection) || isUndefined(property) || isUndefined(search)) { return collection; } getter = $parse(property); return collection.filter(function(elm) { prop = getter(elm); if(!isString(prop)) { return false; } prop = (sensitive) ? prop : prop.toLowerCase(); search = (sensitive) ? search : search.toLowerCase(); return hasApproxPattern(prop, search) !== false }) } }]); /** * @ngdoc filter * @name fuzzy * @kind function * * @description * fuzzy string searching for array of strings, objects */ angular.module('a8m.fuzzy', []) .filter('fuzzy', function () { return function (collection, search, csensitive) { var sensitive = csensitive || false; collection = (isObject(collection)) ? toArray(collection) : collection; if(!isArray(collection) || isUndefined(search)) { return collection; } search = (sensitive) ? search : search.toLowerCase(); return collection.filter(function(elm) { if(isString(elm)) { elm = (sensitive) ? elm : elm.toLowerCase(); return hasApproxPattern(elm, search) !== false } return (isObject(elm)) ? _hasApproximateKey(elm, search) : false; }); /** * checks if object has key{string} that match * to fuzzy search pattern * @param object * @param search * @returns {boolean} * @private */ function _hasApproximateKey(object, search) { var properties = Object.keys(object), prop, flag; return 0 < properties.filter(function (elm) { prop = object[elm]; //avoid iteration if we found some key that equal[performance] if(flag) return true; if (isString(prop)) { prop = (sensitive) ? prop : prop.toLowerCase(); return flag = (hasApproxPattern(prop, search) !== false); } return false; }).length; } } }); /** * @ngdoc filter * @name groupBy * @kind function * * @description * Create an object composed of keys generated from the result of running each element of a collection, * each key is an array of the elements. */ angular.module('a8m.group-by', [ 'a8m.filter-watcher' ]) .filter('groupBy', [ '$parse', 'filterWatcher', function ( $parse, filterWatcher ) { return function (collection, property) { var result, get = $parse(property), prop; if(!isObject(collection) || isUndefined(property)) { return collection; } //Add collection instance to watch list result = filterWatcher.$watch('groupBy', collection); forEach( collection, function( elm ) { prop = get(elm); if(!result[prop]) { result[prop] = []; } if(result[prop].indexOf( elm ) === -1) { result[prop].push(elm); } }); //kill instance filterWatcher.$destroy('groupBy', collection); return result; } }]); /** * @ngdoc filter * @name isEmpty * @kind function * * @description * get collection or string and return if it empty */ angular.module('a8m.is-empty', []) .filter('isEmpty', function () { return function(collection) { return (isObject(collection)) ? !toArray(collection).length : !collection.length; } }); /** * @ngdoc filter * @name last * @kind function * * @description * Gets the last element or last n elements of an array * if callback is provided, is returns as long the callback return truthy */ angular.module('a8m.last', []) .filter('last', ['$parse', function( $parse ) { return function(collection) { var n, getter, args, //cuz reverse change our src collection //and we don't want side effects reversed = copy(collection); reversed = (isObject(reversed)) ? toArray(reversed) : reversed; if(!isArray(reversed)) { return reversed; } args = Array.prototype.slice.call(arguments, 1); n = (isNumber(args[0])) ? args[0] : 1; getter = (!isNumber(args[0])) ? args[0] : (!isNumber(args[1])) ? args[1] : undefined; return (args.length) ? //send reversed collection as arguments, and reverse it back as result getFirstMatches(reversed.reverse(), n,(getter) ? $parse(getter) : getter).reverse() : //get the last element reversed[reversed.length-1]; } }]); /** * @ngdoc filter * @name map * @kind function * * @description * Returns a new collection of the results of each expression execution. */ angular.module('a8m.map', []) .filter('map', ['$parse', function($parse) { return function (collection, expression) { collection = (isObject(collection)) ? toArray(collection) : collection; if(!isArray(collection) || isUndefined(expression)) { return collection; } return collection.map(function (elm) { return $parse(expression)(elm); }); } }]); /** * @ngdoc filter * @name omit * @kind function * * @description * filter collection by expression */ angular.module('a8m.omit', []) .filter('omit', ['$parse', function($parse) { return function (collection, expression) { collection = (isObject(collection)) ? toArray(collection) : collection; if(!isArray(collection) || isUndefined(expression)) { return collection; } return collection.filter(function (elm) { return !($parse(expression)(elm)); }); } }]); /** * @ngdoc filter * @name omit * @kind function * * @description * filter collection by expression */ angular.module('a8m.pick', []) .filter('pick', ['$parse', function($parse) { return function (collection, expression) { collection = (isObject(collection)) ? toArray(collection) : collection; if(!isArray(collection) || isUndefined(expression)) { return collection; } return collection.filter(function (elm) { return $parse(expression)(elm); }); } }]); /** * @ngdoc filter * @name removeWith * @kind function * * @description * get collection and properties object, and removed elements * with this properties */ angular.module('a8m.remove-with', []) .filter('removeWith', function() { return function (collection, object) { if(isUndefined(object)) { return collection; } collection = (isObject(collection)) ? toArray(collection) : collection; return collection.filter(function (elm) { return !objectContains(object, elm); }); } }); /** * @ngdoc filter * @name remove * @kind function * * @description * remove specific members from collection */ angular.module('a8m.remove', []) .filter('remove', function () { return function (collection) { collection = (isObject(collection)) ? toArray(collection) : collection; var args = Array.prototype.slice.call(arguments, 1); if(!isArray(collection)) { return collection; } return collection.filter( function( member ) { return !args.some(function(nest) { return equals(nest, member); }) }); } }); /** * @ngdoc filter * @name reverse * @kind function * * @description * Reverses a string or collection */ angular.module('a8m.reverse', []) .filter('reverse',[ function () { return function (input) { input = (isObject(input)) ? toArray(input) : input; if(isString(input)) { return input.split('').reverse().join(''); } return (isArray(input)) ? input.reverse() : input; } }]); /** * @ngdoc filter * @name searchField * @kind function * * @description * for each member, join several strings field and add them to * new field called 'searchField' (use for search filtering) */ angular.module('a8m.search-field', []) .filter('searchField', ['$parse', function ($parse) { return function (collection) { var get, field; collection = (isObject(collection)) ? toArray(collection) : collection; var args = Array.prototype.slice.call(arguments, 1); if(!isArray(collection) || !args.length) { return collection; } return collection.map(function(member) { field = args.map(function(field) { get = $parse(field); return get(member); }).join(' '); return extend(member, { searchField: field }); }); } }]); /** * @ngdoc filter * @name toArray * @kind function * * @description * Convert objects into stable arrays. * if addKey set to true,the filter also attaches a new property * $key to the value containing the original key that was used in * the object we are iterating over to reference the property */ angular.module('a8m.to-array', []) .filter('toArray', function() { return function (collection, addKey) { if(!isObject(collection)) { return collection; } return (!addKey) ? toArray(collection) : Object.keys(collection).map(function (key) { return extend(collection[key], { $key: key }); }); } }); /** * @ngdoc filter * @name unique/uniq * @kind function * * @description * get collection and filter duplicate members * if uniqueFilter get a property(nested to) as argument it's * filter by this property as unique identifier */ angular.module('a8m.unique', []) .filter({ unique: ['$parse', uniqFilter], uniq: ['$parse', uniqFilter] }); function uniqFilter($parse) { return function (collection, property) { collection = (isObject(collection)) ? toArray(collection) : collection; if (!isArray(collection)) { return collection; } //store all unique identifiers var uniqueItems = [], get = $parse(property); return (isUndefined(property)) ? //if it's kind of primitive array collection.filter(function (elm, pos, self) { return self.indexOf(elm) === pos; }) : //else compare with equals collection.filter(function (elm) { var prop = get(elm); if(some(uniqueItems, prop)) { return false; } uniqueItems.push(prop); return true; }); //checked if the unique identifier is already exist function some(array, member) { if(isUndefined(member)) { return false; } return array.some(function(el) { return equals(el, member); }); } } } /** * @ngdoc filter * @name where * @kind function * * @description * of each element in a collection to the given properties object, * returning an array of all elements that have equivalent property values. * */ angular.module('a8m.where', []) .filter('where', function() { return function (collection, object) { if(isUndefined(object)) { return collection; } collection = (isObject(collection)) ? toArray(collection) : collection; return collection.filter(function (elm) { return objectContains(object, elm); }); } }); /** * @ngdoc filter * @name xor * @kind function * * @description * Exclusive or filter by expression */ angular.module('a8m.xor', []) .filter('xor', ['$parse', function($parse) { return function (col1, col2, expression) { expression = expression || false; col1 = (isObject(col1)) ? toArray(col1) : col1; col2 = (isObject(col2)) ? toArray(col2) : col2; if(!isArray(col1) || !isArray(col2)) return col1; return col1.concat(col2) .filter(function(elm) { return !(some(elm, col1) && some(elm, col2)); }); function some(el, col) { var getter = $parse(expression); return col.some(function(dElm) { return expression ? equals(getter(dElm), getter(el)) : equals(dElm, el); }) } } }]); /** * @ngdoc filter * @name formatBytes * @kind function * * @description * Convert bytes into appropriate display * 1024 bytes => 1 KB */ angular.module('a8m.math.byteFmt', ['a8m.math']) .filter('byteFmt', ['$math', function ($math) { return function (bytes, decimal) { if(isNumber(decimal) && isFinite(decimal) && decimal%1===0 && decimal >= 0 && isNumber(bytes) && isFinite(bytes)) { if(bytes < 1024) { // within 1 KB so B return convertToDecimal(bytes, decimal, $math) + ' B'; } else if(bytes < 1048576) { // within 1 MB so KB return convertToDecimal((bytes / 1024), decimal, $math) + ' KB'; } else if(bytes < 1073741824){ // within 1 GB so MB return convertToDecimal((bytes / 1048576), decimal, $math) + ' MB'; } else { // GB or more return convertToDecimal((bytes / 1073741824), decimal, $math) + ' GB'; } } else { return "NaN"; } } }]); /** * @ngdoc filter * @name degrees * @kind function * * @description * Convert angle from radians to degrees * */ angular.module('a8m.math.degrees', ['a8m.math']) .filter('degrees', ['$math', function ($math) { return function (radians, decimal) { // if decimal is not an integer greater than -1, we cannot do. quit with error "NaN" // if degrees is not a real number, we cannot do also. quit with error "NaN" if(isNumber(decimal) && isFinite(decimal) && decimal%1===0 && decimal >= 0 && isNumber(radians) && isFinite(radians)) { var degrees = (radians * 180) / $math.PI; return $math.round(degrees * $math.pow(10,decimal)) / ($math.pow(10,decimal)); } else { return "NaN"; } } }]); /** * @ngdoc filter * @name formatBytes * @kind function * * @description * Convert bytes into appropriate display * 1024 kilobytes => 1 MB */ angular.module('a8m.math.kbFmt', ['a8m.math']) .filter('kbFmt', ['$math', function ($math) { return function (bytes, decimal) { if(isNumber(decimal) && isFinite(decimal) && decimal%1===0 && decimal >= 0 && isNumber(bytes) && isFinite(bytes)) { if(bytes < 1024) { // within 1 MB so KB return convertToDecimal(bytes, decimal, $math) + ' KB'; } else if(bytes < 1048576) { // within 1 GB so MB return convertToDecimal((bytes / 1024), decimal, $math) + ' MB'; } else { return convertToDecimal((bytes / 1048576), decimal, $math) + ' GB'; } } else { return "NaN"; } } }]); /** * @ngdoc module * @name math * @description * reference to global Math object */ angular.module('a8m.math', []) .factory('$math', ['$window', function ($window) { return $window.Math; }]); /** * @ngdoc filter * @name max * @kind function * * @description * Math.max * */ angular.module('a8m.math.max', ['a8m.math']) .filter('max', ['$math', function ($math) { return function (input) { return (isArray(input)) ? $math.max.apply($math, input) : input; } }]); /** * @ngdoc filter * @name min * @kind function * * @description * Math.min * */ angular.module('a8m.math.min', ['a8m.math']) .filter('min', ['$math', function ($math) { return function (input) { return (isArray(input)) ? $math.min.apply($math, input) : input; } }]); /** * @ngdoc filter * @name Percent * @kind function * * @description * percentage between two numbers * */ angular.module('a8m.math.percent', ['a8m.math']) .filter('percent', ['$math', '$window', function ($math, $window) { return function (input, divided, round) { var divider = (isString(input)) ? $window.Number(input) : input; divided = divided || 100; round = round || false; if (!isNumber(divider) || $window.isNaN(divider)) return input; return (round) ? $math.round((divider / divided) * 100) : ((divider / divided) * 100); } }]); /** * @ngdoc filter * @name toRadians * @kind function * * @description * Convert angle from degrees to radians * */ angular.module('a8m.math.radians', ['a8m.math']) .filter('radians', ['$math', function ($math) { return function (degrees, decimal) { // if decimal is not an integer greater than -1, we cannot do. quit with error "NaN" // if degrees is not a real number, we cannot do also. quit with error "NaN" if(isNumber(decimal) && isFinite(decimal) && decimal%1===0 && decimal >= 0 && isNumber(degrees) && isFinite(degrees)) { var radians = (degrees * 3.14159265359) / 180; return $math.round(radians * $math.pow(10,decimal)) / ($math.pow(10,decimal)); } else { return "NaN"; } } }]); /** * @ngdoc filter * @name Radix * @kind function * * @description * converting decimal numbers to different bases(radix) */ angular.module('a8m.math.radix', []) .filter('radix', function () { return function (input, radix) { var RANGE = /^[2-9]$|^[1-2]\d$|^3[0-6]$/; if(!isNumber(input) || !RANGE.test(radix)) { return input; } return input.toString(radix).toUpperCase(); } }); /** * @ngdoc filter * @name formatBytes * @kind function * * @description * Convert number into abbreviations. * i.e: K for one thousand, M for Million, B for billion * e.g: number of users:235,221, decimal:1 => 235.2 K */ angular.module('a8m.math.shortFmt', ['a8m.math']) .filter('shortFmt', ['$math', function ($math) { return function (number, decimal) { if(isNumber(decimal) && isFinite(decimal) && decimal%1===0 && decimal >= 0 && isNumber(number) && isFinite(number)){ if(number < 1e3) { return number; } else if(number < 1e6) { return convertToDecimal((number / 1e3), decimal, $math) + ' K'; } else if(number < 1e9){ return convertToDecimal((number / 1e6), decimal, $math) + ' M'; } else { return convertToDecimal((number / 1e9), decimal, $math) + ' B'; } }else{ return "NaN"; } } }]); /** * @ngdoc filter * @name sum * @kind function * * @description * Sum up all values within an array * */ angular.module('a8m.math.sum', []) .filter('sum', function () { return function (input, initial) { return (!isArray(input)) ? input : input.reduce(function(prev, curr) { return prev + curr; }, initial || 0); } }); /** * @ngdoc filter * @name endsWith * @kind function * * @description * checks whether string ends with the ends parameter. */ angular.module('a8m.ends-with', []) .filter('endsWith', function () { return function (input, ends, csensitive) { var sensitive = csensitive || false, position; if(!isString(input) || isUndefined(ends)) { return input; } input = (sensitive) ? input : input.toLowerCase(); position = input.length - ends.length; return input.indexOf((sensitive) ? ends : ends.toLowerCase(), position) !== -1; } }); /** * @ngdoc filter * @name ltrim * @kind function * * @description * Left trim. Similar to trimFilter, but only for left side. */ angular.module('a8m.ltrim', []) .filter('ltrim', function () { return function(input, chars) { var trim = chars || '\\s'; if(!isString(input)) { return input; } return input.replace(new RegExp('^' + trim + '+'), ''); } }); /** * @ngdoc filter * @name repeat * @kind function * * @description * Repeats a string n times */ angular.module('a8m.repeat', []) .filter('repeat',[ function () { return function (input, n, separator) { var times = ~~n; if(!isString(input)) { return input; } return (!times) ? input : strRepeat(input, --n, separator || ''); } }]); /** * Repeats a string n times with given separator * @param str string to repeat * @param n number of times * @param sep separator * @returns {*} */ function strRepeat(str, n, sep) { if(!n) { return str; } return str + sep + strRepeat(str, --n, sep); } /** * @ngdoc filter * @name rtrim * @kind function * * @description * Right trim. Similar to trimFilter, but only for right side. */ angular.module('a8m.rtrim', []) .filter('rtrim', function () { return function(input, chars) { var trim = chars || '\\s'; if(!isString(input)) { return input; } return input.replace(new RegExp(trim + '+$'), ''); } }); /** * @ngdoc filter * @name slugify * @kind function * * @description * remove spaces from string, replace with "-" or given argument */ angular.module('a8m.slugify', []) .filter('slugify',[ function () { return function (input, sub) { var replace = sub || '-'; if(isString(input)) { return input.toLowerCase() .replace(/\s+/g, replace); } return input; } }]); /** * @ngdoc filter * @name startWith * @kind function * * @description * checks whether string starts with the starts parameter. */ angular.module('a8m.starts-with', []) .filter('startsWith', function () { return function (input, start, csensitive) { var sensitive = csensitive || false; if(!isString(input) || isUndefined(start)) { return input; } input = (sensitive) ? input : input.toLowerCase(); return !input.indexOf((sensitive) ? start : start.toLowerCase()); } }); /** * @ngdoc filter * @name stringular * @kind function * * @description * get string with {n} and replace match with enumeration values */ angular.module('a8m.stringular', []) .filter('stringular', function () { return function(input) { var args = Array.prototype.slice.call(arguments, 1); return input.replace(/{(\d+)}/g, function (match, number) { return isUndefined(args[number]) ? match : args[number]; }); } }); /** * @ngdoc filter * @name stripTags * @kind function * * @description * strip html tags from string */ angular.module('a8m.strip-tags', []) .filter('stripTags', function () { return function(input) { if(isString(input)) { return input.replace(/<\S[^><]*>/g, ''); } return input; } }); /** * @ngdoc filter * @name trim * @kind function * * @description * Strip whitespace (or other characters) from the beginning and end of a string */ angular.module('a8m.trim', []) .filter('trim', function () { return function(input, chars) { var trim = chars || '\\s'; if(!isString(input)) { return input; } return input.replace(new RegExp('^' + trim + '+|' + trim + '+$', 'g'), ''); } }); /** * @ngdoc filter * @name truncate * @kind function * * @description * truncates a string given a specified length, providing a custom string to denote an omission. */ angular.module('a8m.truncate', []) .filter('truncate', function () { return function(input, length, suffix, preserve) { length = isUndefined(length) ? input.length : length; preserve = preserve || false; suffix = suffix || ''; if(!isString(input) || (input.length <= length)) return input; return input.substring(0, (preserve) ? ((input.indexOf(' ', length) === -1) ? input.length : input.indexOf(' ', length)) : length) + suffix; }; }); /** * @ngdoc filter * @name ucfirst * @kind function * * @description * ucfirst * */ angular.module('a8m.ucfirst', []) .filter('ucfirst', [function() { return function(input) { return angular.isString(input) ? input.split(' ') .map(function (char) { return char.charAt(0).toUpperCase() + char.substring(1); }).join(' ') : input; } }]); /** * @ngdoc filter * @name uriEncode * @kind function * * @description * get string as parameter and return encoded string */ angular.module('a8m.uri-encode', []) .filter('uriEncode',['$window', function ($window) { return function (input) { if(isString(input)) { return $window.encodeURI(input); } return input; } }]); /** * @ngdoc filter * @name wrap * @kind function * * @description * Wrap a string with another string */ angular.module('a8m.wrap', []) .filter('wrap', function () { return function(input, wrap, ends) { if(!isString(input) || isUndefined(wrap)) { return input; } return [wrap, input, ends || wrap].join(''); } }); /** * @ngdoc provider * @name filterWatcher * @kind function * * @description * filterWatchers is a _privateProvider * It's created to solve the problem of $rootScope:infdig(Infinite $digest loop) when using * some filters on the view. */ angular.module('a8m.filter-watcher', []) .provider('filterWatcher', function() { var filterPrefix = '_$$'; /** * @description * change the prefix name for filters on watch phase * @param prefix * @returns {filterWatcher} */ this.setPrefix = function(prefix) { filterPrefix = prefix; return this; }; this.$get = ['$window', function($window) { var $$timeout = $window.setTimeout; /** * @description * return the filter full name * @param name * @returns {string} * @private */ function _getFullName(name) { return filterPrefix + name; } /** * @description * return whether or not this object is watched in current phase * @param fName * @param object * @returns {boolean} * @private */ function _isWatched(fName, object) { return isDefined(object[fName]); } /** * @description * return the object.$$filterName instance in current phase * @param name * @param object * @private */ function _watch(name, object) { var fName = _getFullName(name); if(!_isWatched(fName, object)) { //Create new instance Object.defineProperty(object, fName, { enumerable: false, configurable: true, value: {} }); } return object[fName]; } /** * @description * destroy/delete current watch instance * @param name * @param object * @private */ function _destroy(name, object) { return $$timeout(function() { delete object[_getFullName(name)]; }); } return { $watch: _watch, $destroy: _destroy } }]; }); /** * @ngdoc module * @name angular.filters * @description * Bunch of useful filters for angularJS */ angular.module('angular.filter', [ 'a8m.ucfirst', 'a8m.uri-encode', 'a8m.slugify', 'a8m.strip-tags', 'a8m.stringular', 'a8m.truncate', 'a8m.starts-with', 'a8m.ends-with', 'a8m.wrap', 'a8m.trim', 'a8m.ltrim', 'a8m.rtrim', 'a8m.repeat', 'a8m.to-array', 'a8m.concat', 'a8m.contains', 'a8m.unique', 'a8m.is-empty', 'a8m.after', 'a8m.after-where', 'a8m.before', 'a8m.before-where', 'a8m.defaults', 'a8m.where', 'a8m.reverse', 'a8m.remove', 'a8m.remove-with', 'a8m.group-by', 'a8m.count-by', 'a8m.search-field', 'a8m.fuzzy-by', 'a8m.fuzzy', 'a8m.omit', 'a8m.pick', 'a8m.every', 'a8m.filter-by', 'a8m.xor', 'a8m.map', 'a8m.first', 'a8m.last', 'a8m.flatten', 'a8m.math', 'a8m.math.max', 'a8m.math.min', 'a8m.math.percent', 'a8m.math.radix', 'a8m.math.sum', 'a8m.math.degrees', 'a8m.math.radians', 'a8m.math.byteFmt', 'a8m.math.kbFmt', 'a8m.math.shortFmt', 'a8m.angular', 'a8m.conditions', 'a8m.is-null', 'a8m.filter-watcher' ]); })( window, window.angular );
brix/cdnjs
ajax/libs/angular-filter/0.4.8/angular-filter.js
JavaScript
mit
45,134
<?php /* This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ //require 'Yay/Action.php'; //require 'Yay/Description.php'; /** * An Action which delegates to a callback. * @author Chris Corbyn <chris@w3style.co.uk> * @package Yay */ class Yay_Actions_CallbackAction implements Yay_Action { /** * The callback to invoke. * @var callback * @access private */ private $_callback; /** * Create a new CallbackAction for $callback. * @param callback $callback */ public function __construct($callback) { $this->_callback = $callback; } /** * Mimmick the method Invocation and return a value. * @param Yay_Invocation $invocation * @return mixed */ public function &invoke(Yay_Invocation $invocation) { $ret = call_user_func($this->_callback, $invocation); return $ret; } /** * Describe this Expectation to $description. * @param Yay_Description $description */ public function describeTo(Yay_Description $description) { $description->appendText(' Runs a callback;'); } }
crsiebler/SymBlog
vendor/swiftmailer/test-suite/lib/yaymock/classes/Yay/Actions/CallbackAction.php
PHP
mit
1,649
/* SockJS client, http://sockjs.org, MIT License * * Copyright (c) 2011-2012 VMware, Inc. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ /* SockJS client, version 0.3.4.65.g83db, http://sockjs.org, MIT License Copyright (c) 2011-2012 VMware, Inc. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ // JSON2 by Douglas Crockford (minified). var JSON;JSON||(JSON={}),function(){function str(a,b){var c,d,e,f,g=gap,h,i=b[a];i&&typeof i=="object"&&typeof i.toJSON=="function"&&(i=i.toJSON(a)),typeof rep=="function"&&(i=rep.call(b,a,i));switch(typeof i){case"string":return quote(i);case"number":return isFinite(i)?String(i):"null";case"boolean":case"null":return String(i);case"object":if(!i)return"null";gap+=indent,h=[];if(Object.prototype.toString.apply(i)==="[object Array]"){f=i.length;for(c=0;c<f;c+=1)h[c]=str(c,i)||"null";e=h.length===0?"[]":gap?"[\n"+gap+h.join(",\n"+gap)+"\n"+g+"]":"["+h.join(",")+"]",gap=g;return e}if(rep&&typeof rep=="object"){f=rep.length;for(c=0;c<f;c+=1)typeof rep[c]=="string"&&(d=rep[c],e=str(d,i),e&&h.push(quote(d)+(gap?": ":":")+e))}else for(d in i)Object.prototype.hasOwnProperty.call(i,d)&&(e=str(d,i),e&&h.push(quote(d)+(gap?": ":":")+e));e=h.length===0?"{}":gap?"{\n"+gap+h.join(",\n"+gap)+"\n"+g+"}":"{"+h.join(",")+"}",gap=g;return e}}function quote(a){escapable.lastIndex=0;return escapable.test(a)?'"'+a.replace(escapable,function(a){var b=meta[a];return typeof b=="string"?b:"\\u"+("0000"+a.charCodeAt(0).toString(16)).slice(-4)})+'"':'"'+a+'"'}function f(a){return a<10?"0"+a:a}"use strict",typeof Date.prototype.toJSON!="function"&&(Date.prototype.toJSON=function(a){return isFinite(this.valueOf())?this.getUTCFullYear()+"-"+f(this.getUTCMonth()+1)+"-"+f(this.getUTCDate())+"T"+f(this.getUTCHours())+":"+f(this.getUTCMinutes())+":"+f(this.getUTCSeconds())+"Z":null},String.prototype.toJSON=Number.prototype.toJSON=Boolean.prototype.toJSON=function(a){return this.valueOf()});var cx=/[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,escapable=/[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,gap,indent,meta={"\b":"\\b","\t":"\\t","\n":"\\n","\f":"\\f","\r":"\\r",'"':'\\"',"\\":"\\\\"},rep;typeof JSON.stringify!="function"&&(JSON.stringify=function(a,b,c){var d;gap="",indent="";if(typeof c=="number")for(d=0;d<c;d+=1)indent+=" ";else typeof c=="string"&&(indent=c);rep=b;if(!b||typeof b=="function"||typeof b=="object"&&typeof b.length=="number")return str("",{"":a});throw new Error("JSON.stringify")}),typeof JSON.parse!="function"&&(JSON.parse=function(text,reviver){function walk(a,b){var c,d,e=a[b];if(e&&typeof e=="object")for(c in e)Object.prototype.hasOwnProperty.call(e,c)&&(d=walk(e,c),d!==undefined?e[c]=d:delete e[c]);return reviver.call(a,b,e)}var j;text=String(text),cx.lastIndex=0,cx.test(text)&&(text=text.replace(cx,function(a){return"\\u"+("0000"+a.charCodeAt(0).toString(16)).slice(-4)}));if(/^[\],:{}\s]*$/.test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g,"@").replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,"]").replace(/(?:^|:|,)(?:\s*\[)+/g,""))){j=eval("("+text+")");return typeof reviver=="function"?walk({"":j},""):j}throw new SyntaxError("JSON.parse")})}() // [*] Including lib/index.js // Public object var SockJS = (function(){ var _document = document; var _window = window; var utils = {}; // [*] Including lib/reventtarget.js /* * ***** BEGIN LICENSE BLOCK ***** * Copyright (c) 2011-2012 VMware, Inc. * * For the license see COPYING. * ***** END LICENSE BLOCK ***** */ /* Simplified implementation of DOM2 EventTarget. * http://www.w3.org/TR/DOM-Level-2-Events/events.html#Events-EventTarget */ var REventTarget = function() {}; REventTarget.prototype.addEventListener = function (eventType, listener) { if(!this._listeners) { this._listeners = {}; } if(!(eventType in this._listeners)) { this._listeners[eventType] = []; } var arr = this._listeners[eventType]; if(utils.arrIndexOf(arr, listener) === -1) { arr.push(listener); } return; }; REventTarget.prototype.removeEventListener = function (eventType, listener) { if(!(this._listeners && (eventType in this._listeners))) { return; } var arr = this._listeners[eventType]; var idx = utils.arrIndexOf(arr, listener); if (idx !== -1) { if(arr.length > 1) { this._listeners[eventType] = arr.slice(0, idx).concat( arr.slice(idx+1) ); } else { delete this._listeners[eventType]; } return; } return; }; REventTarget.prototype.dispatchEvent = function (event) { var t = event.type; var args = Array.prototype.slice.call(arguments, 0); if (this['on'+t]) { this['on'+t].apply(this, args); } if (this._listeners && t in this._listeners) { for(var i=0; i < this._listeners[t].length; i++) { this._listeners[t][i].apply(this, args); } } }; // [*] End of lib/reventtarget.js // [*] Including lib/simpleevent.js /* * ***** BEGIN LICENSE BLOCK ***** * Copyright (c) 2011-2012 VMware, Inc. * * For the license see COPYING. * ***** END LICENSE BLOCK ***** */ var SimpleEvent = function(type, obj) { this.type = type; if (typeof obj !== 'undefined') { for(var k in obj) { if (!obj.hasOwnProperty(k)) continue; this[k] = obj[k]; } } }; SimpleEvent.prototype.toString = function() { var r = []; for(var k in this) { if (!this.hasOwnProperty(k)) continue; var v = this[k]; if (typeof v === 'function') v = '[function]'; r.push(k + '=' + v); } return 'SimpleEvent(' + r.join(', ') + ')'; }; // [*] End of lib/simpleevent.js // [*] Including lib/eventemitter.js /* * ***** BEGIN LICENSE BLOCK ***** * Copyright (c) 2011-2012 VMware, Inc. * * For the license see COPYING. * ***** END LICENSE BLOCK ***** */ var EventEmitter = function(events) { var that = this; that._events = events || []; that._listeners = {}; }; EventEmitter.prototype.emit = function(type) { var that = this; that._verifyType(type); if (that._nuked) return; var args = Array.prototype.slice.call(arguments, 1); if (that['on'+type]) { that['on'+type].apply(that, args); } if (type in that._listeners) { for(var i = 0; i < that._listeners[type].length; i++) { that._listeners[type][i].apply(that, args); } } }; EventEmitter.prototype.on = function(type, callback) { var that = this; that._verifyType(type); if (that._nuked) return; if (!(type in that._listeners)) { that._listeners[type] = []; } that._listeners[type].push(callback); }; EventEmitter.prototype._verifyType = function(type) { var that = this; if (utils.arrIndexOf(that._events, type) === -1) { utils.log('Event ' + JSON.stringify(type) + ' not listed ' + JSON.stringify(that._events) + ' in ' + that); } }; EventEmitter.prototype.nuke = function() { var that = this; that._nuked = true; for(var i=0; i<that._events.length; i++) { delete that[that._events[i]]; } that._listeners = {}; }; // [*] End of lib/eventemitter.js // [*] Including lib/utils.js /* * ***** BEGIN LICENSE BLOCK ***** * Copyright (c) 2011-2012 VMware, Inc. * * For the license see COPYING. * ***** END LICENSE BLOCK ***** */ var random_string_chars = 'abcdefghijklmnopqrstuvwxyz0123456789_'; utils.random_string = function(length, max) { max = max || random_string_chars.length; var i, ret = []; for(i=0; i < length; i++) { ret.push( random_string_chars.substr(Math.floor(Math.random() * max),1) ); } return ret.join(''); }; utils.random_number = function(max) { return Math.floor(Math.random() * max); }; utils.random_number_string = function(max) { var t = (''+(max - 1)).length; var p = Array(t+1).join('0'); return (p + utils.random_number(max)).slice(-t); }; utils.getOrigin = function(url) { if (url.match(/^file:\/\//)) { // no origin when using file protocol return null; } var parts = url.match(/^(https?):\/\/([^\/:]+)(:([0-9]+))?/); var protocol = parts[1]; var hostname = parts[2]; var port = parts[4]; if (!port) { port = (protocol === "https") ? 443 : 80; } return protocol + "://" + hostname + ":" + port; }; utils.isSameOriginUrl = function(url_a, url_b) { // location.origin would do, but it's not always available. if (!url_b) url_b = _window.location.href; return utils.getOrigin(url_a) === utils.getOrigin(url_b); }; utils.getParentDomain = function(url) { // ipv4 ip address if (/^[0-9.]*$/.test(url)) return url; // ipv6 ip address if (/^\[/.test(url)) return url; // no dots if (!(/[.]/.test(url))) return url; var parts = url.split('.').slice(1); return parts.join('.'); }; utils.objectExtend = function(dst, src) { for(var k in src) { if (src.hasOwnProperty(k)) { dst[k] = src[k]; } } return dst; }; var WPrefix = '_jp'; utils.polluteGlobalNamespace = function() { if (!(WPrefix in _window)) { _window[WPrefix] = {}; } }; utils.closeFrame = function (code, reason) { return 'c'+JSON.stringify([code, reason]); }; utils.userSetCode = function (code) { return code === 1000 || (code >= 3000 && code <= 4999); }; // See: http://www.erg.abdn.ac.uk/~gerrit/dccp/notes/ccid2/rto_estimator/ // and RFC 2988. utils.countRTO = function (rtt) { var rto; if (rtt > 100) { rto = 3 * rtt; // rto > 300msec } else { rto = rtt + 200; // 200msec < rto <= 300msec } return rto; } utils.log = function() { if (_window.console && console.log && console.log.apply) { console.log.apply(console, arguments); } }; utils.bind = function(fun, that) { if (fun.bind) { return fun.bind(that); } else { return function() { return fun.apply(that, arguments); }; } }; utils.flatUrl = function(url) { return url.indexOf('?') === -1 && url.indexOf('#') === -1; }; utils.amendUrl = function(url) { var dl = _document.location; if (!url) { throw new Error('Wrong url for SockJS'); } if (!utils.flatUrl(url)) { throw new Error('Only basic urls are supported in SockJS'); } // '//abc' --> 'http://abc' if (url.indexOf('//') === 0) { url = dl.protocol + url; } // '/abc' --> 'http://localhost:80/abc' if (url.indexOf('/') === 0) { url = dl.protocol + '//' + dl.host + url; } // strip trailing slashes url = url.replace(/[/]+$/,''); return url; }; // IE doesn't support [].indexOf. utils.arrIndexOf = function(arr, obj){ for(var i=0; i < arr.length; i++){ if(arr[i] === obj){ return i; } } return -1; }; utils.arrSkip = function(arr, obj) { var idx = utils.arrIndexOf(arr, obj); if (idx === -1) { return arr.slice(); } else { var dst = arr.slice(0, idx); return dst.concat(arr.slice(idx+1)); } }; // Via: https://gist.github.com/1133122/2121c601c5549155483f50be3da5305e83b8c5df utils.isArray = Array.isArray || function(value) { return {}.toString.call(value).indexOf('Array') >= 0 }; utils.delay = function(t, fun) { if(typeof t === 'function') { fun = t; t = 0; } return setTimeout(fun, t); }; // Chars worth escaping, as defined by Douglas Crockford: // https://github.com/douglascrockford/JSON-js/blob/47a9882cddeb1e8529e07af9736218075372b8ac/json2.js#L196 var json_escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g, json_lookup = { "\u0000":"\\u0000","\u0001":"\\u0001","\u0002":"\\u0002","\u0003":"\\u0003", "\u0004":"\\u0004","\u0005":"\\u0005","\u0006":"\\u0006","\u0007":"\\u0007", "\b":"\\b","\t":"\\t","\n":"\\n","\u000b":"\\u000b","\f":"\\f","\r":"\\r", "\u000e":"\\u000e","\u000f":"\\u000f","\u0010":"\\u0010","\u0011":"\\u0011", "\u0012":"\\u0012","\u0013":"\\u0013","\u0014":"\\u0014","\u0015":"\\u0015", "\u0016":"\\u0016","\u0017":"\\u0017","\u0018":"\\u0018","\u0019":"\\u0019", "\u001a":"\\u001a","\u001b":"\\u001b","\u001c":"\\u001c","\u001d":"\\u001d", "\u001e":"\\u001e","\u001f":"\\u001f","\"":"\\\"","\\":"\\\\", "\u007f":"\\u007f","\u0080":"\\u0080","\u0081":"\\u0081","\u0082":"\\u0082", "\u0083":"\\u0083","\u0084":"\\u0084","\u0085":"\\u0085","\u0086":"\\u0086", "\u0087":"\\u0087","\u0088":"\\u0088","\u0089":"\\u0089","\u008a":"\\u008a", "\u008b":"\\u008b","\u008c":"\\u008c","\u008d":"\\u008d","\u008e":"\\u008e", "\u008f":"\\u008f","\u0090":"\\u0090","\u0091":"\\u0091","\u0092":"\\u0092", "\u0093":"\\u0093","\u0094":"\\u0094","\u0095":"\\u0095","\u0096":"\\u0096", "\u0097":"\\u0097","\u0098":"\\u0098","\u0099":"\\u0099","\u009a":"\\u009a", "\u009b":"\\u009b","\u009c":"\\u009c","\u009d":"\\u009d","\u009e":"\\u009e", "\u009f":"\\u009f","\u00ad":"\\u00ad","\u0600":"\\u0600","\u0601":"\\u0601", "\u0602":"\\u0602","\u0603":"\\u0603","\u0604":"\\u0604","\u070f":"\\u070f", "\u17b4":"\\u17b4","\u17b5":"\\u17b5","\u200c":"\\u200c","\u200d":"\\u200d", "\u200e":"\\u200e","\u200f":"\\u200f","\u2028":"\\u2028","\u2029":"\\u2029", "\u202a":"\\u202a","\u202b":"\\u202b","\u202c":"\\u202c","\u202d":"\\u202d", "\u202e":"\\u202e","\u202f":"\\u202f","\u2060":"\\u2060","\u2061":"\\u2061", "\u2062":"\\u2062","\u2063":"\\u2063","\u2064":"\\u2064","\u2065":"\\u2065", "\u2066":"\\u2066","\u2067":"\\u2067","\u2068":"\\u2068","\u2069":"\\u2069", "\u206a":"\\u206a","\u206b":"\\u206b","\u206c":"\\u206c","\u206d":"\\u206d", "\u206e":"\\u206e","\u206f":"\\u206f","\ufeff":"\\ufeff","\ufff0":"\\ufff0", "\ufff1":"\\ufff1","\ufff2":"\\ufff2","\ufff3":"\\ufff3","\ufff4":"\\ufff4", "\ufff5":"\\ufff5","\ufff6":"\\ufff6","\ufff7":"\\ufff7","\ufff8":"\\ufff8", "\ufff9":"\\ufff9","\ufffa":"\\ufffa","\ufffb":"\\ufffb","\ufffc":"\\ufffc", "\ufffd":"\\ufffd","\ufffe":"\\ufffe","\uffff":"\\uffff"}; // Some extra characters that Chrome gets wrong, and substitutes with // something else on the wire. var extra_escapable = /[\x00-\x1f\ud800-\udfff\ufffe\uffff\u0300-\u0333\u033d-\u0346\u034a-\u034c\u0350-\u0352\u0357-\u0358\u035c-\u0362\u0374\u037e\u0387\u0591-\u05af\u05c4\u0610-\u0617\u0653-\u0654\u0657-\u065b\u065d-\u065e\u06df-\u06e2\u06eb-\u06ec\u0730\u0732-\u0733\u0735-\u0736\u073a\u073d\u073f-\u0741\u0743\u0745\u0747\u07eb-\u07f1\u0951\u0958-\u095f\u09dc-\u09dd\u09df\u0a33\u0a36\u0a59-\u0a5b\u0a5e\u0b5c-\u0b5d\u0e38-\u0e39\u0f43\u0f4d\u0f52\u0f57\u0f5c\u0f69\u0f72-\u0f76\u0f78\u0f80-\u0f83\u0f93\u0f9d\u0fa2\u0fa7\u0fac\u0fb9\u1939-\u193a\u1a17\u1b6b\u1cda-\u1cdb\u1dc0-\u1dcf\u1dfc\u1dfe\u1f71\u1f73\u1f75\u1f77\u1f79\u1f7b\u1f7d\u1fbb\u1fbe\u1fc9\u1fcb\u1fd3\u1fdb\u1fe3\u1feb\u1fee-\u1fef\u1ff9\u1ffb\u1ffd\u2000-\u2001\u20d0-\u20d1\u20d4-\u20d7\u20e7-\u20e9\u2126\u212a-\u212b\u2329-\u232a\u2adc\u302b-\u302c\uaab2-\uaab3\uf900-\ufa0d\ufa10\ufa12\ufa15-\ufa1e\ufa20\ufa22\ufa25-\ufa26\ufa2a-\ufa2d\ufa30-\ufa6d\ufa70-\ufad9\ufb1d\ufb1f\ufb2a-\ufb36\ufb38-\ufb3c\ufb3e\ufb40-\ufb41\ufb43-\ufb44\ufb46-\ufb4e\ufff0-\uffff]/g, extra_lookup; // JSON Quote string. Use native implementation when possible. var JSONQuote = (JSON && JSON.stringify) || function(string) { json_escapable.lastIndex = 0; if (json_escapable.test(string)) { string = string.replace(json_escapable, function(a) { return json_lookup[a]; }); } return '"' + string + '"'; }; // This may be quite slow, so let's delay until user actually uses bad // characters. var unroll_lookup = function(escapable) { var i; var unrolled = {} var c = [] for(i=0; i<65536; i++) { c.push( String.fromCharCode(i) ); } escapable.lastIndex = 0; c.join('').replace(escapable, function (a) { unrolled[ a ] = '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4); return ''; }); escapable.lastIndex = 0; return unrolled; }; // Quote string, also taking care of unicode characters that browsers // often break. Especially, take care of unicode surrogates: // http://en.wikipedia.org/wiki/Mapping_of_Unicode_characters#Surrogates utils.quote = function(string) { var quoted = JSONQuote(string); // In most cases this should be very fast and good enough. extra_escapable.lastIndex = 0; if(!extra_escapable.test(quoted)) { return quoted; } if(!extra_lookup) extra_lookup = unroll_lookup(extra_escapable); return quoted.replace(extra_escapable, function(a) { return extra_lookup[a]; }); } var _all_protocols = ['websocket', 'xdr-streaming', 'xhr-streaming', 'iframe-eventsource', 'iframe-htmlfile', 'xdr-polling', 'xhr-polling', 'iframe-xhr-polling', 'jsonp-polling']; utils.probeProtocols = function(url) { var probed = {}; for(var i=0; i<_all_protocols.length; i++) { var protocol = _all_protocols[i]; // User can have a typo in protocol name. probed[protocol] = SockJS[protocol] && SockJS[protocol].enabled(url); } return probed; }; utils.detectProtocols = function(probed, protocols_whitelist, info) { var pe = {}, protocols = []; if (!protocols_whitelist) protocols_whitelist = _all_protocols; for(var i=0; i<protocols_whitelist.length; i++) { var protocol = protocols_whitelist[i]; pe[protocol] = probed[protocol]; } var maybe_push = function(protos) { var proto = protos.shift(); if (pe[proto]) { protocols.push(proto); } else { if (protos.length > 0) { maybe_push(protos); } } } // 1. Websocket if (info.websocket !== false) { maybe_push(['websocket']); } // 2. Streaming if (pe['xhr-streaming'] && !info.null_origin) { protocols.push('xhr-streaming'); } else { if (pe['xdr-streaming'] && !info.cookie_needed && !info.null_origin) { protocols.push('xdr-streaming'); } else { maybe_push(['iframe-eventsource', 'iframe-htmlfile']); } } // 3. Polling if (pe['xhr-polling'] && !info.null_origin) { protocols.push('xhr-polling'); } else { if (pe['xdr-polling'] && !info.cookie_needed && !info.null_origin) { protocols.push('xdr-polling'); } else { maybe_push(['iframe-xhr-polling', 'jsonp-polling']); } } return protocols; } utils.defaultOptions = function(){ return {devel: false, debug: false, protocols_whitelist: [], info: undefined, rtt: undefined, max_window_time: 4000, init_window_size: 4096}; } // [*] End of lib/utils.js // [*] Including lib/dom.js /* * ***** BEGIN LICENSE BLOCK ***** * Copyright (c) 2011-2012 VMware, Inc. * * For the license see COPYING. * ***** END LICENSE BLOCK ***** */ // May be used by htmlfile jsonp and transports. var MPrefix = '_sockjs_global'; utils.createHook = function() { var window_id = 'a' + utils.random_string(8); if (!(MPrefix in _window)) { var map = {}; _window[MPrefix] = function(window_id) { if (!(window_id in map)) { map[window_id] = { id: window_id, del: function() {delete map[window_id];} }; } return map[window_id]; } } return _window[MPrefix](window_id); }; utils.attachMessage = function(listener) { utils.attachEvent('message', listener); }; utils.attachEvent = function(event, listener) { if (typeof _window.addEventListener !== 'undefined') { _window.addEventListener(event, listener, false); } else { // IE quirks. // According to: http://stevesouders.com/misc/test-postmessage.php // the message gets delivered only to 'document', not 'window'. _document.attachEvent("on" + event, listener); // I get 'window' for ie8. _window.attachEvent("on" + event, listener); } }; utils.detachMessage = function(listener) { utils.detachEvent('message', listener); }; utils.detachEvent = function(event, listener) { if (typeof _window.addEventListener !== 'undefined') { _window.removeEventListener(event, listener, false); } else { _document.detachEvent("on" + event, listener); _window.detachEvent("on" + event, listener); } }; var on_unload = {}; // Things registered after beforeunload are to be called immediately. var after_unload = false; var trigger_unload_callbacks = function() { for(var ref in on_unload) { on_unload[ref](); delete on_unload[ref]; }; }; var unload_triggered = function() { if(after_unload) return; after_unload = true; trigger_unload_callbacks(); }; // 'unload' alone is not reliable in opera within an iframe, but we // can't use `beforeunload` as IE fires it on javascript: links. utils.attachEvent('unload', unload_triggered); utils.unload_add = function(listener) { var ref = utils.random_string(8); on_unload[ref] = listener; if (after_unload) { utils.delay(trigger_unload_callbacks); } return ref; }; utils.unload_del = function(ref) { if (ref in on_unload) delete on_unload[ref]; }; utils.createIframe = function (iframe_url, error_callback) { var iframe = _document.createElement('iframe'); var tref, unload_ref; var unattach = function() { clearTimeout(tref); // Explorer had problems with that. try {iframe.onload = null;} catch (x) {} iframe.onerror = null; }; var cleanup = function() { if (iframe) { unattach(); // This timeout makes chrome fire onbeforeunload event // within iframe. Without the timeout it goes straight to // onunload. setTimeout(function() { if(iframe) { iframe.parentNode.removeChild(iframe); } iframe = null; }, 0); utils.unload_del(unload_ref); } }; var onerror = function(r) { if (iframe) { cleanup(); error_callback(r); } }; var post = function(msg, origin) { try { // When the iframe is not loaded, IE raises an exception // on 'contentWindow'. if (iframe && iframe.contentWindow) { iframe.contentWindow.postMessage(msg, origin); } } catch (x) {}; }; iframe.src = iframe_url; iframe.style.display = 'none'; iframe.style.position = 'absolute'; iframe.onerror = function(){onerror('onerror');}; iframe.onload = function() { // `onload` is triggered before scripts on the iframe are // executed. Give it few seconds to actually load stuff. clearTimeout(tref); tref = setTimeout(function(){onerror('onload timeout');}, 2000); }; _document.body.appendChild(iframe); tref = setTimeout(function(){onerror('timeout');}, 15000); unload_ref = utils.unload_add(cleanup); return { post: post, cleanup: cleanup, loaded: unattach }; }; utils.createHtmlfile = function (iframe_url, error_callback) { var doc = new ActiveXObject('htmlfile'); var tref, unload_ref; var iframe; var unattach = function() { clearTimeout(tref); }; var cleanup = function() { if (doc) { unattach(); utils.unload_del(unload_ref); iframe.parentNode.removeChild(iframe); iframe = doc = null; CollectGarbage(); } }; var onerror = function(r) { if (doc) { cleanup(); error_callback(r); } }; var post = function(msg, origin) { try { // When the iframe is not loaded, IE raises an exception // on 'contentWindow'. if (iframe && iframe.contentWindow) { iframe.contentWindow.postMessage(msg, origin); } } catch (x) {}; }; doc.open(); doc.write('<html><s' + 'cript>' + 'document.domain="' + document.domain + '";' + '</s' + 'cript></html>'); doc.close(); doc.parentWindow[WPrefix] = _window[WPrefix]; var c = doc.createElement('div'); doc.body.appendChild(c); iframe = doc.createElement('iframe'); c.appendChild(iframe); iframe.src = iframe_url; tref = setTimeout(function(){onerror('timeout');}, 15000); unload_ref = utils.unload_add(cleanup); return { post: post, cleanup: cleanup, loaded: unattach }; }; // [*] End of lib/dom.js // [*] Including lib/dom2.js /* * ***** BEGIN LICENSE BLOCK ***** * Copyright (c) 2011-2012 VMware, Inc. * * For the license see COPYING. * ***** END LICENSE BLOCK ***** */ var AbstractXHRObject = function(){}; AbstractXHRObject.prototype = new EventEmitter(['chunk', 'finish']); AbstractXHRObject.prototype._start = function(method, url, payload, opts) { var that = this; try { that.xhr = new XMLHttpRequest(); } catch(x) {}; if (!that.xhr) { try { that.xhr = new _window.ActiveXObject('Microsoft.XMLHTTP'); } catch(x) {}; } if (_window.ActiveXObject || _window.XDomainRequest) { // IE8 caches even POSTs url += ((url.indexOf('?') === -1) ? '?' : '&') + 't='+(+new Date); } // Explorer tends to keep connection open, even after the // tab gets closed: http://bugs.jquery.com/ticket/5280 that.unload_ref = utils.unload_add(function(){that._cleanup(true);}); try { that.xhr.open(method, url, true); } catch(e) { // IE raises an exception on wrong port. that.emit('finish', 0, ''); that._cleanup(); return; }; if (!opts || !opts.no_credentials) { // Mozilla docs says https://developer.mozilla.org/en/XMLHttpRequest : // "This never affects same-site requests." that.xhr.withCredentials = 'true'; } if (opts && opts.headers) { for(var key in opts.headers) { that.xhr.setRequestHeader(key, opts.headers[key]); } } that.xhr.onreadystatechange = function() { if (that.xhr) { var x = that.xhr; switch (x.readyState) { case 3: // IE doesn't like peeking into responseText or status // on Microsoft.XMLHTTP and readystate=3 try { var status = x.status; var text = x.responseText; } catch (x) {}; // IE returns 1223 for 204: http://bugs.jquery.com/ticket/1450 if (status === 1223) status = 204; // IE does return readystate == 3 for 404 answers. if (text && text.length > 0) { that.emit('chunk', status, text); } break; case 4: var status = x.status; // IE returns 1223 for 204: http://bugs.jquery.com/ticket/1450 if (status === 1223) status = 204; that.emit('finish', status, x.responseText); that._cleanup(false); break; } } }; that.xhr.send(payload); }; AbstractXHRObject.prototype._cleanup = function(abort) { var that = this; if (!that.xhr) return; utils.unload_del(that.unload_ref); // IE needs this field to be a function that.xhr.onreadystatechange = function(){}; if (abort) { try { that.xhr.abort(); } catch(x) {}; } that.unload_ref = that.xhr = null; }; AbstractXHRObject.prototype.close = function() { var that = this; that.nuke(); that._cleanup(true); }; var XHRCorsObject = utils.XHRCorsObject = function() { var that = this, args = arguments; utils.delay(function(){that._start.apply(that, args);}); }; XHRCorsObject.prototype = new AbstractXHRObject(); var XHRLocalObject = utils.XHRLocalObject = function(method, url, payload) { var that = this; utils.delay(function(){ that._start(method, url, payload, { no_credentials: true }); }); }; XHRLocalObject.prototype = new AbstractXHRObject(); // References: // http://ajaxian.com/archives/100-line-ajax-wrapper // http://msdn.microsoft.com/en-us/library/cc288060(v=VS.85).aspx var XDRObject = utils.XDRObject = function(method, url, payload) { var that = this; utils.delay(function(){that._start(method, url, payload);}); }; XDRObject.prototype = new EventEmitter(['chunk', 'finish']); XDRObject.prototype._start = function(method, url, payload) { var that = this; var xdr = new XDomainRequest(); // IE caches even POSTs url += ((url.indexOf('?') === -1) ? '?' : '&') + 't='+(+new Date); var onerror = xdr.ontimeout = xdr.onerror = function() { that.emit('finish', 0, ''); that._cleanup(false); }; xdr.onprogress = function() { that.emit('chunk', 200, xdr.responseText); }; xdr.onload = function() { that.emit('finish', 200, xdr.responseText); that._cleanup(false); }; that.xdr = xdr; that.unload_ref = utils.unload_add(function(){that._cleanup(true);}); try { // Fails with AccessDenied if port number is bogus that.xdr.open(method, url); that.xdr.send(payload); } catch(x) { onerror(); } }; XDRObject.prototype._cleanup = function(abort) { var that = this; if (!that.xdr) return; utils.unload_del(that.unload_ref); that.xdr.ontimeout = that.xdr.onerror = that.xdr.onprogress = that.xdr.onload = null; if (abort) { try { that.xdr.abort(); } catch(x) {}; } that.unload_ref = that.xdr = null; }; XDRObject.prototype.close = function() { var that = this; that.nuke(); that._cleanup(true); }; // 1. Is natively via XHR // 2. Is natively via XDR // 3. Nope, but postMessage is there so it should work via the Iframe. // 4. Nope, sorry. utils.isXHRCorsCapable = function(url) { var protocol = url.match(/^(https?:)/)[0]; if (_window.XMLHttpRequest && 'withCredentials' in new XMLHttpRequest()) { return 1; } // XDomainRequest doesn't work if page is served from file:// if (_window.XDomainRequest && _document.domain && _document.location.protocol == protocol) { return 2; } if (IframeTransport.enabled()) { return 3; } return 4; }; var JsonpSender = function(url, payload, cache){ var that = this; utils.delay(function(){that._start(url, payload, cache);}); }; JsonpSender.prototype = new EventEmitter(['finish']); JsonpSender.prototype._start = function(url, payload, cache){ var that = this; if (!('_send_form' in cache)) { var form = cache._send_form = _document.createElement('form'); var area = cache._send_area = _document.createElement('textarea'); area.name = 'd'; form.style.display = 'none'; form.style.position = 'absolute'; form.method = 'POST'; form.enctype = 'application/x-www-form-urlencoded'; form.acceptCharset = "UTF-8"; form.appendChild(area); _document.body.appendChild(form); } var form = cache._send_form; var area = cache._send_area; var id = 'a' + utils.random_string(8); that.area = area; form.target = id; form.action = url + '/jsonp_send?i=' + id; var iframe; try { // ie6 dynamic iframes with target="" support (thanks Chris Lambacher) iframe = _document.createElement('<iframe name="'+ id +'">'); } catch(x) { iframe = _document.createElement('iframe'); iframe.name = id; } that.iframe = iframe; iframe.id = id; form.appendChild(iframe); iframe.style.display = 'none'; try { area.value = payload; } catch(e) { utils.log('Your browser is seriously broken. Go home! ' + e.message); } form.submit(); var completed = function(e) { if (!that.iframe) return; that._cleanup(); // It is not possible to detect if the iframe succeeded or // failed to submit our form. that.emit('finish'); }; iframe.onerror = iframe.onload = completed; iframe.onreadystatechange = function(e) { if (iframe.readyState == 'complete') completed(); }; }; JsonpSender.prototype._cleanup = function(){ var that = this; if (!that.iframe) return; var iframe = that.iframe; that.area.value = ''; that.iframe.onreadystatechange = that.iframe.onerror = that.iframe.onload = that.area = null; that.iframe = ''; // Opera mini doesn't like if we GC iframe // immediately, thus this timeout. utils.delay(500, function() { iframe.parentNode.removeChild(iframe); iframe = null; }); }; JsonpSender.prototype.close = function(){ var that = this; that.nuke(); that._cleanup(); }; // [*] End of lib/dom2.js // [*] Including lib/sockjs.js /* * ***** BEGIN LICENSE BLOCK ***** * Copyright (c) 2011-2012 VMware, Inc. * * For the license see COPYING. * ***** END LICENSE BLOCK ***** */ var SockJS = function(url, dep_protocols_whitelist, options) { if (this === _window) { // makes `new` optional return new SockJS(url, dep_protocols_whitelist, options); } var that = this, protocols_whitelist; that._options = utils.defaultOptions(); if (options) { utils.objectExtend(that._options, options); } that._base_url = utils.amendUrl(url); that._server = that._options.server || utils.random_number_string(1000); that._bus = new EventEmitter(['close', 'heartbeat', 'message']); if (that._options.protocols_whitelist && that._options.protocols_whitelist.length) { protocols_whitelist = that._options.protocols_whitelist; } else { // Deprecated API if (typeof dep_protocols_whitelist === 'string' && dep_protocols_whitelist.length > 0) { protocols_whitelist = [dep_protocols_whitelist]; } else if (utils.isArray(dep_protocols_whitelist)) { protocols_whitelist = dep_protocols_whitelist } else { protocols_whitelist = null; } if (protocols_whitelist) { that._debug('Deprecated API: Use "protocols_whitelist" option ' + 'instead of supplying protocol list as a second ' + 'parameter to SockJS constructor.'); } } that._protocols = []; that.protocol = null; that.readyState = SockJS.CONNECTING; that._ir = createInfoReceiver(that, that._base_url); that._ir.onfinish = function(info, rtt) { that._ir = null; if (info) { if (that._options.info) { // Override if user supplies the option info = utils.objectExtend(info, that._options.info); } if (that._options.rtt) { rtt = that._options.rtt; } that._applyInfo(info, rtt, protocols_whitelist); that._didClose(undefined, undefined, undefined, "info-onfinish"); } else { that._didClose(1002, 'Can\'t connect to server', true, "info-failed"); } }; }; // Inheritance SockJS.prototype = new REventTarget(); SockJS.version = "0.3.4.65.g83db"; SockJS.CONNECTING = 0; SockJS.OPEN = 1; SockJS.CLOSING = 2; SockJS.CLOSED = 3; SockJS.prototype._debug = function() { if (this._options.debug) utils.log.apply(utils, arguments); }; SockJS.prototype._dispatchOpen = function() { var that = this; if (that.readyState === SockJS.CONNECTING) { if (that._transport_tref) { clearTimeout(that._transport_tref); that._transport_tref = null; } that.readyState = SockJS.OPEN; var shi = that._options.info.server_heartbeat_interval; if (shi) that._startHeartbeats(shi); that.dispatchEvent(new SimpleEvent("open")); } else { // The server might have been restarted, and lost track of our // connection. that._didClose(1006, "Server lost session", undefined, "_dispatchOpen"); } }; SockJS.prototype._dispatchMessage = function(data) { var that = this; if (that.readyState !== SockJS.OPEN) return; that._bus.emit('message', data); that.dispatchEvent(new SimpleEvent("message", {data: data})); }; SockJS.prototype._dispatchHeartbeat = function(flavour) { var that = this; // Ignore heartbeats before "o" frame - prelude. if (that.readyState !== SockJS.OPEN) return; that._bus.emit('heartbeat', flavour); that.dispatchEvent(new SimpleEvent('heartbeat', {flavour: flavour})); }; SockJS.prototype._didClose = function(code, reason, force, debug) { var that = this; if (that.readyState !== SockJS.CONNECTING && that.readyState !== SockJS.OPEN && that.readyState !== SockJS.CLOSING) { // Temporarily disabled below exception until we find the issue // https://github.com/pusher/pusher-js/issues/35 // throw new Error('INVALID_STATE_ERR (' + code + ',' + reason + ',' + force + ',' + debug + ')'); return; } if (that._ir) { that._ir.nuke(); that._ir = null; } if (that._transport) { that._transport.doCleanup(); that._transport = null; } var close_event = new SimpleEvent("close", { code: code, reason: reason, wasClean: utils.userSetCode(code)}); if (!utils.userSetCode(code) && that.readyState === SockJS.CONNECTING && !force) { if (that._try_next_protocol(close_event)) { return; } close_event = new SimpleEvent("close", {code: 2000, reason: "All transports failed", wasClean: false, last_event: close_event}); } that.readyState = SockJS.CLOSED; that._bus.emit('close'); utils.delay(function() { that.dispatchEvent(close_event); }); }; SockJS.prototype._didMessage = function(data) { var that = this; var type = data.slice(0, 1); switch(type) { case 'o': that._dispatchOpen(); break; case 'a': var payload = JSON.parse(data.slice(1) || '[]'); for(var i=0; i < payload.length; i++){ that._dispatchMessage(payload[i]); } if (payload.length === 0) { that._dispatchHeartbeat('recv'); } break; case 'm': var payload = JSON.parse(data.slice(1) || 'null'); that._dispatchMessage(payload); break; case 'c': var payload = JSON.parse(data.slice(1) || '[]'); that._didClose(payload[0], payload[1], undefined, "_didMessage"); break; case 'h': that._dispatchHeartbeat('send'); break; } }; SockJS.prototype._try_next_protocol = function(close_event) { var that = this; if (that.protocol) { that._debug('Closed transport:', that.protocol, ''+close_event); that.protocol = null; } if (that._transport_tref) { clearTimeout(that._transport_tref); that._transport_tref = null; } while(1) { var protocol = that.protocol = that._protocols.shift(); if (!protocol) { return false; } // Some protocols require access to `body`, what if were in // the `head`? if (SockJS[protocol] && SockJS[protocol].need_body === true && (!_document.body || (typeof _document.readyState !== 'undefined' && _document.readyState !== 'complete'))) { that._protocols.unshift(protocol); that.protocol = 'waiting-for-load'; utils.attachEvent('load', function(){ that._try_next_protocol(); }); return true; } if (!SockJS[protocol] || !SockJS[protocol].enabled(that._base_url)) { that._debug('Skipping transport:', protocol); } else { var roundTrips = SockJS[protocol].roundTrips || 1; var to = ((that._options.rto || 0) * roundTrips) || 5000; that._transport_tref = utils.delay(to, function() { if (that.readyState === SockJS.CONNECTING) { // I can't understand how it is possible to run // this timer, when the state is CLOSED, but // apparently in IE everythin is possible. that._didClose(2007, "Transport timeouted"); } }); var connid = utils.random_string(8); var trans_url = that._base_url + '/' + that._server + '/' + connid; that._debug('Opening transport:', protocol, ' url:'+trans_url, ' RTO:'+that._options.rto); that._transport = new SockJS[protocol](that, trans_url, that._base_url); return true; } } }; SockJS.prototype.close = function(code, reason) { var that = this; if (code && !utils.userSetCode(code)) throw new Error("INVALID_ACCESS_ERR"); if(that.readyState !== SockJS.CONNECTING && that.readyState !== SockJS.OPEN) { return false; } that.readyState = SockJS.CLOSING; that._didClose(code || 1000, reason || "Normal closure", undefined, "close"); return true; }; SockJS.prototype.send = function(data) { var that = this; if (that.readyState === SockJS.CONNECTING) throw new Error('INVALID_STATE_ERR'); if (that.readyState === SockJS.OPEN) { that._transport.doSend(utils.quote('' + data)); } return true; }; SockJS.prototype._sendEmpty = function() { var that = this; if (that.readyState === SockJS.OPEN) { that._transport.doSend(''); } return true; }; SockJS.prototype._applyInfo = function(info, rtt, protocols_whitelist) { var that = this; that._options.info = info; that._options.rtt = rtt; that._options.rto = utils.countRTO(rtt); that._options.info.null_origin = Boolean( that._options.ignore_null_origin || !_document.domain ); var probed = utils.probeProtocols(that._base_url); that._protocols = utils.detectProtocols(probed, protocols_whitelist, info); // Replace the hostname part of URL if supplied by the server if (info.hostname) { var url = /(https?:\/\/)([^\/:]+)((\/|:)?.*)/.exec(that._base_url); that._base_url = url[1] + info.hostname + url[3]; } }; // [*] End of lib/sockjs.js // [*] Including lib/trans-websocket.js /* * ***** BEGIN LICENSE BLOCK ***** * Copyright (c) 2011-2012 VMware, Inc. * * For the license see COPYING. * ***** END LICENSE BLOCK ***** */ var WebSocketTransport = SockJS.websocket = function(ri, trans_url) { var that = this; var url = trans_url + '/websocket'; if (url.slice(0, 5) === 'https') { url = 'wss' + url.slice(5); } else { url = 'ws' + url.slice(4); } that.ri = ri; that.url = url; var Constructor = _window.WebSocket || _window.MozWebSocket; that.ws = new Constructor(that.url); that.ws.onmessage = function(e) { that.ri._didMessage(e.data); }; // Firefox has an interesting bug. If a websocket connection is // created after onunload, it stays alive even when user // navigates away from the page. In such situation let's lie - // let's not open the ws connection at all. See: // https://github.com/sockjs/sockjs-client/issues/28 // https://bugzilla.mozilla.org/show_bug.cgi?id=696085 that.unload_ref = utils.unload_add(function(){that.ws.close()}); that.ws.onclose = function() { that.ri._didMessage(utils.closeFrame(1006, "WebSocket connection broken")); }; }; WebSocketTransport.prototype.doSend = function(data) { this.ws.send('[' + data + ']'); }; WebSocketTransport.prototype.doCleanup = function() { var that = this; var ws = that.ws; if (ws) { ws.onmessage = ws.onclose = null; ws.close(); utils.unload_del(that.unload_ref); that.unload_ref = that.ri = that.ws = null; } }; WebSocketTransport.enabled = function() { return !!(_window.WebSocket || _window.MozWebSocket); }; // In theory, ws should require 1 round trip. But in chrome, this is // not very stable over SSL. Most likely a ws connection requires a // separate SSL connection, in which case 2 round trips are an // absolute minumum. WebSocketTransport.roundTrips = 2; // [*] End of lib/trans-websocket.js // [*] Including lib/trans-sender.js /* * ***** BEGIN LICENSE BLOCK ***** * Copyright (c) 2011-2012 VMware, Inc. * * For the license see COPYING. * ***** END LICENSE BLOCK ***** */ var BufferedSender = function() {}; BufferedSender.prototype.send_constructor = function(sender) { var that = this; that.send_buffer = []; that.sender = sender; that.init_window_size = that.ri._options.init_window_size; that.window_size = that.init_window_size; that.max_window_time = that.ri._options.max_window_time; }; BufferedSender.prototype.doSend = function(message) { var that = this; if (message.length > 0) { that.send_buffer.push(message); } if (that.send_stop && message.length == 0) { that.ri._debug('Attempting to send a heartbeat, but sending previous messages is still in progress.'); } if (!that.send_stop) { that.send_schedule(); } }; BufferedSender.prototype.adjustWindow = function(td, full_window) { var that = this; if (td > that.max_window_time) { // Over time, reduce window that.window_size = Math.max(that.window_size / 2, that.init_window_size); return true; } else { if (full_window) { if (td*2 < that.max_window_time) { // A lot time left that.window_size *= 2; } else { // Not so much time left... that.window_size *= 1.1; } return true; } } return false; } // For polling transports in a situation when in the message callback, // new message is being send. If the sending connection was started // before receiving one, it is possible to saturate the network and // timeout due to the lack of receiving socket. To avoid that we delay // sending messages by some small time, in order to let receiving // connection be started beforehand. This is only a halfmeasure and // does not fix the big problem, but it does make the tests go more // stable on slow networks. BufferedSender.prototype.send_schedule_wait = function() { var that = this; var tref; that.send_stop = function() { that.send_stop = null; clearTimeout(tref); }; tref = utils.delay(25, function() { that.send_stop = null; if (that.send_buffer.length > 0) { that.send_schedule(); } }); }; BufferedSender.prototype.send_schedule = function() { var that = this; var t0 = +new Date(); var i, serialized = 2, full_window = false; for (i=0; i < that.send_buffer.length; i++) { serialized += that.send_buffer[i].length + 1; if (serialized > that.window_size) { full_window = true; break; } } // Splice removes messages from the array. var messages = that.send_buffer.splice(0, i); var payload = '[' + messages.join(',') + ']'; that.send_stop = that.sender(that.trans_url, payload, function(success, abort_reason) { that.send_stop = null; if (success === false) { that.ri._didClose(1006, 'Sending error ' + abort_reason); } else { var td = (+new Date()) - t0; if (that.adjustWindow(td, full_window)) { that.ri._debug('window_size adjusted: ' + that.window_size); } that.send_schedule_wait(); } }); }; BufferedSender.prototype.send_destructor = function() { var that = this; if (that.send_stop) { that.send_stop(); } that.send_stop = null; }; var jsonPGenericSender = function(url, payload, callback) { var that = this; var js = new JsonpSender(url, payload, that); js.onfinish = function(){ callback(true); }; return function(){ js.close(); }; }; var createAjaxSender = function(AjaxObject) { return function(url, payload, callback) { var xo = new AjaxObject('POST', url + '/xhr_send', payload); xo.onfinish = function(status, text) { callback(status === 200 || status === 204, 'http status ' + status); }; return function(abort_reason) { xo.close(); }; }; }; // [*] End of lib/trans-sender.js // [*] Including lib/trans-jsonp-receiver.js /* * ***** BEGIN LICENSE BLOCK ***** * Copyright (c) 2011-2012 VMware, Inc. * * For the license see COPYING. * ***** END LICENSE BLOCK ***** */ // Parts derived from Socket.io: // https://github.com/LearnBoost/socket.io/blob/0.6.17/lib/socket.io/transports/jsonp-polling.js // and jQuery-JSONP: // https://code.google.com/p/jquery-jsonp/source/browse/trunk/core/jquery.jsonp.js var jsonPGenericReceiver = function(url, callback) { var tref; var script = _document.createElement('script'); var script2; // Opera synchronous load trick. var close_script = function(frame) { if (script2) { script2.parentNode.removeChild(script2); script2 = null; } if (script) { clearTimeout(tref); // Unfortunately, you can't really abort script loading of // the script. script.parentNode.removeChild(script); script.onreadystatechange = script.onerror = script.onload = script.onclick = null; script = null; callback(frame); callback = null; } }; // IE9 fires 'error' event after orsc or before, in random order. var loaded_okay = false; var error_timer = null; script.id = 'a' + utils.random_string(8); script.src = url; script.type = 'text/javascript'; script.charset = 'UTF-8'; script.onerror = function(e) { if (!error_timer) { // Delay firing close_script. error_timer = setTimeout(function() { if (!loaded_okay) { close_script(utils.closeFrame( 1006, "JSONP script loaded abnormally (onerror)")); } }, 1000); } }; script.onload = function(e) { close_script(utils.closeFrame(1006, "JSONP script loaded abnormally (onload)")); }; script.onreadystatechange = function(e) { if (/loaded|closed/.test(script.readyState)) { if (script && script.htmlFor && script.onclick) { loaded_okay = true; try { // In IE, actually execute the script. script.onclick(); } catch (x) {} } if (script) { close_script(utils.closeFrame(1006, "JSONP script loaded abnormally (onreadystatechange)")); } } }; // IE: event/htmlFor/onclick trick. // One can't rely on proper order for onreadystatechange. In order to // make sure, set a 'htmlFor' and 'event' properties, so that // script code will be installed as 'onclick' handler for the // script object. Later, onreadystatechange, manually execute this // code. FF and Chrome doesn't work with 'event' and 'htmlFor' // set. For reference see: // http://jaubourg.net/2010/07/loading-script-as-onclick-handler-of.html // Also, read on that about script ordering: // http://wiki.whatwg.org/wiki/Dynamic_Script_Execution_Order if (typeof script.async === 'undefined' && _document.attachEvent) { // According to mozilla docs, in recent browsers script.async defaults // to 'true', so we may use it to detect a good browser: // https://developer.mozilla.org/en/HTML/Element/script if (!/opera/i.test(navigator.userAgent)) { // Naively assume we're in IE try { script.htmlFor = script.id; script.event = "onclick"; } catch (x) {} script.async = true; } else { // Opera, second sync script hack script2 = _document.createElement('script'); script2.text = "try{var a = document.getElementById('"+script.id+"'); if(a)a.onerror();}catch(x){};"; script.async = script2.async = false; } } if (typeof script.async !== 'undefined') { script.async = true; } // Fallback mostly for Konqueror - stupid timer, 35 seconds shall be plenty. tref = setTimeout(function() { close_script(utils.closeFrame(1006, "JSONP script loaded abnormally (timeout)")); }, 35000); var head = _document.getElementsByTagName('head')[0]; head.insertBefore(script, head.firstChild); if (script2) { head.insertBefore(script2, head.firstChild); } return close_script; }; // [*] End of lib/trans-jsonp-receiver.js // [*] Including lib/trans-jsonp-polling.js /* * ***** BEGIN LICENSE BLOCK ***** * Copyright (c) 2011-2012 VMware, Inc. * * For the license see COPYING. * ***** END LICENSE BLOCK ***** */ // The simplest and most robust transport, using the well-know cross // domain hack - JSONP. This transport is quite inefficient - one // mssage could use up to one http request. But at least it works almost // everywhere. // Known limitations: // o you will get a spinning cursor // o for Konqueror a dumb timer is needed to detect errors var JsonPTransport = SockJS['jsonp-polling'] = function(ri, trans_url) { utils.polluteGlobalNamespace(); var that = this; that.ri = ri; that.trans_url = trans_url; that.send_constructor(jsonPGenericSender); that._schedule_recv(); }; // Inheritnace JsonPTransport.prototype = new BufferedSender(); JsonPTransport.prototype._schedule_recv = function() { var that = this; var callback = function(data) { that._recv_stop = null; if (data) { // no data - heartbeat; if (!that._is_closing) { that.ri._didMessage(data); } } // The message can be a close message, and change is_closing state. if (!that._is_closing) { that._schedule_recv(); } }; that._recv_stop = jsonPReceiverWrapper(that.trans_url + '/jsonp', jsonPGenericReceiver, callback); }; JsonPTransport.enabled = function() { return true; }; JsonPTransport.need_body = true; JsonPTransport.polling = true; JsonPTransport.prototype.doCleanup = function() { var that = this; that._is_closing = true; if (that._recv_stop) { that._recv_stop(); } that.ri = that._recv_stop = null; that.send_destructor(); }; // Abstract away code that handles global namespace pollution. var jsonPReceiverWrapper = function(url, constructReceiver, user_callback) { var id = 'a' + utils.random_string(6); var url_id = url + '?c=' + escape(WPrefix + '.' + id); // Unfortunately it is not possible to abort loading of the // script. We need to keep track of frake close frames. var aborting = 0; // Callback will be called exactly once. var callback = function(frame) { switch(aborting) { case 0: // Normal behaviour - delete hook _and_ emit message. delete _window[WPrefix][id]; user_callback(frame); break; case 1: // Fake close frame - emit but don't delete hook. user_callback(frame); aborting = 2; break; case 2: // Got frame after connection was closed, delete hook, don't emit. delete _window[WPrefix][id]; break; } }; var close_script = constructReceiver(url_id, callback); _window[WPrefix][id] = close_script; var stop = function() { if (_window[WPrefix][id]) { aborting = 1; _window[WPrefix][id](utils.closeFrame(1000, "JSONP user aborted read")); } }; return stop; }; // [*] End of lib/trans-jsonp-polling.js // [*] Including lib/trans-xhr.js /* * ***** BEGIN LICENSE BLOCK ***** * Copyright (c) 2011-2012 VMware, Inc. * * For the license see COPYING. * ***** END LICENSE BLOCK ***** */ var AjaxBasedTransport = function() {}; AjaxBasedTransport.prototype = new BufferedSender(); AjaxBasedTransport.prototype.run = function(ri, trans_url, url_suffix, Receiver, AjaxObject) { var that = this; that.ri = ri; that.trans_url = trans_url; that.send_constructor(createAjaxSender(AjaxObject)); that.poll = new Polling(ri, Receiver, trans_url + url_suffix, AjaxObject); }; AjaxBasedTransport.prototype.doCleanup = function() { var that = this; if (that.poll) { that.poll.abort(); that.poll = null; } that.send_destructor(); }; // xhr-streaming var XhrStreamingTransport = SockJS['xhr-streaming'] = function(ri, trans_url) { this.run(ri, trans_url, '/xhr_streaming', XhrReceiver, utils.XHRCorsObject); }; XhrStreamingTransport.prototype = new AjaxBasedTransport(); XhrStreamingTransport.enabled = function() { // Support for CORS Ajax aka Ajax2? Opera 12 claims CORS but // doesn't do streaming. return (_window.XMLHttpRequest && 'withCredentials' in new XMLHttpRequest() && (!/opera/i.test(navigator.userAgent))); }; XhrStreamingTransport.roundTrips = 2; // preflight, ajax // Safari gets confused when a streaming ajax request is started // before onload. This causes the load indicator to spin indefinetely. XhrStreamingTransport.need_body = true; // According to: // http://stackoverflow.com/questions/1641507/detect-browser-support-for-cross-domain-xmlhttprequests // http://hacks.mozilla.org/2009/07/cross-site-xmlhttprequest-with-cors/ // xdr-streaming var XdrStreamingTransport = SockJS['xdr-streaming'] = function(ri, trans_url) { this.run(ri, trans_url, '/xhr_streaming', XhrReceiver, utils.XDRObject); }; XdrStreamingTransport.prototype = new AjaxBasedTransport(); XdrStreamingTransport.enabled = function(url) { return utils.isXHRCorsCapable(url) === 2; }; XdrStreamingTransport.roundTrips = 2; // preflight, ajax // xhr-polling var XhrPollingTransport = SockJS['xhr-polling'] = function(ri, trans_url) { this.run(ri, trans_url, '/xhr', XhrReceiver, utils.XHRCorsObject); }; XhrPollingTransport.prototype = new AjaxBasedTransport(); XhrPollingTransport.enabled = XhrStreamingTransport.enabled; XhrPollingTransport.roundTrips = 2; // preflight, ajax XhrPollingTransport.polling = true; // xdr-polling var XdrPollingTransport = SockJS['xdr-polling'] = function(ri, trans_url) { this.run(ri, trans_url, '/xhr', XhrReceiver, utils.XDRObject); }; XdrPollingTransport.prototype = new AjaxBasedTransport(); XdrPollingTransport.enabled = XdrStreamingTransport.enabled; XdrPollingTransport.roundTrips = 2; // preflight, ajax XdrPollingTransport.polling = true; // [*] End of lib/trans-xhr.js // [*] Including lib/trans-iframe.js /* * ***** BEGIN LICENSE BLOCK ***** * Copyright (c) 2011-2012 VMware, Inc. * * For the license see COPYING. * ***** END LICENSE BLOCK ***** */ // Few cool transports do work only for same-origin. In order to make // them working cross-domain we shall use iframe, served form the // remote domain. New browsers, have capabilities to communicate with // cross domain iframe, using postMessage(). In IE it was implemented // from IE 8+, but of course, IE got some details wrong: // http://msdn.microsoft.com/en-us/library/cc197015(v=VS.85).aspx // http://stevesouders.com/misc/test-postmessage.php var IframeTransport = function() {}; IframeTransport.prototype.i_constructor = function(ri, trans_url, base_url) { var that = this; that.ri = ri; that.origin = utils.getOrigin(base_url); that.base_url = base_url; that.trans_url = trans_url; var iframe_url = base_url + '/iframe.html'; var query = []; if (that.ri._options.devel) { query.push('t=' + (+new Date)); } if (that.ri._options.js_path) { query.push('js_path=' + encodeURIComponent(that.ri._options.js_path)); } if (query.length > 0) { iframe_url += ("?" + query.join("&")); } that.window_id = utils.random_string(8); iframe_url += '#' + that.window_id; that.iframeObj = utils.createIframe(iframe_url, function(r) { that.ri._didClose(1006, "Unable to load an iframe (" + r + ")"); }); that.onmessage_cb = utils.bind(that.onmessage, that); utils.attachMessage(that.onmessage_cb); }; IframeTransport.prototype.doCleanup = function() { var that = this; if (that.iframeObj) { utils.detachMessage(that.onmessage_cb); try { // When the iframe is not loaded, IE raises an exception // on 'contentWindow'. if (that.iframeObj.iframe.contentWindow) { that.postMessage('c'); } } catch (x) {} that.iframeObj.cleanup(); that.iframeObj = null; that.onmessage_cb = that.iframeObj = null; } }; IframeTransport.prototype.onmessage = function(e) { var that = this; if (utils.getOrigin(e.origin) !== utils.getOrigin(that.origin)) return; var window_id = e.data.slice(0, 8); var type = e.data.slice(8, 9); var data = e.data.slice(9); if (window_id !== that.window_id) return; switch(type) { case 's': that.iframeObj.loaded(); that.postMessage('s', JSON.stringify([SockJS.version, that.protocol, that.trans_url, that.base_url, that.ri._options])); break; case 't': that.ri._didMessage(data); break; } }; IframeTransport.prototype.postMessage = function(type, data) { var that = this; that.iframeObj.post(that.window_id + type + (data || ''), that.origin); }; IframeTransport.prototype.doSend = function (message) { this.postMessage('m', message); }; IframeTransport.enabled = function() { // postMessage misbehaves in konqueror 4.6.5 - the messages are delivered with // huge delay, or not at all. var konqueror = navigator && navigator.userAgent && navigator.userAgent.indexOf('Konqueror') !== -1; return ((typeof _window.postMessage === 'function' || typeof _window.postMessage === 'object') && (!konqueror)); }; // [*] End of lib/trans-iframe.js // [*] Including lib/trans-iframe-within.js /* * ***** BEGIN LICENSE BLOCK ***** * Copyright (c) 2011-2012 VMware, Inc. * * For the license see COPYING. * ***** END LICENSE BLOCK ***** */ var curr_window_id; var postMessage = function (type, data) { if(parent !== _window) { parent.postMessage(curr_window_id + type + (data || ''), '*'); } else { utils.log("Can't postMessage, no parent window.", type, data); } }; var FacadeJS = function(options) { this._options = options || utils.defaultOptions(); }; FacadeJS.prototype._didClose = function (code, reason) { postMessage('t', utils.closeFrame(code, reason)); }; FacadeJS.prototype._didMessage = function (frame) { postMessage('t', frame); }; FacadeJS.prototype._doSend = function (data) { this._transport.doSend(data); }; FacadeJS.prototype._doCleanup = function () { this._transport.doCleanup(); }; FacadeJS.prototype._debug = function () { utils.log.apply(utils, arguments); } utils.parent_origin = undefined; SockJS.bootstrap_iframe = function() { var facade; curr_window_id = _document.location.hash.slice(1); var onMessage = function(e) { if(e.source !== parent) return; if(typeof utils.parent_origin === 'undefined') utils.parent_origin = e.origin; if (e.origin !== utils.parent_origin) return; var window_id = e.data.slice(0, 8); var type = e.data.slice(8, 9); var data = e.data.slice(9); if (window_id !== curr_window_id) return; switch(type) { case 's': var p = JSON.parse(data); var version = p[0]; var protocol = p[1]; var trans_url = p[2]; var base_url = p[3]; var options = p[4]; if (version !== SockJS.version) { utils.log("Incompatibile SockJS! Main site uses: " + version + ", the iframe: " + SockJS.version + ". " + "Double check SockJS urls and flush browser cache."); } if (!utils.flatUrl(trans_url) || !utils.flatUrl(base_url)) { utils.log("Only basic urls are supported in SockJS"); return; } if (!utils.isSameOriginUrl(trans_url) || !utils.isSameOriginUrl(base_url)) { utils.log("Can't connect to different domain from within an " + "iframe. (" + JSON.stringify([_window.location.href, trans_url, base_url]) + ")"); return; } facade = new FacadeJS(options); facade._transport = new FacadeJS[protocol](facade, trans_url, base_url); break; case 'm': facade._doSend(data); break; case 'c': if (facade) facade._doCleanup(); facade = null; break; } }; // alert('test ticker'); // facade = new FacadeJS(); // facade._transport = new FacadeJS['w-iframe-xhr-polling'](facade, 'http://host.com:9999/ticker/12/basd'); utils.attachMessage(onMessage); // Start postMessage('s'); }; // [*] End of lib/trans-iframe-within.js // [*] Including lib/info.js /* * ***** BEGIN LICENSE BLOCK ***** * Copyright (c) 2011-2012 VMware, Inc. * * For the license see COPYING. * ***** END LICENSE BLOCK ***** */ var InfoReceiver = function(base_url, AjaxObject) { var that = this; utils.delay(function(){that.doXhr(base_url, AjaxObject);}); }; InfoReceiver.prototype = new EventEmitter(['finish']); InfoReceiver.prototype.doXhr = function(base_url, AjaxObject) { var that = this; var t0 = (new Date()).getTime(); var xo = new AjaxObject('GET', base_url + '/info'); var tref = utils.delay(8000, function(){xo.ontimeout();}); xo.onfinish = function(status, text) { clearTimeout(tref); tref = null; if (status === 200) { var rtt = (new Date()).getTime() - t0; var info = JSON.parse(text); if (typeof info !== 'object') info = {}; that.emit('finish', info, rtt); } else { that.emit('finish'); } }; xo.ontimeout = function() { xo.close(); that.emit('finish'); }; }; var InfoReceiverIframe = function(ri, base_url) { var that = this; var go = function() { var ifr = new IframeTransport(); ifr.protocol = 'w-iframe-info-receiver'; var fun = function(r) { if (typeof r === 'string' && r.substr(0,1) === 'm') { var d = JSON.parse(r.substr(1)); var info = d[0], rtt = d[1]; that.emit('finish', info, rtt); } else { that.emit('finish'); } ifr.doCleanup(); ifr = null; }; var mock_ri = { _options: { js_path: ri._options.js_path }, _didClose: fun, _didMessage: fun }; ifr.i_constructor(mock_ri, base_url, base_url); } if(!_document.body) { utils.attachEvent('load', go); } else { go(); } }; InfoReceiverIframe.prototype = new EventEmitter(['finish']); var InfoReceiverFake = function() { // It may not be possible to do cross domain AJAX to get the info // data, for example for IE7. But we want to run JSONP, so let's // fake the response, with rtt=2s (rto=6s). var that = this; utils.delay(function() { that.emit('finish', {}, 2000); }); }; InfoReceiverFake.prototype = new EventEmitter(['finish']); var createInfoReceiver = function(connection, base_url) { if (utils.isSameOriginUrl(base_url)) { // If, for some reason, we have SockJS locally - there's no // need to start up the complex machinery. Just use ajax. return new InfoReceiver(base_url, utils.XHRLocalObject); } switch (utils.isXHRCorsCapable(base_url)) { case 1: // XHRLocalObject -> no_credentials=true return new InfoReceiver(base_url, utils.XHRLocalObject); case 2: return new InfoReceiver(base_url, utils.XDRObject); case 3: // Opera return new InfoReceiverIframe(connection, base_url); default: // IE 7 return new InfoReceiverFake(); }; }; var WInfoReceiverIframe = FacadeJS['w-iframe-info-receiver'] = function(ri, _trans_url, base_url) { var ir = new InfoReceiver(base_url, utils.XHRLocalObject); ir.onfinish = function(info, rtt) { ri._didMessage('m'+JSON.stringify([info, rtt])); ri._didClose(undefined, undefined, undefined, "w-iframe-info-receiver"); } }; WInfoReceiverIframe.prototype.doCleanup = function() {}; // [*] End of lib/info.js // [*] Including lib/trans-iframe-eventsource.js /* * ***** BEGIN LICENSE BLOCK ***** * Copyright (c) 2011-2012 VMware, Inc. * * For the license see COPYING. * ***** END LICENSE BLOCK ***** */ var EventSourceIframeTransport = SockJS['iframe-eventsource'] = function () { var that = this; that.protocol = 'w-iframe-eventsource'; that.i_constructor.apply(that, arguments); }; EventSourceIframeTransport.prototype = new IframeTransport(); EventSourceIframeTransport.enabled = function () { return ('EventSource' in _window) && IframeTransport.enabled(); }; EventSourceIframeTransport.need_body = true; EventSourceIframeTransport.roundTrips = 3; // html, javascript, eventsource // w-iframe-eventsource var EventSourceTransport = FacadeJS['w-iframe-eventsource'] = function(ri, trans_url) { this.run(ri, trans_url, '/eventsource', EventSourceReceiver, utils.XHRLocalObject); } EventSourceTransport.prototype = new AjaxBasedTransport(); // [*] End of lib/trans-iframe-eventsource.js // [*] Including lib/trans-iframe-xhr-polling.js /* * ***** BEGIN LICENSE BLOCK ***** * Copyright (c) 2011-2012 VMware, Inc. * * For the license see COPYING. * ***** END LICENSE BLOCK ***** */ var XhrPollingIframeTransport = SockJS['iframe-xhr-polling'] = function () { var that = this; that.protocol = 'w-iframe-xhr-polling'; that.i_constructor.apply(that, arguments); }; XhrPollingIframeTransport.prototype = new IframeTransport(); XhrPollingIframeTransport.enabled = function () { return _window.XMLHttpRequest && IframeTransport.enabled(); }; XhrPollingIframeTransport.need_body = true; XhrPollingIframeTransport.roundTrips = 3; // html, javascript, xhr // w-iframe-xhr-polling var XhrPollingITransport = FacadeJS['w-iframe-xhr-polling'] = function(ri, trans_url) { this.run(ri, trans_url, '/xhr', XhrReceiver, utils.XHRLocalObject); }; XhrPollingITransport.prototype = new AjaxBasedTransport(); // [*] End of lib/trans-iframe-xhr-polling.js // [*] Including lib/trans-iframe-htmlfile.js /* * ***** BEGIN LICENSE BLOCK ***** * Copyright (c) 2011-2012 VMware, Inc. * * For the license see COPYING. * ***** END LICENSE BLOCK ***** */ // This transport generally works in any browser, but will cause a // spinning cursor to appear in any browser other than IE. // We may test this transport in all browsers - why not, but in // production it should be only run in IE. var HtmlFileIframeTransport = SockJS['iframe-htmlfile'] = function () { var that = this; that.protocol = 'w-iframe-htmlfile'; that.i_constructor.apply(that, arguments); }; // Inheritance. HtmlFileIframeTransport.prototype = new IframeTransport(); HtmlFileIframeTransport.enabled = function() { return IframeTransport.enabled(); }; HtmlFileIframeTransport.need_body = true; HtmlFileIframeTransport.roundTrips = 3; // html, javascript, htmlfile // w-iframe-htmlfile var HtmlFileTransport = FacadeJS['w-iframe-htmlfile'] = function(ri, trans_url) { this.run(ri, trans_url, '/htmlfile', HtmlfileReceiver, utils.XHRLocalObject); }; HtmlFileTransport.prototype = new AjaxBasedTransport(); // [*] End of lib/trans-iframe-htmlfile.js // [*] Including lib/trans-polling.js /* * ***** BEGIN LICENSE BLOCK ***** * Copyright (c) 2011-2012 VMware, Inc. * * For the license see COPYING. * ***** END LICENSE BLOCK ***** */ var Polling = function(ri, Receiver, recv_url, AjaxObject) { var that = this; that.ri = ri; that.Receiver = Receiver; that.recv_url = recv_url; that.AjaxObject = AjaxObject; that._scheduleRecv(); }; Polling.prototype._scheduleRecv = function() { var that = this; var poll = that.poll = new that.Receiver(that.recv_url, that.AjaxObject); var msg_counter = 0; poll.onmessage = function(e) { msg_counter += 1; that.ri._didMessage(e.data); }; poll.onclose = function(e) { that.poll = poll = poll.onmessage = poll.onclose = null; if (!that.poll_is_closing) { if (e.reason === 'permanent') { that.ri._didClose(1006, 'Polling error (' + e.reason + ')'); } else { that._scheduleRecv(); } } }; }; Polling.prototype.abort = function() { var that = this; that.poll_is_closing = true; if (that.poll) { that.poll.abort(); } }; // [*] End of lib/trans-polling.js // [*] Including lib/trans-receiver-eventsource.js /* * ***** BEGIN LICENSE BLOCK ***** * Copyright (c) 2011-2012 VMware, Inc. * * For the license see COPYING. * ***** END LICENSE BLOCK ***** */ var EventSourceReceiver = function(url) { var that = this; var es = new EventSource(url); es.onmessage = function(e) { that.dispatchEvent(new SimpleEvent('message', {'data': unescape(e.data)})); }; that.es_close = es.onerror = function(e, abort_reason) { // ES on reconnection has readyState = 0 or 1. // on network error it's CLOSED = 2 var reason = abort_reason ? 'user' : (es.readyState !== 2 ? 'network' : 'permanent'); that.es_close = es.onmessage = es.onerror = null; // EventSource reconnects automatically. es.close(); es = null; // Safari and chrome < 15 crash if we close window before // waiting for ES cleanup. See: // https://code.google.com/p/chromium/issues/detail?id=89155 utils.delay(200, function() { that.dispatchEvent(new SimpleEvent('close', {reason: reason})); }); }; }; EventSourceReceiver.prototype = new REventTarget(); EventSourceReceiver.prototype.abort = function() { var that = this; if (that.es_close) { that.es_close({}, true); } }; // [*] End of lib/trans-receiver-eventsource.js // [*] Including lib/trans-receiver-htmlfile.js /* * ***** BEGIN LICENSE BLOCK ***** * Copyright (c) 2011-2012 VMware, Inc. * * For the license see COPYING. * ***** END LICENSE BLOCK ***** */ var _is_ie_htmlfile_capable; var isIeHtmlfileCapable = function() { if (_is_ie_htmlfile_capable === undefined) { if ('ActiveXObject' in _window) { try { _is_ie_htmlfile_capable = !!new ActiveXObject('htmlfile'); } catch (x) {} } else { _is_ie_htmlfile_capable = false; } } return _is_ie_htmlfile_capable; }; var HtmlfileReceiver = function(url) { var that = this; utils.polluteGlobalNamespace(); that.id = 'a' + utils.random_string(6, 26); url += ((url.indexOf('?') === -1) ? '?' : '&') + 'c=' + escape(WPrefix + '.' + that.id); var constructor = isIeHtmlfileCapable() ? utils.createHtmlfile : utils.createIframe; var iframeObj; _window[WPrefix][that.id] = { start: function () { iframeObj.loaded(); }, message: function (data) { that.dispatchEvent(new SimpleEvent('message', {'data': data})); }, stop: function () { that.iframe_close({}, 'network'); } }; that.iframe_close = function(e, abort_reason) { iframeObj.cleanup(); that.iframe_close = iframeObj = null; delete _window[WPrefix][that.id]; that.dispatchEvent(new SimpleEvent('close', {reason: abort_reason})); }; iframeObj = constructor(url, function(e) { that.iframe_close({}, 'permanent'); }); }; HtmlfileReceiver.prototype = new REventTarget(); HtmlfileReceiver.prototype.abort = function() { var that = this; if (that.iframe_close) { that.iframe_close({}, 'user'); } }; // [*] End of lib/trans-receiver-htmlfile.js // [*] Including lib/trans-receiver-xhr.js /* * ***** BEGIN LICENSE BLOCK ***** * Copyright (c) 2011-2012 VMware, Inc. * * For the license see COPYING. * ***** END LICENSE BLOCK ***** */ var XhrReceiver = function(url, AjaxObject) { var that = this; var buf_pos = 0; that.xo = new AjaxObject('POST', url, null); that.xo.onchunk = function(status, text) { if (status !== 200) return; while (1) { var buf = text.slice(buf_pos); var p = buf.indexOf('\n'); if (p === -1) break; buf_pos += p+1; var msg = buf.slice(0, p); that.dispatchEvent(new SimpleEvent('message', {data: msg})); } }; that.xo.onfinish = function(status, text) { that.xo.onchunk(status, text); that.xo = null; var reason = status === 200 ? 'network' : 'permanent'; that.dispatchEvent(new SimpleEvent('close', {reason: reason})); } }; XhrReceiver.prototype = new REventTarget(); XhrReceiver.prototype.abort = function() { var that = this; if (that.xo) { that.xo.close(); that.dispatchEvent(new SimpleEvent('close', {reason: 'user'})); that.xo = null; } }; // [*] End of lib/trans-receiver-xhr.js // [*] Including lib/test-hooks.js /* * ***** BEGIN LICENSE BLOCK ***** * Copyright (c) 2011-2012 VMware, Inc. * * For the license see COPYING. * ***** END LICENSE BLOCK ***** */ // For testing SockJS.getUtils = function(){ return utils; }; SockJS.getIframeTransport = function(){ return IframeTransport; }; // [*] End of lib/test-hooks.js // [*] Including lib/heartbeater.js /* * ***** BEGIN LICENSE BLOCK ***** * Copyright (c) 2011-2012 VMware, Inc. * * For the license see COPYING. * ***** END LICENSE BLOCK ***** */ var Heartbeater = function(timeout, how_many_intervals){ var that = this; that.timeout = timeout; that.not_poked = 0; that._onTimeout = function(){ that.not_poked += 1; if (that.not_poked === how_many_intervals) { that.emit('timeout'); } that._restartTimeout(); }; that._restartTimeout(); }; Heartbeater.prototype = new EventEmitter(['first', 'second', 'timeout']); Heartbeater.prototype.poke = function(){ this.not_poked = 0; this._restartTimeout(); }; Heartbeater.prototype.close = function(){ clearTimeout(this.tref); }; Heartbeater.prototype._restartTimeout = function(){ if (this.tref) { clearTimeout(this.tref); } this.tref = setTimeout(this._onTimeout, this.timeout); }; SockJS.prototype._startHeartbeats = function(server_heartbeat_interval){ var that = this; that._heartbeater = new Heartbeater(server_heartbeat_interval, 2); // 1. Answer server pings that._bus.on('heartbeat', function(){ if (!SockJS[that.protocol].polling) { // Polling transports need to reconnect on every delivery, // there is no need to send anything. that._sendEmpty(); } }); // 2. Expect traffic between (2*interval...3*interval) that._heartbeater.ontimeout = function(){ that._didClose(1007, 'Server heartbeat missed'); }; var poke = function(){ that._heartbeater.poke(); }; that._bus.on('heartbeat', poke); that._bus.on('message', poke); that._bus.on('close', function(){ that._heartbeater.nuke(); that._heartbeater.close(); }); }; // [*] End of lib/heartbeater.js return SockJS; })(); if ('_sockjs_onload' in window) setTimeout(_sockjs_onload, 1); // AMD compliance if (typeof define === 'function' && define.amd) { define('sockjs', [], function(){return SockJS;}); } if (typeof module === 'object' && module && module.exports) { module.exports = SockJS; } // [*] End of lib/index.js // [*] End of lib/all.js
ddeveloperr/cdnjs
ajax/libs/pusher/2.1.2/sockjs.js
JavaScript
mit
85,224
#!/usr/bin/env node 'use strict'; // stdlib var fs = require('fs'); // 3rd-party var argparse = require('argparse'); // internal var yaml = require('..'); //////////////////////////////////////////////////////////////////////////////// var cli = new argparse.ArgumentParser({ prog: 'js-yaml', version: require('../package.json').version, addHelp: true }); cli.addArgument(['-c', '--compact'], { help: 'Display errors in compact mode', action: 'storeTrue' }); // deprecated (not needed after we removed output colors) // option suppressed, but not completely removed for compatibility cli.addArgument(['-j', '--to-json'], { help: argparse.Const.SUPPRESS, dest: 'json', action: 'storeTrue' }); cli.addArgument(['-t', '--trace'], { help: 'Show stack trace on error', action: 'storeTrue' }); cli.addArgument(['file'], { help: 'File to read, utf-8 encoded without BOM' }); //////////////////////////////////////////////////////////////////////////////// var options = cli.parseArgs(); //////////////////////////////////////////////////////////////////////////////// fs.readFile(options.file, 'utf8', function (error, input) { var output, isYaml; if (error) { if ('ENOENT' === error.code) { console.error('File not found: ' + options.file); process.exit(2); } console.error( options.trace && error.stack || error.message || String(error)); process.exit(1); } try { output = JSON.parse(input); isYaml = false; } catch (error) { if (error instanceof SyntaxError) { try { output = []; yaml.loadAll(input, function (doc) { output.push(doc); }, {}); isYaml = true; if (0 === output.length) { output = null; } else if (1 === output.length) { output = output[0]; } } catch (error) { if (options.trace && error.stack) { console.error(error.stack); } else { console.error(error.toString(options.compact)); } process.exit(1); } } else { console.error( options.trace && error.stack || error.message || String(error)); process.exit(1); } } if (isYaml) { console.log(JSON.stringify(output, null, ' ')); } else { console.log(yaml.dump(output)); } process.exit(0); });
iyogeshjoshi/angular-table-manipulation
node_modules/bower/node_modules/update-notifier/node_modules/configstore/node_modules/js-yaml/bin/js-yaml.js
JavaScript
mit
2,395
if (typeof _yuitest_coverage == "undefined"){ _yuitest_coverage = {}; _yuitest_coverline = function(src, line){ var coverage = _yuitest_coverage[src]; if (!coverage.lines[line]){ coverage.calledLines++; } coverage.lines[line]++; }; _yuitest_coverfunc = function(src, name, line){ var coverage = _yuitest_coverage[src], funcId = name + ":" + line; if (!coverage.functions[funcId]){ coverage.calledFunctions++; } coverage.functions[funcId]++; }; } _yuitest_coverage["build/yui-log-nodejs/yui-log-nodejs.js"] = { lines: {}, functions: {}, coveredLines: 0, calledLines: 0, coveredFunctions: 0, calledFunctions: 0, path: "build/yui-log-nodejs/yui-log-nodejs.js", code: [] }; _yuitest_coverage["build/yui-log-nodejs/yui-log-nodejs.js"].code=["YUI.add('yui-log-nodejs', function (Y, NAME) {","","var sys = require(process.binding('natives').util ? 'util' : 'sys'),"," hasColor = false;","","try {"," var stdio = require(\"stdio\");"," hasColor = stdio.isStderrATTY();","} catch (ex) {"," hasColor = true;","}","","Y.config.useColor = hasColor;","","Y.consoleColor = function(str, num) {"," if (!this.config.useColor) {"," return str;"," }"," if (!num) {"," num = '32';"," }"," return \"\\u001b[\" + num +\"m\" + str + \"\\u001b[0m\";","};","","","var logFn = function(str, t, m) {"," var id = '', lvl, mLvl;"," if (this.id) {"," id = '[' + this.id + ']:';"," }"," t = t || 'info';"," m = (m) ? this.consoleColor(' (' + m.toLowerCase() + '):', 35) : '';",""," if (str === null) {"," str = 'null';"," }",""," if ((typeof str === 'object') || str instanceof Array) {"," try {"," //Should we use this?"," if (str.tagName || str._yuid || str._query) {"," str = str.toString();"," } else {"," str = sys.inspect(str);"," }"," } catch (e) {"," //Fail catcher"," }"," }",""," lvl = '37;40';"," mLvl = ((str) ? '' : 31);"," t = t+''; //Force to a string.."," switch (t.toLowerCase()) {"," case 'error':"," lvl = mLvl = 31;"," break;"," case 'warn':"," lvl = 33;"," break;"," case 'debug':"," lvl = 34;"," break;"," }"," if (typeof str === 'string') {"," if (str && str.indexOf(\"\\n\") !== -1) {"," str = \"\\n\" + str;"," }"," }",""," // output log messages to stderr"," sys.error(this.consoleColor(t.toLowerCase() + ':', lvl) + m + ' ' + this.consoleColor(str, mLvl));","};","","if (!Y.config.logFn) {"," Y.config.logFn = logFn;","}","","","","}, '@VERSION@');"]; _yuitest_coverage["build/yui-log-nodejs/yui-log-nodejs.js"].lines = {"1":0,"3":0,"6":0,"7":0,"8":0,"10":0,"13":0,"15":0,"16":0,"17":0,"19":0,"20":0,"22":0,"26":0,"27":0,"28":0,"29":0,"31":0,"32":0,"34":0,"35":0,"38":0,"39":0,"41":0,"42":0,"44":0,"51":0,"52":0,"53":0,"54":0,"56":0,"57":0,"59":0,"60":0,"62":0,"63":0,"65":0,"66":0,"67":0,"72":0,"75":0,"76":0}; _yuitest_coverage["build/yui-log-nodejs/yui-log-nodejs.js"].functions = {"consoleColor:15":0,"logFn:26":0,"(anonymous 1):1":0}; _yuitest_coverage["build/yui-log-nodejs/yui-log-nodejs.js"].coveredLines = 42; _yuitest_coverage["build/yui-log-nodejs/yui-log-nodejs.js"].coveredFunctions = 3; _yuitest_coverline("build/yui-log-nodejs/yui-log-nodejs.js", 1); YUI.add('yui-log-nodejs', function (Y, NAME) { _yuitest_coverfunc("build/yui-log-nodejs/yui-log-nodejs.js", "(anonymous 1)", 1); _yuitest_coverline("build/yui-log-nodejs/yui-log-nodejs.js", 3); var sys = require(process.binding('natives').util ? 'util' : 'sys'), hasColor = false; _yuitest_coverline("build/yui-log-nodejs/yui-log-nodejs.js", 6); try { _yuitest_coverline("build/yui-log-nodejs/yui-log-nodejs.js", 7); var stdio = require("stdio"); _yuitest_coverline("build/yui-log-nodejs/yui-log-nodejs.js", 8); hasColor = stdio.isStderrATTY(); } catch (ex) { _yuitest_coverline("build/yui-log-nodejs/yui-log-nodejs.js", 10); hasColor = true; } _yuitest_coverline("build/yui-log-nodejs/yui-log-nodejs.js", 13); Y.config.useColor = hasColor; _yuitest_coverline("build/yui-log-nodejs/yui-log-nodejs.js", 15); Y.consoleColor = function(str, num) { _yuitest_coverfunc("build/yui-log-nodejs/yui-log-nodejs.js", "consoleColor", 15); _yuitest_coverline("build/yui-log-nodejs/yui-log-nodejs.js", 16); if (!this.config.useColor) { _yuitest_coverline("build/yui-log-nodejs/yui-log-nodejs.js", 17); return str; } _yuitest_coverline("build/yui-log-nodejs/yui-log-nodejs.js", 19); if (!num) { _yuitest_coverline("build/yui-log-nodejs/yui-log-nodejs.js", 20); num = '32'; } _yuitest_coverline("build/yui-log-nodejs/yui-log-nodejs.js", 22); return "\u001b[" + num +"m" + str + "\u001b[0m"; }; _yuitest_coverline("build/yui-log-nodejs/yui-log-nodejs.js", 26); var logFn = function(str, t, m) { _yuitest_coverfunc("build/yui-log-nodejs/yui-log-nodejs.js", "logFn", 26); _yuitest_coverline("build/yui-log-nodejs/yui-log-nodejs.js", 27); var id = '', lvl, mLvl; _yuitest_coverline("build/yui-log-nodejs/yui-log-nodejs.js", 28); if (this.id) { _yuitest_coverline("build/yui-log-nodejs/yui-log-nodejs.js", 29); id = '[' + this.id + ']:'; } _yuitest_coverline("build/yui-log-nodejs/yui-log-nodejs.js", 31); t = t || 'info'; _yuitest_coverline("build/yui-log-nodejs/yui-log-nodejs.js", 32); m = (m) ? this.consoleColor(' (' + m.toLowerCase() + '):', 35) : ''; _yuitest_coverline("build/yui-log-nodejs/yui-log-nodejs.js", 34); if (str === null) { _yuitest_coverline("build/yui-log-nodejs/yui-log-nodejs.js", 35); str = 'null'; } _yuitest_coverline("build/yui-log-nodejs/yui-log-nodejs.js", 38); if ((typeof str === 'object') || str instanceof Array) { _yuitest_coverline("build/yui-log-nodejs/yui-log-nodejs.js", 39); try { //Should we use this? _yuitest_coverline("build/yui-log-nodejs/yui-log-nodejs.js", 41); if (str.tagName || str._yuid || str._query) { _yuitest_coverline("build/yui-log-nodejs/yui-log-nodejs.js", 42); str = str.toString(); } else { _yuitest_coverline("build/yui-log-nodejs/yui-log-nodejs.js", 44); str = sys.inspect(str); } } catch (e) { //Fail catcher } } _yuitest_coverline("build/yui-log-nodejs/yui-log-nodejs.js", 51); lvl = '37;40'; _yuitest_coverline("build/yui-log-nodejs/yui-log-nodejs.js", 52); mLvl = ((str) ? '' : 31); _yuitest_coverline("build/yui-log-nodejs/yui-log-nodejs.js", 53); t = t+''; //Force to a string.. _yuitest_coverline("build/yui-log-nodejs/yui-log-nodejs.js", 54); switch (t.toLowerCase()) { case 'error': _yuitest_coverline("build/yui-log-nodejs/yui-log-nodejs.js", 56); lvl = mLvl = 31; _yuitest_coverline("build/yui-log-nodejs/yui-log-nodejs.js", 57); break; case 'warn': _yuitest_coverline("build/yui-log-nodejs/yui-log-nodejs.js", 59); lvl = 33; _yuitest_coverline("build/yui-log-nodejs/yui-log-nodejs.js", 60); break; case 'debug': _yuitest_coverline("build/yui-log-nodejs/yui-log-nodejs.js", 62); lvl = 34; _yuitest_coverline("build/yui-log-nodejs/yui-log-nodejs.js", 63); break; } _yuitest_coverline("build/yui-log-nodejs/yui-log-nodejs.js", 65); if (typeof str === 'string') { _yuitest_coverline("build/yui-log-nodejs/yui-log-nodejs.js", 66); if (str && str.indexOf("\n") !== -1) { _yuitest_coverline("build/yui-log-nodejs/yui-log-nodejs.js", 67); str = "\n" + str; } } // output log messages to stderr _yuitest_coverline("build/yui-log-nodejs/yui-log-nodejs.js", 72); sys.error(this.consoleColor(t.toLowerCase() + ':', lvl) + m + ' ' + this.consoleColor(str, mLvl)); }; _yuitest_coverline("build/yui-log-nodejs/yui-log-nodejs.js", 75); if (!Y.config.logFn) { _yuitest_coverline("build/yui-log-nodejs/yui-log-nodejs.js", 76); Y.config.logFn = logFn; } }, '@VERSION@');
jamesarosen/cdnjs
ajax/libs/yui/3.9.1/yui-log-nodejs/yui-log-nodejs-coverage.js
JavaScript
mit
8,251
define(['../array/some'], function (some) { var datePatterns = [ /^([0-9]{4})$/, // YYYY /^([0-9]{4})-([0-9]{2})$/, // YYYY-MM (YYYYMM not allowed) /^([0-9]{4})-?([0-9]{2})-?([0-9]{2})$/ // YYYY-MM-DD or YYYYMMDD ]; var ORD_DATE = /^([0-9]{4})-?([0-9]{3})$/; // YYYY-DDD var timePatterns = [ /^([0-9]{2}(?:\.[0-9]*)?)$/, // HH.hh /^([0-9]{2}):?([0-9]{2}(?:\.[0-9]*)?)$/, // HH:MM.mm /^([0-9]{2}):?([0-9]{2}):?([0-9]{2}(\.[0-9]*)?)$/ // HH:MM:SS.ss ]; var DATE_TIME = /^(.+)T(.+)$/; var TIME_ZONE = /^(.+)([+\-])([0-9]{2}):?([0-9]{2})$/; function matchAll(str, patterns) { var match; var found = some(patterns, function(pattern) { return !!(match = pattern.exec(str)); }); return found ? match : null; } function getDate(year, month, day) { var date = new Date(Date.UTC(year, month, day)); // Explicitly set year to avoid Date.UTC making dates < 100 relative to // 1900 date.setUTCFullYear(year); var valid = date.getUTCFullYear() === year && date.getUTCMonth() === month && date.getUTCDate() === day; return valid ? +date : NaN; } function parseOrdinalDate(str) { var match = ORD_DATE.exec(str); if (match ) { var year = +match[1], day = +match[2], date = new Date(Date.UTC(year, 0, day)); if (date.getUTCFullYear() === year) { return +date; } } return NaN; } function parseDate(str) { var match, year, month, day; match = matchAll(str, datePatterns); if (match === null) { // Ordinal dates are verified differently. return parseOrdinalDate(str); } year = (match[1] === void 0) ? 0 : +match[1]; month = (match[2] === void 0) ? 0 : +match[2] - 1; day = (match[3] === void 0) ? 1 : +match[3]; return getDate(year, month, day); } function getTime(hr, min, sec) { var valid = (hr < 24 && hr >= 0 && min < 60 && min >= 0 && sec < 60 && min >= 0) || (hr === 24 && min === 0 && sec === 0); if (!valid) { return NaN; } return ((hr * 60 + min) * 60 + sec) * 1000; } function parseOffset(str) { var match; if (str.charAt(str.length - 1) === 'Z') { str = str.substring(0, str.length - 1); } else { match = TIME_ZONE.exec(str); if (match) { var hours = +match[3], minutes = (match[4] === void 0) ? 0 : +match[4], offset = getTime(hours, minutes, 0); if (match[2] === '-') { offset *= -1; } return { offset: offset, time: match[1] }; } } // No time zone specified, assume UTC return { offset: 0, time: str }; } function parseTime(str) { var match; var offset = parseOffset(str); str = offset.time; offset = offset.offset; if (isNaN(offset)) { return NaN; } match = matchAll(str, timePatterns); if (match === null) { return NaN; } var hours = (match[1] === void 0) ? 0 : +match[1], minutes = (match[2] === void 0) ? 0 : +match[2], seconds = (match[3] === void 0) ? 0 : +match[3]; return getTime(hours, minutes, seconds) - offset; } /** * Parse an ISO8601 formatted date string, and return a Date object. */ function parseISO8601(str){ var match = DATE_TIME.exec(str); if (!match) { // No time specified return parseDate(str); } return parseDate(match[1]) + parseTime(match[2]); } return parseISO8601; });
subhodeep-cuelogic/angular_seed
node_modules/bower/node_modules/mout/src/date/parseIso.js
JavaScript
mit
4,082
var getAllKeys = require('./_getAllKeys'); /** Used to compose bitmasks for value comparisons. */ var COMPARE_PARTIAL_FLAG = 1; /** Used for built-in method references. */ var objectProto = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /** * A specialized version of `baseIsEqualDeep` for objects with support for * partial deep comparisons. * * @private * @param {Object} object The object to compare. * @param {Object} other The other object to compare. * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. * @param {Function} customizer The function to customize comparisons. * @param {Function} equalFunc The function to determine equivalents of values. * @param {Object} stack Tracks traversed `object` and `other` objects. * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. */ function equalObjects(object, other, bitmask, customizer, equalFunc, stack) { var isPartial = bitmask & COMPARE_PARTIAL_FLAG, objProps = getAllKeys(object), objLength = objProps.length, othProps = getAllKeys(other), othLength = othProps.length; if (objLength != othLength && !isPartial) { return false; } var index = objLength; while (index--) { var key = objProps[index]; if (!(isPartial ? key in other : hasOwnProperty.call(other, key))) { return false; } } // Assume cyclic values are equal. var stacked = stack.get(object); if (stacked && stack.get(other)) { return stacked == other; } var result = true; stack.set(object, other); stack.set(other, object); var skipCtor = isPartial; while (++index < objLength) { key = objProps[index]; var objValue = object[key], othValue = other[key]; if (customizer) { var compared = isPartial ? customizer(othValue, objValue, key, other, object, stack) : customizer(objValue, othValue, key, object, other, stack); } // Recursively compare objects (susceptible to call stack limits). if (!(compared === undefined ? (objValue === othValue || equalFunc(objValue, othValue, bitmask, customizer, stack)) : compared )) { result = false; break; } skipCtor || (skipCtor = key == 'constructor'); } if (result && !skipCtor) { var objCtor = object.constructor, othCtor = other.constructor; // Non `Object` object instances with different constructors are not equal. if (objCtor != othCtor && ('constructor' in object && 'constructor' in other) && !(typeof objCtor == 'function' && objCtor instanceof objCtor && typeof othCtor == 'function' && othCtor instanceof othCtor)) { result = false; } } stack['delete'](object); stack['delete'](other); return result; } module.exports = equalObjects;
callmeonlyashu/MEANJS
node_modules/google-auth-library/node_modules/lodash/_equalObjects.js
JavaScript
mit
2,903
/* TED player */ .mejs-container.mejs-ted { } .mejs-ted .mejs-controls { background: #eee; height: 65px; } .mejs-ted .mejs-button, .mejs-ted .mejs-time { position: absolute; background: #ddd; } .mejs-ted .mejs-controls .mejs-time-rail .mejs-time-total { background-color: none; background: url(controls-ted.png) repeat-x 0 -52px; height: 6px; } .mejs-ted .mejs-controls .mejs-time-rail .mejs-time-buffering { height: 6px; } .mejs-ted .mejs-controls .mejs-time-rail .mejs-time-loaded { background-color: none; background: url(controls-ted.png) repeat-x 0 -52px; width: 0; height: 6px; } .mejs-ted .mejs-controls .mejs-time-rail .mejs-time-current { width: 0; height: 6px; background-color: none; background: url(controls-ted.png) repeat-x 0 -59px; } .mejs-ted .mejs-controls .mejs-time-rail .mejs-time-handle { display: block; margin: 0; width: 14px; height: 21px; top: -7px; border: 0; background: url(controls-ted.png) no-repeat 0 0; } .mejs-ted .mejs-controls .mejs-time-rail .mejs-time-float { display: none; } .mejs-ted .mejs-controls .mejs-playpause-button { top: 29px; left: 9px; width: 49px; height: 28px; } .mejs-ted .mejs-controls .mejs-playpause-button button { width: 49px; height: 28px; background: url(controls-ted.png) no-repeat -50px -23px; margin: 0; padding: 0; } .mejs-ted .mejs-controls .mejs-pause button { background-position: 0 -23px; } .mejs-ted .mejs-controls .mejs-fullscreen-button { top: 34px; right: 9px; width: 17px; height: 15px; background : none; } .mejs-ted .mejs-controls .mejs-fullscreen-button button { width: 19px; height: 17px; background: transparent url(controls-ted.png) no-repeat 0 -66px; margin: 0; padding: 0; } .mejs-ted .mejs-controls .mejs-unfullscreen button { background: transparent url(controls-ted.png) no-repeat -21px -66px; margin: 0; padding: 0; } .mejs-ted .mejs-controls .mejs-volume-button { top: 30px; right: 35px; width: 24px; height: 22px; } .mejs-ted .mejs-controls .mejs-mute button { background: url(controls-ted.png) no-repeat -15px 0; width: 24px; height: 22px; margin: 0; padding: 0; } .mejs-ted .mejs-controls .mejs-unmute button { background: url(controls-ted.png) no-repeat -40px 0; width: 24px; height: 22px; margin: 0; padding: 0; } .mejs-ted .mejs-controls .mejs-volume-button .mejs-volume-slider { background: #fff; border: solid 1px #aaa; border-width: 1px 1px 0 1px; width: 22px; height: 65px; top: -65px; } .mejs-ted .mejs-controls .mejs-volume-button .mejs-volume-total { background: url(controls-ted.png) repeat-y -41px -66px; left: 8px; width: 6px; height: 50px; } .mejs-ted .mejs-controls .mejs-volume-button .mejs-volume-current { left: 8px; width: 6px; background: url(controls-ted.png) repeat-y -48px -66px; height: 50px; } .mejs-ted .mejs-controls .mejs-volume-button .mejs-volume-handle { display: none; } .mejs-ted .mejs-controls .mejs-time span { color: #333; } .mejs-ted .mejs-controls .mejs-currenttime-container { position: absolute; top: 32px; right: 100px; border: solid 1px #999; background: #fff; color: #333; padding-top: 2px; border-radius: 3px; color: #333; } .mejs-ted .mejs-controls .mejs-duration-container { position: absolute; top: 32px; right: 65px; border: solid 1px #999; background: #fff; color: #333; padding-top: 2px; border-radius: 3px; color: #333; } .mejs-ted .mejs-controls .mejs-time button{ color: #333; } .mejs-ted .mejs-controls .mejs-captions-button { display: none; } /* END: TED player */ /* WMP player */ .mejs-container.mejs-wmp { } .mejs-wmp .mejs-controls { background: transparent url(controls-wmp-bg.png) center 16px no-repeat; height: 65px; } .mejs-wmp .mejs-button, .mejs-wmp .mejs-time { position: absolute; background: transparent; } .mejs-wmp .mejs-controls .mejs-time-rail .mejs-time-total { background-color: transparent; border: solid 1px #ccc; height: 3px; } .mejs-wmp .mejs-controls .mejs-time-rail .mejs-time-buffering { height: 3px; } .mejs-wmp .mejs-controls .mejs-time-rail .mejs-time-loaded { background-color: rgba(255,255,255,0.3); width: 0; height: 3px; } .mejs-wmp .mejs-controls .mejs-time-rail .mejs-time-current { width: 0; height: 1px; background-color: #014CB6; border: solid 1px #7FC9FA; border-width: 1px 0; border-color: #7FC9FA #fff #619FF2 #fff; } .mejs-wmp .mejs-controls .mejs-time-rail .mejs-time-handle { display: block; margin: 0; width: 16px; height: 9px; top: -3px; border: 0; background: url(controls-wmp.png) no-repeat 0 -80px; } .mejs-wmp .mejs-controls .mejs-time-rail .mejs-time-float { display: none; } .mejs-wmp .mejs-controls .mejs-playpause-button { top: 10px; left: 50%; margin: 10px 0 0 -20px; width: 40px; height: 40px; } .mejs-wmp .mejs-controls .mejs-playpause-button button { width: 40px; height: 40px; background: url(controls-wmp.png) no-repeat 0 0; margin: 0; padding: 0; } .mejs-wmp .mejs-controls .mejs-pause button { background-position: 0 -40px; } .mejs-wmp .mejs-controls .mejs-currenttime-container { position: absolute; top: 25px; left: 50%; margin-left: -93px; } .mejs-wmp .mejs-controls .mejs-duration-container { position: absolute; top: 25px; left: 50%; margin-left: -58px; } .mejs-wmp .mejs-controls .mejs-volume-button { top: 32px; right: 50%; margin-right: -55px; width: 20px; height: 15px; } .mejs-wmp .mejs-controls .mejs-volume-button button { margin: 0; padding: 0; background: url(controls-wmp.png) no-repeat -42px -17px; width: 20px; height: 15px; } .mejs-wmp .mejs-controls .mejs-unmute button { margin: 0; padding: 0; background: url(controls-wmp.png) no-repeat -42px 0; width: 20px; height: 15px; } .mejs-wmp .mejs-controls .mejs-volume-button .mejs-volume-slider { background: rgba(102,102,102,0.6); } .mejs-wmp .mejs-controls .mejs-fullscreen-button { top: 32px; right: 50%; margin-right: -82px; width: 15px; height: 14px; } .mejs-wmp .mejs-controls .mejs-fullscreen-button button { margin: 0; padding: 0; background: url(controls-wmp.png) no-repeat -63px 0; width: 15px; height: 14px; } .mejs-wmp .mejs-controls .mejs-captions-button { display: none; } /* END: WMP player */
Download/cdnjs
ajax/libs/mediaelement/2.15.1/mejs-skins.css
CSS
mit
6,201
YUI.add('datasource-jsonschema', function(Y) { /** * Extends DataSource with schema-parsing on JSON data. * * @module datasource * @submodule datasource-jsonschema */ /** * Adds schema-parsing to the DataSource Utility. * @class DataSourceJSONSchema * @extends Plugin.Base */ var DataSourceJSONSchema = function() { DataSourceJSONSchema.superclass.constructor.apply(this, arguments); }; Y.mix(DataSourceJSONSchema, { /** * The namespace for the plugin. This will be the property on the host which * references the plugin instance. * * @property NS * @type String * @static * @final * @value "schema" */ NS: "schema", /** * Class name. * * @property NAME * @type String * @static * @final * @value "dataSourceJSONSchema" */ NAME: "dataSourceJSONSchema", ///////////////////////////////////////////////////////////////////////////// // // DataSourceJSONSchema Attributes // ///////////////////////////////////////////////////////////////////////////// ATTRS: { schema: { //value: {} } } }); Y.extend(DataSourceJSONSchema, Y.Plugin.Base, { /** * Internal init() handler. * * @method initializer * @param config {Object} Config object. * @private */ initializer: function(config) { this.doBefore("_defDataFn", this._beforeDefDataFn); }, /** * Parses raw data into a normalized response. To accommodate XHR responses, * will first look for data in data.responseText. Otherwise will just work * with data. * * @method _beforeDefDataFn * @param tId {Number} Unique transaction ID. * @param request {Object} The request. * @param callback {Object} The callback object with the following properties: * <dl> * <dt>success (Function)</dt> <dd>Success handler.</dd> * <dt>failure (Function)</dt> <dd>Failure handler.</dd> * </dl> * @param data {Object} Raw data. * @protected */ _beforeDefDataFn: function(e) { var data = e.data && (e.data.responseText || e.data), schema = this.get('schema'), payload = e.details[0]; payload.response = Y.DataSchema.JSON.apply.call(this, schema, data) || { meta: {}, results: data }; this.get("host").fire("response", payload); return new Y.Do.Halt("DataSourceJSONSchema plugin halted _defDataFn"); } }); Y.namespace('Plugin').DataSourceJSONSchema = DataSourceJSONSchema; }, '@VERSION@' ,{requires:['datasource-local', 'plugin', 'dataschema-json']});
pvnr0082t/cdnjs
ajax/libs/yui/3.6.0pr4/datasource-jsonschema/datasource-jsonschema-debug.js
JavaScript
mit
2,716
YUI.add('event-mousewheel', function(Y) { /** * Adds mousewheel event support * @module event * @submodule event-mousewheel */ var DOM_MOUSE_SCROLL = 'DOMMouseScroll', fixArgs = function(args) { var a = Y.Array(args, 0, true), target; if (Y.UA.gecko) { a[0] = DOM_MOUSE_SCROLL; target = Y.config.win; } else { target = Y.config.doc; } if (a.length < 3) { a[2] = target; } else { a.splice(2, 0, target); } return a; }; /** * Mousewheel event. This listener is automatically attached to the * correct target, so one should not be supplied. Mouse wheel * direction and velocity is stored in the 'wheelDelta' field. * @event mousewheel * @param type {string} 'mousewheel' * @param fn {function} the callback to execute * @param context optional context object * @param args 0..n additional arguments to provide to the listener. * @return {EventHandle} the detach handle * @for YUI */ Y.Env.evt.plugins.mousewheel = { on: function() { return Y.Event._attach(fixArgs(arguments)); }, detach: function() { return Y.Event.detach.apply(Y.Event, fixArgs(arguments)); } }; }, '@VERSION@' ,{requires:['node-base']});
RoryStolzenberg/cdnjs
ajax/libs/yui/3.5.0pr3/event-mousewheel/event-mousewheel-debug.js
JavaScript
mit
1,293
YUI.add('datasource-arrayschema', function(Y) { /** * Extends DataSource with schema-parsing on array data. * * @module datasource * @submodule datasource-arrayschema */ /** * Adds schema-parsing to the DataSource Utility. * @class DataSourceArraySchema * @extends Plugin.Base */ var DataSourceArraySchema = function() { DataSourceArraySchema.superclass.constructor.apply(this, arguments); }; Y.mix(DataSourceArraySchema, { /** * The namespace for the plugin. This will be the property on the host which * references the plugin instance. * * @property NS * @type String * @static * @final * @value "schema" */ NS: "schema", /** * Class name. * * @property NAME * @type String * @static * @final * @value "dataSourceArraySchema" */ NAME: "dataSourceArraySchema", ///////////////////////////////////////////////////////////////////////////// // // DataSourceArraySchema Attributes // ///////////////////////////////////////////////////////////////////////////// ATTRS: { schema: { //value: {} } } }); Y.extend(DataSourceArraySchema, Y.Plugin.Base, { /** * Internal init() handler. * * @method initializer * @param config {Object} Config object. * @private */ initializer: function(config) { this.doBefore("_defDataFn", this._beforeDefDataFn); }, /** * Parses raw data into a normalized response. * * @method _beforeDefDataFn * @param tId {Number} Unique transaction ID. * @param request {Object} The request. * @param callback {Object} The callback object with the following properties: * <dl> * <dt>success (Function)</dt> <dd>Success handler.</dd> * <dt>failure (Function)</dt> <dd>Failure handler.</dd> * </dl> * @param data {Object} Raw data. * @protected */ _beforeDefDataFn: function(e) { var data = (Y.DataSource.IO && (this.get("host") instanceof Y.DataSource.IO) && Y.Lang.isString(e.data.responseText)) ? e.data.responseText : e.data, response = Y.DataSchema.Array.apply.call(this, this.get("schema"), data), payload = e.details[0]; // Default if (!response) { response = { meta: {}, results: data }; } payload.response = response; this.get("host").fire("response", payload); return new Y.Do.Halt("DataSourceArraySchema plugin halted _defDataFn"); } }); Y.namespace('Plugin').DataSourceArraySchema = DataSourceArraySchema; }, '@VERSION@' ,{requires:['datasource-local', 'plugin', 'dataschema-array']});
maruilian11/cdnjs
ajax/libs/yui/3.4.0pr3/datasource-arrayschema/datasource-arrayschema.js
JavaScript
mit
2,805
<?php /** * DOMPDF - PHP5 HTML to PDF renderer * * File: $RCSfile: table_row_positioner.cls.php,v $ * Created on: 2004-06-08 * * Copyright (c) 2004 - Benj Carson <benjcarson@digitaljunkies.ca> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library in the file LICENSE.LGPL; if not, write to the * Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA * 02111-1307 USA * * Alternatively, you may distribute this software under the terms of the * PHP License, version 3.0 or later. A copy of this license should have * been distributed with this file in the file LICENSE.PHP . If this is not * the case, you can obtain a copy at http://www.php.net/license/3_0.txt. * * The latest version of DOMPDF might be available at: * http://www.dompdf.com/ * * @link http://www.dompdf.com/ * @copyright 2004 Benj Carson * @author Benj Carson <benjcarson@digitaljunkies.ca> * @package dompdf */ /* $Id: table_row_positioner.cls.php 216 2010-03-11 22:49:18Z ryan.masten $ */ /** * Positions table rows * * @access private * @package dompdf */ class Table_Row_Positioner extends Positioner { function __construct(Frame_Decorator $frame) { parent::__construct($frame); } //........................................................................ function position() { $cb = $this->_frame->get_containing_block(); $p = $this->_frame->get_prev_sibling(); if ( $p ) $y = $p->get_position("y") + $p->get_margin_height(); else $y = $cb["y"]; $this->_frame->set_position($cb["x"], $y); } }
IbrahimHanifa/manajemen_pln
application/third_party/dompdf/include/table_row_positioner.cls.php
PHP
mit
2,142
// // ResponseSerializationTests.swift // // Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Alamofire import Foundation import XCTest class ResponseSerializationTestCase: BaseTestCase { let error = NSError(domain: Error.Domain, code: -10000, userInfo: nil) // MARK: - Data Response Serializer Tests func testThatDataResponseSerializerSucceedsWhenDataIsNotNil() { // Given let serializer = Request.dataResponseSerializer() let data = "data".dataUsingEncoding(NSUTF8StringEncoding)! // When let result = serializer.serializeResponse(nil, nil, data, nil) // Then XCTAssertTrue(result.isSuccess, "result is success should be true") XCTAssertNotNil(result.value, "result value should not be nil") XCTAssertNil(result.error, "result error should be nil") } func testThatDataResponseSerializerFailsWhenDataIsNil() { // Given let serializer = Request.dataResponseSerializer() // When let result = serializer.serializeResponse(nil, nil, nil, nil) // Then XCTAssertTrue(result.isFailure, "result is failure should be true") XCTAssertNil(result.value, "result value should be nil") XCTAssertNotNil(result.error, "result error should not be nil") if let error = result.error { XCTAssertEqual(error.domain, Error.Domain, "error domain should match expected value") XCTAssertEqual(error.code, Error.Code.DataSerializationFailed.rawValue, "error code should match expected value") } else { XCTFail("error should not be nil") } } func testThatDataResponseSerializerFailsWhenErrorIsNotNil() { // Given let serializer = Request.dataResponseSerializer() // When let result = serializer.serializeResponse(nil, nil, nil, error) // Then XCTAssertTrue(result.isFailure, "result is failure should be true") XCTAssertNil(result.value, "result value should be nil") XCTAssertNotNil(result.error, "result error should not be nil") if let error = result.error { XCTAssertEqual(error.domain, Error.Domain, "error domain should match expected value") XCTAssertEqual(error.code, self.error.code, "error code should match expected value") } else { XCTFail("error should not be nil") } } func testThatDataResponseSerializerFailsWhenDataIsNilWithNon204ResponseStatusCode() { // Given let serializer = Request.dataResponseSerializer() let URL = NSURL(string: "https://httpbin.org/get")! let response = NSHTTPURLResponse(URL: URL, statusCode: 200, HTTPVersion: "HTTP/1.1", headerFields: nil) // When let result = serializer.serializeResponse(nil, response, nil, nil) // Then XCTAssertTrue(result.isFailure, "result is failure should be true") XCTAssertNil(result.value, "result value should be nil") XCTAssertNotNil(result.error, "result error should not be nil") if let error = result.error { XCTAssertEqual(error.domain, Error.Domain, "error domain should match expected value") XCTAssertEqual(error.code, Error.Code.DataSerializationFailed.rawValue, "error code should match expected value") } else { XCTFail("error should not be nil") } } func testThatDataResponseSerializerSucceedsWhenDataIsNilWith204ResponseStatusCode() { // Given let serializer = Request.dataResponseSerializer() let URL = NSURL(string: "https://httpbin.org/get")! let response = NSHTTPURLResponse(URL: URL, statusCode: 204, HTTPVersion: "HTTP/1.1", headerFields: nil) // When let result = serializer.serializeResponse(nil, response, nil, nil) // Then XCTAssertTrue(result.isSuccess, "result is success should be true") XCTAssertNotNil(result.value, "result value should not be nil") XCTAssertNil(result.error, "result error should be nil") if let data = result.value { XCTAssertEqual(data.length, 0, "data length should be zero") } } // MARK: - String Response Serializer Tests func testThatStringResponseSerializerFailsWhenDataIsNil() { // Given let serializer = Request.stringResponseSerializer() // When let result = serializer.serializeResponse(nil, nil, nil, nil) // Then XCTAssertTrue(result.isFailure, "result is failure should be true") XCTAssertNil(result.value, "result value should be nil") XCTAssertNotNil(result.error, "result error should not be nil") if let error = result.error { XCTAssertEqual(error.domain, Error.Domain, "error domain should match expected value") XCTAssertEqual(error.code, Error.Code.StringSerializationFailed.rawValue, "error code should match expected value") } else { XCTFail("error should not be nil") } } func testThatStringResponseSerializerSucceedsWhenDataIsEmpty() { // Given let serializer = Request.stringResponseSerializer() // When let result = serializer.serializeResponse(nil, nil, NSData(), nil) // Then XCTAssertTrue(result.isSuccess, "result is success should be true") XCTAssertNotNil(result.value, "result value should not be nil") XCTAssertNil(result.error, "result error should be nil") } func testThatStringResponseSerializerSucceedsWithUTF8DataAndNoProvidedEncoding() { let serializer = Request.stringResponseSerializer() let data = "data".dataUsingEncoding(NSUTF8StringEncoding)! // When let result = serializer.serializeResponse(nil, nil, data, nil) // Then XCTAssertTrue(result.isSuccess, "result is success should be true") XCTAssertNotNil(result.value, "result value should not be nil") XCTAssertNil(result.error, "result error should be nil") } func testThatStringResponseSerializerSucceedsWithUTF8DataAndUTF8ProvidedEncoding() { let serializer = Request.stringResponseSerializer(encoding: NSUTF8StringEncoding) let data = "data".dataUsingEncoding(NSUTF8StringEncoding)! // When let result = serializer.serializeResponse(nil, nil, data, nil) // Then XCTAssertTrue(result.isSuccess, "result is success should be true") XCTAssertNotNil(result.value, "result value should not be nil") XCTAssertNil(result.error, "result error should be nil") } func testThatStringResponseSerializerSucceedsWithUTF8DataUsingResponseTextEncodingName() { let serializer = Request.stringResponseSerializer() let data = "data".dataUsingEncoding(NSUTF8StringEncoding)! let response = NSHTTPURLResponse( URL: NSURL(string: "https://httpbin.org/get")!, statusCode: 200, HTTPVersion: "HTTP/1.1", headerFields: ["Content-Type": "image/jpeg; charset=utf-8"] ) // When let result = serializer.serializeResponse(nil, response, data, nil) // Then XCTAssertTrue(result.isSuccess, "result is success should be true") XCTAssertNotNil(result.value, "result value should not be nil") XCTAssertNil(result.error, "result error should be nil") } func testThatStringResponseSerializerFailsWithUTF32DataAndUTF8ProvidedEncoding() { // Given let serializer = Request.stringResponseSerializer(encoding: NSUTF8StringEncoding) let data = "random data".dataUsingEncoding(NSUTF32StringEncoding)! // When let result = serializer.serializeResponse(nil, nil, data, nil) // Then XCTAssertTrue(result.isFailure, "result is failure should be true") XCTAssertNil(result.value, "result value should be nil") XCTAssertNotNil(result.error, "result error should not be nil") if let error = result.error { XCTAssertEqual(error.domain, Error.Domain, "error domain should match expected value") XCTAssertEqual(error.code, Error.Code.StringSerializationFailed.rawValue, "error code should match expected value") } else { XCTFail("error should not be nil") } } func testThatStringResponseSerializerFailsWithUTF32DataAndUTF8ResponseEncoding() { // Given let serializer = Request.stringResponseSerializer() let data = "random data".dataUsingEncoding(NSUTF32StringEncoding)! let response = NSHTTPURLResponse( URL: NSURL(string: "https://httpbin.org/get")!, statusCode: 200, HTTPVersion: "HTTP/1.1", headerFields: ["Content-Type": "image/jpeg; charset=utf-8"] ) // When let result = serializer.serializeResponse(nil, response, data, nil) // Then XCTAssertTrue(result.isFailure, "result is failure should be true") XCTAssertNil(result.value, "result value should be nil") XCTAssertNotNil(result.error, "result error should not be nil") if let error = result.error { XCTAssertEqual(error.domain, Error.Domain, "error domain should match expected value") XCTAssertEqual(error.code, Error.Code.StringSerializationFailed.rawValue, "error code should match expected value") } else { XCTFail("error should not be nil") } } func testThatStringResponseSerializerFailsWhenErrorIsNotNil() { // Given let serializer = Request.stringResponseSerializer() // When let result = serializer.serializeResponse(nil, nil, nil, error) // Then XCTAssertTrue(result.isFailure, "result is failure should be true") XCTAssertNil(result.value, "result value should be nil") XCTAssertNotNil(result.error, "result error should not be nil") if let error = result.error { XCTAssertEqual(error.domain, Error.Domain, "error domain should match expected value") XCTAssertEqual(error.code, self.error.code, "error code should match expected value") } else { XCTFail("error should not be nil") } } func testThatStringResponseSerializerFailsWhenDataIsNilWithNon204ResponseStatusCode() { // Given let serializer = Request.stringResponseSerializer() let URL = NSURL(string: "https://httpbin.org/get")! let response = NSHTTPURLResponse(URL: URL, statusCode: 200, HTTPVersion: "HTTP/1.1", headerFields: nil) // When let result = serializer.serializeResponse(nil, response, nil, nil) // Then XCTAssertTrue(result.isFailure, "result is failure should be true") XCTAssertNil(result.value, "result value should be nil") XCTAssertNotNil(result.error, "result error should not be nil") if let error = result.error { XCTAssertEqual(error.domain, Error.Domain, "error domain should match expected value") XCTAssertEqual(error.code, Error.Code.StringSerializationFailed.rawValue, "error code should match expected value") } else { XCTFail("error should not be nil") } } func testThatStringResponseSerializerSucceedsWhenDataIsNilWith204ResponseStatusCode() { // Given let serializer = Request.stringResponseSerializer() let URL = NSURL(string: "https://httpbin.org/get")! let response = NSHTTPURLResponse(URL: URL, statusCode: 204, HTTPVersion: "HTTP/1.1", headerFields: nil) // When let result = serializer.serializeResponse(nil, response, nil, nil) // Then XCTAssertTrue(result.isSuccess, "result is success should be true") XCTAssertNotNil(result.value, "result value should not be nil") XCTAssertNil(result.error, "result error should be nil") if let string = result.value { XCTAssertEqual(string, "", "string should be equal to empty string") } } // MARK: - JSON Response Serializer Tests func testThatJSONResponseSerializerFailsWhenDataIsNil() { // Given let serializer = Request.JSONResponseSerializer() // When let result = serializer.serializeResponse(nil, nil, nil, nil) // Then XCTAssertTrue(result.isFailure, "result is failure should be true") XCTAssertNil(result.value, "result value should be nil") XCTAssertNotNil(result.error, "result error should not be nil") if let error = result.error { XCTAssertEqual(error.domain, Error.Domain, "error domain should match expected value") XCTAssertEqual(error.code, Error.Code.JSONSerializationFailed.rawValue, "error code should match expected value") } else { XCTFail("error should not be nil") } } func testThatJSONResponseSerializerFailsWhenDataIsEmpty() { // Given let serializer = Request.JSONResponseSerializer() // When let result = serializer.serializeResponse(nil, nil, NSData(), nil) // Then XCTAssertTrue(result.isFailure, "result is failure should be true") XCTAssertNil(result.value, "result value should be nil") XCTAssertNotNil(result.error, "result error should not be nil") if let error = result.error { XCTAssertEqual(error.domain, Error.Domain, "error domain should match expected value") XCTAssertEqual(error.code, Error.Code.JSONSerializationFailed.rawValue, "error code should match expected value") } else { XCTFail("error should not be nil") } } func testThatJSONResponseSerializerSucceedsWhenDataIsValidJSON() { // Given let serializer = Request.JSONResponseSerializer() let data = "{\"json\": true}".dataUsingEncoding(NSUTF8StringEncoding)! // When let result = serializer.serializeResponse(nil, nil, data, nil) // Then XCTAssertTrue(result.isSuccess, "result is success should be true") XCTAssertNotNil(result.value, "result value should not be nil") XCTAssertNil(result.error, "result error should be nil") } func testThatJSONResponseSerializerFailsWhenDataIsInvalidJSON() { // Given let serializer = Request.JSONResponseSerializer() let data = "definitely not valid json".dataUsingEncoding(NSUTF8StringEncoding)! // When let result = serializer.serializeResponse(nil, nil, data, nil) // Then XCTAssertTrue(result.isFailure, "result is failure should be true") XCTAssertNil(result.value, "result value should be nil") XCTAssertNotNil(result.error, "result error should not be nil") if let error = result.error { XCTAssertEqual(error.domain, NSCocoaErrorDomain, "error domain should match expected value") XCTAssertEqual(error.code, 3840, "error code should match expected value") } else { XCTFail("error should not be nil") } } func testThatJSONResponseSerializerFailsWhenErrorIsNotNil() { // Given let serializer = Request.JSONResponseSerializer() // When let result = serializer.serializeResponse(nil, nil, nil, error) // Then XCTAssertTrue(result.isFailure, "result is failure should be true") XCTAssertNil(result.value, "result value should be nil") XCTAssertNotNil(result.error, "result error should not be nil") if let error = result.error { XCTAssertEqual(error.domain, Error.Domain, "error domain should match expected value") XCTAssertEqual(error.code, self.error.code, "error code should match expected value") } else { XCTFail("error should not be nil") } } func testThatJSONResponseSerializerFailsWhenDataIsNilWithNon204ResponseStatusCode() { // Given let serializer = Request.JSONResponseSerializer() let URL = NSURL(string: "https://httpbin.org/get")! let response = NSHTTPURLResponse(URL: URL, statusCode: 200, HTTPVersion: "HTTP/1.1", headerFields: nil) // When let result = serializer.serializeResponse(nil, response, nil, nil) // Then XCTAssertTrue(result.isFailure, "result is failure should be true") XCTAssertNil(result.value, "result value should be nil") XCTAssertNotNil(result.error, "result error should not be nil") if let error = result.error { XCTAssertEqual(error.domain, Error.Domain, "error domain should match expected value") XCTAssertEqual(error.code, Error.Code.JSONSerializationFailed.rawValue, "error code should match expected value") } else { XCTFail("error should not be nil") } } func testThatJSONResponseSerializerSucceedsWhenDataIsNilWith204ResponseStatusCode() { // Given let serializer = Request.JSONResponseSerializer() let URL = NSURL(string: "https://httpbin.org/get")! let response = NSHTTPURLResponse(URL: URL, statusCode: 204, HTTPVersion: "HTTP/1.1", headerFields: nil) // When let result = serializer.serializeResponse(nil, response, nil, nil) // Then XCTAssertTrue(result.isSuccess, "result is success should be true") XCTAssertNotNil(result.value, "result value should not be nil") XCTAssertNil(result.error, "result error should be nil") if let json = result.value as? NSNull { XCTAssertEqual(json, NSNull(), "json should be equal to NSNull") } } // MARK: - Property List Response Serializer Tests func testThatPropertyListResponseSerializerFailsWhenDataIsNil() { // Given let serializer = Request.propertyListResponseSerializer() // When let result = serializer.serializeResponse(nil, nil, nil, nil) // Then XCTAssertTrue(result.isFailure, "result is failure should be true") XCTAssertNil(result.value, "result value should be nil") XCTAssertNotNil(result.error, "result error should not be nil") if let error = result.error { XCTAssertEqual(error.domain, Error.Domain, "error domain should match expected value") XCTAssertEqual(error.code, Error.Code.PropertyListSerializationFailed.rawValue, "error code should match expected value") } else { XCTFail("error should not be nil") } } func testThatPropertyListResponseSerializerFailsWhenDataIsEmpty() { // Given let serializer = Request.propertyListResponseSerializer() // When let result = serializer.serializeResponse(nil, nil, NSData(), nil) // Then XCTAssertTrue(result.isFailure, "result is failure should be true") XCTAssertNil(result.value, "result value should be nil") XCTAssertNotNil(result.error, "result error should not be nil") if let error = result.error { XCTAssertEqual(error.domain, Error.Domain, "error domain should match expected value") XCTAssertEqual(error.code, Error.Code.PropertyListSerializationFailed.rawValue, "error code should match expected value") } else { XCTFail("error should not be nil") } } func testThatPropertyListResponseSerializerSucceedsWhenDataIsValidPropertyListData() { // Given let serializer = Request.propertyListResponseSerializer() let data = NSKeyedArchiver.archivedDataWithRootObject(["foo": "bar"]) // When let result = serializer.serializeResponse(nil, nil, data, nil) // Then XCTAssertTrue(result.isSuccess, "result is success should be true") XCTAssertNotNil(result.value, "result value should not be nil") XCTAssertNil(result.error, "result error should be nil") } func testThatPropertyListResponseSerializerFailsWhenDataIsInvalidPropertyListData() { // Given let serializer = Request.propertyListResponseSerializer() let data = "definitely not valid plist data".dataUsingEncoding(NSUTF8StringEncoding)! // When let result = serializer.serializeResponse(nil, nil, data, nil) // Then XCTAssertTrue(result.isFailure, "result is failure should be true") XCTAssertNil(result.value, "result value should be nil") XCTAssertNotNil(result.error, "result error should not be nil") if let error = result.error { XCTAssertEqual(error.domain, NSCocoaErrorDomain, "error domain should match expected value") XCTAssertEqual(error.code, 3840, "error code should match expected value") } else { XCTFail("error should not be nil") } } func testThatPropertyListResponseSerializerFailsWhenErrorIsNotNil() { // Given let serializer = Request.propertyListResponseSerializer() // When let result = serializer.serializeResponse(nil, nil, nil, error) // Then XCTAssertTrue(result.isFailure, "result is failure should be true") XCTAssertNil(result.value, "result value should be nil") XCTAssertNotNil(result.error, "result error should not be nil") if let error = result.error { XCTAssertEqual(error.domain, Error.Domain, "error domain should match expected value") XCTAssertEqual(error.code, self.error.code, "error code should match expected value") } else { XCTFail("error should not be nil") } } func testThatPropertyListResponseSerializerFailsWhenDataIsNilWithNon204ResponseStatusCode() { // Given let serializer = Request.propertyListResponseSerializer() let URL = NSURL(string: "https://httpbin.org/get")! let response = NSHTTPURLResponse(URL: URL, statusCode: 200, HTTPVersion: "HTTP/1.1", headerFields: nil) // When let result = serializer.serializeResponse(nil, response, nil, nil) // Then XCTAssertTrue(result.isFailure, "result is failure should be true") XCTAssertNil(result.value, "result value should be nil") XCTAssertNotNil(result.error, "result error should not be nil") if let error = result.error { XCTAssertEqual(error.domain, Error.Domain, "error domain should match expected value") XCTAssertEqual(error.code, Error.Code.PropertyListSerializationFailed.rawValue, "error code should match expected value") } else { XCTFail("error should not be nil") } } func testThatPropertyListResponseSerializerSucceedsWhenDataIsNilWith204ResponseStatusCode() { // Given let serializer = Request.propertyListResponseSerializer() let URL = NSURL(string: "https://httpbin.org/get")! let response = NSHTTPURLResponse(URL: URL, statusCode: 204, HTTPVersion: "HTTP/1.1", headerFields: nil) // When let result = serializer.serializeResponse(nil, response, nil, nil) // Then XCTAssertTrue(result.isSuccess, "result is success should be true") XCTAssertNotNil(result.value, "result value should not be nil") XCTAssertNil(result.error, "result error should be nil") if let plist = result.value as? NSNull { XCTAssertEqual(plist, NSNull(), "plist should be equal to NSNull") } } }
necrowman/CRLAlamofireFuture
Examples/SimpleIOSCarthage/Carthage/Checkouts/CRLAlamofireFuture/Examples/SimpleTvOSCarthage/Carthage/Checkouts/CRLAlamofireFuture/Examples/SimpleIOSCarthage/Carthage/Checkouts/CRLAlamofireFuture/Examples/SimpleIOSCarthage/Carthage/Checkouts/Alamofire/Tests/ResponseSerializationTests.swift
Swift
mit
24,746
//********************************************************* // // Copyright (c) Microsoft. All rights reserved. // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT. // //********************************************************* using AppUIBasics.Common; using AppUIBasics.Data; using System.Collections.Generic; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Navigation; // The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238 namespace AppUIBasics.ControlPages { /// <summary> /// An empty page that can be used on its own or navigated to within a Frame. /// </summary> public sealed partial class SemanticZoomPage : Page { private IEnumerable<ControlInfoDataGroup> _groups; public SemanticZoomPage() { this.InitializeComponent(); } public IEnumerable<ControlInfoDataGroup> Groups { get { return this._groups; } } protected async override void OnNavigatedTo(NavigationEventArgs e) { base.OnNavigatedTo(e); _groups = await ControlInfoDataSource.GetGroupsAsync(); } } }
washcycle/Windows-universal-samples
xaml_xamluibasics/CS/AppUIBasics/ControlPages/SemanticZoomPage.xaml.cs
C#
mit
1,329
/*! Sizzle v1.10.11 | (c) 2013 jQuery Foundation, Inc. | jquery.org/license */!function(a){function b(a,b,c,d){var e,f,g,h,i,j,l,o,p,q;if((b?b.ownerDocument||b:P)!==H&&G(b),b=b||H,c=c||[],!a||"string"!=typeof a)return c;if(1!==(h=b.nodeType)&&9!==h)return[];if(J&&!d){if(e=tb.exec(a))if(g=e[1]){if(9===h){if(f=b.getElementById(g),!f||!f.parentNode)return c;if(f.id===g)return c.push(f),c}else if(b.ownerDocument&&(f=b.ownerDocument.getElementById(g))&&N(b,f)&&f.id===g)return c.push(f),c}else{if(e[2])return ab.apply(c,b.getElementsByTagName(a)),c;if((g=e[3])&&x.getElementsByClassName&&b.getElementsByClassName)return ab.apply(c,b.getElementsByClassName(g)),c}if(x.qsa&&(!K||!K.test(a))){if(o=l=O,p=b,q=9===h&&a,1===h&&"object"!==b.nodeName.toLowerCase()){for(j=m(a),(l=b.getAttribute("id"))?o=l.replace(vb,"\\$&"):b.setAttribute("id",o),o="[id='"+o+"'] ",i=j.length;i--;)j[i]=o+n(j[i]);p=ub.test(a)&&k(b.parentNode)||b,q=j.join(",")}if(q)try{return ab.apply(c,p.querySelectorAll(q)),c}catch(r){}finally{l||b.removeAttribute("id")}}}return v(a.replace(jb,"$1"),b,c,d)}function c(){function a(c,d){return b.push(c+" ")>z.cacheLength&&delete a[b.shift()],a[c+" "]=d}var b=[];return a}function d(a){return a[O]=!0,a}function e(a){var b=H.createElement("div");try{return!!a(b)}catch(c){return!1}finally{b.parentNode&&b.parentNode.removeChild(b),b=null}}function f(a,b){for(var c=a.split("|"),d=a.length;d--;)z.attrHandle[c[d]]=b}function g(a,b){var c=b&&a,d=c&&1===a.nodeType&&1===b.nodeType&&(~b.sourceIndex||X)-(~a.sourceIndex||X);if(d)return d;if(c)for(;c=c.nextSibling;)if(c===b)return-1;return a?1:-1}function h(a){return function(b){var c=b.nodeName.toLowerCase();return"input"===c&&b.type===a}}function i(a){return function(b){var c=b.nodeName.toLowerCase();return("input"===c||"button"===c)&&b.type===a}}function j(a){return d(function(b){return b=+b,d(function(c,d){for(var e,f=a([],c.length,b),g=f.length;g--;)c[e=f[g]]&&(c[e]=!(d[e]=c[e]))})})}function k(a){return a&&typeof a.getElementsByTagName!==W&&a}function l(){}function m(a,c){var d,e,f,g,h,i,j,k=T[a+" "];if(k)return c?0:k.slice(0);for(h=a,i=[],j=z.preFilter;h;){(!d||(e=kb.exec(h)))&&(e&&(h=h.slice(e[0].length)||h),i.push(f=[])),d=!1,(e=lb.exec(h))&&(d=e.shift(),f.push({value:d,type:e[0].replace(jb," ")}),h=h.slice(d.length));for(g in z.filter)!(e=pb[g].exec(h))||j[g]&&!(e=j[g](e))||(d=e.shift(),f.push({value:d,type:g,matches:e}),h=h.slice(d.length));if(!d)break}return c?h.length:h?b.error(a):T(a,i).slice(0)}function n(a){for(var b=0,c=a.length,d="";c>b;b++)d+=a[b].value;return d}function o(a,b,c){var d=b.dir,e=c&&"parentNode"===d,f=R++;return b.first?function(b,c,f){for(;b=b[d];)if(1===b.nodeType||e)return a(b,c,f)}:function(b,c,g){var h,i,j,k=Q+" "+f;if(g){for(;b=b[d];)if((1===b.nodeType||e)&&a(b,c,g))return!0}else for(;b=b[d];)if(1===b.nodeType||e)if(j=b[O]||(b[O]={}),(i=j[d])&&i[0]===k){if((h=i[1])===!0||h===y)return h===!0}else if(i=j[d]=[k],i[1]=a(b,c,g)||y,i[1]===!0)return!0}}function p(a){return a.length>1?function(b,c,d){for(var e=a.length;e--;)if(!a[e](b,c,d))return!1;return!0}:a[0]}function q(a,b,c,d,e){for(var f,g=[],h=0,i=a.length,j=null!=b;i>h;h++)(f=a[h])&&(!c||c(f,d,e))&&(g.push(f),j&&b.push(h));return g}function r(a,b,c,e,f,g){return e&&!e[O]&&(e=r(e)),f&&!f[O]&&(f=r(f,g)),d(function(d,g,h,i){var j,k,l,m=[],n=[],o=g.length,p=d||u(b||"*",h.nodeType?[h]:h,[]),r=!a||!d&&b?p:q(p,m,a,h,i),s=c?f||(d?a:o||e)?[]:g:r;if(c&&c(r,s,h,i),e)for(j=q(s,n),e(j,[],h,i),k=j.length;k--;)(l=j[k])&&(s[n[k]]=!(r[n[k]]=l));if(d){if(f||a){if(f){for(j=[],k=s.length;k--;)(l=s[k])&&j.push(r[k]=l);f(null,s=[],j,i)}for(k=s.length;k--;)(l=s[k])&&(j=f?cb.call(d,l):m[k])>-1&&(d[j]=!(g[j]=l))}}else s=q(s===g?s.splice(o,s.length):s),f?f(null,g,s,i):ab.apply(g,s)})}function s(a){for(var b,c,d,e=a.length,f=z.relative[a[0].type],g=f||z.relative[" "],h=f?1:0,i=o(function(a){return a===b},g,!0),j=o(function(a){return cb.call(b,a)>-1},g,!0),k=[function(a,c,d){return!f&&(d||c!==D)||((b=c).nodeType?i(a,c,d):j(a,c,d))}];e>h;h++)if(c=z.relative[a[h].type])k=[o(p(k),c)];else{if(c=z.filter[a[h].type].apply(null,a[h].matches),c[O]){for(d=++h;e>d&&!z.relative[a[d].type];d++);return r(h>1&&p(k),h>1&&n(a.slice(0,h-1).concat({value:" "===a[h-2].type?"*":""})).replace(jb,"$1"),c,d>h&&s(a.slice(h,d)),e>d&&s(a=a.slice(d)),e>d&&n(a))}k.push(c)}return p(k)}function t(a,c){var e=0,f=c.length>0,g=a.length>0,h=function(d,h,i,j,k){var l,m,n,o=0,p="0",r=d&&[],s=[],t=D,u=d||g&&z.find.TAG("*",k),v=Q+=null==t?1:Math.random()||.1,w=u.length;for(k&&(D=h!==H&&h,y=e);p!==w&&null!=(l=u[p]);p++){if(g&&l){for(m=0;n=a[m++];)if(n(l,h,i)){j.push(l);break}k&&(Q=v,y=++e)}f&&((l=!n&&l)&&o--,d&&r.push(l))}if(o+=p,f&&p!==o){for(m=0;n=c[m++];)n(r,s,h,i);if(d){if(o>0)for(;p--;)r[p]||s[p]||(s[p]=$.call(j));s=q(s)}ab.apply(j,s),k&&!d&&s.length>0&&o+c.length>1&&b.uniqueSort(j)}return k&&(Q=v,D=t),r};return f?d(h):h}function u(a,c,d){for(var e=0,f=c.length;f>e;e++)b(a,c[e],d);return d}function v(a,b,c,d){var e,f,g,h,i,j=m(a);if(!d&&1===j.length){if(f=j[0]=j[0].slice(0),f.length>2&&"ID"===(g=f[0]).type&&x.getById&&9===b.nodeType&&J&&z.relative[f[1].type]){if(b=(z.find.ID(g.matches[0].replace(wb,xb),b)||[])[0],!b)return c;a=a.slice(f.shift().value.length)}for(e=pb.needsContext.test(a)?0:f.length;e--&&(g=f[e],!z.relative[h=g.type]);)if((i=z.find[h])&&(d=i(g.matches[0].replace(wb,xb),ub.test(f[0].type)&&k(b.parentNode)||b))){if(f.splice(e,1),a=d.length&&n(f),!a)return ab.apply(c,d),c;break}}return C(a,j)(d,b,!J,c,ub.test(a)&&k(b.parentNode)||b),c}var w,x,y,z,A,B,C,D,E,F,G,H,I,J,K,L,M,N,O="sizzle"+-new Date,P=a.document,Q=0,R=0,S=c(),T=c(),U=c(),V=function(a,b){return a===b&&(F=!0),0},W=typeof void 0,X=1<<31,Y={}.hasOwnProperty,Z=[],$=Z.pop,_=Z.push,ab=Z.push,bb=Z.slice,cb=Z.indexOf||function(a){for(var b=0,c=this.length;c>b;b++)if(this[b]===a)return b;return-1},db="checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped",eb="[\\x20\\t\\r\\n\\f]",fb="(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+",gb=fb.replace("w","w#"),hb="\\["+eb+"*("+fb+")"+eb+"*(?:([*^$|!~]?=)"+eb+"*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|("+gb+")|)|)"+eb+"*\\]",ib=":("+fb+")(?:\\(((['\"])((?:\\\\.|[^\\\\])*?)\\3|((?:\\\\.|[^\\\\()[\\]]|"+hb.replace(3,8)+")*)|.*)\\)|)",jb=new RegExp("^"+eb+"+|((?:^|[^\\\\])(?:\\\\.)*)"+eb+"+$","g"),kb=new RegExp("^"+eb+"*,"+eb+"*"),lb=new RegExp("^"+eb+"*([>+~]|"+eb+")"+eb+"*"),mb=new RegExp("="+eb+"*([^\\]'\"]*)"+eb+"*\\]","g"),nb=new RegExp(ib),ob=new RegExp("^"+gb+"$"),pb={ID:new RegExp("^#("+fb+")"),CLASS:new RegExp("^\\.("+fb+")"),TAG:new RegExp("^("+fb.replace("w","w*")+")"),ATTR:new RegExp("^"+hb),PSEUDO:new RegExp("^"+ib),CHILD:new RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+eb+"*(even|odd|(([+-]|)(\\d*)n|)"+eb+"*(?:([+-]|)"+eb+"*(\\d+)|))"+eb+"*\\)|)","i"),bool:new RegExp("^(?:"+db+")$","i"),needsContext:new RegExp("^"+eb+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+eb+"*((?:-\\d)?\\d*)"+eb+"*\\)|)(?=[^-]|$)","i")},qb=/^(?:input|select|textarea|button)$/i,rb=/^h\d$/i,sb=/^[^{]+\{\s*\[native \w/,tb=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,ub=/[+~]/,vb=/'|\\/g,wb=new RegExp("\\\\([\\da-f]{1,6}"+eb+"?|("+eb+")|.)","ig"),xb=function(a,b,c){var d="0x"+b-65536;return d!==d||c?b:0>d?String.fromCharCode(d+65536):String.fromCharCode(55296|d>>10,56320|1023&d)};try{ab.apply(Z=bb.call(P.childNodes),P.childNodes),Z[P.childNodes.length].nodeType}catch(yb){ab={apply:Z.length?function(a,b){_.apply(a,bb.call(b))}:function(a,b){for(var c=a.length,d=0;a[c++]=b[d++];);a.length=c-1}}}x=b.support={},B=b.isXML=function(a){var b=a&&(a.ownerDocument||a).documentElement;return b?"HTML"!==b.nodeName:!1},G=b.setDocument=function(a){var b=a?a.ownerDocument||a:P,c=b.defaultView;return b!==H&&9===b.nodeType&&b.documentElement?(H=b,I=b.documentElement,J=!B(b),c&&c.attachEvent&&c!==c.top&&c.attachEvent("onbeforeunload",function(){G()}),x.attributes=e(function(a){return a.className="i",!a.getAttribute("className")}),x.getElementsByTagName=e(function(a){return a.appendChild(b.createComment("")),!a.getElementsByTagName("*").length}),x.getElementsByClassName=e(function(a){return a.innerHTML="<div class='a'></div><div class='a i'></div>",a.firstChild.className="i",2===a.getElementsByClassName("i").length}),x.getById=e(function(a){return I.appendChild(a).id=O,!b.getElementsByName||!b.getElementsByName(O).length}),x.getById?(z.find.ID=function(a,b){if(typeof b.getElementById!==W&&J){var c=b.getElementById(a);return c&&c.parentNode?[c]:[]}},z.filter.ID=function(a){var b=a.replace(wb,xb);return function(a){return a.getAttribute("id")===b}}):(delete z.find.ID,z.filter.ID=function(a){var b=a.replace(wb,xb);return function(a){var c=typeof a.getAttributeNode!==W&&a.getAttributeNode("id");return c&&c.value===b}}),z.find.TAG=x.getElementsByTagName?function(a,b){return typeof b.getElementsByTagName!==W?b.getElementsByTagName(a):void 0}:function(a,b){var c,d=[],e=0,f=b.getElementsByTagName(a);if("*"===a){for(;c=f[e++];)1===c.nodeType&&d.push(c);return d}return f},z.find.CLASS=x.getElementsByClassName&&function(a,b){return typeof b.getElementsByClassName!==W&&J?b.getElementsByClassName(a):void 0},L=[],K=[],(x.qsa=sb.test(b.querySelectorAll))&&(e(function(a){a.innerHTML="<select><option selected=''></option></select>",a.querySelectorAll("[selected]").length||K.push("\\["+eb+"*(?:value|"+db+")"),a.querySelectorAll(":checked").length||K.push(":checked")}),e(function(a){var c=b.createElement("input");c.setAttribute("type","hidden"),a.appendChild(c).setAttribute("t",""),a.querySelectorAll("[t^='']").length&&K.push("[*^$]="+eb+"*(?:''|\"\")"),a.querySelectorAll(":enabled").length||K.push(":enabled",":disabled"),a.querySelectorAll("*,:x"),K.push(",.*:")})),(x.matchesSelector=sb.test(M=I.webkitMatchesSelector||I.mozMatchesSelector||I.oMatchesSelector||I.msMatchesSelector))&&e(function(a){x.disconnectedMatch=M.call(a,"div"),M.call(a,"[s!='']:x"),L.push("!=",ib)}),K=K.length&&new RegExp(K.join("|")),L=L.length&&new RegExp(L.join("|")),N=sb.test(I.contains)||I.compareDocumentPosition?function(a,b){var c=9===a.nodeType?a.documentElement:a,d=b&&b.parentNode;return a===d||!(!d||1!==d.nodeType||!(c.contains?c.contains(d):a.compareDocumentPosition&&16&a.compareDocumentPosition(d)))}:function(a,b){if(b)for(;b=b.parentNode;)if(b===a)return!0;return!1},V=I.compareDocumentPosition?function(a,c){if(a===c)return F=!0,0;var d=!a.compareDocumentPosition-!c.compareDocumentPosition;return d?d:(d=(a.ownerDocument||a)===(c.ownerDocument||c)?a.compareDocumentPosition(c):1,1&d||!x.sortDetached&&c.compareDocumentPosition(a)===d?a===b||a.ownerDocument===P&&N(P,a)?-1:c===b||c.ownerDocument===P&&N(P,c)?1:E?cb.call(E,a)-cb.call(E,c):0:4&d?-1:1)}:function(a,c){if(a===c)return F=!0,0;var d,e=0,f=a.parentNode,h=c.parentNode,i=[a],j=[c];if(!f||!h)return a===b?-1:c===b?1:f?-1:h?1:E?cb.call(E,a)-cb.call(E,c):0;if(f===h)return g(a,c);for(d=a;d=d.parentNode;)i.unshift(d);for(d=c;d=d.parentNode;)j.unshift(d);for(;i[e]===j[e];)e++;return e?g(i[e],j[e]):i[e]===P?-1:j[e]===P?1:0},b):H},b.matches=function(a,c){return b(a,null,null,c)},b.matchesSelector=function(a,c){if((a.ownerDocument||a)!==H&&G(a),c=c.replace(mb,"='$1']"),!(!x.matchesSelector||!J||L&&L.test(c)||K&&K.test(c)))try{var d=M.call(a,c);if(d||x.disconnectedMatch||a.document&&11!==a.document.nodeType)return d}catch(e){}return b(c,H,null,[a]).length>0},b.contains=function(a,b){return(a.ownerDocument||a)!==H&&G(a),N(a,b)},b.attr=function(a,b){(a.ownerDocument||a)!==H&&G(a);var c=z.attrHandle[b.toLowerCase()],d=c&&Y.call(z.attrHandle,b.toLowerCase())?c(a,b,!J):void 0;return void 0!==d?d:x.attributes||!J?a.getAttribute(b):(d=a.getAttributeNode(b))&&d.specified?d.value:null},b.error=function(a){throw new Error("Syntax error, unrecognized expression: "+a)},b.uniqueSort=function(a){var b,c=[],d=0,e=0;if(F=!x.detectDuplicates,E=!x.sortStable&&a.slice(0),a.sort(V),F){for(;b=a[e++];)b===a[e]&&(d=c.push(e));for(;d--;)a.splice(c[d],1)}return E=null,a},A=b.getText=function(a){var b,c="",d=0,e=a.nodeType;if(e){if(1===e||9===e||11===e){if("string"==typeof a.textContent)return a.textContent;for(a=a.firstChild;a;a=a.nextSibling)c+=A(a)}else if(3===e||4===e)return a.nodeValue}else for(;b=a[d++];)c+=A(b);return c},z=b.selectors={cacheLength:50,createPseudo:d,match:pb,attrHandle:{},find:{},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(a){return a[1]=a[1].replace(wb,xb),a[3]=(a[4]||a[5]||"").replace(wb,xb),"~="===a[2]&&(a[3]=" "+a[3]+" "),a.slice(0,4)},CHILD:function(a){return a[1]=a[1].toLowerCase(),"nth"===a[1].slice(0,3)?(a[3]||b.error(a[0]),a[4]=+(a[4]?a[5]+(a[6]||1):2*("even"===a[3]||"odd"===a[3])),a[5]=+(a[7]+a[8]||"odd"===a[3])):a[3]&&b.error(a[0]),a},PSEUDO:function(a){var b,c=!a[5]&&a[2];return pb.CHILD.test(a[0])?null:(a[3]&&void 0!==a[4]?a[2]=a[4]:c&&nb.test(c)&&(b=m(c,!0))&&(b=c.indexOf(")",c.length-b)-c.length)&&(a[0]=a[0].slice(0,b),a[2]=c.slice(0,b)),a.slice(0,3))}},filter:{TAG:function(a){var b=a.replace(wb,xb).toLowerCase();return"*"===a?function(){return!0}:function(a){return a.nodeName&&a.nodeName.toLowerCase()===b}},CLASS:function(a){var b=S[a+" "];return b||(b=new RegExp("(^|"+eb+")"+a+"("+eb+"|$)"))&&S(a,function(a){return b.test("string"==typeof a.className&&a.className||typeof a.getAttribute!==W&&a.getAttribute("class")||"")})},ATTR:function(a,c,d){return function(e){var f=b.attr(e,a);return null==f?"!="===c:c?(f+="","="===c?f===d:"!="===c?f!==d:"^="===c?d&&0===f.indexOf(d):"*="===c?d&&f.indexOf(d)>-1:"$="===c?d&&f.slice(-d.length)===d:"~="===c?(" "+f+" ").indexOf(d)>-1:"|="===c?f===d||f.slice(0,d.length+1)===d+"-":!1):!0}},CHILD:function(a,b,c,d,e){var f="nth"!==a.slice(0,3),g="last"!==a.slice(-4),h="of-type"===b;return 1===d&&0===e?function(a){return!!a.parentNode}:function(b,c,i){var j,k,l,m,n,o,p=f!==g?"nextSibling":"previousSibling",q=b.parentNode,r=h&&b.nodeName.toLowerCase(),s=!i&&!h;if(q){if(f){for(;p;){for(l=b;l=l[p];)if(h?l.nodeName.toLowerCase()===r:1===l.nodeType)return!1;o=p="only"===a&&!o&&"nextSibling"}return!0}if(o=[g?q.firstChild:q.lastChild],g&&s){for(k=q[O]||(q[O]={}),j=k[a]||[],n=j[0]===Q&&j[1],m=j[0]===Q&&j[2],l=n&&q.childNodes[n];l=++n&&l&&l[p]||(m=n=0)||o.pop();)if(1===l.nodeType&&++m&&l===b){k[a]=[Q,n,m];break}}else if(s&&(j=(b[O]||(b[O]={}))[a])&&j[0]===Q)m=j[1];else for(;(l=++n&&l&&l[p]||(m=n=0)||o.pop())&&((h?l.nodeName.toLowerCase()!==r:1!==l.nodeType)||!++m||(s&&((l[O]||(l[O]={}))[a]=[Q,m]),l!==b)););return m-=e,m===d||0===m%d&&m/d>=0}}},PSEUDO:function(a,c){var e,f=z.pseudos[a]||z.setFilters[a.toLowerCase()]||b.error("unsupported pseudo: "+a);return f[O]?f(c):f.length>1?(e=[a,a,"",c],z.setFilters.hasOwnProperty(a.toLowerCase())?d(function(a,b){for(var d,e=f(a,c),g=e.length;g--;)d=cb.call(a,e[g]),a[d]=!(b[d]=e[g])}):function(a){return f(a,0,e)}):f}},pseudos:{not:d(function(a){var b=[],c=[],e=C(a.replace(jb,"$1"));return e[O]?d(function(a,b,c,d){for(var f,g=e(a,null,d,[]),h=a.length;h--;)(f=g[h])&&(a[h]=!(b[h]=f))}):function(a,d,f){return b[0]=a,e(b,null,f,c),!c.pop()}}),has:d(function(a){return function(c){return b(a,c).length>0}}),contains:d(function(a){return function(b){return(b.textContent||b.innerText||A(b)).indexOf(a)>-1}}),lang:d(function(a){return ob.test(a||"")||b.error("unsupported lang: "+a),a=a.replace(wb,xb).toLowerCase(),function(b){var c;do if(c=J?b.lang:b.getAttribute("xml:lang")||b.getAttribute("lang"))return c=c.toLowerCase(),c===a||0===c.indexOf(a+"-");while((b=b.parentNode)&&1===b.nodeType);return!1}}),target:function(b){var c=a.location&&a.location.hash;return c&&c.slice(1)===b.id},root:function(a){return a===I},focus:function(a){return a===H.activeElement&&(!H.hasFocus||H.hasFocus())&&!!(a.type||a.href||~a.tabIndex)},enabled:function(a){return a.disabled===!1},disabled:function(a){return a.disabled===!0},checked:function(a){var b=a.nodeName.toLowerCase();return"input"===b&&!!a.checked||"option"===b&&!!a.selected},selected:function(a){return a.parentNode&&a.parentNode.selectedIndex,a.selected===!0},empty:function(a){for(a=a.firstChild;a;a=a.nextSibling)if(a.nodeType<6)return!1;return!0},parent:function(a){return!z.pseudos.empty(a)},header:function(a){return rb.test(a.nodeName)},input:function(a){return qb.test(a.nodeName)},button:function(a){var b=a.nodeName.toLowerCase();return"input"===b&&"button"===a.type||"button"===b},text:function(a){var b;return"input"===a.nodeName.toLowerCase()&&"text"===a.type&&(null==(b=a.getAttribute("type"))||b.toLowerCase()===a.type)},first:j(function(){return[0]}),last:j(function(a,b){return[b-1]}),eq:j(function(a,b,c){return[0>c?c+b:c]}),even:j(function(a,b){for(var c=0;b>c;c+=2)a.push(c);return a}),odd:j(function(a,b){for(var c=1;b>c;c+=2)a.push(c);return a}),lt:j(function(a,b,c){for(var d=0>c?c+b:c;--d>=0;)a.push(d);return a}),gt:j(function(a,b,c){for(var d=0>c?c+b:c;++d<b;)a.push(d);return a})}},z.pseudos.nth=z.pseudos.eq;for(w in{radio:!0,checkbox:!0,file:!0,password:!0,image:!0})z.pseudos[w]=h(w);for(w in{submit:!0,reset:!0})z.pseudos[w]=i(w);l.prototype=z.filters=z.pseudos,z.setFilters=new l,C=b.compile=function(a,b){var c,d=[],e=[],f=U[a+" "];if(!f){for(b||(b=m(a)),c=b.length;c--;)f=s(b[c]),f[O]?d.push(f):e.push(f);f=U(a,t(e,d))}return f},x.sortStable=O.split("").sort(V).join("")===O,x.detectDuplicates=!!F,G(),x.sortDetached=e(function(a){return 1&a.compareDocumentPosition(H.createElement("div"))}),e(function(a){return a.innerHTML="<a href='#'></a>","#"===a.firstChild.getAttribute("href")})||f("type|href|height|width",function(a,b,c){return c?void 0:a.getAttribute(b,"type"===b.toLowerCase()?1:2)}),x.attributes&&e(function(a){return a.innerHTML="<input/>",a.firstChild.setAttribute("value",""),""===a.firstChild.getAttribute("value")})||f("value",function(a,b,c){return c||"input"!==a.nodeName.toLowerCase()?void 0:a.defaultValue}),e(function(a){return null==a.getAttribute("disabled")})||f(db,function(a,b,c){var d;return c?void 0:a[b]===!0?b.toLowerCase():(d=a.getAttributeNode(b))&&d.specified?d.value:null}),"function"==typeof define&&define.amd?define(function(){return b}):"undefined"!=typeof module&&module.exports?module.exports=b:a.Sizzle=b}(window); //# sourceMappingURL=dist/sizzle.min.map
mihneasim/cdnjs
ajax/libs/sizzle/1.10.11/sizzle.min.js
JavaScript
mit
18,241
/*! SWFMini - a SWFObject 2.2 cut down version for webshims * * based on SWFObject v2.2 <http://code.google.com/p/swfobject/> is released under the MIT License <http://www.opensource.org/licenses/mit-license.php> */ var swfmini = function() { var wasRemoved = function(){webshims.error('This method was removed from swfmini');}; var UNDEF = "undefined", OBJECT = "object", webshims = window.webshims, SHOCKWAVE_FLASH = "Shockwave Flash", SHOCKWAVE_FLASH_AX = "ShockwaveFlash.ShockwaveFlash", FLASH_MIME_TYPE = "application/x-shockwave-flash", win = window, doc = document, nav = navigator, plugin = false, domLoadFnArr = [main], isDomLoaded = false, autoHideShow = true, /* Centralized function for browser feature detection - User agent string detection is only used when no good alternative is possible - Is executed directly for optimal performance */ ua = function() { var w3cdom = typeof doc.getElementById != UNDEF && typeof doc.getElementsByTagName != UNDEF && typeof doc.createElement != UNDEF, u = nav.userAgent.toLowerCase(), p = nav.platform.toLowerCase(), windows = p ? /win/.test(p) : /win/.test(u), mac = p ? /mac/.test(p) : /mac/.test(u), webkit = /webkit/.test(u) ? parseFloat(u.replace(/^.*webkit\/(\d+(\.\d+)?).*$/, "$1")) : false, // returns either the webkit version or false if not webkit ie = !+"\v1", // feature detection based on Andrea Giammarchi's solution: http://webreflection.blogspot.com/2009/01/32-bytes-to-know-if-your-browser-is-ie.html playerVersion = [0,0,0], d = null; if (typeof nav.plugins != UNDEF && typeof nav.plugins[SHOCKWAVE_FLASH] == OBJECT) { d = nav.plugins[SHOCKWAVE_FLASH].description; if (d && !(typeof nav.mimeTypes != UNDEF && nav.mimeTypes[FLASH_MIME_TYPE] && !nav.mimeTypes[FLASH_MIME_TYPE].enabledPlugin)) { // navigator.mimeTypes["application/x-shockwave-flash"].enabledPlugin indicates whether plug-ins are enabled or disabled in Safari 3+ plugin = true; ie = false; // cascaded feature detection for Internet Explorer d = d.replace(/^.*\s+(\S+\s+\S+$)/, "$1"); playerVersion[0] = parseInt(d.replace(/^(.*)\..*$/, "$1"), 10); playerVersion[1] = parseInt(d.replace(/^.*\.(.*)\s.*$/, "$1"), 10); playerVersion[2] = /[a-zA-Z]/.test(d) ? parseInt(d.replace(/^.*[a-zA-Z]+(.*)$/, "$1"), 10) : 0; } } else if (typeof win.ActiveXObject != UNDEF) { try { var a = new ActiveXObject(SHOCKWAVE_FLASH_AX); if (a) { // a will return null when ActiveX is disabled d = a.GetVariable("$version"); if (d) { ie = true; // cascaded feature detection for Internet Explorer d = d.split(" ")[1].split(","); playerVersion = [parseInt(d[0], 10), parseInt(d[1], 10), parseInt(d[2], 10)]; } } } catch(e) {} } return { w3:w3cdom, pv:playerVersion, wk:webkit, ie:ie, win:windows, mac:mac }; }(); function callDomLoadFunctions() { if (isDomLoaded) { return; } isDomLoaded = true; var dl = domLoadFnArr.length; for (var i = 0; i < dl; i++) { domLoadFnArr[i](); } } function addDomLoadEvent(fn) { if (isDomLoaded) { fn(); } else { domLoadFnArr[domLoadFnArr.length] = fn; // Array.push() is only available in IE5.5+ } } /* Main function - Will preferably execute onDomLoad, otherwise onload (as a fallback) */ function main() { if (plugin) { testPlayerVersion(); } } /* Detect the Flash Player version for non-Internet Explorer browsers - Detecting the plug-in version via the object element is more precise than using the plugins collection item's description: a. Both release and build numbers can be detected b. Avoid wrong descriptions by corrupt installers provided by Adobe c. Avoid wrong descriptions by multiple Flash Player entries in the plugin Array, caused by incorrect browser imports - Disadvantage of this method is that it depends on the availability of the DOM, while the plugins collection is immediately available */ function testPlayerVersion() { var b = doc.getElementsByTagName("body")[0]; var o = createElement(OBJECT); o.setAttribute("type", FLASH_MIME_TYPE); var t = b.appendChild(o); if (t) { var counter = 0; (function(){ if (typeof t.GetVariable != UNDEF) { var d = t.GetVariable("$version"); if (d) { d = d.split(" ")[1].split(","); ua.pv = [parseInt(d[0], 10), parseInt(d[1], 10), parseInt(d[2], 10)]; } } else if (counter < 10) { counter++; setTimeout(arguments.callee, 10); return; } b.removeChild(o); t = null; })(); } } function createElement(el) { return doc.createElement(el); } /* Flash Player and SWF content version matching */ function hasPlayerVersion(rv) { var pv = ua.pv, v = rv.split("."); v[0] = parseInt(v[0], 10); v[1] = parseInt(v[1], 10) || 0; // supports short notation, e.g. "9" instead of "9.0.0" v[2] = parseInt(v[2], 10) || 0; return (pv[0] > v[0] || (pv[0] == v[0] && pv[1] > v[1]) || (pv[0] == v[0] && pv[1] == v[1] && pv[2] >= v[2])) ? true : false; } webshims.ready('DOM', callDomLoadFunctions); webshims.loader.addModule('swfmini-embed', {d: ['swfmini']}); var loadEmbed = hasPlayerVersion('9.0.0') ? function(){ webshims.loader.loadList(['swfmini-embed']); return true; } : webshims.$.noop ; if(!Modernizr.video){ loadEmbed(); } else { webshims.ready('WINDOWLOAD', loadEmbed); } return { /* Public API - Reference: http://code.google.com/p/swfobject/wiki/documentation */ registerObject: wasRemoved, getObjectById: wasRemoved, embedSWF: function(swfUrlStr, replaceElemIdStr, widthStr, heightStr, swfVersionStr, xiSwfUrlStr, flashvarsObj, parObj, attObj, callbackFn) { var args = arguments; if(loadEmbed()){ webshims.ready('swfmini-embed', function(){ swfmini.embedSWF.apply(swfmini, args); }); } else if(callbackFn) { callbackFn({success:false, id:replaceElemIdStr}); } }, switchOffAutoHideShow: function() { autoHideShow = false; }, ua: ua, getFlashPlayerVersion: function() { return { major:ua.pv[0], minor:ua.pv[1], release:ua.pv[2] }; }, hasFlashPlayerVersion: hasPlayerVersion, createSWF: function(attObj, parObj, replaceElemIdStr) { if (ua.w3) { return createSWF(attObj, parObj, replaceElemIdStr); } else { return undefined; } }, showExpressInstall: wasRemoved, removeSWF: wasRemoved, createCSS: wasRemoved, addDomLoadEvent: addDomLoadEvent, addLoadEvent: wasRemoved, // For internal usage only expressInstallCallback: wasRemoved }; }(); webshims.isReady('swfmini', true); ;// Copyright 2009-2012 by contributors, MIT License // vim: ts=4 sts=4 sw=4 expandtab (function () { setTimeout(function(){ webshims.isReady('es5', true); }); /** * Brings an environment as close to ECMAScript 5 compliance * as is possible with the facilities of erstwhile engines. * * Annotated ES5: http://es5.github.com/ (specific links below) * ES5 Spec: http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-262.pdf * Required reading: http://javascriptweblog.wordpress.com/2011/12/05/extending-javascript-natives/ */ // // Function // ======== // // ES-5 15.3.4.5 // http://es5.github.com/#x15.3.4.5 function Empty() {} if (!Function.prototype.bind) { Function.prototype.bind = function bind(that) { // .length is 1 // 1. Let Target be the this value. var target = this; // 2. If IsCallable(Target) is false, throw a TypeError exception. if (typeof target != "function") { throw new TypeError("Function.prototype.bind called on incompatible " + target); } // 3. Let A be a new (possibly empty) internal list of all of the // argument values provided after thisArg (arg1, arg2 etc), in order. // XXX slicedArgs will stand in for "A" if used var args = _Array_slice_.call(arguments, 1); // for normal call // 4. Let F be a new native ECMAScript object. // 11. Set the [[Prototype]] internal property of F to the standard // built-in Function prototype object as specified in 15.3.3.1. // 12. Set the [[Call]] internal property of F as described in // 15.3.4.5.1. // 13. Set the [[Construct]] internal property of F as described in // 15.3.4.5.2. // 14. Set the [[HasInstance]] internal property of F as described in // 15.3.4.5.3. var bound = function () { if (this instanceof bound) { // 15.3.4.5.2 [[Construct]] // When the [[Construct]] internal method of a function object, // F that was created using the bind function is called with a // list of arguments ExtraArgs, the following steps are taken: // 1. Let target be the value of F's [[TargetFunction]] // internal property. // 2. If target has no [[Construct]] internal method, a // TypeError exception is thrown. // 3. Let boundArgs be the value of F's [[BoundArgs]] internal // property. // 4. Let args be a new list containing the same values as the // list boundArgs in the same order followed by the same // values as the list ExtraArgs in the same order. // 5. Return the result of calling the [[Construct]] internal // method of target providing args as the arguments. var result = target.apply( this, args.concat(_Array_slice_.call(arguments)) ); if (Object(result) === result) { return result; } return this; } else { // 15.3.4.5.1 [[Call]] // When the [[Call]] internal method of a function object, F, // which was created using the bind function is called with a // this value and a list of arguments ExtraArgs, the following // steps are taken: // 1. Let boundArgs be the value of F's [[BoundArgs]] internal // property. // 2. Let boundThis be the value of F's [[BoundThis]] internal // property. // 3. Let target be the value of F's [[TargetFunction]] internal // property. // 4. Let args be a new list containing the same values as the // list boundArgs in the same order followed by the same // values as the list ExtraArgs in the same order. // 5. Return the result of calling the [[Call]] internal method // of target providing boundThis as the this value and // providing args as the arguments. // equiv: target.call(this, ...boundArgs, ...args) return target.apply( that, args.concat(_Array_slice_.call(arguments)) ); } }; if(target.prototype) { Empty.prototype = target.prototype; bound.prototype = new Empty(); // Clean up dangling references. Empty.prototype = null; } // XXX bound.length is never writable, so don't even try // // 15. If the [[Class]] internal property of Target is "Function", then // a. Let L be the length property of Target minus the length of A. // b. Set the length own property of F to either 0 or L, whichever is // larger. // 16. Else set the length own property of F to 0. // 17. Set the attributes of the length own property of F to the values // specified in 15.3.5.1. // TODO // 18. Set the [[Extensible]] internal property of F to true. // TODO // 19. Let thrower be the [[ThrowTypeError]] function Object (13.2.3). // 20. Call the [[DefineOwnProperty]] internal method of F with // arguments "caller", PropertyDescriptor {[[Get]]: thrower, [[Set]]: // thrower, [[Enumerable]]: false, [[Configurable]]: false}, and // false. // 21. Call the [[DefineOwnProperty]] internal method of F with // arguments "arguments", PropertyDescriptor {[[Get]]: thrower, // [[Set]]: thrower, [[Enumerable]]: false, [[Configurable]]: false}, // and false. // TODO // NOTE Function objects created using Function.prototype.bind do not // have a prototype property or the [[Code]], [[FormalParameters]], and // [[Scope]] internal properties. // XXX can't delete prototype in pure-js. // 22. Return F. return bound; }; } // Shortcut to an often accessed properties, in order to avoid multiple // dereference that costs universally. // _Please note: Shortcuts are defined after `Function.prototype.bind` as we // us it in defining shortcuts. var call = Function.prototype.call; var prototypeOfArray = Array.prototype; var prototypeOfObject = Object.prototype; var _Array_slice_ = prototypeOfArray.slice; // Having a toString local variable name breaks in Opera so use _toString. var _toString = call.bind(prototypeOfObject.toString); var owns = call.bind(prototypeOfObject.hasOwnProperty); // If JS engine supports accessors creating shortcuts. var defineGetter; var defineSetter; var lookupGetter; var lookupSetter; var supportsAccessors; if ((supportsAccessors = owns(prototypeOfObject, "__defineGetter__"))) { defineGetter = call.bind(prototypeOfObject.__defineGetter__); defineSetter = call.bind(prototypeOfObject.__defineSetter__); lookupGetter = call.bind(prototypeOfObject.__lookupGetter__); lookupSetter = call.bind(prototypeOfObject.__lookupSetter__); } // // Array // ===== // // ES5 15.4.4.12 // http://es5.github.com/#x15.4.4.12 // Default value for second param // [bugfix, ielt9, old browsers] // IE < 9 bug: [1,2].splice(0).join("") == "" but should be "12" if ([1,2].splice(0).length != 2) { var array_splice = Array.prototype.splice; if(function() { // test IE < 9 to splice bug - see issue #138 function makeArray(l) { var a = []; while (l--) { a.unshift(l) } return a } var array = [] , lengthBefore ; array.splice.bind(array, 0, 0).apply(null, makeArray(20)); array.splice.bind(array, 0, 0).apply(null, makeArray(26)); lengthBefore = array.length; //20 array.splice(5, 0, "XXX"); // add one element if(lengthBefore + 1 == array.length) { return true;// has right splice implementation without bugs } // else { // IE8 bug // } }()) {//IE 6/7 Array.prototype.splice = function(start, deleteCount) { if (!arguments.length) { return []; } else { return array_splice.apply(this, [ start === void 0 ? 0 : start, deleteCount === void 0 ? (this.length - start) : deleteCount ].concat(_Array_slice_.call(arguments, 2))) } }; } else {//IE8 Array.prototype.splice = function(start, deleteCount) { var result , args = _Array_slice_.call(arguments, 2) , addElementsCount = args.length ; if(!arguments.length) { return []; } if(start === void 0) { // default start = 0; } if(deleteCount === void 0) { // default deleteCount = this.length - start; } if(addElementsCount > 0) { if(deleteCount <= 0) { if(start == this.length) { // tiny optimisation #1 this.push.apply(this, args); return []; } if(start == 0) { // tiny optimisation #2 this.unshift.apply(this, args); return []; } } // Array.prototype.splice implementation result = _Array_slice_.call(this, start, start + deleteCount);// delete part args.push.apply(args, _Array_slice_.call(this, start + deleteCount, this.length));// right part args.unshift.apply(args, _Array_slice_.call(this, 0, start));// left part // delete all items from this array and replace it to 'left part' + _Array_slice_.call(arguments, 2) + 'right part' args.unshift(0, this.length); array_splice.apply(this, args); return result; } return array_splice.call(this, start, deleteCount); } } } // ES5 15.4.4.12 // http://es5.github.com/#x15.4.4.13 // Return len+argCount. // [bugfix, ielt8] // IE < 8 bug: [].unshift(0) == undefined but should be "1" if ([].unshift(0) != 1) { var array_unshift = Array.prototype.unshift; Array.prototype.unshift = function() { array_unshift.apply(this, arguments); return this.length; }; } // ES5 15.4.3.2 // http://es5.github.com/#x15.4.3.2 // https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/isArray if (!Array.isArray) { Array.isArray = function isArray(obj) { return _toString(obj) == "[object Array]"; }; } // The IsCallable() check in the Array functions // has been replaced with a strict check on the // internal class of the object to trap cases where // the provided function was actually a regular // expression literal, which in V8 and // JavaScriptCore is a typeof "function". Only in // V8 are regular expression literals permitted as // reduce parameters, so it is desirable in the // general case for the shim to match the more // strict and common behavior of rejecting regular // expressions. // ES5 15.4.4.18 // http://es5.github.com/#x15.4.4.18 // https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/array/forEach // Check failure of by-index access of string characters (IE < 9) // and failure of `0 in boxedString` (Rhino) var boxedString = Object("a"), splitString = boxedString[0] != "a" || !(0 in boxedString); if (!Array.prototype.forEach) { Array.prototype.forEach = function forEach(fun /*, thisp*/) { var object = toObject(this), self = splitString && _toString(this) == "[object String]" ? this.split("") : object, thisp = arguments[1], i = -1, length = self.length >>> 0; // If no callback function or if callback is not a callable function if (_toString(fun) != "[object Function]") { throw new TypeError(); // TODO message } while (++i < length) { if (i in self) { // Invoke the callback function with call, passing arguments: // context, property value, property key, thisArg object // context fun.call(thisp, self[i], i, object); } } }; } // ES5 15.4.4.19 // http://es5.github.com/#x15.4.4.19 // https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Objects/Array/map if (!Array.prototype.map) { Array.prototype.map = function map(fun /*, thisp*/) { var object = toObject(this), self = splitString && _toString(this) == "[object String]" ? this.split("") : object, length = self.length >>> 0, result = Array(length), thisp = arguments[1]; // If no callback function or if callback is not a callable function if (_toString(fun) != "[object Function]") { throw new TypeError(fun + " is not a function"); } for (var i = 0; i < length; i++) { if (i in self) result[i] = fun.call(thisp, self[i], i, object); } return result; }; } // ES5 15.4.4.20 // http://es5.github.com/#x15.4.4.20 // https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Objects/Array/filter if (!Array.prototype.filter) { Array.prototype.filter = function filter(fun /*, thisp */) { var object = toObject(this), self = splitString && _toString(this) == "[object String]" ? this.split("") : object, length = self.length >>> 0, result = [], value, thisp = arguments[1]; // If no callback function or if callback is not a callable function if (_toString(fun) != "[object Function]") { throw new TypeError(fun + " is not a function"); } for (var i = 0; i < length; i++) { if (i in self) { value = self[i]; if (fun.call(thisp, value, i, object)) { result.push(value); } } } return result; }; } // ES5 15.4.4.16 // http://es5.github.com/#x15.4.4.16 // https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/every if (!Array.prototype.every) { Array.prototype.every = function every(fun /*, thisp */) { var object = toObject(this), self = splitString && _toString(this) == "[object String]" ? this.split("") : object, length = self.length >>> 0, thisp = arguments[1]; // If no callback function or if callback is not a callable function if (_toString(fun) != "[object Function]") { throw new TypeError(fun + " is not a function"); } for (var i = 0; i < length; i++) { if (i in self && !fun.call(thisp, self[i], i, object)) { return false; } } return true; }; } // ES5 15.4.4.17 // http://es5.github.com/#x15.4.4.17 // https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/some if (!Array.prototype.some) { Array.prototype.some = function some(fun /*, thisp */) { var object = toObject(this), self = splitString && _toString(this) == "[object String]" ? this.split("") : object, length = self.length >>> 0, thisp = arguments[1]; // If no callback function or if callback is not a callable function if (_toString(fun) != "[object Function]") { throw new TypeError(fun + " is not a function"); } for (var i = 0; i < length; i++) { if (i in self && fun.call(thisp, self[i], i, object)) { return true; } } return false; }; } // ES5 15.4.4.21 // http://es5.github.com/#x15.4.4.21 // https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Objects/Array/reduce if (!Array.prototype.reduce) { Array.prototype.reduce = function reduce(fun /*, initial*/) { var object = toObject(this), self = splitString && _toString(this) == "[object String]" ? this.split("") : object, length = self.length >>> 0; // If no callback function or if callback is not a callable function if (_toString(fun) != "[object Function]") { throw new TypeError(fun + " is not a function"); } // no value to return if no initial value and an empty array if (!length && arguments.length == 1) { throw new TypeError("reduce of empty array with no initial value"); } var i = 0; var result; if (arguments.length >= 2) { result = arguments[1]; } else { do { if (i in self) { result = self[i++]; break; } // if array contains no values, no initial value to return if (++i >= length) { throw new TypeError("reduce of empty array with no initial value"); } } while (true); } for (; i < length; i++) { if (i in self) { result = fun.call(void 0, result, self[i], i, object); } } return result; }; } // ES5 15.4.4.22 // http://es5.github.com/#x15.4.4.22 // https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Objects/Array/reduceRight if (!Array.prototype.reduceRight) { Array.prototype.reduceRight = function reduceRight(fun /*, initial*/) { var object = toObject(this), self = splitString && _toString(this) == "[object String]" ? this.split("") : object, length = self.length >>> 0; // If no callback function or if callback is not a callable function if (_toString(fun) != "[object Function]") { throw new TypeError(fun + " is not a function"); } // no value to return if no initial value, empty array if (!length && arguments.length == 1) { throw new TypeError("reduceRight of empty array with no initial value"); } var result, i = length - 1; if (arguments.length >= 2) { result = arguments[1]; } else { do { if (i in self) { result = self[i--]; break; } // if array contains no values, no initial value to return if (--i < 0) { throw new TypeError("reduceRight of empty array with no initial value"); } } while (true); } if (i < 0) { return result; } do { if (i in this) { result = fun.call(void 0, result, self[i], i, object); } } while (i--); return result; }; } // ES5 15.4.4.14 // http://es5.github.com/#x15.4.4.14 // https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/indexOf if (!Array.prototype.indexOf || ([0, 1].indexOf(1, 2) != -1)) { Array.prototype.indexOf = function indexOf(sought /*, fromIndex */ ) { var self = splitString && _toString(this) == "[object String]" ? this.split("") : toObject(this), length = self.length >>> 0; if (!length) { return -1; } var i = 0; if (arguments.length > 1) { i = toInteger(arguments[1]); } // handle negative indices i = i >= 0 ? i : Math.max(0, length + i); for (; i < length; i++) { if (i in self && self[i] === sought) { return i; } } return -1; }; } // ES5 15.4.4.15 // http://es5.github.com/#x15.4.4.15 // https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/lastIndexOf if (!Array.prototype.lastIndexOf || ([0, 1].lastIndexOf(0, -3) != -1)) { Array.prototype.lastIndexOf = function lastIndexOf(sought /*, fromIndex */) { var self = splitString && _toString(this) == "[object String]" ? this.split("") : toObject(this), length = self.length >>> 0; if (!length) { return -1; } var i = length - 1; if (arguments.length > 1) { i = Math.min(i, toInteger(arguments[1])); } // handle negative indices i = i >= 0 ? i : length - Math.abs(i); for (; i >= 0; i--) { if (i in self && sought === self[i]) { return i; } } return -1; }; } // // Object // ====== // // ES5 15.2.3.14 // http://es5.github.com/#x15.2.3.14 if (!Object.keys) { // http://whattheheadsaid.com/2010/10/a-safer-object-keys-compatibility-implementation var hasDontEnumBug = true, dontEnums = [ "toString", "toLocaleString", "valueOf", "hasOwnProperty", "isPrototypeOf", "propertyIsEnumerable", "constructor" ], dontEnumsLength = dontEnums.length; for (var key in {"toString": null}) { hasDontEnumBug = false; } Object.keys = function keys(object) { if ( (typeof object != "object" && typeof object != "function") || object === null ) { throw new TypeError("Object.keys called on a non-object"); } var keys = []; for (var name in object) { if (owns(object, name)) { keys.push(name); } } if (hasDontEnumBug) { for (var i = 0, ii = dontEnumsLength; i < ii; i++) { var dontEnum = dontEnums[i]; if (owns(object, dontEnum)) { keys.push(dontEnum); } } } return keys; }; } // // Date // ==== // // ES5 15.9.5.43 // http://es5.github.com/#x15.9.5.43 // This function returns a String value represent the instance in time // represented by this Date object. The format of the String is the Date Time // string format defined in 15.9.1.15. All fields are present in the String. // The time zone is always UTC, denoted by the suffix Z. If the time value of // this object is not a finite Number a RangeError exception is thrown. var negativeDate = -62198755200000, negativeYearString = "-000001"; if ( !Date.prototype.toISOString || (new Date(negativeDate).toISOString().indexOf(negativeYearString) === -1) ) { Date.prototype.toISOString = function toISOString() { var result, length, value, year, month; if (!isFinite(this)) { throw new RangeError("Date.prototype.toISOString called on non-finite value."); } year = this.getUTCFullYear(); month = this.getUTCMonth(); // see https://github.com/kriskowal/es5-shim/issues/111 year += Math.floor(month / 12); month = (month % 12 + 12) % 12; // the date time string format is specified in 15.9.1.15. result = [month + 1, this.getUTCDate(), this.getUTCHours(), this.getUTCMinutes(), this.getUTCSeconds()]; year = ( (year < 0 ? "-" : (year > 9999 ? "+" : "")) + ("00000" + Math.abs(year)) .slice(0 <= year && year <= 9999 ? -4 : -6) ); length = result.length; while (length--) { value = result[length]; // pad months, days, hours, minutes, and seconds to have two // digits. if (value < 10) { result[length] = "0" + value; } } // pad milliseconds to have three digits. return ( year + "-" + result.slice(0, 2).join("-") + "T" + result.slice(2).join(":") + "." + ("000" + this.getUTCMilliseconds()).slice(-3) + "Z" ); }; } // ES5 15.9.5.44 // http://es5.github.com/#x15.9.5.44 // This function provides a String representation of a Date object for use by // JSON.stringify (15.12.3). var dateToJSONIsSupported = false; try { dateToJSONIsSupported = ( Date.prototype.toJSON && new Date(NaN).toJSON() === null && new Date(negativeDate).toJSON().indexOf(negativeYearString) !== -1 && Date.prototype.toJSON.call({ // generic toISOString: function () { return true; } }) ); } catch (e) { } if (!dateToJSONIsSupported) { Date.prototype.toJSON = function toJSON(key) { // When the toJSON method is called with argument key, the following // steps are taken: // 1. Let O be the result of calling ToObject, giving it the this // value as its argument. // 2. Let tv be toPrimitive(O, hint Number). var o = Object(this), tv = toPrimitive(o), toISO; // 3. If tv is a Number and is not finite, return null. if (typeof tv === "number" && !isFinite(tv)) { return null; } // 4. Let toISO be the result of calling the [[Get]] internal method of // O with argument "toISOString". toISO = o.toISOString; // 5. If IsCallable(toISO) is false, throw a TypeError exception. if (typeof toISO != "function") { throw new TypeError("toISOString property is not callable"); } // 6. Return the result of calling the [[Call]] internal method of // toISO with O as the this value and an empty argument list. return toISO.call(o); // NOTE 1 The argument is ignored. // NOTE 2 The toJSON function is intentionally generic; it does not // require that its this value be a Date object. Therefore, it can be // transferred to other kinds of objects for use as a method. However, // it does require that any such object have a toISOString method. An // object is free to use the argument key to filter its // stringification. }; } // ES5 15.9.4.2 // http://es5.github.com/#x15.9.4.2 // based on work shared by Daniel Friesen (dantman) // http://gist.github.com/303249 if (!Date.parse || "Date.parse is buggy") { // XXX global assignment won't work in embeddings that use // an alternate object for the context. Date = (function(NativeDate) { // Date.length === 7 function Date(Y, M, D, h, m, s, ms) { var length = arguments.length; if (this instanceof NativeDate) { var date = length == 1 && String(Y) === Y ? // isString(Y) // We explicitly pass it through parse: new NativeDate(Date.parse(Y)) : // We have to manually make calls depending on argument // length here length >= 7 ? new NativeDate(Y, M, D, h, m, s, ms) : length >= 6 ? new NativeDate(Y, M, D, h, m, s) : length >= 5 ? new NativeDate(Y, M, D, h, m) : length >= 4 ? new NativeDate(Y, M, D, h) : length >= 3 ? new NativeDate(Y, M, D) : length >= 2 ? new NativeDate(Y, M) : length >= 1 ? new NativeDate(Y) : new NativeDate(); // Prevent mixups with unfixed Date object date.constructor = Date; return date; } return NativeDate.apply(this, arguments); }; // 15.9.1.15 Date Time String Format. var isoDateExpression = new RegExp("^" + "(\\d{4}|[\+\-]\\d{6})" + // four-digit year capture or sign + // 6-digit extended year "(?:-(\\d{2})" + // optional month capture "(?:-(\\d{2})" + // optional day capture "(?:" + // capture hours:minutes:seconds.milliseconds "T(\\d{2})" + // hours capture ":(\\d{2})" + // minutes capture "(?:" + // optional :seconds.milliseconds ":(\\d{2})" + // seconds capture "(?:(\\.\\d{1,}))?" + // milliseconds capture ")?" + "(" + // capture UTC offset component "Z|" + // UTC capture "(?:" + // offset specifier +/-hours:minutes "([-+])" + // sign capture "(\\d{2})" + // hours offset capture ":(\\d{2})" + // minutes offset capture ")" + ")?)?)?)?" + "$"); var months = [ 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365 ]; function dayFromMonth(year, month) { var t = month > 1 ? 1 : 0; return ( months[month] + Math.floor((year - 1969 + t) / 4) - Math.floor((year - 1901 + t) / 100) + Math.floor((year - 1601 + t) / 400) + 365 * (year - 1970) ); } // Copy any custom methods a 3rd party library may have added for (var key in NativeDate) { Date[key] = NativeDate[key]; } // Copy "native" methods explicitly; they may be non-enumerable Date.now = NativeDate.now; Date.UTC = NativeDate.UTC; Date.prototype = NativeDate.prototype; Date.prototype.constructor = Date; // Upgrade Date.parse to handle simplified ISO 8601 strings Date.parse = function parse(string) { var match = isoDateExpression.exec(string); if (match) { // parse months, days, hours, minutes, seconds, and milliseconds // provide default values if necessary // parse the UTC offset component var year = Number(match[1]), month = Number(match[2] || 1) - 1, day = Number(match[3] || 1) - 1, hour = Number(match[4] || 0), minute = Number(match[5] || 0), second = Number(match[6] || 0), millisecond = Math.floor(Number(match[7] || 0) * 1000), // When time zone is missed, local offset should be used // (ES 5.1 bug) // see https://bugs.ecmascript.org/show_bug.cgi?id=112 offset = !match[4] || match[8] ? 0 : Number(new NativeDate(1970, 0)), signOffset = match[9] === "-" ? 1 : -1, hourOffset = Number(match[10] || 0), minuteOffset = Number(match[11] || 0), result; if ( hour < ( minute > 0 || second > 0 || millisecond > 0 ? 24 : 25 ) && minute < 60 && second < 60 && millisecond < 1000 && month > -1 && month < 12 && hourOffset < 24 && minuteOffset < 60 && // detect invalid offsets day > -1 && day < ( dayFromMonth(year, month + 1) - dayFromMonth(year, month) ) ) { result = ( (dayFromMonth(year, month) + day) * 24 + hour + hourOffset * signOffset ) * 60; result = ( (result + minute + minuteOffset * signOffset) * 60 + second ) * 1000 + millisecond + offset; if (-8.64e15 <= result && result <= 8.64e15) { return result; } } return NaN; } return NativeDate.parse.apply(this, arguments); }; return Date; })(Date); } // ES5 15.9.4.4 // http://es5.github.com/#x15.9.4.4 if (!Date.now) { Date.now = function now() { return new Date().getTime(); }; } // // Number // ====== // // ES5.1 15.7.4.5 // http://es5.github.com/#x15.7.4.5 if (!Number.prototype.toFixed || (0.00008).toFixed(3) !== '0.000' || (0.9).toFixed(0) === '0' || (1.255).toFixed(2) !== '1.25' || (1000000000000000128).toFixed(0) !== "1000000000000000128") { // Hide these variables and functions (function () { var base, size, data, i; base = 1e7; size = 6; data = [0, 0, 0, 0, 0, 0]; function multiply(n, c) { var i = -1; while (++i < size) { c += n * data[i]; data[i] = c % base; c = Math.floor(c / base); } } function divide(n) { var i = size, c = 0; while (--i >= 0) { c += data[i]; data[i] = Math.floor(c / n); c = (c % n) * base; } } function toString() { var i = size; var s = ''; while (--i >= 0) { if (s !== '' || i === 0 || data[i] !== 0) { var t = String(data[i]); if (s === '') { s = t; } else { s += '0000000'.slice(0, 7 - t.length) + t; } } } return s; } function pow(x, n, acc) { return (n === 0 ? acc : (n % 2 === 1 ? pow(x, n - 1, acc * x) : pow(x * x, n / 2, acc))); } function log(x) { var n = 0; while (x >= 4096) { n += 12; x /= 4096; } while (x >= 2) { n += 1; x /= 2; } return n; } Number.prototype.toFixed = function (fractionDigits) { var f, x, s, m, e, z, j, k; // Test for NaN and round fractionDigits down f = Number(fractionDigits); f = f !== f ? 0 : Math.floor(f); if (f < 0 || f > 20) { throw new RangeError("Number.toFixed called with invalid number of decimals"); } x = Number(this); // Test for NaN if (x !== x) { return "NaN"; } // If it is too big or small, return the string value of the number if (x <= -1e21 || x >= 1e21) { return String(x); } s = ""; if (x < 0) { s = "-"; x = -x; } m = "0"; if (x > 1e-21) { // 1e-21 < x < 1e21 // -70 < log2(x) < 70 e = log(x * pow(2, 69, 1)) - 69; z = (e < 0 ? x * pow(2, -e, 1) : x / pow(2, e, 1)); z *= 0x10000000000000; // Math.pow(2, 52); e = 52 - e; // -18 < e < 122 // x = z / 2 ^ e if (e > 0) { multiply(0, z); j = f; while (j >= 7) { multiply(1e7, 0); j -= 7; } multiply(pow(10, j, 1), 0); j = e - 1; while (j >= 23) { divide(1 << 23); j -= 23; } divide(1 << j); multiply(1, 1); divide(2); m = toString(); } else { multiply(0, z); multiply(1 << (-e), 0); m = toString() + '0.00000000000000000000'.slice(2, 2 + f); } } if (f > 0) { k = m.length; if (k <= f) { m = s + '0.0000000000000000000'.slice(0, f - k + 2) + m; } else { m = s + m.slice(0, k - f) + '.' + m.slice(k - f); } } else { m = s + m; } return m; } }()); } // // String // ====== // // ES5 15.5.4.14 // http://es5.github.com/#x15.5.4.14 // [bugfix, IE lt 9, firefox 4, Konqueror, Opera, obscure browsers] // Many browsers do not split properly with regular expressions or they // do not perform the split correctly under obscure conditions. // See http://blog.stevenlevithan.com/archives/cross-browser-split // I've tested in many browsers and this seems to cover the deviant ones: // 'ab'.split(/(?:ab)*/) should be ["", ""], not [""] // '.'.split(/(.?)(.?)/) should be ["", ".", "", ""], not ["", ""] // 'tesst'.split(/(s)*/) should be ["t", undefined, "e", "s", "t"], not // [undefined, "t", undefined, "e", ...] // ''.split(/.?/) should be [], not [""] // '.'.split(/()()/) should be ["."], not ["", "", "."] var string_split = String.prototype.split; if ( 'ab'.split(/(?:ab)*/).length !== 2 || '.'.split(/(.?)(.?)/).length !== 4 || 'tesst'.split(/(s)*/)[1] === "t" || ''.split(/.?/).length === 0 || '.'.split(/()()/).length > 1 ) { (function () { var compliantExecNpcg = /()??/.exec("")[1] === void 0; // NPCG: nonparticipating capturing group String.prototype.split = function (separator, limit) { var string = this; if (separator === void 0 && limit === 0) return []; // If `separator` is not a regex, use native split if (Object.prototype.toString.call(separator) !== "[object RegExp]") { return string_split.apply(this, arguments); } var output = [], flags = (separator.ignoreCase ? "i" : "") + (separator.multiline ? "m" : "") + (separator.extended ? "x" : "") + // Proposed for ES6 (separator.sticky ? "y" : ""), // Firefox 3+ lastLastIndex = 0, // Make `global` and avoid `lastIndex` issues by working with a copy separator = new RegExp(separator.source, flags + "g"), separator2, match, lastIndex, lastLength; string += ""; // Type-convert if (!compliantExecNpcg) { // Doesn't need flags gy, but they don't hurt separator2 = new RegExp("^" + separator.source + "$(?!\\s)", flags); } /* Values for `limit`, per the spec: * If undefined: 4294967295 // Math.pow(2, 32) - 1 * If 0, Infinity, or NaN: 0 * If positive number: limit = Math.floor(limit); if (limit > 4294967295) limit -= 4294967296; * If negative number: 4294967296 - Math.floor(Math.abs(limit)) * If other: Type-convert, then use the above rules */ limit = limit === void 0 ? -1 >>> 0 : // Math.pow(2, 32) - 1 limit >>> 0; // ToUint32(limit) while (match = separator.exec(string)) { // `separator.lastIndex` is not reliable cross-browser lastIndex = match.index + match[0].length; if (lastIndex > lastLastIndex) { output.push(string.slice(lastLastIndex, match.index)); // Fix browsers whose `exec` methods don't consistently return `undefined` for // nonparticipating capturing groups if (!compliantExecNpcg && match.length > 1) { match[0].replace(separator2, function () { for (var i = 1; i < arguments.length - 2; i++) { if (arguments[i] === void 0) { match[i] = void 0; } } }); } if (match.length > 1 && match.index < string.length) { Array.prototype.push.apply(output, match.slice(1)); } lastLength = match[0].length; lastLastIndex = lastIndex; if (output.length >= limit) { break; } } if (separator.lastIndex === match.index) { separator.lastIndex++; // Avoid an infinite loop } } if (lastLastIndex === string.length) { if (lastLength || !separator.test("")) { output.push(""); } } else { output.push(string.slice(lastLastIndex)); } return output.length > limit ? output.slice(0, limit) : output; }; }()); // [bugfix, chrome] // If separator is undefined, then the result array contains just one String, // which is the this value (converted to a String). If limit is not undefined, // then the output array is truncated so that it contains no more than limit // elements. // "0".split(undefined, 0) -> [] } else if ("0".split(void 0, 0).length) { String.prototype.split = function(separator, limit) { if (separator === void 0 && limit === 0) return []; return string_split.apply(this, arguments); } } // ECMA-262, 3rd B.2.3 // Note an ECMAScript standart, although ECMAScript 3rd Edition has a // non-normative section suggesting uniform semantics and it should be // normalized across all browsers // [bugfix, IE lt 9] IE < 9 substr() with negative value not working in IE if("".substr && "0b".substr(-1) !== "b") { var string_substr = String.prototype.substr; /** * Get the substring of a string * @param {integer} start where to start the substring * @param {integer} length how many characters to return * @return {string} */ String.prototype.substr = function(start, length) { return string_substr.call( this, start < 0 ? ((start = this.length + start) < 0 ? 0 : start) : start, length ); } } // ES5 15.5.4.20 // http://es5.github.com/#x15.5.4.20 var ws = "\x09\x0A\x0B\x0C\x0D\x20\xA0\u1680\u180E\u2000\u2001\u2002\u2003" + "\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028" + "\u2029\uFEFF"; if (!String.prototype.trim || ws.trim()) { // http://blog.stevenlevithan.com/archives/faster-trim-javascript // http://perfectionkills.com/whitespace-deviations/ ws = "[" + ws + "]"; var trimBeginRegexp = new RegExp("^" + ws + ws + "*"), trimEndRegexp = new RegExp(ws + ws + "*$"); String.prototype.trim = function trim() { if (this === void 0 || this === null) { throw new TypeError("can't convert "+this+" to object"); } return String(this) .replace(trimBeginRegexp, "") .replace(trimEndRegexp, ""); }; } // // Util // ====== // // ES5 9.4 // http://es5.github.com/#x9.4 // http://jsperf.com/to-integer function toInteger(n) { n = +n; if (n !== n) { // isNaN n = 0; } else if (n !== 0 && n !== (1/0) && n !== -(1/0)) { n = (n > 0 || -1) * Math.floor(Math.abs(n)); } return n; } function isPrimitive(input) { var type = typeof input; return ( input === null || type === "undefined" || type === "boolean" || type === "number" || type === "string" ); } function toPrimitive(input) { var val, valueOf, toString; if (isPrimitive(input)) { return input; } valueOf = input.valueOf; if (typeof valueOf === "function") { val = valueOf.call(input); if (isPrimitive(val)) { return val; } } toString = input.toString; if (typeof toString === "function") { val = toString.call(input); if (isPrimitive(val)) { return val; } } throw new TypeError(); } // ES5 9.9 // http://es5.github.com/#x9.9 var toObject = function (o) { if (o == null) { // this matches both null and undefined throw new TypeError("can't convert "+o+" to object"); } return Object(o); }; })(); (function($, shims){ var defineProperty = 'defineProperty'; var advancedObjectProperties = !!(Object.create && Object.defineProperties && Object.getOwnPropertyDescriptor); //safari5 has defineProperty-interface, but it can't be used on dom-object //only do this test in non-IE browsers, because this hurts dhtml-behavior in some IE8 versions if (advancedObjectProperties && Object[defineProperty] && Object.prototype.__defineGetter__) { (function(){ try { var foo = document.createElement('foo'); Object[defineProperty](foo, 'bar', { get: function(){ return true; } }); advancedObjectProperties = !!foo.bar; } catch (e) { advancedObjectProperties = false; } foo = null; })(); } Modernizr.objectAccessor = !!((advancedObjectProperties || (Object.prototype.__defineGetter__ && Object.prototype.__lookupSetter__))); Modernizr.advancedObjectProperties = advancedObjectProperties; if((!advancedObjectProperties || !Object.create || !Object.defineProperties || !Object.getOwnPropertyDescriptor || !Object.defineProperty)){ var call = Function.prototype.call; var prototypeOfObject = Object.prototype; var owns = call.bind(prototypeOfObject.hasOwnProperty); shims.objectCreate = function(proto, props, opts, no__proto__){ var o; var f = function(){}; f.prototype = proto; o = new f(); if(!no__proto__ && !('__proto__' in o) && !Modernizr.objectAccessor){ o.__proto__ = proto; } if(props){ shims.defineProperties(o, props); } if(opts){ o.options = $.extend(true, {}, o.options || {}, opts); opts = o.options; } if(o._create && $.isFunction(o._create)){ o._create(opts); } return o; }; shims.defineProperties = function(object, props){ for (var name in props) { if (owns(props, name)) { shims.defineProperty(object, name, props[name]); } } return object; }; var descProps = ['configurable', 'enumerable', 'writable']; shims.defineProperty = function(proto, property, descriptor){ if(typeof descriptor != "object" || descriptor === null){return proto;} if(owns(descriptor, "value")){ proto[property] = descriptor.value; return proto; } if(proto.__defineGetter__){ if (typeof descriptor.get == "function") { proto.__defineGetter__(property, descriptor.get); } if (typeof descriptor.set == "function"){ proto.__defineSetter__(property, descriptor.set); } } return proto; }; shims.getPrototypeOf = function (object) { return Object.getPrototypeOf && Object.getPrototypeOf(object) || object.__proto__ || object.constructor && object.constructor.prototype; }; //based on http://www.refactory.org/s/object_getownpropertydescriptor/view/latest shims.getOwnPropertyDescriptor = function(obj, prop){ if (typeof obj !== "object" && typeof obj !== "function" || obj === null){ throw new TypeError("Object.getOwnPropertyDescriptor called on a non-object"); } var descriptor; if(Object.defineProperty && Object.getOwnPropertyDescriptor){ try{ descriptor = Object.getOwnPropertyDescriptor(obj, prop); return descriptor; } catch(e){} } descriptor = { configurable: true, enumerable: true, writable: true, value: undefined }; var getter = obj.__lookupGetter__ && obj.__lookupGetter__(prop), setter = obj.__lookupSetter__ && obj.__lookupSetter__(prop) ; if (!getter && !setter) { // not an accessor so return prop if(!owns(obj, prop)){ return; } descriptor.value = obj[prop]; return descriptor; } // there is an accessor, remove descriptor.writable; populate descriptor.get and descriptor.set delete descriptor.writable; delete descriptor.value; descriptor.get = descriptor.set = undefined; if(getter){ descriptor.get = getter; } if(setter){ descriptor.set = setter; } return descriptor; }; } webshims.isReady('es5', true); })(webshims.$, webshims); ; //this might was already extended by ES5 shim feature (function($){ "use strict"; var webshims = window.webshims; if(webshims.defineProperties){return;} var defineProperty = 'defineProperty'; var has = Object.prototype.hasOwnProperty; var descProps = ['configurable', 'enumerable', 'writable']; var extendUndefined = function(prop){ for(var i = 0; i < 3; i++){ if(prop[descProps[i]] === undefined && (descProps[i] !== 'writable' || prop.value !== undefined)){ prop[descProps[i]] = true; } } }; var extendProps = function(props){ if(props){ for(var i in props){ if(has.call(props, i)){ extendUndefined(props[i]); } } } }; if(Object.create){ webshims.objectCreate = function(proto, props, opts){ extendProps(props); var o = Object.create(proto, props); if(opts){ o.options = $.extend(true, {}, o.options || {}, opts); opts = o.options; } if(o._create && $.isFunction(o._create)){ o._create(opts); } return o; }; } if(Object[defineProperty]){ webshims[defineProperty] = function(obj, prop, desc){ extendUndefined(desc); return Object[defineProperty](obj, prop, desc); }; } if(Object.defineProperties){ webshims.defineProperties = function(obj, props){ extendProps(props); return Object.defineProperties(obj, props); }; } webshims.getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor; webshims.getPrototypeOf = Object.getPrototypeOf; })(window.webshims.$); //DOM-Extension helper webshims.register('dom-extend', function($, webshims, window, document, undefined){ "use strict"; var supportHrefNormalized = !('hrefNormalized' in $.support) || $.support.hrefNormalized; var supportGetSetAttribute = !('getSetAttribute' in $.support) || $.support.getSetAttribute; var has = Object.prototype.hasOwnProperty; webshims.assumeARIA = supportGetSetAttribute || Modernizr.canvas || Modernizr.video || Modernizr.boxsizing; if($('<input type="email" />').attr('type') == 'text' || $('<form />').attr('novalidate') === "" || ('required' in $('<input />')[0].attributes)){ webshims.error("IE browser modes are busted in IE10+. Please test your HTML/CSS/JS with a real IE version or at least IETester or similiar tools"); } if('debug' in webshims){ webshims.error('Use webshims.setOptions("debug", true||false||"noCombo"); to debug flag'); } if (!webshims.cfg.no$Switch) { var switch$ = function(){ if (window.jQuery && (!window.$ || window.jQuery == window.$) && !window.jQuery.webshims) { webshims.error("jQuery was included more than once. Make sure to include it only once or try the $.noConflict(extreme) feature! Webshims and other Plugins might not work properly. Or set webshims.cfg.no$Switch to 'true'."); if (window.$) { window.$ = webshims.$; } window.jQuery = webshims.$; } if(webshims.M != Modernizr){ webshims.error("Modernizr was included more than once. Make sure to include it only once! Webshims and other scripts might not work properly."); for(var i in Modernizr){ if(!(i in webshims.M)){ webshims.M[i] = Modernizr[i]; } } Modernizr = webshims.M; } }; switch$(); setTimeout(switch$, 90); webshims.ready('DOM', switch$); $(switch$); webshims.ready('WINDOWLOAD', switch$); } //shortcus var modules = webshims.modules; var listReg = /\s*,\s*/; //proxying attribute var olds = {}; var havePolyfill = {}; var hasPolyfillMethod = {}; var extendedProps = {}; var extendQ = {}; var modifyProps = {}; var oldVal = $.fn.val; var singleVal = function(elem, name, val, pass, _argless){ return (_argless) ? oldVal.call($(elem)) : oldVal.call($(elem), val); }; //jquery mobile and jquery ui if(!$.widget){ (function(){ var _cleanData = $.cleanData; $.cleanData = function( elems ) { if(!$.widget){ for ( var i = 0, elem; (elem = elems[i]) != null; i++ ) { try { $( elem ).triggerHandler( "remove" ); // http://bugs.jquery.com/ticket/8235 } catch( e ) {} } } _cleanData( elems ); }; })(); } $.fn.val = function(val){ var elem = this[0]; if(arguments.length && val == null){ val = ''; } if(!arguments.length){ if(!elem || elem.nodeType !== 1){return oldVal.call(this);} return $.prop(elem, 'value', val, 'val', true); } if($.isArray(val)){ return oldVal.apply(this, arguments); } var isFunction = $.isFunction(val); return this.each(function(i){ elem = this; if(elem.nodeType === 1){ if(isFunction){ var genVal = val.call( elem, i, $.prop(elem, 'value', undefined, 'val', true)); if(genVal == null){ genVal = ''; } $.prop(elem, 'value', genVal, 'val') ; } else { $.prop(elem, 'value', val, 'val'); } } }); }; $.fn.onTrigger = function(evt, fn){ return this.on(evt, fn).each(fn); }; $.fn.onWSOff = function(evt, fn, trigger, evtDel){ if(!evtDel){ evtDel = document; } $(evtDel)[trigger ? 'onTrigger' : 'on'](evt, fn); this.on('remove', function(e){ if(!e.originalEvent){ $(evtDel).off(evt, fn); } }); return this; }; var dataID = '_webshimsLib'+ (Math.round(Math.random() * 1000)); var elementData = function(elem, key, val){ elem = elem.jquery ? elem[0] : elem; if(!elem){return val || {};} var data = $.data(elem, dataID); if(val !== undefined){ if(!data){ data = $.data(elem, dataID, {}); } if(key){ data[key] = val; } } return key ? data && data[key] : data; }; [{name: 'getNativeElement', prop: 'nativeElement'}, {name: 'getShadowElement', prop: 'shadowElement'}, {name: 'getShadowFocusElement', prop: 'shadowFocusElement'}].forEach(function(data){ $.fn[data.name] = function(){ var elems = []; this.each(function(){ var shadowData = elementData(this, 'shadowData'); var elem = shadowData && shadowData[data.prop] || this; if($.inArray(elem, elems) == -1){ elems.push(elem); } }); return this.pushStack(elems); }; }); //add support for $('video').trigger('play') in case extendNative is set to false if(!webshims.cfg.extendNative && !webshims.cfg.noTriggerOverride){ (function(oldTrigger){ $.event.trigger = function(event, data, elem, onlyHandlers){ if(!hasPolyfillMethod[event] || onlyHandlers || !elem || elem.nodeType !== 1){ return oldTrigger.apply(this, arguments); } var ret, isOrig, origName; var origFn = elem[event]; var polyfilledFn = $.prop(elem, event); var changeFn = polyfilledFn && origFn != polyfilledFn; if(changeFn){ origName = '__ws'+event; isOrig = (event in elem) && has.call(elem, event); elem[event] = polyfilledFn; elem[origName] = origFn; } ret = oldTrigger.apply(this, arguments); if (changeFn) { if(isOrig){ elem[event] = origFn; } else { delete elem[event]; } delete elem[origName]; } return ret; }; })($.event.trigger); } ['removeAttr', 'prop', 'attr'].forEach(function(type){ olds[type] = $[type]; $[type] = function(elem, name, value, pass, _argless){ var isVal = (pass == 'val'); var oldMethod = !isVal ? olds[type] : singleVal; if( !elem || !havePolyfill[name] || elem.nodeType !== 1 || (!isVal && pass && type == 'attr' && $.attrFn[name]) ){ return oldMethod(elem, name, value, pass, _argless); } var nodeName = (elem.nodeName || '').toLowerCase(); var desc = extendedProps[nodeName]; var curType = (type == 'attr' && (value === false || value === null)) ? 'removeAttr' : type; var propMethod; var oldValMethod; var ret; if(!desc){ desc = extendedProps['*']; } if(desc){ desc = desc[name]; } if(desc){ propMethod = desc[curType]; } if(propMethod){ if(name == 'value'){ oldValMethod = propMethod.isVal; propMethod.isVal = isVal; } if(curType === 'removeAttr'){ return propMethod.value.call(elem); } else if(value === undefined){ return (propMethod.get) ? propMethod.get.call(elem) : propMethod.value ; } else if(propMethod.set) { if(type == 'attr' && value === true){ value = name; } ret = propMethod.set.call(elem, value); } if(name == 'value'){ propMethod.isVal = oldValMethod; } } else { ret = oldMethod(elem, name, value, pass, _argless); } if((value !== undefined || curType === 'removeAttr') && modifyProps[nodeName] && modifyProps[nodeName][name]){ var boolValue; if(curType == 'removeAttr'){ boolValue = false; } else if(curType == 'prop'){ boolValue = !!(value); } else { boolValue = true; } modifyProps[nodeName][name].forEach(function(fn){ if(!fn.only || (fn.only = 'prop' && type == 'prop') || (fn.only == 'attr' && type != 'prop')){ fn.call(elem, value, boolValue, (isVal) ? 'val' : curType, type); } }); } return ret; }; extendQ[type] = function(nodeName, prop, desc){ if(!extendedProps[nodeName]){ extendedProps[nodeName] = {}; } if(!extendedProps[nodeName][prop]){ extendedProps[nodeName][prop] = {}; } var oldDesc = extendedProps[nodeName][prop][type]; var getSup = function(propType, descriptor, oDesc){ var origProp; if(descriptor && descriptor[propType]){ return descriptor[propType]; } if(oDesc && oDesc[propType]){ return oDesc[propType]; } if(type == 'prop' && prop == 'value'){ return function(value){ var elem = this; return (desc.isVal) ? singleVal(elem, prop, value, false, (arguments.length === 0)) : olds[type](elem, prop, value) ; }; } if(type == 'prop' && propType == 'value' && desc.value.apply){ origProp = '__ws'+prop; hasPolyfillMethod[prop] = true; return function(value){ var sup = this[origProp] || olds[type](this, prop); if(sup && sup.apply){ sup = sup.apply(this, arguments); } return sup; }; } return function(value){ return olds[type](this, prop, value); }; }; extendedProps[nodeName][prop][type] = desc; if(desc.value === undefined){ if(!desc.set){ desc.set = desc.writeable ? getSup('set', desc, oldDesc) : (webshims.cfg.useStrict && prop == 'prop') ? function(){throw(prop +' is readonly on '+ nodeName);} : function(){webshims.info(prop +' is readonly on '+ nodeName);} ; } if(!desc.get){ desc.get = getSup('get', desc, oldDesc); } } ['value', 'get', 'set'].forEach(function(descProp){ if(desc[descProp]){ desc['_sup'+descProp] = getSup(descProp, oldDesc); } }); }; }); var extendNativeValue = (function(){ var UNKNOWN = webshims.getPrototypeOf(document.createElement('foobar')); //see also: https://github.com/lojjic/PIE/issues/40 | https://prototype.lighthouseapp.com/projects/8886/tickets/1107-ie8-fatal-crash-when-prototypejs-is-loaded-with-rounded-cornershtc var isExtendNativeSave = Modernizr.advancedObjectProperties && Modernizr.objectAccessor; return function(nodeName, prop, desc){ var elem , elemProto; if( isExtendNativeSave && (elem = document.createElement(nodeName)) && (elemProto = webshims.getPrototypeOf(elem)) && UNKNOWN !== elemProto && ( !elem[prop] || !has.call(elem, prop) ) ){ var sup = elem[prop]; desc._supvalue = function(){ if(sup && sup.apply){ return sup.apply(this, arguments); } return sup; }; elemProto[prop] = desc.value; } else { desc._supvalue = function(){ var data = elementData(this, 'propValue'); if(data && data[prop] && data[prop].apply){ return data[prop].apply(this, arguments); } return data && data[prop]; }; initProp.extendValue(nodeName, prop, desc.value); } desc.value._supvalue = desc._supvalue; }; })(); var initProp = (function(){ var initProps = {}; webshims.addReady(function(context, contextElem){ var nodeNameCache = {}; var getElementsByName = function(name){ if(!nodeNameCache[name]){ nodeNameCache[name] = $(context.getElementsByTagName(name)); if(contextElem[0] && $.nodeName(contextElem[0], name)){ nodeNameCache[name] = nodeNameCache[name].add(contextElem); } } }; $.each(initProps, function(name, fns){ getElementsByName(name); if(!fns || !fns.forEach){ webshims.warn('Error: with '+ name +'-property. methods: '+ fns); return; } fns.forEach(function(fn){ nodeNameCache[name].each(fn); }); }); nodeNameCache = null; }); var tempCache; var emptyQ = $([]); var createNodeNameInit = function(nodeName, fn){ if(!initProps[nodeName]){ initProps[nodeName] = [fn]; } else { initProps[nodeName].push(fn); } if($.isDOMReady){ (tempCache || $( document.getElementsByTagName(nodeName) )).each(fn); } }; var elementExtends = {}; return { createTmpCache: function(nodeName){ if($.isDOMReady){ tempCache = tempCache || $( document.getElementsByTagName(nodeName) ); } return tempCache || emptyQ; }, flushTmpCache: function(){ tempCache = null; }, content: function(nodeName, prop){ createNodeNameInit(nodeName, function(){ var val = $.attr(this, prop); if(val != null){ $.attr(this, prop, val); } }); }, createElement: function(nodeName, fn){ createNodeNameInit(nodeName, fn); }, extendValue: function(nodeName, prop, value){ createNodeNameInit(nodeName, function(){ $(this).each(function(){ var data = elementData(this, 'propValue', {}); data[prop] = this[prop]; this[prop] = value; }); }); } }; })(); var createPropDefault = function(descs, removeType){ if(descs.defaultValue === undefined){ descs.defaultValue = ''; } if(!descs.removeAttr){ descs.removeAttr = { value: function(){ descs[removeType || 'prop'].set.call(this, descs.defaultValue); descs.removeAttr._supvalue.call(this); } }; } if(!descs.attr){ descs.attr = {}; } }; $.extend(webshims, { getID: (function(){ var ID = new Date().getTime(); return function(elem){ elem = $(elem); var id = elem.prop('id'); if(!id){ ID++; id = 'ID-'+ ID; elem.eq(0).prop('id', id); } return id; }; })(), implement: function(elem, type){ var data = elementData(elem, 'implemented') || elementData(elem, 'implemented', {}); if(data[type]){ webshims.warn(type +' already implemented for element #'+elem.id); return false; } data[type] = true; return true; }, extendUNDEFProp: function(obj, props){ $.each(props, function(name, prop){ if( !(name in obj) ){ obj[name] = prop; } }); }, getOptions: (function(){ var normalName = /\-([a-z])/g; var regs = {}; var nameRegs = {}; var regFn = function(f, upper){ return upper.toLowerCase(); }; var nameFn = function(f, dashed){ return dashed.toUpperCase(); }; return function(elem, name, bases, stringAllowed){ if(nameRegs[name]){ name = nameRegs[name]; } else { nameRegs[name] = name.replace(normalName, nameFn); name = nameRegs[name]; } var data = elementData(elem, 'cfg'+name); var dataName; var cfg = {}; if(data){ return data; } data = $(elem).data(); if(data && typeof data[name] == 'string'){ if(stringAllowed){ return elementData(elem, 'cfg'+name, data[name]); } webshims.error('data-'+ name +' attribute has to be a valid JSON, was: '+ data[name]); } if(!bases){ bases = [true, {}]; } else if(!Array.isArray(bases)){ bases = [true, {}, bases]; } else { bases.unshift(true, {}); } if(data && typeof data[name] == 'object'){ bases.push(data[name]); } if(!regs[name]){ regs[name] = new RegExp('^'+ name +'([A-Z])'); } for(dataName in data){ if(regs[name].test(dataName)){ cfg[dataName.replace(regs[name], regFn)] = data[dataName]; } } bases.push(cfg); return elementData(elem, 'cfg'+name, $.extend.apply($, bases)); }; })(), //http://www.w3.org/TR/html5/common-dom-interfaces.html#reflect createPropDefault: createPropDefault, data: elementData, moveToFirstEvent: function(elem, eventType, bindType){ var events = ($._data(elem, 'events') || {})[eventType]; var fn; if(events && events.length > 1){ fn = events.pop(); if(!bindType){ bindType = 'bind'; } if(bindType == 'bind' && events.delegateCount){ events.splice( events.delegateCount, 0, fn); } else { events.unshift( fn ); } } elem = null; }, addShadowDom: (function(){ var resizeTimer; var lastHeight; var lastWidth; var $window = $(window); var docObserve = { init: false, runs: 0, test: function(){ var height = docObserve.getHeight(); var width = docObserve.getWidth(); if(height != docObserve.height || width != docObserve.width){ docObserve.height = height; docObserve.width = width; docObserve.handler({type: 'docresize'}); docObserve.runs++; if(docObserve.runs < 9){ setTimeout(docObserve.test, 90); } } else { docObserve.runs = 0; } }, handler: (function(){ var trigger = function(){ $(document).triggerHandler('updateshadowdom'); }; return function(e){ clearTimeout(resizeTimer); resizeTimer = setTimeout(function(){ if(e.type == 'resize'){ var width = $window.width(); var height = $window.width(); if(height == lastHeight && width == lastWidth){ return; } lastHeight = height; lastWidth = width; docObserve.height = docObserve.getHeight(); docObserve.width = docObserve.getWidth(); } if(window.requestAnimationFrame){ requestAnimationFrame(trigger); } else { setTimeout(trigger, 0); } }, (e.type == 'resize' && !window.requestAnimationFrame) ? 50 : 9); }; })(), _create: function(){ $.each({ Height: "getHeight", Width: "getWidth" }, function(name, type){ var body = document.body; var doc = document.documentElement; docObserve[type] = function (){ return Math.max( body[ "scroll" + name ], doc[ "scroll" + name ], body[ "offset" + name ], doc[ "offset" + name ], doc[ "client" + name ] ); }; }); }, start: function(){ if(!this.init && document.body){ this.init = true; this._create(); this.height = docObserve.getHeight(); this.width = docObserve.getWidth(); setInterval(this.test, 999); $(this.test); if($.support.boxSizing == null){ $(function(){ if($.support.boxSizing){ docObserve.handler({type: 'boxsizing'}); } }); } webshims.ready('WINDOWLOAD', this.test); $(document).on('updatelayout.webshim pageinit popupafteropen panelbeforeopen tabsactivate collapsibleexpand shown.bs.modal shown.bs.collapse slid.bs.carousel', this.handler); $(window).on('resize', this.handler); } } }; webshims.docObserve = function(){ webshims.ready('DOM', function(){ docObserve.start(); }); }; return function(nativeElem, shadowElem, opts){ if(nativeElem && shadowElem){ opts = opts || {}; if(nativeElem.jquery){ nativeElem = nativeElem[0]; } if(shadowElem.jquery){ shadowElem = shadowElem[0]; } var nativeData = $.data(nativeElem, dataID) || $.data(nativeElem, dataID, {}); var shadowData = $.data(shadowElem, dataID) || $.data(shadowElem, dataID, {}); var shadowFocusElementData = {}; if(!opts.shadowFocusElement){ opts.shadowFocusElement = shadowElem; } else if(opts.shadowFocusElement){ if(opts.shadowFocusElement.jquery){ opts.shadowFocusElement = opts.shadowFocusElement[0]; } shadowFocusElementData = $.data(opts.shadowFocusElement, dataID) || $.data(opts.shadowFocusElement, dataID, shadowFocusElementData); } $(nativeElem).on('remove', function(e){ if (!e.originalEvent) { setTimeout(function(){ $(shadowElem).remove(); }, 4); } }); nativeData.hasShadow = shadowElem; shadowFocusElementData.nativeElement = shadowData.nativeElement = nativeElem; shadowFocusElementData.shadowData = shadowData.shadowData = nativeData.shadowData = { nativeElement: nativeElem, shadowElement: shadowElem, shadowFocusElement: opts.shadowFocusElement }; if(opts.shadowChilds){ opts.shadowChilds.each(function(){ elementData(this, 'shadowData', shadowData.shadowData); }); } if(opts.data){ shadowFocusElementData.shadowData.data = shadowData.shadowData.data = nativeData.shadowData.data = opts.data; } opts = null; } webshims.docObserve(); }; })(), propTypes: { standard: function(descs, name){ createPropDefault(descs); if(descs.prop){return;} descs.prop = { set: function(val){ descs.attr.set.call(this, ''+val); }, get: function(){ return descs.attr.get.call(this) || descs.defaultValue; } }; }, "boolean": function(descs, name){ createPropDefault(descs); if(descs.prop){return;} descs.prop = { set: function(val){ if(val){ descs.attr.set.call(this, ""); } else { descs.removeAttr.value.call(this); } }, get: function(){ return descs.attr.get.call(this) != null; } }; }, "src": (function(){ var anchor = document.createElement('a'); anchor.style.display = "none"; return function(descs, name){ createPropDefault(descs); if(descs.prop){return;} descs.prop = { set: function(val){ descs.attr.set.call(this, val); }, get: function(){ var href = this.getAttribute(name); var ret; if(href == null){return '';} anchor.setAttribute('href', href+'' ); if(!supportHrefNormalized){ try { $(anchor).insertAfter(this); ret = anchor.getAttribute('href', 4); } catch(er){ ret = anchor.getAttribute('href', 4); } $(anchor).detach(); } return ret || anchor.href; } }; }; })(), enumarated: function(descs, name){ createPropDefault(descs); if(descs.prop){return;} descs.prop = { set: function(val){ descs.attr.set.call(this, val); }, get: function(){ var val = (descs.attr.get.call(this) || '').toLowerCase(); if(!val || descs.limitedTo.indexOf(val) == -1){ val = descs.defaultValue; } return val; } }; } // ,unsignedLong: $.noop // ,"doubble": $.noop // ,"long": $.noop // ,tokenlist: $.noop // ,settableTokenlist: $.noop }, reflectProperties: function(nodeNames, props){ if(typeof props == 'string'){ props = props.split(listReg); } props.forEach(function(prop){ webshims.defineNodeNamesProperty(nodeNames, prop, { prop: { set: function(val){ $.attr(this, prop, val); }, get: function(){ return $.attr(this, prop) || ''; } } }); }); }, defineNodeNameProperty: function(nodeName, prop, descs){ havePolyfill[prop] = true; if(descs.reflect){ if(descs.propType && !webshims.propTypes[descs.propType]){ webshims.error('could not finde propType '+ descs.propType); } else { webshims.propTypes[descs.propType || 'standard'](descs, prop); } } ['prop', 'attr', 'removeAttr'].forEach(function(type){ var desc = descs[type]; if(desc){ if(type === 'prop'){ desc = $.extend({writeable: true}, desc); } else { desc = $.extend({}, desc, {writeable: true}); } extendQ[type](nodeName, prop, desc); if(nodeName != '*' && webshims.cfg.extendNative && type == 'prop' && desc.value && $.isFunction(desc.value)){ extendNativeValue(nodeName, prop, desc); } descs[type] = desc; } }); if(descs.initAttr){ initProp.content(nodeName, prop); } return descs; }, defineNodeNameProperties: function(name, descs, propType, _noTmpCache){ var olddesc; for(var prop in descs){ if(!_noTmpCache && descs[prop].initAttr){ initProp.createTmpCache(name); } if(propType){ if(descs[prop][propType]){ //webshims.log('override: '+ name +'['+prop +'] for '+ propType); } else { descs[prop][propType] = {}; ['value', 'set', 'get'].forEach(function(copyProp){ if(copyProp in descs[prop]){ descs[prop][propType][copyProp] = descs[prop][copyProp]; delete descs[prop][copyProp]; } }); } } descs[prop] = webshims.defineNodeNameProperty(name, prop, descs[prop]); } if(!_noTmpCache){ initProp.flushTmpCache(); } return descs; }, createElement: function(nodeName, create, descs){ var ret; if($.isFunction(create)){ create = { after: create }; } initProp.createTmpCache(nodeName); if(create.before){ initProp.createElement(nodeName, create.before); } if(descs){ ret = webshims.defineNodeNameProperties(nodeName, descs, false, true); } if(create.after){ initProp.createElement(nodeName, create.after); } initProp.flushTmpCache(); return ret; }, onNodeNamesPropertyModify: function(nodeNames, props, desc, only){ if(typeof nodeNames == 'string'){ nodeNames = nodeNames.split(listReg); } if($.isFunction(desc)){ desc = {set: desc}; } nodeNames.forEach(function(name){ if(!modifyProps[name]){ modifyProps[name] = {}; } if(typeof props == 'string'){ props = props.split(listReg); } if(desc.initAttr){ initProp.createTmpCache(name); } props.forEach(function(prop){ if(!modifyProps[name][prop]){ modifyProps[name][prop] = []; havePolyfill[prop] = true; } if(desc.set){ if(only){ desc.set.only = only; } modifyProps[name][prop].push(desc.set); } if(desc.initAttr){ initProp.content(name, prop); } }); initProp.flushTmpCache(); }); }, defineNodeNamesBooleanProperty: function(elementNames, prop, descs){ if(!descs){ descs = {}; } if($.isFunction(descs)){ descs.set = descs; } webshims.defineNodeNamesProperty(elementNames, prop, { attr: { set: function(val){ if(descs.useContentAttribute){ webshims.contentAttr(this, prop, val); } else { this.setAttribute(prop, val); } if(descs.set){ descs.set.call(this, true); } }, get: function(){ var ret = (descs.useContentAttribute) ? webshims.contentAttr(this, prop) : this.getAttribute(prop); return (ret == null) ? undefined : prop; } }, removeAttr: { value: function(){ this.removeAttribute(prop); if(descs.set){ descs.set.call(this, false); } } }, reflect: true, propType: 'boolean', initAttr: descs.initAttr || false }); }, contentAttr: function(elem, name, val){ if(!elem.nodeName){return;} var attr; if(val === undefined){ attr = (elem.attributes[name] || {}); val = attr.specified ? attr.value : null; return (val == null) ? undefined : val; } if(typeof val == 'boolean'){ if(!val){ elem.removeAttribute(name); } else { elem.setAttribute(name, name); } } else { elem.setAttribute(name, val); } }, activeLang: (function(){ var curLang = []; var langDatas = []; var loading = {}; var load = function(src, obj, loadingLang){ obj._isLoading = true; if(loading[src]){ loading[src].push(obj); } else { loading[src] = [obj]; webshims.loader.loadScript(src, function(){ if(loadingLang == curLang.join()){ $.each(loading[src], function(i, obj){ select(obj); }); } delete loading[src]; }); } }; var select = function(obj){ var oldLang = obj.__active; var selectLang = function(i, lang){ obj._isLoading = false; if(obj[lang] || obj.availableLangs.indexOf(lang) != -1){ if(obj[lang]){ obj.__active = obj[lang]; obj.__activeName = lang; } else { load(obj.langSrc+lang, obj, curLang.join()); } return false; } }; $.each(curLang, selectLang); if(!obj.__active){ obj.__active = obj['']; obj.__activeName = ''; } if(oldLang != obj.__active){ $(obj).trigger('change'); } }; return function(lang){ var shortLang; if(typeof lang == 'string'){ if(curLang[0] != lang){ curLang = [lang]; shortLang = curLang[0].split('-')[0]; if(shortLang && shortLang != lang){ curLang.push(shortLang); } langDatas.forEach(select); } } else if(typeof lang == 'object'){ if(!lang.__active){ langDatas.push(lang); select(lang); } return lang.__active; } return curLang[0]; }; })() }); $.each({ defineNodeNamesProperty: 'defineNodeNameProperty', defineNodeNamesProperties: 'defineNodeNameProperties', createElements: 'createElement' }, function(name, baseMethod){ webshims[name] = function(names, a, b, c){ if(typeof names == 'string'){ names = names.split(listReg); } var retDesc = {}; names.forEach(function(nodeName){ retDesc[nodeName] = webshims[baseMethod](nodeName, a, b, c); }); return retDesc; }; }); webshims.isReady('webshimLocalization', true); //html5a11y + hidden attribute (function(){ if(('content' in document.createElement('template'))){return;} $(function(){ var main = $('main').attr({role: 'main'}); if(main.length > 1){ webshims.error('only one main element allowed in document'); } else if(main.is('article *, section *')) { webshims.error('main not allowed inside of article/section elements'); } }); if(('hidden' in document.createElement('a'))){ return; } webshims.defineNodeNamesBooleanProperty(['*'], 'hidden'); var elemMappings = { article: "article", aside: "complementary", section: "region", nav: "navigation", address: "contentinfo" }; var addRole = function(elem, role){ var hasRole = elem.getAttribute('role'); if (!hasRole) { elem.setAttribute('role', role); } }; $.webshims.addReady(function(context, contextElem){ $.each(elemMappings, function(name, role){ var elems = $(name, context).add(contextElem.filter(name)); for (var i = 0, len = elems.length; i < len; i++) { addRole(elems[i], role); } }); if (context === document) { var header = document.getElementsByTagName('header')[0]; var footers = document.getElementsByTagName('footer'); var footerLen = footers.length; if (header && !$(header).closest('section, article')[0]) { addRole(header, 'banner'); } if (!footerLen) { return; } var footer = footers[footerLen - 1]; if (!$(footer).closest('section, article')[0]) { addRole(footer, 'contentinfo'); } } }); })(); }); ;(function(Modernizr, webshims){ "use strict"; var hasNative = Modernizr.audio && Modernizr.video; var supportsLoop = false; var bugs = webshims.bugs; var swfType = 'mediaelement-jaris'; var loadSwf = function(){ webshims.ready(swfType, function(){ if(!webshims.mediaelement.createSWF){ webshims.mediaelement.loadSwf = true; webshims.reTest([swfType], hasNative); } }); }; var wsCfg = webshims.cfg; var options = wsCfg.mediaelement; var hasSwf; if(!options){ webshims.error("mediaelement wasn't implemented but loaded"); return; } if(hasNative){ var videoElem = document.createElement('video'); Modernizr.videoBuffered = ('buffered' in videoElem); Modernizr.mediaDefaultMuted = ('defaultMuted' in videoElem); supportsLoop = ('loop' in videoElem); Modernizr.mediaLoop = supportsLoop; webshims.capturingEvents(['play', 'playing', 'waiting', 'paused', 'ended', 'durationchange', 'loadedmetadata', 'canplay', 'volumechange']); if( !Modernizr.videoBuffered || !supportsLoop || (!Modernizr.mediaDefaultMuted && navigator.userAgent.indexOf('MSIE') != -1 && 'ActiveXObject' in window) ){ webshims.addPolyfill('mediaelement-native-fix', { d: ['dom-support'] }); webshims.loader.loadList(['mediaelement-native-fix']); } } if(Modernizr.track && !bugs.track){ (function(){ if(!bugs.track){ if(window.VTTCue && !window.TextTrackCue){ window.TextTrackCue = window.VTTCue; } else if(!window.VTTCue){ window.VTTCue = window.TextTrackCue; } try { new VTTCue(2, 3, ''); } catch(e){ bugs.track = true; } } })(); } webshims.register('mediaelement-core', function($, webshims, window, document, undefined, options){ hasSwf = swfmini.hasFlashPlayerVersion('10.0.3'); var mediaelement = webshims.mediaelement; mediaelement.parseRtmp = function(data){ var src = data.src.split('://'); var paths = src[1].split('/'); var i, len, found; data.server = src[0]+'://'+paths[0]+'/'; data.streamId = []; for(i = 1, len = paths.length; i < len; i++){ if(!found && paths[i].indexOf(':') !== -1){ paths[i] = paths[i].split(':')[1]; found = true; } if(!found){ data.server += paths[i]+'/'; } else { data.streamId.push(paths[i]); } } if(!data.streamId.length){ webshims.error('Could not parse rtmp url'); } data.streamId = data.streamId.join('/'); }; var getSrcObj = function(elem, nodeName){ elem = $(elem); var src = {src: elem.attr('src') || '', elem: elem, srcProp: elem.prop('src')}; var tmp; if(!src.src){return src;} tmp = elem.attr('data-server'); if(tmp != null){ src.server = tmp; } tmp = elem.attr('type') || elem.attr('data-type'); if(tmp){ src.type = tmp; src.container = $.trim(tmp.split(';')[0]); } else { if(!nodeName){ nodeName = elem[0].nodeName.toLowerCase(); if(nodeName == 'source'){ nodeName = (elem.closest('video, audio')[0] || {nodeName: 'video'}).nodeName.toLowerCase(); } } if(src.server){ src.type = nodeName+'/rtmp'; src.container = nodeName+'/rtmp'; } else { tmp = mediaelement.getTypeForSrc( src.src, nodeName, src ); if(tmp){ src.type = tmp; src.container = tmp; } } } if(!src.container){ $(elem).attr('data-wsrecheckmimetype', ''); } tmp = elem.attr('media'); if(tmp){ src.media = tmp; } if(src.type == 'audio/rtmp' || src.type == 'video/rtmp'){ if(src.server){ src.streamId = src.src; } else { mediaelement.parseRtmp(src); } } return src; }; var hasYt = !hasSwf && ('postMessage' in window) && hasNative; var loadTrackUi = function(){ if(loadTrackUi.loaded){return;} loadTrackUi.loaded = true; if(!options.noAutoTrack){ webshims.ready('WINDOWLOAD', function(){ loadThird(); webshims.loader.loadList(['track-ui']); }); } }; var loadYt = (function(){ var loaded; return function(){ if(loaded || !hasYt){return;} loaded = true; webshims.loader.loadScript("https://www.youtube.com/player_api"); $(function(){ webshims._polyfill(["mediaelement-yt"]); }); }; })(); var loadThird = function(){ if(hasSwf){ loadSwf(); } else { loadYt(); } }; webshims.addPolyfill('mediaelement-yt', { test: !hasYt, d: ['dom-support'] }); mediaelement.mimeTypes = { audio: { //ogm shouldn´t be used! 'audio/ogg': ['ogg','oga', 'ogm'], 'audio/ogg;codecs="opus"': 'opus', 'audio/mpeg': ['mp2','mp3','mpga','mpega'], 'audio/mp4': ['mp4','mpg4', 'm4r', 'm4a', 'm4p', 'm4b', 'aac'], 'audio/wav': ['wav'], 'audio/3gpp': ['3gp','3gpp'], 'audio/webm': ['webm'], 'audio/fla': ['flv', 'f4a', 'fla'], 'application/x-mpegURL': ['m3u8', 'm3u'] }, video: { //ogm shouldn´t be used! 'video/ogg': ['ogg','ogv', 'ogm'], 'video/mpeg': ['mpg','mpeg','mpe'], 'video/mp4': ['mp4','mpg4', 'm4v'], 'video/quicktime': ['mov','qt'], 'video/x-msvideo': ['avi'], 'video/x-ms-asf': ['asf', 'asx'], 'video/flv': ['flv', 'f4v'], 'video/3gpp': ['3gp','3gpp'], 'video/webm': ['webm'], 'application/x-mpegURL': ['m3u8', 'm3u'], 'video/MP2T': ['ts'] } } ; mediaelement.mimeTypes.source = $.extend({}, mediaelement.mimeTypes.audio, mediaelement.mimeTypes.video); mediaelement.getTypeForSrc = function(src, nodeName){ if(src.indexOf('youtube.com/watch?') != -1 || src.indexOf('youtube.com/v/') != -1){ return 'video/youtube'; } if(src.indexOf('rtmp') === 0){ return nodeName+'/rtmp'; } src = src.split('?')[0].split('#')[0].split('.'); src = src[src.length - 1]; var mt; $.each(mediaelement.mimeTypes[nodeName], function(mimeType, exts){ if(exts.indexOf(src) !== -1){ mt = mimeType; return false; } }); return mt; }; mediaelement.srces = function(mediaElem, srces){ mediaElem = $(mediaElem); if(!srces){ srces = []; var nodeName = mediaElem[0].nodeName.toLowerCase(); var src = getSrcObj(mediaElem, nodeName); if(!src.src){ $('source', mediaElem).each(function(){ src = getSrcObj(this, nodeName); if(src.src){srces.push(src);} }); } else { srces.push(src); } return srces; } else { webshims.error('setting sources was removed.'); } }; $.fn.loadMediaSrc = function(){ webshims.error('loadMediaSrc was removed.'); }; mediaelement.swfMimeTypes = ['video/3gpp', 'video/x-msvideo', 'video/quicktime', 'video/x-m4v', 'video/mp4', 'video/m4p', 'video/x-flv', 'video/flv', 'audio/mpeg', 'audio/aac', 'audio/mp4', 'audio/x-m4a', 'audio/m4a', 'audio/mp3', 'audio/x-fla', 'audio/fla', 'youtube/flv', 'video/jarisplayer', 'jarisplayer/jarisplayer', 'video/youtube', 'video/rtmp', 'audio/rtmp']; mediaelement.canThirdPlaySrces = function(mediaElem, srces){ var ret = ''; if(hasSwf || hasYt){ mediaElem = $(mediaElem); srces = srces || mediaelement.srces(mediaElem); $.each(srces, function(i, src){ if(src.container && src.src && ((hasSwf && mediaelement.swfMimeTypes.indexOf(src.container) != -1) || (hasYt && src.container == 'video/youtube'))){ ret = src; return false; } }); } return ret; }; var nativeCanPlayType = {}; mediaelement.canNativePlaySrces = function(mediaElem, srces){ var ret = ''; if(hasNative){ mediaElem = $(mediaElem); var nodeName = (mediaElem[0].nodeName || '').toLowerCase(); var nativeCanPlay = (nativeCanPlayType[nodeName] || {prop: {_supvalue: false}}).prop._supvalue || mediaElem[0].canPlayType; if(!nativeCanPlay){return ret;} srces = srces || mediaelement.srces(mediaElem); $.each(srces, function(i, src){ if(src.type && nativeCanPlay.call(mediaElem[0], src.type) ){ ret = src; return false; } }); } return ret; }; var emptyType = (/^\s*application\/octet\-stream\s*$/i); var getRemoveEmptyType = function(){ var ret = emptyType.test($.attr(this, 'type') || ''); if(ret){ $(this).removeAttr('type'); } return ret; }; mediaelement.setError = function(elem, message){ if($('source', elem).filter(getRemoveEmptyType).length){ webshims.error('"application/octet-stream" is a useless mimetype for audio/video. Please change this attribute.'); try { $(elem).mediaLoad(); } catch(er){} } else { if(!message){ message = "can't play sources"; } $(elem).pause().data('mediaerror', message); webshims.error('mediaelementError: '+ message); setTimeout(function(){ if($(elem).data('mediaerror')){ $(elem).addClass('media-error').trigger('mediaerror'); } }, 1); } }; var handleThird = (function(){ var requested; var readyType = hasSwf ? swfType : 'mediaelement-yt'; return function( mediaElem, ret, data ){ //readd to ready webshims.ready(readyType, function(){ if(mediaelement.createSWF && $(mediaElem).parent()[0]){ mediaelement.createSWF( mediaElem, ret, data ); } else if(!requested) { requested = true; loadThird(); handleThird( mediaElem, ret, data ); } }); if(!requested && hasYt && !mediaelement.createSWF){ loadYt(); } }; })(); var stepSources = function(elem, data, useSwf, _srces, _noLoop){ var ret; if(useSwf || (useSwf !== false && data && data.isActive == 'third')){ ret = mediaelement.canThirdPlaySrces(elem, _srces); if(!ret){ if(_noLoop){ mediaelement.setError(elem, false); } else { stepSources(elem, data, false, _srces, true); } } else { handleThird(elem, ret, data); } } else { ret = mediaelement.canNativePlaySrces(elem, _srces); if(!ret){ if(_noLoop){ mediaelement.setError(elem, false); if(data && data.isActive == 'third') { mediaelement.setActive(elem, 'html5', data); } } else { stepSources(elem, data, true, _srces, true); } } else if(data && data.isActive == 'third') { mediaelement.setActive(elem, 'html5', data); } } }; var stopParent = /^(?:embed|object|datalist)$/i; var selectSource = function(elem, data){ var baseData = webshims.data(elem, 'mediaelementBase') || webshims.data(elem, 'mediaelementBase', {}); var _srces = mediaelement.srces(elem); var parent = elem.parentNode; clearTimeout(baseData.loadTimer); $(elem).removeClass('media-error'); $.data(elem, 'mediaerror', false); if(!_srces.length || !parent || parent.nodeType != 1 || stopParent.test(parent.nodeName || '')){return;} data = data || webshims.data(elem, 'mediaelement'); if(mediaelement.sortMedia){ _srces.sort(mediaelement.sortMedia); } stepSources(elem, data, options.preferFlash || undefined, _srces); }; mediaelement.selectSource = selectSource; $(document).on('ended', function(e){ var data = webshims.data(e.target, 'mediaelement'); if( supportsLoop && (!data || data.isActive == 'html5') && !$.prop(e.target, 'loop')){return;} setTimeout(function(){ if( $.prop(e.target, 'paused') || !$.prop(e.target, 'loop') ){return;} $(e.target).prop('currentTime', 0).play(); }, 1); }); var handleMedia = false; var initMediaElements = function(){ var testFixMedia = function(){ if(webshims.implement(this, 'mediaelement')){ selectSource(this); if(!Modernizr.mediaDefaultMuted && $.attr(this, 'muted') != null){ $.prop(this, 'muted', true); } } }; webshims.ready('dom-support', function(){ handleMedia = true; if(!supportsLoop){ webshims.defineNodeNamesBooleanProperty(['audio', 'video'], 'loop'); } ['audio', 'video'].forEach(function(nodeName){ var supLoad; supLoad = webshims.defineNodeNameProperty(nodeName, 'load', { prop: { value: function(){ var data = webshims.data(this, 'mediaelement'); selectSource(this, data); if(hasNative && (!data || data.isActive == 'html5') && supLoad.prop._supvalue){ supLoad.prop._supvalue.apply(this, arguments); } if(!loadTrackUi.loaded && $('track', this).length){ loadTrackUi(); } $(this).triggerHandler('wsmediareload'); } } }); nativeCanPlayType[nodeName] = webshims.defineNodeNameProperty(nodeName, 'canPlayType', { prop: { value: function(type){ var ret = ''; if(hasNative && nativeCanPlayType[nodeName].prop._supvalue){ ret = nativeCanPlayType[nodeName].prop._supvalue.call(this, type); if(ret == 'no'){ ret = ''; } } if(!ret && hasSwf){ type = $.trim((type || '').split(';')[0]); if(mediaelement.swfMimeTypes.indexOf(type) != -1){ ret = 'maybe'; } } return ret; } } }); }); webshims.onNodeNamesPropertyModify(['audio', 'video'], ['src', 'poster'], { set: function(){ var elem = this; var baseData = webshims.data(elem, 'mediaelementBase') || webshims.data(elem, 'mediaelementBase', {}); clearTimeout(baseData.loadTimer); baseData.loadTimer = setTimeout(function(){ selectSource(elem); elem = null; }, 9); } }); webshims.addReady(function(context, insertedElement){ var media = $('video, audio', context) .add(insertedElement.filter('video, audio')) .each(testFixMedia) ; if(!loadTrackUi.loaded && $('track', media).length){ loadTrackUi(); } media = null; }); }); if(hasNative && !handleMedia){ webshims.addReady(function(context, insertedElement){ if(!handleMedia){ $('video, audio', context) .add(insertedElement.filter('video, audio')) .each(function(){ if(!mediaelement.canNativePlaySrces(this)){ loadThird(); handleMedia = true; return false; } }) ; } }); } }; //set native implementation ready, before swf api is retested if(hasNative){ webshims.isReady('mediaelement-core', true); initMediaElements(); webshims.ready('WINDOWLOAD mediaelement', loadThird); } else { webshims.ready(swfType, initMediaElements); } webshims.ready('track', loadTrackUi); }); })(Modernizr, webshims); ;webshims.register('mediaelement-jaris', function($, webshims, window, document, undefined, options){ "use strict"; var mediaelement = webshims.mediaelement; var swfmini = window.swfmini; var hasNative = Modernizr.audio && Modernizr.video; var hasFlash = swfmini.hasFlashPlayerVersion('9.0.115'); var loadedSwf = 0; var needsLoadPreload = 'ActiveXObject' in window && hasNative; var getProps = { paused: true, ended: false, currentSrc: '', duration: window.NaN, readyState: 0, networkState: 0, videoHeight: 0, videoWidth: 0, seeking: false, error: null, buffered: { start: function(index){ if(index){ webshims.error('buffered index size error'); return; } return 0; }, end: function(index){ if(index){ webshims.error('buffered index size error'); return; } return 0; }, length: 0 } }; var getPropKeys = Object.keys(getProps); var getSetProps = { currentTime: 0, volume: 1, muted: false }; var getSetPropKeys = Object.keys(getSetProps); var playerStateObj = $.extend({ isActive: 'html5', activating: 'html5', wasSwfReady: false, _bufferedEnd: 0, _bufferedStart: 0, currentTime: 0, _ppFlag: undefined, _calledMeta: false, lastDuration: 0 }, getProps, getSetProps); var getSwfDataFromElem = function(elem){ try { (elem.nodeName); } catch(er){ return null; } var data = webshims.data(elem, 'mediaelement'); return (data && data.isActive== 'third') ? data : null; }; var trigger = function(elem, evt){ evt = $.Event(evt); evt.preventDefault(); $.event.trigger(evt, undefined, elem); }; var playerSwfPath = options.playerPath || webshims.cfg.basePath + "swf/" + (options.playerName || 'JarisFLVPlayer.swf'); webshims.extendUNDEFProp(options.params, { allowscriptaccess: 'always', allowfullscreen: 'true', wmode: 'transparent', allowNetworking: 'all' }); webshims.extendUNDEFProp(options.vars, { controltype: '1', jsapi: '1' }); webshims.extendUNDEFProp(options.attrs, { bgcolor: '#000000' }); var setReadyState = function(readyState, data){ if(readyState < 3){ clearTimeout(data._canplaythroughTimer); } if(readyState >= 3 && data.readyState < 3){ data.readyState = readyState; trigger(data._elem, 'canplay'); if(!data.paused){ trigger(data._elem, 'playing'); } clearTimeout(data._canplaythroughTimer); data._canplaythroughTimer = setTimeout(function(){ setReadyState(4, data); }, 4000); } if(readyState >= 4 && data.readyState < 4){ data.readyState = readyState; trigger(data._elem, 'canplaythrough'); } data.readyState = readyState; }; var callSeeked = function(data){ if(data.seeking && Math.abs(data.currentTime - data._lastSeektime) < 2){ data.seeking = false; $(data._elem).triggerHandler('seeked'); } }; mediaelement.jarisEvent = {}; var localConnectionTimer; var onEvent = { onPlayPause: function(jaris, data, override){ var playing, type; if(override == null){ try { playing = data.api.api_get("isPlaying"); } catch(e){} } else { playing = override; } if(playing == data.paused){ data.paused = !playing; type = data.paused ? 'pause' : 'play'; data._ppFlag = true; trigger(data._elem, type); if(data.readyState < 3){ setReadyState(3, data); } if(!data.paused){ trigger(data._elem, 'playing'); } } }, onSeek: function(jaris, data){ data._lastSeektime = jaris.seekTime; data.seeking = true; $(data._elem).triggerHandler('seeking'); clearTimeout(data._seekedTimer); data._seekedTimer = setTimeout(function(){ callSeeked(data); data.seeking = false; }, 300); }, onConnectionFailed: function(){ webshims.error('media error'); }, onNotBuffering: function(jaris, data){ setReadyState(3, data); }, onDataInitialized: function(jaris, data){ var oldDur = data.duration; var durDelta; data.duration = jaris.duration; if(oldDur == data.duration || isNaN(data.duration)){return;} if(data._calledMeta && ((durDelta = Math.abs(data.lastDuration - data.duration)) < 2)){return;} data.videoHeight = jaris.height; data.videoWidth = jaris.width; if(!data.networkState){ data.networkState = 2; } if(data.readyState < 1){ setReadyState(1, data); } clearTimeout(data._durationChangeTimer); if(data._calledMeta && data.duration){ data._durationChangeTimer = setTimeout(function(){ data.lastDuration = data.duration; trigger(data._elem, 'durationchange'); }, durDelta > 50 ? 0 : durDelta > 9 ? 9 : 99); } else { data.lastDuration = data.duration; if(data.duration){ trigger(data._elem, 'durationchange'); } if(!data._calledMeta){ trigger(data._elem, 'loadedmetadata'); } } data._calledMeta = true; }, onBuffering: function(jaris, data){ if(data.ended){ data.ended = false; } setReadyState(1, data); trigger(data._elem, 'waiting'); }, onTimeUpdate: function(jaris, data){ if(data.ended){ data.ended = false; } if(data.readyState < 3){ setReadyState(3, data); trigger(data._elem, 'playing'); } if(data.seeking){ callSeeked(data); } trigger(data._elem, 'timeupdate'); }, onProgress: function(jaris, data){ if(data.ended){ data.ended = false; } if(!data.duration || isNaN(data.duration)){ return; } var percentage = jaris.loaded / jaris.total; if(percentage > 0.02 && percentage < 0.2){ setReadyState(3, data); } else if(percentage > 0.2){ if(percentage > 0.99){ data.networkState = 1; } setReadyState(4, data); } if(data._bufferedEnd && (data._bufferedEnd > percentage)){ data._bufferedStart = data.currentTime || 0; } data._bufferedEnd = percentage; data.buffered.length = 1; $.event.trigger('progress', undefined, data._elem, true); }, onPlaybackFinished: function(jaris, data){ if(data.readyState < 4){ setReadyState(4, data); } data.ended = true; trigger(data._elem, 'ended'); }, onVolumeChange: function(jaris, data){ if(data.volume != jaris.volume || data.muted != jaris.mute){ data.volume = jaris.volume; data.muted = jaris.mute; trigger(data._elem, 'volumechange'); } }, ready: (function(){ var testAPI = function(data){ var passed = true; try { data.api.api_get('volume'); } catch(er){ passed = false; } return passed; }; return function(jaris, data){ var i = 0; var doneFn = function(){ if(i > 9){ data.tryedReframeing = 0; return; } i++; data.tryedReframeing++; if(testAPI(data)){ data.wasSwfReady = true; data.tryedReframeing = 0; startAutoPlay(data); workActionQueue(data); } else if(data.tryedReframeing < 6) { if(data.tryedReframeing < 3){ data.reframeTimer = setTimeout(doneFn, 9); data.shadowElem.css({overflow: 'visible'}); setTimeout(function(){ data.shadowElem.css({overflow: 'hidden'}); }, 1); } else { data.shadowElem.css({overflow: 'hidden'}); $(data._elem).mediaLoad(); } } else { clearTimeout(data.reframeTimer); webshims.error("reframing error"); } }; if(!data || !data.api){return;} if(!data.tryedReframeing){ data.tryedReframeing = 0; } clearTimeout(localConnectionTimer); clearTimeout(data.reframeTimer); data.shadowElem.removeClass('flashblocker-assumed'); if(!i){ doneFn(); } else { data.reframeTimer = setTimeout(doneFn, 9); } }; })() }; onEvent.onMute = onEvent.onVolumeChange; var workActionQueue = function(data){ var actionLen = data.actionQueue.length; var i = 0; var operation; if(actionLen && data.isActive == 'third'){ while(data.actionQueue.length && actionLen > i){ i++; operation = data.actionQueue.shift(); try{ data.api[operation.fn].apply(data.api, operation.args); } catch(er){ webshims.warn(er); } } } if(data.actionQueue.length){ data.actionQueue = []; } }; var startAutoPlay = function(data){ if(!data){return;} if( (data._ppFlag === undefined && ($.prop(data._elem, 'autoplay')) || !data.paused)){ setTimeout(function(){ if(data.isActive == 'third' && (data._ppFlag === undefined || !data.paused)){ try { $(data._elem).play(); data._ppFlag = true; } catch(er){} } }, 1); } if(data.muted){ $.prop(data._elem, 'muted', true); } if(data.volume != 1){ $.prop(data._elem, 'volume', data.volume); } }; var addMediaToStopEvents = $.noop; if(hasNative){ var stopEvents = { play: 1, playing: 1 }; var hideEvtArray = ['play', 'pause', 'playing', 'canplay', 'progress', 'waiting', 'ended', 'loadedmetadata', 'durationchange', 'emptied']; var hidevents = hideEvtArray.map(function(evt){ return evt +'.webshimspolyfill'; }).join(' '); var hidePlayerEvents = function(event){ var data = webshims.data(event.target, 'mediaelement'); if(!data){return;} var isNativeHTML5 = ( event.originalEvent && event.originalEvent.type === event.type ); if( isNativeHTML5 == (data.activating == 'third') ){ event.stopImmediatePropagation(); if(stopEvents[event.type]){ if(data.isActive != data.activating){ $(event.target).pause(); } else if(isNativeHTML5){ ($.prop(event.target, 'pause')._supvalue || $.noop).apply(event.target); } } } }; addMediaToStopEvents = function(elem){ $(elem) .off(hidevents) .on(hidevents, hidePlayerEvents) ; hideEvtArray.forEach(function(evt){ webshims.moveToFirstEvent(elem, evt); }); }; addMediaToStopEvents(document); } mediaelement.setActive = function(elem, type, data){ if(!data){ data = webshims.data(elem, 'mediaelement'); } if(!data || data.isActive == type){return;} if(type != 'html5' && type != 'third'){ webshims.warn('wrong type for mediaelement activating: '+ type); } var shadowData = webshims.data(elem, 'shadowData'); data.activating = type; $(elem).pause(); data.isActive = type; if(type == 'third'){ shadowData.shadowElement = shadowData.shadowFocusElement = data.shadowElem[0]; $(elem).addClass('swf-api-active nonnative-api-active').hide().getShadowElement().show(); } else { $(elem).removeClass('swf-api-active nonnative-api-active').show().getShadowElement().hide(); shadowData.shadowElement = shadowData.shadowFocusElement = false; } $(elem).trigger('mediaelementapichange'); }; var resetSwfProps = (function(){ var resetProtoProps = ['_calledMeta', 'lastDuration', '_bufferedEnd', '_bufferedStart', '_ppFlag', 'currentSrc', 'currentTime', 'duration', 'ended', 'networkState', 'paused', 'seeking', 'videoHeight', 'videoWidth']; var len = resetProtoProps.length; return function(data){ if(!data){return;} clearTimeout(data._seekedTimer); var lenI = len; var networkState = data.networkState; setReadyState(0, data); clearTimeout(data._durationChangeTimer); while(--lenI > -1){ delete data[resetProtoProps[lenI]]; } data.actionQueue = []; data.buffered.length = 0; if(networkState){ trigger(data._elem, 'emptied'); } }; })(); var getComputedDimension = (function(){ var dimCache = {}; var getVideoDims = function(data){ var ret, poster, img; if(dimCache[data.currentSrc]){ ret = dimCache[data.currentSrc]; } else if(data.videoHeight && data.videoWidth){ dimCache[data.currentSrc] = { width: data.videoWidth, height: data.videoHeight }; ret = dimCache[data.currentSrc]; } else if((poster = $.attr(data._elem, 'poster'))){ ret = dimCache[poster]; if(!ret){ img = document.createElement('img'); img.onload = function(){ dimCache[poster] = { width: this.width, height: this.height }; if(dimCache[poster].height && dimCache[poster].width){ setElementDimension(data, $.prop(data._elem, 'controls')); } else { delete dimCache[poster]; } img.onload = null; }; img.src = poster; if(img.complete && img.onload){ img.onload(); } } } return ret || {width: 300, height: data._elemNodeName == 'video' ? 150 : 50}; }; var getCssStyle = function(elem, style){ return elem.style[style] || (elem.currentStyle && elem.currentStyle[style]) || (window.getComputedStyle && (window.getComputedStyle( elem, null ) || {} )[style]) || ''; }; var minMaxProps = ['minWidth', 'maxWidth', 'minHeight', 'maxHeight']; var addMinMax = function(elem, ret){ var i, prop; var hasMinMax = false; for (i = 0; i < 4; i++) { prop = getCssStyle(elem, minMaxProps[i]); if(parseFloat(prop, 10)){ hasMinMax = true; ret[minMaxProps[i]] = prop; } } return hasMinMax; }; var retFn = function(data){ var videoDims, ratio, hasMinMax; var elem = data._elem; var autos = { width: getCssStyle(elem, 'width') == 'auto', height: getCssStyle(elem, 'height') == 'auto' }; var ret = { width: !autos.width && $(elem).width(), height: !autos.height && $(elem).height() }; if(autos.width || autos.height){ videoDims = getVideoDims(data); ratio = videoDims.width / videoDims.height; if(autos.width && autos.height){ ret.width = videoDims.width; ret.height = videoDims.height; } else if(autos.width){ ret.width = ret.height * ratio; } else if(autos.height){ ret.height = ret.width / ratio; } if(addMinMax(elem, ret)){ data.shadowElem.css(ret); if(autos.width){ ret.width = data.shadowElem.height() * ratio; } if(autos.height){ ret.height = ((autos.width) ? ret.width : data.shadowElem.width()) / ratio; } if(autos.width && autos.height){ data.shadowElem.css(ret); ret.height = data.shadowElem.width() / ratio; ret.width = ret.height * ratio; data.shadowElem.css(ret); ret.width = data.shadowElem.height() * ratio; ret.height = ret.width / ratio; } if(!Modernizr.video){ ret.width = data.shadowElem.width(); ret.height = data.shadowElem.height(); } } } return ret; }; return retFn; })(); var setElementDimension = function(data, hasControls){ var dims; var box = data.shadowElem; $(data._elem)[hasControls ? 'addClass' : 'removeClass']('webshims-controls'); if(data.isActive == 'third' || data.activating == 'third'){ if(data._elemNodeName == 'audio' && !hasControls){ box.css({width: 0, height: 0}); } else { data._elem.style.display = ''; dims = getComputedDimension(data); data._elem.style.display = 'none'; box.css(dims); } } }; var bufferSrc = (function(){ var preloads = { '': 1, 'auto': 1 }; return function(elem){ var preload = $.attr(elem, 'preload'); if(preload == null || preload == 'none' || $.prop(elem, 'autoplay')){ return false; } preload = $.prop(elem, 'preload'); return !!(preloads[preload] || (preload == 'metadata' && $(elem).is('.preload-in-doubt, video:not([poster])'))); }; })(); var regs = { A: /&amp;/g, a: /&/g, e: /\=/g, q: /\?/g }, replaceVar = function(val){ return (val.replace) ? val.replace(regs.A, '%26').replace(regs.a, '%26').replace(regs.e, '%3D').replace(regs.q, '%3F') : val; }; if('matchMedia' in window){ var allowMediaSorting = false; try { allowMediaSorting = window.matchMedia('only all').matches; } catch(er){} if(allowMediaSorting){ mediaelement.sortMedia = function(src1, src2){ try { src1 = !src1.media || matchMedia( src1.media ).matches; src2 = !src2.media || matchMedia( src2.media ).matches; } catch(er){ return 0; } return src1 == src2 ? 0 : src1 ? -1 : 1; }; } } mediaelement.createSWF = function( elem, canPlaySrc, data ){ if(!hasFlash){ setTimeout(function(){ $(elem).mediaLoad(); //<- this should produce a mediaerror }, 1); return; } var attrStyle = {}; if(loadedSwf < 1){ loadedSwf = 1; } else { loadedSwf++; } if(!data){ data = webshims.data(elem, 'mediaelement'); } if((attrStyle.height = $.attr(elem, 'height') || '') || (attrStyle.width = $.attr(elem, 'width') || '')){ $(elem).css(attrStyle); webshims.warn("width or height content attributes used. Webshims prefers the usage of CSS (computed styles or inline styles) to detect size of a video/audio. It's really more powerfull."); } var isRtmp = canPlaySrc.type == 'audio/rtmp' || canPlaySrc.type == 'video/rtmp'; var vars = $.extend({}, options.vars, { poster: replaceVar($.attr(elem, 'poster') && $.prop(elem, 'poster') || ''), source: replaceVar(canPlaySrc.streamId || canPlaySrc.srcProp), server: replaceVar(canPlaySrc.server || '') }); var elemVars = $(elem).data('vars') || {}; var hasControls = $.prop(elem, 'controls'); var elemId = 'jarisplayer-'+ webshims.getID(elem); var params = $.extend( {}, options.params, $(elem).data('params') ); var elemNodeName = elem.nodeName.toLowerCase(); var attrs = $.extend( {}, options.attrs, { name: elemId, id: elemId }, $(elem).data('attrs') ); var setDimension = function(){ if(data.isActive == 'third'){ setElementDimension(data, $.prop(elem, 'controls')); } }; var box; if(data && data.swfCreated){ mediaelement.setActive(elem, 'third', data); data.currentSrc = canPlaySrc.srcProp; data.shadowElem.html('<div id="'+ elemId +'">'); data.api = false; data.actionQueue = []; box = data.shadowElem; resetSwfProps(data); } else { $(document.getElementById('wrapper-'+ elemId )).remove(); box = $('<div class="polyfill-'+ (elemNodeName) +' polyfill-mediaelement" id="wrapper-'+ elemId +'"><div id="'+ elemId +'"></div>') .css({ position: 'relative', overflow: 'hidden' }) ; data = webshims.data(elem, 'mediaelement', webshims.objectCreate(playerStateObj, { actionQueue: { value: [] }, shadowElem: { value: box }, _elemNodeName: { value: elemNodeName }, _elem: { value: elem }, currentSrc: { value: canPlaySrc.srcProp }, swfCreated: { value: true }, id: { value: elemId.replace(/-/g, '') }, buffered: { value: { start: function(index){ if(index >= data.buffered.length){ webshims.error('buffered index size error'); return; } return 0; }, end: function(index){ if(index >= data.buffered.length){ webshims.error('buffered index size error'); return; } return ( (data.duration - data._bufferedStart) * data._bufferedEnd) + data._bufferedStart; }, length: 0 } } })); box.insertBefore(elem); if(hasNative){ $.extend(data, {volume: $.prop(elem, 'volume'), muted: $.prop(elem, 'muted'), paused: $.prop(elem, 'paused')}); } webshims.addShadowDom(elem, box); if(!webshims.data(elem, 'mediaelement')){ webshims.data(elem, 'mediaelement', data); } addMediaToStopEvents(elem); mediaelement.setActive(elem, 'third', data); setElementDimension(data, hasControls); $(elem) .on({ 'updatemediaelementdimensions loadedmetadata emptied': setDimension, 'remove': function(e){ if(!e.originalEvent && mediaelement.jarisEvent[data.id] && mediaelement.jarisEvent[data.id].elem == elem){ delete mediaelement.jarisEvent[data.id]; clearTimeout(localConnectionTimer); clearTimeout(data.flashBlock); } } }) .onWSOff('updateshadowdom', setDimension) ; } if(mediaelement.jarisEvent[data.id] && mediaelement.jarisEvent[data.id].elem != elem){ webshims.error('something went wrong'); return; } else if(!mediaelement.jarisEvent[data.id]){ mediaelement.jarisEvent[data.id] = function(jaris){ if(jaris.type == 'ready'){ var onReady = function(){ if(data.api){ if(!data.paused){ data.api.api_play(); } if(bufferSrc(elem)){ data.api.api_preload(); } onEvent.ready(jaris, data); } }; if(data.api){ onReady(); } else { setTimeout(onReady, 9); } } else { data.currentTime = jaris.position; if(data.api){ if(!data._calledMeta && isNaN(jaris.duration) && data.duration != jaris.duration && isNaN(data.duration)){ onEvent.onDataInitialized(jaris, data); } if(!data._ppFlag && jaris.type != 'onPlayPause'){ onEvent.onPlayPause(jaris, data); } if(onEvent[jaris.type]){ onEvent[jaris.type](jaris, data); } } data.duration = jaris.duration; } }; mediaelement.jarisEvent[data.id].elem = elem; } $.extend(vars, { id: elemId, evtId: data.id, controls: ''+hasControls, autostart: 'false', nodename: elemNodeName }, elemVars ); if(isRtmp){ vars.streamtype = 'rtmp'; } else if(canPlaySrc.type == 'audio/mpeg' || canPlaySrc.type == 'audio/mp3'){ vars.type = 'audio'; vars.streamtype = 'file'; } else if(canPlaySrc.type == 'video/youtube'){ vars.streamtype = 'youtube'; } options.changeSWF(vars, elem, canPlaySrc, data, 'embed'); clearTimeout(data.flashBlock); swfmini.embedSWF(playerSwfPath, elemId, "100%", "100%", "9.0.115", false, vars, params, attrs, function(swfData){ if(swfData.success){ var fBlocker = function(){ if((!swfData.ref.parentNode && box[0].parentNode) || swfData.ref.style.display == "none"){ box.addClass('flashblocker-assumed'); $(elem).trigger('flashblocker'); webshims.warn("flashblocker assumed"); } $(swfData.ref).css({'minHeight': '2px', 'minWidth': '2px', display: 'block'}); }; data.api = swfData.ref; if(!hasControls){ $(swfData.ref).attr('tabindex', '-1').css('outline', 'none'); } data.flashBlock = setTimeout(fBlocker, 99); if(!localConnectionTimer){ clearTimeout(localConnectionTimer); localConnectionTimer = setTimeout(function(){ fBlocker(); var flash = $(swfData.ref); if(flash[0].offsetWidth > 1 && flash[0].offsetHeight > 1 && location.protocol.indexOf('file:') === 0){ webshims.error("Add your local development-directory to the local-trusted security sandbox: http://www.macromedia.com/support/documentation/en/flashplayer/help/settings_manager04.html"); } else if(flash[0].offsetWidth < 2 || flash[0].offsetHeight < 2) { webshims.warn("JS-SWF connection can't be established on hidden or unconnected flash objects"); } flash = null; }, 8000); } } }); }; var queueSwfMethod = function(elem, fn, args, data){ data = data || getSwfDataFromElem(elem); if(data){ if(data.api && data.api[fn]){ data.api[fn].apply(data.api, args || []); } else { //todo add to queue data.actionQueue.push({fn: fn, args: args}); if(data.actionQueue.length > 10){ setTimeout(function(){ if(data.actionQueue.length > 5){ data.actionQueue.shift(); } }, 99); } } return data; } return false; }; ['audio', 'video'].forEach(function(nodeName){ var descs = {}; var mediaSup; var createGetProp = function(key){ if(nodeName == 'audio' && (key == 'videoHeight' || key == 'videoWidth')){return;} descs[key] = { get: function(){ var data = getSwfDataFromElem(this); if(data){ return data[key]; } else if(hasNative && mediaSup[key].prop._supget) { return mediaSup[key].prop._supget.apply(this); } else { return playerStateObj[key]; } }, writeable: false }; }; var createGetSetProp = function(key, setFn){ createGetProp(key); delete descs[key].writeable; descs[key].set = setFn; }; createGetSetProp('seeking'); createGetSetProp('volume', function(v){ var data = getSwfDataFromElem(this); if(data){ v *= 1; if(!isNaN(v)){ if(v < 0 || v > 1){ webshims.error('volume greater or less than allowed '+ (v / 100)); } queueSwfMethod(this, 'api_volume', [v], data); if(data.volume != v){ data.volume = v; trigger(data._elem, 'volumechange'); } data = null; } } else if(mediaSup.volume.prop._supset) { return mediaSup.volume.prop._supset.apply(this, arguments); } }); createGetSetProp('muted', function(m){ var data = getSwfDataFromElem(this); if(data){ m = !!m; queueSwfMethod(this, 'api_muted', [m], data); if(data.muted != m){ data.muted = m; trigger(data._elem, 'volumechange'); } data = null; } else if(mediaSup.muted.prop._supset) { return mediaSup.muted.prop._supset.apply(this, arguments); } }); createGetSetProp('currentTime', function(t){ var data = getSwfDataFromElem(this); if(data){ t *= 1; if (!isNaN(t)) { queueSwfMethod(this, 'api_seek', [t], data); } } else if(mediaSup.currentTime.prop._supset) { return mediaSup.currentTime.prop._supset.apply(this, arguments); } }); ['play', 'pause'].forEach(function(fn){ descs[fn] = { value: function(){ var data = getSwfDataFromElem(this); if(data){ if(data.stopPlayPause){ clearTimeout(data.stopPlayPause); } queueSwfMethod(this, fn == 'play' ? 'api_play' : 'api_pause', [], data); data._ppFlag = true; if(data.paused != (fn != 'play')){ data.paused = fn != 'play'; trigger(data._elem, fn); } } else if(mediaSup[fn].prop._supvalue) { return mediaSup[fn].prop._supvalue.apply(this, arguments); } } }; }); getPropKeys.forEach(createGetProp); webshims.onNodeNamesPropertyModify(nodeName, 'controls', function(val, boolProp){ var data = getSwfDataFromElem(this); $(this)[boolProp ? 'addClass' : 'removeClass']('webshims-controls'); if(data){ if(nodeName == 'audio'){ setElementDimension(data, boolProp); } queueSwfMethod(this, 'api_controls', [boolProp], data); } }); webshims.onNodeNamesPropertyModify(nodeName, 'preload', function(val){ var data, baseData, elem; if(bufferSrc(this)){ data = getSwfDataFromElem(this); if(data){ queueSwfMethod(this, 'api_preload', [], data); } else if(needsLoadPreload && this.paused && !this.error && !$.data(this, 'mediaerror') && !this.readyState && !this.networkState && !this.autoplay && $(this).is(':not(.nonnative-api-active)')){ elem = this; baseData = webshims.data(elem, 'mediaelementBase') || webshims.data(elem, 'mediaelementBase', {}); clearTimeout(baseData.loadTimer); baseData.loadTimer = setTimeout(function(){ $(elem).mediaLoad(); }, 9); } } }); mediaSup = webshims.defineNodeNameProperties(nodeName, descs, 'prop'); if(!Modernizr.mediaDefaultMuted){ webshims.defineNodeNameProperties(nodeName, { defaultMuted: { get: function(){ return $.attr(this, 'muted') != null; }, set: function(val){ if(val){ $.attr(this, 'muted', ''); } else { $(this).removeAttr('muted'); } } } }, 'prop'); } }); if(hasFlash && $.cleanData){ var oldClean = $.cleanData; var flashNames = { object: 1, OBJECT: 1 }; $.cleanData = function(elems){ var i, len, prop; if(elems && (len = elems.length) && loadedSwf){ for(i = 0; i < len; i++){ if(flashNames[elems[i].nodeName] && 'api_pause' in elems[i]){ loadedSwf--; try { elems[i].api_pause(); if(elems[i].readyState == 4){ for (prop in elems[i]) { if (typeof elems[i][prop] == "function") { elems[i][prop] = null; } } } } catch(er){} } } } return oldClean.apply(this, arguments); }; } if(!hasNative){ ['poster', 'src'].forEach(function(prop){ webshims.defineNodeNamesProperty(prop == 'src' ? ['audio', 'video', 'source'] : ['video'], prop, { //attr: {}, reflect: true, propType: 'src' }); }); webshims.defineNodeNamesProperty(['audio', 'video'], 'preload', { reflect: true, propType: 'enumarated', defaultValue: '', limitedTo: ['', 'auto', 'metadata', 'none'] }); webshims.reflectProperties('source', ['type', 'media']); ['autoplay', 'controls'].forEach(function(name){ webshims.defineNodeNamesBooleanProperty(['audio', 'video'], name); }); webshims.defineNodeNamesProperties(['audio', 'video'], { HAVE_CURRENT_DATA: { value: 2 }, HAVE_ENOUGH_DATA: { value: 4 }, HAVE_FUTURE_DATA: { value: 3 }, HAVE_METADATA: { value: 1 }, HAVE_NOTHING: { value: 0 }, NETWORK_EMPTY: { value: 0 }, NETWORK_IDLE: { value: 1 }, NETWORK_LOADING: { value: 2 }, NETWORK_NO_SOURCE: { value: 3 } }, 'prop'); if(hasFlash){ webshims.ready('WINDOWLOAD', function(){ setTimeout(function(){ if(!loadedSwf){ document.createElement('img').src = playerSwfPath; } }, 9); }); } } else if(!('media' in document.createElement('source'))){ webshims.reflectProperties('source', ['media']); } if(options.experimentallyMimetypeCheck){ (function(){ var ADDBACK = $.fn.addBack ? 'addBack' : 'andSelf'; var getMimeType = function(){ var done; var unknown = 'media/unknown please provide mime type'; var media = $(this); var xhrs = []; media .not('.ws-after-check') .find('source') [ADDBACK]() .filter('[data-wsrecheckmimetype]:not([type])') .each(function(){ var source = $(this).removeAttr('data-wsrecheckmimetype'); var error = function(){ source.attr('data-type', unknown); }; try { xhrs.push( $.ajax({ type: 'head', url: $.attr(this, 'src'), success: function(content, status, xhr){ var mime = xhr.getResponseHeader('Content-Type'); if(mime){ done = true; } source.attr('data-type', mime || unknown); }, error: error }) ) ; } catch(er){ error(); } }) ; if(xhrs.length){ media.addClass('ws-after-check'); $.when.apply($, xhrs).always(function(){ media.mediaLoad(); setTimeout(function(){ media.removeClass('ws-after-check'); }, 9); }); } }; $('audio.media-error, video.media-error').each(getMimeType); $(document).on('mediaerror', function(e){ getMimeType.call(e.target); }); })(); } if(hasNative && hasFlash && !options.preferFlash){ var noSwitch = { 1: 1 }; var switchOptions = function(e){ var media, error, parent; if(!options.preferFlash && ($(e.target).is('audio, video') || ((parent = e.target.parentNode) && $('source', parent).last()[0] == e.target)) && (media = $(e.target).closest('audio, video')) && (error = media.prop('error')) && !noSwitch[error.code] ){ if(!options.preferFlash){ if(!media.is('.nonnative-api-active')){ options.preferFlash = true; document.removeEventListener('error', switchOptions, true); $('audio, video').each(function(){ webshims.mediaelement.selectSource(this); }); webshims.error("switching mediaelements option to 'preferFlash', due to an error with native player: "+e.target.src+" Mediaerror: "+ media.prop('error')+ 'first error: '+ error); } } else{ document.removeEventListener('error', switchOptions, true); } } }; setTimeout(function(){ document.addEventListener('error', switchOptions, true); $('audio, video').each(function(){ var error = $.prop(this, 'error'); if(error && !noSwitch[error]){ switchOptions({target: this}); return false; } }); }, 9); } });
codevinsky/cdnjs
ajax/libs/webshim/1.12.6/dev/shims/combos/19.js
JavaScript
mit
134,477
// CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: http://codemirror.net/LICENSE (function(mod) { if (typeof exports == "object" && typeof module == "object") // CommonJS mod(require("../../lib/codemirror"), require("../javascript/javascript")); else if (typeof define == "function" && define.amd) // AMD define(["../../lib/codemirror", "../javascript/javascript"], mod); else // Plain browser env mod(CodeMirror); })(function(CodeMirror) { "use strict"; CodeMirror.defineMode("pegjs", function (config) { var jsMode = CodeMirror.getMode(config, "javascript"); function identifier(stream) { return stream.match(/^[a-zA-Z_][a-zA-Z0-9_]*/); } return { startState: function () { return { inString: false, stringType: null, inComment: false, inCharacterClass: false, braced: 0, lhs: true, localState: null }; }, token: function (stream, state) { if (stream) //check for state changes if (!state.inString && !state.inComment && ((stream.peek() == '"') || (stream.peek() == "'"))) { state.stringType = stream.peek(); stream.next(); // Skip quote state.inString = true; // Update state } if (!state.inString && !state.inComment && stream.match(/^\/\*/)) { state.inComment = true; } //return state if (state.inString) { while (state.inString && !stream.eol()) { if (stream.peek() === state.stringType) { stream.next(); // Skip quote state.inString = false; // Clear flag } else if (stream.peek() === '\\') { stream.next(); stream.next(); } else { stream.match(/^.[^\\\"\']*/); } } return state.lhs ? "property string" : "string"; // Token style } else if (state.inComment) { while (state.inComment && !stream.eol()) { if (stream.match(/\*\//)) { state.inComment = false; // Clear flag } else { stream.match(/^.[^\*]*/); } } return "comment"; } else if (state.inCharacterClass) { while (state.inCharacterClass && !stream.eol()) { if (!(stream.match(/^[^\]\\]+/) || stream.match(/^\\./))) { state.inCharacterClass = false; } } } else if (stream.peek() === '[') { stream.next(); state.inCharacterClass = true; return 'bracket'; } else if (stream.match(/^\/\//)) { stream.skipToEnd(); return "comment"; } else if (state.braced || stream.peek() === '{') { if (state.localState === null) { state.localState = CodeMirror.startState(jsMode); } var token = jsMode.token(stream, state.localState); var text = stream.current(); if (!token) { for (var i = 0; i < text.length; i++) { if (text[i] === '{') { state.braced++; } else if (text[i] === '}') { state.braced--; } }; } return token; } else if (identifier(stream)) { if (stream.peek() === ':') { return 'variable'; } return 'variable-2'; } else if (['[', ']', '(', ')'].indexOf(stream.peek()) != -1) { stream.next(); return 'bracket'; } else if (!stream.eatSpace()) { stream.next(); } return null; } }; }, "javascript"); });
him2him2/cdnjs
ajax/libs/codemirror/5.22.2/mode/pegjs/pegjs.js
JavaScript
mit
3,577
/*! JSZip - A Javascript class for generating and reading zip files <http://stuartk.com/jszip> (c) 2009-2014 Stuart Knightley <stuart [at] stuartk.com> Dual licenced under the MIT license or GPLv3. See https://raw.github.com/Stuk/jszip/master/LICENSE.markdown. JSZip uses the library pako released under the MIT license : https://github.com/nodeca/pako/blob/master/LICENSE */ !function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{var f;"undefined"!=typeof window?f=window:"undefined"!=typeof global?f=global:"undefined"!=typeof self&&(f=self),f.JSZip=e()}}(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);throw new Error("Cannot find module '"+o+"'")}var f=n[o]={exports:{}};t[o][0].call(f.exports,function(e){var n=t[o][1][e];return s(n?n:e)},f,f.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(_dereq_,module,exports){ 'use strict'; // private property var _keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; // public method for encoding exports.encode = function(input, utf8) { var output = ""; var chr1, chr2, chr3, enc1, enc2, enc3, enc4; var i = 0; while (i < input.length) { chr1 = input.charCodeAt(i++); chr2 = input.charCodeAt(i++); chr3 = input.charCodeAt(i++); enc1 = chr1 >> 2; enc2 = ((chr1 & 3) << 4) | (chr2 >> 4); enc3 = ((chr2 & 15) << 2) | (chr3 >> 6); enc4 = chr3 & 63; if (isNaN(chr2)) { enc3 = enc4 = 64; } else if (isNaN(chr3)) { enc4 = 64; } output = output + _keyStr.charAt(enc1) + _keyStr.charAt(enc2) + _keyStr.charAt(enc3) + _keyStr.charAt(enc4); } return output; }; // public method for decoding exports.decode = function(input, utf8) { var output = ""; var chr1, chr2, chr3; var enc1, enc2, enc3, enc4; var i = 0; input = input.replace(/[^A-Za-z0-9\+\/\=]/g, ""); while (i < input.length) { enc1 = _keyStr.indexOf(input.charAt(i++)); enc2 = _keyStr.indexOf(input.charAt(i++)); enc3 = _keyStr.indexOf(input.charAt(i++)); enc4 = _keyStr.indexOf(input.charAt(i++)); chr1 = (enc1 << 2) | (enc2 >> 4); chr2 = ((enc2 & 15) << 4) | (enc3 >> 2); chr3 = ((enc3 & 3) << 6) | enc4; output = output + String.fromCharCode(chr1); if (enc3 != 64) { output = output + String.fromCharCode(chr2); } if (enc4 != 64) { output = output + String.fromCharCode(chr3); } } return output; }; },{}],2:[function(_dereq_,module,exports){ 'use strict'; function CompressedObject() { this.compressedSize = 0; this.uncompressedSize = 0; this.crc32 = 0; this.compressionMethod = null; this.compressedContent = null; } CompressedObject.prototype = { /** * Return the decompressed content in an unspecified format. * The format will depend on the decompressor. * @return {Object} the decompressed content. */ getContent: function() { return null; // see implementation }, /** * Return the compressed content in an unspecified format. * The format will depend on the compressed conten source. * @return {Object} the compressed content. */ getCompressedContent: function() { return null; // see implementation } }; module.exports = CompressedObject; },{}],3:[function(_dereq_,module,exports){ 'use strict'; exports.STORE = { magic: "\x00\x00", compress: function(content, compressionOptions) { return content; // no compression }, uncompress: function(content) { return content; // no compression }, compressInputType: null, uncompressInputType: null }; exports.DEFLATE = _dereq_('./flate'); },{"./flate":8}],4:[function(_dereq_,module,exports){ 'use strict'; var utils = _dereq_('./utils'); var table = [ 0x00000000, 0x77073096, 0xEE0E612C, 0x990951BA, 0x076DC419, 0x706AF48F, 0xE963A535, 0x9E6495A3, 0x0EDB8832, 0x79DCB8A4, 0xE0D5E91E, 0x97D2D988, 0x09B64C2B, 0x7EB17CBD, 0xE7B82D07, 0x90BF1D91, 0x1DB71064, 0x6AB020F2, 0xF3B97148, 0x84BE41DE, 0x1ADAD47D, 0x6DDDE4EB, 0xF4D4B551, 0x83D385C7, 0x136C9856, 0x646BA8C0, 0xFD62F97A, 0x8A65C9EC, 0x14015C4F, 0x63066CD9, 0xFA0F3D63, 0x8D080DF5, 0x3B6E20C8, 0x4C69105E, 0xD56041E4, 0xA2677172, 0x3C03E4D1, 0x4B04D447, 0xD20D85FD, 0xA50AB56B, 0x35B5A8FA, 0x42B2986C, 0xDBBBC9D6, 0xACBCF940, 0x32D86CE3, 0x45DF5C75, 0xDCD60DCF, 0xABD13D59, 0x26D930AC, 0x51DE003A, 0xC8D75180, 0xBFD06116, 0x21B4F4B5, 0x56B3C423, 0xCFBA9599, 0xB8BDA50F, 0x2802B89E, 0x5F058808, 0xC60CD9B2, 0xB10BE924, 0x2F6F7C87, 0x58684C11, 0xC1611DAB, 0xB6662D3D, 0x76DC4190, 0x01DB7106, 0x98D220BC, 0xEFD5102A, 0x71B18589, 0x06B6B51F, 0x9FBFE4A5, 0xE8B8D433, 0x7807C9A2, 0x0F00F934, 0x9609A88E, 0xE10E9818, 0x7F6A0DBB, 0x086D3D2D, 0x91646C97, 0xE6635C01, 0x6B6B51F4, 0x1C6C6162, 0x856530D8, 0xF262004E, 0x6C0695ED, 0x1B01A57B, 0x8208F4C1, 0xF50FC457, 0x65B0D9C6, 0x12B7E950, 0x8BBEB8EA, 0xFCB9887C, 0x62DD1DDF, 0x15DA2D49, 0x8CD37CF3, 0xFBD44C65, 0x4DB26158, 0x3AB551CE, 0xA3BC0074, 0xD4BB30E2, 0x4ADFA541, 0x3DD895D7, 0xA4D1C46D, 0xD3D6F4FB, 0x4369E96A, 0x346ED9FC, 0xAD678846, 0xDA60B8D0, 0x44042D73, 0x33031DE5, 0xAA0A4C5F, 0xDD0D7CC9, 0x5005713C, 0x270241AA, 0xBE0B1010, 0xC90C2086, 0x5768B525, 0x206F85B3, 0xB966D409, 0xCE61E49F, 0x5EDEF90E, 0x29D9C998, 0xB0D09822, 0xC7D7A8B4, 0x59B33D17, 0x2EB40D81, 0xB7BD5C3B, 0xC0BA6CAD, 0xEDB88320, 0x9ABFB3B6, 0x03B6E20C, 0x74B1D29A, 0xEAD54739, 0x9DD277AF, 0x04DB2615, 0x73DC1683, 0xE3630B12, 0x94643B84, 0x0D6D6A3E, 0x7A6A5AA8, 0xE40ECF0B, 0x9309FF9D, 0x0A00AE27, 0x7D079EB1, 0xF00F9344, 0x8708A3D2, 0x1E01F268, 0x6906C2FE, 0xF762575D, 0x806567CB, 0x196C3671, 0x6E6B06E7, 0xFED41B76, 0x89D32BE0, 0x10DA7A5A, 0x67DD4ACC, 0xF9B9DF6F, 0x8EBEEFF9, 0x17B7BE43, 0x60B08ED5, 0xD6D6A3E8, 0xA1D1937E, 0x38D8C2C4, 0x4FDFF252, 0xD1BB67F1, 0xA6BC5767, 0x3FB506DD, 0x48B2364B, 0xD80D2BDA, 0xAF0A1B4C, 0x36034AF6, 0x41047A60, 0xDF60EFC3, 0xA867DF55, 0x316E8EEF, 0x4669BE79, 0xCB61B38C, 0xBC66831A, 0x256FD2A0, 0x5268E236, 0xCC0C7795, 0xBB0B4703, 0x220216B9, 0x5505262F, 0xC5BA3BBE, 0xB2BD0B28, 0x2BB45A92, 0x5CB36A04, 0xC2D7FFA7, 0xB5D0CF31, 0x2CD99E8B, 0x5BDEAE1D, 0x9B64C2B0, 0xEC63F226, 0x756AA39C, 0x026D930A, 0x9C0906A9, 0xEB0E363F, 0x72076785, 0x05005713, 0x95BF4A82, 0xE2B87A14, 0x7BB12BAE, 0x0CB61B38, 0x92D28E9B, 0xE5D5BE0D, 0x7CDCEFB7, 0x0BDBDF21, 0x86D3D2D4, 0xF1D4E242, 0x68DDB3F8, 0x1FDA836E, 0x81BE16CD, 0xF6B9265B, 0x6FB077E1, 0x18B74777, 0x88085AE6, 0xFF0F6A70, 0x66063BCA, 0x11010B5C, 0x8F659EFF, 0xF862AE69, 0x616BFFD3, 0x166CCF45, 0xA00AE278, 0xD70DD2EE, 0x4E048354, 0x3903B3C2, 0xA7672661, 0xD06016F7, 0x4969474D, 0x3E6E77DB, 0xAED16A4A, 0xD9D65ADC, 0x40DF0B66, 0x37D83BF0, 0xA9BCAE53, 0xDEBB9EC5, 0x47B2CF7F, 0x30B5FFE9, 0xBDBDF21C, 0xCABAC28A, 0x53B39330, 0x24B4A3A6, 0xBAD03605, 0xCDD70693, 0x54DE5729, 0x23D967BF, 0xB3667A2E, 0xC4614AB8, 0x5D681B02, 0x2A6F2B94, 0xB40BBE37, 0xC30C8EA1, 0x5A05DF1B, 0x2D02EF8D ]; /** * * Javascript crc32 * http://www.webtoolkit.info/ * */ module.exports = function crc32(input, crc) { if (typeof input === "undefined" || !input.length) { return 0; } var isArray = utils.getTypeOf(input) !== "string"; if (typeof(crc) == "undefined") { crc = 0; } var x = 0; var y = 0; var b = 0; crc = crc ^ (-1); for (var i = 0, iTop = input.length; i < iTop; i++) { b = isArray ? input[i] : input.charCodeAt(i); y = (crc ^ b) & 0xFF; x = table[y]; crc = (crc >>> 8) ^ x; } return crc ^ (-1); }; // vim: set shiftwidth=4 softtabstop=4: },{"./utils":21}],5:[function(_dereq_,module,exports){ 'use strict'; var utils = _dereq_('./utils'); function DataReader(data) { this.data = null; // type : see implementation this.length = 0; this.index = 0; } DataReader.prototype = { /** * Check that the offset will not go too far. * @param {string} offset the additional offset to check. * @throws {Error} an Error if the offset is out of bounds. */ checkOffset: function(offset) { this.checkIndex(this.index + offset); }, /** * Check that the specifed index will not be too far. * @param {string} newIndex the index to check. * @throws {Error} an Error if the index is out of bounds. */ checkIndex: function(newIndex) { if (this.length < newIndex || newIndex < 0) { throw new Error("End of data reached (data length = " + this.length + ", asked index = " + (newIndex) + "). Corrupted zip ?"); } }, /** * Change the index. * @param {number} newIndex The new index. * @throws {Error} if the new index is out of the data. */ setIndex: function(newIndex) { this.checkIndex(newIndex); this.index = newIndex; }, /** * Skip the next n bytes. * @param {number} n the number of bytes to skip. * @throws {Error} if the new index is out of the data. */ skip: function(n) { this.setIndex(this.index + n); }, /** * Get the byte at the specified index. * @param {number} i the index to use. * @return {number} a byte. */ byteAt: function(i) { // see implementations }, /** * Get the next number with a given byte size. * @param {number} size the number of bytes to read. * @return {number} the corresponding number. */ readInt: function(size) { var result = 0, i; this.checkOffset(size); for (i = this.index + size - 1; i >= this.index; i--) { result = (result << 8) + this.byteAt(i); } this.index += size; return result; }, /** * Get the next string with a given byte size. * @param {number} size the number of bytes to read. * @return {string} the corresponding string. */ readString: function(size) { return utils.transformTo("string", this.readData(size)); }, /** * Get raw data without conversion, <size> bytes. * @param {number} size the number of bytes to read. * @return {Object} the raw data, implementation specific. */ readData: function(size) { // see implementations }, /** * Find the last occurence of a zip signature (4 bytes). * @param {string} sig the signature to find. * @return {number} the index of the last occurence, -1 if not found. */ lastIndexOfSignature: function(sig) { // see implementations }, /** * Get the next date. * @return {Date} the date. */ readDate: function() { var dostime = this.readInt(4); return new Date( ((dostime >> 25) & 0x7f) + 1980, // year ((dostime >> 21) & 0x0f) - 1, // month (dostime >> 16) & 0x1f, // day (dostime >> 11) & 0x1f, // hour (dostime >> 5) & 0x3f, // minute (dostime & 0x1f) << 1); // second } }; module.exports = DataReader; },{"./utils":21}],6:[function(_dereq_,module,exports){ 'use strict'; exports.base64 = false; exports.binary = false; exports.dir = false; exports.createFolders = false; exports.date = null; exports.compression = null; exports.compressionOptions = null; exports.comment = null; exports.unixPermissions = null; exports.dosPermissions = null; },{}],7:[function(_dereq_,module,exports){ 'use strict'; var utils = _dereq_('./utils'); /** * @deprecated * This function will be removed in a future version without replacement. */ exports.string2binary = function(str) { return utils.string2binary(str); }; /** * @deprecated * This function will be removed in a future version without replacement. */ exports.string2Uint8Array = function(str) { return utils.transformTo("uint8array", str); }; /** * @deprecated * This function will be removed in a future version without replacement. */ exports.uint8Array2String = function(array) { return utils.transformTo("string", array); }; /** * @deprecated * This function will be removed in a future version without replacement. */ exports.string2Blob = function(str) { var buffer = utils.transformTo("arraybuffer", str); return utils.arrayBuffer2Blob(buffer); }; /** * @deprecated * This function will be removed in a future version without replacement. */ exports.arrayBuffer2Blob = function(buffer) { return utils.arrayBuffer2Blob(buffer); }; /** * @deprecated * This function will be removed in a future version without replacement. */ exports.transformTo = function(outputType, input) { return utils.transformTo(outputType, input); }; /** * @deprecated * This function will be removed in a future version without replacement. */ exports.getTypeOf = function(input) { return utils.getTypeOf(input); }; /** * @deprecated * This function will be removed in a future version without replacement. */ exports.checkSupport = function(type) { return utils.checkSupport(type); }; /** * @deprecated * This value will be removed in a future version without replacement. */ exports.MAX_VALUE_16BITS = utils.MAX_VALUE_16BITS; /** * @deprecated * This value will be removed in a future version without replacement. */ exports.MAX_VALUE_32BITS = utils.MAX_VALUE_32BITS; /** * @deprecated * This function will be removed in a future version without replacement. */ exports.pretty = function(str) { return utils.pretty(str); }; /** * @deprecated * This function will be removed in a future version without replacement. */ exports.findCompression = function(compressionMethod) { return utils.findCompression(compressionMethod); }; /** * @deprecated * This function will be removed in a future version without replacement. */ exports.isRegExp = function (object) { return utils.isRegExp(object); }; },{"./utils":21}],8:[function(_dereq_,module,exports){ 'use strict'; var USE_TYPEDARRAY = (typeof Uint8Array !== 'undefined') && (typeof Uint16Array !== 'undefined') && (typeof Uint32Array !== 'undefined'); var pako = _dereq_("pako"); exports.uncompressInputType = USE_TYPEDARRAY ? "uint8array" : "array"; exports.compressInputType = USE_TYPEDARRAY ? "uint8array" : "array"; exports.magic = "\x08\x00"; exports.compress = function(input, compressionOptions) { return pako.deflateRaw(input, { level : compressionOptions.level || -1 // default compression }); }; exports.uncompress = function(input) { return pako.inflateRaw(input); }; },{"pako":24}],9:[function(_dereq_,module,exports){ 'use strict'; var base64 = _dereq_('./base64'); /** Usage: zip = new JSZip(); zip.file("hello.txt", "Hello, World!").file("tempfile", "nothing"); zip.folder("images").file("smile.gif", base64Data, {base64: true}); zip.file("Xmas.txt", "Ho ho ho !", {date : new Date("December 25, 2007 00:00:01")}); zip.remove("tempfile"); base64zip = zip.generate(); **/ /** * Representation a of zip file in js * @constructor * @param {String=|ArrayBuffer=|Uint8Array=} data the data to load, if any (optional). * @param {Object=} options the options for creating this objects (optional). */ function JSZip(data, options) { // if this constructor is used without `new`, it adds `new` before itself: if(!(this instanceof JSZip)) return new JSZip(data, options); // object containing the files : // { // "folder/" : {...}, // "folder/data.txt" : {...} // } this.files = {}; this.comment = null; // Where we are in the hierarchy this.root = ""; if (data) { this.load(data, options); } this.clone = function() { var newObj = new JSZip(); for (var i in this) { if (typeof this[i] !== "function") { newObj[i] = this[i]; } } return newObj; }; } JSZip.prototype = _dereq_('./object'); JSZip.prototype.load = _dereq_('./load'); JSZip.support = _dereq_('./support'); JSZip.defaults = _dereq_('./defaults'); /** * @deprecated * This namespace will be removed in a future version without replacement. */ JSZip.utils = _dereq_('./deprecatedPublicUtils'); JSZip.base64 = { /** * @deprecated * This method will be removed in a future version without replacement. */ encode : function(input) { return base64.encode(input); }, /** * @deprecated * This method will be removed in a future version without replacement. */ decode : function(input) { return base64.decode(input); } }; JSZip.compressions = _dereq_('./compressions'); module.exports = JSZip; },{"./base64":1,"./compressions":3,"./defaults":6,"./deprecatedPublicUtils":7,"./load":10,"./object":13,"./support":17}],10:[function(_dereq_,module,exports){ 'use strict'; var base64 = _dereq_('./base64'); var ZipEntries = _dereq_('./zipEntries'); module.exports = function(data, options) { var files, zipEntries, i, input; options = options || {}; if (options.base64) { data = base64.decode(data); } zipEntries = new ZipEntries(data, options); files = zipEntries.files; for (i = 0; i < files.length; i++) { input = files[i]; this.file(input.fileName, input.decompressed, { binary: true, optimizedBinaryString: true, date: input.date, dir: input.dir, comment : input.fileComment.length ? input.fileComment : null, unixPermissions : input.unixPermissions, dosPermissions : input.dosPermissions, createFolders: options.createFolders }); } if (zipEntries.zipComment.length) { this.comment = zipEntries.zipComment; } return this; }; },{"./base64":1,"./zipEntries":22}],11:[function(_dereq_,module,exports){ (function (Buffer){ 'use strict'; module.exports = function(data, encoding){ return new Buffer(data, encoding); }; module.exports.test = function(b){ return Buffer.isBuffer(b); }; }).call(this,(typeof Buffer !== "undefined" ? Buffer : undefined)) },{}],12:[function(_dereq_,module,exports){ 'use strict'; var Uint8ArrayReader = _dereq_('./uint8ArrayReader'); function NodeBufferReader(data) { this.data = data; this.length = this.data.length; this.index = 0; } NodeBufferReader.prototype = new Uint8ArrayReader(); /** * @see DataReader.readData */ NodeBufferReader.prototype.readData = function(size) { this.checkOffset(size); var result = this.data.slice(this.index, this.index + size); this.index += size; return result; }; module.exports = NodeBufferReader; },{"./uint8ArrayReader":18}],13:[function(_dereq_,module,exports){ 'use strict'; var support = _dereq_('./support'); var utils = _dereq_('./utils'); var crc32 = _dereq_('./crc32'); var signature = _dereq_('./signature'); var defaults = _dereq_('./defaults'); var base64 = _dereq_('./base64'); var compressions = _dereq_('./compressions'); var CompressedObject = _dereq_('./compressedObject'); var nodeBuffer = _dereq_('./nodeBuffer'); var utf8 = _dereq_('./utf8'); var StringWriter = _dereq_('./stringWriter'); var Uint8ArrayWriter = _dereq_('./uint8ArrayWriter'); /** * Returns the raw data of a ZipObject, decompress the content if necessary. * @param {ZipObject} file the file to use. * @return {String|ArrayBuffer|Uint8Array|Buffer} the data. */ var getRawData = function(file) { if (file._data instanceof CompressedObject) { file._data = file._data.getContent(); file.options.binary = true; file.options.base64 = false; if (utils.getTypeOf(file._data) === "uint8array") { var copy = file._data; // when reading an arraybuffer, the CompressedObject mechanism will keep it and subarray() a Uint8Array. // if we request a file in the same format, we might get the same Uint8Array or its ArrayBuffer (the original zip file). file._data = new Uint8Array(copy.length); // with an empty Uint8Array, Opera fails with a "Offset larger than array size" if (copy.length !== 0) { file._data.set(copy, 0); } } } return file._data; }; /** * Returns the data of a ZipObject in a binary form. If the content is an unicode string, encode it. * @param {ZipObject} file the file to use. * @return {String|ArrayBuffer|Uint8Array|Buffer} the data. */ var getBinaryData = function(file) { var result = getRawData(file), type = utils.getTypeOf(result); if (type === "string") { if (!file.options.binary) { // unicode text ! // unicode string => binary string is a painful process, check if we can avoid it. if (support.nodebuffer) { return nodeBuffer(result, "utf-8"); } } return file.asBinary(); } return result; }; /** * Transform this._data into a string. * @param {function} filter a function String -> String, applied if not null on the result. * @return {String} the string representing this._data. */ var dataToString = function(asUTF8) { var result = getRawData(this); if (result === null || typeof result === "undefined") { return ""; } // if the data is a base64 string, we decode it before checking the encoding ! if (this.options.base64) { result = base64.decode(result); } if (asUTF8 && this.options.binary) { // JSZip.prototype.utf8decode supports arrays as input // skip to array => string step, utf8decode will do it. result = out.utf8decode(result); } else { // no utf8 transformation, do the array => string step. result = utils.transformTo("string", result); } if (!asUTF8 && !this.options.binary) { result = utils.transformTo("string", out.utf8encode(result)); } return result; }; /** * A simple object representing a file in the zip file. * @constructor * @param {string} name the name of the file * @param {String|ArrayBuffer|Uint8Array|Buffer} data the data * @param {Object} options the options of the file */ var ZipObject = function(name, data, options) { this.name = name; this.dir = options.dir; this.date = options.date; this.comment = options.comment; this.unixPermissions = options.unixPermissions; this.dosPermissions = options.dosPermissions; this._data = data; this.options = options; /* * This object contains initial values for dir and date. * With them, we can check if the user changed the deprecated metadata in * `ZipObject#options` or not. */ this._initialMetadata = { dir : options.dir, date : options.date }; }; ZipObject.prototype = { /** * Return the content as UTF8 string. * @return {string} the UTF8 string. */ asText: function() { return dataToString.call(this, true); }, /** * Returns the binary content. * @return {string} the content as binary. */ asBinary: function() { return dataToString.call(this, false); }, /** * Returns the content as a nodejs Buffer. * @return {Buffer} the content as a Buffer. */ asNodeBuffer: function() { var result = getBinaryData(this); return utils.transformTo("nodebuffer", result); }, /** * Returns the content as an Uint8Array. * @return {Uint8Array} the content as an Uint8Array. */ asUint8Array: function() { var result = getBinaryData(this); return utils.transformTo("uint8array", result); }, /** * Returns the content as an ArrayBuffer. * @return {ArrayBuffer} the content as an ArrayBufer. */ asArrayBuffer: function() { return this.asUint8Array().buffer; } }; /** * Transform an integer into a string in hexadecimal. * @private * @param {number} dec the number to convert. * @param {number} bytes the number of bytes to generate. * @returns {string} the result. */ var decToHex = function(dec, bytes) { var hex = "", i; for (i = 0; i < bytes; i++) { hex += String.fromCharCode(dec & 0xff); dec = dec >>> 8; } return hex; }; /** * Merge the objects passed as parameters into a new one. * @private * @param {...Object} var_args All objects to merge. * @return {Object} a new object with the data of the others. */ var extend = function() { var result = {}, i, attr; for (i = 0; i < arguments.length; i++) { // arguments is not enumerable in some browsers for (attr in arguments[i]) { if (arguments[i].hasOwnProperty(attr) && typeof result[attr] === "undefined") { result[attr] = arguments[i][attr]; } } } return result; }; /** * Transforms the (incomplete) options from the user into the complete * set of options to create a file. * @private * @param {Object} o the options from the user. * @return {Object} the complete set of options. */ var prepareFileAttrs = function(o) { o = o || {}; if (o.base64 === true && (o.binary === null || o.binary === undefined)) { o.binary = true; } o = extend(o, defaults); o.date = o.date || new Date(); if (o.compression !== null) o.compression = o.compression.toUpperCase(); return o; }; /** * Add a file in the current folder. * @private * @param {string} name the name of the file * @param {String|ArrayBuffer|Uint8Array|Buffer} data the data of the file * @param {Object} o the options of the file * @return {Object} the new file. */ var fileAdd = function(name, data, o) { // be sure sub folders exist var dataType = utils.getTypeOf(data), parent; o = prepareFileAttrs(o); if (typeof o.unixPermissions === "string") { o.unixPermissions = parseInt(o.unixPermissions, 8); } // UNX_IFDIR 0040000 see zipinfo.c if (o.unixPermissions && (o.unixPermissions & 0x4000)) { o.dir = true; } // Bit 4 Directory if (o.dosPermissions && (o.dosPermissions & 0x0010)) { o.dir = true; } if (o.dir) { name = forceTrailingSlash(name); } if (o.createFolders && (parent = parentFolder(name))) { folderAdd.call(this, parent, true); } if (o.dir || data === null || typeof data === "undefined") { o.base64 = false; o.binary = false; data = null; dataType = null; } else if (dataType === "string") { if (o.binary && !o.base64) { // optimizedBinaryString == true means that the file has already been filtered with a 0xFF mask if (o.optimizedBinaryString !== true) { // this is a string, not in a base64 format. // Be sure that this is a correct "binary string" data = utils.string2binary(data); } } } else { // arraybuffer, uint8array, ... o.base64 = false; o.binary = true; if (!dataType && !(data instanceof CompressedObject)) { throw new Error("The data of '" + name + "' is in an unsupported format !"); } // special case : it's way easier to work with Uint8Array than with ArrayBuffer if (dataType === "arraybuffer") { data = utils.transformTo("uint8array", data); } } var object = new ZipObject(name, data, o); this.files[name] = object; return object; }; /** * Find the parent folder of the path. * @private * @param {string} path the path to use * @return {string} the parent folder, or "" */ var parentFolder = function (path) { if (path.slice(-1) == '/') { path = path.substring(0, path.length - 1); } var lastSlash = path.lastIndexOf('/'); return (lastSlash > 0) ? path.substring(0, lastSlash) : ""; }; /** * Returns the path with a slash at the end. * @private * @param {String} path the path to check. * @return {String} the path with a trailing slash. */ var forceTrailingSlash = function(path) { // Check the name ends with a / if (path.slice(-1) != "/") { path += "/"; // IE doesn't like substr(-1) } return path; }; /** * Add a (sub) folder in the current folder. * @private * @param {string} name the folder's name * @param {boolean=} [createFolders] If true, automatically create sub * folders. Defaults to false. * @return {Object} the new folder. */ var folderAdd = function(name, createFolders) { createFolders = (typeof createFolders !== 'undefined') ? createFolders : false; name = forceTrailingSlash(name); // Does this folder already exist? if (!this.files[name]) { fileAdd.call(this, name, null, { dir: true, createFolders: createFolders }); } return this.files[name]; }; /** * Generate a JSZip.CompressedObject for a given zipOject. * @param {ZipObject} file the object to read. * @param {JSZip.compression} compression the compression to use. * @param {Object} compressionOptions the options to use when compressing. * @return {JSZip.CompressedObject} the compressed result. */ var generateCompressedObjectFrom = function(file, compression, compressionOptions) { var result = new CompressedObject(), content; // the data has not been decompressed, we might reuse things ! if (file._data instanceof CompressedObject) { result.uncompressedSize = file._data.uncompressedSize; result.crc32 = file._data.crc32; if (result.uncompressedSize === 0 || file.dir) { compression = compressions['STORE']; result.compressedContent = ""; result.crc32 = 0; } else if (file._data.compressionMethod === compression.magic) { result.compressedContent = file._data.getCompressedContent(); } else { content = file._data.getContent(); // need to decompress / recompress result.compressedContent = compression.compress(utils.transformTo(compression.compressInputType, content), compressionOptions); } } else { // have uncompressed data content = getBinaryData(file); if (!content || content.length === 0 || file.dir) { compression = compressions['STORE']; content = ""; } result.uncompressedSize = content.length; result.crc32 = crc32(content); result.compressedContent = compression.compress(utils.transformTo(compression.compressInputType, content), compressionOptions); } result.compressedSize = result.compressedContent.length; result.compressionMethod = compression.magic; return result; }; /** * Generate the UNIX part of the external file attributes. * @param {Object} unixPermissions the unix permissions or null. * @param {Boolean} isDir true if the entry is a directory, false otherwise. * @return {Number} a 32 bit integer. * * adapted from http://unix.stackexchange.com/questions/14705/the-zip-formats-external-file-attribute : * * TTTTsstrwxrwxrwx0000000000ADVSHR * ^^^^____________________________ file type, see zipinfo.c (UNX_*) * ^^^_________________________ setuid, setgid, sticky * ^^^^^^^^^________________ permissions * ^^^^^^^^^^______ not used ? * ^^^^^^ DOS attribute bits : Archive, Directory, Volume label, System file, Hidden, Read only */ var generateUnixExternalFileAttr = function (unixPermissions, isDir) { var result = unixPermissions; if (!unixPermissions) { // I can't use octal values in strict mode, hence the hexa. // 040775 => 0x41fd // 0100664 => 0x81b4 result = isDir ? 0x41fd : 0x81b4; } return (result & 0xFFFF) << 16; }; /** * Generate the DOS part of the external file attributes. * @param {Object} dosPermissions the dos permissions or null. * @param {Boolean} isDir true if the entry is a directory, false otherwise. * @return {Number} a 32 bit integer. * * Bit 0 Read-Only * Bit 1 Hidden * Bit 2 System * Bit 3 Volume Label * Bit 4 Directory * Bit 5 Archive */ var generateDosExternalFileAttr = function (dosPermissions, isDir) { // the dir flag is already set for compatibility return (dosPermissions || 0) & 0x3F; }; /** * Generate the various parts used in the construction of the final zip file. * @param {string} name the file name. * @param {ZipObject} file the file content. * @param {JSZip.CompressedObject} compressedObject the compressed object. * @param {number} offset the current offset from the start of the zip file. * @param {String} platform let's pretend we are this platform (change platform dependents fields) * @return {object} the zip parts. */ var generateZipParts = function(name, file, compressedObject, offset, platform) { var data = compressedObject.compressedContent, utfEncodedFileName = utils.transformTo("string", utf8.utf8encode(file.name)), comment = file.comment || "", utfEncodedComment = utils.transformTo("string", utf8.utf8encode(comment)), useUTF8ForFileName = utfEncodedFileName.length !== file.name.length, useUTF8ForComment = utfEncodedComment.length !== comment.length, o = file.options, dosTime, dosDate, extraFields = "", unicodePathExtraField = "", unicodeCommentExtraField = "", dir, date; // handle the deprecated options.dir if (file._initialMetadata.dir !== file.dir) { dir = file.dir; } else { dir = o.dir; } // handle the deprecated options.date if(file._initialMetadata.date !== file.date) { date = file.date; } else { date = o.date; } var extFileAttr = 0; var versionMadeBy = 0; if (dir) { // dos or unix, we set the dos dir flag extFileAttr |= 0x00010; } if(platform === "UNIX") { versionMadeBy = 0x031E; // UNIX, version 3.0 extFileAttr |= generateUnixExternalFileAttr(file.unixPermissions, dir); } else { // DOS or other, fallback to DOS versionMadeBy = 0x0014; // DOS, version 2.0 extFileAttr |= generateDosExternalFileAttr(file.dosPermissions, dir); } // date // @see http://www.delorie.com/djgpp/doc/rbinter/it/52/13.html // @see http://www.delorie.com/djgpp/doc/rbinter/it/65/16.html // @see http://www.delorie.com/djgpp/doc/rbinter/it/66/16.html dosTime = date.getHours(); dosTime = dosTime << 6; dosTime = dosTime | date.getMinutes(); dosTime = dosTime << 5; dosTime = dosTime | date.getSeconds() / 2; dosDate = date.getFullYear() - 1980; dosDate = dosDate << 4; dosDate = dosDate | (date.getMonth() + 1); dosDate = dosDate << 5; dosDate = dosDate | date.getDate(); if (useUTF8ForFileName) { // set the unicode path extra field. unzip needs at least one extra // field to correctly handle unicode path, so using the path is as good // as any other information. This could improve the situation with // other archive managers too. // This field is usually used without the utf8 flag, with a non // unicode path in the header (winrar, winzip). This helps (a bit) // with the messy Windows' default compressed folders feature but // breaks on p7zip which doesn't seek the unicode path extra field. // So for now, UTF-8 everywhere ! unicodePathExtraField = // Version decToHex(1, 1) + // NameCRC32 decToHex(crc32(utfEncodedFileName), 4) + // UnicodeName utfEncodedFileName; extraFields += // Info-ZIP Unicode Path Extra Field "\x75\x70" + // size decToHex(unicodePathExtraField.length, 2) + // content unicodePathExtraField; } if(useUTF8ForComment) { unicodeCommentExtraField = // Version decToHex(1, 1) + // CommentCRC32 decToHex(this.crc32(utfEncodedComment), 4) + // UnicodeName utfEncodedComment; extraFields += // Info-ZIP Unicode Path Extra Field "\x75\x63" + // size decToHex(unicodeCommentExtraField.length, 2) + // content unicodeCommentExtraField; } var header = ""; // version needed to extract header += "\x0A\x00"; // general purpose bit flag // set bit 11 if utf8 header += (useUTF8ForFileName || useUTF8ForComment) ? "\x00\x08" : "\x00\x00"; // compression method header += compressedObject.compressionMethod; // last mod file time header += decToHex(dosTime, 2); // last mod file date header += decToHex(dosDate, 2); // crc-32 header += decToHex(compressedObject.crc32, 4); // compressed size header += decToHex(compressedObject.compressedSize, 4); // uncompressed size header += decToHex(compressedObject.uncompressedSize, 4); // file name length header += decToHex(utfEncodedFileName.length, 2); // extra field length header += decToHex(extraFields.length, 2); var fileRecord = signature.LOCAL_FILE_HEADER + header + utfEncodedFileName + extraFields; var dirRecord = signature.CENTRAL_FILE_HEADER + // version made by (00: DOS) decToHex(versionMadeBy, 2) + // file header (common to file and central directory) header + // file comment length decToHex(utfEncodedComment.length, 2) + // disk number start "\x00\x00" + // internal file attributes TODO "\x00\x00" + // external file attributes decToHex(extFileAttr, 4) + // relative offset of local header decToHex(offset, 4) + // file name utfEncodedFileName + // extra field extraFields + // file comment utfEncodedComment; return { fileRecord: fileRecord, dirRecord: dirRecord, compressedObject: compressedObject }; }; // return the actual prototype of JSZip var out = { /** * Read an existing zip and merge the data in the current JSZip object. * The implementation is in jszip-load.js, don't forget to include it. * @param {String|ArrayBuffer|Uint8Array|Buffer} stream The stream to load * @param {Object} options Options for loading the stream. * options.base64 : is the stream in base64 ? default : false * @return {JSZip} the current JSZip object */ load: function(stream, options) { throw new Error("Load method is not defined. Is the file jszip-load.js included ?"); }, /** * Filter nested files/folders with the specified function. * @param {Function} search the predicate to use : * function (relativePath, file) {...} * It takes 2 arguments : the relative path and the file. * @return {Array} An array of matching elements. */ filter: function(search) { var result = [], filename, relativePath, file, fileClone; for (filename in this.files) { if (!this.files.hasOwnProperty(filename)) { continue; } file = this.files[filename]; // return a new object, don't let the user mess with our internal objects :) fileClone = new ZipObject(file.name, file._data, extend(file.options)); relativePath = filename.slice(this.root.length, filename.length); if (filename.slice(0, this.root.length) === this.root && // the file is in the current root search(relativePath, fileClone)) { // and the file matches the function result.push(fileClone); } } return result; }, /** * Add a file to the zip file, or search a file. * @param {string|RegExp} name The name of the file to add (if data is defined), * the name of the file to find (if no data) or a regex to match files. * @param {String|ArrayBuffer|Uint8Array|Buffer} data The file data, either raw or base64 encoded * @param {Object} o File options * @return {JSZip|Object|Array} this JSZip object (when adding a file), * a file (when searching by string) or an array of files (when searching by regex). */ file: function(name, data, o) { if (arguments.length === 1) { if (utils.isRegExp(name)) { var regexp = name; return this.filter(function(relativePath, file) { return !file.dir && regexp.test(relativePath); }); } else { // text return this.filter(function(relativePath, file) { return !file.dir && relativePath === name; })[0] || null; } } else { // more than one argument : we have data ! name = this.root + name; fileAdd.call(this, name, data, o); } return this; }, /** * Add a directory to the zip file, or search. * @param {String|RegExp} arg The name of the directory to add, or a regex to search folders. * @return {JSZip} an object with the new directory as the root, or an array containing matching folders. */ folder: function(arg) { if (!arg) { return this; } if (utils.isRegExp(arg)) { return this.filter(function(relativePath, file) { return file.dir && arg.test(relativePath); }); } // else, name is a new folder var name = this.root + arg; var newFolder = folderAdd.call(this, name); // Allow chaining by returning a new object with this folder as the root var ret = this.clone(); ret.root = newFolder.name; return ret; }, /** * Delete a file, or a directory and all sub-files, from the zip * @param {string} name the name of the file to delete * @return {JSZip} this JSZip object */ remove: function(name) { name = this.root + name; var file = this.files[name]; if (!file) { // Look for any folders if (name.slice(-1) != "/") { name += "/"; } file = this.files[name]; } if (file && !file.dir) { // file delete this.files[name]; } else { // maybe a folder, delete recursively var kids = this.filter(function(relativePath, file) { return file.name.slice(0, name.length) === name; }); for (var i = 0; i < kids.length; i++) { delete this.files[kids[i].name]; } } return this; }, /** * Generate the complete zip file * @param {Object} options the options to generate the zip file : * - base64, (deprecated, use type instead) true to generate base64. * - compression, "STORE" by default. * - type, "base64" by default. Values are : string, base64, uint8array, arraybuffer, blob. * @return {String|Uint8Array|ArrayBuffer|Buffer|Blob} the zip file */ generate: function(options) { options = extend(options || {}, { base64: true, compression: "STORE", compressionOptions : null, type: "base64", platform: "DOS", comment: null, mimeType: 'application/zip' }); utils.checkSupport(options.type); // accept nodejs `process.platform` if( options.platform === 'darwin' || options.platform === 'freebsd' || options.platform === 'linux' || options.platform === 'sunos' ) { options.platform = "UNIX"; } if (options.platform === 'win32') { options.platform = "DOS"; } var zipData = [], localDirLength = 0, centralDirLength = 0, writer, i, utfEncodedComment = utils.transformTo("string", this.utf8encode(options.comment || this.comment || "")); // first, generate all the zip parts. for (var name in this.files) { if (!this.files.hasOwnProperty(name)) { continue; } var file = this.files[name]; var compressionName = file.options.compression || options.compression.toUpperCase(); var compression = compressions[compressionName]; if (!compression) { throw new Error(compressionName + " is not a valid compression method !"); } var compressionOptions = file.options.compressionOptions || options.compressionOptions || {}; var compressedObject = generateCompressedObjectFrom.call(this, file, compression, compressionOptions); var zipPart = generateZipParts.call(this, name, file, compressedObject, localDirLength, options.platform); localDirLength += zipPart.fileRecord.length + compressedObject.compressedSize; centralDirLength += zipPart.dirRecord.length; zipData.push(zipPart); } var dirEnd = ""; // end of central dir signature dirEnd = signature.CENTRAL_DIRECTORY_END + // number of this disk "\x00\x00" + // number of the disk with the start of the central directory "\x00\x00" + // total number of entries in the central directory on this disk decToHex(zipData.length, 2) + // total number of entries in the central directory decToHex(zipData.length, 2) + // size of the central directory 4 bytes decToHex(centralDirLength, 4) + // offset of start of central directory with respect to the starting disk number decToHex(localDirLength, 4) + // .ZIP file comment length decToHex(utfEncodedComment.length, 2) + // .ZIP file comment utfEncodedComment; // we have all the parts (and the total length) // time to create a writer ! var typeName = options.type.toLowerCase(); if(typeName==="uint8array"||typeName==="arraybuffer"||typeName==="blob"||typeName==="nodebuffer") { writer = new Uint8ArrayWriter(localDirLength + centralDirLength + dirEnd.length); }else{ writer = new StringWriter(localDirLength + centralDirLength + dirEnd.length); } for (i = 0; i < zipData.length; i++) { writer.append(zipData[i].fileRecord); writer.append(zipData[i].compressedObject.compressedContent); } for (i = 0; i < zipData.length; i++) { writer.append(zipData[i].dirRecord); } writer.append(dirEnd); var zip = writer.finalize(); switch(options.type.toLowerCase()) { // case "zip is an Uint8Array" case "uint8array" : case "arraybuffer" : case "nodebuffer" : return utils.transformTo(options.type.toLowerCase(), zip); case "blob" : return utils.arrayBuffer2Blob(utils.transformTo("arraybuffer", zip), options.mimeType); // case "zip is a string" case "base64" : return (options.base64) ? base64.encode(zip) : zip; default : // case "string" : return zip; } }, /** * @deprecated * This method will be removed in a future version without replacement. */ crc32: function (input, crc) { return crc32(input, crc); }, /** * @deprecated * This method will be removed in a future version without replacement. */ utf8encode: function (string) { return utils.transformTo("string", utf8.utf8encode(string)); }, /** * @deprecated * This method will be removed in a future version without replacement. */ utf8decode: function (input) { return utf8.utf8decode(input); } }; module.exports = out; },{"./base64":1,"./compressedObject":2,"./compressions":3,"./crc32":4,"./defaults":6,"./nodeBuffer":11,"./signature":14,"./stringWriter":16,"./support":17,"./uint8ArrayWriter":19,"./utf8":20,"./utils":21}],14:[function(_dereq_,module,exports){ 'use strict'; exports.LOCAL_FILE_HEADER = "PK\x03\x04"; exports.CENTRAL_FILE_HEADER = "PK\x01\x02"; exports.CENTRAL_DIRECTORY_END = "PK\x05\x06"; exports.ZIP64_CENTRAL_DIRECTORY_LOCATOR = "PK\x06\x07"; exports.ZIP64_CENTRAL_DIRECTORY_END = "PK\x06\x06"; exports.DATA_DESCRIPTOR = "PK\x07\x08"; },{}],15:[function(_dereq_,module,exports){ 'use strict'; var DataReader = _dereq_('./dataReader'); var utils = _dereq_('./utils'); function StringReader(data, optimizedBinaryString) { this.data = data; if (!optimizedBinaryString) { this.data = utils.string2binary(this.data); } this.length = this.data.length; this.index = 0; } StringReader.prototype = new DataReader(); /** * @see DataReader.byteAt */ StringReader.prototype.byteAt = function(i) { return this.data.charCodeAt(i); }; /** * @see DataReader.lastIndexOfSignature */ StringReader.prototype.lastIndexOfSignature = function(sig) { return this.data.lastIndexOf(sig); }; /** * @see DataReader.readData */ StringReader.prototype.readData = function(size) { this.checkOffset(size); // this will work because the constructor applied the "& 0xff" mask. var result = this.data.slice(this.index, this.index + size); this.index += size; return result; }; module.exports = StringReader; },{"./dataReader":5,"./utils":21}],16:[function(_dereq_,module,exports){ 'use strict'; var utils = _dereq_('./utils'); /** * An object to write any content to a string. * @constructor */ var StringWriter = function() { this.data = []; }; StringWriter.prototype = { /** * Append any content to the current string. * @param {Object} input the content to add. */ append: function(input) { input = utils.transformTo("string", input); this.data.push(input); }, /** * Finalize the construction an return the result. * @return {string} the generated string. */ finalize: function() { return this.data.join(""); } }; module.exports = StringWriter; },{"./utils":21}],17:[function(_dereq_,module,exports){ (function (Buffer){ 'use strict'; exports.base64 = true; exports.array = true; exports.string = true; exports.arraybuffer = typeof ArrayBuffer !== "undefined" && typeof Uint8Array !== "undefined"; // contains true if JSZip can read/generate nodejs Buffer, false otherwise. // Browserify will provide a Buffer implementation for browsers, which is // an augmented Uint8Array (i.e., can be used as either Buffer or U8). exports.nodebuffer = typeof Buffer !== "undefined"; // contains true if JSZip can read/generate Uint8Array, false otherwise. exports.uint8array = typeof Uint8Array !== "undefined"; if (typeof ArrayBuffer === "undefined") { exports.blob = false; } else { var buffer = new ArrayBuffer(0); try { exports.blob = new Blob([buffer], { type: "application/zip" }).size === 0; } catch (e) { try { var Builder = window.BlobBuilder || window.WebKitBlobBuilder || window.MozBlobBuilder || window.MSBlobBuilder; var builder = new Builder(); builder.append(buffer); exports.blob = builder.getBlob('application/zip').size === 0; } catch (e) { exports.blob = false; } } } }).call(this,(typeof Buffer !== "undefined" ? Buffer : undefined)) },{}],18:[function(_dereq_,module,exports){ 'use strict'; var DataReader = _dereq_('./dataReader'); function Uint8ArrayReader(data) { if (data) { this.data = data; this.length = this.data.length; this.index = 0; } } Uint8ArrayReader.prototype = new DataReader(); /** * @see DataReader.byteAt */ Uint8ArrayReader.prototype.byteAt = function(i) { return this.data[i]; }; /** * @see DataReader.lastIndexOfSignature */ Uint8ArrayReader.prototype.lastIndexOfSignature = function(sig) { var sig0 = sig.charCodeAt(0), sig1 = sig.charCodeAt(1), sig2 = sig.charCodeAt(2), sig3 = sig.charCodeAt(3); for (var i = this.length - 4; i >= 0; --i) { if (this.data[i] === sig0 && this.data[i + 1] === sig1 && this.data[i + 2] === sig2 && this.data[i + 3] === sig3) { return i; } } return -1; }; /** * @see DataReader.readData */ Uint8ArrayReader.prototype.readData = function(size) { this.checkOffset(size); if(size === 0) { // in IE10, when using subarray(idx, idx), we get the array [0x00] instead of []. return new Uint8Array(0); } var result = this.data.subarray(this.index, this.index + size); this.index += size; return result; }; module.exports = Uint8ArrayReader; },{"./dataReader":5}],19:[function(_dereq_,module,exports){ 'use strict'; var utils = _dereq_('./utils'); /** * An object to write any content to an Uint8Array. * @constructor * @param {number} length The length of the array. */ var Uint8ArrayWriter = function(length) { this.data = new Uint8Array(length); this.index = 0; }; Uint8ArrayWriter.prototype = { /** * Append any content to the current array. * @param {Object} input the content to add. */ append: function(input) { if (input.length !== 0) { // with an empty Uint8Array, Opera fails with a "Offset larger than array size" input = utils.transformTo("uint8array", input); this.data.set(input, this.index); this.index += input.length; } }, /** * Finalize the construction an return the result. * @return {Uint8Array} the generated array. */ finalize: function() { return this.data; } }; module.exports = Uint8ArrayWriter; },{"./utils":21}],20:[function(_dereq_,module,exports){ 'use strict'; var utils = _dereq_('./utils'); var support = _dereq_('./support'); var nodeBuffer = _dereq_('./nodeBuffer'); /** * The following functions come from pako, from pako/lib/utils/strings * released under the MIT license, see pako https://github.com/nodeca/pako/ */ // Table with utf8 lengths (calculated by first byte of sequence) // Note, that 5 & 6-byte values and some 4-byte values can not be represented in JS, // because max possible codepoint is 0x10ffff var _utf8len = new Array(256); for (var i=0; i<256; i++) { _utf8len[i] = (i >= 252 ? 6 : i >= 248 ? 5 : i >= 240 ? 4 : i >= 224 ? 3 : i >= 192 ? 2 : 1); } _utf8len[254]=_utf8len[254]=1; // Invalid sequence start // convert string to array (typed, when possible) var string2buf = function (str) { var buf, c, c2, m_pos, i, str_len = str.length, buf_len = 0; // count binary size for (m_pos = 0; m_pos < str_len; m_pos++) { c = str.charCodeAt(m_pos); if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) { c2 = str.charCodeAt(m_pos+1); if ((c2 & 0xfc00) === 0xdc00) { c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00); m_pos++; } } buf_len += c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4; } // allocate buffer if (support.uint8array) { buf = new Uint8Array(buf_len); } else { buf = new Array(buf_len); } // convert for (i=0, m_pos = 0; i < buf_len; m_pos++) { c = str.charCodeAt(m_pos); if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) { c2 = str.charCodeAt(m_pos+1); if ((c2 & 0xfc00) === 0xdc00) { c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00); m_pos++; } } if (c < 0x80) { /* one byte */ buf[i++] = c; } else if (c < 0x800) { /* two bytes */ buf[i++] = 0xC0 | (c >>> 6); buf[i++] = 0x80 | (c & 0x3f); } else if (c < 0x10000) { /* three bytes */ buf[i++] = 0xE0 | (c >>> 12); buf[i++] = 0x80 | (c >>> 6 & 0x3f); buf[i++] = 0x80 | (c & 0x3f); } else { /* four bytes */ buf[i++] = 0xf0 | (c >>> 18); buf[i++] = 0x80 | (c >>> 12 & 0x3f); buf[i++] = 0x80 | (c >>> 6 & 0x3f); buf[i++] = 0x80 | (c & 0x3f); } } return buf; }; // Calculate max possible position in utf8 buffer, // that will not break sequence. If that's not possible // - (very small limits) return max size as is. // // buf[] - utf8 bytes array // max - length limit (mandatory); var utf8border = function(buf, max) { var pos; max = max || buf.length; if (max > buf.length) { max = buf.length; } // go back from last position, until start of sequence found pos = max-1; while (pos >= 0 && (buf[pos] & 0xC0) === 0x80) { pos--; } // Fuckup - very small and broken sequence, // return max, because we should return something anyway. if (pos < 0) { return max; } // If we came to start of buffer - that means vuffer is too small, // return max too. if (pos === 0) { return max; } return (pos + _utf8len[buf[pos]] > max) ? pos : max; }; // convert array to string var buf2string = function (buf) { var str, i, out, c, c_len; var len = buf.length; // Reserve max possible length (2 words per char) // NB: by unknown reasons, Array is significantly faster for // String.fromCharCode.apply than Uint16Array. var utf16buf = new Array(len*2); for (out=0, i=0; i<len;) { c = buf[i++]; // quick process ascii if (c < 0x80) { utf16buf[out++] = c; continue; } c_len = _utf8len[c]; // skip 5 & 6 byte codes if (c_len > 4) { utf16buf[out++] = 0xfffd; i += c_len-1; continue; } // apply mask on first byte c &= c_len === 2 ? 0x1f : c_len === 3 ? 0x0f : 0x07; // join the rest while (c_len > 1 && i < len) { c = (c << 6) | (buf[i++] & 0x3f); c_len--; } // terminated by end of string? if (c_len > 1) { utf16buf[out++] = 0xfffd; continue; } if (c < 0x10000) { utf16buf[out++] = c; } else { c -= 0x10000; utf16buf[out++] = 0xd800 | ((c >> 10) & 0x3ff); utf16buf[out++] = 0xdc00 | (c & 0x3ff); } } // shrinkBuf(utf16buf, out) if (utf16buf.length !== out) { if(utf16buf.subarray) { utf16buf = utf16buf.subarray(0, out); } else { utf16buf.length = out; } } // return String.fromCharCode.apply(null, utf16buf); return utils.applyFromCharCode(utf16buf); }; // That's all for the pako functions. /** * Transform a javascript string into an array (typed if possible) of bytes, * UTF-8 encoded. * @param {String} str the string to encode * @return {Array|Uint8Array|Buffer} the UTF-8 encoded string. */ exports.utf8encode = function utf8encode(str) { if (support.nodebuffer) { return nodeBuffer(str, "utf-8"); } return string2buf(str); }; /** * Transform a bytes array (or a representation) representing an UTF-8 encoded * string into a javascript string. * @param {Array|Uint8Array|Buffer} buf the data de decode * @return {String} the decoded string. */ exports.utf8decode = function utf8decode(buf) { if (support.nodebuffer) { return utils.transformTo("nodebuffer", buf).toString("utf-8"); } buf = utils.transformTo(support.uint8array ? "uint8array" : "array", buf); // return buf2string(buf); // Chrome prefers to work with "small" chunks of data // for the method buf2string. // Firefox and Chrome has their own shortcut, IE doesn't seem to really care. var result = [], k = 0, len = buf.length, chunk = 65536; while (k < len) { var nextBoundary = utf8border(buf, Math.min(k + chunk, len)); if (support.uint8array) { result.push(buf2string(buf.subarray(k, nextBoundary))); } else { result.push(buf2string(buf.slice(k, nextBoundary))); } k = nextBoundary; } return result.join(""); }; // vim: set shiftwidth=4 softtabstop=4: },{"./nodeBuffer":11,"./support":17,"./utils":21}],21:[function(_dereq_,module,exports){ 'use strict'; var support = _dereq_('./support'); var compressions = _dereq_('./compressions'); var nodeBuffer = _dereq_('./nodeBuffer'); /** * Convert a string to a "binary string" : a string containing only char codes between 0 and 255. * @param {string} str the string to transform. * @return {String} the binary string. */ exports.string2binary = function(str) { var result = ""; for (var i = 0; i < str.length; i++) { result += String.fromCharCode(str.charCodeAt(i) & 0xff); } return result; }; exports.arrayBuffer2Blob = function(buffer, mimeType) { exports.checkSupport("blob"); mimeType = mimeType || 'application/zip'; try { // Blob constructor return new Blob([buffer], { type: mimeType }); } catch (e) { try { // deprecated, browser only, old way var Builder = window.BlobBuilder || window.WebKitBlobBuilder || window.MozBlobBuilder || window.MSBlobBuilder; var builder = new Builder(); builder.append(buffer); return builder.getBlob(mimeType); } catch (e) { // well, fuck ?! throw new Error("Bug : can't construct the Blob."); } } }; /** * The identity function. * @param {Object} input the input. * @return {Object} the same input. */ function identity(input) { return input; } /** * Fill in an array with a string. * @param {String} str the string to use. * @param {Array|ArrayBuffer|Uint8Array|Buffer} array the array to fill in (will be mutated). * @return {Array|ArrayBuffer|Uint8Array|Buffer} the updated array. */ function stringToArrayLike(str, array) { for (var i = 0; i < str.length; ++i) { array[i] = str.charCodeAt(i) & 0xFF; } return array; } /** * Transform an array-like object to a string. * @param {Array|ArrayBuffer|Uint8Array|Buffer} array the array to transform. * @return {String} the result. */ function arrayLikeToString(array) { // Performances notes : // -------------------- // String.fromCharCode.apply(null, array) is the fastest, see // see http://jsperf.com/converting-a-uint8array-to-a-string/2 // but the stack is limited (and we can get huge arrays !). // // result += String.fromCharCode(array[i]); generate too many strings ! // // This code is inspired by http://jsperf.com/arraybuffer-to-string-apply-performance/2 var chunk = 65536; var result = [], len = array.length, type = exports.getTypeOf(array), k = 0, canUseApply = true; try { switch(type) { case "uint8array": String.fromCharCode.apply(null, new Uint8Array(0)); break; case "nodebuffer": String.fromCharCode.apply(null, nodeBuffer(0)); break; } } catch(e) { canUseApply = false; } // no apply : slow and painful algorithm // default browser on android 4.* if (!canUseApply) { var resultStr = ""; for(var i = 0; i < array.length;i++) { resultStr += String.fromCharCode(array[i]); } return resultStr; } while (k < len && chunk > 1) { try { if (type === "array" || type === "nodebuffer") { result.push(String.fromCharCode.apply(null, array.slice(k, Math.min(k + chunk, len)))); } else { result.push(String.fromCharCode.apply(null, array.subarray(k, Math.min(k + chunk, len)))); } k += chunk; } catch (e) { chunk = Math.floor(chunk / 2); } } return result.join(""); } exports.applyFromCharCode = arrayLikeToString; /** * Copy the data from an array-like to an other array-like. * @param {Array|ArrayBuffer|Uint8Array|Buffer} arrayFrom the origin array. * @param {Array|ArrayBuffer|Uint8Array|Buffer} arrayTo the destination array which will be mutated. * @return {Array|ArrayBuffer|Uint8Array|Buffer} the updated destination array. */ function arrayLikeToArrayLike(arrayFrom, arrayTo) { for (var i = 0; i < arrayFrom.length; i++) { arrayTo[i] = arrayFrom[i]; } return arrayTo; } // a matrix containing functions to transform everything into everything. var transform = {}; // string to ? transform["string"] = { "string": identity, "array": function(input) { return stringToArrayLike(input, new Array(input.length)); }, "arraybuffer": function(input) { return transform["string"]["uint8array"](input).buffer; }, "uint8array": function(input) { return stringToArrayLike(input, new Uint8Array(input.length)); }, "nodebuffer": function(input) { return stringToArrayLike(input, nodeBuffer(input.length)); } }; // array to ? transform["array"] = { "string": arrayLikeToString, "array": identity, "arraybuffer": function(input) { return (new Uint8Array(input)).buffer; }, "uint8array": function(input) { return new Uint8Array(input); }, "nodebuffer": function(input) { return nodeBuffer(input); } }; // arraybuffer to ? transform["arraybuffer"] = { "string": function(input) { return arrayLikeToString(new Uint8Array(input)); }, "array": function(input) { return arrayLikeToArrayLike(new Uint8Array(input), new Array(input.byteLength)); }, "arraybuffer": identity, "uint8array": function(input) { return new Uint8Array(input); }, "nodebuffer": function(input) { return nodeBuffer(new Uint8Array(input)); } }; // uint8array to ? transform["uint8array"] = { "string": arrayLikeToString, "array": function(input) { return arrayLikeToArrayLike(input, new Array(input.length)); }, "arraybuffer": function(input) { return input.buffer; }, "uint8array": identity, "nodebuffer": function(input) { return nodeBuffer(input); } }; // nodebuffer to ? transform["nodebuffer"] = { "string": arrayLikeToString, "array": function(input) { return arrayLikeToArrayLike(input, new Array(input.length)); }, "arraybuffer": function(input) { return transform["nodebuffer"]["uint8array"](input).buffer; }, "uint8array": function(input) { return arrayLikeToArrayLike(input, new Uint8Array(input.length)); }, "nodebuffer": identity }; /** * Transform an input into any type. * The supported output type are : string, array, uint8array, arraybuffer, nodebuffer. * If no output type is specified, the unmodified input will be returned. * @param {String} outputType the output type. * @param {String|Array|ArrayBuffer|Uint8Array|Buffer} input the input to convert. * @throws {Error} an Error if the browser doesn't support the requested output type. */ exports.transformTo = function(outputType, input) { if (!input) { // undefined, null, etc // an empty string won't harm. input = ""; } if (!outputType) { return input; } exports.checkSupport(outputType); var inputType = exports.getTypeOf(input); var result = transform[inputType][outputType](input); return result; }; /** * Return the type of the input. * The type will be in a format valid for JSZip.utils.transformTo : string, array, uint8array, arraybuffer. * @param {Object} input the input to identify. * @return {String} the (lowercase) type of the input. */ exports.getTypeOf = function(input) { if (typeof input === "string") { return "string"; } if (Object.prototype.toString.call(input) === "[object Array]") { return "array"; } if (support.nodebuffer && nodeBuffer.test(input)) { return "nodebuffer"; } if (support.uint8array && input instanceof Uint8Array) { return "uint8array"; } if (support.arraybuffer && input instanceof ArrayBuffer) { return "arraybuffer"; } }; /** * Throw an exception if the type is not supported. * @param {String} type the type to check. * @throws {Error} an Error if the browser doesn't support the requested type. */ exports.checkSupport = function(type) { var supported = support[type.toLowerCase()]; if (!supported) { throw new Error(type + " is not supported by this browser"); } }; exports.MAX_VALUE_16BITS = 65535; exports.MAX_VALUE_32BITS = -1; // well, "\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF" is parsed as -1 /** * Prettify a string read as binary. * @param {string} str the string to prettify. * @return {string} a pretty string. */ exports.pretty = function(str) { var res = '', code, i; for (i = 0; i < (str || "").length; i++) { code = str.charCodeAt(i); res += '\\x' + (code < 16 ? "0" : "") + code.toString(16).toUpperCase(); } return res; }; /** * Find a compression registered in JSZip. * @param {string} compressionMethod the method magic to find. * @return {Object|null} the JSZip compression object, null if none found. */ exports.findCompression = function(compressionMethod) { for (var method in compressions) { if (!compressions.hasOwnProperty(method)) { continue; } if (compressions[method].magic === compressionMethod) { return compressions[method]; } } return null; }; /** * Cross-window, cross-Node-context regular expression detection * @param {Object} object Anything * @return {Boolean} true if the object is a regular expression, * false otherwise */ exports.isRegExp = function (object) { return Object.prototype.toString.call(object) === "[object RegExp]"; }; },{"./compressions":3,"./nodeBuffer":11,"./support":17}],22:[function(_dereq_,module,exports){ 'use strict'; var StringReader = _dereq_('./stringReader'); var NodeBufferReader = _dereq_('./nodeBufferReader'); var Uint8ArrayReader = _dereq_('./uint8ArrayReader'); var utils = _dereq_('./utils'); var sig = _dereq_('./signature'); var ZipEntry = _dereq_('./zipEntry'); var support = _dereq_('./support'); var jszipProto = _dereq_('./object'); // class ZipEntries {{{ /** * All the entries in the zip file. * @constructor * @param {String|ArrayBuffer|Uint8Array} data the binary stream to load. * @param {Object} loadOptions Options for loading the stream. */ function ZipEntries(data, loadOptions) { this.files = []; this.loadOptions = loadOptions; if (data) { this.load(data); } } ZipEntries.prototype = { /** * Check that the reader is on the speficied signature. * @param {string} expectedSignature the expected signature. * @throws {Error} if it is an other signature. */ checkSignature: function(expectedSignature) { var signature = this.reader.readString(4); if (signature !== expectedSignature) { throw new Error("Corrupted zip or bug : unexpected signature " + "(" + utils.pretty(signature) + ", expected " + utils.pretty(expectedSignature) + ")"); } }, /** * Read the end of the central directory. */ readBlockEndOfCentral: function() { this.diskNumber = this.reader.readInt(2); this.diskWithCentralDirStart = this.reader.readInt(2); this.centralDirRecordsOnThisDisk = this.reader.readInt(2); this.centralDirRecords = this.reader.readInt(2); this.centralDirSize = this.reader.readInt(4); this.centralDirOffset = this.reader.readInt(4); this.zipCommentLength = this.reader.readInt(2); // warning : the encoding depends of the system locale // On a linux machine with LANG=en_US.utf8, this field is utf8 encoded. // On a windows machine, this field is encoded with the localized windows code page. this.zipComment = this.reader.readString(this.zipCommentLength); // To get consistent behavior with the generation part, we will assume that // this is utf8 encoded. this.zipComment = jszipProto.utf8decode(this.zipComment); }, /** * Read the end of the Zip 64 central directory. * Not merged with the method readEndOfCentral : * The end of central can coexist with its Zip64 brother, * I don't want to read the wrong number of bytes ! */ readBlockZip64EndOfCentral: function() { this.zip64EndOfCentralSize = this.reader.readInt(8); this.versionMadeBy = this.reader.readString(2); this.versionNeeded = this.reader.readInt(2); this.diskNumber = this.reader.readInt(4); this.diskWithCentralDirStart = this.reader.readInt(4); this.centralDirRecordsOnThisDisk = this.reader.readInt(8); this.centralDirRecords = this.reader.readInt(8); this.centralDirSize = this.reader.readInt(8); this.centralDirOffset = this.reader.readInt(8); this.zip64ExtensibleData = {}; var extraDataSize = this.zip64EndOfCentralSize - 44, index = 0, extraFieldId, extraFieldLength, extraFieldValue; while (index < extraDataSize) { extraFieldId = this.reader.readInt(2); extraFieldLength = this.reader.readInt(4); extraFieldValue = this.reader.readString(extraFieldLength); this.zip64ExtensibleData[extraFieldId] = { id: extraFieldId, length: extraFieldLength, value: extraFieldValue }; } }, /** * Read the end of the Zip 64 central directory locator. */ readBlockZip64EndOfCentralLocator: function() { this.diskWithZip64CentralDirStart = this.reader.readInt(4); this.relativeOffsetEndOfZip64CentralDir = this.reader.readInt(8); this.disksCount = this.reader.readInt(4); if (this.disksCount > 1) { throw new Error("Multi-volumes zip are not supported"); } }, /** * Read the local files, based on the offset read in the central part. */ readLocalFiles: function() { var i, file; for (i = 0; i < this.files.length; i++) { file = this.files[i]; this.reader.setIndex(file.localHeaderOffset); this.checkSignature(sig.LOCAL_FILE_HEADER); file.readLocalPart(this.reader); file.handleUTF8(); file.processAttributes(); } }, /** * Read the central directory. */ readCentralDir: function() { var file; this.reader.setIndex(this.centralDirOffset); while (this.reader.readString(4) === sig.CENTRAL_FILE_HEADER) { file = new ZipEntry({ zip64: this.zip64 }, this.loadOptions); file.readCentralPart(this.reader); this.files.push(file); } }, /** * Read the end of central directory. */ readEndOfCentral: function() { var offset = this.reader.lastIndexOfSignature(sig.CENTRAL_DIRECTORY_END); if (offset === -1) { // Check if the content is a truncated zip or complete garbage. // A "LOCAL_FILE_HEADER" is not required at the beginning (auto // extractible zip for example) but it can give a good hint. // If an ajax request was used without responseType, we will also // get unreadable data. var isGarbage = true; try { this.reader.setIndex(0); this.checkSignature(sig.LOCAL_FILE_HEADER); isGarbage = false; } catch (e) {} if (isGarbage) { throw new Error("Can't find end of central directory : is this a zip file ? " + "If it is, see http://stuk.github.io/jszip/documentation/howto/read_zip.html"); } else { throw new Error("Corrupted zip : can't find end of central directory"); } } this.reader.setIndex(offset); this.checkSignature(sig.CENTRAL_DIRECTORY_END); this.readBlockEndOfCentral(); /* extract from the zip spec : 4) If one of the fields in the end of central directory record is too small to hold required data, the field should be set to -1 (0xFFFF or 0xFFFFFFFF) and the ZIP64 format record should be created. 5) The end of central directory record and the Zip64 end of central directory locator record must reside on the same disk when splitting or spanning an archive. */ if (this.diskNumber === utils.MAX_VALUE_16BITS || this.diskWithCentralDirStart === utils.MAX_VALUE_16BITS || this.centralDirRecordsOnThisDisk === utils.MAX_VALUE_16BITS || this.centralDirRecords === utils.MAX_VALUE_16BITS || this.centralDirSize === utils.MAX_VALUE_32BITS || this.centralDirOffset === utils.MAX_VALUE_32BITS) { this.zip64 = true; /* Warning : the zip64 extension is supported, but ONLY if the 64bits integer read from the zip file can fit into a 32bits integer. This cannot be solved : Javascript represents all numbers as 64-bit double precision IEEE 754 floating point numbers. So, we have 53bits for integers and bitwise operations treat everything as 32bits. see https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Operators/Bitwise_Operators and http://www.ecma-international.org/publications/files/ECMA-ST/ECMA-262.pdf section 8.5 */ // should look for a zip64 EOCD locator offset = this.reader.lastIndexOfSignature(sig.ZIP64_CENTRAL_DIRECTORY_LOCATOR); if (offset === -1) { throw new Error("Corrupted zip : can't find the ZIP64 end of central directory locator"); } this.reader.setIndex(offset); this.checkSignature(sig.ZIP64_CENTRAL_DIRECTORY_LOCATOR); this.readBlockZip64EndOfCentralLocator(); // now the zip64 EOCD record this.reader.setIndex(this.relativeOffsetEndOfZip64CentralDir); this.checkSignature(sig.ZIP64_CENTRAL_DIRECTORY_END); this.readBlockZip64EndOfCentral(); } }, prepareReader: function(data) { var type = utils.getTypeOf(data); if (type === "string" && !support.uint8array) { this.reader = new StringReader(data, this.loadOptions.optimizedBinaryString); } else if (type === "nodebuffer") { this.reader = new NodeBufferReader(data); } else { this.reader = new Uint8ArrayReader(utils.transformTo("uint8array", data)); } }, /** * Read a zip file and create ZipEntries. * @param {String|ArrayBuffer|Uint8Array|Buffer} data the binary string representing a zip file. */ load: function(data) { this.prepareReader(data); this.readEndOfCentral(); this.readCentralDir(); this.readLocalFiles(); } }; // }}} end of ZipEntries module.exports = ZipEntries; },{"./nodeBufferReader":12,"./object":13,"./signature":14,"./stringReader":15,"./support":17,"./uint8ArrayReader":18,"./utils":21,"./zipEntry":23}],23:[function(_dereq_,module,exports){ 'use strict'; var StringReader = _dereq_('./stringReader'); var utils = _dereq_('./utils'); var CompressedObject = _dereq_('./compressedObject'); var jszipProto = _dereq_('./object'); var MADE_BY_DOS = 0x00; var MADE_BY_UNIX = 0x03; // class ZipEntry {{{ /** * An entry in the zip file. * @constructor * @param {Object} options Options of the current file. * @param {Object} loadOptions Options for loading the stream. */ function ZipEntry(options, loadOptions) { this.options = options; this.loadOptions = loadOptions; } ZipEntry.prototype = { /** * say if the file is encrypted. * @return {boolean} true if the file is encrypted, false otherwise. */ isEncrypted: function() { // bit 1 is set return (this.bitFlag & 0x0001) === 0x0001; }, /** * say if the file has utf-8 filename/comment. * @return {boolean} true if the filename/comment is in utf-8, false otherwise. */ useUTF8: function() { // bit 11 is set return (this.bitFlag & 0x0800) === 0x0800; }, /** * Prepare the function used to generate the compressed content from this ZipFile. * @param {DataReader} reader the reader to use. * @param {number} from the offset from where we should read the data. * @param {number} length the length of the data to read. * @return {Function} the callback to get the compressed content (the type depends of the DataReader class). */ prepareCompressedContent: function(reader, from, length) { return function() { var previousIndex = reader.index; reader.setIndex(from); var compressedFileData = reader.readData(length); reader.setIndex(previousIndex); return compressedFileData; }; }, /** * Prepare the function used to generate the uncompressed content from this ZipFile. * @param {DataReader} reader the reader to use. * @param {number} from the offset from where we should read the data. * @param {number} length the length of the data to read. * @param {JSZip.compression} compression the compression used on this file. * @param {number} uncompressedSize the uncompressed size to expect. * @return {Function} the callback to get the uncompressed content (the type depends of the DataReader class). */ prepareContent: function(reader, from, length, compression, uncompressedSize) { return function() { var compressedFileData = utils.transformTo(compression.uncompressInputType, this.getCompressedContent()); var uncompressedFileData = compression.uncompress(compressedFileData); if (uncompressedFileData.length !== uncompressedSize) { throw new Error("Bug : uncompressed data size mismatch"); } return uncompressedFileData; }; }, /** * Read the local part of a zip file and add the info in this object. * @param {DataReader} reader the reader to use. */ readLocalPart: function(reader) { var compression, localExtraFieldsLength; // we already know everything from the central dir ! // If the central dir data are false, we are doomed. // On the bright side, the local part is scary : zip64, data descriptors, both, etc. // The less data we get here, the more reliable this should be. // Let's skip the whole header and dash to the data ! reader.skip(22); // in some zip created on windows, the filename stored in the central dir contains \ instead of /. // Strangely, the filename here is OK. // I would love to treat these zip files as corrupted (see http://www.info-zip.org/FAQ.html#backslashes // or APPNOTE#4.4.17.1, "All slashes MUST be forward slashes '/'") but there are a lot of bad zip generators... // Search "unzip mismatching "local" filename continuing with "central" filename version" on // the internet. // // I think I see the logic here : the central directory is used to display // content and the local directory is used to extract the files. Mixing / and \ // may be used to display \ to windows users and use / when extracting the files. // Unfortunately, this lead also to some issues : http://seclists.org/fulldisclosure/2009/Sep/394 this.fileNameLength = reader.readInt(2); localExtraFieldsLength = reader.readInt(2); // can't be sure this will be the same as the central dir this.fileName = reader.readString(this.fileNameLength); reader.skip(localExtraFieldsLength); if (this.compressedSize == -1 || this.uncompressedSize == -1) { throw new Error("Bug or corrupted zip : didn't get enough informations from the central directory " + "(compressedSize == -1 || uncompressedSize == -1)"); } compression = utils.findCompression(this.compressionMethod); if (compression === null) { // no compression found throw new Error("Corrupted zip : compression " + utils.pretty(this.compressionMethod) + " unknown (inner file : " + this.fileName + ")"); } this.decompressed = new CompressedObject(); this.decompressed.compressedSize = this.compressedSize; this.decompressed.uncompressedSize = this.uncompressedSize; this.decompressed.crc32 = this.crc32; this.decompressed.compressionMethod = this.compressionMethod; this.decompressed.getCompressedContent = this.prepareCompressedContent(reader, reader.index, this.compressedSize, compression); this.decompressed.getContent = this.prepareContent(reader, reader.index, this.compressedSize, compression, this.uncompressedSize); // we need to compute the crc32... if (this.loadOptions.checkCRC32) { this.decompressed = utils.transformTo("string", this.decompressed.getContent()); if (jszipProto.crc32(this.decompressed) !== this.crc32) { throw new Error("Corrupted zip : CRC32 mismatch"); } } }, /** * Read the central part of a zip file and add the info in this object. * @param {DataReader} reader the reader to use. */ readCentralPart: function(reader) { this.versionMadeBy = reader.readInt(2); this.versionNeeded = reader.readInt(2); this.bitFlag = reader.readInt(2); this.compressionMethod = reader.readString(2); this.date = reader.readDate(); this.crc32 = reader.readInt(4); this.compressedSize = reader.readInt(4); this.uncompressedSize = reader.readInt(4); this.fileNameLength = reader.readInt(2); this.extraFieldsLength = reader.readInt(2); this.fileCommentLength = reader.readInt(2); this.diskNumberStart = reader.readInt(2); this.internalFileAttributes = reader.readInt(2); this.externalFileAttributes = reader.readInt(4); this.localHeaderOffset = reader.readInt(4); if (this.isEncrypted()) { throw new Error("Encrypted zip are not supported"); } this.fileName = reader.readString(this.fileNameLength); this.readExtraFields(reader); this.parseZIP64ExtraField(reader); this.fileComment = reader.readString(this.fileCommentLength); }, /** * Parse the external file attributes and get the unix/dos permissions. */ processAttributes: function () { this.unixPermissions = null; this.dosPermissions = null; var madeBy = this.versionMadeBy >> 8; // Check if we have the DOS directory flag set. // We look for it in the DOS and UNIX permissions // but some unknown platform could set it as a compatibility flag. this.dir = this.externalFileAttributes & 0x0010 ? true : false; if(madeBy === MADE_BY_DOS) { // first 6 bits (0 to 5) this.dosPermissions = this.externalFileAttributes & 0x3F; } if(madeBy === MADE_BY_UNIX) { this.unixPermissions = (this.externalFileAttributes >> 16) & 0xFFFF; // the octal permissions are in (this.unixPermissions & 0x01FF).toString(8); } // fail safe : if the name ends with a / it probably means a folder if (!this.dir && this.fileName.slice(-1) === '/') { this.dir = true; } }, /** * Parse the ZIP64 extra field and merge the info in the current ZipEntry. * @param {DataReader} reader the reader to use. */ parseZIP64ExtraField: function(reader) { if (!this.extraFields[0x0001]) { return; } // should be something, preparing the extra reader var extraReader = new StringReader(this.extraFields[0x0001].value); // I really hope that these 64bits integer can fit in 32 bits integer, because js // won't let us have more. if (this.uncompressedSize === utils.MAX_VALUE_32BITS) { this.uncompressedSize = extraReader.readInt(8); } if (this.compressedSize === utils.MAX_VALUE_32BITS) { this.compressedSize = extraReader.readInt(8); } if (this.localHeaderOffset === utils.MAX_VALUE_32BITS) { this.localHeaderOffset = extraReader.readInt(8); } if (this.diskNumberStart === utils.MAX_VALUE_32BITS) { this.diskNumberStart = extraReader.readInt(4); } }, /** * Read the central part of a zip file and add the info in this object. * @param {DataReader} reader the reader to use. */ readExtraFields: function(reader) { var start = reader.index, extraFieldId, extraFieldLength, extraFieldValue; this.extraFields = this.extraFields || {}; while (reader.index < start + this.extraFieldsLength) { extraFieldId = reader.readInt(2); extraFieldLength = reader.readInt(2); extraFieldValue = reader.readString(extraFieldLength); this.extraFields[extraFieldId] = { id: extraFieldId, length: extraFieldLength, value: extraFieldValue }; } }, /** * Apply an UTF8 transformation if needed. */ handleUTF8: function() { if (this.useUTF8()) { this.fileName = jszipProto.utf8decode(this.fileName); this.fileComment = jszipProto.utf8decode(this.fileComment); } else { var upath = this.findExtraFieldUnicodePath(); if (upath !== null) { this.fileName = upath; } var ucomment = this.findExtraFieldUnicodeComment(); if (ucomment !== null) { this.fileComment = ucomment; } } }, /** * Find the unicode path declared in the extra field, if any. * @return {String} the unicode path, null otherwise. */ findExtraFieldUnicodePath: function() { var upathField = this.extraFields[0x7075]; if (upathField) { var extraReader = new StringReader(upathField.value); // wrong version if (extraReader.readInt(1) !== 1) { return null; } // the crc of the filename changed, this field is out of date. if (jszipProto.crc32(this.fileName) !== extraReader.readInt(4)) { return null; } return jszipProto.utf8decode(extraReader.readString(upathField.length - 5)); } return null; }, /** * Find the unicode comment declared in the extra field, if any. * @return {String} the unicode comment, null otherwise. */ findExtraFieldUnicodeComment: function() { var ucommentField = this.extraFields[0x6375]; if (ucommentField) { var extraReader = new StringReader(ucommentField.value); // wrong version if (extraReader.readInt(1) !== 1) { return null; } // the crc of the comment changed, this field is out of date. if (jszipProto.crc32(this.fileComment) !== extraReader.readInt(4)) { return null; } return jszipProto.utf8decode(extraReader.readString(ucommentField.length - 5)); } return null; } }; module.exports = ZipEntry; },{"./compressedObject":2,"./object":13,"./stringReader":15,"./utils":21}],24:[function(_dereq_,module,exports){ // Top level file is just a mixin of submodules & constants 'use strict'; var assign = _dereq_('./lib/utils/common').assign; var deflate = _dereq_('./lib/deflate'); var inflate = _dereq_('./lib/inflate'); var constants = _dereq_('./lib/zlib/constants'); var pako = {}; assign(pako, deflate, inflate, constants); module.exports = pako; },{"./lib/deflate":25,"./lib/inflate":26,"./lib/utils/common":27,"./lib/zlib/constants":30}],25:[function(_dereq_,module,exports){ 'use strict'; var zlib_deflate = _dereq_('./zlib/deflate.js'); var utils = _dereq_('./utils/common'); var strings = _dereq_('./utils/strings'); var msg = _dereq_('./zlib/messages'); var zstream = _dereq_('./zlib/zstream'); /* Public constants ==========================================================*/ /* ===========================================================================*/ var Z_NO_FLUSH = 0; var Z_FINISH = 4; var Z_OK = 0; var Z_STREAM_END = 1; var Z_DEFAULT_COMPRESSION = -1; var Z_DEFAULT_STRATEGY = 0; var Z_DEFLATED = 8; /* ===========================================================================*/ /** * class Deflate * * Generic JS-style wrapper for zlib calls. If you don't need * streaming behaviour - use more simple functions: [[deflate]], * [[deflateRaw]] and [[gzip]]. **/ /* internal * Deflate.chunks -> Array * * Chunks of output data, if [[Deflate#onData]] not overriden. **/ /** * Deflate.result -> Uint8Array|Array * * Compressed result, generated by default [[Deflate#onData]] * and [[Deflate#onEnd]] handlers. Filled after you push last chunk * (call [[Deflate#push]] with `Z_FINISH` / `true` param). **/ /** * Deflate.err -> Number * * Error code after deflate finished. 0 (Z_OK) on success. * You will not need it in real life, because deflate errors * are possible only on wrong options or bad `onData` / `onEnd` * custom handlers. **/ /** * Deflate.msg -> String * * Error message, if [[Deflate.err]] != 0 **/ /** * new Deflate(options) * - options (Object): zlib deflate options. * * Creates new deflator instance with specified params. Throws exception * on bad params. Supported options: * * - `level` * - `windowBits` * - `memLevel` * - `strategy` * * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced) * for more information on these. * * Additional options, for internal needs: * * - `chunkSize` - size of generated data chunks (16K by default) * - `raw` (Boolean) - do raw deflate * - `gzip` (Boolean) - create gzip wrapper * - `to` (String) - if equal to 'string', then result will be "binary string" * (each char code [0..255]) * - `header` (Object) - custom header for gzip * - `text` (Boolean) - true if compressed data believed to be text * - `time` (Number) - modification time, unix timestamp * - `os` (Number) - operation system code * - `extra` (Array) - array of bytes with extra data (max 65536) * - `name` (String) - file name (binary string) * - `comment` (String) - comment (binary string) * - `hcrc` (Boolean) - true if header crc should be added * * ##### Example: * * ```javascript * var pako = require('pako') * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9]) * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]); * * var deflate = new pako.Deflate({ level: 3}); * * deflate.push(chunk1, false); * deflate.push(chunk2, true); // true -> last chunk * * if (deflate.err) { throw new Error(deflate.err); } * * console.log(deflate.result); * ``` **/ var Deflate = function(options) { this.options = utils.assign({ level: Z_DEFAULT_COMPRESSION, method: Z_DEFLATED, chunkSize: 16384, windowBits: 15, memLevel: 8, strategy: Z_DEFAULT_STRATEGY, to: '' }, options || {}); var opt = this.options; if (opt.raw && (opt.windowBits > 0)) { opt.windowBits = -opt.windowBits; } else if (opt.gzip && (opt.windowBits > 0) && (opt.windowBits < 16)) { opt.windowBits += 16; } this.err = 0; // error code, if happens (0 = Z_OK) this.msg = ''; // error message this.ended = false; // used to avoid multiple onEnd() calls this.chunks = []; // chunks of compressed data this.strm = new zstream(); this.strm.avail_out = 0; var status = zlib_deflate.deflateInit2( this.strm, opt.level, opt.method, opt.windowBits, opt.memLevel, opt.strategy ); if (status !== Z_OK) { throw new Error(msg[status]); } if (opt.header) { zlib_deflate.deflateSetHeader(this.strm, opt.header); } }; /** * Deflate#push(data[, mode]) -> Boolean * - data (Uint8Array|Array|String): input data. Strings will be converted to * utf8 byte sequence. * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes. * See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH. * * Sends input data to deflate pipe, generating [[Deflate#onData]] calls with * new compressed chunks. Returns `true` on success. The last data block must have * mode Z_FINISH (or `true`). That flush internal pending buffers and call * [[Deflate#onEnd]]. * * On fail call [[Deflate#onEnd]] with error code and return false. * * We strongly recommend to use `Uint8Array` on input for best speed (output * array format is detected automatically). Also, don't skip last param and always * use the same type in your code (boolean or number). That will improve JS speed. * * For regular `Array`-s make sure all elements are [0..255]. * * ##### Example * * ```javascript * push(chunk, false); // push one of data chunks * ... * push(chunk, true); // push last chunk * ``` **/ Deflate.prototype.push = function(data, mode) { var strm = this.strm; var chunkSize = this.options.chunkSize; var status, _mode; if (this.ended) { return false; } _mode = (mode === ~~mode) ? mode : ((mode === true) ? Z_FINISH : Z_NO_FLUSH); // Convert data if needed if (typeof data === 'string') { // If we need to compress text, change encoding to utf8. strm.input = strings.string2buf(data); } else { strm.input = data; } strm.next_in = 0; strm.avail_in = strm.input.length; do { if (strm.avail_out === 0) { strm.output = new utils.Buf8(chunkSize); strm.next_out = 0; strm.avail_out = chunkSize; } status = zlib_deflate.deflate(strm, _mode); /* no bad return value */ if (status !== Z_STREAM_END && status !== Z_OK) { this.onEnd(status); this.ended = true; return false; } if (strm.avail_out === 0 || (strm.avail_in === 0 && _mode === Z_FINISH)) { if (this.options.to === 'string') { this.onData(strings.buf2binstring(utils.shrinkBuf(strm.output, strm.next_out))); } else { this.onData(utils.shrinkBuf(strm.output, strm.next_out)); } } } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== Z_STREAM_END); // Finalize on the last chunk. if (_mode === Z_FINISH) { status = zlib_deflate.deflateEnd(this.strm); this.onEnd(status); this.ended = true; return status === Z_OK; } return true; }; /** * Deflate#onData(chunk) -> Void * - chunk (Uint8Array|Array|String): ouput data. Type of array depends * on js engine support. When string output requested, each chunk * will be string. * * By default, stores data blocks in `chunks[]` property and glue * those in `onEnd`. Override this handler, if you need another behaviour. **/ Deflate.prototype.onData = function(chunk) { this.chunks.push(chunk); }; /** * Deflate#onEnd(status) -> Void * - status (Number): deflate status. 0 (Z_OK) on success, * other if not. * * Called once after you tell deflate that input stream complete * or error happenned. By default - join collected chunks, * free memory and fill `results` / `err` properties. **/ Deflate.prototype.onEnd = function(status) { // On success - join if (status === Z_OK) { if (this.options.to === 'string') { this.result = this.chunks.join(''); } else { this.result = utils.flattenChunks(this.chunks); } } this.chunks = []; this.err = status; this.msg = this.strm.msg; }; /** * deflate(data[, options]) -> Uint8Array|Array|String * - data (Uint8Array|Array|String): input data to compress. * - options (Object): zlib deflate options. * * Compress `data` with deflate alrorythm and `options`. * * Supported options are: * * - level * - windowBits * - memLevel * - strategy * * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced) * for more information on these. * * Sugar (options): * * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify * negative windowBits implicitly. * - `to` (String) - if equal to 'string', then result will be "binary string" * (each char code [0..255]) * * ##### Example: * * ```javascript * var pako = require('pako') * , data = Uint8Array([1,2,3,4,5,6,7,8,9]); * * console.log(pako.deflate(data)); * ``` **/ function deflate(input, options) { var deflator = new Deflate(options); deflator.push(input, true); // That will never happens, if you don't cheat with options :) if (deflator.err) { throw deflator.msg; } return deflator.result; } /** * deflateRaw(data[, options]) -> Uint8Array|Array|String * - data (Uint8Array|Array|String): input data to compress. * - options (Object): zlib deflate options. * * The same as [[deflate]], but creates raw data, without wrapper * (header and adler32 crc). **/ function deflateRaw(input, options) { options = options || {}; options.raw = true; return deflate(input, options); } /** * gzip(data[, options]) -> Uint8Array|Array|String * - data (Uint8Array|Array|String): input data to compress. * - options (Object): zlib deflate options. * * The same as [[deflate]], but create gzip wrapper instead of * deflate one. **/ function gzip(input, options) { options = options || {}; options.gzip = true; return deflate(input, options); } exports.Deflate = Deflate; exports.deflate = deflate; exports.deflateRaw = deflateRaw; exports.gzip = gzip; },{"./utils/common":27,"./utils/strings":28,"./zlib/deflate.js":32,"./zlib/messages":37,"./zlib/zstream":39}],26:[function(_dereq_,module,exports){ 'use strict'; var zlib_inflate = _dereq_('./zlib/inflate.js'); var utils = _dereq_('./utils/common'); var strings = _dereq_('./utils/strings'); var c = _dereq_('./zlib/constants'); var msg = _dereq_('./zlib/messages'); var zstream = _dereq_('./zlib/zstream'); var gzheader = _dereq_('./zlib/gzheader'); /** * class Inflate * * Generic JS-style wrapper for zlib calls. If you don't need * streaming behaviour - use more simple functions: [[inflate]] * and [[inflateRaw]]. **/ /* internal * inflate.chunks -> Array * * Chunks of output data, if [[Inflate#onData]] not overriden. **/ /** * Inflate.result -> Uint8Array|Array|String * * Uncompressed result, generated by default [[Inflate#onData]] * and [[Inflate#onEnd]] handlers. Filled after you push last chunk * (call [[Inflate#push]] with `Z_FINISH` / `true` param). **/ /** * Inflate.err -> Number * * Error code after inflate finished. 0 (Z_OK) on success. * Should be checked if broken data possible. **/ /** * Inflate.msg -> String * * Error message, if [[Inflate.err]] != 0 **/ /** * new Inflate(options) * - options (Object): zlib inflate options. * * Creates new inflator instance with specified params. Throws exception * on bad params. Supported options: * * - `windowBits` * * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced) * for more information on these. * * Additional options, for internal needs: * * - `chunkSize` - size of generated data chunks (16K by default) * - `raw` (Boolean) - do raw inflate * - `to` (String) - if equal to 'string', then result will be converted * from utf8 to utf16 (javascript) string. When string output requested, * chunk length can differ from `chunkSize`, depending on content. * * By default, when no options set, autodetect deflate/gzip data format via * wrapper header. * * ##### Example: * * ```javascript * var pako = require('pako') * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9]) * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]); * * var inflate = new pako.Inflate({ level: 3}); * * inflate.push(chunk1, false); * inflate.push(chunk2, true); // true -> last chunk * * if (inflate.err) { throw new Error(inflate.err); } * * console.log(inflate.result); * ``` **/ var Inflate = function(options) { this.options = utils.assign({ chunkSize: 16384, windowBits: 0, to: '' }, options || {}); var opt = this.options; // Force window size for `raw` data, if not set directly, // because we have no header for autodetect. if (opt.raw && (opt.windowBits >= 0) && (opt.windowBits < 16)) { opt.windowBits = -opt.windowBits; if (opt.windowBits === 0) { opt.windowBits = -15; } } // If `windowBits` not defined (and mode not raw) - set autodetect flag for gzip/deflate if ((opt.windowBits >= 0) && (opt.windowBits < 16) && !(options && options.windowBits)) { opt.windowBits += 32; } // Gzip header has no info about windows size, we can do autodetect only // for deflate. So, if window size not set, force it to max when gzip possible if ((opt.windowBits > 15) && (opt.windowBits < 48)) { // bit 3 (16) -> gzipped data // bit 4 (32) -> autodetect gzip/deflate if ((opt.windowBits & 15) === 0) { opt.windowBits |= 15; } } this.err = 0; // error code, if happens (0 = Z_OK) this.msg = ''; // error message this.ended = false; // used to avoid multiple onEnd() calls this.chunks = []; // chunks of compressed data this.strm = new zstream(); this.strm.avail_out = 0; var status = zlib_inflate.inflateInit2( this.strm, opt.windowBits ); if (status !== c.Z_OK) { throw new Error(msg[status]); } this.header = new gzheader(); zlib_inflate.inflateGetHeader(this.strm, this.header); }; /** * Inflate#push(data[, mode]) -> Boolean * - data (Uint8Array|Array|String): input data * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes. * See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH. * * Sends input data to inflate pipe, generating [[Inflate#onData]] calls with * new output chunks. Returns `true` on success. The last data block must have * mode Z_FINISH (or `true`). That flush internal pending buffers and call * [[Inflate#onEnd]]. * * On fail call [[Inflate#onEnd]] with error code and return false. * * We strongly recommend to use `Uint8Array` on input for best speed (output * format is detected automatically). Also, don't skip last param and always * use the same type in your code (boolean or number). That will improve JS speed. * * For regular `Array`-s make sure all elements are [0..255]. * * ##### Example * * ```javascript * push(chunk, false); // push one of data chunks * ... * push(chunk, true); // push last chunk * ``` **/ Inflate.prototype.push = function(data, mode) { var strm = this.strm; var chunkSize = this.options.chunkSize; var status, _mode; var next_out_utf8, tail, utf8str; if (this.ended) { return false; } _mode = (mode === ~~mode) ? mode : ((mode === true) ? c.Z_FINISH : c.Z_NO_FLUSH); // Convert data if needed if (typeof data === 'string') { // Only binary strings can be decompressed on practice strm.input = strings.binstring2buf(data); } else { strm.input = data; } strm.next_in = 0; strm.avail_in = strm.input.length; do { if (strm.avail_out === 0) { strm.output = new utils.Buf8(chunkSize); strm.next_out = 0; strm.avail_out = chunkSize; } status = zlib_inflate.inflate(strm, c.Z_NO_FLUSH); /* no bad return value */ if (status !== c.Z_STREAM_END && status !== c.Z_OK) { this.onEnd(status); this.ended = true; return false; } if (strm.next_out) { if (strm.avail_out === 0 || status === c.Z_STREAM_END || (strm.avail_in === 0 && _mode === c.Z_FINISH)) { if (this.options.to === 'string') { next_out_utf8 = strings.utf8border(strm.output, strm.next_out); tail = strm.next_out - next_out_utf8; utf8str = strings.buf2string(strm.output, next_out_utf8); // move tail strm.next_out = tail; strm.avail_out = chunkSize - tail; if (tail) { utils.arraySet(strm.output, strm.output, next_out_utf8, tail, 0); } this.onData(utf8str); } else { this.onData(utils.shrinkBuf(strm.output, strm.next_out)); } } } } while ((strm.avail_in > 0) && status !== c.Z_STREAM_END); if (status === c.Z_STREAM_END) { _mode = c.Z_FINISH; } // Finalize on the last chunk. if (_mode === c.Z_FINISH) { status = zlib_inflate.inflateEnd(this.strm); this.onEnd(status); this.ended = true; return status === c.Z_OK; } return true; }; /** * Inflate#onData(chunk) -> Void * - chunk (Uint8Array|Array|String): ouput data. Type of array depends * on js engine support. When string output requested, each chunk * will be string. * * By default, stores data blocks in `chunks[]` property and glue * those in `onEnd`. Override this handler, if you need another behaviour. **/ Inflate.prototype.onData = function(chunk) { this.chunks.push(chunk); }; /** * Inflate#onEnd(status) -> Void * - status (Number): inflate status. 0 (Z_OK) on success, * other if not. * * Called once after you tell inflate that input stream complete * or error happenned. By default - join collected chunks, * free memory and fill `results` / `err` properties. **/ Inflate.prototype.onEnd = function(status) { // On success - join if (status === c.Z_OK) { if (this.options.to === 'string') { // Glue & convert here, until we teach pako to send // utf8 alligned strings to onData this.result = this.chunks.join(''); } else { this.result = utils.flattenChunks(this.chunks); } } this.chunks = []; this.err = status; this.msg = this.strm.msg; }; /** * inflate(data[, options]) -> Uint8Array|Array|String * - data (Uint8Array|Array|String): input data to decompress. * - options (Object): zlib inflate options. * * Decompress `data` with inflate/ungzip and `options`. Autodetect * format via wrapper header by default. That's why we don't provide * separate `ungzip` method. * * Supported options are: * * - windowBits * * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced) * for more information. * * Sugar (options): * * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify * negative windowBits implicitly. * - `to` (String) - if equal to 'string', then result will be converted * from utf8 to utf16 (javascript) string. When string output requested, * chunk length can differ from `chunkSize`, depending on content. * * * ##### Example: * * ```javascript * var pako = require('pako') * , input = pako.deflate([1,2,3,4,5,6,7,8,9]) * , output; * * try { * output = pako.inflate(input); * } catch (err) * console.log(err); * } * ``` **/ function inflate(input, options) { var inflator = new Inflate(options); inflator.push(input, true); // That will never happens, if you don't cheat with options :) if (inflator.err) { throw inflator.msg; } return inflator.result; } /** * inflateRaw(data[, options]) -> Uint8Array|Array|String * - data (Uint8Array|Array|String): input data to decompress. * - options (Object): zlib inflate options. * * The same as [[inflate]], but creates raw data, without wrapper * (header and adler32 crc). **/ function inflateRaw(input, options) { options = options || {}; options.raw = true; return inflate(input, options); } /** * ungzip(data[, options]) -> Uint8Array|Array|String * - data (Uint8Array|Array|String): input data to decompress. * - options (Object): zlib inflate options. * * Just shortcut to [[inflate]], because it autodetects format * by header.content. Done for convenience. **/ exports.Inflate = Inflate; exports.inflate = inflate; exports.inflateRaw = inflateRaw; exports.ungzip = inflate; },{"./utils/common":27,"./utils/strings":28,"./zlib/constants":30,"./zlib/gzheader":33,"./zlib/inflate.js":35,"./zlib/messages":37,"./zlib/zstream":39}],27:[function(_dereq_,module,exports){ 'use strict'; var TYPED_OK = (typeof Uint8Array !== 'undefined') && (typeof Uint16Array !== 'undefined') && (typeof Int32Array !== 'undefined'); exports.assign = function (obj /*from1, from2, from3, ...*/) { var sources = Array.prototype.slice.call(arguments, 1); while (sources.length) { var source = sources.shift(); if (!source) { continue; } if (typeof(source) !== 'object') { throw new TypeError(source + 'must be non-object'); } for (var p in source) { if (source.hasOwnProperty(p)) { obj[p] = source[p]; } } } return obj; }; // reduce buffer size, avoiding mem copy exports.shrinkBuf = function (buf, size) { if (buf.length === size) { return buf; } if (buf.subarray) { return buf.subarray(0, size); } buf.length = size; return buf; }; var fnTyped = { arraySet: function (dest, src, src_offs, len, dest_offs) { if (src.subarray && dest.subarray) { dest.set(src.subarray(src_offs, src_offs+len), dest_offs); return; } // Fallback to ordinary array for(var i=0; i<len; i++) { dest[dest_offs + i] = src[src_offs + i]; } }, // Join array of chunks to single array. flattenChunks: function(chunks) { var i, l, len, pos, chunk, result; // calculate data length len = 0; for (i=0, l=chunks.length; i<l; i++) { len += chunks[i].length; } // join chunks result = new Uint8Array(len); pos = 0; for (i=0, l=chunks.length; i<l; i++) { chunk = chunks[i]; result.set(chunk, pos); pos += chunk.length; } return result; } }; var fnUntyped = { arraySet: function (dest, src, src_offs, len, dest_offs) { for(var i=0; i<len; i++) { dest[dest_offs + i] = src[src_offs + i]; } }, // Join array of chunks to single array. flattenChunks: function(chunks) { return [].concat.apply([], chunks); } }; // Enable/Disable typed arrays use, for testing // exports.setTyped = function (on) { if (on) { exports.Buf8 = Uint8Array; exports.Buf16 = Uint16Array; exports.Buf32 = Int32Array; exports.assign(exports, fnTyped); } else { exports.Buf8 = Array; exports.Buf16 = Array; exports.Buf32 = Array; exports.assign(exports, fnUntyped); } }; exports.setTyped(TYPED_OK); },{}],28:[function(_dereq_,module,exports){ // String encode/decode helpers 'use strict'; var utils = _dereq_('./common'); // Quick check if we can use fast array to bin string conversion // // - apply(Array) can fail on Android 2.2 // - apply(Uint8Array) can fail on iOS 5.1 Safary // var STR_APPLY_OK = true; var STR_APPLY_UIA_OK = true; try { String.fromCharCode.apply(null, [0]); } catch(__) { STR_APPLY_OK = false; } try { String.fromCharCode.apply(null, new Uint8Array(1)); } catch(__) { STR_APPLY_UIA_OK = false; } // Table with utf8 lengths (calculated by first byte of sequence) // Note, that 5 & 6-byte values and some 4-byte values can not be represented in JS, // because max possible codepoint is 0x10ffff var _utf8len = new utils.Buf8(256); for (var i=0; i<256; i++) { _utf8len[i] = (i >= 252 ? 6 : i >= 248 ? 5 : i >= 240 ? 4 : i >= 224 ? 3 : i >= 192 ? 2 : 1); } _utf8len[254]=_utf8len[254]=1; // Invalid sequence start // convert string to array (typed, when possible) exports.string2buf = function (str) { var buf, c, c2, m_pos, i, str_len = str.length, buf_len = 0; // count binary size for (m_pos = 0; m_pos < str_len; m_pos++) { c = str.charCodeAt(m_pos); if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) { c2 = str.charCodeAt(m_pos+1); if ((c2 & 0xfc00) === 0xdc00) { c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00); m_pos++; } } buf_len += c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4; } // allocate buffer buf = new utils.Buf8(buf_len); // convert for (i=0, m_pos = 0; i < buf_len; m_pos++) { c = str.charCodeAt(m_pos); if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) { c2 = str.charCodeAt(m_pos+1); if ((c2 & 0xfc00) === 0xdc00) { c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00); m_pos++; } } if (c < 0x80) { /* one byte */ buf[i++] = c; } else if (c < 0x800) { /* two bytes */ buf[i++] = 0xC0 | (c >>> 6); buf[i++] = 0x80 | (c & 0x3f); } else if (c < 0x10000) { /* three bytes */ buf[i++] = 0xE0 | (c >>> 12); buf[i++] = 0x80 | (c >>> 6 & 0x3f); buf[i++] = 0x80 | (c & 0x3f); } else { /* four bytes */ buf[i++] = 0xf0 | (c >>> 18); buf[i++] = 0x80 | (c >>> 12 & 0x3f); buf[i++] = 0x80 | (c >>> 6 & 0x3f); buf[i++] = 0x80 | (c & 0x3f); } } return buf; }; // Helper (used in 2 places) function buf2binstring(buf, len) { // use fallback for big arrays to avoid stack overflow if (len < 65537) { if ((buf.subarray && STR_APPLY_UIA_OK) || (!buf.subarray && STR_APPLY_OK)) { return String.fromCharCode.apply(null, utils.shrinkBuf(buf, len)); } } var result = ''; for(var i=0; i < len; i++) { result += String.fromCharCode(buf[i]); } return result; } // Convert byte array to binary string exports.buf2binstring = function(buf) { return buf2binstring(buf, buf.length); }; // Convert binary string (typed, when possible) exports.binstring2buf = function(str) { var buf = new utils.Buf8(str.length); for(var i=0, len=buf.length; i < len; i++) { buf[i] = str.charCodeAt(i); } return buf; }; // convert array to string exports.buf2string = function (buf, max) { var i, out, c, c_len; var len = max || buf.length; // Reserve max possible length (2 words per char) // NB: by unknown reasons, Array is significantly faster for // String.fromCharCode.apply than Uint16Array. var utf16buf = new Array(len*2); for (out=0, i=0; i<len;) { c = buf[i++]; // quick process ascii if (c < 0x80) { utf16buf[out++] = c; continue; } c_len = _utf8len[c]; // skip 5 & 6 byte codes if (c_len > 4) { utf16buf[out++] = 0xfffd; i += c_len-1; continue; } // apply mask on first byte c &= c_len === 2 ? 0x1f : c_len === 3 ? 0x0f : 0x07; // join the rest while (c_len > 1 && i < len) { c = (c << 6) | (buf[i++] & 0x3f); c_len--; } // terminated by end of string? if (c_len > 1) { utf16buf[out++] = 0xfffd; continue; } if (c < 0x10000) { utf16buf[out++] = c; } else { c -= 0x10000; utf16buf[out++] = 0xd800 | ((c >> 10) & 0x3ff); utf16buf[out++] = 0xdc00 | (c & 0x3ff); } } return buf2binstring(utf16buf, out); }; // Calculate max possible position in utf8 buffer, // that will not break sequence. If that's not possible // - (very small limits) return max size as is. // // buf[] - utf8 bytes array // max - length limit (mandatory); exports.utf8border = function(buf, max) { var pos; max = max || buf.length; if (max > buf.length) { max = buf.length; } // go back from last position, until start of sequence found pos = max-1; while (pos >= 0 && (buf[pos] & 0xC0) === 0x80) { pos--; } // Fuckup - very small and broken sequence, // return max, because we should return something anyway. if (pos < 0) { return max; } // If we came to start of buffer - that means vuffer is too small, // return max too. if (pos === 0) { return max; } return (pos + _utf8len[buf[pos]] > max) ? pos : max; }; },{"./common":27}],29:[function(_dereq_,module,exports){ 'use strict'; // Note: adler32 takes 12% for level 0 and 2% for level 6. // It doesn't worth to make additional optimizationa as in original. // Small size is preferable. function adler32(adler, buf, len, pos) { var s1 = (adler & 0xffff) |0 , s2 = ((adler >>> 16) & 0xffff) |0 , n = 0; while (len !== 0) { // Set limit ~ twice less than 5552, to keep // s2 in 31-bits, because we force signed ints. // in other case %= will fail. n = len > 2000 ? 2000 : len; len -= n; do { s1 = (s1 + buf[pos++]) |0; s2 = (s2 + s1) |0; } while (--n); s1 %= 65521; s2 %= 65521; } return (s1 | (s2 << 16)) |0; } module.exports = adler32; },{}],30:[function(_dereq_,module,exports){ module.exports = { /* Allowed flush values; see deflate() and inflate() below for details */ Z_NO_FLUSH: 0, Z_PARTIAL_FLUSH: 1, Z_SYNC_FLUSH: 2, Z_FULL_FLUSH: 3, Z_FINISH: 4, Z_BLOCK: 5, Z_TREES: 6, /* Return codes for the compression/decompression functions. Negative values * are errors, positive values are used for special but normal events. */ Z_OK: 0, Z_STREAM_END: 1, Z_NEED_DICT: 2, Z_ERRNO: -1, Z_STREAM_ERROR: -2, Z_DATA_ERROR: -3, //Z_MEM_ERROR: -4, Z_BUF_ERROR: -5, //Z_VERSION_ERROR: -6, /* compression levels */ Z_NO_COMPRESSION: 0, Z_BEST_SPEED: 1, Z_BEST_COMPRESSION: 9, Z_DEFAULT_COMPRESSION: -1, Z_FILTERED: 1, Z_HUFFMAN_ONLY: 2, Z_RLE: 3, Z_FIXED: 4, Z_DEFAULT_STRATEGY: 0, /* Possible values of the data_type field (though see inflate()) */ Z_BINARY: 0, Z_TEXT: 1, //Z_ASCII: 1, // = Z_TEXT (deprecated) Z_UNKNOWN: 2, /* The deflate compression method */ Z_DEFLATED: 8 //Z_NULL: null // Use -1 or null inline, depending on var type }; },{}],31:[function(_dereq_,module,exports){ 'use strict'; // Note: we can't get significant speed boost here. // So write code to minimize size - no pregenerated tables // and array tools dependencies. // Use ordinary array, since untyped makes no boost here function makeTable() { var c, table = []; for(var n =0; n < 256; n++){ c = n; for(var k =0; k < 8; k++){ c = ((c&1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1)); } table[n] = c; } return table; } // Create table on load. Just 255 signed longs. Not a problem. var crcTable = makeTable(); function crc32(crc, buf, len, pos) { var t = crcTable , end = pos + len; crc = crc ^ (-1); for (var i = pos; i < end; i++ ) { crc = (crc >>> 8) ^ t[(crc ^ buf[i]) & 0xFF]; } return (crc ^ (-1)); // >>> 0; } module.exports = crc32; },{}],32:[function(_dereq_,module,exports){ 'use strict'; var utils = _dereq_('../utils/common'); var trees = _dereq_('./trees'); var adler32 = _dereq_('./adler32'); var crc32 = _dereq_('./crc32'); var msg = _dereq_('./messages'); /* Public constants ==========================================================*/ /* ===========================================================================*/ /* Allowed flush values; see deflate() and inflate() below for details */ var Z_NO_FLUSH = 0; var Z_PARTIAL_FLUSH = 1; //var Z_SYNC_FLUSH = 2; var Z_FULL_FLUSH = 3; var Z_FINISH = 4; var Z_BLOCK = 5; //var Z_TREES = 6; /* Return codes for the compression/decompression functions. Negative values * are errors, positive values are used for special but normal events. */ var Z_OK = 0; var Z_STREAM_END = 1; //var Z_NEED_DICT = 2; //var Z_ERRNO = -1; var Z_STREAM_ERROR = -2; var Z_DATA_ERROR = -3; //var Z_MEM_ERROR = -4; var Z_BUF_ERROR = -5; //var Z_VERSION_ERROR = -6; /* compression levels */ //var Z_NO_COMPRESSION = 0; //var Z_BEST_SPEED = 1; //var Z_BEST_COMPRESSION = 9; var Z_DEFAULT_COMPRESSION = -1; var Z_FILTERED = 1; var Z_HUFFMAN_ONLY = 2; var Z_RLE = 3; var Z_FIXED = 4; var Z_DEFAULT_STRATEGY = 0; /* Possible values of the data_type field (though see inflate()) */ //var Z_BINARY = 0; //var Z_TEXT = 1; //var Z_ASCII = 1; // = Z_TEXT var Z_UNKNOWN = 2; /* The deflate compression method */ var Z_DEFLATED = 8; /*============================================================================*/ var MAX_MEM_LEVEL = 9; /* Maximum value for memLevel in deflateInit2 */ var MAX_WBITS = 15; /* 32K LZ77 window */ var DEF_MEM_LEVEL = 8; var LENGTH_CODES = 29; /* number of length codes, not counting the special END_BLOCK code */ var LITERALS = 256; /* number of literal bytes 0..255 */ var L_CODES = LITERALS + 1 + LENGTH_CODES; /* number of Literal or Length codes, including the END_BLOCK code */ var D_CODES = 30; /* number of distance codes */ var BL_CODES = 19; /* number of codes used to transfer the bit lengths */ var HEAP_SIZE = 2*L_CODES + 1; /* maximum heap size */ var MAX_BITS = 15; /* All codes must not exceed MAX_BITS bits */ var MIN_MATCH = 3; var MAX_MATCH = 258; var MIN_LOOKAHEAD = (MAX_MATCH + MIN_MATCH + 1); var PRESET_DICT = 0x20; var INIT_STATE = 42; var EXTRA_STATE = 69; var NAME_STATE = 73; var COMMENT_STATE = 91; var HCRC_STATE = 103; var BUSY_STATE = 113; var FINISH_STATE = 666; var BS_NEED_MORE = 1; /* block not completed, need more input or more output */ var BS_BLOCK_DONE = 2; /* block flush performed */ var BS_FINISH_STARTED = 3; /* finish started, need only more output at next deflate */ var BS_FINISH_DONE = 4; /* finish done, accept no more input or output */ var OS_CODE = 0x03; // Unix :) . Don't detect, use this default. function err(strm, errorCode) { strm.msg = msg[errorCode]; return errorCode; } function rank(f) { return ((f) << 1) - ((f) > 4 ? 9 : 0); } function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } } /* ========================================================================= * Flush as much pending output as possible. All deflate() output goes * through this function so some applications may wish to modify it * to avoid allocating a large strm->output buffer and copying into it. * (See also read_buf()). */ function flush_pending(strm) { var s = strm.state; //_tr_flush_bits(s); var len = s.pending; if (len > strm.avail_out) { len = strm.avail_out; } if (len === 0) { return; } utils.arraySet(strm.output, s.pending_buf, s.pending_out, len, strm.next_out); strm.next_out += len; s.pending_out += len; strm.total_out += len; strm.avail_out -= len; s.pending -= len; if (s.pending === 0) { s.pending_out = 0; } } function flush_block_only (s, last) { trees._tr_flush_block(s, (s.block_start >= 0 ? s.block_start : -1), s.strstart - s.block_start, last); s.block_start = s.strstart; flush_pending(s.strm); } function put_byte(s, b) { s.pending_buf[s.pending++] = b; } /* ========================================================================= * Put a short in the pending buffer. The 16-bit value is put in MSB order. * IN assertion: the stream state is correct and there is enough room in * pending_buf. */ function putShortMSB(s, b) { // put_byte(s, (Byte)(b >> 8)); // put_byte(s, (Byte)(b & 0xff)); s.pending_buf[s.pending++] = (b >>> 8) & 0xff; s.pending_buf[s.pending++] = b & 0xff; } /* =========================================================================== * Read a new buffer from the current input stream, update the adler32 * and total number of bytes read. All deflate() input goes through * this function so some applications may wish to modify it to avoid * allocating a large strm->input buffer and copying from it. * (See also flush_pending()). */ function read_buf(strm, buf, start, size) { var len = strm.avail_in; if (len > size) { len = size; } if (len === 0) { return 0; } strm.avail_in -= len; utils.arraySet(buf, strm.input, strm.next_in, len, start); if (strm.state.wrap === 1) { strm.adler = adler32(strm.adler, buf, len, start); } else if (strm.state.wrap === 2) { strm.adler = crc32(strm.adler, buf, len, start); } strm.next_in += len; strm.total_in += len; return len; } /* =========================================================================== * Set match_start to the longest match starting at the given string and * return its length. Matches shorter or equal to prev_length are discarded, * in which case the result is equal to prev_length and match_start is * garbage. * IN assertions: cur_match is the head of the hash chain for the current * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1 * OUT assertion: the match length is not greater than s->lookahead. */ function longest_match(s, cur_match) { var chain_length = s.max_chain_length; /* max hash chain length */ var scan = s.strstart; /* current string */ var match; /* matched string */ var len; /* length of current match */ var best_len = s.prev_length; /* best match length so far */ var nice_match = s.nice_match; /* stop if match long enough */ var limit = (s.strstart > (s.w_size - MIN_LOOKAHEAD)) ? s.strstart - (s.w_size - MIN_LOOKAHEAD) : 0/*NIL*/; var _win = s.window; // shortcut var wmask = s.w_mask; var prev = s.prev; /* Stop when cur_match becomes <= limit. To simplify the code, * we prevent matches with the string of window index 0. */ var strend = s.strstart + MAX_MATCH; var scan_end1 = _win[scan + best_len - 1]; var scan_end = _win[scan + best_len]; /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16. * It is easy to get rid of this optimization if necessary. */ // Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever"); /* Do not waste too much time if we already have a good match: */ if (s.prev_length >= s.good_match) { chain_length >>= 2; } /* Do not look for matches beyond the end of the input. This is necessary * to make deflate deterministic. */ if (nice_match > s.lookahead) { nice_match = s.lookahead; } // Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead"); do { // Assert(cur_match < s->strstart, "no future"); match = cur_match; /* Skip to next match if the match length cannot increase * or if the match length is less than 2. Note that the checks below * for insufficient lookahead only occur occasionally for performance * reasons. Therefore uninitialized memory will be accessed, and * conditional jumps will be made that depend on those values. * However the length of the match is limited to the lookahead, so * the output of deflate is not affected by the uninitialized values. */ if (_win[match + best_len] !== scan_end || _win[match + best_len - 1] !== scan_end1 || _win[match] !== _win[scan] || _win[++match] !== _win[scan + 1]) { continue; } /* The check at best_len-1 can be removed because it will be made * again later. (This heuristic is not always a win.) * It is not necessary to compare scan[2] and match[2] since they * are always equal when the other bytes match, given that * the hash keys are equal and that HASH_BITS >= 8. */ scan += 2; match++; // Assert(*scan == *match, "match[2]?"); /* We check for insufficient lookahead only every 8th comparison; * the 256th check will be made at strstart+258. */ do { /*jshint noempty:false*/ } while (_win[++scan] === _win[++match] && _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && scan < strend); // Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan"); len = MAX_MATCH - (strend - scan); scan = strend - MAX_MATCH; if (len > best_len) { s.match_start = cur_match; best_len = len; if (len >= nice_match) { break; } scan_end1 = _win[scan + best_len - 1]; scan_end = _win[scan + best_len]; } } while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length !== 0); if (best_len <= s.lookahead) { return best_len; } return s.lookahead; } /* =========================================================================== * Fill the window when the lookahead becomes insufficient. * Updates strstart and lookahead. * * IN assertion: lookahead < MIN_LOOKAHEAD * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD * At least one byte has been read, or avail_in == 0; reads are * performed for at least two bytes (required for the zip translate_eol * option -- not supported here). */ function fill_window(s) { var _w_size = s.w_size; var p, n, m, more, str; //Assert(s->lookahead < MIN_LOOKAHEAD, "already enough lookahead"); do { more = s.window_size - s.lookahead - s.strstart; // JS ints have 32 bit, block below not needed /* Deal with !@#$% 64K limit: */ //if (sizeof(int) <= 2) { // if (more == 0 && s->strstart == 0 && s->lookahead == 0) { // more = wsize; // // } else if (more == (unsigned)(-1)) { // /* Very unlikely, but possible on 16 bit machine if // * strstart == 0 && lookahead == 1 (input done a byte at time) // */ // more--; // } //} /* If the window is almost full and there is insufficient lookahead, * move the upper half to the lower one to make room in the upper half. */ if (s.strstart >= _w_size + (_w_size - MIN_LOOKAHEAD)) { utils.arraySet(s.window, s.window, _w_size, _w_size, 0); s.match_start -= _w_size; s.strstart -= _w_size; /* we now have strstart >= MAX_DIST */ s.block_start -= _w_size; /* Slide the hash table (could be avoided with 32 bit values at the expense of memory usage). We slide even when level == 0 to keep the hash table consistent if we switch back to level > 0 later. (Using level 0 permanently is not an optimal usage of zlib, so we don't care about this pathological case.) */ n = s.hash_size; p = n; do { m = s.head[--p]; s.head[p] = (m >= _w_size ? m - _w_size : 0); } while (--n); n = _w_size; p = n; do { m = s.prev[--p]; s.prev[p] = (m >= _w_size ? m - _w_size : 0); /* If n is not on any hash chain, prev[n] is garbage but * its value will never be used. */ } while (--n); more += _w_size; } if (s.strm.avail_in === 0) { break; } /* If there was no sliding: * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 && * more == window_size - lookahead - strstart * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1) * => more >= window_size - 2*WSIZE + 2 * In the BIG_MEM or MMAP case (not yet supported), * window_size == input_size + MIN_LOOKAHEAD && * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD. * Otherwise, window_size == 2*WSIZE so more >= 2. * If there was sliding, more >= WSIZE. So in all cases, more >= 2. */ //Assert(more >= 2, "more < 2"); n = read_buf(s.strm, s.window, s.strstart + s.lookahead, more); s.lookahead += n; /* Initialize the hash value now that we have some input: */ if (s.lookahead + s.insert >= MIN_MATCH) { str = s.strstart - s.insert; s.ins_h = s.window[str]; /* UPDATE_HASH(s, s->ins_h, s->window[str + 1]); */ s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + 1]) & s.hash_mask; //#if MIN_MATCH != 3 // Call update_hash() MIN_MATCH-3 more times //#endif while (s.insert) { /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */ s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH-1]) & s.hash_mask; s.prev[str & s.w_mask] = s.head[s.ins_h]; s.head[s.ins_h] = str; str++; s.insert--; if (s.lookahead + s.insert < MIN_MATCH) { break; } } } /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage, * but this is not important since only literal bytes will be emitted. */ } while (s.lookahead < MIN_LOOKAHEAD && s.strm.avail_in !== 0); /* If the WIN_INIT bytes after the end of the current data have never been * written, then zero those bytes in order to avoid memory check reports of * the use of uninitialized (or uninitialised as Julian writes) bytes by * the longest match routines. Update the high water mark for the next * time through here. WIN_INIT is set to MAX_MATCH since the longest match * routines allow scanning to strstart + MAX_MATCH, ignoring lookahead. */ // if (s.high_water < s.window_size) { // var curr = s.strstart + s.lookahead; // var init = 0; // // if (s.high_water < curr) { // /* Previous high water mark below current data -- zero WIN_INIT // * bytes or up to end of window, whichever is less. // */ // init = s.window_size - curr; // if (init > WIN_INIT) // init = WIN_INIT; // zmemzero(s->window + curr, (unsigned)init); // s->high_water = curr + init; // } // else if (s->high_water < (ulg)curr + WIN_INIT) { // /* High water mark at or above current data, but below current data // * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up // * to end of window, whichever is less. // */ // init = (ulg)curr + WIN_INIT - s->high_water; // if (init > s->window_size - s->high_water) // init = s->window_size - s->high_water; // zmemzero(s->window + s->high_water, (unsigned)init); // s->high_water += init; // } // } // // Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD, // "not enough room for search"); } /* =========================================================================== * Copy without compression as much as possible from the input stream, return * the current block state. * This function does not insert new strings in the dictionary since * uncompressible data is probably not useful. This function is used * only for the level=0 compression option. * NOTE: this function should be optimized to avoid extra copying from * window to pending_buf. */ function deflate_stored(s, flush) { /* Stored blocks are limited to 0xffff bytes, pending_buf is limited * to pending_buf_size, and each stored block has a 5 byte header: */ var max_block_size = 0xffff; if (max_block_size > s.pending_buf_size - 5) { max_block_size = s.pending_buf_size - 5; } /* Copy as much as possible from input to output: */ for (;;) { /* Fill the window as much as possible: */ if (s.lookahead <= 1) { //Assert(s->strstart < s->w_size+MAX_DIST(s) || // s->block_start >= (long)s->w_size, "slide too late"); // if (!(s.strstart < s.w_size + (s.w_size - MIN_LOOKAHEAD) || // s.block_start >= s.w_size)) { // throw new Error("slide too late"); // } fill_window(s); if (s.lookahead === 0 && flush === Z_NO_FLUSH) { return BS_NEED_MORE; } if (s.lookahead === 0) { break; } /* flush the current block */ } //Assert(s->block_start >= 0L, "block gone"); // if (s.block_start < 0) throw new Error("block gone"); s.strstart += s.lookahead; s.lookahead = 0; /* Emit a stored block if pending_buf will be full: */ var max_start = s.block_start + max_block_size; if (s.strstart === 0 || s.strstart >= max_start) { /* strstart == 0 is possible when wraparound on 16-bit machine */ s.lookahead = s.strstart - max_start; s.strstart = max_start; /*** FLUSH_BLOCK(s, 0); ***/ flush_block_only(s, false); if (s.strm.avail_out === 0) { return BS_NEED_MORE; } /***/ } /* Flush if we may have to slide, otherwise block_start may become * negative and the data will be gone: */ if (s.strstart - s.block_start >= (s.w_size - MIN_LOOKAHEAD)) { /*** FLUSH_BLOCK(s, 0); ***/ flush_block_only(s, false); if (s.strm.avail_out === 0) { return BS_NEED_MORE; } /***/ } } s.insert = 0; if (flush === Z_FINISH) { /*** FLUSH_BLOCK(s, 1); ***/ flush_block_only(s, true); if (s.strm.avail_out === 0) { return BS_FINISH_STARTED; } /***/ return BS_FINISH_DONE; } if (s.strstart > s.block_start) { /*** FLUSH_BLOCK(s, 0); ***/ flush_block_only(s, false); if (s.strm.avail_out === 0) { return BS_NEED_MORE; } /***/ } return BS_NEED_MORE; } /* =========================================================================== * Compress as much as possible from the input stream, return the current * block state. * This function does not perform lazy evaluation of matches and inserts * new strings in the dictionary only for unmatched strings or for short * matches. It is used only for the fast compression options. */ function deflate_fast(s, flush) { var hash_head; /* head of the hash chain */ var bflush; /* set if current block must be flushed */ for (;;) { /* Make sure that we always have enough lookahead, except * at the end of the input file. We need MAX_MATCH bytes * for the next match, plus MIN_MATCH bytes to insert the * string following the next match. */ if (s.lookahead < MIN_LOOKAHEAD) { fill_window(s); if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) { return BS_NEED_MORE; } if (s.lookahead === 0) { break; /* flush the current block */ } } /* Insert the string window[strstart .. strstart+2] in the * dictionary, and set hash_head to the head of the hash chain: */ hash_head = 0/*NIL*/; if (s.lookahead >= MIN_MATCH) { /*** INSERT_STRING(s, s.strstart, hash_head); ***/ s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask; hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h]; s.head[s.ins_h] = s.strstart; /***/ } /* Find the longest match, discarding those <= prev_length. * At this point we have always match_length < MIN_MATCH */ if (hash_head !== 0/*NIL*/ && ((s.strstart - hash_head) <= (s.w_size - MIN_LOOKAHEAD))) { /* To simplify the code, we prevent matches with the string * of window index 0 (in particular we have to avoid a match * of the string with itself at the start of the input file). */ s.match_length = longest_match(s, hash_head); /* longest_match() sets match_start */ } if (s.match_length >= MIN_MATCH) { // check_match(s, s.strstart, s.match_start, s.match_length); // for debug only /*** _tr_tally_dist(s, s.strstart - s.match_start, s.match_length - MIN_MATCH, bflush); ***/ bflush = trees._tr_tally(s, s.strstart - s.match_start, s.match_length - MIN_MATCH); s.lookahead -= s.match_length; /* Insert new strings in the hash table only if the match length * is not too large. This saves time but degrades compression. */ if (s.match_length <= s.max_lazy_match/*max_insert_length*/ && s.lookahead >= MIN_MATCH) { s.match_length--; /* string at strstart already in table */ do { s.strstart++; /*** INSERT_STRING(s, s.strstart, hash_head); ***/ s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask; hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h]; s.head[s.ins_h] = s.strstart; /***/ /* strstart never exceeds WSIZE-MAX_MATCH, so there are * always MIN_MATCH bytes ahead. */ } while (--s.match_length !== 0); s.strstart++; } else { s.strstart += s.match_length; s.match_length = 0; s.ins_h = s.window[s.strstart]; /* UPDATE_HASH(s, s.ins_h, s.window[s.strstart+1]); */ s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + 1]) & s.hash_mask; //#if MIN_MATCH != 3 // Call UPDATE_HASH() MIN_MATCH-3 more times //#endif /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not * matter since it will be recomputed at next deflate call. */ } } else { /* No match, output a literal byte */ //Tracevv((stderr,"%c", s.window[s.strstart])); /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/ bflush = trees._tr_tally(s, 0, s.window[s.strstart]); s.lookahead--; s.strstart++; } if (bflush) { /*** FLUSH_BLOCK(s, 0); ***/ flush_block_only(s, false); if (s.strm.avail_out === 0) { return BS_NEED_MORE; } /***/ } } s.insert = ((s.strstart < (MIN_MATCH-1)) ? s.strstart : MIN_MATCH-1); if (flush === Z_FINISH) { /*** FLUSH_BLOCK(s, 1); ***/ flush_block_only(s, true); if (s.strm.avail_out === 0) { return BS_FINISH_STARTED; } /***/ return BS_FINISH_DONE; } if (s.last_lit) { /*** FLUSH_BLOCK(s, 0); ***/ flush_block_only(s, false); if (s.strm.avail_out === 0) { return BS_NEED_MORE; } /***/ } return BS_BLOCK_DONE; } /* =========================================================================== * Same as above, but achieves better compression. We use a lazy * evaluation for matches: a match is finally adopted only if there is * no better match at the next window position. */ function deflate_slow(s, flush) { var hash_head; /* head of hash chain */ var bflush; /* set if current block must be flushed */ var max_insert; /* Process the input block. */ for (;;) { /* Make sure that we always have enough lookahead, except * at the end of the input file. We need MAX_MATCH bytes * for the next match, plus MIN_MATCH bytes to insert the * string following the next match. */ if (s.lookahead < MIN_LOOKAHEAD) { fill_window(s); if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) { return BS_NEED_MORE; } if (s.lookahead === 0) { break; } /* flush the current block */ } /* Insert the string window[strstart .. strstart+2] in the * dictionary, and set hash_head to the head of the hash chain: */ hash_head = 0/*NIL*/; if (s.lookahead >= MIN_MATCH) { /*** INSERT_STRING(s, s.strstart, hash_head); ***/ s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask; hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h]; s.head[s.ins_h] = s.strstart; /***/ } /* Find the longest match, discarding those <= prev_length. */ s.prev_length = s.match_length; s.prev_match = s.match_start; s.match_length = MIN_MATCH-1; if (hash_head !== 0/*NIL*/ && s.prev_length < s.max_lazy_match && s.strstart - hash_head <= (s.w_size-MIN_LOOKAHEAD)/*MAX_DIST(s)*/) { /* To simplify the code, we prevent matches with the string * of window index 0 (in particular we have to avoid a match * of the string with itself at the start of the input file). */ s.match_length = longest_match(s, hash_head); /* longest_match() sets match_start */ if (s.match_length <= 5 && (s.strategy === Z_FILTERED || (s.match_length === MIN_MATCH && s.strstart - s.match_start > 4096/*TOO_FAR*/))) { /* If prev_match is also MIN_MATCH, match_start is garbage * but we will ignore the current match anyway. */ s.match_length = MIN_MATCH-1; } } /* If there was a match at the previous step and the current * match is not better, output the previous match: */ if (s.prev_length >= MIN_MATCH && s.match_length <= s.prev_length) { max_insert = s.strstart + s.lookahead - MIN_MATCH; /* Do not insert strings in hash table beyond this. */ //check_match(s, s.strstart-1, s.prev_match, s.prev_length); /***_tr_tally_dist(s, s.strstart - 1 - s.prev_match, s.prev_length - MIN_MATCH, bflush);***/ bflush = trees._tr_tally(s, s.strstart - 1- s.prev_match, s.prev_length - MIN_MATCH); /* Insert in hash table all strings up to the end of the match. * strstart-1 and strstart are already inserted. If there is not * enough lookahead, the last two strings are not inserted in * the hash table. */ s.lookahead -= s.prev_length-1; s.prev_length -= 2; do { if (++s.strstart <= max_insert) { /*** INSERT_STRING(s, s.strstart, hash_head); ***/ s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask; hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h]; s.head[s.ins_h] = s.strstart; /***/ } } while (--s.prev_length !== 0); s.match_available = 0; s.match_length = MIN_MATCH-1; s.strstart++; if (bflush) { /*** FLUSH_BLOCK(s, 0); ***/ flush_block_only(s, false); if (s.strm.avail_out === 0) { return BS_NEED_MORE; } /***/ } } else if (s.match_available) { /* If there was no match at the previous position, output a * single literal. If there was a match but the current match * is longer, truncate the previous match to a single literal. */ //Tracevv((stderr,"%c", s->window[s->strstart-1])); /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/ bflush = trees._tr_tally(s, 0, s.window[s.strstart-1]); if (bflush) { /*** FLUSH_BLOCK_ONLY(s, 0) ***/ flush_block_only(s, false); /***/ } s.strstart++; s.lookahead--; if (s.strm.avail_out === 0) { return BS_NEED_MORE; } } else { /* There is no previous match to compare with, wait for * the next step to decide. */ s.match_available = 1; s.strstart++; s.lookahead--; } } //Assert (flush != Z_NO_FLUSH, "no flush?"); if (s.match_available) { //Tracevv((stderr,"%c", s->window[s->strstart-1])); /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/ bflush = trees._tr_tally(s, 0, s.window[s.strstart-1]); s.match_available = 0; } s.insert = s.strstart < MIN_MATCH-1 ? s.strstart : MIN_MATCH-1; if (flush === Z_FINISH) { /*** FLUSH_BLOCK(s, 1); ***/ flush_block_only(s, true); if (s.strm.avail_out === 0) { return BS_FINISH_STARTED; } /***/ return BS_FINISH_DONE; } if (s.last_lit) { /*** FLUSH_BLOCK(s, 0); ***/ flush_block_only(s, false); if (s.strm.avail_out === 0) { return BS_NEED_MORE; } /***/ } return BS_BLOCK_DONE; } /* =========================================================================== * For Z_RLE, simply look for runs of bytes, generate matches only of distance * one. Do not maintain a hash table. (It will be regenerated if this run of * deflate switches away from Z_RLE.) */ function deflate_rle(s, flush) { var bflush; /* set if current block must be flushed */ var prev; /* byte at distance one to match */ var scan, strend; /* scan goes up to strend for length of run */ var _win = s.window; for (;;) { /* Make sure that we always have enough lookahead, except * at the end of the input file. We need MAX_MATCH bytes * for the longest run, plus one for the unrolled loop. */ if (s.lookahead <= MAX_MATCH) { fill_window(s); if (s.lookahead <= MAX_MATCH && flush === Z_NO_FLUSH) { return BS_NEED_MORE; } if (s.lookahead === 0) { break; } /* flush the current block */ } /* See how many times the previous byte repeats */ s.match_length = 0; if (s.lookahead >= MIN_MATCH && s.strstart > 0) { scan = s.strstart - 1; prev = _win[scan]; if (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan]) { strend = s.strstart + MAX_MATCH; do { /*jshint noempty:false*/ } while (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan] && scan < strend); s.match_length = MAX_MATCH - (strend - scan); if (s.match_length > s.lookahead) { s.match_length = s.lookahead; } } //Assert(scan <= s->window+(uInt)(s->window_size-1), "wild scan"); } /* Emit match if have run of MIN_MATCH or longer, else emit literal */ if (s.match_length >= MIN_MATCH) { //check_match(s, s.strstart, s.strstart - 1, s.match_length); /*** _tr_tally_dist(s, 1, s.match_length - MIN_MATCH, bflush); ***/ bflush = trees._tr_tally(s, 1, s.match_length - MIN_MATCH); s.lookahead -= s.match_length; s.strstart += s.match_length; s.match_length = 0; } else { /* No match, output a literal byte */ //Tracevv((stderr,"%c", s->window[s->strstart])); /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/ bflush = trees._tr_tally(s, 0, s.window[s.strstart]); s.lookahead--; s.strstart++; } if (bflush) { /*** FLUSH_BLOCK(s, 0); ***/ flush_block_only(s, false); if (s.strm.avail_out === 0) { return BS_NEED_MORE; } /***/ } } s.insert = 0; if (flush === Z_FINISH) { /*** FLUSH_BLOCK(s, 1); ***/ flush_block_only(s, true); if (s.strm.avail_out === 0) { return BS_FINISH_STARTED; } /***/ return BS_FINISH_DONE; } if (s.last_lit) { /*** FLUSH_BLOCK(s, 0); ***/ flush_block_only(s, false); if (s.strm.avail_out === 0) { return BS_NEED_MORE; } /***/ } return BS_BLOCK_DONE; } /* =========================================================================== * For Z_HUFFMAN_ONLY, do not look for matches. Do not maintain a hash table. * (It will be regenerated if this run of deflate switches away from Huffman.) */ function deflate_huff(s, flush) { var bflush; /* set if current block must be flushed */ for (;;) { /* Make sure that we have a literal to write. */ if (s.lookahead === 0) { fill_window(s); if (s.lookahead === 0) { if (flush === Z_NO_FLUSH) { return BS_NEED_MORE; } break; /* flush the current block */ } } /* Output a literal byte */ s.match_length = 0; //Tracevv((stderr,"%c", s->window[s->strstart])); /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/ bflush = trees._tr_tally(s, 0, s.window[s.strstart]); s.lookahead--; s.strstart++; if (bflush) { /*** FLUSH_BLOCK(s, 0); ***/ flush_block_only(s, false); if (s.strm.avail_out === 0) { return BS_NEED_MORE; } /***/ } } s.insert = 0; if (flush === Z_FINISH) { /*** FLUSH_BLOCK(s, 1); ***/ flush_block_only(s, true); if (s.strm.avail_out === 0) { return BS_FINISH_STARTED; } /***/ return BS_FINISH_DONE; } if (s.last_lit) { /*** FLUSH_BLOCK(s, 0); ***/ flush_block_only(s, false); if (s.strm.avail_out === 0) { return BS_NEED_MORE; } /***/ } return BS_BLOCK_DONE; } /* Values for max_lazy_match, good_match and max_chain_length, depending on * the desired pack level (0..9). The values given below have been tuned to * exclude worst case performance for pathological files. Better values may be * found for specific files. */ var Config = function (good_length, max_lazy, nice_length, max_chain, func) { this.good_length = good_length; this.max_lazy = max_lazy; this.nice_length = nice_length; this.max_chain = max_chain; this.func = func; }; var configuration_table; configuration_table = [ /* good lazy nice chain */ new Config(0, 0, 0, 0, deflate_stored), /* 0 store only */ new Config(4, 4, 8, 4, deflate_fast), /* 1 max speed, no lazy matches */ new Config(4, 5, 16, 8, deflate_fast), /* 2 */ new Config(4, 6, 32, 32, deflate_fast), /* 3 */ new Config(4, 4, 16, 16, deflate_slow), /* 4 lazy matches */ new Config(8, 16, 32, 32, deflate_slow), /* 5 */ new Config(8, 16, 128, 128, deflate_slow), /* 6 */ new Config(8, 32, 128, 256, deflate_slow), /* 7 */ new Config(32, 128, 258, 1024, deflate_slow), /* 8 */ new Config(32, 258, 258, 4096, deflate_slow) /* 9 max compression */ ]; /* =========================================================================== * Initialize the "longest match" routines for a new zlib stream */ function lm_init(s) { s.window_size = 2 * s.w_size; /*** CLEAR_HASH(s); ***/ zero(s.head); // Fill with NIL (= 0); /* Set the default configuration parameters: */ s.max_lazy_match = configuration_table[s.level].max_lazy; s.good_match = configuration_table[s.level].good_length; s.nice_match = configuration_table[s.level].nice_length; s.max_chain_length = configuration_table[s.level].max_chain; s.strstart = 0; s.block_start = 0; s.lookahead = 0; s.insert = 0; s.match_length = s.prev_length = MIN_MATCH - 1; s.match_available = 0; s.ins_h = 0; } function DeflateState() { this.strm = null; /* pointer back to this zlib stream */ this.status = 0; /* as the name implies */ this.pending_buf = null; /* output still pending */ this.pending_buf_size = 0; /* size of pending_buf */ this.pending_out = 0; /* next pending byte to output to the stream */ this.pending = 0; /* nb of bytes in the pending buffer */ this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */ this.gzhead = null; /* gzip header information to write */ this.gzindex = 0; /* where in extra, name, or comment */ this.method = Z_DEFLATED; /* can only be DEFLATED */ this.last_flush = -1; /* value of flush param for previous deflate call */ this.w_size = 0; /* LZ77 window size (32K by default) */ this.w_bits = 0; /* log2(w_size) (8..16) */ this.w_mask = 0; /* w_size - 1 */ this.window = null; /* Sliding window. Input bytes are read into the second half of the window, * and move to the first half later to keep a dictionary of at least wSize * bytes. With this organization, matches are limited to a distance of * wSize-MAX_MATCH bytes, but this ensures that IO is always * performed with a length multiple of the block size. */ this.window_size = 0; /* Actual size of window: 2*wSize, except when the user input buffer * is directly used as sliding window. */ this.prev = null; /* Link to older string with same hash index. To limit the size of this * array to 64K, this link is maintained only for the last 32K strings. * An index in this array is thus a window index modulo 32K. */ this.head = null; /* Heads of the hash chains or NIL. */ this.ins_h = 0; /* hash index of string to be inserted */ this.hash_size = 0; /* number of elements in hash table */ this.hash_bits = 0; /* log2(hash_size) */ this.hash_mask = 0; /* hash_size-1 */ this.hash_shift = 0; /* Number of bits by which ins_h must be shifted at each input * step. It must be such that after MIN_MATCH steps, the oldest * byte no longer takes part in the hash key, that is: * hash_shift * MIN_MATCH >= hash_bits */ this.block_start = 0; /* Window position at the beginning of the current output block. Gets * negative when the window is moved backwards. */ this.match_length = 0; /* length of best match */ this.prev_match = 0; /* previous match */ this.match_available = 0; /* set if previous match exists */ this.strstart = 0; /* start of string to insert */ this.match_start = 0; /* start of matching string */ this.lookahead = 0; /* number of valid bytes ahead in window */ this.prev_length = 0; /* Length of the best match at previous step. Matches not greater than this * are discarded. This is used in the lazy match evaluation. */ this.max_chain_length = 0; /* To speed up deflation, hash chains are never searched beyond this * length. A higher limit improves compression ratio but degrades the * speed. */ this.max_lazy_match = 0; /* Attempt to find a better match only when the current match is strictly * smaller than this value. This mechanism is used only for compression * levels >= 4. */ // That's alias to max_lazy_match, don't use directly //this.max_insert_length = 0; /* Insert new strings in the hash table only if the match length is not * greater than this length. This saves time but degrades compression. * max_insert_length is used only for compression levels <= 3. */ this.level = 0; /* compression level (1..9) */ this.strategy = 0; /* favor or force Huffman coding*/ this.good_match = 0; /* Use a faster search when the previous match is longer than this */ this.nice_match = 0; /* Stop searching when current match exceeds this */ /* used by trees.c: */ /* Didn't use ct_data typedef below to suppress compiler warning */ // struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */ // struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */ // struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */ // Use flat array of DOUBLE size, with interleaved fata, // because JS does not support effective this.dyn_ltree = new utils.Buf16(HEAP_SIZE * 2); this.dyn_dtree = new utils.Buf16((2*D_CODES+1) * 2); this.bl_tree = new utils.Buf16((2*BL_CODES+1) * 2); zero(this.dyn_ltree); zero(this.dyn_dtree); zero(this.bl_tree); this.l_desc = null; /* desc. for literal tree */ this.d_desc = null; /* desc. for distance tree */ this.bl_desc = null; /* desc. for bit length tree */ //ush bl_count[MAX_BITS+1]; this.bl_count = new utils.Buf16(MAX_BITS+1); /* number of codes at each bit length for an optimal tree */ //int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */ this.heap = new utils.Buf16(2*L_CODES+1); /* heap used to build the Huffman trees */ zero(this.heap); this.heap_len = 0; /* number of elements in the heap */ this.heap_max = 0; /* element of largest frequency */ /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used. * The same heap array is used to build all trees. */ this.depth = new utils.Buf16(2*L_CODES+1); //uch depth[2*L_CODES+1]; zero(this.depth); /* Depth of each subtree used as tie breaker for trees of equal frequency */ this.l_buf = 0; /* buffer index for literals or lengths */ this.lit_bufsize = 0; /* Size of match buffer for literals/lengths. There are 4 reasons for * limiting lit_bufsize to 64K: * - frequencies can be kept in 16 bit counters * - if compression is not successful for the first block, all input * data is still in the window so we can still emit a stored block even * when input comes from standard input. (This can also be done for * all blocks if lit_bufsize is not greater than 32K.) * - if compression is not successful for a file smaller than 64K, we can * even emit a stored file instead of a stored block (saving 5 bytes). * This is applicable only for zip (not gzip or zlib). * - creating new Huffman trees less frequently may not provide fast * adaptation to changes in the input data statistics. (Take for * example a binary file with poorly compressible code followed by * a highly compressible string table.) Smaller buffer sizes give * fast adaptation but have of course the overhead of transmitting * trees more frequently. * - I can't count above 4 */ this.last_lit = 0; /* running index in l_buf */ this.d_buf = 0; /* Buffer index for distances. To simplify the code, d_buf and l_buf have * the same number of elements. To use different lengths, an extra flag * array would be necessary. */ this.opt_len = 0; /* bit length of current block with optimal trees */ this.static_len = 0; /* bit length of current block with static trees */ this.matches = 0; /* number of string matches in current block */ this.insert = 0; /* bytes at end of window left to insert */ this.bi_buf = 0; /* Output buffer. bits are inserted starting at the bottom (least * significant bits). */ this.bi_valid = 0; /* Number of valid bits in bi_buf. All bits above the last valid bit * are always zero. */ // Used for window memory init. We safely ignore it for JS. That makes // sense only for pointers and memory check tools. //this.high_water = 0; /* High water mark offset in window for initialized bytes -- bytes above * this are set to zero in order to avoid memory check warnings when * longest match routines access bytes past the input. This is then * updated to the new high water mark. */ } function deflateResetKeep(strm) { var s; if (!strm || !strm.state) { return err(strm, Z_STREAM_ERROR); } strm.total_in = strm.total_out = 0; strm.data_type = Z_UNKNOWN; s = strm.state; s.pending = 0; s.pending_out = 0; if (s.wrap < 0) { s.wrap = -s.wrap; /* was made negative by deflate(..., Z_FINISH); */ } s.status = (s.wrap ? INIT_STATE : BUSY_STATE); strm.adler = (s.wrap === 2) ? 0 // crc32(0, Z_NULL, 0) : 1; // adler32(0, Z_NULL, 0) s.last_flush = Z_NO_FLUSH; trees._tr_init(s); return Z_OK; } function deflateReset(strm) { var ret = deflateResetKeep(strm); if (ret === Z_OK) { lm_init(strm.state); } return ret; } function deflateSetHeader(strm, head) { if (!strm || !strm.state) { return Z_STREAM_ERROR; } if (strm.state.wrap !== 2) { return Z_STREAM_ERROR; } strm.state.gzhead = head; return Z_OK; } function deflateInit2(strm, level, method, windowBits, memLevel, strategy) { if (!strm) { // === Z_NULL return Z_STREAM_ERROR; } var wrap = 1; if (level === Z_DEFAULT_COMPRESSION) { level = 6; } if (windowBits < 0) { /* suppress zlib wrapper */ wrap = 0; windowBits = -windowBits; } else if (windowBits > 15) { wrap = 2; /* write gzip wrapper instead */ windowBits -= 16; } if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method !== Z_DEFLATED || windowBits < 8 || windowBits > 15 || level < 0 || level > 9 || strategy < 0 || strategy > Z_FIXED) { return err(strm, Z_STREAM_ERROR); } if (windowBits === 8) { windowBits = 9; } /* until 256-byte window bug fixed */ var s = new DeflateState(); strm.state = s; s.strm = strm; s.wrap = wrap; s.gzhead = null; s.w_bits = windowBits; s.w_size = 1 << s.w_bits; s.w_mask = s.w_size - 1; s.hash_bits = memLevel + 7; s.hash_size = 1 << s.hash_bits; s.hash_mask = s.hash_size - 1; s.hash_shift = ~~((s.hash_bits + MIN_MATCH - 1) / MIN_MATCH); s.window = new utils.Buf8(s.w_size * 2); s.head = new utils.Buf16(s.hash_size); s.prev = new utils.Buf16(s.w_size); // Don't need mem init magic for JS. //s.high_water = 0; /* nothing written to s->window yet */ s.lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */ s.pending_buf_size = s.lit_bufsize * 4; s.pending_buf = new utils.Buf8(s.pending_buf_size); s.d_buf = s.lit_bufsize >> 1; s.l_buf = (1 + 2) * s.lit_bufsize; s.level = level; s.strategy = strategy; s.method = method; return deflateReset(strm); } function deflateInit(strm, level) { return deflateInit2(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY); } function deflate(strm, flush) { var old_flush, s; var beg, val; // for gzip header write only if (!strm || !strm.state || flush > Z_BLOCK || flush < 0) { return strm ? err(strm, Z_STREAM_ERROR) : Z_STREAM_ERROR; } s = strm.state; if (!strm.output || (!strm.input && strm.avail_in !== 0) || (s.status === FINISH_STATE && flush !== Z_FINISH)) { return err(strm, (strm.avail_out === 0) ? Z_BUF_ERROR : Z_STREAM_ERROR); } s.strm = strm; /* just in case */ old_flush = s.last_flush; s.last_flush = flush; /* Write the header */ if (s.status === INIT_STATE) { if (s.wrap === 2) { // GZIP header strm.adler = 0; //crc32(0L, Z_NULL, 0); put_byte(s, 31); put_byte(s, 139); put_byte(s, 8); if (!s.gzhead) { // s->gzhead == Z_NULL put_byte(s, 0); put_byte(s, 0); put_byte(s, 0); put_byte(s, 0); put_byte(s, 0); put_byte(s, s.level === 9 ? 2 : (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ? 4 : 0)); put_byte(s, OS_CODE); s.status = BUSY_STATE; } else { put_byte(s, (s.gzhead.text ? 1 : 0) + (s.gzhead.hcrc ? 2 : 0) + (!s.gzhead.extra ? 0 : 4) + (!s.gzhead.name ? 0 : 8) + (!s.gzhead.comment ? 0 : 16) ); put_byte(s, s.gzhead.time & 0xff); put_byte(s, (s.gzhead.time >> 8) & 0xff); put_byte(s, (s.gzhead.time >> 16) & 0xff); put_byte(s, (s.gzhead.time >> 24) & 0xff); put_byte(s, s.level === 9 ? 2 : (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ? 4 : 0)); put_byte(s, s.gzhead.os & 0xff); if (s.gzhead.extra && s.gzhead.extra.length) { put_byte(s, s.gzhead.extra.length & 0xff); put_byte(s, (s.gzhead.extra.length >> 8) & 0xff); } if (s.gzhead.hcrc) { strm.adler = crc32(strm.adler, s.pending_buf, s.pending, 0); } s.gzindex = 0; s.status = EXTRA_STATE; } } else // DEFLATE header { var header = (Z_DEFLATED + ((s.w_bits - 8) << 4)) << 8; var level_flags = -1; if (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2) { level_flags = 0; } else if (s.level < 6) { level_flags = 1; } else if (s.level === 6) { level_flags = 2; } else { level_flags = 3; } header |= (level_flags << 6); if (s.strstart !== 0) { header |= PRESET_DICT; } header += 31 - (header % 31); s.status = BUSY_STATE; putShortMSB(s, header); /* Save the adler32 of the preset dictionary: */ if (s.strstart !== 0) { putShortMSB(s, strm.adler >>> 16); putShortMSB(s, strm.adler & 0xffff); } strm.adler = 1; // adler32(0L, Z_NULL, 0); } } //#ifdef GZIP if (s.status === EXTRA_STATE) { if (s.gzhead.extra/* != Z_NULL*/) { beg = s.pending; /* start of bytes to update crc */ while (s.gzindex < (s.gzhead.extra.length & 0xffff)) { if (s.pending === s.pending_buf_size) { if (s.gzhead.hcrc && s.pending > beg) { strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); } flush_pending(strm); beg = s.pending; if (s.pending === s.pending_buf_size) { break; } } put_byte(s, s.gzhead.extra[s.gzindex] & 0xff); s.gzindex++; } if (s.gzhead.hcrc && s.pending > beg) { strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); } if (s.gzindex === s.gzhead.extra.length) { s.gzindex = 0; s.status = NAME_STATE; } } else { s.status = NAME_STATE; } } if (s.status === NAME_STATE) { if (s.gzhead.name/* != Z_NULL*/) { beg = s.pending; /* start of bytes to update crc */ //int val; do { if (s.pending === s.pending_buf_size) { if (s.gzhead.hcrc && s.pending > beg) { strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); } flush_pending(strm); beg = s.pending; if (s.pending === s.pending_buf_size) { val = 1; break; } } // JS specific: little magic to add zero terminator to end of string if (s.gzindex < s.gzhead.name.length) { val = s.gzhead.name.charCodeAt(s.gzindex++) & 0xff; } else { val = 0; } put_byte(s, val); } while (val !== 0); if (s.gzhead.hcrc && s.pending > beg){ strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); } if (val === 0) { s.gzindex = 0; s.status = COMMENT_STATE; } } else { s.status = COMMENT_STATE; } } if (s.status === COMMENT_STATE) { if (s.gzhead.comment/* != Z_NULL*/) { beg = s.pending; /* start of bytes to update crc */ //int val; do { if (s.pending === s.pending_buf_size) { if (s.gzhead.hcrc && s.pending > beg) { strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); } flush_pending(strm); beg = s.pending; if (s.pending === s.pending_buf_size) { val = 1; break; } } // JS specific: little magic to add zero terminator to end of string if (s.gzindex < s.gzhead.comment.length) { val = s.gzhead.comment.charCodeAt(s.gzindex++) & 0xff; } else { val = 0; } put_byte(s, val); } while (val !== 0); if (s.gzhead.hcrc && s.pending > beg) { strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); } if (val === 0) { s.status = HCRC_STATE; } } else { s.status = HCRC_STATE; } } if (s.status === HCRC_STATE) { if (s.gzhead.hcrc) { if (s.pending + 2 > s.pending_buf_size) { flush_pending(strm); } if (s.pending + 2 <= s.pending_buf_size) { put_byte(s, strm.adler & 0xff); put_byte(s, (strm.adler >> 8) & 0xff); strm.adler = 0; //crc32(0L, Z_NULL, 0); s.status = BUSY_STATE; } } else { s.status = BUSY_STATE; } } //#endif /* Flush as much pending output as possible */ if (s.pending !== 0) { flush_pending(strm); if (strm.avail_out === 0) { /* Since avail_out is 0, deflate will be called again with * more output space, but possibly with both pending and * avail_in equal to zero. There won't be anything to do, * but this is not an error situation so make sure we * return OK instead of BUF_ERROR at next call of deflate: */ s.last_flush = -1; return Z_OK; } /* Make sure there is something to do and avoid duplicate consecutive * flushes. For repeated and useless calls with Z_FINISH, we keep * returning Z_STREAM_END instead of Z_BUF_ERROR. */ } else if (strm.avail_in === 0 && rank(flush) <= rank(old_flush) && flush !== Z_FINISH) { return err(strm, Z_BUF_ERROR); } /* User must not provide more input after the first FINISH: */ if (s.status === FINISH_STATE && strm.avail_in !== 0) { return err(strm, Z_BUF_ERROR); } /* Start a new block or continue the current one. */ if (strm.avail_in !== 0 || s.lookahead !== 0 || (flush !== Z_NO_FLUSH && s.status !== FINISH_STATE)) { var bstate = (s.strategy === Z_HUFFMAN_ONLY) ? deflate_huff(s, flush) : (s.strategy === Z_RLE ? deflate_rle(s, flush) : configuration_table[s.level].func(s, flush)); if (bstate === BS_FINISH_STARTED || bstate === BS_FINISH_DONE) { s.status = FINISH_STATE; } if (bstate === BS_NEED_MORE || bstate === BS_FINISH_STARTED) { if (strm.avail_out === 0) { s.last_flush = -1; /* avoid BUF_ERROR next call, see above */ } return Z_OK; /* If flush != Z_NO_FLUSH && avail_out == 0, the next call * of deflate should use the same flush parameter to make sure * that the flush is complete. So we don't have to output an * empty block here, this will be done at next call. This also * ensures that for a very small output buffer, we emit at most * one empty block. */ } if (bstate === BS_BLOCK_DONE) { if (flush === Z_PARTIAL_FLUSH) { trees._tr_align(s); } else if (flush !== Z_BLOCK) { /* FULL_FLUSH or SYNC_FLUSH */ trees._tr_stored_block(s, 0, 0, false); /* For a full flush, this empty block will be recognized * as a special marker by inflate_sync(). */ if (flush === Z_FULL_FLUSH) { /*** CLEAR_HASH(s); ***/ /* forget history */ zero(s.head); // Fill with NIL (= 0); if (s.lookahead === 0) { s.strstart = 0; s.block_start = 0; s.insert = 0; } } } flush_pending(strm); if (strm.avail_out === 0) { s.last_flush = -1; /* avoid BUF_ERROR at next call, see above */ return Z_OK; } } } //Assert(strm->avail_out > 0, "bug2"); //if (strm.avail_out <= 0) { throw new Error("bug2");} if (flush !== Z_FINISH) { return Z_OK; } if (s.wrap <= 0) { return Z_STREAM_END; } /* Write the trailer */ if (s.wrap === 2) { put_byte(s, strm.adler & 0xff); put_byte(s, (strm.adler >> 8) & 0xff); put_byte(s, (strm.adler >> 16) & 0xff); put_byte(s, (strm.adler >> 24) & 0xff); put_byte(s, strm.total_in & 0xff); put_byte(s, (strm.total_in >> 8) & 0xff); put_byte(s, (strm.total_in >> 16) & 0xff); put_byte(s, (strm.total_in >> 24) & 0xff); } else { putShortMSB(s, strm.adler >>> 16); putShortMSB(s, strm.adler & 0xffff); } flush_pending(strm); /* If avail_out is zero, the application will call deflate again * to flush the rest. */ if (s.wrap > 0) { s.wrap = -s.wrap; } /* write the trailer only once! */ return s.pending !== 0 ? Z_OK : Z_STREAM_END; } function deflateEnd(strm) { var status; if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) { return Z_STREAM_ERROR; } status = strm.state.status; if (status !== INIT_STATE && status !== EXTRA_STATE && status !== NAME_STATE && status !== COMMENT_STATE && status !== HCRC_STATE && status !== BUSY_STATE && status !== FINISH_STATE ) { return err(strm, Z_STREAM_ERROR); } strm.state = null; return status === BUSY_STATE ? err(strm, Z_DATA_ERROR) : Z_OK; } /* ========================================================================= * Copy the source state to the destination state */ //function deflateCopy(dest, source) { // //} exports.deflateInit = deflateInit; exports.deflateInit2 = deflateInit2; exports.deflateReset = deflateReset; exports.deflateResetKeep = deflateResetKeep; exports.deflateSetHeader = deflateSetHeader; exports.deflate = deflate; exports.deflateEnd = deflateEnd; exports.deflateInfo = 'pako deflate (from Nodeca project)'; /* Not implemented exports.deflateBound = deflateBound; exports.deflateCopy = deflateCopy; exports.deflateSetDictionary = deflateSetDictionary; exports.deflateParams = deflateParams; exports.deflatePending = deflatePending; exports.deflatePrime = deflatePrime; exports.deflateTune = deflateTune; */ },{"../utils/common":27,"./adler32":29,"./crc32":31,"./messages":37,"./trees":38}],33:[function(_dereq_,module,exports){ 'use strict'; function GZheader() { /* true if compressed data believed to be text */ this.text = 0; /* modification time */ this.time = 0; /* extra flags (not used when writing a gzip file) */ this.xflags = 0; /* operating system */ this.os = 0; /* pointer to extra field or Z_NULL if none */ this.extra = null; /* extra field length (valid if extra != Z_NULL) */ this.extra_len = 0; // Actually, we don't need it in JS, // but leave for few code modifications // // Setup limits is not necessary because in js we should not preallocate memory // for inflate use constant limit in 65536 bytes // /* space at extra (only when reading header) */ // this.extra_max = 0; /* pointer to zero-terminated file name or Z_NULL */ this.name = ''; /* space at name (only when reading header) */ // this.name_max = 0; /* pointer to zero-terminated comment or Z_NULL */ this.comment = ''; /* space at comment (only when reading header) */ // this.comm_max = 0; /* true if there was or will be a header crc */ this.hcrc = 0; /* true when done reading gzip header (not used when writing a gzip file) */ this.done = false; } module.exports = GZheader; },{}],34:[function(_dereq_,module,exports){ 'use strict'; // See state defs from inflate.js var BAD = 30; /* got a data error -- remain here until reset */ var TYPE = 12; /* i: waiting for type bits, including last-flag bit */ /* Decode literal, length, and distance codes and write out the resulting literal and match bytes until either not enough input or output is available, an end-of-block is encountered, or a data error is encountered. When large enough input and output buffers are supplied to inflate(), for example, a 16K input buffer and a 64K output buffer, more than 95% of the inflate execution time is spent in this routine. Entry assumptions: state.mode === LEN strm.avail_in >= 6 strm.avail_out >= 258 start >= strm.avail_out state.bits < 8 On return, state.mode is one of: LEN -- ran out of enough output space or enough available input TYPE -- reached end of block code, inflate() to interpret next block BAD -- error in block data Notes: - The maximum input bits used by a length/distance pair is 15 bits for the length code, 5 bits for the length extra, 15 bits for the distance code, and 13 bits for the distance extra. This totals 48 bits, or six bytes. Therefore if strm.avail_in >= 6, then there is enough input to avoid checking for available input while decoding. - The maximum bytes that a single length/distance pair can output is 258 bytes, which is the maximum length that can be coded. inflate_fast() requires strm.avail_out >= 258 for each loop to avoid checking for output space. */ module.exports = function inflate_fast(strm, start) { var state; var _in; /* local strm.input */ var last; /* have enough input while in < last */ var _out; /* local strm.output */ var beg; /* inflate()'s initial strm.output */ var end; /* while out < end, enough space available */ //#ifdef INFLATE_STRICT var dmax; /* maximum distance from zlib header */ //#endif var wsize; /* window size or zero if not using window */ var whave; /* valid bytes in the window */ var wnext; /* window write index */ var window; /* allocated sliding window, if wsize != 0 */ var hold; /* local strm.hold */ var bits; /* local strm.bits */ var lcode; /* local strm.lencode */ var dcode; /* local strm.distcode */ var lmask; /* mask for first level of length codes */ var dmask; /* mask for first level of distance codes */ var here; /* retrieved table entry */ var op; /* code bits, operation, extra bits, or */ /* window position, window bytes to copy */ var len; /* match length, unused bytes */ var dist; /* match distance */ var from; /* where to copy match from */ var from_source; var input, output; // JS specific, because we have no pointers /* copy state to local variables */ state = strm.state; //here = state.here; _in = strm.next_in; input = strm.input; last = _in + (strm.avail_in - 5); _out = strm.next_out; output = strm.output; beg = _out - (start - strm.avail_out); end = _out + (strm.avail_out - 257); //#ifdef INFLATE_STRICT dmax = state.dmax; //#endif wsize = state.wsize; whave = state.whave; wnext = state.wnext; window = state.window; hold = state.hold; bits = state.bits; lcode = state.lencode; dcode = state.distcode; lmask = (1 << state.lenbits) - 1; dmask = (1 << state.distbits) - 1; /* decode literals and length/distances until end-of-block or not enough input data or output space */ top: do { if (bits < 15) { hold += input[_in++] << bits; bits += 8; hold += input[_in++] << bits; bits += 8; } here = lcode[hold & lmask]; dolen: for (;;) { // Goto emulation op = here >>> 24/*here.bits*/; hold >>>= op; bits -= op; op = (here >>> 16) & 0xff/*here.op*/; if (op === 0) { /* literal */ //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ? // "inflate: literal '%c'\n" : // "inflate: literal 0x%02x\n", here.val)); output[_out++] = here & 0xffff/*here.val*/; } else if (op & 16) { /* length base */ len = here & 0xffff/*here.val*/; op &= 15; /* number of extra bits */ if (op) { if (bits < op) { hold += input[_in++] << bits; bits += 8; } len += hold & ((1 << op) - 1); hold >>>= op; bits -= op; } //Tracevv((stderr, "inflate: length %u\n", len)); if (bits < 15) { hold += input[_in++] << bits; bits += 8; hold += input[_in++] << bits; bits += 8; } here = dcode[hold & dmask]; dodist: for (;;) { // goto emulation op = here >>> 24/*here.bits*/; hold >>>= op; bits -= op; op = (here >>> 16) & 0xff/*here.op*/; if (op & 16) { /* distance base */ dist = here & 0xffff/*here.val*/; op &= 15; /* number of extra bits */ if (bits < op) { hold += input[_in++] << bits; bits += 8; if (bits < op) { hold += input[_in++] << bits; bits += 8; } } dist += hold & ((1 << op) - 1); //#ifdef INFLATE_STRICT if (dist > dmax) { strm.msg = 'invalid distance too far back'; state.mode = BAD; break top; } //#endif hold >>>= op; bits -= op; //Tracevv((stderr, "inflate: distance %u\n", dist)); op = _out - beg; /* max distance in output */ if (dist > op) { /* see if copy from window */ op = dist - op; /* distance back in window */ if (op > whave) { if (state.sane) { strm.msg = 'invalid distance too far back'; state.mode = BAD; break top; } // (!) This block is disabled in zlib defailts, // don't enable it for binary compatibility //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR // if (len <= op - whave) { // do { // output[_out++] = 0; // } while (--len); // continue top; // } // len -= op - whave; // do { // output[_out++] = 0; // } while (--op > whave); // if (op === 0) { // from = _out - dist; // do { // output[_out++] = output[from++]; // } while (--len); // continue top; // } //#endif } from = 0; // window index from_source = window; if (wnext === 0) { /* very common case */ from += wsize - op; if (op < len) { /* some from window */ len -= op; do { output[_out++] = window[from++]; } while (--op); from = _out - dist; /* rest from output */ from_source = output; } } else if (wnext < op) { /* wrap around window */ from += wsize + wnext - op; op -= wnext; if (op < len) { /* some from end of window */ len -= op; do { output[_out++] = window[from++]; } while (--op); from = 0; if (wnext < len) { /* some from start of window */ op = wnext; len -= op; do { output[_out++] = window[from++]; } while (--op); from = _out - dist; /* rest from output */ from_source = output; } } } else { /* contiguous in window */ from += wnext - op; if (op < len) { /* some from window */ len -= op; do { output[_out++] = window[from++]; } while (--op); from = _out - dist; /* rest from output */ from_source = output; } } while (len > 2) { output[_out++] = from_source[from++]; output[_out++] = from_source[from++]; output[_out++] = from_source[from++]; len -= 3; } if (len) { output[_out++] = from_source[from++]; if (len > 1) { output[_out++] = from_source[from++]; } } } else { from = _out - dist; /* copy direct from output */ do { /* minimum length is three */ output[_out++] = output[from++]; output[_out++] = output[from++]; output[_out++] = output[from++]; len -= 3; } while (len > 2); if (len) { output[_out++] = output[from++]; if (len > 1) { output[_out++] = output[from++]; } } } } else if ((op & 64) === 0) { /* 2nd level distance code */ here = dcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))]; continue dodist; } else { strm.msg = 'invalid distance code'; state.mode = BAD; break top; } break; // need to emulate goto via "continue" } } else if ((op & 64) === 0) { /* 2nd level length code */ here = lcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))]; continue dolen; } else if (op & 32) { /* end-of-block */ //Tracevv((stderr, "inflate: end of block\n")); state.mode = TYPE; break top; } else { strm.msg = 'invalid literal/length code'; state.mode = BAD; break top; } break; // need to emulate goto via "continue" } } while (_in < last && _out < end); /* return unused bytes (on entry, bits < 8, so in won't go too far back) */ len = bits >> 3; _in -= len; bits -= len << 3; hold &= (1 << bits) - 1; /* update state and return */ strm.next_in = _in; strm.next_out = _out; strm.avail_in = (_in < last ? 5 + (last - _in) : 5 - (_in - last)); strm.avail_out = (_out < end ? 257 + (end - _out) : 257 - (_out - end)); state.hold = hold; state.bits = bits; return; }; },{}],35:[function(_dereq_,module,exports){ 'use strict'; var utils = _dereq_('../utils/common'); var adler32 = _dereq_('./adler32'); var crc32 = _dereq_('./crc32'); var inflate_fast = _dereq_('./inffast'); var inflate_table = _dereq_('./inftrees'); var CODES = 0; var LENS = 1; var DISTS = 2; /* Public constants ==========================================================*/ /* ===========================================================================*/ /* Allowed flush values; see deflate() and inflate() below for details */ //var Z_NO_FLUSH = 0; //var Z_PARTIAL_FLUSH = 1; //var Z_SYNC_FLUSH = 2; //var Z_FULL_FLUSH = 3; var Z_FINISH = 4; var Z_BLOCK = 5; var Z_TREES = 6; /* Return codes for the compression/decompression functions. Negative values * are errors, positive values are used for special but normal events. */ var Z_OK = 0; var Z_STREAM_END = 1; var Z_NEED_DICT = 2; //var Z_ERRNO = -1; var Z_STREAM_ERROR = -2; var Z_DATA_ERROR = -3; var Z_MEM_ERROR = -4; var Z_BUF_ERROR = -5; //var Z_VERSION_ERROR = -6; /* The deflate compression method */ var Z_DEFLATED = 8; /* STATES ====================================================================*/ /* ===========================================================================*/ var HEAD = 1; /* i: waiting for magic header */ var FLAGS = 2; /* i: waiting for method and flags (gzip) */ var TIME = 3; /* i: waiting for modification time (gzip) */ var OS = 4; /* i: waiting for extra flags and operating system (gzip) */ var EXLEN = 5; /* i: waiting for extra length (gzip) */ var EXTRA = 6; /* i: waiting for extra bytes (gzip) */ var NAME = 7; /* i: waiting for end of file name (gzip) */ var COMMENT = 8; /* i: waiting for end of comment (gzip) */ var HCRC = 9; /* i: waiting for header crc (gzip) */ var DICTID = 10; /* i: waiting for dictionary check value */ var DICT = 11; /* waiting for inflateSetDictionary() call */ var TYPE = 12; /* i: waiting for type bits, including last-flag bit */ var TYPEDO = 13; /* i: same, but skip check to exit inflate on new block */ var STORED = 14; /* i: waiting for stored size (length and complement) */ var COPY_ = 15; /* i/o: same as COPY below, but only first time in */ var COPY = 16; /* i/o: waiting for input or output to copy stored block */ var TABLE = 17; /* i: waiting for dynamic block table lengths */ var LENLENS = 18; /* i: waiting for code length code lengths */ var CODELENS = 19; /* i: waiting for length/lit and distance code lengths */ var LEN_ = 20; /* i: same as LEN below, but only first time in */ var LEN = 21; /* i: waiting for length/lit/eob code */ var LENEXT = 22; /* i: waiting for length extra bits */ var DIST = 23; /* i: waiting for distance code */ var DISTEXT = 24; /* i: waiting for distance extra bits */ var MATCH = 25; /* o: waiting for output space to copy string */ var LIT = 26; /* o: waiting for output space to write literal */ var CHECK = 27; /* i: waiting for 32-bit check value */ var LENGTH = 28; /* i: waiting for 32-bit length (gzip) */ var DONE = 29; /* finished check, done -- remain here until reset */ var BAD = 30; /* got a data error -- remain here until reset */ var MEM = 31; /* got an inflate() memory error -- remain here until reset */ var SYNC = 32; /* looking for synchronization bytes to restart inflate() */ /* ===========================================================================*/ var ENOUGH_LENS = 852; var ENOUGH_DISTS = 592; //var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS); var MAX_WBITS = 15; /* 32K LZ77 window */ var DEF_WBITS = MAX_WBITS; function ZSWAP32(q) { return (((q >>> 24) & 0xff) + ((q >>> 8) & 0xff00) + ((q & 0xff00) << 8) + ((q & 0xff) << 24)); } function InflateState() { this.mode = 0; /* current inflate mode */ this.last = false; /* true if processing last block */ this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */ this.havedict = false; /* true if dictionary provided */ this.flags = 0; /* gzip header method and flags (0 if zlib) */ this.dmax = 0; /* zlib header max distance (INFLATE_STRICT) */ this.check = 0; /* protected copy of check value */ this.total = 0; /* protected copy of output count */ // TODO: may be {} this.head = null; /* where to save gzip header information */ /* sliding window */ this.wbits = 0; /* log base 2 of requested window size */ this.wsize = 0; /* window size or zero if not using window */ this.whave = 0; /* valid bytes in the window */ this.wnext = 0; /* window write index */ this.window = null; /* allocated sliding window, if needed */ /* bit accumulator */ this.hold = 0; /* input bit accumulator */ this.bits = 0; /* number of bits in "in" */ /* for string and stored block copying */ this.length = 0; /* literal or length of data to copy */ this.offset = 0; /* distance back to copy string from */ /* for table and code decoding */ this.extra = 0; /* extra bits needed */ /* fixed and dynamic code tables */ this.lencode = null; /* starting table for length/literal codes */ this.distcode = null; /* starting table for distance codes */ this.lenbits = 0; /* index bits for lencode */ this.distbits = 0; /* index bits for distcode */ /* dynamic table building */ this.ncode = 0; /* number of code length code lengths */ this.nlen = 0; /* number of length code lengths */ this.ndist = 0; /* number of distance code lengths */ this.have = 0; /* number of code lengths in lens[] */ this.next = null; /* next available space in codes[] */ this.lens = new utils.Buf16(320); /* temporary storage for code lengths */ this.work = new utils.Buf16(288); /* work area for code table building */ /* because we don't have pointers in js, we use lencode and distcode directly as buffers so we don't need codes */ //this.codes = new utils.Buf32(ENOUGH); /* space for code tables */ this.lendyn = null; /* dynamic table for length/literal codes (JS specific) */ this.distdyn = null; /* dynamic table for distance codes (JS specific) */ this.sane = 0; /* if false, allow invalid distance too far */ this.back = 0; /* bits back of last unprocessed length/lit */ this.was = 0; /* initial length of match */ } function inflateResetKeep(strm) { var state; if (!strm || !strm.state) { return Z_STREAM_ERROR; } state = strm.state; strm.total_in = strm.total_out = state.total = 0; strm.msg = ''; /*Z_NULL*/ if (state.wrap) { /* to support ill-conceived Java test suite */ strm.adler = state.wrap & 1; } state.mode = HEAD; state.last = 0; state.havedict = 0; state.dmax = 32768; state.head = null/*Z_NULL*/; state.hold = 0; state.bits = 0; //state.lencode = state.distcode = state.next = state.codes; state.lencode = state.lendyn = new utils.Buf32(ENOUGH_LENS); state.distcode = state.distdyn = new utils.Buf32(ENOUGH_DISTS); state.sane = 1; state.back = -1; //Tracev((stderr, "inflate: reset\n")); return Z_OK; } function inflateReset(strm) { var state; if (!strm || !strm.state) { return Z_STREAM_ERROR; } state = strm.state; state.wsize = 0; state.whave = 0; state.wnext = 0; return inflateResetKeep(strm); } function inflateReset2(strm, windowBits) { var wrap; var state; /* get the state */ if (!strm || !strm.state) { return Z_STREAM_ERROR; } state = strm.state; /* extract wrap request from windowBits parameter */ if (windowBits < 0) { wrap = 0; windowBits = -windowBits; } else { wrap = (windowBits >> 4) + 1; if (windowBits < 48) { windowBits &= 15; } } /* set number of window bits, free window if different */ if (windowBits && (windowBits < 8 || windowBits > 15)) { return Z_STREAM_ERROR; } if (state.window !== null && state.wbits !== windowBits) { state.window = null; } /* update state and reset the rest of it */ state.wrap = wrap; state.wbits = windowBits; return inflateReset(strm); } function inflateInit2(strm, windowBits) { var ret; var state; if (!strm) { return Z_STREAM_ERROR; } //strm.msg = Z_NULL; /* in case we return an error */ state = new InflateState(); //if (state === Z_NULL) return Z_MEM_ERROR; //Tracev((stderr, "inflate: allocated\n")); strm.state = state; state.window = null/*Z_NULL*/; ret = inflateReset2(strm, windowBits); if (ret !== Z_OK) { strm.state = null/*Z_NULL*/; } return ret; } function inflateInit(strm) { return inflateInit2(strm, DEF_WBITS); } /* Return state with length and distance decoding tables and index sizes set to fixed code decoding. Normally this returns fixed tables from inffixed.h. If BUILDFIXED is defined, then instead this routine builds the tables the first time it's called, and returns those tables the first time and thereafter. This reduces the size of the code by about 2K bytes, in exchange for a little execution time. However, BUILDFIXED should not be used for threaded applications, since the rewriting of the tables and virgin may not be thread-safe. */ var virgin = true; var lenfix, distfix; // We have no pointers in JS, so keep tables separate function fixedtables(state) { /* build fixed huffman tables if first call (may not be thread safe) */ if (virgin) { var sym; lenfix = new utils.Buf32(512); distfix = new utils.Buf32(32); /* literal/length table */ sym = 0; while (sym < 144) { state.lens[sym++] = 8; } while (sym < 256) { state.lens[sym++] = 9; } while (sym < 280) { state.lens[sym++] = 7; } while (sym < 288) { state.lens[sym++] = 8; } inflate_table(LENS, state.lens, 0, 288, lenfix, 0, state.work, {bits: 9}); /* distance table */ sym = 0; while (sym < 32) { state.lens[sym++] = 5; } inflate_table(DISTS, state.lens, 0, 32, distfix, 0, state.work, {bits: 5}); /* do this just once */ virgin = false; } state.lencode = lenfix; state.lenbits = 9; state.distcode = distfix; state.distbits = 5; } /* Update the window with the last wsize (normally 32K) bytes written before returning. If window does not exist yet, create it. This is only called when a window is already in use, or when output has been written during this inflate call, but the end of the deflate stream has not been reached yet. It is also called to create a window for dictionary data when a dictionary is loaded. Providing output buffers larger than 32K to inflate() should provide a speed advantage, since only the last 32K of output is copied to the sliding window upon return from inflate(), and since all distances after the first 32K of output will fall in the output data, making match copies simpler and faster. The advantage may be dependent on the size of the processor's data caches. */ function updatewindow(strm, src, end, copy) { var dist; var state = strm.state; /* if it hasn't been done already, allocate space for the window */ if (state.window === null) { state.wsize = 1 << state.wbits; state.wnext = 0; state.whave = 0; state.window = new utils.Buf8(state.wsize); } /* copy state->wsize or less output bytes into the circular window */ if (copy >= state.wsize) { utils.arraySet(state.window,src, end - state.wsize, state.wsize, 0); state.wnext = 0; state.whave = state.wsize; } else { dist = state.wsize - state.wnext; if (dist > copy) { dist = copy; } //zmemcpy(state->window + state->wnext, end - copy, dist); utils.arraySet(state.window,src, end - copy, dist, state.wnext); copy -= dist; if (copy) { //zmemcpy(state->window, end - copy, copy); utils.arraySet(state.window,src, end - copy, copy, 0); state.wnext = copy; state.whave = state.wsize; } else { state.wnext += dist; if (state.wnext === state.wsize) { state.wnext = 0; } if (state.whave < state.wsize) { state.whave += dist; } } } return 0; } function inflate(strm, flush) { var state; var input, output; // input/output buffers var next; /* next input INDEX */ var put; /* next output INDEX */ var have, left; /* available input and output */ var hold; /* bit buffer */ var bits; /* bits in bit buffer */ var _in, _out; /* save starting available input and output */ var copy; /* number of stored or match bytes to copy */ var from; /* where to copy match bytes from */ var from_source; var here = 0; /* current decoding table entry */ var here_bits, here_op, here_val; // paked "here" denormalized (JS specific) //var last; /* parent table entry */ var last_bits, last_op, last_val; // paked "last" denormalized (JS specific) var len; /* length to copy for repeats, bits to drop */ var ret; /* return code */ var hbuf = new utils.Buf8(4); /* buffer for gzip header crc calculation */ var opts; var n; // temporary var for NEED_BITS var order = /* permutation of code lengths */ [16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15]; if (!strm || !strm.state || !strm.output || (!strm.input && strm.avail_in !== 0)) { return Z_STREAM_ERROR; } state = strm.state; if (state.mode === TYPE) { state.mode = TYPEDO; } /* skip check */ //--- LOAD() --- put = strm.next_out; output = strm.output; left = strm.avail_out; next = strm.next_in; input = strm.input; have = strm.avail_in; hold = state.hold; bits = state.bits; //--- _in = have; _out = left; ret = Z_OK; inf_leave: // goto emulation for (;;) { switch (state.mode) { case HEAD: if (state.wrap === 0) { state.mode = TYPEDO; break; } //=== NEEDBITS(16); while (bits < 16) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// if ((state.wrap & 2) && hold === 0x8b1f) { /* gzip header */ state.check = 0/*crc32(0L, Z_NULL, 0)*/; //=== CRC2(state.check, hold); hbuf[0] = hold & 0xff; hbuf[1] = (hold >>> 8) & 0xff; state.check = crc32(state.check, hbuf, 2, 0); //===// //=== INITBITS(); hold = 0; bits = 0; //===// state.mode = FLAGS; break; } state.flags = 0; /* expect zlib header */ if (state.head) { state.head.done = false; } if (!(state.wrap & 1) || /* check if zlib header allowed */ (((hold & 0xff)/*BITS(8)*/ << 8) + (hold >> 8)) % 31) { strm.msg = 'incorrect header check'; state.mode = BAD; break; } if ((hold & 0x0f)/*BITS(4)*/ !== Z_DEFLATED) { strm.msg = 'unknown compression method'; state.mode = BAD; break; } //--- DROPBITS(4) ---// hold >>>= 4; bits -= 4; //---// len = (hold & 0x0f)/*BITS(4)*/ + 8; if (state.wbits === 0) { state.wbits = len; } else if (len > state.wbits) { strm.msg = 'invalid window size'; state.mode = BAD; break; } state.dmax = 1 << len; //Tracev((stderr, "inflate: zlib header ok\n")); strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/; state.mode = hold & 0x200 ? DICTID : TYPE; //=== INITBITS(); hold = 0; bits = 0; //===// break; case FLAGS: //=== NEEDBITS(16); */ while (bits < 16) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// state.flags = hold; if ((state.flags & 0xff) !== Z_DEFLATED) { strm.msg = 'unknown compression method'; state.mode = BAD; break; } if (state.flags & 0xe000) { strm.msg = 'unknown header flags set'; state.mode = BAD; break; } if (state.head) { state.head.text = ((hold >> 8) & 1); } if (state.flags & 0x0200) { //=== CRC2(state.check, hold); hbuf[0] = hold & 0xff; hbuf[1] = (hold >>> 8) & 0xff; state.check = crc32(state.check, hbuf, 2, 0); //===// } //=== INITBITS(); hold = 0; bits = 0; //===// state.mode = TIME; /* falls through */ case TIME: //=== NEEDBITS(32); */ while (bits < 32) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// if (state.head) { state.head.time = hold; } if (state.flags & 0x0200) { //=== CRC4(state.check, hold) hbuf[0] = hold & 0xff; hbuf[1] = (hold >>> 8) & 0xff; hbuf[2] = (hold >>> 16) & 0xff; hbuf[3] = (hold >>> 24) & 0xff; state.check = crc32(state.check, hbuf, 4, 0); //=== } //=== INITBITS(); hold = 0; bits = 0; //===// state.mode = OS; /* falls through */ case OS: //=== NEEDBITS(16); */ while (bits < 16) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// if (state.head) { state.head.xflags = (hold & 0xff); state.head.os = (hold >> 8); } if (state.flags & 0x0200) { //=== CRC2(state.check, hold); hbuf[0] = hold & 0xff; hbuf[1] = (hold >>> 8) & 0xff; state.check = crc32(state.check, hbuf, 2, 0); //===// } //=== INITBITS(); hold = 0; bits = 0; //===// state.mode = EXLEN; /* falls through */ case EXLEN: if (state.flags & 0x0400) { //=== NEEDBITS(16); */ while (bits < 16) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// state.length = hold; if (state.head) { state.head.extra_len = hold; } if (state.flags & 0x0200) { //=== CRC2(state.check, hold); hbuf[0] = hold & 0xff; hbuf[1] = (hold >>> 8) & 0xff; state.check = crc32(state.check, hbuf, 2, 0); //===// } //=== INITBITS(); hold = 0; bits = 0; //===// } else if (state.head) { state.head.extra = null/*Z_NULL*/; } state.mode = EXTRA; /* falls through */ case EXTRA: if (state.flags & 0x0400) { copy = state.length; if (copy > have) { copy = have; } if (copy) { if (state.head) { len = state.head.extra_len - state.length; if (!state.head.extra) { // Use untyped array for more conveniend processing later state.head.extra = new Array(state.head.extra_len); } utils.arraySet( state.head.extra, input, next, // extra field is limited to 65536 bytes // - no need for additional size check copy, /*len + copy > state.head.extra_max - len ? state.head.extra_max : copy,*/ len ); //zmemcpy(state.head.extra + len, next, // len + copy > state.head.extra_max ? // state.head.extra_max - len : copy); } if (state.flags & 0x0200) { state.check = crc32(state.check, input, copy, next); } have -= copy; next += copy; state.length -= copy; } if (state.length) { break inf_leave; } } state.length = 0; state.mode = NAME; /* falls through */ case NAME: if (state.flags & 0x0800) { if (have === 0) { break inf_leave; } copy = 0; do { // TODO: 2 or 1 bytes? len = input[next + copy++]; /* use constant limit because in js we should not preallocate memory */ if (state.head && len && (state.length < 65536 /*state.head.name_max*/)) { state.head.name += String.fromCharCode(len); } } while (len && copy < have); if (state.flags & 0x0200) { state.check = crc32(state.check, input, copy, next); } have -= copy; next += copy; if (len) { break inf_leave; } } else if (state.head) { state.head.name = null; } state.length = 0; state.mode = COMMENT; /* falls through */ case COMMENT: if (state.flags & 0x1000) { if (have === 0) { break inf_leave; } copy = 0; do { len = input[next + copy++]; /* use constant limit because in js we should not preallocate memory */ if (state.head && len && (state.length < 65536 /*state.head.comm_max*/)) { state.head.comment += String.fromCharCode(len); } } while (len && copy < have); if (state.flags & 0x0200) { state.check = crc32(state.check, input, copy, next); } have -= copy; next += copy; if (len) { break inf_leave; } } else if (state.head) { state.head.comment = null; } state.mode = HCRC; /* falls through */ case HCRC: if (state.flags & 0x0200) { //=== NEEDBITS(16); */ while (bits < 16) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// if (hold !== (state.check & 0xffff)) { strm.msg = 'header crc mismatch'; state.mode = BAD; break; } //=== INITBITS(); hold = 0; bits = 0; //===// } if (state.head) { state.head.hcrc = ((state.flags >> 9) & 1); state.head.done = true; } strm.adler = state.check = 0 /*crc32(0L, Z_NULL, 0)*/; state.mode = TYPE; break; case DICTID: //=== NEEDBITS(32); */ while (bits < 32) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// strm.adler = state.check = ZSWAP32(hold); //=== INITBITS(); hold = 0; bits = 0; //===// state.mode = DICT; /* falls through */ case DICT: if (state.havedict === 0) { //--- RESTORE() --- strm.next_out = put; strm.avail_out = left; strm.next_in = next; strm.avail_in = have; state.hold = hold; state.bits = bits; //--- return Z_NEED_DICT; } strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/; state.mode = TYPE; /* falls through */ case TYPE: if (flush === Z_BLOCK || flush === Z_TREES) { break inf_leave; } /* falls through */ case TYPEDO: if (state.last) { //--- BYTEBITS() ---// hold >>>= bits & 7; bits -= bits & 7; //---// state.mode = CHECK; break; } //=== NEEDBITS(3); */ while (bits < 3) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// state.last = (hold & 0x01)/*BITS(1)*/; //--- DROPBITS(1) ---// hold >>>= 1; bits -= 1; //---// switch ((hold & 0x03)/*BITS(2)*/) { case 0: /* stored block */ //Tracev((stderr, "inflate: stored block%s\n", // state.last ? " (last)" : "")); state.mode = STORED; break; case 1: /* fixed block */ fixedtables(state); //Tracev((stderr, "inflate: fixed codes block%s\n", // state.last ? " (last)" : "")); state.mode = LEN_; /* decode codes */ if (flush === Z_TREES) { //--- DROPBITS(2) ---// hold >>>= 2; bits -= 2; //---// break inf_leave; } break; case 2: /* dynamic block */ //Tracev((stderr, "inflate: dynamic codes block%s\n", // state.last ? " (last)" : "")); state.mode = TABLE; break; case 3: strm.msg = 'invalid block type'; state.mode = BAD; } //--- DROPBITS(2) ---// hold >>>= 2; bits -= 2; //---// break; case STORED: //--- BYTEBITS() ---// /* go to byte boundary */ hold >>>= bits & 7; bits -= bits & 7; //---// //=== NEEDBITS(32); */ while (bits < 32) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// if ((hold & 0xffff) !== ((hold >>> 16) ^ 0xffff)) { strm.msg = 'invalid stored block lengths'; state.mode = BAD; break; } state.length = hold & 0xffff; //Tracev((stderr, "inflate: stored length %u\n", // state.length)); //=== INITBITS(); hold = 0; bits = 0; //===// state.mode = COPY_; if (flush === Z_TREES) { break inf_leave; } /* falls through */ case COPY_: state.mode = COPY; /* falls through */ case COPY: copy = state.length; if (copy) { if (copy > have) { copy = have; } if (copy > left) { copy = left; } if (copy === 0) { break inf_leave; } //--- zmemcpy(put, next, copy); --- utils.arraySet(output, input, next, copy, put); //---// have -= copy; next += copy; left -= copy; put += copy; state.length -= copy; break; } //Tracev((stderr, "inflate: stored end\n")); state.mode = TYPE; break; case TABLE: //=== NEEDBITS(14); */ while (bits < 14) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// state.nlen = (hold & 0x1f)/*BITS(5)*/ + 257; //--- DROPBITS(5) ---// hold >>>= 5; bits -= 5; //---// state.ndist = (hold & 0x1f)/*BITS(5)*/ + 1; //--- DROPBITS(5) ---// hold >>>= 5; bits -= 5; //---// state.ncode = (hold & 0x0f)/*BITS(4)*/ + 4; //--- DROPBITS(4) ---// hold >>>= 4; bits -= 4; //---// //#ifndef PKZIP_BUG_WORKAROUND if (state.nlen > 286 || state.ndist > 30) { strm.msg = 'too many length or distance symbols'; state.mode = BAD; break; } //#endif //Tracev((stderr, "inflate: table sizes ok\n")); state.have = 0; state.mode = LENLENS; /* falls through */ case LENLENS: while (state.have < state.ncode) { //=== NEEDBITS(3); while (bits < 3) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// state.lens[order[state.have++]] = (hold & 0x07);//BITS(3); //--- DROPBITS(3) ---// hold >>>= 3; bits -= 3; //---// } while (state.have < 19) { state.lens[order[state.have++]] = 0; } // We have separate tables & no pointers. 2 commented lines below not needed. //state.next = state.codes; //state.lencode = state.next; // Switch to use dynamic table state.lencode = state.lendyn; state.lenbits = 7; opts = {bits: state.lenbits}; ret = inflate_table(CODES, state.lens, 0, 19, state.lencode, 0, state.work, opts); state.lenbits = opts.bits; if (ret) { strm.msg = 'invalid code lengths set'; state.mode = BAD; break; } //Tracev((stderr, "inflate: code lengths ok\n")); state.have = 0; state.mode = CODELENS; /* falls through */ case CODELENS: while (state.have < state.nlen + state.ndist) { for (;;) { here = state.lencode[hold & ((1 << state.lenbits) - 1)];/*BITS(state.lenbits)*/ here_bits = here >>> 24; here_op = (here >>> 16) & 0xff; here_val = here & 0xffff; if ((here_bits) <= bits) { break; } //--- PULLBYTE() ---// if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; //---// } if (here_val < 16) { //--- DROPBITS(here.bits) ---// hold >>>= here_bits; bits -= here_bits; //---// state.lens[state.have++] = here_val; } else { if (here_val === 16) { //=== NEEDBITS(here.bits + 2); n = here_bits + 2; while (bits < n) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// //--- DROPBITS(here.bits) ---// hold >>>= here_bits; bits -= here_bits; //---// if (state.have === 0) { strm.msg = 'invalid bit length repeat'; state.mode = BAD; break; } len = state.lens[state.have - 1]; copy = 3 + (hold & 0x03);//BITS(2); //--- DROPBITS(2) ---// hold >>>= 2; bits -= 2; //---// } else if (here_val === 17) { //=== NEEDBITS(here.bits + 3); n = here_bits + 3; while (bits < n) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// //--- DROPBITS(here.bits) ---// hold >>>= here_bits; bits -= here_bits; //---// len = 0; copy = 3 + (hold & 0x07);//BITS(3); //--- DROPBITS(3) ---// hold >>>= 3; bits -= 3; //---// } else { //=== NEEDBITS(here.bits + 7); n = here_bits + 7; while (bits < n) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// //--- DROPBITS(here.bits) ---// hold >>>= here_bits; bits -= here_bits; //---// len = 0; copy = 11 + (hold & 0x7f);//BITS(7); //--- DROPBITS(7) ---// hold >>>= 7; bits -= 7; //---// } if (state.have + copy > state.nlen + state.ndist) { strm.msg = 'invalid bit length repeat'; state.mode = BAD; break; } while (copy--) { state.lens[state.have++] = len; } } } /* handle error breaks in while */ if (state.mode === BAD) { break; } /* check for end-of-block code (better have one) */ if (state.lens[256] === 0) { strm.msg = 'invalid code -- missing end-of-block'; state.mode = BAD; break; } /* build code tables -- note: do not change the lenbits or distbits values here (9 and 6) without reading the comments in inftrees.h concerning the ENOUGH constants, which depend on those values */ state.lenbits = 9; opts = {bits: state.lenbits}; ret = inflate_table(LENS, state.lens, 0, state.nlen, state.lencode, 0, state.work, opts); // We have separate tables & no pointers. 2 commented lines below not needed. // state.next_index = opts.table_index; state.lenbits = opts.bits; // state.lencode = state.next; if (ret) { strm.msg = 'invalid literal/lengths set'; state.mode = BAD; break; } state.distbits = 6; //state.distcode.copy(state.codes); // Switch to use dynamic table state.distcode = state.distdyn; opts = {bits: state.distbits}; ret = inflate_table(DISTS, state.lens, state.nlen, state.ndist, state.distcode, 0, state.work, opts); // We have separate tables & no pointers. 2 commented lines below not needed. // state.next_index = opts.table_index; state.distbits = opts.bits; // state.distcode = state.next; if (ret) { strm.msg = 'invalid distances set'; state.mode = BAD; break; } //Tracev((stderr, 'inflate: codes ok\n')); state.mode = LEN_; if (flush === Z_TREES) { break inf_leave; } /* falls through */ case LEN_: state.mode = LEN; /* falls through */ case LEN: if (have >= 6 && left >= 258) { //--- RESTORE() --- strm.next_out = put; strm.avail_out = left; strm.next_in = next; strm.avail_in = have; state.hold = hold; state.bits = bits; //--- inflate_fast(strm, _out); //--- LOAD() --- put = strm.next_out; output = strm.output; left = strm.avail_out; next = strm.next_in; input = strm.input; have = strm.avail_in; hold = state.hold; bits = state.bits; //--- if (state.mode === TYPE) { state.back = -1; } break; } state.back = 0; for (;;) { here = state.lencode[hold & ((1 << state.lenbits) -1)]; /*BITS(state.lenbits)*/ here_bits = here >>> 24; here_op = (here >>> 16) & 0xff; here_val = here & 0xffff; if (here_bits <= bits) { break; } //--- PULLBYTE() ---// if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; //---// } if (here_op && (here_op & 0xf0) === 0) { last_bits = here_bits; last_op = here_op; last_val = here_val; for (;;) { here = state.lencode[last_val + ((hold & ((1 << (last_bits + last_op)) -1))/*BITS(last.bits + last.op)*/ >> last_bits)]; here_bits = here >>> 24; here_op = (here >>> 16) & 0xff; here_val = here & 0xffff; if ((last_bits + here_bits) <= bits) { break; } //--- PULLBYTE() ---// if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; //---// } //--- DROPBITS(last.bits) ---// hold >>>= last_bits; bits -= last_bits; //---// state.back += last_bits; } //--- DROPBITS(here.bits) ---// hold >>>= here_bits; bits -= here_bits; //---// state.back += here_bits; state.length = here_val; if (here_op === 0) { //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ? // "inflate: literal '%c'\n" : // "inflate: literal 0x%02x\n", here.val)); state.mode = LIT; break; } if (here_op & 32) { //Tracevv((stderr, "inflate: end of block\n")); state.back = -1; state.mode = TYPE; break; } if (here_op & 64) { strm.msg = 'invalid literal/length code'; state.mode = BAD; break; } state.extra = here_op & 15; state.mode = LENEXT; /* falls through */ case LENEXT: if (state.extra) { //=== NEEDBITS(state.extra); n = state.extra; while (bits < n) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// state.length += hold & ((1 << state.extra) -1)/*BITS(state.extra)*/; //--- DROPBITS(state.extra) ---// hold >>>= state.extra; bits -= state.extra; //---// state.back += state.extra; } //Tracevv((stderr, "inflate: length %u\n", state.length)); state.was = state.length; state.mode = DIST; /* falls through */ case DIST: for (;;) { here = state.distcode[hold & ((1 << state.distbits) -1)];/*BITS(state.distbits)*/ here_bits = here >>> 24; here_op = (here >>> 16) & 0xff; here_val = here & 0xffff; if ((here_bits) <= bits) { break; } //--- PULLBYTE() ---// if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; //---// } if ((here_op & 0xf0) === 0) { last_bits = here_bits; last_op = here_op; last_val = here_val; for (;;) { here = state.distcode[last_val + ((hold & ((1 << (last_bits + last_op)) -1))/*BITS(last.bits + last.op)*/ >> last_bits)]; here_bits = here >>> 24; here_op = (here >>> 16) & 0xff; here_val = here & 0xffff; if ((last_bits + here_bits) <= bits) { break; } //--- PULLBYTE() ---// if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; //---// } //--- DROPBITS(last.bits) ---// hold >>>= last_bits; bits -= last_bits; //---// state.back += last_bits; } //--- DROPBITS(here.bits) ---// hold >>>= here_bits; bits -= here_bits; //---// state.back += here_bits; if (here_op & 64) { strm.msg = 'invalid distance code'; state.mode = BAD; break; } state.offset = here_val; state.extra = (here_op) & 15; state.mode = DISTEXT; /* falls through */ case DISTEXT: if (state.extra) { //=== NEEDBITS(state.extra); n = state.extra; while (bits < n) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// state.offset += hold & ((1 << state.extra) -1)/*BITS(state.extra)*/; //--- DROPBITS(state.extra) ---// hold >>>= state.extra; bits -= state.extra; //---// state.back += state.extra; } //#ifdef INFLATE_STRICT if (state.offset > state.dmax) { strm.msg = 'invalid distance too far back'; state.mode = BAD; break; } //#endif //Tracevv((stderr, "inflate: distance %u\n", state.offset)); state.mode = MATCH; /* falls through */ case MATCH: if (left === 0) { break inf_leave; } copy = _out - left; if (state.offset > copy) { /* copy from window */ copy = state.offset - copy; if (copy > state.whave) { if (state.sane) { strm.msg = 'invalid distance too far back'; state.mode = BAD; break; } // (!) This block is disabled in zlib defailts, // don't enable it for binary compatibility //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR // Trace((stderr, "inflate.c too far\n")); // copy -= state.whave; // if (copy > state.length) { copy = state.length; } // if (copy > left) { copy = left; } // left -= copy; // state.length -= copy; // do { // output[put++] = 0; // } while (--copy); // if (state.length === 0) { state.mode = LEN; } // break; //#endif } if (copy > state.wnext) { copy -= state.wnext; from = state.wsize - copy; } else { from = state.wnext - copy; } if (copy > state.length) { copy = state.length; } from_source = state.window; } else { /* copy from output */ from_source = output; from = put - state.offset; copy = state.length; } if (copy > left) { copy = left; } left -= copy; state.length -= copy; do { output[put++] = from_source[from++]; } while (--copy); if (state.length === 0) { state.mode = LEN; } break; case LIT: if (left === 0) { break inf_leave; } output[put++] = state.length; left--; state.mode = LEN; break; case CHECK: if (state.wrap) { //=== NEEDBITS(32); while (bits < 32) { if (have === 0) { break inf_leave; } have--; // Use '|' insdead of '+' to make sure that result is signed hold |= input[next++] << bits; bits += 8; } //===// _out -= left; strm.total_out += _out; state.total += _out; if (_out) { strm.adler = state.check = /*UPDATE(state.check, put - _out, _out);*/ (state.flags ? crc32(state.check, output, _out, put - _out) : adler32(state.check, output, _out, put - _out)); } _out = left; // NB: crc32 stored as signed 32-bit int, ZSWAP32 returns signed too if ((state.flags ? hold : ZSWAP32(hold)) !== state.check) { strm.msg = 'incorrect data check'; state.mode = BAD; break; } //=== INITBITS(); hold = 0; bits = 0; //===// //Tracev((stderr, "inflate: check matches trailer\n")); } state.mode = LENGTH; /* falls through */ case LENGTH: if (state.wrap && state.flags) { //=== NEEDBITS(32); while (bits < 32) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// if (hold !== (state.total & 0xffffffff)) { strm.msg = 'incorrect length check'; state.mode = BAD; break; } //=== INITBITS(); hold = 0; bits = 0; //===// //Tracev((stderr, "inflate: length matches trailer\n")); } state.mode = DONE; /* falls through */ case DONE: ret = Z_STREAM_END; break inf_leave; case BAD: ret = Z_DATA_ERROR; break inf_leave; case MEM: return Z_MEM_ERROR; case SYNC: /* falls through */ default: return Z_STREAM_ERROR; } } // inf_leave <- here is real place for "goto inf_leave", emulated via "break inf_leave" /* Return from inflate(), updating the total counts and the check value. If there was no progress during the inflate() call, return a buffer error. Call updatewindow() to create and/or update the window state. Note: a memory error from inflate() is non-recoverable. */ //--- RESTORE() --- strm.next_out = put; strm.avail_out = left; strm.next_in = next; strm.avail_in = have; state.hold = hold; state.bits = bits; //--- if (state.wsize || (_out !== strm.avail_out && state.mode < BAD && (state.mode < CHECK || flush !== Z_FINISH))) { if (updatewindow(strm, strm.output, strm.next_out, _out - strm.avail_out)) { state.mode = MEM; return Z_MEM_ERROR; } } _in -= strm.avail_in; _out -= strm.avail_out; strm.total_in += _in; strm.total_out += _out; state.total += _out; if (state.wrap && _out) { strm.adler = state.check = /*UPDATE(state.check, strm.next_out - _out, _out);*/ (state.flags ? crc32(state.check, output, _out, strm.next_out - _out) : adler32(state.check, output, _out, strm.next_out - _out)); } strm.data_type = state.bits + (state.last ? 64 : 0) + (state.mode === TYPE ? 128 : 0) + (state.mode === LEN_ || state.mode === COPY_ ? 256 : 0); if (((_in === 0 && _out === 0) || flush === Z_FINISH) && ret === Z_OK) { ret = Z_BUF_ERROR; } return ret; } function inflateEnd(strm) { if (!strm || !strm.state /*|| strm->zfree == (free_func)0*/) { return Z_STREAM_ERROR; } var state = strm.state; if (state.window) { state.window = null; } strm.state = null; return Z_OK; } function inflateGetHeader(strm, head) { var state; /* check state */ if (!strm || !strm.state) { return Z_STREAM_ERROR; } state = strm.state; if ((state.wrap & 2) === 0) { return Z_STREAM_ERROR; } /* save header structure */ state.head = head; head.done = false; return Z_OK; } exports.inflateReset = inflateReset; exports.inflateReset2 = inflateReset2; exports.inflateResetKeep = inflateResetKeep; exports.inflateInit = inflateInit; exports.inflateInit2 = inflateInit2; exports.inflate = inflate; exports.inflateEnd = inflateEnd; exports.inflateGetHeader = inflateGetHeader; exports.inflateInfo = 'pako inflate (from Nodeca project)'; /* Not implemented exports.inflateCopy = inflateCopy; exports.inflateGetDictionary = inflateGetDictionary; exports.inflateMark = inflateMark; exports.inflatePrime = inflatePrime; exports.inflateSetDictionary = inflateSetDictionary; exports.inflateSync = inflateSync; exports.inflateSyncPoint = inflateSyncPoint; exports.inflateUndermine = inflateUndermine; */ },{"../utils/common":27,"./adler32":29,"./crc32":31,"./inffast":34,"./inftrees":36}],36:[function(_dereq_,module,exports){ 'use strict'; var utils = _dereq_('../utils/common'); var MAXBITS = 15; var ENOUGH_LENS = 852; var ENOUGH_DISTS = 592; //var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS); var CODES = 0; var LENS = 1; var DISTS = 2; var lbase = [ /* Length codes 257..285 base */ 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0 ]; var lext = [ /* Length codes 257..285 extra */ 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18, 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 72, 78 ]; var dbase = [ /* Distance codes 0..29 base */ 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145, 8193, 12289, 16385, 24577, 0, 0 ]; var dext = [ /* Distance codes 0..29 extra */ 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22, 23, 23, 24, 24, 25, 25, 26, 26, 27, 27, 28, 28, 29, 29, 64, 64 ]; module.exports = function inflate_table(type, lens, lens_index, codes, table, table_index, work, opts) { var bits = opts.bits; //here = opts.here; /* table entry for duplication */ var len = 0; /* a code's length in bits */ var sym = 0; /* index of code symbols */ var min = 0, max = 0; /* minimum and maximum code lengths */ var root = 0; /* number of index bits for root table */ var curr = 0; /* number of index bits for current table */ var drop = 0; /* code bits to drop for sub-table */ var left = 0; /* number of prefix codes available */ var used = 0; /* code entries in table used */ var huff = 0; /* Huffman code */ var incr; /* for incrementing code, index */ var fill; /* index for replicating entries */ var low; /* low bits for current root entry */ var mask; /* mask for low root bits */ var next; /* next available space in table */ var base = null; /* base value table to use */ var base_index = 0; // var shoextra; /* extra bits table to use */ var end; /* use base and extra for symbol > end */ var count = new utils.Buf16(MAXBITS+1); //[MAXBITS+1]; /* number of codes of each length */ var offs = new utils.Buf16(MAXBITS+1); //[MAXBITS+1]; /* offsets in table for each length */ var extra = null; var extra_index = 0; var here_bits, here_op, here_val; /* Process a set of code lengths to create a canonical Huffman code. The code lengths are lens[0..codes-1]. Each length corresponds to the symbols 0..codes-1. The Huffman code is generated by first sorting the symbols by length from short to long, and retaining the symbol order for codes with equal lengths. Then the code starts with all zero bits for the first code of the shortest length, and the codes are integer increments for the same length, and zeros are appended as the length increases. For the deflate format, these bits are stored backwards from their more natural integer increment ordering, and so when the decoding tables are built in the large loop below, the integer codes are incremented backwards. This routine assumes, but does not check, that all of the entries in lens[] are in the range 0..MAXBITS. The caller must assure this. 1..MAXBITS is interpreted as that code length. zero means that that symbol does not occur in this code. The codes are sorted by computing a count of codes for each length, creating from that a table of starting indices for each length in the sorted table, and then entering the symbols in order in the sorted table. The sorted table is work[], with that space being provided by the caller. The length counts are used for other purposes as well, i.e. finding the minimum and maximum length codes, determining if there are any codes at all, checking for a valid set of lengths, and looking ahead at length counts to determine sub-table sizes when building the decoding tables. */ /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */ for (len = 0; len <= MAXBITS; len++) { count[len] = 0; } for (sym = 0; sym < codes; sym++) { count[lens[lens_index + sym]]++; } /* bound code lengths, force root to be within code lengths */ root = bits; for (max = MAXBITS; max >= 1; max--) { if (count[max] !== 0) { break; } } if (root > max) { root = max; } if (max === 0) { /* no symbols to code at all */ //table.op[opts.table_index] = 64; //here.op = (var char)64; /* invalid code marker */ //table.bits[opts.table_index] = 1; //here.bits = (var char)1; //table.val[opts.table_index++] = 0; //here.val = (var short)0; table[table_index++] = (1 << 24) | (64 << 16) | 0; //table.op[opts.table_index] = 64; //table.bits[opts.table_index] = 1; //table.val[opts.table_index++] = 0; table[table_index++] = (1 << 24) | (64 << 16) | 0; opts.bits = 1; return 0; /* no symbols, but wait for decoding to report error */ } for (min = 1; min < max; min++) { if (count[min] !== 0) { break; } } if (root < min) { root = min; } /* check for an over-subscribed or incomplete set of lengths */ left = 1; for (len = 1; len <= MAXBITS; len++) { left <<= 1; left -= count[len]; if (left < 0) { return -1; } /* over-subscribed */ } if (left > 0 && (type === CODES || max !== 1)) { return -1; /* incomplete set */ } /* generate offsets into symbol table for each length for sorting */ offs[1] = 0; for (len = 1; len < MAXBITS; len++) { offs[len + 1] = offs[len] + count[len]; } /* sort symbols by length, by symbol order within each length */ for (sym = 0; sym < codes; sym++) { if (lens[lens_index + sym] !== 0) { work[offs[lens[lens_index + sym]]++] = sym; } } /* Create and fill in decoding tables. In this loop, the table being filled is at next and has curr index bits. The code being used is huff with length len. That code is converted to an index by dropping drop bits off of the bottom. For codes where len is less than drop + curr, those top drop + curr - len bits are incremented through all values to fill the table with replicated entries. root is the number of index bits for the root table. When len exceeds root, sub-tables are created pointed to by the root entry with an index of the low root bits of huff. This is saved in low to check for when a new sub-table should be started. drop is zero when the root table is being filled, and drop is root when sub-tables are being filled. When a new sub-table is needed, it is necessary to look ahead in the code lengths to determine what size sub-table is needed. The length counts are used for this, and so count[] is decremented as codes are entered in the tables. used keeps track of how many table entries have been allocated from the provided *table space. It is checked for LENS and DIST tables against the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in the initial root table size constants. See the comments in inftrees.h for more information. sym increments through all symbols, and the loop terminates when all codes of length max, i.e. all codes, have been processed. This routine permits incomplete codes, so another loop after this one fills in the rest of the decoding tables with invalid code markers. */ /* set up for code type */ // poor man optimization - use if-else instead of switch, // to avoid deopts in old v8 if (type === CODES) { base = extra = work; /* dummy value--not used */ end = 19; } else if (type === LENS) { base = lbase; base_index -= 257; extra = lext; extra_index -= 257; end = 256; } else { /* DISTS */ base = dbase; extra = dext; end = -1; } /* initialize opts for loop */ huff = 0; /* starting code */ sym = 0; /* starting code symbol */ len = min; /* starting code length */ next = table_index; /* current table to fill in */ curr = root; /* current table index bits */ drop = 0; /* current bits to drop from code for index */ low = -1; /* trigger new sub-table when len > root */ used = 1 << root; /* use root table entries */ mask = used - 1; /* mask for comparing low */ /* check available table space */ if ((type === LENS && used > ENOUGH_LENS) || (type === DISTS && used > ENOUGH_DISTS)) { return 1; } var i=0; /* process all codes and make table entries */ for (;;) { i++; /* create table entry */ here_bits = len - drop; if (work[sym] < end) { here_op = 0; here_val = work[sym]; } else if (work[sym] > end) { here_op = extra[extra_index + work[sym]]; here_val = base[base_index + work[sym]]; } else { here_op = 32 + 64; /* end of block */ here_val = 0; } /* replicate for those indices with low len bits equal to huff */ incr = 1 << (len - drop); fill = 1 << curr; min = fill; /* save offset to next table */ do { fill -= incr; table[next + (huff >> drop) + fill] = (here_bits << 24) | (here_op << 16) | here_val |0; } while (fill !== 0); /* backwards increment the len-bit code huff */ incr = 1 << (len - 1); while (huff & incr) { incr >>= 1; } if (incr !== 0) { huff &= incr - 1; huff += incr; } else { huff = 0; } /* go to next symbol, update count, len */ sym++; if (--count[len] === 0) { if (len === max) { break; } len = lens[lens_index + work[sym]]; } /* create new sub-table if needed */ if (len > root && (huff & mask) !== low) { /* if first time, transition to sub-tables */ if (drop === 0) { drop = root; } /* increment past last table */ next += min; /* here min is 1 << curr */ /* determine length of next table */ curr = len - drop; left = 1 << curr; while (curr + drop < max) { left -= count[curr + drop]; if (left <= 0) { break; } curr++; left <<= 1; } /* check for enough space */ used += 1 << curr; if ((type === LENS && used > ENOUGH_LENS) || (type === DISTS && used > ENOUGH_DISTS)) { return 1; } /* point entry in root table to sub-table */ low = huff & mask; /*table.op[low] = curr; table.bits[low] = root; table.val[low] = next - opts.table_index;*/ table[low] = (root << 24) | (curr << 16) | (next - table_index) |0; } } /* fill in remaining table entry if code is incomplete (guaranteed to have at most one remaining entry, since if the code is incomplete, the maximum code length that was allowed to get this far is one bit) */ if (huff !== 0) { //table.op[next + huff] = 64; /* invalid code marker */ //table.bits[next + huff] = len - drop; //table.val[next + huff] = 0; table[next + huff] = ((len - drop) << 24) | (64 << 16) |0; } /* set return parameters */ //opts.table_index += used; opts.bits = root; return 0; }; },{"../utils/common":27}],37:[function(_dereq_,module,exports){ 'use strict'; module.exports = { '2': 'need dictionary', /* Z_NEED_DICT 2 */ '1': 'stream end', /* Z_STREAM_END 1 */ '0': '', /* Z_OK 0 */ '-1': 'file error', /* Z_ERRNO (-1) */ '-2': 'stream error', /* Z_STREAM_ERROR (-2) */ '-3': 'data error', /* Z_DATA_ERROR (-3) */ '-4': 'insufficient memory', /* Z_MEM_ERROR (-4) */ '-5': 'buffer error', /* Z_BUF_ERROR (-5) */ '-6': 'incompatible version' /* Z_VERSION_ERROR (-6) */ }; },{}],38:[function(_dereq_,module,exports){ 'use strict'; var utils = _dereq_('../utils/common'); /* Public constants ==========================================================*/ /* ===========================================================================*/ //var Z_FILTERED = 1; //var Z_HUFFMAN_ONLY = 2; //var Z_RLE = 3; var Z_FIXED = 4; //var Z_DEFAULT_STRATEGY = 0; /* Possible values of the data_type field (though see inflate()) */ var Z_BINARY = 0; var Z_TEXT = 1; //var Z_ASCII = 1; // = Z_TEXT var Z_UNKNOWN = 2; /*============================================================================*/ function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } } // From zutil.h var STORED_BLOCK = 0; var STATIC_TREES = 1; var DYN_TREES = 2; /* The three kinds of block type */ var MIN_MATCH = 3; var MAX_MATCH = 258; /* The minimum and maximum match lengths */ // From deflate.h /* =========================================================================== * Internal compression state. */ var LENGTH_CODES = 29; /* number of length codes, not counting the special END_BLOCK code */ var LITERALS = 256; /* number of literal bytes 0..255 */ var L_CODES = LITERALS + 1 + LENGTH_CODES; /* number of Literal or Length codes, including the END_BLOCK code */ var D_CODES = 30; /* number of distance codes */ var BL_CODES = 19; /* number of codes used to transfer the bit lengths */ var HEAP_SIZE = 2*L_CODES + 1; /* maximum heap size */ var MAX_BITS = 15; /* All codes must not exceed MAX_BITS bits */ var Buf_size = 16; /* size of bit buffer in bi_buf */ /* =========================================================================== * Constants */ var MAX_BL_BITS = 7; /* Bit length codes must not exceed MAX_BL_BITS bits */ var END_BLOCK = 256; /* end of block literal code */ var REP_3_6 = 16; /* repeat previous bit length 3-6 times (2 bits of repeat count) */ var REPZ_3_10 = 17; /* repeat a zero length 3-10 times (3 bits of repeat count) */ var REPZ_11_138 = 18; /* repeat a zero length 11-138 times (7 bits of repeat count) */ var extra_lbits = /* extra bits for each length code */ [0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0]; var extra_dbits = /* extra bits for each distance code */ [0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13]; var extra_blbits = /* extra bits for each bit length code */ [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7]; var bl_order = [16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]; /* The lengths of the bit length codes are sent in order of decreasing * probability, to avoid transmitting the lengths for unused bit length codes. */ /* =========================================================================== * Local data. These are initialized only once. */ // We pre-fill arrays with 0 to avoid uninitialized gaps var DIST_CODE_LEN = 512; /* see definition of array dist_code below */ // !!!! Use flat array insdead of structure, Freq = i*2, Len = i*2+1 var static_ltree = new Array((L_CODES+2) * 2); zero(static_ltree); /* The static literal tree. Since the bit lengths are imposed, there is no * need for the L_CODES extra codes used during heap construction. However * The codes 286 and 287 are needed to build a canonical tree (see _tr_init * below). */ var static_dtree = new Array(D_CODES * 2); zero(static_dtree); /* The static distance tree. (Actually a trivial tree since all codes use * 5 bits.) */ var _dist_code = new Array(DIST_CODE_LEN); zero(_dist_code); /* Distance codes. The first 256 values correspond to the distances * 3 .. 258, the last 256 values correspond to the top 8 bits of * the 15 bit distances. */ var _length_code = new Array(MAX_MATCH-MIN_MATCH+1); zero(_length_code); /* length code for each normalized match length (0 == MIN_MATCH) */ var base_length = new Array(LENGTH_CODES); zero(base_length); /* First normalized length for each code (0 = MIN_MATCH) */ var base_dist = new Array(D_CODES); zero(base_dist); /* First normalized distance for each code (0 = distance of 1) */ var StaticTreeDesc = function (static_tree, extra_bits, extra_base, elems, max_length) { this.static_tree = static_tree; /* static tree or NULL */ this.extra_bits = extra_bits; /* extra bits for each code or NULL */ this.extra_base = extra_base; /* base index for extra_bits */ this.elems = elems; /* max number of elements in the tree */ this.max_length = max_length; /* max bit length for the codes */ // show if `static_tree` has data or dummy - needed for monomorphic objects this.has_stree = static_tree && static_tree.length; }; var static_l_desc; var static_d_desc; var static_bl_desc; var TreeDesc = function(dyn_tree, stat_desc) { this.dyn_tree = dyn_tree; /* the dynamic tree */ this.max_code = 0; /* largest code with non zero frequency */ this.stat_desc = stat_desc; /* the corresponding static tree */ }; function d_code(dist) { return dist < 256 ? _dist_code[dist] : _dist_code[256 + (dist >>> 7)]; } /* =========================================================================== * Output a short LSB first on the stream. * IN assertion: there is enough room in pendingBuf. */ function put_short (s, w) { // put_byte(s, (uch)((w) & 0xff)); // put_byte(s, (uch)((ush)(w) >> 8)); s.pending_buf[s.pending++] = (w) & 0xff; s.pending_buf[s.pending++] = (w >>> 8) & 0xff; } /* =========================================================================== * Send a value on a given number of bits. * IN assertion: length <= 16 and value fits in length bits. */ function send_bits(s, value, length) { if (s.bi_valid > (Buf_size - length)) { s.bi_buf |= (value << s.bi_valid) & 0xffff; put_short(s, s.bi_buf); s.bi_buf = value >> (Buf_size - s.bi_valid); s.bi_valid += length - Buf_size; } else { s.bi_buf |= (value << s.bi_valid) & 0xffff; s.bi_valid += length; } } function send_code(s, c, tree) { send_bits(s, tree[c*2]/*.Code*/, tree[c*2 + 1]/*.Len*/); } /* =========================================================================== * Reverse the first len bits of a code, using straightforward code (a faster * method would use a table) * IN assertion: 1 <= len <= 15 */ function bi_reverse(code, len) { var res = 0; do { res |= code & 1; code >>>= 1; res <<= 1; } while (--len > 0); return res >>> 1; } /* =========================================================================== * Flush the bit buffer, keeping at most 7 bits in it. */ function bi_flush(s) { if (s.bi_valid === 16) { put_short(s, s.bi_buf); s.bi_buf = 0; s.bi_valid = 0; } else if (s.bi_valid >= 8) { s.pending_buf[s.pending++] = s.bi_buf & 0xff; s.bi_buf >>= 8; s.bi_valid -= 8; } } /* =========================================================================== * Compute the optimal bit lengths for a tree and update the total bit length * for the current block. * IN assertion: the fields freq and dad are set, heap[heap_max] and * above are the tree nodes sorted by increasing frequency. * OUT assertions: the field len is set to the optimal bit length, the * array bl_count contains the frequencies for each bit length. * The length opt_len is updated; static_len is also updated if stree is * not null. */ function gen_bitlen(s, desc) // deflate_state *s; // tree_desc *desc; /* the tree descriptor */ { var tree = desc.dyn_tree; var max_code = desc.max_code; var stree = desc.stat_desc.static_tree; var has_stree = desc.stat_desc.has_stree; var extra = desc.stat_desc.extra_bits; var base = desc.stat_desc.extra_base; var max_length = desc.stat_desc.max_length; var h; /* heap index */ var n, m; /* iterate over the tree elements */ var bits; /* bit length */ var xbits; /* extra bits */ var f; /* frequency */ var overflow = 0; /* number of elements with bit length too large */ for (bits = 0; bits <= MAX_BITS; bits++) { s.bl_count[bits] = 0; } /* In a first pass, compute the optimal bit lengths (which may * overflow in the case of the bit length tree). */ tree[s.heap[s.heap_max]*2 + 1]/*.Len*/ = 0; /* root of the heap */ for (h = s.heap_max+1; h < HEAP_SIZE; h++) { n = s.heap[h]; bits = tree[tree[n*2 +1]/*.Dad*/ * 2 + 1]/*.Len*/ + 1; if (bits > max_length) { bits = max_length; overflow++; } tree[n*2 + 1]/*.Len*/ = bits; /* We overwrite tree[n].Dad which is no longer needed */ if (n > max_code) { continue; } /* not a leaf node */ s.bl_count[bits]++; xbits = 0; if (n >= base) { xbits = extra[n-base]; } f = tree[n * 2]/*.Freq*/; s.opt_len += f * (bits + xbits); if (has_stree) { s.static_len += f * (stree[n*2 + 1]/*.Len*/ + xbits); } } if (overflow === 0) { return; } // Trace((stderr,"\nbit length overflow\n")); /* This happens for example on obj2 and pic of the Calgary corpus */ /* Find the first bit length which could increase: */ do { bits = max_length-1; while (s.bl_count[bits] === 0) { bits--; } s.bl_count[bits]--; /* move one leaf down the tree */ s.bl_count[bits+1] += 2; /* move one overflow item as its brother */ s.bl_count[max_length]--; /* The brother of the overflow item also moves one step up, * but this does not affect bl_count[max_length] */ overflow -= 2; } while (overflow > 0); /* Now recompute all bit lengths, scanning in increasing frequency. * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all * lengths instead of fixing only the wrong ones. This idea is taken * from 'ar' written by Haruhiko Okumura.) */ for (bits = max_length; bits !== 0; bits--) { n = s.bl_count[bits]; while (n !== 0) { m = s.heap[--h]; if (m > max_code) { continue; } if (tree[m*2 + 1]/*.Len*/ !== bits) { // Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits)); s.opt_len += (bits - tree[m*2 + 1]/*.Len*/)*tree[m*2]/*.Freq*/; tree[m*2 + 1]/*.Len*/ = bits; } n--; } } } /* =========================================================================== * Generate the codes for a given tree and bit counts (which need not be * optimal). * IN assertion: the array bl_count contains the bit length statistics for * the given tree and the field len is set for all tree elements. * OUT assertion: the field code is set for all tree elements of non * zero code length. */ function gen_codes(tree, max_code, bl_count) // ct_data *tree; /* the tree to decorate */ // int max_code; /* largest code with non zero frequency */ // ushf *bl_count; /* number of codes at each bit length */ { var next_code = new Array(MAX_BITS+1); /* next code value for each bit length */ var code = 0; /* running code value */ var bits; /* bit index */ var n; /* code index */ /* The distribution counts are first used to generate the code values * without bit reversal. */ for (bits = 1; bits <= MAX_BITS; bits++) { next_code[bits] = code = (code + bl_count[bits-1]) << 1; } /* Check that the bit counts in bl_count are consistent. The last code * must be all ones. */ //Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1, // "inconsistent bit counts"); //Tracev((stderr,"\ngen_codes: max_code %d ", max_code)); for (n = 0; n <= max_code; n++) { var len = tree[n*2 + 1]/*.Len*/; if (len === 0) { continue; } /* Now reverse the bits */ tree[n*2]/*.Code*/ = bi_reverse(next_code[len]++, len); //Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ", // n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1)); } } /* =========================================================================== * Initialize the various 'constant' tables. */ function tr_static_init() { var n; /* iterates over tree elements */ var bits; /* bit counter */ var length; /* length value */ var code; /* code value */ var dist; /* distance index */ var bl_count = new Array(MAX_BITS+1); /* number of codes at each bit length for an optimal tree */ // do check in _tr_init() //if (static_init_done) return; /* For some embedded targets, global variables are not initialized: */ /*#ifdef NO_INIT_GLOBAL_POINTERS static_l_desc.static_tree = static_ltree; static_l_desc.extra_bits = extra_lbits; static_d_desc.static_tree = static_dtree; static_d_desc.extra_bits = extra_dbits; static_bl_desc.extra_bits = extra_blbits; #endif*/ /* Initialize the mapping length (0..255) -> length code (0..28) */ length = 0; for (code = 0; code < LENGTH_CODES-1; code++) { base_length[code] = length; for (n = 0; n < (1<<extra_lbits[code]); n++) { _length_code[length++] = code; } } //Assert (length == 256, "tr_static_init: length != 256"); /* Note that the length 255 (match length 258) can be represented * in two different ways: code 284 + 5 bits or code 285, so we * overwrite length_code[255] to use the best encoding: */ _length_code[length-1] = code; /* Initialize the mapping dist (0..32K) -> dist code (0..29) */ dist = 0; for (code = 0 ; code < 16; code++) { base_dist[code] = dist; for (n = 0; n < (1<<extra_dbits[code]); n++) { _dist_code[dist++] = code; } } //Assert (dist == 256, "tr_static_init: dist != 256"); dist >>= 7; /* from now on, all distances are divided by 128 */ for ( ; code < D_CODES; code++) { base_dist[code] = dist << 7; for (n = 0; n < (1<<(extra_dbits[code]-7)); n++) { _dist_code[256 + dist++] = code; } } //Assert (dist == 256, "tr_static_init: 256+dist != 512"); /* Construct the codes of the static literal tree */ for (bits = 0; bits <= MAX_BITS; bits++) { bl_count[bits] = 0; } n = 0; while (n <= 143) { static_ltree[n*2 + 1]/*.Len*/ = 8; n++; bl_count[8]++; } while (n <= 255) { static_ltree[n*2 + 1]/*.Len*/ = 9; n++; bl_count[9]++; } while (n <= 279) { static_ltree[n*2 + 1]/*.Len*/ = 7; n++; bl_count[7]++; } while (n <= 287) { static_ltree[n*2 + 1]/*.Len*/ = 8; n++; bl_count[8]++; } /* Codes 286 and 287 do not exist, but we must include them in the * tree construction to get a canonical Huffman tree (longest code * all ones) */ gen_codes(static_ltree, L_CODES+1, bl_count); /* The static distance tree is trivial: */ for (n = 0; n < D_CODES; n++) { static_dtree[n*2 + 1]/*.Len*/ = 5; static_dtree[n*2]/*.Code*/ = bi_reverse(n, 5); } // Now data ready and we can init static trees static_l_desc = new StaticTreeDesc(static_ltree, extra_lbits, LITERALS+1, L_CODES, MAX_BITS); static_d_desc = new StaticTreeDesc(static_dtree, extra_dbits, 0, D_CODES, MAX_BITS); static_bl_desc =new StaticTreeDesc(new Array(0), extra_blbits, 0, BL_CODES, MAX_BL_BITS); //static_init_done = true; } /* =========================================================================== * Initialize a new block. */ function init_block(s) { var n; /* iterates over tree elements */ /* Initialize the trees. */ for (n = 0; n < L_CODES; n++) { s.dyn_ltree[n*2]/*.Freq*/ = 0; } for (n = 0; n < D_CODES; n++) { s.dyn_dtree[n*2]/*.Freq*/ = 0; } for (n = 0; n < BL_CODES; n++) { s.bl_tree[n*2]/*.Freq*/ = 0; } s.dyn_ltree[END_BLOCK*2]/*.Freq*/ = 1; s.opt_len = s.static_len = 0; s.last_lit = s.matches = 0; } /* =========================================================================== * Flush the bit buffer and align the output on a byte boundary */ function bi_windup(s) { if (s.bi_valid > 8) { put_short(s, s.bi_buf); } else if (s.bi_valid > 0) { //put_byte(s, (Byte)s->bi_buf); s.pending_buf[s.pending++] = s.bi_buf; } s.bi_buf = 0; s.bi_valid = 0; } /* =========================================================================== * Copy a stored block, storing first the length and its * one's complement if requested. */ function copy_block(s, buf, len, header) //DeflateState *s; //charf *buf; /* the input data */ //unsigned len; /* its length */ //int header; /* true if block header must be written */ { bi_windup(s); /* align on byte boundary */ if (header) { put_short(s, len); put_short(s, ~len); } // while (len--) { // put_byte(s, *buf++); // } utils.arraySet(s.pending_buf, s.window, buf, len, s.pending); s.pending += len; } /* =========================================================================== * Compares to subtrees, using the tree depth as tie breaker when * the subtrees have equal frequency. This minimizes the worst case length. */ function smaller(tree, n, m, depth) { var _n2 = n*2; var _m2 = m*2; return (tree[_n2]/*.Freq*/ < tree[_m2]/*.Freq*/ || (tree[_n2]/*.Freq*/ === tree[_m2]/*.Freq*/ && depth[n] <= depth[m])); } /* =========================================================================== * Restore the heap property by moving down the tree starting at node k, * exchanging a node with the smallest of its two sons if necessary, stopping * when the heap property is re-established (each father smaller than its * two sons). */ function pqdownheap(s, tree, k) // deflate_state *s; // ct_data *tree; /* the tree to restore */ // int k; /* node to move down */ { var v = s.heap[k]; var j = k << 1; /* left son of k */ while (j <= s.heap_len) { /* Set j to the smallest of the two sons: */ if (j < s.heap_len && smaller(tree, s.heap[j+1], s.heap[j], s.depth)) { j++; } /* Exit if v is smaller than both sons */ if (smaller(tree, v, s.heap[j], s.depth)) { break; } /* Exchange v with the smallest son */ s.heap[k] = s.heap[j]; k = j; /* And continue down the tree, setting j to the left son of k */ j <<= 1; } s.heap[k] = v; } // inlined manually // var SMALLEST = 1; /* =========================================================================== * Send the block data compressed using the given Huffman trees */ function compress_block(s, ltree, dtree) // deflate_state *s; // const ct_data *ltree; /* literal tree */ // const ct_data *dtree; /* distance tree */ { var dist; /* distance of matched string */ var lc; /* match length or unmatched char (if dist == 0) */ var lx = 0; /* running index in l_buf */ var code; /* the code to send */ var extra; /* number of extra bits to send */ if (s.last_lit !== 0) { do { dist = (s.pending_buf[s.d_buf + lx*2] << 8) | (s.pending_buf[s.d_buf + lx*2 + 1]); lc = s.pending_buf[s.l_buf + lx]; lx++; if (dist === 0) { send_code(s, lc, ltree); /* send a literal byte */ //Tracecv(isgraph(lc), (stderr," '%c' ", lc)); } else { /* Here, lc is the match length - MIN_MATCH */ code = _length_code[lc]; send_code(s, code+LITERALS+1, ltree); /* send the length code */ extra = extra_lbits[code]; if (extra !== 0) { lc -= base_length[code]; send_bits(s, lc, extra); /* send the extra length bits */ } dist--; /* dist is now the match distance - 1 */ code = d_code(dist); //Assert (code < D_CODES, "bad d_code"); send_code(s, code, dtree); /* send the distance code */ extra = extra_dbits[code]; if (extra !== 0) { dist -= base_dist[code]; send_bits(s, dist, extra); /* send the extra distance bits */ } } /* literal or match pair ? */ /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */ //Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx, // "pendingBuf overflow"); } while (lx < s.last_lit); } send_code(s, END_BLOCK, ltree); } /* =========================================================================== * Construct one Huffman tree and assigns the code bit strings and lengths. * Update the total bit length for the current block. * IN assertion: the field freq is set for all tree elements. * OUT assertions: the fields len and code are set to the optimal bit length * and corresponding code. The length opt_len is updated; static_len is * also updated if stree is not null. The field max_code is set. */ function build_tree(s, desc) // deflate_state *s; // tree_desc *desc; /* the tree descriptor */ { var tree = desc.dyn_tree; var stree = desc.stat_desc.static_tree; var has_stree = desc.stat_desc.has_stree; var elems = desc.stat_desc.elems; var n, m; /* iterate over heap elements */ var max_code = -1; /* largest code with non zero frequency */ var node; /* new node being created */ /* Construct the initial heap, with least frequent element in * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1]. * heap[0] is not used. */ s.heap_len = 0; s.heap_max = HEAP_SIZE; for (n = 0; n < elems; n++) { if (tree[n * 2]/*.Freq*/ !== 0) { s.heap[++s.heap_len] = max_code = n; s.depth[n] = 0; } else { tree[n*2 + 1]/*.Len*/ = 0; } } /* The pkzip format requires that at least one distance code exists, * and that at least one bit should be sent even if there is only one * possible code. So to avoid special checks later on we force at least * two codes of non zero frequency. */ while (s.heap_len < 2) { node = s.heap[++s.heap_len] = (max_code < 2 ? ++max_code : 0); tree[node * 2]/*.Freq*/ = 1; s.depth[node] = 0; s.opt_len--; if (has_stree) { s.static_len -= stree[node*2 + 1]/*.Len*/; } /* node is 0 or 1 so it does not have extra bits */ } desc.max_code = max_code; /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree, * establish sub-heaps of increasing lengths: */ for (n = (s.heap_len >> 1/*int /2*/); n >= 1; n--) { pqdownheap(s, tree, n); } /* Construct the Huffman tree by repeatedly combining the least two * frequent nodes. */ node = elems; /* next internal node of the tree */ do { //pqremove(s, tree, n); /* n = node of least frequency */ /*** pqremove ***/ n = s.heap[1/*SMALLEST*/]; s.heap[1/*SMALLEST*/] = s.heap[s.heap_len--]; pqdownheap(s, tree, 1/*SMALLEST*/); /***/ m = s.heap[1/*SMALLEST*/]; /* m = node of next least frequency */ s.heap[--s.heap_max] = n; /* keep the nodes sorted by frequency */ s.heap[--s.heap_max] = m; /* Create a new node father of n and m */ tree[node * 2]/*.Freq*/ = tree[n * 2]/*.Freq*/ + tree[m * 2]/*.Freq*/; s.depth[node] = (s.depth[n] >= s.depth[m] ? s.depth[n] : s.depth[m]) + 1; tree[n*2 + 1]/*.Dad*/ = tree[m*2 + 1]/*.Dad*/ = node; /* and insert the new node in the heap */ s.heap[1/*SMALLEST*/] = node++; pqdownheap(s, tree, 1/*SMALLEST*/); } while (s.heap_len >= 2); s.heap[--s.heap_max] = s.heap[1/*SMALLEST*/]; /* At this point, the fields freq and dad are set. We can now * generate the bit lengths. */ gen_bitlen(s, desc); /* The field len is now set, we can generate the bit codes */ gen_codes(tree, max_code, s.bl_count); } /* =========================================================================== * Scan a literal or distance tree to determine the frequencies of the codes * in the bit length tree. */ function scan_tree(s, tree, max_code) // deflate_state *s; // ct_data *tree; /* the tree to be scanned */ // int max_code; /* and its largest code of non zero frequency */ { var n; /* iterates over all tree elements */ var prevlen = -1; /* last emitted length */ var curlen; /* length of current code */ var nextlen = tree[0*2 + 1]/*.Len*/; /* length of next code */ var count = 0; /* repeat count of the current code */ var max_count = 7; /* max repeat count */ var min_count = 4; /* min repeat count */ if (nextlen === 0) { max_count = 138; min_count = 3; } tree[(max_code+1)*2 + 1]/*.Len*/ = 0xffff; /* guard */ for (n = 0; n <= max_code; n++) { curlen = nextlen; nextlen = tree[(n+1)*2 + 1]/*.Len*/; if (++count < max_count && curlen === nextlen) { continue; } else if (count < min_count) { s.bl_tree[curlen * 2]/*.Freq*/ += count; } else if (curlen !== 0) { if (curlen !== prevlen) { s.bl_tree[curlen * 2]/*.Freq*/++; } s.bl_tree[REP_3_6*2]/*.Freq*/++; } else if (count <= 10) { s.bl_tree[REPZ_3_10*2]/*.Freq*/++; } else { s.bl_tree[REPZ_11_138*2]/*.Freq*/++; } count = 0; prevlen = curlen; if (nextlen === 0) { max_count = 138; min_count = 3; } else if (curlen === nextlen) { max_count = 6; min_count = 3; } else { max_count = 7; min_count = 4; } } } /* =========================================================================== * Send a literal or distance tree in compressed form, using the codes in * bl_tree. */ function send_tree(s, tree, max_code) // deflate_state *s; // ct_data *tree; /* the tree to be scanned */ // int max_code; /* and its largest code of non zero frequency */ { var n; /* iterates over all tree elements */ var prevlen = -1; /* last emitted length */ var curlen; /* length of current code */ var nextlen = tree[0*2 + 1]/*.Len*/; /* length of next code */ var count = 0; /* repeat count of the current code */ var max_count = 7; /* max repeat count */ var min_count = 4; /* min repeat count */ /* tree[max_code+1].Len = -1; */ /* guard already set */ if (nextlen === 0) { max_count = 138; min_count = 3; } for (n = 0; n <= max_code; n++) { curlen = nextlen; nextlen = tree[(n+1)*2 + 1]/*.Len*/; if (++count < max_count && curlen === nextlen) { continue; } else if (count < min_count) { do { send_code(s, curlen, s.bl_tree); } while (--count !== 0); } else if (curlen !== 0) { if (curlen !== prevlen) { send_code(s, curlen, s.bl_tree); count--; } //Assert(count >= 3 && count <= 6, " 3_6?"); send_code(s, REP_3_6, s.bl_tree); send_bits(s, count-3, 2); } else if (count <= 10) { send_code(s, REPZ_3_10, s.bl_tree); send_bits(s, count-3, 3); } else { send_code(s, REPZ_11_138, s.bl_tree); send_bits(s, count-11, 7); } count = 0; prevlen = curlen; if (nextlen === 0) { max_count = 138; min_count = 3; } else if (curlen === nextlen) { max_count = 6; min_count = 3; } else { max_count = 7; min_count = 4; } } } /* =========================================================================== * Construct the Huffman tree for the bit lengths and return the index in * bl_order of the last bit length code to send. */ function build_bl_tree(s) { var max_blindex; /* index of last bit length code of non zero freq */ /* Determine the bit length frequencies for literal and distance trees */ scan_tree(s, s.dyn_ltree, s.l_desc.max_code); scan_tree(s, s.dyn_dtree, s.d_desc.max_code); /* Build the bit length tree: */ build_tree(s, s.bl_desc); /* opt_len now includes the length of the tree representations, except * the lengths of the bit lengths codes and the 5+5+4 bits for the counts. */ /* Determine the number of bit length codes to send. The pkzip format * requires that at least 4 bit length codes be sent. (appnote.txt says * 3 but the actual value used is 4.) */ for (max_blindex = BL_CODES-1; max_blindex >= 3; max_blindex--) { if (s.bl_tree[bl_order[max_blindex]*2 + 1]/*.Len*/ !== 0) { break; } } /* Update opt_len to include the bit length tree and counts */ s.opt_len += 3*(max_blindex+1) + 5+5+4; //Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld", // s->opt_len, s->static_len)); return max_blindex; } /* =========================================================================== * Send the header for a block using dynamic Huffman trees: the counts, the * lengths of the bit length codes, the literal tree and the distance tree. * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4. */ function send_all_trees(s, lcodes, dcodes, blcodes) // deflate_state *s; // int lcodes, dcodes, blcodes; /* number of codes for each tree */ { var rank; /* index in bl_order */ //Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes"); //Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES, // "too many codes"); //Tracev((stderr, "\nbl counts: ")); send_bits(s, lcodes-257, 5); /* not +255 as stated in appnote.txt */ send_bits(s, dcodes-1, 5); send_bits(s, blcodes-4, 4); /* not -3 as stated in appnote.txt */ for (rank = 0; rank < blcodes; rank++) { //Tracev((stderr, "\nbl code %2d ", bl_order[rank])); send_bits(s, s.bl_tree[bl_order[rank]*2 + 1]/*.Len*/, 3); } //Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent)); send_tree(s, s.dyn_ltree, lcodes-1); /* literal tree */ //Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent)); send_tree(s, s.dyn_dtree, dcodes-1); /* distance tree */ //Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent)); } /* =========================================================================== * Check if the data type is TEXT or BINARY, using the following algorithm: * - TEXT if the two conditions below are satisfied: * a) There are no non-portable control characters belonging to the * "black list" (0..6, 14..25, 28..31). * b) There is at least one printable character belonging to the * "white list" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255). * - BINARY otherwise. * - The following partially-portable control characters form a * "gray list" that is ignored in this detection algorithm: * (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}). * IN assertion: the fields Freq of dyn_ltree are set. */ function detect_data_type(s) { /* black_mask is the bit mask of black-listed bytes * set bits 0..6, 14..25, and 28..31 * 0xf3ffc07f = binary 11110011111111111100000001111111 */ var black_mask = 0xf3ffc07f; var n; /* Check for non-textual ("black-listed") bytes. */ for (n = 0; n <= 31; n++, black_mask >>>= 1) { if ((black_mask & 1) && (s.dyn_ltree[n*2]/*.Freq*/ !== 0)) { return Z_BINARY; } } /* Check for textual ("white-listed") bytes. */ if (s.dyn_ltree[9 * 2]/*.Freq*/ !== 0 || s.dyn_ltree[10 * 2]/*.Freq*/ !== 0 || s.dyn_ltree[13 * 2]/*.Freq*/ !== 0) { return Z_TEXT; } for (n = 32; n < LITERALS; n++) { if (s.dyn_ltree[n * 2]/*.Freq*/ !== 0) { return Z_TEXT; } } /* There are no "black-listed" or "white-listed" bytes: * this stream either is empty or has tolerated ("gray-listed") bytes only. */ return Z_BINARY; } var static_init_done = false; /* =========================================================================== * Initialize the tree data structures for a new zlib stream. */ function _tr_init(s) { if (!static_init_done) { tr_static_init(); static_init_done = true; } s.l_desc = new TreeDesc(s.dyn_ltree, static_l_desc); s.d_desc = new TreeDesc(s.dyn_dtree, static_d_desc); s.bl_desc = new TreeDesc(s.bl_tree, static_bl_desc); s.bi_buf = 0; s.bi_valid = 0; /* Initialize the first block of the first file: */ init_block(s); } /* =========================================================================== * Send a stored block */ function _tr_stored_block(s, buf, stored_len, last) //DeflateState *s; //charf *buf; /* input block */ //ulg stored_len; /* length of input block */ //int last; /* one if this is the last block for a file */ { send_bits(s, (STORED_BLOCK<<1)+(last ? 1 : 0), 3); /* send block type */ copy_block(s, buf, stored_len, true); /* with header */ } /* =========================================================================== * Send one empty static block to give enough lookahead for inflate. * This takes 10 bits, of which 7 may remain in the bit buffer. */ function _tr_align(s) { send_bits(s, STATIC_TREES<<1, 3); send_code(s, END_BLOCK, static_ltree); bi_flush(s); } /* =========================================================================== * Determine the best encoding for the current block: dynamic trees, static * trees or store, and output the encoded block to the zip file. */ function _tr_flush_block(s, buf, stored_len, last) //DeflateState *s; //charf *buf; /* input block, or NULL if too old */ //ulg stored_len; /* length of input block */ //int last; /* one if this is the last block for a file */ { var opt_lenb, static_lenb; /* opt_len and static_len in bytes */ var max_blindex = 0; /* index of last bit length code of non zero freq */ /* Build the Huffman trees unless a stored block is forced */ if (s.level > 0) { /* Check if the file is binary or text */ if (s.strm.data_type === Z_UNKNOWN) { s.strm.data_type = detect_data_type(s); } /* Construct the literal and distance trees */ build_tree(s, s.l_desc); // Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len, // s->static_len)); build_tree(s, s.d_desc); // Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len, // s->static_len)); /* At this point, opt_len and static_len are the total bit lengths of * the compressed block data, excluding the tree representations. */ /* Build the bit length tree for the above two trees, and get the index * in bl_order of the last bit length code to send. */ max_blindex = build_bl_tree(s); /* Determine the best encoding. Compute the block lengths in bytes. */ opt_lenb = (s.opt_len+3+7) >>> 3; static_lenb = (s.static_len+3+7) >>> 3; // Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ", // opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len, // s->last_lit)); if (static_lenb <= opt_lenb) { opt_lenb = static_lenb; } } else { // Assert(buf != (char*)0, "lost buf"); opt_lenb = static_lenb = stored_len + 5; /* force a stored block */ } if ((stored_len+4 <= opt_lenb) && (buf !== -1)) { /* 4: two words for the lengths */ /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE. * Otherwise we can't have processed more than WSIZE input bytes since * the last block flush, because compression would have been * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to * transform a block into a stored block. */ _tr_stored_block(s, buf, stored_len, last); } else if (s.strategy === Z_FIXED || static_lenb === opt_lenb) { send_bits(s, (STATIC_TREES<<1) + (last ? 1 : 0), 3); compress_block(s, static_ltree, static_dtree); } else { send_bits(s, (DYN_TREES<<1) + (last ? 1 : 0), 3); send_all_trees(s, s.l_desc.max_code+1, s.d_desc.max_code+1, max_blindex+1); compress_block(s, s.dyn_ltree, s.dyn_dtree); } // Assert (s->compressed_len == s->bits_sent, "bad compressed size"); /* The above check is made mod 2^32, for files larger than 512 MB * and uLong implemented on 32 bits. */ init_block(s); if (last) { bi_windup(s); } // Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3, // s->compressed_len-7*last)); } /* =========================================================================== * Save the match info and tally the frequency counts. Return true if * the current block must be flushed. */ function _tr_tally(s, dist, lc) // deflate_state *s; // unsigned dist; /* distance of matched string */ // unsigned lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */ { //var out_length, in_length, dcode; s.pending_buf[s.d_buf + s.last_lit * 2] = (dist >>> 8) & 0xff; s.pending_buf[s.d_buf + s.last_lit * 2 + 1] = dist & 0xff; s.pending_buf[s.l_buf + s.last_lit] = lc & 0xff; s.last_lit++; if (dist === 0) { /* lc is the unmatched char */ s.dyn_ltree[lc*2]/*.Freq*/++; } else { s.matches++; /* Here, lc is the match length - MIN_MATCH */ dist--; /* dist = match distance - 1 */ //Assert((ush)dist < (ush)MAX_DIST(s) && // (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) && // (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match"); s.dyn_ltree[(_length_code[lc]+LITERALS+1) * 2]/*.Freq*/++; s.dyn_dtree[d_code(dist) * 2]/*.Freq*/++; } // (!) This block is disabled in zlib defailts, // don't enable it for binary compatibility //#ifdef TRUNCATE_BLOCK // /* Try to guess if it is profitable to stop the current block here */ // if ((s.last_lit & 0x1fff) === 0 && s.level > 2) { // /* Compute an upper bound for the compressed length */ // out_length = s.last_lit*8; // in_length = s.strstart - s.block_start; // // for (dcode = 0; dcode < D_CODES; dcode++) { // out_length += s.dyn_dtree[dcode*2]/*.Freq*/ * (5 + extra_dbits[dcode]); // } // out_length >>>= 3; // //Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ", // // s->last_lit, in_length, out_length, // // 100L - out_length*100L/in_length)); // if (s.matches < (s.last_lit>>1)/*int /2*/ && out_length < (in_length>>1)/*int /2*/) { // return true; // } // } //#endif return (s.last_lit === s.lit_bufsize-1); /* We avoid equality with lit_bufsize because of wraparound at 64K * on 16 bit machines and because stored blocks are restricted to * 64K-1 bytes. */ } exports._tr_init = _tr_init; exports._tr_stored_block = _tr_stored_block; exports._tr_flush_block = _tr_flush_block; exports._tr_tally = _tr_tally; exports._tr_align = _tr_align; },{"../utils/common":27}],39:[function(_dereq_,module,exports){ 'use strict'; function ZStream() { /* next input byte */ this.input = null; // JS specific, because we have no pointers this.next_in = 0; /* number of bytes available at input */ this.avail_in = 0; /* total number of input bytes read so far */ this.total_in = 0; /* next output byte should be put there */ this.output = null; // JS specific, because we have no pointers this.next_out = 0; /* remaining free space at output */ this.avail_out = 0; /* total number of bytes output so far */ this.total_out = 0; /* last error message, NULL if no error */ this.msg = ''/*Z_NULL*/; /* not visible by applications */ this.state = null; /* best guess about the data type: binary or text */ this.data_type = 2/*Z_UNKNOWN*/; /* adler32 value of the uncompressed data */ this.adler = 0; } module.exports = ZStream; },{}]},{},[9]) (9) });
Piicksarn/cdnjs
ajax/libs/amcharts/3.20.4/plugins/export/libs/jszip/jszip.js
JavaScript
mit
293,471
require(__dirname).test ( { xml : "<root xmlns:x='x1' xmlns:y='y1' x:a='x1' y:a='y1'>"+ "<rebind xmlns:x='x2'>"+ "<check x:a='x2' y:a='y1'/>"+ "</rebind>"+ "<check x:a='x1' y:a='y1'/>"+ "</root>" , expect : [ [ "opennamespace", { prefix: "x", uri: "x1" } ] , [ "opennamespace", { prefix: "y", uri: "y1" } ] , [ "attribute", { name: "xmlns:x", value: "x1", uri: "http://www.w3.org/2000/xmlns/", prefix: "xmlns", local: "x" } ] , [ "attribute", { name: "xmlns:y", value: "y1", uri: "http://www.w3.org/2000/xmlns/", prefix: "xmlns", local: "y" } ] , [ "attribute", { name: "x:a", value: "x1", uri: "x1", prefix: "x", local: "a" } ] , [ "attribute", { name: "y:a", value: "y1", uri: "y1", prefix: "y", local: "a" } ] , [ "opentag", { name: "root", uri: "", prefix: "", local: "root", attributes: { "xmlns:x": { name: "xmlns:x", value: "x1", uri: "http://www.w3.org/2000/xmlns/", prefix: "xmlns", local: "x" } , "xmlns:y": { name: "xmlns:y", value: "y1", uri: "http://www.w3.org/2000/xmlns/", prefix: "xmlns", local: "y" } , "x:a": { name: "x:a", value: "x1", uri: "x1", prefix: "x", local: "a" } , "y:a": { name: "y:a", value: "y1", uri: "y1", prefix: "y", local: "a" } }, ns: { x: 'x1', y: 'y1' }, isSelfClosing: false } ] , [ "opennamespace", { prefix: "x", uri: "x2" } ] , [ "attribute", { name: "xmlns:x", value: "x2", uri: "http://www.w3.org/2000/xmlns/", prefix: "xmlns", local: "x" } ] , [ "opentag", { name: "rebind", uri: "", prefix: "", local: "rebind", attributes: { "xmlns:x": { name: "xmlns:x", value: "x2", uri: "http://www.w3.org/2000/xmlns/", prefix: "xmlns", local: "x" } }, ns: { x: 'x2' }, isSelfClosing: false } ] , [ "attribute", { name: "x:a", value: "x2", uri: "x2", prefix: "x", local: "a" } ] , [ "attribute", { name: "y:a", value: "y1", uri: "y1", prefix: "y", local: "a" } ] , [ "opentag", { name: "check", uri: "", prefix: "", local: "check", attributes: { "x:a": { name: "x:a", value: "x2", uri: "x2", prefix: "x", local: "a" } , "y:a": { name: "y:a", value: "y1", uri: "y1", prefix: "y", local: "a" } }, ns: { x: 'x2' }, isSelfClosing: true } ] , [ "closetag", "check" ] , [ "closetag", "rebind" ] , [ "closenamespace", { prefix: "x", uri: "x2" } ] , [ "attribute", { name: "x:a", value: "x1", uri: "x1", prefix: "x", local: "a" } ] , [ "attribute", { name: "y:a", value: "y1", uri: "y1", prefix: "y", local: "a" } ] , [ "opentag", { name: "check", uri: "", prefix: "", local: "check", attributes: { "x:a": { name: "x:a", value: "x1", uri: "x1", prefix: "x", local: "a" } , "y:a": { name: "y:a", value: "y1", uri: "y1", prefix: "y", local: "a" } }, ns: { x: 'x1', y: 'y1' }, isSelfClosing: true } ] , [ "closetag", "check" ] , [ "closetag", "root" ] , [ "closenamespace", { prefix: "x", uri: "x1" } ] , [ "closenamespace", { prefix: "y", uri: "y1" } ] ] , strict : true , opt : { xmlns: true } } )
NelsonChu/cloud-command
node_modules/aws-sdk/node_modules/xml2js/node_modules/sax/test/xmlns-rebinding.js
JavaScript
mit
3,307
var t = require(__dirname) , xmls = // should be the same both ways. [ "<parent xmlns:a='http://ATTRIBUTE' a:attr='value' />" , "<parent a:attr='value' xmlns:a='http://ATTRIBUTE' />" ] , ex1 = [ [ "opennamespace" , { prefix: "a" , uri: "http://ATTRIBUTE" } ] , [ "attribute" , { name: "xmlns:a" , value: "http://ATTRIBUTE" , prefix: "xmlns" , local: "a" , uri: "http://www.w3.org/2000/xmlns/" } ] , [ "attribute" , { name: "a:attr" , local: "attr" , prefix: "a" , uri: "http://ATTRIBUTE" , value: "value" } ] , [ "opentag" , { name: "parent" , uri: "" , prefix: "" , local: "parent" , attributes: { "a:attr": { name: "a:attr" , local: "attr" , prefix: "a" , uri: "http://ATTRIBUTE" , value: "value" } , "xmlns:a": { name: "xmlns:a" , local: "a" , prefix: "xmlns" , uri: "http://www.w3.org/2000/xmlns/" , value: "http://ATTRIBUTE" } } , ns: {"a": "http://ATTRIBUTE"} , isSelfClosing: true } ] , ["closetag", "parent"] , ["closenamespace", { prefix: "a", uri: "http://ATTRIBUTE" }] ] // swap the order of elements 2 and 1 , ex2 = [ex1[0], ex1[2], ex1[1]].concat(ex1.slice(3)) , expected = [ex1, ex2] xmls.forEach(function (x, i) { t.test({ xml: x , expect: expected[i] , strict: true , opt: { xmlns: true } }) })
rockbot/vektor
sonar-scan/node_modules/stylus/node_modules/sax/test/xmlns-issue-41.js
JavaScript
mit
1,673
.cm-s-cobalt { background: #002240; color: white; } .cm-s-cobalt div.CodeMirror-selected { background: #b36539 !important; } .cm-s-cobalt .CodeMirror-gutter { background: #002240; border-right: 1px solid #aaa; } .cm-s-cobalt .CodeMirror-gutter-text { color: #d0d0d0; } .cm-s-cobalt .CodeMirror-cursor { border-left: 1px solid white !important; } .cm-s-cobalt span.cm-comment { color: #08f; } .cm-s-cobalt span.cm-atom { color: #845dc4; } .cm-s-cobalt span.cm-number, .cm-s-cobalt span.cm-attribute { color: #ff80e1; } .cm-s-cobalt span.cm-keyword { color: #ffee80; } .cm-s-cobalt span.cm-string { color: #3ad900; } .cm-s-cobalt span.cm-meta { color: #ff9d00; } .cm-s-cobalt span.cm-variable-2, .cm-s-cobalt span.cm-tag { color: #9effff; } .cm-s-cobalt span.cm-variable-3, .cm-s-cobalt span.cm-def { color: white; } .cm-s-cobalt span.cm-error { color: #9d1e15; } .cm-s-cobalt span.cm-bracket { color: #d8d8d8; } .cm-s-cobalt span.cm-builtin, .cm-s-cobalt span.cm-special { color: #ff9e59; } .cm-s-cobalt span.cm-link { color: #845dc4; }
Shazwazza/Umbraco-CMS
src/Umbraco.Web.UI/umbraco_client/CodeMirror/js/theme/cobalt.css
CSS
mit
1,055
/*! lazysizes - v1.2.1 */ !function(a,b){var c=b(a,a.document);a.lazySizes=c,"object"==typeof module&&module.exports?module.exports=c:"function"==typeof define&&define.amd&&define(c)}(window,function(a,b){"use strict";if(b.getElementsByClassName){var c,d=b.documentElement,e=a.HTMLPictureElement&&"sizes"in b.createElement("img"),f="addEventListener",g=a[f],h=a.setTimeout,i=a.requestAnimationFrame||h,j=a.setImmediate||h,k=/^picture$/i,l=["load","error","lazyincluded","_lazyloaded"],m={},n=function(a,b){return m[b]||(m[b]=new RegExp("(\\s|^)"+b+"(\\s|$)")),m[b].test(a.className)&&m[b]},o=function(a,b){n(a,b)||(a.className=a.className.trim()+" "+b)},p=function(a,b){var c;(c=n(a,b))&&(a.className=a.className.replace(c," "))},q=function(a,b,c){var d=c?f:"removeEventListener";c&&q(a,b),l.forEach(function(c){a[d](c,b)})},r=function(a,c,d,e,f){var g=b.createEvent("CustomEvent");return g.initCustomEvent(c,!e,!f,d||{}),a.dispatchEvent(g),g},s=function(b,d){var f;!e&&(f=a.picturefill||a.respimage||c.pf)?f({reevaluate:!0,elements:[b]}):d&&d.src&&(b.src=d.src)},t=function(a,b){return(getComputedStyle(a,null)||{})[b]},u=function(a,b,d){for(d=d||a.offsetWidth;d<c.minSize&&b&&!a._lazysizesWidth;)d=b.offsetWidth,b=b.parentNode;return d},v=function(b){var c,d=0,e=a.Date,f=function(){c=!1,d=e.now(),b()},g=function(){j(f)},k=function(){i(g)};return function(){if(!c){var a=125-(e.now()-d);c=!0,6>a&&(a=6),h(k,a)}}},w=function(){var e,j,l,m,u,w,y,z,A,B,C,D,E,F,G,H,I=/^img$/i,J=/^iframe$/i,K="onscroll"in a&&!/glebot/.test(navigator.userAgent),L=0,M=0,N=0,O=0,P=function(a){N--,a&&a.target&&q(a.target,P),(!a||0>N||!a.target)&&(N=0)},Q=function(a,b){var c,d=a,e="hidden"!=t(a,"visibility");for(A-=b,D+=b,B-=b,C+=b;e&&(d=d.offsetParent);)e=(t(d,"opacity")||1)>0,e&&"visible"!=t(d,"overflow")&&(c=d.getBoundingClientRect(),e=C>c.left&&B<c.right&&D>c.top-1&&A<c.bottom+1);return e},R=function(){var a,b,d,f,g,h,i,k,m;if((u=c.loadMode)&&8>N&&(a=e.length)){for(b=0,O++,H>M&&1>N&&O>3&&u>2?(M=H,O=0):M=u>1&&O>2&&6>N?G:L;a>b;b++)if(e[b]&&!e[b]._lazyRace)if(K)if((k=e[b].getAttribute("data-expand"))&&(h=1*k)||(h=M),m!==h&&(y=innerWidth+h,z=innerHeight+h,i=-1*h,m=h),d=e[b].getBoundingClientRect(),(D=d.bottom)>=i&&(A=d.top)<=z&&(C=d.right)>=i&&(B=d.left)<=y&&(D||C||B||A)&&(l&&3>N&&!k&&(3>u||4>O)||Q(e[b],h))){if(W(e[b]),g=!0,N>9)break;N>6&&(M=L)}else!g&&l&&!f&&3>N&&4>O&&u>2&&(j[0]||c.preloadAfterLoad)&&(j[0]||!k&&(D||C||B||A||"auto"!=e[b].getAttribute(c.sizesAttr)))&&(f=j[0]||e[b]);else W(e[b]);f&&!g&&W(f)}},S=v(R),T=function(a){o(a.target,c.loadedClass),p(a.target,c.loadingClass),q(a.target,T)},U=function(a,b){try{a.contentWindow.location.replace(b)}catch(c){a.setAttribute("src",b)}},V=function(){var a,b=[],c=function(){for(;b.length;)b.shift()();a=!1};return function(d){b.push(d),a||(a=!0,i(c))}}(),W=function(a){var b,d,e,f,g,i,j,t,u,v,w,y,z=I.test(a.nodeName),A=z&&(a.getAttribute(c.sizesAttr)||a.getAttribute("sizes")),B="auto"==A;(!B&&l||!z||!a.src&&!a.srcset||a.complete||n(a,c.errorClass))&&(B&&(y=a.offsetWidth),a._lazyRace=!0,N++,V(function(){if(a._lazyRace&&delete a._lazyRace,p(a,c.lazyClass),!(u=r(a,"lazybeforeunveil")).defaultPrevented){if(A&&(B?(o(a,c.autosizesClass),x.updateElem(a,!0,y)):a.setAttribute("sizes",A)),i=a.getAttribute(c.srcsetAttr),g=a.getAttribute(c.srcAttr),z&&(j=a.parentNode,t=j&&k.test(j.nodeName||"")),v=u.detail.firesLoad||"src"in a&&(i||g||t),u={target:a},v&&(q(a,P,!0),clearTimeout(m),m=h(P,2500),o(a,c.loadingClass),q(a,T,!0)),t)for(b=j.getElementsByTagName("source"),d=0,e=b.length;e>d;d++)(w=c.customMedia[b[d].getAttribute("data-media")||b[d].getAttribute("media")])&&b[d].setAttribute("media",w),f=b[d].getAttribute(c.srcsetAttr),f&&b[d].setAttribute("srcset",f);i?a.setAttribute("srcset",i):g&&!t&&(J.test(a.nodeName)?U(a,g):a.setAttribute("src",g)),(i||t)&&s(a,{src:g})}(!v||a.complete)&&(v?P(u):N--,T(u))}))},X=function(){if(!l){if(Date.now()-w<999)return void h(X,999);var a,b=function(){c.loadMode=3,G=E,S()};l=!0,c.loadMode=3,N||S(),g("scroll",function(){3==c.loadMode&&(G=F,c.loadMode=2),clearTimeout(a),a=h(b,99)},!0)}};return{_:function(){w=Date.now(),e=b.getElementsByClassName(c.lazyClass),j=b.getElementsByClassName(c.lazyClass+" "+c.preloadClass),G=c.expand,E=G,F=G*((c.expFactor+1)/2),H=G*c.expFactor,g("scroll",S,!0),g("resize",S,!0),a.MutationObserver?new MutationObserver(S).observe(d,{childList:!0,subtree:!0,attributes:!0}):(d[f]("DOMNodeInserted",S,!0),d[f]("DOMAttrModified",S,!0),setInterval(S,999)),g("hashchange",S,!0),["focus","mouseover","click","load","transitionend","animationend","webkitAnimationEnd"].forEach(function(a){b[f](a,S,!0)}),/d$|^c/.test(b.readyState)?X():(g("load",X),b[f]("DOMContentLoaded",S),h(X,2e4)),S(e.length>0)},checkElems:S,unveil:W}}(),x=function(){var a,d=function(a,b,c){var d,e,f,g,h=a.parentNode;if(h&&(c=u(a,h,c),g=r(a,"lazybeforesizes",{width:c,dataAttr:!!b}),!g.defaultPrevented&&(c=g.detail.width,c&&c!==a._lazysizesWidth))){if(a._lazysizesWidth=c,c+="px",a.setAttribute("sizes",c),k.test(h.nodeName||""))for(d=h.getElementsByTagName("source"),e=0,f=d.length;f>e;e++)d[e].setAttribute("sizes",c);g.detail.dataAttr||s(a,g.detail)}},e=function(){var b,c=a.length;if(c)for(b=0;c>b;b++)d(a[b])},f=v(e);return{_:function(){a=b.getElementsByClassName(c.autosizesClass),g("resize",f)},checkElems:f,updateElem:d}}(),y=function(){y.i||(y.i=!0,x._(),w._())};return function(){var b,d={lazyClass:"lazyload",loadedClass:"lazyloaded",loadingClass:"lazyloading",preloadClass:"lazypreload",errorClass:"lazyerror",autosizesClass:"lazyautosizes",srcAttr:"data-src",srcsetAttr:"data-srcset",sizesAttr:"data-sizes",minSize:40,customMedia:{},init:!0,expFactor:2,expand:359,loadMode:2};c=a.lazySizesConfig||a.lazysizesConfig||{};for(b in d)b in c||(c[b]=d[b]);a.lazySizesConfig=c,h(function(){c.init&&y()})}(),{cfg:c,autoSizer:x,loader:w,init:y,uP:s,aC:o,rC:p,hC:n,fire:r,gW:u}}});
gswalden/jsdelivr
files/lazysizes/1.2.1/lazysizes.min.js
JavaScript
mit
5,869
webshims.register('details', function($, webshims, window, doc, undefined, options){ var isInterActiveSummary = function(summary){ var details = $(summary).parent('details'); if(details[0] && details.children(':first').get(0) === summary){ return details; } }; var bindDetailsSummary = function(summary, details){ summary = $(summary); details = $(details); var oldSummary = $.data(details[0], 'summaryElement'); $.data(summary[0], 'detailsElement', details); if(!oldSummary || summary[0] !== oldSummary[0]){ if(oldSummary){ if(oldSummary.hasClass('fallback-summary')){ oldSummary.remove(); } else { oldSummary .off('.summaryPolyfill') .removeData('detailsElement') .removeAttr('role') .removeAttr('tabindex') .removeAttr('aria-expanded') .removeClass('summary-button') .find('span.details-open-indicator') .remove() ; } } $.data(details[0], 'summaryElement', summary); details.prop('open', details.prop('open')); } }; var getSummary = function(details){ var summary = $.data(details, 'summaryElement'); if(!summary){ summary = $(details).children('summary:first-child'); if(!summary[0]){ $(details).prependPolyfill('<summary class="fallback-summary">'+ options.text +'</summary>'); summary = $.data(details, 'summaryElement'); } else { bindDetailsSummary(summary, details); } } return summary; }; // var isOriginalPrevented = function(e){ // var src = e.originalEvent; // if(!src){return e.isDefaultPrevented();} // // return src.defaultPrevented || src.returnValue === false || // src.getPreventDefault && src.getPreventDefault(); // }; webshims.createElement('summary', function(){ var details = isInterActiveSummary(this); if(!details || $.data(this, 'detailsElement')){return;} var timer; var stopNativeClickTest; var tabindex = $.attr(this, 'tabIndex') || '0'; bindDetailsSummary(this, details); $(this) .on({ 'focus.summaryPolyfill': function(){ $(this).addClass('summary-has-focus'); }, 'blur.summaryPolyfill': function(){ $(this).removeClass('summary-has-focus'); }, 'mouseenter.summaryPolyfill': function(){ $(this).addClass('summary-has-hover'); }, 'mouseleave.summaryPolyfill': function(){ $(this).removeClass('summary-has-hover'); }, 'click.summaryPolyfill': function(e){ var details = isInterActiveSummary(this); if(details){ if(!stopNativeClickTest && e.originalEvent){ stopNativeClickTest = true; e.stopImmediatePropagation(); e.preventDefault(); $(this).trigger('click'); stopNativeClickTest = false; return false; } else { clearTimeout(timer); timer = setTimeout(function(){ if(!e.isDefaultPrevented()){ details.prop('open', !details.prop('open')); } }, 0); } } }, 'keydown.summaryPolyfill': function(e){ if( (e.keyCode == 13 || e.keyCode == 32) && !e.isDefaultPrevented()){ stopNativeClickTest = true; e.preventDefault(); $(this).trigger('click'); stopNativeClickTest = false; } } }) .attr({tabindex: tabindex, role: 'button'}) .prepend('<span class="details-open-indicator" />') ; webshims.moveToFirstEvent(this, 'click'); }); var initDetails; webshims.defineNodeNamesBooleanProperty('details', 'open', function(val){ var summary = $($.data(this, 'summaryElement')); if(!summary){return;} var action = (val) ? 'removeClass' : 'addClass'; var details = $(this); if (!initDetails && options.animate){ details.stop().css({width: '', height: ''}); var start = { width: details.width(), height: details.height() }; } summary.attr('aria-expanded', ''+val); details[action]('closed-details-summary').children().not(summary[0])[action]('closed-details-child'); if(!initDetails && options.animate){ var end = { width: details.width(), height: details.height() }; details.css(start).animate(end, { complete: function(){ $(this).css({width: '', height: ''}); } }); } }); webshims.createElement('details', function(){ initDetails = true; var summary = getSummary(this); $.prop(this, 'open', $.prop(this, 'open')); initDetails = false; }); }); ;webshims.register('track', function($, webshims, window, document, undefined){ "use strict"; var mediaelement = webshims.mediaelement; var id = new Date().getTime(); //descriptions are not really shown, but they are inserted into the dom var showTracks = {subtitles: 1, captions: 1, descriptions: 1}; var dummyTrack = $('<track />'); var support = webshims.support; var supportTrackMod = support.ES5 && support.objectAccessor; var createEventTarget = function(obj){ var eventList = {}; obj.addEventListener = function(name, fn){ if(eventList[name]){ webshims.error('always use $.on to the shimed event: '+ name +' already bound fn was: '+ eventList[name] +' your fn was: '+ fn); } eventList[name] = fn; }; obj.removeEventListener = function(name, fn){ if(eventList[name] && eventList[name] != fn){ webshims.error('always use $.on/$.off to the shimed event: '+ name +' already bound fn was: '+ eventList[name] +' your fn was: '+ fn); } if(eventList[name]){ delete eventList[name]; } }; return obj; }; var cueListProto = { getCueById: function(id){ var cue = null; for(var i = 0, len = this.length; i < len; i++){ if(this[i].id === id){ cue = this[i]; break; } } return cue; } }; var numericModes = { 0: 'disabled', 1: 'hidden', 2: 'showing' }; var textTrackProto = { shimActiveCues: null, _shimActiveCues: null, activeCues: null, cues: null, kind: 'subtitles', label: '', language: '', id: '', mode: 'disabled', oncuechange: null, toString: function() { return "[object TextTrack]"; }, addCue: function(cue){ if(!this.cues){ this.cues = mediaelement.createCueList(); } else { var lastCue = this.cues[this.cues.length-1]; if(lastCue && lastCue.startTime > cue.startTime){ webshims.error("cue startTime higher than previous cue's startTime"); } } if(cue.track && cue.track.removeCue){ cue.track.removeCue(cue); } cue.track = this; this.cues.push(cue); }, //ToDo: make it more dynamic removeCue: function(cue){ var cues = this.cues || []; var i = 0; var len = cues.length; if(cue.track != this){ webshims.error("cue not part of track"); return; } for(; i < len; i++){ if(cues[i] === cue){ cues.splice(i, 1); cue.track = null; break; } } if(cue.track){ webshims.error("cue not part of track"); return; } }/*, DISABLED: 'disabled', OFF: 'disabled', HIDDEN: 'hidden', SHOWING: 'showing', ERROR: 3, LOADED: 2, LOADING: 1, NONE: 0*/ }; var copyProps = ['kind', 'label', 'srclang']; var copyName = {srclang: 'language'}; var updateMediaTrackList = function(baseData, trackList){ var removed = []; var added = []; var newTracks = []; var i, len; if(!baseData){ baseData = webshims.data(this, 'mediaelementBase') || webshims.data(this, 'mediaelementBase', {}); } if(!trackList){ baseData.blockTrackListUpdate = true; trackList = $.prop(this, 'textTracks'); baseData.blockTrackListUpdate = false; } clearTimeout(baseData.updateTrackListTimer); $('track', this).each(function(){ var track = $.prop(this, 'track'); newTracks.push(track); if(trackList.indexOf(track) == -1){ added.push(track); } }); if(baseData.scriptedTextTracks){ for(i = 0, len = baseData.scriptedTextTracks.length; i < len; i++){ newTracks.push(baseData.scriptedTextTracks[i]); if(trackList.indexOf(baseData.scriptedTextTracks[i]) == -1){ added.push(baseData.scriptedTextTracks[i]); } } } for(i = 0, len = trackList.length; i < len; i++){ if(newTracks.indexOf(trackList[i]) == -1){ removed.push(trackList[i]); } } if(removed.length || added.length){ trackList.splice(0); for(i = 0, len = newTracks.length; i < len; i++){ trackList.push(newTracks[i]); } for(i = 0, len = removed.length; i < len; i++){ $([trackList]).triggerHandler($.Event({type: 'removetrack', track: removed[i]})); } for(i = 0, len = added.length; i < len; i++){ $([trackList]).triggerHandler($.Event({type: 'addtrack', track: added[i]})); } if(baseData.scriptedTextTracks || removed.length){ $(this).triggerHandler('updatetrackdisplay'); } } }; var refreshTrack = function(track, trackData){ if(!trackData){ trackData = webshims.data(track, 'trackData'); } if(trackData && !trackData.isTriggering){ trackData.isTriggering = true; setTimeout(function(){ $(track).closest('audio, video').triggerHandler('updatetrackdisplay'); trackData.isTriggering = false; }, 1); } }; var isDefaultTrack = (function(){ var defaultKinds = { subtitles: { subtitles: 1, captions: 1 }, descriptions: {descriptions: 1}, chapters: {chapters: 1} }; defaultKinds.captions = defaultKinds.subtitles; return function(track){ var kind, firstDefaultTrack; var isDefault = $.prop(track, 'default'); if(isDefault && (kind = $.prop(track, 'kind')) != 'metadata'){ firstDefaultTrack = $(track) .parent() .find('track[default]') .filter(function(){ return !!(defaultKinds[kind][$.prop(this, 'kind')]); })[0] ; if(firstDefaultTrack != track){ isDefault = false; webshims.error('more than one default track of a specific kind detected. Fall back to default = false'); } } return isDefault; }; })(); var emptyDiv = $('<div />')[0]; function VTTCue(startTime, endTime, text){ if(arguments.length != 3){ webshims.error("wrong arguments.length for VTTCue.constructor"); } this.startTime = startTime; this.endTime = endTime; this.text = text; this.onenter = null; this.onexit = null; this.pauseOnExit = false; this.track = null; this.id = null; this.getCueAsHTML = (function(){ var lastText = ""; var parsedText = ""; var fragment; return function(){ var i, len; if(!fragment){ fragment = document.createDocumentFragment(); } if(lastText != this.text){ lastText = this.text; parsedText = mediaelement.parseCueTextToHTML(lastText); emptyDiv.innerHTML = parsedText; for(i = 0, len = emptyDiv.childNodes.length; i < len; i++){ fragment.appendChild(emptyDiv.childNodes[i].cloneNode(true)); } } return fragment.cloneNode(true); }; })(); } window.VTTCue = VTTCue; window.TextTrackCue = function(){ webshims.error("Use VTTCue constructor instead of abstract TextTrackCue constructor."); VTTCue.apply(this, arguments); }; window.TextTrackCue.prototype = VTTCue.prototype; mediaelement.createCueList = function(){ return $.extend([], cueListProto); }; mediaelement.parseCueTextToHTML = (function(){ var tagSplits = /(<\/?[^>]+>)/ig; var allowedTags = /^(?:c|v|ruby|rt|b|i|u)/; var regEnd = /\<\s*\//; var addToTemplate = function(localName, attribute, tag, html){ var ret; if(regEnd.test(html)){ ret = '</'+ localName +'>'; } else { tag.splice(0, 1); ret = '<'+ localName +' '+ attribute +'="'+ (tag.join(' ').replace(/\"/g, '&#34;')) +'">'; } return ret; }; var replacer = function(html){ var tag = html.replace(/[<\/>]+/ig,"").split(/[\s\.]+/); if(tag[0]){ tag[0] = tag[0].toLowerCase(); if(allowedTags.test(tag[0])){ if(tag[0] == 'c'){ html = addToTemplate('span', 'class', tag, html); } else if(tag[0] == 'v'){ html = addToTemplate('q', 'title', tag, html); } } else { html = ""; } } return html; }; return function(cueText){ return cueText.replace(tagSplits, replacer); }; })(); var mapTtmlToVtt = function(i){ var content = i+''; var begin = this.getAttribute('begin') || ''; var end = this.getAttribute('end') || ''; var text = $.trim($.text(this)); if(!/\./.test(begin)){ begin += '.000'; } if(!/\./.test(end)){ end += '.000'; } content += '\n'; content += begin +' --> '+end+'\n'; content += text; return content; }; var ttmlTextToVTT = function(ttml){ ttml = $.parseXML(ttml) || []; return $(ttml).find('[begin][end]').map(mapTtmlToVtt).get().join('\n\n') || ''; }; mediaelement.loadTextTrack = function(mediaelem, track, trackData, _default){ var loadEvents = 'play playing'; var obj = trackData.track; var load = function(){ var error, ajax, createAjax; var src = obj.mode != 'disabled' && ($.attr(track, 'src') && $.prop(track, 'src')); if(src){ $(mediaelem).off(loadEvents, load).off('updatetrackdisplay', load); if(!trackData.readyState){ error = function(){ trackData.readyState = 3; obj.cues = null; obj.activeCues = obj.shimActiveCues = obj._shimActiveCues = null; $(track).triggerHandler('error'); }; trackData.readyState = 1; try { obj.cues = mediaelement.createCueList(); obj.activeCues = obj.shimActiveCues = obj._shimActiveCues = mediaelement.createCueList(); createAjax = function(){ ajax = $.ajax({ dataType: 'text', url: src, success: function(text){ var contentType = ajax.getResponseHeader('content-type') || ''; if(!contentType.indexOf('application/xml')){ text = ttmlTextToVTT(text); } else if(contentType.indexOf('text/vtt')){ webshims.error('set the mime-type of your WebVTT files to text/vtt. see: http://dev.w3.org/html5/webvtt/#text/vtt'); } mediaelement.parseCaptions(text, obj, function(cues){ if(cues && 'length' in cues){ trackData.readyState = 2; $(track).triggerHandler('load'); $(mediaelem).triggerHandler('updatetrackdisplay'); } else { error(); } }); }, error: error }); }; if($.ajax && $.ajaxSettings.xhr){ createAjax(); } else { webshims.ready('jajax', createAjax); webshims.loader.loadList(['jajax']); } } catch(er){ error(); webshims.error(er); } } } }; trackData.readyState = 0; obj.shimActiveCues = null; obj._shimActiveCues = null; obj.activeCues = null; obj.cues = null; $(mediaelem).on(loadEvents, load); if(_default){ obj.mode = showTracks[obj.kind] ? 'showing' : 'hidden'; load(); } else { $(mediaelem).on('updatetrackdisplay', load); } }; mediaelement.createTextTrack = function(mediaelem, track){ var obj, trackData; if(track.nodeName){ trackData = webshims.data(track, 'trackData'); if(trackData){ refreshTrack(track, trackData); obj = trackData.track; } } if(!obj){ obj = createEventTarget(webshims.objectCreate(textTrackProto)); if(!supportTrackMod){ copyProps.forEach(function(copyProp){ var prop = $.prop(track, copyProp); if(prop){ obj[copyName[copyProp] || copyProp] = prop; } }); } if(track.nodeName){ if(supportTrackMod){ copyProps.forEach(function(copyProp){ webshims.defineProperty(obj, copyName[copyProp] || copyProp, { get: function(){ return $.prop(track, copyProp); } }); }); } obj.id = $(track).prop('id'); trackData = webshims.data(track, 'trackData', {track: obj}); mediaelement.loadTextTrack(mediaelem, track, trackData, isDefaultTrack(track)); } else { if(supportTrackMod){ copyProps.forEach(function(copyProp){ webshims.defineProperty(obj, copyName[copyProp] || copyProp, { value: track[copyProp], writeable: false }); }); } obj.cues = mediaelement.createCueList(); obj.activeCues = obj._shimActiveCues = obj.shimActiveCues = mediaelement.createCueList(); obj.mode = 'hidden'; obj.readyState = 2; } if(obj.kind == 'subtitles' && !obj.language){ webshims.error('you must provide a language for track in subtitles state'); } obj.__wsmode = obj.mode; } return obj; }; /* taken from: Captionator 0.5.1 [CaptionCrunch] Christopher Giffard, 2011 Share and enjoy https://github.com/cgiffard/Captionator modified for webshims */ mediaelement.parseCaptionChunk = (function(){ // Set up timestamp parsers var WebVTTTimestampParser = /^(\d{2})?:?(\d{2}):(\d{2})\.(\d+)\s+\-\-\>\s+(\d{2})?:?(\d{2}):(\d{2})\.(\d+)\s*(.*)/; var WebVTTDEFAULTSCueParser = /^(DEFAULTS|DEFAULT)\s+\-\-\>\s+(.*)/g; var WebVTTSTYLECueParser = /^(STYLE|STYLES)\s+\-\-\>\s*\n([\s\S]*)/g; var WebVTTCOMMENTCueParser = /^(COMMENT|COMMENTS)\s+\-\-\>\s+(.*)/g; var SRTTimestampParser = /^(\d{2})?:?(\d{2}):(\d{2})[\.\,](\d+)\s+\-\-\>\s+(\d{2})?:?(\d{2}):(\d{2})[\.\,](\d+)\s*(.*)/; return function(subtitleElement,objectCount){ var subtitleParts, timeIn, timeOut, html, timeData, subtitlePartIndex, id; var timestampMatch, tmpCue; // WebVTT Special Cue Logic if (WebVTTDEFAULTSCueParser.exec(subtitleElement) || WebVTTCOMMENTCueParser.exec(subtitleElement) || WebVTTSTYLECueParser.exec(subtitleElement)) { return null; } subtitleParts = subtitleElement.split(/\n/g); // Trim off any blank lines (logically, should only be max. one, but loop to be sure) while (!subtitleParts[0].replace(/\s+/ig,"").length && subtitleParts.length > 0) { subtitleParts.shift(); } if (subtitleParts[0].match(/^\s*[a-z0-9-\_]+\s*$/ig)) { // The identifier becomes the cue ID (when *we* load the cues from file. Programatically created cues can have an ID of whatever.) id = String(subtitleParts.shift().replace(/\s*/ig,"")); } for (subtitlePartIndex = 0; subtitlePartIndex < subtitleParts.length; subtitlePartIndex ++) { var timestamp = subtitleParts[subtitlePartIndex]; if ((timestampMatch = WebVTTTimestampParser.exec(timestamp)) || (timestampMatch = SRTTimestampParser.exec(timestamp))) { // WebVTT timeData = timestampMatch.slice(1); timeIn = parseInt((timeData[0]||0) * 60 * 60,10) + // Hours parseInt((timeData[1]||0) * 60,10) + // Minutes parseInt((timeData[2]||0),10) + // Seconds parseFloat("0." + (timeData[3]||0)); // MS timeOut = parseInt((timeData[4]||0) * 60 * 60,10) + // Hours parseInt((timeData[5]||0) * 60,10) + // Minutes parseInt((timeData[6]||0),10) + // Seconds parseFloat("0." + (timeData[7]||0)); // MS /* if (timeData[8]) { cueSettings = timeData[8]; } */ } // We've got the timestamp - return all the other unmatched lines as the raw subtitle data subtitleParts = subtitleParts.slice(0,subtitlePartIndex).concat(subtitleParts.slice(subtitlePartIndex+1)); break; } if (!timeIn && !timeOut) { // We didn't extract any time information. Assume the cue is invalid! webshims.warn("couldn't extract time information: "+[timeIn, timeOut, subtitleParts.join("\n"), id].join(' ; ')); return null; } /* // Consolidate cue settings, convert defaults to object var compositeCueSettings = cueDefaults .reduce(function(previous,current,index,array){ previous[current.split(":")[0]] = current.split(":")[1]; return previous; },{}); // Loop through cue settings, replace defaults with cue specific settings if they exist compositeCueSettings = cueSettings .split(/\s+/g) .filter(function(set) { return set && !!set.length; }) // Convert array to a key/val object .reduce(function(previous,current,index,array){ previous[current.split(":")[0]] = current.split(":")[1]; return previous; },compositeCueSettings); // Turn back into string like the VTTCue constructor expects cueSettings = ""; for (var key in compositeCueSettings) { if (compositeCueSettings.hasOwnProperty(key)) { cueSettings += !!cueSettings.length ? " " : ""; cueSettings += key + ":" + compositeCueSettings[key]; } } */ // The remaining lines are the subtitle payload itself (after removing an ID if present, and the time); html = subtitleParts.join("\n"); tmpCue = new VTTCue(timeIn, timeOut, html); if(id){ tmpCue.id = id; } return tmpCue; }; })(); mediaelement.parseCaptions = function(captionData, track, complete) { var cue, lazyProcess, regWevVTT, startDate, isWEBVTT; mediaelement.createCueList(); if (captionData) { regWevVTT = /^WEBVTT(\s*FILE)?/ig; lazyProcess = function(i, len){ for(; i < len; i++){ cue = captionData[i]; if(regWevVTT.test(cue)){ isWEBVTT = true; } else if(cue.replace(/\s*/ig,"").length){ cue = mediaelement.parseCaptionChunk(cue, i); if(cue){ track.addCue(cue); } } if(startDate < (new Date().getTime()) - 30){ i++; setTimeout(function(){ startDate = new Date().getTime(); lazyProcess(i, len); }, 90); break; } } if(i >= len){ if(!isWEBVTT){ webshims.error('please use WebVTT format. This is the standard'); } complete(track.cues); } }; captionData = captionData.replace(/\r\n/g,"\n"); setTimeout(function(){ captionData = captionData.replace(/\r/g,"\n"); setTimeout(function(){ startDate = new Date().getTime(); captionData = captionData.split(/\n\n+/g); lazyProcess(0, captionData.length); }, 9); }, 9); } else { webshims.error("Required parameter captionData not supplied."); } }; mediaelement.createTrackList = function(mediaelem, baseData){ baseData = baseData || webshims.data(mediaelem, 'mediaelementBase') || webshims.data(mediaelem, 'mediaelementBase', {}); if(!baseData.textTracks){ baseData.textTracks = []; webshims.defineProperties(baseData.textTracks, { onaddtrack: {value: null}, onremovetrack: {value: null}, onchange: {value: null}, getTrackById: { value: function(id){ var track = null; for(var i = 0; i < baseData.textTracks.length; i++){ if(id == baseData.textTracks[i].id){ track = baseData.textTracks[i]; break; } } return track; } } }); createEventTarget(baseData.textTracks); $(mediaelem).on('updatetrackdisplay', function(){ var track; for(var i = 0; i < baseData.textTracks.length; i++){ track = baseData.textTracks[i]; if(track.__wsmode != track.mode){ track.__wsmode = track.mode; $([ baseData.textTracks ]).triggerHandler('change'); } } }); } return baseData.textTracks; }; if(!support.track){ webshims.defineNodeNamesBooleanProperty(['track'], 'default'); webshims.reflectProperties(['track'], ['srclang', 'label']); webshims.defineNodeNameProperties('track', { src: { //attr: {}, reflect: true, propType: 'src' } }); } webshims.defineNodeNameProperties('track', { kind: { attr: support.track ? { set: function(value){ var trackData = webshims.data(this, 'trackData'); this.setAttribute('data-kind', value); if(trackData){ trackData.attrKind = value; } }, get: function(){ var trackData = webshims.data(this, 'trackData'); if(trackData && ('attrKind' in trackData)){ return trackData.attrKind; } return this.getAttribute('kind'); } } : {}, reflect: true, propType: 'enumarated', defaultValue: 'subtitles', limitedTo: ['subtitles', 'captions', 'descriptions', 'chapters', 'metadata'] } }); $.each(copyProps, function(i, copyProp){ var name = copyName[copyProp] || copyProp; webshims.onNodeNamesPropertyModify('track', copyProp, function(){ var trackData = webshims.data(this, 'trackData'); var track = this; if(trackData){ if(copyProp == 'kind'){ refreshTrack(this, trackData); } if(!supportTrackMod){ trackData.track[name] = $.prop(this, copyProp); } } }); }); webshims.onNodeNamesPropertyModify('track', 'src', function(val){ if(val){ var data = webshims.data(this, 'trackData'); var media; if(data){ media = $(this).closest('video, audio'); if(media[0]){ mediaelement.loadTextTrack(media, this, data); } } } }); // webshims.defineNodeNamesProperties(['track'], { ERROR: { value: 3 }, LOADED: { value: 2 }, LOADING: { value: 1 }, NONE: { value: 0 }, readyState: { get: function(){ return (webshims.data(this, 'trackData') || {readyState: 0}).readyState; }, writeable: false }, track: { get: function(){ return mediaelement.createTextTrack($(this).closest('audio, video')[0], this); }, writeable: false } }, 'prop'); webshims.defineNodeNamesProperties(['audio', 'video'], { textTracks: { get: function(){ var media = this; var baseData = webshims.data(media, 'mediaelementBase') || webshims.data(media, 'mediaelementBase', {}); var tracks = mediaelement.createTrackList(media, baseData); if(!baseData.blockTrackListUpdate){ updateMediaTrackList.call(media, baseData, tracks); } return tracks; }, writeable: false }, addTextTrack: { value: function(kind, label, lang){ var textTrack = mediaelement.createTextTrack(this, { kind: dummyTrack.prop('kind', kind || '').prop('kind'), label: label || '', srclang: lang || '' }); var baseData = webshims.data(this, 'mediaelementBase') || webshims.data(this, 'mediaelementBase', {}); if (!baseData.scriptedTextTracks) { baseData.scriptedTextTracks = []; } baseData.scriptedTextTracks.push(textTrack); updateMediaTrackList.call(this); return textTrack; } } }, 'prop'); //wsmediareload var thUpdateList = function(e){ if($(e.target).is('audio, video')){ var baseData = webshims.data(e.target, 'mediaelementBase'); if(baseData){ clearTimeout(baseData.updateTrackListTimer); baseData.updateTrackListTimer = setTimeout(function(){ updateMediaTrackList.call(e.target, baseData); }, 0); } } }; var getNativeReadyState = function(trackElem, textTrack){ return textTrack.readyState || trackElem.readyState; }; var stopOriginalEvent = function(e){ if(e.originalEvent){ e.stopImmediatePropagation(); } }; var hideNativeTracks = function(){ if(webshims.implement(this, 'track')){ var kind; var origTrack = this.track; if(origTrack){ if (!webshims.bugs.track && (origTrack.mode || getNativeReadyState(this, origTrack))) { $.prop(this, 'track').mode = numericModes[origTrack.mode] || origTrack.mode; } //disable track from showing + remove UI kind = $.prop(this, 'kind'); origTrack.mode = (typeof origTrack.mode == 'string') ? 'disabled' : 0; this.kind = 'metadata'; $(this).attr({kind: kind}); } $(this).on('load error', stopOriginalEvent); } }; webshims.addReady(function(context, insertedElement){ var insertedMedia = insertedElement.filter('video, audio, track').closest('audio, video'); $('video, audio', context) .add(insertedMedia) .each(function(){ updateMediaTrackList.call(this); }) .on('emptied updatetracklist wsmediareload', thUpdateList) .each(function(){ if(support.track){ var shimedTextTracks = $.prop(this, 'textTracks'); var origTextTracks = this.textTracks; if(shimedTextTracks.length != origTextTracks.length){ webshims.warn("textTracks couldn't be copied"); } $('track', this).each(hideNativeTracks); } }) ; insertedMedia.each(function(){ var media = this; var baseData = webshims.data(media, 'mediaelementBase'); if(baseData){ clearTimeout(baseData.updateTrackListTimer); baseData.updateTrackListTimer = setTimeout(function(){ updateMediaTrackList.call(media, baseData); }, 9); } }); }); if(support.texttrackapi){ $('video, audio').trigger('trackapichange'); } });
khasinski/cdnjs
ajax/libs/webshim/1.14.4-RC1/dev/shims/combos/22.js
JavaScript
mit
28,257
/* Modernizr 2.7.1 (Custom Build) | MIT & BSD * Build: http://modernizr.com/download/#-canvas-audio-video-input-inputtypes-localstorage-sessionstorage-geolocation-shiv-cssclasses-addtest-prefixed-testprop-testallprops-prefixes-domprefixes-elem_track */ ; window.Modernizr = (function( window, document, undefined ) { var version = '2.7.1', Modernizr = {}, enableClasses = true, docElement = document.documentElement, mod = 'modernizr', modElem = document.createElement(mod), mStyle = modElem.style, inputElem = document.createElement('input') , smile = ':)', toString = {}.toString, prefixes = ' -webkit- -moz- -o- -ms- '.split(' '), omPrefixes = 'Webkit Moz O ms', cssomPrefixes = omPrefixes.split(' '), domPrefixes = omPrefixes.toLowerCase().split(' '), tests = {}, inputs = {}, attrs = {}, classes = [], slice = classes.slice, featureName, _hasOwnProperty = ({}).hasOwnProperty, hasOwnProp; if ( !is(_hasOwnProperty, 'undefined') && !is(_hasOwnProperty.call, 'undefined') ) { hasOwnProp = function (object, property) { return _hasOwnProperty.call(object, property); }; } else { hasOwnProp = function (object, property) { return ((property in object) && is(object.constructor.prototype[property], 'undefined')); }; } if (!Function.prototype.bind) { Function.prototype.bind = function bind(that) { var target = this; if (typeof target != "function") { throw new TypeError(); } var args = slice.call(arguments, 1), bound = function () { if (this instanceof bound) { var F = function(){}; F.prototype = target.prototype; var self = new F(); var result = target.apply( self, args.concat(slice.call(arguments)) ); if (Object(result) === result) { return result; } return self; } else { return target.apply( that, args.concat(slice.call(arguments)) ); } }; return bound; }; } function setCss( str ) { mStyle.cssText = str; } function setCssAll( str1, str2 ) { return setCss(prefixes.join(str1 + ';') + ( str2 || '' )); } function is( obj, type ) { return typeof obj === type; } function contains( str, substr ) { return !!~('' + str).indexOf(substr); } function testProps( props, prefixed ) { for ( var i in props ) { var prop = props[i]; if ( !contains(prop, "-") && mStyle[prop] !== undefined ) { return prefixed == 'pfx' ? prop : true; } } return false; } function testDOMProps( props, obj, elem ) { for ( var i in props ) { var item = obj[props[i]]; if ( item !== undefined) { if (elem === false) return props[i]; if (is(item, 'function')){ return item.bind(elem || obj); } return item; } } return false; } function testPropsAll( prop, prefixed, elem ) { var ucProp = prop.charAt(0).toUpperCase() + prop.slice(1), props = (prop + ' ' + cssomPrefixes.join(ucProp + ' ') + ucProp).split(' '); if(is(prefixed, "string") || is(prefixed, "undefined")) { return testProps(props, prefixed); } else { props = (prop + ' ' + (domPrefixes).join(ucProp + ' ') + ucProp).split(' '); return testDOMProps(props, prefixed, elem); } } tests['canvas'] = function() { var elem = document.createElement('canvas'); return !!(elem.getContext && elem.getContext('2d')); }; tests['geolocation'] = function() { return 'geolocation' in navigator; }; tests['video'] = function() { var elem = document.createElement('video'), bool = false; try { if ( bool = !!elem.canPlayType ) { bool = new Boolean(bool); bool.ogg = elem.canPlayType('video/ogg; codecs="theora"') .replace(/^no$/,''); bool.h264 = elem.canPlayType('video/mp4; codecs="avc1.42E01E"') .replace(/^no$/,''); bool.webm = elem.canPlayType('video/webm; codecs="vp8, vorbis"').replace(/^no$/,''); } } catch(e) { } return bool; }; tests['audio'] = function() { var elem = document.createElement('audio'), bool = false; try { if ( bool = !!elem.canPlayType ) { bool = new Boolean(bool); bool.ogg = elem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/,''); bool.mp3 = elem.canPlayType('audio/mpeg;') .replace(/^no$/,''); bool.wav = elem.canPlayType('audio/wav; codecs="1"') .replace(/^no$/,''); bool.m4a = ( elem.canPlayType('audio/x-m4a;') || elem.canPlayType('audio/aac;')) .replace(/^no$/,''); } } catch(e) { } return bool; }; tests['localstorage'] = function() { try { localStorage.setItem(mod, mod); localStorage.removeItem(mod); return true; } catch(e) { return false; } }; tests['sessionstorage'] = function() { try { sessionStorage.setItem(mod, mod); sessionStorage.removeItem(mod); return true; } catch(e) { return false; } }; function webforms() { Modernizr['input'] = (function( props ) { for ( var i = 0, len = props.length; i < len; i++ ) { attrs[ props[i] ] = !!(props[i] in inputElem); } if (attrs.list){ attrs.list = !!(document.createElement('datalist') && window.HTMLDataListElement); } return attrs; })('autocomplete autofocus list placeholder max min multiple pattern required step'.split(' ')); Modernizr['inputtypes'] = (function(props) { for ( var i = 0, bool, inputElemType, defaultView, len = props.length; i < len; i++ ) { inputElem.setAttribute('type', inputElemType = props[i]); bool = inputElem.type !== 'text'; if ( bool ) { inputElem.value = smile; inputElem.style.cssText = 'position:absolute;visibility:hidden;'; if ( /^range$/.test(inputElemType) && inputElem.style.WebkitAppearance !== undefined ) { docElement.appendChild(inputElem); defaultView = document.defaultView; bool = defaultView.getComputedStyle && defaultView.getComputedStyle(inputElem, null).WebkitAppearance !== 'textfield' && (inputElem.offsetHeight !== 0); docElement.removeChild(inputElem); } else if ( /^(search|tel)$/.test(inputElemType) ){ } else if ( /^(url|email)$/.test(inputElemType) ) { bool = inputElem.checkValidity && inputElem.checkValidity() === false; } else { bool = inputElem.value != smile; } } inputs[ props[i] ] = !!bool; } return inputs; })('search tel url email datetime date month week time datetime-local number range color'.split(' ')); } for ( var feature in tests ) { if ( hasOwnProp(tests, feature) ) { featureName = feature.toLowerCase(); Modernizr[featureName] = tests[feature](); classes.push((Modernizr[featureName] ? '' : 'no-') + featureName); } } Modernizr.input || webforms(); Modernizr.addTest = function ( feature, test ) { if ( typeof feature == 'object' ) { for ( var key in feature ) { if ( hasOwnProp( feature, key ) ) { Modernizr.addTest( key, feature[ key ] ); } } } else { feature = feature.toLowerCase(); if ( Modernizr[feature] !== undefined ) { return Modernizr; } test = typeof test == 'function' ? test() : test; if (typeof enableClasses !== "undefined" && enableClasses) { docElement.className += ' ' + (test ? '' : 'no-') + feature; } Modernizr[feature] = test; } return Modernizr; }; setCss(''); modElem = inputElem = null; ;(function(window, document) { var version = '3.7.0'; var options = window.html5 || {}; var reSkip = /^<|^(?:button|map|select|textarea|object|iframe|option|optgroup)$/i; var saveClones = /^(?:a|b|code|div|fieldset|h1|h2|h3|h4|h5|h6|i|label|li|ol|p|q|span|strong|style|table|tbody|td|th|tr|ul)$/i; var supportsHtml5Styles; var expando = '_html5shiv'; var expanID = 0; var expandoData = {}; var supportsUnknownElements; (function() { try { var a = document.createElement('a'); a.innerHTML = '<xyz></xyz>'; supportsHtml5Styles = ('hidden' in a); supportsUnknownElements = a.childNodes.length == 1 || (function() { (document.createElement)('a'); var frag = document.createDocumentFragment(); return ( typeof frag.cloneNode == 'undefined' || typeof frag.createDocumentFragment == 'undefined' || typeof frag.createElement == 'undefined' ); }()); } catch(e) { supportsHtml5Styles = true; supportsUnknownElements = true; } }()); function addStyleSheet(ownerDocument, cssText) { var p = ownerDocument.createElement('p'), parent = ownerDocument.getElementsByTagName('head')[0] || ownerDocument.documentElement; p.innerHTML = 'x<style>' + cssText + '</style>'; return parent.insertBefore(p.lastChild, parent.firstChild); } function getElements() { var elements = html5.elements; return typeof elements == 'string' ? elements.split(' ') : elements; } function getExpandoData(ownerDocument) { var data = expandoData[ownerDocument[expando]]; if (!data) { data = {}; expanID++; ownerDocument[expando] = expanID; expandoData[expanID] = data; } return data; } function createElement(nodeName, ownerDocument, data){ if (!ownerDocument) { ownerDocument = document; } if(supportsUnknownElements){ return ownerDocument.createElement(nodeName); } if (!data) { data = getExpandoData(ownerDocument); } var node; if (data.cache[nodeName]) { node = data.cache[nodeName].cloneNode(); } else if (saveClones.test(nodeName)) { node = (data.cache[nodeName] = data.createElem(nodeName)).cloneNode(); } else { node = data.createElem(nodeName); } return node.canHaveChildren && !reSkip.test(nodeName) && !node.tagUrn ? data.frag.appendChild(node) : node; } function createDocumentFragment(ownerDocument, data){ if (!ownerDocument) { ownerDocument = document; } if(supportsUnknownElements){ return ownerDocument.createDocumentFragment(); } data = data || getExpandoData(ownerDocument); var clone = data.frag.cloneNode(), i = 0, elems = getElements(), l = elems.length; for(;i<l;i++){ clone.createElement(elems[i]); } return clone; } function shivMethods(ownerDocument, data) { if (!data.cache) { data.cache = {}; data.createElem = ownerDocument.createElement; data.createFrag = ownerDocument.createDocumentFragment; data.frag = data.createFrag(); } ownerDocument.createElement = function(nodeName) { if (!html5.shivMethods) { return data.createElem(nodeName); } return createElement(nodeName, ownerDocument, data); }; ownerDocument.createDocumentFragment = Function('h,f', 'return function(){' + 'var n=f.cloneNode(),c=n.createElement;' + 'h.shivMethods&&(' + getElements().join().replace(/[\w\-]+/g, function(nodeName) { data.createElem(nodeName); data.frag.createElement(nodeName); return 'c("' + nodeName + '")'; }) + ');return n}' )(html5, data.frag); } function shivDocument(ownerDocument) { if (!ownerDocument) { ownerDocument = document; } var data = getExpandoData(ownerDocument); if (html5.shivCSS && !supportsHtml5Styles && !data.hasCSS) { data.hasCSS = !!addStyleSheet(ownerDocument, 'article,aside,dialog,figcaption,figure,footer,header,hgroup,main,nav,section{display:block}' + 'mark{background:#FF0;color:#000}' + 'template{display:none}' ); } if (!supportsUnknownElements) { shivMethods(ownerDocument, data); } return ownerDocument; } var html5 = { 'elements': options.elements || 'abbr article aside audio bdi canvas data datalist details dialog figcaption figure footer header hgroup main mark meter nav output progress section summary template time video', 'version': version, 'shivCSS': (options.shivCSS !== false), 'supportsUnknownElements': supportsUnknownElements, 'shivMethods': (options.shivMethods !== false), 'type': 'default', 'shivDocument': shivDocument, createElement: createElement, createDocumentFragment: createDocumentFragment }; window.html5 = html5; shivDocument(document); }(this, document)); Modernizr._version = version; Modernizr._prefixes = prefixes; Modernizr._domPrefixes = domPrefixes; Modernizr._cssomPrefixes = cssomPrefixes; Modernizr.testProp = function(prop){ return testProps([prop]); }; Modernizr.testAllProps = testPropsAll; Modernizr.prefixed = function(prop, obj, elem){ if(!obj) { return testPropsAll(prop, 'pfx'); } else { return testPropsAll(prop, obj, elem); } }; docElement.className = docElement.className.replace(/(^|\s)no-js(\s|$)/, '$1$2') + (enableClasses ? ' js ' + classes.join(' ') : ''); return Modernizr; })(this, this.document); // Track element + Timed Text Track API // http://www.w3.org/TR/html5/video.html#the-track-element // http://www.w3.org/TR/html5/media-elements.html#text-track-api // // While IE10 has implemented the track element, IE10 does not expose the underlying APIs to create timed text tracks by JS (really sad) // By Addy Osmani Modernizr.addTest({ texttrackapi: (typeof (document.createElement('video').addTextTrack) === 'function'), // a more strict test for track including UI support: document.createElement('track').kind === 'subtitles' track: ('kind' in document.createElement('track')) }); ;
nagyist/OpenF2-cdnjs
ajax/libs/webshim/1.12.2/dev/extras/modernizr-custom.js
JavaScript
mit
13,467
webshims.register("form-shim-extend2",function(a,b,c,d,e,f){"use strict";var g=function(a){return"number"==typeof a||a&&a==1*a},h=!("getSetAttribute"in a.support&&!a.support.getSetAttribute),i=!("submitBubbles"in a.support)||a.support.submitBubbles,j=function(b){i||!b||"object"!=typeof b||b._submit_attached||(a.event.add(b,"submit._submit",function(a){a._submit_bubble=!0}),b._submit_attached=!0)};if(!i&&a.event.special.submit&&(a.event.special.submit.setup=function(){return a.nodeName(this,"form")?!1:void a.event.add(this,"click._submit keypress._submit",function(b){var c=b.target,d=a.nodeName(c,"input")||a.nodeName(c,"button")?a.prop(c,"form"):e;j(d)})}),b.reflectProperties(["input"],["pattern"]),!("maxLength"in d.createElement("textarea"))){var k=function(){var b,c=0,d=a([]),e=1e9,f=function(){var a=d.prop("value"),b=a.length;b>c&&b>e&&(b=Math.max(c,e),d.prop("value",a.substr(0,b))),c=b},g=function(){clearTimeout(b),d.off(".maxlengthconstraint")};return function(h,i){g(),i>-1&&(e=i,c=a.prop(h,"value").length,d=a(h),d.on({"keydown.maxlengthconstraint keypress.maxlengthconstraint paste.maxlengthconstraint cut.maxlengthconstraint":function(){setTimeout(f,0)},"keyup.maxlengthconstraint":f,"blur.maxlengthconstraint":g}),b=setInterval(f,200))}}();k.update=function(b,c){a(b).is(":focus")&&(c||(c=a.prop(b,"maxlength")),k(b,c))},a(d).on("focusin",function(b){var c;"TEXTAREA"==b.target.nodeName&&(c=a.prop(b.target,"maxlength"))>-1&&k(b.target,c)}),b.defineNodeNameProperty("textarea","maxlength",{attr:{set:function(a){this.setAttribute("maxlength",""+a),k.update(this)},get:function(){var a=this.getAttribute("maxlength");return null==a?e:a}},prop:{set:function(a){if(g(a)){if(0>a)throw"INDEX_SIZE_ERR";return a=parseInt(a,10),this.setAttribute("maxlength",a),void k.update(this,a)}this.setAttribute("maxlength","0"),k.update(this,0)},get:function(){var a=this.getAttribute("maxlength");return g(a)&&a>=0?parseInt(a,10):-1}}}),b.defineNodeNameProperty("textarea","maxLength",{prop:{set:function(b){a.prop(this,"maxlength",b)},get:function(){return a.prop(this,"maxlength")}}})}h||null!=a("<form novalidate></form>").attr("novalidate")||b.defineNodeNameProperty("form","novalidate",{attr:{set:function(a){this.setAttribute("novalidate",""+a)},get:function(){var a=this.getAttribute("novalidate");return null==a?e:a}}}),Modernizr.formattribute&&Modernizr.fieldsetdisabled&&Modernizr.fieldsetelements||!function(){if(!Modernizr.fieldsetdisabled){var f={fieldset:1,FIELDSET:1},g="input, textarea, select, button";a.extend(a.expr[":"],{enabled:function(c){return c.disabled===!1||f[c.nodeName]&&null==b.contentAttr(c,"disabled")&&!a(c).is("fieldset[disabled] *")},disabled:function(c){return c.disabled===!0||f[c.nodeName]&&(null!=b.contentAttr(c,"disabled")||a(c).is("fieldset[disabled] *"))}});var h={disable:function(){this.disabled||(b.data(this,"groupedisabled",!0),this.disabled=!0)},enable:function(){this.disabled&&b.data(this,"groupedisabled")&&(b.data(this,"groupedisabled",!1),this.disabled=!1)}};a(c).on("unload",function(){a(g).each(h.enable)}),b.defineNodeNamesBooleanProperty(["fieldset"],"disabled",{set:function(b){if(b=!!b)a(g,this).each(h.disable);else if(!a(this).is("fieldset[disabled] *")){var c=a(this.querySelectorAll(g));this.querySelector("fieldset[disabled]")&&(c=c.not("fieldset[disabled] *")),c.each(h.enable)}},initAttr:!0,useContentAttribute:!0}),["input","textarea","select","button"].forEach(function(c){var d=b.defineNodeNameProperty(c,"disabled",{prop:{set:function(c){c?(b.data(this,"groupedisabled",!1),d.prop._supset.call(this,c)):a(this).is("fieldset[disabled] *")?(b.data(this,"groupedisabled",!0),d.prop._supset.call(this,!0)):(b.data(this,"groupedisabled",!1),d.prop._supset.call(this,c))},get:function(){var a=d.prop._supget.call(this);return a?!b.data(this,"groupedisabled"):a}},removeAttr:{value:function(){d.prop.set.call(this,!1)}}})}),b.addReady(function(b){a(b).filter("fieldset[disabled], fieldset[disabled] *").find(g).each(h.disable)})}if(!Modernizr.formattribute){!function(b,c){var e={form:1,FORM:1};a.prop=function(f,g,h){var i;return f&&1==f.nodeType&&h===c&&e[f.nodeName]&&f.id&&(i=d.getElementsByName(g),i&&i.length||(i=d.getElementById(g)),i&&(i=a(i).filter(function(){return a.prop(this,"form")==f}).get(),i.length))?1==i.length?i[0]:i:b.apply(this,arguments)}}(a.prop,e);var i=function(b){var c=a.data(b,"webshimsAddedElements");c&&(c.remove(),a.removeData(b,"webshimsAddedElements"))};if(b.defineNodeNamesProperty(["input","textarea","select","button","fieldset"],"form",{prop:{get:function(){var c=b.contentAttr(this,"form");return c&&(c=d.getElementById(c),c&&!a.nodeName(c,"form")&&(c=null)),c||this.form},writeable:!1}}),b.defineNodeNamesProperty(["form"],"elements",{prop:{get:function(){var b,c,e,f=this.id,g=a.makeArray(this.elements);return f&&(e=a.data(this,"webshimsAddedElements"),e&&e.detach(),b='input[form="'+f+'"], select[form="'+f+'"], textarea[form="'+f+'"], button[form="'+f+'"], fieldset[form="'+f+'"]',c=d.querySelectorAll(b)||[],c.length&&(g=a(g).add(c).get()),e&&e.appendTo(this)),g},writeable:!1}}),a(function(){var c=function(a){a.stopPropagation()},e={image:1,submit:1};a(d).on("submit",function(b){if(!b.isDefaultPrevented()){var c,e=b.target,f=e.id;f&&(i(e),c=d.querySelectorAll('input[form="'+f+'"], select[form="'+f+'"], textarea[form="'+f+'"]'),c=a(c).filter(function(){return!this.disabled&&this.name&&this.form!=e}).clone(),c.length&&(a.data(e,"webshimsAddedElements",a('<div class="webshims-visual-hide" />').append(c).appendTo(e)),setTimeout(function(){i(e)},9)),c=null)}}),a(d).on("click",function(d){if(e[d.target.type]&&!d.isDefaultPrevented()&&b.contentAttr(d.target,"form")){var f,g=a.prop(d.target,"form"),h=d.target.form;g&&g!=h&&(f=a(d.target).clone().removeAttr("form").addClass("webshims-visual-hide").on("click",c).appendTo(g),h&&d.preventDefault(),j(g),f.trigger("click"),setTimeout(function(){f.remove(),f=null},9))}})}),!a.fn.finish&&parseFloat(a.fn.jquery,10)<1.9){var k=/\r?\n/g,l=/^(?:color|date|datetime|datetime-local|email|hidden|month|number|password|range|search|tel|text|time|url|week)$/i,m=/^(?:select|textarea)/i;a.fn.serializeArray=function(){return this.map(function(){var b=a.prop(this,"elements");return b?a.makeArray(b):this}).filter(function(){return this.name&&!a(this).is(":disabled")&&(this.checked||m.test(this.nodeName)||l.test(this.type))}).map(function(b,c){var d=a(this).val();return null==d?null:a.isArray(d)?a.map(d,function(a){return{name:c.name,value:a.replace(k,"\r\n")}}):{name:c.name,value:d.replace(k,"\r\n")}}).get()}}}Modernizr.fieldsetelements||b.defineNodeNamesProperty(["fieldset"],"elements",{prop:{get:function(){return this.querySelectorAll("input, select, textarea, button, fieldset")||[]},writeable:!1}})}(),null==a("<input />").prop("labels")&&b.defineNodeNamesProperty("button, input, keygen, meter, output, progress, select, textarea","labels",{prop:{get:function(){if("hidden"==this.type)return null;var b=this.id,c=a(this).closest("label").filter(function(){var a=this.attributes["for"]||{};return!a.specified||a.value==b});return b&&(c=c.add(d.querySelectorAll('label[for="'+b+'"]'))),c.get()},writeable:!1}}),"value"in d.createElement("progress")||!function(){var c=parseInt("NaN",10),d=function(b){var c=a.prop(b,"position");a.attr(b,"data-position",c),a("> span",b).css({width:(0>c?100:100*c)+"%"})},e={position:{prop:{get:function(){var b,e=this.getAttribute("value"),f=-1;return e=e?1*e:c,isNaN(e)?d.isInChange&&a(this).removeAttr("aria-valuenow").addClass("ws-indeterminate"):(b=a.prop(this,"max"),f=Math.max(Math.min(e/b,1),0),d.isInChange&&(a.attr(this,"aria-valuenow",100*f),"max"==d.isInChange&&a.attr(this,"aria-valuemax",b)),a(this).removeClass("ws-indeterminate")),f},writeable:!1}}};a.each({value:0,max:1},function(c,f){var g="value"==c&&!a.fn.finish;e[c]={attr:{set:function(a){var b=e[c].attr._supset.call(this,a);return d.isInChange=c,d(this),d.isInChange=!1,b}},removeAttr:{value:function(){if(this.removeAttribute(c),g)try{delete this.value}catch(a){}d.isInChange=c,d(this),d.isInChange=!1}},prop:{get:function(){var b=1*e[c].attr.get.call(this);return 0>b||isNaN(b)?b=f:"value"==c?b=Math.min(b,a.prop(this,"max")):0===b&&(b=f),b},set:function(a){return a=1*a,isNaN(a)&&b.error("Floating-point value is not finite."),e[c].attr.set.call(this,a)}}}}),b.createElement("progress",function(){var c=a(this).attr({role:"progressbar","aria-valuemin":"0"}).html('<span class="progress-value" />').jProp("labels").map(function(){return b.getID(this)}).get();c.length?a.attr(this,"aria-labelledby",c.join(" ")):b.info("you should use label elements for your prgogress elements"),"rtl"==a(this).css("direction")&&a(this).addClass("ws-is-rtl"),d.isInChange="max",d(this),d.isInChange=!1},e)}(),"setSelectionRange"in d.createElement("input")||!function(){var c=function(b,c){var e,f,g,h,i,j,k=0,l=0;return d.selection&&(e=d.selection.createRange())&&e.parentElement()==b&&(f=a.prop(b,"value"),i=f.length,g=f.replace(/\r\n/g,"\n"),h=b.createTextRange(),h.moveToBookmark(e.getBookmark()),j=b.createTextRange(),j.collapse(!1),h.compareEndPoints("StartToEnd",j)>-1?k=l=i:c?(k=-h.moveStart("character",-i),k+=g.slice(0,k).split("\n").length-1):h.compareEndPoints("EndToEnd",j)>-1?l=i:(l=-h.moveEnd("character",-i),l+=g.slice(0,l).split("\n").length-1)),{start:k,end:l}};["input","textarea"].forEach(function(d){var e="textarea"==d,f={text:1,search:1,url:1,tel:1,password:1,email:1},g="InvalidStateError: An attempt was made to use an object that is not, or is no longer, usable. selection not allowed on this type";b.defineNodeNameProperties(d,{selectionStart:{get:function(){return e||f[a.prop(this,"type")]?c(this,!0).start:void b.error(g)},set:function(c){if(this.createTextRange&&(e||f[a.prop(this,"type")])){var d=this.createTextRange();d.collapse(!0),d.moveStart("character",c),d.moveEnd("character",a.prop(this,"selectionEnd")),a(this).is(":focus")&&d.select()}else b.error(g)}},selectionEnd:{get:function(){return e||f[a.prop(this,"type")]?c(this).end:void b.error(g)},set:function(d){if(this.createTextRange&&(e||f[a.prop(this,"type")])){var h,i=this.createTextRange();i.collapse(!0),h=c(this,!0).start,i.moveStart("character",h),i.moveEnd("character",d-h),a(this).is(":focus")&&i.select()}else b.error(g)}},setSelectionRange:{value:function(c,d){if(this.createTextRange&&(e||f[a.prop(this,"type")])){var h=this.createTextRange();h.collapse(!0),h.moveStart("character",c),h.moveEnd("character",d-c),a(this).is(":focus")&&h.select()}else b.error(g)}}},"prop")})}(),function(){if(!f.noPlaceholderPolyfill){var d;if(Modernizr.textareaPlaceholder=!!("placeholder"in a("<textarea />")[0]),Modernizr.input.placeholder&&f.overridePlaceholder&&(d=!0),Modernizr.input.placeholder&&Modernizr.textareaPlaceholder&&!d)return void function(){var b=navigator.userAgent;-1!=b.indexOf("Mobile")&&-1!=b.indexOf("Safari")&&a(c).on("orientationchange",function(){var b,c=function(a,b){return b},d=function(){a("input[placeholder], textarea[placeholder]").attr("placeholder",c)};return function(){clearTimeout(b),b=setTimeout(d,9)}}())}();var e="over"==b.cfg.forms.placeholderType,g=b.cfg.forms.responsivePlaceholder,h=["textarea"];(!Modernizr.input.placeholder||d)&&h.push("input");var i=function(b){try{return a(b).setSelectionRange(0,0),!0}catch(c){}},j=function(b,c,d,f){if(d===!1&&(d=a.prop(b,"value")),e||"password"==b.type){if(!d&&f)return void a(b).off(".placeholderremove").on({"keydown.placeholderremove keypress.placeholderremove paste.placeholderremove input.placeholderremove":function(d){(!d||17!=d.keyCode&&16!=d.keyCode)&&(c.box.removeClass("placeholder-visible"),a(b).off(".placeholderremove"))},"blur.placeholderremove":function(){a(b).off(".placeholderremove")}})}else{if(!d&&f&&i(b)){var g=setTimeout(function(){i(b)},9);return void a(b).off(".placeholderremove").on({"keydown.placeholderremove keypress.placeholderremove paste.placeholderremove input.placeholderremove":function(d){(!d||17!=d.keyCode&&16!=d.keyCode)&&(b.value=a.prop(b,"value"),c.box.removeClass("placeholder-visible"),clearTimeout(g),a(b).off(".placeholderremove"))},"mousedown.placeholderremove drag.placeholderremove select.placeholderremove":function(){i(b),clearTimeout(g),g=setTimeout(function(){i(b)},9)},"blur.placeholderremove":function(){clearTimeout(g),a(b).off(".placeholderremove")}})}f||d||!b.value||(b.value=d)}c.box.removeClass("placeholder-visible")},k=function(b,c,d){d===!1&&(d=a.prop(b,"placeholder")),e||"password"==b.type||(b.value=d),c.box.addClass("placeholder-visible")},l=function(b,c,d,f,g){if(f||(f=a.data(b,"placeHolder"))){var h=a(b).hasClass("placeholder-visible");return d===!1&&(d=a.attr(b,"placeholder")||""),a(b).off(".placeholderremove"),c===!1&&(c=a.prop(b,"value")),c||"focus"!=g&&(g||!a(b).is(":focus"))?c?void j(b,f,c):void(d&&!c?k(b,f,d):j(b,f,c)):void(("password"==b.type||e||h)&&j(b,f,"",!0))}},m=function(){return a('<span class="placeholder-text"></span>')},n=function(){var d={text:1,search:1,url:1,email:1,password:1,tel:1,number:1};return b.modules["form-number-date-ui"].loaded&&delete d.number,{create:function(b){var d,f=a.data(b,"placeHolder");if(f)return f;if(f=a.data(b,"placeHolder",{}),a(b).on("focus.placeholder blur.placeholder",function(a){l(this,!1,!1,f,a.type),f.box["focus"==a.type?"addClass":"removeClass"]("placeholder-focused")}),(d=a.prop(b,"form"))&&a(b).onWSOff("reset.placeholder",function(a){setTimeout(function(){l(b,!1,!1,f,a.type)},0)},!1,d),"password"==b.type||e)f.text=m(b),g||a(b).is(".responsive-width")||-1!=(b.currentStyle||{width:""}).width.indexOf("%")?f.box=f.text:(f.box=a('<span class="placeholder-box placeholder-box-'+(b.nodeName||"").toLowerCase()+" placeholder-box-"+a.css(b,"float")+'" />').insertAfter(b),f.box.append(b)),f.text.insertAfter(b).on("mousedown.placeholder",function(){l(this,!1,!1,f,"focus");try{setTimeout(function(){b.focus()},0)}catch(a){}return!1}),a.each(["lineHeight","fontSize","fontFamily","fontWeight"],function(c,d){var e=a.css(b,d);f.text.css(d)!=e&&f.text.css(d,e)}),a.each(["Left","Top"],function(c,d){var e=(parseInt(a.css(b,"padding"+d),10)||0)+Math.max(parseInt(a.css(b,"margin"+d),10)||0,0)+(parseInt(a.css(b,"border"+d+"Width"),10)||0);f.text.css("padding"+d,e)}),a(b).onWSOff("updateshadowdom",function(){var c,d,e,g=a(b),h={};return function(){var a,i;(a=b.offsetWidth)&&(i=function(){var b=g.position();a!==c&&(c=a,f.text[0].style.width=a+"px"),(b.top!==h.top||b.left!==h.left)&&(h=b,f.text[0].style.top=b.top+"px",f.text[0].style.left=b.left+"px")},d?(clearTimeout(e),e=setTimeout(i,99)):(i(),d=!0))}}(),!0);else{var h=function(c){a(b).hasClass("placeholder-visible")&&(j(b,f,""),setTimeout(function(){(!c||"submit"!=c.type||c.isDefaultPrevented())&&l(b,!1,!1,f)},9))};a(b).onWSOff("beforeunload",h,!1,c),f.box=a(b),d&&a(b).onWSOff("submit",h,!1,d)}return f},update:function(c,e){var f=(a.attr(c,"type")||a.prop(c,"type")||"").toLowerCase();if(!d[f]&&!a.nodeName(c,"textarea"))return void b.warn('placeholder not allowed on input[type="'+f+'"], but it is a good fallback :-)');var g=n.create(c);g.text&&g.text.text(e),l(c,!1,e,g)}}}();a.webshims.publicMethods={pHolder:n},h.forEach(function(a){b.defineNodeNameProperty(a,"placeholder",{attr:{set:function(a){var c=this;d?(b.data(c,"bustedPlaceholder",a),c.placeholder=""):b.contentAttr(c,"placeholder",a),n.update(c,a)},get:function(){var a;return d&&(a=b.data(this,"bustedPlaceholder")),a||b.contentAttr(this,"placeholder")}},reflect:!0,initAttr:!0})}),h.forEach(function(c){var e,f={};["attr","prop"].forEach(function(c){f[c]={set:function(f){var g,h=this;d&&(g=b.data(h,"bustedPlaceholder")),g||(g=b.contentAttr(h,"placeholder")),a.removeData(h,"cachedValidity");var i=e[c]._supset.call(h,f);return g&&"value"in h&&l(h,f,g),i},get:function(){var b=this;return a(b).hasClass("placeholder-visible")?"":e[c]._supget.call(b)}}}),e=b.defineNodeNameProperty(c,"value",f)})}}(),function(){var c=d;if(!("value"in d.createElement("output"))){b.defineNodeNameProperty("output","value",{prop:{set:function(b){var c=a.data(this,"outputShim");c||(c=e(this)),c(b)},get:function(){return b.contentAttr(this,"value")||a(this).text()||""}}}),b.onNodeNamesPropertyModify("input","value",function(b,c,d){if("removeAttr"!=d){var e=a.data(this,"outputShim");e&&e(b)}});var e=function(c){if(!a.data(c,"outputShim")){c=a(c);var e=(c.text()||"").trim(),f=c.prop("id"),g=c.attr("for"),h=a('<input class="output-shim" type="text" disabled name="'+(c.attr("name")||"")+'" value="'+e+'" style="display: none !important;" />').insertAfter(c),i=function(a){h[0].value=a,a=h[0].value,c.text(a),b.contentAttr(c[0],"value",a)};return c[0].defaultValue=e,b.contentAttr(c[0],"value",e),c.attr({"aria-live":"polite"}),f&&(h.attr("id",f),c.attr("aria-labelledby",c.jProp("labels").map(function(){return b.getID(this)}).get().join(" "))),g&&(f=b.getID(c),g.split(" ").forEach(function(a){a=d.getElementById(a),a&&a.setAttribute("aria-controls",f)})),c.data("outputShim",i),h.data("outputShim",i),i}};b.addReady(function(b,c){a(b.getElementsByTagName("output")).add(c.filter("output")).each(function(){e(this)})}),function(){var d,e,f,g,h={updateInput:1,input:1},i={radio:1,checkbox:1,submit:1,button:1,image:1,reset:1,file:1,color:1},j=function(a){if(f){var c=f.prop("value");c!==e&&(e=c,a&&h[a.type]||b.triggerInlineForm&&b.triggerInlineForm(f[0],"input"))}},k=function(){clearTimeout(g),g=setTimeout(j,9)},l=function(){clearTimeout(g),clearInterval(d),f&&f.off("focusout",l).off("keyup keypress keydown paste cut",k).off("input change updateInput triggerinput",j)},m=function(a){l(),f=a,e=f.prop("value"),clearInterval(d),d=setInterval(j,200),k(),f.on({"keyup keypress keydown paste cut":k,"focusout wswidgetfocusout":l,"input updateInput change triggerinput":j})};a(c).on("focusin wswidgetfocusin",function(c){!c.target||c.target.readOnly||c.target.disabled||"input"!=(c.target.nodeName||"").toLowerCase()||i[c.target.type]||(b.data(c.target,"implemented")||{}).inputwidgets||m(a(c.target))})}()}}()});
dryajov/cdnjs
ajax/libs/webshim/1.12.6/minified/shims/form-shim-extend2.js
JavaScript
mit
17,994
webshims.register("form-validators",function(a,b,c,d,e,f){"use strict";var g="."+f.iVal.errorClass+", ."+f.iVal.successClass;!function(){b.refreshCustomValidityRules&&b.error("form-validators already included. please remove custom-validity.js");var c,e,f={},g=!1,h="input, select, textarea, fieldset[data-dependent-validation]",i=function(a){b.refreshCustomValidityRules(a.target)},j=function(){return!j.types[this.type]};j.types={hidden:1,image:1,button:1,reset:1,submit:1},b.customErrorMessages={},b.addCustomValidityRule=function(){var c,e=function(){a(d.querySelectorAll(h)).filter(j).each(function(){k(this)})};return function(a,d,h){f[a]=d,b.customErrorMessages[a]||(b.customErrorMessages[a]=[],b.customErrorMessages[a][""]=h||a),g&&(clearTimeout(c),c=setTimeout(e))}}(),b.refreshCustomValidityRules=function(d){if(e){var g,h,i=a(d).data(),j="",k=i&&i.customMismatchedRule,l=i&&a.prop(d,"validity")||{valid:1};return i&&(k||l.valid)&&(h=function(e,f){c=!0,e?(i.customMismatchedRule=f,"string"!=typeof e&&(e=b.getContentValidationMessage(d,!1,f),e&&"object"==typeof e&&(e=e[f]),e&&"string"==typeof e||(e=b.customErrorMessages[f][b.activeLang()]||b.customErrorMessages[f][""]||e.customError||e.defaultMessage||""))):(e="",i.customMismatchedRule=""),a(d).setCustomValidity(e),c=!1},g=a(d).val(),a.each(f,function(a,b){return j=b(d,g,i,h)||"",k=a,j?!1:void 0}),i&&i.dependentValidation&&!i.dependentValidation._init&&!i.dependentValidation.masterElement&&f.dependent(d,g,i,a.noop),"async"==j||!j&&l.valid||h(j,k)),j}};var k=b.refreshCustomValidityRules;"unknown"!=typeof d.activeElement&&a("body").on("click",function(b){if("submit"==b.target.type){var c=d.activeElement;c!=b.target&&a.data(c,"webshimsswitchvalidityclass")&&a(c).trigger("updatevalidation.webshims")}}),b.ready("forms form-validation",function(){a.propHooks.setCustomValidity={get:function(b){return c||a.data(b,"customMismatchedRule",""),null}},setTimeout(function(){b.addReady(function(b,c){e=!0,a(b.querySelectorAll(h)).add(c.filter(h)).filter(j).each(function(){k(this)}),g=!0}),a(d).on("refreshCustomValidityRules",i)},29)})}(),function(){var e=b.cfg.forms,h=b.addCustomValidityRule,i=function(a){return d.getElementById(a)||d.getElementsByName(a)};h("partialPattern",function(a,b,c){return c=c.partialPattern,b&&c?!new RegExp("("+c+")","i").test(b):void 0},"This format is not allowed here."),h("tooShort",function(c,d,e){return d&&e.minlength?(a.nodeName(c,"input")&&b.warn('depreacated data-minlength usage: Use pattern=".{'+e.minlength+',}" instead.'),e.minlength>d.length):void 0},"Entered value is too short."),h("grouprequired",function(c,e,f){var g,h=c.name;return h&&"checkbox"===c.type&&"grouprequired"in f?(f.grouprequired&&f.grouprequired.checkboxes||(f.grouprequired.checkboxes=a((g=a.prop(c,"form"))&&g[h]||d.getElementsByName(h)).filter('[type="checkbox"]'),f.grouprequired.checkboxes.off("click.groupRequired").on("click.groupRequired",function(){b.refreshCustomValidityRules(c)}),f.grouprequired.checkboxes.not(c).removeData("grouprequired")),!f.grouprequired.checkboxes.filter(":checked:enabled")[0]):void 0},"Please check one of these checkboxes."),h("creditcard",function(a,b,c){if(b&&c&&"creditcard"in c){if(b=b.replace(/\-/g,""),b!=1*b)return!0;for(var d,e=b.length,f=0,g=1;e--;)d=parseInt(b.charAt(e),10)*g,f+=d-9*(d>9),g^=3;return!(f%10===0&&f>0)}},"Please enter a valid credit card number");var j={prop:"value","from-prop":"value",toggle:!1},k=function(b){return a(b.form[b.name]).filter('[type="radio"]')};b.ready("form-validation",function(){b.modules&&(k=b.modules["form-core"].getGroupElements||k)}),h("dependent",function(c,e,f){if(f=f.dependentValidation){var h,i=function(b){var d=a.prop(f.masterElement,f["from-prop"]);h&&(d=-1!==a.inArray(d,h)),f.toggle&&(d=!d),a.prop(c,f.prop,d),b&&a(c).getShadowElement().filter(g).trigger("updatevalidation.webshims")};if(!f._init||!f.masterElement){if("string"==typeof f&&(f={from:f}),f.masterElement=d.getElementById(f.from)||d.getElementsByName(f.from||[])[0],f._init=!0,!f.masterElement||!f.masterElement.form)return;/radio|checkbox/i.test(f.masterElement.type)?(f["from-prop"]||(f["from-prop"]="checked"),f.prop||"checked"!=f["from-prop"]||(f.prop="disabled")):f["from-prop"]||(f["from-prop"]="value"),0===f["from-prop"].indexOf("value:")&&(h=f["from-prop"].replace("value:","").split("||"),f["from-prop"]="value"),f=a.data(c,"dependentValidation",a.extend({_init:!0},j,f)),"value"!==f.prop||h?a("radio"===f.masterElement.type&&k(f.masterElement)||f.masterElement).on("change",i):a(f.masterElement).on("change",function(){b.refreshCustomValidityRules(c),a(c).getShadowElement().filter(g).trigger("updatevalidation.webshims")})}return"value"!=f.prop||h?(i(),""):a.prop(f.masterElement,"value")!=e}},"The value of this field does not repeat the value of the other field"),h("valuevalidation",function(b,c,d){return c&&"valuevalidation"in d?a(b).triggerHandler("valuevalidation",[{value:c,valueAsDate:a.prop(b,"valueAsDate"),isPartial:!1}])||"":void 0},"This value is not allowed here"),c.JSON&&h("ajaxvalidate",function(c,d,g){if(d&&g.ajaxvalidate){var h;if(!g.remoteValidate){b.loader.loadList(["jajax"]),"string"==typeof g.ajaxvalidate?g.ajaxvalidate={url:g.ajaxvalidate,depends:a([])}:g.ajaxvalidate.depends=g.ajaxvalidate.depends?a("string"==typeof g.ajaxvalidate.depends&&g.ajaxvalidate.depends.split(" ")||g.ajaxvalidate.depends).map(i):a([]),g.ajaxvalidate.depends.on("refreshCustomValidityRules",function(){b.refreshCustomValidityRules(c)}),h=g.ajaxvalidate;var j={ajaxLoading:!1,restartAjax:!1,message:"async",cache:{},update:function(b){this.ajaxLoading?this.restartAjax=b:(this.restartAjax=!1,this.ajaxLoading=!0,a.ajax(a.extend({dataType:"json"},h,{url:h.url,depData:b,data:e.fullRemoteForm||h.fullForm?a(c).jProp("form").serializeArray():b,success:this.getResponse,complete:this._complete,timeout:3e3})))},_complete:function(){j.ajaxLoading=!1,j.restartAjax&&this.update(j.restartAjax),j.restartAjax=!1},getResponse:function(b){if(f.transformAjaxValidate&&(b=f.transformAjaxValidate(b)),b){if("string"==typeof b)try{b=JSON.parse(b)}catch(d){}}else b={message:"",valid:!0};j.message="message"in b?b.message:!b.valid,j.lastMessage=j.message,j.blockUpdate=!0,a(c).triggerHandler("updatevalidation.webshims"),j.message="async",j.blockUpdate=!1},getData:function(){var b;return b={},b[a.prop(c,"name")||a.prop(c,"id")]=a(c).val(),h.depends.each(function(){return a(this).is(":invalid")?(b=!1,!1):void(b[a.prop(this,"name")||a.prop(this,"id")]=a(this).val())}),b},getTempMessage:function(){var a,b,c="async";if(g.remoteValidate.blockUpdate)c=j.message;else if(a=this.getData()){try{b=JSON.stringify(a)}catch(d){}b===this.lastString?c=this.ajaxLoading?"async":this.lastMessage:(this.lastString=b,this.lastMessage="async",clearTimeout(g.remoteValidate.timer),g.remoteValidate.timer=setTimeout(function(){g.remoteValidate.update(a)},9))}else c="";return c}};g.remoteValidate=j}return g.remoteValidate.getTempMessage()}},"remote error")}()});
TerryMooreII/cdnjs
ajax/libs/webshim/1.12.7/minified/shims/form-validators.js
JavaScript
mit
6,993
<!doctype html> <title>CodeMirror: HTTP mode</title> <meta charset="utf-8"/> <link rel=stylesheet href="../../doc/docs.css"> <link rel="stylesheet" href="../../lib/codemirror.css"> <script src="../../lib/codemirror.js"></script> <script src="http.js"></script> <style type="text/css">.CodeMirror {border-top: 1px solid black; border-bottom: 1px solid black;}</style> <div id=nav> <a href="http://codemirror.net"><h1>CodeMirror</h1><img id=logo src="../../doc/logo.png"></a> <ul> <li><a href="../../index.html">Home</a> <li><a href="../../doc/manual.html">Manual</a> <li><a href="https://github.com/codemirror/codemirror">Code</a> </ul> <ul> <li><a href="../index.html">Language modes</a> <li><a class=active href="#">HTTP</a> </ul> </div> <article> <h2>HTTP mode</h2> <div><textarea id="code" name="code"> POST /somewhere HTTP/1.1 Host: example.com If-Modified-Since: Sat, 29 Oct 1994 19:43:31 GMT Content-Type: application/x-www-form-urlencoded; charset=utf-8 User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/536.11 (KHTML, like Gecko) Ubuntu/12.04 Chromium/20.0.1132.47 Chrome/20.0.1132.47 Safari/536.11 This is the request body! </textarea></div> <script> var editor = CodeMirror.fromTextArea(document.getElementById("code"), {}); </script> <p><strong>MIME types defined:</strong> <code>message/http</code>.</p> </article>
davidpham87/CodeMirror
mode/http/index.html
HTML
mit
1,393
// moment.js language configuration // language : korean (kr) // author : Kyungwook, Park : https://github.com/kyungw00k // This language config was incorrectly named 'kr' instead of 'ko'. // In version 2.0.0, this will be deprecated and you should use 'ko' instead. (function () { var lang = { months : "1월_2월_3월_4월_5월_6월_7월_8월_9월_10월_11월_12월".split("_"), monthsShort : "1월_2월_3월_4월_5월_6월_7월_8월_9월_10월_11월_12월".split("_"), weekdays : "일요일_월요일_화요일_수요일_목요일_금요일_토요일".split("_"), weekdaysShort : "일_월_화_수_목_금_토".split("_"), weekdaysMin : "일_월_화_수_목_금_토".split("_"), longDateFormat : { LT : "A h시 mm분", L : "YYYY.MM.DD", LL : "YYYY년 MMMM D일", LLL : "YYYY년 MMMM D일 LT", LLLL : "YYYY년 MMMM D일 dddd LT" }, meridiem : function (hour, minute, isUpper) { return hour < 12 ? '오전' : '오후'; }, calendar : { sameDay : '오늘 LT', nextDay : '내일 LT', nextWeek : 'dddd LT', lastDay : '어제 LT', lastWeek : '지난주 dddd LT', sameElse : 'L' }, relativeTime : { future : "%s 후", past : "%s 전", s : "몇초", ss : "%d초", m : "일분", mm : "%d분", h : "한시간", hh : "%d시간", d : "하루", dd : "%d일", M : "한달", MM : "%d달", y : "일년", yy : "%d년" }, ordinal : function (number) { return '일'; } }; // Node if (typeof module !== 'undefined' && module.exports) { module.exports = lang; } // Browser if (typeof window !== 'undefined' && this.moment && this.moment.lang) { this.moment.lang('kr', lang); } }());
sahat/cdnjs
ajax/libs/moment.js/1.7.0/lang/kr.js
JavaScript
mit
2,229
.mm-menu.mm-bottom,.mm-menu.mm-top{width:100%;min-width:100%;max-width:100%}.mm-menu.mm-right{left:auto;right:0}.mm-menu.mm-bottom{top:auto;bottom:0}html.mm-right.mm-opening .mm-slideout{-webkit-transform:translate(-80%,0);-moz-transform:translate(-80%,0);-ms-transform:translate(-80%,0);-o-transform:translate(-80%,0);transform:translate(-80%,0)}@media all and (max-width:175px){html.mm-right.mm-opening .mm-slideout{-webkit-transform:translate(-140px,0);-moz-transform:translate(-140px,0);-ms-transform:translate(-140px,0);-o-transform:translate(-140px,0);transform:translate(-140px,0)}}@media all and (min-width:550px){html.mm-right.mm-opening .mm-slideout{-webkit-transform:translate(-440px,0);-moz-transform:translate(-440px,0);-ms-transform:translate(-440px,0);-o-transform:translate(-440px,0);transform:translate(-440px,0)}}html.mm-front .mm-slideout{-webkit-transform:none!important;-moz-transform:none!important;-ms-transform:none!important;-o-transform:none!important;transform:none!important;z-index:0!important}.mm-menu.mm-front{z-index:1;box-shadow:0 0 15px rgba(0,0,0,.5)}html.mm-opened.mm-next .mm-page{box-shadow:none}.mm-menu.mm-front,.mm-menu.mm-next{-webkit-transition:-webkit-transform .4s ease;-ms-transition:-ms-transform .4s ease;transition:transform .4s ease;-webkit-transform:translate(-100%,0);-moz-transform:translate(-100%,0);-ms-transform:translate(-100%,0);-o-transform:translate(-100%,0);transform:translate(-100%,0)}.mm-menu.mm-front.mm-right,.mm-menu.mm-next.mm-right{-webkit-transform:translate(100%,0);-moz-transform:translate(100%,0);-ms-transform:translate(100%,0);-o-transform:translate(100%,0);transform:translate(100%,0)}.mm-menu.mm-front.mm-top{-webkit-transform:translate(0,-100%);-moz-transform:translate(0,-100%);-ms-transform:translate(0,-100%);-o-transform:translate(0,-100%);transform:translate(0,-100%)}.mm-menu.mm-front.mm-bottom{-webkit-transform:translate(0,100%);-moz-transform:translate(0,100%);-ms-transform:translate(0,100%);-o-transform:translate(0,100%);transform:translate(0,100%)}html.mm-opening .mm-menu.mm-front,html.mm-opening .mm-menu.mm-next{-webkit-transform:translate(0,0);-moz-transform:translate(0,0);-ms-transform:translate(0,0);-o-transform:translate(0,0);transform:translate(0,0)}.mm-menu.mm-front.mm-bottom,.mm-menu.mm-front.mm-top{height:80%;min-height:140px;max-height:880px}
taydakov/cdnjs
ajax/libs/jQuery.mmenu/4.7.0/css/extensions/jquery.mmenu.positioning.min.css
CSS
mit
2,349
.tether-element, .tether-element:after, .tether-element:before, .tether-element *, .tether-element *:after, .tether-element *:before { -webkit-box-sizing: border-box; -moz-box-sizing: border-box; box-sizing: border-box; } .tether-element { position: absolute; display: none; } .tether-element.tether-open { display: block; } .tether-element.tether-theme-arrows { max-width: 100%; max-height: 100%; } .tether-element.tether-theme-arrows .tether-content { -webkit-border-radius: 5px; -moz-border-radius: 5px; -ms-border-radius: 5px; -o-border-radius: 5px; border-radius: 5px; position: relative; font-family: inherit; background: white; color: inherit; padding: 1em; font-size: 1.1em; line-height: 1.5em; -webkit-filter: drop-shadow(0 1px 4px rgba(0, 0, 0, 0.2)); -webkit-transform: translateZ(0); } .tether-element.tether-theme-arrows .tether-content:before { content: ""; display: block; position: absolute; width: 0; height: 0; border-color: transparent; border-width: 16px; border-style: solid; } .tether-element.tether-theme-arrows.tether-element-attached-bottom.tether-element-attached-center .tether-content { margin-bottom: 16px; } .tether-element.tether-theme-arrows.tether-element-attached-bottom.tether-element-attached-center .tether-content:before { top: 100%; left: 50%; margin-left: -16px; border-top-color: white; } .tether-element.tether-theme-arrows.tether-element-attached-top.tether-element-attached-center .tether-content { margin-top: 16px; } .tether-element.tether-theme-arrows.tether-element-attached-top.tether-element-attached-center .tether-content:before { bottom: 100%; left: 50%; margin-left: -16px; border-bottom-color: white; } .tether-element.tether-theme-arrows.tether-element-attached-right.tether-element-attached-middle .tether-content { margin-right: 16px; } .tether-element.tether-theme-arrows.tether-element-attached-right.tether-element-attached-middle .tether-content:before { left: 100%; top: 50%; margin-top: -16px; border-left-color: white; } .tether-element.tether-theme-arrows.tether-element-attached-left.tether-element-attached-middle .tether-content { margin-left: 16px; } .tether-element.tether-theme-arrows.tether-element-attached-left.tether-element-attached-middle .tether-content:before { right: 100%; top: 50%; margin-top: -16px; border-right-color: white; } .tether-element.tether-theme-arrows.tether-element-attached-top.tether-element-attached-left.tether-target-attached-bottom .tether-content { margin-top: 16px; } .tether-element.tether-theme-arrows.tether-element-attached-top.tether-element-attached-left.tether-target-attached-bottom .tether-content:before { bottom: 100%; left: 16px; border-bottom-color: white; } .tether-element.tether-theme-arrows.tether-element-attached-top.tether-element-attached-right.tether-target-attached-bottom .tether-content { margin-top: 16px; } .tether-element.tether-theme-arrows.tether-element-attached-top.tether-element-attached-right.tether-target-attached-bottom .tether-content:before { bottom: 100%; right: 16px; border-bottom-color: white; } .tether-element.tether-theme-arrows.tether-element-attached-bottom.tether-element-attached-left.tether-target-attached-top .tether-content { margin-bottom: 16px; } .tether-element.tether-theme-arrows.tether-element-attached-bottom.tether-element-attached-left.tether-target-attached-top .tether-content:before { top: 100%; left: 16px; border-top-color: white; } .tether-element.tether-theme-arrows.tether-element-attached-bottom.tether-element-attached-right.tether-target-attached-top .tether-content { margin-bottom: 16px; } .tether-element.tether-theme-arrows.tether-element-attached-bottom.tether-element-attached-right.tether-target-attached-top .tether-content:before { top: 100%; right: 16px; border-top-color: white; } .tether-element.tether-theme-arrows.tether-element-attached-top.tether-element-attached-right.tether-target-attached-left .tether-content { margin-right: 16px; } .tether-element.tether-theme-arrows.tether-element-attached-top.tether-element-attached-right.tether-target-attached-left .tether-content:before { top: 16px; left: 100%; border-left-color: white; } .tether-element.tether-theme-arrows.tether-element-attached-top.tether-element-attached-left.tether-target-attached-right .tether-content { margin-left: 16px; } .tether-element.tether-theme-arrows.tether-element-attached-top.tether-element-attached-left.tether-target-attached-right .tether-content:before { top: 16px; right: 100%; border-right-color: white; } .tether-element.tether-theme-arrows.tether-element-attached-bottom.tether-element-attached-right.tether-target-attached-left .tether-content { margin-right: 16px; } .tether-element.tether-theme-arrows.tether-element-attached-bottom.tether-element-attached-right.tether-target-attached-left .tether-content:before { bottom: 16px; left: 100%; border-left-color: white; } .tether-element.tether-theme-arrows.tether-element-attached-bottom.tether-element-attached-left.tether-target-attached-right .tether-content { margin-left: 16px; } .tether-element.tether-theme-arrows.tether-element-attached-bottom.tether-element-attached-left.tether-target-attached-right .tether-content:before { bottom: 16px; right: 100%; border-right-color: white; }
dlueth/cdnjs
ajax/libs/tether/0.4.4/css/tether-theme-arrows.css
CSS
mit
5,725
// Copyright 2011 Mark Cavage <mcavage@gmail.com> All rights reserved. var test = require('tap').test; ///--- Globals var BerReader; ///--- Tests test('load library', function(t) { BerReader = require('../../lib/index').BerReader; t.ok(BerReader); try { new BerReader(); t.fail('Should have thrown'); } catch (e) { t.ok(e instanceof TypeError, 'Should have been a type error'); } t.end(); }); test('read byte', function(t) { var reader = new BerReader(new Buffer([0xde])); t.ok(reader); t.equal(reader.readByte(), 0xde, 'wrong value'); t.end(); }); test('read 1 byte int', function(t) { var reader = new BerReader(new Buffer([0x02, 0x01, 0x03])); t.ok(reader); t.equal(reader.readInt(), 0x03, 'wrong value'); t.equal(reader.length, 0x01, 'wrong length'); t.end(); }); test('read 2 byte int', function(t) { var reader = new BerReader(new Buffer([0x02, 0x02, 0x7e, 0xde])); t.ok(reader); t.equal(reader.readInt(), 0x7ede, 'wrong value'); t.equal(reader.length, 0x02, 'wrong length'); t.end(); }); test('read 3 byte int', function(t) { var reader = new BerReader(new Buffer([0x02, 0x03, 0x7e, 0xde, 0x03])); t.ok(reader); t.equal(reader.readInt(), 0x7ede03, 'wrong value'); t.equal(reader.length, 0x03, 'wrong length'); t.end(); }); test('read 4 byte int', function(t) { var reader = new BerReader(new Buffer([0x02, 0x04, 0x7e, 0xde, 0x03, 0x01])); t.ok(reader); t.equal(reader.readInt(), 0x7ede0301, 'wrong value'); t.equal(reader.length, 0x04, 'wrong length'); t.end(); }); test('read 1 byte negative int', function(t) { var reader = new BerReader(new Buffer([0x02, 0x01, 0xdc])); t.ok(reader); t.equal(reader.readInt(), -36, 'wrong value'); t.equal(reader.length, 0x01, 'wrong length'); t.end(); }); test('read 2 byte negative int', function(t) { var reader = new BerReader(new Buffer([0x02, 0x02, 0xc0, 0x4e])); t.ok(reader); t.equal(reader.readInt(), -16306, 'wrong value'); t.equal(reader.length, 0x02, 'wrong length'); t.end(); }); test('read 3 byte negative int', function(t) { var reader = new BerReader(new Buffer([0x02, 0x03, 0xff, 0x00, 0x19])); t.ok(reader); t.equal(reader.readInt(), -65511, 'wrong value'); t.equal(reader.length, 0x03, 'wrong length'); t.end(); }); test('read 4 byte negative int', function(t) { var reader = new BerReader(new Buffer([0x02, 0x04, 0x91, 0x7c, 0x22, 0x1f])); t.ok(reader); t.equal(reader.readInt(), -1854135777, 'wrong value'); t.equal(reader.length, 0x04, 'wrong length'); t.end(); }); test('read boolean true', function(t) { var reader = new BerReader(new Buffer([0x01, 0x01, 0xff])); t.ok(reader); t.equal(reader.readBoolean(), true, 'wrong value'); t.equal(reader.length, 0x01, 'wrong length'); t.end(); }); test('read boolean false', function(t) { var reader = new BerReader(new Buffer([0x01, 0x01, 0x00])); t.ok(reader); t.equal(reader.readBoolean(), false, 'wrong value'); t.equal(reader.length, 0x01, 'wrong length'); t.end(); }); test('read enumeration', function(t) { var reader = new BerReader(new Buffer([0x0a, 0x01, 0x20])); t.ok(reader); t.equal(reader.readEnumeration(), 0x20, 'wrong value'); t.equal(reader.length, 0x01, 'wrong length'); t.end(); }); test('read string', function(t) { var dn = 'cn=foo,ou=unit,o=test'; var buf = new Buffer(dn.length + 2); buf[0] = 0x04; buf[1] = Buffer.byteLength(dn); buf.write(dn, 2); var reader = new BerReader(buf); t.ok(reader); t.equal(reader.readString(), dn, 'wrong value'); t.equal(reader.length, dn.length, 'wrong length'); t.end(); }); test('read sequence', function(t) { var reader = new BerReader(new Buffer([0x30, 0x03, 0x01, 0x01, 0xff])); t.ok(reader); t.equal(reader.readSequence(), 0x30, 'wrong value'); t.equal(reader.length, 0x03, 'wrong length'); t.equal(reader.readBoolean(), true, 'wrong value'); t.equal(reader.length, 0x01, 'wrong length'); t.end(); }); test('anonymous LDAPv3 bind', function(t) { var BIND = new Buffer(14); BIND[0] = 0x30; // Sequence BIND[1] = 12; // len BIND[2] = 0x02; // ASN.1 Integer BIND[3] = 1; // len BIND[4] = 0x04; // msgid (make up 4) BIND[5] = 0x60; // Bind Request BIND[6] = 7; // len BIND[7] = 0x02; // ASN.1 Integer BIND[8] = 1; // len BIND[9] = 0x03; // v3 BIND[10] = 0x04; // String (bind dn) BIND[11] = 0; // len BIND[12] = 0x80; // ContextSpecific (choice) BIND[13] = 0; // simple bind // Start testing ^^ var ber = new BerReader(BIND); t.equal(ber.readSequence(), 48, 'Not an ASN.1 Sequence'); t.equal(ber.length, 12, 'Message length should be 12'); t.equal(ber.readInt(), 4, 'Message id should have been 4'); t.equal(ber.readSequence(), 96, 'Bind Request should have been 96'); t.equal(ber.length, 7, 'Bind length should have been 7'); t.equal(ber.readInt(), 3, 'LDAP version should have been 3'); t.equal(ber.readString(), '', 'Bind DN should have been empty'); t.equal(ber.length, 0, 'string length should have been 0'); t.equal(ber.readByte(), 0x80, 'Should have been ContextSpecific (choice)'); t.equal(ber.readByte(), 0, 'Should have been simple bind'); t.equal(null, ber.readByte(), 'Should be out of data'); t.end(); }); test('long string', function(t) { var buf = new Buffer(256); var o; var s = '2;649;CN=Red Hat CS 71GA Demo,O=Red Hat CS 71GA Demo,C=US;' + 'CN=RHCS Agent - admin01,UID=admin01,O=redhat,C=US [1] This is ' + 'Teena Vradmin\'s description.'; buf[0] = 0x04; buf[1] = 0x81; buf[2] = 0x94; buf.write(s, 3); var ber = new BerReader(buf.slice(0, 3 + s.length)); t.equal(ber.readString(), s); t.end(); });
RollMan/mashup201608
node_modules/asn1/tst/ber/reader.test.js
JavaScript
mit
5,718
define([ "./core", "./var/pnum", "./css/var/cssExpand", "./css/var/isHidden", "./css/defaultDisplay", "./data/var/data_priv", "./core/init", "./effects/Tween", "./queue", "./css", "./deferred", "./traversing" ], function( jQuery, pnum, cssExpand, isHidden, defaultDisplay, data_priv ) { var fxNow, timerId, rfxtypes = /^(?:toggle|show|hide)$/, rfxnum = new RegExp( "^(?:([+-])=|)(" + pnum + ")([a-z%]*)$", "i" ), rrun = /queueHooks$/, animationPrefilters = [ defaultPrefilter ], tweeners = { "*": [ function( prop, value ) { var tween = this.createTween( prop, value ), target = tween.cur(), parts = rfxnum.exec( value ), unit = parts && parts[ 3 ] || ( jQuery.cssNumber[ prop ] ? "" : "px" ), // Starting value computation is required for potential unit mismatches start = ( jQuery.cssNumber[ prop ] || unit !== "px" && +target ) && rfxnum.exec( jQuery.css( tween.elem, prop ) ), scale = 1, maxIterations = 20; if ( start && start[ 3 ] !== unit ) { // Trust units reported by jQuery.css unit = unit || start[ 3 ]; // Make sure we update the tween properties later on parts = parts || []; // Iteratively approximate from a nonzero starting point start = +target || 1; do { // If previous iteration zeroed out, double until we get *something*. // Use string for doubling so we don't accidentally see scale as unchanged below scale = scale || ".5"; // Adjust and apply start = start / scale; jQuery.style( tween.elem, prop, start + unit ); // Update scale, tolerating zero or NaN from tween.cur(), // break the loop if scale is unchanged or perfect, or if we've just had enough } while ( scale !== (scale = tween.cur() / target) && scale !== 1 && --maxIterations ); } // Update tween properties if ( parts ) { start = tween.start = +start || +target || 0; tween.unit = unit; // If a +=/-= token was provided, we're doing a relative animation tween.end = parts[ 1 ] ? start + ( parts[ 1 ] + 1 ) * parts[ 2 ] : +parts[ 2 ]; } return tween; } ] }; // Animations created synchronously will run synchronously function createFxNow() { setTimeout(function() { fxNow = undefined; }); return ( fxNow = jQuery.now() ); } // Generate parameters to create a standard animation function genFx( type, includeWidth ) { var which, i = 0, attrs = { height: type }; // If we include width, step value is 1 to do all cssExpand values, // otherwise step value is 2 to skip over Left and Right includeWidth = includeWidth ? 1 : 0; for ( ; i < 4 ; i += 2 - includeWidth ) { which = cssExpand[ i ]; attrs[ "margin" + which ] = attrs[ "padding" + which ] = type; } if ( includeWidth ) { attrs.opacity = attrs.width = type; } return attrs; } function createTween( value, prop, animation ) { var tween, collection = ( tweeners[ prop ] || [] ).concat( tweeners[ "*" ] ), index = 0, length = collection.length; for ( ; index < length; index++ ) { if ( (tween = collection[ index ].call( animation, prop, value )) ) { // We're done with this property return tween; } } } function defaultPrefilter( elem, props, opts ) { /* jshint validthis: true */ var prop, value, toggle, tween, hooks, oldfire, display, checkDisplay, anim = this, orig = {}, style = elem.style, hidden = elem.nodeType && isHidden( elem ), dataShow = data_priv.get( elem, "fxshow" ); // Handle queue: false promises if ( !opts.queue ) { hooks = jQuery._queueHooks( elem, "fx" ); if ( hooks.unqueued == null ) { hooks.unqueued = 0; oldfire = hooks.empty.fire; hooks.empty.fire = function() { if ( !hooks.unqueued ) { oldfire(); } }; } hooks.unqueued++; anim.always(function() { // Ensure the complete handler is called before this completes anim.always(function() { hooks.unqueued--; if ( !jQuery.queue( elem, "fx" ).length ) { hooks.empty.fire(); } }); }); } // Height/width overflow pass if ( elem.nodeType === 1 && ( "height" in props || "width" in props ) ) { // Make sure that nothing sneaks out // Record all 3 overflow attributes because IE9-10 do not // change the overflow attribute when overflowX and // overflowY are set to the same value opts.overflow = [ style.overflow, style.overflowX, style.overflowY ]; // Set display property to inline-block for height/width // animations on inline elements that are having width/height animated display = jQuery.css( elem, "display" ); // Test default display if display is currently "none" checkDisplay = display === "none" ? data_priv.get( elem, "olddisplay" ) || defaultDisplay( elem.nodeName ) : display; if ( checkDisplay === "inline" && jQuery.css( elem, "float" ) === "none" ) { style.display = "inline-block"; } } if ( opts.overflow ) { style.overflow = "hidden"; anim.always(function() { style.overflow = opts.overflow[ 0 ]; style.overflowX = opts.overflow[ 1 ]; style.overflowY = opts.overflow[ 2 ]; }); } // show/hide pass for ( prop in props ) { value = props[ prop ]; if ( rfxtypes.exec( value ) ) { delete props[ prop ]; toggle = toggle || value === "toggle"; if ( value === ( hidden ? "hide" : "show" ) ) { // If there is dataShow left over from a stopped hide or show and we are going to proceed with show, we should pretend to be hidden if ( value === "show" && dataShow && dataShow[ prop ] !== undefined ) { hidden = true; } else { continue; } } orig[ prop ] = dataShow && dataShow[ prop ] || jQuery.style( elem, prop ); // Any non-fx value stops us from restoring the original display value } else { display = undefined; } } if ( !jQuery.isEmptyObject( orig ) ) { if ( dataShow ) { if ( "hidden" in dataShow ) { hidden = dataShow.hidden; } } else { dataShow = data_priv.access( elem, "fxshow", {} ); } // Store state if its toggle - enables .stop().toggle() to "reverse" if ( toggle ) { dataShow.hidden = !hidden; } if ( hidden ) { jQuery( elem ).show(); } else { anim.done(function() { jQuery( elem ).hide(); }); } anim.done(function() { var prop; data_priv.remove( elem, "fxshow" ); for ( prop in orig ) { jQuery.style( elem, prop, orig[ prop ] ); } }); for ( prop in orig ) { tween = createTween( hidden ? dataShow[ prop ] : 0, prop, anim ); if ( !( prop in dataShow ) ) { dataShow[ prop ] = tween.start; if ( hidden ) { tween.end = tween.start; tween.start = prop === "width" || prop === "height" ? 1 : 0; } } } // If this is a noop like .hide().hide(), restore an overwritten display value } else if ( (display === "none" ? defaultDisplay( elem.nodeName ) : display) === "inline" ) { style.display = display; } } function propFilter( props, specialEasing ) { var index, name, easing, value, hooks; // camelCase, specialEasing and expand cssHook pass for ( index in props ) { name = jQuery.camelCase( index ); easing = specialEasing[ name ]; value = props[ index ]; if ( jQuery.isArray( value ) ) { easing = value[ 1 ]; value = props[ index ] = value[ 0 ]; } if ( index !== name ) { props[ name ] = value; delete props[ index ]; } hooks = jQuery.cssHooks[ name ]; if ( hooks && "expand" in hooks ) { value = hooks.expand( value ); delete props[ name ]; // Not quite $.extend, this won't overwrite existing keys. // Reusing 'index' because we have the correct "name" for ( index in value ) { if ( !( index in props ) ) { props[ index ] = value[ index ]; specialEasing[ index ] = easing; } } } else { specialEasing[ name ] = easing; } } } function Animation( elem, properties, options ) { var result, stopped, index = 0, length = animationPrefilters.length, deferred = jQuery.Deferred().always( function() { // Don't match elem in the :animated selector delete tick.elem; }), tick = function() { if ( stopped ) { return false; } var currentTime = fxNow || createFxNow(), remaining = Math.max( 0, animation.startTime + animation.duration - currentTime ), // Support: Android 2.3 // Archaic crash bug won't allow us to use `1 - ( 0.5 || 0 )` (#12497) temp = remaining / animation.duration || 0, percent = 1 - temp, index = 0, length = animation.tweens.length; for ( ; index < length ; index++ ) { animation.tweens[ index ].run( percent ); } deferred.notifyWith( elem, [ animation, percent, remaining ]); if ( percent < 1 && length ) { return remaining; } else { deferred.resolveWith( elem, [ animation ] ); return false; } }, animation = deferred.promise({ elem: elem, props: jQuery.extend( {}, properties ), opts: jQuery.extend( true, { specialEasing: {} }, options ), originalProperties: properties, originalOptions: options, startTime: fxNow || createFxNow(), duration: options.duration, tweens: [], createTween: function( prop, end ) { var tween = jQuery.Tween( elem, animation.opts, prop, end, animation.opts.specialEasing[ prop ] || animation.opts.easing ); animation.tweens.push( tween ); return tween; }, stop: function( gotoEnd ) { var index = 0, // If we are going to the end, we want to run all the tweens // otherwise we skip this part length = gotoEnd ? animation.tweens.length : 0; if ( stopped ) { return this; } stopped = true; for ( ; index < length ; index++ ) { animation.tweens[ index ].run( 1 ); } // Resolve when we played the last frame; otherwise, reject if ( gotoEnd ) { deferred.resolveWith( elem, [ animation, gotoEnd ] ); } else { deferred.rejectWith( elem, [ animation, gotoEnd ] ); } return this; } }), props = animation.props; propFilter( props, animation.opts.specialEasing ); for ( ; index < length ; index++ ) { result = animationPrefilters[ index ].call( animation, elem, props, animation.opts ); if ( result ) { return result; } } jQuery.map( props, createTween, animation ); if ( jQuery.isFunction( animation.opts.start ) ) { animation.opts.start.call( elem, animation ); } jQuery.fx.timer( jQuery.extend( tick, { elem: elem, anim: animation, queue: animation.opts.queue }) ); // attach callbacks from options return animation.progress( animation.opts.progress ) .done( animation.opts.done, animation.opts.complete ) .fail( animation.opts.fail ) .always( animation.opts.always ); } jQuery.Animation = jQuery.extend( Animation, { tweener: function( props, callback ) { if ( jQuery.isFunction( props ) ) { callback = props; props = [ "*" ]; } else { props = props.split(" "); } var prop, index = 0, length = props.length; for ( ; index < length ; index++ ) { prop = props[ index ]; tweeners[ prop ] = tweeners[ prop ] || []; tweeners[ prop ].unshift( callback ); } }, prefilter: function( callback, prepend ) { if ( prepend ) { animationPrefilters.unshift( callback ); } else { animationPrefilters.push( callback ); } } }); jQuery.speed = function( speed, easing, fn ) { var opt = speed && typeof speed === "object" ? jQuery.extend( {}, speed ) : { complete: fn || !fn && easing || jQuery.isFunction( speed ) && speed, duration: speed, easing: fn && easing || easing && !jQuery.isFunction( easing ) && easing }; opt.duration = jQuery.fx.off ? 0 : typeof opt.duration === "number" ? opt.duration : opt.duration in jQuery.fx.speeds ? jQuery.fx.speeds[ opt.duration ] : jQuery.fx.speeds._default; // Normalize opt.queue - true/undefined/null -> "fx" if ( opt.queue == null || opt.queue === true ) { opt.queue = "fx"; } // Queueing opt.old = opt.complete; opt.complete = function() { if ( jQuery.isFunction( opt.old ) ) { opt.old.call( this ); } if ( opt.queue ) { jQuery.dequeue( this, opt.queue ); } }; return opt; }; jQuery.fn.extend({ fadeTo: function( speed, to, easing, callback ) { // Show any hidden elements after setting opacity to 0 return this.filter( isHidden ).css( "opacity", 0 ).show() // Animate to the value specified .end().animate({ opacity: to }, speed, easing, callback ); }, animate: function( prop, speed, easing, callback ) { var empty = jQuery.isEmptyObject( prop ), optall = jQuery.speed( speed, easing, callback ), doAnimation = function() { // Operate on a copy of prop so per-property easing won't be lost var anim = Animation( this, jQuery.extend( {}, prop ), optall ); // Empty animations, or finishing resolves immediately if ( empty || data_priv.get( this, "finish" ) ) { anim.stop( true ); } }; doAnimation.finish = doAnimation; return empty || optall.queue === false ? this.each( doAnimation ) : this.queue( optall.queue, doAnimation ); }, stop: function( type, clearQueue, gotoEnd ) { var stopQueue = function( hooks ) { var stop = hooks.stop; delete hooks.stop; stop( gotoEnd ); }; if ( typeof type !== "string" ) { gotoEnd = clearQueue; clearQueue = type; type = undefined; } if ( clearQueue && type !== false ) { this.queue( type || "fx", [] ); } return this.each(function() { var dequeue = true, index = type != null && type + "queueHooks", timers = jQuery.timers, data = data_priv.get( this ); if ( index ) { if ( data[ index ] && data[ index ].stop ) { stopQueue( data[ index ] ); } } else { for ( index in data ) { if ( data[ index ] && data[ index ].stop && rrun.test( index ) ) { stopQueue( data[ index ] ); } } } for ( index = timers.length; index--; ) { if ( timers[ index ].elem === this && (type == null || timers[ index ].queue === type) ) { timers[ index ].anim.stop( gotoEnd ); dequeue = false; timers.splice( index, 1 ); } } // Start the next in the queue if the last step wasn't forced. // Timers currently will call their complete callbacks, which // will dequeue but only if they were gotoEnd. if ( dequeue || !gotoEnd ) { jQuery.dequeue( this, type ); } }); }, finish: function( type ) { if ( type !== false ) { type = type || "fx"; } return this.each(function() { var index, data = data_priv.get( this ), queue = data[ type + "queue" ], hooks = data[ type + "queueHooks" ], timers = jQuery.timers, length = queue ? queue.length : 0; // Enable finishing flag on private data data.finish = true; // Empty the queue first jQuery.queue( this, type, [] ); if ( hooks && hooks.stop ) { hooks.stop.call( this, true ); } // Look for any active animations, and finish them for ( index = timers.length; index--; ) { if ( timers[ index ].elem === this && timers[ index ].queue === type ) { timers[ index ].anim.stop( true ); timers.splice( index, 1 ); } } // Look for any animations in the old queue and finish them for ( index = 0; index < length; index++ ) { if ( queue[ index ] && queue[ index ].finish ) { queue[ index ].finish.call( this ); } } // Turn off finishing flag delete data.finish; }); } }); jQuery.each([ "toggle", "show", "hide" ], function( i, name ) { var cssFn = jQuery.fn[ name ]; jQuery.fn[ name ] = function( speed, easing, callback ) { return speed == null || typeof speed === "boolean" ? cssFn.apply( this, arguments ) : this.animate( genFx( name, true ), speed, easing, callback ); }; }); // Generate shortcuts for custom animations jQuery.each({ slideDown: genFx("show"), slideUp: genFx("hide"), slideToggle: genFx("toggle"), fadeIn: { opacity: "show" }, fadeOut: { opacity: "hide" }, fadeToggle: { opacity: "toggle" } }, function( name, props ) { jQuery.fn[ name ] = function( speed, easing, callback ) { return this.animate( props, speed, easing, callback ); }; }); jQuery.timers = []; jQuery.fx.tick = function() { var timer, i = 0, timers = jQuery.timers; fxNow = jQuery.now(); for ( ; i < timers.length; i++ ) { timer = timers[ i ]; // Checks the timer has not already been removed if ( !timer() && timers[ i ] === timer ) { timers.splice( i--, 1 ); } } if ( !timers.length ) { jQuery.fx.stop(); } fxNow = undefined; }; jQuery.fx.timer = function( timer ) { jQuery.timers.push( timer ); if ( timer() ) { jQuery.fx.start(); } else { jQuery.timers.pop(); } }; jQuery.fx.interval = 13; jQuery.fx.start = function() { if ( !timerId ) { timerId = setInterval( jQuery.fx.tick, jQuery.fx.interval ); } }; jQuery.fx.stop = function() { clearInterval( timerId ); timerId = null; }; jQuery.fx.speeds = { slow: 600, fast: 200, // Default speed _default: 400 }; return jQuery; });
snake-345/jcarouselLazyLoading
bower_components/jquery/src/effects.js
JavaScript
mit
16,914
/** * Owl Carousel v2.2.0 * Copyright 2013-2016 David Deutsch * Licensed under MIT (https://github.com/OwlCarousel2/OwlCarousel2/blob/master/LICENSE) */ /* * Default theme - Owl Carousel CSS File */ .owl-theme .owl-nav { margin-top: 10px; text-align: center; -webkit-tap-highlight-color: transparent; } .owl-theme .owl-nav [class*='owl-'] { color: #FFF; font-size: 14px; margin: 5px; padding: 4px 7px; background: #D6D6D6; display: inline-block; cursor: pointer; border-radius: 3px; } .owl-theme .owl-nav [class*='owl-']:hover { background: #869791; color: #FFF; text-decoration: none; } .owl-theme .owl-nav .disabled { opacity: 0.5; cursor: default; } .owl-theme .owl-nav.disabled + .owl-dots { margin-top: 10px; } .owl-theme .owl-dots { text-align: center; -webkit-tap-highlight-color: transparent; } .owl-theme .owl-dots .owl-dot { display: inline-block; zoom: 1; *display: inline; } .owl-theme .owl-dots .owl-dot span { width: 10px; height: 10px; margin: 5px 7px; background: #D6D6D6; display: block; -webkit-backface-visibility: visible; transition: opacity 200ms ease; border-radius: 30px; } .owl-theme .owl-dots .owl-dot.active span, .owl-theme .owl-dots .owl-dot:hover span { background: #869791; }
qaisarirfan/wireframe
bower_components/owl.carousel/dist/assets/owl.theme.default.css
CSS
mit
1,370
module Jekyll class LiquidRenderer::Table def initialize(stats) @stats = stats end def to_s(n = 50) data = data_for_table(n) widths = table_widths(data) generate_table(data, widths) end private def generate_table(data, widths) str = "\n" table_head = data.shift str << generate_row(table_head, widths) str << generate_table_head_border(table_head, widths) data.each do |row_data| str << generate_row(row_data, widths) end str << "\n" str end def generate_table_head_border(row_data, widths) str = "" row_data.each_index do |cell_index| str << '-' * widths[cell_index] str << '-+-' unless cell_index == row_data.length-1 end str << "\n" str end def generate_row(row_data, widths) str = '' row_data.each_with_index do |cell_data, cell_index| if cell_index == 0 str << cell_data.ljust(widths[cell_index], ' ') else str << cell_data.rjust(widths[cell_index], ' ') end str << ' | ' unless cell_index == row_data.length-1 end str << "\n" str end def table_widths(data) widths = [] data.each do |row| row.each_with_index do |cell, index| widths[index] = [ cell.length, widths[index] ].compact.max end end widths end def data_for_table(n) sorted = @stats.sort_by{ |filename, file_stats| -file_stats[:time] } sorted = sorted.slice(0, n) table = [[ 'Filename', 'Count', 'Bytes', 'Time' ]] sorted.each do |filename, file_stats| row = [] row << filename row << file_stats[:count].to_s row << format_bytes(file_stats[:bytes]) row << "%.3f" % file_stats[:time] table << row end table end def format_bytes(bytes) bytes /= 1024.0 "%.2fK" % bytes end end end
shuber2/jekyll
lib/jekyll/liquid_renderer/table.rb
Ruby
mit
1,989
'use strict';/*! * This is a `i18n` language object. * * Catalan * * @author * Tongro * * @see core/i18n.js */ (function (exports) { if (exports.ca === undefined) { exports.ca = { "mejs.plural-form": 1, // "mejs.install-flash": "You are using a browser that does not have Flash player enabled or installed. Please turn on your Flash player plugin or download the latest version from https://get.adobe.com/flashplayer/", "mejs.fullscreen": "Pantalla completa", "mejs.play": "Reproducció", "mejs.pause": "Pausa", // "mejs.time-slider": "Time Slider", // "mejs.time-help-text": "Use Left/Right Arrow keys to advance one second, Up/Down arrows to advance ten seconds.", //"mejs.live-broadcast" : "Live Broadcast", // "mejs.volume-help-text": "Use Up/Down Arrow keys to increase or decrease volume.", "mejs.unmute": "Reactivar silenci", "mejs.mute": "Silenci", // "mejs.volume-slider": "Volume Slider", "mejs.video-player": "Reproductor de vídeo", "mejs.audio-player": "Reproductor d'àudio", "mejs.captions-subtitles": "Llegendes/Subtítols", // "mejs.captions-chapters": "Chapters", "mejs.none": "Ningú" // "mejs.afrikaans": "Afrikaans", // "mejs.albanian": "Albanian", // "mejs.arabic": "Arabic", // "mejs.belarusian": "Belarusian", // "mejs.bulgarian": "Bulgarian", // "mejs.catalan": "Catalan", // "mejs.chinese": "Chinese", // "mejs.chinese-simplified": "Chinese (Simplified)", // "mejs.chinese-traditional": "Chinese (Traditional)", // "mejs.croatian": "Croatian", // "mejs.czech": "Czech", // "mejs.danish": "Danish", // "mejs.dutch": "Dutch", // "mejs.english": "English", // "mejs.estonian": "Estonian", // "mejs.filipino": "Filipino", // "mejs.finnish": "Finnish", // "mejs.french": "French", // "mejs.galician": "Galician", // "mejs.german": "German", // "mejs.greek": "Greek", // "mejs.haitian-creole": "Haitian Creole", // "mejs.hebrew": "Hebrew", // "mejs.hindi": "Hindi", // "mejs.hungarian": "Hungarian", // "mejs.icelandic": "Icelandic", // "mejs.indonesian": "Indonesian", // "mejs.irish": "Irish", // "mejs.italian": "Italian", // "mejs.japanese": "Japanese", // "mejs.korean": "Korean", // "mejs.latvian": "Latvian", // "mejs.lithuanian": "Lithuanian", // "mejs.macedonian": "Macedonian", // "mejs.malay": "Malay", // "mejs.maltese": "Maltese", // "mejs.norwegian": "Norwegian", // "mejs.persian": "Persian", // "mejs.polish": "Polish", // "mejs.portuguese": "Portuguese", // "mejs.romanian": "Romanian", // "mejs.russian": "Russian", // "mejs.serbian": "Serbian", // "mejs.slovak": "Slovak", // "mejs.slovenian": "Slovenian", // "mejs.spanish": "Spanish", // "mejs.swahili": "Swahili", // "mejs.swedish": "Swedish", // "mejs.tagalog": "Tagalog", // "mejs.thai": "Thai", // "mejs.turkish": "Turkish", // "mejs.ukrainian": "Ukrainian", // "mejs.vietnamese": "Vietnamese", // "mejs.welsh": "Welsh", // "mejs.yiddish": "Yiddish" }; } })(mejs.i18n);
seogi1004/cdnjs
ajax/libs/mediaelement/3.2.3/lang/ca.js
JavaScript
mit
3,117
<!doctype html> <html lang="en"> <head> <title>three.js webgl - interactive - raycasting - pointcloud</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0"> <style> body { color: #ffffff; background-color: #000000; margin: 0px; overflow: hidden; } #info { position: absolute; top: 0px; width: 100%; padding: 5px; font-family: Monospace; font-size: 13px; text-align: center; font-weight: bold; } a { color: #fff; } </style> </head> <body> <div id="container"></div> <div id="info"><a href="http://threejs.org" target="_blank">three.js</a> webgl - interactive - raycasting - pointcloud </div> <script src="../build/three.min.js"></script> <script src="js/Detector.js"></script> <script src="js/libs/stats.min.js"></script> <script> if ( ! Detector.webgl ) Detector.addGetWebGLMessage(); var renderer, scene, camera, stats; var pointclouds; var raycaster, intersects; var mouse = new THREE.Vector2(); var intersection = null; var spheres = []; var spheresIndex = 0; var clock; var threshold = 0.1; var pointSize = 0.05; var width = 150; var length = 150; var rotateY = new THREE.Matrix4().makeRotationY( 0.005 ); init(); animate(); function generatePointCloudGeometry( color, width, length ){ var geometry = new THREE.BufferGeometry(); var numPoints = width*length; var positions = new Float32Array( numPoints*3 ); var colors = new Float32Array( numPoints*3 ); var k = 0; for( var i = 0; i < width; i++ ) { for( var j = 0; j < length; j++ ) { var u = i / width; var v = j / length; var x = u - 0.5; var y = ( Math.cos( u * Math.PI * 8 ) + Math.sin( v * Math.PI * 8 ) ) / 20; var z = v - 0.5; positions[ 3 * k ] = x; positions[ 3 * k + 1 ] = y; positions[ 3 * k + 2 ] = z; var intensity = ( y + 0.1 ) * 5; colors[ 3 * k ] = color.r * intensity; colors[ 3 * k + 1 ] = color.g * intensity; colors[ 3 * k + 2 ] = color.b * intensity; k++; } } geometry.addAttribute( 'position', new THREE.BufferAttribute( positions, 3 ) ); geometry.addAttribute( 'color', new THREE.BufferAttribute( colors, 3 ) ); geometry.computeBoundingBox(); return geometry; } function generatePointcloud( color, width, length ) { var geometry = generatePointCloudGeometry( color, width, length ); var material = new THREE.PointCloudMaterial( { size: pointSize, vertexColors: THREE.VertexColors } ); var pointcloud = new THREE.PointCloud( geometry, material ); return pointcloud; } function generateIndexedPointcloud( color, width, length ) { var geometry = generatePointCloudGeometry( color, width, length ); var numPoints = width * length; var indices = new Uint16Array( numPoints ); var k = 0; for( var i = 0; i < width; i++ ) { for( var j = 0; j < length; j++ ) { indices[ k ] = k; k++; } } geometry.addAttribute( 'index', new THREE.BufferAttribute( indices, 1 ) ); var material = new THREE.PointCloudMaterial( { size: pointSize, vertexColors: THREE.VertexColors } ); var pointcloud = new THREE.PointCloud( geometry, material ); return pointcloud; } function generateIndexedWithOffsetPointcloud( color, width, length ){ var geometry = generatePointCloudGeometry( color, width, length ); var numPoints = width * length; var indices = new Uint16Array( numPoints ); var k = 0; for( var i = 0; i < width; i++ ){ for( var j = 0; j < length; j++ ) { indices[ k ] = k; k++; } } geometry.addAttribute( 'index', new THREE.BufferAttribute( indices, 1 ) ); var offset = { start: 0, count: indices.length, index: 0 }; geometry.offsets.push( offset ); var material = new THREE.PointCloudMaterial( { size: pointSize, vertexColors: THREE.VertexColors } ); var pointcloud = new THREE.PointCloud( geometry, material ); return pointcloud; } function generateRegularPointcloud( color, width, length ) { var geometry = new THREE.Geometry(); var numPoints = width * length; var colors = []; var k = 0; for( var i = 0; i < width; i++ ) { for( var j = 0; j < length; j++ ) { var u = i / width; var v = j / length; var x = u - 0.5; var y = ( Math.cos( u * Math.PI * 8 ) + Math.sin( v * Math.PI * 8) ) / 20; var z = v - 0.5; var v = new THREE.Vector3( x,y,z ); var intensity = ( y + 0.1 ) * 7; colors[ 3 * k ] = color.r * intensity; colors[ 3 * k + 1 ] = color.g * intensity; colors[ 3 * k + 2 ] = color.b * intensity; geometry.vertices.push( v ); colors[ k ] = ( color.clone().multiplyScalar( intensity ) ); k++; } } geometry.colors = colors; geometry.computeBoundingBox(); var material = new THREE.PointCloudMaterial( { size: pointSize, vertexColors: THREE.VertexColors } ); var pointcloud = new THREE.PointCloud( geometry, material ); return pointcloud; } function init() { container = document.getElementById( 'container' ); scene = new THREE.Scene(); clock = new THREE.Clock(); camera = new THREE.PerspectiveCamera( 45, window.innerWidth / window.innerHeight, 1, 10000 ); camera.applyMatrix( new THREE.Matrix4().makeTranslation( 0,0,20 ) ); camera.applyMatrix( new THREE.Matrix4().makeRotationX( -0.5 ) ); // pcBuffer = generatePointcloud( new THREE.Color( 1,0,0 ), width, length ); pcBuffer.scale.set( 10,10,10 ); pcBuffer.position.set( -5,0,5 ); scene.add( pcBuffer ); var pcIndexed = generateIndexedPointcloud( new THREE.Color( 0,1,0 ), width, length ); pcIndexed.scale.set( 10,10,10 ); pcIndexed.position.set( 5,0,5 ); scene.add( pcIndexed ); var pcIndexedOffset = generateIndexedWithOffsetPointcloud( new THREE.Color( 0,1,1 ), width, length ); pcIndexedOffset.scale.set( 10,10,10 ); pcIndexedOffset.position.set( 5,0,-5 ); scene.add( pcIndexedOffset ); var pcRegular = generateRegularPointcloud( new THREE.Color( 1,0,1 ), width, length ); pcRegular.scale.set( 10,10,10 ); pcRegular.position.set( -5,0,-5 ); scene.add( pcRegular ); pointclouds = [ pcBuffer, pcIndexed, pcIndexedOffset, pcRegular ]; // var sphereGeometry = new THREE.SphereGeometry( 0.1, 32, 32 ); var sphereMaterial = new THREE.MeshBasicMaterial( { color: 0xff0000, shading: THREE.FlatShading } ); for ( var i = 0; i < 40; i++ ) { var sphere = new THREE.Mesh( sphereGeometry, sphereMaterial ); scene.add( sphere ); spheres.push( sphere ); } // renderer = new THREE.WebGLRenderer(); renderer.setPixelRatio( window.devicePixelRatio ); renderer.setSize( window.innerWidth, window.innerHeight ); container.appendChild( renderer.domElement ); // raycaster = new THREE.Raycaster(); raycaster.params.PointCloud.threshold = threshold; // stats = new Stats(); stats.domElement.style.position = 'absolute'; stats.domElement.style.top = '0px'; container.appendChild( stats.domElement ); // window.addEventListener( 'resize', onWindowResize, false ); document.addEventListener( 'mousemove', onDocumentMouseMove, false ); } function onDocumentMouseMove( event ) { event.preventDefault(); mouse.x = ( event.clientX / window.innerWidth ) * 2 - 1; mouse.y = - ( event.clientY / window.innerHeight ) * 2 + 1; } function onWindowResize() { camera.aspect = window.innerWidth / window.innerHeight; camera.updateProjectionMatrix(); renderer.setSize( window.innerWidth, window.innerHeight ); } function animate() { requestAnimationFrame( animate ); render(); stats.update(); } var toggle = 0; function render() { camera.applyMatrix( rotateY ); camera.updateMatrixWorld(); raycaster.setFromCamera( mouse, camera ); var intersections = raycaster.intersectObjects( pointclouds ); intersection = ( intersections.length ) > 0 ? intersections[ 0 ] : null; if ( toggle > 0.02 && intersection !== null) { spheres[ spheresIndex ].position.copy( intersection.point ); spheres[ spheresIndex ].scale.set( 1, 1, 1 ); spheresIndex = ( spheresIndex + 1 ) % spheres.length; toggle = 0; } for ( var i = 0; i < spheres.length; i++ ) { var sphere = spheres[ i ]; sphere.scale.multiplyScalar( 0.98 ); sphere.scale.clampScalar( 0.01, 1 ); } toggle += clock.getDelta(); renderer.render( scene, camera ); } </script> </body> </html>
archilogic-com/three.js
examples/webgl_interactive_raycasting_pointcloud.html
HTML
mit
8,845
<?php /* * This file is part of the Symfony package. * * (c) Fabien Potencier <fabien@symfony.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\VarDumper\Cloner; /** * Represents the main properties of a PHP variable. * * @author Nicolas Grekas <p@tchwork.com> */ class Stub implements \Serializable { const TYPE_REF = 1; const TYPE_STRING = 2; const TYPE_ARRAY = 3; const TYPE_OBJECT = 4; const TYPE_RESOURCE = 5; const STRING_BINARY = 1; const STRING_UTF8 = 2; const ARRAY_ASSOC = 1; const ARRAY_INDEXED = 2; public $type = self::TYPE_REF; public $class = ''; public $value; public $cut = 0; public $handle = 0; public $refCount = 0; public $position = 0; public $attr = array(); /** * @internal */ public function serialize() { return \serialize(array($this->class, $this->position, $this->cut, $this->type, $this->value, $this->handle, $this->refCount, $this->attr)); } /** * @internal */ public function unserialize($serialized) { list($this->class, $this->position, $this->cut, $this->type, $this->value, $this->handle, $this->refCount, $this->attr) = \unserialize($serialized); } }
KevinLejeune/seriestv
vendor/symfony/symfony/src/Symfony/Component/VarDumper/Cloner/Stub.php
PHP
mit
1,357
import "../core/document"; import "../core/vendor"; var d3_timer_queueHead, d3_timer_queueTail, d3_timer_interval, // is an interval (or frame) active? d3_timer_timeout, // is a timeout active? d3_timer_frame = this[d3_vendorSymbol(this, "requestAnimationFrame")] || function(callback) { setTimeout(callback, 17); }; // The timer will continue to fire until callback returns true. d3.timer = function() { d3_timer.apply(this, arguments); }; function d3_timer(callback, delay, then) { var n = arguments.length; if (n < 2) delay = 0; if (n < 3) then = Date.now(); // Add the callback to the tail of the queue. var time = then + delay, timer = {c: callback, t: time, n: null}; if (d3_timer_queueTail) d3_timer_queueTail.n = timer; else d3_timer_queueHead = timer; d3_timer_queueTail = timer; // Start animatin'! if (!d3_timer_interval) { d3_timer_timeout = clearTimeout(d3_timer_timeout); d3_timer_interval = 1; d3_timer_frame(d3_timer_step); } return timer; } function d3_timer_step() { var now = d3_timer_mark(), delay = d3_timer_sweep() - now; if (delay > 24) { if (isFinite(delay)) { clearTimeout(d3_timer_timeout); d3_timer_timeout = setTimeout(d3_timer_step, delay); } d3_timer_interval = 0; } else { d3_timer_interval = 1; d3_timer_frame(d3_timer_step); } } d3.timer.flush = function() { d3_timer_mark(); d3_timer_sweep(); }; function d3_timer_mark() { var now = Date.now(), timer = d3_timer_queueHead; while (timer) { if (now >= timer.t && timer.c(now - timer.t)) timer.c = null; timer = timer.n; } return now; } // Flush after callbacks to avoid concurrent queue modification. // Returns the time of the earliest active timer, post-sweep. function d3_timer_sweep() { var t0, t1 = d3_timer_queueHead, time = Infinity; while (t1) { if (t1.c) { if (t1.t < time) time = t1.t; t1 = (t0 = t1).n; } else { t1 = t0 ? t0.n = t1.n : d3_timer_queueHead = t1.n; } } d3_timer_queueTail = t0; return time; }
cielly/cielly.github.io
node_modules/topojson/node_modules/d3/src/event/timer.js
JavaScript
mit
2,088
/** * Bunch of useful filters for angularJS * @version v0.3.5 - 2014-08-02 * @link https://github.com/a8m/angular-filter * @author Ariel Mashraki <ariel@mashraki.co.il> * @license MIT License, http://www.opensource.org/licenses/MIT */!function(a,b){"use strict";function c(a){for(var b=-1,c=Object.keys(a),d=new Array(c.length);++b<c.length;)d[b]=a[c[b]];return d}function d(a){return null===a}function e(a,b){var c=Object.keys(a);return-1==c.map(function(c){return!(!b[c]||b[c]!=a[c])}).indexOf(!1)}function f(a,b){if(""===b)return a;var c=a.indexOf(b.charAt(0));return-1===c?!1:f(a.substr(c+1),b.substr(1))}function g(a){return function(b,d){return b=m(b)?c(b):b,!n(b)||j(d)?!0:b.some(function(b){return m(b)||k(d)?a(d)(b):b===d})}}function h(a){return function(b,d){function e(a,b){return j(b)?!1:a.some(function(a){return p(a,b)})}if(b=m(b)?c(b):b,j(d))return b.filter(function(a,b,c){return c.indexOf(a)===b});var f=[],g=a(d);return b.filter(function(a){var b=g(a);return e(f,b)?!1:(f.push(b),!0)})}}function i(a,b,c){return b?a+c+i(a,--b,c):a}var j=(b.isDefined,b.isUndefined),k=b.isFunction,l=b.isString,m=b.isObject,n=b.isArray,o=(b.forEach,b.extend),p=(b.copy,b.equals);b.module("a8m.angular",[]).filter("isUndefined",function(){return function(a){return b.isUndefined(a)}}).filter("isDefined",function(){return function(a){return b.isDefined(a)}}).filter("isFunction",function(){return function(a){return b.isFunction(a)}}).filter("isString",function(){return function(a){return b.isString(a)}}).filter("isNumber",function(){return function(a){return b.isNumber(a)}}).filter("isArray",function(){return function(a){return b.isArray(a)}}).filter("isObject",function(){return function(a){return b.isObject(a)}}).filter("isEqual",function(){return function(a,c){return b.equals(a,c)}}),b.module("a8m.is-null",[]).filter("isNull",function(){return function(a){return d(a)}}),b.module("a8m.after-where",[]).filter("afterWhere",function(){return function(a,b){if(a=m(a)?c(a):a,!n(a)||j(b))return a;var d=a.map(function(a){return e(b,a)}).indexOf(!0);return a.slice(-1===d?0:d)}}),b.module("a8m.after",[]).filter("after",function(){return function(a,b){return a=m(a)?c(a):a,n(a)?a.slice(b):a}}),b.module("a8m.before-where",[]).filter("beforeWhere",function(){return function(a,b){if(a=m(a)?c(a):a,!n(a)||j(b))return a;var d=a.map(function(a){return e(b,a)}).indexOf(!0);return a.slice(0,-1===d?a.length:++d)}}),b.module("a8m.before",[]).filter("before",function(){return function(a,b){return a=m(a)?c(a):a,n(a)?a.slice(0,b?--b:b):a}}),b.module("a8m.concat",[]).filter("concat",[function(){return function(a,b){if(j(b))return a;if(n(a))return a.concat(m(b)?c(b):b);if(m(a)){var d=c(a);return d.concat(m(b)?c(b):b)}return a}}]),b.module("a8m.contains",[]).filter({contains:["$parse",g],some:["$parse",g]}),b.module("a8m.count-by",[]).filter("countBy",["$parse",function(a){return function(b,d){var e,f={},g=a(d);return b=m(b)?c(b):b,!n(b)||j(d)?b:(b.forEach(function(a){e=g(a),f[e]||(f[e]=0),f[e]++}),f)}}]),b.module("a8m.every",[]).filter("every",["$parse",function(a){return function(b,d){return b=m(b)?c(b):b,!n(b)||j(d)?!0:b.every(function(b){return m(b)||k(d)?a(d)(b):b===d})}}]),b.module("a8m.fuzzy-by",[]).filter("fuzzyBy",["$parse",function(a){return function(b,d,e,g){var h,i,k=g||!1;return b=m(b)?c(b):b,!n(b)||j(d)||j(e)?b:(i=a(d),b.filter(function(a){return h=i(a),l(h)?(h=k?h:h.toLowerCase(),e=k?e:e.toLowerCase(),f(h,e)!==!1):!1}))}}]),b.module("a8m.fuzzy",[]).filter("fuzzy",function(){return function(a,b,d){function e(a,b){var c,d,e=Object.keys(a);return 0<e.filter(function(e){return c=a[e],d?!0:l(c)?(c=g?c:c.toLowerCase(),d=f(c,b)!==!1):!1}).length}var g=d||!1;return a=m(a)?c(a):a,!n(a)||j(b)?a:(b=g?b:b.toLowerCase(),a.filter(function(a){return l(a)?(a=g?a:a.toLowerCase(),f(a,b)!==!1):m(a)?e(a,b):!1}))}}),b.module("a8m.group-by",[]).filter("groupBy",["$parse",function(a){return function(b,d){var e,f={},g=a(d);return b=m(b)?c(b):b,!n(b)||j(d)?b:(b.forEach(function(a){e=g(a),f[e]||(f[e]=[]),f[e].push(a)}),f)}}]),b.module("a8m.is-empty",[]).filter("isEmpty",function(){return function(a){return m(a)?!c(a).length:!a.length}}),b.module("a8m.omit",[]).filter("omit",["$parse",function(a){return function(b,d){return b=m(b)?c(b):b,!n(b)||j(d)?b:b.filter(function(b){return!a(d)(b)})}}]),b.module("a8m.pick",[]).filter("pick",["$parse",function(a){return function(b,d){return b=m(b)?c(b):b,!n(b)||j(d)?b:b.filter(function(b){return a(d)(b)})}}]),b.module("a8m.remove-with",[]).filter("removeWith",function(){return function(a,b){return j(b)?a:(a=m(a)?c(a):a,a.filter(function(a){return!e(b,a)}))}}),b.module("a8m.remove",[]).filter("remove",function(){return function(a){a=m(a)?c(a):a;var b=Array.prototype.slice.call(arguments,1);return n(a)?a.filter(function(a){return!b.some(function(b){return p(b,a)})}):a}}),b.module("a8m.reverse",[]).filter("reverse",[function(){return function(a){return a=m(a)?c(a):a,l(a)?a.split("").reverse().join(""):n(a)?a.reverse():a}}]),b.module("a8m.search-field",[]).filter("searchField",["$parse",function(a){return function(b){var d,e;b=m(b)?c(b):b;var f=Array.prototype.slice.call(arguments,1);return n(b)&&f.length?b.map(function(b){return e=f.map(function(c){return(d=a(c))(b)}).join(" "),o({searchField:e},b)}):b}}]),b.module("a8m.unique",[]).filter({unique:["$parse",h],uniq:["$parse",h]}),b.module("a8m.where",[]).filter("where",function(){return function(a,b){return j(b)?a:(a=m(a)?c(a):a,a.filter(function(a){return e(b,a)}))}}),b.module("a8m.math",[]).factory("$math",["$window",function(a){return a.Math}]),b.module("a8m.math.max",["a8m.math"]).filter("max",["$math",function(a){return function(b){return n(b)?a.max.apply(a,b):b}}]),b.module("a8m.math.min",["a8m.math"]).filter("min",["$math",function(a){return function(b){return n(b)?a.min.apply(a,b):b}}]),b.module("a8m.ends-with",[]).filter("endsWith",function(){return function(a,b,c){var d,e=c||!1;return!l(a)||j(b)?a:(a=e?a:a.toLowerCase(),d=a.length-b.length,-1!==a.indexOf(e?b:b.toLowerCase(),d))}}),b.module("a8m.ltrim",[]).filter("ltrim",function(){return function(a,b){var c=b||"\\s";return l(a)?a.replace(new RegExp("^"+c+"+"),""):a}}),b.module("a8m.repeat",[]).filter("repeat",[function(){return function(a,b,c){var d=~~b;return l(a)&&d?i(a,--b,c||""):a}}]),b.module("a8m.rtrim",[]).filter("rtrim",function(){return function(a,b){var c=b||"\\s";return l(a)?a.replace(new RegExp(c+"+$"),""):a}}),b.module("a8m.slugify",[]).filter("slugify",[function(){return function(a,b){var c=b||"-";return l(a)?a.toLowerCase().replace(/\s+/g,c):a}}]),b.module("a8m.starts-with",[]).filter("startsWith",function(){return function(a,b,c){var d=c||!1;return!l(a)||j(b)?a:(a=d?a:a.toLowerCase(),!a.indexOf(d?b:b.toLowerCase()))}}),b.module("a8m.stringular",[]).filter("stringular",function(){return function(a){var b=Array.prototype.slice.call(arguments,1);return a.replace(/{(\d+)}/g,function(a,c){return j(b[c])?a:b[c]})}}),b.module("a8m.strip-tags",[]).filter("stripTags",function(){return function(a){return l(a)?a.replace(/<\S[^><]*>/g,""):a}}),b.module("a8m.trim",[]).filter("trim",function(){return function(a,b){var c=b||"\\s";return l(a)?a.replace(new RegExp("^"+c+"+|"+c+"+$","g"),""):a}}),b.module("a8m.truncate",[]).filter("truncate",function(){return function(a,b,c,d){return l(a)?(b=j(b)?a.length:b,d=d||!1,c=c||"",a.substring(0,d?-1===a.indexOf(" ",b)?b:a.indexOf(" ",b):b)+c):a}}),b.module("a8m.ucfirst",[]).filter("ucfirst",[function(){return function(a){return b.isString(a)?a.split(" ").map(function(a){return a.charAt(0).toUpperCase()+a.substring(1)}).join(" "):a}}]),b.module("a8m.uri-encode",[]).filter("uriEncode",["$window",function(a){return function(b){return l(b)?a.encodeURI(b):b}}]),b.module("a8m.wrap",[]).filter("wrap",function(){return function(a,b,c){return!l(a)||j(b)?a:[b,a,c||b].join("")}}),b.module("angular.filter",["a8m.ucfirst","a8m.uri-encode","a8m.slugify","a8m.strip-tags","a8m.stringular","a8m.truncate","a8m.starts-with","a8m.ends-with","a8m.wrap","a8m.trim","a8m.ltrim","a8m.rtrim","a8m.repeat","a8m.concat","a8m.contains","a8m.unique","a8m.is-empty","a8m.after","a8m.after-where","a8m.before","a8m.before-where","a8m.where","a8m.reverse","a8m.remove","a8m.remove-with","a8m.group-by","a8m.count-by","a8m.search-field","a8m.fuzzy-by","a8m.fuzzy","a8m.omit","a8m.pick","a8m.every","a8m.math","a8m.math.max","a8m.math.min","a8m.angular","a8m.is-null"])}(window,window.angular);
ramda/cdnjs
ajax/libs/angular-filter/0.3.5/angular-filter.min.js
JavaScript
mit
8,439
/** * Bunch of useful filters for angularJS * @version v0.4.3 - 2014-09-01 * @link https://github.com/a8m/angular-filter * @author Ariel Mashraki <ariel@mashraki.co.il> * @license MIT License, http://www.opensource.org/licenses/MIT */ (function ( window, angular, undefined ) { /*jshint globalstrict:true*/ 'use strict'; var isDefined = angular.isDefined, isUndefined = angular.isUndefined, isFunction = angular.isFunction, isString = angular.isString, isNumber = angular.isNumber, isObject = angular.isObject, isArray = angular.isArray, forEach = angular.forEach, extend = angular.extend, copy = angular.copy, equals = angular.equals; /** * get an object and return array of values * @param object * @returns {Array} */ function toArray(object) { return isArray(object) ? object : Object.keys(object).map(function(key) { return object[key]; }); } /** * * @param value * @returns {boolean} */ function isNull(value) { return value === null; } /** * return if object contains partial object * @param partial{object} * @param object{object} * @returns {boolean} */ function objectContains(partial, object) { var keys = Object.keys(partial); return keys.map(function(el) { return !(!object[el] || (object[el] != partial[el])); }).indexOf(false) == -1; } /** * search for approximate pattern in string * @param word * @param pattern * @returns {*} */ function hasApproxPattern(word, pattern) { if(pattern === '') return word; var index = word.indexOf(pattern.charAt(0)); if(index === -1) return false; return hasApproxPattern(word.substr(index+1), pattern.substr(1)) } /** * return the first n element of an array, * if expression provided, is returns as long the expression return truthy * @param array * @param n {number} * @param expression {$parse} * @return array or single object */ function getFirstMatches(array, n, expression) { var result, count = ~~result; result = array.filter(function(elm) { var rest = isDefined(expression) ? (count < n && expression(elm)) : count < n; count = rest ? count+1 : count; return rest; }); return (count < 2) ? result[0] : result; } /** * @ngdoc filter * @name a8m.angular * @kind function * * @description * reference to angular function */ angular.module('a8m.angular', []) .filter('isUndefined', function () { return function (input) { return angular.isUndefined(input); } }) .filter('isDefined', function() { return function (input) { return angular.isDefined(input); } }) .filter('isFunction', function() { return function (input) { return angular.isFunction(input); } }) .filter('isString', function() { return function (input) { return angular.isString(input) } }) .filter('isNumber', function() { return function (input) { return angular.isNumber(input); } }) .filter('isArray', function() { return function (input) { return angular.isArray(input); } }) .filter('isObject', function() { return function (input) { return angular.isObject(input); } }) .filter('isEqual', function() { return function (o1, o2) { return angular.equals(o1, o2); } }); /** * @ngdoc filter * @name isNull * @kind function * * @description * checks if value is null or not * @return Boolean */ angular.module('a8m.is-null', []) .filter('isNull', function () { return function(input) { return isNull(input); } }); /** * @ngdoc filter * @name after-where * @kind function * * @description * get a collection and properties object, and returns all of the items * in the collection after the first that found with the given properties. * */ angular.module('a8m.after-where', []) .filter('afterWhere', function() { return function (collection, object) { collection = (isObject(collection)) ? toArray(collection) : collection; if(!isArray(collection) || isUndefined(object)) return collection; var index = collection.map( function( elm ) { return objectContains(object, elm); }).indexOf( true ); return collection.slice((index === -1) ? 0 : index); } }); /** * @ngdoc filter * @name after * @kind function * * @description * get a collection and specified count, and returns all of the items * in the collection after the specified count. * */ angular.module('a8m.after', []) .filter('after', function() { return function (collection, count) { collection = (isObject(collection)) ? toArray(collection) : collection; return (isArray(collection)) ? collection.slice(count) : collection; } }); /** * @ngdoc filter * @name before-where * @kind function * * @description * get a collection and properties object, and returns all of the items * in the collection before the first that found with the given properties. * */ angular.module('a8m.before-where', []) .filter('beforeWhere', function() { return function (collection, object) { collection = (isObject(collection)) ? toArray(collection) : collection; if(!isArray(collection) || isUndefined(object)) return collection; var index = collection.map( function( elm ) { return objectContains(object, elm); }).indexOf( true ); return collection.slice(0, (index === -1) ? collection.length : ++index); } }); /** * @ngdoc filter * @name before * @kind function * * @description * get a collection and specified count, and returns all of the items * in the collection before the specified count. * */ angular.module('a8m.before', []) .filter('before', function() { return function (collection, count) { collection = (isObject(collection)) ? toArray(collection) : collection; return (isArray(collection)) ? collection.slice(0, (!count) ? count : --count) : collection; } }); /** * @ngdoc filter * @name concat * @kind function * * @description * get (array/object, object/array) and return merged collection * */ angular.module('a8m.concat', []) //TODO:unique option ? or use unique filter to filter result .filter('concat', [function () { return function (collection, joined) { if (isUndefined(joined)) { return collection; } if (isArray(collection)) { return (isObject(joined)) ? collection.concat(toArray(joined)) : collection.concat(joined); } if (isObject(collection)) { var array = toArray(collection); return (isObject(joined)) ? array.concat(toArray(joined)) : array.concat(joined); } return collection; }; } ]); /** * @ngdoc filter * @name contains * @kind function * * @description * Checks if given expression is present in one or more object in the collection */ angular.module('a8m.contains', []) .filter({ contains: ['$parse', containsFilter], some: ['$parse', containsFilter] }); function containsFilter( $parse ) { return function (collection, expression) { collection = (isObject(collection)) ? toArray(collection) : collection; if(!isArray(collection) || isUndefined(expression)) { return true; } return collection.some( function(elm) { return (isObject(elm) || isFunction(expression)) ? $parse(expression)(elm) : elm === expression; }); } } /** * @ngdoc filter * @name countBy * @kind function * * @description * Sorts a list into groups and returns a count for the number of objects in each group. */ angular.module('a8m.count-by', []) .filter('countBy', [ '$parse', function ( $parse ) { return function (collection, property) { var result = {}, get = $parse(property), prop; collection = (isObject(collection)) ? toArray(collection) : collection; if(!isArray(collection) || isUndefined(property)) { return collection; } collection.forEach( function( elm ) { prop = get(elm); if(!result[prop]) { result[prop] = 0; } result[prop]++; }); return result; } }]); /** * @ngdoc filter * @name every * @kind function * * @description * Checks if given expression is present in all members in the collection * */ angular.module('a8m.every', []) .filter('every', ['$parse', function($parse) { return function (collection, expression) { collection = (isObject(collection)) ? toArray(collection) : collection; if(!isArray(collection) || isUndefined(expression)) { return true; } return collection.every( function(elm) { return (isObject(elm) || isFunction(expression)) ? $parse(expression)(elm) : elm === expression; }); } }]); /** * @ngdoc filter * @name filterBy * @kind function * * @description * filter by specific properties, avoid the rest */ angular.module('a8m.filter-by', []) .filter('filterBy', ['$parse', function( $parse ) { return function(collection, properties, search) { var comparator; search = (isString(search) || isNumber(search)) ? String(search).toLowerCase() : undefined; collection = (isObject(collection)) ? toArray(collection) : collection; if(!isArray(collection) || isUndefined(search)) { return collection; } return collection.filter(function(elm) { return properties.some(function(prop) { /** * check if there is concatenate properties * example: * object: { first: 'foo', last:'bar' } * filterBy: ['first + last'] => search by full name(i.e 'foo bar') */ if(!~prop.indexOf('+')) { comparator = $parse(prop)(elm) } else { var propList = prop.replace(new RegExp('\\s', 'g'), '').split('+'); comparator = propList.reduce(function(prev, cur, index) { return (index === 1) ? $parse(prev)(elm) + ' ' + $parse(cur)(elm) : prev + ' ' + $parse(cur)(elm); }); } return (isString(comparator) || isNumber(comparator)) ? !String(comparator).toLowerCase().indexOf(search) : false; }) }); } }]); /** * @ngdoc filter * @name first * @kind function * * @description * Gets the first element or first n elements of an array * if callback is provided, is returns as long the callback return truthy */ angular.module('a8m.first', []) .filter('first', ['$parse', function( $parse ) { return function(collection) { var n, getter, args; collection = (isObject(collection)) ? toArray(collection) : collection; if(!isArray(collection)) { return collection; } args = Array.prototype.slice.call(arguments, 1); n = (isNumber(args[0])) ? args[0] : 1; getter = (!isNumber(args[0])) ? args[0] : (!isNumber(args[1])) ? args[1] : undefined; return getFirstMatches(collection, n,(getter) ? $parse(getter) : getter); } }]); /** * @ngdoc filter * @name flatten * @kind function * * @description * Flattens a nested array (the nesting can be to any depth). * If you pass shallow, the array will only be flattened a single level */ angular.module('a8m.flatten', []) .filter('flatten', function () { return function(collection, shallow) { shallow = shallow || false; collection = (isObject(collection)) ? toArray(collection) : collection; if(!isArray(collection)) { return collection; } return (!shallow) ? flatten(collection, 0) : [].concat.apply([], collection); } }); /** * flatten nested array (the nesting can be to any depth). * @param array {Array} * @param i {int} * @returns {Array} * @private */ function flatten(array, i) { i = i || 0; if(i >= array.length) return array; if(isArray(array[i])) { return flatten(array.slice(0,i) .concat(array[i], array.slice(i+1)), i); } return flatten(array, i+1); } /** * @ngdoc filter * @name fuzzyByKey * @kind function * * @description * fuzzy string searching by key */ angular.module('a8m.fuzzy-by', []) .filter('fuzzyBy', ['$parse', function ( $parse ) { return function (collection, property, search, csensitive) { var sensitive = csensitive || false, prop, getter; collection = (isObject(collection)) ? toArray(collection) : collection; if(!isArray(collection) || isUndefined(property) || isUndefined(search)) { return collection; } getter = $parse(property); return collection.filter(function(elm) { prop = getter(elm); if(!isString(prop)) { return false; } prop = (sensitive) ? prop : prop.toLowerCase(); search = (sensitive) ? search : search.toLowerCase(); return hasApproxPattern(prop, search) !== false }) } }]); /** * @ngdoc filter * @name fuzzy * @kind function * * @description * fuzzy string searching for array of strings, objects */ angular.module('a8m.fuzzy', []) .filter('fuzzy', function () { return function (collection, search, csensitive) { var sensitive = csensitive || false; collection = (isObject(collection)) ? toArray(collection) : collection; if(!isArray(collection) || isUndefined(search)) { return collection; } search = (sensitive) ? search : search.toLowerCase(); return collection.filter(function(elm) { if(isString(elm)) { elm = (sensitive) ? elm : elm.toLowerCase(); return hasApproxPattern(elm, search) !== false } return (isObject(elm)) ? _hasApproximateKey(elm, search) : false; }); /** * checks if object has key{string} that match * to fuzzy search pattern * @param object * @param search * @returns {boolean} * @private */ function _hasApproximateKey(object, search) { var properties = Object.keys(object), prop, flag; return 0 < properties.filter(function (elm) { prop = object[elm]; //avoid iteration if we found some key that equal[performance] if(flag) return true; if (isString(prop)) { prop = (sensitive) ? prop : prop.toLowerCase(); return flag = (hasApproxPattern(prop, search) !== false); } return false; }).length; } } }); /** * @ngdoc filter * @name groupBy * @kind function * * @description * Create an object composed of keys generated from the result of running each element of a collection, * each key is an array of the elements. */ angular.module('a8m.group-by', [ 'a8m.filter-watcher' ]) .filter('groupBy', [ '$parse', 'filterWatcher', function ( $parse, filterWatcher ) { return function (collection, property) { var result, get = $parse(property), prop; if(!isObject(collection) || isUndefined(property)) { return collection; } //Add collection instance to watch list result = filterWatcher.$watch('groupBy', collection); forEach( collection, function( elm ) { prop = get(elm); if(!result[prop]) { result[prop] = []; } if(result[prop].indexOf( elm ) === -1) { result[prop].push(elm); } }); //kill instance filterWatcher.$destroy('groupBy', collection); return result; } }]); /** * @ngdoc filter * @name isEmpty * @kind function * * @description * get collection or string and return if it empty */ angular.module('a8m.is-empty', []) .filter('isEmpty', function () { return function(collection) { return (isObject(collection)) ? !toArray(collection).length : !collection.length; } }); /** * @ngdoc filter * @name last * @kind function * * @description * Gets the last element or last n elements of an array * if callback is provided, is returns as long the callback return truthy */ angular.module('a8m.last', []) .filter('last', ['$parse', function( $parse ) { return function(collection) { var n, getter, args, result, //cuz reverse change our src collection //and we don't want side effects reversed = copy(collection); reversed = (isObject(reversed)) ? toArray(reversed) : reversed; if(!isArray(reversed)) { return reversed; } args = Array.prototype.slice.call(arguments, 1); n = (isNumber(args[0])) ? args[0] : 1; getter = (!isNumber(args[0])) ? args[0] : (!isNumber(args[1])) ? args[1] : undefined; return isArray(result = getFirstMatches(reversed.reverse(), n,(getter) ? $parse(getter) : getter)) ? result.reverse() : result; } }]); /** * @ngdoc filter * @name map * @kind function * * @description * Returns a new collection of the results of each expression execution. */ angular.module('a8m.map', []) .filter('map', ['$parse', function($parse) { return function (collection, expression) { collection = (isObject(collection)) ? toArray(collection) : collection; if(!isArray(collection) || isUndefined(expression)) { return collection; } return collection.map(function (elm) { return $parse(expression)(elm); }); } }]); /** * @ngdoc filter * @name omit * @kind function * * @description * filter collection by expression */ angular.module('a8m.omit', []) .filter('omit', ['$parse', function($parse) { return function (collection, expression) { collection = (isObject(collection)) ? toArray(collection) : collection; if(!isArray(collection) || isUndefined(expression)) { return collection; } return collection.filter(function (elm) { return !($parse(expression)(elm)); }); } }]); /** * @ngdoc filter * @name omit * @kind function * * @description * filter collection by expression */ angular.module('a8m.pick', []) .filter('pick', ['$parse', function($parse) { return function (collection, expression) { collection = (isObject(collection)) ? toArray(collection) : collection; if(!isArray(collection) || isUndefined(expression)) { return collection; } return collection.filter(function (elm) { return $parse(expression)(elm); }); } }]); /** * @ngdoc filter * @name removeWith * @kind function * * @description * get collection and properties object, and removed elements * with this properties */ angular.module('a8m.remove-with', []) .filter('removeWith', function() { return function (collection, object) { if(isUndefined(object)) { return collection; } collection = (isObject(collection)) ? toArray(collection) : collection; return collection.filter(function (elm) { return !objectContains(object, elm); }); } }); /** * @ngdoc filter * @name remove * @kind function * * @description * remove specific members from collection */ angular.module('a8m.remove', []) .filter('remove', function () { return function (collection) { collection = (isObject(collection)) ? toArray(collection) : collection; var args = Array.prototype.slice.call(arguments, 1); if(!isArray(collection)) { return collection; } return collection.filter( function( member ) { return !args.some(function(nest) { return equals(nest, member); }) }); } }); /** * @ngdoc filter * @name reverse * @kind function * * @description * Reverses a string or collection */ angular.module('a8m.reverse', []) .filter('reverse',[ function () { return function (input) { input = (isObject(input)) ? toArray(input) : input; if(isString(input)) { return input.split('').reverse().join(''); } return (isArray(input)) ? input.reverse() : input; } }]); /** * @ngdoc filter * @name searchField * @kind function * * @description * for each member, join several strings field and add them to * new field called 'searchField' (use for search filtering) */ angular.module('a8m.search-field', []) .filter('searchField', ['$parse', function ($parse) { return function (collection) { var get, field; collection = (isObject(collection)) ? toArray(collection) : collection; var args = Array.prototype.slice.call(arguments, 1); if(!isArray(collection) || !args.length) { return collection; } return collection.map(function(member) { field = args.map(function(field) { get = $parse(field); return get(member); }).join(' '); //TODO(ariel):we don't wanna change the source, but I'm not sure about the performance. return extend({ searchField: field }, member); }); } }]); /** * @ngdoc filter * @name toArray * @kind function * * @description * Convert objects into stable arrays. * if addKey set to true,the filter also attaches a new property * $key to the value containing the original key that was used in * the object we are iterating over to reference the property */ angular.module('a8m.to-array', []) .filter('toArray', function() { return function (collection, addKey) { if(!isObject(collection)) { return collection; } return (!addKey) ? toArray(collection) : Object.keys(collection).map(function (key) { return extend(collection[key], { $key: key }); }); } }); /** * @ngdoc filter * @name unique/uniq * @kind function * * @description * get collection and filter duplicate members * if uniqueFilter get a property(nested to) as argument it's * filter by this property as unique identifier */ angular.module('a8m.unique', []) .filter({ unique: ['$parse', uniqFilter], uniq: ['$parse', uniqFilter] }); function uniqFilter($parse) { return function (collection, property) { collection = (isObject(collection)) ? toArray(collection) : collection; if (isUndefined(property)) { return collection.filter(function (elm, pos, self) { return self.indexOf(elm) === pos; }) } //store all unique members var uniqueItems = [], get = $parse(property); return collection.filter(function (elm) { var prop = get(elm); if(some(uniqueItems, prop)) { return false; } uniqueItems.push(prop); return true; }); //checked if the unique identifier is already exist function some(array, member) { if(isUndefined(member)) { return false; } return array.some(function(el) { return equals(el, member); }); } } } /** * @ngdoc filter * @name where * @kind function * * @description * of each element in a collection to the given properties object, * returning an array of all elements that have equivalent property values. * */ angular.module('a8m.where', []) .filter('where', function() { return function (collection, object) { if(isUndefined(object)) { return collection; } collection = (isObject(collection)) ? toArray(collection) : collection; return collection.filter(function (elm) { return objectContains(object, elm); }); } }); /** * @ngdoc filter * @name xor * @kind function * * @description * Exclusive or filter by expression */ angular.module('a8m.xor', []) .filter('xor', ['$parse', function($parse) { return function (col1, col2, expression) { expression = expression || false; col1 = (isObject(col1)) ? toArray(col1) : col1; col2 = (isObject(col2)) ? toArray(col2) : col2; if(!isArray(col1) || !isArray(col2)) return col1; return col1.concat(col2) .filter(function(elm) { return !(some(elm, col1) && some(elm, col2)); }); function some(el, col) { var getter = $parse(expression); return col.some(function(dElm) { return expression ? equals(getter(dElm), getter(el)) : equals(dElm, el); }) } } }]); /** * @ngdoc module * @name math * @description * reference to global Math object */ angular.module('a8m.math', []) .factory('$math', ['$window', function ($window) { return $window.Math; }]); /** * @ngdoc filter * @name max * @kind function * * @description * Math.max * */ angular.module('a8m.math.max', ['a8m.math']) .filter('max', ['$math', function ($math) { return function (input) { return (isArray(input)) ? $math.max.apply($math, input) : input; } }]); /** * @ngdoc filter * @name min * @kind function * * @description * Math.min * */ angular.module('a8m.math.min', ['a8m.math']) .filter('min', ['$math', function ($math) { return function (input) { return (isArray(input)) ? $math.min.apply($math, input) : input; } }]); /** * @ngdoc filter * @name Percent * @kind function * * @description * percentage between two numbers * */ angular.module('a8m.math.percent', ['a8m.math']) .filter('percent', ['$math', '$window', function ($math, $window) { return function (input, divided, round) { var divider = (isString(input)) ? $window.Number(input) : input; divided = divided || 100; round = round || false; if (!isNumber(divider) || $window.isNaN(divider)) return input; return (round) ? $math.round((divider / divided) * 100) : ((divider / divided) * 100); } }]); /** * @ngdoc filter * @name Radix * @kind function * * @description * converting decimal numbers to different bases(radix) */ angular.module('a8m.math.radix', []) .filter('radix', function () { return function (input, radix) { var RANGE = /^[2-9]$|^[1-2]\d$|^3[0-6]$/; if(!isNumber(input) || !RANGE.test(radix)) { return input; } return input.toString(radix).toUpperCase(); } }); /** * @ngdoc filter * @name sum * @kind function * * @description * Sum up all values within an array * */ angular.module('a8m.math.sum', []) .filter('sum', function () { return function (input, initial) { return (!isArray(input)) ? input : input.reduce(function(prev, curr) { return prev + curr; }, initial || 0); } }); /** * @ngdoc filter * @name endsWith * @kind function * * @description * checks whether string ends with the ends parameter. */ angular.module('a8m.ends-with', []) .filter('endsWith', function () { return function (input, ends, csensitive) { var sensitive = csensitive || false, position; if(!isString(input) || isUndefined(ends)) { return input; } input = (sensitive) ? input : input.toLowerCase(); position = input.length - ends.length; return input.indexOf((sensitive) ? ends : ends.toLowerCase(), position) !== -1; } }); /** * @ngdoc filter * @name ltrim * @kind function * * @description * Left trim. Similar to trimFilter, but only for left side. */ angular.module('a8m.ltrim', []) .filter('ltrim', function () { return function(input, chars) { var trim = chars || '\\s'; if(!isString(input)) { return input; } return input.replace(new RegExp('^' + trim + '+'), ''); } }); /** * @ngdoc filter * @name repeat * @kind function * * @description * Repeats a string n times */ angular.module('a8m.repeat', []) .filter('repeat',[ function () { return function (input, n, separator) { var times = ~~n; if(!isString(input)) { return input; } return (!times) ? input : strRepeat(input, --n, separator || ''); } }]); /** * Repeats a string n times with given separator * @param str string to repeat * @param n number of times * @param sep separator * @returns {*} */ function strRepeat(str, n, sep) { if(!n) { return str; } return str + sep + strRepeat(str, --n, sep); } /** * @ngdoc filter * @name rtrim * @kind function * * @description * Right trim. Similar to trimFilter, but only for right side. */ angular.module('a8m.rtrim', []) .filter('rtrim', function () { return function(input, chars) { var trim = chars || '\\s'; if(!isString(input)) { return input; } return input.replace(new RegExp(trim + '+$'), ''); } }); /** * @ngdoc filter * @name slugify * @kind function * * @description * remove spaces from string, replace with "-" or given argument */ angular.module('a8m.slugify', []) .filter('slugify',[ function () { return function (input, sub) { var replace = sub || '-'; if(isString(input)) { return input.toLowerCase() .replace(/\s+/g, replace); } return input; } }]); /** * @ngdoc filter * @name startWith * @kind function * * @description * checks whether string starts with the starts parameter. */ angular.module('a8m.starts-with', []) .filter('startsWith', function () { return function (input, start, csensitive) { var sensitive = csensitive || false; if(!isString(input) || isUndefined(start)) { return input; } input = (sensitive) ? input : input.toLowerCase(); return !input.indexOf((sensitive) ? start : start.toLowerCase()); } }); /** * @ngdoc filter * @name stringular * @kind function * * @description * get string with {n} and replace match with enumeration values */ angular.module('a8m.stringular', []) .filter('stringular', function () { return function(input) { var args = Array.prototype.slice.call(arguments, 1); return input.replace(/{(\d+)}/g, function (match, number) { return isUndefined(args[number]) ? match : args[number]; }); } }); /** * @ngdoc filter * @name stripTags * @kind function * * @description * strip html tags from string */ angular.module('a8m.strip-tags', []) .filter('stripTags', function () { return function(input) { if(isString(input)) { return input.replace(/<\S[^><]*>/g, ''); } return input; } }); /** * @ngdoc filter * @name trim * @kind function * * @description * Strip whitespace (or other characters) from the beginning and end of a string */ angular.module('a8m.trim', []) .filter('trim', function () { return function(input, chars) { var trim = chars || '\\s'; if(!isString(input)) { return input; } return input.replace(new RegExp('^' + trim + '+|' + trim + '+$', 'g'), ''); } }); /** * @ngdoc filter * @name truncate * @kind function * * @description * truncates a string given a specified length, providing a custom string to denote an omission. */ angular.module('a8m.truncate', []) .filter('truncate', function () { return function(input, length, suffix, preserve) { length = isUndefined(length) ? input.length : length; preserve = preserve || false; suffix = suffix || ''; if(!isString(input) || (input.length <= length)) return input; return input.substring(0, (preserve) ? ((input.indexOf(' ', length) === -1) ? input.length : input.indexOf(' ', length)) : length) + suffix; }; }); /** * @ngdoc filter * @name ucfirst * @kind function * * @description * ucfirst * */ angular.module('a8m.ucfirst', []) .filter('ucfirst', [function() { return function(input) { return angular.isString(input) ? input.split(' ') .map(function (char) { return char.charAt(0).toUpperCase() + char.substring(1); }).join(' ') : input; } }]); /** * @ngdoc filter * @name uriEncode * @kind function * * @description * get string as parameter and return encoded string */ angular.module('a8m.uri-encode', []) .filter('uriEncode',['$window', function ($window) { return function (input) { if(isString(input)) { return $window.encodeURI(input); } return input; } }]); /** * @ngdoc filter * @name wrap * @kind function * * @description * Wrap a string with another string */ angular.module('a8m.wrap', []) .filter('wrap', function () { return function(input, wrap, ends) { if(!isString(input) || isUndefined(wrap)) { return input; } return [wrap, input, ends || wrap].join(''); } }); /** * @ngdoc provider * @name filterWatcher * @kind function * * @description * filterWatchers is a _privateProvider * It's created to solve the problem of $rootScope:infdig(Infinite $digest loop) when using * some filters on the view. */ angular.module('a8m.filter-watcher', []) .provider('filterWatcher', function() { var filterPrefix = '_$$'; /** * @description * change the prefix name for filters on watch phase * @param prefix * @returns {filterWatcher} */ this.setPrefix = function(prefix) { filterPrefix = prefix; return this; }; this.$get = ['$window', function($window) { var $$timeout = $window.setTimeout; /** * @description * return the filter full name * @param name * @returns {string} * @private */ function _getFullName(name) { return filterPrefix + name; } /** * @description * return whether or not this object is watched in current phase * @param fName * @param object * @returns {boolean} * @private */ function _isWatched(fName, object) { return isDefined(object[fName]); } /** * @description * return the object.$$filterName instance in current phase * @param name * @param object * @private */ function _watch(name, object) { var fName = _getFullName(name); if(!_isWatched(fName, object)) { //Create new instance Object.defineProperty(object, fName, { enumerable: false, configurable: true, value: {} }); } return object[fName]; } /** * @description * destroy/delete current watch instance * @param name * @param object * @private */ function _destroy(name, object) { return $$timeout(function() { delete object[_getFullName(name)]; }); } return { $watch: _watch, $destroy: _destroy } }]; }); /** * @ngdoc module * @name angular.filters * @description * Bunch of useful filters for angularJS */ angular.module('angular.filter', [ 'a8m.ucfirst', 'a8m.uri-encode', 'a8m.slugify', 'a8m.strip-tags', 'a8m.stringular', 'a8m.truncate', 'a8m.starts-with', 'a8m.ends-with', 'a8m.wrap', 'a8m.trim', 'a8m.ltrim', 'a8m.rtrim', 'a8m.repeat', 'a8m.to-array', 'a8m.concat', 'a8m.contains', 'a8m.unique', 'a8m.is-empty', 'a8m.after', 'a8m.after-where', 'a8m.before', 'a8m.before-where', 'a8m.where', 'a8m.reverse', 'a8m.remove', 'a8m.remove-with', 'a8m.group-by', 'a8m.count-by', 'a8m.search-field', 'a8m.fuzzy-by', 'a8m.fuzzy', 'a8m.omit', 'a8m.pick', 'a8m.every', 'a8m.filter-by', 'a8m.xor', 'a8m.map', 'a8m.first', 'a8m.last', 'a8m.flatten', 'a8m.math', 'a8m.math.max', 'a8m.math.min', 'a8m.math.percent', 'a8m.math.radix', 'a8m.math.sum', 'a8m.angular', 'a8m.is-null', 'a8m.filter-watcher' ]); })( window, window.angular );
marxo/cdnjs
ajax/libs/angular-filter/0.4.3/angular-filter.js
JavaScript
mit
36,538
/** * Bunch of useful filters for angularJS * @version v0.4.4 - 2014-09-02 * @link https://github.com/a8m/angular-filter * @author Ariel Mashraki <ariel@mashraki.co.il> * @license MIT License, http://www.opensource.org/licenses/MIT */ (function ( window, angular, undefined ) { /*jshint globalstrict:true*/ 'use strict'; var isDefined = angular.isDefined, isUndefined = angular.isUndefined, isFunction = angular.isFunction, isString = angular.isString, isNumber = angular.isNumber, isObject = angular.isObject, isArray = angular.isArray, forEach = angular.forEach, extend = angular.extend, copy = angular.copy, equals = angular.equals; /** * get an object and return array of values * @param object * @returns {Array} */ function toArray(object) { return isArray(object) ? object : Object.keys(object).map(function(key) { return object[key]; }); } /** * * @param value * @returns {boolean} */ function isNull(value) { return value === null; } /** * return if object contains partial object * @param partial{object} * @param object{object} * @returns {boolean} */ function objectContains(partial, object) { var keys = Object.keys(partial); return keys.map(function(el) { return !(!object[el] || (object[el] != partial[el])); }).indexOf(false) == -1; } /** * search for approximate pattern in string * @param word * @param pattern * @returns {*} */ function hasApproxPattern(word, pattern) { if(pattern === '') return word; var index = word.indexOf(pattern.charAt(0)); if(index === -1) return false; return hasApproxPattern(word.substr(index+1), pattern.substr(1)) } /** * return the first n element of an array, * if expression provided, is returns as long the expression return truthy * @param array * @param n {number} * @param expression {$parse} * @return array or single object */ function getFirstMatches(array, n, expression) { var result, count = ~~result; result = array.filter(function(elm) { var rest = isDefined(expression) ? (count < n && expression(elm)) : count < n; count = rest ? count+1 : count; return rest; }); return (count < 2) ? result[0] : result; } /** * Polyfill to ECMA6 String.prototype.contains */ if (!String.prototype.contains) { String.prototype.contains = function() { return String.prototype.indexOf.apply(this, arguments) !== -1; }; } /** * @ngdoc filter * @name a8m.angular * @kind function * * @description * reference to angular function */ angular.module('a8m.angular', []) .filter('isUndefined', function () { return function (input) { return angular.isUndefined(input); } }) .filter('isDefined', function() { return function (input) { return angular.isDefined(input); } }) .filter('isFunction', function() { return function (input) { return angular.isFunction(input); } }) .filter('isString', function() { return function (input) { return angular.isString(input) } }) .filter('isNumber', function() { return function (input) { return angular.isNumber(input); } }) .filter('isArray', function() { return function (input) { return angular.isArray(input); } }) .filter('isObject', function() { return function (input) { return angular.isObject(input); } }) .filter('isEqual', function() { return function (o1, o2) { return angular.equals(o1, o2); } }); /** * @ngdoc filter * @name isNull * @kind function * * @description * checks if value is null or not * @return Boolean */ angular.module('a8m.is-null', []) .filter('isNull', function () { return function(input) { return isNull(input); } }); /** * @ngdoc filter * @name after-where * @kind function * * @description * get a collection and properties object, and returns all of the items * in the collection after the first that found with the given properties. * */ angular.module('a8m.after-where', []) .filter('afterWhere', function() { return function (collection, object) { collection = (isObject(collection)) ? toArray(collection) : collection; if(!isArray(collection) || isUndefined(object)) return collection; var index = collection.map( function( elm ) { return objectContains(object, elm); }).indexOf( true ); return collection.slice((index === -1) ? 0 : index); } }); /** * @ngdoc filter * @name after * @kind function * * @description * get a collection and specified count, and returns all of the items * in the collection after the specified count. * */ angular.module('a8m.after', []) .filter('after', function() { return function (collection, count) { collection = (isObject(collection)) ? toArray(collection) : collection; return (isArray(collection)) ? collection.slice(count) : collection; } }); /** * @ngdoc filter * @name before-where * @kind function * * @description * get a collection and properties object, and returns all of the items * in the collection before the first that found with the given properties. * */ angular.module('a8m.before-where', []) .filter('beforeWhere', function() { return function (collection, object) { collection = (isObject(collection)) ? toArray(collection) : collection; if(!isArray(collection) || isUndefined(object)) return collection; var index = collection.map( function( elm ) { return objectContains(object, elm); }).indexOf( true ); return collection.slice(0, (index === -1) ? collection.length : ++index); } }); /** * @ngdoc filter * @name before * @kind function * * @description * get a collection and specified count, and returns all of the items * in the collection before the specified count. * */ angular.module('a8m.before', []) .filter('before', function() { return function (collection, count) { collection = (isObject(collection)) ? toArray(collection) : collection; return (isArray(collection)) ? collection.slice(0, (!count) ? count : --count) : collection; } }); /** * @ngdoc filter * @name concat * @kind function * * @description * get (array/object, object/array) and return merged collection * */ angular.module('a8m.concat', []) //TODO:unique option ? or use unique filter to filter result .filter('concat', [function () { return function (collection, joined) { if (isUndefined(joined)) { return collection; } if (isArray(collection)) { return (isObject(joined)) ? collection.concat(toArray(joined)) : collection.concat(joined); } if (isObject(collection)) { var array = toArray(collection); return (isObject(joined)) ? array.concat(toArray(joined)) : array.concat(joined); } return collection; }; } ]); /** * @ngdoc filter * @name contains * @kind function * * @description * Checks if given expression is present in one or more object in the collection */ angular.module('a8m.contains', []) .filter({ contains: ['$parse', containsFilter], some: ['$parse', containsFilter] }); function containsFilter( $parse ) { return function (collection, expression) { collection = (isObject(collection)) ? toArray(collection) : collection; if(!isArray(collection) || isUndefined(expression)) { return true; } return collection.some( function(elm) { return (isObject(elm) || isFunction(expression)) ? $parse(expression)(elm) : elm === expression; }); } } /** * @ngdoc filter * @name countBy * @kind function * * @description * Sorts a list into groups and returns a count for the number of objects in each group. */ angular.module('a8m.count-by', []) .filter('countBy', [ '$parse', function ( $parse ) { return function (collection, property) { var result = {}, get = $parse(property), prop; collection = (isObject(collection)) ? toArray(collection) : collection; if(!isArray(collection) || isUndefined(property)) { return collection; } collection.forEach( function( elm ) { prop = get(elm); if(!result[prop]) { result[prop] = 0; } result[prop]++; }); return result; } }]); /** * @ngdoc filter * @name every * @kind function * * @description * Checks if given expression is present in all members in the collection * */ angular.module('a8m.every', []) .filter('every', ['$parse', function($parse) { return function (collection, expression) { collection = (isObject(collection)) ? toArray(collection) : collection; if(!isArray(collection) || isUndefined(expression)) { return true; } return collection.every( function(elm) { return (isObject(elm) || isFunction(expression)) ? $parse(expression)(elm) : elm === expression; }); } }]); /** * @ngdoc filter * @name filterBy * @kind function * * @description * filter by specific properties, avoid the rest */ angular.module('a8m.filter-by', []) .filter('filterBy', ['$parse', function( $parse ) { return function(collection, properties, search) { var comparator; search = (isString(search) || isNumber(search)) ? String(search).toLowerCase() : undefined; collection = (isObject(collection)) ? toArray(collection) : collection; if(!isArray(collection) || isUndefined(search)) { return collection; } return collection.filter(function(elm) { return properties.some(function(prop) { /** * check if there is concatenate properties * example: * object: { first: 'foo', last:'bar' } * filterBy: ['first + last'] => search by full name(i.e 'foo bar') */ if(!~prop.indexOf('+')) { comparator = $parse(prop)(elm) } else { var propList = prop.replace(new RegExp('\\s', 'g'), '').split('+'); comparator = propList.reduce(function(prev, cur, index) { return (index === 1) ? $parse(prev)(elm) + ' ' + $parse(cur)(elm) : prev + ' ' + $parse(cur)(elm); }); } return (isString(comparator) || isNumber(comparator)) ? String(comparator).toLowerCase().contains(search) : false; }) }); } }]); /** * @ngdoc filter * @name first * @kind function * * @description * Gets the first element or first n elements of an array * if callback is provided, is returns as long the callback return truthy */ angular.module('a8m.first', []) .filter('first', ['$parse', function( $parse ) { return function(collection) { var n, getter, args; collection = (isObject(collection)) ? toArray(collection) : collection; if(!isArray(collection)) { return collection; } args = Array.prototype.slice.call(arguments, 1); n = (isNumber(args[0])) ? args[0] : 1; getter = (!isNumber(args[0])) ? args[0] : (!isNumber(args[1])) ? args[1] : undefined; return getFirstMatches(collection, n,(getter) ? $parse(getter) : getter); } }]); /** * @ngdoc filter * @name flatten * @kind function * * @description * Flattens a nested array (the nesting can be to any depth). * If you pass shallow, the array will only be flattened a single level */ angular.module('a8m.flatten', []) .filter('flatten', function () { return function(collection, shallow) { shallow = shallow || false; collection = (isObject(collection)) ? toArray(collection) : collection; if(!isArray(collection)) { return collection; } return (!shallow) ? flatten(collection, 0) : [].concat.apply([], collection); } }); /** * flatten nested array (the nesting can be to any depth). * @param array {Array} * @param i {int} * @returns {Array} * @private */ function flatten(array, i) { i = i || 0; if(i >= array.length) return array; if(isArray(array[i])) { return flatten(array.slice(0,i) .concat(array[i], array.slice(i+1)), i); } return flatten(array, i+1); } /** * @ngdoc filter * @name fuzzyByKey * @kind function * * @description * fuzzy string searching by key */ angular.module('a8m.fuzzy-by', []) .filter('fuzzyBy', ['$parse', function ( $parse ) { return function (collection, property, search, csensitive) { var sensitive = csensitive || false, prop, getter; collection = (isObject(collection)) ? toArray(collection) : collection; if(!isArray(collection) || isUndefined(property) || isUndefined(search)) { return collection; } getter = $parse(property); return collection.filter(function(elm) { prop = getter(elm); if(!isString(prop)) { return false; } prop = (sensitive) ? prop : prop.toLowerCase(); search = (sensitive) ? search : search.toLowerCase(); return hasApproxPattern(prop, search) !== false }) } }]); /** * @ngdoc filter * @name fuzzy * @kind function * * @description * fuzzy string searching for array of strings, objects */ angular.module('a8m.fuzzy', []) .filter('fuzzy', function () { return function (collection, search, csensitive) { var sensitive = csensitive || false; collection = (isObject(collection)) ? toArray(collection) : collection; if(!isArray(collection) || isUndefined(search)) { return collection; } search = (sensitive) ? search : search.toLowerCase(); return collection.filter(function(elm) { if(isString(elm)) { elm = (sensitive) ? elm : elm.toLowerCase(); return hasApproxPattern(elm, search) !== false } return (isObject(elm)) ? _hasApproximateKey(elm, search) : false; }); /** * checks if object has key{string} that match * to fuzzy search pattern * @param object * @param search * @returns {boolean} * @private */ function _hasApproximateKey(object, search) { var properties = Object.keys(object), prop, flag; return 0 < properties.filter(function (elm) { prop = object[elm]; //avoid iteration if we found some key that equal[performance] if(flag) return true; if (isString(prop)) { prop = (sensitive) ? prop : prop.toLowerCase(); return flag = (hasApproxPattern(prop, search) !== false); } return false; }).length; } } }); /** * @ngdoc filter * @name groupBy * @kind function * * @description * Create an object composed of keys generated from the result of running each element of a collection, * each key is an array of the elements. */ angular.module('a8m.group-by', [ 'a8m.filter-watcher' ]) .filter('groupBy', [ '$parse', 'filterWatcher', function ( $parse, filterWatcher ) { return function (collection, property) { var result, get = $parse(property), prop; if(!isObject(collection) || isUndefined(property)) { return collection; } //Add collection instance to watch list result = filterWatcher.$watch('groupBy', collection); forEach( collection, function( elm ) { prop = get(elm); if(!result[prop]) { result[prop] = []; } if(result[prop].indexOf( elm ) === -1) { result[prop].push(elm); } }); //kill instance filterWatcher.$destroy('groupBy', collection); return result; } }]); /** * @ngdoc filter * @name isEmpty * @kind function * * @description * get collection or string and return if it empty */ angular.module('a8m.is-empty', []) .filter('isEmpty', function () { return function(collection) { return (isObject(collection)) ? !toArray(collection).length : !collection.length; } }); /** * @ngdoc filter * @name last * @kind function * * @description * Gets the last element or last n elements of an array * if callback is provided, is returns as long the callback return truthy */ angular.module('a8m.last', []) .filter('last', ['$parse', function( $parse ) { return function(collection) { var n, getter, args, result, //cuz reverse change our src collection //and we don't want side effects reversed = copy(collection); reversed = (isObject(reversed)) ? toArray(reversed) : reversed; if(!isArray(reversed)) { return reversed; } args = Array.prototype.slice.call(arguments, 1); n = (isNumber(args[0])) ? args[0] : 1; getter = (!isNumber(args[0])) ? args[0] : (!isNumber(args[1])) ? args[1] : undefined; return isArray(result = getFirstMatches(reversed.reverse(), n,(getter) ? $parse(getter) : getter)) ? result.reverse() : result; } }]); /** * @ngdoc filter * @name map * @kind function * * @description * Returns a new collection of the results of each expression execution. */ angular.module('a8m.map', []) .filter('map', ['$parse', function($parse) { return function (collection, expression) { collection = (isObject(collection)) ? toArray(collection) : collection; if(!isArray(collection) || isUndefined(expression)) { return collection; } return collection.map(function (elm) { return $parse(expression)(elm); }); } }]); /** * @ngdoc filter * @name omit * @kind function * * @description * filter collection by expression */ angular.module('a8m.omit', []) .filter('omit', ['$parse', function($parse) { return function (collection, expression) { collection = (isObject(collection)) ? toArray(collection) : collection; if(!isArray(collection) || isUndefined(expression)) { return collection; } return collection.filter(function (elm) { return !($parse(expression)(elm)); }); } }]); /** * @ngdoc filter * @name omit * @kind function * * @description * filter collection by expression */ angular.module('a8m.pick', []) .filter('pick', ['$parse', function($parse) { return function (collection, expression) { collection = (isObject(collection)) ? toArray(collection) : collection; if(!isArray(collection) || isUndefined(expression)) { return collection; } return collection.filter(function (elm) { return $parse(expression)(elm); }); } }]); /** * @ngdoc filter * @name removeWith * @kind function * * @description * get collection and properties object, and removed elements * with this properties */ angular.module('a8m.remove-with', []) .filter('removeWith', function() { return function (collection, object) { if(isUndefined(object)) { return collection; } collection = (isObject(collection)) ? toArray(collection) : collection; return collection.filter(function (elm) { return !objectContains(object, elm); }); } }); /** * @ngdoc filter * @name remove * @kind function * * @description * remove specific members from collection */ angular.module('a8m.remove', []) .filter('remove', function () { return function (collection) { collection = (isObject(collection)) ? toArray(collection) : collection; var args = Array.prototype.slice.call(arguments, 1); if(!isArray(collection)) { return collection; } return collection.filter( function( member ) { return !args.some(function(nest) { return equals(nest, member); }) }); } }); /** * @ngdoc filter * @name reverse * @kind function * * @description * Reverses a string or collection */ angular.module('a8m.reverse', []) .filter('reverse',[ function () { return function (input) { input = (isObject(input)) ? toArray(input) : input; if(isString(input)) { return input.split('').reverse().join(''); } return (isArray(input)) ? input.reverse() : input; } }]); /** * @ngdoc filter * @name searchField * @kind function * * @description * for each member, join several strings field and add them to * new field called 'searchField' (use for search filtering) */ angular.module('a8m.search-field', []) .filter('searchField', ['$parse', function ($parse) { return function (collection) { var get, field; collection = (isObject(collection)) ? toArray(collection) : collection; var args = Array.prototype.slice.call(arguments, 1); if(!isArray(collection) || !args.length) { return collection; } return collection.map(function(member) { field = args.map(function(field) { get = $parse(field); return get(member); }).join(' '); //TODO(ariel):we don't wanna change the source, but I'm not sure about the performance. return extend({ searchField: field }, member); }); } }]); /** * @ngdoc filter * @name toArray * @kind function * * @description * Convert objects into stable arrays. * if addKey set to true,the filter also attaches a new property * $key to the value containing the original key that was used in * the object we are iterating over to reference the property */ angular.module('a8m.to-array', []) .filter('toArray', function() { return function (collection, addKey) { if(!isObject(collection)) { return collection; } return (!addKey) ? toArray(collection) : Object.keys(collection).map(function (key) { return extend(collection[key], { $key: key }); }); } }); /** * @ngdoc filter * @name unique/uniq * @kind function * * @description * get collection and filter duplicate members * if uniqueFilter get a property(nested to) as argument it's * filter by this property as unique identifier */ angular.module('a8m.unique', []) .filter({ unique: ['$parse', uniqFilter], uniq: ['$parse', uniqFilter] }); function uniqFilter($parse) { return function (collection, property) { collection = (isObject(collection)) ? toArray(collection) : collection; if (isUndefined(property)) { return collection.filter(function (elm, pos, self) { return self.indexOf(elm) === pos; }) } //store all unique members var uniqueItems = [], get = $parse(property); return collection.filter(function (elm) { var prop = get(elm); if(some(uniqueItems, prop)) { return false; } uniqueItems.push(prop); return true; }); //checked if the unique identifier is already exist function some(array, member) { if(isUndefined(member)) { return false; } return array.some(function(el) { return equals(el, member); }); } } } /** * @ngdoc filter * @name where * @kind function * * @description * of each element in a collection to the given properties object, * returning an array of all elements that have equivalent property values. * */ angular.module('a8m.where', []) .filter('where', function() { return function (collection, object) { if(isUndefined(object)) { return collection; } collection = (isObject(collection)) ? toArray(collection) : collection; return collection.filter(function (elm) { return objectContains(object, elm); }); } }); /** * @ngdoc filter * @name xor * @kind function * * @description * Exclusive or filter by expression */ angular.module('a8m.xor', []) .filter('xor', ['$parse', function($parse) { return function (col1, col2, expression) { expression = expression || false; col1 = (isObject(col1)) ? toArray(col1) : col1; col2 = (isObject(col2)) ? toArray(col2) : col2; if(!isArray(col1) || !isArray(col2)) return col1; return col1.concat(col2) .filter(function(elm) { return !(some(elm, col1) && some(elm, col2)); }); function some(el, col) { var getter = $parse(expression); return col.some(function(dElm) { return expression ? equals(getter(dElm), getter(el)) : equals(dElm, el); }) } } }]); /** * @ngdoc module * @name math * @description * reference to global Math object */ angular.module('a8m.math', []) .factory('$math', ['$window', function ($window) { return $window.Math; }]); /** * @ngdoc filter * @name max * @kind function * * @description * Math.max * */ angular.module('a8m.math.max', ['a8m.math']) .filter('max', ['$math', function ($math) { return function (input) { return (isArray(input)) ? $math.max.apply($math, input) : input; } }]); /** * @ngdoc filter * @name min * @kind function * * @description * Math.min * */ angular.module('a8m.math.min', ['a8m.math']) .filter('min', ['$math', function ($math) { return function (input) { return (isArray(input)) ? $math.min.apply($math, input) : input; } }]); /** * @ngdoc filter * @name Percent * @kind function * * @description * percentage between two numbers * */ angular.module('a8m.math.percent', ['a8m.math']) .filter('percent', ['$math', '$window', function ($math, $window) { return function (input, divided, round) { var divider = (isString(input)) ? $window.Number(input) : input; divided = divided || 100; round = round || false; if (!isNumber(divider) || $window.isNaN(divider)) return input; return (round) ? $math.round((divider / divided) * 100) : ((divider / divided) * 100); } }]); /** * @ngdoc filter * @name Radix * @kind function * * @description * converting decimal numbers to different bases(radix) */ angular.module('a8m.math.radix', []) .filter('radix', function () { return function (input, radix) { var RANGE = /^[2-9]$|^[1-2]\d$|^3[0-6]$/; if(!isNumber(input) || !RANGE.test(radix)) { return input; } return input.toString(radix).toUpperCase(); } }); /** * @ngdoc filter * @name sum * @kind function * * @description * Sum up all values within an array * */ angular.module('a8m.math.sum', []) .filter('sum', function () { return function (input, initial) { return (!isArray(input)) ? input : input.reduce(function(prev, curr) { return prev + curr; }, initial || 0); } }); /** * @ngdoc filter * @name endsWith * @kind function * * @description * checks whether string ends with the ends parameter. */ angular.module('a8m.ends-with', []) .filter('endsWith', function () { return function (input, ends, csensitive) { var sensitive = csensitive || false, position; if(!isString(input) || isUndefined(ends)) { return input; } input = (sensitive) ? input : input.toLowerCase(); position = input.length - ends.length; return input.indexOf((sensitive) ? ends : ends.toLowerCase(), position) !== -1; } }); /** * @ngdoc filter * @name ltrim * @kind function * * @description * Left trim. Similar to trimFilter, but only for left side. */ angular.module('a8m.ltrim', []) .filter('ltrim', function () { return function(input, chars) { var trim = chars || '\\s'; if(!isString(input)) { return input; } return input.replace(new RegExp('^' + trim + '+'), ''); } }); /** * @ngdoc filter * @name repeat * @kind function * * @description * Repeats a string n times */ angular.module('a8m.repeat', []) .filter('repeat',[ function () { return function (input, n, separator) { var times = ~~n; if(!isString(input)) { return input; } return (!times) ? input : strRepeat(input, --n, separator || ''); } }]); /** * Repeats a string n times with given separator * @param str string to repeat * @param n number of times * @param sep separator * @returns {*} */ function strRepeat(str, n, sep) { if(!n) { return str; } return str + sep + strRepeat(str, --n, sep); } /** * @ngdoc filter * @name rtrim * @kind function * * @description * Right trim. Similar to trimFilter, but only for right side. */ angular.module('a8m.rtrim', []) .filter('rtrim', function () { return function(input, chars) { var trim = chars || '\\s'; if(!isString(input)) { return input; } return input.replace(new RegExp(trim + '+$'), ''); } }); /** * @ngdoc filter * @name slugify * @kind function * * @description * remove spaces from string, replace with "-" or given argument */ angular.module('a8m.slugify', []) .filter('slugify',[ function () { return function (input, sub) { var replace = sub || '-'; if(isString(input)) { return input.toLowerCase() .replace(/\s+/g, replace); } return input; } }]); /** * @ngdoc filter * @name startWith * @kind function * * @description * checks whether string starts with the starts parameter. */ angular.module('a8m.starts-with', []) .filter('startsWith', function () { return function (input, start, csensitive) { var sensitive = csensitive || false; if(!isString(input) || isUndefined(start)) { return input; } input = (sensitive) ? input : input.toLowerCase(); return !input.indexOf((sensitive) ? start : start.toLowerCase()); } }); /** * @ngdoc filter * @name stringular * @kind function * * @description * get string with {n} and replace match with enumeration values */ angular.module('a8m.stringular', []) .filter('stringular', function () { return function(input) { var args = Array.prototype.slice.call(arguments, 1); return input.replace(/{(\d+)}/g, function (match, number) { return isUndefined(args[number]) ? match : args[number]; }); } }); /** * @ngdoc filter * @name stripTags * @kind function * * @description * strip html tags from string */ angular.module('a8m.strip-tags', []) .filter('stripTags', function () { return function(input) { if(isString(input)) { return input.replace(/<\S[^><]*>/g, ''); } return input; } }); /** * @ngdoc filter * @name trim * @kind function * * @description * Strip whitespace (or other characters) from the beginning and end of a string */ angular.module('a8m.trim', []) .filter('trim', function () { return function(input, chars) { var trim = chars || '\\s'; if(!isString(input)) { return input; } return input.replace(new RegExp('^' + trim + '+|' + trim + '+$', 'g'), ''); } }); /** * @ngdoc filter * @name truncate * @kind function * * @description * truncates a string given a specified length, providing a custom string to denote an omission. */ angular.module('a8m.truncate', []) .filter('truncate', function () { return function(input, length, suffix, preserve) { length = isUndefined(length) ? input.length : length; preserve = preserve || false; suffix = suffix || ''; if(!isString(input) || (input.length <= length)) return input; return input.substring(0, (preserve) ? ((input.indexOf(' ', length) === -1) ? input.length : input.indexOf(' ', length)) : length) + suffix; }; }); /** * @ngdoc filter * @name ucfirst * @kind function * * @description * ucfirst * */ angular.module('a8m.ucfirst', []) .filter('ucfirst', [function() { return function(input) { return angular.isString(input) ? input.split(' ') .map(function (char) { return char.charAt(0).toUpperCase() + char.substring(1); }).join(' ') : input; } }]); /** * @ngdoc filter * @name uriEncode * @kind function * * @description * get string as parameter and return encoded string */ angular.module('a8m.uri-encode', []) .filter('uriEncode',['$window', function ($window) { return function (input) { if(isString(input)) { return $window.encodeURI(input); } return input; } }]); /** * @ngdoc filter * @name wrap * @kind function * * @description * Wrap a string with another string */ angular.module('a8m.wrap', []) .filter('wrap', function () { return function(input, wrap, ends) { if(!isString(input) || isUndefined(wrap)) { return input; } return [wrap, input, ends || wrap].join(''); } }); /** * @ngdoc provider * @name filterWatcher * @kind function * * @description * filterWatchers is a _privateProvider * It's created to solve the problem of $rootScope:infdig(Infinite $digest loop) when using * some filters on the view. */ angular.module('a8m.filter-watcher', []) .provider('filterWatcher', function() { var filterPrefix = '_$$'; /** * @description * change the prefix name for filters on watch phase * @param prefix * @returns {filterWatcher} */ this.setPrefix = function(prefix) { filterPrefix = prefix; return this; }; this.$get = ['$window', function($window) { var $$timeout = $window.setTimeout; /** * @description * return the filter full name * @param name * @returns {string} * @private */ function _getFullName(name) { return filterPrefix + name; } /** * @description * return whether or not this object is watched in current phase * @param fName * @param object * @returns {boolean} * @private */ function _isWatched(fName, object) { return isDefined(object[fName]); } /** * @description * return the object.$$filterName instance in current phase * @param name * @param object * @private */ function _watch(name, object) { var fName = _getFullName(name); if(!_isWatched(fName, object)) { //Create new instance Object.defineProperty(object, fName, { enumerable: false, configurable: true, value: {} }); } return object[fName]; } /** * @description * destroy/delete current watch instance * @param name * @param object * @private */ function _destroy(name, object) { return $$timeout(function() { delete object[_getFullName(name)]; }); } return { $watch: _watch, $destroy: _destroy } }]; }); /** * @ngdoc module * @name angular.filters * @description * Bunch of useful filters for angularJS */ angular.module('angular.filter', [ 'a8m.ucfirst', 'a8m.uri-encode', 'a8m.slugify', 'a8m.strip-tags', 'a8m.stringular', 'a8m.truncate', 'a8m.starts-with', 'a8m.ends-with', 'a8m.wrap', 'a8m.trim', 'a8m.ltrim', 'a8m.rtrim', 'a8m.repeat', 'a8m.to-array', 'a8m.concat', 'a8m.contains', 'a8m.unique', 'a8m.is-empty', 'a8m.after', 'a8m.after-where', 'a8m.before', 'a8m.before-where', 'a8m.where', 'a8m.reverse', 'a8m.remove', 'a8m.remove-with', 'a8m.group-by', 'a8m.count-by', 'a8m.search-field', 'a8m.fuzzy-by', 'a8m.fuzzy', 'a8m.omit', 'a8m.pick', 'a8m.every', 'a8m.filter-by', 'a8m.xor', 'a8m.map', 'a8m.first', 'a8m.last', 'a8m.flatten', 'a8m.math', 'a8m.math.max', 'a8m.math.min', 'a8m.math.percent', 'a8m.math.radix', 'a8m.math.sum', 'a8m.angular', 'a8m.is-null', 'a8m.filter-watcher' ]); })( window, window.angular );
sreym/cdnjs
ajax/libs/angular-filter/0.4.4/angular-filter.js
JavaScript
mit
36,743
/* * Foundation Responsive Library * http://foundation.zurb.com * Copyright 2014, ZURB * Free to use under the MIT license. * http://www.opensource.org/licenses/mit-license.php */ (function(e,t,n,r){"use strict";function l(e){if(typeof e=="string"||e instanceof String)e=e.replace(/^['\\/"]+|(;\s?})+|['\\/"]+$/g,"");return e}var i=function(t){var n=t.length,r=e("head");while(n--)r.has("."+t[n]).length===0&&r.append('<meta class="'+t[n]+'" />')};i(["foundation-mq-small","foundation-mq-medium","foundation-mq-large","foundation-mq-xlarge","foundation-mq-xxlarge","foundation-data-attribute-namespace"]),e(function(){typeof FastClick!="undefined"&&typeof n.body!="undefined"&&FastClick.attach(n.body)});var s=function(t,r){if(typeof t=="string"){if(r){var i;if(r.jquery){i=r[0];if(!i)return r}else i=r;return e(i.querySelectorAll(t))}return e(n.querySelectorAll(t))}return e(t,r)},o=function(e){var t=[];return e||t.push("data"),this.namespace.length>0&&t.push(this.namespace),t.push(this.name),t.join("-")},u=function(e){var t=e.split("-"),n=t.length,r=[];while(n--)n!==0?r.push(t[n]):this.namespace.length>0?r.push(this.namespace,t[n]):r.push(t[n]);return r.reverse().join("-")},a=function(t,n){var r=this,i=!s(this).data(this.attr_name(!0));s(this.scope).is("["+this.attr_name()+"]")?(s(this.scope).data(this.attr_name(!0)+"-init",e.extend({},this.settings,n||t,this.data_options(s(this.scope)))),i&&this.events(this.scope)):s("["+this.attr_name()+"]",this.scope).each(function(){var i=!s(this).data(r.attr_name(!0)+"-init");s(this).data(r.attr_name(!0)+"-init",e.extend({},r.settings,n||t,r.data_options(s(this)))),i&&r.events(this)});if(typeof t=="string")return this[t].call(this,n)},f=function(e,t){function n(){t(e[0])}function r(){this.one("load",n);if(/MSIE (\d+\.\d+);/.test(navigator.userAgent)){var e=this.attr("src"),t=e.match(/\?/)?"&":"?";t+="random="+(new Date).getTime(),this.attr("src",e+t)}}if(!e.attr("src")){n();return}e[0].complete||e[0].readyState===4?n():r.call(e)};t.matchMedia=t.matchMedia||function(e){var t,n=e.documentElement,r=n.firstElementChild||n.firstChild,i=e.createElement("body"),s=e.createElement("div");return s.id="mq-test-1",s.style.cssText="position:absolute;top:-100em",i.style.background="none",i.appendChild(s),function(e){return s.innerHTML='&shy;<style media="'+e+'"> #mq-test-1 { width: 42px; }</style>',n.insertBefore(i,r),t=s.offsetWidth===42,n.removeChild(i),{matches:t,media:e}}}(n),function(e){function a(){n&&(s(a),u&&jQuery.fx.tick())}var n,r=0,i=["webkit","moz"],s=t.requestAnimationFrame,o=t.cancelAnimationFrame,u="undefined"!=typeof jQuery.fx;for(;r<i.length&&!s;r++)s=t[i[r]+"RequestAnimationFrame"],o=o||t[i[r]+"CancelAnimationFrame"]||t[i[r]+"CancelRequestAnimationFrame"];s?(t.requestAnimationFrame=s,t.cancelAnimationFrame=o,u&&(jQuery.fx.timer=function(e){e()&&jQuery.timers.push(e)&&!n&&(n=!0,a())},jQuery.fx.stop=function(){n=!1})):(t.requestAnimationFrame=function(e){var n=(new Date).getTime(),i=Math.max(0,16-(n-r)),s=t.setTimeout(function(){e(n+i)},i);return r=n+i,s},t.cancelAnimationFrame=function(e){clearTimeout(e)})}(jQuery),t.Foundation={name:"Foundation",version:"5.3.3",media_queries:{small:s(".foundation-mq-small").css("font-family").replace(/^[\/\\'"]+|(;\s?})+|[\/\\'"]+$/g,""),medium:s(".foundation-mq-medium").css("font-family").replace(/^[\/\\'"]+|(;\s?})+|[\/\\'"]+$/g,""),large:s(".foundation-mq-large").css("font-family").replace(/^[\/\\'"]+|(;\s?})+|[\/\\'"]+$/g,""),xlarge:s(".foundation-mq-xlarge").css("font-family").replace(/^[\/\\'"]+|(;\s?})+|[\/\\'"]+$/g,""),xxlarge:s(".foundation-mq-xxlarge").css("font-family").replace(/^[\/\\'"]+|(;\s?})+|[\/\\'"]+$/g,"")},stylesheet:e("<style></style>").appendTo("head")[0].sheet,global:{namespace:r},init:function(e,n,r,i,o){var u=[e,r,i,o],a=[];this.rtl=/rtl/i.test(s("html").attr("dir")),this.scope=e||this.scope,this.set_namespace();if(n&&typeof n=="string"&&!/reflow/i.test(n))this.libs.hasOwnProperty(n)&&a.push(this.init_lib(n,u));else for(var f in this.libs)a.push(this.init_lib(f,n));return s(t).load(function(){s(t).trigger("resize.fndtn.clearing").trigger("resize.fndtn.dropdown").trigger("resize.fndtn.equalizer").trigger("resize.fndtn.interchange").trigger("resize.fndtn.joyride").trigger("resize.fndtn.magellan").trigger("resize.fndtn.topbar").trigger("resize.fndtn.slider")}),e},init_lib:function(t,n){return this.libs.hasOwnProperty(t)?(this.patch(this.libs[t]),n&&n.hasOwnProperty(t)?(typeof this.libs[t].settings!="undefined"?e.extend(!0,this.libs[t].settings,n[t]):typeof this.libs[t].defaults!="undefined"&&e.extend(!0,this.libs[t].defaults,n[t]),this.libs[t].init.apply(this.libs[t],[this.scope,n[t]])):(n=n instanceof Array?n:new Array(n),this.libs[t].init.apply(this.libs[t],n))):function(){}},patch:function(e){e.scope=this.scope,e.namespace=this.global.namespace,e.rtl=this.rtl,e.data_options=this.utils.data_options,e.attr_name=o,e.add_namespace=u,e.bindings=a,e.S=this.utils.S},inherit:function(e,t){var n=t.split(" "),r=n.length;while(r--)this.utils.hasOwnProperty(n[r])&&(e[n[r]]=this.utils[n[r]])},set_namespace:function(){var t=this.global.namespace===r?e(".foundation-data-attribute-namespace").css("font-family"):this.global.namespace;this.global.namespace=t===r||/false/i.test(t)?"":t},libs:{},utils:{S:s,throttle:function(e,t){var n=null;return function(){var r=this,i=arguments;n==null&&(n=setTimeout(function(){e.apply(r,i),n=null},t))}},debounce:function(e,t,n){var r,i;return function(){var s=this,o=arguments,u=function(){r=null,n||(i=e.apply(s,o))},a=n&&!r;return clearTimeout(r),r=setTimeout(u,t),a&&(i=e.apply(s,o)),i}},data_options:function(t,n){function f(e){return!isNaN(e-0)&&e!==null&&e!==""&&e!==!1&&e!==!0}function l(t){return typeof t=="string"?e.trim(t):t}n=n||"options";var r={},i,s,o,u=function(e){var t=Foundation.global.namespace;return t.length>0?e.data(t+"-"+n):e.data(n)},a=u(t);if(typeof a=="object")return a;o=(a||":").split(";"),i=o.length;while(i--)s=o[i].split(":"),s=[s[0],s.slice(1).join(":")],/true/i.test(s[1])&&(s[1]=!0),/false/i.test(s[1])&&(s[1]=!1),f(s[1])&&(s[1].indexOf(".")===-1?s[1]=parseInt(s[1],10):s[1]=parseFloat(s[1])),s.length===2&&s[0].length>0&&(r[l(s[0])]=l(s[1]));return r},register_media:function(t,n){Foundation.media_queries[t]===r&&(e("head").append('<meta class="'+n+'"/>'),Foundation.media_queries[t]=l(e("."+n).css("font-family")))},add_custom_rule:function(e,t){if(t===r&&Foundation.stylesheet)Foundation.stylesheet.insertRule(e,Foundation.stylesheet.cssRules.length);else{var n=Foundation.media_queries[t];n!==r&&Foundation.stylesheet.insertRule("@media "+Foundation.media_queries[t]+"{ "+e+" }")}},image_loaded:function(e,t){var n=this,r=e.length;r===0&&t(e),e.each(function(){f(n.S(this),function(){r-=1,r===0&&t(e)})})},random_str:function(){return this.fidx||(this.fidx=0),this.prefix=this.prefix||[this.name||"F",(+(new Date)).toString(36)].join("-"),this.prefix+(this.fidx++).toString(36)}}},e.fn.foundation=function(){var e=Array.prototype.slice.call(arguments,0);return this.each(function(){return Foundation.init.apply(Foundation,[this].concat(e)),this})}})(jQuery,window,window.document),function(e,t,n,r){"use strict";Foundation.libs.slider={name:"slider",version:"5.3.3",settings:{start:0,end:100,step:1,initial:null,display_selector:"",vertical:!1,on_change:function(){}},cache:{},init:function(e,t,n){Foundation.inherit(this,"throttle"),this.bindings(t,n),this.reflow()},events:function(){var n=this;e(this.scope).off(".slider").on("mousedown.fndtn.slider touchstart.fndtn.slider pointerdown.fndtn.slider","["+n.attr_name()+"]:not(.disabled, [disabled]) .range-slider-handle",function(t){n.cache.active||(t.preventDefault(),n.set_active_slider(e(t.target)))}).on("mousemove.fndtn.slider touchmove.fndtn.slider pointermove.fndtn.slider",function(r){if(!!n.cache.active){r.preventDefault();if(e.data(n.cache.active[0],"settings").vertical){var i=0;r.pageY||(i=t.scrollY),n.calculate_position(n.cache.active,(r.pageY||r.originalEvent.clientY||r.originalEvent.touches[0].clientY||r.currentPoint.y)+i)}else n.calculate_position(n.cache.active,r.pageX||r.originalEvent.clientX||r.originalEvent.touches[0].clientX||r.currentPoint.x)}}).on("mouseup.fndtn.slider touchend.fndtn.slider pointerup.fndtn.slider",function(e){n.remove_active_slider()}).on("change.fndtn.slider",function(e){n.settings.on_change()}),n.S(t).on("resize.fndtn.slider",n.throttle(function(e){n.reflow()},300))},set_active_slider:function(e){this.cache.active=e},remove_active_slider:function(){this.cache.active=null},calculate_position:function(t,n){var r=this,i=e.data(t[0],"settings"),s=e.data(t[0],"handle_l"),o=e.data(t[0],"handle_o"),u=e.data(t[0],"bar_l"),a=e.data(t[0],"bar_o");requestAnimationFrame(function(){var e;Foundation.rtl&&!i.vertical?e=r.limit_to((a+u-n)/u,0,1):e=r.limit_to((n-a)/u,0,1),e=i.vertical?1-e:e;var s=r.normalized_value(e,i.start,i.end,i.step);r.set_ui(t,s)})},set_ui:function(t,n){var r=e.data(t[0],"settings"),i=e.data(t[0],"handle_l"),s=e.data(t[0],"bar_l"),o=this.normalized_percentage(n,r.start,r.end),u=o*(s-i)-1,a=o*100;Foundation.rtl&&!r.vertical&&(u=-u),u=r.vertical?-u+s-i+1:u,this.set_translate(t,u,r.vertical),r.vertical?t.siblings(".range-slider-active-segment").css("height",a+"%"):t.siblings(".range-slider-active-segment").css("width",a+"%"),t.parent().attr(this.attr_name(),n).trigger("change").trigger("change.fndtn.slider"),t.parent().children("input[type=hidden]").val(n),r.input_id!=""&&e(r.display_selector).each(function(){this.hasOwnProperty("value")?e(this).val(n):e(this).text(n)})},normalized_percentage:function(e,t,n){return Math.min(1,(e-t)/(n-t))},normalized_value:function(e,t,n,r){var i=n-t,s=e*i,o=(s-s%r)/r,u=s%r,a=u>=r*.5?r:0;return o*r+a+t},set_translate:function(t,n,r){r?e(t).css("-webkit-transform","translateY("+n+"px)").css("-moz-transform","translateY("+n+"px)").css("-ms-transform","translateY("+n+"px)").css("-o-transform","translateY("+n+"px)").css("transform","translateY("+n+"px)"):e(t).css("-webkit-transform","translateX("+n+"px)").css("-moz-transform","translateX("+n+"px)").css("-ms-transform","translateX("+n+"px)").css("-o-transform","translateX("+n+"px)").css("transform","translateX("+n+"px)")},limit_to:function(e,t,n){return Math.min(Math.max(e,t),n)},initialize_settings:function(t){var n=e.extend({},this.settings,this.data_options(e(t).parent()));n.vertical?(e.data(t,"bar_o",e(t).parent().offset().top),e.data(t,"bar_l",e(t).parent().outerHeight()),e.data(t,"handle_o",e(t).offset().top),e.data(t,"handle_l",e(t).outerHeight())):(e.data(t,"bar_o",e(t).parent().offset().left),e.data(t,"bar_l",e(t).parent().outerWidth()),e.data(t,"handle_o",e(t).offset().left),e.data(t,"handle_l",e(t).outerWidth())),e.data(t,"bar",e(t).parent()),e.data(t,"settings",n)},set_initial_position:function(t){var n=e.data(t.children(".range-slider-handle")[0],"settings"),r=n.initial?n.initial:Math.floor((n.end-n.start)*.5/n.step)*n.step+n.start,i=t.children(".range-slider-handle");this.set_ui(i,r)},set_value:function(t){var n=this;e("["+n.attr_name()+"]",this.scope).each(function(){e(this).attr(n.attr_name(),t)}),!e(this.scope).attr(n.attr_name())||e(this.scope).attr(n.attr_name(),t),n.reflow()},reflow:function(){var t=this;t.S("["+this.attr_name()+"]").each(function(){var n=e(this).children(".range-slider-handle")[0],r=e(this).attr(t.attr_name());t.initialize_settings(n),r?t.set_ui(e(n),parseFloat(r)):t.set_initial_position(e(this))})}}}(jQuery,window,window.document),function(e,t,n,r){"use strict";var i=i||!1;Foundation.libs.joyride={name:"joyride",version:"5.3.3",defaults:{expose:!1,modal:!0,keyboard:!0,tip_location:"bottom",nub_position:"auto",scroll_speed:1500,scroll_animation:"linear",timer:0,start_timer_on_click:!0,start_offset:0,next_button:!0,prev_button:!0,tip_animation:"fade",pause_after:[],exposed:[],tip_animation_fade_speed:300,cookie_monster:!1,cookie_name:"joyride",cookie_domain:!1,cookie_expires:365,tip_container:"body",abort_on_close:!0,tip_location_patterns:{top:["bottom"],bottom:[],left:["right","top","bottom"],right:["left","top","bottom"]},post_ride_callback:function(){},post_step_callback:function(){},pre_step_callback:function(){},pre_ride_callback:function(){},post_expose_callback:function(){},template:{link:'<a href="#close" class="joyride-close-tip">&times;</a>',timer:'<div class="joyride-timer-indicator-wrap"><span class="joyride-timer-indicator"></span></div>',tip:'<div class="joyride-tip-guide"><span class="joyride-nub"></span></div>',wrapper:'<div class="joyride-content-wrapper"></div>',button:'<a href="#" class="small button joyride-next-tip"></a>',prev_button:'<a href="#" class="small button joyride-prev-tip"></a>',modal:'<div class="joyride-modal-bg"></div>',expose:'<div class="joyride-expose-wrapper"></div>',expose_cover:'<div class="joyride-expose-cover"></div>'},expose_add_class:""},init:function(t,n,r){Foundation.inherit(this,"throttle random_str"),this.settings=this.settings||e.extend({},this.defaults,r||n),this.bindings(n,r)},go_next:function(){this.settings.$li.next().length<1?this.end():this.settings.timer>0?(clearTimeout(this.settings.automate),this.hide(),this.show(),this.startTimer()):(this.hide(),this.show())},go_prev:function(){this.settings.$li.prev().length<1||(this.settings.timer>0?(clearTimeout(this.settings.automate),this.hide(),this.show(null,!0),this.startTimer()):(this.hide(),this.show(null,!0)))},events:function(){var n=this;e(this.scope).off(".joyride").on("click.fndtn.joyride",".joyride-next-tip, .joyride-modal-bg",function(e){e.preventDefault(),this.go_next()}.bind(this)).on("click.fndtn.joyride",".joyride-prev-tip",function(e){e.preventDefault(),this.go_prev()}.bind(this)).on("click.fndtn.joyride",".joyride-close-tip",function(e){e.preventDefault(),this.end(this.settings.abort_on_close)}.bind(this)).on("keyup.joyride",function(e){if(!this.settings.keyboard)return;switch(e.which){case 39:e.preventDefault(),this.go_next();break;case 37:e.preventDefault(),this.go_prev();break;case 27:e.preventDefault(),this.end(this.settings.abort_on_close)}}.bind(this)),e(t).off(".joyride").on("resize.fndtn.joyride",n.throttle(function(){if(e("["+n.attr_name()+"]").length>0&&n.settings.$next_tip&&n.settings.riding){if(n.settings.exposed.length>0){var t=e(n.settings.exposed);t.each(function(){var t=e(this);n.un_expose(t),n.expose(t)})}n.is_phone()?n.pos_phone():n.pos_default(!1)}},100))},start:function(){var t=this,n=e("["+this.attr_name()+"]",this.scope),r=["timer","scrollSpeed","startOffset","tipAnimationFadeSpeed","cookieExpires"],i=r.length;if(!n.length>0)return;this.settings.init||this.events(),this.settings=n.data(this.attr_name(!0)+"-init"),this.settings.$content_el=n,this.settings.$body=e(this.settings.tip_container),this.settings.body_offset=e(this.settings.tip_container).position(),this.settings.$tip_content=this.settings.$content_el.find("> li"),this.settings.paused=!1,this.settings.attempts=0,this.settings.riding=!0,typeof e.cookie!="function"&&(this.settings.cookie_monster=!1);if(!this.settings.cookie_monster||this.settings.cookie_monster&&!e.cookie(this.settings.cookie_name))this.settings.$tip_content.each(function(n){var s=e(this);this.settings=e.extend({},t.defaults,t.data_options(s));var o=i;while(o--)t.settings[r[o]]=parseInt(t.settings[r[o]],10);t.create({$li:s,index:n})}),!this.settings.start_timer_on_click&&this.settings.timer>0?(this.show("init"),this.startTimer()):this.show("init")},resume:function(){this.set_li(),this.show()},tip_template:function(t){var n,r;return t.tip_class=t.tip_class||"",n=e(this.settings.template.tip).addClass(t.tip_class),r=e.trim(e(t.li).html())+this.prev_button_text(t.prev_button_text,t.index)+this.button_text(t.button_text)+this.settings.template.link+this.timer_instance(t.index),n.append(e(this.settings.template.wrapper)),n.first().attr(this.add_namespace("data-index"),t.index),e(".joyride-content-wrapper",n).append(r),n[0]},timer_instance:function(t){var n;return t===0&&this.settings.start_timer_on_click&&this.settings.timer>0||this.settings.timer===0?n="":n=e(this.settings.template.timer)[0].outerHTML,n},button_text:function(t){return this.settings.tip_settings.next_button?(t=e.trim(t)||"Next",t=e(this.settings.template.button).append(t)[0].outerHTML):t="",t},prev_button_text:function(t,n){return this.settings.tip_settings.prev_button?(t=e.trim(t)||"Previous",n==0?t=e(this.settings.template.prev_button).append(t).addClass("disabled")[0].outerHTML:t=e(this.settings.template.prev_button).append(t)[0].outerHTML):t="",t},create:function(t){this.settings.tip_settings=e.extend({},this.settings,this.data_options(t.$li));var n=t.$li.attr(this.add_namespace("data-button"))||t.$li.attr(this.add_namespace("data-text")),r=t.$li.attr(this.add_namespace("data-button-prev"))||t.$li.attr(this.add_namespace("data-prev-text")),i=t.$li.attr("class"),s=e(this.tip_template({tip_class:i,index:t.index,button_text:n,prev_button_text:r,li:t.$li}));e(this.settings.tip_container).append(s)},show:function(t,n){var i=null;this.settings.$li===r||e.inArray(this.settings.$li.index(),this.settings.pause_after)===-1?(this.settings.paused?this.settings.paused=!1:this.set_li(t,n),this.settings.attempts=0,this.settings.$li.length&&this.settings.$target.length>0?(t&&(this.settings.pre_ride_callback(this.settings.$li.index(),this.settings.$next_tip),this.settings.modal&&this.show_modal()),this.settings.pre_step_callback(this.settings.$li.index(),this.settings.$next_tip),this.settings.modal&&this.settings.expose&&this.expose(),this.settings.tip_settings=e.extend({},this.settings,this.data_options(this.settings.$li)),this.settings.timer=parseInt(this.settings.timer,10),this.settings.tip_settings.tip_location_pattern=this.settings.tip_location_patterns[this.settings.tip_settings.tip_location],/body/i.test(this.settings.$target.selector)||this.scroll_to(),this.is_phone()?this.pos_phone(!0):this.pos_default(!0),i=this.settings.$next_tip.find(".joyride-timer-indicator"),/pop/i.test(this.settings.tip_animation)?(i.width(0),this.settings.timer>0?(this.settings.$next_tip.show(),setTimeout(function(){i.animate({width:i.parent().width()},this.settings.timer,"linear")}.bind(this),this.settings.tip_animation_fade_speed)):this.settings.$next_tip.show()):/fade/i.test(this.settings.tip_animation)&&(i.width(0),this.settings.timer>0?(this.settings.$next_tip.fadeIn(this.settings.tip_animation_fade_speed).show(),setTimeout(function(){i.animate({width:i.parent().width()},this.settings.timer,"linear")}.bind(this),this.settings.tip_animation_fade_speed)):this.settings.$next_tip.fadeIn(this.settings.tip_animation_fade_speed)),this.settings.$current_tip=this.settings.$next_tip):this.settings.$li&&this.settings.$target.length<1?this.show():this.end()):this.settings.paused=!0},is_phone:function(){return matchMedia(Foundation.media_queries.small).matches&&!matchMedia(Foundation.media_queries.medium).matches},hide:function(){this.settings.modal&&this.settings.expose&&this.un_expose(),this.settings.modal||e(".joyride-modal-bg").hide(),this.settings.$current_tip.css("visibility","hidden"),setTimeout(e.proxy(function(){this.hide(),this.css("visibility","visible")},this.settings.$current_tip),0),this.settings.post_step_callback(this.settings.$li.index(),this.settings.$current_tip)},set_li:function(e,t){e?(this.settings.$li=this.settings.$tip_content.eq(this.settings.start_offset),this.set_next_tip(),this.settings.$current_tip=this.settings.$next_tip):(t?this.settings.$li=this.settings.$li.prev():this.settings.$li=this.settings.$li.next(),this.set_next_tip()),this.set_target()},set_next_tip:function(){this.settings.$next_tip=e(".joyride-tip-guide").eq(this.settings.$li.index()),this.settings.$next_tip.data("closed","")},set_target:function(){var t=this.settings.$li.attr(this.add_namespace("data-class")),r=this.settings.$li.attr(this.add_namespace("data-id")),i=function(){return r?e(n.getElementById(r)):t?e("."+t).first():e("body")};this.settings.$target=i()},scroll_to:function(){var n,r;n=e(t).height()/2,r=Math.ceil(this.settings.$target.offset().top-n+this.settings.$next_tip.outerHeight()),r!=0&&e("html, body").stop().animate({scrollTop:r},this.settings.scroll_speed,"swing")},paused:function(){return e.inArray(this.settings.$li.index()+1,this.settings.pause_after)===-1},restart:function(){this.hide(),this.settings.$li=r,this.show("init")},pos_default:function(e){var t=this.settings.$next_tip.find(".joyride-nub"),n=Math.ceil(t.outerWidth()/2),r=Math.ceil(t.outerHeight()/2),i=e||!1;i&&(this.settings.$next_tip.css("visibility","hidden"),this.settings.$next_tip.show());if(!/body/i.test(this.settings.$target.selector)){var s=this.settings.tip_settings.tipAdjustmentY?parseInt(this.settings.tip_settings.tipAdjustmentY):0,o=this.settings.tip_settings.tipAdjustmentX?parseInt(this.settings.tip_settings.tipAdjustmentX):0;this.bottom()?(this.rtl?this.settings.$next_tip.css({top:this.settings.$target.offset().top+r+this.settings.$target.outerHeight()+s,left:this.settings.$target.offset().left+this.settings.$target.outerWidth()-this.settings.$next_tip.outerWidth()+o}):this.settings.$next_tip.css({top:this.settings.$target.offset().top+r+this.settings.$target.outerHeight()+s,left:this.settings.$target.offset().left+o}),this.nub_position(t,this.settings.tip_settings.nub_position,"top")):this.top()?(this.rtl?this.settings.$next_tip.css({top:this.settings.$target.offset().top-this.settings.$next_tip.outerHeight()-r+s,left:this.settings.$target.offset().left+this.settings.$target.outerWidth()-this.settings.$next_tip.outerWidth()}):this.settings.$next_tip.css({top:this.settings.$target.offset().top-this.settings.$next_tip.outerHeight()-r+s,left:this.settings.$target.offset().left+o}),this.nub_position(t,this.settings.tip_settings.nub_position,"bottom")):this.right()?(this.settings.$next_tip.css({top:this.settings.$target.offset().top+s,left:this.settings.$target.outerWidth()+this.settings.$target.offset().left+n+o}),this.nub_position(t,this.settings.tip_settings.nub_position,"left")):this.left()&&(this.settings.$next_tip.css({top:this.settings.$target.offset().top+s,left:this.settings.$target.offset().left-this.settings.$next_tip.outerWidth()-n+o}),this.nub_position(t,this.settings.tip_settings.nub_position,"right")),!this.visible(this.corners(this.settings.$next_tip))&&this.settings.attempts<this.settings.tip_settings.tip_location_pattern.length&&(t.removeClass("bottom").removeClass("top").removeClass("right").removeClass("left"),this.settings.tip_settings.tip_location=this.settings.tip_settings.tip_location_pattern[this.settings.attempts],this.settings.attempts++,this.pos_default())}else this.settings.$li.length&&this.pos_modal(t);i&&(this.settings.$next_tip.hide(),this.settings.$next_tip.css("visibility","visible"))},pos_phone:function(t){var n=this.settings.$next_tip.outerHeight(),r=this.settings.$next_tip.offset(),i=this.settings.$target.outerHeight(),s=e(".joyride-nub",this.settings.$next_tip),o=Math.ceil(s.outerHeight()/2),u=t||!1;s.removeClass("bottom").removeClass("top").removeClass("right").removeClass("left"),u&&(this.settings.$next_tip.css("visibility","hidden"),this.settings.$next_tip.show()),/body/i.test(this.settings.$target.selector)?this.settings.$li.length&&this.pos_modal(s):this.top()?(this.settings.$next_tip.offset({top:this.settings.$target.offset().top-n-o}),s.addClass("bottom")):(this.settings.$next_tip.offset({top:this.settings.$target.offset().top+i+o}),s.addClass("top")),u&&(this.settings.$next_tip.hide(),this.settings.$next_tip.css("visibility","visible"))},pos_modal:function(e){this.center(),e.hide(),this.show_modal()},show_modal:function(){if(!this.settings.$next_tip.data("closed")){var t=e(".joyride-modal-bg");t.length<1&&e("body").append(this.settings.template.modal).show(),/pop/i.test(this.settings.tip_animation)?t.show():t.fadeIn(this.settings.tip_animation_fade_speed)}},expose:function(){var n,r,i,s,o,u="expose-"+this.random_str(6);if(arguments.length>0&&arguments[0]instanceof e)i=arguments[0];else{if(!this.settings.$target||!!/body/i.test(this.settings.$target.selector))return!1;i=this.settings.$target}if(i.length<1)return t.console&&console.error("element not valid",i),!1;n=e(this.settings.template.expose),this.settings.$body.append(n),n.css({top:i.offset().top,left:i.offset().left,width:i.outerWidth(!0),height:i.outerHeight(!0)}),r=e(this.settings.template.expose_cover),s={zIndex:i.css("z-index"),position:i.css("position")},o=i.attr("class")==null?"":i.attr("class"),i.css("z-index",parseInt(n.css("z-index"))+1),s.position=="static"&&i.css("position","relative"),i.data("expose-css",s),i.data("orig-class",o),i.attr("class",o+" "+this.settings.expose_add_class),r.css({top:i.offset().top,left:i.offset().left,width:i.outerWidth(!0),height:i.outerHeight(!0)}),this.settings.modal&&this.show_modal(),this.settings.$body.append(r),n.addClass(u),r.addClass(u),i.data("expose",u),this.settings.post_expose_callback(this.settings.$li.index(),this.settings.$next_tip,i),this.add_exposed(i)},un_expose:function(){var n,r,i,s,o,u=!1;if(arguments.length>0&&arguments[0]instanceof e)r=arguments[0];else{if(!this.settings.$target||!!/body/i.test(this.settings.$target.selector))return!1;r=this.settings.$target}if(r.length<1)return t.console&&console.error("element not valid",r),!1;n=r.data("expose"),i=e("."+n),arguments.length>1&&(u=arguments[1]),u===!0?e(".joyride-expose-wrapper,.joyride-expose-cover").remove():i.remove(),s=r.data("expose-css"),s.zIndex=="auto"?r.css("z-index",""):r.css("z-index",s.zIndex),s.position!=r.css("position")&&(s.position=="static"?r.css("position",""):r.css("position",s.position)),o=r.data("orig-class"),r.attr("class",o),r.removeData("orig-classes"),r.removeData("expose"),r.removeData("expose-z-index"),this.remove_exposed(r)},add_exposed:function(t){this.settings.exposed=this.settings.exposed||[],t instanceof e||typeof t=="object"?this.settings.exposed.push(t[0]):typeof t=="string"&&this.settings.exposed.push(t)},remove_exposed:function(t){var n,r;t instanceof e?n=t[0]:typeof t=="string"&&(n=t),this.settings.exposed=this.settings.exposed||[],r=this.settings.exposed.length;while(r--)if(this.settings.exposed[r]==n){this.settings.exposed.splice(r,1);return}},center:function(){var n=e(t);return this.settings.$next_tip.css({top:(n.height()-this.settings.$next_tip.outerHeight())/2+n.scrollTop(),left:(n.width()-this.settings.$next_tip.outerWidth())/2+n.scrollLeft()}),!0},bottom:function(){return/bottom/i.test(this.settings.tip_settings.tip_location)},top:function(){return/top/i.test(this.settings.tip_settings.tip_location)},right:function(){return/right/i.test(this.settings.tip_settings.tip_location)},left:function(){return/left/i.test(this.settings.tip_settings.tip_location)},corners:function(n){var r=e(t),i=r.height()/2,s=Math.ceil(this.settings.$target.offset().top-i+this.settings.$next_tip.outerHeight()),o=r.width()+r.scrollLeft(),u=r.height()+s,a=r.height()+r.scrollTop(),f=r.scrollTop();return s<f&&(s<0?f=0:f=s),u>a&&(a=u),[n.offset().top<f,o<n.offset().left+n.outerWidth(),a<n.offset().top+n.outerHeight(),r.scrollLeft()>n.offset().left]},visible:function(e){var t=e.length;while(t--)if(e[t])return!1;return!0},nub_position:function(e,t,n){t==="auto"?e.addClass(n):e.addClass(t)},startTimer:function(){this.settings.$li.length?this.settings.automate=setTimeout(function(){this.hide(),this.show(),this.startTimer()}.bind(this),this.settings.timer):clearTimeout(this.settings.automate)},end:function(t){this.settings.cookie_monster&&e.cookie(this.settings.cookie_name,"ridden",{expires:this.settings.cookie_expires,domain:this.settings.cookie_domain}),this.settings.timer>0&&clearTimeout(this.settings.automate),this.settings.modal&&this.settings.expose&&this.un_expose(),e(this.scope).off("keyup.joyride"),this.settings.$next_tip.data("closed",!0),this.settings.riding=!1,e(".joyride-modal-bg").hide(),this.settings.$current_tip.hide();if(typeof t=="undefined"||t===!1)this.settings.post_step_callback(this.settings.$li.index(),this.settings.$current_tip),this.settings.post_ride_callback(this.settings.$li.index(),this.settings.$current_tip);e(".joyride-tip-guide").remove()},off:function(){e(this.scope).off(".joyride"),e(t).off(".joyride"),e(".joyride-close-tip, .joyride-next-tip, .joyride-modal-bg").off(".joyride"),e(".joyride-tip-guide, .joyride-modal-bg").remove(),clearTimeout(this.settings.automate),this.settings={}},reflow:function(){}}}(jQuery,window,window.document),function(e,t,n,r){"use strict";Foundation.libs.equalizer={name:"equalizer",version:"5.3.3",settings:{use_tallest:!0,before_height_change:e.noop,after_height_change:e.noop,equalize_on_stack:!1},init:function(e,t,n){Foundation.inherit(this,"image_loaded"),this.bindings(t,n),this.reflow()},events:function(){this.S(t).off(".equalizer").on("resize.fndtn.equalizer",function(e){this.reflow()}.bind(this))},equalize:function(t){var n=!1,r=t.find("["+this.attr_name()+"-watch]:visible"),i=t.data(this.attr_name(!0)+"-init");if(r.length===0)return;var s=r.first().offset().top;i.before_height_change(),t.trigger("before-height-change").trigger("before-height-change.fndth.equalizer"),r.height("inherit"),r.each(function(){var t=e(this);t.offset().top!==s&&(n=!0)});if(i.equalize_on_stack===!1&&n)return;var o=r.map(function(){return e(this).outerHeight(!1)}).get();if(i.use_tallest){var u=Math.max.apply(null,o);r.css("height",u)}else{var a=Math.min.apply(null,o);r.css("height",a)}i.after_height_change(),t.trigger("after-height-change").trigger("after-height-change.fndtn.equalizer")},reflow:function(){var t=this;this.S("["+this.attr_name()+"]",this.scope).each(function(){var n=e(this);t.image_loaded(t.S("img",this),function(){t.equalize(n)})})}}}(jQuery,window,window.document),function(e,t,n,r){"use strict";Foundation.libs.dropdown={name:"dropdown",version:"5.3.3",settings:{active_class:"open",align:"bottom",is_hover:!1,opened:function(){},closed:function(){}},init:function(e,t,n){Foundation.inherit(this,"throttle"),this.bindings(t,n)},events:function(n){var r=this,i=r.S;i(this.scope).off(".dropdown").on("click.fndtn.dropdown","["+this.attr_name()+"]",function(t){var n=i(this).data(r.attr_name(!0)+"-init")||r.settings;if(!n.is_hover||Modernizr.touch)t.preventDefault(),r.toggle(e(this))}).on("mouseenter.fndtn.dropdown","["+this.attr_name()+"], ["+this.attr_name()+"-content]",function(e){var t=i(this),n,s;clearTimeout(r.timeout),t.data(r.data_attr())?(n=i("#"+t.data(r.data_attr())),s=t):(n=t,s=i("["+r.attr_name()+"='"+n.attr("id")+"']"));var o=s.data(r.attr_name(!0)+"-init")||r.settings;i(e.target).data(r.data_attr())&&o.is_hover&&r.closeall.call(r),o.is_hover&&r.open.apply(r,[n,s])}).on("mouseleave.fndtn.dropdown","["+this.attr_name()+"], ["+this.attr_name()+"-content]",function(e){var t=i(this);r.timeout=setTimeout(function(){if(t.data(r.data_attr())){var e=t.data(r.data_attr(!0)+"-init")||r.settings;e.is_hover&&r.close.call(r,i("#"+t.data(r.data_attr())))}else{var n=i("["+r.attr_name()+'="'+i(this).attr("id")+'"]'),e=n.data(r.attr_name(!0)+"-init")||r.settings;e.is_hover&&r.close.call(r,t)}}.bind(this),150)}).on("click.fndtn.dropdown",function(t){var n=i(t.target).closest("["+r.attr_name()+"-content]");if(i(t.target).closest("["+r.attr_name()+"]").length>0)return;if(!i(t.target).data("revealId")&&n.length>0&&(i(t.target).is("["+r.attr_name()+"-content]")||e.contains(n.first()[0],t.target))){t.stopPropagation();return}r.close.call(r,i("["+r.attr_name()+"-content]"))}).on("opened.fndtn.dropdown","["+r.attr_name()+"-content]",function(){r.settings.opened.call(this)}).on("closed.fndtn.dropdown","["+r.attr_name()+"-content]",function(){r.settings.closed.call(this)}),i(t).off(".dropdown").on("resize.fndtn.dropdown",r.throttle(function(){r.resize.call(r)},50)),this.resize()},close:function(e){var t=this;e.each(function(){t.S(this).hasClass(t.settings.active_class)&&(t.S(this).css(Foundation.rtl?"right":"left","-99999px").removeClass(t.settings.active_class).prev("["+t.attr_name()+"]").removeClass(t.settings.active_class).removeData("target"),t.S(this).trigger("closed").trigger("closed.fndtn.dropdown",[e]))})},closeall:function(){var t=this;e.each(t.S("["+this.attr_name()+"-content]"),function(){t.close.call(t,t.S(this))})},open:function(e,t){this.css(e.addClass(this.settings.active_class),t),e.prev("["+this.attr_name()+"]").addClass(this.settings.active_class),e.data("target",t.get(0)).trigger("opened").trigger("opened.fndtn.dropdown",[e,t])},data_attr:function(){return this.namespace.length>0?this.namespace+"-"+this.name:this.name},toggle:function(e){var t=this.S("#"+e.data(this.data_attr()));if(t.length===0)return;this.close.call(this,this.S("["+this.attr_name()+"-content]").not(t)),t.hasClass(this.settings.active_class)?(this.close.call(this,t),t.data("target")!==e.get(0)&&this.open.call( this,t,e)):this.open.call(this,t,e)},resize:function(){var e=this.S("["+this.attr_name()+"-content].open"),t=this.S("["+this.attr_name()+"='"+e.attr("id")+"']");e.length&&t.length&&this.css(e,t)},css:function(e,t){var n=Math.max((t.width()-e.width())/2,8);this.clear_idx();if(this.small()){var r=this.dirs.bottom.call(e,t);e.attr("style","").removeClass("drop-left drop-right drop-top").css({position:"absolute",width:"95%","max-width":"none",top:r.top}),e.css(Foundation.rtl?"right":"left",n)}else{var i=t.data(this.attr_name(!0)+"-init")||this.settings;this.style(e,t,i)}return e},style:function(t,n,r){var i=e.extend({position:"absolute"},this.dirs[r.align].call(t,n,r));t.attr("style","").css(i)},dirs:{_base:function(e){var t=this.offsetParent(),n=t.offset(),r=e.offset();return r.top-=n.top,r.left-=n.left,r},top:function(e,t){var n=Foundation.libs.dropdown,r=n.dirs._base.call(this,e),i=8;return this.addClass("drop-top"),(e.outerWidth()<this.outerWidth()||n.small())&&n.adjust_pip(i,r),Foundation.rtl?{left:r.left-this.outerWidth()+e.outerWidth(),top:r.top-this.outerHeight()}:{left:r.left,top:r.top-this.outerHeight()}},bottom:function(e,t){var n=Foundation.libs.dropdown,r=n.dirs._base.call(this,e),i=8;return(e.outerWidth()<this.outerWidth()||n.small())&&n.adjust_pip(i,r),n.rtl?{left:r.left-this.outerWidth()+e.outerWidth(),top:r.top+e.outerHeight()}:{left:r.left,top:r.top+e.outerHeight()}},left:function(e,t){var n=Foundation.libs.dropdown.dirs._base.call(this,e);return this.addClass("drop-left"),{left:n.left-this.outerWidth(),top:n.top}},right:function(e,t){var n=Foundation.libs.dropdown.dirs._base.call(this,e);return this.addClass("drop-right"),{left:n.left+e.outerWidth(),top:n.top}}},adjust_pip:function(e,t){var n=Foundation.stylesheet;this.small()&&(e+=t.left-8),this.rule_idx=n.cssRules.length;var r=".f-dropdown.open:before",i=".f-dropdown.open:after",s="left: "+e+"px;",o="left: "+(e-1)+"px;";n.insertRule?(n.insertRule([r,"{",s,"}"].join(" "),this.rule_idx),n.insertRule([i,"{",o,"}"].join(" "),this.rule_idx+1)):(n.addRule(r,s,this.rule_idx),n.addRule(i,o,this.rule_idx+1))},clear_idx:function(){var e=Foundation.stylesheet;this.rule_idx&&(e.deleteRule(this.rule_idx),e.deleteRule(this.rule_idx),delete this.rule_idx)},small:function(){return matchMedia(Foundation.media_queries.small).matches&&!matchMedia(Foundation.media_queries.medium).matches},off:function(){this.S(this.scope).off(".fndtn.dropdown"),this.S("html, body").off(".fndtn.dropdown"),this.S(t).off(".fndtn.dropdown"),this.S("[data-dropdown-content]").off(".fndtn.dropdown")},reflow:function(){}}}(jQuery,window,window.document),function(e,t,n,r){"use strict";Foundation.libs.clearing={name:"clearing",version:"5.3.3",settings:{templates:{viewing:'<a href="#" class="clearing-close">&times;</a><div class="visible-img" style="display: none"><div class="clearing-touch-label"></div><img src="data:image/gif;base64,R0lGODlhAQABAAD/ACwAAAAAAQABAAACADs%3D" alt="" /><p class="clearing-caption"></p><a href="#" class="clearing-main-prev"><span></span></a><a href="#" class="clearing-main-next"><span></span></a></div>'},close_selectors:".clearing-close, div.clearing-blackout",open_selectors:"",skip_selector:"",touch_label:"",init:!1,locked:!1},init:function(e,t,n){var r=this;Foundation.inherit(this,"throttle image_loaded"),this.bindings(t,n),r.S(this.scope).is("["+this.attr_name()+"]")?this.assemble(r.S("li",this.scope)):r.S("["+this.attr_name()+"]",this.scope).each(function(){r.assemble(r.S("li",this))})},events:function(r){var i=this,s=i.S,o=e(".scroll-container");o.length>0&&(this.scope=o),s(this.scope).off(".clearing").on("click.fndtn.clearing","ul["+this.attr_name()+"] li "+this.settings.open_selectors,function(e,t,n){var t=t||s(this),n=n||t,r=t.next("li"),o=t.closest("["+i.attr_name()+"]").data(i.attr_name(!0)+"-init"),u=s(e.target);e.preventDefault(),o||(i.init(),o=t.closest("["+i.attr_name()+"]").data(i.attr_name(!0)+"-init")),n.hasClass("visible")&&t[0]===n[0]&&r.length>0&&i.is_open(t)&&(n=r,u=s("img",n)),i.open(u,t,n),i.update_paddles(n)}).on("click.fndtn.clearing",".clearing-main-next",function(e){i.nav(e,"next")}).on("click.fndtn.clearing",".clearing-main-prev",function(e){i.nav(e,"prev")}).on("click.fndtn.clearing",this.settings.close_selectors,function(e){Foundation.libs.clearing.close(e,this)}),e(n).on("keydown.fndtn.clearing",function(e){i.keydown(e)}),s(t).off(".clearing").on("resize.fndtn.clearing",function(){i.resize()}),this.swipe_events(r)},swipe_events:function(e){var t=this,n=t.S;n(this.scope).on("touchstart.fndtn.clearing",".visible-img",function(e){e.touches||(e=e.originalEvent);var t={start_page_x:e.touches[0].pageX,start_page_y:e.touches[0].pageY,start_time:(new Date).getTime(),delta_x:0,is_scrolling:r};n(this).data("swipe-transition",t),e.stopPropagation()}).on("touchmove.fndtn.clearing",".visible-img",function(e){e.touches||(e=e.originalEvent);if(e.touches.length>1||e.scale&&e.scale!==1)return;var r=n(this).data("swipe-transition");typeof r=="undefined"&&(r={}),r.delta_x=e.touches[0].pageX-r.start_page_x,Foundation.rtl&&(r.delta_x=-r.delta_x),typeof r.is_scrolling=="undefined"&&(r.is_scrolling=!!(r.is_scrolling||Math.abs(r.delta_x)<Math.abs(e.touches[0].pageY-r.start_page_y)));if(!r.is_scrolling&&!r.active){e.preventDefault();var i=r.delta_x<0?"next":"prev";r.active=!0,t.nav(e,i)}}).on("touchend.fndtn.clearing",".visible-img",function(e){n(this).data("swipe-transition",{}),e.stopPropagation()})},assemble:function(t){var n=t.parent();if(n.parent().hasClass("carousel"))return;n.after('<div id="foundationClearingHolder"></div>');var r=n.detach(),i="";if(r[0]==null)return;i=r[0].outerHTML;var s=this.S("#foundationClearingHolder"),o=n.data(this.attr_name(!0)+"-init"),u={grid:'<div class="carousel">'+i+"</div>",viewing:o.templates.viewing},a='<div class="clearing-assembled"><div>'+u.viewing+u.grid+"</div></div>",f=this.settings.touch_label;Modernizr.touch&&(a=e(a).find(".clearing-touch-label").html(f).end()),s.after(a).remove()},open:function(t,r,i){function p(){setTimeout(function(){this.image_loaded(l,function(){l.outerWidth()===1&&!h?p.call(this):d.call(this,l)}.bind(this))}.bind(this),100)}function d(t){var n=e(t);n.css("visibility","visible"),o.css("overflow","hidden"),u.addClass("clearing-blackout"),a.addClass("clearing-container"),f.show(),this.fix_height(i).caption(s.S(".clearing-caption",f),s.S("img",i)).center_and_label(t,c).shift(r,i,function(){i.closest("li").siblings().removeClass("visible"),i.closest("li").addClass("visible")}),f.trigger("opened.fndtn.clearing")}var s=this,o=e(n.body),u=i.closest(".clearing-assembled"),a=s.S("div",u).first(),f=s.S(".visible-img",a),l=s.S("img",f).not(t),c=s.S(".clearing-touch-label",a),h=!1;e("body").on("touchmove",function(e){e.preventDefault()}),l.error(function(){h=!0}),this.locked()||(f.trigger("open.fndtn.clearing"),l.attr("src",this.load(t)).css("visibility","hidden"),p.call(this))},close:function(t,r){t.preventDefault();var i=function(e){return/blackout/.test(e.selector)?e:e.closest(".clearing-blackout")}(e(r)),s=e(n.body),o,u;return r===t.target&&i&&(s.css("overflow",""),o=e("div",i).first(),u=e(".visible-img",o),u.trigger("close.fndtn.clearing"),this.settings.prev_index=0,e("ul["+this.attr_name()+"]",i).attr("style","").closest(".clearing-blackout").removeClass("clearing-blackout"),o.removeClass("clearing-container"),u.hide(),u.trigger("closed.fndtn.clearing")),e("body").off("touchmove"),!1},is_open:function(e){return e.parent().prop("style").length>0},keydown:function(t){var n=e(".clearing-blackout ul["+this.attr_name()+"]"),r=this.rtl?37:39,i=this.rtl?39:37,s=27;t.which===r&&this.go(n,"next"),t.which===i&&this.go(n,"prev"),t.which===s&&this.S("a.clearing-close").trigger("click").trigger("click.fndtn.clearing")},nav:function(t,n){var r=e("ul["+this.attr_name()+"]",".clearing-blackout");t.preventDefault(),this.go(r,n)},resize:function(){var t=e("img",".clearing-blackout .visible-img"),n=e(".clearing-touch-label",".clearing-blackout");t.length&&(this.center_and_label(t,n),t.trigger("resized.fndtn.clearing"))},fix_height:function(e){var t=e.parent().children(),n=this;return t.each(function(){var e=n.S(this),t=e.find("img");e.height()>t.outerHeight()&&e.addClass("fix-height")}).closest("ul").width(t.length*100+"%"),this},update_paddles:function(e){e=e.closest("li");var t=e.closest(".carousel").siblings(".visible-img");e.next().length>0?this.S(".clearing-main-next",t).removeClass("disabled"):this.S(".clearing-main-next",t).addClass("disabled"),e.prev().length>0?this.S(".clearing-main-prev",t).removeClass("disabled"):this.S(".clearing-main-prev",t).addClass("disabled")},center_and_label:function(e,t){return this.rtl?(e.css({marginRight:-(e.outerWidth()/2),marginTop:-(e.outerHeight()/2),left:"auto",right:"50%"}),t.length>0&&t.css({marginRight:-(t.outerWidth()/2),marginTop:-(e.outerHeight()/2)-t.outerHeight()-10,left:"auto",right:"50%"})):(e.css({marginLeft:-(e.outerWidth()/2),marginTop:-(e.outerHeight()/2)}),t.length>0&&t.css({marginLeft:-(t.outerWidth()/2),marginTop:-(e.outerHeight()/2)-t.outerHeight()-10})),this},load:function(e){var t;return e[0].nodeName==="A"?t=e.attr("href"):t=e.parent().attr("href"),this.preload(e),t?t:e.attr("src")},preload:function(e){this.img(e.closest("li").next()).img(e.closest("li").prev())},img:function(e){if(e.length){var t=new Image,n=this.S("a",e);n.length?t.src=n.attr("href"):t.src=this.S("img",e).attr("src")}return this},caption:function(e,t){var n=t.attr("data-caption");return n?e.html(n).show():e.text("").hide(),this},go:function(e,t){var n=this.S(".visible",e),r=n[t]();this.settings.skip_selector&&r.find(this.settings.skip_selector).length!=0&&(r=r[t]()),r.length&&this.S("img",r).trigger("click",[n,r]).trigger("click.fndtn.clearing",[n,r]).trigger("change.fndtn.clearing")},shift:function(e,t,n){var r=t.parent(),i=this.settings.prev_index||t.index(),s=this.direction(r,e,t),o=this.rtl?"right":"left",u=parseInt(r.css("left"),10),a=t.outerWidth(),f,l={};t.index()!==i&&!/skip/.test(s)?/left/.test(s)?(this.lock(),l[o]=u+a,r.animate(l,300,this.unlock())):/right/.test(s)&&(this.lock(),l[o]=u-a,r.animate(l,300,this.unlock())):/skip/.test(s)&&(f=t.index()-this.settings.up_count,this.lock(),f>0?(l[o]=-(f*a),r.animate(l,300,this.unlock())):(l[o]=0,r.animate(l,300,this.unlock()))),n()},direction:function(e,t,n){var r=this.S("li",e),i=r.outerWidth()+r.outerWidth()/4,s=Math.floor(this.S(".clearing-container").outerWidth()/i)-1,o=r.index(n),u;return this.settings.up_count=s,this.adjacent(this.settings.prev_index,o)?o>s&&o>this.settings.prev_index?u="right":o>s-1&&o<=this.settings.prev_index?u="left":u=!1:u="skip",this.settings.prev_index=o,u},adjacent:function(e,t){for(var n=t+1;n>=t-1;n--)if(n===e)return!0;return!1},lock:function(){this.settings.locked=!0},unlock:function(){this.settings.locked=!1},locked:function(){return this.settings.locked},off:function(){this.S(this.scope).off(".fndtn.clearing"),this.S(t).off(".fndtn.clearing")},reflow:function(){this.init()}}}(jQuery,window,window.document),function(e,t,n,r){"use strict";var i=function(){},s=function(i,s){if(i.hasClass(s.slides_container_class))return this;var f=this,l,c=i,h,p,d,v=0,m,g,y=!1,b=!1;f.slides=function(){return c.children(s.slide_selector)},f.slides().first().addClass(s.active_slide_class),f.update_slide_number=function(t){s.slide_number&&(h.find("span:first").text(parseInt(t)+1),h.find("span:last").text(f.slides().length)),s.bullets&&(p.children().removeClass(s.bullets_active_class),e(p.children().get(t)).addClass(s.bullets_active_class))},f.update_active_link=function(t){var n=e('[data-orbit-link="'+f.slides().eq(t).attr("data-orbit-slide")+'"]');n.siblings().removeClass(s.bullets_active_class),n.addClass(s.bullets_active_class)},f.build_markup=function(){c.wrap('<div class="'+s.container_class+'"></div>'),l=c.parent(),c.addClass(s.slides_container_class),s.stack_on_small&&l.addClass(s.stack_on_small_class),s.navigation_arrows&&(l.append(e('<a href="#"><span></span></a>').addClass(s.prev_class)),l.append(e('<a href="#"><span></span></a>').addClass(s.next_class))),s.timer&&(d=e("<div>").addClass(s.timer_container_class),d.append("<span>"),d.append(e("<div>").addClass(s.timer_progress_class)),d.addClass(s.timer_paused_class),l.append(d)),s.slide_number&&(h=e("<div>").addClass(s.slide_number_class),h.append("<span></span> "+s.slide_number_text+" <span></span>"),l.append(h)),s.bullets&&(p=e("<ol>").addClass(s.bullets_container_class),l.append(p),p.wrap('<div class="orbit-bullets-container"></div>'),f.slides().each(function(t,n){var r=e("<li>").attr("data-orbit-slide",t).on("click",f.link_bullet);p.append(r)}))},f._goto=function(t,n){if(t===v)return!1;typeof g=="object"&&g.restart();var r=f.slides(),i="next";y=!0,t<v&&(i="prev");if(t>=r.length){if(!s.circular)return!1;t=0}else if(t<0){if(!s.circular)return!1;t=r.length-1}var o=e(r.get(v)),u=e(r.get(t));o.css("zIndex",2),o.removeClass(s.active_slide_class),u.css("zIndex",4).addClass(s.active_slide_class),c.trigger("before-slide-change.fndtn.orbit"),s.before_slide_change(),f.update_active_link(t);var a=function(){var e=function(){v=t,y=!1,n===!0&&(g=f.create_timer(),g.start()),f.update_slide_number(v),c.trigger("after-slide-change.fndtn.orbit",[{slide_number:v,total_slides:r.length}]),s.after_slide_change(v,r.length)};c.height()!=u.height()&&s.variable_height?c.animate({height:u.height()},250,"linear",e):e()};if(r.length===1)return a(),!1;var l=function(){i==="next"&&m.next(o,u,a),i==="prev"&&m.prev(o,u,a)};u.height()>c.height()&&s.variable_height?c.animate({height:u.height()},250,"linear",l):l()},f.next=function(e){e.stopImmediatePropagation(),e.preventDefault(),f._goto(v+1)},f.prev=function(e){e.stopImmediatePropagation(),e.preventDefault(),f._goto(v-1)},f.link_custom=function(t){t.preventDefault();var n=e(this).attr("data-orbit-link");if(typeof n=="string"&&(n=e.trim(n))!=""){var r=l.find("[data-orbit-slide="+n+"]");r.index()!=-1&&f._goto(r.index())}},f.link_bullet=function(t){var n=e(this).attr("data-orbit-slide");if(typeof n=="string"&&(n=e.trim(n))!="")if(isNaN(parseInt(n))){var r=l.find("[data-orbit-slide="+n+"]");r.index()!=-1&&f._goto(r.index()+1)}else f._goto(parseInt(n))},f.timer_callback=function(){f._goto(v+1,!0)},f.compute_dimensions=function(){var t=e(f.slides().get(v)),n=t.height();s.variable_height||f.slides().each(function(){e(this).height()>n&&(n=e(this).height())}),c.height(n)},f.create_timer=function(){var e=new o(l.find("."+s.timer_container_class),s,f.timer_callback);return e},f.stop_timer=function(){typeof g=="object"&&g.stop()},f.toggle_timer=function(){var e=l.find("."+s.timer_container_class);e.hasClass(s.timer_paused_class)?(typeof g=="undefined"&&(g=f.create_timer()),g.start()):typeof g=="object"&&g.stop()},f.init=function(){f.build_markup(),s.timer&&(g=f.create_timer(),Foundation.utils.image_loaded(this.slides().children("img"),g.start)),m=new a(s,c),s.animation==="slide"&&(m=new u(s,c)),l.on("click","."+s.next_class,f.next),l.on("click","."+s.prev_class,f.prev),s.next_on_click&&l.on("click","."+s.slides_container_class+" [data-orbit-slide]",f.link_bullet),l.on("click",f.toggle_timer),s.swipe&&l.on("touchstart.fndtn.orbit",function(e){e.touches||(e=e.originalEvent);var t={start_page_x:e.touches[0].pageX,start_page_y:e.touches[0].pageY,start_time:(new Date).getTime(),delta_x:0,is_scrolling:r};l.data("swipe-transition",t),e.stopPropagation()}).on("touchmove.fndtn.orbit",function(e){e.touches||(e=e.originalEvent);if(e.touches.length>1||e.scale&&e.scale!==1)return;var t=l.data("swipe-transition");typeof t=="undefined"&&(t={}),t.delta_x=e.touches[0].pageX-t.start_page_x,typeof t.is_scrolling=="undefined"&&(t.is_scrolling=!!(t.is_scrolling||Math.abs(t.delta_x)<Math.abs(e.touches[0].pageY-t.start_page_y)));if(!t.is_scrolling&&!t.active){e.preventDefault();var n=t.delta_x<0?v+1:v-1;t.active=!0,f._goto(n)}}).on("touchend.fndtn.orbit",function(e){l.data("swipe-transition",{}),e.stopPropagation()}),l.on("mouseenter.fndtn.orbit",function(e){s.timer&&s.pause_on_hover&&f.stop_timer()}).on("mouseleave.fndtn.orbit",function(e){s.timer&&s.resume_on_mouseout&&g.start()}),e(n).on("click","[data-orbit-link]",f.link_custom),e(t).on("load resize",f.compute_dimensions),Foundation.utils.image_loaded(this.slides().children("img"),f.compute_dimensions),Foundation.utils.image_loaded(this.slides().children("img"),function(){l.prev("."+s.preloader_class).css("display","none"),f.update_slide_number(0),f.update_active_link(0),c.trigger("ready.fndtn.orbit")})},f.init()},o=function(e,t,n){var r=this,i=t.timer_speed,s=e.find("."+t.timer_progress_class),o,u,a=-1;this.update_progress=function(e){var t=s.clone();t.attr("style",""),t.css("width",e+"%"),s.replaceWith(t),s=t},this.restart=function(){clearTimeout(u),e.addClass(t.timer_paused_class),a=-1,r.update_progress(0)},this.start=function(){if(!e.hasClass(t.timer_paused_class))return!0;a=a===-1?i:a,e.removeClass(t.timer_paused_class),o=(new Date).getTime(),s.animate({width:"100%"},a,"linear"),u=setTimeout(function(){r.restart(),n()},a),e.trigger("timer-started.fndtn.orbit")},this.stop=function(){if(e.hasClass(t.timer_paused_class))return!0;clearTimeout(u),e.addClass(t.timer_paused_class);var n=(new Date).getTime();a-=n-o;var s=100-a/i*100;r.update_progress(s),e.trigger("timer-stopped.fndtn.orbit")}},u=function(t,n){var r=t.animation_speed,i=e("html[dir=rtl]").length===1,s=i?"marginRight":"marginLeft",o={};o[s]="0%",this.next=function(e,t,n){e.animate({marginLeft:"-100%"},r),t.animate(o,r,function(){e.css(s,"100%"),n()})},this.prev=function(e,t,n){e.animate({marginLeft:"100%"},r),t.css(s,"-100%"),t.animate(o,r,function(){e.css(s,"100%"),n()})}},a=function(t,n){var r=t.animation_speed,i=e("html[dir=rtl]").length===1,s=i?"marginRight":"marginLeft";this.next=function(e,t,n){t.css({margin:"0%",opacity:"0.01"}),t.animate({opacity:"1"},r,"linear",function(){e.css("margin","100%"),n()})},this.prev=function(e,t,n){t.css({margin:"0%",opacity:"0.01"}),t.animate({opacity:"1"},r,"linear",function(){e.css("margin","100%"),n()})}};Foundation.libs=Foundation.libs||{},Foundation.libs.orbit={name:"orbit",version:"5.3.3",settings:{animation:"slide",timer_speed:1e4,pause_on_hover:!0,resume_on_mouseout:!1,next_on_click:!0,animation_speed:500,stack_on_small:!1,navigation_arrows:!0,slide_number:!0,slide_number_text:"of",container_class:"orbit-container",stack_on_small_class:"orbit-stack-on-small",next_class:"orbit-next",prev_class:"orbit-prev",timer_container_class:"orbit-timer",timer_paused_class:"paused",timer_progress_class:"orbit-progress",slides_container_class:"orbit-slides-container",preloader_class:"preloader",slide_selector:"*",bullets_container_class:"orbit-bullets",bullets_active_class:"active",slide_number_class:"orbit-slide-number",caption_class:"orbit-caption",active_slide_class:"active",orbit_transition_class:"orbit-transitioning",bullets:!0,circular:!0,timer:!0,variable_height:!1,swipe:!0,before_slide_change:i,after_slide_change:i},init:function(e,t,n){var r=this;this.bindings(t,n)},events:function(e){var t=new s(this.S(e),this.S(e).data("orbit-init"));this.S(e).data(this.name+"-instance",t)},reflow:function(){var e=this;if(e.S(e.scope).is("[data-orbit]")){var t=e.S(e.scope),n=t.data(e.name+"-instance");n.compute_dimensions()}else e.S("[data-orbit]",e.scope).each(function(t,n){var r=e.S(n),i=e.data_options(r),s=r.data(e.name+"-instance");s.compute_dimensions()})}}}(jQuery,window,window.document),function(e,t,n,r){"use strict";Foundation.libs.offcanvas={name:"offcanvas",version:"5.3.3",settings:{open_method:"move",close_on_click:!1},init:function(e,t,n){this.bindings(t,n)},events:function(){var e=this,t=e.S,n="",r="",i="";this.settings.open_method==="move"?(n="move-",r="right",i="left"):this.settings.open_method==="overlap_single"?(n="offcanvas-overlap-",r="right",i="left"):this.settings.open_method==="overlap"&&(n="offcanvas-overlap"),t(this.scope).off(".offcanvas").on("click.fndtn.offcanvas",".left-off-canvas-toggle",function(i){e.click_toggle_class(i,n+r),e.settings.open_method!=="overlap"&&t(".left-submenu").removeClass(n+r)}).on("click.fndtn.offcanvas",".left-off-canvas-menu a",function(i){var s=e.get_settings(i),o=t(this).parent();s.close_on_click&&!o.hasClass("has-submenu")&&!o.hasClass("back")?(e.hide.call(e,n+r,e.get_wrapper(i)),o.parent().removeClass(n+r)):t(this).parent().hasClass("has-submenu")?(i.preventDefault(),t(this).siblings(".left-submenu").toggleClass(n+r)):o.hasClass("back")&&(i.preventDefault(),o.parent().removeClass(n+r))}).on("click.fndtn.offcanvas",".right-off-canvas-toggle",function(r){e.click_toggle_class(r,n+i),e.settings.open_method!=="overlap"&&t(".right-submenu").removeClass(n+i)}).on("click.fndtn.offcanvas",".right-off-canvas-menu a",function(r){var s=e.get_settings(r),o=t(this).parent();s.close_on_click&&!o.hasClass("has-submenu")&&!o.hasClass("back")?(e.hide.call(e,n+i,e.get_wrapper(r)),o.parent().removeClass(n+i)):t(this).parent().hasClass("has-submenu")?(r.preventDefault(),t(this).siblings(".right-submenu").toggleClass(n+i)):o.hasClass("back")&&(r.preventDefault(),o.parent().removeClass(n+i))}).on("click.fndtn.offcanvas",".exit-off-canvas",function(s){e.click_remove_class(s,n+i),t(".right-submenu").removeClass(n+i),r&&(e.click_remove_class(s,n+r),t(".left-submenu").removeClass(n+i))})},toggle:function(e,t){t=t||this.get_wrapper(),t.is("."+e)?this.hide(e,t):this.show(e,t)},show:function(e,t){t=t||this.get_wrapper(),t.trigger("open").trigger("open.fndtn.offcanvas"),t.addClass(e)},hide:function(e,t){t=t||this.get_wrapper(),t.trigger("close").trigger("close.fndtn.offcanvas"),t.removeClass(e)},click_toggle_class:function(e,t){e.preventDefault();var n=this.get_wrapper(e);this.toggle(t,n)},click_remove_class:function(e,t){e.preventDefault();var n=this.get_wrapper(e);this.hide(t,n)},get_settings:function(e){var t=this.S(e.target).closest("["+this.attr_name()+"]");return t.data(this.attr_name(!0)+"-init")||this.settings},get_wrapper:function(e){var t=this.S(e?e.target:this.scope).closest(".off-canvas-wrap");return t.length===0&&(t=this.S(".off-canvas-wrap")),t},reflow:function(){}}}(jQuery,window,window.document),function(e,t,n,r){"use strict";Foundation.libs.alert={name:"alert",version:"5.3.3",settings:{callback:function(){}},init:function(e,t,n){this.bindings(t,n)},events:function(){var t=this,n=this.S;e(this.scope).off(".alert").on("click.fndtn.alert","["+this.attr_name()+"] a.close",function(e){var r=n(this).closest("["+t.attr_name()+"]"),i=r.data(t.attr_name(!0)+"-init")||t.settings;e.preventDefault(),Modernizr.csstransitions?(r.addClass("alert-close"),r.on("transitionend webkitTransitionEnd oTransitionEnd",function(e){n(this).trigger("close").trigger("close.fndtn.alert").remove(),i.callback()})):r.fadeOut(300,function(){n(this).trigger("close").trigger("close.fndtn.alert").remove(),i.callback()})})},reflow:function(){}}}(jQuery,window,window.document),function(e,t,n,r){"use strict";function i(e){var t=/fade/i.test(e),n=/pop/i.test(e);return{animate:t||n,pop:n,fade:t}}Foundation.libs.reveal={name:"reveal",version:"5.3.3",locked:!1,settings:{animation:"fadeAndPop",animation_speed:250,close_on_background_click:!0,close_on_esc:!0,dismiss_modal_class:"close-reveal-modal",bg_class:"reveal-modal-bg",root_element:"body",open:function(){},opened:function(){},close:function(){},closed:function(){},bg:e(".reveal-modal-bg"),css:{open:{opacity:0,visibility:"visible",display:"block"},close:{opacity:1,visibility:"hidden",display:"none"}}},init:function(t,n,r){e.extend(!0,this.settings,n,r),this.bindings(n,r)},events:function(e){var t=this,r=t.S;return r(this.scope).off(".reveal").on("click.fndtn.reveal","["+this.add_namespace("data-reveal-id")+"]:not([disabled])",function(e){e.preventDefault();if(!t.locked){var n=r(this),i=n.data(t.data_attr("reveal-ajax"));t.locked=!0;if(typeof i=="undefined")t.open.call(t,n);else{var s=i===!0?n.attr("href"):i;t.open.call(t,n,{url:s})}}}),r(n).on("click.fndtn.reveal",this.close_targets(),function(e){e.preventDefault();if(!t.locked){var n=r("["+t.attr_name()+"].open").data(t.attr_name(!0)+"-init"),i=r(e.target)[0]===r("."+n.bg_class)[0];if(i){if(!n.close_on_background_click)return;e.stopPropagation()}t.locked=!0,t.close.call(t,i?r("["+t.attr_name()+"].open"):r(this).closest("["+t.attr_name()+"]"))}}),r("["+t.attr_name()+"]",this.scope).length>0?r(this.scope).on("open.fndtn.reveal",this.settings.open).on("opened.fndtn.reveal",this.settings.opened).on("opened.fndtn.reveal",this.open_video).on("close.fndtn.reveal",this.settings.close).on("closed.fndtn.reveal",this.settings.closed).on("closed.fndtn.reveal",this.close_video):r(this.scope).on("open.fndtn.reveal","["+t.attr_name()+"]",this.settings.open).on("opened.fndtn.reveal","["+t.attr_name()+"]",this.settings.opened).on("opened.fndtn.reveal","["+t.attr_name()+"]",this.open_video).on("close.fndtn.reveal","["+t.attr_name()+"]",this.settings.close).on("closed.fndtn.reveal","["+t.attr_name()+"]",this.settings.closed).on("closed.fndtn.reveal","["+t.attr_name()+"]",this.close_video),!0},key_up_on:function(e){var t=this;return t.S("body").off("keyup.fndtn.reveal").on("keyup.fndtn.reveal",function(e){var n=t.S("["+t.attr_name()+"].open"),r=n.data(t.attr_name(!0)+"-init")||t.settings;r&&e.which===27&&r.close_on_esc&&!t.locked&&t.close.call(t,n)}),!0},key_up_off:function(e){return this.S("body").off("keyup.fndtn.reveal"),!0},open:function(t,n){var r=this,i;t?typeof t.selector!="undefined"?i=r.S("#"+t.data(r.data_attr("reveal-id"))).first():(i=r.S(this.scope),n=t):i=r.S(this.scope);var s=i.data(r.attr_name(!0)+"-init");s=s||this.settings;if(i.hasClass("open")&&t.attr("data-reveal-id")==i.attr("id"))return r.close(i);if(!i.hasClass("open")){var o=r.S("["+r.attr_name()+"].open");typeof i.data("css-top")=="undefined"&&i.data("css-top",parseInt(i.css("top"),10)).data("offset",this.cache_offset(i)),this.key_up_on(i),i.trigger("open").trigger("open.fndtn.reveal"),o.length<1&&this.toggle_bg(i,!0),typeof n=="string"&&(n={url:n});if(typeof n=="undefined"||!n.url)o.length>0&&this.hide(o,s.css.close),this.show(i,s.css.open);else{var u=typeof n.success!="undefined"?n.success:null;e.extend(n,{success:function(t,n,a){e.isFunction(u)&&u(t,n,a),i.html(t),r.S(i).foundation("section","reflow"),r.S(i).children().foundation(),o.length>0&&r.hide(o,s.css.close),r.show(i,s.css.open)}}),e.ajax(n)}}},close:function(e){var e=e&&e.length?e:this.S(this.scope),t=this.S("["+this.attr_name()+"].open"),n=e.data(this.attr_name(!0)+"-init")||this.settings;t.length>0&&(this.locked=!0,this.key_up_off(e),e.trigger("close").trigger("close.fndtn.reveal"),this.toggle_bg(e,!1),this.hide(t,n.css.close,n))},close_targets:function(){var e="."+this.settings.dismiss_modal_class;return this.settings.close_on_background_click?e+", ."+this.settings.bg_class:e},toggle_bg:function(t,n){this.S("."+this.settings.bg_class).length===0&&(this.settings.bg=e("<div />",{"class":this.settings.bg_class}).appendTo("body").hide());var i=this.settings.bg.filter(":visible").length>0;n!=i&&((n==r?i:!n)?this.hide(this.settings.bg):this.show(this.settings.bg))},show:function(n,r){if(r){var s=n.data(this.attr_name(!0)+"-init")||this.settings,o=s.root_element;if(n.parent(o).length===0){var u=n.wrap('<div style="display: none;" />').parent();n.on("closed.fndtn.reveal.wrapped",function(){n.detach().appendTo(u),n.unwrap().unbind("closed.fndtn.reveal.wrapped")}),n.detach().appendTo(o)}var a=i(s.animation);a.animate||(this.locked=!1);if(a.pop){r.top=e(t).scrollTop()-n.data("offset")+"px";var f={top:e(t).scrollTop()+n.data("css-top")+"px",opacity:1};return setTimeout(function(){return n.css(r).animate(f,s.animation_speed,"linear",function(){this.locked=!1,n.trigger("opened").trigger("opened.fndtn.reveal")}.bind(this)).addClass("open")}.bind(this),s.animation_speed/2)}if(a.fade){r.top=e(t).scrollTop()+n.data("css-top")+"px";var f={opacity:1};return setTimeout(function(){return n.css(r).animate(f,s.animation_speed,"linear",function(){this.locked=!1,n.trigger("opened").trigger("opened.fndtn.reveal")}.bind(this)).addClass("open")}.bind(this),s.animation_speed/2)}return n.css(r).show().css({opacity:1}).addClass("open").trigger("opened").trigger("opened.fndtn.reveal")}var s=this.settings;return i(s.animation).fade?n.fadeIn(s.animation_speed/2):(this.locked=!1,n.show())},hide:function(n,r){if(r){var s=n.data(this.attr_name(!0)+"-init");s=s||this.settings;var o=i(s.animation);o.animate||(this.locked=!1);if(o.pop){var u={top:-e(t).scrollTop()-n.data("offset")+"px",opacity:0};return setTimeout(function(){return n.animate(u,s.animation_speed,"linear",function(){this.locked=!1,n.css(r).trigger("closed").trigger("closed.fndtn.reveal")}.bind(this)).removeClass("open")}.bind(this),s.animation_speed/2)}if(o.fade){var u={opacity:0};return setTimeout(function(){return n.animate(u,s.animation_speed,"linear",function(){this.locked=!1,n.css(r).trigger("closed").trigger("closed.fndtn.reveal")}.bind(this)).removeClass("open")}.bind(this),s.animation_speed/2)}return n.hide().css(r).removeClass("open").trigger("closed").trigger("closed.fndtn.reveal")}var s=this.settings;return i(s.animation).fade?n.fadeOut(s.animation_speed/2):n.hide()},close_video:function(t){var n=e(".flex-video",t.target),r=e("iframe",n);r.length>0&&(r.attr("data-src",r[0].src),r.attr("src",r.attr("src")),n.hide())},open_video:function(t){var n=e(".flex-video",t.target),i=n.find("iframe");if(i.length>0){var s=i.attr("data-src");if(typeof s=="string")i[0].src=i.attr("data-src");else{var o=i[0].src;i[0].src=r,i[0].src=o}n.show()}},data_attr:function(e){return this.namespace.length>0?this.namespace+"-"+e:e},cache_offset:function(e){var t=e.show().height()+parseInt(e.css("top"),10);return e.hide(),t},off:function(){e(this.scope).off(".fndtn.reveal")},reflow:function(){}}}(jQuery,window,window.document),function(e,t,n,r){"use strict";Foundation.libs.interchange={name:"interchange",version:"5.3.3",cache:{},images_loaded:!1,nodes_loaded:!1,settings:{load_attr:"interchange",named_queries:{"default":"only screen",small:Foundation.media_queries.small,medium:Foundation.media_queries.medium,large:Foundation.media_queries.large,xlarge:Foundation.media_queries.xlarge,xxlarge:Foundation.media_queries.xxlarge,landscape:"only screen and (orientation: landscape)",portrait:"only screen and (orientation: portrait)",retina:"only screen and (-webkit-min-device-pixel-ratio: 2),only screen and (min--moz-device-pixel-ratio: 2),only screen and (-o-min-device-pixel-ratio: 2/1),only screen and (min-device-pixel-ratio: 2),only screen and (min-resolution: 192dpi),only screen and (min-resolution: 2dppx)"},directives:{replace:function(t,n,r){if(/IMG/.test(t[0].nodeName)){var i=t[0].src;if((new RegExp(n,"i")).test(i))return;return t[0].src=n,r(t[0].src)}var s=t.data(this.data_attr+"-last-path"),o=this;if(s==n)return;return/\.(gif|jpg|jpeg|tiff|png)([?#].*)?/i.test(n)?(e(t).css("background-image","url("+n+")"),t.data("interchange-last-path",n),r(n)):e.get(n,function(e){t.html(e),t.data(o.data_attr+"-last-path",n),r()})}}},init:function(t,n,r){Foundation.inherit(this,"throttle random_str"),this.data_attr=this.set_data_attr(),e.extend(!0,this.settings,n,r),this.bindings(n,r),this.load("images"),this.load("nodes")},get_media_hash:function(){var e="";for(var t in this.settings.named_queries)e+=matchMedia(this.settings.named_queries[t]).matches.toString();return e},events:function(){var n=this,r;return e(t).off(".interchange").on("resize.fndtn.interchange",n.throttle(function(){var e=n.get_media_hash();e!==r&&n.resize(),r=e},50)),this},resize:function(){var t=this.cache;if(!this.images_loaded||!this.nodes_loaded){setTimeout(e.proxy(this.resize,this),50);return}for(var n in t)if(t.hasOwnProperty(n)){var r=this.results(n,t[n]);r&&this.settings.directives[r.scenario[1]].call(this,r.el,r.scenario[0],function(){if(arguments[0]instanceof Array)var e=arguments[0];else var e=Array.prototype.slice.call(arguments,0);r.el.trigger(r.scenario[1],e)})}},results:function(e,t){var n=t.length;if(n>0){var r=this.S("["+this.add_namespace("data-uuid")+'="'+e+'"]');while(n--){var i,s=t[n][2];this.settings.named_queries.hasOwnProperty(s)?i=matchMedia(this.settings.named_queries[s]):i=matchMedia(s);if(i.matches)return{el:r,scenario:t[n]}}}return!1},load:function(e,t){return(typeof this["cached_"+e]=="undefined"||t)&&this["update_"+e](),this["cached_"+e]},update_images:function(){var e=this.S("img["+this.data_attr+"]"),t=e.length,n=t,r=0,i=this.data_attr;this.cache={},this.cached_images=[],this.images_loaded=t===0;while(n--){r++;if(e[n]){var s=e[n].getAttribute(i)||"";s.length>0&&this.cached_images.push(e[n])}r===t&&(this.images_loaded=!0,this.enhance("images"))}return this},update_nodes:function(){var e=this.S("["+this.data_attr+"]").not("img"),t=e.length ,n=t,r=0,i=this.data_attr;this.cached_nodes=[],this.nodes_loaded=t===0;while(n--){r++;var s=e[n].getAttribute(i)||"";s.length>0&&this.cached_nodes.push(e[n]),r===t&&(this.nodes_loaded=!0,this.enhance("nodes"))}return this},enhance:function(n){var r=this["cached_"+n].length;while(r--)this.object(e(this["cached_"+n][r]));return e(t).trigger("resize").trigger("resize.fndtn.interchange")},convert_directive:function(e){var t=this.trim(e);return t.length>0?t:"replace"},parse_scenario:function(e){var t=e[0].match(/(.+),\s*(\w+)\s*$/),n=e[1];if(t)var r=t[1],i=t[2];else var s=e[0].split(/,\s*$/),r=s[0],i="";return[this.trim(r),this.convert_directive(i),this.trim(n)]},object:function(e){var t=this.parse_data_attr(e),n=[],r=t.length;if(r>0)while(r--){var i=t[r].split(/\((.*?)(\))$/);if(i.length>1){var s=this.parse_scenario(i);n.push(s)}}return this.store(e,n)},store:function(e,t){var n=this.random_str(),r=e.data(this.add_namespace("uuid",!0));return this.cache[r]?this.cache[r]:(e.attr(this.add_namespace("data-uuid"),n),this.cache[n]=t)},trim:function(t){return typeof t=="string"?e.trim(t):t},set_data_attr:function(e){return e?this.namespace.length>0?this.namespace+"-"+this.settings.load_attr:this.settings.load_attr:this.namespace.length>0?"data-"+this.namespace+"-"+this.settings.load_attr:"data-"+this.settings.load_attr},parse_data_attr:function(e){var t=e.attr(this.attr_name()).split(/\[(.*?)\]/),n=t.length,r=[];while(n--)t[n].replace(/[\W\d]+/,"").length>4&&r.push(t[n]);return r},reflow:function(){this.load("images",!0),this.load("nodes",!0)}}}(jQuery,window,window.document),function(e,t,n,r){"use strict";Foundation.libs["magellan-expedition"]={name:"magellan-expedition",version:"5.3.3",settings:{active_class:"active",threshold:0,destination_threshold:20,throttle_delay:30,fixed_top:0},init:function(e,t,n){Foundation.inherit(this,"throttle"),this.bindings(t,n)},events:function(){var n=this,r=n.S,i=n.settings;n.set_expedition_position(),r(n.scope).off(".magellan").on("click.fndtn.magellan","["+n.add_namespace("data-magellan-arrival")+'] a[href^="#"]',function(t){t.preventDefault();var r=e(this).closest("["+n.attr_name()+"]"),i=r.data("magellan-expedition-init"),s=this.hash.split("#").join(""),o=e("a[name='"+s+"']");o.length===0&&(o=e("#"+s));var u=o.offset().top-i.destination_threshold+1;u-=r.outerHeight(),e("html, body").stop().animate({scrollTop:u},700,"swing",function(){history.pushState?history.pushState(null,null,"#"+s):location.hash="#"+s})}).on("scroll.fndtn.magellan",n.throttle(this.check_for_arrivals.bind(this),i.throttle_delay)),e(t).on("resize.fndtn.magellan",n.throttle(this.set_expedition_position.bind(this),i.throttle_delay))},check_for_arrivals:function(){var e=this;e.update_arrivals(),e.update_expedition_positions()},set_expedition_position:function(){var t=this;e("["+this.attr_name()+"=fixed]",t.scope).each(function(n,r){var i=e(this),s=i.data("magellan-expedition-init"),o=i.attr("styles"),u,a;i.attr("style",""),u=i.offset().top+s.threshold,a=parseInt(i.data("magellan-fixed-top")),isNaN(a)||(t.settings.fixed_top=a),i.data(t.data_attr("magellan-top-offset"),u),i.attr("style",o)})},update_expedition_positions:function(){var n=this,r=e(t).scrollTop();e("["+this.attr_name()+"=fixed]",n.scope).each(function(){var t=e(this),i=t.data("magellan-expedition-init"),s=t.attr("style"),o=t.data("magellan-top-offset");if(r+n.settings.fixed_top>=o){var u=t.prev("["+n.add_namespace("data-magellan-expedition-clone")+"]");u.length===0&&(u=t.clone(),u.removeAttr(n.attr_name()),u.attr(n.add_namespace("data-magellan-expedition-clone"),""),t.before(u)),t.css({position:"fixed",top:i.fixed_top}).addClass("fixed")}else t.prev("["+n.add_namespace("data-magellan-expedition-clone")+"]").remove(),t.attr("style",s).css("position","").css("top","").removeClass("fixed")})},update_arrivals:function(){var n=this,r=e(t).scrollTop();e("["+this.attr_name()+"]",n.scope).each(function(){var t=e(this),i=t.data(n.attr_name(!0)+"-init"),s=n.offsets(t,r),o=t.find("["+n.add_namespace("data-magellan-arrival")+"]"),u=!1;s.each(function(e,r){if(r.viewport_offset>=r.top_offset){var s=t.find("["+n.add_namespace("data-magellan-arrival")+"]");return s.not(r.arrival).removeClass(i.active_class),r.arrival.addClass(i.active_class),u=!0,!0}}),u||o.removeClass(i.active_class)})},offsets:function(t,n){var r=this,i=t.data(r.attr_name(!0)+"-init"),s=n;return t.find("["+r.add_namespace("data-magellan-arrival")+"]").map(function(n,o){var u=e(this).data(r.data_attr("magellan-arrival")),a=e("["+r.add_namespace("data-magellan-destination")+"="+u+"]");if(a.length>0){var f=Math.floor(a.offset().top-i.destination_threshold-t.outerHeight());return{destination:a,arrival:e(this),top_offset:f,viewport_offset:s}}}).sort(function(e,t){return e.top_offset<t.top_offset?-1:e.top_offset>t.top_offset?1:0})},data_attr:function(e){return this.namespace.length>0?this.namespace+"-"+e:e},off:function(){this.S(this.scope).off(".magellan"),this.S(t).off(".magellan")},reflow:function(){var t=this;e("["+t.add_namespace("data-magellan-expedition-clone")+"]",t.scope).remove()}}}(jQuery,window,window.document),function(e,t,n,r){"use strict";Foundation.libs.accordion={name:"accordion",version:"5.3.3",settings:{active_class:"active",multi_expand:!1,toggleable:!0,callback:function(){}},init:function(e,t,n){this.bindings(t,n)},events:function(){var t=this,n=this.S;n(this.scope).off(".fndtn.accordion").on("click.fndtn.accordion","["+this.attr_name()+"] > dd > a",function(r){var i=n(this).closest("["+t.attr_name()+"]"),s=t.attr_name()+"="+i.attr(t.attr_name()),o=i.data(t.attr_name(!0)+"-init"),u=n("#"+this.href.split("#")[1]),a=e("> dd",i),f=a.children(".content"),l=f.filter("."+o.active_class);r.preventDefault(),i.attr(t.attr_name())&&(f=f.add("["+s+"] dd > .content"),a=a.add("["+s+"] dd"));if(o.toggleable&&u.is(l)){u.parent("dd").toggleClass(o.active_class,!1),u.toggleClass(o.active_class,!1),o.callback(u),u.triggerHandler("toggled",[i]),i.triggerHandler("toggled",[u]);return}o.multi_expand||(f.removeClass(o.active_class),a.removeClass(o.active_class)),u.addClass(o.active_class).parent().addClass(o.active_class),o.callback(u),u.triggerHandler("toggled",[i]),i.triggerHandler("toggled",[u])})},off:function(){},reflow:function(){}}}(jQuery,window,window.document),function(e,t,n,r){"use strict";Foundation.libs.topbar={name:"topbar",version:"5.3.3",settings:{index:0,sticky_class:"sticky",custom_back_text:!0,back_text:"Back",mobile_show_parent_link:!0,is_hover:!0,scrolltop:!0,sticky_on:"all"},init:function(t,n,r){Foundation.inherit(this,"add_custom_rule register_media throttle");var i=this;i.register_media("topbar","foundation-mq-topbar"),this.bindings(n,r),i.S("["+this.attr_name()+"]",this.scope).each(function(){var t=e(this),n=t.data(i.attr_name(!0)+"-init"),r=i.S("section, .top-bar-section",this);t.data("index",0);var s=t.parent();s.hasClass("fixed")||i.is_sticky(t,s,n)?(i.settings.sticky_class=n.sticky_class,i.settings.sticky_topbar=t,t.data("height",s.outerHeight()),t.data("stickyoffset",s.offset().top)):t.data("height",t.outerHeight()),n.assembled||i.assemble(t),n.is_hover?i.S(".has-dropdown",t).addClass("not-click"):i.S(".has-dropdown",t).removeClass("not-click"),i.add_custom_rule(".f-topbar-fixed { padding-top: "+t.data("height")+"px }"),s.hasClass("fixed")&&i.S("body").addClass("f-topbar-fixed")})},is_sticky:function(e,t,n){var r=t.hasClass(n.sticky_class);return r&&n.sticky_on==="all"?!0:r&&this.small()&&n.sticky_on==="small"?matchMedia(Foundation.media_queries.small).matches&&!matchMedia(Foundation.media_queries.medium).matches&&!matchMedia(Foundation.media_queries.large).matches:r&&this.medium()&&n.sticky_on==="medium"?matchMedia(Foundation.media_queries.small).matches&&matchMedia(Foundation.media_queries.medium).matches&&!matchMedia(Foundation.media_queries.large).matches:r&&this.large()&&n.sticky_on==="large"?matchMedia(Foundation.media_queries.small).matches&&matchMedia(Foundation.media_queries.medium).matches&&matchMedia(Foundation.media_queries.large).matches:!1},toggle:function(n){var r=this,i;n?i=r.S(n).closest("["+this.attr_name()+"]"):i=r.S("["+this.attr_name()+"]");var s=i.data(this.attr_name(!0)+"-init"),o=r.S("section, .top-bar-section",i);r.breakpoint()&&(r.rtl?(o.css({right:"0%"}),e(">.name",o).css({right:"100%"})):(o.css({left:"0%"}),e(">.name",o).css({left:"100%"})),r.S("li.moved",o).removeClass("moved"),i.data("index",0),i.toggleClass("expanded").css("height","")),s.scrolltop?i.hasClass("expanded")?i.parent().hasClass("fixed")&&(s.scrolltop?(i.parent().removeClass("fixed"),i.addClass("fixed"),r.S("body").removeClass("f-topbar-fixed"),t.scrollTo(0,0)):i.parent().removeClass("expanded")):i.hasClass("fixed")&&(i.parent().addClass("fixed"),i.removeClass("fixed"),r.S("body").addClass("f-topbar-fixed")):(r.is_sticky(i,i.parent(),s)&&i.parent().addClass("fixed"),i.parent().hasClass("fixed")&&(i.hasClass("expanded")?(i.addClass("fixed"),i.parent().addClass("expanded"),r.S("body").addClass("f-topbar-fixed")):(i.removeClass("fixed"),i.parent().removeClass("expanded"),r.update_sticky_positioning())))},timer:null,events:function(n){var r=this,i=this.S;i(this.scope).off(".topbar").on("click.fndtn.topbar","["+this.attr_name()+"] .toggle-topbar",function(e){e.preventDefault(),r.toggle(this)}).on("click.fndtn.topbar",'.top-bar .top-bar-section li a[href^="#"],['+this.attr_name()+'] .top-bar-section li a[href^="#"]',function(t){var n=e(this).closest("li");r.breakpoint()&&!n.hasClass("back")&&!n.hasClass("has-dropdown")&&r.toggle()}).on("click.fndtn.topbar","["+this.attr_name()+"] li.has-dropdown",function(t){var n=i(this),s=i(t.target),o=n.closest("["+r.attr_name()+"]"),u=o.data(r.attr_name(!0)+"-init");if(s.data("revealId")){r.toggle();return}if(r.breakpoint())return;if(u.is_hover&&!Modernizr.touch)return;t.stopImmediatePropagation(),n.hasClass("hover")?(n.removeClass("hover").find("li").removeClass("hover"),n.parents("li.hover").removeClass("hover")):(n.addClass("hover"),e(n).siblings().removeClass("hover"),s[0].nodeName==="A"&&s.parent().hasClass("has-dropdown")&&t.preventDefault())}).on("click.fndtn.topbar","["+this.attr_name()+"] .has-dropdown>a",function(e){if(r.breakpoint()){e.preventDefault();var t=i(this),n=t.closest("["+r.attr_name()+"]"),s=n.find("section, .top-bar-section"),o=t.next(".dropdown").outerHeight(),u=t.closest("li");n.data("index",n.data("index")+1),u.addClass("moved"),r.rtl?(s.css({right:-(100*n.data("index"))+"%"}),s.find(">.name").css({right:100*n.data("index")+"%"})):(s.css({left:-(100*n.data("index"))+"%"}),s.find(">.name").css({left:100*n.data("index")+"%"})),n.css("height",t.siblings("ul").outerHeight(!0)+n.data("height"))}}),i(t).off(".topbar").on("resize.fndtn.topbar",r.throttle(function(){r.resize.call(r)},50)).trigger("resize").trigger("resize.fndtn.topbar").load(function(){i(this).trigger("resize.fndtn.topbar")}),i("body").off(".topbar").on("click.fndtn.topbar",function(e){var t=i(e.target).closest("li").closest("li.hover");if(t.length>0)return;i("["+r.attr_name()+"] li.hover").removeClass("hover")}),i(this.scope).on("click.fndtn.topbar","["+this.attr_name()+"] .has-dropdown .back",function(e){e.preventDefault();var t=i(this),n=t.closest("["+r.attr_name()+"]"),s=n.find("section, .top-bar-section"),o=n.data(r.attr_name(!0)+"-init"),u=t.closest("li.moved"),a=u.parent();n.data("index",n.data("index")-1),r.rtl?(s.css({right:-(100*n.data("index"))+"%"}),s.find(">.name").css({right:100*n.data("index")+"%"})):(s.css({left:-(100*n.data("index"))+"%"}),s.find(">.name").css({left:100*n.data("index")+"%"})),n.data("index")===0?n.css("height",""):n.css("height",a.outerHeight(!0)+n.data("height")),setTimeout(function(){u.removeClass("moved")},300)})},resize:function(){var e=this;e.S("["+this.attr_name()+"]").each(function(){var t=e.S(this),r=t.data(e.attr_name(!0)+"-init"),i=t.parent("."+e.settings.sticky_class),s;if(!e.breakpoint()){var o=t.hasClass("expanded");t.css("height","").removeClass("expanded").find("li").removeClass("hover"),o&&e.toggle(t)}e.is_sticky(t,i,r)&&(i.hasClass("fixed")?(i.removeClass("fixed"),s=i.offset().top,e.S(n.body).hasClass("f-topbar-fixed")&&(s-=t.data("height")),t.data("stickyoffset",s),i.addClass("fixed")):(s=i.offset().top,t.data("stickyoffset",s)))})},breakpoint:function(){return!matchMedia(Foundation.media_queries.topbar).matches},small:function(){return matchMedia(Foundation.media_queries.small).matches},medium:function(){return matchMedia(Foundation.media_queries.medium).matches},large:function(){return matchMedia(Foundation.media_queries.large).matches},assemble:function(t){var n=this,r=t.data(this.attr_name(!0)+"-init"),i=n.S("section, .top-bar-section",t);i.detach(),n.S(".has-dropdown>a",i).each(function(){var t=n.S(this),i=t.siblings(".dropdown"),s=t.attr("href"),o;i.find(".title.back").length||(r.mobile_show_parent_link==1&&s?o=e('<li class="title back js-generated"><h5><a href="javascript:void(0)"></a></h5></li><li class="parent-link show-for-small"><a class="parent-link js-generated" href="'+s+'">'+t.html()+"</a></li>"):o=e('<li class="title back js-generated"><h5><a href="javascript:void(0)"></a></h5>'),r.custom_back_text==1?e("h5>a",o).html(r.back_text):e("h5>a",o).html("&laquo; "+t.html()),i.prepend(o))}),i.appendTo(t),this.sticky(),this.assembled(t)},assembled:function(t){t.data(this.attr_name(!0),e.extend({},t.data(this.attr_name(!0)),{assembled:!0}))},height:function(t){var n=0,r=this;return e("> li",t).each(function(){n+=r.S(this).outerHeight(!0)}),n},sticky:function(){var e=this;this.S(t).on("scroll",function(){e.update_sticky_positioning()})},update_sticky_positioning:function(){var e="."+this.settings.sticky_class,n=this.S(t),r=this;if(r.settings.sticky_topbar&&r.is_sticky(this.settings.sticky_topbar,this.settings.sticky_topbar.parent(),this.settings)){var i=this.settings.sticky_topbar.data("stickyoffset");r.S(e).hasClass("expanded")||(n.scrollTop()>i?r.S(e).hasClass("fixed")||(r.S(e).addClass("fixed"),r.S("body").addClass("f-topbar-fixed")):n.scrollTop()<=i&&r.S(e).hasClass("fixed")&&(r.S(e).removeClass("fixed"),r.S("body").removeClass("f-topbar-fixed")))}},off:function(){this.S(this.scope).off(".fndtn.topbar"),this.S(t).off(".fndtn.topbar")},reflow:function(){}}}(jQuery,window,window.document),function(e,t,n,r){"use strict";Foundation.libs.tab={name:"tab",version:"5.3.3",settings:{active_class:"active",callback:function(){},deep_linking:!1,scroll_to_content:!0,is_hover:!1},default_tab_hashes:[],init:function(e,t,n){var r=this,i=this.S;this.bindings(t,n),this.handle_location_hash_change(),i("["+this.attr_name()+"] > .active > a",this.scope).each(function(){r.default_tab_hashes.push(this.hash)})},events:function(){var e=this,n=this.S;n(this.scope).off(".tab").on("click.fndtn.tab","["+this.attr_name()+"] > * > a",function(t){var r=n(this).closest("["+e.attr_name()+"]").data(e.attr_name(!0)+"-init");if(!r.is_hover||Modernizr.touch)t.preventDefault(),t.stopPropagation(),e.toggle_active_tab(n(this).parent())}).on("mouseenter.fndtn.tab","["+this.attr_name()+"] > * > a",function(t){var r=n(this).closest("["+e.attr_name()+"]").data(e.attr_name(!0)+"-init");r.is_hover&&e.toggle_active_tab(n(this).parent())}),n(t).on("hashchange.fndtn.tab",function(t){t.preventDefault(),e.handle_location_hash_change()})},handle_location_hash_change:function(){var t=this,n=this.S;n("["+this.attr_name()+"]",this.scope).each(function(){var i=n(this).data(t.attr_name(!0)+"-init");if(i.deep_linking){var s=t.scope.location.hash;if(s!=""){var o=n(s);if(o.hasClass("content")&&o.parent().hasClass("tab-content"))t.toggle_active_tab(e("["+t.attr_name()+"] > * > a[href="+s+"]").parent());else{var u=o.closest(".content").attr("id");u!=r&&t.toggle_active_tab(e("["+t.attr_name()+"] > * > a[href=#"+u+"]").parent(),s)}}else for(var a in t.default_tab_hashes)t.toggle_active_tab(e("["+t.attr_name()+"] > * > a[href="+t.default_tab_hashes[a]+"]").parent())}})},toggle_active_tab:function(n,i){var s=this.S,o=n.closest("["+this.attr_name()+"]"),u=n.children("a").first(),a="#"+u.attr("href").split("#")[1],f=s(a),l=n.siblings(),c=o.data(this.attr_name(!0)+"-init");s(this).data(this.data_attr("tab-content"))&&(a="#"+s(this).data(this.data_attr("tab-content")).split("#")[1],f=s(a));if(c.deep_linking){var h=e("body,html").scrollTop();i!=r?t.location.hash=i:t.location.hash=a,c.scroll_to_content?i==r||i==a?n.parent()[0].scrollIntoView():s(a)[0].scrollIntoView():(i==r||i==a)&&e("body,html").scrollTop(h)}n.addClass(c.active_class).triggerHandler("opened"),l.removeClass(c.active_class),f.siblings().removeClass(c.active_class).end().addClass(c.active_class),c.callback(n),f.triggerHandler("toggled",[n]),o.triggerHandler("toggled",[f])},data_attr:function(e){return this.namespace.length>0?this.namespace+"-"+e:e},off:function(){},reflow:function(){}}}(jQuery,window,window.document),function(e,t,n,r){"use strict";Foundation.libs.abide={name:"abide",version:"5.3.3",settings:{live_validate:!0,focus_on_invalid:!0,error_labels:!0,timeout:1e3,patterns:{alpha:/^[a-zA-Z]+$/,alpha_numeric:/^[a-zA-Z0-9]+$/,integer:/^[-+]?\d+$/,number:/^[-+]?\d*(?:[\.\,]\d+)?$/,card:/^(?:4[0-9]{12}(?:[0-9]{3})?|5[1-5][0-9]{14}|6(?:011|5[0-9][0-9])[0-9]{12}|3[47][0-9]{13}|3(?:0[0-5]|[68][0-9])[0-9]{11}|(?:2131|1800|35\d{3})\d{11})$/,cvv:/^([0-9]){3,4}$/,email:/^[a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/,url:/^(https?|ftp|file|ssh):\/\/(((([a-zA-Z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:)*@)?(((\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5]))|((([a-zA-Z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-zA-Z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-zA-Z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-zA-Z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-zA-Z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-zA-Z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-zA-Z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-zA-Z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?)(:\d*)?)(\/((([a-zA-Z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)+(\/(([a-zA-Z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)*)*)?)?(\?((([a-zA-Z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|[\uE000-\uF8FF]|\/|\?)*)?(\#((([a-zA-Z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|\/|\?)*)?$/,domain:/^([a-zA-Z0-9]([a-zA-Z0-9\-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,6}$/,datetime:/^([0-2][0-9]{3})\-([0-1][0-9])\-([0-3][0-9])T([0-5][0-9])\:([0-5][0-9])\:([0-5][0-9])(Z|([\-\+]([0-1][0-9])\:00))$/,date:/(?:19|20)[0-9]{2}-(?:(?:0[1-9]|1[0-2])-(?:0[1-9]|1[0-9]|2[0-9])|(?:(?!02)(?:0[1-9]|1[0-2])-(?:30))|(?:(?:0[13578]|1[02])-31))$/,time:/^(0[0-9]|1[0-9]|2[0-3])(:[0-5][0-9]){2}$/,dateISO:/^\d{4}[\/\-]\d{1,2}[\/\-]\d{1,2}$/,month_day_year:/^(0[1-9]|1[012])[- \/.](0[1-9]|[12][0-9]|3[01])[- \/.]\d{4}$/,color:/^#?([a-fA-F0-9]{6}|[a-fA-F0-9]{3})$/},validators:{equalTo:function(e,t,r){var i=n.getElementById(e.getAttribute(this.add_namespace("data-equalto"))).value,s=e.value,o=i===s;return o}}},timer:null,init:function(e,t,n){this.bindings(t,n)},events:function(t){var n=this,r=n.S(t).attr("novalidate","novalidate"),i=r.data(this.attr_name(!0)+"-init")||{};this.invalid_attr=this.add_namespace("data-invalid"),r.off(".abide").on("submit.fndtn.abide validate.fndtn.abide",function(e){var t=/ajax/i.test(n.S(this).attr(n.attr_name()));return n.validate(n.S(this).find("input, textarea, select").get(),e,t)}).on("reset",function(){return n.reset(e(this))}).find("input, textarea, select").off(".abide").on("blur.fndtn.abide change.fndtn.abide",function(e){n.validate([this],e)}).on("keydown.fndtn.abide",function(e){i.live_validate===!0&&(clearTimeout(n.timer),n.timer=setTimeout(function(){n.validate([this],e)}.bind(this),i.timeout))})},reset:function(t){t.removeAttr(this.invalid_attr),e(this.invalid_attr,t).removeAttr(this.invalid_attr),e(".error",t).not("small").removeClass("error")},validate:function(e,t,n){var r=this.parse_patterns(e),i=r.length,s=this.S(e[0]).closest("form"),o=/submit/.test(t.type);for(var u=0;u<i;u++)if(!r[u]&&(o||n))return this.settings.focus_on_invalid&&e[u].focus(),s.trigger("invalid"),this.S(e[u]).closest("form").attr(this.invalid_attr,""),!1;return(o||n)&&s.trigger("valid"),s.removeAttr(this.invalid_attr),n?!1:!0},parse_patterns:function(e){var t=e.length,n=[];while(t--)n.push(this.pattern(e[t]));return this.check_validation_and_apply_styles(n)},pattern:function(e){var t=e.getAttribute("type"),n=typeof e.getAttribute("required")=="string",r=e.getAttribute("pattern")||"";return this.settings.patterns.hasOwnProperty(r)&&r.length>0?[e,this.settings.patterns[r],n]:r.length>0?[e,new RegExp(r),n]:this.settings.patterns.hasOwnProperty(t)?[e,this.settings.patterns[t],n]:(r=/.*/,[e,r,n])},check_validation_and_apply_styles:function(t){var n=t.length,r=[],i=this.S(t[0][0]).closest("[data-"+this.attr_name(!0)+"]"),s=i.data(this.attr_name(!0)+"-init")||{};while(n--){var o=t[n][0],u=t[n][2],a=o.value.trim(),f=this.S(o).parent(),l=o.getAttribute(this.add_namespace("data-abide-validator")),c=o.type==="radio",h=o.type==="checkbox",p=this.S('label[for="'+o.getAttribute("id")+'"]'),d=u?o.value.length>0:!0,v,m;o.getAttribute(this.add_namespace("data-equalto"))&&(l="equalTo"),f.is("label")?v=f.parent():v=f,c&&u?r.push(this.valid_radio(o,u)):h&&u?r.push(this.valid_checkbox(o,u)):(l&&(m=this.settings.validators[l].apply(this,[o,u,v]),r.push(m)),t[n][1].test(a)&&d||!u&&o.value.length<1||e(o).attr("disabled")?r.push(!0):r.push(!1),r=[r.every(function(e){return e})],r[0]?(this.S(o).removeAttr(this.invalid_attr),v.removeClass("error"),p.length>0&&this.settings.error_labels&&p.removeClass("error"),e(o).triggerHandler("valid")):(v.addClass("error"),this.S(o).attr(this.invalid_attr,""),p.length>0&&this.settings.error_labels&&p.addClass("error"),e(o).triggerHandler("invalid")))}return r},valid_checkbox:function(e,t){var e=this.S(e),n=e.is(":checked")||!t;return n?e.removeAttr(this.invalid_attr).parent().removeClass("error"):e.attr(this.invalid_attr,"").parent().addClass("error"),n},valid_radio:function(e,t){var n=e.getAttribute("name"),r=this.S(e).closest("[data-"+this.attr_name(!0)+"]").find("[name='"+n+"']"),i=r.length,s=!1;for(var o=0;o<i;o++)r[o].checked&&(s=!0);for(var o=0;o<i;o++)s?this.S(r[o]).removeAttr(this.invalid_attr).parent().removeClass("error"):this.S(r[o]).attr(this.invalid_attr,"").parent().addClass("error");return s},valid_equal:function(e,t,r){var i=n.getElementById(e.getAttribute(this.add_namespace("data-equalto"))).value,s=e.value,o=i===s;return o?(this.S(e).removeAttr(this.invalid_attr),r.removeClass("error")):(this.S(e).attr(this.invalid_attr,""),r.addClass("error")),o},valid_oneof:function(e,t,n,r){var e=this.S(e),i=this.S("["+this.add_namespace("data-oneof")+"]"),s=i.filter(":checked").length>0;s?e.removeAttr(this.invalid_attr).parent().removeClass("error"):e.attr(this.invalid_attr,"").parent().addClass("error");if(!r){var o=this;i.each(function(){o.valid_oneof.call(o,this,null,null,!0)})}return s}}}(jQuery,window,window.document),function(e,t,n,r){"use strict";Foundation.libs.tooltip={name:"tooltip",version:"5.3.3",settings:{additional_inheritable_classes:[],tooltip_class:".tooltip",append_to:"body",touch_close_text:"Tap To Close",disable_for_touch:!1,hover_delay:200,show_on:"all",tip_template:function(e,t){return'<span data-selector="'+e+'" class="'+Foundation.libs.tooltip.settings.tooltip_class.substring(1)+'">'+t+'<span class="nub"></span></span>'}},cache:{},init:function(e,t,n){Foundation.inherit(this,"random_str"),this.bindings(t,n)},should_show:function(t,n){var r=e.extend({},this.settings,this.data_options(t));return r.show_on==="all"?!0:this.small()&&r.show_on==="small"?!0:this.medium()&&r.show_on==="medium"?!0:this.large()&&r.show_on==="large"?!0:!1},medium:function(){return matchMedia(Foundation.media_queries.medium).matches},large:function(){return matchMedia(Foundation.media_queries.large).matches},events:function(t){var n=this,r=n.S;n.create(this.S(t)),e(this.scope).off(".tooltip").on("mouseenter.fndtn.tooltip mouseleave.fndtn.tooltip touchstart.fndtn.tooltip MSPointerDown.fndtn.tooltip","["+this.attr_name()+"]",function(t){var i=r(this),s=e.extend({},n.settings,n.data_options(i)),o=!1;if(Modernizr.touch&&/touchstart|MSPointerDown/i.test(t.type)&&r(t.target).is("a"))return!1;if(/mouse/i.test(t.type)&&n.ie_touch(t))return!1;if(i.hasClass("open"))Modernizr.touch&&/touchstart|MSPointerDown/i.test(t.type)&&t.preventDefault(),n.hide(i);else{if(s.disable_for_touch&&Modernizr.touch&&/touchstart|MSPointerDown/i.test(t.type))return;!s.disable_for_touch&&Modernizr.touch&&/touchstart|MSPointerDown/i.test(t.type)&&(t.preventDefault(),r(s.tooltip_class+".open").hide(),o=!0),/enter|over/i.test(t.type)?this.timer=setTimeout(function(){var e=n.showTip(i)}.bind(this),n.settings.hover_delay):t.type==="mouseout"||t.type==="mouseleave"?(clearTimeout(this.timer),n.hide(i)):n.showTip(i)}}).on("mouseleave.fndtn.tooltip touchstart.fndtn.tooltip MSPointerDown.fndtn.tooltip","["+this.attr_name()+"].open",function(t){if(/mouse/i.test(t.type)&&n.ie_touch(t))return!1;if(e(this).data("tooltip-open-event-type")=="touch"&&t.type=="mouseleave")return;e(this).data("tooltip-open-event-type")=="mouse"&&/MSPointerDown|touchstart/i.test(t.type)?n.convert_to_touch(e(this)):n.hide(e(this))}).on("DOMNodeRemoved DOMAttrModified","["+this.attr_name()+"]:not(a)",function(e){n.hide(r(this))})},ie_touch:function(e){return!1},showTip:function(e){var t=this.getTip(e);if(this.should_show(e,t))return this.show(e);return},getTip:function(t){var n=this.selector(t),r=e.extend({},this.settings,this.data_options(t)),i=null;return n&&(i=this.S('span[data-selector="'+n+'"]'+r.tooltip_class)),typeof i=="object"?i:!1},selector:function(e){var t=e.attr("id"),n=e.attr(this.attr_name())||e.attr("data-selector");return(t&&t.length<1||!t)&&typeof n!="string"&&(n=this.random_str(6),e.attr("data-selector",n)),t&&t.length>0?t:n},create:function(n){var r=this,i=e.extend({},this.settings,this.data_options(n)),s=this.settings.tip_template;typeof i.tip_template=="string"&&t.hasOwnProperty(i.tip_template)&&(s=t[i.tip_template]);var o=e(s(this.selector(n),e("<div></div>").html(n.attr("title")).html())),u=this.inheritable_classes(n);o.addClass(u).appendTo(i.append_to),Modernizr.touch&&(o.append('<span class="tap-to-close">'+i.touch_close_text+"</span>"),o.on("touchstart.fndtn.tooltip MSPointerDown.fndtn.tooltip",function(e){r.hide(n)})),n.removeAttr("title").attr("title","")},reposition:function(t,n,r){var i,s,o,u,a,f;n.css("visibility","hidden").show(),i=t.data("width"),s=n.children(".nub"),o=s.outerHeight(),u=s.outerHeight(),this.small()?n.css({width:"100%"}):n.css({width:i?i:"auto"}),f=function(e,t,n,r,i,s){return e.css({top:t?t:"auto",bottom:r?r:"auto",left:i?i:"auto",right:n?n:"auto"}).end()},f(n,t.offset().top+t.outerHeight()+10,"auto","auto",t.offset().left);if(this.small())f(n,t.offset().top+t.outerHeight()+10,"auto","auto",12.5,e(this.scope).width()),n.addClass("tip-override"),f(s,-o,"auto","auto",t.offset().left);else{var l=t.offset().left;Foundation.rtl&&(s.addClass("rtl"),l=t.offset().left+t.outerWidth()-n.outerWidth()),f(n,t.offset().top+t.outerHeight()+10,"auto","auto",l),n.removeClass("tip-override"),r&&r.indexOf("tip-top")>-1?(Foundation.rtl&&s.addClass("rtl"),f(n,t.offset().top-n.outerHeight(),"auto","auto",l).removeClass("tip-override")):r&&r.indexOf("tip-left")>-1?(f(n,t.offset().top+t.outerHeight()/2-n.outerHeight()/2,"auto","auto",t.offset().left-n.outerWidth()-o).removeClass("tip-override"),s.removeClass("rtl")):r&&r.indexOf("tip-right")>-1&&(f(n,t.offset().top+t.outerHeight()/2-n.outerHeight()/2,"auto","auto",t.offset().left+t.outerWidth()+o).removeClass("tip-override"),s.removeClass("rtl"))}n.css("visibility","visible").hide()},small:function(){return matchMedia(Foundation.media_queries.small).matches&&!matchMedia(Foundation.media_queries.medium).matches},inheritable_classes:function(t){var n=e.extend({},this.settings,this.data_options(t)),r=["tip-top","tip-left","tip-bottom","tip-right","radius","round"].concat(n.additional_inheritable_classes),i=t.attr("class"),s=i?e.map(i.split(" "),function(t,n){if(e.inArray(t,r)!==-1)return t}).join(" "):"";return e.trim(s)},convert_to_touch:function(t){var n=this,r=n.getTip(t),i=e.extend({},n.settings,n.data_options(t));r.find(".tap-to-close").length===0&&(r.append('<span class="tap-to-close">'+i.touch_close_text+"</span>"),r.on("click.fndtn.tooltip.tapclose touchstart.fndtn.tooltip.tapclose MSPointerDown.fndtn.tooltip.tapclose",function(e){n.hide(t)})),t.data("tooltip-open-event-type","touch")},show:function(e){var t=this.getTip(e);e.data("tooltip-open-event-type")=="touch"&&this.convert_to_touch(e),this.reposition(e,t,e.attr("class")),e.addClass("open"),t.fadeIn(150)},hide:function(e){var t=this.getTip(e);t.fadeOut(150,function(){t.find(".tap-to-close").remove(),t.off("click.fndtn.tooltip.tapclose MSPointerDown.fndtn.tapclose"),e.removeClass("open")})},off:function(){var t=this;this.S(this.scope).off(".fndtn.tooltip"),this.S(this.settings.tooltip_class).each(function(n){e("["+t.attr_name()+"]").eq(n).attr("title",e(this).text())}).remove()},reflow:function(){}}}(jQuery,window,window.document);
akkumar/jsdelivr
files/foundation/5.4.4/js/foundation.min.js
JavaScript
mit
95,120
(function(){var mode=CodeMirror.getMode({tabSize:4},"gfm");function MT(name){test.mode(name,mode,Array.prototype.slice.call(arguments,1))}MT("emInWordAsterisk","foo[em *bar*]hello");MT("emInWordUnderscore","foo_bar_hello");MT("emStrongUnderscore","[strong __][em&strong _foo__][em _] bar");MT("fencedCodeBlocks","[comment ```]","[comment foo]","","[comment ```]","bar");MT("fencedCodeBlockModeSwitching","[comment ```javascript]","[variable foo]","","[comment ```]","bar");MT("taskListAsterisk","[variable-2 * []] foo]","[variable-2 * [ ]]bar]","[variable-2 * [x]]hello]","[variable-2 * ][meta [ ]]][variable-2 [world]]]"," [variable-3 * ][property [x]]][variable-3 foo]");MT("taskListPlus","[variable-2 + []] foo]","[variable-2 + [ ]]bar]","[variable-2 + [x]]hello]","[variable-2 + ][meta [ ]]][variable-2 [world]]]"," [variable-3 + ][property [x]]][variable-3 foo]");MT("taskListDash","[variable-2 - []] foo]","[variable-2 - [ ]]bar]","[variable-2 - [x]]hello]","[variable-2 - ][meta [ ]]][variable-2 [world]]]"," [variable-3 - ][property [x]]][variable-3 foo]");MT("taskListNumber","[variable-2 1. []] foo]","[variable-2 2. [ ]]bar]","[variable-2 3. [x]]hello]","[variable-2 4. ][meta [ ]]][variable-2 [world]]]"," [variable-3 1. ][property [x]]][variable-3 foo]");MT("SHA","foo [link be6a8cc1c1ecfe9489fb51e4869af15a13fc2cd2] bar");MT("shortSHA","foo [link be6a8cc] bar");MT("tooShortSHA","foo be6a8c bar");MT("longSHA","foo be6a8cc1c1ecfe9489fb51e4869af15a13fc2cd22 bar");MT("badSHA","foo be6a8cc1c1ecfe9489fb51e4869af15a13fc2cg2 bar");MT("userSHA","foo [link bar@be6a8cc1c1ecfe9489fb51e4869af15a13fc2cd2] hello");MT("userProjectSHA","foo [link bar/hello@be6a8cc1c1ecfe9489fb51e4869af15a13fc2cd2] world");MT("num","foo [link #1] bar");MT("badNum","foo #1bar hello");MT("userNum","foo [link bar#1] hello");MT("userProjectNum","foo [link bar/hello#1] world");MT("vanillaLink","foo [link http://www.example.com/] bar");MT("vanillaLinkPunctuation","foo [link http://www.example.com/]. bar");MT("vanillaLinkExtension","foo [link http://www.example.com/index.html] bar");MT("notALink","[comment ```css]","[tag foo] {[property color][operator :][keyword black];}","[comment ```][link http://www.example.com/]");MT("notALink","[comment ``foo `bar` http://www.example.com/``] hello");MT("notALink","[comment `foo]","[link http://www.example.com/]","[comment `foo]","","[link http://www.example.com/]")})();
tcorral/cdnjs
ajax/libs/codemirror/3.19.0/mode/gfm/test.min.js
JavaScript
mit
2,422
@import url('//fonts.googleapis.com/css?family=News+Cycle:400,700');/*! * Bootstrap v2.3.0 * * Copyright 2012 Twitter, Inc * Licensed under the Apache License v2.0 * http://www.apache.org/licenses/LICENSE-2.0 * * Designed and built with all the love in the world @twitter by @mdo and @fat. */.clearfix{*zoom:1}.clearfix:before,.clearfix:after{display:table;line-height:0;content:""}.clearfix:after{clear:both}.hide-text{font:0/0 a;color:transparent;text-shadow:none;background-color:transparent;border:0}.input-block-level{display:block;width:100%;min-height:30px;-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}article,aside,details,figcaption,figure,footer,header,hgroup,nav,section{display:block}audio,canvas,video{display:inline-block;*display:inline;*zoom:1}audio:not([controls]){display:none}html{font-size:100%;-webkit-text-size-adjust:100%;-ms-text-size-adjust:100%}a:focus{outline:thin dotted #333;outline:5px auto -webkit-focus-ring-color;outline-offset:-2px}a:hover,a:active{outline:0}sub,sup{position:relative;font-size:75%;line-height:0;vertical-align:baseline}sup{top:-0.5em}sub{bottom:-0.25em}img{width:auto\9;height:auto;max-width:100%;vertical-align:middle;border:0;-ms-interpolation-mode:bicubic}#map_canvas img,.google-maps img{max-width:none}button,input,select,textarea{margin:0;font-size:100%;vertical-align:middle}button,input{*overflow:visible;line-height:normal}button::-moz-focus-inner,input::-moz-focus-inner{padding:0;border:0}button,html input[type="button"],input[type="reset"],input[type="submit"]{cursor:pointer;-webkit-appearance:button}label,select,button,input[type="button"],input[type="reset"],input[type="submit"],input[type="radio"],input[type="checkbox"]{cursor:pointer}input[type="search"]{-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box;-webkit-appearance:textfield}input[type="search"]::-webkit-search-decoration,input[type="search"]::-webkit-search-cancel-button{-webkit-appearance:none}textarea{overflow:auto;vertical-align:top}@media print{*{color:#000!important;text-shadow:none!important;background:transparent!important;box-shadow:none!important}a,a:visited{text-decoration:underline}a[href]:after{content:" (" attr(href) ")"}abbr[title]:after{content:" (" attr(title) ")"}.ir a:after,a[href^="javascript:"]:after,a[href^="#"]:after{content:""}pre,blockquote{border:1px solid #999;page-break-inside:avoid}thead{display:table-header-group}tr,img{page-break-inside:avoid}img{max-width:100%!important}@page{margin:.5cm}p,h2,h3{orphans:3;widows:3}h2,h3{page-break-after:avoid}}body{margin:0;font-family:Georgia,"Times New Roman",Times,serif;font-size:14px;line-height:20px;color:#777;background-color:#fff}a{color:#777;text-decoration:none}a:hover,a:focus{color:#777;text-decoration:underline}.img-rounded{-webkit-border-radius:6px;-moz-border-radius:6px;border-radius:6px}.img-polaroid{padding:4px;background-color:#fff;border:1px solid #ccc;border:1px solid rgba(0,0,0,0.2);-webkit-box-shadow:0 1px 3px rgba(0,0,0,0.1);-moz-box-shadow:0 1px 3px rgba(0,0,0,0.1);box-shadow:0 1px 3px rgba(0,0,0,0.1)}.img-circle{-webkit-border-radius:500px;-moz-border-radius:500px;border-radius:500px}.row{margin-left:-20px;*zoom:1}.row:before,.row:after{display:table;line-height:0;content:""}.row:after{clear:both}[class*="span"]{float:left;min-height:1px;margin-left:20px}.container,.navbar-static-top .container,.navbar-fixed-top .container,.navbar-fixed-bottom .container{width:940px}.span12{width:940px}.span11{width:860px}.span10{width:780px}.span9{width:700px}.span8{width:620px}.span7{width:540px}.span6{width:460px}.span5{width:380px}.span4{width:300px}.span3{width:220px}.span2{width:140px}.span1{width:60px}.offset12{margin-left:980px}.offset11{margin-left:900px}.offset10{margin-left:820px}.offset9{margin-left:740px}.offset8{margin-left:660px}.offset7{margin-left:580px}.offset6{margin-left:500px}.offset5{margin-left:420px}.offset4{margin-left:340px}.offset3{margin-left:260px}.offset2{margin-left:180px}.offset1{margin-left:100px}.row-fluid{width:100%;*zoom:1}.row-fluid:before,.row-fluid:after{display:table;line-height:0;content:""}.row-fluid:after{clear:both}.row-fluid [class*="span"]{display:block;float:left;width:100%;min-height:30px;margin-left:2.127659574468085%;*margin-left:2.074468085106383%;-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}.row-fluid [class*="span"]:first-child{margin-left:0}.row-fluid .controls-row [class*="span"]+[class*="span"]{margin-left:2.127659574468085%}.row-fluid .span12{width:100%;*width:99.94680851063829%}.row-fluid .span11{width:91.48936170212765%;*width:91.43617021276594%}.row-fluid .span10{width:82.97872340425532%;*width:82.92553191489361%}.row-fluid .span9{width:74.46808510638297%;*width:74.41489361702126%}.row-fluid .span8{width:65.95744680851064%;*width:65.90425531914893%}.row-fluid .span7{width:57.44680851063829%;*width:57.39361702127659%}.row-fluid .span6{width:48.93617021276595%;*width:48.88297872340425%}.row-fluid .span5{width:40.42553191489362%;*width:40.37234042553192%}.row-fluid .span4{width:31.914893617021278%;*width:31.861702127659576%}.row-fluid .span3{width:23.404255319148934%;*width:23.351063829787233%}.row-fluid .span2{width:14.893617021276595%;*width:14.840425531914894%}.row-fluid .span1{width:6.382978723404255%;*width:6.329787234042553%}.row-fluid .offset12{margin-left:104.25531914893617%;*margin-left:104.14893617021275%}.row-fluid .offset12:first-child{margin-left:102.12765957446808%;*margin-left:102.02127659574467%}.row-fluid .offset11{margin-left:95.74468085106382%;*margin-left:95.6382978723404%}.row-fluid .offset11:first-child{margin-left:93.61702127659574%;*margin-left:93.51063829787232%}.row-fluid .offset10{margin-left:87.23404255319149%;*margin-left:87.12765957446807%}.row-fluid .offset10:first-child{margin-left:85.1063829787234%;*margin-left:84.99999999999999%}.row-fluid .offset9{margin-left:78.72340425531914%;*margin-left:78.61702127659572%}.row-fluid .offset9:first-child{margin-left:76.59574468085106%;*margin-left:76.48936170212764%}.row-fluid .offset8{margin-left:70.2127659574468%;*margin-left:70.10638297872339%}.row-fluid .offset8:first-child{margin-left:68.08510638297872%;*margin-left:67.9787234042553%}.row-fluid .offset7{margin-left:61.70212765957446%;*margin-left:61.59574468085106%}.row-fluid .offset7:first-child{margin-left:59.574468085106375%;*margin-left:59.46808510638297%}.row-fluid .offset6{margin-left:53.191489361702125%;*margin-left:53.085106382978715%}.row-fluid .offset6:first-child{margin-left:51.063829787234035%;*margin-left:50.95744680851063%}.row-fluid .offset5{margin-left:44.68085106382979%;*margin-left:44.57446808510638%}.row-fluid .offset5:first-child{margin-left:42.5531914893617%;*margin-left:42.4468085106383%}.row-fluid .offset4{margin-left:36.170212765957444%;*margin-left:36.06382978723405%}.row-fluid .offset4:first-child{margin-left:34.04255319148936%;*margin-left:33.93617021276596%}.row-fluid .offset3{margin-left:27.659574468085104%;*margin-left:27.5531914893617%}.row-fluid .offset3:first-child{margin-left:25.53191489361702%;*margin-left:25.425531914893618%}.row-fluid .offset2{margin-left:19.148936170212764%;*margin-left:19.04255319148936%}.row-fluid .offset2:first-child{margin-left:17.02127659574468%;*margin-left:16.914893617021278%}.row-fluid .offset1{margin-left:10.638297872340425%;*margin-left:10.53191489361702%}.row-fluid .offset1:first-child{margin-left:8.51063829787234%;*margin-left:8.404255319148938%}[class*="span"].hide,.row-fluid [class*="span"].hide{display:none}[class*="span"].pull-right,.row-fluid [class*="span"].pull-right{float:right}.container{margin-right:auto;margin-left:auto;*zoom:1}.container:before,.container:after{display:table;line-height:0;content:""}.container:after{clear:both}.container-fluid{padding-right:20px;padding-left:20px;*zoom:1}.container-fluid:before,.container-fluid:after{display:table;line-height:0;content:""}.container-fluid:after{clear:both}p{margin:0 0 10px}.lead{margin-bottom:20px;font-size:21px;font-weight:200;line-height:30px}small{font-size:85%}strong{font-weight:bold}em{font-style:italic}cite{font-style:normal}.muted{color:#bbb}a.muted:hover,a.muted:focus{color:#a2a2a2}.text-warning{color:#c09853}a.text-warning:hover,a.text-warning:focus{color:#a47e3c}.text-error{color:#b94a48}a.text-error:hover,a.text-error:focus{color:#953b39}.text-info{color:#3a87ad}a.text-info:hover,a.text-info:focus{color:#2d6987}.text-success{color:#468847}a.text-success:hover,a.text-success:focus{color:#356635}.text-left{text-align:left}.text-right{text-align:right}.text-center{text-align:center}h1,h2,h3,h4,h5,h6{margin:10px 0;font-family:"News Cycle","Arial Narrow Bold",sans-serif;font-weight:bold;line-height:20px;color:#000;text-rendering:optimizelegibility}h1 small,h2 small,h3 small,h4 small,h5 small,h6 small{font-weight:normal;line-height:1;color:#bbb}h1,h2,h3{line-height:40px}h1{font-size:38.5px}h2{font-size:31.5px}h3{font-size:24.5px}h4{font-size:17.5px}h5{font-size:14px}h6{font-size:11.9px}h1 small{font-size:24.5px}h2 small{font-size:17.5px}h3 small{font-size:14px}h4 small{font-size:14px}.page-header{padding-bottom:9px;margin:20px 0 30px;border-bottom:1px solid #eee}ul,ol{padding:0;margin:0 0 10px 25px}ul ul,ul ol,ol ol,ol ul{margin-bottom:0}li{line-height:20px}ul.unstyled,ol.unstyled{margin-left:0;list-style:none}ul.inline,ol.inline{margin-left:0;list-style:none}ul.inline>li,ol.inline>li{display:inline-block;*display:inline;padding-right:5px;padding-left:5px;*zoom:1}dl{margin-bottom:20px}dt,dd{line-height:20px}dt{font-weight:bold}dd{margin-left:10px}.dl-horizontal{*zoom:1}.dl-horizontal:before,.dl-horizontal:after{display:table;line-height:0;content:""}.dl-horizontal:after{clear:both}.dl-horizontal dt{float:left;width:160px;overflow:hidden;clear:left;text-align:right;text-overflow:ellipsis;white-space:nowrap}.dl-horizontal dd{margin-left:180px}hr{margin:20px 0;border:0;border-top:1px solid #eee;border-bottom:1px solid #fff}abbr[title],abbr[data-original-title]{cursor:help;border-bottom:1px dotted #bbb}abbr.initialism{font-size:90%;text-transform:uppercase}blockquote{padding:0 0 0 15px;margin:0 0 20px;border-left:5px solid #eee}blockquote p{margin-bottom:0;font-size:17.5px;font-weight:300;line-height:1.25}blockquote small{display:block;line-height:20px;color:#bbb}blockquote small:before{content:'\2014 \00A0'}blockquote.pull-right{float:right;padding-right:15px;padding-left:0;border-right:5px solid #eee;border-left:0}blockquote.pull-right p,blockquote.pull-right small{text-align:right}blockquote.pull-right small:before{content:''}blockquote.pull-right small:after{content:'\00A0 \2014'}q:before,q:after,blockquote:before,blockquote:after{content:""}address{display:block;margin-bottom:20px;font-style:normal;line-height:20px}code,pre{padding:0 3px 2px;font-family:Menlo,Monaco,Consolas,"Courier New",monospace;font-size:12px;color:#777;-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px}code{padding:2px 4px;color:#d14;white-space:nowrap;background-color:#f7f7f9;border:1px solid #e1e1e8}pre{display:block;padding:9.5px;margin:0 0 10px;font-size:13px;line-height:20px;word-break:break-all;word-wrap:break-word;white-space:pre;white-space:pre-wrap;background-color:#f5f5f5;border:1px solid #ccc;border:1px solid rgba(0,0,0,0.15);-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px}pre.prettyprint{margin-bottom:20px}pre code{padding:0;color:inherit;white-space:pre;white-space:pre-wrap;background-color:transparent;border:0}.pre-scrollable{max-height:340px;overflow-y:scroll}form{margin:0 0 20px}fieldset{padding:0;margin:0;border:0}legend{display:block;width:100%;padding:0;margin-bottom:20px;font-size:21px;line-height:40px;color:#777;border:0;border-bottom:1px solid #e5e5e5}legend small{font-size:15px;color:#bbb}label,input,button,select,textarea{font-size:14px;font-weight:normal;line-height:20px}input,button,select,textarea{font-family:Georgia,"Times New Roman",Times,serif}label{display:block;margin-bottom:5px}select,textarea,input[type="text"],input[type="password"],input[type="datetime"],input[type="datetime-local"],input[type="date"],input[type="month"],input[type="time"],input[type="week"],input[type="number"],input[type="email"],input[type="url"],input[type="search"],input[type="tel"],input[type="color"],.uneditable-input{display:inline-block;height:20px;padding:4px 6px;margin-bottom:10px;font-size:14px;line-height:20px;color:#999;vertical-align:middle;-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px}input,textarea,.uneditable-input{width:206px}textarea{height:auto}textarea,input[type="text"],input[type="password"],input[type="datetime"],input[type="datetime-local"],input[type="date"],input[type="month"],input[type="time"],input[type="week"],input[type="number"],input[type="email"],input[type="url"],input[type="search"],input[type="tel"],input[type="color"],.uneditable-input{background-color:#fff;border:1px solid #ccc;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,0.075);-moz-box-shadow:inset 0 1px 1px rgba(0,0,0,0.075);box-shadow:inset 0 1px 1px rgba(0,0,0,0.075);-webkit-transition:border linear .2s,box-shadow linear .2s;-moz-transition:border linear .2s,box-shadow linear .2s;-o-transition:border linear .2s,box-shadow linear .2s;transition:border linear .2s,box-shadow linear .2s}textarea:focus,input[type="text"]:focus,input[type="password"]:focus,input[type="datetime"]:focus,input[type="datetime-local"]:focus,input[type="date"]:focus,input[type="month"]:focus,input[type="time"]:focus,input[type="week"]:focus,input[type="number"]:focus,input[type="email"]:focus,input[type="url"]:focus,input[type="search"]:focus,input[type="tel"]:focus,input[type="color"]:focus,.uneditable-input:focus{border-color:rgba(82,168,236,0.8);outline:0;outline:thin dotted \9;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,0.075),0 0 8px rgba(82,168,236,0.6);-moz-box-shadow:inset 0 1px 1px rgba(0,0,0,0.075),0 0 8px rgba(82,168,236,0.6);box-shadow:inset 0 1px 1px rgba(0,0,0,0.075),0 0 8px rgba(82,168,236,0.6)}input[type="radio"],input[type="checkbox"]{margin:4px 0 0;margin-top:1px \9;*margin-top:0;line-height:normal}input[type="file"],input[type="image"],input[type="submit"],input[type="reset"],input[type="button"],input[type="radio"],input[type="checkbox"]{width:auto}select,input[type="file"]{height:30px;*margin-top:4px;line-height:30px}select{width:220px;background-color:#fff;border:1px solid #ccc}select[multiple],select[size]{height:auto}select:focus,input[type="file"]:focus,input[type="radio"]:focus,input[type="checkbox"]:focus{outline:thin dotted #333;outline:5px auto -webkit-focus-ring-color;outline-offset:-2px}.uneditable-input,.uneditable-textarea{color:#bbb;cursor:not-allowed;background-color:#fcfcfc;border-color:#ccc;-webkit-box-shadow:inset 0 1px 2px rgba(0,0,0,0.025);-moz-box-shadow:inset 0 1px 2px rgba(0,0,0,0.025);box-shadow:inset 0 1px 2px rgba(0,0,0,0.025)}.uneditable-input{overflow:hidden;white-space:nowrap}.uneditable-textarea{width:auto;height:auto}input:-moz-placeholder,textarea:-moz-placeholder{color:#bbb}input:-ms-input-placeholder,textarea:-ms-input-placeholder{color:#bbb}input::-webkit-input-placeholder,textarea::-webkit-input-placeholder{color:#bbb}.radio,.checkbox{min-height:20px;padding-left:20px}.radio input[type="radio"],.checkbox input[type="checkbox"]{float:left;margin-left:-20px}.controls>.radio:first-child,.controls>.checkbox:first-child{padding-top:5px}.radio.inline,.checkbox.inline{display:inline-block;padding-top:5px;margin-bottom:0;vertical-align:middle}.radio.inline+.radio.inline,.checkbox.inline+.checkbox.inline{margin-left:10px}.input-mini{width:60px}.input-small{width:90px}.input-medium{width:150px}.input-large{width:210px}.input-xlarge{width:270px}.input-xxlarge{width:530px}input[class*="span"],select[class*="span"],textarea[class*="span"],.uneditable-input[class*="span"],.row-fluid input[class*="span"],.row-fluid select[class*="span"],.row-fluid textarea[class*="span"],.row-fluid .uneditable-input[class*="span"]{float:none;margin-left:0}.input-append input[class*="span"],.input-append .uneditable-input[class*="span"],.input-prepend input[class*="span"],.input-prepend .uneditable-input[class*="span"],.row-fluid input[class*="span"],.row-fluid select[class*="span"],.row-fluid textarea[class*="span"],.row-fluid .uneditable-input[class*="span"],.row-fluid .input-prepend [class*="span"],.row-fluid .input-append [class*="span"]{display:inline-block}input,textarea,.uneditable-input{margin-left:0}.controls-row [class*="span"]+[class*="span"]{margin-left:20px}input.span12,textarea.span12,.uneditable-input.span12{width:926px}input.span11,textarea.span11,.uneditable-input.span11{width:846px}input.span10,textarea.span10,.uneditable-input.span10{width:766px}input.span9,textarea.span9,.uneditable-input.span9{width:686px}input.span8,textarea.span8,.uneditable-input.span8{width:606px}input.span7,textarea.span7,.uneditable-input.span7{width:526px}input.span6,textarea.span6,.uneditable-input.span6{width:446px}input.span5,textarea.span5,.uneditable-input.span5{width:366px}input.span4,textarea.span4,.uneditable-input.span4{width:286px}input.span3,textarea.span3,.uneditable-input.span3{width:206px}input.span2,textarea.span2,.uneditable-input.span2{width:126px}input.span1,textarea.span1,.uneditable-input.span1{width:46px}.controls-row{*zoom:1}.controls-row:before,.controls-row:after{display:table;line-height:0;content:""}.controls-row:after{clear:both}.controls-row [class*="span"],.row-fluid .controls-row [class*="span"]{float:left}.controls-row .checkbox[class*="span"],.controls-row .radio[class*="span"]{padding-top:5px}input[disabled],select[disabled],textarea[disabled],input[readonly],select[readonly],textarea[readonly]{cursor:not-allowed;background-color:#eee}input[type="radio"][disabled],input[type="checkbox"][disabled],input[type="radio"][readonly],input[type="checkbox"][readonly]{background-color:transparent}.control-group.warning .control-label,.control-group.warning .help-block,.control-group.warning .help-inline{color:#c09853}.control-group.warning .checkbox,.control-group.warning .radio,.control-group.warning input,.control-group.warning select,.control-group.warning textarea{color:#c09853}.control-group.warning input,.control-group.warning select,.control-group.warning textarea{border-color:#c09853;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,0.075);-moz-box-shadow:inset 0 1px 1px rgba(0,0,0,0.075);box-shadow:inset 0 1px 1px rgba(0,0,0,0.075)}.control-group.warning input:focus,.control-group.warning select:focus,.control-group.warning textarea:focus{border-color:#a47e3c;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,0.075),0 0 6px #dbc59e;-moz-box-shadow:inset 0 1px 1px rgba(0,0,0,0.075),0 0 6px #dbc59e;box-shadow:inset 0 1px 1px rgba(0,0,0,0.075),0 0 6px #dbc59e}.control-group.warning .input-prepend .add-on,.control-group.warning .input-append .add-on{color:#c09853;background-color:#fcf8e3;border-color:#c09853}.control-group.error .control-label,.control-group.error .help-block,.control-group.error .help-inline{color:#b94a48}.control-group.error .checkbox,.control-group.error .radio,.control-group.error input,.control-group.error select,.control-group.error textarea{color:#b94a48}.control-group.error input,.control-group.error select,.control-group.error textarea{border-color:#b94a48;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,0.075);-moz-box-shadow:inset 0 1px 1px rgba(0,0,0,0.075);box-shadow:inset 0 1px 1px rgba(0,0,0,0.075)}.control-group.error input:focus,.control-group.error select:focus,.control-group.error textarea:focus{border-color:#953b39;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,0.075),0 0 6px #d59392;-moz-box-shadow:inset 0 1px 1px rgba(0,0,0,0.075),0 0 6px #d59392;box-shadow:inset 0 1px 1px rgba(0,0,0,0.075),0 0 6px #d59392}.control-group.error .input-prepend .add-on,.control-group.error .input-append .add-on{color:#b94a48;background-color:#f2dede;border-color:#b94a48}.control-group.success .control-label,.control-group.success .help-block,.control-group.success .help-inline{color:#468847}.control-group.success .checkbox,.control-group.success .radio,.control-group.success input,.control-group.success select,.control-group.success textarea{color:#468847}.control-group.success input,.control-group.success select,.control-group.success textarea{border-color:#468847;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,0.075);-moz-box-shadow:inset 0 1px 1px rgba(0,0,0,0.075);box-shadow:inset 0 1px 1px rgba(0,0,0,0.075)}.control-group.success input:focus,.control-group.success select:focus,.control-group.success textarea:focus{border-color:#356635;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,0.075),0 0 6px #7aba7b;-moz-box-shadow:inset 0 1px 1px rgba(0,0,0,0.075),0 0 6px #7aba7b;box-shadow:inset 0 1px 1px rgba(0,0,0,0.075),0 0 6px #7aba7b}.control-group.success .input-prepend .add-on,.control-group.success .input-append .add-on{color:#468847;background-color:#dff0d8;border-color:#468847}.control-group.info .control-label,.control-group.info .help-block,.control-group.info .help-inline{color:#3a87ad}.control-group.info .checkbox,.control-group.info .radio,.control-group.info input,.control-group.info select,.control-group.info textarea{color:#3a87ad}.control-group.info input,.control-group.info select,.control-group.info textarea{border-color:#3a87ad;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,0.075);-moz-box-shadow:inset 0 1px 1px rgba(0,0,0,0.075);box-shadow:inset 0 1px 1px rgba(0,0,0,0.075)}.control-group.info input:focus,.control-group.info select:focus,.control-group.info textarea:focus{border-color:#2d6987;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,0.075),0 0 6px #7ab5d3;-moz-box-shadow:inset 0 1px 1px rgba(0,0,0,0.075),0 0 6px #7ab5d3;box-shadow:inset 0 1px 1px rgba(0,0,0,0.075),0 0 6px #7ab5d3}.control-group.info .input-prepend .add-on,.control-group.info .input-append .add-on{color:#3a87ad;background-color:#d9edf7;border-color:#3a87ad}input:focus:invalid,textarea:focus:invalid,select:focus:invalid{color:#b94a48;border-color:#ee5f5b}input:focus:invalid:focus,textarea:focus:invalid:focus,select:focus:invalid:focus{border-color:#e9322d;-webkit-box-shadow:0 0 6px #f8b9b7;-moz-box-shadow:0 0 6px #f8b9b7;box-shadow:0 0 6px #f8b9b7}.form-actions{padding:19px 20px 20px;margin-top:20px;margin-bottom:20px;background-color:#eee;border-top:1px solid #e5e5e5;*zoom:1}.form-actions:before,.form-actions:after{display:table;line-height:0;content:""}.form-actions:after{clear:both}.help-block,.help-inline{color:#9d9d9d}.help-block{display:block;margin-bottom:10px}.help-inline{display:inline-block;*display:inline;padding-left:5px;vertical-align:middle;*zoom:1}.input-append,.input-prepend{display:inline-block;margin-bottom:10px;font-size:0;white-space:nowrap;vertical-align:middle}.input-append input,.input-prepend input,.input-append select,.input-prepend select,.input-append .uneditable-input,.input-prepend .uneditable-input,.input-append .dropdown-menu,.input-prepend .dropdown-menu,.input-append .popover,.input-prepend .popover{font-size:14px}.input-append input,.input-prepend input,.input-append select,.input-prepend select,.input-append .uneditable-input,.input-prepend .uneditable-input{position:relative;margin-bottom:0;*margin-left:0;vertical-align:top;-webkit-border-radius:0 4px 4px 0;-moz-border-radius:0 4px 4px 0;border-radius:0 4px 4px 0}.input-append input:focus,.input-prepend input:focus,.input-append select:focus,.input-prepend select:focus,.input-append .uneditable-input:focus,.input-prepend .uneditable-input:focus{z-index:2}.input-append .add-on,.input-prepend .add-on{display:inline-block;width:auto;height:20px;min-width:16px;padding:4px 5px;font-size:14px;font-weight:normal;line-height:20px;text-align:center;text-shadow:0 1px 0 #fff;background-color:#eee;border:1px solid #ccc}.input-append .add-on,.input-prepend .add-on,.input-append .btn,.input-prepend .btn,.input-append .btn-group>.dropdown-toggle,.input-prepend .btn-group>.dropdown-toggle{vertical-align:top;-webkit-border-radius:0;-moz-border-radius:0;border-radius:0}.input-append .active,.input-prepend .active{background-color:#85e8a2;border-color:#22b24c}.input-prepend .add-on,.input-prepend .btn{margin-right:-1px}.input-prepend .add-on:first-child,.input-prepend .btn:first-child{-webkit-border-radius:4px 0 0 4px;-moz-border-radius:4px 0 0 4px;border-radius:4px 0 0 4px}.input-append input,.input-append select,.input-append .uneditable-input{-webkit-border-radius:4px 0 0 4px;-moz-border-radius:4px 0 0 4px;border-radius:4px 0 0 4px}.input-append input+.btn-group .btn:last-child,.input-append select+.btn-group .btn:last-child,.input-append .uneditable-input+.btn-group .btn:last-child{-webkit-border-radius:0 4px 4px 0;-moz-border-radius:0 4px 4px 0;border-radius:0 4px 4px 0}.input-append .add-on,.input-append .btn,.input-append .btn-group{margin-left:-1px}.input-append .add-on:last-child,.input-append .btn:last-child,.input-append .btn-group:last-child>.dropdown-toggle{-webkit-border-radius:0 4px 4px 0;-moz-border-radius:0 4px 4px 0;border-radius:0 4px 4px 0}.input-prepend.input-append input,.input-prepend.input-append select,.input-prepend.input-append .uneditable-input{-webkit-border-radius:0;-moz-border-radius:0;border-radius:0}.input-prepend.input-append input+.btn-group .btn,.input-prepend.input-append select+.btn-group .btn,.input-prepend.input-append .uneditable-input+.btn-group .btn{-webkit-border-radius:0 4px 4px 0;-moz-border-radius:0 4px 4px 0;border-radius:0 4px 4px 0}.input-prepend.input-append .add-on:first-child,.input-prepend.input-append .btn:first-child{margin-right:-1px;-webkit-border-radius:4px 0 0 4px;-moz-border-radius:4px 0 0 4px;border-radius:4px 0 0 4px}.input-prepend.input-append .add-on:last-child,.input-prepend.input-append .btn:last-child{margin-left:-1px;-webkit-border-radius:0 4px 4px 0;-moz-border-radius:0 4px 4px 0;border-radius:0 4px 4px 0}.input-prepend.input-append .btn-group:first-child{margin-left:0}input.search-query{padding-right:14px;padding-right:4px \9;padding-left:14px;padding-left:4px \9;margin-bottom:0;-webkit-border-radius:15px;-moz-border-radius:15px;border-radius:15px}.form-search .input-append .search-query,.form-search .input-prepend .search-query{-webkit-border-radius:0;-moz-border-radius:0;border-radius:0}.form-search .input-append .search-query{-webkit-border-radius:14px 0 0 14px;-moz-border-radius:14px 0 0 14px;border-radius:14px 0 0 14px}.form-search .input-append .btn{-webkit-border-radius:0 14px 14px 0;-moz-border-radius:0 14px 14px 0;border-radius:0 14px 14px 0}.form-search .input-prepend .search-query{-webkit-border-radius:0 14px 14px 0;-moz-border-radius:0 14px 14px 0;border-radius:0 14px 14px 0}.form-search .input-prepend .btn{-webkit-border-radius:14px 0 0 14px;-moz-border-radius:14px 0 0 14px;border-radius:14px 0 0 14px}.form-search input,.form-inline input,.form-horizontal input,.form-search textarea,.form-inline textarea,.form-horizontal textarea,.form-search select,.form-inline select,.form-horizontal select,.form-search .help-inline,.form-inline .help-inline,.form-horizontal .help-inline,.form-search .uneditable-input,.form-inline .uneditable-input,.form-horizontal .uneditable-input,.form-search .input-prepend,.form-inline .input-prepend,.form-horizontal .input-prepend,.form-search .input-append,.form-inline .input-append,.form-horizontal .input-append{display:inline-block;*display:inline;margin-bottom:0;vertical-align:middle;*zoom:1}.form-search .hide,.form-inline .hide,.form-horizontal .hide{display:none}.form-search label,.form-inline label,.form-search .btn-group,.form-inline .btn-group{display:inline-block}.form-search .input-append,.form-inline .input-append,.form-search .input-prepend,.form-inline .input-prepend{margin-bottom:0}.form-search .radio,.form-search .checkbox,.form-inline .radio,.form-inline .checkbox{padding-left:0;margin-bottom:0;vertical-align:middle}.form-search .radio input[type="radio"],.form-search .checkbox input[type="checkbox"],.form-inline .radio input[type="radio"],.form-inline .checkbox input[type="checkbox"]{float:left;margin-right:3px;margin-left:0}.control-group{margin-bottom:10px}legend+.control-group{margin-top:20px;-webkit-margin-top-collapse:separate}.form-horizontal .control-group{margin-bottom:20px;*zoom:1}.form-horizontal .control-group:before,.form-horizontal .control-group:after{display:table;line-height:0;content:""}.form-horizontal .control-group:after{clear:both}.form-horizontal .control-label{float:left;width:160px;padding-top:5px;text-align:right}.form-horizontal .controls{*display:inline-block;*padding-left:20px;margin-left:180px;*margin-left:0}.form-horizontal .controls:first-child{*padding-left:180px}.form-horizontal .help-block{margin-bottom:0}.form-horizontal input+.help-block,.form-horizontal select+.help-block,.form-horizontal textarea+.help-block,.form-horizontal .uneditable-input+.help-block,.form-horizontal .input-prepend+.help-block,.form-horizontal .input-append+.help-block{margin-top:10px}.form-horizontal .form-actions{padding-left:180px}table{max-width:100%;background-color:transparent;border-collapse:collapse;border-spacing:0}.table{width:100%;margin-bottom:20px}.table th,.table td{padding:8px;line-height:20px;text-align:left;vertical-align:top;border-top:1px solid #ddd}.table th{font-weight:bold}.table thead th{vertical-align:bottom}.table caption+thead tr:first-child th,.table caption+thead tr:first-child td,.table colgroup+thead tr:first-child th,.table colgroup+thead tr:first-child td,.table thead:first-child tr:first-child th,.table thead:first-child tr:first-child td{border-top:0}.table tbody+tbody{border-top:2px solid #ddd}.table .table{background-color:#fff}.table-condensed th,.table-condensed td{padding:4px 5px}.table-bordered{border:1px solid #ddd;border-collapse:separate;*border-collapse:collapse;border-left:0;-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px}.table-bordered th,.table-bordered td{border-left:1px solid #ddd}.table-bordered caption+thead tr:first-child th,.table-bordered caption+tbody tr:first-child th,.table-bordered caption+tbody tr:first-child td,.table-bordered colgroup+thead tr:first-child th,.table-bordered colgroup+tbody tr:first-child th,.table-bordered colgroup+tbody tr:first-child td,.table-bordered thead:first-child tr:first-child th,.table-bordered tbody:first-child tr:first-child th,.table-bordered tbody:first-child tr:first-child td{border-top:0}.table-bordered thead:first-child tr:first-child>th:first-child,.table-bordered tbody:first-child tr:first-child>td:first-child,.table-bordered tbody:first-child tr:first-child>th:first-child{-webkit-border-top-left-radius:4px;border-top-left-radius:4px;-moz-border-radius-topleft:4px}.table-bordered thead:first-child tr:first-child>th:last-child,.table-bordered tbody:first-child tr:first-child>td:last-child,.table-bordered tbody:first-child tr:first-child>th:last-child{-webkit-border-top-right-radius:4px;border-top-right-radius:4px;-moz-border-radius-topright:4px}.table-bordered thead:last-child tr:last-child>th:first-child,.table-bordered tbody:last-child tr:last-child>td:first-child,.table-bordered tbody:last-child tr:last-child>th:first-child,.table-bordered tfoot:last-child tr:last-child>td:first-child,.table-bordered tfoot:last-child tr:last-child>th:first-child{-webkit-border-bottom-left-radius:4px;border-bottom-left-radius:4px;-moz-border-radius-bottomleft:4px}.table-bordered thead:last-child tr:last-child>th:last-child,.table-bordered tbody:last-child tr:last-child>td:last-child,.table-bordered tbody:last-child tr:last-child>th:last-child,.table-bordered tfoot:last-child tr:last-child>td:last-child,.table-bordered tfoot:last-child tr:last-child>th:last-child{-webkit-border-bottom-right-radius:4px;border-bottom-right-radius:4px;-moz-border-radius-bottomright:4px}.table-bordered tfoot+tbody:last-child tr:last-child td:first-child{-webkit-border-bottom-left-radius:0;border-bottom-left-radius:0;-moz-border-radius-bottomleft:0}.table-bordered tfoot+tbody:last-child tr:last-child td:last-child{-webkit-border-bottom-right-radius:0;border-bottom-right-radius:0;-moz-border-radius-bottomright:0}.table-bordered caption+thead tr:first-child th:first-child,.table-bordered caption+tbody tr:first-child td:first-child,.table-bordered colgroup+thead tr:first-child th:first-child,.table-bordered colgroup+tbody tr:first-child td:first-child{-webkit-border-top-left-radius:4px;border-top-left-radius:4px;-moz-border-radius-topleft:4px}.table-bordered caption+thead tr:first-child th:last-child,.table-bordered caption+tbody tr:first-child td:last-child,.table-bordered colgroup+thead tr:first-child th:last-child,.table-bordered colgroup+tbody tr:first-child td:last-child{-webkit-border-top-right-radius:4px;border-top-right-radius:4px;-moz-border-radius-topright:4px}.table-striped tbody>tr:nth-child(odd)>td,.table-striped tbody>tr:nth-child(odd)>th{background-color:#f5f5f5}.table-hover tbody tr:hover>td,.table-hover tbody tr:hover>th{background-color:#eee}table td[class*="span"],table th[class*="span"],.row-fluid table td[class*="span"],.row-fluid table th[class*="span"]{display:table-cell;float:none;margin-left:0}.table td.span1,.table th.span1{float:none;width:44px;margin-left:0}.table td.span2,.table th.span2{float:none;width:124px;margin-left:0}.table td.span3,.table th.span3{float:none;width:204px;margin-left:0}.table td.span4,.table th.span4{float:none;width:284px;margin-left:0}.table td.span5,.table th.span5{float:none;width:364px;margin-left:0}.table td.span6,.table th.span6{float:none;width:444px;margin-left:0}.table td.span7,.table th.span7{float:none;width:524px;margin-left:0}.table td.span8,.table th.span8{float:none;width:604px;margin-left:0}.table td.span9,.table th.span9{float:none;width:684px;margin-left:0}.table td.span10,.table th.span10{float:none;width:764px;margin-left:0}.table td.span11,.table th.span11{float:none;width:844px;margin-left:0}.table td.span12,.table th.span12{float:none;width:924px;margin-left:0}.table tbody tr.success>td{background-color:#dff0d8}.table tbody tr.error>td{background-color:#f2dede}.table tbody tr.warning>td{background-color:#fcf8e3}.table tbody tr.info>td{background-color:#d9edf7}.table-hover tbody tr.success:hover>td{background-color:#d0e9c6}.table-hover tbody tr.error:hover>td{background-color:#ebcccc}.table-hover tbody tr.warning:hover>td{background-color:#faf2cc}.table-hover tbody tr.info:hover>td{background-color:#c4e3f3}[class^="icon-"],[class*=" icon-"]{display:inline-block;width:14px;height:14px;margin-top:1px;*margin-right:.3em;line-height:14px;vertical-align:text-top;background-image:url("../img/glyphicons-halflings.png");background-position:14px 14px;background-repeat:no-repeat}.icon-white,.nav-pills>.active>a>[class^="icon-"],.nav-pills>.active>a>[class*=" icon-"],.nav-list>.active>a>[class^="icon-"],.nav-list>.active>a>[class*=" icon-"],.navbar-inverse .nav>.active>a>[class^="icon-"],.navbar-inverse .nav>.active>a>[class*=" icon-"],.dropdown-menu>li>a:hover>[class^="icon-"],.dropdown-menu>li>a:focus>[class^="icon-"],.dropdown-menu>li>a:hover>[class*=" icon-"],.dropdown-menu>li>a:focus>[class*=" icon-"],.dropdown-menu>.active>a>[class^="icon-"],.dropdown-menu>.active>a>[class*=" icon-"],.dropdown-submenu:hover>a>[class^="icon-"],.dropdown-submenu:focus>a>[class^="icon-"],.dropdown-submenu:hover>a>[class*=" icon-"],.dropdown-submenu:focus>a>[class*=" icon-"]{background-image:url("../img/glyphicons-halflings-white.png")}.icon-glass{background-position:0 0}.icon-music{background-position:-24px 0}.icon-search{background-position:-48px 0}.icon-envelope{background-position:-72px 0}.icon-heart{background-position:-96px 0}.icon-star{background-position:-120px 0}.icon-star-empty{background-position:-144px 0}.icon-user{background-position:-168px 0}.icon-film{background-position:-192px 0}.icon-th-large{background-position:-216px 0}.icon-th{background-position:-240px 0}.icon-th-list{background-position:-264px 0}.icon-ok{background-position:-288px 0}.icon-remove{background-position:-312px 0}.icon-zoom-in{background-position:-336px 0}.icon-zoom-out{background-position:-360px 0}.icon-off{background-position:-384px 0}.icon-signal{background-position:-408px 0}.icon-cog{background-position:-432px 0}.icon-trash{background-position:-456px 0}.icon-home{background-position:0 -24px}.icon-file{background-position:-24px -24px}.icon-time{background-position:-48px -24px}.icon-road{background-position:-72px -24px}.icon-download-alt{background-position:-96px -24px}.icon-download{background-position:-120px -24px}.icon-upload{background-position:-144px -24px}.icon-inbox{background-position:-168px -24px}.icon-play-circle{background-position:-192px -24px}.icon-repeat{background-position:-216px -24px}.icon-refresh{background-position:-240px -24px}.icon-list-alt{background-position:-264px -24px}.icon-lock{background-position:-287px -24px}.icon-flag{background-position:-312px -24px}.icon-headphones{background-position:-336px -24px}.icon-volume-off{background-position:-360px -24px}.icon-volume-down{background-position:-384px -24px}.icon-volume-up{background-position:-408px -24px}.icon-qrcode{background-position:-432px -24px}.icon-barcode{background-position:-456px -24px}.icon-tag{background-position:0 -48px}.icon-tags{background-position:-25px -48px}.icon-book{background-position:-48px -48px}.icon-bookmark{background-position:-72px -48px}.icon-print{background-position:-96px -48px}.icon-camera{background-position:-120px -48px}.icon-font{background-position:-144px -48px}.icon-bold{background-position:-167px -48px}.icon-italic{background-position:-192px -48px}.icon-text-height{background-position:-216px -48px}.icon-text-width{background-position:-240px -48px}.icon-align-left{background-position:-264px -48px}.icon-align-center{background-position:-288px -48px}.icon-align-right{background-position:-312px -48px}.icon-align-justify{background-position:-336px -48px}.icon-list{background-position:-360px -48px}.icon-indent-left{background-position:-384px -48px}.icon-indent-right{background-position:-408px -48px}.icon-facetime-video{background-position:-432px -48px}.icon-picture{background-position:-456px -48px}.icon-pencil{background-position:0 -72px}.icon-map-marker{background-position:-24px -72px}.icon-adjust{background-position:-48px -72px}.icon-tint{background-position:-72px -72px}.icon-edit{background-position:-96px -72px}.icon-share{background-position:-120px -72px}.icon-check{background-position:-144px -72px}.icon-move{background-position:-168px -72px}.icon-step-backward{background-position:-192px -72px}.icon-fast-backward{background-position:-216px -72px}.icon-backward{background-position:-240px -72px}.icon-play{background-position:-264px -72px}.icon-pause{background-position:-288px -72px}.icon-stop{background-position:-312px -72px}.icon-forward{background-position:-336px -72px}.icon-fast-forward{background-position:-360px -72px}.icon-step-forward{background-position:-384px -72px}.icon-eject{background-position:-408px -72px}.icon-chevron-left{background-position:-432px -72px}.icon-chevron-right{background-position:-456px -72px}.icon-plus-sign{background-position:0 -96px}.icon-minus-sign{background-position:-24px -96px}.icon-remove-sign{background-position:-48px -96px}.icon-ok-sign{background-position:-72px -96px}.icon-question-sign{background-position:-96px -96px}.icon-info-sign{background-position:-120px -96px}.icon-screenshot{background-position:-144px -96px}.icon-remove-circle{background-position:-168px -96px}.icon-ok-circle{background-position:-192px -96px}.icon-ban-circle{background-position:-216px -96px}.icon-arrow-left{background-position:-240px -96px}.icon-arrow-right{background-position:-264px -96px}.icon-arrow-up{background-position:-289px -96px}.icon-arrow-down{background-position:-312px -96px}.icon-share-alt{background-position:-336px -96px}.icon-resize-full{background-position:-360px -96px}.icon-resize-small{background-position:-384px -96px}.icon-plus{background-position:-408px -96px}.icon-minus{background-position:-433px -96px}.icon-asterisk{background-position:-456px -96px}.icon-exclamation-sign{background-position:0 -120px}.icon-gift{background-position:-24px -120px}.icon-leaf{background-position:-48px -120px}.icon-fire{background-position:-72px -120px}.icon-eye-open{background-position:-96px -120px}.icon-eye-close{background-position:-120px -120px}.icon-warning-sign{background-position:-144px -120px}.icon-plane{background-position:-168px -120px}.icon-calendar{background-position:-192px -120px}.icon-random{width:16px;background-position:-216px -120px}.icon-comment{background-position:-240px -120px}.icon-magnet{background-position:-264px -120px}.icon-chevron-up{background-position:-288px -120px}.icon-chevron-down{background-position:-313px -119px}.icon-retweet{background-position:-336px -120px}.icon-shopping-cart{background-position:-360px -120px}.icon-folder-close{width:16px;background-position:-384px -120px}.icon-folder-open{width:16px;background-position:-408px -120px}.icon-resize-vertical{background-position:-432px -119px}.icon-resize-horizontal{background-position:-456px -118px}.icon-hdd{background-position:0 -144px}.icon-bullhorn{background-position:-24px -144px}.icon-bell{background-position:-48px -144px}.icon-certificate{background-position:-72px -144px}.icon-thumbs-up{background-position:-96px -144px}.icon-thumbs-down{background-position:-120px -144px}.icon-hand-right{background-position:-144px -144px}.icon-hand-left{background-position:-168px -144px}.icon-hand-up{background-position:-192px -144px}.icon-hand-down{background-position:-216px -144px}.icon-circle-arrow-right{background-position:-240px -144px}.icon-circle-arrow-left{background-position:-264px -144px}.icon-circle-arrow-up{background-position:-288px -144px}.icon-circle-arrow-down{background-position:-312px -144px}.icon-globe{background-position:-336px -144px}.icon-wrench{background-position:-360px -144px}.icon-tasks{background-position:-384px -144px}.icon-filter{background-position:-408px -144px}.icon-briefcase{background-position:-432px -144px}.icon-fullscreen{background-position:-456px -144px}.dropup,.dropdown{position:relative}.dropdown-toggle{*margin-bottom:-3px}.dropdown-toggle:active,.open .dropdown-toggle{outline:0}.caret{display:inline-block;width:0;height:0;vertical-align:top;border-top:4px solid #000;border-right:4px solid transparent;border-left:4px solid transparent;content:""}.dropdown .caret{margin-top:8px;margin-left:2px}.dropdown-menu{position:absolute;top:100%;left:0;z-index:1000;display:none;float:left;min-width:160px;padding:5px 0;margin:2px 0 0;list-style:none;background-color:#fff;border:1px solid #ccc;border:1px solid rgba(0,0,0,0.2);*border-right-width:2px;*border-bottom-width:2px;-webkit-border-radius:6px;-moz-border-radius:6px;border-radius:6px;-webkit-box-shadow:0 5px 10px rgba(0,0,0,0.2);-moz-box-shadow:0 5px 10px rgba(0,0,0,0.2);box-shadow:0 5px 10px rgba(0,0,0,0.2);-webkit-background-clip:padding-box;-moz-background-clip:padding;background-clip:padding-box}.dropdown-menu.pull-right{right:0;left:auto}.dropdown-menu .divider{*width:100%;height:1px;margin:9px 1px;*margin:-5px 0 5px;overflow:hidden;background-color:#eee;border-bottom:1px solid #eee}.dropdown-menu>li>a{display:block;padding:3px 20px;clear:both;font-weight:normal;line-height:20px;color:#000;white-space:nowrap}.dropdown-menu>li>a:hover,.dropdown-menu>li>a:focus,.dropdown-submenu:hover>a,.dropdown-submenu:focus>a{color:#000;text-decoration:none;background-color:#e9e9e9;background-image:-moz-linear-gradient(top,#eee,#e1e1e1);background-image:-webkit-gradient(linear,0 0,0 100%,from(#eee),to(#e1e1e1));background-image:-webkit-linear-gradient(top,#eee,#e1e1e1);background-image:-o-linear-gradient(top,#eee,#e1e1e1);background-image:linear-gradient(to bottom,#eee,#e1e1e1);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffeeeeee',endColorstr='#ffe1e1e1',GradientType=0)}.dropdown-menu>.active>a,.dropdown-menu>.active>a:hover,.dropdown-menu>.active>a:focus{color:#000;text-decoration:none;background-color:#e9e9e9;background-image:-moz-linear-gradient(top,#eee,#e1e1e1);background-image:-webkit-gradient(linear,0 0,0 100%,from(#eee),to(#e1e1e1));background-image:-webkit-linear-gradient(top,#eee,#e1e1e1);background-image:-o-linear-gradient(top,#eee,#e1e1e1);background-image:linear-gradient(to bottom,#eee,#e1e1e1);background-repeat:repeat-x;outline:0;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffeeeeee',endColorstr='#ffe1e1e1',GradientType=0)}.dropdown-menu>.disabled>a,.dropdown-menu>.disabled>a:hover,.dropdown-menu>.disabled>a:focus{color:#bbb}.dropdown-menu>.disabled>a:hover,.dropdown-menu>.disabled>a:focus{text-decoration:none;cursor:default;background-color:transparent;background-image:none;filter:progid:DXImageTransform.Microsoft.gradient(enabled=false)}.open{*z-index:1000}.open>.dropdown-menu{display:block}.pull-right>.dropdown-menu{right:0;left:auto}.dropup .caret,.navbar-fixed-bottom .dropdown .caret{border-top:0;border-bottom:4px solid #000;content:""}.dropup .dropdown-menu,.navbar-fixed-bottom .dropdown .dropdown-menu{top:auto;bottom:100%;margin-bottom:1px}.dropdown-submenu{position:relative}.dropdown-submenu>.dropdown-menu{top:0;left:100%;margin-top:-6px;margin-left:-1px;-webkit-border-radius:0 6px 6px 6px;-moz-border-radius:0 6px 6px 6px;border-radius:0 6px 6px 6px}.dropdown-submenu:hover>.dropdown-menu{display:block}.dropup .dropdown-submenu>.dropdown-menu{top:auto;bottom:0;margin-top:0;margin-bottom:-2px;-webkit-border-radius:5px 5px 5px 0;-moz-border-radius:5px 5px 5px 0;border-radius:5px 5px 5px 0}.dropdown-submenu>a:after{display:block;float:right;width:0;height:0;margin-top:5px;margin-right:-10px;border-color:transparent;border-left-color:#ccc;border-style:solid;border-width:5px 0 5px 5px;content:" "}.dropdown-submenu:hover>a:after{border-left-color:#000}.dropdown-submenu.pull-left{float:none}.dropdown-submenu.pull-left>.dropdown-menu{left:-100%;margin-left:10px;-webkit-border-radius:6px 0 6px 6px;-moz-border-radius:6px 0 6px 6px;border-radius:6px 0 6px 6px}.dropdown .dropdown-menu .nav-header{padding-right:20px;padding-left:20px}.typeahead{z-index:1051;margin-top:2px;-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px}.well{min-height:20px;padding:19px;margin-bottom:20px;background-color:#eee;border:1px solid #dcdcdc;-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,0.05);-moz-box-shadow:inset 0 1px 1px rgba(0,0,0,0.05);box-shadow:inset 0 1px 1px rgba(0,0,0,0.05)}.well blockquote{border-color:#ddd;border-color:rgba(0,0,0,0.15)}.well-large{padding:24px;-webkit-border-radius:6px;-moz-border-radius:6px;border-radius:6px}.well-small{padding:9px;-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px}.fade{opacity:0;-webkit-transition:opacity .15s linear;-moz-transition:opacity .15s linear;-o-transition:opacity .15s linear;transition:opacity .15s linear}.fade.in{opacity:1}.collapse{position:relative;height:0;overflow:hidden;-webkit-transition:height .35s ease;-moz-transition:height .35s ease;-o-transition:height .35s ease;transition:height .35s ease}.collapse.in{height:auto}.close{float:right;font-size:20px;font-weight:bold;line-height:20px;color:#000;text-shadow:0 1px 0 #fff;opacity:.2;filter:alpha(opacity=20)}.close:hover,.close:focus{color:#000;text-decoration:none;cursor:pointer;opacity:.4;filter:alpha(opacity=40)}button.close{padding:0;cursor:pointer;background:transparent;border:0;-webkit-appearance:none}.btn{display:inline-block;*display:inline;padding:4px 12px;margin-bottom:0;*margin-left:.3em;font-size:14px;line-height:20px;color:#777;text-align:center;text-shadow:0 1px 1px rgba(255,255,255,0.75);vertical-align:middle;cursor:pointer;background-color:#f5f5f5;*background-color:#e6e6e6;background-image:-moz-linear-gradient(top,#fff,#e6e6e6);background-image:-webkit-gradient(linear,0 0,0 100%,from(#fff),to(#e6e6e6));background-image:-webkit-linear-gradient(top,#fff,#e6e6e6);background-image:-o-linear-gradient(top,#fff,#e6e6e6);background-image:linear-gradient(to bottom,#fff,#e6e6e6);background-repeat:repeat-x;border:1px solid #d9d9d9;*border:0;border-color:#e6e6e6 #e6e6e6 #bfbfbf;border-color:rgba(0,0,0,0.1) rgba(0,0,0,0.1) rgba(0,0,0,0.25);border-bottom-color:#bfbfbf;-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffffffff',endColorstr='#ffe6e6e6',GradientType=0);filter:progid:DXImageTransform.Microsoft.gradient(enabled=false);*zoom:1;-webkit-box-shadow:inset 0 1px 0 rgba(255,255,255,0.2),0 1px 2px rgba(0,0,0,0.05);-moz-box-shadow:inset 0 1px 0 rgba(255,255,255,0.2),0 1px 2px rgba(0,0,0,0.05);box-shadow:inset 0 1px 0 rgba(255,255,255,0.2),0 1px 2px rgba(0,0,0,0.05)}.btn:hover,.btn:focus,.btn:active,.btn.active,.btn.disabled,.btn[disabled]{color:#777;background-color:#e6e6e6;*background-color:#d9d9d9}.btn:active,.btn.active{background-color:#ccc \9}.btn:first-child{*margin-left:0}.btn:hover,.btn:focus{color:#777;text-decoration:none;background-position:0 -15px;-webkit-transition:background-position .1s linear;-moz-transition:background-position .1s linear;-o-transition:background-position .1s linear;transition:background-position .1s linear}.btn:focus{outline:thin dotted #333;outline:5px auto -webkit-focus-ring-color;outline-offset:-2px}.btn.active,.btn:active{background-image:none;outline:0;-webkit-box-shadow:inset 0 2px 4px rgba(0,0,0,0.15),0 1px 2px rgba(0,0,0,0.05);-moz-box-shadow:inset 0 2px 4px rgba(0,0,0,0.15),0 1px 2px rgba(0,0,0,0.05);box-shadow:inset 0 2px 4px rgba(0,0,0,0.15),0 1px 2px rgba(0,0,0,0.05)}.btn.disabled,.btn[disabled]{cursor:default;background-image:none;opacity:.65;filter:alpha(opacity=65);-webkit-box-shadow:none;-moz-box-shadow:none;box-shadow:none}.btn-large{padding:11px 19px;font-size:17.5px;-webkit-border-radius:6px;-moz-border-radius:6px;border-radius:6px}.btn-large [class^="icon-"],.btn-large [class*=" icon-"]{margin-top:4px}.btn-small{padding:2px 10px;font-size:11.9px;-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px}.btn-small [class^="icon-"],.btn-small [class*=" icon-"]{margin-top:0}.btn-mini [class^="icon-"],.btn-mini [class*=" icon-"]{margin-top:-1px}.btn-mini{padding:0 6px;font-size:10.5px;-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px}.btn-block{display:block;width:100%;padding-right:0;padding-left:0;-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}.btn-block+.btn-block{margin-top:5px}input[type="submit"].btn-block,input[type="reset"].btn-block,input[type="button"].btn-block{width:100%}.btn-primary.active,.btn-warning.active,.btn-danger.active,.btn-success.active,.btn-info.active,.btn-inverse.active{color:rgba(255,255,255,0.75)}.btn-primary{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,0.25);background-color:#7f7f7f;*background-color:#777;background-image:-moz-linear-gradient(top,#848484,#777);background-image:-webkit-gradient(linear,0 0,0 100%,from(#848484),to(#777));background-image:-webkit-linear-gradient(top,#848484,#777);background-image:-o-linear-gradient(top,#848484,#777);background-image:linear-gradient(to bottom,#848484,#777);background-repeat:repeat-x;border-color:#777 #777 #515151;border-color:rgba(0,0,0,0.1) rgba(0,0,0,0.1) rgba(0,0,0,0.25);filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff848484',endColorstr='#ff777777',GradientType=0);filter:progid:DXImageTransform.Microsoft.gradient(enabled=false)}.btn-primary:hover,.btn-primary:focus,.btn-primary:active,.btn-primary.active,.btn-primary.disabled,.btn-primary[disabled]{color:#fff;background-color:#777;*background-color:#6a6a6a}.btn-primary:active,.btn-primary.active{background-color:#5e5e5e \9}.btn-warning{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,0.25);background-color:#ff8e1f;*background-color:#ff7f00;background-image:-moz-linear-gradient(top,#f93,#ff7f00);background-image:-webkit-gradient(linear,0 0,0 100%,from(#f93),to(#ff7f00));background-image:-webkit-linear-gradient(top,#f93,#ff7f00);background-image:-o-linear-gradient(top,#f93,#ff7f00);background-image:linear-gradient(to bottom,#f93,#ff7f00);background-repeat:repeat-x;border-color:#ff7f00 #ff7f00 #b35900;border-color:rgba(0,0,0,0.1) rgba(0,0,0,0.1) rgba(0,0,0,0.25);filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffff9933',endColorstr='#ffff7f00',GradientType=0);filter:progid:DXImageTransform.Microsoft.gradient(enabled=false)}.btn-warning:hover,.btn-warning:focus,.btn-warning:active,.btn-warning.active,.btn-warning.disabled,.btn-warning[disabled]{color:#fff;background-color:#ff7f00;*background-color:#e67200}.btn-warning:active,.btn-warning.active{background-color:#c60 \9}.btn-danger{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,0.25);background-color:#eb0000;*background-color:#c00;background-image:-moz-linear-gradient(top,#f00,#c00);background-image:-webkit-gradient(linear,0 0,0 100%,from(#f00),to(#c00));background-image:-webkit-linear-gradient(top,#f00,#c00);background-image:-o-linear-gradient(top,#f00,#c00);background-image:linear-gradient(to bottom,#f00,#c00);background-repeat:repeat-x;border-color:#c00 #c00 #800000;border-color:rgba(0,0,0,0.1) rgba(0,0,0,0.1) rgba(0,0,0,0.25);filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffff0000',endColorstr='#ffcc0000',GradientType=0);filter:progid:DXImageTransform.Microsoft.gradient(enabled=false)}.btn-danger:hover,.btn-danger:focus,.btn-danger:active,.btn-danger.active,.btn-danger.disabled,.btn-danger[disabled]{color:#fff;background-color:#c00;*background-color:#b30000}.btn-danger:active,.btn-danger.active{background-color:#900 \9}.btn-success{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,0.25);background-color:#24bf51;*background-color:#22b24c;background-image:-moz-linear-gradient(top,#26c755,#22b24c);background-image:-webkit-gradient(linear,0 0,0 100%,from(#26c755),to(#22b24c));background-image:-webkit-linear-gradient(top,#26c755,#22b24c);background-image:-o-linear-gradient(top,#26c755,#22b24c);background-image:linear-gradient(to bottom,#26c755,#22b24c);background-repeat:repeat-x;border-color:#22b24c #22b24c #167231;border-color:rgba(0,0,0,0.1) rgba(0,0,0,0.1) rgba(0,0,0,0.25);filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff26c755',endColorstr='#ff22b24c',GradientType=0);filter:progid:DXImageTransform.Microsoft.gradient(enabled=false)}.btn-success:hover,.btn-success:focus,.btn-success:active,.btn-success.active,.btn-success.disabled,.btn-success[disabled]{color:#fff;background-color:#22b24c;*background-color:#1e9d43}.btn-success:active,.btn-success.active{background-color:#1a873a \9}.btn-info{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,0.25);background-color:#376ea4;*background-color:#369;background-image:-moz-linear-gradient(top,#3973ac,#369);background-image:-webkit-gradient(linear,0 0,0 100%,from(#3973ac),to(#369));background-image:-webkit-linear-gradient(top,#3973ac,#369);background-image:-o-linear-gradient(top,#3973ac,#369);background-image:linear-gradient(to bottom,#3973ac,#369);background-repeat:repeat-x;border-color:#369 #369 #204060;border-color:rgba(0,0,0,0.1) rgba(0,0,0,0.1) rgba(0,0,0,0.25);filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff3973ac',endColorstr='#ff336699',GradientType=0);filter:progid:DXImageTransform.Microsoft.gradient(enabled=false)}.btn-info:hover,.btn-info:focus,.btn-info:active,.btn-info.active,.btn-info.disabled,.btn-info[disabled]{color:#fff;background-color:#369;*background-color:#2d5986}.btn-info:active,.btn-info.active{background-color:#264c73 \9}.btn-inverse{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,0.25);background-color:#7f7f7f;*background-color:#777;background-image:-moz-linear-gradient(top,#848484,#777);background-image:-webkit-gradient(linear,0 0,0 100%,from(#848484),to(#777));background-image:-webkit-linear-gradient(top,#848484,#777);background-image:-o-linear-gradient(top,#848484,#777);background-image:linear-gradient(to bottom,#848484,#777);background-repeat:repeat-x;border-color:#777 #777 #515151;border-color:rgba(0,0,0,0.1) rgba(0,0,0,0.1) rgba(0,0,0,0.25);filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff848484',endColorstr='#ff777777',GradientType=0);filter:progid:DXImageTransform.Microsoft.gradient(enabled=false)}.btn-inverse:hover,.btn-inverse:focus,.btn-inverse:active,.btn-inverse.active,.btn-inverse.disabled,.btn-inverse[disabled]{color:#fff;background-color:#777;*background-color:#6a6a6a}.btn-inverse:active,.btn-inverse.active{background-color:#5e5e5e \9}button.btn,input[type="submit"].btn{*padding-top:3px;*padding-bottom:3px}button.btn::-moz-focus-inner,input[type="submit"].btn::-moz-focus-inner{padding:0;border:0}button.btn.btn-large,input[type="submit"].btn.btn-large{*padding-top:7px;*padding-bottom:7px}button.btn.btn-small,input[type="submit"].btn.btn-small{*padding-top:3px;*padding-bottom:3px}button.btn.btn-mini,input[type="submit"].btn.btn-mini{*padding-top:1px;*padding-bottom:1px}.btn-link,.btn-link:active,.btn-link[disabled]{background-color:transparent;background-image:none;-webkit-box-shadow:none;-moz-box-shadow:none;box-shadow:none}.btn-link{color:#777;cursor:pointer;border-color:transparent;-webkit-border-radius:0;-moz-border-radius:0;border-radius:0}.btn-link:hover,.btn-link:focus{color:#777;text-decoration:underline;background-color:transparent}.btn-link[disabled]:hover,.btn-link[disabled]:focus{color:#777;text-decoration:none}.btn-group{position:relative;display:inline-block;*display:inline;*margin-left:.3em;font-size:0;white-space:nowrap;vertical-align:middle;*zoom:1}.btn-group:first-child{*margin-left:0}.btn-group+.btn-group{margin-left:5px}.btn-toolbar{margin-top:10px;margin-bottom:10px;font-size:0}.btn-toolbar>.btn+.btn,.btn-toolbar>.btn-group+.btn,.btn-toolbar>.btn+.btn-group{margin-left:5px}.btn-group>.btn{position:relative;-webkit-border-radius:0;-moz-border-radius:0;border-radius:0}.btn-group>.btn+.btn{margin-left:-1px}.btn-group>.btn,.btn-group>.dropdown-menu,.btn-group>.popover{font-size:14px}.btn-group>.btn-mini{font-size:10.5px}.btn-group>.btn-small{font-size:11.9px}.btn-group>.btn-large{font-size:17.5px}.btn-group>.btn:first-child{margin-left:0;-webkit-border-bottom-left-radius:4px;border-bottom-left-radius:4px;-webkit-border-top-left-radius:4px;border-top-left-radius:4px;-moz-border-radius-bottomleft:4px;-moz-border-radius-topleft:4px}.btn-group>.btn:last-child,.btn-group>.dropdown-toggle{-webkit-border-top-right-radius:4px;border-top-right-radius:4px;-webkit-border-bottom-right-radius:4px;border-bottom-right-radius:4px;-moz-border-radius-topright:4px;-moz-border-radius-bottomright:4px}.btn-group>.btn.large:first-child{margin-left:0;-webkit-border-bottom-left-radius:6px;border-bottom-left-radius:6px;-webkit-border-top-left-radius:6px;border-top-left-radius:6px;-moz-border-radius-bottomleft:6px;-moz-border-radius-topleft:6px}.btn-group>.btn.large:last-child,.btn-group>.large.dropdown-toggle{-webkit-border-top-right-radius:6px;border-top-right-radius:6px;-webkit-border-bottom-right-radius:6px;border-bottom-right-radius:6px;-moz-border-radius-topright:6px;-moz-border-radius-bottomright:6px}.btn-group>.btn:hover,.btn-group>.btn:focus,.btn-group>.btn:active,.btn-group>.btn.active{z-index:2}.btn-group .dropdown-toggle:active,.btn-group.open .dropdown-toggle{outline:0}.btn-group>.btn+.dropdown-toggle{*padding-top:5px;padding-right:8px;*padding-bottom:5px;padding-left:8px;-webkit-box-shadow:inset 1px 0 0 rgba(255,255,255,0.125),inset 0 1px 0 rgba(255,255,255,0.2),0 1px 2px rgba(0,0,0,0.05);-moz-box-shadow:inset 1px 0 0 rgba(255,255,255,0.125),inset 0 1px 0 rgba(255,255,255,0.2),0 1px 2px rgba(0,0,0,0.05);box-shadow:inset 1px 0 0 rgba(255,255,255,0.125),inset 0 1px 0 rgba(255,255,255,0.2),0 1px 2px rgba(0,0,0,0.05)}.btn-group>.btn-mini+.dropdown-toggle{*padding-top:2px;padding-right:5px;*padding-bottom:2px;padding-left:5px}.btn-group>.btn-small+.dropdown-toggle{*padding-top:5px;*padding-bottom:4px}.btn-group>.btn-large+.dropdown-toggle{*padding-top:7px;padding-right:12px;*padding-bottom:7px;padding-left:12px}.btn-group.open .dropdown-toggle{background-image:none;-webkit-box-shadow:inset 0 2px 4px rgba(0,0,0,0.15),0 1px 2px rgba(0,0,0,0.05);-moz-box-shadow:inset 0 2px 4px rgba(0,0,0,0.15),0 1px 2px rgba(0,0,0,0.05);box-shadow:inset 0 2px 4px rgba(0,0,0,0.15),0 1px 2px rgba(0,0,0,0.05)}.btn-group.open .btn.dropdown-toggle{background-color:#e6e6e6}.btn-group.open .btn-primary.dropdown-toggle{background-color:#777}.btn-group.open .btn-warning.dropdown-toggle{background-color:#ff7f00}.btn-group.open .btn-danger.dropdown-toggle{background-color:#c00}.btn-group.open .btn-success.dropdown-toggle{background-color:#22b24c}.btn-group.open .btn-info.dropdown-toggle{background-color:#369}.btn-group.open .btn-inverse.dropdown-toggle{background-color:#777}.btn .caret{margin-top:8px;margin-left:0}.btn-large .caret{margin-top:6px}.btn-large .caret{border-top-width:5px;border-right-width:5px;border-left-width:5px}.btn-mini .caret,.btn-small .caret{margin-top:8px}.dropup .btn-large .caret{border-bottom-width:5px}.btn-primary .caret,.btn-warning .caret,.btn-danger .caret,.btn-info .caret,.btn-success .caret,.btn-inverse .caret{border-top-color:#fff;border-bottom-color:#fff}.btn-group-vertical{display:inline-block;*display:inline;*zoom:1}.btn-group-vertical>.btn{display:block;float:none;max-width:100%;-webkit-border-radius:0;-moz-border-radius:0;border-radius:0}.btn-group-vertical>.btn+.btn{margin-top:-1px;margin-left:0}.btn-group-vertical>.btn:first-child{-webkit-border-radius:4px 4px 0 0;-moz-border-radius:4px 4px 0 0;border-radius:4px 4px 0 0}.btn-group-vertical>.btn:last-child{-webkit-border-radius:0 0 4px 4px;-moz-border-radius:0 0 4px 4px;border-radius:0 0 4px 4px}.btn-group-vertical>.btn-large:first-child{-webkit-border-radius:6px 6px 0 0;-moz-border-radius:6px 6px 0 0;border-radius:6px 6px 0 0}.btn-group-vertical>.btn-large:last-child{-webkit-border-radius:0 0 6px 6px;-moz-border-radius:0 0 6px 6px;border-radius:0 0 6px 6px}.alert{padding:8px 35px 8px 14px;margin-bottom:20px;text-shadow:0 1px 0 rgba(255,255,255,0.5);background-color:#fcf8e3;border:1px solid #fbeed5;-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px}.alert,.alert h4{color:#c09853}.alert h4{margin:0}.alert .close{position:relative;top:-2px;right:-21px;line-height:20px}.alert-success{color:#468847;background-color:#dff0d8;border-color:#d6e9c6}.alert-success h4{color:#468847}.alert-danger,.alert-error{color:#b94a48;background-color:#f2dede;border-color:#eed3d7}.alert-danger h4,.alert-error h4{color:#b94a48}.alert-info{color:#3a87ad;background-color:#d9edf7;border-color:#bce8f1}.alert-info h4{color:#3a87ad}.alert-block{padding-top:14px;padding-bottom:14px}.alert-block>p,.alert-block>ul{margin-bottom:0}.alert-block p+p{margin-top:5px}.nav{margin-bottom:20px;margin-left:0;list-style:none}.nav>li>a{display:block}.nav>li>a:hover,.nav>li>a:focus{text-decoration:none;background-color:#eee}.nav>li>a>img{max-width:none}.nav>.pull-right{float:right}.nav-header{display:block;padding:3px 15px;font-size:11px;font-weight:bold;line-height:20px;color:#bbb;text-shadow:0 1px 0 rgba(255,255,255,0.5);text-transform:uppercase}.nav li+.nav-header{margin-top:9px}.nav-list{padding-right:15px;padding-left:15px;margin-bottom:0}.nav-list>li>a,.nav-list .nav-header{margin-right:-15px;margin-left:-15px;text-shadow:0 1px 0 rgba(255,255,255,0.5)}.nav-list>li>a{padding:3px 15px}.nav-list>.active>a,.nav-list>.active>a:hover,.nav-list>.active>a:focus{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,0.2);background-color:#777}.nav-list [class^="icon-"],.nav-list [class*=" icon-"]{margin-right:2px}.nav-list .divider{*width:100%;height:1px;margin:9px 1px;*margin:-5px 0 5px;overflow:hidden;background-color:#e5e5e5;border-bottom:1px solid #fff}.nav-tabs,.nav-pills{*zoom:1}.nav-tabs:before,.nav-pills:before,.nav-tabs:after,.nav-pills:after{display:table;line-height:0;content:""}.nav-tabs:after,.nav-pills:after{clear:both}.nav-tabs>li,.nav-pills>li{float:left}.nav-tabs>li>a,.nav-pills>li>a{padding-right:12px;padding-left:12px;margin-right:2px;line-height:14px}.nav-tabs{border-bottom:1px solid #ddd}.nav-tabs>li{margin-bottom:-1px}.nav-tabs>li>a{padding-top:8px;padding-bottom:8px;line-height:20px;border:1px solid transparent;-webkit-border-radius:4px 4px 0 0;-moz-border-radius:4px 4px 0 0;border-radius:4px 4px 0 0}.nav-tabs>li>a:hover,.nav-tabs>li>a:focus{border-color:#eee #eee #ddd}.nav-tabs>.active>a,.nav-tabs>.active>a:hover,.nav-tabs>.active>a:focus{color:#999;cursor:default;background-color:#fff;border:1px solid #ddd;border-bottom-color:transparent}.nav-pills>li>a{padding-top:8px;padding-bottom:8px;margin-top:2px;margin-bottom:2px;-webkit-border-radius:5px;-moz-border-radius:5px;border-radius:5px}.nav-pills>.active>a,.nav-pills>.active>a:hover,.nav-pills>.active>a:focus{color:#fff;background-color:#777}.nav-stacked>li{float:none}.nav-stacked>li>a{margin-right:0}.nav-tabs.nav-stacked{border-bottom:0}.nav-tabs.nav-stacked>li>a{border:1px solid #ddd;-webkit-border-radius:0;-moz-border-radius:0;border-radius:0}.nav-tabs.nav-stacked>li:first-child>a{-webkit-border-top-right-radius:4px;border-top-right-radius:4px;-webkit-border-top-left-radius:4px;border-top-left-radius:4px;-moz-border-radius-topright:4px;-moz-border-radius-topleft:4px}.nav-tabs.nav-stacked>li:last-child>a{-webkit-border-bottom-right-radius:4px;border-bottom-right-radius:4px;-webkit-border-bottom-left-radius:4px;border-bottom-left-radius:4px;-moz-border-radius-bottomright:4px;-moz-border-radius-bottomleft:4px}.nav-tabs.nav-stacked>li>a:hover,.nav-tabs.nav-stacked>li>a:focus{z-index:2;border-color:#ddd}.nav-pills.nav-stacked>li>a{margin-bottom:3px}.nav-pills.nav-stacked>li:last-child>a{margin-bottom:1px}.nav-tabs .dropdown-menu{-webkit-border-radius:0 0 6px 6px;-moz-border-radius:0 0 6px 6px;border-radius:0 0 6px 6px}.nav-pills .dropdown-menu{-webkit-border-radius:6px;-moz-border-radius:6px;border-radius:6px}.nav .dropdown-toggle .caret{margin-top:6px;border-top-color:#777;border-bottom-color:#777}.nav .dropdown-toggle:hover .caret,.nav .dropdown-toggle:focus .caret{border-top-color:#777;border-bottom-color:#777}.nav-tabs .dropdown-toggle .caret{margin-top:8px}.nav .active .dropdown-toggle .caret{border-top-color:#fff;border-bottom-color:#fff}.nav-tabs .active .dropdown-toggle .caret{border-top-color:#999;border-bottom-color:#999}.nav>.dropdown.active>a:hover,.nav>.dropdown.active>a:focus{cursor:pointer}.nav-tabs .open .dropdown-toggle,.nav-pills .open .dropdown-toggle,.nav>li.dropdown.open.active>a:hover,.nav>li.dropdown.open.active>a:focus{color:#fff;background-color:#bbb;border-color:#bbb}.nav li.dropdown.open .caret,.nav li.dropdown.open.active .caret,.nav li.dropdown.open a:hover .caret,.nav li.dropdown.open a:focus .caret{border-top-color:#fff;border-bottom-color:#fff;opacity:1;filter:alpha(opacity=100)}.tabs-stacked .open>a:hover,.tabs-stacked .open>a:focus{border-color:#bbb}.tabbable{*zoom:1}.tabbable:before,.tabbable:after{display:table;line-height:0;content:""}.tabbable:after{clear:both}.tab-content{overflow:auto}.tabs-below>.nav-tabs,.tabs-right>.nav-tabs,.tabs-left>.nav-tabs{border-bottom:0}.tab-content>.tab-pane,.pill-content>.pill-pane{display:none}.tab-content>.active,.pill-content>.active{display:block}.tabs-below>.nav-tabs{border-top:1px solid #ddd}.tabs-below>.nav-tabs>li{margin-top:-1px;margin-bottom:0}.tabs-below>.nav-tabs>li>a{-webkit-border-radius:0 0 4px 4px;-moz-border-radius:0 0 4px 4px;border-radius:0 0 4px 4px}.tabs-below>.nav-tabs>li>a:hover,.tabs-below>.nav-tabs>li>a:focus{border-top-color:#ddd;border-bottom-color:transparent}.tabs-below>.nav-tabs>.active>a,.tabs-below>.nav-tabs>.active>a:hover,.tabs-below>.nav-tabs>.active>a:focus{border-color:transparent #ddd #ddd #ddd}.tabs-left>.nav-tabs>li,.tabs-right>.nav-tabs>li{float:none}.tabs-left>.nav-tabs>li>a,.tabs-right>.nav-tabs>li>a{min-width:74px;margin-right:0;margin-bottom:3px}.tabs-left>.nav-tabs{float:left;margin-right:19px;border-right:1px solid #ddd}.tabs-left>.nav-tabs>li>a{margin-right:-1px;-webkit-border-radius:4px 0 0 4px;-moz-border-radius:4px 0 0 4px;border-radius:4px 0 0 4px}.tabs-left>.nav-tabs>li>a:hover,.tabs-left>.nav-tabs>li>a:focus{border-color:#eee #ddd #eee #eee}.tabs-left>.nav-tabs .active>a,.tabs-left>.nav-tabs .active>a:hover,.tabs-left>.nav-tabs .active>a:focus{border-color:#ddd transparent #ddd #ddd;*border-right-color:#fff}.tabs-right>.nav-tabs{float:right;margin-left:19px;border-left:1px solid #ddd}.tabs-right>.nav-tabs>li>a{margin-left:-1px;-webkit-border-radius:0 4px 4px 0;-moz-border-radius:0 4px 4px 0;border-radius:0 4px 4px 0}.tabs-right>.nav-tabs>li>a:hover,.tabs-right>.nav-tabs>li>a:focus{border-color:#eee #eee #eee #ddd}.tabs-right>.nav-tabs .active>a,.tabs-right>.nav-tabs .active>a:hover,.tabs-right>.nav-tabs .active>a:focus{border-color:#ddd #ddd #ddd transparent;*border-left-color:#fff}.nav>.disabled>a{color:#bbb}.nav>.disabled>a:hover,.nav>.disabled>a:focus{text-decoration:none;cursor:default;background-color:transparent}.navbar{*position:relative;*z-index:2;margin-bottom:20px;overflow:visible}.navbar-inner{min-height:60px;padding-right:20px;padding-left:20px;background-color:#fff;background-image:-moz-linear-gradient(top,#fff,#fff);background-image:-webkit-gradient(linear,0 0,0 100%,from(#fff),to(#fff));background-image:-webkit-linear-gradient(top,#fff,#fff);background-image:-o-linear-gradient(top,#fff,#fff);background-image:linear-gradient(to bottom,#fff,#fff);background-repeat:repeat-x;border:1px solid #e0e0e0;-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffffffff',endColorstr='#ffffffff',GradientType=0);*zoom:1;-webkit-box-shadow:0 1px 4px rgba(0,0,0,0.065);-moz-box-shadow:0 1px 4px rgba(0,0,0,0.065);box-shadow:0 1px 4px rgba(0,0,0,0.065)}.navbar-inner:before,.navbar-inner:after{display:table;line-height:0;content:""}.navbar-inner:after{clear:both}.navbar .container{width:auto}.nav-collapse.collapse{height:auto;overflow:visible}.navbar .brand{display:block;float:left;padding:20px 20px 20px;margin-left:-20px;font-size:20px;font-weight:200;color:#000;text-shadow:0 1px 0 #fff}.navbar .brand:hover,.navbar .brand:focus{text-decoration:none}.navbar-text{margin-bottom:0;line-height:60px;color:#777}.navbar-link{color:#000}.navbar-link:hover,.navbar-link:focus{color:#000}.navbar .divider-vertical{height:60px;margin:0 9px;border-right:1px solid #fff;border-left:1px solid #fff}.navbar .btn,.navbar .btn-group{margin-top:15px}.navbar .btn-group .btn,.navbar .input-prepend .btn,.navbar .input-append .btn,.navbar .input-prepend .btn-group,.navbar .input-append .btn-group{margin-top:0}.navbar-form{margin-bottom:0;*zoom:1}.navbar-form:before,.navbar-form:after{display:table;line-height:0;content:""}.navbar-form:after{clear:both}.navbar-form input,.navbar-form select,.navbar-form .radio,.navbar-form .checkbox{margin-top:15px}.navbar-form input,.navbar-form select,.navbar-form .btn{display:inline-block;margin-bottom:0}.navbar-form input[type="image"],.navbar-form input[type="checkbox"],.navbar-form input[type="radio"]{margin-top:3px}.navbar-form .input-append,.navbar-form .input-prepend{margin-top:5px;white-space:nowrap}.navbar-form .input-append input,.navbar-form .input-prepend input{margin-top:0}.navbar-search{position:relative;float:left;margin-top:15px;margin-bottom:0}.navbar-search .search-query{padding:4px 14px;margin-bottom:0;font-family:"News Cycle","Arial Narrow Bold",sans-serif;font-size:13px;font-weight:normal;line-height:1;-webkit-border-radius:15px;-moz-border-radius:15px;border-radius:15px}.navbar-static-top{position:static;margin-bottom:0}.navbar-static-top .navbar-inner{-webkit-border-radius:0;-moz-border-radius:0;border-radius:0}.navbar-fixed-top,.navbar-fixed-bottom{position:fixed;right:0;left:0;z-index:1030;margin-bottom:0}.navbar-fixed-top .navbar-inner,.navbar-static-top .navbar-inner{border-width:0 0 1px}.navbar-fixed-bottom .navbar-inner{border-width:1px 0 0}.navbar-fixed-top .navbar-inner,.navbar-fixed-bottom .navbar-inner{padding-right:0;padding-left:0;-webkit-border-radius:0;-moz-border-radius:0;border-radius:0}.navbar-static-top .container,.navbar-fixed-top .container,.navbar-fixed-bottom .container{width:940px}.navbar-fixed-top{top:0}.navbar-fixed-top .navbar-inner,.navbar-static-top .navbar-inner{-webkit-box-shadow:0 1px 10px rgba(0,0,0,0.1);-moz-box-shadow:0 1px 10px rgba(0,0,0,0.1);box-shadow:0 1px 10px rgba(0,0,0,0.1)}.navbar-fixed-bottom{bottom:0}.navbar-fixed-bottom .navbar-inner{-webkit-box-shadow:0 -1px 10px rgba(0,0,0,0.1);-moz-box-shadow:0 -1px 10px rgba(0,0,0,0.1);box-shadow:0 -1px 10px rgba(0,0,0,0.1)}.navbar .nav{position:relative;left:0;display:block;float:left;margin:0 10px 0 0}.navbar .nav.pull-right{float:right;margin-right:0}.navbar .nav>li{float:left}.navbar .nav>li>a{float:none;padding:20px 15px 20px;color:#000;text-decoration:none;text-shadow:0 1px 0 #fff}.navbar .nav .dropdown-toggle .caret{margin-top:8px}.navbar .nav>li>a:focus,.navbar .nav>li>a:hover{color:#000;text-decoration:none;background-color:transparent}.navbar .nav>.active>a,.navbar .nav>.active>a:hover,.navbar .nav>.active>a:focus{color:#000;text-decoration:none;background-color:transparent;-webkit-box-shadow:inset 0 3px 8px rgba(0,0,0,0.125);-moz-box-shadow:inset 0 3px 8px rgba(0,0,0,0.125);box-shadow:inset 0 3px 8px rgba(0,0,0,0.125)}.navbar .btn-navbar{display:none;float:right;padding:7px 10px;margin-right:5px;margin-left:5px;color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,0.25);background-color:#f2f2f2;*background-color:#f2f2f2;background-image:-moz-linear-gradient(top,#f2f2f2,#f2f2f2);background-image:-webkit-gradient(linear,0 0,0 100%,from(#f2f2f2),to(#f2f2f2));background-image:-webkit-linear-gradient(top,#f2f2f2,#f2f2f2);background-image:-o-linear-gradient(top,#f2f2f2,#f2f2f2);background-image:linear-gradient(to bottom,#f2f2f2,#f2f2f2);background-repeat:repeat-x;border-color:#f2f2f2 #f2f2f2 #ccc;border-color:rgba(0,0,0,0.1) rgba(0,0,0,0.1) rgba(0,0,0,0.25);filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#fff2f2f2',endColorstr='#fff2f2f2',GradientType=0);filter:progid:DXImageTransform.Microsoft.gradient(enabled=false);-webkit-box-shadow:inset 0 1px 0 rgba(255,255,255,0.1),0 1px 0 rgba(255,255,255,0.075);-moz-box-shadow:inset 0 1px 0 rgba(255,255,255,0.1),0 1px 0 rgba(255,255,255,0.075);box-shadow:inset 0 1px 0 rgba(255,255,255,0.1),0 1px 0 rgba(255,255,255,0.075)}.navbar .btn-navbar:hover,.navbar .btn-navbar:focus,.navbar .btn-navbar:active,.navbar .btn-navbar.active,.navbar .btn-navbar.disabled,.navbar .btn-navbar[disabled]{color:#fff;background-color:#f2f2f2;*background-color:#e5e5e5}.navbar .btn-navbar:active,.navbar .btn-navbar.active{background-color:#d9d9d9 \9}.navbar .btn-navbar .icon-bar{display:block;width:18px;height:2px;background-color:#f5f5f5;-webkit-border-radius:1px;-moz-border-radius:1px;border-radius:1px;-webkit-box-shadow:0 1px 0 rgba(0,0,0,0.25);-moz-box-shadow:0 1px 0 rgba(0,0,0,0.25);box-shadow:0 1px 0 rgba(0,0,0,0.25)}.btn-navbar .icon-bar+.icon-bar{margin-top:3px}.navbar .nav>li>.dropdown-menu:before{position:absolute;top:-7px;left:9px;display:inline-block;border-right:7px solid transparent;border-bottom:7px solid #ccc;border-left:7px solid transparent;border-bottom-color:rgba(0,0,0,0.2);content:''}.navbar .nav>li>.dropdown-menu:after{position:absolute;top:-6px;left:10px;display:inline-block;border-right:6px solid transparent;border-bottom:6px solid #fff;border-left:6px solid transparent;content:''}.navbar-fixed-bottom .nav>li>.dropdown-menu:before{top:auto;bottom:-7px;border-top:7px solid #ccc;border-bottom:0;border-top-color:rgba(0,0,0,0.2)}.navbar-fixed-bottom .nav>li>.dropdown-menu:after{top:auto;bottom:-6px;border-top:6px solid #fff;border-bottom:0}.navbar .nav li.dropdown>a:hover .caret,.navbar .nav li.dropdown>a:focus .caret{border-top-color:#000;border-bottom-color:#000}.navbar .nav li.dropdown.open>.dropdown-toggle,.navbar .nav li.dropdown.active>.dropdown-toggle,.navbar .nav li.dropdown.open.active>.dropdown-toggle{color:#000;background-color:transparent}.navbar .nav li.dropdown>.dropdown-toggle .caret{border-top-color:#000;border-bottom-color:#000}.navbar .nav li.dropdown.open>.dropdown-toggle .caret,.navbar .nav li.dropdown.active>.dropdown-toggle .caret,.navbar .nav li.dropdown.open.active>.dropdown-toggle .caret{border-top-color:#000;border-bottom-color:#000}.navbar .pull-right>li>.dropdown-menu,.navbar .nav>li>.dropdown-menu.pull-right{right:0;left:auto}.navbar .pull-right>li>.dropdown-menu:before,.navbar .nav>li>.dropdown-menu.pull-right:before{right:12px;left:auto}.navbar .pull-right>li>.dropdown-menu:after,.navbar .nav>li>.dropdown-menu.pull-right:after{right:13px;left:auto}.navbar .pull-right>li>.dropdown-menu .dropdown-menu,.navbar .nav>li>.dropdown-menu.pull-right .dropdown-menu{right:100%;left:auto;margin-right:-1px;margin-left:0;-webkit-border-radius:6px 0 6px 6px;-moz-border-radius:6px 0 6px 6px;border-radius:6px 0 6px 6px}.navbar-inverse .navbar-inner{background-color:#1b1b1b;background-image:-moz-linear-gradient(top,#222,#111);background-image:-webkit-gradient(linear,0 0,0 100%,from(#222),to(#111));background-image:-webkit-linear-gradient(top,#222,#111);background-image:-o-linear-gradient(top,#222,#111);background-image:linear-gradient(to bottom,#222,#111);background-repeat:repeat-x;border-color:#252525;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff222222',endColorstr='#ff111111',GradientType=0)}.navbar-inverse .brand,.navbar-inverse .nav>li>a{color:#bbb;text-shadow:0 -1px 0 rgba(0,0,0,0.25)}.navbar-inverse .brand:hover,.navbar-inverse .nav>li>a:hover,.navbar-inverse .brand:focus,.navbar-inverse .nav>li>a:focus{color:#fff}.navbar-inverse .brand{color:#bbb}.navbar-inverse .navbar-text{color:#bbb}.navbar-inverse .nav>li>a:focus,.navbar-inverse .nav>li>a:hover{color:#fff;background-color:transparent}.navbar-inverse .nav .active>a,.navbar-inverse .nav .active>a:hover,.navbar-inverse .nav .active>a:focus{color:#fff;background-color:#111}.navbar-inverse .navbar-link{color:#bbb}.navbar-inverse .navbar-link:hover,.navbar-inverse .navbar-link:focus{color:#fff}.navbar-inverse .divider-vertical{border-right-color:#222;border-left-color:#111}.navbar-inverse .nav li.dropdown.open>.dropdown-toggle,.navbar-inverse .nav li.dropdown.active>.dropdown-toggle,.navbar-inverse .nav li.dropdown.open.active>.dropdown-toggle{color:#fff;background-color:#111}.navbar-inverse .nav li.dropdown>a:hover .caret,.navbar-inverse .nav li.dropdown>a:focus .caret{border-top-color:#fff;border-bottom-color:#fff}.navbar-inverse .nav li.dropdown>.dropdown-toggle .caret{border-top-color:#bbb;border-bottom-color:#bbb}.navbar-inverse .nav li.dropdown.open>.dropdown-toggle .caret,.navbar-inverse .nav li.dropdown.active>.dropdown-toggle .caret,.navbar-inverse .nav li.dropdown.open.active>.dropdown-toggle .caret{border-top-color:#fff;border-bottom-color:#fff}.navbar-inverse .navbar-search .search-query{color:#fff;background-color:#515151;border-color:#111;-webkit-box-shadow:inset 0 1px 2px rgba(0,0,0,0.1),0 1px 0 rgba(255,255,255,0.15);-moz-box-shadow:inset 0 1px 2px rgba(0,0,0,0.1),0 1px 0 rgba(255,255,255,0.15);box-shadow:inset 0 1px 2px rgba(0,0,0,0.1),0 1px 0 rgba(255,255,255,0.15);-webkit-transition:none;-moz-transition:none;-o-transition:none;transition:none}.navbar-inverse .navbar-search .search-query:-moz-placeholder{color:#ccc}.navbar-inverse .navbar-search .search-query:-ms-input-placeholder{color:#ccc}.navbar-inverse .navbar-search .search-query::-webkit-input-placeholder{color:#ccc}.navbar-inverse .navbar-search .search-query:focus,.navbar-inverse .navbar-search .search-query.focused{padding:5px 15px;color:#777;text-shadow:0 1px 0 #fff;background-color:#fff;border:0;outline:0;-webkit-box-shadow:0 0 3px rgba(0,0,0,0.15);-moz-box-shadow:0 0 3px rgba(0,0,0,0.15);box-shadow:0 0 3px rgba(0,0,0,0.15)}.navbar-inverse .btn-navbar{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,0.25);background-color:#0e0e0e;*background-color:#040404;background-image:-moz-linear-gradient(top,#151515,#040404);background-image:-webkit-gradient(linear,0 0,0 100%,from(#151515),to(#040404));background-image:-webkit-linear-gradient(top,#151515,#040404);background-image:-o-linear-gradient(top,#151515,#040404);background-image:linear-gradient(to bottom,#151515,#040404);background-repeat:repeat-x;border-color:#040404 #040404 #000;border-color:rgba(0,0,0,0.1) rgba(0,0,0,0.1) rgba(0,0,0,0.25);filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff151515',endColorstr='#ff040404',GradientType=0);filter:progid:DXImageTransform.Microsoft.gradient(enabled=false)}.navbar-inverse .btn-navbar:hover,.navbar-inverse .btn-navbar:focus,.navbar-inverse .btn-navbar:active,.navbar-inverse .btn-navbar.active,.navbar-inverse .btn-navbar.disabled,.navbar-inverse .btn-navbar[disabled]{color:#fff;background-color:#040404;*background-color:#000}.navbar-inverse .btn-navbar:active,.navbar-inverse .btn-navbar.active{background-color:#000 \9}.breadcrumb{padding:8px 15px;margin:0 0 20px;list-style:none;background-color:#f5f5f5;-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px}.breadcrumb>li{display:inline-block;*display:inline;text-shadow:0 1px 0 #fff;*zoom:1}.breadcrumb>li>.divider{padding:0 5px;color:#ccc}.breadcrumb>.active{color:#bbb}.pagination{margin:20px 0}.pagination ul{display:inline-block;*display:inline;margin-bottom:0;margin-left:0;-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px;*zoom:1;-webkit-box-shadow:0 1px 2px rgba(0,0,0,0.05);-moz-box-shadow:0 1px 2px rgba(0,0,0,0.05);box-shadow:0 1px 2px rgba(0,0,0,0.05)}.pagination ul>li{display:inline}.pagination ul>li>a,.pagination ul>li>span{float:left;padding:4px 12px;line-height:20px;text-decoration:none;background-color:#fff;border:1px solid #ddd;border-left-width:0}.pagination ul>li>a:hover,.pagination ul>li>a:focus,.pagination ul>.active>a,.pagination ul>.active>span{background-color:#eee}.pagination ul>.active>a,.pagination ul>.active>span{color:#bbb;cursor:default}.pagination ul>.disabled>span,.pagination ul>.disabled>a,.pagination ul>.disabled>a:hover,.pagination ul>.disabled>a:focus{color:#bbb;cursor:default;background-color:transparent}.pagination ul>li:first-child>a,.pagination ul>li:first-child>span{border-left-width:1px;-webkit-border-bottom-left-radius:4px;border-bottom-left-radius:4px;-webkit-border-top-left-radius:4px;border-top-left-radius:4px;-moz-border-radius-bottomleft:4px;-moz-border-radius-topleft:4px}.pagination ul>li:last-child>a,.pagination ul>li:last-child>span{-webkit-border-top-right-radius:4px;border-top-right-radius:4px;-webkit-border-bottom-right-radius:4px;border-bottom-right-radius:4px;-moz-border-radius-topright:4px;-moz-border-radius-bottomright:4px}.pagination-centered{text-align:center}.pagination-right{text-align:right}.pagination-large ul>li>a,.pagination-large ul>li>span{padding:11px 19px;font-size:17.5px}.pagination-large ul>li:first-child>a,.pagination-large ul>li:first-child>span{-webkit-border-bottom-left-radius:6px;border-bottom-left-radius:6px;-webkit-border-top-left-radius:6px;border-top-left-radius:6px;-moz-border-radius-bottomleft:6px;-moz-border-radius-topleft:6px}.pagination-large ul>li:last-child>a,.pagination-large ul>li:last-child>span{-webkit-border-top-right-radius:6px;border-top-right-radius:6px;-webkit-border-bottom-right-radius:6px;border-bottom-right-radius:6px;-moz-border-radius-topright:6px;-moz-border-radius-bottomright:6px}.pagination-mini ul>li:first-child>a,.pagination-small ul>li:first-child>a,.pagination-mini ul>li:first-child>span,.pagination-small ul>li:first-child>span{-webkit-border-bottom-left-radius:3px;border-bottom-left-radius:3px;-webkit-border-top-left-radius:3px;border-top-left-radius:3px;-moz-border-radius-bottomleft:3px;-moz-border-radius-topleft:3px}.pagination-mini ul>li:last-child>a,.pagination-small ul>li:last-child>a,.pagination-mini ul>li:last-child>span,.pagination-small ul>li:last-child>span{-webkit-border-top-right-radius:3px;border-top-right-radius:3px;-webkit-border-bottom-right-radius:3px;border-bottom-right-radius:3px;-moz-border-radius-topright:3px;-moz-border-radius-bottomright:3px}.pagination-small ul>li>a,.pagination-small ul>li>span{padding:2px 10px;font-size:11.9px}.pagination-mini ul>li>a,.pagination-mini ul>li>span{padding:0 6px;font-size:10.5px}.pager{margin:20px 0;text-align:center;list-style:none;*zoom:1}.pager:before,.pager:after{display:table;line-height:0;content:""}.pager:after{clear:both}.pager li{display:inline}.pager li>a,.pager li>span{display:inline-block;padding:5px 14px;background-color:#fff;border:1px solid #ddd;-webkit-border-radius:15px;-moz-border-radius:15px;border-radius:15px}.pager li>a:hover,.pager li>a:focus{text-decoration:none;background-color:#f5f5f5}.pager .next>a,.pager .next>span{float:right}.pager .previous>a,.pager .previous>span{float:left}.pager .disabled>a,.pager .disabled>a:hover,.pager .disabled>a:focus,.pager .disabled>span{color:#bbb;cursor:default;background-color:#fff}.modal-backdrop{position:fixed;top:0;right:0;bottom:0;left:0;z-index:1040;background-color:#000}.modal-backdrop.fade{opacity:0}.modal-backdrop,.modal-backdrop.fade.in{opacity:.8;filter:alpha(opacity=80)}.modal{position:fixed;top:10%;left:50%;z-index:1050;width:560px;margin-left:-280px;background-color:#fff;border:1px solid #999;border:1px solid rgba(0,0,0,0.3);*border:1px solid #999;-webkit-border-radius:6px;-moz-border-radius:6px;border-radius:6px;outline:0;-webkit-box-shadow:0 3px 7px rgba(0,0,0,0.3);-moz-box-shadow:0 3px 7px rgba(0,0,0,0.3);box-shadow:0 3px 7px rgba(0,0,0,0.3);-webkit-background-clip:padding-box;-moz-background-clip:padding-box;background-clip:padding-box}.modal.fade{top:-25%;-webkit-transition:opacity .3s linear,top .3s ease-out;-moz-transition:opacity .3s linear,top .3s ease-out;-o-transition:opacity .3s linear,top .3s ease-out;transition:opacity .3s linear,top .3s ease-out}.modal.fade.in{top:10%}.modal-header{padding:9px 15px;border-bottom:1px solid #eee}.modal-header .close{margin-top:2px}.modal-header h3{margin:0;line-height:30px}.modal-body{position:relative;max-height:400px;padding:15px;overflow-y:auto}.modal-form{margin-bottom:0}.modal-footer{padding:14px 15px 15px;margin-bottom:0;text-align:right;background-color:#f5f5f5;border-top:1px solid #ddd;-webkit-border-radius:0 0 6px 6px;-moz-border-radius:0 0 6px 6px;border-radius:0 0 6px 6px;*zoom:1;-webkit-box-shadow:inset 0 1px 0 #fff;-moz-box-shadow:inset 0 1px 0 #fff;box-shadow:inset 0 1px 0 #fff}.modal-footer:before,.modal-footer:after{display:table;line-height:0;content:""}.modal-footer:after{clear:both}.modal-footer .btn+.btn{margin-bottom:0;margin-left:5px}.modal-footer .btn-group .btn+.btn{margin-left:-1px}.modal-footer .btn-block+.btn-block{margin-left:0}.tooltip{position:absolute;z-index:1020;display:block;font-size:11px;line-height:1.4;opacity:0;filter:alpha(opacity=0);visibility:visible}.tooltip.in{opacity:.8;filter:alpha(opacity=80)}.tooltip.top{padding:5px 0;margin-top:-3px}.tooltip.right{padding:0 5px;margin-left:3px}.tooltip.bottom{padding:5px 0;margin-top:3px}.tooltip.left{padding:0 5px;margin-left:-3px}.tooltip-inner{max-width:200px;padding:8px;color:#fff;text-align:center;text-decoration:none;background-color:#000;-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px}.tooltip-arrow{position:absolute;width:0;height:0;border-color:transparent;border-style:solid}.tooltip.top .tooltip-arrow{bottom:0;left:50%;margin-left:-5px;border-top-color:#000;border-width:5px 5px 0}.tooltip.right .tooltip-arrow{top:50%;left:0;margin-top:-5px;border-right-color:#000;border-width:5px 5px 5px 0}.tooltip.left .tooltip-arrow{top:50%;right:0;margin-top:-5px;border-left-color:#000;border-width:5px 0 5px 5px}.tooltip.bottom .tooltip-arrow{top:0;left:50%;margin-left:-5px;border-bottom-color:#000;border-width:0 5px 5px}.popover{position:absolute;top:0;left:0;z-index:1010;display:none;max-width:276px;padding:1px;text-align:left;white-space:normal;background-color:#fff;border:1px solid #ccc;border:1px solid rgba(0,0,0,0.2);-webkit-border-radius:6px;-moz-border-radius:6px;border-radius:6px;-webkit-box-shadow:0 5px 10px rgba(0,0,0,0.2);-moz-box-shadow:0 5px 10px rgba(0,0,0,0.2);box-shadow:0 5px 10px rgba(0,0,0,0.2);-webkit-background-clip:padding-box;-moz-background-clip:padding;background-clip:padding-box}.popover.top{margin-top:-10px}.popover.right{margin-left:10px}.popover.bottom{margin-top:10px}.popover.left{margin-left:-10px}.popover-title{padding:8px 14px;margin:0;font-size:14px;font-weight:normal;line-height:18px;background-color:#f7f7f7;border-bottom:1px solid #ebebeb;-webkit-border-radius:5px 5px 0 0;-moz-border-radius:5px 5px 0 0;border-radius:5px 5px 0 0}.popover-title:empty{display:none}.popover-content{padding:9px 14px}.popover .arrow,.popover .arrow:after{position:absolute;display:block;width:0;height:0;border-color:transparent;border-style:solid}.popover .arrow{border-width:11px}.popover .arrow:after{border-width:10px;content:""}.popover.top .arrow{bottom:-11px;left:50%;margin-left:-11px;border-top-color:#999;border-top-color:rgba(0,0,0,0.25);border-bottom-width:0}.popover.top .arrow:after{bottom:1px;margin-left:-10px;border-top-color:#fff;border-bottom-width:0}.popover.right .arrow{top:50%;left:-11px;margin-top:-11px;border-right-color:#999;border-right-color:rgba(0,0,0,0.25);border-left-width:0}.popover.right .arrow:after{bottom:-10px;left:1px;border-right-color:#fff;border-left-width:0}.popover.bottom .arrow{top:-11px;left:50%;margin-left:-11px;border-bottom-color:#999;border-bottom-color:rgba(0,0,0,0.25);border-top-width:0}.popover.bottom .arrow:after{top:1px;margin-left:-10px;border-bottom-color:#fff;border-top-width:0}.popover.left .arrow{top:50%;right:-11px;margin-top:-11px;border-left-color:#999;border-left-color:rgba(0,0,0,0.25);border-right-width:0}.popover.left .arrow:after{right:1px;bottom:-10px;border-left-color:#fff;border-right-width:0}.thumbnails{margin-left:-20px;list-style:none;*zoom:1}.thumbnails:before,.thumbnails:after{display:table;line-height:0;content:""}.thumbnails:after{clear:both}.row-fluid .thumbnails{margin-left:0}.thumbnails>li{float:left;margin-bottom:20px;margin-left:20px}.thumbnail{display:block;padding:4px;line-height:20px;border:1px solid #ddd;-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px;-webkit-box-shadow:0 1px 3px rgba(0,0,0,0.055);-moz-box-shadow:0 1px 3px rgba(0,0,0,0.055);box-shadow:0 1px 3px rgba(0,0,0,0.055);-webkit-transition:all .2s ease-in-out;-moz-transition:all .2s ease-in-out;-o-transition:all .2s ease-in-out;transition:all .2s ease-in-out}a.thumbnail:hover,a.thumbnail:focus{border-color:#777;-webkit-box-shadow:0 1px 4px rgba(0,105,214,0.25);-moz-box-shadow:0 1px 4px rgba(0,105,214,0.25);box-shadow:0 1px 4px rgba(0,105,214,0.25)}.thumbnail>img{display:block;max-width:100%;margin-right:auto;margin-left:auto}.thumbnail .caption{padding:9px;color:#999}.media,.media-body{overflow:hidden;*overflow:visible;zoom:1}.media,.media .media{margin-top:15px}.media:first-child{margin-top:0}.media-object{display:block}.media-heading{margin:0 0 5px}.media>.pull-left{margin-right:10px}.media>.pull-right{margin-left:10px}.media-list{margin-left:0;list-style:none}.label,.badge{display:inline-block;padding:2px 4px;font-size:11.844px;font-weight:bold;line-height:14px;color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,0.25);white-space:nowrap;vertical-align:baseline;background-color:#bbb}.label{-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px}.badge{padding-right:9px;padding-left:9px;-webkit-border-radius:9px;-moz-border-radius:9px;border-radius:9px}.label:empty,.badge:empty{display:none}a.label:hover,a.label:focus,a.badge:hover,a.badge:focus{color:#fff;text-decoration:none;cursor:pointer}.label-important,.badge-important{background-color:#b94a48}.label-important[href],.badge-important[href]{background-color:#953b39}.label-warning,.badge-warning{background-color:#ff7f00}.label-warning[href],.badge-warning[href]{background-color:#c60}.label-success,.badge-success{background-color:#468847}.label-success[href],.badge-success[href]{background-color:#356635}.label-info,.badge-info{background-color:#3a87ad}.label-info[href],.badge-info[href]{background-color:#2d6987}.label-inverse,.badge-inverse{background-color:#777}.label-inverse[href],.badge-inverse[href]{background-color:#5e5e5e}.btn .label,.btn .badge{position:relative;top:-1px}.btn-mini .label,.btn-mini .badge{top:0}@-webkit-keyframes progress-bar-stripes{from{background-position:40px 0}to{background-position:0 0}}@-moz-keyframes progress-bar-stripes{from{background-position:40px 0}to{background-position:0 0}}@-ms-keyframes progress-bar-stripes{from{background-position:40px 0}to{background-position:0 0}}@-o-keyframes progress-bar-stripes{from{background-position:0 0}to{background-position:40px 0}}@keyframes progress-bar-stripes{from{background-position:40px 0}to{background-position:0 0}}.progress{height:20px;margin-bottom:20px;overflow:hidden;background-color:#f7f7f7;background-image:-moz-linear-gradient(top,#f5f5f5,#f9f9f9);background-image:-webkit-gradient(linear,0 0,0 100%,from(#f5f5f5),to(#f9f9f9));background-image:-webkit-linear-gradient(top,#f5f5f5,#f9f9f9);background-image:-o-linear-gradient(top,#f5f5f5,#f9f9f9);background-image:linear-gradient(to bottom,#f5f5f5,#f9f9f9);background-repeat:repeat-x;-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#fff5f5f5',endColorstr='#fff9f9f9',GradientType=0);-webkit-box-shadow:inset 0 1px 2px rgba(0,0,0,0.1);-moz-box-shadow:inset 0 1px 2px rgba(0,0,0,0.1);box-shadow:inset 0 1px 2px rgba(0,0,0,0.1)}.progress .bar{float:left;width:0;height:100%;font-size:12px;color:#fff;text-align:center;text-shadow:0 -1px 0 rgba(0,0,0,0.25);background-color:#0e90d2;background-image:-moz-linear-gradient(top,#149bdf,#0480be);background-image:-webkit-gradient(linear,0 0,0 100%,from(#149bdf),to(#0480be));background-image:-webkit-linear-gradient(top,#149bdf,#0480be);background-image:-o-linear-gradient(top,#149bdf,#0480be);background-image:linear-gradient(to bottom,#149bdf,#0480be);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff149bdf',endColorstr='#ff0480be',GradientType=0);-webkit-box-shadow:inset 0 -1px 0 rgba(0,0,0,0.15);-moz-box-shadow:inset 0 -1px 0 rgba(0,0,0,0.15);box-shadow:inset 0 -1px 0 rgba(0,0,0,0.15);-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box;-webkit-transition:width .6s ease;-moz-transition:width .6s ease;-o-transition:width .6s ease;transition:width .6s ease}.progress .bar+.bar{-webkit-box-shadow:inset 1px 0 0 rgba(0,0,0,0.15),inset 0 -1px 0 rgba(0,0,0,0.15);-moz-box-shadow:inset 1px 0 0 rgba(0,0,0,0.15),inset 0 -1px 0 rgba(0,0,0,0.15);box-shadow:inset 1px 0 0 rgba(0,0,0,0.15),inset 0 -1px 0 rgba(0,0,0,0.15)}.progress-striped .bar{background-color:#149bdf;background-image:-webkit-gradient(linear,0 100%,100% 0,color-stop(0.25,rgba(255,255,255,0.15)),color-stop(0.25,transparent),color-stop(0.5,transparent),color-stop(0.5,rgba(255,255,255,0.15)),color-stop(0.75,rgba(255,255,255,0.15)),color-stop(0.75,transparent),to(transparent));background-image:-webkit-linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent);background-image:-moz-linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent);background-image:-o-linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent);background-image:linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent);-webkit-background-size:40px 40px;-moz-background-size:40px 40px;-o-background-size:40px 40px;background-size:40px 40px}.progress.active .bar{-webkit-animation:progress-bar-stripes 2s linear infinite;-moz-animation:progress-bar-stripes 2s linear infinite;-ms-animation:progress-bar-stripes 2s linear infinite;-o-animation:progress-bar-stripes 2s linear infinite;animation:progress-bar-stripes 2s linear infinite}.progress-danger .bar,.progress .bar-danger{background-color:#dd514c;background-image:-moz-linear-gradient(top,#ee5f5b,#c43c35);background-image:-webkit-gradient(linear,0 0,0 100%,from(#ee5f5b),to(#c43c35));background-image:-webkit-linear-gradient(top,#ee5f5b,#c43c35);background-image:-o-linear-gradient(top,#ee5f5b,#c43c35);background-image:linear-gradient(to bottom,#ee5f5b,#c43c35);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffee5f5b',endColorstr='#ffc43c35',GradientType=0)}.progress-danger.progress-striped .bar,.progress-striped .bar-danger{background-color:#ee5f5b;background-image:-webkit-gradient(linear,0 100%,100% 0,color-stop(0.25,rgba(255,255,255,0.15)),color-stop(0.25,transparent),color-stop(0.5,transparent),color-stop(0.5,rgba(255,255,255,0.15)),color-stop(0.75,rgba(255,255,255,0.15)),color-stop(0.75,transparent),to(transparent));background-image:-webkit-linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent);background-image:-moz-linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent);background-image:-o-linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent);background-image:linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent)}.progress-success .bar,.progress .bar-success{background-color:#5eb95e;background-image:-moz-linear-gradient(top,#62c462,#57a957);background-image:-webkit-gradient(linear,0 0,0 100%,from(#62c462),to(#57a957));background-image:-webkit-linear-gradient(top,#62c462,#57a957);background-image:-o-linear-gradient(top,#62c462,#57a957);background-image:linear-gradient(to bottom,#62c462,#57a957);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff62c462',endColorstr='#ff57a957',GradientType=0)}.progress-success.progress-striped .bar,.progress-striped .bar-success{background-color:#62c462;background-image:-webkit-gradient(linear,0 100%,100% 0,color-stop(0.25,rgba(255,255,255,0.15)),color-stop(0.25,transparent),color-stop(0.5,transparent),color-stop(0.5,rgba(255,255,255,0.15)),color-stop(0.75,rgba(255,255,255,0.15)),color-stop(0.75,transparent),to(transparent));background-image:-webkit-linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent);background-image:-moz-linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent);background-image:-o-linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent);background-image:linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent)}.progress-info .bar,.progress .bar-info{background-color:#4bb1cf;background-image:-moz-linear-gradient(top,#5bc0de,#339bb9);background-image:-webkit-gradient(linear,0 0,0 100%,from(#5bc0de),to(#339bb9));background-image:-webkit-linear-gradient(top,#5bc0de,#339bb9);background-image:-o-linear-gradient(top,#5bc0de,#339bb9);background-image:linear-gradient(to bottom,#5bc0de,#339bb9);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff5bc0de',endColorstr='#ff339bb9',GradientType=0)}.progress-info.progress-striped .bar,.progress-striped .bar-info{background-color:#5bc0de;background-image:-webkit-gradient(linear,0 100%,100% 0,color-stop(0.25,rgba(255,255,255,0.15)),color-stop(0.25,transparent),color-stop(0.5,transparent),color-stop(0.5,rgba(255,255,255,0.15)),color-stop(0.75,rgba(255,255,255,0.15)),color-stop(0.75,transparent),to(transparent));background-image:-webkit-linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent);background-image:-moz-linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent);background-image:-o-linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent);background-image:linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent)}.progress-warning .bar,.progress .bar-warning{background-color:#ff962e;background-image:-moz-linear-gradient(top,#ffa54d,#ff7f00);background-image:-webkit-gradient(linear,0 0,0 100%,from(#ffa54d),to(#ff7f00));background-image:-webkit-linear-gradient(top,#ffa54d,#ff7f00);background-image:-o-linear-gradient(top,#ffa54d,#ff7f00);background-image:linear-gradient(to bottom,#ffa54d,#ff7f00);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffffa54d',endColorstr='#ffff7f00',GradientType=0)}.progress-warning.progress-striped .bar,.progress-striped .bar-warning{background-color:#ffa54d;background-image:-webkit-gradient(linear,0 100%,100% 0,color-stop(0.25,rgba(255,255,255,0.15)),color-stop(0.25,transparent),color-stop(0.5,transparent),color-stop(0.5,rgba(255,255,255,0.15)),color-stop(0.75,rgba(255,255,255,0.15)),color-stop(0.75,transparent),to(transparent));background-image:-webkit-linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent);background-image:-moz-linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent);background-image:-o-linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent);background-image:linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent)}.accordion{margin-bottom:20px}.accordion-group{margin-bottom:2px;border:1px solid #e5e5e5;-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px}.accordion-heading{border-bottom:0}.accordion-heading .accordion-toggle{display:block;padding:8px 15px}.accordion-toggle{cursor:pointer}.accordion-inner{padding:9px 15px;border-top:1px solid #e5e5e5}.carousel{position:relative;margin-bottom:20px;line-height:1}.carousel-inner{position:relative;width:100%;overflow:hidden}.carousel-inner>.item{position:relative;display:none;-webkit-transition:.6s ease-in-out left;-moz-transition:.6s ease-in-out left;-o-transition:.6s ease-in-out left;transition:.6s ease-in-out left}.carousel-inner>.item>img,.carousel-inner>.item>a>img{display:block;line-height:1}.carousel-inner>.active,.carousel-inner>.next,.carousel-inner>.prev{display:block}.carousel-inner>.active{left:0}.carousel-inner>.next,.carousel-inner>.prev{position:absolute;top:0;width:100%}.carousel-inner>.next{left:100%}.carousel-inner>.prev{left:-100%}.carousel-inner>.next.left,.carousel-inner>.prev.right{left:0}.carousel-inner>.active.left{left:-100%}.carousel-inner>.active.right{left:100%}.carousel-control{position:absolute;top:40%;left:15px;width:40px;height:40px;margin-top:-20px;font-size:60px;font-weight:100;line-height:30px;color:#fff;text-align:center;background:#222;border:3px solid #fff;-webkit-border-radius:23px;-moz-border-radius:23px;border-radius:23px;opacity:.5;filter:alpha(opacity=50)}.carousel-control.right{right:15px;left:auto}.carousel-control:hover,.carousel-control:focus{color:#fff;text-decoration:none;opacity:.9;filter:alpha(opacity=90)}.carousel-indicators{position:absolute;top:15px;right:15px;z-index:5;margin:0;list-style:none}.carousel-indicators li{display:block;float:left;width:10px;height:10px;margin-left:5px;text-indent:-999px;background-color:#ccc;background-color:rgba(255,255,255,0.25);border-radius:5px}.carousel-indicators .active{background-color:#fff}.carousel-caption{position:absolute;right:0;bottom:0;left:0;padding:15px;background:#777;background:rgba(0,0,0,0.75)}.carousel-caption h4,.carousel-caption p{line-height:20px;color:#fff}.carousel-caption h4{margin:0 0 5px}.carousel-caption p{margin-bottom:0}.hero-unit{padding:60px;margin-bottom:30px;font-size:18px;font-weight:200;line-height:30px;color:inherit;background-color:#eee;-webkit-border-radius:6px;-moz-border-radius:6px;border-radius:6px}.hero-unit h1{margin-bottom:0;font-size:60px;line-height:1;letter-spacing:-1px;color:#000}.hero-unit li{line-height:30px}.pull-right{float:right}.pull-left{float:left}.hide{display:none}.show{display:block}.invisible{visibility:hidden}.affix{position:fixed}h1,h2,h3,h4,h5,h6{margin:0 0 10px;line-height:1.2}h1 a,h2 a,h3 a,h4 a,h5 a,h6 a{color:#000}h1{font-size:48px}h2{font-size:36px}h3{font-size:28px}h4{font-size:20px}h5{font-size:13px}p>a,address>a,.breadcrumb a,abbr[title]{text-decoration:none;border-bottom:1px dotted}p>a:hover,address>a:hover,.breadcrumb a:hover,abbr[title]:hover{text-decoration:none;border-bottom:1px solid}code,pre{background-color:#eee;-webkit-border-radius:0;-moz-border-radius:0;border-radius:0;-webkit-box-shadow:none;-moz-box-shadow:none;box-shadow:none}.page-header{border-bottom:2px solid #eee}hr{border-bottom:1px solid #eee}.navbar{font-family:"News Cycle","Arial Narrow Bold",sans-serif;font-weight:bold}.navbar .navbar-inner{border-bottom:2px solid #eee;-webkit-border-radius:0;-moz-border-radius:0;border-radius:0;-webkit-box-shadow:none;-moz-box-shadow:none;box-shadow:none}.navbar .brand{padding:19px 20px 21px;font-size:24px;font-weight:bold;text-shadow:none;text-transform:uppercase}.navbar .nav>li>a{padding:20px 10px 20px;font-size:18px;text-shadow:none;text-transform:uppercase}.navbar .nav>.active>a{background-color:transparent}.navbar .navbar-text{padding-right:10px;padding-left:10px;margin-top:20px;font-size:18px;line-height:20px}.navbar .nav>.active>a,.navbar .nav>.active>a:hover,.navbar .nav>.active>a:focus{-webkit-box-shadow:none;-moz-box-shadow:none;box-shadow:none}.navbar .divider-vertical{border-right-color:#eee;border-left-color:#eee}.navbar .dropdown-menu{top:85%;-webkit-border-radius:0;-moz-border-radius:0;border-radius:0}.navbar .dropdown-menu a{font-size:15px;font-weight:bold}.navbar .navbar-search .search-query,.navbar .navbar-search .search-query:hover{color:#777;border:2px solid #eee}.navbar .navbar-search .search-query:-moz-placeholder,.navbar .navbar-search .search-query:hover:-moz-placeholder{color:#999}.navbar .navbar-search .search-query:-ms-input-placeholder,.navbar .navbar-search .search-query:hover:-ms-input-placeholder{color:#999}.navbar .navbar-search .search-query::-webkit-input-placeholder,.navbar .navbar-search .search-query:hover::-webkit-input-placeholder{color:#999}@media(max-width:979px){.nav-collapse .navbar-form,.nav-collapse .navbar-search{margin-bottom:0;border-top:2px solid #eee;border-bottom:2px solid #eee}.navbar .nav-collapse .nav li>a{color:#000}.navbar .nav-collapse .nav li>a:hover{background-color:#eee}.navbar .nav-collapse .navbar-text{margin-top:0}.navbar-inverse .nav-collapse .nav li>a{color:#bbb}.navbar-inverse .nav-collapse .nav li>a:hover{background-color:#111;background-image:none}}div.subnav{height:54px;margin:0 1px;background:#fff none;border:2px solid #eee;border-right:0;border-left:none;-webkit-border-radius:0;-moz-border-radius:0;border-radius:0;-webkit-box-shadow:none;-moz-box-shadow:none;box-shadow:none}div.subnav.subnav-fixed{top:61px;margin:0;border-top:0}div.subnav .nav>li>a,div.subnav .nav>li:first-child>a,div.subnav .nav>li.active>a{padding:20px 15px;font-family:"News Cycle","Arial Narrow Bold",sans-serif;font-size:15px;font-weight:bold;color:#000;background-color:transparent;border-right:0;border-left:none;-webkit-box-shadow:none;-moz-box-shadow:none;box-shadow:none}div.subnav .nav>li>a:hover,div.subnav .nav>li:first-child>a:hover,div.subnav .nav>li.active>a:hover{padding:20px 15px;color:#000;background-color:transparent;-webkit-box-shadow:none;-moz-box-shadow:none;box-shadow:none}div.subnav li.dropdown>.dropdown-toggle .caret,div.subnav li.dropdown>.dropdown-toggle:hover .caret,div.subnav li.dropdown.open>.dropdown-toggle .caret{border-top-color:#000;border-bottom-color:#000;opacity:1}div.subnav li.dropdown.open .dropdown-toggle,div.subnav li.dropdown.open .dropdown-toggle:hover{color:#000;background-color:#fff}[class^="icon-"],[class*=" icon-"]{vertical-align:baseline}.btn-inverse{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,0.25);background-color:#141414;*background-color:#000;background-image:-moz-linear-gradient(top,#222,#000);background-image:-webkit-gradient(linear,0 0,0 100%,from(#222),to(#000));background-image:-webkit-linear-gradient(top,#222,#000);background-image:-o-linear-gradient(top,#222,#000);background-image:linear-gradient(to bottom,#222,#000);background-repeat:repeat-x;border-color:#000 #000 #000;border-color:rgba(0,0,0,0.1) rgba(0,0,0,0.1) rgba(0,0,0,0.25);filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff222222',endColorstr='#ff000000',GradientType=0);filter:progid:DXImageTransform.Microsoft.gradient(enabled=false)}.btn-inverse:hover,.btn-inverse:focus,.btn-inverse:active,.btn-inverse.active,.btn-inverse.disabled,.btn-inverse[disabled]{color:#fff;background-color:#000;*background-color:#000}.btn-inverse:active,.btn-inverse.active{background-color:#000 \9}.table-bordered{-webkit-border-radius:0;-moz-border-radius:0;border-radius:0;-webkit-box-shadow:none;-moz-box-shadow:none;box-shadow:none}legend{font-family:"News Cycle","Arial Narrow Bold",sans-serif;font-weight:bold;color:#000;border-bottom:2px solid #eee}.well{-webkit-border-radius:0;-moz-border-radius:0;border-radius:0;-webkit-box-shadow:none;-moz-box-shadow:none;box-shadow:none}.hero-unit{padding:30px 60px;border:1px solid rgba(0,0,0,0.05);-webkit-border-radius:0;-moz-border-radius:0;border-radius:0;-webkit-box-shadow:none;-moz-box-shadow:none;box-shadow:none}.hero-unit h1{margin:0 0 10px;line-height:1.2}.modal{background:#fff;-webkit-border-radius:0;-moz-border-radius:0;border-radius:0}.modal-header{border-bottom:0}.modal-footer{background:transparent;border-top:0;-webkit-box-shadow:none;-moz-box-shadow:none;box-shadow:none}.close,.close:hover{border-bottom:0}@media(max-width:768px){div.subnav{height:auto}div.subnav .nav>li.active>a{border-top:0}div.subnav .nav>li:hover>a,div.subnav .nav>li:first-child:hover>a,div.subnav .nav>li.active:hover>a,div.subnav .nav>li.dropdown.open .dropdown-toggle,div.subnav .nav>li.dropdown.open .dropdown-toggle:hover{background-color:#eee}.nav-tabs .open .dropdown-toggle,.nav-pills .open .dropdown-toggle,.nav>li.dropdown.open.active>a:hover{border-color:#e5e5e5}}.pull-right{float:right}.pull-left{float:left}.hide{display:none}.show{display:block}.invisible{visibility:hidden}.affix{position:fixed}
kristoferjoseph/cdnjs
ajax/libs/bootswatch/2.3.0-2/journal/bootstrap.min.css
CSS
mit
112,099
!function(e){"object"==typeof exports&&"object"==typeof module?e(require("../../lib/codemirror")):"function"==typeof define&&define.amd?define(["../../lib/codemirror"],e):e(CodeMirror)}(function(e){"use strict";e.defineMode("velocity",function(){function e(e){for(var t={},n=e.split(" "),r=0;r<n.length;++r)t[n[r]]=!0;return t}function t(e,t,n){return t.tokenize=n,n(e,t)}function n(e,n){var f=n.beforeParams;n.beforeParams=!1;var c=e.next();if("'"==c&&n.inParams)return n.lastTokenWasBuiltin=!1,t(e,n,r(c));if('"'!=c){if(/[\[\]{}\(\),;\.]/.test(c))return"("==c&&f?n.inParams=!0:")"==c&&(n.inParams=!1,n.lastTokenWasBuiltin=!0),null;if(/\d/.test(c))return n.lastTokenWasBuiltin=!1,e.eatWhile(/[\w\.]/),"number";if("#"==c&&e.eat("*"))return n.lastTokenWasBuiltin=!1,t(e,n,i);if("#"==c&&e.match(/ *\[ *\[/))return n.lastTokenWasBuiltin=!1,t(e,n,a);if("#"==c&&e.eat("#"))return n.lastTokenWasBuiltin=!1,e.skipToEnd(),"comment";if("$"==c)return e.eatWhile(/[\w\d\$_\.{}]/),l&&l.propertyIsEnumerable(e.current())?"keyword":(n.lastTokenWasBuiltin=!0,n.beforeParams=!0,"builtin");if(u.test(c))return n.lastTokenWasBuiltin=!1,e.eatWhile(u),"operator";e.eatWhile(/[\w\$_{}@]/);var k=e.current();return o&&o.propertyIsEnumerable(k)?"keyword":s&&s.propertyIsEnumerable(k)||e.current().match(/^#@?[a-z0-9_]+ *$/i)&&"("==e.peek()&&(!s||!s.propertyIsEnumerable(k.toLowerCase()))?(n.beforeParams=!0,n.lastTokenWasBuiltin=!1,"keyword"):n.inString?(n.lastTokenWasBuiltin=!1,"string"):e.pos>k.length&&"."==e.string.charAt(e.pos-k.length-1)&&n.lastTokenWasBuiltin?"builtin":(n.lastTokenWasBuiltin=!1,null)}return n.lastTokenWasBuiltin=!1,n.inString?(n.inString=!1,"string"):n.inParams?t(e,n,r(c)):void 0}function r(e){return function(t,r){for(var i,a=!1,o=!1;null!=(i=t.next());){if(i==e&&!a){o=!0;break}if('"'==e&&"$"==t.peek()&&!a){r.inString=!0,o=!0;break}a=!a&&"\\"==i}return o&&(r.tokenize=n),"string"}}function i(e,t){for(var r,i=!1;r=e.next();){if("#"==r&&i){t.tokenize=n;break}i="*"==r}return"comment"}function a(e,t){for(var r,i=0;r=e.next();){if("#"==r&&2==i){t.tokenize=n;break}"]"==r?i++:" "!=r&&(i=0)}return"meta"}var o=e("#end #else #break #stop #[[ #]] #{end} #{else} #{break} #{stop}"),s=e("#if #elseif #foreach #set #include #parse #macro #define #evaluate #{if} #{elseif} #{foreach} #{set} #{include} #{parse} #{macro} #{define} #{evaluate}"),l=e("$foreach.count $foreach.hasNext $foreach.first $foreach.last $foreach.topmost $foreach.parent.count $foreach.parent.hasNext $foreach.parent.first $foreach.parent.last $foreach.parent $velocityCount $!bodyContent $bodyContent"),u=/[+\-*&%=<>!?:\/|]/;return{startState:function(){return{tokenize:n,beforeParams:!1,inParams:!1,inString:!1,lastTokenWasBuiltin:!1}},token:function(e,t){return e.eatSpace()?null:t.tokenize(e,t)},blockCommentStart:"#*",blockCommentEnd:"*#",lineComment:"##",fold:"velocity"}}),e.defineMIME("text/velocity","velocity")});
lucasls/cdnjs
ajax/libs/codemirror/4.13.0/mode/velocity/velocity.min.js
JavaScript
mit
2,893
webshims.validityMessages.fa={typeMismatch:{defaultMessage:"\u062e\u0648\u0627\u0647\u0634\u0645\u0646\u062f\u06cc\u0645 \u06cc\u06a9 \u0645\u0642\u062f\u0627\u0631 \u0645\u0639\u062a\u0628\u0631 \u0648\u0627\u0631\u062f \u0646\u0645\u0627\u06cc\u06cc\u062f.",email:"\u062e\u0648\u0627\u0647\u0634\u0645\u0646\u062f\u06cc\u0645 \u06cc\u06a9 \u0622\u062f\u0631\u0633 \u0631\u0627\u06cc\u0627\u0646\u0627\u0645\u0647 \u0648\u0627\u0631\u062f \u0646\u0645\u0627\u06cc\u06cc\u062f.",url:"\u062e\u0648\u0627\u0647\u0634\u0645\u0646\u062f\u06cc\u0645 \u06cc\u06a9 \u0622\u062f\u0631\u0633 \u0627\u06cc\u0646\u062a\u0631\u0646\u062a\u06cc \u0648\u0627\u0631\u062f \u0646\u0645\u0627\u06cc\u06cc\u062f."},badInput:{defaultMessage:"\u062e\u0648\u0627\u0647\u0634\u0645\u0646\u062f\u06cc\u0645 \u06cc\u06a9 \u0645\u0642\u062f\u0627\u0631 \u0645\u0639\u062a\u0628\u0631 \u0648\u0627\u0631\u062f \u0646\u0645\u0627\u06cc\u06cc\u062f.",number:"\u062e\u0648\u0627\u0647\u0634\u0645\u0646\u062f\u06cc\u0645 \u06cc\u06a9 \u0639\u062f\u062f \u0648\u0627\u0631\u062f \u0646\u0645\u0627\u06cc\u06cc\u062f.",date:"\u062e\u0648\u0627\u0647\u0634\u0645\u0646\u062f\u06cc\u0645 \u06cc\u06a9 \u062a\u0627\u0631\u06cc\u062e \u0648\u0627\u0631\u062f \u0646\u0645\u0627\u06cc\u06cc\u062f.",time:"\u062e\u0648\u0627\u0647\u0634\u0645\u0646\u062f\u06cc\u0645 \u06cc\u06a9 \u0632\u0645\u0627\u0646 \u0648\u0627\u0631\u062f \u0646\u0645\u0627\u06cc\u06cc\u062f.",range:"\u0648\u0631\u0648\u062f\u06cc \u0646\u0627\u0645\u0639\u062a\u0628\u0631.",month:"\u062e\u0648\u0627\u0647\u0634\u0645\u0646\u062f\u06cc\u0645 \u06cc\u06a9 \u0645\u0642\u062f\u0627\u0631 \u0645\u0639\u062a\u0628\u0631 \u0648\u0627\u0631\u062f \u0646\u0645\u0627\u06cc\u06cc\u062f.","datetime-local":"\u062e\u0648\u0627\u0647\u0634\u0645\u0646\u062f\u06cc\u0645 \u06cc\u06a9 \u062a\u0627\u0631\u06cc\u062e-\u0632\u0645\u0627\u0646 \u0648\u0627\u0631\u062f \u0646\u0645\u0627\u06cc\u06cc\u062f."},rangeUnderflow:{defaultMessage:"\u0645\u0642\u062f\u0627\u0631 \u0648\u0627\u0631\u062f\u0647 \u0645\u06cc \u0628\u0627\u06cc\u0633\u062a \u0628\u0632\u0631\u06af\u062a\u0631-\u0645\u0633\u0627\u0648\u06cc {%min} \u0628\u0627\u0634\u062f.",date:"\u0645\u0642\u062f\u0627\u0631 \u0648\u0627\u0631\u062f\u0647 \u0645\u06cc \u0628\u0627\u06cc\u0633\u062a \u0628\u0631\u0627\u0628\u0631 {%min} \u06cc\u0627 \u0628\u0639\u062f \u062a\u0631 \u0627\u0632 \u0622\u0646 \u0628\u0627\u0634\u062f.",time:"\u0645\u0642\u062f\u0627\u0631 \u0648\u0627\u0631\u062f\u0647 \u0645\u06cc \u0628\u0627\u06cc\u0633\u062a \u0628\u0631\u0627\u0628\u0631 {%min} \u06cc\u0627 \u0628\u0639\u062f \u062a\u0631 \u0627\u0632 \u0622\u0646 \u0628\u0627\u0634\u062f.","datetime-local":"\u0645\u0642\u062f\u0627\u0631 \u0648\u0627\u0631\u062f\u0647 \u0645\u06cc \u0628\u0627\u06cc\u0633\u062a \u0628\u0631\u0627\u0628\u0631 {%min} \u06cc\u0627 \u0628\u0639\u062f \u062a\u0631 \u0627\u0632 \u0622\u0646 \u0628\u0627\u0634\u062f.",month:"\u0645\u0642\u062f\u0627\u0631 \u0648\u0627\u0631\u062f\u0647 \u0645\u06cc \u0628\u0627\u06cc\u0633\u062a \u0628\u0631\u0627\u0628\u0631 {%min} \u06cc\u0627 \u0628\u0639\u062f \u062a\u0631 \u0627\u0632 \u0622\u0646 \u0628\u0627\u0634\u062f."},rangeOverflow:{defaultMessage:"\u0645\u0642\u062f\u0627\u0631 \u0648\u0627\u0631\u062f\u0647 \u0645\u06cc \u0628\u0627\u06cc\u0633\u062a \u06a9\u0648\u0686\u06a9\u062a\u0631-\u0645\u0633\u0627\u0648\u06cc {%max} \u0628\u0627\u0634\u062f.",date:"\u0645\u0642\u062f\u0627\u0631 \u0648\u0627\u0631\u062f\u0647 \u0645\u06cc \u0628\u0627\u06cc\u0633\u062a \u0628\u0631\u0627\u0628\u0631 {%max} \u06cc\u0627 \u0642\u0628\u0644 \u062a\u0631 \u0627\u0632 \u0622\u0646 \u0628\u0627\u0634\u062f.",time:"\u0645\u0642\u062f\u0627\u0631 \u0648\u0627\u0631\u062f\u0647 \u0645\u06cc \u0628\u0627\u06cc\u0633\u062a \u0628\u0631\u0627\u0628\u0631 {%max} \u06cc\u0627 \u0642\u0628\u0644 \u062a\u0631 \u0627\u0632 \u0622\u0646 \u0628\u0627\u0634\u062f.","datetime-local":"\u0645\u0642\u062f\u0627\u0631 \u0648\u0627\u0631\u062f\u0647 \u0645\u06cc \u0628\u0627\u06cc\u0633\u062a \u0628\u0631\u0627\u0628\u0631 {%max} \u06cc\u0627 \u0642\u0628\u0644 \u062a\u0631 \u0627\u0632 \u0622\u0646 \u0628\u0627\u0634\u062f.",month:"\u0645\u0642\u062f\u0627\u0631 \u0648\u0627\u0631\u062f\u0647 \u0645\u06cc \u0628\u0627\u06cc\u0633\u062a \u0628\u0631\u0627\u0628\u0631 {%max} \u06cc\u0627 \u0642\u0628\u0644 \u062a\u0631 \u0627\u0632 \u0622\u0646 \u0628\u0627\u0634\u062f."},stepMismatch:"\u0648\u0631\u0648\u062f\u06cc \u0646\u0627\u0645\u0639\u062a\u0628\u0631.",tooLong:"\u062e\u0648\u0627\u0647\u0634\u0645\u0646\u062f\u06cc\u0645 \u0628\u06cc\u0634 \u0627\u0632 {%maxlength} \u0646\u0648\u06cc\u0633\u0647 \u0648\u0627\u0631\u062f \u0646\u06a9\u0646\u06cc\u062f. \u0634\u0645\u0627 {%valueLen} \u0648\u0627\u0631\u062f \u0646\u0645\u0648\u062f\u0647 \u0627\u06cc\u062f.",tooShort:"\u062e\u0648\u0627\u0647\u0634\u0645\u0646\u062f\u06cc\u0645 \u06a9\u0645 \u062a\u0631 \u0627\u0632 {%minlength} \u0646\u0648\u06cc\u0633\u0647 \u0648\u0627\u0631\u062f \u0646\u06a9\u0646\u06cc\u062f. \u0634\u0645\u0627 {%valueLen} \u0648\u0627\u0631\u062f \u0646\u0645\u0648\u062f\u0647 \u0627\u06cc\u062f.",patternMismatch:"\u0648\u0631\u0648\u062f\u06cc \u0646\u0627\u0645\u0639\u062a\u0628\u0631. {%title}",valueMissing:{defaultMessage:"\u062e\u0648\u0627\u0647\u0634\u0645\u0646\u062f\u06cc\u0645 \u0627\u06cc\u0646 \u0648\u0631\u0648\u062f\u06cc \u0631\u0627 \u067e\u0631 \u0646\u0645\u0627\u06cc\u06cc\u062f.",checkbox:"\u062e\u0648\u0627\u0647\u0634\u0645\u0646\u062f\u06cc\u0645 \u062c\u0647\u062a \u0627\u062f\u0627\u0645\u0647 \u0641\u0639\u0627\u0644\u06cc\u062a\u060c \u0627\u06cc\u0646 \u0648\u0631\u0648\u062f\u06cc \u0631\u0627 \u0639\u0644\u0627\u0645\u062a \u06af\u0630\u0627\u0631\u06cc \u0646\u0645\u0627\u06cc\u06cc\u062f.",select:"\u062e\u0648\u0627\u0647\u0634\u0645\u0646\u062f\u06cc\u0645 \u06af\u0632\u06cc\u0646\u0647 \u0627\u06cc \u0631\u0627 \u0627\u0646\u062a\u062e\u0627\u0628 \u0646\u0645\u0627\u06cc\u06cc\u062f.",radio:"\u062e\u0648\u0627\u0647\u0634\u0645\u0646\u062f\u06cc\u0645 \u06af\u0632\u06cc\u0646\u0647 \u0627\u06cc \u0631\u0627 \u0627\u0646\u062a\u062e\u0627\u0628 \u0646\u0645\u0627\u06cc\u06cc\u062f."}},webshims.formcfg.fa={numberFormat:{".":".",",":","},numberSigns:".",dateSigns:"/",timeSigns:":. ",dFormat:"/",patterns:{d:"yy/mm/dd"},meridian:["\u0628.\u0638","\u0642.\u0638"],month:{currentText:"\u0627\u06cc\u0646 \u0645\u0627\u0647"},time:{currentText:"\u062d\u0627\u0644"},date:{closeText:"\u0627\u0646\u062c\u0627\u0645 \u0634\u062f",clear:"\u0627\u0632 \u0646\u0648",prevText:"\u067e\u06cc\u0634",nextText:"\u067e\u0633",currentText:"\u0627\u0645\u0631\u0648\u0632",monthNames:["\u0698\u0627\u0646\u0648\u06cc\u0647","\u0641\u0648\u0631\u06cc\u0647","\u0645\u0627\u0631\u0633","\u0622\u0648\u0631\u06cc\u0644","\u0645\u0647","\u0698\u0648\u0626\u0646","\u0698\u0648\u0626\u06cc\u0647","\u0627\u0648\u062a","\u0633\u067e\u062a\u0627\u0645\u0628\u0631","\u0627\u06a9\u062a\u0628\u0631","\u0646\u0648\u0627\u0628\u0631","\u062f\u0633\u0627\u0645\u0628\u0631"],monthNamesShort:["\u0698\u0627\u0646\u0648\u06cc\u0647","\u0641\u0648\u0631\u06cc\u0647","\u0645\u0627\u0631\u0633","\u0622\u0648\u0631\u06cc\u0644","\u0645\u0647","\u0698\u0648\u0626\u0646","\u0698\u0648\u0626\u06cc\u0647","\u0627\u0648\u062a","\u0633\u067e\u062a\u0627\u0645\u0628\u0631","\u0627\u06a9\u062a\u0628\u0631","\u0646\u0648\u0627\u0628\u0631","\u062f\u0633\u0627\u0645\u0628\u0631"],dayNames:["\u06cc\u06a9\u0634\u0646\u0628\u0647","\u062f\u0648\u0634\u0646\u0628\u0647","\u0633\u0647 \u0634\u0646\u0628\u0647","\u0686\u0647\u0627\u0631 \u0634\u0646\u0628\u0647","\u067e\u0646\u062c\u0634\u0646\u0628\u0647","\u0622\u062f\u06cc\u0646\u0647","\u0634\u0646\u0628\u0647"],dayNamesShort:["\u06cc","\u062f","\u0633","\u0686","\u067e","\u0622","\u0634"],dayNamesMin:["\u06cc","\u062f","\u0633","\u0686","\u067e","\u0622","\u0634"],weekHeader:"\u0647\u0641\u062a\u0647",firstDay:6,isRTL:!0,showMonthAfterYear:!1,yearSuffix:""}};
kalkidanf/cdnjs
ajax/libs/webshim/1.14.6-RC1/minified/shims/i18n/formcfg-fa.js
JavaScript
mit
7,984
/** * Sinon.JS 1.3.3, 2012/04/16 * * @author Christian Johansen (christian@cjohansen.no) * * (The BSD License) * * Copyright (c) 2010-2011, Christian Johansen, christian@cjohansen.no * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * Neither the name of Christian Johansen nor the names of his contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ "use strict"; /*global sinon, setTimeout, setInterval, clearTimeout, clearInterval, Date*/ /** * Helps IE run the fake timers. By defining global functions, IE allows * them to be overwritten at a later point. If these are not defined like * this, overwriting them will result in anything from an exception to browser * crash. * * If you don't require fake timers to work in IE, don't include this file. * * @author Christian Johansen (christian@cjohansen.no) * @license BSD * * Copyright (c) 2010-2011 Christian Johansen */ function setTimeout() {} function clearTimeout() {} function setInterval() {} function clearInterval() {} function Date() {} // Reassign the original functions. Now their writable attribute // should be true. Hackish, I know, but it works. setTimeout = sinon.timers.setTimeout; clearTimeout = sinon.timers.clearTimeout; setInterval = sinon.timers.setInterval; clearInterval = sinon.timers.clearInterval; Date = sinon.timers.Date;
tresni/cdnjs
ajax/libs/sinon.js/1.3.3/sinon-timers-ie.js
JavaScript
mit
2,721
/*! iScroll v5.0.9 ~ (c) 2008-2013 Matteo Spinelli ~ http://cubiq.org/license */ (function(d,a,c){var f=d.requestAnimationFrame||d.webkitRequestAnimationFrame||d.mozRequestAnimationFrame||d.oRequestAnimationFrame||d.msRequestAnimationFrame||function(g){d.setTimeout(g,1000/60)};var b=(function(){var k={};var l=a.createElement("div").style;var i=(function(){var p=["t","webkitT","MozT","msT","OT"],n,o=0,m=p.length;for(;o<m;o++){n=p[o]+"ransform";if(n in l){return p[o].substr(0,p[o].length-1)}}return false})();function j(m){if(i===false){return false}if(i===""){return m}return i+m.charAt(0).toUpperCase()+m.substr(1)}k.getTime=Date.now||function g(){return new Date().getTime()};k.extend=function(o,n){for(var m in n){o[m]=n[m]}};k.addEvent=function(p,o,n,m){p.addEventListener(o,n,!!m)};k.removeEvent=function(p,o,n,m){p.removeEventListener(o,n,!!m)};k.momentum=function(t,o,p,m,u){var n=t-o,q=c.abs(n)/p,v,r,s=0.0006;v=t+(q*q)/(2*s)*(n<0?-1:1);r=q/s;if(v<m){v=u?m-(u/2.5*(q/8)):m;n=c.abs(v-t);r=n/q}else{if(v>0){v=u?u/2.5*(q/8):0;n=c.abs(t)+v;r=n/q}}return{destination:c.round(v),duration:r}};var h=j("transform");k.extend(k,{hasTransform:h!==false,hasPerspective:j("perspective") in l,hasTouch:"ontouchstart" in d,hasPointer:navigator.msPointerEnabled,hasTransition:j("transition") in l});k.isBadAndroid=/Android/.test(d.navigator.appVersion)&&!(/Chrome\/\d/.test(d.navigator.appVersion));k.extend(k.style={},{transform:h,transitionTimingFunction:j("transitionTimingFunction"),transitionDuration:j("transitionDuration"),transitionDelay:j("transitionDelay"),transformOrigin:j("transformOrigin")});k.hasClass=function(n,o){var m=new RegExp("(^|\\s)"+o+"(\\s|$)");return m.test(n.className)};k.addClass=function(n,o){if(k.hasClass(n,o)){return}var m=n.className.split(" ");m.push(o);n.className=m.join(" ")};k.removeClass=function(n,o){if(!k.hasClass(n,o)){return}var m=new RegExp("(^|\\s)"+o+"(\\s|$)","g");n.className=n.className.replace(m," ")};k.offset=function(m){var o=-m.offsetLeft,n=-m.offsetTop;while(m=m.offsetParent){o-=m.offsetLeft;n-=m.offsetTop}return{left:o,top:n}};k.preventDefaultException=function(o,n){for(var m in n){if(n[m].test(o[m])){return true}}return false};k.extend(k.eventType={},{touchstart:1,touchmove:1,touchend:1,mousedown:2,mousemove:2,mouseup:2,MSPointerDown:3,MSPointerMove:3,MSPointerUp:3});k.extend(k.ease={},{quadratic:{style:"cubic-bezier(0.25, 0.46, 0.45, 0.94)",fn:function(m){return m*(2-m)}},circular:{style:"cubic-bezier(0.1, 0.57, 0.1, 1)",fn:function(m){return c.sqrt(1-(--m*m))}},back:{style:"cubic-bezier(0.175, 0.885, 0.32, 1.275)",fn:function(n){var m=4;return(n=n-1)*n*((m+1)*n+m)+1}},bounce:{style:"",fn:function(m){if((m/=1)<(1/2.75)){return 7.5625*m*m}else{if(m<(2/2.75)){return 7.5625*(m-=(1.5/2.75))*m+0.75}else{if(m<(2.5/2.75)){return 7.5625*(m-=(2.25/2.75))*m+0.9375}else{return 7.5625*(m-=(2.625/2.75))*m+0.984375}}}}},elastic:{style:"",fn:function(m){var n=0.22,o=0.4;if(m===0){return 0}if(m==1){return 1}return(o*c.pow(2,-10*m)*c.sin((m-n/4)*(2*c.PI)/n)+1)}}});k.tap=function(o,m){var n=a.createEvent("Event");n.initEvent(m,true,true);n.pageX=o.pageX;n.pageY=o.pageY;o.target.dispatchEvent(n)};k.click=function(o){var n=o.target,m;if(n.tagName!="SELECT"&&n.tagName!="INPUT"&&n.tagName!="TEXTAREA"){m=a.createEvent("MouseEvents");m.initMouseEvent("click",true,true,o.view,1,n.screenX,n.screenY,n.clientX,n.clientY,o.ctrlKey,o.altKey,o.shiftKey,o.metaKey,0,null);m._constructed=true;n.dispatchEvent(m)}};return k})();function e(j,g){this.wrapper=typeof j=="string"?a.querySelector(j):j;this.scroller=this.wrapper.children[0];this.scrollerStyle=this.scroller.style;this.options={startX:0,startY:0,scrollY:true,directionLockThreshold:5,momentum:true,bounce:true,bounceTime:600,bounceEasing:"",preventDefault:true,preventDefaultException:{tagName:/^(INPUT|TEXTAREA|BUTTON|SELECT)$/},HWCompositing:true,useTransition:true,useTransform:true};for(var h in g){this.options[h]=g[h]}this.translateZ=this.options.HWCompositing&&b.hasPerspective?" translateZ(0)":"";this.options.useTransition=b.hasTransition&&this.options.useTransition;this.options.useTransform=b.hasTransform&&this.options.useTransform;this.options.eventPassthrough=this.options.eventPassthrough===true?"vertical":this.options.eventPassthrough;this.options.preventDefault=!this.options.eventPassthrough&&this.options.preventDefault;this.options.scrollY=this.options.eventPassthrough=="vertical"?false:this.options.scrollY;this.options.scrollX=this.options.eventPassthrough=="horizontal"?false:this.options.scrollX;this.options.freeScroll=this.options.freeScroll&&!this.options.eventPassthrough;this.options.directionLockThreshold=this.options.eventPassthrough?0:this.options.directionLockThreshold;this.options.bounceEasing=typeof this.options.bounceEasing=="string"?b.ease[this.options.bounceEasing]||b.ease.circular:this.options.bounceEasing;this.options.resizePolling=this.options.resizePolling===undefined?60:this.options.resizePolling;if(this.options.tap===true){this.options.tap="tap"}this.x=0;this.y=0;this.directionX=0;this.directionY=0;this._events={};this._init();this.refresh();this.scrollTo(this.options.startX,this.options.startY);this.enable()}e.prototype={version:"5.0.9",_init:function(){this._initEvents()},destroy:function(){this._initEvents(true);this._execEvent("destroy")},_transitionEnd:function(g){if(g.target!=this.scroller||!this.isInTransition){return}this._transitionTime();if(!this.resetPosition(this.options.bounceTime)){this.isInTransition=false;this._execEvent("scrollEnd")}},_start:function(h){if(b.eventType[h.type]!=1){if(h.button!==0){return}}if(!this.enabled||(this.initiated&&b.eventType[h.type]!==this.initiated)){return}if(this.options.preventDefault&&!b.isBadAndroid&&!b.preventDefaultException(h.target,this.options.preventDefaultException)){h.preventDefault()}var g=h.touches?h.touches[0]:h,i;this.initiated=b.eventType[h.type];this.moved=false;this.distX=0;this.distY=0;this.directionX=0;this.directionY=0;this.directionLocked=0;this._transitionTime();this.startTime=b.getTime();if(this.options.useTransition&&this.isInTransition){this.isInTransition=false;i=this.getComputedPosition();this._translate(c.round(i.x),c.round(i.y));this._execEvent("scrollEnd")}else{if(!this.options.useTransition&&this.isAnimating){this.isAnimating=false;this._execEvent("scrollEnd")}}this.startX=this.x;this.startY=this.y;this.absStartX=this.x;this.absStartY=this.y;this.pointX=g.pageX;this.pointY=g.pageY;this._execEvent("beforeScrollStart")},_move:function(l){if(!this.enabled||b.eventType[l.type]!==this.initiated){return}if(this.options.preventDefault){l.preventDefault()}var n=l.touches?l.touches[0]:l,i=n.pageX-this.pointX,h=n.pageY-this.pointY,m=b.getTime(),g,o,k,j;this.pointX=n.pageX;this.pointY=n.pageY;this.distX+=i;this.distY+=h;k=c.abs(this.distX);j=c.abs(this.distY);if(m-this.endTime>300&&(k<10&&j<10)){return}if(!this.directionLocked&&!this.options.freeScroll){if(k>j+this.options.directionLockThreshold){this.directionLocked="h"}else{if(j>=k+this.options.directionLockThreshold){this.directionLocked="v"}else{this.directionLocked="n"}}}if(this.directionLocked=="h"){if(this.options.eventPassthrough=="vertical"){l.preventDefault()}else{if(this.options.eventPassthrough=="horizontal"){this.initiated=false;return}}h=0}else{if(this.directionLocked=="v"){if(this.options.eventPassthrough=="horizontal"){l.preventDefault()}else{if(this.options.eventPassthrough=="vertical"){this.initiated=false;return}}i=0}}i=this.hasHorizontalScroll?i:0;h=this.hasVerticalScroll?h:0;g=this.x+i;o=this.y+h;if(g>0||g<this.maxScrollX){g=this.options.bounce?this.x+i/3:g>0?0:this.maxScrollX}if(o>0||o<this.maxScrollY){o=this.options.bounce?this.y+h/3:o>0?0:this.maxScrollY}this.directionX=i>0?-1:i<0?1:0;this.directionY=h>0?-1:h<0?1:0;if(!this.moved){this._execEvent("scrollStart")}this.moved=true;this._translate(g,o);if(m-this.startTime>300){this.startTime=m;this.startX=this.x;this.startY=this.y}},_end:function(l){if(!this.enabled||b.eventType[l.type]!==this.initiated){return}if(this.options.preventDefault&&!b.preventDefaultException(l.target,this.options.preventDefaultException)){l.preventDefault()}var n=l.changedTouches?l.changedTouches[0]:l,i,h,k=b.getTime()-this.startTime,g=c.round(this.x),q=c.round(this.y),p=c.abs(g-this.startX),o=c.abs(q-this.startY),j=0,m="";this.isInTransition=0;this.initiated=0;this.endTime=b.getTime();if(this.resetPosition(this.options.bounceTime)){return}this.scrollTo(g,q);if(!this.moved){if(this.options.tap){b.tap(l,this.options.tap)}if(this.options.click){b.click(l)}this._execEvent("scrollCancel");return}if(this._events.flick&&k<200&&p<100&&o<100){this._execEvent("flick");return}if(this.options.momentum&&k<300){i=this.hasHorizontalScroll?b.momentum(this.x,this.startX,k,this.maxScrollX,this.options.bounce?this.wrapperWidth:0):{destination:g,duration:0};h=this.hasVerticalScroll?b.momentum(this.y,this.startY,k,this.maxScrollY,this.options.bounce?this.wrapperHeight:0):{destination:q,duration:0};g=i.destination;q=h.destination;j=c.max(i.duration,h.duration);this.isInTransition=1}if(g!=this.x||q!=this.y){if(g>0||g<this.maxScrollX||q>0||q<this.maxScrollY){m=b.ease.quadratic}this.scrollTo(g,q,j,m);return}this._execEvent("scrollEnd")},_resize:function(){var g=this;clearTimeout(this.resizeTimeout);this.resizeTimeout=setTimeout(function(){g.refresh()},this.options.resizePolling)},resetPosition:function(h){var g=this.x,i=this.y;h=h||0;if(!this.hasHorizontalScroll||this.x>0){g=0}else{if(this.x<this.maxScrollX){g=this.maxScrollX}}if(!this.hasVerticalScroll||this.y>0){i=0}else{if(this.y<this.maxScrollY){i=this.maxScrollY}}if(g==this.x&&i==this.y){return false}this.scrollTo(g,i,h,this.options.bounceEasing);return true},disable:function(){this.enabled=false},enable:function(){this.enabled=true},refresh:function(){var g=this.wrapper.offsetHeight;this.wrapperWidth=this.wrapper.clientWidth;this.wrapperHeight=this.wrapper.clientHeight;this.scrollerWidth=this.scroller.offsetWidth;this.scrollerHeight=this.scroller.offsetHeight;this.maxScrollX=this.wrapperWidth-this.scrollerWidth;this.maxScrollY=this.wrapperHeight-this.scrollerHeight;this.hasHorizontalScroll=this.options.scrollX&&this.maxScrollX<0;this.hasVerticalScroll=this.options.scrollY&&this.maxScrollY<0;if(!this.hasHorizontalScroll){this.maxScrollX=0;this.scrollerWidth=this.wrapperWidth}if(!this.hasVerticalScroll){this.maxScrollY=0;this.scrollerHeight=this.wrapperHeight}this.endTime=0;this.directionX=0;this.directionY=0;this.wrapperOffset=b.offset(this.wrapper);this._execEvent("refresh");this.resetPosition()},on:function(h,g){if(!this._events[h]){this._events[h]=[]}this._events[h].push(g)},_execEvent:function(j){if(!this._events[j]){return}var h=0,g=this._events[j].length;if(!g){return}for(;h<g;h++){this._events[j][h].call(this)}},scrollBy:function(g,j,h,i){g=this.x+g;j=this.y+j;h=h||0;this.scrollTo(g,j,h,i)},scrollTo:function(g,j,h,i){i=i||b.ease.circular;this.isInTransition=this.options.useTransition&&h>0;if(!h||(this.options.useTransition&&i.style)){this._transitionTimingFunction(i.style);this._transitionTime(h);this._translate(g,j)}else{this._animate(g,j,h,i.fn)}},scrollToElement:function(h,i,g,l,k){h=h.nodeType?h:this.scroller.querySelector(h);if(!h){return}var j=b.offset(h);j.left-=this.wrapperOffset.left;j.top-=this.wrapperOffset.top;if(g===true){g=c.round(h.offsetWidth/2-this.wrapper.offsetWidth/2)}if(l===true){l=c.round(h.offsetHeight/2-this.wrapper.offsetHeight/2)}j.left-=g||0;j.top-=l||0;j.left=j.left>0?0:j.left<this.maxScrollX?this.maxScrollX:j.left;j.top=j.top>0?0:j.top<this.maxScrollY?this.maxScrollY:j.top;i=i===undefined||i===null||i==="auto"?c.max(c.abs(this.x-j.left),c.abs(this.y-j.top)):i;this.scrollTo(j.left,j.top,i,k)},_transitionTime:function(g){g=g||0;this.scrollerStyle[b.style.transitionDuration]=g+"ms";if(!g&&b.isBadAndroid){this.scrollerStyle[b.style.transitionDuration]="0.001s"}},_transitionTimingFunction:function(g){this.scrollerStyle[b.style.transitionTimingFunction]=g},_translate:function(g,h){if(this.options.useTransform){this.scrollerStyle[b.style.transform]="translate("+g+"px,"+h+"px)"+this.translateZ}else{g=c.round(g);h=c.round(h);this.scrollerStyle.left=g+"px";this.scrollerStyle.top=h+"px"}this.x=g;this.y=h},_initEvents:function(g){var h=g?b.removeEvent:b.addEvent,i=this.options.bindToWrapper?this.wrapper:d;h(d,"orientationchange",this);h(d,"resize",this);if(this.options.click){h(this.wrapper,"click",this,true)}if(!this.options.disableMouse){h(this.wrapper,"mousedown",this);h(i,"mousemove",this);h(i,"mousecancel",this);h(i,"mouseup",this)}if(b.hasPointer&&!this.options.disablePointer){h(this.wrapper,"MSPointerDown",this);h(i,"MSPointerMove",this);h(i,"MSPointerCancel",this);h(i,"MSPointerUp",this)}if(b.hasTouch&&!this.options.disableTouch){h(this.wrapper,"touchstart",this);h(i,"touchmove",this);h(i,"touchcancel",this);h(i,"touchend",this)}h(this.scroller,"transitionend",this);h(this.scroller,"webkitTransitionEnd",this);h(this.scroller,"oTransitionEnd",this);h(this.scroller,"MSTransitionEnd",this)},getComputedPosition:function(){var h=d.getComputedStyle(this.scroller,null),g,i;if(this.options.useTransform){h=h[b.style.transform].split(")")[0].split(", ");g=+(h[12]||h[4]);i=+(h[13]||h[5])}else{g=+h.left.replace(/[^-\d.]/g,"");i=+h.top.replace(/[^-\d.]/g,"")}return{x:g,y:i}},_animate:function(p,o,j,g){var m=this,l=this.x,k=this.y,h=b.getTime(),n=h+j;function i(){var q=b.getTime(),s,r,t;if(q>=n){m.isAnimating=false;m._translate(p,o);if(!m.resetPosition(m.options.bounceTime)){m._execEvent("scrollEnd")}return}q=(q-h)/j;t=g(q);s=(p-l)*t+l;r=(o-k)*t+k;m._translate(s,r);if(m.isAnimating){f(i)}}this.isAnimating=true;i()},handleEvent:function(g){switch(g.type){case"touchstart":case"MSPointerDown":case"mousedown":this._start(g);break;case"touchmove":case"MSPointerMove":case"mousemove":this._move(g);break;case"touchend":case"MSPointerUp":case"mouseup":case"touchcancel":case"MSPointerCancel":case"mousecancel":this._end(g);break;case"orientationchange":case"resize":this._resize();break;case"transitionend":case"webkitTransitionEnd":case"oTransitionEnd":case"MSTransitionEnd":this._transitionEnd(g);break;case"wheel":case"DOMMouseScroll":case"mousewheel":this._wheel(g);break;case"keydown":this._key(g);break;case"click":if(!g._constructed){g.preventDefault();g.stopPropagation()}break}}};e.utils=b;if(typeof module!="undefined"&&module.exports){module.exports=e}else{d.IScroll=e}})(window,document,Math);
LeaYeh/cdnjs
ajax/libs/iScroll/5.0.9/iscroll-lite.min.js
JavaScript
mit
14,446
/* YUI 3.15.0 (build 834026e) Copyright 2014 Yahoo! Inc. All rights reserved. Licensed under the BSD License. http://yuilibrary.com/license/ */ YUI.add('datatype-number-format', function (Y, NAME) { /** * The Number Utility provides type-conversion and string-formatting * convenience methods for Numbers. * * @module datatype-number * @main datatype-number */ /** * Format number submodule. * * @module datatype-number * @submodule datatype-number-format */ /** * Number provides a set of utility functions to operate against Number objects. * * @class Number * @static */ var LANG = Y.Lang; Y.mix(Y.namespace("Number"), { /** * Takes a Number and formats to string for display to user. * * @method format * @param data {Number} Number. * @param config {Object} (Optional) Optional configuration values: * <dl> * <dt>prefix {String}</dd> * <dd>String prepended before each number, like a currency designator "$"</dd> * <dt>decimalPlaces {Number}</dd> * <dd>Number of decimal places to round. Must be a number 0 to 20.</dd> * <dt>decimalSeparator {String}</dd> * <dd>Decimal separator</dd> * <dt>thousandsSeparator {String}</dd> * <dd>Thousands separator</dd> * <dt>suffix {String}</dd> * <dd>String appended after each number, like " items" (note the space)</dd> * </dl> * @return {String} Formatted number for display. Note, the following values * return as "": null, undefined, NaN, "". */ format: function(data, config) { if(LANG.isNumber(data)) { config = config || {}; var isNeg = (data < 0), output = data + "", decPlaces = config.decimalPlaces, decSep = config.decimalSeparator || ".", thouSep = config.thousandsSeparator, decIndex, newOutput, count, i; // Decimal precision if(LANG.isNumber(decPlaces) && (decPlaces >= 0) && (decPlaces <= 20)) { // Round to the correct decimal place output = data.toFixed(decPlaces); } // Decimal separator if(decSep !== "."){ output = output.replace(".", decSep); } // Add the thousands separator if(thouSep) { // Find the dot or where it would be decIndex = output.lastIndexOf(decSep); decIndex = (decIndex > -1) ? decIndex : output.length; // Start with the dot and everything to the right newOutput = output.substring(decIndex); // Working left, every third time add a separator, every time add a digit for (count = 0, i=decIndex; i>0; i--) { if ((count%3 === 0) && (i !== decIndex) && (!isNeg || (i > 1))) { newOutput = thouSep + newOutput; } newOutput = output.charAt(i-1) + newOutput; count++; } output = newOutput; } // Prepend prefix output = (config.prefix) ? config.prefix + output : output; // Append suffix output = (config.suffix) ? output + config.suffix : output; return output; } // Not a Number, just return as string else { return (LANG.isValue(data) && data.toString) ? data.toString() : ""; } } }); Y.namespace("DataType"); Y.DataType.Number = Y.Number; }, '3.15.0');
pc035860/cdnjs
ajax/libs/yui/3.15.0/datatype-number-format/datatype-number-format.js
JavaScript
mit
3,634
"use strict";angular.module("azure-mobile-service.module",[]).service("Azureservice",function(e){var r="https://<AZURE_APP_NAME>.azure-mobile.net/",n="<AZURE_APP_API_KEY>",o=["google","twitter","facebook","microsoftaccount","aad"],t=WindowsAzure.MobileServiceClient,i=new t(r,n),u=function(){sessionStorage.loggedInUser&&(i.currentUser=JSON.parse(sessionStorage.loggedInUser))};u();var s=function(e,r){return"function"==typeof r?i.withFilter(r).getTable(e):i.getTable(e)},l=function(e){return"undefined"==typeof e||"object"!=typeof e&&"function"!=typeof e},c=function(e){return a(e)||"object"!=typeof e},a=function(e){return null===e||"undefined"==typeof e},f=function(e){return!a(e)},d=function(r){var n=e.defer();return r.done(function(e){n.resolve(e)},function(e){n.reject(e)}),n.promise};return{query:function(e,r,n){var o=null;if(a(e))return console.error("Azureservice.query: You must specify a table name"),null;if(angular.isDefined(r)&&angular.isObject(r)){if(l(r.criteria)&&(r.criteria={}),o=s(e,n).where(r.criteria,r.params),f(r.take)&&angular.isNumber(r.take)&&(o=o.take(r.take)),f(r.skip)&&angular.isNumber(r.take)&&(o=o.skip(r.skip)),angular.isDefined(r.orderBy)&&angular.isArray(r.orderBy))for(var t=r.orderBy,i=0;i<t.length;i++){var u=t[i].column,c=t[i].direction;angular.isDefined(u)&&(angular.isDefined(c)&&"desc"===c.toLowerCase()?o=o.orderByDescending(u):angular.isDefined(u)&&(o=o.orderBy(u)))}angular.isDefined(r.columns)&&angular.isArray(r.columns)&&(o=o.select(r.columns.join()))}else o=s(e,n).where({});return d(o.includeTotalCount().read())},getById:function(e,r,n){return a(e)?(console.error("Azureservice.getById: You must specify a table name"),null):a(r)?(console.error("Azureservice.getById: You must specify the id"),null):d(s(e,n).lookup(r))},getAll:function(e,r){return this.query(e,null,r)},insert:function(e,r,n){return a(e)?(console.error("Azureservice.insert: You must specify a table name"),null):c(r)?(console.error("Azureservice.insert: You must specify the insert object"),null):d(s(e,n).insert(r))},update:function(e,r,n){return a(e)?(console.error("Azureservice.update: You must specify a table name"),null):c(r)?(console.error("Azureservice.update: You must specify the insert object"),null):d(s(e,n).update(r))},del:function(e,r,n){return a(e)?(console.error("Azureservice.del: You must specify a table name"),null):c(r)?(console.error("Azureservice.del: You must specify the insert object"),null):d(s(e,n).del(r))},login:function(e){if(!angular.isDefined(e)||-1===o.indexOf(e))throw new Error("Azureservice.login Invalid or no oauth provider listed.");var r=i.login(e).then(function(){sessionStorage.loggedInUser=JSON.stringify(i.currentUser)});return d(r)},logout:function(){sessionStorage.loggedInUser=null,i.logout()},isLoggedIn:function(){return f(i.currentUser)&&f(sessionStorage.loggedInUser)},invokeApi:function(r,n){var o=e.defer(),t=["get","post","put","delete"];if(a(r))return console.error("Azureservice.invokeApi No custom api name specified"),null;if(c(n))n={method:"get"};else if(a(n.method))n.method="get";else if(-1===t.indexOf(n.method.toLowerCase()))return console.error("Azureservice.invokeApi Invalid method type"),null;return i.invokeApi(r,n).done(function(e){o.resolve(e.result)},function(e){o.reject(e)}),o.promise}}});
wmkcc/cdnjs
ajax/libs/angular-azure-mobile-service/1.0.5/angular-azure-mobile-service.min.js
JavaScript
mit
3,288
webshims.register("dom-extend",function(a,b,c,d,e){"use strict";var f=!("hrefNormalized"in a.support)||a.support.hrefNormalized,g=!("getSetAttribute"in a.support)||a.support.getSetAttribute,h=Object.prototype.hasOwnProperty;if(b.assumeARIA=g||Modernizr.canvas||Modernizr.video||Modernizr.boxsizing,("text"==a('<input type="email" />').attr("type")||""===a("<form />").attr("novalidate")||"required"in a("<input />")[0].attributes)&&b.error("IE browser modes are busted in IE10+. Please test your HTML/CSS/JS with a real IE version or at least IETester or similiar tools"),"debug"in b&&b.error('Use webshims.setOptions("debug", true||false||"noCombo"); to debug flag'),!b.cfg.no$Switch){var i=function(){if(!c.jQuery||c.$&&c.jQuery!=c.$||c.jQuery.webshims||(b.error("jQuery was included more than once. Make sure to include it only once or try the $.noConflict(extreme) feature! Webshims and other Plugins might not work properly. Or set webshims.cfg.no$Switch to 'true'."),c.$&&(c.$=b.$),c.jQuery=b.$),b.M!=Modernizr){b.error("Modernizr was included more than once. Make sure to include it only once! Webshims and other scripts might not work properly.");for(var a in Modernizr)a in b.M||(b.M[a]=Modernizr[a]);Modernizr=b.M}};i(),setTimeout(i,90),b.ready("DOM",i),a(i),b.ready("WINDOWLOAD",i)}var j=(b.modules,/\s*,\s*/),k={},l={},m={},n={},o={},p={},q=a.fn.val,r=function(b,c,d,e,f){return f?q.call(a(b)):q.call(a(b),d)};a.widget||!function(){var b=a.cleanData;a.cleanData=function(c){if(!a.widget)for(var d,e=0;null!=(d=c[e]);e++)try{a(d).triggerHandler("remove")}catch(f){}b(c)}}(),a.fn.val=function(b){var c=this[0];if(arguments.length&&null==b&&(b=""),!arguments.length)return c&&1===c.nodeType?a.prop(c,"value",b,"val",!0):q.call(this);if(a.isArray(b))return q.apply(this,arguments);var d=a.isFunction(b);return this.each(function(f){if(c=this,1===c.nodeType)if(d){var g=b.call(c,f,a.prop(c,"value",e,"val",!0));null==g&&(g=""),a.prop(c,"value",g,"val")}else a.prop(c,"value",b,"val")})},a.fn.onTrigger=function(a,b){return this.on(a,b).each(b)},a.fn.onWSOff=function(b,c,e,f){return f||(f=d),a(f)[e?"onTrigger":"on"](b,c),this.on("remove",function(d){d.originalEvent||a(f).off(b,c)}),this};var s="_webshimsLib"+Math.round(1e3*Math.random()),t=function(b,c,d){if(b=b.jquery?b[0]:b,!b)return d||{};var f=a.data(b,s);return d!==e&&(f||(f=a.data(b,s,{})),c&&(f[c]=d)),c?f&&f[c]:f};[{name:"getNativeElement",prop:"nativeElement"},{name:"getShadowElement",prop:"shadowElement"},{name:"getShadowFocusElement",prop:"shadowFocusElement"}].forEach(function(b){a.fn[b.name]=function(){var c=[];return this.each(function(){var d=t(this,"shadowData"),e=d&&d[b.prop]||this;-1==a.inArray(e,c)&&c.push(e)}),this.pushStack(c)}}),b.cfg.extendNative||b.cfg.noTriggerOverride||!function(b){a.event.trigger=function(c,d,e,f){if(!m[c]||f||!e||1!==e.nodeType)return b.apply(this,arguments);var g,i,j,k=e[c],l=a.prop(e,c),n=l&&k!=l;return n&&(j="__ws"+c,i=c in e&&h.call(e,c),e[c]=l,e[j]=k),g=b.apply(this,arguments),n&&(i?e[c]=k:delete e[c],delete e[j]),g}}(a.event.trigger),["removeAttr","prop","attr"].forEach(function(c){k[c]=a[c],a[c]=function(b,d,f,g,h){var i="val"==g,j=i?r:k[c];if(!b||!l[d]||1!==b.nodeType||!i&&g&&"attr"==c&&a.attrFn[d])return j(b,d,f,g,h);var m,o,q,s=(b.nodeName||"").toLowerCase(),t=n[s],u="attr"!=c||f!==!1&&null!==f?c:"removeAttr";if(t||(t=n["*"]),t&&(t=t[d]),t&&(m=t[u]),m){if("value"==d&&(o=m.isVal,m.isVal=i),"removeAttr"===u)return m.value.call(b);if(f===e)return m.get?m.get.call(b):m.value;m.set&&("attr"==c&&f===!0&&(f=d),q=m.set.call(b,f)),"value"==d&&(m.isVal=o)}else q=j(b,d,f,g,h);if((f!==e||"removeAttr"===u)&&p[s]&&p[s][d]){var v;v="removeAttr"==u?!1:"prop"==u?!!f:!0,p[s][d].forEach(function(a){(!a.only||(a.only="prop"&&"prop"==c)||"attr"==a.only&&"prop"!=c)&&a.call(b,f,v,i?"val":u,c)})}return q},o[c]=function(a,d,f){n[a]||(n[a]={}),n[a][d]||(n[a][d]={});var g=n[a][d][c],h=function(a,b,e){var g;return b&&b[a]?b[a]:e&&e[a]?e[a]:"prop"==c&&"value"==d?function(a){var b=this;return f.isVal?r(b,d,a,!1,0===arguments.length):k[c](b,d,a)}:"prop"==c&&"value"==a&&f.value.apply?(g="__ws"+d,m[d]=!0,function(){var a=this[g]||k[c](this,d);return a&&a.apply&&(a=a.apply(this,arguments)),a}):function(a){return k[c](this,d,a)}};n[a][d][c]=f,f.value===e&&(f.set||(f.set=f.writeable?h("set",f,g):b.cfg.useStrict&&"prop"==d?function(){throw d+" is readonly on "+a}:function(){b.info(d+" is readonly on "+a)}),f.get||(f.get=h("get",f,g))),["value","get","set"].forEach(function(a){f[a]&&(f["_sup"+a]=h(a,g))})}});var u=function(){var a=b.getPrototypeOf(d.createElement("foobar")),c=Modernizr.advancedObjectProperties&&Modernizr.objectAccessor;return function(e,f,g){var i,j;if(!(c&&(i=d.createElement(e))&&(j=b.getPrototypeOf(i))&&a!==j)||i[f]&&h.call(i,f))g._supvalue=function(){var a=t(this,"propValue");return a&&a[f]&&a[f].apply?a[f].apply(this,arguments):a&&a[f]},v.extendValue(e,f,g.value);else{var k=i[f];g._supvalue=function(){return k&&k.apply?k.apply(this,arguments):k},j[f]=g.value}g.value._supvalue=g._supvalue}}(),v=function(){var c={};b.addReady(function(d,e){var f={},g=function(b){f[b]||(f[b]=a(d.getElementsByTagName(b)),e[0]&&a.nodeName(e[0],b)&&(f[b]=f[b].add(e)))};a.each(c,function(a,c){return g(a),c&&c.forEach?(c.forEach(function(b){f[a].each(b)}),void 0):(b.warn("Error: with "+a+"-property. methods: "+c),void 0)}),f=null});var e,f=a([]),g=function(b,f){c[b]?c[b].push(f):c[b]=[f],a.isDOMReady&&(e||a(d.getElementsByTagName(b))).each(f)};return{createTmpCache:function(b){return a.isDOMReady&&(e=e||a(d.getElementsByTagName(b))),e||f},flushTmpCache:function(){e=null},content:function(b,c){g(b,function(){var b=a.attr(this,c);null!=b&&a.attr(this,c,b)})},createElement:function(a,b){g(a,b)},extendValue:function(b,c,d){g(b,function(){a(this).each(function(){var a=t(this,"propValue",{});a[c]=this[c],this[c]=d})})}}}(),w=function(a,b){a.defaultValue===e&&(a.defaultValue=""),a.removeAttr||(a.removeAttr={value:function(){a[b||"prop"].set.call(this,a.defaultValue),a.removeAttr._supvalue.call(this)}}),a.attr||(a.attr={})};a.extend(b,{getID:function(){var b=(new Date).getTime();return function(c){c=a(c);var d=c.prop("id");return d||(b++,d="ID-"+b,c.eq(0).prop("id",d)),d}}(),implement:function(a,c){var d=t(a,"implemented")||t(a,"implemented",{});return d[c]?(b.warn(c+" already implemented for element #"+a.id),!1):(d[c]=!0,!0)},extendUNDEFProp:function(b,c){a.each(c,function(a,c){a in b||(b[a]=c)})},getOptions:function(){var c=/\-([a-z])/g,d={},e={},f=function(a,b){return b.toLowerCase()},g=function(a,b){return b.toUpperCase()};return function(h,i,j,k){e[i]?i=e[i]:(e[i]=i.replace(c,g),i=e[i]);var l,m=t(h,"cfg"+i),n={};if(m)return m;if(m=a(h).data(),m&&"string"==typeof m[i]){if(k)return t(h,"cfg"+i,m[i]);b.error("data-"+i+" attribute has to be a valid JSON, was: "+m[i])}j?Array.isArray(j)?j.unshift(!0,{}):j=[!0,{},j]:j=[!0,{}],m&&"object"==typeof m[i]&&j.push(m[i]),d[i]||(d[i]=new RegExp("^"+i+"([A-Z])"));for(l in m)d[i].test(l)&&(n[l.replace(d[i],f)]=m[l]);return j.push(n),t(h,"cfg"+i,a.extend.apply(a,j))}}(),createPropDefault:w,data:t,moveToFirstEvent:function(b,c,d){var e,f=(a._data(b,"events")||{})[c];f&&f.length>1&&(e=f.pop(),d||(d="bind"),"bind"==d&&f.delegateCount?f.splice(f.delegateCount,0,e):f.unshift(e)),b=null},addShadowDom:function(){var e,f,g,h=a(c),i={init:!1,runs:0,test:function(){var a=i.getHeight(),b=i.getWidth();a!=i.height||b!=i.width?(i.height=a,i.width=b,i.handler({type:"docresize"}),i.runs++,i.runs<9&&setTimeout(i.test,90)):i.runs=0},handler:function(){var b=function(){a(d).triggerHandler("updateshadowdom")};return function(a){clearTimeout(e),e=setTimeout(function(){if("resize"==a.type){var d=h.width(),e=h.width();if(e==f&&d==g)return;f=e,g=d,i.height=i.getHeight(),i.width=i.getWidth()}c.requestAnimationFrame?requestAnimationFrame(b):setTimeout(b,0)},"resize"!=a.type||c.requestAnimationFrame?9:50)}}(),_create:function(){a.each({Height:"getHeight",Width:"getWidth"},function(a,b){var c=d.body,e=d.documentElement;i[b]=function(){return Math.max(c["scroll"+a],e["scroll"+a],c["offset"+a],e["offset"+a],e["client"+a])}})},start:function(){!this.init&&d.body&&(this.init=!0,this._create(),this.height=i.getHeight(),this.width=i.getWidth(),setInterval(this.test,600),a(this.test),b.ready("WINDOWLOAD",this.test),a(d).on("updatelayout.webshim pageinit popupafteropen panelbeforeopen tabsactivate collapsibleexpand shown.bs.modal shown.bs.collapse slid.bs.carousel",this.handler),a(c).on("resize",this.handler),function(){var b,c=a.fn.animate;a.fn.animate=function(){return clearTimeout(b),b=setTimeout(function(){i.test()},99),c.apply(this,arguments)}}())}};return b.docObserve=function(){b.ready("DOM",function(){i.start(),null==a.support.boxSizing&&a(function(){a.support.boxSizing&&i.handler({type:"boxsizing"})})})},function(c,d,e){if(c&&d){e=e||{},c.jquery&&(c=c[0]),d.jquery&&(d=d[0]);var f=a.data(c,s)||a.data(c,s,{}),g=a.data(d,s)||a.data(d,s,{}),h={};e.shadowFocusElement?e.shadowFocusElement&&(e.shadowFocusElement.jquery&&(e.shadowFocusElement=e.shadowFocusElement[0]),h=a.data(e.shadowFocusElement,s)||a.data(e.shadowFocusElement,s,h)):e.shadowFocusElement=d,a(c).on("remove",function(b){b.originalEvent||setTimeout(function(){a(d).remove()},4)}),f.hasShadow=d,h.nativeElement=g.nativeElement=c,h.shadowData=g.shadowData=f.shadowData={nativeElement:c,shadowElement:d,shadowFocusElement:e.shadowFocusElement},e.shadowChilds&&e.shadowChilds.each(function(){t(this,"shadowData",g.shadowData)}),e.data&&(h.shadowData.data=g.shadowData.data=f.shadowData.data=e.data),e=null}b.docObserve()}}(),propTypes:{standard:function(a){w(a),a.prop||(a.prop={set:function(b){a.attr.set.call(this,""+b)},get:function(){return a.attr.get.call(this)||a.defaultValue}})},"boolean":function(a){w(a),a.prop||(a.prop={set:function(b){b?a.attr.set.call(this,""):a.removeAttr.value.call(this)},get:function(){return null!=a.attr.get.call(this)}})},src:function(){var b=d.createElement("a");return b.style.display="none",function(c,d){w(c),c.prop||(c.prop={set:function(a){c.attr.set.call(this,a)},get:function(){var c,e=this.getAttribute(d);if(null==e)return"";if(b.setAttribute("href",e+""),!f){try{a(b).insertAfter(this),c=b.getAttribute("href",4)}catch(g){c=b.getAttribute("href",4)}a(b).detach()}return c||b.href}})}}(),enumarated:function(a){w(a),a.prop||(a.prop={set:function(b){a.attr.set.call(this,b)},get:function(){var b=(a.attr.get.call(this)||"").toLowerCase();return b&&-1!=a.limitedTo.indexOf(b)||(b=a.defaultValue),b}})}},reflectProperties:function(c,d){"string"==typeof d&&(d=d.split(j)),d.forEach(function(d){b.defineNodeNamesProperty(c,d,{prop:{set:function(b){a.attr(this,d,b)},get:function(){return a.attr(this,d)||""}}})})},defineNodeNameProperty:function(c,d,e){return l[d]=!0,e.reflect&&(e.propType&&!b.propTypes[e.propType]?b.error("could not finde propType "+e.propType):b.propTypes[e.propType||"standard"](e,d)),["prop","attr","removeAttr"].forEach(function(f){var g=e[f];g&&(g="prop"===f?a.extend({writeable:!0},g):a.extend({},g,{writeable:!0}),o[f](c,d,g),"*"!=c&&b.cfg.extendNative&&"prop"==f&&g.value&&a.isFunction(g.value)&&u(c,d,g),e[f]=g)}),e.initAttr&&v.content(c,d),e},defineNodeNameProperties:function(a,c,d,e){for(var f in c)!e&&c[f].initAttr&&v.createTmpCache(a),d&&(c[f][d]||(c[f][d]={},["value","set","get"].forEach(function(a){a in c[f]&&(c[f][d][a]=c[f][a],delete c[f][a])}))),c[f]=b.defineNodeNameProperty(a,f,c[f]);return e||v.flushTmpCache(),c},createElement:function(c,d,e){var f;return a.isFunction(d)&&(d={after:d}),v.createTmpCache(c),d.before&&v.createElement(c,d.before),e&&(f=b.defineNodeNameProperties(c,e,!1,!0)),d.after&&v.createElement(c,d.after),v.flushTmpCache(),f},onNodeNamesPropertyModify:function(b,c,d,e){"string"==typeof b&&(b=b.split(j)),a.isFunction(d)&&(d={set:d}),b.forEach(function(a){p[a]||(p[a]={}),"string"==typeof c&&(c=c.split(j)),d.initAttr&&v.createTmpCache(a),c.forEach(function(b){p[a][b]||(p[a][b]=[],l[b]=!0),d.set&&(e&&(d.set.only=e),p[a][b].push(d.set)),d.initAttr&&v.content(a,b)}),v.flushTmpCache()})},defineNodeNamesBooleanProperty:function(c,d,f){f||(f={}),a.isFunction(f)&&(f.set=f),b.defineNodeNamesProperty(c,d,{attr:{set:function(a){f.useContentAttribute?b.contentAttr(this,d,a):this.setAttribute(d,a),f.set&&f.set.call(this,!0)},get:function(){var a=f.useContentAttribute?b.contentAttr(this,d):this.getAttribute(d);return null==a?e:d}},removeAttr:{value:function(){this.removeAttribute(d),f.set&&f.set.call(this,!1)}},reflect:!0,propType:"boolean",initAttr:f.initAttr||!1})},contentAttr:function(a,b,c){if(a.nodeName){var d;return c===e?(d=a.attributes[b]||{},c=d.specified?d.value:null,null==c?e:c):("boolean"==typeof c?c?a.setAttribute(b,b):a.removeAttribute(b):a.setAttribute(b,c),void 0)}},activeLang:function(){var c=[],d=[],e={},f=function(d,f,h){f._isLoading=!0,e[d]?e[d].push(f):(e[d]=[f],b.loader.loadScript(d,function(){h==c.join()&&a.each(e[d],function(a,b){g(b)}),delete e[d]}))},g=function(b){var d=b.__active,e=function(a,d){return b._isLoading=!1,b[d]||-1!=b.availableLangs.indexOf(d)?(b[d]?(b.__active=b[d],b.__activeName=d):f(b.langSrc+d,b,c.join()),!1):void 0};a.each(c,e),b.__active||(b.__active=b[""],b.__activeName=""),d!=b.__active&&a(b).trigger("change")};return function(a){var b;if("string"==typeof a)c[0]!=a&&(c=[a],b=c[0].split("-")[0],b&&b!=a&&c.push(b),d.forEach(g));else if("object"==typeof a)return a.__active||(d.push(a),g(a)),a.__active;return c[0]}}()}),a.each({defineNodeNamesProperty:"defineNodeNameProperty",defineNodeNamesProperties:"defineNodeNameProperties",createElements:"createElement"},function(a,c){b[a]=function(a,d,e,f){"string"==typeof a&&(a=a.split(j));var g={};return a.forEach(function(a){g[a]=b[c](a,d,e,f)}),g}}),b.isReady("webshimLocalization",!0),function(){if(!("content"in d.createElement("template")||(a(function(){var c=a("main").attr({role:"main"});c.length>1?b.error("only one main element allowed in document"):c.is("article *, section *")&&b.error("main not allowed inside of article/section elements")}),"hidden"in d.createElement("a")))){b.defineNodeNamesBooleanProperty(["*"],"hidden");var c={article:"article",aside:"complementary",section:"region",nav:"navigation",address:"contentinfo"},e=function(a,b){var c=a.getAttribute("role");c||a.setAttribute("role",b)};a.webshims.addReady(function(b,f){if(a.each(c,function(c,d){for(var g=a(c,b).add(f.filter(c)),h=0,i=g.length;i>h;h++)e(g[h],d)}),b===d){var g=d.getElementsByTagName("header")[0],h=d.getElementsByTagName("footer"),i=h.length;if(g&&!a(g).closest("section, article")[0]&&e(g,"banner"),!i)return;var j=h[i-1];a(j).closest("section, article")[0]||e(j,"contentinfo")}})}}()}),webshims.register("form-core",function(a,b,c,d,e,f){"use strict";b.capturingEventPrevented=function(b){if(!b._isPolyfilled){var c=b.isDefaultPrevented,d=b.preventDefault;b.preventDefault=function(){return clearTimeout(a.data(b.target,b.type+"DefaultPrevented")),a.data(b.target,b.type+"DefaultPrevented",setTimeout(function(){a.removeData(b.target,b.type+"DefaultPrevented")},30)),d.apply(this,arguments)},b.isDefaultPrevented=function(){return!(!c.apply(this,arguments)&&!a.data(b.target,b.type+"DefaultPrevented"))},b._isPolyfilled=!0}},Modernizr.formvalidation&&!b.bugs.bustedValidity&&b.capturingEvents(["invalid"],!0);var g=function(b){return(a.prop(b,"validity")||{valid:1}).valid},h=function(){var c=["form-validation"];f.lazyCustomMessages&&(f.customMessages=!0,c.push("form-message")),f.customDatalist&&(f.fD=!0,c.push("form-datalist")),f.addValidators&&c.push("form-validators"),b.reTest(c),a(d).off(".lazyloadvalidation")},i=/^(?:form|fieldset)$/i,j=function(b){var c=!1;return a(b).jProp("elements").each(function(){return!i.test(b.nodeName||"")&&(c=a(this).is(":invalid"))?!1:void 0}),c},k=function(){var c,e,f=a.expr[":"];if(a.extend(f,{"valid-element":function(b){return i.test(b.nodeName||"")?!j(b):!(!a.prop(b,"willValidate")||!g(b))},"invalid-element":function(b){return i.test(b.nodeName||"")?j(b):!(!a.prop(b,"willValidate")||g(b))},"required-element":function(b){return!(!a.prop(b,"willValidate")||!a.prop(b,"required"))},"user-error":function(b){return a.prop(b,"willValidate")&&a(b).hasClass("user-error")},"optional-element":function(b){return!(!a.prop(b,"willValidate")||a.prop(b,"required")!==!1)}}),["valid","invalid","required","optional"].forEach(function(b){f[b]=a.expr[":"][b+"-element"]}),Modernizr.fieldsetdisabled&&!a('<fieldset disabled=""><input /><input /></fieldset>').find(":disabled").filter(":disabled").is(":disabled")&&(c=a.find.matches,e={":disabled":1,":enabled":1},a.find.matches=function(a,b){return e[a]?c.call(this,"*"+a,b):c.apply(this,arguments)},a.extend(f,{enabled:function(b){return b.disabled===!1&&!a(b).is("fieldset[disabled] *")},disabled:function(b){return b.disabled===!0||"disabled"in b&&a(b).is("fieldset[disabled] *")}})),"unknown"==typeof d.activeElement){var h=f.focus;f.focus=function(){try{return h.apply(this,arguments)}catch(a){b.error(a)}return!1}}};a.expr.filters?k():b.ready("sizzle",k),b.triggerInlineForm=function(b,c){a(b).trigger(c)};var l=function(a,c,d){h(),b.ready("form-validation",function(){a[c].apply(a,d)})},m="transitionDelay"in d.documentElement.style?"":" no-transition",n=b.cfg.wspopover;n.position||n.position===!1||(n.position={at:"left bottom",my:"left top",collision:"fit flip"}),b.wsPopover={id:0,_create:function(){this.options=a.extend(!0,{},n,this.options),this.id=b.wsPopover.id++,this.eventns=".wsoverlay"+this.id,this.timers={},this.element=a('<div class="ws-popover'+m+'" tabindex="-1"><div class="ws-po-outerbox"><div class="ws-po-arrow"><div class="ws-po-arrowbox" /></div><div class="ws-po-box" /></div></div>'),this.contentElement=a(".ws-po-box",this.element),this.lastElement=a([]),this.bindElement(),this.element.data("wspopover",this)},options:{},content:function(a){this.contentElement.html(a)},bindElement:function(){var a=this,b=function(){a.stopBlur=!1};this.preventBlur=function(){a.stopBlur=!0,clearTimeout(a.timers.stopBlur),a.timers.stopBlur=setTimeout(b,9)},this.element.on({mousedown:this.preventBlur})},show:function(){l(this,"show",arguments)}},b.validityAlert={showFor:function(){l(this,"showFor",arguments)}},b.getContentValidationMessage=function(c,d,e){b.errorbox&&b.errorbox.initIvalContentMessage&&b.errorbox.initIvalContentMessage(c);var f=(b.getOptions&&b.errorbox?b.getOptions(c,"errormessage",!1,!0):a(c).data("errormessage"))||c.getAttribute("x-moz-errormessage")||"";return e&&f[e]?f=f[e]:f&&(d=d||a.prop(c,"validity")||{valid:1},d.valid&&(f="")),"object"==typeof f&&(d=d||a.prop(c,"validity")||{valid:1},d.valid||(a.each(d,function(a,b){return b&&"valid"!=a&&f[a]?(f=f[a],!1):void 0}),"object"==typeof f&&(d.typeMismatch&&f.badInput&&(f=f.badInput),d.badInput&&f.typeMismatch&&(f=f.typeMismatch)))),"object"==typeof f&&(f=f.defaultMessage),f||""},a.fn.getErrorMessage=function(c){var d="",e=this[0];return e&&(d=b.getContentValidationMessage(e,!1,c)||a.prop(e,"customValidationMessage")||a.prop(e,"validationMessage")),d},a(d).on("focusin.lazyloadvalidation",function(a){"form"in a.target&&h()}),b.ready("WINDOWLOAD",h)}),webshims.register("form-message",function(a,b,c,d,e,f){"use strict";f.lazyCustomMessages&&(f.customMessages=!0);var g=b.validityMessages,h=f.customMessages?["customValidationMessage"]:[];g.en=a.extend(!0,{typeMismatch:{defaultMessage:"Please enter a valid value.",email:"Please enter an email address.",url:"Please enter a URL."},badInput:{defaultMessage:"Please enter a valid value.",number:"Please enter a number.",date:"Please enter a date.",time:"Please enter a time.",range:"Invalid input.",month:"Please enter a valid value.","datetime-local":"Please enter a datetime."},rangeUnderflow:{defaultMessage:"Value must be greater than or equal to {%min}."},rangeOverflow:{defaultMessage:"Value must be less than or equal to {%max}."},stepMismatch:"Invalid input.",tooLong:"Please enter at most {%maxlength} character(s). You entered {%valueLen}.",tooShort:"Please enter at least {%minlength} character(s). You entered {%valueLen}.",patternMismatch:"Invalid input. {%title}",valueMissing:{defaultMessage:"Please fill out this field.",checkbox:"Please check this box if you want to proceed."}},g.en||g["en-US"]||{}),"object"==typeof g.en.valueMissing&&["select","radio"].forEach(function(a){g.en.valueMissing[a]=g.en.valueMissing[a]||"Please select an option."}),"object"==typeof g.en.rangeUnderflow&&["date","time","datetime-local","month"].forEach(function(a){g.en.rangeUnderflow[a]=g.en.rangeUnderflow[a]||"Value must be at or after {%min}."}),"object"==typeof g.en.rangeOverflow&&["date","time","datetime-local","month"].forEach(function(a){g.en.rangeOverflow[a]=g.en.rangeOverflow[a]||"Value must be at or before {%max}."}),g["en-US"]||(g["en-US"]=a.extend(!0,{},g.en)),g["en-GB"]||(g["en-GB"]=a.extend(!0,{},g.en)),g["en-AU"]||(g["en-AU"]=a.extend(!0,{},g.en)),g[""]=g[""]||g["en-US"],g.de=a.extend(!0,{typeMismatch:{defaultMessage:"{%value} ist in diesem Feld nicht zul\xe4ssig.",email:"{%value} ist keine g\xfcltige E-Mail-Adresse.",url:"{%value} ist kein(e) g\xfcltige(r) Webadresse/Pfad."},badInput:{defaultMessage:"Geben Sie einen zul\xe4ssigen Wert ein.",number:"Geben Sie eine Nummer ein.",date:"Geben Sie ein Datum ein.",time:"Geben Sie eine Uhrzeit ein.",month:"Geben Sie einen Monat mit Jahr ein.",range:"Geben Sie eine Nummer.","datetime-local":"Geben Sie ein Datum mit Uhrzeit ein."},rangeUnderflow:{defaultMessage:"{%value} ist zu niedrig. {%min} ist der unterste Wert, den Sie benutzen k\xf6nnen."},rangeOverflow:{defaultMessage:"{%value} ist zu hoch. {%max} ist der oberste Wert, den Sie benutzen k\xf6nnen."},stepMismatch:"Der Wert {%value} ist in diesem Feld nicht zul\xe4ssig. Hier sind nur bestimmte Werte zul\xe4ssig. {%title}",tooLong:"Der eingegebene Text ist zu lang! Sie haben {%valueLen} Zeichen eingegeben, dabei sind {%maxlength} das Maximum.",tooShort:"Der eingegebene Text ist zu kurz! Sie haben {%valueLen} Zeichen eingegeben, dabei sind {%minlength} das Minimum.",patternMismatch:"{%value} hat f\xfcr dieses Eingabefeld ein falsches Format. {%title}",valueMissing:{defaultMessage:"Bitte geben Sie einen Wert ein.",checkbox:"Bitte aktivieren Sie das K\xe4stchen."}},g.de||{}),"object"==typeof g.de.valueMissing&&["select","radio"].forEach(function(a){g.de.valueMissing[a]=g.de.valueMissing[a]||"Bitte w\xe4hlen Sie eine Option aus."}),"object"==typeof g.de.rangeUnderflow&&["date","time","datetime-local","month"].forEach(function(a){g.de.rangeUnderflow[a]=g.de.rangeUnderflow[a]||"{%value} ist zu fr\xfch. {%min} ist die fr\xfcheste Zeit, die Sie benutzen k\xf6nnen."}),"object"==typeof g.de.rangeOverflow&&["date","time","datetime-local","month"].forEach(function(a){g.de.rangeOverflow[a]=g.de.rangeOverflow[a]||"{%value} ist zu sp\xe4t. {%max} ist die sp\xe4teste Zeit, die Sie benutzen k\xf6nnen."});var i=g[""],j=function(b,c){return b&&"string"!=typeof b&&(b=b[a.prop(c,"type")]||b[(c.nodeName||"").toLowerCase()]||b.defaultMessage),b||""},k={value:1,min:1,max:1};b.createValidationMessage=function(c,d){var e,f=a.prop(c,"type"),h=j(i[d],c);return h||"badInput"!=d||(h=j(i.typeMismatch,c)),h||"typeMismatch"!=d||(h=j(i.badInput,c)),h||(h=j(g[""][d],c)||a.prop(c,"validationMessage"),b.info("could not find errormessage for: "+d+" / "+f+". in language: "+b.activeLang())),h&&["value","min","max","title","maxlength","minlength","label"].forEach(function(g){if(-1!==h.indexOf("{%"+g)){var i=("label"==g?a.trim(a('label[for="'+c.id+'"]',c.form).text()).replace(/\*$|:$/,""):a.prop(c,g))||"";"patternMismatch"!=d||"title"!=g||i||b.error("no title for patternMismatch provided. Always add a title attribute."),k[g]&&(e||(e=a(c).getShadowElement().data("wsWidget"+f)),e&&e.formatValue&&(i=e.formatValue(i,!1))),h=h.replace("{%"+g+"}",i),"value"==g&&(h=h.replace("{%valueLen}",i.length))}}),h||""},(!Modernizr.formvalidation||b.bugs.bustedValidity)&&h.push("validationMessage"),i=b.activeLang(g),a(g).on("change",function(){i=g.__active}),h.forEach(function(c){b.defineNodeNamesProperty(["fieldset","output","button"],c,{prop:{value:"",writeable:!1}}),["input","select","textarea"].forEach(function(d){var e=b.defineNodeNameProperty(d,c,{prop:{get:function(){var c=this,d="";if(!a.prop(c,"willValidate"))return d;var f=a.prop(c,"validity")||{valid:1};return f.valid?d:(d=b.getContentValidationMessage(c,f))?d:f.customError&&c.nodeName&&(d=Modernizr.formvalidation&&!b.bugs.bustedValidity&&e.prop._supget?e.prop._supget.call(c):b.data(c,"customvalidationMessage"))?d:(a.each(f,function(a,e){return"valid"!=a&&e?(d=b.createValidationMessage(c,a),d?!1:void 0):void 0}),d||"")},writeable:!1}})})})});
amoyeh/cdnjs
ajax/libs/webshim/1.12.2/minified/shims/combos/3.js
JavaScript
mit
24,650
'use strict'; angular.module("ngLocale", [], ["$provide", function($provide) { var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"}; function getDecimals(n) { n = n + ''; var i = n.indexOf('.'); return (i == -1) ? 0 : n.length - i - 1; } function getVF(n, opt_precision) { var v = opt_precision; if (undefined === v) { v = Math.min(getDecimals(n), 3); } var base = Math.pow(10, v); var f = ((n * base) | 0) % base; return {v: v, f: f}; } $provide.value("$locale", { "DATETIME_FORMATS": { "AMPMS": [ "Mambia", "Mog" ], "DAY": [ "Chumapiri", "Chumatato", "Chumaine", "Chumatano", "Aramisi", "Ichuma", "Esabato" ], "ERANAMES": [ "Yeso ataiborwa", "Yeso kaiboirwe" ], "ERAS": [ "YA", "YK" ], "FIRSTDAYOFWEEK": 0, "MONTH": [ "Chanuari", "Feburari", "Machi", "Apiriri", "Mei", "Juni", "Chulai", "Agosti", "Septemba", "Okitoba", "Nobemba", "Disemba" ], "SHORTDAY": [ "Cpr", "Ctt", "Cmn", "Cmt", "Ars", "Icm", "Est" ], "SHORTMONTH": [ "Can", "Feb", "Mac", "Apr", "Mei", "Jun", "Cul", "Agt", "Sep", "Okt", "Nob", "Dis" ], "STANDALONEMONTH": [ "Chanuari", "Feburari", "Machi", "Apiriri", "Mei", "Juni", "Chulai", "Agosti", "Septemba", "Okitoba", "Nobemba", "Disemba" ], "WEEKENDRANGE": [ 5, 6 ], "fullDate": "EEEE, d MMMM y", "longDate": "d MMMM y", "medium": "d MMM y HH:mm:ss", "mediumDate": "d MMM y", "mediumTime": "HH:mm:ss", "short": "dd/MM/y HH:mm", "shortDate": "dd/MM/y", "shortTime": "HH:mm" }, "NUMBER_FORMATS": { "CURRENCY_SYM": "Ksh", "DECIMAL_SEP": ".", "GROUP_SEP": ",", "PATTERNS": [ { "gSize": 3, "lgSize": 3, "maxFrac": 3, "minFrac": 0, "minInt": 1, "negPre": "-", "negSuf": "", "posPre": "", "posSuf": "" }, { "gSize": 3, "lgSize": 3, "maxFrac": 2, "minFrac": 2, "minInt": 1, "negPre": "-\u00a4", "negSuf": "", "posPre": "\u00a4", "posSuf": "" } ] }, "id": "guz", "localeID": "guz", "pluralCat": function(n, opt_precision) { var i = n | 0; var vf = getVF(n, opt_precision); if (i == 1 && vf.v == 0) { return PLURAL_CATEGORY.ONE; } return PLURAL_CATEGORY.OTHER;} }); }]);
Amomo/cdnjs
ajax/libs/angular.js/1.6.0-rc.1/i18n/angular-locale_guz.js
JavaScript
mit
2,722
/* YUI 3.15.0 (build 834026e) Copyright 2014 Yahoo! Inc. All rights reserved. Licensed under the BSD License. http://yuilibrary.com/license/ */ YUI.add("scrollview-base",function(e,t){function F(){F.superclass.constructor.apply(this,arguments)}var n=e.ClassNameManager.getClassName,r=e.config.doc,i=e.UA.ie,s=e.Transition.useNative,o=e.Transition._VENDOR_PREFIX,u="scrollview",a={vertical:n(u,"vert"),horizontal:n(u,"horiz")},f="scrollEnd",l="flick",c="drag",h="mousewheel",p="ui",d="top",v="left",m="px",g="axis",y="scrollY",b="scrollX",w="bounce",E="disabled",S="deceleration",x="x",T="y",N="boundingBox",C="contentBox",k="gesturemove",L="start",A="end",O="",M="0s",_="snapDuration",D="snapEasing",P="easing",H="frameDuration",B="bounceRange",j=function(e,t,n){return Math.min(Math.max(e,t),n)};e.ScrollView=e.extend(F,e.Widget,{_forceHWTransforms:e.UA.webkit?!0:!1,_prevent:{start:!1,move:!0,end:!1},lastScrolledAmt:0,_minScrollX:null,_maxScrollX:null,_minScrollY:null,_maxScrollY:null,initializer:function(){var e=this;e._bb=e.get(N),e._cb=e.get(C),e._cAxis=e.get(g),e._cBounce=e.get(w),e._cBounceRange=e.get(B),e._cDeceleration=e.get(S),e._cFrameDuration=e.get(H)},bindUI:function(){var e=this;e._bindFlick(e.get(l)),e._bindDrag(e.get(c)),e._bindMousewheel(!0),e._bindAttrs(),i&&e._fixIESelect(e._bb,e._cb),F.SNAP_DURATION&&e.set(_,F.SNAP_DURATION),F.SNAP_EASING&&e.set(D,F.SNAP_EASING),F.EASING&&e.set(P,F.EASING),F.FRAME_STEP&&e.set(H,F.FRAME_STEP),F.BOUNCE_RANGE&&e.set(B,F.BOUNCE_RANGE)},_bindAttrs:function(){var e=this,t=e._afterScrollChange,n=e._afterDimChange;e.after({scrollEnd:e._afterScrollEnd,disabledChange:e._afterDisabledChange,flickChange:e._afterFlickChange,dragChange:e._afterDragChange,axisChange:e._afterAxisChange,scrollYChange:t,scrollXChange:t,heightChange:n,widthChange:n})},_bindDrag:function(t){var n=this,r=n._bb;r.detach(c+"|*"),t&&r.on(c+"|"+k+L,e.bind(n._onGestureMoveStart,n))},_bindFlick:function(t){var n=this,r=n._bb;r.detach(l+"|*"),t&&(r.on(l+"|"+l,e.bind(n._flick,n),t),n._bindDrag(n.get(c)))},_bindMousewheel:function(t){var n=this,i=n._bb;i.detach(h+"|*"),t&&e.one(r).on(h,e.bind(n._mousewheel,n))},syncUI:function(){var e=this,t=e._getScrollDims(),n=t.offsetWidth,r=t.offsetHeight,i=t.scrollWidth,s=t.scrollHeight;e._cAxis===undefined&&(e._cAxis={x:i>n,y:s>r},e._set(g,e._cAxis)),e.rtl=e._cb.getComputedStyle("direction")==="rtl",e._cDisabled=e.get(E),e._uiDimensionsChange(),e._isOutOfBounds()&&e._snapBack()},_getScrollDims:function(){var e=this,t=e._cb,n=e._bb,r=F._TRANSITION,i=e.get(b),o=e.get(y),u,a;return s&&(t.setStyle(r.DURATION,M),t.setStyle(r.PROPERTY,O)),u=e._forceHWTransforms,e._forceHWTransforms=!1,e._moveTo(t,0,0),a={offsetWidth:n.get("offsetWidth"),offsetHeight:n.get("offsetHeight"),scrollWidth:n.get("scrollWidth"),scrollHeight:n.get("scrollHeight")},e._moveTo(t,-i,-o),e._forceHWTransforms=u,a},_uiDimensionsChange:function(){var e=this,t=e._bb,n=e._getScrollDims(),r=n.offsetWidth,i=n.offsetHeight,s=n.scrollWidth,o=n.scrollHeight,u=e.rtl,f=e._cAxis,l=u?Math.min(0,-(s-r)):0,c=u?0:Math.max(0,s-r),h=0,p=Math.max(0,o-i);f&&f.x&&t.addClass(a.horizontal),f&&f.y&&t.addClass(a.vertical),e._setBounds({minScrollX:l,maxScrollX:c,minScrollY:h,maxScrollY:p})},_setBounds:function(e){var t=this;t._minScrollX=e.minScrollX,t._maxScrollX=e.maxScrollX,t._minScrollY=e.minScrollY,t._maxScrollY=e.maxScrollY},_getBounds:function(){var e=this;return{minScrollX:e._minScrollX,maxScrollX:e._maxScrollX,minScrollY:e._minScrollY,maxScrollY:e._maxScrollY}},scrollTo:function(t,n,r,i,o){if(this._cDisabled)return;var u=this,a=u._cb,f=F._TRANSITION,l=e.bind(u._onTransEnd,u),c=0,h=0,g={},w;r=r||0,i=i||u.get(P),o=o||a,t!==null&&(u.set(b,t,{src:p}),c=-t),n!==null&&(u.set(y,n,{src:p}),h=-n),w=u._transform(c,h),s&&o.setStyle(f.DURATION,M).setStyle(f.PROPERTY,O),r===0?s?o.setStyle("transform",w):(t!==null&&o.setStyle(v,c+m),n!==null&&o.setStyle(d,h+m)):(g.easing=i,g.duration=r/1e3,s?g.transform=w:(g.left=c+m,g.top=h+m),o.transition(g,l))},_transform:function(e,t){var n="translate("+e+"px, "+t+"px)";return this._forceHWTransforms&&(n+=" translateZ(0)"),n},_moveTo:function(e,t,n){s?e.setStyle("transform",this._transform(t,n)):(e.setStyle(v,t+m),e.setStyle(d,n+m))},_onTransEnd:function(){var e=this;e._isOutOfBounds()?e._snapBack():e.fire(f)},_onGestureMoveStart:function(t){if(this._cDisabled)return!1;var n=this,r=n._bb,i=n.get(b),s=n.get(y),o=t.clientX,u=t.clientY;n._prevent.start&&t.preventDefault(),n._flickAnim&&(n._cancelFlick(),n._onTransEnd()),n.lastScrolledAmt=0,n._gesture={axis:null,startX:i,startY:s,startClientX:o,startClientY:u,endClientX:null,endClientY:null,deltaX:null,deltaY:null,flick:null,onGestureMove:r.on(c+"|"+k,e.bind(n._onGestureMove,n)),onGestureMoveEnd:r.on(c+"|"+k+A,e.bind(n._onGestureMoveEnd,n))}},_onGestureMove:function(e){var t=this,n=t._gesture,r=t._cAxis,i=r.x,s=r.y,o=n.startX,u=n.startY,a=n.startClientX,f=n.startClientY,l=e.clientX,c=e.clientY;t._prevent.move&&e.preventDefault(),n.deltaX=a-l,n.deltaY=f-c,n.axis===null&&(n.axis=Math.abs(n.deltaX)>Math.abs(n.deltaY)?x:T),n.axis===x&&i?t.set(b,o+n.deltaX):n.axis===T&&s&&t.set(y,u+n.deltaY)},_onGestureMoveEnd:function(e){var t=this,n=t._gesture,r=n.flick,i=e.clientX,s=e.clientY,o;t._prevent.end&&e.preventDefault(),n.endClientX=i,n.endClientY=s,n.onGestureMove.detach(),n.onGestureMoveEnd.detach(),r||n.deltaX!==null&&n.deltaY!==null&&(o=t._isOutOfBounds(),o?t._snapBack():(!t.pages||t.pages&&!t.pages.get(g)[n.axis])&&t._onTransEnd())},_flick:function(e){if(this._cDisabled)return!1;var t=this,n=t._cAxis,r=e.flick,i=r.axis,s=r.velocity,o=i===x?b:y,u=t.get(o);t._gesture&&(t._gesture.flick=r),n[i]&&t._flickFrame(s,i,u)},_flickFrame:function(t,n,r){var i=this,s=n===x?b:y,o=i._getBounds(),u=i._cBounce,a=i._cBounceRange,f=i._cDeceleration,l=i._cFrameDuration,c=t*f,h=r-l*c,p=n===x?o.minScrollX:o.minScrollY,d=n===x?o.maxScrollX:o.maxScrollY,v=h<p,m=h<d,g=h>p,w=h>d,E=h<p-a,S=v&&h>p-a,T=w&&h<d+a,N=h>d+a,C;if(S||T)c*=u;C=Math.abs(c).toFixed(4)<.015,C||E||N?(i._flickAnim&&i._cancelFlick(),g&&m?i._onTransEnd():i._snapBack()):(i._flickAnim=e.later(l,i,"_flickFrame",[c,n,h]),i.set(s,h))},_cancelFlick:function( ){var e=this;e._flickAnim&&(e._flickAnim.cancel(),delete e._flickAnim)},_mousewheel:function(e){var t=this,n=t.get(y),r=t._getBounds(),i=t._bb,s=10,o=e.wheelDelta>0,u=n-(o?1:-1)*s;u=j(u,r.minScrollY,r.maxScrollY),i.contains(e.target)&&t._cAxis[T]&&(t.lastScrolledAmt=0,t.set(y,u),t.scrollbars&&(t.scrollbars._update(),t.scrollbars.flash()),t._onTransEnd(),e.preventDefault())},_isOutOfBounds:function(e,t){var n=this,r=n._cAxis,i=r.x,s=r.y,o=e||n.get(b),u=t||n.get(y),a=n._getBounds(),f=a.minScrollX,l=a.minScrollY,c=a.maxScrollX,h=a.maxScrollY;return i&&(o<f||o>c)||s&&(u<l||u>h)},_snapBack:function(){var e=this,t=e.get(b),n=e.get(y),r=e._getBounds(),i=r.minScrollX,s=r.minScrollY,o=r.maxScrollX,u=r.maxScrollY,a=j(n,s,u),f=j(t,i,o),l=e.get(_),c=e.get(D);f!==t?e.set(b,f,{duration:l,easing:c}):a!==n?e.set(y,a,{duration:l,easing:c}):e._onTransEnd()},_afterScrollChange:function(e){if(e.src===F.UI_SRC)return!1;var t=this,n=e.duration,r=e.easing,i=e.newVal,s=[];t.lastScrolledAmt=t.lastScrolledAmt+(e.newVal-e.prevVal),e.attrName===b?(s.push(i),s.push(t.get(y))):(s.push(t.get(b)),s.push(i)),s.push(n),s.push(r),t.scrollTo.apply(t,s)},_afterFlickChange:function(e){this._bindFlick(e.newVal)},_afterDisabledChange:function(e){this._cDisabled=e.newVal},_afterAxisChange:function(e){this._cAxis=e.newVal},_afterDragChange:function(e){this._bindDrag(e.newVal)},_afterDimChange:function(){this._uiDimensionsChange()},_afterScrollEnd:function(){var e=this;e._flickAnim&&e._cancelFlick()},_axisSetter:function(t){if(e.Lang.isString(t))return{x:t.match(/x/i)?!0:!1,y:t.match(/y/i)?!0:!1}},_setScroll:function(t){return this._cDisabled&&(t=e.Attribute.INVALID_VALUE),t},_setScrollX:function(e){return this._setScroll(e,x)},_setScrollY:function(e){return this._setScroll(e,T)}},{NAME:"scrollview",ATTRS:{axis:{setter:"_axisSetter",writeOnce:"initOnly"},scrollX:{value:0,setter:"_setScrollX"},scrollY:{value:0,setter:"_setScrollY"},deceleration:{value:.93},bounce:{value:.1},flick:{value:{minDistance:10,minVelocity:.3}},drag:{value:!0},snapDuration:{value:400},snapEasing:{value:"ease-out"},easing:{value:"cubic-bezier(0, 0.1, 0, 1.0)"},frameDuration:{value:15},bounceRange:{value:150}},CLASS_NAMES:a,UI_SRC:p,_TRANSITION:{DURATION:o?o+"TransitionDuration":"transitionDuration",PROPERTY:o?o+"TransitionProperty":"transitionProperty"},BOUNCE_RANGE:!1,FRAME_STEP:!1,EASING:!1,SNAP_EASING:!1,SNAP_DURATION:!1})},"3.15.0",{requires:["widget","event-gestures","event-mousewheel","transition"],skinnable:!0});
abhi901abhi/cdnjs
ajax/libs/yui/3.15.0/scrollview-base/scrollview-base-min.js
JavaScript
mit
8,649
/* YUI 3.15.0 (build 834026e) Copyright 2014 Yahoo! Inc. All rights reserved. Licensed under the BSD License. http://yuilibrary.com/license/ */ YUI.add('stylesheet', function (Y, NAME) { /** * The StyleSheet component is a module for creating and modifying CSS * stylesheets. * * @module stylesheet */ var d = Y.config.doc, p = d.createElement('p'), // Have to hold the node (see notes) workerStyle = p.style, // worker style collection isString = Y.Lang.isString, selectors = {}, sheets = {}, floatAttr = ('cssFloat' in workerStyle) ? 'cssFloat' : 'styleFloat', _toCssText, _unsetOpacity, _unsetProperty, OPACITY = 'opacity', FLOAT = 'float', EMPTY = ''; // Normalizes the removal of an assigned style for opacity. IE uses the filter // property. _unsetOpacity = (OPACITY in workerStyle) ? function (style) { style.opacity = EMPTY; } : function (style) { style.filter = EMPTY; }; // Normalizes the removal of an assigned style for a given property. Expands // shortcut properties if necessary and handles the various names for the float // property. workerStyle.border = "1px solid red"; workerStyle.border = EMPTY; // IE doesn't unset child properties _unsetProperty = workerStyle.borderLeft ? function (style,prop) { var p; if (prop !== floatAttr && prop.toLowerCase().indexOf(FLOAT) != -1) { prop = floatAttr; } if (isString(style[prop])) { switch (prop) { case OPACITY: case 'filter' : _unsetOpacity(style); break; case 'font' : style.font = style.fontStyle = style.fontVariant = style.fontWeight = style.fontSize = style.lineHeight = style.fontFamily = EMPTY; break; default : for (p in style) { if (p.indexOf(prop) === 0) { style[p] = EMPTY; } } } } } : function (style,prop) { if (prop !== floatAttr && prop.toLowerCase().indexOf(FLOAT) != -1) { prop = floatAttr; } if (isString(style[prop])) { if (prop === OPACITY) { _unsetOpacity(style); } else { style[prop] = EMPTY; } } }; /** * Create an instance of StyleSheet to encapsulate a css stylesheet. * The constructor can be called using function or constructor syntax. * <pre><code>var sheet = Y.StyleSheet(..);</pre></code> * or * <pre><code>var sheet = new Y.StyleSheet(..);</pre></code> * * The first parameter passed can be any of the following things: * <ul> * <li>The desired string name to register a new empty sheet</li> * <li>The string name of an existing StyleSheet instance</li> * <li>The unique guid generated for an existing StyleSheet instance</li> * <li>The id of an existing <code>&lt;link&gt;</code> or <code>&lt;style&gt;</code> node</li> * <li>The node reference for an existing <code>&lt;link&gt;</code> or <code>&lt;style&gt;</code> node</li> * <li>The Y.Node instance wrapping an existing <code>&lt;link&gt;</code> or <code>&lt;style&gt;</code> node</li> * <li>A chunk of css text to create a new stylesheet from</li> * </ul> * * <p>If a string is passed, StyleSheet will first look in its static name * registry for an existing sheet, then in the DOM for an element with that id. * If neither are found and the string contains the { character, it will be * used as a the initial cssText for a new StyleSheet. Otherwise, a new empty * StyleSheet is created, assigned the string value as a name, and registered * statically by that name.</p> * * <p>The optional second parameter is a string name to register the sheet as. * This param is largely useful when providing a node id/ref or chunk of css * text to create a populated instance.</p> * * @class StyleSheet * @constructor * @param seed {String|HTMLElement|Node} a style or link node, its id, or a * name or guid of a StyleSheet, or a string of css text * @param name {String} (optional) name to register instance for future static * access */ function StyleSheet(seed, name) { var head, node, sheet, cssRules = {}, _rules, _insertRule, _deleteRule, i,r,sel; // Factory or constructor if (!(Y.instanceOf(this, StyleSheet))) { return new StyleSheet(seed,name); } // Extract the DOM node from Node instances if (seed) { if (Y.Node && seed instanceof Y.Node) { node = seed._node; } else if (seed.nodeName) { node = seed; // capture the DOM node if the string is an id } else if (isString(seed)) { if (seed && sheets[seed]) { return sheets[seed]; } node = d.getElementById(seed.replace(/^#/,EMPTY)); } // Check for the StyleSheet in the static registry if (node && sheets[Y.stamp(node)]) { return sheets[Y.stamp(node)]; } } // Create a style node if necessary if (!node || !/^(?:style|link)$/i.test(node.nodeName)) { node = d.createElement('style'); node.type = 'text/css'; } if (isString(seed)) { // Create entire sheet from seed cssText if (seed.indexOf('{') != -1) { // Not a load-time fork because low run-time impact and IE fails // test for s.styleSheet at page load time (oddly) if (node.styleSheet) { node.styleSheet.cssText = seed; } else { node.appendChild(d.createTextNode(seed)); } } else if (!name) { name = seed; } } // Make sure the node is attached to the appropriate head element if (!node.parentNode || node.parentNode.nodeName.toLowerCase() !== 'head') { head = (node.ownerDocument || d).getElementsByTagName('head')[0]; // styleSheet isn't available on the style node in FF2 until appended // to the head element. style nodes appended to body do not affect // change in Safari. head.appendChild(node); } // Begin setting up private aliases to the important moving parts // 1. The stylesheet object // IE stores StyleSheet under the "styleSheet" property // Safari doesn't populate sheet for xdomain link elements sheet = node.sheet || node.styleSheet; // 2. The style rules collection // IE stores the rules collection under the "rules" property _rules = sheet && ('cssRules' in sheet) ? 'cssRules' : 'rules'; // 3. The method to remove a rule from the stylesheet // IE supports removeRule _deleteRule = ('deleteRule' in sheet) ? function (i) { sheet.deleteRule(i); } : function (i) { sheet.removeRule(i); }; // 4. The method to add a new rule to the stylesheet // IE supports addRule with different signature _insertRule = ('insertRule' in sheet) ? function (sel,css,i) { sheet.insertRule(sel+' {'+css+'}',i); } : function (sel,css,i) { sheet.addRule(sel,css,i); }; // 5. Initialize the cssRules map from the node // xdomain link nodes forbid access to the cssRules collection, so this // will throw an error. // TODO: research alternate stylesheet, @media for (i = sheet[_rules].length - 1; i >= 0; --i) { r = sheet[_rules][i]; sel = r.selectorText; if (cssRules[sel]) { cssRules[sel].style.cssText += ';' + r.style.cssText; _deleteRule(i); } else { cssRules[sel] = r; } } // Cache the instance by the generated Id StyleSheet.register(Y.stamp(node),this); // Register the instance by name if provided or defaulted from seed if (name) { StyleSheet.register(name,this); } // Public API Y.mix(this,{ /** * Get the unique stamp for this StyleSheet instance * * @method getId * @return {Number} the static id */ getId : function () { return Y.stamp(node); }, /** * Enable all the rules in the sheet * * @method enable * @return {StyleSheet} * @chainable */ enable : function () { sheet.disabled = false; return this; }, /** * Disable all the rules in the sheet. Rules may be changed while the * StyleSheet is disabled. * * @method disable * @return {StyleSheet} * @chainable */ disable : function () { sheet.disabled = true; return this; }, /** * Returns false if the StyleSheet is disabled. Otherwise true. * * @method isEnabled * @return {Boolean} */ isEnabled : function () { return !sheet.disabled; }, /** * <p>Set style properties for a provided selector string. * If the selector includes commas, it will be split into individual * selectors and applied accordingly. If the selector string does not * have a corresponding rule in the sheet, it will be added.</p> * * <p>The object properties in the second parameter must be the JavaScript * names of style properties. E.g. fontSize rather than font-size.</p> * * <p>The float style property will be set by any of &quot;float&quot;, * &quot;styleFloat&quot;, or &quot;cssFloat&quot;.</p> * * @method set * @param sel {String} the selector string to apply the changes to * @param css {Object} Object literal of style properties and new values * @return {StyleSheet} * @chainable */ set : function (sel,css) { var rule = cssRules[sel], multi = sel.split(/\s*,\s*/),i, idx; // IE's addRule doesn't support multiple comma delimited selectors if (multi.length > 1) { for (i = multi.length - 1; i >= 0; --i) { this.set(multi[i], css); } return this; } // Some selector values can cause IE to hang if (!StyleSheet.isValidSelector(sel)) { return this; } // Opera throws an error if there's a syntax error in assigned // cssText. Avoid this using a worker style collection, then // assigning the resulting cssText. if (rule) { rule.style.cssText = StyleSheet.toCssText(css,rule.style.cssText); } else { idx = sheet[_rules].length; css = StyleSheet.toCssText(css); // IE throws an error when attempting to addRule(sel,'',n) // which would crop up if no, or only invalid values are used if (css) { _insertRule(sel, css, idx); // Safari replaces the rules collection, but maintains the // rule instances in the new collection when rules are // added/removed cssRules[sel] = sheet[_rules][idx]; } } return this; }, /** * <p>Unset style properties for a provided selector string, removing * their effect from the style cascade.</p> * * <p>If the selector includes commas, it will be split into individual * selectors and applied accordingly. If there are no properties * remaining in the rule after unsetting, the rule is removed.</p> * * <p>The style property or properties in the second parameter must be the * JavaScript style property names. E.g. fontSize rather than font-size.</p> * * <p>The float style property will be unset by any of &quot;float&quot;, * &quot;styleFloat&quot;, or &quot;cssFloat&quot;.</p> * * @method unset * @param sel {String} the selector string to apply the changes to * @param css {String|Array} style property name or Array of names * @return {StyleSheet} * @chainable */ unset : function (sel,css) { var rule = cssRules[sel], multi = sel.split(/\s*,\s*/), remove = !css, rules, i; // IE's addRule doesn't support multiple comma delimited selectors // so rules are mapped internally by atomic selectors if (multi.length > 1) { for (i = multi.length - 1; i >= 0; --i) { this.unset(multi[i], css); } return this; } if (rule) { if (!remove) { css = Y.Array(css); workerStyle.cssText = rule.style.cssText; for (i = css.length - 1; i >= 0; --i) { _unsetProperty(workerStyle,css[i]); } if (workerStyle.cssText) { rule.style.cssText = workerStyle.cssText; } else { remove = true; } } if (remove) { // remove the rule altogether rules = sheet[_rules]; for (i = rules.length - 1; i >= 0; --i) { if (rules[i] === rule) { delete cssRules[sel]; _deleteRule(i); break; } } } } return this; }, /** * Get the current cssText for a rule or the entire sheet. If the * selector param is supplied, only the cssText for that rule will be * returned, if found. If the selector string targets multiple * selectors separated by commas, the cssText of the first rule only * will be returned. If no selector string, the stylesheet's full * cssText will be returned. * * @method getCssText * @param sel {String} Selector string * @return {String} */ getCssText : function (sel) { var rule, css, selector; if (isString(sel)) { // IE's addRule doesn't support multiple comma delimited // selectors so rules are mapped internally by atomic selectors rule = cssRules[sel.split(/\s*,\s*/)[0]]; return rule ? rule.style.cssText : null; } else { css = []; for (selector in cssRules) { if (cssRules.hasOwnProperty(selector)) { rule = cssRules[selector]; css.push(rule.selectorText+" {"+rule.style.cssText+"}"); } } return css.join("\n"); } } }); } _toCssText = function (css,base) { var f = css.styleFloat || css.cssFloat || css[FLOAT], trim = Y.Lang.trim, prop; // A very difficult to repro/isolate IE 9 beta (and Platform Preview 7) bug // was reduced to this line throwing the error: // "Invalid this pointer used as target for method call" // It appears that the style collection is corrupted. The error is // catchable, so in a best effort to work around it, replace the // p and workerStyle and try the assignment again. try { workerStyle.cssText = base || EMPTY; } catch (e) { p = d.createElement('p'); workerStyle = p.style; workerStyle.cssText = base || EMPTY; } if (f && !css[floatAttr]) { css = Y.merge(css); delete css.styleFloat; delete css.cssFloat; delete css[FLOAT]; css[floatAttr] = f; } for (prop in css) { if (css.hasOwnProperty(prop)) { try { // IE throws Invalid Value errors and doesn't like whitespace // in values ala ' red' or 'red ' workerStyle[prop] = trim(css[prop]); } catch (ex) { } } } return workerStyle.cssText; }; Y.mix(StyleSheet, { /** * <p>Converts an object literal of style properties and values into a string * of css text. This can then be assigned to el.style.cssText.</p> * * <p>The optional second parameter is a cssText string representing the * starting state of the style prior to alterations. This is most often * extracted from the eventual target's current el.style.cssText.</p> * * @method toCssText * @param css {Object} object literal of style properties and values * @param cssText {String} (optional) starting cssText value * @return {String} the resulting cssText string * @static */ toCssText : ((OPACITY in workerStyle) ? _toCssText : // Wrap IE's toCssText to catch opacity. The copy/merge is to preserve // the input object's integrity, but if float and opacity are set, the // input will be copied twice in IE. Is there a way to avoid this // without increasing the byte count? function (css, cssText) { if (OPACITY in css) { css = Y.merge(css,{ filter: 'alpha(opacity='+(css.opacity*100)+')' }); delete css.opacity; } return _toCssText(css,cssText); }), /** * Registers a StyleSheet instance in the static registry by the given name * * @method register * @param name {String} the name to assign the StyleSheet in the registry * @param sheet {StyleSheet} The StyleSheet instance * @return {Boolean} false if no name or sheet is not a StyleSheet * instance. true otherwise. * @static */ register : function (name,sheet) { return !!(name && sheet instanceof StyleSheet && !sheets[name] && (sheets[name] = sheet)); }, /** * <p>Determines if a selector string is safe to use. Used internally * in set to prevent IE from locking up when attempting to add a rule for a * &quot;bad selector&quot;.</p> * * <p>Bad selectors are considered to be any string containing unescaped * `~!@$%^&()+=|{}[];'"?< or space. Also forbidden are . or # followed by * anything other than an alphanumeric. Additionally -abc or .-abc or * #_abc or '# ' all fail. There are likely more failure cases, so * please file a bug if you encounter one.</p> * * @method isValidSelector * @param sel {String} the selector string * @return {Boolean} * @static */ isValidSelector : function (sel) { var valid = false; if (sel && isString(sel)) { if (!selectors.hasOwnProperty(sel)) { // TEST: there should be nothing but white-space left after // these destructive regexs selectors[sel] = !/\S/.test( // combinators sel.replace(/\s+|\s*[+~>]\s*/g,' '). // attribute selectors (contents not validated) replace(/([^ ])\[.*?\]/g,'$1'). // pseudo-class|element selectors (contents of parens // such as :nth-of-type(2) or :not(...) not validated) replace(/([^ ])::?[a-z][a-z\-]+[a-z](?:\(.*?\))?/ig,'$1'). // element tags replace(/(?:^| )[a-z0-6]+/ig,' '). // escaped characters replace(/\\./g,EMPTY). // class and id identifiers replace(/[.#]\w[\w\-]*/g,EMPTY)); } valid = selectors[sel]; } return valid; } },true); Y.StyleSheet = StyleSheet; /* NOTES * Style node must be added to the head element. Safari does not honor styles applied to StyleSheet objects on style nodes in the body. * StyleSheet object is created on the style node when the style node is added to the head element in Firefox 2 (and maybe 3?) * The cssRules collection is replaced after insertRule/deleteRule calls in Safari 3.1. Existing Rules are used in the new collection, so the collection cannot be cached, but the rules can be. * Opera requires that the index be passed with insertRule. * Same-domain restrictions prevent modifying StyleSheet objects attached to link elements with remote href (or "about:blank" or "javascript:false") * Same-domain restrictions prevent reading StyleSheet cssRules/rules collection of link elements with remote href (or "about:blank" or "javascript:false") * Same-domain restrictions result in Safari not populating node.sheet property for link elements with remote href (et.al) * IE names StyleSheet related properties and methods differently (see code) * IE converts tag names to upper case in the Rule's selectorText * IE converts empty string assignment to complex properties to value settings for all child properties. E.g. style.background = '' sets non-'' values on style.backgroundPosition, style.backgroundColor, etc. All else clear style.background and all child properties. * IE assignment style.filter = '' will result in style.cssText == 'FILTER:' * All browsers support Rule.style.cssText as a read/write property, leaving only opacity needing to be accounted for. * Benchmarks of style.property = value vs style.cssText += 'property: value' indicate cssText is slightly slower for single property assignment. For multiple property assignment, cssText speed stays relatively the same where style.property speed decreases linearly by the number of properties set. Exception being Opera 9.27, where style.property is always faster than style.cssText. * Opera 9.5b throws a syntax error when assigning cssText with a syntax error. * Opera 9.5 doesn't honor rule.style.cssText = ''. Previous style persists. You have to remove the rule altogether. * Stylesheet properties set with !important will trump inline style set on an element or in el.style.property. * Creating a worker style collection like document.createElement('p').style; will fail after a time in FF (~5secs of inactivity). Property assignments will not alter the property or cssText. It may be the generated node is garbage collected and the style collection becomes inert (speculation). * IE locks up when attempting to add a rule with a selector including at least characters {[]}~`!@%^&*()+=|? (unescaped) and leading _ or - such as addRule('-foo','{ color: red }') or addRule('._abc','{...}') * IE's addRule doesn't support comma separated selectors such as addRule('.foo, .bar','{..}') * IE throws an error on valid values with leading/trailing white space. * When creating an entire sheet at once, only FF2/3 & Opera allow creating a style node, setting its innerHTML and appending to head. * When creating an entire sheet at once, Safari requires the style node to be created with content in innerHTML of another element. * When creating an entire sheet at once, IE requires the style node content to be set via node.styleSheet.cssText * When creating an entire sheet at once in IE, styleSheet.cssText can't be written until node.type = 'text/css'; is performed. * When creating an entire sheet at once in IE, load-time fork on var styleNode = d.createElement('style'); _method = styleNode.styleSheet ?.. fails (falsey). During run-time, the test for .styleSheet works fine * Setting complex properties in cssText will SOMETIMES allow child properties to be unset set unset FF2 FF3 S3.1 IE6 IE7 Op9.27 Op9.5 ---------- ----------------- --- --- ---- --- --- ------ ----- border -top NO NO YES YES YES YES YES -top-color NO NO YES YES YES -color NO NO NO NO NO background -color NO NO YES YES YES -position NO NO YES YES YES -position-x NO NO NO NO NO font line-height YES YES NO NO NO NO YES -style YES YES NO YES YES -size YES YES NO YES YES -size-adjust ??? ??? n/a n/a n/a ??? ??? padding -top NO NO YES YES YES margin -top NO NO YES YES YES list-style -type YES YES YES YES YES -position YES YES YES YES YES overflow -x NO NO YES n/a YES ??? - unsetting font-size-adjust has the same effect as unsetting font-size * FireFox and WebKit populate rule.cssText as "SELECTOR { CSSTEXT }", but Opera and IE do not. * IE6 and IE7 silently ignore the { and } if passed into addRule('.foo','{ color:#000}',0). IE8 does not and creates an empty rule. * IE6-8 addRule('.foo','',n) throws an error. Must supply *some* cssText */ }, '3.15.0', {"requires": ["yui-base"]});
abbychau/cdnjs
ajax/libs/yui/3.15.0/stylesheet/stylesheet.js
JavaScript
mit
25,811
/* YUI 3.15.0 (build 834026e) Copyright 2014 Yahoo! Inc. All rights reserved. Licensed under the BSD License. http://yuilibrary.com/license/ */ YUI.add("datatable-sort",function(e,t){function l(){}var n=e.Lang,r=n.isBoolean,i=n.isString,s=n.isArray,o=n.isObject,u=e.Array,a=n.sub,f={asc:1,desc:-1,1:1,"-1":-1};l.ATTRS={sortable:{value:"auto",validator:"_validateSortable"},sortBy:{validator:"_validateSortBy",getter:"_getSortBy"},strings:{}},e.mix(l.prototype,{sort:function(t,n){return this.fire("sort",e.merge(n||{},{sortBy:t||this.get("sortBy")}))},SORTABLE_HEADER_TEMPLATE:'<div class="{className}" tabindex="0" unselectable="on"><span class="{indicatorClass}"></span></div>',toggleSort:function(t,n){var r=this._sortBy,i=[],s,o,a,f,l;for(s=0,o=r.length;s<o;++s)f={},f[r[s]._id]=r[s].sortDir,i.push(f);if(t){t=u(t);for(s=0,o=t.length;s<o;++s){f=t[s],l=-1;for(a=i.length-1;s>=0;--s)if(i[a][f]){i[a][f]*=-1;break}}}else for(s=0,o=i.length;s<o;++s)for(f in i[s])if(i[s].hasOwnProperty(f)){i[s][f]*=-1;break}return this.fire("sort",e.merge(n||{},{sortBy:i}))},_afterSortByChange:function(){this._setSortBy(),this._sortBy.length&&(this.data.comparator||(this.data.comparator=this._sortComparator),this.data.sort())},_afterSortDataChange:function(e){(e.prevVal!==e.newVal||e.newVal.hasOwnProperty("_compare"))&&this._initSortFn()},_afterSortRecordChange:function(e){var t,n;for(t=0,n=this._sortBy.length;t<n;++t)if(e.changed[this._sortBy[t].key]){this.data.sort();break}},_bindSortUI:function(){var t=this._eventHandles;t.sortAttrs||(t.sortAttrs=this.after(["sortableChange","sortByChange","columnsChange"],e.bind("_uiSetSortable",this))),!t.sortUITrigger&&this._theadNode&&(t.sortUITrigger=this.delegate(["click","keydown"],e.rbind("_onUITriggerSort",this),"."+this.getClassName("sortable","column")))},_defSortFn:function(e){this.set.apply(this,["sortBy",e.sortBy].concat(e.details))},_getSortBy:function(e,t){var n,r,i,s;t=t.slice(7);if(t==="state"){n=[];for(r=0,i=this._sortBy.length;r<i;++r)s=this._sortBy[r],n.push({column:s._id,dir:s.sortDir});return{state:n.length===1?n[0]:n}}return e},initializer:function(){var t=e.bind("_parseSortable",this);this._parseSortable(),this._setSortBy(),this._initSortFn(),this._initSortStrings(),this.after({"table:renderHeader":e.bind("_renderSortable",this),dataChange:e.bind("_afterSortDataChange",this),sortByChange:e.bind("_afterSortByChange",this),sortableChange:t,columnsChange:t}),this.data.after(this.data.model.NAME+":change",e.bind("_afterSortRecordChange",this)),this.publish("sort",{defaultFn:e.bind("_defSortFn",this)})},_initSortFn:function(){var e=this;this.data._compare=function(t,n){var r=0,i,s,o,u,a,f,l;for(i=0,s=e._sortBy.length;!r&&i<s;++i)o=e._sortBy[i],u=o.sortDir,a=o.caseSensitive,o.sortFn?r=o.sortFn(t,n,u===-1):(f=t.get(o.key)||"",l=n.get(o.key)||"",!a&&typeof f=="string"&&typeof l=="string"&&(f=f.toLowerCase(),l=l.toLowerCase()),r=f>l?u:f<l?-u:0);return r},this._sortBy.length?(this.data.comparator=this._sortComparator,this.data.sort()):delete this.data.comparator},_initSortStrings:function(){this.set("strings",e.mix(this.get("strings")||{},e.Intl.get("datatable-sort")))},_onUITriggerSort:function(e){var t=e.currentTarget.getAttribute("data-yui3-col-id"),n=t&&this.getColumn(t),r,i,s;if(e.type==="keydown"&&e.keyCode!==32)return;e.preventDefault();if(n){if(e.shiftKey){r=this.get("sortBy")||[];for(i=0,s=r.length;i<s;++i)if(t===r[i]||Math.abs(r[i][t])===1){o(r[i])||(r[i]={}),r[i][t]=-(n.sortDir||0)||1;break}i>=s&&r.push(n._id)}else r=[{}],r[0][t]=-(n.sortDir||0)||1;this.fire("sort",{originEvent:e,sortBy:r})}},_parseSortable:function(){var e=this.get("sortable"),t=[],n,r,i;if(s(e))for(n=0,r=e.length;n<r;++n){i=e[n];if(!o(i,!0)||s(i))i=this.getColumn(i);i&&t.push(i)}else if(e){t=this._displayColumns.slice();if(e==="auto")for(n=t.length-1;n>=0;--n)t[n].sortable||t.splice(n,1)}this._sortable=t},_renderSortable:function(){this._uiSetSortable(),this._bindSortUI()},_setSortBy:function(){var e=this._displayColumns,t=this.get("sortBy")||[],n=" "+this.getClassName("sorted"),r,i,s,a,l,c;this._sortBy=[];for(r=0,i=e.length;r<i;++r)c=e[r],delete c.sortDir,c.className&&(c.className=c.className.replace(n,""));t=u(t);for(r=0,i=t.length;r<i;++r){s=t[r],a=1;if(o(s)){l=s;for(s in l)if(l.hasOwnProperty(s)){a=f[l[s]];break}}s&&(c=this.getColumn(s)||{_id:s,key:s},c&&(c.sortDir=a,c.className||(c.className=""),c.className+=n,this._sortBy.push(c)))}},_sortComparator:function(e){return e},_uiSetSortable:function(){var t=this._sortable||[],n=this.getClassName("sortable","column"),r=this.getClassName("sorted"),i=this.getClassName("sorted","desc"),s=this.getClassName("sort","liner"),o=this.getClassName("sort","indicator"),u={},f,l,c,h,p,d,v;this.get("boundingBox").toggleClass(this.getClassName("sortable"),t.length);for(f=0,l=t.length;f<l;++f)u[t[f].id]=t[f];this._theadNode.all("."+n).each(function(e){var t=u[e.get("id")],a=e.one("."+s),f;t?t.sortDir||e.removeClass(r).removeClass(i):(e.removeClass(n).removeClass(r).removeClass(i),a&&a.replace(a.get("childNodes").toFrag()),f=e.one("."+o),f&&f.remove().destroy(!0))});for(f=0,l=t.length;f<l;++f)c=t[f],h=this._theadNode.one("#"+c.id),v=c.sortDir===-1,h&&(p=h.one("."+s),h.addClass(n),c.sortDir&&(h.addClass(r),h.toggleClass(i,v),h.setAttribute("aria-sort",v?"descending":"ascending")),p||(p=e.Node.create(e.Lang.sub(this.SORTABLE_HEADER_TEMPLATE,{className:s,indicatorClass:o})),p.prepend(h.get("childNodes").toFrag()),h.append(p)),d=a(this.getString(c.sortDir===1?"reverseSortBy":"sortBy"),{title:c.title||"",key:c.key||"",abbr:c.abbr||"",label:c.label||"",column:c.abbr||c.label||c.key||"column "+f}),h.setAttribute("title",d),h.setAttribute("aria-labelledby",c.id))},_validateSortable:function(e){return e==="auto"||r(e)||s(e)},_validateSortBy:function(e){return e===null||i(e)||o(e,!0)||s(e)&&(i(e[0])||o(e,!0))}},!0),e.DataTable.Sortable=l,e.Base.mix(e.DataTable,[l])},"3.15.0",{requires:["datatable-base"],lang:["en","fr","es","hu"],skinnable:!0});
ProfNandaa/cdnjs
ajax/libs/yui/3.15.0/datatable-sort/datatable-sort-min.js
JavaScript
mit
5,982
'use strict'; angular.module("ngLocale", [], ["$provide", function($provide) { var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"}; function getDecimals(n) { n = n + ''; var i = n.indexOf('.'); return (i == -1) ? 0 : n.length - i - 1; } function getVF(n, opt_precision) { var v = opt_precision; if (undefined === v) { v = Math.min(getDecimals(n), 3); } var base = Math.pow(10, v); var f = ((n * base) | 0) % base; return {v: v, f: f}; } $provide.value("$locale", { "DATETIME_FORMATS": { "AMPMS": [ "Tesiran", "Teipa" ], "DAY": [ "Mderot ee are", "Mderot ee kuni", "Mderot ee ong\u2019wan", "Mderot ee inet", "Mderot ee ile", "Mderot ee sapa", "Mderot ee kwe" ], "ERANAMES": [ "Kabla ya Christo", "Baada ya Christo" ], "ERAS": [ "KK", "BK" ], "FIRSTDAYOFWEEK": 0, "MONTH": [ "Lapa le obo", "Lapa le waare", "Lapa le okuni", "Lapa le ong\u2019wan", "Lapa le imet", "Lapa le ile", "Lapa le sapa", "Lapa le isiet", "Lapa le saal", "Lapa le tomon", "Lapa le tomon obo", "Lapa le tomon waare" ], "SHORTDAY": [ "Are", "Kun", "Ong", "Ine", "Ile", "Sap", "Kwe" ], "SHORTMONTH": [ "Obo", "Waa", "Oku", "Ong", "Ime", "Ile", "Sap", "Isi", "Saa", "Tom", "Tob", "Tow" ], "STANDALONEMONTH": [ "Lapa le obo", "Lapa le waare", "Lapa le okuni", "Lapa le ong\u2019wan", "Lapa le imet", "Lapa le ile", "Lapa le sapa", "Lapa le isiet", "Lapa le saal", "Lapa le tomon", "Lapa le tomon obo", "Lapa le tomon waare" ], "WEEKENDRANGE": [ 5, 6 ], "fullDate": "EEEE, d MMMM y", "longDate": "d MMMM y", "medium": "d MMM y HH:mm:ss", "mediumDate": "d MMM y", "mediumTime": "HH:mm:ss", "short": "dd/MM/y HH:mm", "shortDate": "dd/MM/y", "shortTime": "HH:mm" }, "NUMBER_FORMATS": { "CURRENCY_SYM": "Ksh", "DECIMAL_SEP": ".", "GROUP_SEP": ",", "PATTERNS": [ { "gSize": 3, "lgSize": 3, "maxFrac": 3, "minFrac": 0, "minInt": 1, "negPre": "-", "negSuf": "", "posPre": "", "posSuf": "" }, { "gSize": 3, "lgSize": 3, "maxFrac": 2, "minFrac": 2, "minInt": 1, "negPre": "-\u00a4", "negSuf": "", "posPre": "\u00a4", "posSuf": "" } ] }, "id": "saq-ke", "localeID": "saq_KE", "pluralCat": function(n, opt_precision) { var i = n | 0; var vf = getVF(n, opt_precision); if (i == 1 && vf.v == 0) { return PLURAL_CATEGORY.ONE; } return PLURAL_CATEGORY.OTHER;} }); }]);
him2him2/cdnjs
ajax/libs/angular.js/1.6.4/i18n/angular-locale_saq-ke.js
JavaScript
mit
2,963
webshims.register("dom-extend",function(a,b,c,d,e){"use strict";var f=!("hrefNormalized"in a.support)||a.support.hrefNormalized,g=!("getSetAttribute"in a.support)||a.support.getSetAttribute,h=Object.prototype.hasOwnProperty;if(b.assumeARIA=g||Modernizr.canvas||Modernizr.video||Modernizr.boxsizing,("text"==a('<input type="email" />').attr("type")||""===a("<form />").attr("novalidate")||"required"in a("<input />")[0].attributes)&&b.error("IE browser modes are busted in IE10+. Please test your HTML/CSS/JS with a real IE version or at least IETester or similiar tools"),"debug"in b&&b.error('Use webshims.setOptions("debug", true||false||"noCombo"); to debug flag'),!b.cfg.no$Switch){var i=function(){if(!c.jQuery||c.$&&c.jQuery!=c.$||c.jQuery.webshims||(b.error("jQuery was included more than once. Make sure to include it only once or try the $.noConflict(extreme) feature! Webshims and other Plugins might not work properly. Or set webshims.cfg.no$Switch to 'true'."),c.$&&(c.$=b.$),c.jQuery=b.$),b.M!=Modernizr){b.error("Modernizr was included more than once. Make sure to include it only once! Webshims and other scripts might not work properly.");for(var a in Modernizr)a in b.M||(b.M[a]=Modernizr[a]);Modernizr=b.M}};i(),setTimeout(i,90),b.ready("DOM",i),a(i),b.ready("WINDOWLOAD",i)}var j=(b.modules,/\s*,\s*/),k={},l={},m={},n={},o={},p={},q=a.fn.val,r=function(b,c,d,e,f){return f?q.call(a(b)):q.call(a(b),d)};a.widget||!function(){var b=a.cleanData;a.cleanData=function(c){if(!a.widget)for(var d,e=0;null!=(d=c[e]);e++)try{a(d).triggerHandler("remove")}catch(f){}b(c)}}(),a.fn.val=function(b){var c=this[0];if(arguments.length&&null==b&&(b=""),!arguments.length)return c&&1===c.nodeType?a.prop(c,"value",b,"val",!0):q.call(this);if(a.isArray(b))return q.apply(this,arguments);var d=a.isFunction(b);return this.each(function(f){if(c=this,1===c.nodeType)if(d){var g=b.call(c,f,a.prop(c,"value",e,"val",!0));null==g&&(g=""),a.prop(c,"value",g,"val")}else a.prop(c,"value",b,"val")})},a.fn.onTrigger=function(a,b){return this.on(a,b).each(b)},a.fn.onWSOff=function(b,c,e,f){return f||(f=d),a(f)[e?"onTrigger":"on"](b,c),this.on("remove",function(d){d.originalEvent||a(f).off(b,c)}),this};var s="_webshimsLib"+Math.round(1e3*Math.random()),t=function(b,c,d){if(b=b.jquery?b[0]:b,!b)return d||{};var f=a.data(b,s);return d!==e&&(f||(f=a.data(b,s,{})),c&&(f[c]=d)),c?f&&f[c]:f};[{name:"getNativeElement",prop:"nativeElement"},{name:"getShadowElement",prop:"shadowElement"},{name:"getShadowFocusElement",prop:"shadowFocusElement"}].forEach(function(b){a.fn[b.name]=function(){var c=[];return this.each(function(){var d=t(this,"shadowData"),e=d&&d[b.prop]||this;-1==a.inArray(e,c)&&c.push(e)}),this.pushStack(c)}}),b.cfg.extendNative||b.cfg.noTriggerOverride||!function(b){a.event.trigger=function(c,d,e,f){if(!m[c]||f||!e||1!==e.nodeType)return b.apply(this,arguments);var g,i,j,k=e[c],l=a.prop(e,c),n=l&&k!=l;return n&&(j="__ws"+c,i=c in e&&h.call(e,c),e[c]=l,e[j]=k),g=b.apply(this,arguments),n&&(i?e[c]=k:delete e[c],delete e[j]),g}}(a.event.trigger),["removeAttr","prop","attr"].forEach(function(c){k[c]=a[c],a[c]=function(b,d,f,g,h){var i="val"==g,j=i?r:k[c];if(!b||!l[d]||1!==b.nodeType||!i&&g&&"attr"==c&&a.attrFn[d])return j(b,d,f,g,h);var m,o,q,s=(b.nodeName||"").toLowerCase(),t=n[s],u="attr"!=c||f!==!1&&null!==f?c:"removeAttr";if(t||(t=n["*"]),t&&(t=t[d]),t&&(m=t[u]),m){if("value"==d&&(o=m.isVal,m.isVal=i),"removeAttr"===u)return m.value.call(b);if(f===e)return m.get?m.get.call(b):m.value;m.set&&("attr"==c&&f===!0&&(f=d),q=m.set.call(b,f)),"value"==d&&(m.isVal=o)}else q=j(b,d,f,g,h);if((f!==e||"removeAttr"===u)&&p[s]&&p[s][d]){var v;v="removeAttr"==u?!1:"prop"==u?!!f:!0,p[s][d].forEach(function(a){(!a.only||(a.only="prop"&&"prop"==c)||"attr"==a.only&&"prop"!=c)&&a.call(b,f,v,i?"val":u,c)})}return q},o[c]=function(a,d,f){n[a]||(n[a]={}),n[a][d]||(n[a][d]={});var g=n[a][d][c],h=function(a,b,e){var g;return b&&b[a]?b[a]:e&&e[a]?e[a]:"prop"==c&&"value"==d?function(a){var b=this;return f.isVal?r(b,d,a,!1,0===arguments.length):k[c](b,d,a)}:"prop"==c&&"value"==a&&f.value.apply?(g="__ws"+d,m[d]=!0,function(){var a=this[g]||k[c](this,d);return a&&a.apply&&(a=a.apply(this,arguments)),a}):function(a){return k[c](this,d,a)}};n[a][d][c]=f,f.value===e&&(f.set||(f.set=f.writeable?h("set",f,g):b.cfg.useStrict&&"prop"==d?function(){throw d+" is readonly on "+a}:function(){b.info(d+" is readonly on "+a)}),f.get||(f.get=h("get",f,g))),["value","get","set"].forEach(function(a){f[a]&&(f["_sup"+a]=h(a,g))})}});var u=function(){var a=b.getPrototypeOf(d.createElement("foobar")),c=Modernizr.advancedObjectProperties&&Modernizr.objectAccessor;return function(e,f,g){var i,j;if(!(c&&(i=d.createElement(e))&&(j=b.getPrototypeOf(i))&&a!==j)||i[f]&&h.call(i,f))g._supvalue=function(){var a=t(this,"propValue");return a&&a[f]&&a[f].apply?a[f].apply(this,arguments):a&&a[f]},v.extendValue(e,f,g.value);else{var k=i[f];g._supvalue=function(){return k&&k.apply?k.apply(this,arguments):k},j[f]=g.value}g.value._supvalue=g._supvalue}}(),v=function(){var c={};b.addReady(function(d,e){var f={},g=function(b){f[b]||(f[b]=a(d.getElementsByTagName(b)),e[0]&&a.nodeName(e[0],b)&&(f[b]=f[b].add(e)))};a.each(c,function(a,c){return g(a),c&&c.forEach?(c.forEach(function(b){f[a].each(b)}),void 0):(b.warn("Error: with "+a+"-property. methods: "+c),void 0)}),f=null});var e,f=a([]),g=function(b,f){c[b]?c[b].push(f):c[b]=[f],a.isDOMReady&&(e||a(d.getElementsByTagName(b))).each(f)};return{createTmpCache:function(b){return a.isDOMReady&&(e=e||a(d.getElementsByTagName(b))),e||f},flushTmpCache:function(){e=null},content:function(b,c){g(b,function(){var b=a.attr(this,c);null!=b&&a.attr(this,c,b)})},createElement:function(a,b){g(a,b)},extendValue:function(b,c,d){g(b,function(){a(this).each(function(){var a=t(this,"propValue",{});a[c]=this[c],this[c]=d})})}}}(),w=function(a,b){a.defaultValue===e&&(a.defaultValue=""),a.removeAttr||(a.removeAttr={value:function(){a[b||"prop"].set.call(this,a.defaultValue),a.removeAttr._supvalue.call(this)}}),a.attr||(a.attr={})};a.extend(b,{getID:function(){var b=(new Date).getTime();return function(c){c=a(c);var d=c.prop("id");return d||(b++,d="ID-"+b,c.eq(0).prop("id",d)),d}}(),implement:function(a,c){var d=t(a,"implemented")||t(a,"implemented",{});return d[c]?(b.warn(c+" already implemented for element #"+a.id),!1):(d[c]=!0,!0)},extendUNDEFProp:function(b,c){a.each(c,function(a,c){a in b||(b[a]=c)})},getOptions:function(){var c=/\-([a-z])/g,d={},e={},f=function(a,b){return b.toLowerCase()},g=function(a,b){return b.toUpperCase()};return function(h,i,j,k){e[i]?i=e[i]:(e[i]=i.replace(c,g),i=e[i]);var l,m=t(h,"cfg"+i),n={};if(m)return m;if(m=a(h).data(),m&&"string"==typeof m[i]){if(k)return t(h,"cfg"+i,m[i]);b.error("data-"+i+" attribute has to be a valid JSON, was: "+m[i])}j?Array.isArray(j)?j.unshift(!0,{}):j=[!0,{},j]:j=[!0,{}],m&&"object"==typeof m[i]&&j.push(m[i]),d[i]||(d[i]=new RegExp("^"+i+"([A-Z])"));for(l in m)d[i].test(l)&&(n[l.replace(d[i],f)]=m[l]);return j.push(n),t(h,"cfg"+i,a.extend.apply(a,j))}}(),createPropDefault:w,data:t,moveToFirstEvent:function(b,c,d){var e,f=(a._data(b,"events")||{})[c];f&&f.length>1&&(e=f.pop(),d||(d="bind"),"bind"==d&&f.delegateCount?f.splice(f.delegateCount,0,e):f.unshift(e)),b=null},addShadowDom:function(){var e,f,g,h=a(c),i={init:!1,runs:0,test:function(){var a=i.getHeight(),b=i.getWidth();a!=i.height||b!=i.width?(i.height=a,i.width=b,i.handler({type:"docresize"}),i.runs++,i.runs<9&&setTimeout(i.test,90)):i.runs=0},handler:function(){var b=function(){a(d).triggerHandler("updateshadowdom")};return function(a){clearTimeout(e),e=setTimeout(function(){if("resize"==a.type){var d=h.width(),e=h.width();if(e==f&&d==g)return;f=e,g=d,i.height=i.getHeight(),i.width=i.getWidth()}c.requestAnimationFrame?requestAnimationFrame(b):setTimeout(b,0)},"resize"!=a.type||c.requestAnimationFrame?9:50)}}(),_create:function(){a.each({Height:"getHeight",Width:"getWidth"},function(a,b){var c=d.body,e=d.documentElement;i[b]=function(){return Math.max(c["scroll"+a],e["scroll"+a],c["offset"+a],e["offset"+a],e["client"+a])}})},start:function(){!this.init&&d.body&&(this.init=!0,this._create(),this.height=i.getHeight(),this.width=i.getWidth(),setInterval(this.test,600),a(this.test),b.ready("WINDOWLOAD",this.test),a(d).on("updatelayout.webshim pageinit popupafteropen panelbeforeopen tabsactivate collapsibleexpand shown.bs.modal shown.bs.collapse slid.bs.carousel",this.handler),a(c).on("resize",this.handler),function(){var b,c=a.fn.animate;a.fn.animate=function(){return clearTimeout(b),b=setTimeout(function(){i.test()},99),c.apply(this,arguments)}}())}};return b.docObserve=function(){b.ready("DOM",function(){i.start(),null==a.support.boxSizing&&a(function(){a.support.boxSizing&&i.handler({type:"boxsizing"})})})},function(c,d,e){if(c&&d){e=e||{},c.jquery&&(c=c[0]),d.jquery&&(d=d[0]);var f=a.data(c,s)||a.data(c,s,{}),g=a.data(d,s)||a.data(d,s,{}),h={};e.shadowFocusElement?e.shadowFocusElement&&(e.shadowFocusElement.jquery&&(e.shadowFocusElement=e.shadowFocusElement[0]),h=a.data(e.shadowFocusElement,s)||a.data(e.shadowFocusElement,s,h)):e.shadowFocusElement=d,a(c).on("remove",function(b){b.originalEvent||setTimeout(function(){a(d).remove()},4)}),f.hasShadow=d,h.nativeElement=g.nativeElement=c,h.shadowData=g.shadowData=f.shadowData={nativeElement:c,shadowElement:d,shadowFocusElement:e.shadowFocusElement},e.shadowChilds&&e.shadowChilds.each(function(){t(this,"shadowData",g.shadowData)}),e.data&&(h.shadowData.data=g.shadowData.data=f.shadowData.data=e.data),e=null}b.docObserve()}}(),propTypes:{standard:function(a){w(a),a.prop||(a.prop={set:function(b){a.attr.set.call(this,""+b)},get:function(){return a.attr.get.call(this)||a.defaultValue}})},"boolean":function(a){w(a),a.prop||(a.prop={set:function(b){b?a.attr.set.call(this,""):a.removeAttr.value.call(this)},get:function(){return null!=a.attr.get.call(this)}})},src:function(){var b=d.createElement("a");return b.style.display="none",function(c,d){w(c),c.prop||(c.prop={set:function(a){c.attr.set.call(this,a)},get:function(){var c,e=this.getAttribute(d);if(null==e)return"";if(b.setAttribute("href",e+""),!f){try{a(b).insertAfter(this),c=b.getAttribute("href",4)}catch(g){c=b.getAttribute("href",4)}a(b).detach()}return c||b.href}})}}(),enumarated:function(a){w(a),a.prop||(a.prop={set:function(b){a.attr.set.call(this,b)},get:function(){var b=(a.attr.get.call(this)||"").toLowerCase();return b&&-1!=a.limitedTo.indexOf(b)||(b=a.defaultValue),b}})}},reflectProperties:function(c,d){"string"==typeof d&&(d=d.split(j)),d.forEach(function(d){b.defineNodeNamesProperty(c,d,{prop:{set:function(b){a.attr(this,d,b)},get:function(){return a.attr(this,d)||""}}})})},defineNodeNameProperty:function(c,d,e){return l[d]=!0,e.reflect&&(e.propType&&!b.propTypes[e.propType]?b.error("could not finde propType "+e.propType):b.propTypes[e.propType||"standard"](e,d)),["prop","attr","removeAttr"].forEach(function(f){var g=e[f];g&&(g="prop"===f?a.extend({writeable:!0},g):a.extend({},g,{writeable:!0}),o[f](c,d,g),"*"!=c&&b.cfg.extendNative&&"prop"==f&&g.value&&a.isFunction(g.value)&&u(c,d,g),e[f]=g)}),e.initAttr&&v.content(c,d),e},defineNodeNameProperties:function(a,c,d,e){for(var f in c)!e&&c[f].initAttr&&v.createTmpCache(a),d&&(c[f][d]||(c[f][d]={},["value","set","get"].forEach(function(a){a in c[f]&&(c[f][d][a]=c[f][a],delete c[f][a])}))),c[f]=b.defineNodeNameProperty(a,f,c[f]);return e||v.flushTmpCache(),c},createElement:function(c,d,e){var f;return a.isFunction(d)&&(d={after:d}),v.createTmpCache(c),d.before&&v.createElement(c,d.before),e&&(f=b.defineNodeNameProperties(c,e,!1,!0)),d.after&&v.createElement(c,d.after),v.flushTmpCache(),f},onNodeNamesPropertyModify:function(b,c,d,e){"string"==typeof b&&(b=b.split(j)),a.isFunction(d)&&(d={set:d}),b.forEach(function(a){p[a]||(p[a]={}),"string"==typeof c&&(c=c.split(j)),d.initAttr&&v.createTmpCache(a),c.forEach(function(b){p[a][b]||(p[a][b]=[],l[b]=!0),d.set&&(e&&(d.set.only=e),p[a][b].push(d.set)),d.initAttr&&v.content(a,b)}),v.flushTmpCache()})},defineNodeNamesBooleanProperty:function(c,d,f){f||(f={}),a.isFunction(f)&&(f.set=f),b.defineNodeNamesProperty(c,d,{attr:{set:function(a){f.useContentAttribute?b.contentAttr(this,d,a):this.setAttribute(d,a),f.set&&f.set.call(this,!0)},get:function(){var a=f.useContentAttribute?b.contentAttr(this,d):this.getAttribute(d);return null==a?e:d}},removeAttr:{value:function(){this.removeAttribute(d),f.set&&f.set.call(this,!1)}},reflect:!0,propType:"boolean",initAttr:f.initAttr||!1})},contentAttr:function(a,b,c){if(a.nodeName){var d;return c===e?(d=a.attributes[b]||{},c=d.specified?d.value:null,null==c?e:c):("boolean"==typeof c?c?a.setAttribute(b,b):a.removeAttribute(b):a.setAttribute(b,c),void 0)}},activeLang:function(){var c=[],d=[],e={},f=function(d,f,h){f._isLoading=!0,e[d]?e[d].push(f):(e[d]=[f],b.loader.loadScript(d,function(){h==c.join()&&a.each(e[d],function(a,b){g(b)}),delete e[d]}))},g=function(b){var d=b.__active,e=function(a,d){return b._isLoading=!1,b[d]||-1!=b.availableLangs.indexOf(d)?(b[d]?(b.__active=b[d],b.__activeName=d):f(b.langSrc+d,b,c.join()),!1):void 0};a.each(c,e),b.__active||(b.__active=b[""],b.__activeName=""),d!=b.__active&&a(b).trigger("change")};return function(a){var b;if("string"==typeof a)c[0]!=a&&(c=[a],b=c[0].split("-")[0],b&&b!=a&&c.push(b),d.forEach(g));else if("object"==typeof a)return a.__active||(d.push(a),g(a)),a.__active;return c[0]}}()}),a.each({defineNodeNamesProperty:"defineNodeNameProperty",defineNodeNamesProperties:"defineNodeNameProperties",createElements:"createElement"},function(a,c){b[a]=function(a,d,e,f){"string"==typeof a&&(a=a.split(j));var g={};return a.forEach(function(a){g[a]=b[c](a,d,e,f)}),g}}),b.isReady("webshimLocalization",!0),function(){if(!("content"in d.createElement("template")||(a(function(){var c=a("main").attr({role:"main"});c.length>1?b.error("only one main element allowed in document"):c.is("article *, section *")&&b.error("main not allowed inside of article/section elements")}),"hidden"in d.createElement("a")))){b.defineNodeNamesBooleanProperty(["*"],"hidden");var c={article:"article",aside:"complementary",section:"region",nav:"navigation",address:"contentinfo"},e=function(a,b){var c=a.getAttribute("role");c||a.setAttribute("role",b)};a.webshims.addReady(function(b,f){if(a.each(c,function(c,d){for(var g=a(c,b).add(f.filter(c)),h=0,i=g.length;i>h;h++)e(g[h],d)}),b===d){var g=d.getElementsByTagName("header")[0],h=d.getElementsByTagName("footer"),i=h.length;if(g&&!a(g).closest("section, article")[0]&&e(g,"banner"),!i)return;var j=h[i-1];a(j).closest("section, article")[0]||e(j,"contentinfo")}})}}()}),webshims.register("form-message",function(a,b,c,d,e,f){"use strict";f.lazyCustomMessages&&(f.customMessages=!0);var g=b.validityMessages,h=f.customMessages?["customValidationMessage"]:[];g.en=a.extend(!0,{typeMismatch:{defaultMessage:"Please enter a valid value.",email:"Please enter an email address.",url:"Please enter a URL."},badInput:{defaultMessage:"Please enter a valid value.",number:"Please enter a number.",date:"Please enter a date.",time:"Please enter a time.",range:"Invalid input.",month:"Please enter a valid value.","datetime-local":"Please enter a datetime."},rangeUnderflow:{defaultMessage:"Value must be greater than or equal to {%min}."},rangeOverflow:{defaultMessage:"Value must be less than or equal to {%max}."},stepMismatch:"Invalid input.",tooLong:"Please enter at most {%maxlength} character(s). You entered {%valueLen}.",tooShort:"Please enter at least {%minlength} character(s). You entered {%valueLen}.",patternMismatch:"Invalid input. {%title}",valueMissing:{defaultMessage:"Please fill out this field.",checkbox:"Please check this box if you want to proceed."}},g.en||g["en-US"]||{}),"object"==typeof g.en.valueMissing&&["select","radio"].forEach(function(a){g.en.valueMissing[a]=g.en.valueMissing[a]||"Please select an option."}),"object"==typeof g.en.rangeUnderflow&&["date","time","datetime-local","month"].forEach(function(a){g.en.rangeUnderflow[a]=g.en.rangeUnderflow[a]||"Value must be at or after {%min}."}),"object"==typeof g.en.rangeOverflow&&["date","time","datetime-local","month"].forEach(function(a){g.en.rangeOverflow[a]=g.en.rangeOverflow[a]||"Value must be at or before {%max}."}),g["en-US"]||(g["en-US"]=a.extend(!0,{},g.en)),g["en-GB"]||(g["en-GB"]=a.extend(!0,{},g.en)),g["en-AU"]||(g["en-AU"]=a.extend(!0,{},g.en)),g[""]=g[""]||g["en-US"],g.de=a.extend(!0,{typeMismatch:{defaultMessage:"{%value} ist in diesem Feld nicht zul\xe4ssig.",email:"{%value} ist keine g\xfcltige E-Mail-Adresse.",url:"{%value} ist kein(e) g\xfcltige(r) Webadresse/Pfad."},badInput:{defaultMessage:"Geben Sie einen zul\xe4ssigen Wert ein.",number:"Geben Sie eine Nummer ein.",date:"Geben Sie ein Datum ein.",time:"Geben Sie eine Uhrzeit ein.",month:"Geben Sie einen Monat mit Jahr ein.",range:"Geben Sie eine Nummer.","datetime-local":"Geben Sie ein Datum mit Uhrzeit ein."},rangeUnderflow:{defaultMessage:"{%value} ist zu niedrig. {%min} ist der unterste Wert, den Sie benutzen k\xf6nnen."},rangeOverflow:{defaultMessage:"{%value} ist zu hoch. {%max} ist der oberste Wert, den Sie benutzen k\xf6nnen."},stepMismatch:"Der Wert {%value} ist in diesem Feld nicht zul\xe4ssig. Hier sind nur bestimmte Werte zul\xe4ssig. {%title}",tooLong:"Der eingegebene Text ist zu lang! Sie haben {%valueLen} Zeichen eingegeben, dabei sind {%maxlength} das Maximum.",tooShort:"Der eingegebene Text ist zu kurz! Sie haben {%valueLen} Zeichen eingegeben, dabei sind {%minlength} das Minimum.",patternMismatch:"{%value} hat f\xfcr dieses Eingabefeld ein falsches Format. {%title}",valueMissing:{defaultMessage:"Bitte geben Sie einen Wert ein.",checkbox:"Bitte aktivieren Sie das K\xe4stchen."}},g.de||{}),"object"==typeof g.de.valueMissing&&["select","radio"].forEach(function(a){g.de.valueMissing[a]=g.de.valueMissing[a]||"Bitte w\xe4hlen Sie eine Option aus."}),"object"==typeof g.de.rangeUnderflow&&["date","time","datetime-local","month"].forEach(function(a){g.de.rangeUnderflow[a]=g.de.rangeUnderflow[a]||"{%value} ist zu fr\xfch. {%min} ist die fr\xfcheste Zeit, die Sie benutzen k\xf6nnen."}),"object"==typeof g.de.rangeOverflow&&["date","time","datetime-local","month"].forEach(function(a){g.de.rangeOverflow[a]=g.de.rangeOverflow[a]||"{%value} ist zu sp\xe4t. {%max} ist die sp\xe4teste Zeit, die Sie benutzen k\xf6nnen."});var i=g[""],j=function(b,c){return b&&"string"!=typeof b&&(b=b[a.prop(c,"type")]||b[(c.nodeName||"").toLowerCase()]||b.defaultMessage),b||""},k={value:1,min:1,max:1};b.createValidationMessage=function(c,d){var e,f=a.prop(c,"type"),h=j(i[d],c);return h||"badInput"!=d||(h=j(i.typeMismatch,c)),h||"typeMismatch"!=d||(h=j(i.badInput,c)),h||(h=j(g[""][d],c)||a.prop(c,"validationMessage"),b.info("could not find errormessage for: "+d+" / "+f+". in language: "+b.activeLang())),h&&["value","min","max","title","maxlength","minlength","label"].forEach(function(g){if(-1!==h.indexOf("{%"+g)){var i=("label"==g?a.trim(a('label[for="'+c.id+'"]',c.form).text()).replace(/\*$|:$/,""):a.prop(c,g))||"";"patternMismatch"!=d||"title"!=g||i||b.error("no title for patternMismatch provided. Always add a title attribute."),k[g]&&(e||(e=a(c).getShadowElement().data("wsWidget"+f)),e&&e.formatValue&&(i=e.formatValue(i,!1))),h=h.replace("{%"+g+"}",i),"value"==g&&(h=h.replace("{%valueLen}",i.length))}}),h||""},(!Modernizr.formvalidation||b.bugs.bustedValidity)&&h.push("validationMessage"),i=b.activeLang(g),a(g).on("change",function(){i=g.__active}),h.forEach(function(c){b.defineNodeNamesProperty(["fieldset","output","button"],c,{prop:{value:"",writeable:!1}}),["input","select","textarea"].forEach(function(d){var e=b.defineNodeNameProperty(d,c,{prop:{get:function(){var c=this,d="";if(!a.prop(c,"willValidate"))return d;var f=a.prop(c,"validity")||{valid:1};return f.valid?d:(d=b.getContentValidationMessage(c,f))?d:f.customError&&c.nodeName&&(d=Modernizr.formvalidation&&!b.bugs.bustedValidity&&e.prop._supget?e.prop._supget.call(c):b.data(c,"customvalidationMessage"))?d:(a.each(f,function(a,e){return"valid"!=a&&e?(d=b.createValidationMessage(c,a),d?!1:void 0):void 0}),d||"")},writeable:!1}})})})});
JorgeBailo/Peliculas
js/js-webshim/minified/shims/combos/4.js
JavaScript
mit
20,196
/* tablesorter pager plugin updated 2/19/2014 (v2.15.0) */ ;(function(h){var k=h.tablesorter;h.extend({tablesorterPager:new function(){this.defaults={container:null,ajaxUrl:null,customAjaxUrl:function(b,a){return a},ajaxObject:{dataType:"json"},processAjaxOnInit:!0,ajaxProcessing:function(b){return[0,[],null]},output:"{startRow} to {endRow} of {totalRows} rows",updateArrows:!0,page:0,size:10,savePages:!0,storageKey:"tablesorter-pager",fixedHeight:!1,countChildRows:!1,removeRows:!1,cssFirst:".first",cssPrev:".prev",cssNext:".next",cssLast:".last",cssGoto:".gotoPage", cssPageDisplay:".pagedisplay",cssPageSize:".pagesize",cssErrorRow:"tablesorter-errorRow",cssDisabled:"disabled",totalRows:0,totalPages:0,filteredRows:0,filteredPages:0,ajaxCounter:0,currentFilters:[],startRow:0,endRow:0,$size:null,last:{}};var u=this,l=function(b,a){var e=b.cssDisabled,d=!!a,f=d||0===b.page,g=Math.min(b.totalPages,b.filteredPages),d=d||b.page===g-1||0===b.totalPages;b.updateArrows&&(b.$container.find(b.cssFirst+","+b.cssPrev)[f?"addClass":"removeClass"](e).attr("aria-disabled",f), b.$container.find(b.cssNext+","+b.cssLast)[d?"addClass":"removeClass"](e).attr("aria-disabled",d))},q=function(b,a,e){var d,f,g,c=b.config;d=c.$table.hasClass("hasFilters")&&!a.ajaxUrl;g=(c.widgetOptions&&c.widgetOptions.filter_filteredRow||"filtered")+","+c.selectorRemove+(a.countChildRows?"":",."+c.cssChildRow);f=a.size||10;a.totalPages=Math.ceil(a.totalRows/f);a.filteredRows=d?c.$tbodies.eq(0).children("tr").not("."+g).length:a.totalRows;a.filteredPages=d?Math.ceil(a.filteredRows/f)||1:a.totalPages; if(0<=Math.min(a.totalPages,a.filteredPages)&&(g=a.size*a.page>a.filteredRows,a.startRow=g?1:0===a.filteredRows?0:a.size*a.page+1,a.page=g?0:a.page,a.endRow=Math.min(a.filteredRows,a.totalRows,a.size*(a.page+1)),d=a.$container.find(a.cssPageDisplay),g=(a.ajaxData&&a.ajaxData.output?a.ajaxData.output||a.output:a.output).replace(/\{page([\-+]\d+)?\}/gi,function(b,c){return a.totalPages?a.page+(c?parseInt(c,10):1):0}).replace(/\{\w+(\s*:\s*\w+)?\}/gi,function(b){b=b.replace(/[{}\s]/g,"");var c=b.split(":"), d=a.ajaxData,e=/(rows?|pages?)$/i.test(b)?0:"";return 1<c.length&&d&&d[c[0]]?d[c[0]][c[1]]:a[b]||(d?d[b]:e)||e}),d.length&&(d["INPUT"===d[0].tagName?"val":"html"](g),a.$goto.length))){g="";f=Math.min(a.totalPages,a.filteredPages);for(d=1;d<=f;d++)g+="<option>"+d+"</option>";a.$goto.html(g).val(a.page+1)}l(a);a.initialized&&!1!==e&&(c.$table.trigger("pagerComplete",a),a.savePages&&k.storage&&k.storage(b,a.storageKey,{page:a.page,size:a.size}))},s=function(b,a){var e,d=b.config,f=d.$tbodies.eq(0);a.fixedHeight&& (f.find("tr.pagerSavedHeightSpacer").remove(),e=h.data(b,"pagerSavedHeight"))&&(e-=f.height(),5<e&&h.data(b,"pagerLastSize")===a.size&&f.children("tr:visible").length<a.size&&f.append('<tr class="pagerSavedHeightSpacer '+d.selectorRemove.replace(/(tr)?\./g,"")+'" style="height:'+e+'px;"></tr>'))},z=function(b,a){var e=b.config.$tbodies.eq(0);e.find("tr.pagerSavedHeightSpacer").remove();h.data(b,"pagerSavedHeight",e.height());s(b,a);h.data(b,"pagerLastSize",a.size)},t=function(b,a){if(!a.ajaxUrl){var e, d=b.config,f=d.$tbodies.eq(0).children(),g=f.length,c=a.page*a.size,h=c+a.size,k=d.widgetOptions&&d.widgetOptions.filter_filteredRow||"filtered",p=0;for(e=0;e<g;e++)f[e].className.match(k)||(f[e].style.display=p>=c&&p<h?"":"none",p+=f[e].className.match(d.cssChildRow+"|"+d.selectorRemove.slice(1))&&!a.countChildRows?0:1)}},A=function(b,a){a.size=parseInt(a.$size.val(),10)||a.size;h.data(b,"pagerLastSize",a.size);l(a);a.removeRows||(t(b,a),h(b).bind("sortEnd.pager filterEnd.pager",function(){t(b,a)}))}, B=function(b,a,e,d,f){if("function"===typeof e.ajaxProcessing){var g,c,y,m,p,v,r=a.config,n=r.$table,l="";g=e.ajaxProcessing(b,a)||[0,[]];b=n.find("thead th").length;k.showError(a);if(f)r.debug&&k.log("Ajax Error",d,f),k.showError(a,0===d.status?"Not connected, verify Network":404===d.status?"Requested page not found [404]":500===d.status?"Internal Server Error [500]":"parsererror"===f?"Requested JSON parse failed":"timeout"===f?"Time out error":"abort"===f?"Ajax Request aborted":"Uncaught error: "+ d.statusText+" ["+d.status+"]"),r.$tbodies.eq(0).empty();else{h.isArray(g)?(d=isNaN(g[0])&&!isNaN(g[1]),f=g[d?1:0],e.totalRows=isNaN(f)?e.totalRows||0:f,d=0===e.totalRows?[""]:g[d?0:1]||[],p=g[2]):(e.ajaxData=g,e.totalRows=g.total,p=g.headers,d=g.rows);v=d.length;if(d instanceof jQuery)r.$tbodies.eq(0).empty().append(d);else if(v){for(g=0;g<v;g++){l+="<tr>";for(f=0;f<d[g].length;f++)l+=/^\s*<td/.test(d[g][f])?h.trim(d[g][f]):"<td>"+d[g][f]+"</td>";l+="</tr>"}e.processAjaxOnInit?r.$tbodies.eq(0).html(l): e.processAjaxOnInit=!0}p&&p.length===b&&(m=(c=n.hasClass("hasStickyHeaders"))?r.widgetOptions.$sticky.children("thead:first").children().children():"",y=n.find("tfoot tr:first").children(),r.$headers.filter("th").each(function(a){var b=h(this),d;b.find("."+k.css.icon).length?(d=b.find("."+k.css.icon).clone(!0),b.find(".tablesorter-header-inner").html(p[a]).append(d),c&&m.length&&(d=m.eq(a).find("."+k.css.icon).clone(!0),m.eq(a).find(".tablesorter-header-inner").html(p[a]).append(d))):(b.find(".tablesorter-header-inner").html(p[a]), c&&m.length&&m.eq(a).find(".tablesorter-header-inner").html(p[a]));y.eq(a).html(p[a])}))}r.showProcessing&&k.isProcessing(a);e.last.totalPages=e.totalPages=Math.ceil(e.totalRows/(e.size||10));e.last.currentFilters=e.currentFilters;e.last.sortList=(r.sortList||[]).join(",");q(a,e);s(a,e);n.trigger("applyWidgets");n.trigger("updateRows",[!1,function(){e.initialized&&(n.trigger("updateComplete"),n.trigger("pagerChange",e))}])}e.initialized||(e.initialized=!0,h(a).trigger("pagerInitialized",e))},G=function(b, a){var e=F(b,a),d=h(document),f,g=b.config;""!==e&&(g.showProcessing&&k.isProcessing(b,!0),d.bind("ajaxError.pager",function(c,e,f,g){B(null,b,a,e,g);d.unbind("ajaxError.pager")}),f=++a.ajaxCounter,a.ajaxObject.url=e,a.ajaxObject.success=function(c){f<a.ajaxCounter||(B(c,b,a),d.unbind("ajaxError.pager"),"function"===typeof a.oldAjaxSuccess&&a.oldAjaxSuccess(c))},g.debug&&k.log("ajax initialized",a.ajaxObject),h.ajax(a.ajaxObject))},F=function(b,a){var e=b.config,d=a.ajaxUrl?a.ajaxUrl.replace(/\{page([\-+]\d+)?\}/, function(b,c){return a.page+(c?parseInt(c,10):0)}).replace(/\{size\}/g,a.size):"",f=e.sortList,g=a.currentFilters||h(b).data("lastSearch")||[],c=d.match(/\{\s*sort(?:List)?\s*:\s*(\w*)\s*\}/),q=d.match(/\{\s*filter(?:List)?\s*:\s*(\w*)\s*\}/),m=[];c&&(c=c[1],h.each(f,function(a,b){m.push(c+"["+b[0]+"]="+b[1])}),d=d.replace(/\{\s*sort(?:List)?\s*:\s*(\w*)\s*\}/g,m.length?m.join("&"):c),m=[]);q&&(q=q[1],h.each(g,function(a,b){b&&m.push(q+"["+a+"]="+encodeURIComponent(b))}),d=d.replace(/\{\s*filter(?:List)?\s*:\s*(\w*)\s*\}/g, m.length?m.join("&"):q),a.currentFilters=g);"function"===typeof a.customAjaxUrl&&(d=a.customAjaxUrl(b,d));e.debug&&k.log("Pager ajax url: "+d);return d},w=function(b,a,e){var d,f;d=e.page*e.size;var g=d+e.size;if(!(1>(a&&a.length||0))){e.page>=e.totalPages&&C(b,e);e.isDisabled=!1;e.initialized&&h(b).trigger("pagerChange",e);if(e.removeRows){g>a.length&&(g=a.length);k.clearTableBody(b);for(f=k.processTbody(b,b.config.$tbodies.eq(0),!0);d<g;d++)f.append(a[d]);k.processTbody(b,f,!1)}else t(b,e);q(b, e);e.isDisabled||s(b,e);h(b).trigger("applyWidgets")}},D=function(b,a){a.ajax?l(a,!0):(a.isDisabled=!0,h.data(b,"pagerLastPage",a.page),h.data(b,"pagerLastSize",a.size),a.page=0,a.size=a.totalRows,a.totalPages=1,h(b).addClass("pagerDisabled").removeAttr("aria-describedby").find("tr.pagerSavedHeightSpacer").remove(),w(b,b.config.rowsCopy,a),b.config.debug&&k.log("pager disabled"));a.$size.add(a.$goto).each(function(){h(this).attr("aria-disabled","true").addClass(a.cssDisabled)[0].disabled=!0})},n= function(b,a,e){if(!a.isDisabled){var d=b.config,f=a.last,g=Math.min(a.totalPages,a.filteredPages);0>a.page&&(a.page=0);a.page>g-1&&0!==g&&(a.page=g-1);if(f.page!==a.page||f.size!==a.size||f.totalPages!==a.totalPages||(f.currentFilters||[]).join(",")!==(a.currentFilters||[]).join(",")||f.sortList!==(d.sortList||[]).join(","))d.debug&&k.log("Pager changing to page "+a.page),a.last={page:a.page,size:a.size,sortList:(d.sortList||[]).join(","),totalPages:a.totalPages,currentFilters:a.currentFilters|| []},a.ajax?G(b,a):a.ajax||w(b,b.config.rowsCopy,a),h.data(b,"pagerLastPage",a.page),a.initialized&&!1!==e&&(d.$table.trigger("pageMoved",a),d.$table.trigger("applyWidgets"))}},x=function(b,a,e){e.size=a||e.size||10;e.$size.val(e.size);h.data(b,"pagerLastPage",e.page);h.data(b,"pagerLastSize",e.size);e.totalPages=Math.ceil(e.totalRows/e.size);n(b,e)},H=function(b,a){a.page=0;n(b,a)},C=function(b,a){a.page=Math.min(a.totalPages,a.filteredPages)-1;n(b,a)},I=function(b,a){a.page++;a.page>=Math.min(a.totalPages, a.filteredPages)-1&&(a.page=Math.min(a.totalPages,a.filteredPages)-1);n(b,a)},J=function(b,a){a.page--;0>=a.page&&(a.page=0);n(b,a)},E=function(b,a,e){var d,f=b.config;a.$size.add(a.$goto).removeClass(a.cssDisabled).removeAttr("disabled").attr("aria-disabled","false");a.isDisabled=!1;a.page=h.data(b,"pagerLastPage")||a.page||0;a.size=h.data(b,"pagerLastSize")||parseInt(a.$size.find("option[selected]").val(),10)||a.size||10;a.$size.val(a.size);a.totalPages=Math.ceil(Math.min(a.totalRows,a.filteredRows)/ a.size);b.id&&(d=b.id+"_pager_info",a.$container.find(a.cssPageDisplay).attr("id",d),f.$table.attr("aria-describedby",d));e&&(f.$table.trigger("updateRows"),x(b,a.size,a),A(b,a),s(b,a),f.debug&&k.log("pager enabled"))};u.appender=function(b,a){var e=b.config,d=e.pager;d.ajax||(e.rowsCopy=a,d.totalRows=d.countChildRows?e.$tbodies.eq(0).children().length:a.length,d.size=h.data(b,"pagerLastSize")||d.size||10,d.totalPages=Math.ceil(d.totalRows/d.size),w(b,a,d),q(b,d,!1))};u.construct=function(b){return this.each(function(){if(this.config&& this.hasInitialized){var a,e,d,f=this,g=f.config,c=g.pager=h.extend({},h.tablesorterPager.defaults,b),l=g.$table,m=c.$container=h(c.container).addClass("tablesorter-pager").show();g.debug&&k.log("Pager initializing");c.oldAjaxSuccess=c.oldAjaxSuccess||c.ajaxObject.success;g.appender=u.appender;k.filter&&0<=h.inArray("filter",g.widgets)&&(c.currentFilters=g.$table.data("lastSearch")||k.filter.setDefaults(f,g,g.widgetOptions)||[],k.setFilters(f,c.currentFilters,!1));c.savePages&&k.storage&&(a=k.storage(f, c.storageKey)||{},c.page=isNaN(a.page)?c.page:a.page,c.size=(isNaN(a.size)?c.size:a.size)||10,h.data(f,"pagerLastSize",c.size));l.unbind("filterStart filterEnd sortEnd disable enable destroy update updateRows updateAll addRows pageSize ".split(" ").join(".pager ")).bind("filterStart.pager",function(a,b){c.currentFilters=b;c.page=0}).bind("filterEnd.pager sortEnd.pager",function(){c.initialized&&(n(f,c,!1),q(f,c,!1),s(f,c))}).bind("disable.pager",function(a){a.stopPropagation();D(f,c)}).bind("enable.pager", function(a){a.stopPropagation();E(f,c,!0)}).bind("destroy.pager",function(a){a.stopPropagation();D(f,c);c.$container.hide();f.config.appender=null;c.initialized=!1;h(f).unbind("destroy.pager sortEnd.pager filterEnd.pager enable.pager disable.pager");k.storage&&k.storage(f,c.storageKey,"")}).bind("update.pager updateRows.pager updateAll.pager addRows.pager ",function(a){a.stopPropagation();t(f,c)}).bind("pageSize.pager",function(a,b){a.stopPropagation();x(f,parseInt(b,10)||10,c);t(f,c);q(f,c,!1);c.$size.length&& c.$size.val(c.size)}).bind("pageSet.pager",function(a,b){a.stopPropagation();c.page=(parseInt(b,10)||1)-1;c.$goto.length&&c.$goto.val(c.size);n(f,c);q(f,c,!1)});e=[c.cssFirst,c.cssPrev,c.cssNext,c.cssLast];d=[H,J,I,C];m.find(e.join(",")).attr("tabindex",0).unbind("click.pager").bind("click.pager",function(a){a.stopPropagation();var b=h(this),g=e.length;if(!b.hasClass(c.cssDisabled))for(a=0;a<g;a++)if(b.is(e[a])){d[a](f,c);break}});c.$goto=m.find(c.cssGoto);c.$goto.length&&c.$goto.unbind("change").bind("change", function(){c.page=h(this).val()-1;n(f,c);q(f,c,!1)});c.$size=m.find(c.cssPageSize);c.$size.length&&c.$size.unbind("change.pager").bind("change.pager",function(){c.$size.val(h(this).val());h(this).hasClass(c.cssDisabled)||(x(f,parseInt(h(this).val(),10),c),z(f,c));return!1});c.initialized=!1;l.trigger("pagerBeforeInitialized",c);E(f,c,!1);"string"===typeof c.ajaxUrl?(c.ajax=!0,g.widgetOptions.filter_serversideFiltering=!0,g.serverSideSorting=!0,n(f,c)):(c.ajax=!1,h(this).trigger("appendCache",!0), A(f,c));z(f,c);c.ajax||(c.initialized=!0,h(f).trigger("pagerInitialized",c))}})}}});k.showError=function(k,l){h(k).each(function(){var k=this.config,s=k.pager&&k.pager.cssErrorRow||k.widgetOptions.pager_css&&k.widgetOptions.pager_css.errorRow||"tablesorter-errorRow";k&&("undefined"===typeof l?k.$table.find("thead").find(k.selectorRemove).remove():(/tr\>/.test(l)?h(l):h('<tr><td colspan="'+k.columns+'">'+l+"</td></tr>")).click(function(){h(this).remove()}).appendTo(k.$table.find("thead:first")).addClass(s+ " "+k.selectorRemove.replace(/^[.#]/,"")).attr({role:"alert","aria-live":"assertive"}))})};h.fn.extend({tablesorterPager:h.tablesorterPager.construct})})(jQuery);
sparkgeo/cdnjs
ajax/libs/jquery.tablesorter/2.15.1/addons/pager/jquery.tablesorter.pager.min.js
JavaScript
mit
13,039
/*! tableSorter 2.8+ widgets - updated 5/28/2013 */ ;(function(f){ var h=f.tablesorter=f.tablesorter||{}; h.themes={bootstrap:{table:"table table-bordered table-striped",header:"bootstrap-header",footerRow:"",footerCells:"",icons:"",sortNone:"bootstrap-icon-unsorted",sortAsc:"icon-chevron-up",sortDesc:"icon-chevron-down",active:"",hover:"",filterRow:"",even:"",odd:""},jui:{table:"ui-widget ui-widget-content ui-corner-all",header:"ui-widget-header ui-corner-all ui-state-default",footerRow:"",footerCells:"",icons:"ui-icon",sortNone:"ui-icon-carat-2-n-s", sortAsc:"ui-icon-carat-1-n",sortDesc:"ui-icon-carat-1-s",active:"ui-state-active",hover:"ui-state-hover",filterRow:"",even:"ui-widget-content",odd:"ui-state-default"}}; h.storage=function(d,c,b){var a,e=!1;a={};var g=d.id||f(".tablesorter").index(f(d)),h=window.location.pathname;if("localStorage"in window)try{window.localStorage.setItem("_tmptest","temp"),e=!0,window.localStorage.removeItem("_tmptest")}catch(k){}f.parseJSON&&(e?a=f.parseJSON(localStorage[c]||"{}"):(a=document.cookie.split(/[;\s|=]/), d=f.inArray(c,a)+1,a=0!==d?f.parseJSON(a[d]||"{}"):{}));if((b||""===b)&&window.JSON&&JSON.hasOwnProperty("stringify"))a[h]||(a[h]={}),a[h][g]=b,e?localStorage[c]=JSON.stringify(a):(d=new Date,d.setTime(d.getTime()+31536E6),document.cookie=c+"="+JSON.stringify(a).replace(/\"/g,'"')+"; expires="+d.toGMTString()+"; path=/");else return a&&a[h]?a[h][g]:{}}; h.addHeaderResizeEvent=function(d,c,b){b=f.extend({},{timer:250},b);var a=d.config,e=a.widgetOptions,g;clearInterval(e.resize_timer);if(c)return e.resize_flag= !1;a.$headers.each(function(){f.data(this,"savedSizes",[this.offsetWidth,this.offsetHeight])});e.resize_timer=setInterval(function(){e.resize_flag||(e.resize_flag=!0,g=[],a.$headers.each(function(){var a=f.data(this,"savedSizes"),b=this.offsetWidth,c=this.offsetHeight;if(b!==a[0]||c!==a[1])f.data(this,"savedSizes",[b,c]),g.push(this)}),g.length&&a.$table.trigger("resize",[g]),e.resize_flag=!1)},b.timer)}; h.addWidget({id:"uitheme",priority:10,options:{uitheme:"jui"},format:function(d,c,b){var a,e, g,m,k=h.themes,l=c.$table,v="default"!==c.theme?c.theme:b.uitheme||"jui",j=k[k[v]?v:k[b.uitheme]?b.uitheme:"jui"],s=c.$headers,z="tr."+(b.stickyHeaders||"tablesorter-stickyHeader"),q=j.sortNone+" "+j.sortDesc+" "+j.sortAsc;c.debug&&(a=new Date);if(!l.hasClass("tablesorter-"+v)||c.theme===v||!d.hasInitialized)""!==j.even&&(b.zebra[0]+=" "+j.even),""!==j.odd&&(b.zebra[1]+=" "+j.odd),k=l.removeClass(""===c.theme?"":"tablesorter-"+c.theme).addClass("tablesorter-"+v+" "+j.table).find("tfoot"),k.length&& k.find("tr").addClass(j.footerRow).children("th, td").addClass(j.footerCells),s.addClass(j.header).filter(":not(.sorter-false)").bind("mouseenter.tsuitheme mouseleave.tsuitheme",function(a){f(this)["mouseenter"===a.type?"addClass":"removeClass"](j.hover)}),s.find(".tablesorter-wrapper").length||s.wrapInner('<div class="tablesorter-wrapper" style="position:relative;height:100%;width:100%"></div>'),c.cssIcon&&s.find("."+c.cssIcon).addClass(j.icons),l.hasClass("hasFilters")&&s.find(".tablesorter-filter-row").addClass(j.filterRow); f.each(s,function(a){g=f(this);m=c.cssIcon?g.find("."+c.cssIcon):g;this.sortDisabled?(g.removeClass(q),m.removeClass(q+" tablesorter-icon "+j.icons)):(k=l.hasClass("hasStickyHeaders")?l.find(z).find("th").eq(a).add(g):g,e=g.hasClass(c.cssAsc)?j.sortAsc:g.hasClass(c.cssDesc)?j.sortDesc:g.hasClass(c.cssHeader)?j.sortNone:"",g[e===j.sortNone?"removeClass":"addClass"](j.active),m.removeClass(q).addClass(e))});c.debug&&h.benchmark("Applying "+v+" theme",a)},remove:function(d,c,b){d=c.$table;var a="object"=== typeof b.uitheme?"jui":b.uitheme||"jui";b="object"===typeof b.uitheme?b.uitheme:h.themes[h.themes.hasOwnProperty(a)?a:"jui"];var e=d.children("thead").children(),f=b.sortNone+" "+b.sortDesc+" "+b.sortAsc;d.removeClass("tablesorter-"+a+" "+b.table).find(c.cssHeader).removeClass(b.header);e.unbind("mouseenter.tsuitheme mouseleave.tsuitheme").removeClass(b.hover+" "+f+" "+b.active).find(".tablesorter-filter-row").removeClass(b.filterRow);e.find(".tablesorter-icon").removeClass(b.icons)}}); h.addWidget({id:"columns", priority:30,options:{columns:["primary","secondary","tertiary"]},format:function(d,c,b){var a,e,g,m,k,l,v,j,s,z=c.$table,q=c.$tbodies,r=c.sortList,t=r.length,n=c.widgetColumns&&c.widgetColumns.hasOwnProperty("css")?c.widgetColumns.css||n:b&&b.hasOwnProperty("columns")?b.columns||n:n;l=n.length-1;v=n.join(" ");c.debug&&(k=new Date);for(s=0;s<q.length;s++)a=h.processTbody(d,q.eq(s),!0),e=a.children("tr"),e.each(function(){m=f(this);if("none"!==this.style.display&&(g=m.children().removeClass(v),r&&r[0]&& (g.eq(r[0][0]).addClass(n[0]),1<t)))for(j=1;j<t;j++)g.eq(r[j][0]).addClass(n[j]||n[l])}),h.processTbody(d,a,!1);e=!1!==b.columns_thead?"thead tr":"";!1!==b.columns_tfoot&&(e+=(""===e?"":",")+"tfoot tr");if(e.length&&(m=z.find(e).children().removeClass(v),r&&r[0]&&(m.filter('[data-column="'+r[0][0]+'"]').addClass(n[0]),1<t)))for(j=1;j<t;j++)m.filter('[data-column="'+r[j][0]+'"]').addClass(n[j]||n[l]);c.debug&&h.benchmark("Applying Columns widget",k)},remove:function(d,c,b){var a=c.$tbodies,e=(b.columns|| ["primary","secondary","tertiary"]).join(" ");c.$headers.removeClass(e);c.$table.children("tfoot").children("tr").children("th, td").removeClass(e);for(c=0;c<a.length;c++)b=h.processTbody(d,a.eq(c),!0),b.children("tr").each(function(){f(this).children().removeClass(e)}),h.processTbody(d,b,!1)}}); h.addWidget({id:"filter",priority:50,options:{filter_childRows:!1,filter_columnFilters:!0,filter_cssFilter:"tablesorter-filter",filter_filteredRow:"filtered",filter_formatter:null,filter_functions:null,filter_hideFilters:!1, filter_ignoreCase:!0,filter_liveSearch:!0,filter_onlyAvail:"filter-onlyAvail",filter_reset:null,filter_searchDelay:300,filter_startsWith:!1,filter_useParsedData:!1,filter_serversideFiltering:!1,filter_regex:{regex:/^\/((?:\\\/|[^\/])+)\/([mig]{0,3})?$/,child:/tablesorter-childRow/,filtered:/filtered/,type:/undefined|number/,exact:/(^[\"|\'|=])|([\"|\'|=]$)/g,nondigit:/[^\w,. \-()]/g,operators:/[<>=]/g}},format:function(d,c,b){if(c.parsers&&!c.$table.hasClass("hasFilters")){var a,e,g,m,k,l,v,j,s,z, q,r,t,n,u,p,E,x,D=h.formatFloat,L="",B=c.$headers,A=b.filter_cssFilter,w=c.$table.addClass("hasFilters"),H=w.find("tbody"),I=c.parsers.length,F,M,N,G=function(a){var e=f.isArray(a),p=e?a:h.getFilters(d),g=(p||[]).join("");e&&h.setFilters(w,p);b.filter_hideFilters&&w.find(".tablesorter-filter-row").trigger(""===g?"mouseleave":"mouseenter");if(!(L===g&&!1!==a))if(w.trigger("filterStart",[p]),c.showProcessing)setTimeout(function(){O(a,p,g);return!1},30);else return O(a,p,g),!1},O=function(J,m,r){var l, s,t,q,E,y,z,x,C,A;c.debug&&(z=new Date);for(g=0;g<H.length;g++)if(!H.eq(g).hasClass(c.cssInfoBlock)){J=h.processTbody(d,H.eq(g),!0);l=J.children("tr:not(."+c.cssChildRow+")");E=l.length;if(""===r||b.filter_serversideFiltering)J.children().show().removeClass(b.filter_filteredRow);else{A=!0;q=w.data("lastSearch")||[];f.each(m,function(a,b){A=0===(b||"").indexOf(q[a]||"")&&A&&!/(\s+or\s+|\|)/g.test(b||"")});A&&0===l.filter(":visible").length&&(A=!1);for(e=0;e<E;e++)if(q=l[e].className,!(b.filter_regex.child.test(q)|| A&&b.filter_regex.filtered.test(q))){q=!0;t=l.eq(e).nextUntil("tr:not(."+c.cssChildRow+")");p=t.length&&b.filter_childRows?t.text():"";p=b.filter_ignoreCase?p.toLocaleLowerCase():p;s=l.eq(e).children("td");for(a=0;a<I;a++)if(m[a]){v=b.filter_useParsedData||F[a]?c.cache[g].normalized[e][a]:f.trim(s.eq(a).text());j=!b.filter_regex.type.test(typeof v)&&b.filter_ignoreCase?v.toLocaleLowerCase():v;y=q;k=b.filter_ignoreCase?m[a].toLocaleLowerCase():m[a];if(b.filter_functions&&b.filter_functions[a])!0=== b.filter_functions[a]?y=B.filter('[data-column="'+a+'"]:last').hasClass("filter-match")?0<=j.search(k):m[a]===v:"function"===typeof b.filter_functions[a]?y=b.filter_functions[a](v,c.cache[g].normalized[e][a],m[a],a):"function"===typeof b.filter_functions[a][m[a]]&&(y=b.filter_functions[a][m[a]](v,c.cache[g].normalized[e][a],m[a],a));else if(b.filter_regex.regex.test(k)){n=b.filter_regex.regex.exec(k);try{y=RegExp(n[1],n[2]).test(j)}catch(G){y=!1}}else if(k.replace(b.filter_regex.exact,"")==j)y=!0; else if(/^\!/.test(k))k=k.replace("!",""),u=j.search(f.trim(k)),y=""===k?!0:!(b.filter_startsWith?0===u:0<=u);else if(/^[<>]=?/.test(k)){u=D(k.replace(b.filter_regex.nondigit,"").replace(b.filter_regex.operators,""),d);if(F[a]||"numeric"===c.parsers[a].type)n=c.parsers[a].format(""+k.replace(b.filter_regex.operators,""),d,B.eq(a),a),u=""!==n&&!isNaN(n)?n:u;n=(F[a]||"numeric"===c.parsers[a].type)&&!isNaN(u)&&c.cache[g].normalized[e]?c.cache[g].normalized[e][a]:isNaN(j)?D(j.replace(b.filter_regex.nondigit, ""),d):D(j,d);/>/.test(k)&&(y=/>=/.test(k)?n>=u:n>u);/</.test(k)&&(y=/<=/.test(k)?n<=u:n<u);""===u&&(y=!0)}else if(/\s+(AND|&&)\s+/g.test(m[a])){u=k.split(/(?:\s+(?:and|&&)\s+)/g);y=0<=j.search(f.trim(u[0]));for(x=u.length-1;y&&x;)y=y&&0<=j.search(f.trim(u[x])),x--}else if(/\s+(-|to)\s+/.test(k)){u=k.split(/(?: - | to )/);x=D(u[0].replace(b.filter_regex.nondigit,""),d);C=D(u[1].replace(b.filter_regex.nondigit,""),d);if(F[a]||"numeric"===c.parsers[a].type)n=c.parsers[a].format(""+u[0],d,B.eq(a),a), x=""!==n&&!isNaN(n)?n:x,n=c.parsers[a].format(""+u[1],d,B.eq(a),a),C=""!==n&&!isNaN(n)?n:C;n=(F[a]||"numeric"===c.parsers[a].type)&&!isNaN(x)&&!isNaN(C)?c.cache[g].normalized[e][a]:isNaN(j)?D(j.replace(b.filter_regex.nondigit,""),d):D(j,d);x>C&&(y=x,x=C,C=y);y=n>=x&&n<=C||""===x||""===C?!0:!1}else/[\?|\*]/.test(k)||/\s+OR\s+/.test(m[a])?(u=k.replace(/\s+OR\s+/gi,"|"),!B.filter('[data-column="'+a+'"]:last').hasClass("filter-match")&&/\|/.test(u)&&(u="^("+u+")$"),y=RegExp(u.replace(/\?/g,"\\S{1}").replace(/\*/g, "\\S*")).test(j)):(v=(j+p).indexOf(k),y=!b.filter_startsWith&&0<=v||b.filter_startsWith&&0===v);q=y?q?!0:!1:!1}l[e].style.display=q?"":"none";l.eq(e)[q?"removeClass":"addClass"](b.filter_filteredRow);if(t.length)t[q?"show":"hide"]()}}h.processTbody(d,J,!1)}L=r;w.data("lastSearch",m);c.debug&&h.benchmark("Completed filter widget search",z);w.trigger("applyWidgets");w.trigger("filterEnd")},P=function(a,p,j){var k,n,l=[];a=parseInt(a,10);n=B.filter('[data-column="'+a+'"]:last');k='<option value="">'+ (n.data("placeholder")||n.attr("data-placeholder")||"")+"</option>";for(g=0;g<H.length;g++){m=c.cache[g].row.length;for(e=0;e<m;e++)if(!j||!c.cache[g].row[e][0].className.match(b.filter_filteredRow))b.filter_useParsedData?l.push(""+c.cache[g].normalized[e][a]):(n=c.cache[g].row[e][0].cells[a])&&l.push(f.trim(c.supportsTextContent?n.textContent:f(n).text()))}l=f.grep(l,function(a,b){return f.inArray(a,l)===b});l=h.sortText?l.sort(function(b,c){return h.sortText(d,b,c,a)}):l.sort(!0);j=w.find("thead").find("select."+ A+'[data-column="'+a+'"]').val();for(g=0;g<l.length;g++)n=l[g].replace(/\"/g,"&quot;"),k+=""!==l[g]?'<option value="'+n+'"'+(j===n?' selected="selected"':"")+">"+l[g]+"</option>":"";w.find("thead").find("select."+A+'[data-column="'+a+'"]')[p?"html":"append"](k)},K=function(c){for(a=0;a<I;a++)if(p=B.filter('[data-column="'+a+'"]:last'),(p.hasClass("filter-select")||b.filter_functions&&!0===b.filter_functions[a])&&!p.hasClass("filter-false"))b.filter_functions||(b.filter_functions={}),b.filter_functions[a]= !0,P(a,c,p.hasClass(b.filter_onlyAvail))},Q=function(a){"undefined"===typeof a||!0===a?(clearTimeout(N),N=setTimeout(function(){G(a)},b.filter_liveSearch?b.filter_searchDelay:10)):G(a)};c.debug&&(M=new Date);b.filter_regex.child=RegExp(c.cssChildRow);b.filter_regex.filtered=RegExp(b.filter_filteredRow);if(!1!==b.filter_columnFilters&&B.filter(".filter-false").length!==B.length){p='<tr class="tablesorter-filter-row">';for(a=0;a<I;a++)p+="<td></td>";c.$filters=f(p+="</tr>").appendTo(w.find("thead").eq(0)).find("td"); for(a=0;a<I;a++)E=!1,t=B.filter('[data-column="'+a+'"]:last'),l=b.filter_functions&&b.filter_functions[a]&&"function"!==typeof b.filter_functions[a]||t.hasClass("filter-select"),E=h.getData?"false"===h.getData(t[0],c.headers[a],"filter"):c.headers[a]&&c.headers[a].hasOwnProperty("filter")&&!1===c.headers[a].filter||t.hasClass("filter-false"),l?p=f("<select>").appendTo(c.$filters.eq(a)):(b.filter_formatter&&f.isFunction(b.filter_formatter[a])?((p=b.filter_formatter[a](c.$filters.eq(a),a))&&0===p.length&& (p=c.$filters.eq(a).children("input")),p&&(0===p.parent().length||p.parent().length&&p.parent()[0]!==c.$filters[a])&&c.$filters.eq(a).append(p)):p=f('<input type="search">').appendTo(c.$filters.eq(a)),p&&p.attr("placeholder",t.data("placeholder")||t.attr("data-placeholder")||"")),p&&(p.addClass(A).attr("data-column",a),E&&(p.addClass("disabled")[0].disabled=!0))}w.bind("addRows updateCell update updateRows updateComplete appendCache filterReset filterEnd search ".split(" ").join(".tsfilter "),function(a, b){/(search|filterReset|filterEnd)/.test(a.type)||(a.stopPropagation(),K(!0));"filterReset"===a.type&&w.find("."+A).val("");"filterEnd"===a.type?K(!0):(b="search"===a.type?b:"updateComplete"===a.type?w.data("lastSearch"):"",Q(b));return!1}).find("input."+A).bind("keyup search",function(a,c){if(27===a.which)this.value="";else if("number"===typeof b.filter_liveSearch&&this.value.length<b.filter_liveSearch&&""!==this.value||"keyup"===a.type&&(32>a.which&&8!==a.which&&!0===b.filter_liveSearch&&13!==a.which|| 37<=a.which&&40>=a.which||13!==a.which&&!1===b.filter_liveSearch))return;Q(c)});F=B.map(function(a){return h.getData?"parsed"===h.getData(B.filter('[data-column="'+a+'"]:last'),c.headers[a],"filter"):f(this).hasClass("filter-parsed")}).get();b.filter_reset&&f(b.filter_reset).length&&f(b.filter_reset).bind("click.tsfilter",function(){w.trigger("filterReset")});if(b.filter_functions)for(x in b.filter_functions)if(b.filter_functions.hasOwnProperty(x)&&"string"===typeof x)if(p=B.filter('[data-column="'+ x+'"]:last'),l="",!0===b.filter_functions[x]&&!p.hasClass("filter-false"))P(x);else if("string"===typeof x&&!p.hasClass("filter-false")){for(z in b.filter_functions[x])"string"===typeof z&&(l+=""===l?'<option value="">'+(p.data("placeholder")||p.attr("data-placeholder")||"")+"</option>":"",l+='<option value="'+z+'">'+z+"</option>");w.find("thead").find("select."+A+'[data-column="'+x+'"]').append(l)}K(!0);w.find("select."+A).bind("change search",function(a,b){G(b)});b.filter_hideFilters&&w.find(".tablesorter-filter-row").addClass("hideme").bind("mouseenter mouseleave", function(a){var c;q=f(this);clearTimeout(s);s=setTimeout(function(){/enter|over/.test(a.type)?q.removeClass("hideme"):f(document.activeElement).closest("tr")[0]!==q[0]&&(c=w.find("."+b.filter_cssFilter).map(function(){return f(this).val()||""}).get().join(""),""===c&&q.addClass("hideme"))},200)}).find("input, select").bind("focus blur",function(a){r=f(this).closest("tr");clearTimeout(s);s=setTimeout(function(){if(""===w.find("."+b.filter_cssFilter).map(function(){return f(this).val()||""}).get().join(""))r["focus"=== a.type?"removeClass":"addClass"]("hideme")},200)});c.showProcessing&&w.bind("filterStart.tsfilter filterEnd.tsfilter",function(a,b){var e=b?w.find("."+c.cssHeader).filter("[data-column]").filter(function(){return""!==b[f(this).data("column")]}):"";h.isProcessing(w[0],"filterStart"===a.type,b?e:"")});c.debug&&h.benchmark("Applying Filter widget",M);w.trigger("filterInit");G()}},remove:function(d,c,b){var a,e=c.$tbodies;c.$table.removeClass("hasFilters").unbind("addRows updateCell update updateComplete appendCache search filterStart filterEnd ".split(" ").join(".tsfilter ")).find(".tablesorter-filter-row").remove(); for(c=0;c<e.length;c++)a=h.processTbody(d,e.eq(c),!0),a.children().removeClass(b.filter_filteredRow).show(),h.processTbody(d,a,!1);b.filterreset&&f(b.filter_reset).unbind("click.tsfilter")}}); h.getFilters=function(d){var c=d?f(d)[0].config:{};return c&&c.widgetOptions&&!c.widgetOptions.filter_columnFilters?f(d).data("lastSearch"):c&&c.$filters?c.$filters.find("."+c.widgetOptions.filter_cssFilter).map(function(b,a){return f(a).val()}).get()||[]:!1}; h.setFilters=function(d,c,b){d=f(d);var a=d.length? d[0].config:{},a=a&&a.$filters?a.$filters.find("."+a.widgetOptions.filter_cssFilter).each(function(a,b){f(b).val(c[a]||"")})||!1:!1;b&&d.trigger("search",[c,!1]);return!!a}; h.addWidget({id:"stickyHeaders",priority:60,options:{stickyHeaders:"tablesorter-stickyHeader",stickyHeaders_offset:0,stickyHeaders_cloneId:"-sticky",stickyHeaders_addResizeEvent:!0},format:function(d,c,b){if(!c.$table.hasClass("hasStickyHeaders")){var a=c.$table,e=f(window),g=a.children("thead:first"),m=g.children("tr:not(.sticky-false)").children(), k=a.find("tfoot"),l="."+(b.filter_cssFilter||"tablesorter-filter"),v=isNaN(b.stickyHeaders_offset)?f(b.stickyHeaders_offset):"",j=v.length?v.height()||0:parseInt(b.stickyHeaders_offset,10)||0,s=b.$sticky=a.clone().addClass("containsStickyHeaders").css({position:"fixed",margin:0,top:j,visibility:"hidden",zIndex:2}),z=s.children("thead:first").addClass(b.stickyHeaders),q,r="",t=0,n=!1,u=function(){j=v.length?v.height()||0:parseInt(b.stickyHeaders_offset,10)||0;var c=navigator.userAgent;t=0;"collapse"!== a.css("border-collapse")&&!/(webkit|msie)/i.test(c)&&(t=2*parseInt(m.eq(0).css("border-left-width"),10));s.css({left:g.offset().left-e.scrollLeft()-t,width:a.width()});q.filter(":visible").each(function(a){a=m.filter(":visible").eq(a);f(this).css({width:a.width()-t,height:a.height()}).find(".tablesorter-header-inner").width(a.find(".tablesorter-header-inner").width())})};s.attr("id")&&(s[0].id+=b.stickyHeaders_cloneId);s.find("thead:gt(0), tr.sticky-false, tbody, tfoot").remove();q=z.children().children(); s.css({height:0,width:0,padding:0,margin:0,border:0});q.find(".tablesorter-resizer").remove();a.addClass("hasStickyHeaders").bind("sortEnd.tsSticky",function(){m.filter(":visible").each(function(a){a=q.filter(":visible").eq(a);a.attr("class",f(this).attr("class")).removeClass(c.cssProcessing);c.cssIcon&&a.find("."+c.cssIcon).attr("class",f(this).find("."+c.cssIcon).attr("class"))})}).bind("pagerComplete.tsSticky",function(){u()});m.find(c.selectorSort).add(c.$headers.filter(c.selectorSort)).each(function(a){var b= f(this);a=z.children("tr.tablesorter-headerRow").children().eq(a).bind("mouseup",function(a){b.trigger(a,!0)});c.cancelSelection&&a.attr("unselectable","on").bind("selectstart",!1).css({"user-select":"none",MozUserSelect:"none"})});a.after(s);e.bind("scroll.tsSticky resize.tsSticky",function(b){if(a.is(":visible")){var c=a.offset(),d=e.scrollTop()+j,f=a.height()-(s.height()+(k.height()||0)),c=d>c.top&&d<c.top+f?"visible":"hidden";s.removeClass("tablesorter-sticky-visible tablesorter-sticky-hidden").addClass("tablesorter-sticky-"+ c).css({left:g.offset().left-e.scrollLeft()-t,visibility:c});if(c!==r||"resize"===b.type)u(),r=c}});b.stickyHeaders_addResizeEvent&&h.addHeaderResizeEvent(d);a.bind("filterEnd",function(){n||z.find(".tablesorter-filter-row").children().each(function(a){f(this).find(l).val(c.$filters.find(l).eq(a).val())})});q.find(l).bind("keyup search change",function(a){if(!(32>a.which&&8!==a.which||37<=a.which&&40>=a.which)){n=!0;a=f(this);var d=a.attr("data-column");c.$filters.find(l).eq(d).val(a.val()).trigger("search"); setTimeout(function(){n=!1},b.filter_searchDelay)}});a.trigger("stickyHeadersInit")}},remove:function(d,c,b){c.$table.removeClass("hasStickyHeaders").unbind("sortEnd.tsSticky pagerComplete.tsSticky").find("."+b.stickyHeaders).remove();b.$sticky&&b.$sticky.remove();f(window).unbind("scroll.tsSticky resize.tsSticky");h.addHeaderResizeEvent(d,!1)}}); h.addWidget({id:"resizable",priority:40,options:{resizable:!0,resizable_addLastColumn:!1},format:function(d,c,b){if(!c.$table.hasClass("hasResizable")){c.$table.addClass("hasResizable"); var a,e,g,m,k={},l,v,j,s,z=c.$table,q=0,r=null,t=null,n=20>Math.abs(z.parent().width()-z.width()),u=function(){h.storage&&r&&(k[r.index()]=r.width(),k[t.index()]=t.width(),r.width(k[r.index()]),t.width(k[t.index()]),!1!==b.resizable&&h.storage(d,"tablesorter-resizable",k));q=0;r=t=null;f(window).trigger("resize")};if(k=h.storage&&!1!==b.resizable?h.storage(d,"tablesorter-resizable"):{})for(m in k)!isNaN(m)&&m<c.$headers.length&&c.$headers.eq(m).width(k[m]);a=z.children("thead:first").children("tr"); a.children().each(function(){e=f(this);g=e.attr("data-column");m="false"===h.getData(e,c.headers[g],"resizable");a.children().filter('[data-column="'+g+'"]').toggleClass("resizable-false",m)});a.each(function(){l=f(this).children(":not(.resizable-false)");f(this).find(".tablesorter-wrapper").length||l.wrapInner('<div class="tablesorter-wrapper" style="position:relative;height:100%;width:100%"></div>');b.resizable_addLastColumn||(l=l.slice(0,-1));v=v?v.add(l):l});v.each(function(){a=f(this);m=parseInt(a.css("padding-right"), 10)+10;e='<div class="tablesorter-resizer" style="cursor:w-resize;position:absolute;z-index:1;right:-'+m+'px;top:0;height:100%;width:20px;"></div>';a.find(".tablesorter-wrapper").append(e)}).bind("mousemove.tsresize",function(a){0!==q&&r&&(j=a.pageX-q,s=r.width(),r.width(s+j),r.width()!==s&&n&&t.width(t.width()-j),q=a.pageX)}).bind("mouseup.tsresize",function(){u()}).find(".tablesorter-resizer,.tablesorter-resizer-grip").bind("mousedown",function(a){r=f(a.target).closest("th");e=c.$headers.filter('[data-column="'+ r.attr("data-column")+'"]');1<e.length&&(r=r.add(e));t=a.shiftKey?r.parent().find("th:not(.resizable-false)").filter(":last"):r.nextAll(":not(.resizable-false)").eq(0);q=a.pageX});z.find("thead:first").bind("mouseup.tsresize mouseleave.tsresize",function(){u()}).bind("contextmenu.tsresize",function(){h.resizableReset(d);var a=f.isEmptyObject?f.isEmptyObject(k):k==={};k={};return a})}},remove:function(d,c){c.$table.removeClass("hasResizable").find("thead").unbind("mouseup.tsresize mouseleave.tsresize contextmenu.tsresize").find("tr").children().unbind("mousemove.tsresize mouseup.tsresize").find(".tablesorter-resizer,.tablesorter-resizer-grip").remove(); h.resizableReset(d)}}); h.resizableReset=function(d){d.config.$headers.filter(":not(.resizable-false)").css("width","");h.storage&&h.storage(d,"tablesorter-resizable",{})}; h.addWidget({id:"saveSort",priority:20,options:{saveSort:!0},init:function(d,c,b,a){c.format(d,b,a,!0)},format:function(d,c,b,a){var e,g=c.$table;b=!1!==b.saveSort;var m={sortList:c.sortList};c.debug&&(e=new Date);g.hasClass("hasSaveSort")?b&&(d.hasInitialized&&h.storage)&&(h.storage(d,"tablesorter-savesort",m),c.debug&&h.benchmark("saveSort widget: Saving last sort: "+ c.sortList,e)):(g.addClass("hasSaveSort"),m="",h.storage&&(m=(b=h.storage(d,"tablesorter-savesort"))&&b.hasOwnProperty("sortList")&&f.isArray(b.sortList)?b.sortList:"",c.debug&&h.benchmark('saveSort: Last sort loaded: "'+m+'"',e),g.bind("saveSortReset",function(a){a.stopPropagation();h.storage(d,"tablesorter-savesort","")})),a&&m&&0<m.length?c.sortList=m:d.hasInitialized&&(m&&0<m.length)&&g.trigger("sorton",[m]))},remove:function(d){h.storage&&h.storage(d,"tablesorter-savesort","")}}) })(jQuery);
chrillep/cdnjs
ajax/libs/jquery.tablesorter/2.10.6/js/jquery.tablesorter.widgets.min.js
JavaScript
mit
22,986
<?php /** * CodeIgniter * * An open source application development framework for PHP * * This content is released under the MIT License (MIT) * * Copyright (c) 2014 - 2015, British Columbia Institute of Technology * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * * @package CodeIgniter * @author EllisLab Dev Team * @copyright Copyright (c) 2008 - 2014, EllisLab, Inc. (http://ellislab.com/) * @copyright Copyright (c) 2014 - 2015, British Columbia Institute of Technology (http://bcit.ca/) * @license http://opensource.org/licenses/MIT MIT License * @link http://codeigniter.com * @since Version 1.0.0 * @filesource */ defined('BASEPATH') OR exit('No direct script access allowed'); $lang['cal_su'] = 'Su'; $lang['cal_mo'] = 'Mo'; $lang['cal_tu'] = 'Tu'; $lang['cal_we'] = 'We'; $lang['cal_th'] = 'Th'; $lang['cal_fr'] = 'Fr'; $lang['cal_sa'] = 'Sa'; $lang['cal_sun'] = 'Sun'; $lang['cal_mon'] = 'Mon'; $lang['cal_tue'] = 'Tue'; $lang['cal_wed'] = 'Wed'; $lang['cal_thu'] = 'Thu'; $lang['cal_fri'] = 'Fri'; $lang['cal_sat'] = 'Sat'; $lang['cal_sunday'] = 'Sunday'; $lang['cal_monday'] = 'Monday'; $lang['cal_tuesday'] = 'Tuesday'; $lang['cal_wednesday'] = 'Wednesday'; $lang['cal_thursday'] = 'Thursday'; $lang['cal_friday'] = 'Friday'; $lang['cal_saturday'] = 'Saturday'; $lang['cal_jan'] = 'Jan'; $lang['cal_feb'] = 'Feb'; $lang['cal_mar'] = 'Mar'; $lang['cal_apr'] = 'Apr'; $lang['cal_may'] = 'May'; $lang['cal_jun'] = 'Jun'; $lang['cal_jul'] = 'Jul'; $lang['cal_aug'] = 'Aug'; $lang['cal_sep'] = 'Sep'; $lang['cal_oct'] = 'Oct'; $lang['cal_nov'] = 'Nov'; $lang['cal_dec'] = 'Dec'; $lang['cal_january'] = 'January'; $lang['cal_february'] = 'February'; $lang['cal_march'] = 'March'; $lang['cal_april'] = 'April'; $lang['cal_mayl'] = 'May'; $lang['cal_june'] = 'June'; $lang['cal_july'] = 'July'; $lang['cal_august'] = 'August'; $lang['cal_september'] = 'September'; $lang['cal_october'] = 'October'; $lang['cal_november'] = 'November'; $lang['cal_december'] = 'December';
HaleyBowler/Crafter
system/language/english/calendar_lang.php
PHP
mit
3,021
/** * @license * Highcharts funnel module * * (c) 2010-2014 Torstein Honsi * * License: www.highcharts.com/license */ /*global Highcharts */ (function (Highcharts) { 'use strict'; // create shortcuts var defaultOptions = Highcharts.getOptions(), defaultPlotOptions = defaultOptions.plotOptions, seriesTypes = Highcharts.seriesTypes, merge = Highcharts.merge, noop = function () {}, each = Highcharts.each, pick = Highcharts.pick; // set default options defaultPlotOptions.funnel = merge(defaultPlotOptions.pie, { animation: false, center: ['50%', '50%'], width: '90%', neckWidth: '30%', height: '100%', neckHeight: '25%', reversed: false, dataLabels: { //position: 'right', connectorWidth: 1, connectorColor: '#606060' }, size: true, // to avoid adapting to data label size in Pie.drawDataLabels states: { select: { color: '#C0C0C0', borderColor: '#000000', shadow: false } } }); seriesTypes.funnel = Highcharts.extendClass(seriesTypes.pie, { type: 'funnel', animate: noop, /** * Overrides the pie translate method */ translate: function () { var // Get positions - either an integer or a percentage string must be given getLength = function (length, relativeTo) { return (/%$/).test(length) ? relativeTo * parseInt(length, 10) / 100 : parseInt(length, 10); }, sum = 0, series = this, chart = series.chart, options = series.options, reversed = options.reversed, plotWidth = chart.plotWidth, plotHeight = chart.plotHeight, cumulative = 0, // start at top center = options.center, centerX = getLength(center[0], plotWidth), centerY = getLength(center[1], plotHeight), width = getLength(options.width, plotWidth), tempWidth, getWidthAt, height = getLength(options.height, plotHeight), neckWidth = getLength(options.neckWidth, plotWidth), neckHeight = getLength(options.neckHeight, plotHeight), neckY = height - neckHeight, data = series.data, path, fraction, half = options.dataLabels.position === 'left' ? 1 : 0, x1, y1, x2, x3, y3, x4, y5; // Return the width at a specific y coordinate series.getWidthAt = getWidthAt = function (y) { return y > height - neckHeight || height === neckHeight ? neckWidth : neckWidth + (width - neckWidth) * ((height - neckHeight - y) / (height - neckHeight)); }; series.getX = function (y, half) { return centerX + (half ? -1 : 1) * ((getWidthAt(reversed ? plotHeight - y : y) / 2) + options.dataLabels.distance); }; // Expose series.center = [centerX, centerY, height]; series.centerX = centerX; /* * Individual point coordinate naming: * * x1,y1 _________________ x2,y1 * \ / * \ / * \ / * \ / * \ / * x3,y3 _________ x4,y3 * * Additional for the base of the neck: * * | | * | | * | | * x3,y5 _________ x4,y5 */ // get the total sum each(data, function (point) { sum += point.y; }); each(data, function (point) { // set start and end positions y5 = null; fraction = sum ? point.y / sum : 0; y1 = centerY - height / 2 + cumulative * height; y3 = y1 + fraction * height; //tempWidth = neckWidth + (width - neckWidth) * ((height - neckHeight - y1) / (height - neckHeight)); tempWidth = getWidthAt(y1); x1 = centerX - tempWidth / 2; x2 = x1 + tempWidth; tempWidth = getWidthAt(y3); x3 = centerX - tempWidth / 2; x4 = x3 + tempWidth; // the entire point is within the neck if (y1 > neckY) { x1 = x3 = centerX - neckWidth / 2; x2 = x4 = centerX + neckWidth / 2; // the base of the neck } else if (y3 > neckY) { y5 = y3; tempWidth = getWidthAt(neckY); x3 = centerX - tempWidth / 2; x4 = x3 + tempWidth; y3 = neckY; } if (reversed) { y1 = height - y1; y3 = height - y3; y5 = (y5 ? height - y5 : null); } // save the path path = [ 'M', x1, y1, 'L', x2, y1, x4, y3 ]; if (y5) { path.push(x4, y5, x3, y5); } path.push(x3, y3, 'Z'); // prepare for using shared dr point.shapeType = 'path'; point.shapeArgs = { d: path }; // for tooltips and data labels point.percentage = fraction * 100; point.plotX = centerX; point.plotY = (y1 + (y5 || y3)) / 2; // Placement of tooltips and data labels point.tooltipPos = [ centerX, point.plotY ]; // Slice is a noop on funnel points point.slice = noop; // Mimicking pie data label placement logic point.half = half; cumulative += fraction; }); }, /** * Draw a single point (wedge) * @param {Object} point The point object * @param {Object} color The color of the point * @param {Number} brightness The brightness relative to the color */ drawPoints: function () { var series = this, options = series.options, chart = series.chart, renderer = chart.renderer; each(series.data, function (point) { var pointOptions = point.options, graphic = point.graphic, shapeArgs = point.shapeArgs; if (!graphic) { // Create the shapes point.graphic = renderer.path(shapeArgs). attr({ fill: point.color, stroke: pick(pointOptions.borderColor, options.borderColor), 'stroke-width': pick(pointOptions.borderWidth, options.borderWidth) }). add(series.group); } else { // Update the shapes graphic.animate(shapeArgs); } }); }, /** * Funnel items don't have angles (#2289) */ sortByAngle: function (points) { points.sort(function (a, b) { return a.plotY - b.plotY; }); }, /** * Extend the pie data label method */ drawDataLabels: function () { var data = this.data, labelDistance = this.options.dataLabels.distance, leftSide, sign, point, i = data.length, x, y; // In the original pie label anticollision logic, the slots are distributed // from one labelDistance above to one labelDistance below the pie. In funnels // we don't want this. this.center[2] -= 2 * labelDistance; // Set the label position array for each point. while (i--) { point = data[i]; leftSide = point.half; sign = leftSide ? 1 : -1; y = point.plotY; x = this.getX(y, leftSide); // set the anchor point for data labels point.labelPos = [ 0, // first break of connector y, // a/a x + (labelDistance - 5) * sign, // second break, right outside point shape y, // a/a x + labelDistance * sign, // landing point for connector y, // a/a leftSide ? 'right' : 'left', // alignment 0 // center angle ]; } seriesTypes.pie.prototype.drawDataLabels.call(this); } }); /** * Pyramid series type. * A pyramid series is a special type of funnel, without neck and reversed by default. */ defaultOptions.plotOptions.pyramid = Highcharts.merge(defaultOptions.plotOptions.funnel, { neckWidth: '0%', neckHeight: '0%', reversed: true }); Highcharts.seriesTypes.pyramid = Highcharts.extendClass(Highcharts.seriesTypes.funnel, { type: 'pyramid' }); }(Highcharts));
sympmarc/cdnjs
ajax/libs/highcharts/4.1.3/modules/funnel.src.js
JavaScript
mit
7,295
YUI.add("tree-openable",function(e,t){function i(){}function s(){}var n="close",r="open";i.prototype={initializer:function(){this.nodeExtensions=this.nodeExtensions.concat(e.Tree.Node.Openable)},closeNode:function(e,t){return e.canHaveChildren&&e.isOpen()&&this._fireTreeEvent(n,{node:e,src:t&&t.src},{defaultFn:this._defCloseFn,silent:t&&t.silent}),this},openNode:function(e,t){return e.canHaveChildren&&!e.isOpen()&&this._fireTreeEvent(r,{node:e,src:t&&t.src},{defaultFn:this._defOpenFn,silent:t&&t.silent}),this},toggleOpenNode:function(e,t){return e.isOpen()?this.closeNode(e,t):this.openNode(e,t)},_defCloseFn:function(e){delete e.node.state.open},_defOpenFn:function(e){e.node.state.open=!0}},e.Tree.Openable=i,s.prototype={close:function(e){return this.tree.closeNode(this,e),this},isOpen:function(){return!!this.state.open||this.isRoot()},open:function(e){return this.tree.openNode(this,e),this},toggleOpen:function(e){return this.tree.toggleOpenNode(this,e),this}},e.Tree.Node.Openable=s},"@VERSION@",{requires:["tree"]});
TerryMooreII/cdnjs
ajax/libs/yui/3.10.2/tree-openable/tree-openable-min.js
JavaScript
mit
1,032
YUI.add("series-stacked",function(e,t){function r(){}var n=e.Lang;r.prototype={_stacked:!0,_stackCoordinates:function(){this.get("direction")==="vertical"?this._stackXCoords():this._stackYCoords()},_stackXCoords:function(){var e=this.get("order"),t=this.get("seriesTypeCollection"),r=0,i=this.get("xcoords"),s=this.get("ycoords"),o,u,a,f,l=i.concat(),c,h,p=[],d;e>0?(c=t[e-1].get("stackedXCoords"),h=t[e-1].get("stackedYCoords"),o=c.length):o=i.length;for(;r<o;r+=1)if(n.isNumber(i[r])){if(e>0){a=c[r];if(!n.isNumber(a)){f=e;while(f>-1&&!n.isNumber(a))f-=1,f>-1?a=t[f].get("stackedXCoords")[r]:a=this._leftOrigin}i[r]=i[r]+a}l[r]=i[r]}else p.push(r);this._cleanXNaN(l,s),o=p.length;if(o>0)for(r=0;r<o;r+=1)d=p[r],u=e>0?c[d]:this._leftOrigin,l[d]=Math.max(l[d],u);this.set("stackedXCoords",l),this.set("stackedYCoords",s)},_stackYCoords:function(){var e=this.get("order"),t=this.get("graphic"),r=t.get("height"),i=this.get("seriesTypeCollection"),s=0,o=this.get("xcoords"),u=this.get("ycoords"),a,f,l,c,h=u.concat(),p,d,v=[],m;e>0?(p=i[e-1].get("stackedXCoords"),d=i[e-1].get("stackedYCoords"),a=d.length):a=u.length;for(;s<a;s+=1)if(n.isNumber(u[s])){if(e>0){l=d[s];if(!n.isNumber(l)){c=e;while(c>-1&&!n.isNumber(l))c-=1,c>-1?l=i[c].get("stackedYCoords")[s]:l=this._bottomOrigin}u[s]=l-(r-u[s])}h[s]=u[s]}else v.push(s);this._cleanYNaN(o,h),a=v.length;if(a>0)for(s=0;s<a;s+=1)m=v[s],f=e>0?d[m]:r,h[m]=Math.min(h[m],f);this.set("stackedXCoords",o),this.set("stackedYCoords",h)},_cleanXNaN:function(e,t){var r,i,s,o,u,a,f,l,c=n.isNumber,h,p=0,d=t.length;for(;p<d;++p)u=e[p],a=t[p],!c(u)&&p>0&&p<d-1&&(o=t[p-1],s=this._getPreviousValidCoordValue(e,p),l=t[p+1],f=this._getNextValidCoordValue(e,p),c(s)&&c(f)&&(h=(l-o)/(f-s),e[p]=(a+h*s-o)/h),r=NaN,i=NaN)},_getPreviousValidCoordValue:function(e,t){var r,i=n.isNumber,s=-1;while(!i(r)&&t>s)t-=1,r=e[t];return r},_getNextValidCoordValue:function(e,t){var r,i=n.isNumber,s=e.length;while(!i(r)&&t<s)t+=1,r=e[t];return r},_cleanYNaN:function(e,t){var r,i,s,o,u,a,f,l,c=n.isNumber,h,p=0,d=e.length;for(;p<d;++p)u=e[p],a=t[p],!c(a)&&p>0&&p<d-1&&(s=e[p-1],o=this._getPreviousValidCoordValue(t,p),f=e[p+1],l=this._getNextValidCoordValue(t,p),c(o)&&c(l)&&(h=(l-o)/(f-s),t[p]=o+(h*u-h*s)),r=NaN,i=NaN)}},e.StackingUtil=r},"@VERSION@",{requires:["axis-stacked"]});
linjunpop/cdnjs
ajax/libs/yui/3.9.1/series-stacked/series-stacked-min.js
JavaScript
mit
2,300
YUI.add("tree-openable",function(e,t){function i(){}function s(){}var n="close",r="open";i.prototype={initializer:function(){this.nodeExtensions=this.nodeExtensions.concat(e.Tree.Node.Openable)},closeNode:function(e,t){return e.canHaveChildren&&e.isOpen()&&this._fireTreeEvent(n,{node:e,src:t&&t.src},{defaultFn:this._defCloseFn,silent:t&&t.silent}),this},openNode:function(e,t){return e.canHaveChildren&&!e.isOpen()&&this._fireTreeEvent(r,{node:e,src:t&&t.src},{defaultFn:this._defOpenFn,silent:t&&t.silent}),this},toggleOpenNode:function(e,t){return e.isOpen()?this.closeNode(e,t):this.openNode(e,t)},_defCloseFn:function(e){delete e.node.state.open},_defOpenFn:function(e){e.node.state.open=!0}},e.Tree.Openable=i,s.prototype={close:function(e){return this.tree.closeNode(this,e),this},isOpen:function(){return!!this.state.open||this.isRoot()},open:function(e){return this.tree.openNode(this,e),this},toggleOpen:function(e){return this.tree.toggleOpenNode(this,e),this}},e.Tree.Node.Openable=s},"@VERSION@",{requires:["tree"]});
perdona/cdnjs
ajax/libs/yui/3.10.3/tree-openable/tree-openable-min.js
JavaScript
mit
1,032
YUI.add("graphics",function(e,t){var n="setter",r=e.Plugin.Host,i="value",s="valueFn",o="readOnly",u=e.Lang,a="string",f="writeOnce",l,c;c=function(){var t=this;t._ATTR_E_FACADE={},e.EventTarget.call(this,{emitFacade:!0}),t._state={},t.prototype=e.mix(c.prototype,t.prototype)},c.prototype={addAttrs:function(e){var t=this,r=this.constructor.ATTRS,a,l,c,h=t._state;for(l in r)r.hasOwnProperty(l)&&(a=r[l],a.hasOwnProperty(i)?h[l]=a.value:a.hasOwnProperty(s)&&(c=a.valueFn,u.isString(c)?h[l]=t[c].apply(t):h[l]=c.apply(t)));t._state=h;for(l in r)if(r.hasOwnProperty(l)){a=r[l];if(a.hasOwnProperty(o)&&a.readOnly)continue;a.hasOwnProperty(f)&&a.writeOnce&&(a.readOnly=!0),e&&e.hasOwnProperty(l)&&(a.hasOwnProperty(n)?t._state[l]=a.setter.apply(t,[e[l]]):t._state[l]=e[l])}},get:function(e){var t=this,n,r=t.constructor.ATTRS;if(r&&r[e])return n=r[e].getter,n?typeof n===a?t[n].apply(t):r[e].getter.apply(t):t._state[e];return null},set:function(){var e=arguments[0],t;if(u.isObject(e))for(t in e)e.hasOwnProperty(t)&&this._set(t,e[t]);else this._set.apply(this,arguments)},_set:function(e,t){var n=this,r,i,s=n.constructor.ATTRS;s&&s.hasOwnProperty(e)&&(r=s[e].setter,r&&(i=[t],typeof r===a?t=n[r].apply(n,i):t=s[e].setter.apply(n,i)),n._state[e]=t)}},e.mix(c,e.EventTarget,!1,null,1),e.AttributeLite=c,l=function(t){var n=this,r=e.Plugin&&e.Plugin.Host;n._initPlugins&&r&&r.call(n),n.name=n.constructor.NAME,n._eventPrefix=n.constructor.EVENT_PREFIX||n.constructor.NAME,c.call(n),n.addAttrs(t),n.init.apply(this,arguments),n._initPlugins&&n._initPlugins(t),n.initialized=!0},l.NAME="baseGraphic",l.prototype={init:function(){this.publish("init",{fireOnce:!0}),this.initializer.apply(this,arguments),this.fire("init",{cfg:arguments[0]})},_camelCaseConcat:function(e,t){return e+t.charAt(0).toUpperCase()+t.slice(1)}},e.mix(l,e.AttributeLite,!1,null,1),e.mix(l,r,!1,null,1),l.prototype.constructor=l,l.plug=r.plug,l.unplug=r.unplug,e.GraphicBase=l},"@VERSION@",{requires:["node","event-custom","pluginhost","matrix","classnamemanager"]});
ppoffice/cdnjs
ajax/libs/yui/3.13.0/graphics/graphics-min.js
JavaScript
mit
2,036
YUI.add("series-line-util",function(e,t){function r(){}var n=e.Lang;r.prototype={_lineDefaults:null,_getGraphic:function(){var e=this.get("graphic")||this.get("graph").get("graphic");return this._lineGraphic||(this._lineGraphic=e.addShape({type:"path"})),this._lineGraphic.clear(),this._lineGraphic},_toggleVisible:function(e){this._lineGraphic&&this._lineGraphic.set("visible",e)},drawLines:function(){if(this.get("xcoords").length<1)return;var e=n.isNumber,t,r,i=this.get("direction"),s,o,u,a=!0,f,l,c,h,p,d=this.get("styles").line,v=d.lineType,m=d.color||this._getDefaultColor(this.get("graphOrder"),"line"),g=d.alpha,y=d.dashLength,b=d.gapSpace,w=d.connectDiscontinuousPoints,E=d.discontinuousType,S=d.discontinuousDashLength,x=d.discontinuousGapSpace,T=this._getGraphic();this._stacked?(t=this.get("stackedXCoords"),r=this.get("stackedYCoords")):(t=this.get("xcoords"),r=this.get("ycoords")),s=i==="vertical"?r.length:t.length,T.set("stroke",{weight:d.weight,color:m,opacity:g});for(p=0;p<s;p=++p){c=t[p],h=r[p],u=e(c)&&e(h);if(!u){o=u;continue}a?(a=!1,T.moveTo(c,h)):o?v!=="dashed"?T.lineTo(c,h):this.drawDashedLine(T,f,l,c,h,y,b):w?E!=="solid"?this.drawDashedLine(T,f,l,c,h,S,x):T.lineTo(c,h):T.moveTo(c,h),f=c,l=h,o=!0}T.end()},drawSpline:function(){if(this.get("xcoords").length<1)return;var e=this.get("xcoords"),t=this.get("ycoords"),n=this.getCurveControlPoints(e,t),r=n.length,i,s,o,u,a,f,l=0,c=this.get("styles").line,h=this._getGraphic(),p=c.alpha,d=c.color||this._getDefaultColor(this.get("graphOrder"),"line");h.set("stroke",{weight:c.weight,color:d,opacity:p}),h.moveTo(e[0],t[0]);for(;l<r;l=++l)a=n[l].endx,f=n[l].endy,i=n[l].ctrlx1,s=n[l].ctrlx2,o=n[l].ctrly1,u=n[l].ctrly2,h.curveTo(i,o,s,u,a,f);h.end()},drawDashedLine:function(e,t,n,r,i,s,o){s=s||10,o=o||10;var u=s+o,a=r-t,f=i-n,l=Math.sqrt(Math.pow(a,2)+Math.pow(f,2)),c=Math.floor(Math.abs(l/u)),h=Math.atan2(f,a),p=t,d=n,v;a=Math.cos(h)*u,f=Math.sin(h)*u;for(v=0;v<c;++v)e.moveTo(p,d),e.lineTo(p+Math.cos(h)*s,d+Math.sin(h)*s),p+=a,d+=f;e.moveTo(p,d),l=Math.sqrt((r-p)*(r-p)+(i-d)*(i-d)),l>s?e.lineTo(p+Math.cos(h)*s,d+Math.sin(h)*s):l>0&&e.lineTo(p+Math.cos(h)*l,d+Math.sin(h)*l),e.moveTo(r,i)},_getLineDefaults:function(){return{alpha:1,weight:6,lineType:"solid",dashLength:10,gapSpace:10,connectDiscontinuousPoints:!0,discontinuousType:"solid",discontinuousDashLength:10,discontinuousGapSpace:10}}},e.augment(r,e.Attribute),e.Lines=r},"@VERSION@");
stefanneculai/cdnjs
ajax/libs/yui/3.13.0/series-line-util/series-line-util-min.js
JavaScript
mit
2,429
/** * Select2 <Language> translation. * * Author: bigmihail <bigmihail@bigmir.net> */ (function ($) { "use strict"; $.extend($.fn.select2.defaults, { formatNoMatches: function () { return "Нічого не знайдено"; }, formatInputTooShort: function (input, min) { var n = min - input.length, s = ["", "и", "ів"], p = [2,0,1,1,1,2]; return "Введіть буль ласка ще " + n + " символ" + s[ (n%100>4 && n%100<=20)? 2 : p[Math.min(n%10, 5)] ]; }, formatInputTooLong: function (input, max) { var n = input.length - max, s = ["", "и", "ів"], p = [2,0,1,1,1,2]; return "Введіть буль ласка на " + n + " символ" + s[ (n%100>4 && n%100<=20)? 2 : p[Math.min(n%10, 5)] ] + " менше"; }, formatSelectionTooBig: function (limit) {var s = ["", "и", "ів"], p = [2,0,1,1,1,2]; return "Ви можете вибрати лише " + limit + " елемент" + s[ (limit%100>4 && limit%100<=20)? 2 : p[Math.min(limit%10, 5)] ]; }, formatLoadMore: function (pageNumber) { return "Завантаження даних..."; }, formatSearching: function () { return "Пошук..."; } }); })(jQuery);
alucard001/cdnjs
ajax/libs/select2/3.4.3/select2_locale_ua.js
JavaScript
mit
1,212
var apply = require('./_apply'), arrayMap = require('./_arrayMap'), unzip = require('./unzip'); /** * This method is like `_.unzip` except that it accepts `iteratee` to specify * how regrouped values should be combined. The iteratee is invoked with the * elements of each group: (...group). * * @static * @memberOf _ * @since 3.8.0 * @category Array * @param {Array} array The array of grouped elements to process. * @param {Function} [iteratee=_.identity] The function to combine * regrouped values. * @returns {Array} Returns the new array of regrouped elements. * @example * * var zipped = _.zip([1, 2], [10, 20], [100, 200]); * // => [[1, 10, 100], [2, 20, 200]] * * _.unzipWith(zipped, _.add); * // => [3, 30, 300] */ function unzipWith(array, iteratee) { if (!(array && array.length)) { return []; } var result = unzip(array); if (iteratee == null) { return result; } return arrayMap(result, function(group) { return apply(iteratee, undefined, group); }); } module.exports = unzipWith;
humanityroad/humanity-road
WebApp/node_modules/bower/lib/node_modules/lodash/unzipWith.js
JavaScript
mit
1,049
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.IO; public class GenException<T> : Exception { } public interface IGen { bool ExceptionTest(); } public class Gen<T> : IGen { public bool ExceptionTest() { try { Console.WriteLine("in try"); throw new GenException<T>(); } catch (GenException<T> exp) { Console.WriteLine("in catch: " + exp.Message); return true; } } } public class Test { private static TestUtil.TestLog testLog; static Test() { // Create test writer object to hold expected output StringWriter expectedOut = new StringWriter(); // Write expected output to string writer object Exception[] expList = new Exception[] { new GenException<Exception>(), new GenException<GenException<Exception>>(), new GenException<GenException<GenException<Exception>>>(), new GenException<GenException<GenException<GenException<Exception>>>>(), new GenException<GenException<GenException<GenException<GenException<Exception>>>>>(), new GenException<GenException<GenException<GenException<GenException<GenException<Exception>>>>>>(), new GenException<GenException<GenException<GenException<GenException<GenException<GenException<Exception>>>>>>>(), new GenException<GenException<GenException<GenException<GenException<GenException<GenException<GenException<Exception>>>>>>>>(), new GenException<GenException<GenException<GenException<GenException<GenException<GenException<GenException<GenException<Exception>>>>>>>>>(), new GenException<GenException<GenException<GenException<GenException<GenException<GenException<GenException<GenException<GenException<Exception>>>>>>>>>>() }; for (int i = 0; i < expList.Length; i++) { expectedOut.WriteLine("in try"); expectedOut.WriteLine("in catch: " + expList[i].Message); expectedOut.WriteLine("{0}", true); } // Create and initialize test log object testLog = new TestUtil.TestLog(expectedOut); } public static int Main() { //Start recording testLog.StartRecording(); // create test list IGen[] genList = new IGen[] { new Gen<Exception>(), new Gen<GenException<Exception>>(), new Gen<GenException<GenException<Exception>>>(), new Gen<GenException<GenException<GenException<Exception>>>>(), new Gen<GenException<GenException<GenException<GenException<Exception>>>>>(), new Gen<GenException<GenException<GenException<GenException<GenException<Exception>>>>>>(), new Gen<GenException<GenException<GenException<GenException<GenException<GenException<Exception>>>>>>>(), new Gen<GenException<GenException<GenException<GenException<GenException<GenException<GenException<Exception>>>>>>>>(), new Gen<GenException<GenException<GenException<GenException<GenException<GenException<GenException<GenException<Exception>>>>>>>>>(), new Gen<GenException<GenException<GenException<GenException<GenException<GenException<GenException<GenException<GenException<Exception>>>>>>>>>>() }; // run test for (int i = 0; i < genList.Length; i++) { Console.WriteLine(genList[i].ExceptionTest()); } // stop recoding testLog.StopRecording(); return testLog.VerifyOutput(); } }
yeaicc/coreclr
tests/src/JIT/Methodical/eh/generics/trycatchnestedtype.cs
C#
mit
3,790