

/************** http://use.typekit.com/sdc8qvu.js ******************/
/*{"k":"0.10.0","mac":"1:5a3dd181bd71d6f962ce711e0c51a026ccaf4f1210c25cddd1d87a2cfe73e4ca","version":"6889959","created":"2011-12-08T18:19:12Z"}*/
;(function(window,document,undefined){
var j=true,o=null,q=false;function r(a){return function(c){this[a]=c}}function s(a){return function(){return this[a]}}var t;function u(a,c){var b=arguments.length>2?Array.prototype.slice.call(arguments,2):[];return function(){b.push.apply(b,arguments);return c.apply(a,b)}}function v(a,c){this.p=a;this.f=c}t=v.prototype;
t.createElement=function(a,c,b){a=this.p.createElement(a);if(c)for(var d in c)if(c.hasOwnProperty(d))if(d=="style"&&this.f.getName()=="MSIE")a.style.cssText=c[d];else a.setAttribute(d,c[d]);b&&a.appendChild(this.p.createTextNode(b));return a};t.insertInto=function(a,c){var b=this.p.getElementsByTagName(a)[0];if(!b)b=document.documentElement;if(b&&b.lastChild){b.insertBefore(c,b.lastChild);return j}return q};t.whenBodyExists=function(a){function c(){document.body?a():setTimeout(c,0)}c()};
t.removeElement=function(a){if(a.parentNode){a.parentNode.removeChild(a);return j}return q};t.createCssLink=function(a){return this.createElement("link",{rel:"stylesheet",href:a})};t.appendClassName=function(a,c){for(var b=a.className.split(/\s+/),d=0,e=b.length;d<e;d++)if(b[d]==c)return;b.push(c);a.className=b.join(" ").replace(/^\s+/,"")};
t.removeClassName=function(a,c){for(var b=a.className.split(/\s+/),d=[],e=0,g=b.length;e<g;e++)b[e]!=c&&d.push(b[e]);a.className=d.join(" ").replace(/^\s+/,"").replace(/\s+$/,"")};t.hasClassName=function(a,c){for(var b=a.className.split(/\s+/),d=0,e=b.length;d<e;d++)if(b[d]==c)return j;return q};function w(a,c,b,d,e,g,k,h){this.Q=a;this.Pa=c;this.ya=b;this.xa=d;this.Ja=e;this.Ia=g;this.wa=k;this.Ta=h}t=w.prototype;t.getName=s("Q");t.getVersion=s("Pa");t.getEngine=s("ya");t.getEngineVersion=s("xa");
t.getPlatform=s("Ja");t.getPlatformVersion=s("Ia");t.getDocumentMode=s("wa");function x(a,c){this.f=a;this.u=c}var aa=new w("Unknown","Unknown","Unknown","Unknown","Unknown","Unknown",undefined,q);
x.prototype.parse=function(){var a;if(this.f.indexOf("MSIE")!=-1){a=y(this,this.f,/(MSIE [\d\w\.]+)/,1);if(a!=""){var c=a.split(" ");a=c[0];c=c[1];a=new w(a,c,a,c,z(this),A(this),B(this,this.u),C(this,c)>=6)}else a=new w("MSIE","Unknown","MSIE","Unknown",z(this),A(this),B(this,this.u),q)}else{if(this.f.indexOf("Opera")!=-1)a:{c=a="Unknown";var b=y(this,this.f,/(Presto\/[\d\w\.]+)/,1);if(b!=""){c=b.split("/");a=c[0];c=c[1]}else{if(this.f.indexOf("Gecko")!=-1)a="Gecko";b=y(this,this.f,/rv:([^\)]+)/,
1);if(b!="")c=b}if(this.f.indexOf("Version/")!=-1){b=y(this,this.f,/Version\/([\d\.]+)/,1);if(b!=""){a=new w("Opera",b,a,c,z(this),A(this),B(this,this.u),C(this,b)>=10);break a}}b=y(this,this.f,/Opera[\/ ]([\d\.]+)/,1);a=b!=""?new w("Opera",b,a,c,z(this),A(this),B(this,this.u),C(this,b)>=10):new w("Opera","Unknown",a,c,z(this),A(this),B(this,this.u),q)}else{if(this.f.indexOf("AppleWebKit")!=-1){a=z(this);c=A(this);b=y(this,this.f,/AppleWebKit\/([\d\.]+)/,1);if(b=="")b="Unknown";var d="Unknown";
if(this.f.indexOf("Chrome")!=-1)d="Chrome";else if(this.f.indexOf("Safari")!=-1)d="Safari";else if(this.f.indexOf("AdobeAIR")!=-1)d="AdobeAIR";var e="Unknown";if(this.f.indexOf("Version/")!=-1)e=y(this,this.f,/Version\/([\d\.\w]+)/,1);else if(d=="Chrome")e=y(this,this.f,/Chrome\/([\d\.]+)/,1);else if(d=="AdobeAIR")e=y(this,this.f,/AdobeAIR\/([\d\.]+)/,1);var g=q;if(d=="AdobeAIR"){g=y(this,e,/\d+\.(\d+)/,1);g=C(this,e)>2||C(this,e)==2&&parseInt(g,10)>=5}else{g=y(this,b,/\d+\.(\d+)/,1);g=C(this,b)>=
526||C(this,b)>=525&&parseInt(g,10)>=13}a=new w(d,e,"AppleWebKit",b,a,c,B(this,this.u),g)}else{if(this.f.indexOf("Gecko")!=-1){c=a="Unknown";d=q;if(this.f.indexOf("Firefox")!=-1){a="Firefox";b=y(this,this.f,/Firefox\/([\d\w\.]+)/,1);if(b!=""){d=y(this,b,/\d+\.(\d+)/,1);c=b;d=b!=""&&C(this,b)>=3&&parseInt(d,10)>=5}}else if(this.f.indexOf("Mozilla")!=-1)a="Mozilla";b=y(this,this.f,/rv:([^\)]+)/,1);if(b=="")b="Unknown";else if(!d){d=C(this,b);e=parseInt(y(this,b,/\d+\.(\d+)/,1),10);g=parseInt(y(this,
b,/\d+\.\d+\.(\d+)/,1),10);d=d>1||d==1&&e>9||d==1&&e==9&&g>=2||b.match(/1\.9\.1b[123]/)!=o||b.match(/1\.9\.1\.[\d\.]+/)!=o}a=new w(a,c,"Gecko",b,z(this),A(this),B(this,this.u),d)}else a=aa;a=a}a=a}a=a}return a};function z(a){var c=y(a,a.f,/(iPod|iPad|iPhone|Android)/,1);if(c!="")return c;a=y(a,a.f,/(Linux|Mac_PowerPC|Macintosh|Windows)/,1);if(a!=""){if(a=="Mac_PowerPC")a="Macintosh";return a}return"Unknown"}
function A(a){var c=y(a,a.f,/(OS X|Windows NT|Android) ([^;)]+)/,2);if(c)return c;if(c=y(a,a.f,/(iPhone )?OS ([\d_]+)/,2))return c;if(a=y(a,a.f,/Linux ([i\d]+)/,1))return a;return"Unknown"}function C(a,c){var b=y(a,c,/(\d+)/,1);if(b!="")return parseInt(b,10);return-1}function y(a,c,b,d){if((a=c.match(b))&&a[d])return a[d];return""}function B(a,c){if(c.documentMode)return c.documentMode}function ba(a,c,b,d){this.c=a;this.j=c;this.T=b;this.n=d||"wf";this.l=new D("-")}
function E(a){a.c.removeClassName(a.j,a.l.k(a.n,"loading"));a.c.hasClassName(a.j,a.l.k(a.n,"active"))||a.c.appendClassName(a.j,a.l.k(a.n,"inactive"));F(a,"inactive")}function F(a,c,b,d){a.T[c]&&a.T[c](b,d)}function G(a,c,b,d,e){this.c=a;this.A=c;this.C=b;this.s=d;this.M=e;this.W=0;this.sa=this.fa=q}
G.prototype.watch=function(a,c,b,d){for(var e=a.length,g=0;g<e;g++){var k=a[g];c[k]||(c[k]=["n4"]);this.W+=c[k].length}if(d)this.fa=d;for(g=0;g<e;g++){k=a[g];d=c[k];for(var h=b[k],f=0,l=d.length;f<l;f++){var n=d[f],p=this.A,i=k,m=n;p.c.appendClassName(p.j,p.l.k(p.n,i,m,"loading"));F(p,"fontloading",i,m);p=u(this,this.za);i=u(this,this.Aa);new H(p,i,this.c,this.C,this.s,this.M,k,n,h)}}};
G.prototype.za=function(a,c){var b=this.A;b.c.removeClassName(b.j,b.l.k(b.n,a,c,"loading"));b.c.removeClassName(b.j,b.l.k(b.n,a,c,"inactive"));b.c.appendClassName(b.j,b.l.k(b.n,a,c,"active"));F(b,"fontactive",a,c);this.sa=j;I(this)};G.prototype.Aa=function(a,c){var b=this.A;b.c.removeClassName(b.j,b.l.k(b.n,a,c,"loading"));b.c.hasClassName(b.j,b.l.k(b.n,a,c,"active"))||b.c.appendClassName(b.j,b.l.k(b.n,a,c,"inactive"));F(b,"fontinactive",a,c);I(this)};
function I(a){if(--a.W==0&&a.fa)if(a.sa){a=a.A;a.c.removeClassName(a.j,a.l.k(a.n,"loading"));a.c.removeClassName(a.j,a.l.k(a.n,"inactive"));a.c.appendClassName(a.j,a.l.k(a.n,"active"));F(a,"active")}else E(a.A)}
function H(a,c,b,d,e,g,k,h,f){this.ua=a;this.Da=c;this.c=b;this.C=d;this.s=e;this.M=g;this.Ha=new J;this.Ca=new ca;this.$=k;this.Z=h;this.Ba=f||"BESs";this.ha=da(this,"arial,'URW Gothic L',sans-serif");this.ia=da(this,"Georgia,'Century Schoolbook L',serif");this.da=this.ha;this.ea=this.ia;this.na=K(this,"arial,'URW Gothic L',sans-serif");this.oa=K(this,"Georgia,'Century Schoolbook L',serif");this.Na=g();this.U()}
H.prototype.U=function(){var a=this.C.N(this.na),c=this.C.N(this.oa);if((this.ha!=a||this.ia!=c)&&this.da==a&&this.ea==c)ea(this,this.ua);else if(this.M()-this.Na>=5E3)ea(this,this.Da);else{this.da=a;this.ea=c;fa(this)}};function fa(a){a.s(function(c,b){return function(){b.call(c)}}(a,a.U),25)}function ea(a,c){a.c.removeElement(a.na);a.c.removeElement(a.oa);c(a.$,a.Z)}function da(a,c){var b=K(a,c,j),d=a.C.N(b);a.c.removeElement(b);return d}
function K(a,c,b){var d=a.Ca.expand(a.Z);c=a.c.createElement("span",{style:"position:absolute;top:-999px;left:-999px;font-size:300px;width:auto;height:auto;line-height:normal;margin:0;padding:0;font-variant:normal;font-family:"+(b?"":a.Ha.quote(a.$)+",")+c+";"+d},a.Ba);a.c.insertInto("body",c);return c}function D(a){this.Fa=a||"-"}D.prototype.k=function(){for(var a=[],c=0;c<arguments.length;c++)a.push(arguments[c].replace(/[\W_]+/g,"").toLowerCase());return a.join(this.Fa)};
function J(){this.ma="'"}J.prototype.quote=function(a){var c=[];a=a.split(/,\s*/);for(var b=0;b<a.length;b++){var d=a[b].replace(/['"]/g,"");d.indexOf(" ")==-1?c.push(d):c.push(this.ma+d+this.ma)}return c.join(",")};function ca(){this.ka=ga;this.D=ha}var ga=["font-style","font-weight"],ha={"font-style":[["n","normal"],["i","italic"],["o","oblique"]],"font-weight":[["1","100"],["2","200"],["3","300"],["4","400"],["5","500"],["6","600"],["7","700"],["8","800"],["9","900"],["4","normal"],["7","bold"]]};
function ia(a,c,b){this.Ea=a;this.Ka=c;this.D=b}ia.prototype.expand=function(a,c){for(var b=0;b<this.D.length;b++)if(c==this.D[b][0]){a[this.Ea]=this.Ka+":"+this.D[b][1];break}};ca.prototype.expand=function(a){if(a.length!=2)return o;for(var c=[o,o],b=0,d=this.ka.length;b<d;b++){var e=this.ka[b];(new ia(b,e,this.D[e])).expand(c,a.substr(b,1))}return c[0]&&c[1]?c.join(";")+";":o};function M(a,c){this.p=a;this.f=c}M.prototype=v.prototype;
M.prototype.isHttps=function(){return this.p.location.protocol=="https:"};M.prototype.getHostName=function(){return this.p.location.hostname};M.prototype.loadScript=function(a,c){var b=this.p.getElementsByTagName("head")[0];if(b){var d=this.p.createElement("script");d.src=a;var e=q;d.onload=d.onreadystatechange=function(){if(!e&&(!this.readyState||this.readyState=="loaded"||this.readyState=="complete")){e=j;c&&c();d.onload=d.onreadystatechange=o;d.parentNode.tagName=="HEAD"&&b.removeChild(d)}};b.appendChild(d)}};
M.prototype.createStyle=function(a){var c=this.p.createElement("style");c.setAttribute("type","text/css");if(c.styleSheet)c.styleSheet.cssText=a;else c.appendChild(document.createTextNode(a));return c};function ja(a){for(var c=a.La.join(","),b=[],d=0;d<a.X.length;d++){var e=a.X[d];b.push(e.name+":"+e.value+";")}return c+"{"+b.join("")+"}"}function N(a,c,b,d){this.B=a;this.H=c;this.v=b;this.Sa=d;this.aa={};this.Y={}}
N.prototype.w=function(a){return a?(this.aa[a.getStylesheetFormatId()]||this.H).slice(0):this.H.slice(0)};N.prototype.getId=s("v");function ka(a,c,b){for(var d=[],e=a.B.split(",")[0].replace(/"|'/g,""),g=a.w(),k,h=[],f={},l=0;l<g.length;l++){k=g[l];if(k.length>0&&!f[k]){f[k]=j;h.push(k)}}b=b.la?b.la(e,h,d):h;c=c.getStylesheetFormatId();a.aa[c]=b;a.Y[c]=d}N.prototype.watch=function(a,c,b){var d=[],e={};la(this,c,d,e);a.watch(d,e,{},b)};
function la(a,c,b,d){b.push(a.B);d[a.B]=a.w(c);a=a.Y[c.getStylesheetFormatId()]||[];for(c=0;c<a.length;c++){for(var e=a[c],g=e.B,k=q,h=0;h<b.length;h++)if(b[h]==g)k=j;if(!k){b.push(g);d[g]=e.w()}}}function ma(a,c){this.B=a;this.H=c}ma.prototype.w=s("H");function O(a,c,b){this.Ma=a;this.O=c;this.pa=b}O.prototype.buildUrl=function(a,c){var b=this.Ma&&a?"https:":"http:",d=typeof this.O=="function"?this.O(b):this.O;return b+"//"+d+(this.pa=="/"?"":this.pa)+c};
function na(a,c){var b=new Image(1,1);b.src=c;b.onload=function(){b.onload=o}}function P(a,c,b){this.v=a;this.ra=c;this.ca=b}P.prototype.getId=s("v");P.prototype.getStylesheetFormatId=s("ra");P.prototype.isUserAgent=function(a){return this.ca?this.ca(a.getName(),a.getVersion(),a.getEngine(),a.getEngineVersion(),a.getPlatform(),a.getPlatformVersion(),a.getDocumentMode()):q};P.prototype.buildCssUrl=function(a,c,b,d){b="/"+b+"-"+this.ra+".css";if(d)b+="?"+d;return c.buildUrl(a,b)};
function Q(){this.t=[]}Q.prototype.addBrowser=function(a){this.getBrowserById(a.getId())||this.t.push(a)};Q.prototype.getBrowserById=function(a){for(var c=0;c<this.t.length;c++){var b=this.t[c];if(a===b.getId())return b}return o};Q.prototype.findBrowser=function(a){for(var c=0;c<this.t.length;c++){var b=this.t[c];if(b.isUserAgent(a))return b}return o};Q.prototype.addBrowsersToBrowserSet=function(a){for(var c=0;c<this.t.length;c++)a.addBrowser(this.t[c])};
function oa(a){this.v=a;this.J=new Q;this.m=[];this.K=[];this.L=this.V=this.z=o}t=oa.prototype;t.getId=s("v");t.setSecurityToken=r("qa");t.setNestedUrl=r("ga");t.setFontFilterSet=r("L");t.setKitOptions=r("P");t.addBrowser=function(a){this.J.addBrowser(a)};t.addFontFamily=function(a){this.m.push(a)};t.addCssRule=function(a){this.K.push(a)};t.supportsBrowser=function(a){return!!this.J.getBrowserById(a.getId())};t.addBrowsersToBrowserSet=function(a){this.J.addBrowsersToBrowserSet(a)};
t.init=function(a){for(var c=[],b=0;b<this.K.length;b++)c.push(ja(this.K[b]));a.insertInto("head",a.createStyle(c.join("")))};
t.load=function(a,c,b,d){if(this.L)for(var e=pa(this.L,b.getStylesheetFormatId()),g=0;g<this.m.length;g++)ka(this.m[g],b,e);if(this.z&&this.V){this.z.va(new qa(b.getStylesheetFormatId()));g=new ra(a,this.F,this.m);e=sa(this.V,b.getStylesheetFormatId(),g);for(g=0;g<e.length;g++)this.z.va(e[g]);this.z.Ra(this.qa);g=this.z.buildUrl(a.isHttps(),this.ga)}else g=b.buildCssUrl(a.isHttps(),this.ga,this.v,this.qa);a.insertInto("head",a.createCssLink(g));c&&a.whenBodyExists(function(k,h,f,l){return function(){for(var n=
0;n<k.m.length;n++)k.m[n].watch(h,f,l&&n==k.m.length-1)}}(this,c,b,d))};t.collectFontFamilies=function(a,c,b){for(var d=0;d<this.m.length;d++)la(this.m[d],a,c,b)};t.performOptionalActions=function(a,c,b){this.P&&b.whenBodyExists(function(d,e,g,k){return function(){var h=d.P;h.ja&&na(h,h.ja.buildUrl(k.isHttps()));var f=d.P;h=d.v;if(f.S){f=f.S.k(h,g,k);f.setAttribute("id","typekit-badge-"+h);k.insertInto("body",f)}}}(this,a,c,b))};
function R(a,c,b,d,e){this.Ga=a;this.c=c;this.f=b;this.j=d;this.s=e;this.o=[]}R.prototype.I=function(a){this.o.push(a)};R.prototype.load=function(a,c){var b=a,d=c||{};if(typeof b=="string")b=[b];else if(b&&b.length)b=b;else{d=b||{};b=[]}if(b.length)for(var e=this,g=b.length,k=0;k<b.length;k++)this.ta(b[k],function(){--g==0&&e.R(d)});else this.R(d)};R.prototype.ta=function(a,c){this.c.loadScript(this.Ga.buildUrl(this.c.isHttps(),"/"+a+".js"),c)};
R.prototype.R=function(a){if(a.userAgent)this.f=(new x(a.userAgent,document)).parse();a=new ba(this.c,this.j,a);for(var c=new Q,b=0;b<this.o.length;b++)this.o[b].addBrowsersToBrowserSet(c);c=c.findBrowser(this.f);for(b=0;b<this.o.length;b++)this.o[b].init(this.c);if(c){a.c.appendClassName(a.j,a.l.k(a.n,"loading"));F(a,"loading");ta(this,c,a)}else E(a);this.o=[]};
function ta(a,c,b){b=new G(a.c,b,{N:function(g){return g.offsetWidth}},a.s,function(){return+new Date});for(var d=0;d<a.o.length;d++){var e=a.o[d];if(e.supportsBrowser(c)){e.load(a.c,b,c,d==a.o.length-1);e.performOptionalActions(window,a.f,a.c)}}}function S(a,c,b){this.ba=a;this.c=c;this.s=b;this.o=[]}S.prototype.I=function(a){this.o.push(a)};
S.prototype.load=function(){var a=this.ba.__webfonttypekitmodule__;if(a)for(var c=0;c<this.o.length;c++){var b=this.o[c],d=a[b.getId()];if(d){var e=this.c,g=this.s;d(function(k,h,f){var l=new Q;b.addBrowsersToBrowserSet(l);h=[];var n={};if(l=l.findBrowser(k)){b.init(e);b.load(e,o,l,g);b.collectFontFamilies(l,h,n);b.performOptionalActions(window,k,e,g)}f(!!l,h,n)})}}};function T(a,c){this.Q=a;this.la=c}T.prototype.getName=s("Q");
function U(a,c){for(var b=0;b<a.G.length;b++){var d=a.G[b];if(c===d.getName())return d}return o}function pa(a,c){var b=a.q[c];return b?U(a,b):o}function sa(a,c,b){var d=[];a=a.r[c]||[];for(c=0;c<a.length;c++){var e;a:switch(a[c]){case "observeddomain":e=new ua(b.c);break a;case "fontmask":e=new va(b.F,b.m);break a;default:e=o}e&&d.push(e)}return d}function ra(a,c,b){this.c=a;this.F=c;this.m=b}function qa(a){this.Oa=a}qa.prototype.toString=s("Oa");function ua(a){this.c=a}
ua.prototype.toString=function(){var a;a=this.c.getHostName?this.c.getHostName():document.location.hostname;return encodeURIComponent(a)};function va(a,c){this.F=a;this.m=c}va.prototype.toString=function(){for(var a=[],c=0;c<this.m.length;c++){var b=this.m[c],d=b.w();b=b.w(this.F);for(var e=0;e<d.length;e++){var g;a:{for(g=0;g<b.length;g++)if(d[e]===b[g]){g=j;break a}g=q}a.push(g?1:0)}}a=a.join("");a=a.replace(/^0+/,"");c=[];for(d=a.length;d>0;d-=4){b=a.slice(d-4<0?0:d-4,d);c.unshift(parseInt(b,2).toString(16))}return c.join("")};
var V=new Q;V.addBrowser(new P("ie9plus-win7plus-winvista","d",function(a,c,b,d,e,g,k){var h=q;h=(h=h||function(l,n,p,i,m,L){l=/^([0-9]+).([0-9]+)/.exec(L);if(m=="Windows"&&l){m=parseInt(l[1],10);l=parseInt(l[2],10);return m>6||m==6&&l>=1}else return q}(a,c,b,d,e,g,k))||(e=="Windows"&&g=="6.0"?j:q);if(!h)return q;var f;if(a=="MSIE")f=k>=9;return f}));
V.addBrowser(new P("safari-osx","b",function(a,c,b,d,e,g,k){var h=q;h=h||function(f,l,n,p,i,m){f=/^([0-9]+)(_|.)([0-9]+)/.exec(m);if(i=="Macintosh"&&f){i=parseInt(f[1],10);m=parseInt(f[3],10);return i>10||i==10&&m>=4}else return i=="Macintosh"&&m=="Unknown"?j:q}(a,c,b,d,e,g,k);if(!h)return q;return function(f,l,n,p,i){if(f=="Safari"&&n=="AppleWebKit"||f=="Unknown"&&n=="AppleWebKit"&&(i=="iPhone"||i=="iPad"))if(f=/([0-9]+.[0-9]+)/.exec(p))return parseFloat(f[1])>=525.13;return q}(a,c,b,d,e,g,k)}));
V.addBrowser(new P("safari-android-ipad-iphone-win2003-win7plus-winvista-winxp","a",function(a,c,b,d,e,g,k){var h=q;h=(h=(h=(h=(h=(h=(h=h||(e=="Windows"&&g=="5.1"?j:q))||(e=="Windows"&&g=="5.2"?j:q))||(e=="Windows"&&g=="6.0"?j:q))||function(f,l,n,p,i,m){f=/^([0-9]+).([0-9]+)/.exec(m);if(i=="Windows"&&f){i=parseInt(f[1],10);f=parseInt(f[2],10);return i>6||i==6&&f>=1}else return q}(a,c,b,d,e,g,k))||function(f,l,n,p,i,m){f=/([0-9]+).([0-9]+)/.exec(m);if(i=="Android"&&f){i=parseInt(f[1]);f=parseInt(f[2]);
return i>2||i==2&&f>=2}else return q}(a,c,b,d,e,g,k))||function(f,l,n,p,i,m){if(i=="iPad")if(l=/^([0-9]+)_([0-9]+)/.exec(m)){f=parseInt(l[1],10);l=parseInt(l[2],10);return f>4||f==4&&l>=2}else return q;else return q}(a,c,b,d,e,g,k))||function(f,l,n,p,i,m){if(i=="iPhone"||i=="iPod")if(l=/^([0-9]+)_([0-9]+)/.exec(m)){f=parseInt(l[1],10);l=parseInt(l[2],10);return f>4||f==4&&l>=2}else return q;else return q}(a,c,b,d,e,g,k);if(!h)return q;return function(f,l,n,p,i){if(f=="Safari"&&n=="AppleWebKit"||f==
"Unknown"&&n=="AppleWebKit"&&(i=="iPhone"||i=="iPad"))if(f=/([0-9]+.[0-9]+)/.exec(p))return parseFloat(f[1])>=525.13;return q}(a,c,b,d,e,g,k)}));
V.addBrowser(new P("air-linux-osx-win","a",function(a,c,b,d,e,g,k){var h=q;h=(h=(h=h||function(f,l,n,p,i,m){f=/^([0-9]+)(_|.)([0-9]+)/.exec(m);if(i=="Macintosh"&&f){i=parseInt(f[1],10);m=parseInt(f[3],10);return i>10||i==10&&m>=4}else return i=="Macintosh"&&m=="Unknown"?j:q}(a,c,b,d,e,g,k))||(e=="Ubuntu"||e=="Linux"?j:q))||(e=="Windows"&&g=="Unknown"?j:q);if(!h)return q;return function(f,l){if(f=="AdobeAIR"){var n=/([0-9]+.[0-9]+)/.exec(l);if(n)return parseFloat(n[1])>=2.5}return q}(a,c,b,d,e,g,k)}));
V.addBrowser(new P("chrome4to5-linux-osx-win2003-win7plus-winvista-winxp","a",function(a,c,b,d,e,g,k){var h=q;h=(h=(h=(h=(h=(h=h||(e=="Windows"&&g=="5.1"?j:q))||(e=="Windows"&&g=="5.2"?j:q))||(e=="Windows"&&g=="6.0"?j:q))||function(f,l,n,p,i,m){f=/^([0-9]+).([0-9]+)/.exec(m);if(i=="Windows"&&f){i=parseInt(f[1],10);f=parseInt(f[2],10);return i>6||i==6&&f>=1}else return q}(a,c,b,d,e,g,k))||function(f,l,n,p,i,m){f=/^([0-9]+)(_|.)([0-9]+)/.exec(m);if(i=="Macintosh"&&f){i=parseInt(f[1],10);m=parseInt(f[3],
10);return i>10||i==10&&m>=4}else return i=="Macintosh"&&m=="Unknown"?j:q}(a,c,b,d,e,g,k))||(e=="Ubuntu"||e=="Linux"?j:q);if(!h)return q;return function(f,l){if(f=="Chrome"){var n=/([0-9]+.[0-9]+).([0-9]+).([0-9]+)/.exec(l);if(n){var p=parseFloat(n[1]),i=parseInt(n[2],10);n=parseInt(n[3],10);if(p>=6)return q;else if(p>4)return j;else if(p==4&&i>249)return j;else if(p==4&&i==249&&n>=4)return j}}return q}(a,c,b,d,e,g,k)}));
V.addBrowser(new P("chrome6plus-linux-osx-win2003-win7plus-winvista-winxp","d",function(a,c,b,d,e,g,k){var h=q;h=(h=(h=(h=(h=(h=h||(e=="Windows"&&g=="5.1"?j:q))||(e=="Windows"&&g=="5.2"?j:q))||(e=="Windows"&&g=="6.0"?j:q))||function(f,l,n,p,i,m){f=/^([0-9]+).([0-9]+)/.exec(m);if(i=="Windows"&&f){i=parseInt(f[1],10);f=parseInt(f[2],10);return i>6||i==6&&f>=1}else return q}(a,c,b,d,e,g,k))||function(f,l,n,p,i,m){f=/^([0-9]+)(_|.)([0-9]+)/.exec(m);if(i=="Macintosh"&&f){i=parseInt(f[1],10);m=parseInt(f[3],
10);return i>10||i==10&&m>=4}else return i=="Macintosh"&&m=="Unknown"?j:q}(a,c,b,d,e,g,k))||(e=="Ubuntu"||e=="Linux"?j:q);if(!h)return q;return function(f,l){if(f=="Chrome"){var n=/([0-9]+.[0-9]+).([0-9]+).([0-9]+)/.exec(l);if(n)if(parseFloat(n[1])>=6)return j}}(a,c,b,d,e,g,k)}));
V.addBrowser(new P("opera-osx","b",function(a,c,b,d,e,g,k){var h=q;h=h||function(f,l,n,p,i,m){f=/^([0-9]+)(_|.)([0-9]+)/.exec(m);if(i=="Macintosh"&&f){i=parseInt(f[1],10);m=parseInt(f[3],10);return i>10||i==10&&m>=4}else return i=="Macintosh"&&m=="Unknown"?j:q}(a,c,b,d,e,g,k);if(!h)return q;a=a=="Opera"?parseFloat(c)>=10.54:q;return a}));
V.addBrowser(new P("opera-linux-win2003-win7plus-winvista-winxp","a",function(a,c,b,d,e,g,k){var h=q;h=(h=(h=(h=(h=h||(e=="Windows"&&g=="5.1"?j:q))||(e=="Windows"&&g=="5.2"?j:q))||(e=="Windows"&&g=="6.0"?j:q))||function(f,l,n,p,i,m){f=/^([0-9]+).([0-9]+)/.exec(m);if(i=="Windows"&&f){i=parseInt(f[1],10);f=parseInt(f[2],10);return i>6||i==6&&f>=1}else return q}(a,c,b,d,e,g,k))||(e=="Ubuntu"||e=="Linux"?j:q);if(!h)return q;a=a=="Opera"?parseFloat(c)>=10.54:q;return a}));
V.addBrowser(new P("ie6to8-win2003-win7plus-winvista-winxp","i",function(a,c,b,d,e,g,k){var h=q;h=(h=(h=(h=h||(e=="Windows"&&g=="5.1"?j:q))||(e=="Windows"&&g=="5.2"?j:q))||(e=="Windows"&&g=="6.0"?j:q))||function(f,l,n,p,i,m){f=/^([0-9]+).([0-9]+)/.exec(m);if(i=="Windows"&&f){i=parseInt(f[1],10);f=parseInt(f[2],10);return i>6||i==6&&f>=1}else return q}(a,c,b,d,e,g,k);if(!h)return q;return function(f,l,n,p,i,m,L){if(f=="MSIE"){if(f=/([0-9]+.[0-9]+)/.exec(l))return parseFloat(f[1])>=6&&(L===undefined||
L<9);return q}}(a,c,b,d,e,g,k)}));
V.addBrowser(new P("ff36plus-linux-osx-win2003-win7plus-winvista-winxp","d",function(a,c,b,d,e,g,k){var h=q;h=(h=(h=(h=(h=(h=h||(e=="Windows"&&g=="5.1"?j:q))||(e=="Windows"&&g=="5.2"?j:q))||(e=="Windows"&&g=="6.0"?j:q))||function(f,l,n,p,i,m){f=/^([0-9]+).([0-9]+)/.exec(m);if(i=="Windows"&&f){i=parseInt(f[1],10);f=parseInt(f[2],10);return i>6||i==6&&f>=1}else return q}(a,c,b,d,e,g,k))||function(f,l,n,p,i,m){f=/^([0-9]+)(_|.)([0-9]+)/.exec(m);if(i=="Macintosh"&&f){i=parseInt(f[1],10);m=parseInt(f[3],
10);return i>10||i==10&&m>=4}else return i=="Macintosh"&&m=="Unknown"?j:q}(a,c,b,d,e,g,k))||(e=="Ubuntu"||e=="Linux"?j:q);if(!h)return q;return function(f,l,n,p){if(n=="Gecko")if(l=/([0-9]+.[0-9]+)(.([0-9]+)|)/.exec(p)){f=parseFloat(l[1]);l=parseInt(l[3],10);return f>1.9||f>=1.9&&l>1}return q}(a,c,b,d,e,g,k)}));
V.addBrowser(new P("ff35-osx","b",function(a,c,b,d,e,g,k){var h=q;h=h||function(f,l,n,p,i,m){f=/^([0-9]+)(_|.)([0-9]+)/.exec(m);if(i=="Macintosh"&&f){i=parseInt(f[1],10);m=parseInt(f[3],10);return i>10||i==10&&m>=4}else return i=="Macintosh"&&m=="Unknown"?j:q}(a,c,b,d,e,g,k);if(!h)return q;return function(f,l,n,p){if(n=="Gecko"){f=/1.9.1b[1-3]{1}/;return/1.9.1/.test(p)&&!f.test(p)}return q}(a,c,b,d,e,g,k)}));
V.addBrowser(new P("ff35-linux-win2003-win7plus-winvista-winxp","a",function(a,c,b,d,e,g,k){var h=q;h=(h=(h=(h=(h=h||(e=="Windows"&&g=="5.1"?j:q))||(e=="Windows"&&g=="5.2"?j:q))||(e=="Windows"&&g=="6.0"?j:q))||function(f,l,n,p,i,m){f=/^([0-9]+).([0-9]+)/.exec(m);if(i=="Windows"&&f){i=parseInt(f[1],10);f=parseInt(f[2],10);return i>6||i==6&&f>=1}else return q}(a,c,b,d,e,g,k))||(e=="Ubuntu"||e=="Linux"?j:q);if(!h)return q;return function(f,l,n,p){if(n=="Gecko"){f=/1.9.1b[1-3]{1}/;return/1.9.1/.test(p)&&
!f.test(p)}return q}(a,c,b,d,e,g,k)}));var W=new function(){this.G=[];this.q={}},wa=new T("AllFonts",function(a,c){return c});U(W,wa.getName())||W.G.push(wa);
var xa=new T("DefaultFourFontsWithSingleFvdFamilies",function(a,c,b){for(var d=0;d<c.length;d++){var e=c[d],g=a.replace(/(-1|-2)$/,"").slice(0,28)+"-"+e;b.push(new ma(g,[e]))}a={};for(e=0;e<c.length;e++){b=c[e];d=b.charAt(1);(a[d]||(a[d]=[])).push(b)}b=[[4,3,2,1,5,6,7,8,9],[7,8,9,6,5,4,3,2,1]];d=[];for(e=0;e<b.length;e++){g=b[e];for(var k=0;k<g.length;k++){var h=g[k];if(a[h]){d=d.concat(a[h]);break}}}b=d;d={};a=[];for(e=0;e<b.length;e++){g=b[e];if(!d[g]){d[g]=j;a.push(g)}}b=[];for(d=0;d<c.length;d++){e=
c[d];for(g=0;g<a.length;g++){k=a[g];k==e&&b.push(k)}}return b});U(W,xa.getName())||W.G.push(xa);W.q.a="AllFonts";W.q.b="AllFonts";W.q.d="AllFonts";W.q.e="AllFonts";W.q.g="AllFonts";W.q.h="AllFonts";W.q.i="DefaultFourFontsWithSingleFvdFamilies";var X=new function(){this.r={}};X.r.a=[];X.r.b=[];X.r.d=[];X.r.e=[];X.r.g=["observeddomain"];X.r.h=["observeddomain"];X.r.i=["observeddomain","fontmask"];
if(!window.Typekit){var ya=new O(j,"use.typekit.com","/"),za=(new x(navigator.userAgent,document)).parse(),Aa=new M(document,za),Ba=function(a,c){setTimeout(a,c)},Y=new R(ya,Aa,za,document.documentElement,Ba),Z=new S(window,Aa,Ba);window.Typekit=Y;window.Typekit.load=Y.load;window.Typekit.addKit=Y.I}var Ca,Da,$;Ca=new O(j,"use.typekit.com","/k");Da=new function(a,c,b){this.S=a;this.Qa=o;this.ja=b}(o,o,o);$=new oa("sdc8qvu");$.setSecurityToken("3bb2a6e53c9684ffdc9a98f7135b2a62a5dfccee9471fce533fd918dddd9a09ef617c9feebad3ddbabc109f28c536bcbfd96e2ec633cb00db33912020f1a4b920bc5cc5e6d4dad3a75d18de71d863575911c11be63ec99f0ac3c764137facb72bda096cf146fd3a6dd6ba3da9f0daac7bdbeabd996dbaa90754ce825e686335e1f2acf57cc581885ec9bf68dc2ca6f925790747eb97f56074b885b54051b9f3ad26fed50f99515f95c8881e781e1a911d9e885d209d7f07eb7cdd55f66d2b2fe56933900fab3866003750ce9ee7fdac408a1b14f049b78297b61f0");
$.setNestedUrl(Ca);$.setKitOptions(Da);$.addFontFamily(new N("proxima-nova-1,proxima-nova-2",["n1","n3","i3","n4","i4","n6","i6"]));$.addCssRule(new function(a,c){this.La=a;this.X=c}([".tk-proxima-nova"],[{name:"font-family",value:"proxima-nova-1,proxima-nova-2,sans-serif"}]));$.addBrowser(V.getBrowserById("air-linux-osx-win"));$.addBrowser(V.getBrowserById("chrome4to5-linux-osx-win2003-win7plus-winvista-winxp"));$.addBrowser(V.getBrowserById("chrome6plus-linux-osx-win2003-win7plus-winvista-winxp"));
$.addBrowser(V.getBrowserById("ff35-linux-win2003-win7plus-winvista-winxp"));$.addBrowser(V.getBrowserById("ff35-osx"));$.addBrowser(V.getBrowserById("ff36plus-linux-osx-win2003-win7plus-winvista-winxp"));$.addBrowser(V.getBrowserById("ie6to8-win2003-win7plus-winvista-winxp"));$.addBrowser(V.getBrowserById("ie9plus-win7plus-winvista"));$.addBrowser(V.getBrowserById("opera-linux-win2003-win7plus-winvista-winxp"));$.addBrowser(V.getBrowserById("opera-osx"));$.addBrowser(V.getBrowserById("safari-android-ipad-iphone-win2003-win7plus-winvista-winxp"));
$.addBrowser(V.getBrowserById("safari-osx"));$.setFontFilterSet(W);if(Z&&Z.ba.__webfonttypekitmodule__){Z.I($);Z.load()}else window.Typekit.addKit($);
})(this,document);

/************** try{Typekit.load();}catch(e){}.js ******************/
try{Typekit.load();}catch(e){}

/************** jquery.dropp.js ******************/
/*
 * Dropp
 * http://github.com/matrushka/Dropp
 * @requires jQuery v1.3 or later
 * 
 * Dropp is a jQuery plugin which replaces regular droprown menus ( <select> elements ) with stylable alternatives.
 *
 * 2010 - Baris Gumustas
 */
(function($){
	$.fn.dropp = function() {
		return this.each(function() {
			var select = $(this);
			select.hide();
			select.wrap('<div class="dropdown_wrapper"></div>');
			
			var dropdown = $('<a href="#"/>').attr('class', select.attr('class')).addClass('dropdown').appendTo(select.parent());
			var list = $('<ul/>').addClass('dropdown_list').hide().appendTo(select.parent());
			
			// duplicate this line for dropdown opening
			list.css('min-width', dropdown.width()+parseInt(dropdown.css("padding-left"), 10)+parseInt(dropdown.css("padding-right"), 10));
			list.css('position', 'absolute').css('z-index', '9999');
			
			select.find('option').each(function() {
				var item = $(this);
				var list = item.closest('.dropdown_wrapper').find('ul.dropdown_list');
				var list_item = $('<li/>').appendTo(list);
				var link = $('<a href="#"/>').text(item.text());
				link.data('option',item);
				list_item.append(link);
				item.data('replacement',link);
				
				if (typeof select.attr('multiple') !== undefined && (select.attr('multiple') === true || select.attr('multiple') == 'multiple')) {
					if (typeof item.attr('selected') !== undefined && (item.attr('selected') === true || item.attr('selected') == 'selected')) {
						link.addClass('selected');
					}
				}
				
				// Select Event Listener
				link.bind('select',function(event,trigger_drowndown){
					var link = $(this);
					var wrapper = link.closest('.dropdown_wrapper');
					var item = link.data('option');
					var select = wrapper.find('select');
					var dropdown = wrapper.find('.dropdown');
					
					if (typeof select.attr('multiple') === 'undefined' || select.attr('multiple') === false) {
						select.find('option:selected').removeAttr('selected');
						dropdown.text($(this).text());
						item.attr('selected', 'selected');
						list.hide();
					} else {
						if (typeof item.attr('selected') === 'undefined' || item.attr('selected') === false) {
							item.attr('selected','selected');
							link.addClass('selected');
						} else {
							item.removeAttr('selected');
							link.removeClass('selected');
						}
						
						var values = [];
						select.find('option:selected').each(function(){
							values.push($(this).text());
						});
						
						if (values.length === 0) {
							if (typeof select.attr('placeholder') !== 'undefined') {
								dropdown.text(select.attr('placeholder'));
							} else {
								dropdown.html('&nbsp;');
							}
						} else {
							dropdown.text(values.join(', '));
						}
					}

					if(trigger_drowndown) {
						select.trigger('change');
					}
				});
				// Click Event
				link.click(function() {
					$(this).trigger('select',[true]);
					return false;
				});
			});
			
			// Each loop ends here
			if (select.find('option:selected').length === 0) {
				if (typeof select.attr('placeholder') !== 'undefined') {
					dropdown.text(select.attr('placeholder'));
				} else {
					dropdown.html('&nbsp;');
				}
			} else {
				if (typeof select.attr('multiple') !== undefined && (select.attr('multiple') === true || select.attr('multiple') == 'multiple')) {
					var values = [];
					select.find('option:selected').each(function(){
						values.push($(this).text());
					});
					dropdown.html(values.join(', '));
				} else {
					dropdown.text($(this).find('option:selected').text());
				}
			}
			
			dropdown.click(function() {
				if (list.is(':visible')) {
						list.hide();
						$('ul.dropdown_list').hide();
				} else {
					$('ul.dropdown_list').hide();
						list.show();
				}
				return false;
			});
			
			$(document).click(function() {
					list.hide();
			});
			
			$('.dropdown_wrapper').click(function(event) {
					event.stopPropagation();
			});
		});
	};
}(jQuery));


/************** jquery.build.js ******************/
(function($) {
	
	// private
	var _util, _elements, _doc;
	
	// public
	var api;
	
	// shortcut to document
	_doc = document;
	
	// cache all elements here for cloning later
	_elements = {};
	
	_util = {
		
		/**
		 *  Creates Element and adds to storage or clones existing
		 * 
		 *  @param {String} tag
		 */
		new_element : function(tag) {
			if (!_elements[tag]) _elements[tag] = (tag === 'fragment') ? _doc.createDocumentFragment() : _doc.createElement(tag);
			return _elements[tag].cloneNode(false);
		},

		/**
		 *  Adds text to element 
		 *  - auto-detects HTML Entities and uses innerHTML to parse
		 * 
		 *  @param {HTMLElement} el
		 *  @param {String} string
		 */
		insert_text : function(el, text) {
			(/\&\S+;/.test(text)) ? el.innerHTML += text : el.appendChild(_doc.createTextNode(text));
		},
		
		/**
		 *  Loops through object of attributes and applies them
		 *
		 *  @param {HTMLElement} element to attribute-ize
		 *  @param {Object} attribute object to parse
		 */
		apply_attributes : function(el, attrs) {
			
			var $el = $(el);
			
			var attr;
			for (var name in attrs) {
				attr = attrs[name];
				switch(name) {
					case 'style' : $el.style(attr); break;
					case 'class' : el.className = attr; break;
					default : (typeof el[name] !== 'undefined') ? el[name] = attr : el.setAttribute(name, attr);
				}
			}
		},
		
		/**
		 *  Parses contents and adds according to whatever technique works best
		 *
		 *  @param {HTMLElement} element to add content to
		 *  @param {String|Number|Array|Function|HTMLElement|HTMLFragment|HTMLCollection} contents to parse and add
		 */
		process_contents : function(el, contents) {
			
			if (!$.isArray(contents)) {
				contents = [contents];
			}

			var content;
			for (var i = 0, len = contents.length; i < len; i++) {
				
				content = contents[i];
				
				if (typeof content === 'function') {
					// if content is a function
					
					el.appendChild(content());
				}
				else if (content.nodeType && (content.nodeType === 1 || content.nodeType === 11)) {
					// if content is an element or a document fragment
					
					el.appendChild(content);
				}
				else {
					// if it is string or number
					
					_util.insert_text(el, content);
				}
			}
		}
		
	}
	
	api = {
		
		/**
		 *  Builds and returns HTMLElement, with any content (including other 'built' elements)
		 *
		 *  Examples:
		 *  build('div', {'id' : 'container'}, 'a container')
		 *  => <div id="container">a container</div>
		 *
		 *  build('a', {'href' : '#'}, [
		 *    'click here,
		 *    build('span', 'a contained element')
		 *  ])
		 *  => <a href="#">click here<span>a contained element</span></a>
		 *
		 *  @param {String} element tag name
		 *  @param {Object} optional - HTML attributes
		 *  @param {String|Number|Array|HTMLElement} optional - contents, or list of content
		 */
		build : function(tag, attrs, contents) {

			// make element available for util functions
			var el = _util.new_element(tag);
			
			// if attrs is attrs object, otherwise its content
			if ($.isPlainObject(attrs)) {
				_util.apply_attributes(el, attrs);
			}
			else {
				contents = attrs;
			}
			
			if (contents) {
				_util.process_contents(el, contents);
			}
			
			return el;
		}
	}
	
	$.extend(api);
	
})(jQuery);

/************** common.js ******************/
var debug = false;

//Universal input field focus/blur
(function($){
	$.fn.focusBlur = function(textVal) {
		this
			.live('focusin', function() {
				if(this.value == textVal) { this.value = ""; }
			})
			.live('focusout', function() {
				if(this.value == '') { this.value = textVal; }
			});
		return this;
	};
})( jQuery );

function setFlavorImageHeight() {
	$('img', '#brand_hero').css('max-height', $(window).height() - 40); // 40: gap between window top and the image
}

function setBottleBrowserCarousel(isTypeFilter, listPos) {
	var windowWidth = $(window).width();
	var totalBottles = $('#dropdowns ul li').length;
	var firstBottle = $('#dropdowns ul li').eq(1);
	// on pages where bottle browser is not visible on initial load, firstBottle.width() would return 0
	var bottleWidth = (firstBottle.width() < 1 ? 99 : firstBottle.width()) + parseInt(firstBottle.css('paddingLeft')) + parseInt(firstBottle.css('paddingRight'));
	var bottlesInWindow = Math.floor(windowWidth / bottleWidth);
	var shiftBy = isTypeFilter ? bottlesInWindow - 3 : bottlesInWindow - 1;
	$('ul', '#our_brands').dp_carousel({ triggers: $('a', '#bottles_pagination'), shift: shiftBy, startPos: listPos, speed: 1000, continuous: false });
}

function getTweets() {
	if (!$('#tweeter_url').attr('href')) {
		return;
	}
	var l_sTweeterUrl = $('#tweeter_url').attr('href');
	var l_sTweeterUsername = l_sTweeterUrl.match(/\.com\/([a-zA-Z0-9\_]+)/)[1]; // 'drpeppersnapple';
	$("#twitter_dps").livetweet({
		'url' : "/smedia/www/twitter/" + l_sTweeterUsername + ".json",
		'dataType' : 'json',
//      'username' : l_sTweeterUsername,
//      'html_before' : 'These are my tweets:<br>',
		'html_tweets' : '<li><p>{text}</p><span class="secondary_info">{date} by <a href="' + l_sTweeterUrl + '">@' + l_sTweeterUsername + '</a></span></li>',
//      'html_after' : '<br>Ciao!',
		'format_date' : function(my_date) {
			// This will return an ISO 8601 timestamp: http://en.wikipedia.org/wiki/ISO_8601
			var l_nMonth = my_date.getMonth() + 1; if (l_nMonth < 10) { l_nMonth = '0' + l_nMonth; }
			var l_nDate = my_date.getDate(); if (l_nDate < 10) { l_nDate = '0' + l_nDate; }
			var l_nHours = my_date.getHours(); if (l_nHours < 10) { l_nHours = '0' + l_nHours; }
			var l_nMinutes = my_date.getMinutes(); if (l_nMinutes < 10) { l_nMinutes = '0' + l_nMinutes; }
			var l_nSeconds = my_date.getSeconds(); if (l_nSeconds < 10) { l_nSeconds = '0' + l_nSeconds; }

			var l_sISODate = my_date.getFullYear() + '-' + l_nMonth + '-' + l_nDate + 'T' + l_nHours + ':' + l_nMinutes + ':' + l_nSeconds + 'Z';
			var l_sTimeAgoDate = $.timeago(l_sISODate);
			// A bug in Safari does not support ISO 8601 and returns NaN. http://lists.w3.org/Archives/Public/public-media-fragment/2011Mar/0030.html
			if (l_sTimeAgoDate.substring(0, 3) == 'NaN') {
				return '';
			}
			return l_sTimeAgoDate;
//          return my_date.getDay()+'/'+my_date.getMonth()+'/'+my_date.getFullYear();
		},
		'loading_text' : '',
		'error_text' : '',
		'limit' : (!$('#tweeter_url').attr('limit') ? 3 : $('#tweeter_url').attr('limit'))
	});
};

// adjust large image height to browser height
$(document).ready(function(){
	code_and_theory.init();
	$('#carousel').show();
	setFlavorImageHeight();
	getTweets();
});

function windowResizeDone() {
	setFlavorImageHeight();
}

var resizeTimer = null;
$(window).bind('resize', function() {
    if (resizeTimer) clearTimeout(resizeTimer);
    resizeTimer = setTimeout(windowResizeDone, 500);
});

//Custom carousel for dpsg, extends jquery.
//Use: $(selector).dp_carousel({ options_as_seen_in_var_config });
(function($) {

	$.fn.dp_carousel = function(options) { 
		
		//merge default and user-set options
		var config = {
			triggers: '', //set of prev and next buttons as a jquery object i.e. $('#buttons a') or $('.previous, .next') assumes the order .prev is 0 and .next is 1
			shift: 1, //number of elements to shift by
			startPos: 0,
			speed: 1000,
			easing: 'easeOutBack', //easing requires jqueryui
			continuous: true, //for the purposes of the bottle carousel, otherwise should always be in 'true' state
			callback: function() {  } //
		},
		opts = $.extend({}, config, options);
		
		//PRIVATE PARTS
		var dontSpazzClick = false; //prevents craziness between transitions
		var $list = this,
			width = 0,
			last = $('li', $list).length - 1;
		
		function checkDisability() {
			opts.triggers.removeClass('disabled');
			
			if(opts.startPos == 0) { opts.triggers.eq(0).addClass('disabled'); }
			if(opts.startPos >= last - opts.shift) { opts.triggers.eq(1).addClass('disabled'); }
		}
		function repositionFullCarousel() {
			$(window).resize(function() {
				var carousel_padding = $('body').width() > 980 ? ($(window).width() - 940)/2 : 20;
				$('li', '#carousel').css({ 'padding-left': carousel_padding, 'padding-right': carousel_padding });
				$('li', '#carousel_homepage_values').css({ 'margin-left': carousel_padding, 'margin-right': carousel_padding });
				$list.css({ 'left': $('li:eq(' + opts.startPos + ')', $list).outerWidth(true) * opts.startPos * -1 });
			});
		}
		
		function gotoPrev() {
			dontSpazzClick = true;
			var $clone;
			
			if(opts.continuous && opts.startPos == 0) {
				$clone = $('li:last', $list).clone();
				$list
					.prepend($clone)
					.css({ 'left': $('li:eq(1)', $list).position().left * - 1 });
			} else {
				opts.startPos = opts.startPos > 0 && opts.startPos >= opts.shift ? opts.startPos - opts.shift : 0;
			}
			
			$list.animate({ 'left': $('li:eq(' + opts.startPos + ')', $list).position().left * -1 }, opts.speed, opts.easing, function() {
				if(typeof $clone == 'object') {
					opts.startPos = last;
					$clone.detach();
					$list.css({ 'left': $('li:eq(' + (last) + ')', $list).position().left * -1 });
				}
				dontSpazzClick = false;
				opts.callback.call({ position: opts.startPos, count: last });
			});
		}
		
		function gotoNext() {
			dontSpazzClick = true;
			var $clone;
			
			if(opts.continuous && opts.startPos == last) {
				$clone = $('li:eq(0)', $list).clone().appendTo($list)
				opts.startPos = $('li', $list).index($clone);
			} else {
				if (opts.continuous) {
					opts.startPos = opts.startPos <= last - opts.shift ? opts.startPos + opts.shift : opts.startPos;
				} else {
					opts.startPos = opts.startPos < last - opts.shift ? opts.startPos + opts.shift : opts.startPos;
					if (last - opts.startPos < (opts.shift - 1)) {
						opts.startPos = last - opts.shift + 1;
					}
				}
			}
			
			$list.animate({ 'left': $('li:eq(' + opts.startPos + ')', $list).position().left * -1 }, opts.speed, opts.easing, function() {
				if(typeof $clone == 'object') {
					opts.startPos = 0;
					$clone.detach();
					$list.css({ 'left': 0 })
				}
				dontSpazzClick = false;
				opts.callback.call({ position: opts.startPos, count: last });
			});
		}
		
		//Everything that happens on init (when .dp_carousel is called)
		!opts.continuous ? checkDisability() : repositionFullCarousel();
		
		$.each($('li', $list), function(i, e) {
			width += $(e).outerWidth(true) == 0 ? 200 : $(e).outerWidth(true); //cheating on brands carousel
		});
		
		$list
			.width(width * 2 + 5000) //extend the width for continuouse and to be safety
			.css({ 'position': $list.css('position') != 'absolute' ? 'relative' : 'absolute' })
			.animate({ 'left': $('li:eq(' + opts.startPos + ')', $list).position().left * -1 }, opts.speed, opts.easing, function() {
			//	if($('.homepage_bar').length > 0) { $('html, body').removeAttr('style'); } //undoes what homepage.js has done
				dontSpazzClick = false;
			});
		
		$('li', $list).length < 2 ? $('#carousel_pagination, #carousel_homepage_values_pagination', $list.parent('div')).hide() : $list.next('#carousel_pagination, #carousel_homepage_values_pagination').find('span').text(opts.startPos + 1 + ' of ' + $('li', $list).length);
		
		return $.each(opts.triggers, function(i, e) {
			$(e).unbind('click').bind('click', function() {
				if(!dontSpazzClick) {
					i == 0 ? gotoPrev(e) : gotoNext(e);
				}
				if(!opts.continuous) { checkDisability(); }
				return false;
			});
		});
	};

})(jQuery);

// create code_and_theory namespace
var code_and_theory = function(){
	
	// PRIVATE VARIABLES START
	var brand_nav = null;
	// PRIVATE VARIABLES END
	
	// CLASS DEFINITIONS START
	
	function brand_browser() {
		var list = $('#our_brands ul');
		var type_order = ['soda', 'juice', 'tea', 'mixer', 'water', 'other'];
		var list_array = $('#our_brands ul li').toArray();
		var types = {'soda' : null, 'juice' : null, 'tea' : null, 'mixer' : null, 'water' : null, 'other' : null};
		
		function reset(button, listPos) {
			if($('ul', '#our_brands').position().left >= listPos) {
				$('ul', '#our_brands').css('left', -1000);
			}
			
			$('.on', '#bottles_navigation').removeClass('on');
			var isTypeFilter = false;
			if ($(button).parent().is('#type_filter') || $(button).is('#type_filter_button')) {
				isTypeFilter = true;
			}
			isTypeFilter ? $('#type_filter_button').addClass('on') : $('#name_filter_button').addClass('on');
			
			//start the carousel over when filter changes
			setBottleBrowserCarousel(isTypeFilter, listPos);
		}
		
		return {
			init: function() {
				var l_aBrandNames = new Array();
				list.empty();
				//alpha sort original list
				list_array.sort(function(a, b) {
					var eleA = $('img', a).attr('data-brand-name').toLowerCase().replace(/[^a-zA-Z 0-9]+/g,''),
						eleB = $('img', b).attr('data-brand-name').toLowerCase().replace(/[^a-zA-Z 0-9]+/g,'');
					return (eleA < eleB) ? -1 : (eleA > eleB) ? 1 : 0;
				});

				//append each list items to ul, alphabetically
				$.each(list_array, function(i, e) {
//                  list.empty().append(list_array);
					var l_sBrandName = $('img', e).attr('data-brand-name').toLowerCase().replace(/[^a-zA-Z 0-9]+/g,'');
					if (!l_aBrandNames[l_sBrandName]) {
						list.append(e);
						l_aBrandNames[l_sBrandName] = true;
					}
				});

				reset('#name_filter_button', 0);
			},
			'name_filter' : function() {
				$('#type_filter').hide();
				 var l_aBrandNames = new Array();
				 list.empty();
				//alpha sort original list
				list_array.sort(function(a, b) {
					var eleA = $('img', a).attr('data-brand-name').toLowerCase().replace(/[^a-zA-Z 0-9]+/g,''),
						eleB = $('img', b).attr('data-brand-name').toLowerCase().replace(/[^a-zA-Z 0-9]+/g,'');

					return (eleA < eleB) ? -1 : (eleA > eleB) ? 1 : 0;
				});

				//append each list items to ul, alphabetically
				$.each(list_array, function(i, e) {
//                  list.empty().append(list_array);
					var l_sBrandName = $('img', e).attr('data-brand-name').toLowerCase().replace(/[^a-zA-Z 0-9]+/g,'');
					if (!l_aBrandNames[l_sBrandName]) {
						list.append(e);
						l_aBrandNames[l_sBrandName] = true;
					}
				});

				reset(this, 0);
				return false;
			},
			'type_options' : function(){
				$('#type_filter').is(':visible') ? $('#type_filter').hide() : $('#type_filter').show();
				//reset(this, 0);
				return false;
			},
			'type_filter' : function(){
				list.empty();
			
				$.each(type_order, function(i, e) {
					list.append('<li class="type_label" data-label="' + e + '"><img src="/image/bottles/label-' + e + '.gif" alt="' + e +'"></li>');
					list.append(types[e]);
				});
			
				var newPosition = $('li', list).index($('.type_label[data-label=' + $(this).attr('data-sort-by-type') + ']'));
				
				reset(this, newPosition);
				return false;
			},
			'gather_types' : function(){
				var li = $('#our_brands ul li');
				
				for(var type in types){
					// do not include prototype objects
					if(types.hasOwnProperty(type)){
						types[type] = li.filter(function(index){
							// filter list elements depending on if img data-type tag matches the corresponding type
							return $(this).children().children('[data-type=' + type + ']').length == 1;
						});
					}
				}
			}
		};
	}
	
	//pagination for flavor browser
	var flavor_selector = (function() {
		
		var viewable = 6,
			starting_count = viewable,
			all_bottles = '#flavors_selector dd',
			total_pages = 1,
			current_page = 1,
			easing = 'linear';
		
		var get_more_flavors = function() {
			var remainder = $(all_bottles).length - starting_count;
			
			if(remainder > 0) {
				$.each($(all_bottles), function(i, e) {
					if(i < starting_count) {
						$(e).fadeOut('fast', easing, $.noop());
					}
					if(i >= starting_count && i < starting_count + viewable) {
						$(e).fadeIn('normal', easing, $.noop());
					}
				});
			
				starting_count += remainder > viewable ? viewable : remainder;
				current_page++;
				
				$('span', '#flavors_pagination').text(current_page + ' of ' + total_pages);
				starting_count == $(all_bottles).length ? $('#flavors_pagination .next').addClass('disabled') : $('#flavors_pagination .next').removeClass('disabled');
				$('#flavors_pagination .prev').removeClass('disabled');
			}
			
			return false;
		};
		
		var get_less_flavors = function() {
			
			if(current_page > 1) {
				starting_count -= starting_count == $(all_bottles).length
					? ($(all_bottles).length % viewable > 0 ? $(all_bottles).length % viewable : viewable) // if $(all_bottles).length % viewable == 0, the starting_count won't change
					: viewable;
			
				$.each($(all_bottles), function(i, e) {
					i += 1; //make i count from 1
				
					if(i > starting_count) {
						$(e).fadeOut('fast', easing, $.noop());
					}
					if(i <= starting_count && i > starting_count - viewable) {
						$(e).fadeIn('normal', easing, $.noop());
					}
				});

				current_page--;
			}
			
			$('span', '#flavors_pagination').text(current_page + ' of ' + total_pages);
			current_page == 1 ? $('#flavors_pagination .prev').addClass('disabled') : $('#flavors_pagination .prev').removeClass('disabled');
			$('#flavors_pagination .next').removeClass('disabled');
			return false;
		};
		
		function set_viewable() {
			total_pages = Math.ceil($(all_bottles).length / viewable);
			current_page = 1;
				
			if($(all_bottles).length > viewable) {
				$.each($(all_bottles), function(i, e) {
					if(i > viewable - 1) {
						$(e).hide();
					} else {
						$(e).show();
					}
				});
				$('span', '#flavors_pagination').text(current_page + ' of ' + total_pages);
			} else {
				$('#flavors_pagination').hide();
			}
		}
		
		return {
			init: function() {
				set_viewable();
				
				$('#flavors_pagination .prev').live('click', get_less_flavors);
				$('#flavors_pagination .next').live('click', get_more_flavors);
			},
			kill: function() {
				starting_count = viewable;
				$('#flavors_pagination .prev').addClass('disabled');
				$('#flavors_pagination .next').removeClass('disabled');
				
				set_viewable();
				
				$('#flavors_pagination .prev').die('click');
				$('#flavors_pagination .next').die('click');
			}
		}
		
	})();
	// CLASS DEFINITIONS END

	// PRIVATE FUNCTIONS START
	function get_viewport_width(){
		return $(window).width();
	}

	// JQUERY CALLBACKS START
	
	//Brand page overlays
	function generateOverlay() {
		var overlayID = $(this).attr('data-overlay-id');
		$('#' + overlayID).dialog({
			closeText: '',
			dialogClass: overlayID + '_dialog',
			draggable: false,
			resizable: false,
			stack: false,
			width: '100%',
			zindex: 1001,
			show: 'fade',
			hide: 'fade',
			open: function(event, ui) {
				setTimeout( function() {
					$('body').css({ 'overflow': 'hidden' });
				}, 100);
				$('.ui-dialog-titlebar-close').hover(function() {
					$(this).animate({
						'background-size': '106%',
						'-moz-background-size': '106%',
						'-webkit-background-size': '106%'
					}, 200, 'easeOutCubic', $.noop());
				}, function() {
					$(this).animate({
						'background-size': '100%',
						'-moz-background-size': '100%',
						'-webkit-background-size': '100%'
					}, 125, 'easeInSine', $.noop());
				});
				if($('#history_carousel').length) {
					$('ul', '#history_carousel')
						.css({ 'margin-left': ($('#history_carousel').outerWidth() - $('li:eq(0)', '#history_carousel').outerWidth()) / 2 })
						.dp_carousel({ triggers: $('a', '#history_carousel_pagination'), startPos: 1, continuous: false });
						
					$(window).resize(function() {
						$('ul', '#history_carousel').css({ 'margin-left': ($('#history_carousel').outerWidth() - $('li:eq(0)', '#history_carousel').outerWidth()) / 2 })
					});
				}

				//for flavor browser pagination
				if($('#flavors_selector').length) { flavor_selector.init(); }
			},
			close: function(event, ui) {
				 setTimeout( function() {
					 $('body').css({ 'overflow': '' });
					 $('html').css({ 'overflow': '' });
				 }, 100);
				
				//for flavor browser pagination reset
				if($('#flavors_selector').length) { flavor_selector.kill(); }
			}
		});
		return false;
	}
	
	//utilities for main navigation hover effects
	var mainNav = {
		keepNavOpen: null,
		waitToHover: null,
		speed: 250,
		easing: 'easeInOutCubic',
		showDefault: function() {
			if($('.onload_visible').length == 0) {
				$('#dropdowns').css({
					'position': 'static',
					'padding-bottom': 0,
					'background-position': 'center -1000px'
				});
				$('#our_values, #our_company').css({ 'height': 340 });
			}
			$('.onload_visible').fadeIn(mainNav.speed, mainNav.easing);
			clearTimeout(mainNav.keepNavOpen);
			$('#our_values, #our_company, #our_brands').not('.onload_visible').hide();
		}
	};
		
	function main_navigation_hover_over(nav_dropdown, nav_item) {
		mainNav.waitToHover = setTimeout(function() {
			if($('.onload_visible').length == 0) {
				$('#dropdowns').css({
					'position': 'absolute',
					'padding-bottom': 25,
					'background-position': 'center bottom'
				})
				$('#our_values, #our_company').css({ 'height': 315 });
			}
			$('#' + nav_dropdown).fadeIn(mainNav.speed, mainNav.easing, function() { });
			$('#our_values, #our_company, #our_brands').not('#' + nav_dropdown).hide();
		}, 500);
		clearTimeout(mainNav.keepNavOpen);
	}
	function main_navigation_hover_out(nav_dropdown, nav_item) {
		mainNav.keepNavOpen = setTimeout(function() {
			$('#' + nav_dropdown).not('.onload_visible').fadeOut(mainNav.speed, mainNav.easing, mainNav.showDefault);
		}, 800);
		clearTimeout(mainNav.waitToHover);
	}
	
	function dropdown_hover_over(nav_dropdown_id) {
		clearTimeout(mainNav.keepNavOpen);
		$('#'+nav_dropdown_id).show();
		$('#main_navigation').children('a').each(function(){
			if($(this).attr('data-dropdown-id') == nav_dropdown_id){
				$(this).addClass('hover');
			}
		});
	}
	function dropdown_hover_out(nav_dropdown_id) {
		mainNav.keepNavOpen = setTimeout(function() {
			$('#'+nav_dropdown_id).not('.onload_visible').fadeOut(mainNav.speed, mainNav.easing, mainNav.showDefault);
		}, 800);
		$('#main_navigation').children('a').each(function(){
			if($(this).attr('data-dropdown-id') == nav_dropdown_id){
				$(this).removeClass('hover');
			}
		});
	}
	
	//content carousel callback
	var carousel_callback = function() {
		$('span', '#carousel_pagination')
			.text( (this.position + 1) + ' of ' + (this.count + 1) )
			.animate({ 'color': $('li:eq(' + this.position + ')', '#carousel').css('color') }, 50);
		$('#carousel').css({ 'background-color': $('li:eq(' + this.position + ')', '#carousel').css('background-color') })
	};
	var values_callback = function() {
		$('span', '#carousel_homepage_values_pagination').text( (this.position + 1) + ' of ' + (this.count + 1) );
	};
	
	// JQUERY CALLBACKS END
	// PRIVATE FUNCTIONS END
	
	// PUBLIC FUNCTIONS START
	return {
		'init' : function(){
			// run initial function calls
			brand_nav = new brand_browser();
			brand_nav.gather_types();
			brand_nav.init();
			
			// setup jquery callbacks
			$('#name_filter_button').click(brand_nav.name_filter);
			$('#type_filter_button').click(brand_nav.type_filter); // type_options
			$('#type_filter a').click(brand_nav.type_filter);
			
			//Brands dropdown carousel good to go on init
			setBottleBrowserCarousel(false, 0);
			
			//content carousel setup
			code_and_theory.set_up_carousel();
			
			//Main Navigation dropdown hover effects
			$('a', '#main_navigation').hover(function() {
				main_navigation_hover_over($(this).attr('data-dropdown-id'), this);
			}, function() {
				main_navigation_hover_out($(this).attr('data-dropdown-id'), this);
			});
			
			$('#our_brands, #our_values, #our_company').hover(function() {
				dropdown_hover_over($(this).attr('id'));
			}, function() {
				dropdown_hover_out($(this).attr('id'));
			});
			
			
			//Search box blur/focus
			$('.search_input')
				.live('focusin', function() {
					if(this.value == 'Search') { this.value = ""; }
					$(this).parent().css({ 'border-color': '#59abc8', 'background-color': '#f9f9f9' });
				})
				.live('focusout', function() {
					if(this.value == '') { this.value = 'Search'; }
					$(this).parent().css({ 'border-color': '#c3c3c3', 'background-color': '#f4f4f4' });
				});
			
			//Brand detail pages - open overlay
			$('a[data-overlay-id]', '#brand_image').click(generateOverlay);
			$('a[data-overlay-id]', '#brand_slideshow')
				.click(generateOverlay)
				.eq(0).prepend('<img src="/image/btn-slideshow-overlay.png" alt="" style="position: absolute; top: 0; left: 0;" />');
				
			$('img', '#flavors dd').live('click', function() {
				var l_sNewHeroImgSrc = $(this).data('enlarged-image');
				$('#brand_hero').fadeOut('fast', function() {
					$(this).find('img').first().attr('src', l_sNewHeroImgSrc).bind('load', function() { $(this).parent('div').fadeIn('slow'); });
				});
			});
			
			//Brand details video in carousel
			$('a.carousel_image').live('click', function() {
				$(this).hide().next().show();
				return false;
			});
			
			//Init custom-styled select menues, uses jquery.dropp.js https://github.com/matrushka/Dropp/
			$('select').dropp();
			
			//Contact page dropdown change
			$('#issue', '#contact_forms').change(function() {
				var fieldset = $('option:eq(' + this.selectedIndex + ')', this).data('fieldset');
				if($('#' + fieldset).css('display') == 'none') {
					$('#general, #consumer, #none').hide();
					$('#' + fieldset).show();
                 if ($.browser.msie && parseInt($.browser.version) < 9){
	 				document.getElementById("iFrameId").src = "http://www.econsumeraffairs.com/am_bev/contactus.htm?F2=corporate&DummyParam=something&F9=//www.drpeppersnapplegroup.com/script/form_styles.js";
 				}
        	}
			});
		},
		'get_viewport_width' : get_viewport_width,
		'set_up_carousel': function() {
			var carousel_padding = $('body').width() > 980 ? ($(window).width() - 940)/2 : 20;
			if($('#carousel').length) {
				$('ul', '#carousel').dp_carousel({ triggers: $('a', '#carousel_pagination'), callback: carousel_callback });
				$('li', '#carousel').css({ 'padding-left': carousel_padding, 'padding-right': carousel_padding });
				$('span', '#carousel_pagination').animate({ 'color': $('li:eq(0)', '#carousel').css('color') }, 50);
			}
			if($('#carousel_homepage_values').length) {
				$('li', '#carousel_homepage_values').css({ 'margin-left': carousel_padding, 'margin-right': carousel_padding });
				$('ul', '#carousel_homepage_values').dp_carousel({ triggers: $('a', '#carousel_homepage_values_pagination'), callback: values_callback });
			}
		}
	};
	// PUBLIC FUNCTIONS END
    
}();


/************** homepage.js ******************/
code_and_theory.homepage = function(){
	var offset = 69;
	var is_brands_homepage = true;
	var transition_speed = 500;
	var already_animated = false;
	
	function change_homepage(homepage_vars){
		
		$('html,body').animate({scrollTop: 0}, 50);
		$('#content, #our_brands').not(':hidden').hide('slide', {direction : homepage_vars.initial_direction, queue : false}, transition_speed, function(){
			// because we are animating on 4 elements this function will run 4 times
			// the following check makes sure the logic only runs once
		
			if(already_animated){	
				if(debug){ console.log('is brands homepage = ' + is_brands_homepage); }
				$('#content').load(homepage_vars.filename + ' #content > *', function() {
					var carousel_padding = $('body').width() > 980 ? ($(window).width() - 940)/2 : 20;
					$('li', '#carousel_homepage_values').css({ 'margin-left': carousel_padding, 'margin-right': carousel_padding });
					getTweets();
					$('#carousel').show();
				});
				is_brands_homepage = is_brands_homepage == true ? false : true;
				already_animated = false;
			}
		});
		
		$('#content').show('slide', {direction : homepage_vars.secondary_direction}, transition_speed, code_and_theory.set_up_carousel);
		if(!is_brands_homepage) {
			setTimeout(function() {
				$('#our_brands').show('slide', {direction : homepage_vars.secondary_direction}, 600, function() {
					code_and_theory.set_up_carousel();
					$('#our_brands').addClass('onload_visible');
				});
			}, 450);
			$('body').removeClass('home_v2');
			pageTracker._trackPageview('/homepage1/');
		} else {
			$('#our_brands').removeClass('onload_visible');
			$('body').addClass('home_v2');
			pageTracker._trackPageview('/homepage2/');
		}
	}
	
	function bar_click(){
		already_animated = true;
		
		var bar_initial_animation = { 'opacity'	: 'toggle' };
		var bar_secondary_animation = { 'opacity'	: 'toggle' };
		var bar_direction = null;
		var bar_attributes = {};
		var img_attributes = {};
		var homepage_vars = {};
		
		is_brands_homepage = $('.home_v2').length ? false : true;
		if(is_brands_homepage){
			bar_direction = 'right';
			homepage_vars.filename = '/template/index-v2.php';
			homepage_vars.initial_direction = 'left';
			homepage_vars.secondary_direction = 'right';
			bar_initial_animation.right = '+=' + (code_and_theory.get_viewport_width() - offset);
			bar_attributes.id = 'homepage_brands_bar';
			bar_attributes.alt = 'What\'s Going on Right Now';
			img_attributes.src = '/image/homepage-bar-brands.jpg';
		} else {
			bar_direction = 'left';
			homepage_vars.filename = '/template/index.php';
			homepage_vars.initial_direction = 'right';
			homepage_vars.secondary_direction = 'left';
			bar_initial_animation.left = '+=' + (code_and_theory.get_viewport_width() - offset);
			bar_attributes.id = 'homepage_values_bar';
			bar_attributes.alt = 'Making the Future with DPS';
			img_attributes.src = '/image/homepage-bar-values.png';
		}
		
		//console.log(is_brands_homepage);
		//console.log(bar_initial_animation);
		//console.log(bar_secondary_animation);
		//console.log(bar_attributes);
		//console.log(img_attributes);
		//console.log(directions);
		
		$('.homepage_bar')
			.animate(bar_initial_animation, transition_speed, function(){
				$(this).attr(bar_attributes).css(bar_direction, '').animate(bar_secondary_animation, transition_speed);
				$(this).find('img').attr(img_attributes);
			})
		//	.css('top', $(window).scrollTop()); //immediately moves click bar to top if at bottom of page
		change_homepage(homepage_vars);
		return false;
	}
	
	return {
		'init' : function(){
			$('.homepage_bar a').click(bar_click);
		//	$(window).scroll(function(){ $('.homepage_bar').css('top', $(window).scrollTop()); });
		}
	};
}();

$(document).ready(function(){
	code_and_theory.homepage.init();
});

/************** stock_ticker.js ******************/
if (typeof dpsg === 'undefined') {
	var dpsg = {};
}

/**
 *  Queries Yahoo Financial via YQL for current and historic quotes.
 *  Populates historic data into a line-graph via Google charts
 */
dpsg.stock_ticker = (function() {
	
	var _util, _dates, app;
	
	_util = {
		
		/**
		 *  Rounds amounts to nearest penny, and ensures full dollar format of xx.xx
		 *  This could use some refactoring.
		 *
		 *  @param {String}
		 */
		nearest_penny : function(amount) {
			
			// rounds to nearest penny
			amount = (Math.round(parseFloat(amount) * 100) / 100);
			amount = amount.toString();
			
			// ensures decimal
			if (amount.indexOf('.') === -1) amount += '.';
			
			// adds 0's if needed
			while (!/\.\d{2}$/.test(amount)) {
				amount += '0';
			}
			
			return amount;
		},
		
		/**
		 *  Returns date string formatted like "Jul 4, 2000 at 12:00 EST"
		 *
		 *  @param {Date}
		 */
		format_date : function(date) {
			 if ($('#content_stock_ticker').length < 1) { // date is only displayed on this div
				 return;
			 }
//          date = new Date(date);
			date = new Date(Date.parse(date).setTimezoneOffset(-4)); // using date.js (datejs.com)
			
			var month_year = date.toDateString(),
				month_year = month_year.substr(month_year.indexOf(' ')),
				month_year = month_year.replace(/(\d)\s/, '$1, '),
				hour = date.getHours(),
				meridiem = 'A',
				minute = date.getMinutes();

			if (hour >= 12) {
				hour -= 12;
				meridiem = 'P';
			}

			if (hour == 0) {
				hour = 12;
			}

			if (minute < 10) {
				minute = '0' + minute;
			}

			var out = [
				month_year,
				' at ',
				hour, ':', minute, meridiem, 'M ET'
			].join('');
			
			return out;
		},
		
		/**
		 *  Returns a proper SQL/JSONP request uri
		 *
		 *  @param {String} 
		 */
		generate_uri : function(query) {
			return "//query.yahooapis.com/v1/public/yql?q=" + encodeURIComponent(query) + "&format=json";
		},
		
		/**
		 *  Returns object with array of day close values, and the min/max of that period
		 *
		 *  @param {Object} the JSON object returned by historic request
		 */
		extract_graph_data : function(data) {
			if (!data.query.results) {
				return false;
			}
			var max = 0, min = false, value;
			
			// remove first result, which is just the data keys
			data.query.results.row.pop();
			
			return {
				
				// reduce to just daily close values, extracting min and max
				days : $.map(data.query.results.row, function(day, i) {
					value = day['col4'];
					max = (value > max) ? value : max;
					min = min || max;
					min = (value < min) ? value : min;
					return value;
				}).join(','),

				// buffer min and max by a dollar on either side
				min : Math.ceil(parseFloat(min) - 1),
				max : Math.floor(parseFloat(max) + 1)
			}
		},
		
		/**
		 *  Partial application, first time stores graph data, second time returns img element
		 *
		 *  @param {Object} the JSON object returned by historic request
		 */
		create_graph_builder : function(data) {
			
			data = _util.extract_graph_data(data);
			
			return function(attrs) {
				
				attrs.src = [
					'https://chart.googleapis.com/chart?cht=lc:nda&chco=5fb8d6&chd=t:',
					data.days,
					'&chs=', attrs.width, 'x', attrs.height,
					'&chds=', data.min, ',', data.max
				].join('');
				
				return $.build('img', attrs);
			}
		}
	}
	
	_dates = {
		
		start : {},
		end : {},
		
		/**
		 *  Gathers and stores start/end dates for stock history
		 *
		 *  @param {Number}
		 */
		init : function(days_in_history) {
			
			var start_date = end_date = new Date();
			
			_dates.start = {
				year : start_date.getFullYear(),
				month : start_date.getMonth(),
				day : start_date.getDate()
			};

			end_date.setTime(start_date.getTime() - (86400000 * days_in_history));
			
			_dates.end = {
				year : end_date.getFullYear(),
				month : end_date.getMonth(),
				day : end_date.getDate()
			}
		}
	}
	
	app = {
		
		/**
		 *  Builds URI's and makes requests
		 */
		request : function() {
			
			var current_uri, history_uri;
			
			historic_uri = _util.generate_uri([
				"select col1, col4 from csv where ",
				"url='", app.queries.historic.url,
					"&a=", _dates.end.month,
					"&b=", _dates.end.day,
					"&c=", _dates.end.year,
					"&d=", _dates.start.month,
					"&e=", _dates.start.day,
					"&f=", _dates.start.year, 
				"' | sort(field='col0') | reverse()"
			].join(''));
			
			current_uri = _util.generate_uri("select col1, col4 from csv where url='" + app.queries.current.url + "'");

			dpsg.stock_ticker.current_callback = function(data) {
				if (!data.query.results) { // avoid js error if no results are returned
					return;
				}
				app.render({
					current : _util.nearest_penny(data.query.results.row.col1),
					change : _util.nearest_penny(data.query.results.row.col4),
					date : _util.format_date(data.query.created)
				})
			};

			$.ajax({
				url: current_uri + '&_maxage=' + app.queries.current.cache,
				dataType: 'jsonp',
				jsonpCallback: 'dpsg.stock_ticker.current_callback',
				cache: true
			});
			
			dpsg.stock_ticker.historic_callback = function(data) { 
				app.render({ build_graph : _util.create_graph_builder(data) });
			};

			$.ajax({
				url: historic_uri + '&_maxage=' + app.queries.historic.cache,
				dataType: 'jsonp',
				jsonpCallback: 'dpsg.stock_ticker.historic_callback',
				cache: true
			});
			
		},
		
		/**
		 *  Runs any given views with data from app.request()  
		 *  Partial application used to catch both asynch requests
		 *  
		 *  @param {Object} JSON object from request
		 */
		render : function(data) {
			
			var old_data = data;
			
			app.render = function(data) {
				
				data = $.extend(data, old_data);
				data.change = data.change.replace(/^(\d.*)/, "+$1")
				// populate any elements by id with the appropriate blank template
				for (var id in app.templates) {
					$('#' + id).click(function(e) {
						window.location = 'http://investor.drpeppersnapple.com/';
					}).append(app.templates[id](data));
				}
			}
		},
		
		/**
		 *  Starts the whole show, takes a config, makes request, and attempts to render any given templates
		 *
		 *  @param {Object}
		 */
		init : function(config) {
			
			config = config || {};

			app.templates = config.templates;
			app.company = config.company;
			
			app.queries = {
				
				historic : {
					cache : '43200',
					url : 'http://ichart.finance.yahoo.com/table.csv?s=' + app.company
				},
				
				current : {
					cache : '1200',
					url : 'http://download.finance.yahoo.com/d/quotes.csv?s=' + app.company + '&f=sl1d1t1c1ohgv&e=.csv'
				}
			}
			
			// overwrite default query info
			$.extend(true, app.queries, config.queries);
			
			// prepare dates
			_dates.init(config.days_in_history || 30);
			
			// ready? go!
			app.request();
		}
	}
	
	return app;
	
})();

// initialize the ticker with configuration
$(function() {

	dpsg.stock_ticker.init({
		company : 'DPS',
		
		templates : {
	
			header_stock_ticker : function(data) {
				// if Yahoo API returns an error, do not display current stock quote
				if (data.current > 500 || data.current <= 0) {
					return;
				}
				return $.build('fragment', [
					'NYSE: DPS',
					data.build_graph({ 'class' : 'history', 'height' : 20, 'width' : 85 }),
					$.build('strong', { 'class' : 'current' }, '$' + data.current),
					$.build('span', { 'class' : 'change' }, data.change)
				]);		
			},
	
			content_stock_ticker : function(data) {
				// if Yahoo API returns an error, do not display current stock quote
				if (data.current > 500 || data.current <= 0) {
					return;
				}
				return $.build('fragment', [
					$.build('h2', 'Stock Price'),
					$.build('div', [
						'NYSE: DPS', 
						$.build('span', { 'class' : 'date' }, data.date)
					]),
					$.build('strong', { 'class' : 'current' }, '$' + data.current),
					$.build('span', { 'class' : 'change' }, data.change),
					data.build_graph({ 'class' : 'history', 'height' : 80, 'width' : 220 })
				]);
			}
		}
	});

});

/************** jquery.timeago.js ******************/
/*
 * timeago: a jQuery plugin, version: 0.9.3 (2011-01-21)
 * @requires jQuery v1.2.3 or later
 *
 * Timeago is a jQuery plugin that makes it easy to support automatically
 * updating fuzzy timestamps (e.g. "4 minutes ago" or "about 1 day ago").
 *
 * For usage and examples, visit:
 * http://timeago.yarp.com/
 *
 * Licensed under the MIT:
 * http://www.opensource.org/licenses/mit-license.php
 *
 * Copyright (c) 2008-2011, Ryan McGeary (ryanonjavascript -[at]- mcgeary [*dot*] org)
 */
(function($) {
  $.timeago = function(timestamp) {
    if (timestamp instanceof Date) {
      return inWords(timestamp);
    } else if (typeof timestamp === "string") {
      return inWords($.timeago.parse(timestamp));
    } else {
      return inWords($.timeago.datetime(timestamp));
    }
  };
  var $t = $.timeago;

  $.extend($.timeago, {
    settings: {
      refreshMillis: 60000,
      allowFuture: false,
      strings: {
        prefixAgo: null,
        prefixFromNow: null,
        suffixAgo: "ago",
        suffixFromNow: "from now",
        seconds: "less than a minute",
        minute: "about a minute",
        minutes: "%d minutes",
        hour: "about an hour",
        hours: "about %d hours",
        day: "a day",
        days: "%d days",
        month: "about a month",
        months: "%d months",
        year: "about a year",
        years: "%d years",
        numbers: []
      }
    },
    inWords: function(distanceMillis) {
      var $l = this.settings.strings;
      var prefix = $l.prefixAgo;
      var suffix = $l.suffixAgo;
      if (this.settings.allowFuture) {
        if (distanceMillis < 0) {
          prefix = $l.prefixFromNow;
          suffix = $l.suffixFromNow;
        }
        distanceMillis = Math.abs(distanceMillis);
      }

      var seconds = distanceMillis / 1000;
      var minutes = seconds / 60;
      var hours = minutes / 60;
      var days = hours / 24;
      var years = days / 365;

      function substitute(stringOrFunction, number) {
        var string = $.isFunction(stringOrFunction) ? stringOrFunction(number, distanceMillis) : stringOrFunction;
        var value = ($l.numbers && $l.numbers[number]) || number;
        return string.replace(/%d/i, value);
      }

      var words = seconds < 45 && substitute($l.seconds, Math.round(seconds)) ||
        seconds < 90 && substitute($l.minute, 1) ||
        minutes < 45 && substitute($l.minutes, Math.round(minutes)) ||
        minutes < 90 && substitute($l.hour, 1) ||
        hours < 24 && substitute($l.hours, Math.round(hours)) ||
        hours < 48 && substitute($l.day, 1) ||
        days < 30 && substitute($l.days, Math.floor(days)) ||
        days < 60 && substitute($l.month, 1) ||
        days < 365 && substitute($l.months, Math.floor(days / 30)) ||
        years < 2 && substitute($l.year, 1) ||
        substitute($l.years, Math.floor(years));

      return $.trim([prefix, words, suffix].join(" "));
    },
    parse: function(iso8601) {
      var s = $.trim(iso8601);
      s = s.replace(/\.\d\d\d+/,""); // remove milliseconds
      s = s.replace(/-/,"/").replace(/-/,"/");
      s = s.replace(/T/," ").replace(/Z/," UTC");
      s = s.replace(/([\+\-]\d\d)\:?(\d\d)/," $1$2"); // -04:00 -> -0400
      return new Date(s);
    },
    datetime: function(elem) {
      // jQuery's `is()` doesn't play well with HTML5 in IE
      var isTime = $(elem).get(0).tagName.toLowerCase() === "time"; // $(elem).is("time");
      var iso8601 = isTime ? $(elem).attr("datetime") : $(elem).attr("title");
      return $t.parse(iso8601);
    }
  });

  $.fn.timeago = function() {
    var self = this;
    self.each(refresh);

    var $s = $t.settings;
    if ($s.refreshMillis > 0) {
      setInterval(function() { self.each(refresh); }, $s.refreshMillis);
    }
    return self;
  };

  function refresh() {
    var data = prepareData(this);
    if (!isNaN(data.datetime)) {
      $(this).text(inWords(data.datetime));
    }
    return this;
  }

  function prepareData(element) {
    element = $(element);
    if (!element.data("timeago")) {
      element.data("timeago", { datetime: $t.datetime(element) });
      var text = $.trim(element.text());
      if (text.length > 0) {
        element.attr("title", text);
      }
    }
    return element.data("timeago");
  }

  function inWords(date) {
    return $t.inWords(distance(date));
  }

  function distance(date) {
    return (new Date().getTime() - date.getTime());
  }

  // fix for IE6 suckage
  document.createElement("abbr");
  document.createElement("time");
}(jQuery));


/************** jquery.livetweet.js ******************/
/* 
JQUERY LIVETWEET 0.2
by Sergio Martino
http://www.dailygrind.it
https://github.com/sergiomartino/jQuery-LiveTweet
*/

(function($){
	var settings = {
		'url' : 'http://api.twitter.com/1/statuses/user_timeline.json?',
		'dataType' : 'jsonp',
		'limit' : 5,
		'username' : '',
		'timeout' : 2000,		
		'html_before' : '<ul>',
		'html_tweets' : '<li>{text}<br>{date}</li>',
		'html_after' : '</ul>',
		'loading_text' : 'loading...',
		'error_text' : 'an error has occurred!',
		'format_date' : function(d) {
			return $.fn.livetweet('format_date', d)		
		}
	};

	var methods = {
		init : function(options) {
			var $this = this;			
			if(options) $.extend(settings, options);

			$.ajax({
//              beforeSend : $this.html('<span class="livetweet-loading">'+settings.loading_text+'</span>'),
				url: settings.url,
				type: 'GET',
				data: (settings.username != '' ? 'screen_name='+settings.username : ''),
				dataType: settings.dataType,
				timeout: settings.timeout,
				error: function(msg) {
					$this.html('<span class="livetweet-error">' + settings.error_text + '</span>');
				},
				success: function(json){																		
					$this.find(".livetweet-loading").remove();
					sizer = json.length > settings.limit ? settings.limit : json.length;
					rt = settings.html_before;
					tweets = '';
					for(i=0;i<sizer;i++) {							
						var l_nTimestamp = new Date(Date.parse(new Date(Date.parse(json[i].created_at.replace(/(\+\S+) (.*)/, '$2 $1')))));
						text = settings.html_tweets.replace('{text}', $.fn.livetweet('format_links', json[i].text));																								
						text = text.replace('{date}', settings.format_date(l_nTimestamp));
						tweets += text;
					}
					rt += tweets+settings.html_after;					
					return $this.each(function() {
						$(this).append(rt);
					});	
				}
			});
		
		},
		format_links : function(t) {			
			var rxp_url = /((ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?)/gi;
            var rxp_user = /[\@]+([A-Za-z0-9-_]+)/gi;
            var rxp_hash = / [\#]+([A-Za-z0-9-_]+)/gi;

			t = t.replace(rxp_url,'<a target="_blank" href="$1">$1</a>');
			t = t.replace(rxp_user,'<a target="_blank" href="http://twitter.com/$1">@$1</a>');
			t = t.replace(rxp_hash,'<a target="_blank" href="http://search.twitter.com/search?q=&tag=$1&lang=all">#$1</a>');
			
			return t;
		},
		format_date : function(dt) {			
			var m = new Array('GEN', 'FEB', 'MAR', 'APR', 'MAG', 'GIU', 'LUG', 'AGO', 'SET', 'OTT', 'NOV', 'DIC');
			var d = new Array('Domenica', 'Lunedì', 'Martedì', 'Mercoledì', 'Giovedì', 'Venerdì', 'Sabato');		
			return d[dt.getDay()]+ " " + dt.getDate() + " " + m[dt.getMonth()] + " " + dt.getFullYear();		
		}
	};

	$.fn.livetweet = function(method) {
		if(methods[method]) {
			return methods[method].apply(this, Array.prototype.slice.call(arguments,1));
		} else if(typeof method === 'object' || !method) {
			return methods.init.apply(this, arguments);
		} else {
			$.error('Method '+method+' does not exist on jQuery.livetweet');
		}    
	};
})(jQuery);

/************** jquery.postMessage.js ******************/
/*
 * jQuery postMessage - v0.5 - 9/11/2009
 * http://benalman.com/projects/jquery-postmessage-plugin/
 * 
 * Copyright (c) 2009 "Cowboy" Ben Alman
 * Dual licensed under the MIT and GPL licenses.
 * http://benalman.com/about/license/
 */
(function($){var g,d,j=1,a,b=this,f=!1,h="postMessage",e="addEventListener",c,i=b[h]&&!$.browser.opera;$[h]=function(k,l,m){if(!l){return}k=typeof k==="string"?k:$.param(k);m=m||parent;if(i){m[h](k,l.replace(/([^:]+:\/\/[^\/]+).*/,"$1"))}else{if(l){m.location=l.replace(/#.*$/,"")+"#"+(+new Date)+(j++)+"&"+k}}};$.receiveMessage=c=function(l,m,k){if(i){if(l){a&&c();a=function(n){if((typeof m==="string"&&n.origin!==m)||($.isFunction(m)&&m(n.origin)===f)){return f}l(n)}}if(b[e]){b[l?e:"removeEventListener"]("message",a,f)}else{b[l?"attachEvent":"detachEvent"]("onmessage",a)}}else{g&&clearInterval(g);g=null;if(l){k=typeof m==="number"?m:typeof k==="number"?k:100;g=setInterval(function(){var o=document.location.hash,n=/^#?\d+&/;if(o!==d&&n.test(o)){d=o;l({data:o.replace(n,"")})}},k)}}}})(jQuery);

